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