1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
3
4 #include "../utils.hpp"
5 #include "fru_utils.hpp"
6
7 #include <fcntl.h>
8 #include <sys/inotify.h>
9 #include <sys/ioctl.h>
10
11 #include <boost/asio/io_context.hpp>
12 #include <boost/asio/steady_timer.hpp>
13 #include <boost/container/flat_map.hpp>
14 #include <nlohmann/json.hpp>
15 #include <phosphor-logging/lg2.hpp>
16 #include <sdbusplus/asio/connection.hpp>
17 #include <sdbusplus/asio/object_server.hpp>
18
19 #include <array>
20 #include <cerrno>
21 #include <charconv>
22 #include <chrono>
23 #include <ctime>
24 #include <filesystem>
25 #include <fstream>
26 #include <functional>
27 #include <future>
28 #include <iomanip>
29 #include <iostream>
30 #include <limits>
31 #include <map>
32 #include <optional>
33 #include <regex>
34 #include <set>
35 #include <sstream>
36 #include <string>
37 #include <thread>
38 #include <utility>
39 #include <variant>
40 #include <vector>
41
42 extern "C"
43 {
44 #include <i2c/smbus.h>
45 #include <linux/i2c-dev.h>
46 }
47
48 namespace fs = std::filesystem;
49 constexpr size_t maxFruSize = 512;
50 constexpr size_t maxEepromPageIndex = 255;
51 constexpr size_t busTimeoutSeconds = 10;
52
53 constexpr const char* blocklistPath = PACKAGE_DIR "blacklist.json";
54
55 const static constexpr char* baseboardFruLocation =
56 "/etc/fru/baseboard.fru.bin";
57
58 const static constexpr char* i2CDevLocation = "/dev";
59
60 constexpr const char* fruDevice16BitDetectMode = FRU_DEVICE_16BITDETECTMODE;
61
62 // TODO Refactor these to not be globals
63 // NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
64 static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
65 busBlocklist;
66 struct FindDevicesWithCallback;
67
68 static boost::container::flat_map<
69 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
70 foundDevices;
71
72 static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
73 static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
74
75 boost::asio::io_context io;
76 // NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
77
78 bool updateFRUProperty(
79 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
80 const std::string& propertyName,
81 boost::container::flat_map<
82 std::pair<size_t, size_t>,
83 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
84 size_t& unknownBusObjectCount, const bool& powerIsOn,
85 sdbusplus::asio::object_server& objServer);
86
87 // Given a bus/address, produce the path in sysfs for an eeprom.
getEepromPath(size_t bus,size_t address)88 static std::string getEepromPath(size_t bus, size_t address)
89 {
90 std::stringstream output;
91 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
92 << std::setfill('0') << std::setw(4) << std::hex << address
93 << "/eeprom";
94 return output.str();
95 }
96
hasEepromFile(size_t bus,size_t address)97 static bool hasEepromFile(size_t bus, size_t address)
98 {
99 auto path = getEepromPath(bus, address);
100 try
101 {
102 return fs::exists(path);
103 }
104 catch (...)
105 {
106 return false;
107 }
108 }
109
readFromEeprom(int fd,off_t offset,size_t len,uint8_t * buf)110 static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
111 {
112 auto result = lseek(fd, offset, SEEK_SET);
113 if (result < 0)
114 {
115 std::cerr << "failed to seek\n";
116 return -1;
117 }
118
119 return read(fd, buf, len);
120 }
121
busStrToInt(const std::string_view busName)122 static int busStrToInt(const std::string_view busName)
123 {
124 auto findBus = busName.rfind('-');
125 if (findBus == std::string::npos)
126 {
127 return -1;
128 }
129 std::string_view num = busName.substr(findBus + 1);
130 int val = 0;
131 bool fullMatch = false;
132 fromCharsWrapper(num, val, fullMatch);
133 return val;
134 }
135
getRootBus(size_t bus)136 static int getRootBus(size_t bus)
137 {
138 auto ec = std::error_code();
139 auto path = std::filesystem::read_symlink(
140 std::filesystem::path(
141 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"),
142 ec);
143 if (ec)
144 {
145 return -1;
146 }
147
148 std::string filename = path.filename();
149 auto findBus = filename.find('-');
150 if (findBus == std::string::npos)
151 {
152 return -1;
153 }
154 return std::stoi(filename.substr(0, findBus));
155 }
156
isMuxBus(size_t bus)157 static bool isMuxBus(size_t bus)
158 {
159 auto ec = std::error_code();
160 auto isSymlink =
161 is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
162 std::to_string(bus) + "/mux_device"),
163 ec);
164 return (!ec && isSymlink);
165 }
166
makeProbeInterface(size_t bus,size_t address,sdbusplus::asio::object_server & objServer)167 static void makeProbeInterface(size_t bus, size_t address,
168 sdbusplus::asio::object_server& objServer)
169 {
170 if (isMuxBus(bus))
171 {
172 return; // the mux buses are random, no need to publish
173 }
174 auto [it, success] = foundDevices.emplace(
175 std::make_pair(bus, address),
176 objServer.add_interface(
177 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
178 std::to_string(address),
179 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
180 if (!success)
181 {
182 return; // already added
183 }
184 it->second->register_property("Bus", bus);
185 it->second->register_property("Address", address);
186 it->second->initialize();
187 }
188
189 // Issue an I2C transaction to first write to_target_buf_len bytes,then read
190 // from_target_buf_len bytes.
i2cSmbusWriteThenRead(int file,uint16_t address,uint8_t * toTargetBuf,uint8_t toTargetBufLen,uint8_t * fromTargetBuf,uint8_t fromTargetBufLen)191 static int i2cSmbusWriteThenRead(
192 int file, uint16_t address, uint8_t* toTargetBuf, uint8_t toTargetBufLen,
193 uint8_t* fromTargetBuf, uint8_t fromTargetBufLen)
194 {
195 if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
196 fromTargetBuf == nullptr || fromTargetBufLen == 0)
197 {
198 return -1;
199 }
200
201 constexpr size_t smbusWriteThenReadMsgCount = 2;
202 std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
203 struct i2c_rdwr_ioctl_data rdwr{};
204
205 msgs[0].addr = address;
206 msgs[0].flags = 0;
207 msgs[0].len = toTargetBufLen;
208 msgs[0].buf = toTargetBuf;
209 msgs[1].addr = address;
210 msgs[1].flags = I2C_M_RD;
211 msgs[1].len = fromTargetBufLen;
212 msgs[1].buf = fromTargetBuf;
213
214 rdwr.msgs = msgs.data();
215 rdwr.nmsgs = msgs.size();
216
217 int ret = ioctl(file, I2C_RDWR, &rdwr);
218
219 return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
220 }
221
readData(bool is16bit,bool isBytewise,int file,uint16_t address,off_t offset,size_t len,uint8_t * buf)222 static int64_t readData(bool is16bit, bool isBytewise, int file,
223 uint16_t address, off_t offset, size_t len,
224 uint8_t* buf)
225 {
226 if (!is16bit)
227 {
228 if (!isBytewise)
229 {
230 return i2c_smbus_read_i2c_block_data(
231 file, static_cast<uint8_t>(offset), len, buf);
232 }
233
234 std::span<uint8_t> bufspan{buf, len};
235 for (size_t i = 0; i < len; i++)
236 {
237 int byte = i2c_smbus_read_byte_data(
238 file, static_cast<uint8_t>(offset + i));
239 if (byte < 0)
240 {
241 return static_cast<int64_t>(byte);
242 }
243 bufspan[i] = static_cast<uint8_t>(byte);
244 }
245 return static_cast<int64_t>(len);
246 }
247
248 offset = htobe16(offset);
249 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
250 uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
251 return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
252 }
253
254 // Mode_1:
255 // --------
256 // Please refer to document docs/address_size_detection_modes.md for
257 // more details and explanations.
isDevice16BitMode1(int file)258 static std::optional<bool> isDevice16BitMode1(int file)
259 {
260 // Set the higher data word address bits to 0. It's safe on 8-bit
261 // addressing EEPROMs because it doesn't write any actual data.
262 int ret = i2c_smbus_write_byte(file, 0);
263 if (ret < 0)
264 {
265 return std::nullopt;
266 }
267
268 /* Get first byte */
269 int byte1 = i2c_smbus_read_byte_data(file, 0);
270 if (byte1 < 0)
271 {
272 return std::nullopt;
273 }
274 /* Read 7 more bytes, it will read same first byte in case of
275 * 8 bit but it will read next byte in case of 16 bit
276 */
277 for (int i = 0; i < 7; i++)
278 {
279 int byte2 = i2c_smbus_read_byte_data(file, 0);
280 if (byte2 < 0)
281 {
282 return std::nullopt;
283 }
284 if (byte2 != byte1)
285 {
286 return true;
287 }
288 }
289 return false;
290 }
291
292 // Mode_2:
293 // --------
294 // Please refer to document docs/address_size_detection_modes.md for
295 // more details and explanations.
isDevice16BitMode2(int file,uint16_t address)296 static std::optional<bool> isDevice16BitMode2(int file, uint16_t address)
297 {
298 uint8_t first = 0;
299 uint8_t cur = 0;
300 uint16_t v = 0;
301 int ret = 0;
302 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
303 uint8_t* p = reinterpret_cast<uint8_t*>(&v);
304
305 /*
306 * Write 2 bytes byte0 = 0, byte1 = {0..7} and then subsequent read byte
307 * It will read same first byte in case of 8 bit but
308 * it will read next byte in case of 16 bit
309 */
310 for (int i = 0; i < 8; i++)
311 {
312 v = htobe16(i);
313
314 ret = i2cSmbusWriteThenRead(file, address, p, 2, &cur, 1);
315 if (ret < 0)
316 {
317 return std::nullopt;
318 }
319
320 if (i == 0)
321 {
322 first = cur;
323 }
324
325 if (first != cur)
326 {
327 return true;
328 }
329 }
330 return false;
331 }
332
isDevice16Bit(int file,uint16_t address)333 static std::optional<bool> isDevice16Bit(int file, uint16_t address)
334 {
335 std::string mode(fruDevice16BitDetectMode);
336
337 if (mode == "MODE_2")
338 {
339 return isDevice16BitMode2(file, address);
340 }
341
342 return isDevice16BitMode1(file);
343 }
344
345 // TODO: This code is very similar to the non-eeprom version and can be merged
346 // with some tweaks.
processEeprom(int bus,int address)347 static std::vector<uint8_t> processEeprom(int bus, int address)
348 {
349 auto path = getEepromPath(bus, address);
350
351 int file = open(path.c_str(), O_RDONLY);
352 if (file < 0)
353 {
354 std::cerr << "Unable to open eeprom file: " << path << "\n";
355 return {};
356 }
357
358 std::string errorMessage = "eeprom at " + std::to_string(bus) +
359 " address " + std::to_string(address);
360 auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
361 return readFromEeprom(file, offset, length, outbuf);
362 };
363 FRUReader reader(std::move(readFunc));
364 std::pair<std::vector<uint8_t>, bool> pair =
365 readFRUContents(reader, errorMessage);
366
367 close(file);
368 return pair.first;
369 }
370
findI2CEeproms(int i2cBus,const std::shared_ptr<DeviceMap> & devices)371 std::set<size_t> findI2CEeproms(int i2cBus,
372 const std::shared_ptr<DeviceMap>& devices)
373 {
374 std::set<size_t> foundList;
375
376 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
377
378 // For each file listed under the i2c device
379 // NOTE: This should be faster than just checking for each possible address
380 // path.
381 auto ec = std::error_code();
382 for (const auto& p : fs::directory_iterator(path, ec))
383 {
384 if (ec)
385 {
386 std::cerr << "directory_iterator err " << ec.message() << "\n";
387 break;
388 }
389 const std::string node = p.path().string();
390 std::smatch m;
391 bool found =
392 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
393
394 if (!found)
395 {
396 continue;
397 }
398 if (m.size() != 2)
399 {
400 std::cerr << "regex didn't capture\n";
401 continue;
402 }
403
404 std::ssub_match subMatch = m[1];
405 std::string addressString = subMatch.str();
406 std::string_view addressStringView(addressString);
407
408 size_t address = 0;
409 std::from_chars(addressStringView.begin(), addressStringView.end(),
410 address, 16);
411
412 const std::string eeprom = node + "/eeprom";
413
414 try
415 {
416 if (!fs::exists(eeprom))
417 {
418 continue;
419 }
420 }
421 catch (...)
422 {
423 continue;
424 }
425
426 // There is an eeprom file at this address, it may have invalid
427 // contents, but we found it.
428 foundList.insert(address);
429
430 std::vector<uint8_t> device = processEeprom(i2cBus, address);
431 if (!device.empty())
432 {
433 devices->emplace(address, device);
434 }
435 }
436
437 return foundList;
438 }
439
getBusFRUs(int file,int first,int last,int bus,std::shared_ptr<DeviceMap> devices,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)440 int getBusFRUs(int file, int first, int last, int bus,
441 std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
442 sdbusplus::asio::object_server& objServer)
443 {
444 std::future<int> future = std::async(std::launch::async, [&]() {
445 // NOTE: When reading the devices raw on the bus, it can interfere with
446 // the driver's ability to operate, therefore read eeproms first before
447 // scanning for devices without drivers. Several experiments were run
448 // and it was determined that if there were any devices on the bus
449 // before the eeprom was hit and read, the eeprom driver wouldn't open
450 // while the bus device was open. An experiment was not performed to see
451 // if this issue was resolved if the i2c bus device was closed, but
452 // hexdumps of the eeprom later were successful.
453
454 // Scan for i2c eeproms loaded on this bus.
455 std::set<size_t> skipList = findI2CEeproms(bus, devices);
456 std::set<size_t>& failedItems = failedAddresses[bus];
457 std::set<size_t>& foundItems = fruAddresses[bus];
458 foundItems.clear();
459
460 auto busFind = busBlocklist.find(bus);
461 if (busFind != busBlocklist.end())
462 {
463 if (busFind->second != std::nullopt)
464 {
465 for (const auto& address : *(busFind->second))
466 {
467 skipList.insert(address);
468 }
469 }
470 }
471
472 std::set<size_t>* rootFailures = nullptr;
473 int rootBus = getRootBus(bus);
474
475 if (rootBus >= 0)
476 {
477 auto rootBusFind = busBlocklist.find(rootBus);
478 if (rootBusFind != busBlocklist.end())
479 {
480 if (rootBusFind->second != std::nullopt)
481 {
482 for (const auto& rootAddress : *(rootBusFind->second))
483 {
484 skipList.insert(rootAddress);
485 }
486 }
487 }
488 rootFailures = &(failedAddresses[rootBus]);
489 foundItems = fruAddresses[rootBus];
490 }
491
492 constexpr int startSkipTargetAddr = 0;
493 constexpr int endSkipTargetAddr = 12;
494
495 for (int ii = first; ii <= last; ii++)
496 {
497 if (foundItems.contains(ii))
498 {
499 continue;
500 }
501 if (skipList.contains(ii))
502 {
503 continue;
504 }
505 // skipping since no device is present in this range
506 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
507 {
508 continue;
509 }
510 // Set target address
511 if (ioctl(file, I2C_SLAVE, ii) < 0)
512 {
513 std::cerr << "device at bus " << bus << " address " << ii
514 << " busy\n";
515 continue;
516 }
517 // probe
518 if (i2c_smbus_read_byte(file) < 0)
519 {
520 continue;
521 }
522
523 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
524 "ADDR", ii);
525
526 makeProbeInterface(bus, ii, objServer);
527
528 if (failedItems.contains(ii))
529 {
530 // if we failed to read it once, unlikely we can read it later
531 continue;
532 }
533
534 if (rootFailures != nullptr)
535 {
536 if (rootFailures->contains(ii))
537 {
538 continue;
539 }
540 }
541
542 /* Check for Device type if it is 8 bit or 16 bit */
543 std::optional<bool> is16Bit = isDevice16Bit(file, ii);
544 if (!is16Bit.has_value())
545 {
546 std::cerr << "failed to read bus " << bus << " address " << ii
547 << "\n";
548 if (powerIsOn)
549 {
550 failedItems.insert(ii);
551 }
552 continue;
553 }
554 bool is16BitBool{*is16Bit};
555
556 auto readFunc = [is16BitBool, file,
557 ii](off_t offset, size_t length, uint8_t* outbuf) {
558 return readData(is16BitBool, false, file, ii, offset, length,
559 outbuf);
560 };
561 FRUReader reader(std::move(readFunc));
562 std::string errorMessage =
563 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
564 std::pair<std::vector<uint8_t>, bool> pair =
565 readFRUContents(reader, errorMessage);
566 const bool foundHeader = pair.second;
567
568 if (!foundHeader && !is16BitBool)
569 {
570 // certain FRU eeproms require bytewise reading.
571 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
572
573 auto readFunc =
574 [is16BitBool, file,
575 ii](off_t offset, size_t length, uint8_t* outbuf) {
576 return readData(is16BitBool, true, file, ii, offset,
577 length, outbuf);
578 };
579 FRUReader readerBytewise(std::move(readFunc));
580 pair = readFRUContents(readerBytewise, errorMessage);
581 }
582
583 if (pair.first.empty())
584 {
585 continue;
586 }
587
588 devices->emplace(ii, pair.first);
589 fruAddresses[bus].insert(ii);
590 }
591 return 1;
592 });
593 std::future_status status =
594 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
595 if (status == std::future_status::timeout)
596 {
597 std::cerr << "Error reading bus " << bus << "\n";
598 if (powerIsOn)
599 {
600 busBlocklist[bus] = std::nullopt;
601 }
602 close(file);
603 return -1;
604 }
605
606 close(file);
607 return future.get();
608 }
609
loadBlocklist(const char * path)610 void loadBlocklist(const char* path)
611 {
612 std::ifstream blocklistStream(path);
613 if (!blocklistStream.good())
614 {
615 // File is optional.
616 std::cerr << "Cannot open blocklist file.\n\n";
617 return;
618 }
619
620 nlohmann::json data =
621 nlohmann::json::parse(blocklistStream, nullptr, false);
622 if (data.is_discarded())
623 {
624 std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
625 "exiting\n";
626 std::exit(EXIT_FAILURE);
627 }
628
629 // It's expected to have at least one field, "buses" that is an array of the
630 // buses by integer. Allow for future options to exclude further aspects,
631 // such as specific addresses or ranges.
632 if (data.type() != nlohmann::json::value_t::object)
633 {
634 std::cerr << "Illegal blocklist, expected to read dictionary\n";
635 std::exit(EXIT_FAILURE);
636 }
637
638 // If buses field is missing, that's fine.
639 if (data.count("buses") == 1)
640 {
641 // Parse the buses array after a little validation.
642 auto buses = data.at("buses");
643 if (buses.type() != nlohmann::json::value_t::array)
644 {
645 // Buses field present but invalid, therefore this is an error.
646 std::cerr << "Invalid contents for blocklist buses field\n";
647 std::exit(EXIT_FAILURE);
648 }
649
650 // Catch exception here for type mis-match.
651 try
652 {
653 for (const auto& busIterator : buses)
654 {
655 // If bus and addresses field are missing, that's fine.
656 if (busIterator.contains("bus") &&
657 busIterator.contains("addresses"))
658 {
659 auto busData = busIterator.at("bus");
660 auto bus = busData.get<size_t>();
661
662 auto addressData = busIterator.at("addresses");
663 auto addresses =
664 addressData.get<std::set<std::string_view>>();
665
666 auto& block = busBlocklist[bus].emplace();
667 for (const auto& address : addresses)
668 {
669 size_t addressInt = 0;
670 bool fullMatch = false;
671 fromCharsWrapper(address.substr(2), addressInt,
672 fullMatch, 16);
673 block.insert(addressInt);
674 }
675 }
676 else
677 {
678 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
679 }
680 }
681 }
682 catch (const nlohmann::detail::type_error& e)
683 {
684 // Type mis-match is a critical error.
685 std::cerr << "Invalid bus type: " << e.what() << "\n";
686 std::exit(EXIT_FAILURE);
687 }
688 }
689 }
690
findI2CDevices(const std::vector<fs::path> & i2cBuses,BusMap & busmap,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)691 static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
692 BusMap& busmap, const bool& powerIsOn,
693 sdbusplus::asio::object_server& objServer)
694 {
695 for (const auto& i2cBus : i2cBuses)
696 {
697 int bus = busStrToInt(i2cBus.string());
698
699 if (bus < 0)
700 {
701 std::cerr << "Cannot translate " << i2cBus << " to int\n";
702 continue;
703 }
704 auto busFind = busBlocklist.find(bus);
705 if (busFind != busBlocklist.end())
706 {
707 if (busFind->second == std::nullopt)
708 {
709 continue; // Skip blocked busses.
710 }
711 }
712 int rootBus = getRootBus(bus);
713 auto rootBusFind = busBlocklist.find(rootBus);
714 if (rootBusFind != busBlocklist.end())
715 {
716 if (rootBusFind->second == std::nullopt)
717 {
718 continue;
719 }
720 }
721
722 auto file = open(i2cBus.c_str(), O_RDWR);
723 if (file < 0)
724 {
725 std::cerr << "unable to open i2c device " << i2cBus.string()
726 << "\n";
727 continue;
728 }
729 unsigned long funcs = 0;
730
731 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
732 {
733 std::cerr
734 << "Error: Could not get the adapter functionality matrix bus "
735 << bus << "\n";
736 close(file);
737 continue;
738 }
739 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
740 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
741 {
742 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
743 << bus << "\n";
744 close(file);
745 continue;
746 }
747 auto& device = busmap[bus];
748 device = std::make_shared<DeviceMap>();
749
750 // i2cdetect by default uses the range 0x03 to 0x77, as
751 // this is what we have tested with, use this range. Could be
752 // changed in future.
753 lg2::debug("Scanning bus {BUS}", "BUS", bus);
754
755 // fd is closed in this function in case the bus locks up
756 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
757
758 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
759 }
760 }
761
762 // this class allows an async response after all i2c devices are discovered
763 struct FindDevicesWithCallback :
764 std::enable_shared_from_this<FindDevicesWithCallback>
765 {
FindDevicesWithCallbackFindDevicesWithCallback766 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
767 BusMap& busmap, const bool& powerIsOn,
768 sdbusplus::asio::object_server& objServer,
769 std::function<void()>&& callback) :
770 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
771 _objServer(objServer), _callback(std::move(callback))
772 {}
~FindDevicesWithCallbackFindDevicesWithCallback773 ~FindDevicesWithCallback()
774 {
775 _callback();
776 }
runFindDevicesWithCallback777 void run()
778 {
779 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
780 }
781
782 const std::vector<fs::path>& _i2cBuses;
783 BusMap& _busMap;
784 const bool& _powerIsOn;
785 sdbusplus::asio::object_server& _objServer;
786 std::function<void()> _callback;
787 };
788
addFruObjectToDbus(std::vector<uint8_t> & device,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,uint32_t bus,uint32_t address,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)789 void addFruObjectToDbus(
790 std::vector<uint8_t>& device,
791 boost::container::flat_map<
792 std::pair<size_t, size_t>,
793 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
794 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
795 const bool& powerIsOn, sdbusplus::asio::object_server& objServer)
796 {
797 boost::container::flat_map<std::string, std::string> formattedFRU;
798
799 std::optional<std::string> optionalProductName = getProductName(
800 device, formattedFRU, bus, address, unknownBusObjectCount);
801 if (!optionalProductName)
802 {
803 std::cerr << "getProductName failed. product name is empty.\n";
804 return;
805 }
806
807 std::string productName =
808 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
809
810 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
811 if (index.has_value())
812 {
813 productName += "_";
814 productName += std::to_string(++(*index));
815 }
816
817 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
818 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
819 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
820
821 for (auto& property : formattedFRU)
822 {
823 std::regex_replace(property.second.begin(), property.second.begin(),
824 property.second.end(), nonAsciiRegex, "_");
825 if (property.second.empty())
826 {
827 continue;
828 }
829 std::string key =
830 std::regex_replace(property.first, nonAsciiRegex, "_");
831
832 // Allow FRU field update if ENABLE_FRU_UPDATE_PROPERTY is set.
833 if (isFieldEditable(property.first))
834 {
835 std::string propertyName = property.first;
836 iface->register_property(
837 key, property.second + '\0',
838 [bus, address, propertyName, &dbusInterfaceMap,
839 &unknownBusObjectCount, &powerIsOn,
840 &objServer](const std::string& req, std::string& resp) {
841 if (strcmp(req.c_str(), resp.c_str()) != 0)
842 {
843 // call the method which will update
844 if (updateFRUProperty(req, bus, address, propertyName,
845 dbusInterfaceMap,
846 unknownBusObjectCount, powerIsOn,
847 objServer))
848 {
849 resp = req;
850 }
851 else
852 {
853 throw std::invalid_argument(
854 "FRU property update failed.");
855 }
856 }
857 return 1;
858 });
859 }
860 else if (!iface->register_property(key, property.second + '\0'))
861 {
862 std::cerr << "illegal key: " << key << "\n";
863 }
864 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
865 property.first, "SECOND", property.second);
866 }
867
868 // baseboard will be 0, 0
869 iface->register_property("BUS", bus);
870 iface->register_property("ADDRESS", address);
871
872 iface->initialize();
873 }
874
readBaseboardFRU(std::vector<uint8_t> & baseboardFRU)875 static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
876 {
877 // try to read baseboard fru from file
878 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
879 if (baseboardFRUFile.good())
880 {
881 baseboardFRUFile.seekg(0, std::ios_base::end);
882 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
883 baseboardFRU.resize(fileSize);
884 baseboardFRUFile.seekg(0, std::ios_base::beg);
885 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
886 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
887 baseboardFRUFile.read(charOffset, fileSize);
888 }
889 else
890 {
891 return false;
892 }
893 return true;
894 }
895
writeFRU(uint8_t bus,uint8_t address,const std::vector<uint8_t> & fru)896 bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
897 {
898 boost::container::flat_map<std::string, std::string> tmp;
899 if (fru.size() > maxFruSize)
900 {
901 std::cerr << "Invalid fru.size() during writeFRU\n";
902 return false;
903 }
904 // verify legal fru by running it through fru parsing logic
905 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
906 {
907 std::cerr << "Invalid fru format during writeFRU\n";
908 return false;
909 }
910 // baseboard fru
911 if (bus == 0 && address == 0)
912 {
913 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
914 if (!file.good())
915 {
916 std::cerr << "Error opening file " << baseboardFruLocation << "\n";
917 throw DBusInternalError();
918 return false;
919 }
920 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
921 const char* charOffset = reinterpret_cast<const char*>(fru.data());
922 file.write(charOffset, fru.size());
923 return file.good();
924 }
925
926 if (hasEepromFile(bus, address))
927 {
928 auto path = getEepromPath(bus, address);
929 off_t offset = 0;
930
931 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
932 if (eeprom < 0)
933 {
934 std::cerr << "unable to open i2c device " << path << "\n";
935 throw DBusInternalError();
936 return false;
937 }
938
939 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
940 std::string errorMessage = "eeprom at " + std::to_string(bus) +
941 " address " + std::to_string(address);
942 auto readFunc = [eeprom](off_t offset, size_t length, uint8_t* outbuf) {
943 return readFromEeprom(eeprom, offset, length, outbuf);
944 };
945 FRUReader reader(std::move(readFunc));
946
947 if (!findFRUHeader(reader, errorMessage, blockData, offset))
948 {
949 offset = 0;
950 }
951
952 if (lseek(eeprom, offset, SEEK_SET) < 0)
953 {
954 std::cerr << "Unable to seek to offset " << offset
955 << " in device: " << path << "\n";
956 close(eeprom);
957 throw DBusInternalError();
958 }
959
960 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
961 if (writtenBytes < 0)
962 {
963 std::cerr << "unable to write to i2c device " << path << "\n";
964 close(eeprom);
965 throw DBusInternalError();
966 return false;
967 }
968
969 close(eeprom);
970 return true;
971 }
972
973 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
974
975 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
976 if (file < 0)
977 {
978 std::cerr << "unable to open i2c device " << i2cBus << "\n";
979 throw DBusInternalError();
980 return false;
981 }
982 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
983 {
984 std::cerr << "unable to set device address\n";
985 close(file);
986 throw DBusInternalError();
987 return false;
988 }
989
990 constexpr const size_t retryMax = 2;
991 uint16_t index = 0;
992 size_t retries = retryMax;
993 while (index < fru.size())
994 {
995 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
996 (retries == retryMax))
997 {
998 // The 4K EEPROM only uses the A2 and A1 device address bits
999 // with the third bit being a memory page address bit.
1000 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1001 {
1002 std::cerr << "unable to set device address\n";
1003 close(file);
1004 throw DBusInternalError();
1005 return false;
1006 }
1007 }
1008
1009 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1010 fru[index]) < 0)
1011 {
1012 if ((retries--) == 0U)
1013 {
1014 std::cerr << "error writing fru: " << strerror(errno) << "\n";
1015 close(file);
1016 throw DBusInternalError();
1017 return false;
1018 }
1019 }
1020 else
1021 {
1022 retries = retryMax;
1023 index++;
1024 }
1025 // most eeproms require 5-10ms between writes
1026 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1027 }
1028 close(file);
1029 return true;
1030 }
1031
rescanOneBus(BusMap & busmap,uint16_t busNum,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,bool dbusCall,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)1032 void rescanOneBus(
1033 BusMap& busmap, uint16_t busNum,
1034 boost::container::flat_map<
1035 std::pair<size_t, size_t>,
1036 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1037 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
1038 sdbusplus::asio::object_server& objServer)
1039 {
1040 for (auto device = foundDevices.begin(); device != foundDevices.end();)
1041 {
1042 if (device->first.first == static_cast<size_t>(busNum))
1043 {
1044 objServer.remove_interface(device->second);
1045 device = foundDevices.erase(device);
1046 }
1047 else
1048 {
1049 device++;
1050 }
1051 }
1052
1053 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1054 if (!fs::exists(busPath))
1055 {
1056 if (dbusCall)
1057 {
1058 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1059 << "\n";
1060 throw std::invalid_argument("Invalid Bus.");
1061 }
1062 return;
1063 }
1064
1065 std::vector<fs::path> i2cBuses;
1066 i2cBuses.emplace_back(busPath);
1067
1068 auto scan = std::make_shared<FindDevicesWithCallback>(
1069 i2cBuses, busmap, powerIsOn, objServer,
1070 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1071 &objServer]() {
1072 for (auto busIface = dbusInterfaceMap.begin();
1073 busIface != dbusInterfaceMap.end();)
1074 {
1075 if (busIface->first.first == static_cast<size_t>(busNum))
1076 {
1077 objServer.remove_interface(busIface->second);
1078 busIface = dbusInterfaceMap.erase(busIface);
1079 }
1080 else
1081 {
1082 busIface++;
1083 }
1084 }
1085 auto found = busmap.find(busNum);
1086 if (found == busmap.end() || found->second == nullptr)
1087 {
1088 return;
1089 }
1090 for (auto& device : *(found->second))
1091 {
1092 addFruObjectToDbus(device.second, dbusInterfaceMap,
1093 static_cast<uint32_t>(busNum), device.first,
1094 unknownBusObjectCount, powerIsOn, objServer);
1095 }
1096 });
1097 scan->run();
1098 }
1099
rescanBusses(BusMap & busmap,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)1100 void rescanBusses(
1101 BusMap& busmap,
1102 boost::container::flat_map<
1103 std::pair<size_t, size_t>,
1104 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1105 size_t& unknownBusObjectCount, const bool& powerIsOn,
1106 sdbusplus::asio::object_server& objServer)
1107 {
1108 static boost::asio::steady_timer timer(io);
1109 timer.expires_after(std::chrono::seconds(1));
1110
1111 // setup an async wait in case we get flooded with requests
1112 timer.async_wait([&](const boost::system::error_code& ec) {
1113 if (ec == boost::asio::error::operation_aborted)
1114 {
1115 return;
1116 }
1117
1118 if (ec)
1119 {
1120 std::cerr << "Error in timer: " << ec.message() << "\n";
1121 return;
1122 }
1123
1124 auto devDir = fs::path("/dev/");
1125 std::vector<fs::path> i2cBuses;
1126
1127 boost::container::flat_map<size_t, fs::path> busPaths;
1128 if (!getI2cDevicePaths(devDir, busPaths))
1129 {
1130 std::cerr << "unable to find i2c devices\n";
1131 return;
1132 }
1133
1134 for (const auto& busPath : busPaths)
1135 {
1136 i2cBuses.emplace_back(busPath.second);
1137 }
1138
1139 busmap.clear();
1140 for (auto& [pair, interface] : foundDevices)
1141 {
1142 objServer.remove_interface(interface);
1143 }
1144 foundDevices.clear();
1145
1146 auto scan = std::make_shared<FindDevicesWithCallback>(
1147 i2cBuses, busmap, powerIsOn, objServer, [&]() {
1148 for (auto& busIface : dbusInterfaceMap)
1149 {
1150 objServer.remove_interface(busIface.second);
1151 }
1152
1153 dbusInterfaceMap.clear();
1154 unknownBusObjectCount = 0;
1155
1156 // todo, get this from a more sensable place
1157 std::vector<uint8_t> baseboardFRU;
1158 if (readBaseboardFRU(baseboardFRU))
1159 {
1160 // If no device on i2c bus 0, the insertion will happen.
1161 auto bus0 =
1162 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1163 bus0.first->second->emplace(0, baseboardFRU);
1164 }
1165 for (auto& devicemap : busmap)
1166 {
1167 for (auto& device : *devicemap.second)
1168 {
1169 addFruObjectToDbus(device.second, dbusInterfaceMap,
1170 devicemap.first, device.first,
1171 unknownBusObjectCount, powerIsOn,
1172 objServer);
1173 }
1174 }
1175 });
1176 scan->run();
1177 });
1178 }
1179
1180 // Details with example of Asset Tag Update
1181 // To find location of Product Info Area asset tag as per FRU specification
1182 // 1. Find product Info area starting offset (*8 - as header will be in
1183 // multiple of 8 bytes).
1184 // 2. Skip 3 bytes of product info area (like format version, area length,
1185 // and language code).
1186 // 3. Traverse manufacturer name, product name, product version, & product
1187 // serial number, by reading type/length code to reach the Asset Tag.
1188 // 4. Update the Asset Tag, reposition the product Info area in multiple of
1189 // 8 bytes. Update the Product area length and checksum.
1190
updateFRUProperty(const std::string & updatePropertyReq,uint32_t bus,uint32_t address,const std::string & propertyName,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)1191 bool updateFRUProperty(
1192 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1193 const std::string& propertyName,
1194 boost::container::flat_map<
1195 std::pair<size_t, size_t>,
1196 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1197 size_t& unknownBusObjectCount, const bool& powerIsOn,
1198 sdbusplus::asio::object_server& objServer)
1199 {
1200 size_t updatePropertyReqLen = updatePropertyReq.length();
1201 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1202 {
1203 std::cerr
1204 << "FRU field data cannot be of 1 char or more than 63 chars. "
1205 "Invalid Length "
1206 << updatePropertyReqLen << "\n";
1207 return false;
1208 }
1209
1210 std::vector<uint8_t> fruData;
1211
1212 if (!getFruData(fruData, bus, address))
1213 {
1214 std::cerr << "Failure getting FRU Data \n";
1215 return false;
1216 }
1217
1218 struct FruArea fruAreaParams{};
1219
1220 if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
1221 {
1222 std::cerr << "findFruAreaLocationAndField failed \n";
1223 return false;
1224 }
1225
1226 std::vector<uint8_t> restFRUAreaFieldsData;
1227 if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1228 restFRUAreaFieldsData))
1229 {
1230 std::cerr << "copyRestFRUArea failed \n";
1231 return false;
1232 }
1233
1234 // Push post update fru areas if any
1235 unsigned int nextFRUAreaLoc = 0;
1236 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1237 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1238 {
1239 unsigned int fruAreaLoc =
1240 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
1241 if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
1242 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1243 {
1244 nextFRUAreaLoc = fruAreaLoc;
1245 }
1246 }
1247 std::vector<uint8_t> restFRUAreasData;
1248 if (nextFRUAreaLoc != 0U)
1249 {
1250 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1251 fruData.size() - nextFRUAreaLoc,
1252 std::back_inserter(restFRUAreasData));
1253 }
1254
1255 // check FRU area size
1256 size_t fruAreaDataSize =
1257 ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1258 restFRUAreaFieldsData.size());
1259 size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
1260 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1261 {
1262 #ifdef ENABLE_FRU_AREA_RESIZE
1263 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1264 // round size to 8-byte blocks
1265 newFRUAreaSize =
1266 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1267 size_t newFRUDataSize =
1268 fruData.size() + newFRUAreaSize - fruAreaParams.size;
1269 fruData.resize(newFRUDataSize);
1270 fruAreaParams.size = newFRUAreaSize;
1271 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
1272 #else
1273 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1274 << " should not be greater than available FRU area size: "
1275 << fruAreaAvailableSize << "\n";
1276 return false;
1277 #endif // ENABLE_FRU_AREA_RESIZE
1278 }
1279
1280 // write new requested property field length and data
1281 constexpr uint8_t newTypeLenMask = 0xC0;
1282 fruData[fruAreaParams.updateFieldLoc] =
1283 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1284 fruAreaParams.updateFieldLoc++;
1285 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1286 fruData.begin() + fruAreaParams.updateFieldLoc);
1287
1288 // Copy remaining data to main fru area - post updated fru field vector
1289 fruAreaParams.restFieldsLoc =
1290 fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1291 size_t fruAreaDataEnd =
1292 fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
1293
1294 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1295 fruData.begin() + fruAreaParams.restFieldsLoc);
1296
1297 // Update final fru with new fru area length and checksum
1298 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1299 fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
1300
1301 #ifdef ENABLE_FRU_AREA_RESIZE
1302 ++nextFRUAreaNewLoc;
1303 ssize_t nextFRUAreaOffsetDiff =
1304 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1305 // Append rest FRU Areas if size changed and there were other sections after
1306 // updated one
1307 if ((nextFRUAreaOffsetDiff != 0) && (nextFRUAreaLoc != 0U))
1308 {
1309 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1310 fruData.begin() + nextFRUAreaNewLoc);
1311 // Update Common Header
1312 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1313 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1314 {
1315 unsigned int fruAreaOffsetField =
1316 getHeaderAreaFieldOffset(nextFRUArea);
1317 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1318 if (curFRUAreaOffset > fruAreaParams.end)
1319 {
1320 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1321 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1322 }
1323 }
1324 // Calculate new checksum
1325 std::vector<uint8_t> headerFRUData;
1326 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1327 size_t checksumVal = calculateChecksum(headerFRUData);
1328 fruData[7] = static_cast<uint8_t>(checksumVal);
1329 // fill zeros if FRU Area size decreased
1330 if (nextFRUAreaOffsetDiff < 0)
1331 {
1332 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1333 restFRUAreasData.size(),
1334 fruData.end(), 0);
1335 }
1336 }
1337 #else
1338 // this is to avoid "unused variable" warning
1339 (void)nextFRUAreaNewLoc;
1340 #endif // ENABLE_FRU_AREA_RESIZE
1341 if (fruData.empty())
1342 {
1343 return false;
1344 }
1345
1346 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1347 fruData))
1348 {
1349 return false;
1350 }
1351
1352 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1353 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1354 objServer);
1355 return true;
1356 }
1357
main()1358 int main()
1359 {
1360 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1361 sdbusplus::asio::object_server objServer(systemBus);
1362
1363 static size_t unknownBusObjectCount = 0;
1364 static bool powerIsOn = false;
1365 auto devDir = fs::path("/dev/");
1366 auto matchString = std::string(R"(i2c-\d+$)");
1367 std::vector<fs::path> i2cBuses;
1368
1369 if (!findFiles(devDir, matchString, i2cBuses))
1370 {
1371 std::cerr << "unable to find i2c devices\n";
1372 return 1;
1373 }
1374
1375 // check for and load blocklist with initial buses.
1376 loadBlocklist(blocklistPath);
1377
1378 systemBus->request_name("xyz.openbmc_project.FruDevice");
1379
1380 // this is a map with keys of pair(bus number, address) and values of
1381 // the object on dbus
1382 boost::container::flat_map<std::pair<size_t, size_t>,
1383 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1384 dbusInterfaceMap;
1385
1386 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1387 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1388 "xyz.openbmc_project.FruDeviceManager");
1389
1390 iface->register_method("ReScan", [&]() {
1391 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1392 objServer);
1393 });
1394
1395 iface->register_method("ReScanBus", [&](uint16_t bus) {
1396 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
1397 powerIsOn, objServer);
1398 });
1399
1400 iface->register_method("GetRawFru", getFRUInfo);
1401
1402 iface->register_method(
1403 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1404 const std::vector<uint8_t>& data) {
1405 if (!writeFRU(bus, address, data))
1406 {
1407 throw std::invalid_argument("Invalid Arguments.");
1408 return;
1409 }
1410 // schedule rescan on success
1411 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1412 powerIsOn, objServer);
1413 });
1414 iface->initialize();
1415
1416 std::function<void(sdbusplus::message_t & message)> eventHandler =
1417 [&](sdbusplus::message_t& message) {
1418 std::string objectName;
1419 boost::container::flat_map<
1420 std::string,
1421 std::variant<std::string, bool, int64_t, uint64_t, double>>
1422 values;
1423 message.read(objectName, values);
1424 auto findState = values.find("CurrentHostState");
1425 if (findState != values.end())
1426 {
1427 if (std::get<std::string>(findState->second) ==
1428 "xyz.openbmc_project.State.Host.HostState.Running")
1429 {
1430 powerIsOn = true;
1431 }
1432 }
1433
1434 if (powerIsOn)
1435 {
1436 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1437 powerIsOn, objServer);
1438 }
1439 };
1440
1441 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1442 static_cast<sdbusplus::bus_t&>(*systemBus),
1443 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
1444 "openbmc_project/state/"
1445 "host0',arg0='xyz.openbmc_project.State.Host'",
1446 eventHandler);
1447
1448 int fd = inotify_init();
1449 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
1450 std::array<char, 4096> readBuffer{};
1451 // monitor for new i2c devices
1452 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1453 std::function<void(const boost::system::error_code, std::size_t)>
1454 watchI2cBusses = [&](const boost::system::error_code& ec,
1455 std::size_t bytesTransferred) {
1456 if (ec)
1457 {
1458 std::cout << "Callback Error " << ec << "\n";
1459 return;
1460 }
1461 size_t index = 0;
1462 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1463 {
1464 const char* p = &readBuffer[index];
1465 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1466 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1467 switch (iEvent->mask)
1468 {
1469 case IN_CREATE:
1470 case IN_MOVED_TO:
1471 case IN_DELETE:
1472 {
1473 std::string_view name(&iEvent->name[0], iEvent->len);
1474 if (name.starts_with("i2c"))
1475 {
1476 int bus = busStrToInt(name);
1477 if (bus < 0)
1478 {
1479 std::cerr
1480 << "Could not parse bus " << name << "\n";
1481 continue;
1482 }
1483 int rootBus = getRootBus(bus);
1484 if (rootBus >= 0)
1485 {
1486 rescanOneBus(busMap,
1487 static_cast<uint16_t>(rootBus),
1488 dbusInterfaceMap, false,
1489 unknownBusObjectCount, powerIsOn,
1490 objServer);
1491 }
1492 rescanOneBus(busMap, static_cast<uint16_t>(bus),
1493 dbusInterfaceMap, false,
1494 unknownBusObjectCount, powerIsOn,
1495 objServer);
1496 }
1497 }
1498 break;
1499 default:
1500 break;
1501 }
1502 index += sizeof(inotify_event) + iEvent->len;
1503 }
1504
1505 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1506 watchI2cBusses);
1507 };
1508
1509 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
1510 // run the initial scan
1511 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1512 objServer);
1513
1514 io.run();
1515 return 0;
1516 }
1517