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