1 /*
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/asio/detached.hpp>
24 #include <boost/container/flat_map.hpp>
25 #include <ipmid/api.hpp>
26 #include <ipmid/message.hpp>
27 #include <ipmid/types.hpp>
28 #include <ipmid/utils.hpp>
29 #include <phosphor-logging/lg2.hpp>
30 #include <sdbusplus/message/types.hpp>
31 #include <sdbusplus/timer.hpp>
32 #include <xyz/openbmc_project/ObjectMapper/common.hpp>
33
34 #include <filesystem>
35 #include <fstream>
36 #include <functional>
37 #include <optional>
38 #include <stdexcept>
39 #include <string_view>
40
41 using ObjectMapper = sdbusplus::common::xyz::openbmc_project::ObjectMapper;
42
43 static constexpr bool DEBUG = false;
44
45 namespace dynamic_sensors::ipmi::sel
46 {
47 static const std::filesystem::path selLogDir = "/var/log";
48 static const std::string selLogFilename = "ipmi_sel";
49
getFileTimestamp(const std::filesystem::path & file)50 static int getFileTimestamp(const std::filesystem::path& file)
51 {
52 struct stat st;
53
54 if (stat(file.c_str(), &st) >= 0)
55 {
56 return st.st_mtime;
57 }
58 return ::ipmi::sel::invalidTimeStamp;
59 }
60
61 namespace erase_time
62 {
63 static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
64
get()65 int get()
66 {
67 return getFileTimestamp(selEraseTimestamp);
68 }
69 } // namespace erase_time
70 } // namespace dynamic_sensors::ipmi::sel
71
72 namespace ipmi
73 {
74
75 namespace storage
76 {
77
78 constexpr static const size_t maxFruSdrNameSize = 16;
79 using ObjectType =
80 boost::container::flat_map<std::string,
81 boost::container::flat_map<std::string, Value>>;
82 using ManagedObjectType =
83 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
84 using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
85 using Paths = std::vector<std::string>;
86
87 constexpr static const char* fruDeviceServiceName =
88 "xyz.openbmc_project.FruDevice";
89 constexpr static const size_t writeTimeoutSeconds = 10;
90 constexpr static const char* chassisTypeRackMount = "23";
91 constexpr static const char* chassisTypeMainServer = "17";
92
93 static std::vector<uint8_t> fruCache;
94 static constexpr uint16_t invalidBus = 0xFFFF;
95 static constexpr uint8_t invalidAddr = 0xFF;
96 static constexpr uint8_t typeASCIILatin8 = 0xC0;
97 static uint16_t cacheBus = invalidBus;
98 static uint8_t cacheAddr = invalidAddr;
99 static uint8_t lastDevId = 0xFF;
100
101 static uint16_t writeBus = invalidBus;
102 static uint8_t writeAddr = invalidAddr;
103
104 std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
105 static std::vector<sdbusplus::bus::match_t> fruMatches;
106
107 ManagedObjectType frus;
108
109 // we unfortunately have to build a map of hashes in case there is a
110 // collision to verify our dev-id
111 boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
112 void registerStorageFunctions() __attribute__((constructor));
113
writeFru(const std::vector<uint8_t> & fru)114 bool writeFru(const std::vector<uint8_t>& fru)
115 {
116 if (writeBus == invalidBus && writeAddr == invalidAddr)
117 {
118 return true;
119 }
120 lastDevId = 0xFF;
121 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
122 sdbusplus::message_t writeFru = dbus->new_method_call(
123 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
124 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
125 writeFru.append(writeBus, writeAddr, fru);
126 try
127 {
128 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
129 }
130 catch (const sdbusplus::exception_t&)
131 {
132 // todo: log sel?
133 lg2::error("error writing fru");
134 return false;
135 }
136 writeBus = invalidBus;
137 writeAddr = invalidAddr;
138 return true;
139 }
140
writeFruCache()141 void writeFruCache()
142 {
143 writeFru(fruCache);
144 }
145
createTimers()146 void createTimers()
147 {
148 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
149 }
150
recalculateHashes()151 void recalculateHashes()
152 {
153 deviceHashes.clear();
154 // hash the object paths to create unique device id's. increment on
155 // collision
156 std::hash<std::string> hasher;
157 for (const auto& fru : frus)
158 {
159 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
160 if (fruIface == fru.second.end())
161 {
162 continue;
163 }
164
165 auto busFind = fruIface->second.find("BUS");
166 auto addrFind = fruIface->second.find("ADDRESS");
167 if (busFind == fruIface->second.end() ||
168 addrFind == fruIface->second.end())
169 {
170 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
171 fru.first.str);
172 continue;
173 }
174
175 uint16_t fruBus = std::get<uint32_t>(busFind->second);
176 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
177 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
178 std::string chassisType;
179 if (chassisFind != fruIface->second.end())
180 {
181 chassisType = std::get<std::string>(chassisFind->second);
182 }
183
184 uint8_t fruHash = 0;
185 if (chassisType.compare(chassisTypeRackMount) != 0 &&
186 chassisType.compare(chassisTypeMainServer) != 0)
187 {
188 fruHash = hasher(fru.first.str);
189 // can't be 0xFF based on spec, and 0 is reserved for baseboard
190 if (fruHash == 0 || fruHash == 0xFF)
191 {
192 fruHash = 1;
193 }
194 }
195 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
196
197 bool emplacePassed = false;
198 while (!emplacePassed)
199 {
200 auto resp = deviceHashes.emplace(fruHash, newDev);
201 emplacePassed = resp.second;
202 if (!emplacePassed)
203 {
204 fruHash++;
205 // can't be 0xFF based on spec, and 0 is reserved for
206 // baseboard
207 if (fruHash == 0XFF)
208 {
209 fruHash = 0x1;
210 }
211 }
212 }
213 }
214 }
215
replaceCacheFru(const std::shared_ptr<sdbusplus::asio::connection> & bus,boost::asio::yield_context & yield,const std::optional<std::string> & path=std::nullopt)216 void replaceCacheFru(
217 const std::shared_ptr<sdbusplus::asio::connection>& bus,
218 boost::asio::yield_context& yield,
219 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
220 {
221 boost::system::error_code ec;
222
223 frus = bus->yield_method_call<ManagedObjectType>(
224 yield, ec, fruDeviceServiceName, "/",
225 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
226 if (ec)
227 {
228 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
229 "ERROR", ec.message());
230
231 return;
232 }
233 recalculateHashes();
234 }
235
getFru(ipmi::Context::ptr ctx,uint8_t devId)236 std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
237 uint8_t devId)
238 {
239 if (lastDevId == devId && devId != 0xFF)
240 {
241 return {ipmi::ccSuccess, fruCache};
242 }
243
244 auto deviceFind = deviceHashes.find(devId);
245 if (deviceFind == deviceHashes.end())
246 {
247 return {ipmi::ccSensorInvalid, {}};
248 }
249
250 cacheBus = deviceFind->second.first;
251 cacheAddr = deviceFind->second.second;
252
253 boost::system::error_code ec;
254 std::vector<uint8_t> fru = ipmi::callDbusMethod<std::vector<uint8_t>>(
255 ctx, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
256 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
257 cacheAddr);
258
259 if (ec)
260 {
261 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
262
263 cacheBus = invalidBus;
264 cacheAddr = invalidAddr;
265 return {ipmi::ccResponseError, {}};
266 }
267
268 fruCache.clear();
269 lastDevId = devId;
270 fruCache = fru;
271
272 return {ipmi::ccSuccess, fru};
273 }
274
writeFruIfRunning()275 void writeFruIfRunning()
276 {
277 if (!writeTimer->isRunning())
278 {
279 return;
280 }
281 writeTimer->stop();
282 writeFruCache();
283 }
284
startMatch(void)285 void startMatch(void)
286 {
287 if (fruMatches.size())
288 {
289 return;
290 }
291
292 fruMatches.reserve(2);
293
294 auto bus = getSdBus();
295 fruMatches.emplace_back(
296 *bus,
297 "type='signal',arg0path='/xyz/openbmc_project/"
298 "FruDevice/',member='InterfacesAdded'",
299 [](sdbusplus::message_t& message) {
300 sdbusplus::message::object_path path;
301 ObjectType object;
302 try
303 {
304 message.read(path, object);
305 }
306 catch (const sdbusplus::exception_t&)
307 {
308 return;
309 }
310 auto findType = object.find("xyz.openbmc_project.FruDevice");
311 if (findType == object.end())
312 {
313 return;
314 }
315 writeFruIfRunning();
316 frus[path] = object;
317 recalculateHashes();
318 lastDevId = 0xFF;
319 });
320
321 fruMatches.emplace_back(
322 *bus,
323 "type='signal',arg0path='/xyz/openbmc_project/"
324 "FruDevice/',member='InterfacesRemoved'",
325 [](sdbusplus::message_t& message) {
326 sdbusplus::message::object_path path;
327 std::set<std::string> interfaces;
328 try
329 {
330 message.read(path, interfaces);
331 }
332 catch (const sdbusplus::exception_t&)
333 {
334 return;
335 }
336 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
337 if (findType == interfaces.end())
338 {
339 return;
340 }
341 writeFruIfRunning();
342 frus.erase(path);
343 recalculateHashes();
344 lastDevId = 0xFF;
345 });
346
347 // call once to populate
348 boost::asio::spawn(
349 *getIoContext(),
350 [](boost::asio::yield_context yield) {
351 replaceCacheFru(getSdBus(), yield);
352 },
353 boost::asio::detached);
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 */
364 ipmi::RspType<uint8_t, // Count
365 std::vector<uint8_t> // Requested data
366 >
ipmiStorageReadFruData(ipmi::Context::ptr ctx,uint8_t fruDeviceId,uint16_t fruInventoryOffset,uint8_t countToRead)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
375 auto [status, fru] = getFru(ctx, fruDeviceId);
376 if (status != ipmi::ccSuccess)
377 {
378 return ipmi::response(status);
379 }
380
381 size_t fromFruByteLen = 0;
382 if (countToRead + fruInventoryOffset < fru.size())
383 {
384 fromFruByteLen = countToRead;
385 }
386 else if (fru.size() > fruInventoryOffset)
387 {
388 fromFruByteLen = fru.size() - fruInventoryOffset;
389 }
390 else
391 {
392 return ipmi::responseReqDataLenExceeded();
393 }
394
395 std::vector<uint8_t> requestedData;
396
397 requestedData.insert(requestedData.begin(),
398 fru.begin() + fruInventoryOffset,
399 fru.begin() + fruInventoryOffset + fromFruByteLen);
400
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 */
ipmiStorageWriteFruData(ipmi::Context::ptr ctx,uint8_t fruDeviceId,uint16_t fruInventoryOffset,std::vector<uint8_t> & dataToWrite)413 ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
414 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
415 std::vector<uint8_t>& dataToWrite)
416 {
417 if (fruDeviceId == 0xFF)
418 {
419 return ipmi::responseInvalidFieldRequest();
420 }
421
422 size_t writeLen = dataToWrite.size();
423
424 auto [status, fru] = getFru(ctx, fruDeviceId);
425 if (status != ipmi::ccSuccess)
426 {
427 return ipmi::response(status);
428 }
429 size_t lastWriteAddr = fruInventoryOffset + writeLen;
430 if (fru.size() < lastWriteAddr)
431 {
432 fru.resize(fruInventoryOffset + writeLen);
433 }
434
435 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
436 fru.begin() + fruInventoryOffset);
437
438 bool atEnd = false;
439
440 if (fru.size() >= sizeof(FRUHeader))
441 {
442 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
443
444 size_t areaLength = 0;
445 size_t lastRecordStart = std::max(
446 {header->internalOffset, header->chassisOffset, header->boardOffset,
447 header->productOffset, header->multiRecordOffset});
448 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
449
450 if (header->multiRecordOffset)
451 {
452 // This FRU has a MultiRecord Area
453 uint8_t endOfList = 0;
454 // Walk the MultiRecord headers until the last record
455 while (!endOfList)
456 {
457 // The MSB in the second byte of the MultiRecord header signals
458 // "End of list"
459 endOfList = fru[lastRecordStart + 1] & 0x80;
460 // Third byte in the MultiRecord header is the length
461 areaLength = fru[lastRecordStart + 2];
462 // This length is in bytes (not 8 bytes like other headers)
463 areaLength += 5; // The length omits the 5 byte header
464 if (!endOfList)
465 {
466 // Next MultiRecord header
467 lastRecordStart += areaLength;
468 }
469 }
470 }
471 else
472 {
473 // This FRU does not have a MultiRecord Area
474 // Get the length of the area in multiples of 8 bytes
475 if (lastWriteAddr > (lastRecordStart + 1))
476 {
477 // second byte in record area is the length
478 areaLength = fru[lastRecordStart + 1];
479 areaLength *= 8; // it is in multiples of 8 bytes
480 }
481 }
482 if (lastWriteAddr >= (areaLength + lastRecordStart))
483 {
484 atEnd = true;
485 }
486 }
487 uint8_t countWritten = 0;
488
489 writeBus = cacheBus;
490 writeAddr = cacheAddr;
491 if (atEnd)
492 {
493 // cancel timer, we're at the end so might as well send it
494 writeTimer->stop();
495 if (!writeFru(fru))
496 {
497 return ipmi::responseInvalidFieldRequest();
498 }
499 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
500 }
501 else
502 {
503 fruCache = fru; // Write-back
504 // start a timer, if no further data is sent to check to see if it is
505 // valid
506 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
507 std::chrono::seconds(writeTimeoutSeconds)));
508 countWritten = 0;
509 }
510
511 return ipmi::responseSuccess(countWritten);
512 }
513
514 /** @brief implements the get FRU inventory area info command
515 * @param fruDeviceId - FRU Device ID
516 *
517 * @returns IPMI completion code plus response data
518 * - inventorySize - Number of possible allocation units
519 * - accessType - Allocation unit size in bytes.
520 */
521 ipmi::RspType<uint16_t, // inventorySize
522 uint8_t> // accessType
ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx,uint8_t fruDeviceId)523 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
524 {
525 if (fruDeviceId == 0xFF)
526 {
527 return ipmi::responseInvalidFieldRequest();
528 }
529
530 auto [ret, fru] = getFru(ctx, fruDeviceId);
531 if (ret != ipmi::ccSuccess)
532 {
533 return ipmi::response(ret);
534 }
535
536 constexpr uint8_t accessType =
537 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
538
539 return ipmi::responseSuccess(fru.size(), accessType);
540 }
541
getFruSdrCount(ipmi::Context::ptr,size_t & count)542 ipmi::Cc getFruSdrCount(ipmi::Context::ptr, size_t& count)
543 {
544 count = deviceHashes.size();
545 return ipmi::ccSuccess;
546 }
547
getFruSdrs(ipmi::Context::ptr ctx,size_t index,get_sdr::SensorDataFruRecord & resp)548 ipmi::Cc getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
549 get_sdr::SensorDataFruRecord& resp)
550 {
551 if (deviceHashes.size() < index)
552 {
553 return ipmi::ccInvalidFieldRequest;
554 }
555 auto device = deviceHashes.begin() + index;
556 uint16_t& bus = device->second.first;
557 uint8_t& address = device->second.second;
558
559 boost::container::flat_map<std::string, Value>* fruData = nullptr;
560 auto fru = std::find_if(
561 frus.begin(), frus.end(),
562 [bus, address, &fruData](ManagedEntry& entry) {
563 auto findFruDevice =
564 entry.second.find("xyz.openbmc_project.FruDevice");
565 if (findFruDevice == entry.second.end())
566 {
567 return false;
568 }
569 fruData = &(findFruDevice->second);
570 auto findBus = findFruDevice->second.find("BUS");
571 auto findAddress = findFruDevice->second.find("ADDRESS");
572 if (findBus == findFruDevice->second.end() ||
573 findAddress == findFruDevice->second.end())
574 {
575 return false;
576 }
577 if (std::get<uint32_t>(findBus->second) != bus)
578 {
579 return false;
580 }
581 if (std::get<uint32_t>(findAddress->second) != address)
582 {
583 return false;
584 }
585 return true;
586 });
587 if (fru == frus.end())
588 {
589 return ipmi::ccResponseError;
590 }
591 std::string name;
592 uint8_t entityID = 0;
593 uint8_t entityInstance = 0x1;
594
595 #ifdef USING_ENTITY_MANAGER_DECORATORS
596 boost::system::error_code ec;
597
598 Paths subtreePaths = ipmi::callDbusMethod<Paths>(
599 ctx, ec, ObjectMapper::default_service, ObjectMapper::instance_path,
600 ObjectMapper::interface, ObjectMapper::method_names::get_sub_tree_paths,
601 "/xyz/openbmc_project/inventory", 0,
602 std::array<const char*, 2>{
603 "xyz.openbmc_project.Inventory.Decorator.I2CDevice",
604 "xyz.openbmc_project.Inventory.Decorator.Ipmi",
605 });
606 if (ec)
607 {
608 lg2::error(
609 "GetSubTreePaths for ipmiStorageGetFruInvAreaInfo failed: {ERROR}",
610 "ERROR", ec.message());
611 return ipmi::ccResponseError;
612 }
613
614 bool foundDevice = false;
615 for (const auto& path : subtreePaths)
616 {
617 ipmi::PropertyMap i2cProperties;
618 boost::system::error_code ec = ipmi::getAllDbusProperties(
619 ctx, "xyz.openbmc_project.EntityManager", path,
620 "xyz.openbmc_project.Inventory.Decorator.I2CDevice", i2cProperties);
621 if (ec)
622 {
623 continue;
624 }
625
626 std::optional<uint64_t> maybeBus;
627 std::optional<uint64_t> maybeAddress;
628 std::optional<std::string> maybeName;
629 for (const auto& [key, val] : i2cProperties)
630 {
631 if (key == "Bus")
632 {
633 maybeBus = std::get<uint64_t>(val);
634 }
635 else if (key == "Address")
636 {
637 maybeAddress = std::get<uint64_t>(val);
638 }
639 else if (key == "Name")
640 {
641 maybeName = std::get<std::string>(val);
642 }
643 }
644 if (!maybeBus || *maybeBus != bus || !maybeAddress ||
645 *maybeAddress != address)
646 {
647 continue;
648 }
649 // At this point we found the device entry and will populate the
650 // information if exist.
651 foundDevice = true;
652
653 if (maybeName.has_value())
654 {
655 name = *maybeName;
656 }
657
658 ipmi::PropertyMap entityData;
659 ec = ipmi::getAllDbusProperties(
660 ctx, "xyz.openbmc_project.EntityManager", path,
661 "xyz.openbmc_project.Inventory.Decorator.Ipmi", entityData);
662 if (!ec)
663 {
664 for (const auto& [key, val] : entityData)
665 {
666 if (key == "EntityId")
667 {
668 entityID = std::get<uint64_t>(val);
669 }
670 else if (key == "EntityInstance")
671 {
672 entityInstance = std::get<uint64_t>(val);
673 }
674 }
675 }
676 break;
677 }
678
679 if (!foundDevice)
680 {
681 if constexpr (DEBUG)
682 {
683 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
684 "not found for Fru\n");
685 }
686 }
687 #endif
688
689 std::vector<std::string> nameProperties = {
690 "BOARD_PRODUCT_NAME", "PRODUCT_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
691 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
692 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
693
694 for (const std::string& prop : nameProperties)
695 {
696 auto findProp = fruData->find(prop);
697 if (findProp != fruData->end())
698 {
699 name = std::get<std::string>(findProp->second);
700 break;
701 }
702 }
703
704 if (name.empty())
705 {
706 name = "UNKNOWN";
707 }
708 if (name.size() > maxFruSdrNameSize)
709 {
710 name = name.substr(0, maxFruSdrNameSize);
711 }
712 size_t sizeDiff = maxFruSdrNameSize - name.size();
713
714 resp.header.recordId = 0x0; // calling code is to implement these
715 resp.header.sdrVersion = ipmiSdrVersion;
716 resp.header.recordType = get_sdr::SENSOR_DATA_FRU_RECORD;
717 resp.header.recordLength = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
718 resp.key.deviceAddress = 0x20;
719 resp.key.fruID = device->first;
720 resp.key.accessLun = 0x80; // logical / physical fru device
721 resp.key.channelNumber = 0x0;
722 resp.body.reserved = 0x0;
723 resp.body.deviceType = 0x10;
724 resp.body.deviceTypeModifier = 0x0;
725
726 resp.body.entityID = entityID;
727 resp.body.entityInstance = entityInstance;
728
729 resp.body.oem = 0x0;
730 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
731 name.copy(resp.body.deviceID, name.size());
732
733 return ipmi::ccSuccess;
734 }
735
getSELLogFiles(std::vector<std::filesystem::path> & selLogFiles)736 static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
737 {
738 // Loop through the directory looking for ipmi_sel log files
739 for (const std::filesystem::directory_entry& dirEnt :
740 std::filesystem::directory_iterator(
741 dynamic_sensors::ipmi::sel::selLogDir))
742 {
743 std::string filename = dirEnt.path().filename();
744 if (filename.starts_with(dynamic_sensors::ipmi::sel::selLogFilename))
745 {
746 // If we find an ipmi_sel log file, save the path
747 selLogFiles.emplace_back(
748 dynamic_sensors::ipmi::sel::selLogDir / filename);
749 }
750 }
751 // As the log files rotate, they are appended with a ".#" that is higher for
752 // the older logs. Since we don't expect more than 10 log files, we
753 // can just sort the list to get them in order from newest to oldest
754 std::sort(selLogFiles.begin(), selLogFiles.end());
755
756 return !selLogFiles.empty();
757 }
758
countSELEntries()759 static int countSELEntries()
760 {
761 // Get the list of ipmi_sel log files
762 std::vector<std::filesystem::path> selLogFiles;
763 if (!getSELLogFiles(selLogFiles))
764 {
765 return 0;
766 }
767 int numSELEntries = 0;
768 // Loop through each log file and count the number of logs
769 for (const std::filesystem::path& file : selLogFiles)
770 {
771 std::ifstream logStream(file);
772 if (!logStream.is_open())
773 {
774 continue;
775 }
776
777 std::string line;
778 while (std::getline(logStream, line))
779 {
780 numSELEntries++;
781 }
782 }
783 return numSELEntries;
784 }
785
findSELEntry(const int recordID,const std::vector<std::filesystem::path> & selLogFiles,std::string & entry)786 static bool findSELEntry(const int recordID,
787 const std::vector<std::filesystem::path>& selLogFiles,
788 std::string& entry)
789 {
790 // Record ID is the first entry field following the timestamp. It is
791 // preceded by a space and followed by a comma
792 std::string search = " " + std::to_string(recordID) + ",";
793
794 // Loop through the ipmi_sel log entries
795 for (const std::filesystem::path& file : selLogFiles)
796 {
797 std::ifstream logStream(file);
798 if (!logStream.is_open())
799 {
800 continue;
801 }
802
803 while (std::getline(logStream, entry))
804 {
805 // Check if the record ID matches
806 if (entry.find(search) != std::string::npos)
807 {
808 return true;
809 }
810 }
811 }
812 return false;
813 }
814
getNextRecordID(const uint16_t recordID,const std::vector<std::filesystem::path> & selLogFiles)815 static uint16_t getNextRecordID(
816 const uint16_t recordID,
817 const std::vector<std::filesystem::path>& selLogFiles)
818 {
819 uint16_t nextRecordID = recordID + 1;
820 std::string entry;
821 if (findSELEntry(nextRecordID, selLogFiles, entry))
822 {
823 return nextRecordID;
824 }
825 else
826 {
827 return ipmi::sel::lastEntry;
828 }
829 }
830
fromHexStr(const std::string & hexStr,std::vector<uint8_t> & data)831 static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
832 {
833 for (unsigned int i = 0; i < hexStr.size(); i += 2)
834 {
835 try
836 {
837 data.push_back(static_cast<uint8_t>(
838 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
839 }
840 catch (const std::invalid_argument& e)
841 {
842 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
843 return -1;
844 }
845 catch (const std::out_of_range& e)
846 {
847 lg2::error("Out of range: {ERROR}", "ERROR", e);
848 return -1;
849 }
850 }
851 return 0;
852 }
853
854 ipmi::RspType<uint8_t, // SEL version
855 uint16_t, // SEL entry count
856 uint16_t, // free space
857 uint32_t, // last add timestamp
858 uint32_t, // last erase timestamp
859 uint8_t> // operation support
ipmiStorageGetSELInfo()860 ipmiStorageGetSELInfo()
861 {
862 constexpr uint8_t selVersion = ipmi::sel::selVersion;
863 uint16_t entries = countSELEntries();
864 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
865 dynamic_sensors::ipmi::sel::selLogDir /
866 dynamic_sensors::ipmi::sel::selLogFilename);
867 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
868 constexpr uint8_t operationSupport =
869 dynamic_sensors::ipmi::sel::selOperationSupport;
870 constexpr uint16_t freeSpace =
871 0xffff; // Spec indicates that more than 64kB is free
872
873 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
874 eraseTimeStamp, operationSupport);
875 }
876
877 using systemEventType = std::tuple<
878 uint32_t, // Timestamp
879 uint16_t, // Generator ID
880 uint8_t, // EvM Rev
881 uint8_t, // Sensor Type
882 uint8_t, // Sensor Number
883 uint7_t, // Event Type
884 bool, // Event Direction
885 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
886 // Data
887 using oemTsEventType = std::tuple<
888 uint32_t, // Timestamp
889 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
890 // Data
891 using oemEventType =
892 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
893
894 ipmi::RspType<uint16_t, // Next Record ID
895 uint16_t, // Record ID
896 uint8_t, // Record Type
897 std::variant<systemEventType, oemTsEventType,
898 oemEventType>> // Record Content
ipmiStorageGetSELEntry(uint16_t reservationID,uint16_t targetID,uint8_t offset,uint8_t size)899 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
900 uint8_t offset, uint8_t size)
901 {
902 // Only support getting the entire SEL record. If a partial size or non-zero
903 // offset is requested, return an error
904 if (offset != 0 || size != ipmi::sel::entireRecord)
905 {
906 return ipmi::responseRetBytesUnavailable();
907 }
908
909 // Check the reservation ID if one is provided or required (only if the
910 // offset is non-zero)
911 if (reservationID != 0 || offset != 0)
912 {
913 if (!checkSELReservation(reservationID))
914 {
915 return ipmi::responseInvalidReservationId();
916 }
917 }
918
919 // Get the ipmi_sel log files
920 std::vector<std::filesystem::path> selLogFiles;
921 if (!getSELLogFiles(selLogFiles))
922 {
923 return ipmi::responseSensorInvalid();
924 }
925
926 std::string targetEntry;
927
928 if (targetID == ipmi::sel::firstEntry)
929 {
930 // The first entry will be at the top of the oldest log file
931 std::ifstream logStream(selLogFiles.back());
932 if (!logStream.is_open())
933 {
934 return ipmi::responseUnspecifiedError();
935 }
936
937 if (!std::getline(logStream, targetEntry))
938 {
939 return ipmi::responseUnspecifiedError();
940 }
941 }
942 else if (targetID == ipmi::sel::lastEntry)
943 {
944 // The last entry will be at the bottom of the newest log file
945 std::ifstream logStream(selLogFiles.front());
946 if (!logStream.is_open())
947 {
948 return ipmi::responseUnspecifiedError();
949 }
950
951 std::string line;
952 while (std::getline(logStream, line))
953 {
954 targetEntry = line;
955 }
956 }
957 else
958 {
959 if (!findSELEntry(targetID, selLogFiles, targetEntry))
960 {
961 return ipmi::responseSensorInvalid();
962 }
963 }
964
965 // The format of the ipmi_sel message is "<Timestamp>
966 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
967 // First get the Timestamp
968 size_t space = targetEntry.find_first_of(" ");
969 if (space == std::string::npos)
970 {
971 return ipmi::responseUnspecifiedError();
972 }
973 std::string entryTimestamp = targetEntry.substr(0, space);
974 // Then get the log contents
975 size_t entryStart = targetEntry.find_first_not_of(" ", space);
976 if (entryStart == std::string::npos)
977 {
978 return ipmi::responseUnspecifiedError();
979 }
980 std::string_view entry(targetEntry);
981 entry.remove_prefix(entryStart);
982 // Use split to separate the entry into its fields
983 std::vector<std::string> targetEntryFields;
984 boost::split(targetEntryFields, entry, boost::is_any_of(","),
985 boost::token_compress_on);
986 if (targetEntryFields.size() < 3)
987 {
988 return ipmi::responseUnspecifiedError();
989 }
990 std::string& recordIDStr = targetEntryFields[0];
991 std::string& recordTypeStr = targetEntryFields[1];
992 std::string& eventDataStr = targetEntryFields[2];
993
994 uint16_t recordID;
995 uint8_t recordType;
996 try
997 {
998 recordID = std::stoul(recordIDStr);
999 recordType = std::stoul(recordTypeStr, nullptr, 16);
1000 }
1001 catch (const std::invalid_argument&)
1002 {
1003 return ipmi::responseUnspecifiedError();
1004 }
1005 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1006 std::vector<uint8_t> eventDataBytes;
1007 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1008 {
1009 return ipmi::responseUnspecifiedError();
1010 }
1011
1012 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1013 {
1014 // Get the timestamp
1015 std::tm timeStruct = {};
1016 std::istringstream entryStream(entryTimestamp);
1017
1018 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1019 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1020 {
1021 timeStruct.tm_isdst = -1;
1022 timestamp = std::mktime(&timeStruct);
1023 }
1024
1025 // Set the event message revision
1026 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1027
1028 uint16_t generatorID = 0;
1029 uint8_t sensorType = 0;
1030 uint16_t sensorAndLun = 0;
1031 uint8_t sensorNum = 0xFF;
1032 uint7_t eventType = 0;
1033 bool eventDir = 0;
1034 // System type events should have six fields
1035 if (targetEntryFields.size() >= 6)
1036 {
1037 std::string& generatorIDStr = targetEntryFields[3];
1038 std::string& sensorPath = targetEntryFields[4];
1039 std::string& eventDirStr = targetEntryFields[5];
1040
1041 // Get the generator ID
1042 try
1043 {
1044 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1045 }
1046 catch (const std::invalid_argument&)
1047 {
1048 lg2::error("Invalid Generator ID");
1049 }
1050
1051 // Get the sensor type, sensor number, and event type for the sensor
1052 sensorType = getSensorTypeFromPath(sensorPath);
1053 sensorAndLun = getSensorNumberFromPath(sensorPath);
1054 sensorNum = static_cast<uint8_t>(sensorAndLun);
1055 if ((generatorID & 0x0001) == 0)
1056 {
1057 // IPMB Address
1058 generatorID |= sensorAndLun & 0x0300;
1059 }
1060 else
1061 {
1062 // system software
1063 generatorID |= sensorAndLun >> 8;
1064 }
1065 eventType = getSensorEventTypeFromPath(sensorPath);
1066
1067 // Get the event direction
1068 try
1069 {
1070 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1071 }
1072 catch (const std::invalid_argument&)
1073 {
1074 lg2::error("Invalid Event Direction");
1075 }
1076 }
1077
1078 // Only keep the eventData bytes that fit in the record
1079 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1080 eventData{};
1081 std::copy_n(eventDataBytes.begin(),
1082 std::min(eventDataBytes.size(), eventData.size()),
1083 eventData.begin());
1084
1085 return ipmi::responseSuccess(
1086 nextRecordID, recordID, recordType,
1087 systemEventType{timestamp, generatorID, evmRev, sensorType,
1088 sensorNum, eventType, eventDir, eventData});
1089 }
1090
1091 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1092 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1093 {
1094 // Get the timestamp
1095 std::tm timeStruct = {};
1096 std::istringstream entryStream(entryTimestamp);
1097
1098 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1099 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1100 {
1101 timeStruct.tm_isdst = -1;
1102 timestamp = std::mktime(&timeStruct);
1103 }
1104
1105 // Only keep the bytes that fit in the record
1106 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1107 eventData{};
1108 std::copy_n(eventDataBytes.begin(),
1109 std::min(eventDataBytes.size(), eventData.size()),
1110 eventData.begin());
1111
1112 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1113 oemTsEventType{timestamp, eventData});
1114 }
1115
1116 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1117 {
1118 // Only keep the bytes that fit in the record
1119 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1120 eventData{};
1121 std::copy_n(eventDataBytes.begin(),
1122 std::min(eventDataBytes.size(), eventData.size()),
1123 eventData.begin());
1124
1125 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1126 eventData);
1127 }
1128
1129 return ipmi::responseUnspecifiedError();
1130 }
1131
1132 /*
1133 Unused arguments
1134 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1135 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1136 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1137 uint8_t eventData3
1138 */
ipmiStorageAddSELEntry(uint16_t,uint8_t,uint32_t,uint16_t,uint8_t,uint8_t,uint8_t,uint8_t,uint8_t,uint8_t,uint8_t)1139 ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1140 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1141 uint8_t, uint8_t, uint8_t)
1142 {
1143 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1144 // added
1145 cancelSELReservation();
1146
1147 uint16_t responseID = 0xFFFF;
1148 return ipmi::responseSuccess(responseID);
1149 }
1150
ipmiStorageClearSEL(ipmi::Context::ptr ctx,uint16_t reservationID,const std::array<uint8_t,3> & clr,uint8_t eraseOperation)1151 ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1152 ipmi::Context::ptr ctx, uint16_t reservationID,
1153 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
1154 {
1155 if (!checkSELReservation(reservationID))
1156 {
1157 return ipmi::responseInvalidReservationId();
1158 }
1159
1160 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1161 if (clr != clrExpected)
1162 {
1163 return ipmi::responseInvalidFieldRequest();
1164 }
1165
1166 // Erasure status cannot be fetched, so always return erasure status as
1167 // `erase completed`.
1168 if (eraseOperation == ipmi::sel::getEraseStatus)
1169 {
1170 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1171 }
1172
1173 // Check that initiate erase is correct
1174 if (eraseOperation != ipmi::sel::initiateErase)
1175 {
1176 return ipmi::responseInvalidFieldRequest();
1177 }
1178
1179 // Per the IPMI spec, need to cancel any reservation when the SEL is
1180 // cleared
1181 cancelSELReservation();
1182
1183 boost::system::error_code ec =
1184 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1185 "/xyz/openbmc_project/Logging/IPMI",
1186 "xyz.openbmc_project.Logging.IPMI", "Clear");
1187 if (ec)
1188 {
1189 lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
1190 return ipmi::responseUnspecifiedError();
1191 }
1192
1193 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1194 }
1195
getType8SDRs(ipmi::sensor::EntityInfoMap::const_iterator & entity,uint16_t recordId)1196 std::vector<uint8_t> getType8SDRs(
1197 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
1198 {
1199 std::vector<uint8_t> resp;
1200 get_sdr::SensorDataEntityRecord data{};
1201
1202 /* Header */
1203 // Based on IPMI Spec v2.0 rev 1.1
1204 data.header.recordId = recordId;
1205 data.header.sdrVersion = SDR_VERSION;
1206 data.header.recordType = 0x08;
1207 data.header.recordLength = sizeof(data.key) + sizeof(data.body);
1208
1209 /* Key */
1210 data.key.containerEntityId = entity->second.containerEntityId;
1211 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1212 get_sdr::key::setFlags(entity->second.isList, entity->second.isLinked,
1213 data.key);
1214 data.key.entityId1 = entity->second.containedEntities[0].first;
1215 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1216
1217 /* Body */
1218 data.body.entityId2 = entity->second.containedEntities[1].first;
1219 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1220 data.body.entityId3 = entity->second.containedEntities[2].first;
1221 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1222 data.body.entityId4 = entity->second.containedEntities[3].first;
1223 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1224
1225 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1226
1227 return resp;
1228 }
1229
getType12SDRs(uint16_t index,uint16_t recordId)1230 std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1231 {
1232 std::vector<uint8_t> resp;
1233 if (index == 0)
1234 {
1235 std::string bmcName = "Basbrd Mgmt Ctlr";
1236 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
1237 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1238 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1239 }
1240 else if (index == 1)
1241 {
1242 std::string meName = "Mgmt Engine";
1243 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
1244 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1245 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1246 }
1247 else
1248 {
1249 throw std::runtime_error(
1250 "getType12SDRs:: Illegal index " + std::to_string(index));
1251 }
1252
1253 return resp;
1254 }
1255
registerStorageFunctions()1256 void registerStorageFunctions()
1257 {
1258 createTimers();
1259 startMatch();
1260
1261 // <Get FRU Inventory Area Info>
1262 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1263 ipmi::storage::cmdGetFruInventoryAreaInfo,
1264 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1265 // <READ FRU Data>
1266 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1267 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1268 ipmiStorageReadFruData);
1269
1270 // <WRITE FRU Data>
1271 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1272 ipmi::storage::cmdWriteFruData,
1273 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1274
1275 // <Get SEL Info>
1276 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1277 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1278 ipmiStorageGetSELInfo);
1279
1280 // <Get SEL Entry>
1281 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1282 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1283 ipmiStorageGetSELEntry);
1284
1285 // <Add SEL Entry>
1286 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1287 ipmi::storage::cmdAddSelEntry,
1288 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1289
1290 // <Clear SEL>
1291 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1292 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1293 ipmiStorageClearSEL);
1294 }
1295 } // namespace storage
1296 } // namespace ipmi
1297