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