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