xref: /openbmc/entity-manager/src/fru_device.cpp (revision 6fdfac0a898ced2a660722667e4a5aed85a0deb8)
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 device = foundDevices.begin(); device != foundDevices.end();)
983     {
984         if (device->first.first == static_cast<size_t>(busNum))
985         {
986             objServer.remove_interface(device->second);
987             device = foundDevices.erase(device);
988         }
989         else
990         {
991             device++;
992         }
993     }
994 
995     fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
996     if (!fs::exists(busPath))
997     {
998         if (dbusCall)
999         {
1000             std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1001                       << "\n";
1002             throw std::invalid_argument("Invalid Bus.");
1003         }
1004         return;
1005     }
1006 
1007     std::vector<fs::path> i2cBuses;
1008     i2cBuses.emplace_back(busPath);
1009 
1010     auto scan = std::make_shared<FindDevicesWithCallback>(
1011         i2cBuses, busmap, powerIsOn, objServer,
1012         [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1013          &objServer, &systemBus]() {
1014         for (auto busIface = dbusInterfaceMap.begin();
1015              busIface != dbusInterfaceMap.end();)
1016         {
1017             if (busIface->first.first == static_cast<size_t>(busNum))
1018             {
1019                 objServer.remove_interface(busIface->second);
1020                 busIface = dbusInterfaceMap.erase(busIface);
1021             }
1022             else
1023             {
1024                 busIface++;
1025             }
1026         }
1027         auto found = busmap.find(busNum);
1028         if (found == busmap.end() || found->second == nullptr)
1029         {
1030             return;
1031         }
1032         for (auto& device : *(found->second))
1033         {
1034             addFruObjectToDbus(device.second, dbusInterfaceMap,
1035                                static_cast<uint32_t>(busNum), device.first,
1036                                unknownBusObjectCount, powerIsOn, objServer,
1037                                systemBus);
1038         }
1039     });
1040     scan->run();
1041 }
1042 
1043 void rescanBusses(
1044     BusMap& busmap,
1045     boost::container::flat_map<
1046         std::pair<size_t, size_t>,
1047         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1048     size_t& unknownBusObjectCount, const bool& powerIsOn,
1049     sdbusplus::asio::object_server& objServer,
1050     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
1051 {
1052     static boost::asio::steady_timer timer(io);
1053     timer.expires_from_now(std::chrono::seconds(1));
1054 
1055     // setup an async wait in case we get flooded with requests
1056     timer.async_wait([&](const boost::system::error_code& ec) {
1057         if (ec == boost::asio::error::operation_aborted)
1058         {
1059             return;
1060         }
1061 
1062         if (ec)
1063         {
1064             std::cerr << "Error in timer: " << ec.message() << "\n";
1065             return;
1066         }
1067 
1068         auto devDir = fs::path("/dev/");
1069         std::vector<fs::path> i2cBuses;
1070 
1071         boost::container::flat_map<size_t, fs::path> busPaths;
1072         if (!getI2cDevicePaths(devDir, busPaths))
1073         {
1074             std::cerr << "unable to find i2c devices\n";
1075             return;
1076         }
1077 
1078         for (const auto& busPath : busPaths)
1079         {
1080             i2cBuses.emplace_back(busPath.second);
1081         }
1082 
1083         busmap.clear();
1084         for (auto& [pair, interface] : foundDevices)
1085         {
1086             objServer.remove_interface(interface);
1087         }
1088         foundDevices.clear();
1089 
1090         auto scan = std::make_shared<FindDevicesWithCallback>(
1091             i2cBuses, busmap, powerIsOn, objServer, [&]() {
1092             for (auto& busIface : dbusInterfaceMap)
1093             {
1094                 objServer.remove_interface(busIface.second);
1095             }
1096 
1097             dbusInterfaceMap.clear();
1098             unknownBusObjectCount = 0;
1099 
1100             // todo, get this from a more sensable place
1101             std::vector<uint8_t> baseboardFRU;
1102             if (readBaseboardFRU(baseboardFRU))
1103             {
1104                 // If no device on i2c bus 0, the insertion will happen.
1105                 auto bus0 = busmap.try_emplace(0,
1106                                                std::make_shared<DeviceMap>());
1107                 bus0.first->second->emplace(0, baseboardFRU);
1108             }
1109             for (auto& devicemap : busmap)
1110             {
1111                 for (auto& device : *devicemap.second)
1112                 {
1113                     addFruObjectToDbus(device.second, dbusInterfaceMap,
1114                                        devicemap.first, device.first,
1115                                        unknownBusObjectCount, powerIsOn,
1116                                        objServer, systemBus);
1117                 }
1118             }
1119         });
1120         scan->run();
1121     });
1122 }
1123 
1124 // Details with example of Asset Tag Update
1125 // To find location of Product Info Area asset tag as per FRU specification
1126 // 1. Find product Info area starting offset (*8 - as header will be in
1127 // multiple of 8 bytes).
1128 // 2. Skip 3 bytes of product info area (like format version, area length,
1129 // and language code).
1130 // 3. Traverse manufacturer name, product name, product version, & product
1131 // serial number, by reading type/length code to reach the Asset Tag.
1132 // 4. Update the Asset Tag, reposition the product Info area in multiple of
1133 // 8 bytes. Update the Product area length and checksum.
1134 
1135 bool updateFRUProperty(
1136     const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1137     const std::string& propertyName,
1138     boost::container::flat_map<
1139         std::pair<size_t, size_t>,
1140         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1141     size_t& unknownBusObjectCount, const bool& powerIsOn,
1142     sdbusplus::asio::object_server& objServer,
1143     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
1144 {
1145     size_t updatePropertyReqLen = updatePropertyReq.length();
1146     if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1147     {
1148         std::cerr
1149             << "FRU field data cannot be of 1 char or more than 63 chars. "
1150                "Invalid Length "
1151             << updatePropertyReqLen << "\n";
1152         return false;
1153     }
1154 
1155     std::vector<uint8_t> fruData;
1156 
1157     if (!getFruData(fruData, bus, address))
1158     {
1159         std::cerr << "Failure getting FRU Data \n";
1160         return false;
1161     }
1162 
1163     struct FruArea fruAreaParams
1164     {};
1165 
1166     if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
1167     {
1168         std::cerr << "findFruAreaLocationAndField failed \n";
1169         return false;
1170     }
1171 
1172     std::vector<uint8_t> restFRUAreaFieldsData;
1173     if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1174                          restFRUAreaFieldsData))
1175     {
1176         std::cerr << "copyRestFRUArea failed \n";
1177         return false;
1178     }
1179 
1180     // Push post update fru areas if any
1181     unsigned int nextFRUAreaLoc = 0;
1182     for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1183          nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1184     {
1185         unsigned int fruAreaLoc =
1186             fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
1187         if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
1188             ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1189         {
1190             nextFRUAreaLoc = fruAreaLoc;
1191         }
1192     }
1193     std::vector<uint8_t> restFRUAreasData;
1194     if (nextFRUAreaLoc != 0U)
1195     {
1196         std::copy_n(fruData.begin() + nextFRUAreaLoc,
1197                     fruData.size() - nextFRUAreaLoc,
1198                     std::back_inserter(restFRUAreasData));
1199     }
1200 
1201     // check FRU area size
1202     size_t fruAreaDataSize =
1203         ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1204          restFRUAreaFieldsData.size());
1205     size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
1206     if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1207     {
1208 #ifdef ENABLE_FRU_AREA_RESIZE
1209         size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1210         // round size to 8-byte blocks
1211         newFRUAreaSize = ((newFRUAreaSize - 1) / fruBlockSize + 1) *
1212                          fruBlockSize;
1213         size_t newFRUDataSize = fruData.size() + newFRUAreaSize -
1214                                 fruAreaParams.size;
1215         fruData.resize(newFRUDataSize);
1216         fruAreaParams.size = newFRUAreaSize;
1217         fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
1218 #else
1219         std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1220                   << " should not be greater than available FRU area size: "
1221                   << fruAreaAvailableSize << "\n";
1222         return false;
1223 #endif // ENABLE_FRU_AREA_RESIZE
1224     }
1225 
1226     // write new requested property field length and data
1227     constexpr uint8_t newTypeLenMask = 0xC0;
1228     fruData[fruAreaParams.updateFieldLoc] =
1229         static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1230     fruAreaParams.updateFieldLoc++;
1231     std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1232               fruData.begin() + fruAreaParams.updateFieldLoc);
1233 
1234     // Copy remaining data to main fru area - post updated fru field vector
1235     fruAreaParams.restFieldsLoc = fruAreaParams.updateFieldLoc +
1236                                   updatePropertyReqLen;
1237     size_t fruAreaDataEnd = fruAreaParams.restFieldsLoc +
1238                             restFRUAreaFieldsData.size();
1239 
1240     std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1241               fruData.begin() + fruAreaParams.restFieldsLoc);
1242 
1243     // Update final fru with new fru area length and checksum
1244     unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1245         fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
1246 
1247 #ifdef ENABLE_FRU_AREA_RESIZE
1248     ++nextFRUAreaNewLoc;
1249     ssize_t nextFRUAreaOffsetDiff = (nextFRUAreaNewLoc - nextFRUAreaLoc) /
1250                                     fruBlockSize;
1251     // Append rest FRU Areas if size changed and there were other sections after
1252     // updated one
1253     if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1254     {
1255         std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1256                   fruData.begin() + nextFRUAreaNewLoc);
1257         // Update Common Header
1258         for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1259              nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1260         {
1261             unsigned int fruAreaOffsetField =
1262                 getHeaderAreaFieldOffset(nextFRUArea);
1263             size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1264             if (curFRUAreaOffset > fruAreaParams.end)
1265             {
1266                 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1267                     curFRUAreaOffset + nextFRUAreaOffsetDiff);
1268             }
1269         }
1270         // Calculate new checksum
1271         std::vector<uint8_t> headerFRUData;
1272         std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1273         size_t checksumVal = calculateChecksum(headerFRUData);
1274         fruData[7] = static_cast<uint8_t>(checksumVal);
1275         // fill zeros if FRU Area size decreased
1276         if (nextFRUAreaOffsetDiff < 0)
1277         {
1278             std::fill(fruData.begin() + nextFRUAreaNewLoc +
1279                           restFRUAreasData.size(),
1280                       fruData.end(), 0);
1281         }
1282     }
1283 #else
1284     // this is to avoid "unused variable" warning
1285     (void)nextFRUAreaNewLoc;
1286 #endif // ENABLE_FRU_AREA_RESIZE
1287     if (fruData.empty())
1288     {
1289         return false;
1290     }
1291 
1292     if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1293                   fruData))
1294     {
1295         return false;
1296     }
1297 
1298     // Rescan the bus so that GetRawFru dbus-call fetches updated values
1299     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1300                  objServer, systemBus);
1301     return true;
1302 }
1303 
1304 int main()
1305 {
1306     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1307     sdbusplus::asio::object_server objServer(systemBus);
1308 
1309     static size_t unknownBusObjectCount = 0;
1310     static bool powerIsOn = false;
1311     auto devDir = fs::path("/dev/");
1312     auto matchString = std::string(R"(i2c-\d+$)");
1313     std::vector<fs::path> i2cBuses;
1314 
1315     if (!findFiles(devDir, matchString, i2cBuses))
1316     {
1317         std::cerr << "unable to find i2c devices\n";
1318         return 1;
1319     }
1320 
1321     // check for and load blacklist with initial buses.
1322     loadBlacklist(blacklistPath);
1323 
1324     systemBus->request_name("xyz.openbmc_project.FruDevice");
1325 
1326     // this is a map with keys of pair(bus number, address) and values of
1327     // the object on dbus
1328     boost::container::flat_map<std::pair<size_t, size_t>,
1329                                std::shared_ptr<sdbusplus::asio::dbus_interface>>
1330         dbusInterfaceMap;
1331 
1332     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1333         objServer.add_interface("/xyz/openbmc_project/FruDevice",
1334                                 "xyz.openbmc_project.FruDeviceManager");
1335 
1336     iface->register_method("ReScan", [&]() {
1337         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1338                      objServer, systemBus);
1339     });
1340 
1341     iface->register_method("ReScanBus", [&](uint16_t bus) {
1342         rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
1343                      powerIsOn, objServer, systemBus);
1344     });
1345 
1346     iface->register_method("GetRawFru", getFRUInfo);
1347 
1348     iface->register_method("WriteFru",
1349                            [&](const uint16_t bus, const uint8_t address,
1350                                const std::vector<uint8_t>& data) {
1351         if (!writeFRU(bus, address, data))
1352         {
1353             throw std::invalid_argument("Invalid Arguments.");
1354             return;
1355         }
1356         // schedule rescan on success
1357         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1358                      objServer, systemBus);
1359     });
1360     iface->initialize();
1361 
1362     std::function<void(sdbusplus::message_t & message)> eventHandler =
1363         [&](sdbusplus::message_t& message) {
1364         std::string objectName;
1365         boost::container::flat_map<
1366             std::string,
1367             std::variant<std::string, bool, int64_t, uint64_t, double>>
1368             values;
1369         message.read(objectName, values);
1370         auto findState = values.find("CurrentHostState");
1371         if (findState != values.end())
1372         {
1373             if (std::get<std::string>(findState->second) ==
1374                 "xyz.openbmc_project.State.Host.HostState.Running")
1375             {
1376                 powerIsOn = true;
1377             }
1378         }
1379 
1380         if (powerIsOn)
1381         {
1382             rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1383                          powerIsOn, objServer, systemBus);
1384         }
1385     };
1386 
1387     sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1388         static_cast<sdbusplus::bus_t&>(*systemBus),
1389         "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
1390         "openbmc_project/state/"
1391         "host0',arg0='xyz.openbmc_project.State.Host'",
1392         eventHandler);
1393 
1394     int fd = inotify_init();
1395     inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
1396     std::array<char, 4096> readBuffer{};
1397     // monitor for new i2c devices
1398     boost::asio::posix::stream_descriptor dirWatch(io, fd);
1399     std::function<void(const boost::system::error_code, std::size_t)>
1400         watchI2cBusses = [&](const boost::system::error_code& ec,
1401                              std::size_t bytesTransferred) {
1402         if (ec)
1403         {
1404             std::cout << "Callback Error " << ec << "\n";
1405             return;
1406         }
1407         size_t index = 0;
1408         while ((index + sizeof(inotify_event)) <= bytesTransferred)
1409         {
1410             const char* p = &readBuffer[index];
1411             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1412             const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1413             switch (iEvent->mask)
1414             {
1415                 case IN_CREATE:
1416                 case IN_MOVED_TO:
1417                 case IN_DELETE:
1418                     std::string_view name(&iEvent->name[0], iEvent->len);
1419                     if (boost::starts_with(name, "i2c"))
1420                     {
1421                         int bus = busStrToInt(name);
1422                         if (bus < 0)
1423                         {
1424                             std::cerr << "Could not parse bus " << name << "\n";
1425                             continue;
1426                         }
1427                         int rootBus = getRootBus(bus);
1428                         if (rootBus >= 0)
1429                         {
1430                             rescanOneBus(busMap, static_cast<uint16_t>(rootBus),
1431                                          dbusInterfaceMap, false,
1432                                          unknownBusObjectCount, powerIsOn,
1433                                          objServer, systemBus);
1434                         }
1435                         rescanOneBus(busMap, static_cast<uint16_t>(bus),
1436                                      dbusInterfaceMap, false,
1437                                      unknownBusObjectCount, powerIsOn,
1438                                      objServer, systemBus);
1439                     }
1440             }
1441             index += sizeof(inotify_event) + iEvent->len;
1442         }
1443 
1444         dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1445                                  watchI2cBusses);
1446     };
1447 
1448     dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
1449     // run the initial scan
1450     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1451                  objServer, systemBus);
1452 
1453     io.run();
1454     return 0;
1455 }
1456