blob: afe35352edca325a10f4e1c5946dd2bf26f5f9e5 [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
Willy Tu48fe64e2022-08-01 23:23:46 +0000239std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
240 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();
300 fruMatches.emplace_back(*bus,
301 "type='signal',arg0path='/xyz/openbmc_project/"
302 "FruDevice/',member='InterfacesAdded'",
Patrick Williams5d82f472022-07-22 19:26:53 -0500303 [](sdbusplus::message_t& message) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500304 sdbusplus::message::object_path path;
305 ObjectType object;
306 try
307 {
308 message.read(path, object);
309 }
310 catch (const sdbusplus::exception_t&)
311 {
312 return;
313 }
314 auto findType = object.find("xyz.openbmc_project.FruDevice");
315 if (findType == object.end())
316 {
317 return;
318 }
319 writeFruIfRunning();
320 frus[path] = object;
321 recalculateHashes();
322 lastDevId = 0xFF;
323 });
Willy Tude54f482021-01-26 15:59:09 -0800324
325 fruMatches.emplace_back(*bus,
326 "type='signal',arg0path='/xyz/openbmc_project/"
327 "FruDevice/',member='InterfacesRemoved'",
Patrick Williams5d82f472022-07-22 19:26:53 -0500328 [](sdbusplus::message_t& message) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500329 sdbusplus::message::object_path path;
330 std::set<std::string> interfaces;
331 try
332 {
333 message.read(path, interfaces);
334 }
335 catch (const sdbusplus::exception_t&)
336 {
337 return;
338 }
339 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
340 if (findType == interfaces.end())
341 {
342 return;
343 }
344 writeFruIfRunning();
345 frus.erase(path);
346 recalculateHashes();
347 lastDevId = 0xFF;
348 });
Willy Tude54f482021-01-26 15:59:09 -0800349
350 // call once to populate
351 boost::asio::spawn(*getIoContext(), [](boost::asio::yield_context yield) {
352 replaceCacheFru(getSdBus(), yield);
353 });
354}
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 */
413ipmi::RspType<uint8_t>
414 ipmiStorageWriteFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
415 uint16_t fruInventoryOffset,
416 std::vector<uint8_t>& dataToWrite)
417{
418 if (fruDeviceId == 0xFF)
419 {
420 return ipmi::responseInvalidFieldRequest();
421 }
422
423 size_t writeLen = dataToWrite.size();
424
Willy Tu48fe64e2022-08-01 23:23:46 +0000425 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800426 if (status != ipmi::ccSuccess)
427 {
428 return ipmi::response(status);
429 }
430 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000431 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800432 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000433 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800434 }
435
436 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000437 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800438
439 bool atEnd = false;
440
Willy Tu48fe64e2022-08-01 23:23:46 +0000441 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800442 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000443 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800444
445 size_t areaLength = 0;
446 size_t lastRecordStart = std::max(
447 {header->internalOffset, header->chassisOffset, header->boardOffset,
448 header->productOffset, header->multiRecordOffset});
449 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
450
451 if (header->multiRecordOffset)
452 {
453 // This FRU has a MultiRecord Area
454 uint8_t endOfList = 0;
455 // Walk the MultiRecord headers until the last record
456 while (!endOfList)
457 {
458 // The MSB in the second byte of the MultiRecord header signals
459 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000460 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800461 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000462 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800463 // This length is in bytes (not 8 bytes like other headers)
464 areaLength += 5; // The length omits the 5 byte header
465 if (!endOfList)
466 {
467 // Next MultiRecord header
468 lastRecordStart += areaLength;
469 }
470 }
471 }
472 else
473 {
474 // This FRU does not have a MultiRecord Area
475 // Get the length of the area in multiples of 8 bytes
476 if (lastWriteAddr > (lastRecordStart + 1))
477 {
478 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000479 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800480 areaLength *= 8; // it is in multiples of 8 bytes
481 }
482 }
483 if (lastWriteAddr >= (areaLength + lastRecordStart))
484 {
485 atEnd = true;
486 }
487 }
488 uint8_t countWritten = 0;
489
490 writeBus = cacheBus;
491 writeAddr = cacheAddr;
492 if (atEnd)
493 {
494 // cancel timer, we're at the end so might as well send it
495 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000496 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800497 {
498 return ipmi::responseInvalidFieldRequest();
499 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000500 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800501 }
502 else
503 {
Sui Chen548d1a22022-09-14 07:41:17 -0700504 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800505 // start a timer, if no further data is sent to check to see if it is
506 // valid
507 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
508 std::chrono::seconds(writeTimeoutSeconds)));
509 countWritten = 0;
510 }
511
512 return ipmi::responseSuccess(countWritten);
513}
514
515/** @brief implements the get FRU inventory area info command
516 * @param fruDeviceId - FRU Device ID
517 *
518 * @returns IPMI completion code plus response data
519 * - inventorySize - Number of possible allocation units
520 * - accessType - Allocation unit size in bytes.
521 */
522ipmi::RspType<uint16_t, // inventorySize
523 uint8_t> // accessType
524 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
525{
526 if (fruDeviceId == 0xFF)
527 {
528 return ipmi::responseInvalidFieldRequest();
529 }
530
Willy Tu48fe64e2022-08-01 23:23:46 +0000531 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800532 if (ret != ipmi::ccSuccess)
533 {
534 return ipmi::response(ret);
535 }
536
537 constexpr uint8_t accessType =
538 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
539
Willy Tu48fe64e2022-08-01 23:23:46 +0000540 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800541}
542
Willy Tu11d68892022-01-20 10:37:34 -0800543ipmi_ret_t getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800544{
545 count = deviceHashes.size();
546 return IPMI_CC_OK;
547}
548
Johnathan Mantey23a722c2023-05-12 08:18:54 -0700549ipmi_ret_t getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
Willy Tude54f482021-01-26 15:59:09 -0800550 get_sdr::SensorDataFruRecord& resp)
551{
552 if (deviceHashes.size() < index)
553 {
554 return IPMI_CC_INVALID_FIELD_REQUEST;
555 }
556 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530557 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800558 uint8_t& address = device->second.second;
559
560 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500561 auto fru = std::find_if(frus.begin(), frus.end(),
562 [bus, address, &fruData](ManagedEntry& entry) {
563 auto findFruDevice = entry.second.find("xyz.openbmc_project.FruDevice");
564 if (findFruDevice == entry.second.end())
565 {
566 return false;
567 }
568 fruData = &(findFruDevice->second);
569 auto findBus = findFruDevice->second.find("BUS");
570 auto findAddress = findFruDevice->second.find("ADDRESS");
571 if (findBus == findFruDevice->second.end() ||
572 findAddress == findFruDevice->second.end())
573 {
574 return false;
575 }
576 if (std::get<uint32_t>(findBus->second) != bus)
577 {
578 return false;
579 }
580 if (std::get<uint32_t>(findAddress->second) != address)
581 {
582 return false;
583 }
584 return true;
585 });
Willy Tude54f482021-01-26 15:59:09 -0800586 if (fru == frus.end())
587 {
588 return IPMI_CC_RESPONSE_ERROR;
589 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530590 std::string name;
Willy Tude54f482021-01-26 15:59:09 -0800591
592#ifdef USING_ENTITY_MANAGER_DECORATORS
593
594 boost::container::flat_map<std::string, Value>* entityData = nullptr;
595
596 // todo: this should really use caching, this is a very inefficient lookup
597 boost::system::error_code ec;
Nan Zhou947da1b2022-09-20 20:40:59 +0000598
Willy Tude54f482021-01-26 15:59:09 -0800599 ManagedObjectType entities = ctx->bus->yield_method_call<ManagedObjectType>(
Nan Zhou947da1b2022-09-20 20:40:59 +0000600 ctx->yield, ec, entityManagerServiceName,
601 "/xyz/openbmc_project/inventory", "org.freedesktop.DBus.ObjectManager",
602 "GetManagedObjects");
Willy Tude54f482021-01-26 15:59:09 -0800603
604 if (ec)
605 {
George Liude6694e2024-07-17 15:22:25 +0800606 lg2::error("GetMangagedObjects for ipmiStorageGetFruInvAreaInfo "
607 "failed: {ERROR}",
608 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800609
610 return ipmi::ccResponseError;
611 }
612
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500613 auto entity =
614 std::find_if(entities.begin(), entities.end(),
615 [bus, address, &entityData, &name](ManagedEntry& entry) {
616 auto findFruDevice = entry.second.find(
617 "xyz.openbmc_project.Inventory.Decorator.I2CDevice");
618 if (findFruDevice == entry.second.end())
619 {
620 return false;
621 }
Willy Tude54f482021-01-26 15:59:09 -0800622
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500623 // Integer fields added via Entity-Manager json are uint64_ts by
624 // default.
625 auto findBus = findFruDevice->second.find("Bus");
626 auto findAddress = findFruDevice->second.find("Address");
Willy Tude54f482021-01-26 15:59:09 -0800627
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500628 if (findBus == findFruDevice->second.end() ||
629 findAddress == findFruDevice->second.end())
630 {
631 return false;
632 }
633 if ((std::get<uint64_t>(findBus->second) != bus) ||
634 (std::get<uint64_t>(findAddress->second) != address))
635 {
636 return false;
637 }
Willy Tude54f482021-01-26 15:59:09 -0800638
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500639 auto fruName = findFruDevice->second.find("Name");
640 if (fruName != findFruDevice->second.end())
641 {
642 name = std::get<std::string>(fruName->second);
643 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530644
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500645 // At this point we found the device entry and should return
646 // true.
647 auto findIpmiDevice =
648 entry.second.find("xyz.openbmc_project.Inventory.Decorator.Ipmi");
649 if (findIpmiDevice != entry.second.end())
650 {
651 entityData = &(findIpmiDevice->second);
652 }
Willy Tude54f482021-01-26 15:59:09 -0800653
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500654 return true;
Patrick Williams369824e2023-10-20 11:18:23 -0500655 });
Willy Tude54f482021-01-26 15:59:09 -0800656
657 if (entity == entities.end())
658 {
659 if constexpr (DEBUG)
660 {
661 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
662 "not found for Fru\n");
663 }
664 }
665
666#endif
667
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200668 std::vector<std::string> nameProperties = {
669 "PRODUCT_PRODUCT_NAME", "BOARD_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
670 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
671 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
672
673 for (const std::string& prop : nameProperties)
674 {
675 auto findProp = fruData->find(prop);
676 if (findProp != fruData->end())
677 {
678 name = std::get<std::string>(findProp->second);
679 break;
680 }
681 }
682
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530683 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800684 {
685 name = "UNKNOWN";
686 }
687 if (name.size() > maxFruSdrNameSize)
688 {
689 name = name.substr(0, maxFruSdrNameSize);
690 }
691 size_t sizeDiff = maxFruSdrNameSize - name.size();
692
693 resp.header.record_id_lsb = 0x0; // calling code is to implement these
694 resp.header.record_id_msb = 0x0;
695 resp.header.sdr_version = ipmiSdrVersion;
696 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
697 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
698 resp.key.deviceAddress = 0x20;
699 resp.key.fruID = device->first;
700 resp.key.accessLun = 0x80; // logical / physical fru device
701 resp.key.channelNumber = 0x0;
702 resp.body.reserved = 0x0;
703 resp.body.deviceType = 0x10;
704 resp.body.deviceTypeModifier = 0x0;
705
706 uint8_t entityID = 0;
707 uint8_t entityInstance = 0x1;
708
709#ifdef USING_ENTITY_MANAGER_DECORATORS
710 if (entityData)
711 {
712 auto entityIdProperty = entityData->find("EntityId");
713 auto entityInstanceProperty = entityData->find("EntityInstance");
714
715 if (entityIdProperty != entityData->end())
716 {
717 entityID = static_cast<uint8_t>(
718 std::get<uint64_t>(entityIdProperty->second));
719 }
720 if (entityInstanceProperty != entityData->end())
721 {
722 entityInstance = static_cast<uint8_t>(
723 std::get<uint64_t>(entityInstanceProperty->second));
724 }
725 }
726#endif
727
728 resp.body.entityID = entityID;
729 resp.body.entityInstance = entityInstance;
730
731 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800732 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800733 name.copy(resp.body.deviceID, name.size());
734
735 return IPMI_CC_OK;
736}
737
738static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
739{
740 // Loop through the directory looking for ipmi_sel log files
741 for (const std::filesystem::directory_entry& dirEnt :
742 std::filesystem::directory_iterator(
743 dynamic_sensors::ipmi::sel::selLogDir))
744 {
745 std::string filename = dirEnt.path().filename();
746 if (boost::starts_with(filename,
747 dynamic_sensors::ipmi::sel::selLogFilename))
748 {
749 // If we find an ipmi_sel log file, save the path
750 selLogFiles.emplace_back(dynamic_sensors::ipmi::sel::selLogDir /
751 filename);
752 }
753 }
754 // As the log files rotate, they are appended with a ".#" that is higher for
755 // the older logs. Since we don't expect more than 10 log files, we
756 // can just sort the list to get them in order from newest to oldest
757 std::sort(selLogFiles.begin(), selLogFiles.end());
758
759 return !selLogFiles.empty();
760}
761
762static int countSELEntries()
763{
764 // Get the list of ipmi_sel log files
765 std::vector<std::filesystem::path> selLogFiles;
766 if (!getSELLogFiles(selLogFiles))
767 {
768 return 0;
769 }
770 int numSELEntries = 0;
771 // Loop through each log file and count the number of logs
772 for (const std::filesystem::path& file : selLogFiles)
773 {
774 std::ifstream logStream(file);
775 if (!logStream.is_open())
776 {
777 continue;
778 }
779
780 std::string line;
781 while (std::getline(logStream, line))
782 {
783 numSELEntries++;
784 }
785 }
786 return numSELEntries;
787}
788
789static bool findSELEntry(const int recordID,
790 const std::vector<std::filesystem::path>& selLogFiles,
791 std::string& entry)
792{
793 // Record ID is the first entry field following the timestamp. It is
794 // preceded by a space and followed by a comma
795 std::string search = " " + std::to_string(recordID) + ",";
796
797 // Loop through the ipmi_sel log entries
798 for (const std::filesystem::path& file : selLogFiles)
799 {
800 std::ifstream logStream(file);
801 if (!logStream.is_open())
802 {
803 continue;
804 }
805
806 while (std::getline(logStream, entry))
807 {
808 // Check if the record ID matches
809 if (entry.find(search) != std::string::npos)
810 {
811 return true;
812 }
813 }
814 }
815 return false;
816}
817
818static uint16_t
819 getNextRecordID(const uint16_t recordID,
820 const std::vector<std::filesystem::path>& selLogFiles)
821{
822 uint16_t nextRecordID = recordID + 1;
823 std::string entry;
824 if (findSELEntry(nextRecordID, selLogFiles, entry))
825 {
826 return nextRecordID;
827 }
828 else
829 {
830 return ipmi::sel::lastEntry;
831 }
832}
833
834static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
835{
836 for (unsigned int i = 0; i < hexStr.size(); i += 2)
837 {
838 try
839 {
840 data.push_back(static_cast<uint8_t>(
841 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
842 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500843 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800844 {
George Liude6694e2024-07-17 15:22:25 +0800845 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800846 return -1;
847 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500848 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800849 {
George Liude6694e2024-07-17 15:22:25 +0800850 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800851 return -1;
852 }
853 }
854 return 0;
855}
856
857ipmi::RspType<uint8_t, // SEL version
858 uint16_t, // SEL entry count
859 uint16_t, // free space
860 uint32_t, // last add timestamp
861 uint32_t, // last erase timestamp
862 uint8_t> // operation support
863 ipmiStorageGetSELInfo()
864{
865 constexpr uint8_t selVersion = ipmi::sel::selVersion;
866 uint16_t entries = countSELEntries();
867 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
868 dynamic_sensors::ipmi::sel::selLogDir /
869 dynamic_sensors::ipmi::sel::selLogFilename);
870 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
871 constexpr uint8_t operationSupport =
872 dynamic_sensors::ipmi::sel::selOperationSupport;
873 constexpr uint16_t freeSpace =
874 0xffff; // Spec indicates that more than 64kB is free
875
876 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
877 eraseTimeStamp, operationSupport);
878}
879
880using systemEventType = std::tuple<
881 uint32_t, // Timestamp
882 uint16_t, // Generator ID
883 uint8_t, // EvM Rev
884 uint8_t, // Sensor Type
885 uint8_t, // Sensor Number
886 uint7_t, // Event Type
887 bool, // Event Direction
888 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
889 // Data
890using oemTsEventType = std::tuple<
891 uint32_t, // Timestamp
892 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
893 // Data
894using oemEventType =
895 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
896
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500897ipmi::RspType<uint16_t, // Next Record ID
898 uint16_t, // Record ID
899 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800900 std::variant<systemEventType, oemTsEventType,
901 oemEventType>> // Record Content
902 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
903 uint8_t offset, uint8_t size)
904{
905 // Only support getting the entire SEL record. If a partial size or non-zero
906 // offset is requested, return an error
907 if (offset != 0 || size != ipmi::sel::entireRecord)
908 {
909 return ipmi::responseRetBytesUnavailable();
910 }
911
912 // Check the reservation ID if one is provided or required (only if the
913 // offset is non-zero)
914 if (reservationID != 0 || offset != 0)
915 {
916 if (!checkSELReservation(reservationID))
917 {
918 return ipmi::responseInvalidReservationId();
919 }
920 }
921
922 // Get the ipmi_sel log files
923 std::vector<std::filesystem::path> selLogFiles;
924 if (!getSELLogFiles(selLogFiles))
925 {
926 return ipmi::responseSensorInvalid();
927 }
928
929 std::string targetEntry;
930
931 if (targetID == ipmi::sel::firstEntry)
932 {
933 // The first entry will be at the top of the oldest log file
934 std::ifstream logStream(selLogFiles.back());
935 if (!logStream.is_open())
936 {
937 return ipmi::responseUnspecifiedError();
938 }
939
940 if (!std::getline(logStream, targetEntry))
941 {
942 return ipmi::responseUnspecifiedError();
943 }
944 }
945 else if (targetID == ipmi::sel::lastEntry)
946 {
947 // The last entry will be at the bottom of the newest log file
948 std::ifstream logStream(selLogFiles.front());
949 if (!logStream.is_open())
950 {
951 return ipmi::responseUnspecifiedError();
952 }
953
954 std::string line;
955 while (std::getline(logStream, line))
956 {
957 targetEntry = line;
958 }
959 }
960 else
961 {
962 if (!findSELEntry(targetID, selLogFiles, targetEntry))
963 {
964 return ipmi::responseSensorInvalid();
965 }
966 }
967
968 // The format of the ipmi_sel message is "<Timestamp>
969 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
970 // First get the Timestamp
971 size_t space = targetEntry.find_first_of(" ");
972 if (space == std::string::npos)
973 {
974 return ipmi::responseUnspecifiedError();
975 }
976 std::string entryTimestamp = targetEntry.substr(0, space);
977 // Then get the log contents
978 size_t entryStart = targetEntry.find_first_not_of(" ", space);
979 if (entryStart == std::string::npos)
980 {
981 return ipmi::responseUnspecifiedError();
982 }
983 std::string_view entry(targetEntry);
984 entry.remove_prefix(entryStart);
985 // Use split to separate the entry into its fields
986 std::vector<std::string> targetEntryFields;
987 boost::split(targetEntryFields, entry, boost::is_any_of(","),
988 boost::token_compress_on);
989 if (targetEntryFields.size() < 3)
990 {
991 return ipmi::responseUnspecifiedError();
992 }
993 std::string& recordIDStr = targetEntryFields[0];
994 std::string& recordTypeStr = targetEntryFields[1];
995 std::string& eventDataStr = targetEntryFields[2];
996
997 uint16_t recordID;
998 uint8_t recordType;
999 try
1000 {
1001 recordID = std::stoul(recordIDStr);
1002 recordType = std::stoul(recordTypeStr, nullptr, 16);
1003 }
1004 catch (const std::invalid_argument&)
1005 {
1006 return ipmi::responseUnspecifiedError();
1007 }
1008 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1009 std::vector<uint8_t> eventDataBytes;
1010 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1011 {
1012 return ipmi::responseUnspecifiedError();
1013 }
1014
1015 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1016 {
1017 // Get the timestamp
1018 std::tm timeStruct = {};
1019 std::istringstream entryStream(entryTimestamp);
1020
1021 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1022 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1023 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001024 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001025 timestamp = std::mktime(&timeStruct);
1026 }
1027
1028 // Set the event message revision
1029 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1030
1031 uint16_t generatorID = 0;
1032 uint8_t sensorType = 0;
1033 uint16_t sensorAndLun = 0;
1034 uint8_t sensorNum = 0xFF;
1035 uint7_t eventType = 0;
1036 bool eventDir = 0;
1037 // System type events should have six fields
1038 if (targetEntryFields.size() >= 6)
1039 {
1040 std::string& generatorIDStr = targetEntryFields[3];
1041 std::string& sensorPath = targetEntryFields[4];
1042 std::string& eventDirStr = targetEntryFields[5];
1043
1044 // Get the generator ID
1045 try
1046 {
1047 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1048 }
1049 catch (const std::invalid_argument&)
1050 {
1051 std::cerr << "Invalid Generator ID\n";
1052 }
1053
1054 // Get the sensor type, sensor number, and event type for the sensor
1055 sensorType = getSensorTypeFromPath(sensorPath);
1056 sensorAndLun = getSensorNumberFromPath(sensorPath);
1057 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001058 if ((generatorID & 0x0001) == 0)
1059 {
1060 // IPMB Address
1061 generatorID |= sensorAndLun & 0x0300;
1062 }
1063 else
1064 {
1065 // system software
1066 generatorID |= sensorAndLun >> 8;
1067 }
Willy Tude54f482021-01-26 15:59:09 -08001068 eventType = getSensorEventTypeFromPath(sensorPath);
1069
1070 // Get the event direction
1071 try
1072 {
1073 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1074 }
1075 catch (const std::invalid_argument&)
1076 {
1077 std::cerr << "Invalid Event Direction\n";
1078 }
1079 }
1080
1081 // Only keep the eventData bytes that fit in the record
1082 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1083 eventData{};
1084 std::copy_n(eventDataBytes.begin(),
1085 std::min(eventDataBytes.size(), eventData.size()),
1086 eventData.begin());
1087
1088 return ipmi::responseSuccess(
1089 nextRecordID, recordID, recordType,
1090 systemEventType{timestamp, generatorID, evmRev, sensorType,
1091 sensorNum, eventType, eventDir, eventData});
1092 }
1093
Thang Trane70c59b2023-09-21 13:54:28 +07001094 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1095 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1096 {
1097 // Get the timestamp
1098 std::tm timeStruct = {};
1099 std::istringstream entryStream(entryTimestamp);
1100
1101 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1102 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1103 {
1104 timeStruct.tm_isdst = -1;
1105 timestamp = std::mktime(&timeStruct);
1106 }
1107
1108 // Only keep the bytes that fit in the record
1109 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1110 eventData{};
1111 std::copy_n(eventDataBytes.begin(),
1112 std::min(eventDataBytes.size(), eventData.size()),
1113 eventData.begin());
1114
1115 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1116 oemTsEventType{timestamp, eventData});
1117 }
1118
1119 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1120 {
1121 // Only keep the bytes that fit in the record
1122 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1123 eventData{};
1124 std::copy_n(eventDataBytes.begin(),
1125 std::min(eventDataBytes.size(), eventData.size()),
1126 eventData.begin());
1127
1128 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1129 eventData);
1130 }
1131
Willy Tude54f482021-01-26 15:59:09 -08001132 return ipmi::responseUnspecifiedError();
1133}
1134
Willy Tu11d68892022-01-20 10:37:34 -08001135/*
1136Unused arguments
1137 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1138 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1139 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1140 uint8_t eventData3
1141*/
1142ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(uint16_t, uint8_t, uint32_t,
1143 uint16_t, uint8_t, uint8_t,
1144 uint8_t, uint8_t, uint8_t,
1145 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
Tim Lee11317d72022-07-27 10:13:46 +08001155ipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx,
Willy Tude54f482021-01-26 15:59:09 -08001156 uint16_t reservationID,
1157 const std::array<uint8_t, 3>& clr,
1158 uint8_t eraseOperation)
1159{
1160 if (!checkSELReservation(reservationID))
1161 {
1162 return ipmi::responseInvalidReservationId();
1163 }
1164
1165 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1166 if (clr != clrExpected)
1167 {
1168 return ipmi::responseInvalidFieldRequest();
1169 }
1170
1171 // Erasure status cannot be fetched, so always return erasure status as
1172 // `erase completed`.
1173 if (eraseOperation == ipmi::sel::getEraseStatus)
1174 {
1175 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1176 }
1177
1178 // Check that initiate erase is correct
1179 if (eraseOperation != ipmi::sel::initiateErase)
1180 {
1181 return ipmi::responseInvalidFieldRequest();
1182 }
1183
1184 // Per the IPMI spec, need to cancel any reservation when the SEL is
1185 // cleared
1186 cancelSELReservation();
1187
Charles Boyer818bea12021-09-20 16:56:36 -05001188 boost::system::error_code ec;
1189 ctx->bus->yield_method_call<>(ctx->yield, ec, selLoggerServiceName,
1190 "/xyz/openbmc_project/Logging/IPMI",
1191 "xyz.openbmc_project.Logging.IPMI", "Clear");
1192 if (ec)
1193 {
1194 std::cerr << "error in clear SEL: " << ec << std::endl;
1195 return ipmi::responseUnspecifiedError();
1196 }
Willy Tude54f482021-01-26 15:59:09 -08001197
1198 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1199}
1200
Harvey Wu05d17c02021-09-15 08:46:59 +08001201std::vector<uint8_t>
1202 getType8SDRs(ipmi::sensor::EntityInfoMap::const_iterator& entity,
1203 uint16_t recordId)
1204{
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 {
1255 throw std::runtime_error("getType12SDRs:: Illegal index " +
1256 std::to_string(index));
1257 }
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