blob: fbc0c983285fd4202b15b24a12ab79d9022180af [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>
23#include <boost/container/flat_map.hpp>
24#include <boost/process.hpp>
Willy Tude54f482021-01-26 15:59:09 -080025#include <ipmid/api.hpp>
26#include <ipmid/message.hpp>
27#include <ipmid/types.hpp>
George Liude6694e2024-07-17 15:22:25 +080028#include <phosphor-logging/lg2.hpp>
Willy Tude54f482021-01-26 15:59:09 -080029#include <sdbusplus/message/types.hpp>
30#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050031
32#include <filesystem>
33#include <fstream>
34#include <functional>
35#include <iostream>
Willy Tude54f482021-01-26 15:59:09 -080036#include <stdexcept>
37#include <string_view>
38
39static constexpr bool DEBUG = false;
40
41namespace dynamic_sensors::ipmi::sel
42{
43static const std::filesystem::path selLogDir = "/var/log";
44static const std::string selLogFilename = "ipmi_sel";
45
46static int getFileTimestamp(const std::filesystem::path& file)
47{
48 struct stat st;
49
50 if (stat(file.c_str(), &st) >= 0)
51 {
52 return st.st_mtime;
53 }
54 return ::ipmi::sel::invalidTimeStamp;
55}
56
57namespace erase_time
58{
59static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
60
Willy Tude54f482021-01-26 15:59:09 -080061int get()
62{
63 return getFileTimestamp(selEraseTimestamp);
64}
65} // namespace erase_time
66} // namespace dynamic_sensors::ipmi::sel
67
68namespace ipmi
69{
70
71namespace storage
72{
73
Willy Tude54f482021-01-26 15:59:09 -080074constexpr static const size_t maxFruSdrNameSize = 16;
75using ObjectType =
76 boost::container::flat_map<std::string,
77 boost::container::flat_map<std::string, Value>>;
78using ManagedObjectType =
79 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
80using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
81
Charles Boyer818bea12021-09-20 16:56:36 -050082constexpr static const char* selLoggerServiceName =
83 "xyz.openbmc_project.Logging.IPMI";
Willy Tude54f482021-01-26 15:59:09 -080084constexpr static const char* fruDeviceServiceName =
85 "xyz.openbmc_project.FruDevice";
86constexpr static const char* entityManagerServiceName =
87 "xyz.openbmc_project.EntityManager";
88constexpr static const size_t writeTimeoutSeconds = 10;
89constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -050090constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -080091
Willy Tude54f482021-01-26 15:59:09 -080092static std::vector<uint8_t> fruCache;
krishnar4d90b3f02022-11-11 16:18:32 +053093static constexpr uint16_t invalidBus = 0xFFFF;
94static constexpr uint8_t invalidAddr = 0xFF;
Johnathan Manteyb99de182023-12-21 08:28:18 -080095static constexpr uint8_t typeASCIILatin8 = 0xC0;
krishnar4d90b3f02022-11-11 16:18:32 +053096static uint16_t cacheBus = invalidBus;
97static uint8_t cacheAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -080098static uint8_t lastDevId = 0xFF;
99
krishnar4d90b3f02022-11-11 16:18:32 +0530100static uint16_t writeBus = invalidBus;
101static uint8_t writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800102
Patrick Williams95655222023-12-05 12:45:02 -0600103std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
Patrick Williams5d82f472022-07-22 19:26:53 -0500104static std::vector<sdbusplus::bus::match_t> fruMatches;
Willy Tude54f482021-01-26 15:59:09 -0800105
106ManagedObjectType frus;
107
108// we unfortunately have to build a map of hashes in case there is a
109// collision to verify our dev-id
krishnar4d90b3f02022-11-11 16:18:32 +0530110boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
Willy Tude54f482021-01-26 15:59:09 -0800111void registerStorageFunctions() __attribute__((constructor));
112
Willy Tu48fe64e2022-08-01 23:23:46 +0000113bool writeFru(const std::vector<uint8_t>& fru)
Willy Tude54f482021-01-26 15:59:09 -0800114{
krishnar4d90b3f02022-11-11 16:18:32 +0530115 if (writeBus == invalidBus && writeAddr == invalidAddr)
Willy Tude54f482021-01-26 15:59:09 -0800116 {
117 return true;
118 }
Thang Trand934be92021-12-08 10:13:50 +0700119 lastDevId = 0xFF;
Willy Tude54f482021-01-26 15:59:09 -0800120 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
Patrick Williams5d82f472022-07-22 19:26:53 -0500121 sdbusplus::message_t writeFru = dbus->new_method_call(
Willy Tude54f482021-01-26 15:59:09 -0800122 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
123 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
Willy Tu48fe64e2022-08-01 23:23:46 +0000124 writeFru.append(writeBus, writeAddr, fru);
Willy Tude54f482021-01-26 15:59:09 -0800125 try
126 {
Patrick Williams5d82f472022-07-22 19:26:53 -0500127 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
Willy Tude54f482021-01-26 15:59:09 -0800128 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500129 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800130 {
131 // todo: log sel?
George Liude6694e2024-07-17 15:22:25 +0800132 lg2::error("error writing fru");
Willy Tude54f482021-01-26 15:59:09 -0800133 return false;
134 }
krishnar4d90b3f02022-11-11 16:18:32 +0530135 writeBus = invalidBus;
136 writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800137 return true;
138}
139
William A. Kennington III52535622022-11-28 18:28:22 -0800140void writeFruCache()
Willy Tu48fe64e2022-08-01 23:23:46 +0000141{
William A. Kennington III52535622022-11-28 18:28:22 -0800142 writeFru(fruCache);
Willy Tu48fe64e2022-08-01 23:23:46 +0000143}
144
Willy Tude54f482021-01-26 15:59:09 -0800145void createTimers()
146{
Patrick Williams95655222023-12-05 12:45:02 -0600147 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
Willy Tude54f482021-01-26 15:59:09 -0800148}
149
150void recalculateHashes()
151{
Willy Tude54f482021-01-26 15:59:09 -0800152 deviceHashes.clear();
153 // hash the object paths to create unique device id's. increment on
154 // collision
155 std::hash<std::string> hasher;
156 for (const auto& fru : frus)
157 {
158 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
159 if (fruIface == fru.second.end())
160 {
161 continue;
162 }
163
164 auto busFind = fruIface->second.find("BUS");
165 auto addrFind = fruIface->second.find("ADDRESS");
166 if (busFind == fruIface->second.end() ||
167 addrFind == fruIface->second.end())
168 {
George Liude6694e2024-07-17 15:22:25 +0800169 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
170 fru.first.str);
Willy Tude54f482021-01-26 15:59:09 -0800171 continue;
172 }
173
krishnar4d90b3f02022-11-11 16:18:32 +0530174 uint16_t fruBus = std::get<uint32_t>(busFind->second);
Willy Tude54f482021-01-26 15:59:09 -0800175 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
176 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
177 std::string chassisType;
178 if (chassisFind != fruIface->second.end())
179 {
180 chassisType = std::get<std::string>(chassisFind->second);
181 }
182
183 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500184 if (chassisType.compare(chassisTypeRackMount) != 0 &&
185 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800186 {
187 fruHash = hasher(fru.first.str);
188 // can't be 0xFF based on spec, and 0 is reserved for baseboard
189 if (fruHash == 0 || fruHash == 0xFF)
190 {
191 fruHash = 1;
192 }
193 }
krishnar4d90b3f02022-11-11 16:18:32 +0530194 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
Willy Tude54f482021-01-26 15:59:09 -0800195
196 bool emplacePassed = false;
197 while (!emplacePassed)
198 {
199 auto resp = deviceHashes.emplace(fruHash, newDev);
200 emplacePassed = resp.second;
201 if (!emplacePassed)
202 {
203 fruHash++;
204 // can't be 0xFF based on spec, and 0 is reserved for
205 // baseboard
206 if (fruHash == 0XFF)
207 {
208 fruHash = 0x1;
209 }
210 }
211 }
212 }
213}
214
Willy Tu11d68892022-01-20 10:37:34 -0800215void replaceCacheFru(
216 const std::shared_ptr<sdbusplus::asio::connection>& bus,
217 boost::asio::yield_context& yield,
218 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
Willy Tude54f482021-01-26 15:59:09 -0800219{
220 boost::system::error_code ec;
221
222 frus = bus->yield_method_call<ManagedObjectType>(
223 yield, ec, fruDeviceServiceName, "/",
224 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
225 if (ec)
226 {
George Liude6694e2024-07-17 15:22:25 +0800227 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
228 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800229
230 return;
231 }
232 recalculateHashes();
233}
234
Patrick Williams1318a5e2024-08-16 15:19:54 -0400235std::pair<ipmi::Cc, std::vector<uint8_t>>
236 getFru(ipmi::Context::ptr ctx, uint8_t devId)
Willy Tude54f482021-01-26 15:59:09 -0800237{
238 if (lastDevId == devId && devId != 0xFF)
239 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000240 return {ipmi::ccSuccess, fruCache};
Willy Tude54f482021-01-26 15:59:09 -0800241 }
242
Willy Tude54f482021-01-26 15:59:09 -0800243 auto deviceFind = deviceHashes.find(devId);
244 if (deviceFind == deviceHashes.end())
245 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000246 return {IPMI_CC_SENSOR_INVALID, {}};
Willy Tude54f482021-01-26 15:59:09 -0800247 }
248
Willy Tude54f482021-01-26 15:59:09 -0800249 cacheBus = deviceFind->second.first;
250 cacheAddr = deviceFind->second.second;
251
252 boost::system::error_code ec;
253
Willy Tu48fe64e2022-08-01 23:23:46 +0000254 std::vector<uint8_t> fru =
255 ctx->bus->yield_method_call<std::vector<uint8_t>>(
256 ctx->yield, ec, fruDeviceServiceName,
257 "/xyz/openbmc_project/FruDevice",
258 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
259 cacheAddr);
Willy Tude54f482021-01-26 15:59:09 -0800260 if (ec)
261 {
George Liude6694e2024-07-17 15:22:25 +0800262 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800263
krishnar4d90b3f02022-11-11 16:18:32 +0530264 cacheBus = invalidBus;
265 cacheAddr = invalidAddr;
Willy Tu48fe64e2022-08-01 23:23:46 +0000266 return {ipmi::ccResponseError, {}};
Willy Tude54f482021-01-26 15:59:09 -0800267 }
268
Willy Tu48fe64e2022-08-01 23:23:46 +0000269 fruCache.clear();
Willy Tude54f482021-01-26 15:59:09 -0800270 lastDevId = devId;
Willy Tu48fe64e2022-08-01 23:23:46 +0000271 fruCache = fru;
272
273 return {ipmi::ccSuccess, fru};
Willy Tude54f482021-01-26 15:59:09 -0800274}
275
276void writeFruIfRunning()
277{
278 if (!writeTimer->isRunning())
279 {
280 return;
281 }
282 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000283 writeFruCache();
Willy Tude54f482021-01-26 15:59:09 -0800284}
285
286void startMatch(void)
287{
288 if (fruMatches.size())
289 {
290 return;
291 }
292
293 fruMatches.reserve(2);
294
295 auto bus = getSdBus();
Patrick Williams1318a5e2024-08-16 15:19:54 -0400296 fruMatches.emplace_back(
297 *bus,
298 "type='signal',arg0path='/xyz/openbmc_project/"
299 "FruDevice/',member='InterfacesAdded'",
300 [](sdbusplus::message_t& message) {
301 sdbusplus::message::object_path path;
302 ObjectType object;
303 try
304 {
305 message.read(path, object);
306 }
307 catch (const sdbusplus::exception_t&)
308 {
309 return;
310 }
311 auto findType = object.find("xyz.openbmc_project.FruDevice");
312 if (findType == object.end())
313 {
314 return;
315 }
316 writeFruIfRunning();
317 frus[path] = object;
318 recalculateHashes();
319 lastDevId = 0xFF;
320 });
Willy Tude54f482021-01-26 15:59:09 -0800321
Patrick Williams1318a5e2024-08-16 15:19:54 -0400322 fruMatches.emplace_back(
323 *bus,
324 "type='signal',arg0path='/xyz/openbmc_project/"
325 "FruDevice/',member='InterfacesRemoved'",
326 [](sdbusplus::message_t& message) {
327 sdbusplus::message::object_path path;
328 std::set<std::string> interfaces;
329 try
330 {
331 message.read(path, interfaces);
332 }
333 catch (const sdbusplus::exception_t&)
334 {
335 return;
336 }
337 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
338 if (findType == interfaces.end())
339 {
340 return;
341 }
342 writeFruIfRunning();
343 frus.erase(path);
344 recalculateHashes();
345 lastDevId = 0xFF;
346 });
Willy Tude54f482021-01-26 15:59:09 -0800347
348 // call once to populate
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600349 boost::asio::spawn(*getIoContext(),
350 [](boost::asio::yield_context yield) {
351 replaceCacheFru(getSdBus(), yield);
352 },
353 {});
Willy Tude54f482021-01-26 15:59:09 -0800354}
355
356/** @brief implements the read FRU data command
357 * @param fruDeviceId - FRU Device ID
358 * @param fruInventoryOffset - FRU Inventory Offset to write
359 * @param countToRead - Count to read
360 *
361 * @returns ipmi completion code plus response data
362 * - countWritten - Count written
363 */
364ipmi::RspType<uint8_t, // Count
365 std::vector<uint8_t> // Requested data
366 >
367 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
368 uint16_t fruInventoryOffset, uint8_t countToRead)
369{
370 if (fruDeviceId == 0xFF)
371 {
372 return ipmi::responseInvalidFieldRequest();
373 }
374
Willy Tu48fe64e2022-08-01 23:23:46 +0000375 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800376 if (status != ipmi::ccSuccess)
377 {
378 return ipmi::response(status);
379 }
380
381 size_t fromFruByteLen = 0;
Willy Tu48fe64e2022-08-01 23:23:46 +0000382 if (countToRead + fruInventoryOffset < fru.size())
Willy Tude54f482021-01-26 15:59:09 -0800383 {
384 fromFruByteLen = countToRead;
385 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000386 else if (fru.size() > fruInventoryOffset)
Willy Tude54f482021-01-26 15:59:09 -0800387 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000388 fromFruByteLen = fru.size() - fruInventoryOffset;
Willy Tude54f482021-01-26 15:59:09 -0800389 }
390 else
391 {
392 return ipmi::responseReqDataLenExceeded();
393 }
394
395 std::vector<uint8_t> requestedData;
396
Willy Tu48fe64e2022-08-01 23:23:46 +0000397 requestedData.insert(requestedData.begin(),
398 fru.begin() + fruInventoryOffset,
399 fru.begin() + fruInventoryOffset + fromFruByteLen);
Willy Tude54f482021-01-26 15:59:09 -0800400
401 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
402 requestedData);
403}
404
405/** @brief implements the write FRU data command
406 * @param fruDeviceId - FRU Device ID
407 * @param fruInventoryOffset - FRU Inventory Offset to write
408 * @param dataToWrite - Data to write
409 *
410 * @returns ipmi completion code plus response data
411 * - countWritten - Count written
412 */
Patrick Williams1318a5e2024-08-16 15:19:54 -0400413ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
414 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
415 std::vector<uint8_t>& dataToWrite)
Willy Tude54f482021-01-26 15:59:09 -0800416{
417 if (fruDeviceId == 0xFF)
418 {
419 return ipmi::responseInvalidFieldRequest();
420 }
421
422 size_t writeLen = dataToWrite.size();
423
Willy Tu48fe64e2022-08-01 23:23:46 +0000424 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800425 if (status != ipmi::ccSuccess)
426 {
427 return ipmi::response(status);
428 }
429 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000430 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800431 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000432 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800433 }
434
435 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000436 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800437
438 bool atEnd = false;
439
Willy Tu48fe64e2022-08-01 23:23:46 +0000440 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800441 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000442 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800443
444 size_t areaLength = 0;
445 size_t lastRecordStart = std::max(
446 {header->internalOffset, header->chassisOffset, header->boardOffset,
447 header->productOffset, header->multiRecordOffset});
448 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
449
450 if (header->multiRecordOffset)
451 {
452 // This FRU has a MultiRecord Area
453 uint8_t endOfList = 0;
454 // Walk the MultiRecord headers until the last record
455 while (!endOfList)
456 {
457 // The MSB in the second byte of the MultiRecord header signals
458 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000459 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800460 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000461 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800462 // This length is in bytes (not 8 bytes like other headers)
463 areaLength += 5; // The length omits the 5 byte header
464 if (!endOfList)
465 {
466 // Next MultiRecord header
467 lastRecordStart += areaLength;
468 }
469 }
470 }
471 else
472 {
473 // This FRU does not have a MultiRecord Area
474 // Get the length of the area in multiples of 8 bytes
475 if (lastWriteAddr > (lastRecordStart + 1))
476 {
477 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000478 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800479 areaLength *= 8; // it is in multiples of 8 bytes
480 }
481 }
482 if (lastWriteAddr >= (areaLength + lastRecordStart))
483 {
484 atEnd = true;
485 }
486 }
487 uint8_t countWritten = 0;
488
489 writeBus = cacheBus;
490 writeAddr = cacheAddr;
491 if (atEnd)
492 {
493 // cancel timer, we're at the end so might as well send it
494 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000495 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800496 {
497 return ipmi::responseInvalidFieldRequest();
498 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000499 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800500 }
501 else
502 {
Sui Chen548d1a22022-09-14 07:41:17 -0700503 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800504 // start a timer, if no further data is sent to check to see if it is
505 // valid
506 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
507 std::chrono::seconds(writeTimeoutSeconds)));
508 countWritten = 0;
509 }
510
511 return ipmi::responseSuccess(countWritten);
512}
513
514/** @brief implements the get FRU inventory area info command
515 * @param fruDeviceId - FRU Device ID
516 *
517 * @returns IPMI completion code plus response data
518 * - inventorySize - Number of possible allocation units
519 * - accessType - Allocation unit size in bytes.
520 */
521ipmi::RspType<uint16_t, // inventorySize
522 uint8_t> // accessType
523 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
524{
525 if (fruDeviceId == 0xFF)
526 {
527 return ipmi::responseInvalidFieldRequest();
528 }
529
Willy Tu48fe64e2022-08-01 23:23:46 +0000530 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800531 if (ret != ipmi::ccSuccess)
532 {
533 return ipmi::response(ret);
534 }
535
536 constexpr uint8_t accessType =
537 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
538
Willy Tu48fe64e2022-08-01 23:23:46 +0000539 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800540}
541
Willy Tu11d68892022-01-20 10:37:34 -0800542ipmi_ret_t getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800543{
544 count = deviceHashes.size();
545 return IPMI_CC_OK;
546}
547
Johnathan Mantey23a722c2023-05-12 08:18:54 -0700548ipmi_ret_t getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
Willy Tude54f482021-01-26 15:59:09 -0800549 get_sdr::SensorDataFruRecord& resp)
550{
551 if (deviceHashes.size() < index)
552 {
553 return IPMI_CC_INVALID_FIELD_REQUEST;
554 }
555 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530556 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800557 uint8_t& address = device->second.second;
558
559 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400560 auto fru = std::find_if(
561 frus.begin(), frus.end(),
562 [bus, address, &fruData](ManagedEntry& entry) {
563 auto findFruDevice =
564 entry.second.find("xyz.openbmc_project.FruDevice");
565 if (findFruDevice == entry.second.end())
566 {
567 return false;
568 }
569 fruData = &(findFruDevice->second);
570 auto findBus = findFruDevice->second.find("BUS");
571 auto findAddress = findFruDevice->second.find("ADDRESS");
572 if (findBus == findFruDevice->second.end() ||
573 findAddress == findFruDevice->second.end())
574 {
575 return false;
576 }
577 if (std::get<uint32_t>(findBus->second) != bus)
578 {
579 return false;
580 }
581 if (std::get<uint32_t>(findAddress->second) != address)
582 {
583 return false;
584 }
585 return true;
586 });
Willy Tude54f482021-01-26 15:59:09 -0800587 if (fru == frus.end())
588 {
589 return IPMI_CC_RESPONSE_ERROR;
590 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530591 std::string name;
Willy Tude54f482021-01-26 15:59:09 -0800592
593#ifdef USING_ENTITY_MANAGER_DECORATORS
594
595 boost::container::flat_map<std::string, Value>* entityData = nullptr;
596
597 // todo: this should really use caching, this is a very inefficient lookup
598 boost::system::error_code ec;
Nan Zhou947da1b2022-09-20 20:40:59 +0000599
Willy Tude54f482021-01-26 15:59:09 -0800600 ManagedObjectType entities = ctx->bus->yield_method_call<ManagedObjectType>(
Nan Zhou947da1b2022-09-20 20:40:59 +0000601 ctx->yield, ec, entityManagerServiceName,
602 "/xyz/openbmc_project/inventory", "org.freedesktop.DBus.ObjectManager",
603 "GetManagedObjects");
Willy Tude54f482021-01-26 15:59:09 -0800604
605 if (ec)
606 {
George Liude6694e2024-07-17 15:22:25 +0800607 lg2::error("GetMangagedObjects for ipmiStorageGetFruInvAreaInfo "
608 "failed: {ERROR}",
609 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800610
611 return ipmi::ccResponseError;
612 }
613
Patrick Williams1318a5e2024-08-16 15:19:54 -0400614 auto entity = std::find_if(
615 entities.begin(), entities.end(),
616 [bus, address, &entityData, &name](ManagedEntry& entry) {
617 auto findFruDevice = entry.second.find(
618 "xyz.openbmc_project.Inventory.Decorator.I2CDevice");
619 if (findFruDevice == entry.second.end())
620 {
621 return false;
622 }
Willy Tude54f482021-01-26 15:59:09 -0800623
Patrick Williams1318a5e2024-08-16 15:19:54 -0400624 // Integer fields added via Entity-Manager json are uint64_ts by
625 // default.
626 auto findBus = findFruDevice->second.find("Bus");
627 auto findAddress = findFruDevice->second.find("Address");
Willy Tude54f482021-01-26 15:59:09 -0800628
Patrick Williams1318a5e2024-08-16 15:19:54 -0400629 if (findBus == findFruDevice->second.end() ||
630 findAddress == findFruDevice->second.end())
631 {
632 return false;
633 }
634 if ((std::get<uint64_t>(findBus->second) != bus) ||
635 (std::get<uint64_t>(findAddress->second) != address))
636 {
637 return false;
638 }
Willy Tude54f482021-01-26 15:59:09 -0800639
Patrick Williams1318a5e2024-08-16 15:19:54 -0400640 auto fruName = findFruDevice->second.find("Name");
641 if (fruName != findFruDevice->second.end())
642 {
643 name = std::get<std::string>(fruName->second);
644 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530645
Patrick Williams1318a5e2024-08-16 15:19:54 -0400646 // At this point we found the device entry and should return
647 // true.
648 auto findIpmiDevice = entry.second.find(
649 "xyz.openbmc_project.Inventory.Decorator.Ipmi");
650 if (findIpmiDevice != entry.second.end())
651 {
652 entityData = &(findIpmiDevice->second);
653 }
Willy Tude54f482021-01-26 15:59:09 -0800654
Patrick Williams1318a5e2024-08-16 15:19:54 -0400655 return true;
656 });
Willy Tude54f482021-01-26 15:59:09 -0800657
658 if (entity == entities.end())
659 {
660 if constexpr (DEBUG)
661 {
662 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
663 "not found for Fru\n");
664 }
665 }
666
667#endif
668
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200669 std::vector<std::string> nameProperties = {
670 "PRODUCT_PRODUCT_NAME", "BOARD_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
671 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
672 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
673
674 for (const std::string& prop : nameProperties)
675 {
676 auto findProp = fruData->find(prop);
677 if (findProp != fruData->end())
678 {
679 name = std::get<std::string>(findProp->second);
680 break;
681 }
682 }
683
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530684 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800685 {
686 name = "UNKNOWN";
687 }
688 if (name.size() > maxFruSdrNameSize)
689 {
690 name = name.substr(0, maxFruSdrNameSize);
691 }
692 size_t sizeDiff = maxFruSdrNameSize - name.size();
693
694 resp.header.record_id_lsb = 0x0; // calling code is to implement these
695 resp.header.record_id_msb = 0x0;
696 resp.header.sdr_version = ipmiSdrVersion;
697 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
698 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
699 resp.key.deviceAddress = 0x20;
700 resp.key.fruID = device->first;
701 resp.key.accessLun = 0x80; // logical / physical fru device
702 resp.key.channelNumber = 0x0;
703 resp.body.reserved = 0x0;
704 resp.body.deviceType = 0x10;
705 resp.body.deviceTypeModifier = 0x0;
706
707 uint8_t entityID = 0;
708 uint8_t entityInstance = 0x1;
709
710#ifdef USING_ENTITY_MANAGER_DECORATORS
711 if (entityData)
712 {
713 auto entityIdProperty = entityData->find("EntityId");
714 auto entityInstanceProperty = entityData->find("EntityInstance");
715
716 if (entityIdProperty != entityData->end())
717 {
718 entityID = static_cast<uint8_t>(
719 std::get<uint64_t>(entityIdProperty->second));
720 }
721 if (entityInstanceProperty != entityData->end())
722 {
723 entityInstance = static_cast<uint8_t>(
724 std::get<uint64_t>(entityInstanceProperty->second));
725 }
726 }
727#endif
728
729 resp.body.entityID = entityID;
730 resp.body.entityInstance = entityInstance;
731
732 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800733 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800734 name.copy(resp.body.deviceID, name.size());
735
736 return IPMI_CC_OK;
737}
738
739static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
740{
741 // Loop through the directory looking for ipmi_sel log files
742 for (const std::filesystem::directory_entry& dirEnt :
743 std::filesystem::directory_iterator(
744 dynamic_sensors::ipmi::sel::selLogDir))
745 {
746 std::string filename = dirEnt.path().filename();
747 if (boost::starts_with(filename,
748 dynamic_sensors::ipmi::sel::selLogFilename))
749 {
750 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400751 selLogFiles.emplace_back(
752 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800753 }
754 }
755 // As the log files rotate, they are appended with a ".#" that is higher for
756 // the older logs. Since we don't expect more than 10 log files, we
757 // can just sort the list to get them in order from newest to oldest
758 std::sort(selLogFiles.begin(), selLogFiles.end());
759
760 return !selLogFiles.empty();
761}
762
763static int countSELEntries()
764{
765 // Get the list of ipmi_sel log files
766 std::vector<std::filesystem::path> selLogFiles;
767 if (!getSELLogFiles(selLogFiles))
768 {
769 return 0;
770 }
771 int numSELEntries = 0;
772 // Loop through each log file and count the number of logs
773 for (const std::filesystem::path& file : selLogFiles)
774 {
775 std::ifstream logStream(file);
776 if (!logStream.is_open())
777 {
778 continue;
779 }
780
781 std::string line;
782 while (std::getline(logStream, line))
783 {
784 numSELEntries++;
785 }
786 }
787 return numSELEntries;
788}
789
790static bool findSELEntry(const int recordID,
791 const std::vector<std::filesystem::path>& selLogFiles,
792 std::string& entry)
793{
794 // Record ID is the first entry field following the timestamp. It is
795 // preceded by a space and followed by a comma
796 std::string search = " " + std::to_string(recordID) + ",";
797
798 // Loop through the ipmi_sel log entries
799 for (const std::filesystem::path& file : selLogFiles)
800 {
801 std::ifstream logStream(file);
802 if (!logStream.is_open())
803 {
804 continue;
805 }
806
807 while (std::getline(logStream, entry))
808 {
809 // Check if the record ID matches
810 if (entry.find(search) != std::string::npos)
811 {
812 return true;
813 }
814 }
815 }
816 return false;
817}
818
819static uint16_t
820 getNextRecordID(const uint16_t recordID,
821 const std::vector<std::filesystem::path>& selLogFiles)
822{
823 uint16_t nextRecordID = recordID + 1;
824 std::string entry;
825 if (findSELEntry(nextRecordID, selLogFiles, entry))
826 {
827 return nextRecordID;
828 }
829 else
830 {
831 return ipmi::sel::lastEntry;
832 }
833}
834
835static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
836{
837 for (unsigned int i = 0; i < hexStr.size(); i += 2)
838 {
839 try
840 {
841 data.push_back(static_cast<uint8_t>(
842 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
843 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500844 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800845 {
George Liude6694e2024-07-17 15:22:25 +0800846 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800847 return -1;
848 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500849 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800850 {
George Liude6694e2024-07-17 15:22:25 +0800851 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800852 return -1;
853 }
854 }
855 return 0;
856}
857
858ipmi::RspType<uint8_t, // SEL version
859 uint16_t, // SEL entry count
860 uint16_t, // free space
861 uint32_t, // last add timestamp
862 uint32_t, // last erase timestamp
863 uint8_t> // operation support
864 ipmiStorageGetSELInfo()
865{
866 constexpr uint8_t selVersion = ipmi::sel::selVersion;
867 uint16_t entries = countSELEntries();
868 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
869 dynamic_sensors::ipmi::sel::selLogDir /
870 dynamic_sensors::ipmi::sel::selLogFilename);
871 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
872 constexpr uint8_t operationSupport =
873 dynamic_sensors::ipmi::sel::selOperationSupport;
874 constexpr uint16_t freeSpace =
875 0xffff; // Spec indicates that more than 64kB is free
876
877 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
878 eraseTimeStamp, operationSupport);
879}
880
881using systemEventType = std::tuple<
882 uint32_t, // Timestamp
883 uint16_t, // Generator ID
884 uint8_t, // EvM Rev
885 uint8_t, // Sensor Type
886 uint8_t, // Sensor Number
887 uint7_t, // Event Type
888 bool, // Event Direction
889 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
890 // Data
891using oemTsEventType = std::tuple<
892 uint32_t, // Timestamp
893 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
894 // Data
895using oemEventType =
896 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
897
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500898ipmi::RspType<uint16_t, // Next Record ID
899 uint16_t, // Record ID
900 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800901 std::variant<systemEventType, oemTsEventType,
902 oemEventType>> // Record Content
903 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
904 uint8_t offset, uint8_t size)
905{
906 // Only support getting the entire SEL record. If a partial size or non-zero
907 // offset is requested, return an error
908 if (offset != 0 || size != ipmi::sel::entireRecord)
909 {
910 return ipmi::responseRetBytesUnavailable();
911 }
912
913 // Check the reservation ID if one is provided or required (only if the
914 // offset is non-zero)
915 if (reservationID != 0 || offset != 0)
916 {
917 if (!checkSELReservation(reservationID))
918 {
919 return ipmi::responseInvalidReservationId();
920 }
921 }
922
923 // Get the ipmi_sel log files
924 std::vector<std::filesystem::path> selLogFiles;
925 if (!getSELLogFiles(selLogFiles))
926 {
927 return ipmi::responseSensorInvalid();
928 }
929
930 std::string targetEntry;
931
932 if (targetID == ipmi::sel::firstEntry)
933 {
934 // The first entry will be at the top of the oldest log file
935 std::ifstream logStream(selLogFiles.back());
936 if (!logStream.is_open())
937 {
938 return ipmi::responseUnspecifiedError();
939 }
940
941 if (!std::getline(logStream, targetEntry))
942 {
943 return ipmi::responseUnspecifiedError();
944 }
945 }
946 else if (targetID == ipmi::sel::lastEntry)
947 {
948 // The last entry will be at the bottom of the newest log file
949 std::ifstream logStream(selLogFiles.front());
950 if (!logStream.is_open())
951 {
952 return ipmi::responseUnspecifiedError();
953 }
954
955 std::string line;
956 while (std::getline(logStream, line))
957 {
958 targetEntry = line;
959 }
960 }
961 else
962 {
963 if (!findSELEntry(targetID, selLogFiles, targetEntry))
964 {
965 return ipmi::responseSensorInvalid();
966 }
967 }
968
969 // The format of the ipmi_sel message is "<Timestamp>
970 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
971 // First get the Timestamp
972 size_t space = targetEntry.find_first_of(" ");
973 if (space == std::string::npos)
974 {
975 return ipmi::responseUnspecifiedError();
976 }
977 std::string entryTimestamp = targetEntry.substr(0, space);
978 // Then get the log contents
979 size_t entryStart = targetEntry.find_first_not_of(" ", space);
980 if (entryStart == std::string::npos)
981 {
982 return ipmi::responseUnspecifiedError();
983 }
984 std::string_view entry(targetEntry);
985 entry.remove_prefix(entryStart);
986 // Use split to separate the entry into its fields
987 std::vector<std::string> targetEntryFields;
988 boost::split(targetEntryFields, entry, boost::is_any_of(","),
989 boost::token_compress_on);
990 if (targetEntryFields.size() < 3)
991 {
992 return ipmi::responseUnspecifiedError();
993 }
994 std::string& recordIDStr = targetEntryFields[0];
995 std::string& recordTypeStr = targetEntryFields[1];
996 std::string& eventDataStr = targetEntryFields[2];
997
998 uint16_t recordID;
999 uint8_t recordType;
1000 try
1001 {
1002 recordID = std::stoul(recordIDStr);
1003 recordType = std::stoul(recordTypeStr, nullptr, 16);
1004 }
1005 catch (const std::invalid_argument&)
1006 {
1007 return ipmi::responseUnspecifiedError();
1008 }
1009 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1010 std::vector<uint8_t> eventDataBytes;
1011 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1012 {
1013 return ipmi::responseUnspecifiedError();
1014 }
1015
1016 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1017 {
1018 // Get the timestamp
1019 std::tm timeStruct = {};
1020 std::istringstream entryStream(entryTimestamp);
1021
1022 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1023 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1024 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001025 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001026 timestamp = std::mktime(&timeStruct);
1027 }
1028
1029 // Set the event message revision
1030 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1031
1032 uint16_t generatorID = 0;
1033 uint8_t sensorType = 0;
1034 uint16_t sensorAndLun = 0;
1035 uint8_t sensorNum = 0xFF;
1036 uint7_t eventType = 0;
1037 bool eventDir = 0;
1038 // System type events should have six fields
1039 if (targetEntryFields.size() >= 6)
1040 {
1041 std::string& generatorIDStr = targetEntryFields[3];
1042 std::string& sensorPath = targetEntryFields[4];
1043 std::string& eventDirStr = targetEntryFields[5];
1044
1045 // Get the generator ID
1046 try
1047 {
1048 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1049 }
1050 catch (const std::invalid_argument&)
1051 {
1052 std::cerr << "Invalid Generator ID\n";
1053 }
1054
1055 // Get the sensor type, sensor number, and event type for the sensor
1056 sensorType = getSensorTypeFromPath(sensorPath);
1057 sensorAndLun = getSensorNumberFromPath(sensorPath);
1058 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001059 if ((generatorID & 0x0001) == 0)
1060 {
1061 // IPMB Address
1062 generatorID |= sensorAndLun & 0x0300;
1063 }
1064 else
1065 {
1066 // system software
1067 generatorID |= sensorAndLun >> 8;
1068 }
Willy Tude54f482021-01-26 15:59:09 -08001069 eventType = getSensorEventTypeFromPath(sensorPath);
1070
1071 // Get the event direction
1072 try
1073 {
1074 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1075 }
1076 catch (const std::invalid_argument&)
1077 {
1078 std::cerr << "Invalid Event Direction\n";
1079 }
1080 }
1081
1082 // Only keep the eventData bytes that fit in the record
1083 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1084 eventData{};
1085 std::copy_n(eventDataBytes.begin(),
1086 std::min(eventDataBytes.size(), eventData.size()),
1087 eventData.begin());
1088
1089 return ipmi::responseSuccess(
1090 nextRecordID, recordID, recordType,
1091 systemEventType{timestamp, generatorID, evmRev, sensorType,
1092 sensorNum, eventType, eventDir, eventData});
1093 }
1094
Thang Trane70c59b2023-09-21 13:54:28 +07001095 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1096 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1097 {
1098 // Get the timestamp
1099 std::tm timeStruct = {};
1100 std::istringstream entryStream(entryTimestamp);
1101
1102 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1103 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1104 {
1105 timeStruct.tm_isdst = -1;
1106 timestamp = std::mktime(&timeStruct);
1107 }
1108
1109 // Only keep the bytes that fit in the record
1110 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1111 eventData{};
1112 std::copy_n(eventDataBytes.begin(),
1113 std::min(eventDataBytes.size(), eventData.size()),
1114 eventData.begin());
1115
1116 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1117 oemTsEventType{timestamp, eventData});
1118 }
1119
1120 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1121 {
1122 // Only keep the bytes that fit in the record
1123 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1124 eventData{};
1125 std::copy_n(eventDataBytes.begin(),
1126 std::min(eventDataBytes.size(), eventData.size()),
1127 eventData.begin());
1128
1129 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1130 eventData);
1131 }
1132
Willy Tude54f482021-01-26 15:59:09 -08001133 return ipmi::responseUnspecifiedError();
1134}
1135
Willy Tu11d68892022-01-20 10:37:34 -08001136/*
1137Unused arguments
1138 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1139 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1140 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1141 uint8_t eventData3
1142*/
Patrick Williams1318a5e2024-08-16 15:19:54 -04001143ipmi::RspType<uint16_t>
1144 ipmiStorageAddSELEntry(uint16_t, uint8_t, uint32_t, uint16_t, uint8_t,
1145 uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001146{
1147 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1148 // added
1149 cancelSELReservation();
1150
1151 uint16_t responseID = 0xFFFF;
1152 return ipmi::responseSuccess(responseID);
1153}
1154
Patrick Williams1318a5e2024-08-16 15:19:54 -04001155ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1156 ipmi::Context::ptr ctx, uint16_t reservationID,
1157 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001158{
1159 if (!checkSELReservation(reservationID))
1160 {
1161 return ipmi::responseInvalidReservationId();
1162 }
1163
1164 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1165 if (clr != clrExpected)
1166 {
1167 return ipmi::responseInvalidFieldRequest();
1168 }
1169
1170 // Erasure status cannot be fetched, so always return erasure status as
1171 // `erase completed`.
1172 if (eraseOperation == ipmi::sel::getEraseStatus)
1173 {
1174 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1175 }
1176
1177 // Check that initiate erase is correct
1178 if (eraseOperation != ipmi::sel::initiateErase)
1179 {
1180 return ipmi::responseInvalidFieldRequest();
1181 }
1182
1183 // Per the IPMI spec, need to cancel any reservation when the SEL is
1184 // cleared
1185 cancelSELReservation();
1186
Charles Boyer818bea12021-09-20 16:56:36 -05001187 boost::system::error_code ec;
1188 ctx->bus->yield_method_call<>(ctx->yield, ec, selLoggerServiceName,
1189 "/xyz/openbmc_project/Logging/IPMI",
1190 "xyz.openbmc_project.Logging.IPMI", "Clear");
1191 if (ec)
1192 {
1193 std::cerr << "error in clear SEL: " << ec << std::endl;
1194 return ipmi::responseUnspecifiedError();
1195 }
Willy Tude54f482021-01-26 15:59:09 -08001196
1197 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1198}
1199
Patrick Williams1318a5e2024-08-16 15:19:54 -04001200std::vector<uint8_t> getType8SDRs(
1201 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001202{
1203 std::vector<uint8_t> resp;
1204 get_sdr::SensorDataEntityRecord data{};
1205
1206 /* Header */
1207 get_sdr::header::set_record_id(recordId, &(data.header));
1208 // Based on IPMI Spec v2.0 rev 1.1
1209 data.header.sdr_version = SDR_VERSION;
1210 data.header.record_type = 0x08;
1211 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1212
1213 /* Key */
1214 data.key.containerEntityId = entity->second.containerEntityId;
1215 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1216 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1217 &(data.key));
1218 data.key.entityId1 = entity->second.containedEntities[0].first;
1219 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1220
1221 /* Body */
1222 data.body.entityId2 = entity->second.containedEntities[1].first;
1223 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1224 data.body.entityId3 = entity->second.containedEntities[2].first;
1225 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1226 data.body.entityId4 = entity->second.containedEntities[3].first;
1227 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1228
1229 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1230
1231 return resp;
1232}
1233
Willy Tude54f482021-01-26 15:59:09 -08001234std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1235{
1236 std::vector<uint8_t> resp;
1237 if (index == 0)
1238 {
Willy Tude54f482021-01-26 15:59:09 -08001239 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001240 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001241 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1242 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1243 }
1244 else if (index == 1)
1245 {
Willy Tude54f482021-01-26 15:59:09 -08001246 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001247 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001248 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1249 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1250 }
1251 else
1252 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001253 throw std::runtime_error(
1254 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001255 }
1256
1257 return resp;
1258}
1259
1260void registerStorageFunctions()
1261{
1262 createTimers();
1263 startMatch();
1264
1265 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001266 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001267 ipmi::storage::cmdGetFruInventoryAreaInfo,
1268 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1269 // <READ FRU Data>
1270 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1271 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1272 ipmiStorageReadFruData);
1273
1274 // <WRITE FRU Data>
1275 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1276 ipmi::storage::cmdWriteFruData,
1277 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1278
1279 // <Get SEL Info>
1280 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1281 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1282 ipmiStorageGetSELInfo);
1283
1284 // <Get SEL Entry>
1285 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1286 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1287 ipmiStorageGetSELEntry);
1288
1289 // <Add SEL Entry>
1290 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1291 ipmi::storage::cmdAddSelEntry,
1292 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1293
1294 // <Clear SEL>
1295 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1296 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1297 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001298}
1299} // namespace storage
1300} // namespace ipmi