blob: f8380fd57992d51ddf5b62739d3b8465528a65d2 [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>
25#include <filesystem>
26#include <functional>
27#include <iostream>
28#include <ipmid/api.hpp>
29#include <ipmid/message.hpp>
30#include <ipmid/types.hpp>
31#include <phosphor-logging/log.hpp>
32#include <sdbusplus/message/types.hpp>
33#include <sdbusplus/timer.hpp>
34#include <stdexcept>
35#include <string_view>
36
37static constexpr bool DEBUG = false;
38
39namespace dynamic_sensors::ipmi::sel
40{
41static const std::filesystem::path selLogDir = "/var/log";
42static const std::string selLogFilename = "ipmi_sel";
43
44static int getFileTimestamp(const std::filesystem::path& file)
45{
46 struct stat st;
47
48 if (stat(file.c_str(), &st) >= 0)
49 {
50 return st.st_mtime;
51 }
52 return ::ipmi::sel::invalidTimeStamp;
53}
54
55namespace erase_time
56{
57static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
58
59void save()
60{
61 // open the file, creating it if necessary
62 int fd = open(selEraseTimestamp, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
63 if (fd < 0)
64 {
65 std::cerr << "Failed to open file\n";
66 return;
67 }
68
69 // update the file timestamp to the current time
70 if (futimens(fd, NULL) < 0)
71 {
72 std::cerr << "Failed to update timestamp: "
73 << std::string(strerror(errno));
74 }
75 close(fd);
76}
77
78int get()
79{
80 return getFileTimestamp(selEraseTimestamp);
81}
82} // namespace erase_time
83} // namespace dynamic_sensors::ipmi::sel
84
85namespace ipmi
86{
87
88namespace storage
89{
90
91constexpr static const size_t maxMessageSize = 64;
92constexpr static const size_t maxFruSdrNameSize = 16;
93using ObjectType =
94 boost::container::flat_map<std::string,
95 boost::container::flat_map<std::string, Value>>;
96using ManagedObjectType =
97 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
98using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
99
100constexpr static const char* fruDeviceServiceName =
101 "xyz.openbmc_project.FruDevice";
102constexpr static const char* entityManagerServiceName =
103 "xyz.openbmc_project.EntityManager";
104constexpr static const size_t writeTimeoutSeconds = 10;
105constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -0500106constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -0800107
108// event direction is bit[7] of eventType where 1b = Deassertion event
109constexpr static const uint8_t deassertionEvent = 0x80;
110
111static std::vector<uint8_t> fruCache;
112static uint8_t cacheBus = 0xFF;
113static uint8_t cacheAddr = 0XFF;
114static uint8_t lastDevId = 0xFF;
115
116static uint8_t writeBus = 0xFF;
117static uint8_t writeAddr = 0XFF;
118
119std::unique_ptr<phosphor::Timer> writeTimer = nullptr;
120static std::vector<sdbusplus::bus::match::match> fruMatches;
121
122ManagedObjectType frus;
123
124// we unfortunately have to build a map of hashes in case there is a
125// collision to verify our dev-id
126boost::container::flat_map<uint8_t, std::pair<uint8_t, uint8_t>> deviceHashes;
127
128void registerStorageFunctions() __attribute__((constructor));
129
130bool writeFru()
131{
132 if (writeBus == 0xFF && writeAddr == 0xFF)
133 {
134 return true;
135 }
136 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
137 sdbusplus::message::message 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::message writeFruResp = dbus->call(writeFru);
144 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500145 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800146 {
147 // todo: log sel?
148 phosphor::logging::log<phosphor::logging::level::ERR>(
149 "error writing fru");
150 return false;
151 }
152 writeBus = 0xFF;
153 writeAddr = 0xFF;
154 return true;
155}
156
157void createTimers()
158{
159 writeTimer = std::make_unique<phosphor::Timer>(writeFru);
160}
161
162void recalculateHashes()
163{
164
165 deviceHashes.clear();
166 // hash the object paths to create unique device id's. increment on
167 // collision
168 std::hash<std::string> hasher;
169 for (const auto& fru : frus)
170 {
171 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
172 if (fruIface == fru.second.end())
173 {
174 continue;
175 }
176
177 auto busFind = fruIface->second.find("BUS");
178 auto addrFind = fruIface->second.find("ADDRESS");
179 if (busFind == fruIface->second.end() ||
180 addrFind == fruIface->second.end())
181 {
182 phosphor::logging::log<phosphor::logging::level::INFO>(
183 "fru device missing Bus or Address",
184 phosphor::logging::entry("FRU=%s", fru.first.str.c_str()));
185 continue;
186 }
187
188 uint8_t fruBus = std::get<uint32_t>(busFind->second);
189 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
190 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
191 std::string chassisType;
192 if (chassisFind != fruIface->second.end())
193 {
194 chassisType = std::get<std::string>(chassisFind->second);
195 }
196
197 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500198 if (chassisType.compare(chassisTypeRackMount) != 0 &&
199 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800200 {
201 fruHash = hasher(fru.first.str);
202 // can't be 0xFF based on spec, and 0 is reserved for baseboard
203 if (fruHash == 0 || fruHash == 0xFF)
204 {
205 fruHash = 1;
206 }
207 }
208 std::pair<uint8_t, uint8_t> newDev(fruBus, fruAddr);
209
210 bool emplacePassed = false;
211 while (!emplacePassed)
212 {
213 auto resp = deviceHashes.emplace(fruHash, newDev);
214 emplacePassed = resp.second;
215 if (!emplacePassed)
216 {
217 fruHash++;
218 // can't be 0xFF based on spec, and 0 is reserved for
219 // baseboard
220 if (fruHash == 0XFF)
221 {
222 fruHash = 0x1;
223 }
224 }
225 }
226 }
227}
228
229void replaceCacheFru(const std::shared_ptr<sdbusplus::asio::connection>& bus,
230 boost::asio::yield_context& yield,
231 const std::optional<std::string>& path = std::nullopt)
232{
233 boost::system::error_code ec;
234
235 frus = bus->yield_method_call<ManagedObjectType>(
236 yield, ec, fruDeviceServiceName, "/",
237 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
238 if (ec)
239 {
240 phosphor::logging::log<phosphor::logging::level::ERR>(
241 "GetMangagedObjects for replaceCacheFru failed",
242 phosphor::logging::entry("ERROR=%s", ec.message().c_str()));
243
244 return;
245 }
246 recalculateHashes();
247}
248
249ipmi::Cc getFru(ipmi::Context::ptr ctx, uint8_t devId)
250{
251 if (lastDevId == devId && devId != 0xFF)
252 {
253 return ipmi::ccSuccess;
254 }
255
Willy Tude54f482021-01-26 15:59:09 -0800256 auto deviceFind = deviceHashes.find(devId);
257 if (deviceFind == deviceHashes.end())
258 {
259 return IPMI_CC_SENSOR_INVALID;
260 }
261
262 fruCache.clear();
263
264 cacheBus = deviceFind->second.first;
265 cacheAddr = deviceFind->second.second;
266
267 boost::system::error_code ec;
268
269 fruCache = ctx->bus->yield_method_call<std::vector<uint8_t>>(
270 ctx->yield, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
271 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
272 cacheAddr);
273 if (ec)
274 {
275 phosphor::logging::log<phosphor::logging::level::ERR>(
276 "Couldn't get raw fru",
277 phosphor::logging::entry("ERROR=%s", ec.message().c_str()));
278
279 cacheBus = 0xFF;
280 cacheAddr = 0xFF;
281 return ipmi::ccResponseError;
282 }
283
284 lastDevId = devId;
285 return ipmi::ccSuccess;
286}
287
288void writeFruIfRunning()
289{
290 if (!writeTimer->isRunning())
291 {
292 return;
293 }
294 writeTimer->stop();
295 writeFru();
296}
297
298void startMatch(void)
299{
300 if (fruMatches.size())
301 {
302 return;
303 }
304
305 fruMatches.reserve(2);
306
307 auto bus = getSdBus();
308 fruMatches.emplace_back(*bus,
309 "type='signal',arg0path='/xyz/openbmc_project/"
310 "FruDevice/',member='InterfacesAdded'",
311 [](sdbusplus::message::message& message) {
312 sdbusplus::message::object_path path;
313 ObjectType object;
314 try
315 {
316 message.read(path, object);
317 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500318 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800319 {
320 return;
321 }
322 auto findType = object.find(
323 "xyz.openbmc_project.FruDevice");
324 if (findType == object.end())
325 {
326 return;
327 }
328 writeFruIfRunning();
329 frus[path] = object;
330 recalculateHashes();
331 lastDevId = 0xFF;
332 });
333
334 fruMatches.emplace_back(*bus,
335 "type='signal',arg0path='/xyz/openbmc_project/"
336 "FruDevice/',member='InterfacesRemoved'",
337 [](sdbusplus::message::message& message) {
338 sdbusplus::message::object_path path;
339 std::set<std::string> interfaces;
340 try
341 {
342 message.read(path, interfaces);
343 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500344 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800345 {
346 return;
347 }
348 auto findType = interfaces.find(
349 "xyz.openbmc_project.FruDevice");
350 if (findType == interfaces.end())
351 {
352 return;
353 }
354 writeFruIfRunning();
355 frus.erase(path);
356 recalculateHashes();
357 lastDevId = 0xFF;
358 });
359
360 // call once to populate
361 boost::asio::spawn(*getIoContext(), [](boost::asio::yield_context yield) {
362 replaceCacheFru(getSdBus(), yield);
363 });
364}
365
366/** @brief implements the read FRU data command
367 * @param fruDeviceId - FRU Device ID
368 * @param fruInventoryOffset - FRU Inventory Offset to write
369 * @param countToRead - Count to read
370 *
371 * @returns ipmi completion code plus response data
372 * - countWritten - Count written
373 */
374ipmi::RspType<uint8_t, // Count
375 std::vector<uint8_t> // Requested data
376 >
377 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
378 uint16_t fruInventoryOffset, uint8_t countToRead)
379{
380 if (fruDeviceId == 0xFF)
381 {
382 return ipmi::responseInvalidFieldRequest();
383 }
384
385 ipmi::Cc status = getFru(ctx, fruDeviceId);
386
387 if (status != ipmi::ccSuccess)
388 {
389 return ipmi::response(status);
390 }
391
392 size_t fromFruByteLen = 0;
393 if (countToRead + fruInventoryOffset < fruCache.size())
394 {
395 fromFruByteLen = countToRead;
396 }
397 else if (fruCache.size() > fruInventoryOffset)
398 {
399 fromFruByteLen = fruCache.size() - fruInventoryOffset;
400 }
401 else
402 {
403 return ipmi::responseReqDataLenExceeded();
404 }
405
406 std::vector<uint8_t> requestedData;
407
408 requestedData.insert(
409 requestedData.begin(), fruCache.begin() + fruInventoryOffset,
410 fruCache.begin() + fruInventoryOffset + fromFruByteLen);
411
412 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
413 requestedData);
414}
415
416/** @brief implements the write FRU data command
417 * @param fruDeviceId - FRU Device ID
418 * @param fruInventoryOffset - FRU Inventory Offset to write
419 * @param dataToWrite - Data to write
420 *
421 * @returns ipmi completion code plus response data
422 * - countWritten - Count written
423 */
424ipmi::RspType<uint8_t>
425 ipmiStorageWriteFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
426 uint16_t fruInventoryOffset,
427 std::vector<uint8_t>& dataToWrite)
428{
429 if (fruDeviceId == 0xFF)
430 {
431 return ipmi::responseInvalidFieldRequest();
432 }
433
434 size_t writeLen = dataToWrite.size();
435
436 ipmi::Cc status = getFru(ctx, fruDeviceId);
437 if (status != ipmi::ccSuccess)
438 {
439 return ipmi::response(status);
440 }
441 size_t lastWriteAddr = fruInventoryOffset + writeLen;
442 if (fruCache.size() < lastWriteAddr)
443 {
444 fruCache.resize(fruInventoryOffset + writeLen);
445 }
446
447 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
448 fruCache.begin() + fruInventoryOffset);
449
450 bool atEnd = false;
451
452 if (fruCache.size() >= sizeof(FRUHeader))
453 {
454 FRUHeader* header = reinterpret_cast<FRUHeader*>(fruCache.data());
455
456 size_t areaLength = 0;
457 size_t lastRecordStart = std::max(
458 {header->internalOffset, header->chassisOffset, header->boardOffset,
459 header->productOffset, header->multiRecordOffset});
460 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
461
462 if (header->multiRecordOffset)
463 {
464 // This FRU has a MultiRecord Area
465 uint8_t endOfList = 0;
466 // Walk the MultiRecord headers until the last record
467 while (!endOfList)
468 {
469 // The MSB in the second byte of the MultiRecord header signals
470 // "End of list"
471 endOfList = fruCache[lastRecordStart + 1] & 0x80;
472 // Third byte in the MultiRecord header is the length
473 areaLength = fruCache[lastRecordStart + 2];
474 // This length is in bytes (not 8 bytes like other headers)
475 areaLength += 5; // The length omits the 5 byte header
476 if (!endOfList)
477 {
478 // Next MultiRecord header
479 lastRecordStart += areaLength;
480 }
481 }
482 }
483 else
484 {
485 // This FRU does not have a MultiRecord Area
486 // Get the length of the area in multiples of 8 bytes
487 if (lastWriteAddr > (lastRecordStart + 1))
488 {
489 // second byte in record area is the length
490 areaLength = fruCache[lastRecordStart + 1];
491 areaLength *= 8; // it is in multiples of 8 bytes
492 }
493 }
494 if (lastWriteAddr >= (areaLength + lastRecordStart))
495 {
496 atEnd = true;
497 }
498 }
499 uint8_t countWritten = 0;
500
501 writeBus = cacheBus;
502 writeAddr = cacheAddr;
503 if (atEnd)
504 {
505 // cancel timer, we're at the end so might as well send it
506 writeTimer->stop();
507 if (!writeFru())
508 {
509 return ipmi::responseInvalidFieldRequest();
510 }
511 countWritten = std::min(fruCache.size(), static_cast<size_t>(0xFF));
512 }
513 else
514 {
515 // start a timer, if no further data is sent to check to see if it is
516 // valid
517 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
518 std::chrono::seconds(writeTimeoutSeconds)));
519 countWritten = 0;
520 }
521
522 return ipmi::responseSuccess(countWritten);
523}
524
525/** @brief implements the get FRU inventory area info command
526 * @param fruDeviceId - FRU Device ID
527 *
528 * @returns IPMI completion code plus response data
529 * - inventorySize - Number of possible allocation units
530 * - accessType - Allocation unit size in bytes.
531 */
532ipmi::RspType<uint16_t, // inventorySize
533 uint8_t> // accessType
534 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
535{
536 if (fruDeviceId == 0xFF)
537 {
538 return ipmi::responseInvalidFieldRequest();
539 }
540
541 ipmi::Cc ret = getFru(ctx, fruDeviceId);
542 if (ret != ipmi::ccSuccess)
543 {
544 return ipmi::response(ret);
545 }
546
547 constexpr uint8_t accessType =
548 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
549
550 return ipmi::responseSuccess(fruCache.size(), accessType);
551}
552
553ipmi_ret_t getFruSdrCount(ipmi::Context::ptr ctx, size_t& count)
554{
555 count = deviceHashes.size();
556 return IPMI_CC_OK;
557}
558
559ipmi_ret_t getFruSdrs(ipmi::Context::ptr ctx, size_t index,
560 get_sdr::SensorDataFruRecord& resp)
561{
562 if (deviceHashes.size() < index)
563 {
564 return IPMI_CC_INVALID_FIELD_REQUEST;
565 }
566 auto device = deviceHashes.begin() + index;
567 uint8_t& bus = device->second.first;
568 uint8_t& address = device->second.second;
569
570 boost::container::flat_map<std::string, Value>* fruData = nullptr;
571 auto fru =
572 std::find_if(frus.begin(), frus.end(),
573 [bus, address, &fruData](ManagedEntry& entry) {
574 auto findFruDevice =
575 entry.second.find("xyz.openbmc_project.FruDevice");
576 if (findFruDevice == entry.second.end())
577 {
578 return false;
579 }
580 fruData = &(findFruDevice->second);
581 auto findBus = findFruDevice->second.find("BUS");
582 auto findAddress =
583 findFruDevice->second.find("ADDRESS");
584 if (findBus == findFruDevice->second.end() ||
585 findAddress == findFruDevice->second.end())
586 {
587 return false;
588 }
589 if (std::get<uint32_t>(findBus->second) != bus)
590 {
591 return false;
592 }
593 if (std::get<uint32_t>(findAddress->second) != address)
594 {
595 return false;
596 }
597 return true;
598 });
599 if (fru == frus.end())
600 {
601 return IPMI_CC_RESPONSE_ERROR;
602 }
603
604#ifdef USING_ENTITY_MANAGER_DECORATORS
605
606 boost::container::flat_map<std::string, Value>* entityData = nullptr;
607
608 // todo: this should really use caching, this is a very inefficient lookup
609 boost::system::error_code ec;
610 ManagedObjectType entities = ctx->bus->yield_method_call<ManagedObjectType>(
611 ctx->yield, ec, entityManagerServiceName, "/",
612 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
613
614 if (ec)
615 {
616 phosphor::logging::log<phosphor::logging::level::ERR>(
617 "GetMangagedObjects for ipmiStorageGetFruInvAreaInfo failed",
618 phosphor::logging::entry("ERROR=%s", ec.message().c_str()));
619
620 return ipmi::ccResponseError;
621 }
622
623 auto entity = std::find_if(
624 entities.begin(), entities.end(),
625 [bus, address, &entityData](ManagedEntry& entry) {
626 auto findFruDevice = entry.second.find(
627 "xyz.openbmc_project.Inventory.Decorator.FruDevice");
628 if (findFruDevice == entry.second.end())
629 {
630 return false;
631 }
632
633 // Integer fields added via Entity-Manager json are uint64_ts by
634 // default.
635 auto findBus = findFruDevice->second.find("Bus");
636 auto findAddress = findFruDevice->second.find("Address");
637
638 if (findBus == findFruDevice->second.end() ||
639 findAddress == findFruDevice->second.end())
640 {
641 return false;
642 }
643 if ((std::get<uint64_t>(findBus->second) != bus) ||
644 (std::get<uint64_t>(findAddress->second) != address))
645 {
646 return false;
647 }
648
649 // At this point we found the device entry and should return
650 // true.
651 auto findIpmiDevice = entry.second.find(
652 "xyz.openbmc_project.Inventory.Decorator.Ipmi");
653 if (findIpmiDevice != entry.second.end())
654 {
655 entityData = &(findIpmiDevice->second);
656 }
657
658 return true;
659 });
660
661 if (entity == entities.end())
662 {
663 if constexpr (DEBUG)
664 {
665 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
666 "not found for Fru\n");
667 }
668 }
669
670#endif
671
672 std::string name;
673 auto findProductName = fruData->find("BOARD_PRODUCT_NAME");
674 auto findBoardName = fruData->find("PRODUCT_PRODUCT_NAME");
675 if (findProductName != fruData->end())
676 {
677 name = std::get<std::string>(findProductName->second);
678 }
679 else if (findBoardName != fruData->end())
680 {
681 name = std::get<std::string>(findBoardName->second);
682 }
683 else
684 {
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;
732 resp.body.deviceIDLen = name.size();
733 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 {
845 phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
846 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 {
850 phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
851 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
897ipmi::RspType<uint16_t, // Next Record ID
898 uint16_t, // Record ID
899 uint8_t, // Record Type
900 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 {
1024 timestamp = std::mktime(&timeStruct);
1025 }
1026
1027 // Set the event message revision
1028 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1029
1030 uint16_t generatorID = 0;
1031 uint8_t sensorType = 0;
1032 uint16_t sensorAndLun = 0;
1033 uint8_t sensorNum = 0xFF;
1034 uint7_t eventType = 0;
1035 bool eventDir = 0;
1036 // System type events should have six fields
1037 if (targetEntryFields.size() >= 6)
1038 {
1039 std::string& generatorIDStr = targetEntryFields[3];
1040 std::string& sensorPath = targetEntryFields[4];
1041 std::string& eventDirStr = targetEntryFields[5];
1042
1043 // Get the generator ID
1044 try
1045 {
1046 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1047 }
1048 catch (const std::invalid_argument&)
1049 {
1050 std::cerr << "Invalid Generator ID\n";
1051 }
1052
1053 // Get the sensor type, sensor number, and event type for the sensor
1054 sensorType = getSensorTypeFromPath(sensorPath);
1055 sensorAndLun = getSensorNumberFromPath(sensorPath);
1056 sensorNum = static_cast<uint8_t>(sensorAndLun);
1057 generatorID |= sensorAndLun >> 8;
1058 eventType = getSensorEventTypeFromPath(sensorPath);
1059
1060 // Get the event direction
1061 try
1062 {
1063 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1064 }
1065 catch (const std::invalid_argument&)
1066 {
1067 std::cerr << "Invalid Event Direction\n";
1068 }
1069 }
1070
1071 // Only keep the eventData bytes that fit in the record
1072 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1073 eventData{};
1074 std::copy_n(eventDataBytes.begin(),
1075 std::min(eventDataBytes.size(), eventData.size()),
1076 eventData.begin());
1077
1078 return ipmi::responseSuccess(
1079 nextRecordID, recordID, recordType,
1080 systemEventType{timestamp, generatorID, evmRev, sensorType,
1081 sensorNum, eventType, eventDir, eventData});
1082 }
1083
1084 return ipmi::responseUnspecifiedError();
1085}
1086
1087ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1088 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1089 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1090 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1091 uint8_t eventData3)
1092{
1093 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1094 // added
1095 cancelSELReservation();
1096
1097 uint16_t responseID = 0xFFFF;
1098 return ipmi::responseSuccess(responseID);
1099}
1100
1101ipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx,
1102 uint16_t reservationID,
1103 const std::array<uint8_t, 3>& clr,
1104 uint8_t eraseOperation)
1105{
1106 if (!checkSELReservation(reservationID))
1107 {
1108 return ipmi::responseInvalidReservationId();
1109 }
1110
1111 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1112 if (clr != clrExpected)
1113 {
1114 return ipmi::responseInvalidFieldRequest();
1115 }
1116
1117 // Erasure status cannot be fetched, so always return erasure status as
1118 // `erase completed`.
1119 if (eraseOperation == ipmi::sel::getEraseStatus)
1120 {
1121 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1122 }
1123
1124 // Check that initiate erase is correct
1125 if (eraseOperation != ipmi::sel::initiateErase)
1126 {
1127 return ipmi::responseInvalidFieldRequest();
1128 }
1129
1130 // Per the IPMI spec, need to cancel any reservation when the SEL is
1131 // cleared
1132 cancelSELReservation();
1133
1134 // Save the erase time
1135 dynamic_sensors::ipmi::sel::erase_time::save();
1136
1137 // Clear the SEL by deleting the log files
1138 std::vector<std::filesystem::path> selLogFiles;
1139 if (getSELLogFiles(selLogFiles))
1140 {
1141 for (const std::filesystem::path& file : selLogFiles)
1142 {
1143 std::error_code ec;
1144 std::filesystem::remove(file, ec);
1145 }
1146 }
1147
1148 // Reload rsyslog so it knows to start new log files
1149 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
1150 sdbusplus::message::message rsyslogReload = dbus->new_method_call(
1151 "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
1152 "org.freedesktop.systemd1.Manager", "ReloadUnit");
1153 rsyslogReload.append("rsyslog.service", "replace");
1154 try
1155 {
1156 sdbusplus::message::message reloadResponse = dbus->call(rsyslogReload);
1157 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -05001158 catch (const sdbusplus::exception_t& e)
Willy Tude54f482021-01-26 15:59:09 -08001159 {
1160 phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
1161 }
1162
1163 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1164}
1165
1166ipmi::RspType<uint32_t> ipmiStorageGetSELTime()
1167{
1168 struct timespec selTime = {};
1169
1170 if (clock_gettime(CLOCK_REALTIME, &selTime) < 0)
1171 {
1172 return ipmi::responseUnspecifiedError();
1173 }
1174
1175 return ipmi::responseSuccess(selTime.tv_sec);
1176}
1177
1178ipmi::RspType<> ipmiStorageSetSELTime(uint32_t selTime)
1179{
1180 // Set SEL Time is not supported
1181 return ipmi::responseInvalidCommand();
1182}
1183
1184std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1185{
1186 std::vector<uint8_t> resp;
1187 if (index == 0)
1188 {
1189 Type12Record bmc = {};
1190 bmc.header.record_id_lsb = recordId;
1191 bmc.header.record_id_msb = recordId >> 8;
1192 bmc.header.sdr_version = ipmiSdrVersion;
1193 bmc.header.record_type = 0x12;
1194 bmc.header.record_length = 0x1b;
1195 bmc.slaveAddress = 0x20;
1196 bmc.channelNumber = 0;
1197 bmc.powerStateNotification = 0;
1198 bmc.deviceCapabilities = 0xBF;
1199 bmc.reserved = 0;
1200 bmc.entityID = 0x2E;
1201 bmc.entityInstance = 1;
1202 bmc.oem = 0;
1203 bmc.typeLengthCode = 0xD0;
1204 std::string bmcName = "Basbrd Mgmt Ctlr";
1205 std::copy(bmcName.begin(), bmcName.end(), bmc.name);
1206 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1207 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1208 }
1209 else if (index == 1)
1210 {
1211 Type12Record me = {};
1212 me.header.record_id_lsb = recordId;
1213 me.header.record_id_msb = recordId >> 8;
1214 me.header.sdr_version = ipmiSdrVersion;
1215 me.header.record_type = 0x12;
1216 me.header.record_length = 0x16;
1217 me.slaveAddress = 0x2C;
1218 me.channelNumber = 6;
1219 me.powerStateNotification = 0x24;
1220 me.deviceCapabilities = 0x21;
1221 me.reserved = 0;
1222 me.entityID = 0x2E;
1223 me.entityInstance = 2;
1224 me.oem = 0;
1225 me.typeLengthCode = 0xCB;
1226 std::string meName = "Mgmt Engine";
1227 std::copy(meName.begin(), meName.end(), me.name);
1228 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1229 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1230 }
1231 else
1232 {
1233 throw std::runtime_error("getType12SDRs:: Illegal index " +
1234 std::to_string(index));
1235 }
1236
1237 return resp;
1238}
1239
1240void registerStorageFunctions()
1241{
1242 createTimers();
1243 startMatch();
1244
1245 // <Get FRU Inventory Area Info>
1246 ipmi::registerHandler(ipmi::prioOemBase, ipmi::netFnStorage,
1247 ipmi::storage::cmdGetFruInventoryAreaInfo,
1248 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1249 // <READ FRU Data>
1250 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1251 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1252 ipmiStorageReadFruData);
1253
1254 // <WRITE FRU Data>
1255 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1256 ipmi::storage::cmdWriteFruData,
1257 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1258
1259 // <Get SEL Info>
1260 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1261 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1262 ipmiStorageGetSELInfo);
1263
1264 // <Get SEL Entry>
1265 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1266 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1267 ipmiStorageGetSELEntry);
1268
1269 // <Add SEL Entry>
1270 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1271 ipmi::storage::cmdAddSelEntry,
1272 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1273
1274 // <Clear SEL>
1275 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1276 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1277 ipmiStorageClearSEL);
1278
1279 // <Get SEL Time>
1280 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1281 ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,
1282 ipmiStorageGetSELTime);
1283
1284 // <Set SEL Time>
1285 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1286 ipmi::storage::cmdSetSelTime,
1287 ipmi::Privilege::Operator, ipmiStorageSetSELTime);
1288}
1289} // namespace storage
1290} // namespace ipmi