blob: a93a04598bbb4ddb935496dec274fd67d01e3fcc [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
74constexpr static const size_t maxMessageSize = 64;
75constexpr static const size_t maxFruSdrNameSize = 16;
76using ObjectType =
77 boost::container::flat_map<std::string,
78 boost::container::flat_map<std::string, Value>>;
79using ManagedObjectType =
80 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
81using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
82
Charles Boyer818bea12021-09-20 16:56:36 -050083constexpr static const char* selLoggerServiceName =
84 "xyz.openbmc_project.Logging.IPMI";
Willy Tude54f482021-01-26 15:59:09 -080085constexpr static const char* fruDeviceServiceName =
86 "xyz.openbmc_project.FruDevice";
87constexpr static const char* entityManagerServiceName =
88 "xyz.openbmc_project.EntityManager";
89constexpr static const size_t writeTimeoutSeconds = 10;
90constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -050091constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -080092
93// event direction is bit[7] of eventType where 1b = Deassertion event
94constexpr static const uint8_t deassertionEvent = 0x80;
95
96static std::vector<uint8_t> fruCache;
krishnar4d90b3f02022-11-11 16:18:32 +053097static constexpr uint16_t invalidBus = 0xFFFF;
98static constexpr uint8_t invalidAddr = 0xFF;
Johnathan Manteyb99de182023-12-21 08:28:18 -080099static constexpr uint8_t typeASCIILatin8 = 0xC0;
krishnar4d90b3f02022-11-11 16:18:32 +0530100static uint16_t cacheBus = invalidBus;
101static uint8_t cacheAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800102static uint8_t lastDevId = 0xFF;
103
krishnar4d90b3f02022-11-11 16:18:32 +0530104static uint16_t writeBus = invalidBus;
105static uint8_t writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800106
Patrick Williams95655222023-12-05 12:45:02 -0600107std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
Patrick Williams5d82f472022-07-22 19:26:53 -0500108static std::vector<sdbusplus::bus::match_t> fruMatches;
Willy Tude54f482021-01-26 15:59:09 -0800109
110ManagedObjectType frus;
111
112// we unfortunately have to build a map of hashes in case there is a
113// collision to verify our dev-id
krishnar4d90b3f02022-11-11 16:18:32 +0530114boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
Willy Tude54f482021-01-26 15:59:09 -0800115void registerStorageFunctions() __attribute__((constructor));
116
Willy Tu48fe64e2022-08-01 23:23:46 +0000117bool writeFru(const std::vector<uint8_t>& fru)
Willy Tude54f482021-01-26 15:59:09 -0800118{
krishnar4d90b3f02022-11-11 16:18:32 +0530119 if (writeBus == invalidBus && writeAddr == invalidAddr)
Willy Tude54f482021-01-26 15:59:09 -0800120 {
121 return true;
122 }
Thang Trand934be92021-12-08 10:13:50 +0700123 lastDevId = 0xFF;
Willy Tude54f482021-01-26 15:59:09 -0800124 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
Patrick Williams5d82f472022-07-22 19:26:53 -0500125 sdbusplus::message_t writeFru = dbus->new_method_call(
Willy Tude54f482021-01-26 15:59:09 -0800126 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
127 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
Willy Tu48fe64e2022-08-01 23:23:46 +0000128 writeFru.append(writeBus, writeAddr, fru);
Willy Tude54f482021-01-26 15:59:09 -0800129 try
130 {
Patrick Williams5d82f472022-07-22 19:26:53 -0500131 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
Willy Tude54f482021-01-26 15:59:09 -0800132 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500133 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800134 {
135 // todo: log sel?
George Liude6694e2024-07-17 15:22:25 +0800136 lg2::error("error writing fru");
Willy Tude54f482021-01-26 15:59:09 -0800137 return false;
138 }
krishnar4d90b3f02022-11-11 16:18:32 +0530139 writeBus = invalidBus;
140 writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800141 return true;
142}
143
William A. Kennington III52535622022-11-28 18:28:22 -0800144void writeFruCache()
Willy Tu48fe64e2022-08-01 23:23:46 +0000145{
William A. Kennington III52535622022-11-28 18:28:22 -0800146 writeFru(fruCache);
Willy Tu48fe64e2022-08-01 23:23:46 +0000147}
148
Willy Tude54f482021-01-26 15:59:09 -0800149void createTimers()
150{
Patrick Williams95655222023-12-05 12:45:02 -0600151 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
Willy Tude54f482021-01-26 15:59:09 -0800152}
153
154void recalculateHashes()
155{
Willy Tude54f482021-01-26 15:59:09 -0800156 deviceHashes.clear();
157 // hash the object paths to create unique device id's. increment on
158 // collision
159 std::hash<std::string> hasher;
160 for (const auto& fru : frus)
161 {
162 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
163 if (fruIface == fru.second.end())
164 {
165 continue;
166 }
167
168 auto busFind = fruIface->second.find("BUS");
169 auto addrFind = fruIface->second.find("ADDRESS");
170 if (busFind == fruIface->second.end() ||
171 addrFind == fruIface->second.end())
172 {
George Liude6694e2024-07-17 15:22:25 +0800173 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
174 fru.first.str);
Willy Tude54f482021-01-26 15:59:09 -0800175 continue;
176 }
177
krishnar4d90b3f02022-11-11 16:18:32 +0530178 uint16_t fruBus = std::get<uint32_t>(busFind->second);
Willy Tude54f482021-01-26 15:59:09 -0800179 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
180 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
181 std::string chassisType;
182 if (chassisFind != fruIface->second.end())
183 {
184 chassisType = std::get<std::string>(chassisFind->second);
185 }
186
187 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500188 if (chassisType.compare(chassisTypeRackMount) != 0 &&
189 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800190 {
191 fruHash = hasher(fru.first.str);
192 // can't be 0xFF based on spec, and 0 is reserved for baseboard
193 if (fruHash == 0 || fruHash == 0xFF)
194 {
195 fruHash = 1;
196 }
197 }
krishnar4d90b3f02022-11-11 16:18:32 +0530198 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
Willy Tude54f482021-01-26 15:59:09 -0800199
200 bool emplacePassed = false;
201 while (!emplacePassed)
202 {
203 auto resp = deviceHashes.emplace(fruHash, newDev);
204 emplacePassed = resp.second;
205 if (!emplacePassed)
206 {
207 fruHash++;
208 // can't be 0xFF based on spec, and 0 is reserved for
209 // baseboard
210 if (fruHash == 0XFF)
211 {
212 fruHash = 0x1;
213 }
214 }
215 }
216 }
217}
218
Willy Tu11d68892022-01-20 10:37:34 -0800219void replaceCacheFru(
220 const std::shared_ptr<sdbusplus::asio::connection>& bus,
221 boost::asio::yield_context& yield,
222 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
Willy Tude54f482021-01-26 15:59:09 -0800223{
224 boost::system::error_code ec;
225
226 frus = bus->yield_method_call<ManagedObjectType>(
227 yield, ec, fruDeviceServiceName, "/",
228 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
229 if (ec)
230 {
George Liude6694e2024-07-17 15:22:25 +0800231 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
232 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800233
234 return;
235 }
236 recalculateHashes();
237}
238
Patrick Williams1318a5e2024-08-16 15:19:54 -0400239std::pair<ipmi::Cc, std::vector<uint8_t>>
240 getFru(ipmi::Context::ptr ctx, uint8_t devId)
Willy Tude54f482021-01-26 15:59:09 -0800241{
242 if (lastDevId == devId && devId != 0xFF)
243 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000244 return {ipmi::ccSuccess, fruCache};
Willy Tude54f482021-01-26 15:59:09 -0800245 }
246
Willy Tude54f482021-01-26 15:59:09 -0800247 auto deviceFind = deviceHashes.find(devId);
248 if (deviceFind == deviceHashes.end())
249 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000250 return {IPMI_CC_SENSOR_INVALID, {}};
Willy Tude54f482021-01-26 15:59:09 -0800251 }
252
Willy Tude54f482021-01-26 15:59:09 -0800253 cacheBus = deviceFind->second.first;
254 cacheAddr = deviceFind->second.second;
255
256 boost::system::error_code ec;
257
Willy Tu48fe64e2022-08-01 23:23:46 +0000258 std::vector<uint8_t> fru =
259 ctx->bus->yield_method_call<std::vector<uint8_t>>(
260 ctx->yield, ec, fruDeviceServiceName,
261 "/xyz/openbmc_project/FruDevice",
262 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
263 cacheAddr);
Willy Tude54f482021-01-26 15:59:09 -0800264 if (ec)
265 {
George Liude6694e2024-07-17 15:22:25 +0800266 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800267
krishnar4d90b3f02022-11-11 16:18:32 +0530268 cacheBus = invalidBus;
269 cacheAddr = invalidAddr;
Willy Tu48fe64e2022-08-01 23:23:46 +0000270 return {ipmi::ccResponseError, {}};
Willy Tude54f482021-01-26 15:59:09 -0800271 }
272
Willy Tu48fe64e2022-08-01 23:23:46 +0000273 fruCache.clear();
Willy Tude54f482021-01-26 15:59:09 -0800274 lastDevId = devId;
Willy Tu48fe64e2022-08-01 23:23:46 +0000275 fruCache = fru;
276
277 return {ipmi::ccSuccess, fru};
Willy Tude54f482021-01-26 15:59:09 -0800278}
279
280void writeFruIfRunning()
281{
282 if (!writeTimer->isRunning())
283 {
284 return;
285 }
286 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000287 writeFruCache();
Willy Tude54f482021-01-26 15:59:09 -0800288}
289
290void startMatch(void)
291{
292 if (fruMatches.size())
293 {
294 return;
295 }
296
297 fruMatches.reserve(2);
298
299 auto bus = getSdBus();
Patrick Williams1318a5e2024-08-16 15:19:54 -0400300 fruMatches.emplace_back(
301 *bus,
302 "type='signal',arg0path='/xyz/openbmc_project/"
303 "FruDevice/',member='InterfacesAdded'",
304 [](sdbusplus::message_t& message) {
305 sdbusplus::message::object_path path;
306 ObjectType object;
307 try
308 {
309 message.read(path, object);
310 }
311 catch (const sdbusplus::exception_t&)
312 {
313 return;
314 }
315 auto findType = object.find("xyz.openbmc_project.FruDevice");
316 if (findType == object.end())
317 {
318 return;
319 }
320 writeFruIfRunning();
321 frus[path] = object;
322 recalculateHashes();
323 lastDevId = 0xFF;
324 });
Willy Tude54f482021-01-26 15:59:09 -0800325
Patrick Williams1318a5e2024-08-16 15:19:54 -0400326 fruMatches.emplace_back(
327 *bus,
328 "type='signal',arg0path='/xyz/openbmc_project/"
329 "FruDevice/',member='InterfacesRemoved'",
330 [](sdbusplus::message_t& message) {
331 sdbusplus::message::object_path path;
332 std::set<std::string> interfaces;
333 try
334 {
335 message.read(path, interfaces);
336 }
337 catch (const sdbusplus::exception_t&)
338 {
339 return;
340 }
341 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
342 if (findType == interfaces.end())
343 {
344 return;
345 }
346 writeFruIfRunning();
347 frus.erase(path);
348 recalculateHashes();
349 lastDevId = 0xFF;
350 });
Willy Tude54f482021-01-26 15:59:09 -0800351
352 // call once to populate
353 boost::asio::spawn(*getIoContext(), [](boost::asio::yield_context yield) {
354 replaceCacheFru(getSdBus(), yield);
355 });
356}
357
358/** @brief implements the read FRU data command
359 * @param fruDeviceId - FRU Device ID
360 * @param fruInventoryOffset - FRU Inventory Offset to write
361 * @param countToRead - Count to read
362 *
363 * @returns ipmi completion code plus response data
364 * - countWritten - Count written
365 */
366ipmi::RspType<uint8_t, // Count
367 std::vector<uint8_t> // Requested data
368 >
369 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
370 uint16_t fruInventoryOffset, uint8_t countToRead)
371{
372 if (fruDeviceId == 0xFF)
373 {
374 return ipmi::responseInvalidFieldRequest();
375 }
376
Willy Tu48fe64e2022-08-01 23:23:46 +0000377 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800378 if (status != ipmi::ccSuccess)
379 {
380 return ipmi::response(status);
381 }
382
383 size_t fromFruByteLen = 0;
Willy Tu48fe64e2022-08-01 23:23:46 +0000384 if (countToRead + fruInventoryOffset < fru.size())
Willy Tude54f482021-01-26 15:59:09 -0800385 {
386 fromFruByteLen = countToRead;
387 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000388 else if (fru.size() > fruInventoryOffset)
Willy Tude54f482021-01-26 15:59:09 -0800389 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000390 fromFruByteLen = fru.size() - fruInventoryOffset;
Willy Tude54f482021-01-26 15:59:09 -0800391 }
392 else
393 {
394 return ipmi::responseReqDataLenExceeded();
395 }
396
397 std::vector<uint8_t> requestedData;
398
Willy Tu48fe64e2022-08-01 23:23:46 +0000399 requestedData.insert(requestedData.begin(),
400 fru.begin() + fruInventoryOffset,
401 fru.begin() + fruInventoryOffset + fromFruByteLen);
Willy Tude54f482021-01-26 15:59:09 -0800402
403 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
404 requestedData);
405}
406
407/** @brief implements the write FRU data command
408 * @param fruDeviceId - FRU Device ID
409 * @param fruInventoryOffset - FRU Inventory Offset to write
410 * @param dataToWrite - Data to write
411 *
412 * @returns ipmi completion code plus response data
413 * - countWritten - Count written
414 */
Patrick Williams1318a5e2024-08-16 15:19:54 -0400415ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
416 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
417 std::vector<uint8_t>& dataToWrite)
Willy Tude54f482021-01-26 15:59:09 -0800418{
419 if (fruDeviceId == 0xFF)
420 {
421 return ipmi::responseInvalidFieldRequest();
422 }
423
424 size_t writeLen = dataToWrite.size();
425
Willy Tu48fe64e2022-08-01 23:23:46 +0000426 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800427 if (status != ipmi::ccSuccess)
428 {
429 return ipmi::response(status);
430 }
431 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000432 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800433 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000434 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800435 }
436
437 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000438 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800439
440 bool atEnd = false;
441
Willy Tu48fe64e2022-08-01 23:23:46 +0000442 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800443 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000444 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800445
446 size_t areaLength = 0;
447 size_t lastRecordStart = std::max(
448 {header->internalOffset, header->chassisOffset, header->boardOffset,
449 header->productOffset, header->multiRecordOffset});
450 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
451
452 if (header->multiRecordOffset)
453 {
454 // This FRU has a MultiRecord Area
455 uint8_t endOfList = 0;
456 // Walk the MultiRecord headers until the last record
457 while (!endOfList)
458 {
459 // The MSB in the second byte of the MultiRecord header signals
460 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000461 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800462 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000463 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800464 // This length is in bytes (not 8 bytes like other headers)
465 areaLength += 5; // The length omits the 5 byte header
466 if (!endOfList)
467 {
468 // Next MultiRecord header
469 lastRecordStart += areaLength;
470 }
471 }
472 }
473 else
474 {
475 // This FRU does not have a MultiRecord Area
476 // Get the length of the area in multiples of 8 bytes
477 if (lastWriteAddr > (lastRecordStart + 1))
478 {
479 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000480 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800481 areaLength *= 8; // it is in multiples of 8 bytes
482 }
483 }
484 if (lastWriteAddr >= (areaLength + lastRecordStart))
485 {
486 atEnd = true;
487 }
488 }
489 uint8_t countWritten = 0;
490
491 writeBus = cacheBus;
492 writeAddr = cacheAddr;
493 if (atEnd)
494 {
495 // cancel timer, we're at the end so might as well send it
496 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000497 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800498 {
499 return ipmi::responseInvalidFieldRequest();
500 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000501 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800502 }
503 else
504 {
Sui Chen548d1a22022-09-14 07:41:17 -0700505 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800506 // start a timer, if no further data is sent to check to see if it is
507 // valid
508 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
509 std::chrono::seconds(writeTimeoutSeconds)));
510 countWritten = 0;
511 }
512
513 return ipmi::responseSuccess(countWritten);
514}
515
516/** @brief implements the get FRU inventory area info command
517 * @param fruDeviceId - FRU Device ID
518 *
519 * @returns IPMI completion code plus response data
520 * - inventorySize - Number of possible allocation units
521 * - accessType - Allocation unit size in bytes.
522 */
523ipmi::RspType<uint16_t, // inventorySize
524 uint8_t> // accessType
525 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
526{
527 if (fruDeviceId == 0xFF)
528 {
529 return ipmi::responseInvalidFieldRequest();
530 }
531
Willy Tu48fe64e2022-08-01 23:23:46 +0000532 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800533 if (ret != ipmi::ccSuccess)
534 {
535 return ipmi::response(ret);
536 }
537
538 constexpr uint8_t accessType =
539 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
540
Willy Tu48fe64e2022-08-01 23:23:46 +0000541 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800542}
543
Willy Tu11d68892022-01-20 10:37:34 -0800544ipmi_ret_t getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800545{
546 count = deviceHashes.size();
547 return IPMI_CC_OK;
548}
549
Johnathan Mantey23a722c2023-05-12 08:18:54 -0700550ipmi_ret_t getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
Willy Tude54f482021-01-26 15:59:09 -0800551 get_sdr::SensorDataFruRecord& resp)
552{
553 if (deviceHashes.size() < index)
554 {
555 return IPMI_CC_INVALID_FIELD_REQUEST;
556 }
557 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530558 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800559 uint8_t& address = device->second.second;
560
561 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400562 auto fru = std::find_if(
563 frus.begin(), frus.end(),
564 [bus, address, &fruData](ManagedEntry& entry) {
565 auto findFruDevice =
566 entry.second.find("xyz.openbmc_project.FruDevice");
567 if (findFruDevice == entry.second.end())
568 {
569 return false;
570 }
571 fruData = &(findFruDevice->second);
572 auto findBus = findFruDevice->second.find("BUS");
573 auto findAddress = findFruDevice->second.find("ADDRESS");
574 if (findBus == findFruDevice->second.end() ||
575 findAddress == findFruDevice->second.end())
576 {
577 return false;
578 }
579 if (std::get<uint32_t>(findBus->second) != bus)
580 {
581 return false;
582 }
583 if (std::get<uint32_t>(findAddress->second) != address)
584 {
585 return false;
586 }
587 return true;
588 });
Willy Tude54f482021-01-26 15:59:09 -0800589 if (fru == frus.end())
590 {
591 return IPMI_CC_RESPONSE_ERROR;
592 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530593 std::string name;
Willy Tude54f482021-01-26 15:59:09 -0800594
595#ifdef USING_ENTITY_MANAGER_DECORATORS
596
597 boost::container::flat_map<std::string, Value>* entityData = nullptr;
598
599 // todo: this should really use caching, this is a very inefficient lookup
600 boost::system::error_code ec;
Nan Zhou947da1b2022-09-20 20:40:59 +0000601
Willy Tude54f482021-01-26 15:59:09 -0800602 ManagedObjectType entities = ctx->bus->yield_method_call<ManagedObjectType>(
Nan Zhou947da1b2022-09-20 20:40:59 +0000603 ctx->yield, ec, entityManagerServiceName,
604 "/xyz/openbmc_project/inventory", "org.freedesktop.DBus.ObjectManager",
605 "GetManagedObjects");
Willy Tude54f482021-01-26 15:59:09 -0800606
607 if (ec)
608 {
George Liude6694e2024-07-17 15:22:25 +0800609 lg2::error("GetMangagedObjects for ipmiStorageGetFruInvAreaInfo "
610 "failed: {ERROR}",
611 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800612
613 return ipmi::ccResponseError;
614 }
615
Patrick Williams1318a5e2024-08-16 15:19:54 -0400616 auto entity = std::find_if(
617 entities.begin(), entities.end(),
618 [bus, address, &entityData, &name](ManagedEntry& entry) {
619 auto findFruDevice = entry.second.find(
620 "xyz.openbmc_project.Inventory.Decorator.I2CDevice");
621 if (findFruDevice == entry.second.end())
622 {
623 return false;
624 }
Willy Tude54f482021-01-26 15:59:09 -0800625
Patrick Williams1318a5e2024-08-16 15:19:54 -0400626 // Integer fields added via Entity-Manager json are uint64_ts by
627 // default.
628 auto findBus = findFruDevice->second.find("Bus");
629 auto findAddress = findFruDevice->second.find("Address");
Willy Tude54f482021-01-26 15:59:09 -0800630
Patrick Williams1318a5e2024-08-16 15:19:54 -0400631 if (findBus == findFruDevice->second.end() ||
632 findAddress == findFruDevice->second.end())
633 {
634 return false;
635 }
636 if ((std::get<uint64_t>(findBus->second) != bus) ||
637 (std::get<uint64_t>(findAddress->second) != address))
638 {
639 return false;
640 }
Willy Tude54f482021-01-26 15:59:09 -0800641
Patrick Williams1318a5e2024-08-16 15:19:54 -0400642 auto fruName = findFruDevice->second.find("Name");
643 if (fruName != findFruDevice->second.end())
644 {
645 name = std::get<std::string>(fruName->second);
646 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530647
Patrick Williams1318a5e2024-08-16 15:19:54 -0400648 // At this point we found the device entry and should return
649 // true.
650 auto findIpmiDevice = entry.second.find(
651 "xyz.openbmc_project.Inventory.Decorator.Ipmi");
652 if (findIpmiDevice != entry.second.end())
653 {
654 entityData = &(findIpmiDevice->second);
655 }
Willy Tude54f482021-01-26 15:59:09 -0800656
Patrick Williams1318a5e2024-08-16 15:19:54 -0400657 return true;
658 });
Willy Tude54f482021-01-26 15:59:09 -0800659
660 if (entity == entities.end())
661 {
662 if constexpr (DEBUG)
663 {
664 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
665 "not found for Fru\n");
666 }
667 }
668
669#endif
670
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200671 std::vector<std::string> nameProperties = {
672 "PRODUCT_PRODUCT_NAME", "BOARD_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
673 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
674 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
675
676 for (const std::string& prop : nameProperties)
677 {
678 auto findProp = fruData->find(prop);
679 if (findProp != fruData->end())
680 {
681 name = std::get<std::string>(findProp->second);
682 break;
683 }
684 }
685
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530686 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800687 {
688 name = "UNKNOWN";
689 }
690 if (name.size() > maxFruSdrNameSize)
691 {
692 name = name.substr(0, maxFruSdrNameSize);
693 }
694 size_t sizeDiff = maxFruSdrNameSize - name.size();
695
696 resp.header.record_id_lsb = 0x0; // calling code is to implement these
697 resp.header.record_id_msb = 0x0;
698 resp.header.sdr_version = ipmiSdrVersion;
699 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
700 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
701 resp.key.deviceAddress = 0x20;
702 resp.key.fruID = device->first;
703 resp.key.accessLun = 0x80; // logical / physical fru device
704 resp.key.channelNumber = 0x0;
705 resp.body.reserved = 0x0;
706 resp.body.deviceType = 0x10;
707 resp.body.deviceTypeModifier = 0x0;
708
709 uint8_t entityID = 0;
710 uint8_t entityInstance = 0x1;
711
712#ifdef USING_ENTITY_MANAGER_DECORATORS
713 if (entityData)
714 {
715 auto entityIdProperty = entityData->find("EntityId");
716 auto entityInstanceProperty = entityData->find("EntityInstance");
717
718 if (entityIdProperty != entityData->end())
719 {
720 entityID = static_cast<uint8_t>(
721 std::get<uint64_t>(entityIdProperty->second));
722 }
723 if (entityInstanceProperty != entityData->end())
724 {
725 entityInstance = static_cast<uint8_t>(
726 std::get<uint64_t>(entityInstanceProperty->second));
727 }
728 }
729#endif
730
731 resp.body.entityID = entityID;
732 resp.body.entityInstance = entityInstance;
733
734 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800735 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800736 name.copy(resp.body.deviceID, name.size());
737
738 return IPMI_CC_OK;
739}
740
741static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
742{
743 // Loop through the directory looking for ipmi_sel log files
744 for (const std::filesystem::directory_entry& dirEnt :
745 std::filesystem::directory_iterator(
746 dynamic_sensors::ipmi::sel::selLogDir))
747 {
748 std::string filename = dirEnt.path().filename();
749 if (boost::starts_with(filename,
750 dynamic_sensors::ipmi::sel::selLogFilename))
751 {
752 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400753 selLogFiles.emplace_back(
754 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800755 }
756 }
757 // As the log files rotate, they are appended with a ".#" that is higher for
758 // the older logs. Since we don't expect more than 10 log files, we
759 // can just sort the list to get them in order from newest to oldest
760 std::sort(selLogFiles.begin(), selLogFiles.end());
761
762 return !selLogFiles.empty();
763}
764
765static int countSELEntries()
766{
767 // Get the list of ipmi_sel log files
768 std::vector<std::filesystem::path> selLogFiles;
769 if (!getSELLogFiles(selLogFiles))
770 {
771 return 0;
772 }
773 int numSELEntries = 0;
774 // Loop through each log file and count the number of logs
775 for (const std::filesystem::path& file : selLogFiles)
776 {
777 std::ifstream logStream(file);
778 if (!logStream.is_open())
779 {
780 continue;
781 }
782
783 std::string line;
784 while (std::getline(logStream, line))
785 {
786 numSELEntries++;
787 }
788 }
789 return numSELEntries;
790}
791
792static bool findSELEntry(const int recordID,
793 const std::vector<std::filesystem::path>& selLogFiles,
794 std::string& entry)
795{
796 // Record ID is the first entry field following the timestamp. It is
797 // preceded by a space and followed by a comma
798 std::string search = " " + std::to_string(recordID) + ",";
799
800 // Loop through the ipmi_sel log entries
801 for (const std::filesystem::path& file : selLogFiles)
802 {
803 std::ifstream logStream(file);
804 if (!logStream.is_open())
805 {
806 continue;
807 }
808
809 while (std::getline(logStream, entry))
810 {
811 // Check if the record ID matches
812 if (entry.find(search) != std::string::npos)
813 {
814 return true;
815 }
816 }
817 }
818 return false;
819}
820
821static uint16_t
822 getNextRecordID(const uint16_t recordID,
823 const std::vector<std::filesystem::path>& selLogFiles)
824{
825 uint16_t nextRecordID = recordID + 1;
826 std::string entry;
827 if (findSELEntry(nextRecordID, selLogFiles, entry))
828 {
829 return nextRecordID;
830 }
831 else
832 {
833 return ipmi::sel::lastEntry;
834 }
835}
836
837static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
838{
839 for (unsigned int i = 0; i < hexStr.size(); i += 2)
840 {
841 try
842 {
843 data.push_back(static_cast<uint8_t>(
844 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
845 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500846 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800847 {
George Liude6694e2024-07-17 15:22:25 +0800848 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800849 return -1;
850 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500851 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800852 {
George Liude6694e2024-07-17 15:22:25 +0800853 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800854 return -1;
855 }
856 }
857 return 0;
858}
859
860ipmi::RspType<uint8_t, // SEL version
861 uint16_t, // SEL entry count
862 uint16_t, // free space
863 uint32_t, // last add timestamp
864 uint32_t, // last erase timestamp
865 uint8_t> // operation support
866 ipmiStorageGetSELInfo()
867{
868 constexpr uint8_t selVersion = ipmi::sel::selVersion;
869 uint16_t entries = countSELEntries();
870 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
871 dynamic_sensors::ipmi::sel::selLogDir /
872 dynamic_sensors::ipmi::sel::selLogFilename);
873 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
874 constexpr uint8_t operationSupport =
875 dynamic_sensors::ipmi::sel::selOperationSupport;
876 constexpr uint16_t freeSpace =
877 0xffff; // Spec indicates that more than 64kB is free
878
879 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
880 eraseTimeStamp, operationSupport);
881}
882
883using systemEventType = std::tuple<
884 uint32_t, // Timestamp
885 uint16_t, // Generator ID
886 uint8_t, // EvM Rev
887 uint8_t, // Sensor Type
888 uint8_t, // Sensor Number
889 uint7_t, // Event Type
890 bool, // Event Direction
891 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
892 // Data
893using oemTsEventType = std::tuple<
894 uint32_t, // Timestamp
895 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
896 // Data
897using oemEventType =
898 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
899
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500900ipmi::RspType<uint16_t, // Next Record ID
901 uint16_t, // Record ID
902 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800903 std::variant<systemEventType, oemTsEventType,
904 oemEventType>> // Record Content
905 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
906 uint8_t offset, uint8_t size)
907{
908 // Only support getting the entire SEL record. If a partial size or non-zero
909 // offset is requested, return an error
910 if (offset != 0 || size != ipmi::sel::entireRecord)
911 {
912 return ipmi::responseRetBytesUnavailable();
913 }
914
915 // Check the reservation ID if one is provided or required (only if the
916 // offset is non-zero)
917 if (reservationID != 0 || offset != 0)
918 {
919 if (!checkSELReservation(reservationID))
920 {
921 return ipmi::responseInvalidReservationId();
922 }
923 }
924
925 // Get the ipmi_sel log files
926 std::vector<std::filesystem::path> selLogFiles;
927 if (!getSELLogFiles(selLogFiles))
928 {
929 return ipmi::responseSensorInvalid();
930 }
931
932 std::string targetEntry;
933
934 if (targetID == ipmi::sel::firstEntry)
935 {
936 // The first entry will be at the top of the oldest log file
937 std::ifstream logStream(selLogFiles.back());
938 if (!logStream.is_open())
939 {
940 return ipmi::responseUnspecifiedError();
941 }
942
943 if (!std::getline(logStream, targetEntry))
944 {
945 return ipmi::responseUnspecifiedError();
946 }
947 }
948 else if (targetID == ipmi::sel::lastEntry)
949 {
950 // The last entry will be at the bottom of the newest log file
951 std::ifstream logStream(selLogFiles.front());
952 if (!logStream.is_open())
953 {
954 return ipmi::responseUnspecifiedError();
955 }
956
957 std::string line;
958 while (std::getline(logStream, line))
959 {
960 targetEntry = line;
961 }
962 }
963 else
964 {
965 if (!findSELEntry(targetID, selLogFiles, targetEntry))
966 {
967 return ipmi::responseSensorInvalid();
968 }
969 }
970
971 // The format of the ipmi_sel message is "<Timestamp>
972 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
973 // First get the Timestamp
974 size_t space = targetEntry.find_first_of(" ");
975 if (space == std::string::npos)
976 {
977 return ipmi::responseUnspecifiedError();
978 }
979 std::string entryTimestamp = targetEntry.substr(0, space);
980 // Then get the log contents
981 size_t entryStart = targetEntry.find_first_not_of(" ", space);
982 if (entryStart == std::string::npos)
983 {
984 return ipmi::responseUnspecifiedError();
985 }
986 std::string_view entry(targetEntry);
987 entry.remove_prefix(entryStart);
988 // Use split to separate the entry into its fields
989 std::vector<std::string> targetEntryFields;
990 boost::split(targetEntryFields, entry, boost::is_any_of(","),
991 boost::token_compress_on);
992 if (targetEntryFields.size() < 3)
993 {
994 return ipmi::responseUnspecifiedError();
995 }
996 std::string& recordIDStr = targetEntryFields[0];
997 std::string& recordTypeStr = targetEntryFields[1];
998 std::string& eventDataStr = targetEntryFields[2];
999
1000 uint16_t recordID;
1001 uint8_t recordType;
1002 try
1003 {
1004 recordID = std::stoul(recordIDStr);
1005 recordType = std::stoul(recordTypeStr, nullptr, 16);
1006 }
1007 catch (const std::invalid_argument&)
1008 {
1009 return ipmi::responseUnspecifiedError();
1010 }
1011 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1012 std::vector<uint8_t> eventDataBytes;
1013 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1014 {
1015 return ipmi::responseUnspecifiedError();
1016 }
1017
1018 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1019 {
1020 // Get the timestamp
1021 std::tm timeStruct = {};
1022 std::istringstream entryStream(entryTimestamp);
1023
1024 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1025 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1026 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001027 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001028 timestamp = std::mktime(&timeStruct);
1029 }
1030
1031 // Set the event message revision
1032 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1033
1034 uint16_t generatorID = 0;
1035 uint8_t sensorType = 0;
1036 uint16_t sensorAndLun = 0;
1037 uint8_t sensorNum = 0xFF;
1038 uint7_t eventType = 0;
1039 bool eventDir = 0;
1040 // System type events should have six fields
1041 if (targetEntryFields.size() >= 6)
1042 {
1043 std::string& generatorIDStr = targetEntryFields[3];
1044 std::string& sensorPath = targetEntryFields[4];
1045 std::string& eventDirStr = targetEntryFields[5];
1046
1047 // Get the generator ID
1048 try
1049 {
1050 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1051 }
1052 catch (const std::invalid_argument&)
1053 {
1054 std::cerr << "Invalid Generator ID\n";
1055 }
1056
1057 // Get the sensor type, sensor number, and event type for the sensor
1058 sensorType = getSensorTypeFromPath(sensorPath);
1059 sensorAndLun = getSensorNumberFromPath(sensorPath);
1060 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001061 if ((generatorID & 0x0001) == 0)
1062 {
1063 // IPMB Address
1064 generatorID |= sensorAndLun & 0x0300;
1065 }
1066 else
1067 {
1068 // system software
1069 generatorID |= sensorAndLun >> 8;
1070 }
Willy Tude54f482021-01-26 15:59:09 -08001071 eventType = getSensorEventTypeFromPath(sensorPath);
1072
1073 // Get the event direction
1074 try
1075 {
1076 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1077 }
1078 catch (const std::invalid_argument&)
1079 {
1080 std::cerr << "Invalid Event Direction\n";
1081 }
1082 }
1083
1084 // Only keep the eventData bytes that fit in the record
1085 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1086 eventData{};
1087 std::copy_n(eventDataBytes.begin(),
1088 std::min(eventDataBytes.size(), eventData.size()),
1089 eventData.begin());
1090
1091 return ipmi::responseSuccess(
1092 nextRecordID, recordID, recordType,
1093 systemEventType{timestamp, generatorID, evmRev, sensorType,
1094 sensorNum, eventType, eventDir, eventData});
1095 }
1096
Thang Trane70c59b2023-09-21 13:54:28 +07001097 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1098 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1099 {
1100 // Get the timestamp
1101 std::tm timeStruct = {};
1102 std::istringstream entryStream(entryTimestamp);
1103
1104 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1105 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1106 {
1107 timeStruct.tm_isdst = -1;
1108 timestamp = std::mktime(&timeStruct);
1109 }
1110
1111 // Only keep the bytes that fit in the record
1112 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1113 eventData{};
1114 std::copy_n(eventDataBytes.begin(),
1115 std::min(eventDataBytes.size(), eventData.size()),
1116 eventData.begin());
1117
1118 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1119 oemTsEventType{timestamp, eventData});
1120 }
1121
1122 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1123 {
1124 // Only keep the bytes that fit in the record
1125 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1126 eventData{};
1127 std::copy_n(eventDataBytes.begin(),
1128 std::min(eventDataBytes.size(), eventData.size()),
1129 eventData.begin());
1130
1131 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1132 eventData);
1133 }
1134
Willy Tude54f482021-01-26 15:59:09 -08001135 return ipmi::responseUnspecifiedError();
1136}
1137
Willy Tu11d68892022-01-20 10:37:34 -08001138/*
1139Unused arguments
1140 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1141 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1142 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1143 uint8_t eventData3
1144*/
Patrick Williams1318a5e2024-08-16 15:19:54 -04001145ipmi::RspType<uint16_t>
1146 ipmiStorageAddSELEntry(uint16_t, uint8_t, uint32_t, uint16_t, uint8_t,
1147 uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001148{
1149 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1150 // added
1151 cancelSELReservation();
1152
1153 uint16_t responseID = 0xFFFF;
1154 return ipmi::responseSuccess(responseID);
1155}
1156
Patrick Williams1318a5e2024-08-16 15:19:54 -04001157ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1158 ipmi::Context::ptr ctx, uint16_t reservationID,
1159 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001160{
1161 if (!checkSELReservation(reservationID))
1162 {
1163 return ipmi::responseInvalidReservationId();
1164 }
1165
1166 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1167 if (clr != clrExpected)
1168 {
1169 return ipmi::responseInvalidFieldRequest();
1170 }
1171
1172 // Erasure status cannot be fetched, so always return erasure status as
1173 // `erase completed`.
1174 if (eraseOperation == ipmi::sel::getEraseStatus)
1175 {
1176 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1177 }
1178
1179 // Check that initiate erase is correct
1180 if (eraseOperation != ipmi::sel::initiateErase)
1181 {
1182 return ipmi::responseInvalidFieldRequest();
1183 }
1184
1185 // Per the IPMI spec, need to cancel any reservation when the SEL is
1186 // cleared
1187 cancelSELReservation();
1188
Charles Boyer818bea12021-09-20 16:56:36 -05001189 boost::system::error_code ec;
1190 ctx->bus->yield_method_call<>(ctx->yield, ec, selLoggerServiceName,
1191 "/xyz/openbmc_project/Logging/IPMI",
1192 "xyz.openbmc_project.Logging.IPMI", "Clear");
1193 if (ec)
1194 {
1195 std::cerr << "error in clear SEL: " << ec << std::endl;
1196 return ipmi::responseUnspecifiedError();
1197 }
Willy Tude54f482021-01-26 15:59:09 -08001198
1199 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1200}
1201
Patrick Williams1318a5e2024-08-16 15:19:54 -04001202std::vector<uint8_t> getType8SDRs(
1203 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001204{
1205 std::vector<uint8_t> resp;
1206 get_sdr::SensorDataEntityRecord data{};
1207
1208 /* Header */
1209 get_sdr::header::set_record_id(recordId, &(data.header));
1210 // Based on IPMI Spec v2.0 rev 1.1
1211 data.header.sdr_version = SDR_VERSION;
1212 data.header.record_type = 0x08;
1213 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1214
1215 /* Key */
1216 data.key.containerEntityId = entity->second.containerEntityId;
1217 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1218 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1219 &(data.key));
1220 data.key.entityId1 = entity->second.containedEntities[0].first;
1221 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1222
1223 /* Body */
1224 data.body.entityId2 = entity->second.containedEntities[1].first;
1225 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1226 data.body.entityId3 = entity->second.containedEntities[2].first;
1227 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1228 data.body.entityId4 = entity->second.containedEntities[3].first;
1229 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1230
1231 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1232
1233 return resp;
1234}
1235
Willy Tude54f482021-01-26 15:59:09 -08001236std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1237{
1238 std::vector<uint8_t> resp;
1239 if (index == 0)
1240 {
Willy Tude54f482021-01-26 15:59:09 -08001241 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001242 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001243 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1244 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1245 }
1246 else if (index == 1)
1247 {
Willy Tude54f482021-01-26 15:59:09 -08001248 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001249 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001250 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1251 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1252 }
1253 else
1254 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001255 throw std::runtime_error(
1256 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001257 }
1258
1259 return resp;
1260}
1261
1262void registerStorageFunctions()
1263{
1264 createTimers();
1265 startMatch();
1266
1267 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001268 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001269 ipmi::storage::cmdGetFruInventoryAreaInfo,
1270 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1271 // <READ FRU Data>
1272 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1273 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1274 ipmiStorageReadFruData);
1275
1276 // <WRITE FRU Data>
1277 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1278 ipmi::storage::cmdWriteFruData,
1279 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1280
1281 // <Get SEL Info>
1282 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1283 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1284 ipmiStorageGetSELInfo);
1285
1286 // <Get SEL Entry>
1287 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1288 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1289 ipmiStorageGetSELEntry);
1290
1291 // <Add SEL Entry>
1292 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1293 ipmi::storage::cmdAddSelEntry,
1294 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1295
1296 // <Clear SEL>
1297 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1298 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1299 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001300}
1301} // namespace storage
1302} // namespace ipmi