xref: /openbmc/entity-manager/src/fru_device.cpp (revision fc171428)
1e45d8c71SBrad Bishop /*
2e45d8c71SBrad Bishop // Copyright (c) 2018 Intel Corporation
3e45d8c71SBrad Bishop //
4e45d8c71SBrad Bishop // Licensed under the Apache License, Version 2.0 (the "License");
5e45d8c71SBrad Bishop // you may not use this file except in compliance with the License.
6e45d8c71SBrad Bishop // You may obtain a copy of the License at
7e45d8c71SBrad Bishop //
8e45d8c71SBrad Bishop //      http://www.apache.org/licenses/LICENSE-2.0
9e45d8c71SBrad Bishop //
10e45d8c71SBrad Bishop // Unless required by applicable law or agreed to in writing, software
11e45d8c71SBrad Bishop // distributed under the License is distributed on an "AS IS" BASIS,
12e45d8c71SBrad Bishop // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13e45d8c71SBrad Bishop // See the License for the specific language governing permissions and
14e45d8c71SBrad Bishop // limitations under the License.
15e45d8c71SBrad Bishop */
16e45d8c71SBrad Bishop /// \file fru_device.cpp
17e45d8c71SBrad Bishop 
18e45d8c71SBrad Bishop #include "fru_utils.hpp"
19e45d8c71SBrad Bishop #include "utils.hpp"
20e45d8c71SBrad Bishop 
21e45d8c71SBrad Bishop #include <fcntl.h>
22e45d8c71SBrad Bishop #include <sys/inotify.h>
23e45d8c71SBrad Bishop #include <sys/ioctl.h>
24e45d8c71SBrad Bishop 
25e45d8c71SBrad Bishop #include <boost/algorithm/string/predicate.hpp>
2634c3e016SEd Tanous #include <boost/asio/io_context.hpp>
27aa497edfSEd Tanous #include <boost/asio/steady_timer.hpp>
28e45d8c71SBrad Bishop #include <boost/container/flat_map.hpp>
29e45d8c71SBrad Bishop #include <nlohmann/json.hpp>
30e45d8c71SBrad Bishop #include <sdbusplus/asio/connection.hpp>
31e45d8c71SBrad Bishop #include <sdbusplus/asio/object_server.hpp>
32e45d8c71SBrad Bishop 
33e45d8c71SBrad Bishop #include <array>
34e45d8c71SBrad Bishop #include <cerrno>
353013fb49SEd Tanous #include <charconv>
36e45d8c71SBrad Bishop #include <chrono>
37e45d8c71SBrad Bishop #include <ctime>
38e45d8c71SBrad Bishop #include <filesystem>
39e45d8c71SBrad Bishop #include <fstream>
40e45d8c71SBrad Bishop #include <functional>
41e45d8c71SBrad Bishop #include <future>
42e45d8c71SBrad Bishop #include <iomanip>
43e45d8c71SBrad Bishop #include <iostream>
44e45d8c71SBrad Bishop #include <limits>
45e45d8c71SBrad Bishop #include <map>
46bfda2c43SBonnie Lo #include <optional>
47e45d8c71SBrad Bishop #include <regex>
48e45d8c71SBrad Bishop #include <set>
49e45d8c71SBrad Bishop #include <sstream>
50e45d8c71SBrad Bishop #include <string>
51e45d8c71SBrad Bishop #include <thread>
52e45d8c71SBrad Bishop #include <utility>
53e45d8c71SBrad Bishop #include <variant>
54e45d8c71SBrad Bishop #include <vector>
55e45d8c71SBrad Bishop 
56e45d8c71SBrad Bishop extern "C"
57e45d8c71SBrad Bishop {
58e45d8c71SBrad Bishop #include <i2c/smbus.h>
59e45d8c71SBrad Bishop #include <linux/i2c-dev.h>
60e45d8c71SBrad Bishop }
61e45d8c71SBrad Bishop 
62e45d8c71SBrad Bishop namespace fs = std::filesystem;
63e45d8c71SBrad Bishop static constexpr bool debug = false;
64e45d8c71SBrad Bishop constexpr size_t maxFruSize = 512;
65e45d8c71SBrad Bishop constexpr size_t maxEepromPageIndex = 255;
667329a225Sankita prasad constexpr size_t busTimeoutSeconds = 10;
67e45d8c71SBrad Bishop 
682447c24dSMatt Simmering constexpr const char* blocklistPath = PACKAGE_DIR "blacklist.json";
69e45d8c71SBrad Bishop 
70e45d8c71SBrad Bishop const static constexpr char* baseboardFruLocation =
71e45d8c71SBrad Bishop     "/etc/fru/baseboard.fru.bin";
72e45d8c71SBrad Bishop 
73e45d8c71SBrad Bishop const static constexpr char* i2CDevLocation = "/dev";
74e45d8c71SBrad Bishop 
75*fc171428SEd Tanous // TODO Refactor these to not be globals
76*fc171428SEd Tanous // NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
77bfda2c43SBonnie Lo static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
782447c24dSMatt Simmering     busBlocklist;
79e45d8c71SBrad Bishop struct FindDevicesWithCallback;
80e45d8c71SBrad Bishop 
81e45d8c71SBrad Bishop static boost::container::flat_map<
82e45d8c71SBrad Bishop     std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
83e45d8c71SBrad Bishop     foundDevices;
84e45d8c71SBrad Bishop 
85e45d8c71SBrad Bishop static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
864d4df5b4SAKSHAY RAVEENDRAN K static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
87e45d8c71SBrad Bishop 
8834c3e016SEd Tanous boost::asio::io_context io;
89*fc171428SEd Tanous // NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
90e45d8c71SBrad Bishop 
91e45d8c71SBrad Bishop bool updateFRUProperty(
923013fb49SEd Tanous     const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
93e45d8c71SBrad Bishop     const std::string& propertyName,
94e45d8c71SBrad Bishop     boost::container::flat_map<
95e45d8c71SBrad Bishop         std::pair<size_t, size_t>,
96e45d8c71SBrad Bishop         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
97e45d8c71SBrad Bishop     size_t& unknownBusObjectCount, const bool& powerIsOn,
98e45d8c71SBrad Bishop     sdbusplus::asio::object_server& objServer,
99e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::connection>& systemBus);
100e45d8c71SBrad Bishop 
101e45d8c71SBrad Bishop // Given a bus/address, produce the path in sysfs for an eeprom.
getEepromPath(size_t bus,size_t address)102e45d8c71SBrad Bishop static std::string getEepromPath(size_t bus, size_t address)
103e45d8c71SBrad Bishop {
104e45d8c71SBrad Bishop     std::stringstream output;
105e45d8c71SBrad Bishop     output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
106e45d8c71SBrad Bishop            << std::setfill('0') << std::setw(4) << std::hex << address
107e45d8c71SBrad Bishop            << "/eeprom";
108e45d8c71SBrad Bishop     return output.str();
109e45d8c71SBrad Bishop }
110e45d8c71SBrad Bishop 
hasEepromFile(size_t bus,size_t address)111e45d8c71SBrad Bishop static bool hasEepromFile(size_t bus, size_t address)
112e45d8c71SBrad Bishop {
113e45d8c71SBrad Bishop     auto path = getEepromPath(bus, address);
114e45d8c71SBrad Bishop     try
115e45d8c71SBrad Bishop     {
116e45d8c71SBrad Bishop         return fs::exists(path);
117e45d8c71SBrad Bishop     }
118e45d8c71SBrad Bishop     catch (...)
119e45d8c71SBrad Bishop     {
120e45d8c71SBrad Bishop         return false;
121e45d8c71SBrad Bishop     }
122e45d8c71SBrad Bishop }
123e45d8c71SBrad Bishop 
readFromEeprom(int fd,off_t offset,size_t len,uint8_t * buf)124309c0b13SZev Weiss static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
125e45d8c71SBrad Bishop {
126e45d8c71SBrad Bishop     auto result = lseek(fd, offset, SEEK_SET);
127e45d8c71SBrad Bishop     if (result < 0)
128e45d8c71SBrad Bishop     {
129e45d8c71SBrad Bishop         std::cerr << "failed to seek\n";
130e45d8c71SBrad Bishop         return -1;
131e45d8c71SBrad Bishop     }
132e45d8c71SBrad Bishop 
133e45d8c71SBrad Bishop     return read(fd, buf, len);
134e45d8c71SBrad Bishop }
135e45d8c71SBrad Bishop 
busStrToInt(const std::string_view busName)1363013fb49SEd Tanous static int busStrToInt(const std::string_view busName)
137e45d8c71SBrad Bishop {
138e45d8c71SBrad Bishop     auto findBus = busName.rfind('-');
139e45d8c71SBrad Bishop     if (findBus == std::string::npos)
140e45d8c71SBrad Bishop     {
141e45d8c71SBrad Bishop         return -1;
142e45d8c71SBrad Bishop     }
1433013fb49SEd Tanous     std::string_view num = busName.substr(findBus + 1);
1443013fb49SEd Tanous     int val = 0;
1453013fb49SEd Tanous     std::from_chars(num.data(), num.data() + num.size(), val);
1463013fb49SEd Tanous     return val;
147e45d8c71SBrad Bishop }
148e45d8c71SBrad Bishop 
getRootBus(size_t bus)149e45d8c71SBrad Bishop static int getRootBus(size_t bus)
150e45d8c71SBrad Bishop {
151e45d8c71SBrad Bishop     auto ec = std::error_code();
152e45d8c71SBrad Bishop     auto path = std::filesystem::read_symlink(
153e45d8c71SBrad Bishop         std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
154e45d8c71SBrad Bishop                               std::to_string(bus) + "/mux_device"),
155e45d8c71SBrad Bishop         ec);
156e45d8c71SBrad Bishop     if (ec)
157e45d8c71SBrad Bishop     {
158e45d8c71SBrad Bishop         return -1;
159e45d8c71SBrad Bishop     }
160e45d8c71SBrad Bishop 
161e45d8c71SBrad Bishop     std::string filename = path.filename();
162e45d8c71SBrad Bishop     auto findBus = filename.find('-');
163e45d8c71SBrad Bishop     if (findBus == std::string::npos)
164e45d8c71SBrad Bishop     {
165e45d8c71SBrad Bishop         return -1;
166e45d8c71SBrad Bishop     }
167e45d8c71SBrad Bishop     return std::stoi(filename.substr(0, findBus));
168e45d8c71SBrad Bishop }
169e45d8c71SBrad Bishop 
isMuxBus(size_t bus)170e45d8c71SBrad Bishop static bool isMuxBus(size_t bus)
171e45d8c71SBrad Bishop {
1728af5d3c5SZhikui Ren     auto ec = std::error_code();
1738af5d3c5SZhikui Ren     auto isSymlink =
1748af5d3c5SZhikui Ren         is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
1758af5d3c5SZhikui Ren                                          std::to_string(bus) + "/mux_device"),
1768af5d3c5SZhikui Ren                    ec);
1778af5d3c5SZhikui Ren     return (!ec && isSymlink);
178e45d8c71SBrad Bishop }
179e45d8c71SBrad Bishop 
makeProbeInterface(size_t bus,size_t address,sdbusplus::asio::object_server & objServer)180e45d8c71SBrad Bishop static void makeProbeInterface(size_t bus, size_t address,
181e45d8c71SBrad Bishop                                sdbusplus::asio::object_server& objServer)
182e45d8c71SBrad Bishop {
183e45d8c71SBrad Bishop     if (isMuxBus(bus))
184e45d8c71SBrad Bishop     {
185e45d8c71SBrad Bishop         return; // the mux buses are random, no need to publish
186e45d8c71SBrad Bishop     }
187e45d8c71SBrad Bishop     auto [it, success] = foundDevices.emplace(
188e45d8c71SBrad Bishop         std::make_pair(bus, address),
189e45d8c71SBrad Bishop         objServer.add_interface(
190e45d8c71SBrad Bishop             "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
191e45d8c71SBrad Bishop                 std::to_string(address),
192e45d8c71SBrad Bishop             "xyz.openbmc_project.Inventory.Item.I2CDevice"));
193e45d8c71SBrad Bishop     if (!success)
194e45d8c71SBrad Bishop     {
195e45d8c71SBrad Bishop         return; // already added
196e45d8c71SBrad Bishop     }
197e45d8c71SBrad Bishop     it->second->register_property("Bus", bus);
198e45d8c71SBrad Bishop     it->second->register_property("Address", address);
199e45d8c71SBrad Bishop     it->second->initialize();
200e45d8c71SBrad Bishop }
201e45d8c71SBrad Bishop 
isDevice16Bit(int file)202309c0b13SZev Weiss static std::optional<bool> isDevice16Bit(int file)
203e45d8c71SBrad Bishop {
204e45d8c71SBrad Bishop     // Set the higher data word address bits to 0. It's safe on 8-bit addressing
205e45d8c71SBrad Bishop     // EEPROMs because it doesn't write any actual data.
206e45d8c71SBrad Bishop     int ret = i2c_smbus_write_byte(file, 0);
207e45d8c71SBrad Bishop     if (ret < 0)
208e45d8c71SBrad Bishop     {
209309c0b13SZev Weiss         return std::nullopt;
210e45d8c71SBrad Bishop     }
211e45d8c71SBrad Bishop 
212e45d8c71SBrad Bishop     /* Get first byte */
213e45d8c71SBrad Bishop     int byte1 = i2c_smbus_read_byte_data(file, 0);
214e45d8c71SBrad Bishop     if (byte1 < 0)
215e45d8c71SBrad Bishop     {
216309c0b13SZev Weiss         return std::nullopt;
217e45d8c71SBrad Bishop     }
218e45d8c71SBrad Bishop     /* Read 7 more bytes, it will read same first byte in case of
219e45d8c71SBrad Bishop      * 8 bit but it will read next byte in case of 16 bit
220e45d8c71SBrad Bishop      */
221e45d8c71SBrad Bishop     for (int i = 0; i < 7; i++)
222e45d8c71SBrad Bishop     {
223e45d8c71SBrad Bishop         int byte2 = i2c_smbus_read_byte_data(file, 0);
224e45d8c71SBrad Bishop         if (byte2 < 0)
225e45d8c71SBrad Bishop         {
226309c0b13SZev Weiss             return std::nullopt;
227e45d8c71SBrad Bishop         }
228e45d8c71SBrad Bishop         if (byte2 != byte1)
229e45d8c71SBrad Bishop         {
230309c0b13SZev Weiss             return true;
231e45d8c71SBrad Bishop         }
232e45d8c71SBrad Bishop     }
233309c0b13SZev Weiss     return false;
234e45d8c71SBrad Bishop }
235e45d8c71SBrad Bishop 
2362447c24dSMatt Simmering // Issue an I2C transaction to first write to_target_buf_len bytes,then read
2372447c24dSMatt Simmering // from_target_buf_len bytes.
i2cSmbusWriteThenRead(int file,uint16_t address,uint8_t * toTargetBuf,uint8_t toTargetBufLen,uint8_t * fromTargetBuf,uint8_t fromTargetBufLen)238e45d8c71SBrad Bishop static int i2cSmbusWriteThenRead(int file, uint16_t address,
2392447c24dSMatt Simmering                                  uint8_t* toTargetBuf, uint8_t toTargetBufLen,
2402447c24dSMatt Simmering                                  uint8_t* fromTargetBuf,
2412447c24dSMatt Simmering                                  uint8_t fromTargetBufLen)
242e45d8c71SBrad Bishop {
2432447c24dSMatt Simmering     if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
2442447c24dSMatt Simmering         fromTargetBuf == nullptr || fromTargetBufLen == 0)
245e45d8c71SBrad Bishop     {
246e45d8c71SBrad Bishop         return -1;
247e45d8c71SBrad Bishop     }
248e45d8c71SBrad Bishop 
2493013fb49SEd Tanous     constexpr size_t smbusWriteThenReadMsgCount = 2;
2503013fb49SEd Tanous     std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
2513013fb49SEd Tanous     struct i2c_rdwr_ioctl_data rdwr
2523013fb49SEd Tanous     {};
253e45d8c71SBrad Bishop 
254e45d8c71SBrad Bishop     msgs[0].addr = address;
255e45d8c71SBrad Bishop     msgs[0].flags = 0;
2562447c24dSMatt Simmering     msgs[0].len = toTargetBufLen;
2572447c24dSMatt Simmering     msgs[0].buf = toTargetBuf;
258e45d8c71SBrad Bishop     msgs[1].addr = address;
259e45d8c71SBrad Bishop     msgs[1].flags = I2C_M_RD;
2602447c24dSMatt Simmering     msgs[1].len = fromTargetBufLen;
2612447c24dSMatt Simmering     msgs[1].buf = fromTargetBuf;
262e45d8c71SBrad Bishop 
2633013fb49SEd Tanous     rdwr.msgs = msgs.data();
2643013fb49SEd Tanous     rdwr.nmsgs = msgs.size();
265e45d8c71SBrad Bishop 
266e45d8c71SBrad Bishop     int ret = ioctl(file, I2C_RDWR, &rdwr);
267e45d8c71SBrad Bishop 
268f6e4c1f5SJason M. Bills     return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
269e45d8c71SBrad Bishop }
270e45d8c71SBrad Bishop 
readData(bool is16bit,bool isBytewise,int file,uint16_t address,off_t offset,size_t len,uint8_t * buf)2712b3ed30cSMarvin Drees static int64_t readData(bool is16bit, bool isBytewise, int file,
2722b3ed30cSMarvin Drees                         uint16_t address, off_t offset, size_t len,
2732b3ed30cSMarvin Drees                         uint8_t* buf)
274e45d8c71SBrad Bishop {
275309c0b13SZev Weiss     if (!is16bit)
276e45d8c71SBrad Bishop     {
2772b3ed30cSMarvin Drees         if (!isBytewise)
2782b3ed30cSMarvin Drees         {
2792b3ed30cSMarvin Drees             return i2c_smbus_read_i2c_block_data(
2802b3ed30cSMarvin Drees                 file, static_cast<uint8_t>(offset), len, buf);
2812b3ed30cSMarvin Drees         }
2822b3ed30cSMarvin Drees 
2832b3ed30cSMarvin Drees         std::span<uint8_t> bufspan{buf, len};
2842b3ed30cSMarvin Drees         for (size_t i = 0; i < len; i++)
2852b3ed30cSMarvin Drees         {
2862b3ed30cSMarvin Drees             int byte = i2c_smbus_read_byte_data(
2872b3ed30cSMarvin Drees                 file, static_cast<uint8_t>(offset + i));
2882b3ed30cSMarvin Drees             if (byte < 0)
2892b3ed30cSMarvin Drees             {
2902b3ed30cSMarvin Drees                 return static_cast<int64_t>(byte);
2912b3ed30cSMarvin Drees             }
2922b3ed30cSMarvin Drees             bufspan[i] = static_cast<uint8_t>(byte);
2932b3ed30cSMarvin Drees         }
2942b3ed30cSMarvin Drees         return static_cast<int64_t>(len);
295e45d8c71SBrad Bishop     }
296e45d8c71SBrad Bishop 
297e45d8c71SBrad Bishop     offset = htobe16(offset);
2983013fb49SEd Tanous     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
2993013fb49SEd Tanous     uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
3003013fb49SEd Tanous     return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
301e45d8c71SBrad Bishop }
302e45d8c71SBrad Bishop 
303e45d8c71SBrad Bishop // TODO: This code is very similar to the non-eeprom version and can be merged
304e45d8c71SBrad Bishop // with some tweaks.
processEeprom(int bus,int address)305e45d8c71SBrad Bishop static std::vector<uint8_t> processEeprom(int bus, int address)
306e45d8c71SBrad Bishop {
307e45d8c71SBrad Bishop     auto path = getEepromPath(bus, address);
308e45d8c71SBrad Bishop 
309e45d8c71SBrad Bishop     int file = open(path.c_str(), O_RDONLY);
310e45d8c71SBrad Bishop     if (file < 0)
311e45d8c71SBrad Bishop     {
312e45d8c71SBrad Bishop         std::cerr << "Unable to open eeprom file: " << path << "\n";
313e45d8c71SBrad Bishop         return {};
314e45d8c71SBrad Bishop     }
315e45d8c71SBrad Bishop 
316e45d8c71SBrad Bishop     std::string errorMessage = "eeprom at " + std::to_string(bus) +
317e45d8c71SBrad Bishop                                " address " + std::to_string(address);
318309c0b13SZev Weiss     auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
319309c0b13SZev Weiss         return readFromEeprom(file, offset, length, outbuf);
320309c0b13SZev Weiss     };
321309c0b13SZev Weiss     FRUReader reader(std::move(readFunc));
3222b3ed30cSMarvin Drees     std::pair<std::vector<uint8_t>, bool> pair = readFRUContents(reader,
3232b3ed30cSMarvin Drees                                                                  errorMessage);
324e45d8c71SBrad Bishop 
325e45d8c71SBrad Bishop     close(file);
3262b3ed30cSMarvin Drees     return pair.first;
327e45d8c71SBrad Bishop }
328e45d8c71SBrad Bishop 
findI2CEeproms(int i2cBus,const std::shared_ptr<DeviceMap> & devices)329bfda2c43SBonnie Lo std::set<size_t> findI2CEeproms(int i2cBus,
330e45d8c71SBrad Bishop                                 const std::shared_ptr<DeviceMap>& devices)
331e45d8c71SBrad Bishop {
332bfda2c43SBonnie Lo     std::set<size_t> foundList;
333e45d8c71SBrad Bishop 
334e45d8c71SBrad Bishop     std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
335e45d8c71SBrad Bishop 
336e45d8c71SBrad Bishop     // For each file listed under the i2c device
337e45d8c71SBrad Bishop     // NOTE: This should be faster than just checking for each possible address
338e45d8c71SBrad Bishop     // path.
3398af5d3c5SZhikui Ren     auto ec = std::error_code();
3408af5d3c5SZhikui Ren     for (const auto& p : fs::directory_iterator(path, ec))
341e45d8c71SBrad Bishop     {
3428af5d3c5SZhikui Ren         if (ec)
3438af5d3c5SZhikui Ren         {
3448af5d3c5SZhikui Ren             std::cerr << "directory_iterator err " << ec.message() << "\n";
3458af5d3c5SZhikui Ren             break;
3468af5d3c5SZhikui Ren         }
347e45d8c71SBrad Bishop         const std::string node = p.path().string();
348e45d8c71SBrad Bishop         std::smatch m;
349df190619SPatrick Williams         bool found = std::regex_match(node, m,
350df190619SPatrick Williams                                       std::regex(".+\\d+-([0-9abcdef]+$)"));
351e45d8c71SBrad Bishop 
352e45d8c71SBrad Bishop         if (!found)
353e45d8c71SBrad Bishop         {
354e45d8c71SBrad Bishop             continue;
355e45d8c71SBrad Bishop         }
356e45d8c71SBrad Bishop         if (m.size() != 2)
357e45d8c71SBrad Bishop         {
358e45d8c71SBrad Bishop             std::cerr << "regex didn't capture\n";
359e45d8c71SBrad Bishop             continue;
360e45d8c71SBrad Bishop         }
361e45d8c71SBrad Bishop 
362e45d8c71SBrad Bishop         std::ssub_match subMatch = m[1];
363e45d8c71SBrad Bishop         std::string addressString = subMatch.str();
364bfda2c43SBonnie Lo         std::string_view addressStringView(addressString);
365e45d8c71SBrad Bishop 
366bfda2c43SBonnie Lo         size_t address = 0;
367bfda2c43SBonnie Lo         std::from_chars(addressStringView.begin(), addressStringView.end(),
368bfda2c43SBonnie Lo                         address, 16);
369e45d8c71SBrad Bishop 
370e45d8c71SBrad Bishop         const std::string eeprom = node + "/eeprom";
371e45d8c71SBrad Bishop 
372e45d8c71SBrad Bishop         try
373e45d8c71SBrad Bishop         {
374e45d8c71SBrad Bishop             if (!fs::exists(eeprom))
375e45d8c71SBrad Bishop             {
376e45d8c71SBrad Bishop                 continue;
377e45d8c71SBrad Bishop             }
378e45d8c71SBrad Bishop         }
379e45d8c71SBrad Bishop         catch (...)
380e45d8c71SBrad Bishop         {
381e45d8c71SBrad Bishop             continue;
382e45d8c71SBrad Bishop         }
383e45d8c71SBrad Bishop 
384e45d8c71SBrad Bishop         // There is an eeprom file at this address, it may have invalid
385e45d8c71SBrad Bishop         // contents, but we found it.
386e45d8c71SBrad Bishop         foundList.insert(address);
387e45d8c71SBrad Bishop 
388e45d8c71SBrad Bishop         std::vector<uint8_t> device = processEeprom(i2cBus, address);
389e45d8c71SBrad Bishop         if (!device.empty())
390e45d8c71SBrad Bishop         {
391e45d8c71SBrad Bishop             devices->emplace(address, device);
392e45d8c71SBrad Bishop         }
393e45d8c71SBrad Bishop     }
394e45d8c71SBrad Bishop 
395e45d8c71SBrad Bishop     return foundList;
396e45d8c71SBrad Bishop }
397e45d8c71SBrad Bishop 
getBusFRUs(int file,int first,int last,int bus,std::shared_ptr<DeviceMap> devices,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)398e45d8c71SBrad Bishop int getBusFRUs(int file, int first, int last, int bus,
399e45d8c71SBrad Bishop                std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
400e45d8c71SBrad Bishop                sdbusplus::asio::object_server& objServer)
401e45d8c71SBrad Bishop {
402e45d8c71SBrad Bishop     std::future<int> future = std::async(std::launch::async, [&]() {
403e45d8c71SBrad Bishop         // NOTE: When reading the devices raw on the bus, it can interfere with
404e45d8c71SBrad Bishop         // the driver's ability to operate, therefore read eeproms first before
405e45d8c71SBrad Bishop         // scanning for devices without drivers. Several experiments were run
406e45d8c71SBrad Bishop         // and it was determined that if there were any devices on the bus
407e45d8c71SBrad Bishop         // before the eeprom was hit and read, the eeprom driver wouldn't open
408e45d8c71SBrad Bishop         // while the bus device was open. An experiment was not performed to see
409e45d8c71SBrad Bishop         // if this issue was resolved if the i2c bus device was closed, but
410e45d8c71SBrad Bishop         // hexdumps of the eeprom later were successful.
411e45d8c71SBrad Bishop 
412e45d8c71SBrad Bishop         // Scan for i2c eeproms loaded on this bus.
413bfda2c43SBonnie Lo         std::set<size_t> skipList = findI2CEeproms(bus, devices);
414e45d8c71SBrad Bishop         std::set<size_t>& failedItems = failedAddresses[bus];
4154d4df5b4SAKSHAY RAVEENDRAN K         std::set<size_t>& foundItems = fruAddresses[bus];
4164d4df5b4SAKSHAY RAVEENDRAN K         foundItems.clear();
417e45d8c71SBrad Bishop 
4182447c24dSMatt Simmering         auto busFind = busBlocklist.find(bus);
4192447c24dSMatt Simmering         if (busFind != busBlocklist.end())
420bfda2c43SBonnie Lo         {
421bfda2c43SBonnie Lo             if (busFind->second != std::nullopt)
422bfda2c43SBonnie Lo             {
423bfda2c43SBonnie Lo                 for (const auto& address : *(busFind->second))
424bfda2c43SBonnie Lo                 {
425bfda2c43SBonnie Lo                     skipList.insert(address);
426bfda2c43SBonnie Lo                 }
427bfda2c43SBonnie Lo             }
428bfda2c43SBonnie Lo         }
429bfda2c43SBonnie Lo 
430e45d8c71SBrad Bishop         std::set<size_t>* rootFailures = nullptr;
431e45d8c71SBrad Bishop         int rootBus = getRootBus(bus);
432e45d8c71SBrad Bishop 
433e45d8c71SBrad Bishop         if (rootBus >= 0)
434e45d8c71SBrad Bishop         {
4352447c24dSMatt Simmering             auto rootBusFind = busBlocklist.find(rootBus);
4362447c24dSMatt Simmering             if (rootBusFind != busBlocklist.end())
437bfda2c43SBonnie Lo             {
438bfda2c43SBonnie Lo                 if (rootBusFind->second != std::nullopt)
439bfda2c43SBonnie Lo                 {
440bfda2c43SBonnie Lo                     for (const auto& rootAddress : *(rootBusFind->second))
441bfda2c43SBonnie Lo                     {
442bfda2c43SBonnie Lo                         skipList.insert(rootAddress);
443bfda2c43SBonnie Lo                     }
444bfda2c43SBonnie Lo                 }
445bfda2c43SBonnie Lo             }
446e45d8c71SBrad Bishop             rootFailures = &(failedAddresses[rootBus]);
4474d4df5b4SAKSHAY RAVEENDRAN K             foundItems = fruAddresses[rootBus];
448e45d8c71SBrad Bishop         }
449e45d8c71SBrad Bishop 
4502447c24dSMatt Simmering         constexpr int startSkipTargetAddr = 0;
4512447c24dSMatt Simmering         constexpr int endSkipTargetAddr = 12;
452e45d8c71SBrad Bishop 
453e45d8c71SBrad Bishop         for (int ii = first; ii <= last; ii++)
454e45d8c71SBrad Bishop         {
4554d4df5b4SAKSHAY RAVEENDRAN K             if (foundItems.find(ii) != foundItems.end())
4564d4df5b4SAKSHAY RAVEENDRAN K             {
4574d4df5b4SAKSHAY RAVEENDRAN K                 continue;
4584d4df5b4SAKSHAY RAVEENDRAN K             }
459e45d8c71SBrad Bishop             if (skipList.find(ii) != skipList.end())
460e45d8c71SBrad Bishop             {
461e45d8c71SBrad Bishop                 continue;
462e45d8c71SBrad Bishop             }
463e45d8c71SBrad Bishop             // skipping since no device is present in this range
4642447c24dSMatt Simmering             if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
465e45d8c71SBrad Bishop             {
466e45d8c71SBrad Bishop                 continue;
467e45d8c71SBrad Bishop             }
4682447c24dSMatt Simmering             // Set target address
469e45d8c71SBrad Bishop             if (ioctl(file, I2C_SLAVE, ii) < 0)
470e45d8c71SBrad Bishop             {
471e45d8c71SBrad Bishop                 std::cerr << "device at bus " << bus << " address " << ii
472e45d8c71SBrad Bishop                           << " busy\n";
473e45d8c71SBrad Bishop                 continue;
474e45d8c71SBrad Bishop             }
475e45d8c71SBrad Bishop             // probe
476e45d8c71SBrad Bishop             if (i2c_smbus_read_byte(file) < 0)
477e45d8c71SBrad Bishop             {
478e45d8c71SBrad Bishop                 continue;
479e45d8c71SBrad Bishop             }
480e45d8c71SBrad Bishop 
481e45d8c71SBrad Bishop             if (debug)
482e45d8c71SBrad Bishop             {
483e45d8c71SBrad Bishop                 std::cout << "something at bus " << bus << " addr " << ii
484e45d8c71SBrad Bishop                           << "\n";
485e45d8c71SBrad Bishop             }
486e45d8c71SBrad Bishop 
487e45d8c71SBrad Bishop             makeProbeInterface(bus, ii, objServer);
488e45d8c71SBrad Bishop 
489e45d8c71SBrad Bishop             if (failedItems.find(ii) != failedItems.end())
490e45d8c71SBrad Bishop             {
491e45d8c71SBrad Bishop                 // if we failed to read it once, unlikely we can read it later
492e45d8c71SBrad Bishop                 continue;
493e45d8c71SBrad Bishop             }
494e45d8c71SBrad Bishop 
495e45d8c71SBrad Bishop             if (rootFailures != nullptr)
496e45d8c71SBrad Bishop             {
497e45d8c71SBrad Bishop                 if (rootFailures->find(ii) != rootFailures->end())
498e45d8c71SBrad Bishop                 {
499e45d8c71SBrad Bishop                     continue;
500e45d8c71SBrad Bishop                 }
501e45d8c71SBrad Bishop             }
502e45d8c71SBrad Bishop 
503e45d8c71SBrad Bishop             /* Check for Device type if it is 8 bit or 16 bit */
504309c0b13SZev Weiss             std::optional<bool> is16Bit = isDevice16Bit(file);
505309c0b13SZev Weiss             if (!is16Bit.has_value())
506e45d8c71SBrad Bishop             {
507e45d8c71SBrad Bishop                 std::cerr << "failed to read bus " << bus << " address " << ii
508e45d8c71SBrad Bishop                           << "\n";
509e45d8c71SBrad Bishop                 if (powerIsOn)
510e45d8c71SBrad Bishop                 {
511e45d8c71SBrad Bishop                     failedItems.insert(ii);
512e45d8c71SBrad Bishop                 }
513e45d8c71SBrad Bishop                 continue;
514e45d8c71SBrad Bishop             }
515309c0b13SZev Weiss             bool is16BitBool{*is16Bit};
516e45d8c71SBrad Bishop 
517309c0b13SZev Weiss             auto readFunc = [is16BitBool, file, ii](off_t offset, size_t length,
518309c0b13SZev Weiss                                                     uint8_t* outbuf) {
5192b3ed30cSMarvin Drees                 return readData(is16BitBool, false, file, ii, offset, length,
520309c0b13SZev Weiss                                 outbuf);
521309c0b13SZev Weiss             };
522309c0b13SZev Weiss             FRUReader reader(std::move(readFunc));
523df190619SPatrick Williams             std::string errorMessage = "bus " + std::to_string(bus) +
524df190619SPatrick Williams                                        " address " + std::to_string(ii);
5252b3ed30cSMarvin Drees             std::pair<std::vector<uint8_t>, bool> pair =
5262b3ed30cSMarvin Drees                 readFRUContents(reader, errorMessage);
5272b3ed30cSMarvin Drees             const bool foundHeader = pair.second;
5282b3ed30cSMarvin Drees 
5292b3ed30cSMarvin Drees             if (!foundHeader && !is16BitBool)
5302b3ed30cSMarvin Drees             {
5312b3ed30cSMarvin Drees                 // certain FRU eeproms require bytewise reading.
5322b3ed30cSMarvin Drees                 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
5332b3ed30cSMarvin Drees 
5342b3ed30cSMarvin Drees                 auto readFunc = [is16BitBool, file, ii](off_t offset,
5352b3ed30cSMarvin Drees                                                         size_t length,
5362b3ed30cSMarvin Drees                                                         uint8_t* outbuf) {
5372b3ed30cSMarvin Drees                     return readData(is16BitBool, true, file, ii, offset, length,
5382b3ed30cSMarvin Drees                                     outbuf);
5392b3ed30cSMarvin Drees                 };
5402b3ed30cSMarvin Drees                 FRUReader readerBytewise(std::move(readFunc));
5412b3ed30cSMarvin Drees                 pair = readFRUContents(readerBytewise, errorMessage);
5422b3ed30cSMarvin Drees             }
5432b3ed30cSMarvin Drees 
5442b3ed30cSMarvin Drees             if (pair.first.empty())
545e45d8c71SBrad Bishop             {
546e45d8c71SBrad Bishop                 continue;
547e45d8c71SBrad Bishop             }
548e45d8c71SBrad Bishop 
5492b3ed30cSMarvin Drees             devices->emplace(ii, pair.first);
5504d4df5b4SAKSHAY RAVEENDRAN K             fruAddresses[bus].insert(ii);
551e45d8c71SBrad Bishop         }
552e45d8c71SBrad Bishop         return 1;
553e45d8c71SBrad Bishop     });
554e45d8c71SBrad Bishop     std::future_status status =
555e45d8c71SBrad Bishop         future.wait_for(std::chrono::seconds(busTimeoutSeconds));
556e45d8c71SBrad Bishop     if (status == std::future_status::timeout)
557e45d8c71SBrad Bishop     {
558e45d8c71SBrad Bishop         std::cerr << "Error reading bus " << bus << "\n";
559e45d8c71SBrad Bishop         if (powerIsOn)
560e45d8c71SBrad Bishop         {
5612447c24dSMatt Simmering             busBlocklist[bus] = std::nullopt;
562e45d8c71SBrad Bishop         }
563e45d8c71SBrad Bishop         close(file);
564e45d8c71SBrad Bishop         return -1;
565e45d8c71SBrad Bishop     }
566e45d8c71SBrad Bishop 
567e45d8c71SBrad Bishop     close(file);
568e45d8c71SBrad Bishop     return future.get();
569e45d8c71SBrad Bishop }
570e45d8c71SBrad Bishop 
loadBlocklist(const char * path)5712447c24dSMatt Simmering void loadBlocklist(const char* path)
572e45d8c71SBrad Bishop {
5732447c24dSMatt Simmering     std::ifstream blocklistStream(path);
5742447c24dSMatt Simmering     if (!blocklistStream.good())
575e45d8c71SBrad Bishop     {
576e45d8c71SBrad Bishop         // File is optional.
5772447c24dSMatt Simmering         std::cerr << "Cannot open blocklist file.\n\n";
578e45d8c71SBrad Bishop         return;
579e45d8c71SBrad Bishop     }
580e45d8c71SBrad Bishop 
5812447c24dSMatt Simmering     nlohmann::json data = nlohmann::json::parse(blocklistStream, nullptr,
582df190619SPatrick Williams                                                 false);
583e45d8c71SBrad Bishop     if (data.is_discarded())
584e45d8c71SBrad Bishop     {
5852447c24dSMatt Simmering         std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
586e45d8c71SBrad Bishop                      "exiting\n";
587e45d8c71SBrad Bishop         std::exit(EXIT_FAILURE);
588e45d8c71SBrad Bishop     }
589e45d8c71SBrad Bishop 
590e45d8c71SBrad Bishop     // It's expected to have at least one field, "buses" that is an array of the
591e45d8c71SBrad Bishop     // buses by integer. Allow for future options to exclude further aspects,
592e45d8c71SBrad Bishop     // such as specific addresses or ranges.
593e45d8c71SBrad Bishop     if (data.type() != nlohmann::json::value_t::object)
594e45d8c71SBrad Bishop     {
5952447c24dSMatt Simmering         std::cerr << "Illegal blocklist, expected to read dictionary\n";
596e45d8c71SBrad Bishop         std::exit(EXIT_FAILURE);
597e45d8c71SBrad Bishop     }
598e45d8c71SBrad Bishop 
599e45d8c71SBrad Bishop     // If buses field is missing, that's fine.
600e45d8c71SBrad Bishop     if (data.count("buses") == 1)
601e45d8c71SBrad Bishop     {
602e45d8c71SBrad Bishop         // Parse the buses array after a little validation.
603e45d8c71SBrad Bishop         auto buses = data.at("buses");
604e45d8c71SBrad Bishop         if (buses.type() != nlohmann::json::value_t::array)
605e45d8c71SBrad Bishop         {
606e45d8c71SBrad Bishop             // Buses field present but invalid, therefore this is an error.
6072447c24dSMatt Simmering             std::cerr << "Invalid contents for blocklist buses field\n";
608e45d8c71SBrad Bishop             std::exit(EXIT_FAILURE);
609e45d8c71SBrad Bishop         }
610e45d8c71SBrad Bishop 
611e45d8c71SBrad Bishop         // Catch exception here for type mis-match.
612e45d8c71SBrad Bishop         try
613e45d8c71SBrad Bishop         {
614bfda2c43SBonnie Lo             for (const auto& busIterator : buses)
615e45d8c71SBrad Bishop             {
616bfda2c43SBonnie Lo                 // If bus and addresses field are missing, that's fine.
617bfda2c43SBonnie Lo                 if (busIterator.contains("bus") &&
618bfda2c43SBonnie Lo                     busIterator.contains("addresses"))
619bfda2c43SBonnie Lo                 {
620bfda2c43SBonnie Lo                     auto busData = busIterator.at("bus");
621bfda2c43SBonnie Lo                     auto bus = busData.get<size_t>();
622bfda2c43SBonnie Lo 
623bfda2c43SBonnie Lo                     auto addressData = busIterator.at("addresses");
624bfda2c43SBonnie Lo                     auto addresses =
625bfda2c43SBonnie Lo                         addressData.get<std::set<std::string_view>>();
626bfda2c43SBonnie Lo 
627*fc171428SEd Tanous                     auto& block = busBlocklist[bus].emplace();
628bfda2c43SBonnie Lo                     for (const auto& address : addresses)
629bfda2c43SBonnie Lo                     {
630bfda2c43SBonnie Lo                         size_t addressInt = 0;
631bfda2c43SBonnie Lo                         std::from_chars(address.begin() + 2, address.end(),
632bfda2c43SBonnie Lo                                         addressInt, 16);
633*fc171428SEd Tanous                         block.insert(addressInt);
634bfda2c43SBonnie Lo                     }
635bfda2c43SBonnie Lo                 }
636bfda2c43SBonnie Lo                 else
637bfda2c43SBonnie Lo                 {
6382447c24dSMatt Simmering                     busBlocklist[busIterator.get<size_t>()] = std::nullopt;
639bfda2c43SBonnie Lo                 }
640e45d8c71SBrad Bishop             }
641e45d8c71SBrad Bishop         }
642e45d8c71SBrad Bishop         catch (const nlohmann::detail::type_error& e)
643e45d8c71SBrad Bishop         {
644e45d8c71SBrad Bishop             // Type mis-match is a critical error.
645e45d8c71SBrad Bishop             std::cerr << "Invalid bus type: " << e.what() << "\n";
646e45d8c71SBrad Bishop             std::exit(EXIT_FAILURE);
647e45d8c71SBrad Bishop         }
648e45d8c71SBrad Bishop     }
649e45d8c71SBrad Bishop }
650e45d8c71SBrad Bishop 
findI2CDevices(const std::vector<fs::path> & i2cBuses,BusMap & busmap,const bool & powerIsOn,sdbusplus::asio::object_server & objServer)651e45d8c71SBrad Bishop static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
652e45d8c71SBrad Bishop                            BusMap& busmap, const bool& powerIsOn,
653e45d8c71SBrad Bishop                            sdbusplus::asio::object_server& objServer)
654e45d8c71SBrad Bishop {
6553013fb49SEd Tanous     for (const auto& i2cBus : i2cBuses)
656e45d8c71SBrad Bishop     {
6573013fb49SEd Tanous         int bus = busStrToInt(i2cBus.string());
658e45d8c71SBrad Bishop 
659e45d8c71SBrad Bishop         if (bus < 0)
660e45d8c71SBrad Bishop         {
661e45d8c71SBrad Bishop             std::cerr << "Cannot translate " << i2cBus << " to int\n";
662e45d8c71SBrad Bishop             continue;
663e45d8c71SBrad Bishop         }
6642447c24dSMatt Simmering         auto busFind = busBlocklist.find(bus);
6652447c24dSMatt Simmering         if (busFind != busBlocklist.end())
666e45d8c71SBrad Bishop         {
667bfda2c43SBonnie Lo             if (busFind->second == std::nullopt)
668bfda2c43SBonnie Lo             {
669bfda2c43SBonnie Lo                 continue; // Skip blocked busses.
670e45d8c71SBrad Bishop             }
671bfda2c43SBonnie Lo         }
672e45d8c71SBrad Bishop         int rootBus = getRootBus(bus);
6732447c24dSMatt Simmering         auto rootBusFind = busBlocklist.find(rootBus);
6742447c24dSMatt Simmering         if (rootBusFind != busBlocklist.end())
675bfda2c43SBonnie Lo         {
676bfda2c43SBonnie Lo             if (rootBusFind->second == std::nullopt)
677e45d8c71SBrad Bishop             {
678e45d8c71SBrad Bishop                 continue;
679e45d8c71SBrad Bishop             }
680bfda2c43SBonnie Lo         }
681e45d8c71SBrad Bishop 
682e45d8c71SBrad Bishop         auto file = open(i2cBus.c_str(), O_RDWR);
683e45d8c71SBrad Bishop         if (file < 0)
684e45d8c71SBrad Bishop         {
685e45d8c71SBrad Bishop             std::cerr << "unable to open i2c device " << i2cBus.string()
686e45d8c71SBrad Bishop                       << "\n";
687e45d8c71SBrad Bishop             continue;
688e45d8c71SBrad Bishop         }
689e45d8c71SBrad Bishop         unsigned long funcs = 0;
690e45d8c71SBrad Bishop 
691e45d8c71SBrad Bishop         if (ioctl(file, I2C_FUNCS, &funcs) < 0)
692e45d8c71SBrad Bishop         {
693e45d8c71SBrad Bishop             std::cerr
694e45d8c71SBrad Bishop                 << "Error: Could not get the adapter functionality matrix bus "
695e45d8c71SBrad Bishop                 << bus << "\n";
696e45d8c71SBrad Bishop             close(file);
697e45d8c71SBrad Bishop             continue;
698e45d8c71SBrad Bishop         }
6993013fb49SEd Tanous         if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
7003013fb49SEd Tanous             ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
701e45d8c71SBrad Bishop         {
702e45d8c71SBrad Bishop             std::cerr << "Error: Can't use SMBus Receive Byte command bus "
703e45d8c71SBrad Bishop                       << bus << "\n";
704e45d8c71SBrad Bishop             continue;
705e45d8c71SBrad Bishop         }
706e45d8c71SBrad Bishop         auto& device = busmap[bus];
707e45d8c71SBrad Bishop         device = std::make_shared<DeviceMap>();
708e45d8c71SBrad Bishop 
709e45d8c71SBrad Bishop         //  i2cdetect by default uses the range 0x03 to 0x77, as
710e45d8c71SBrad Bishop         //  this is  what we have tested with, use this range. Could be
711e45d8c71SBrad Bishop         //  changed in future.
712e45d8c71SBrad Bishop         if (debug)
713e45d8c71SBrad Bishop         {
714e45d8c71SBrad Bishop             std::cerr << "Scanning bus " << bus << "\n";
715e45d8c71SBrad Bishop         }
716e45d8c71SBrad Bishop 
717e45d8c71SBrad Bishop         // fd is closed in this function in case the bus locks up
718e45d8c71SBrad Bishop         getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
719e45d8c71SBrad Bishop 
720e45d8c71SBrad Bishop         if (debug)
721e45d8c71SBrad Bishop         {
722e45d8c71SBrad Bishop             std::cerr << "Done scanning bus " << bus << "\n";
723e45d8c71SBrad Bishop         }
724e45d8c71SBrad Bishop     }
725e45d8c71SBrad Bishop }
726e45d8c71SBrad Bishop 
727e45d8c71SBrad Bishop // this class allows an async response after all i2c devices are discovered
728e45d8c71SBrad Bishop struct FindDevicesWithCallback :
729e45d8c71SBrad Bishop     std::enable_shared_from_this<FindDevicesWithCallback>
730e45d8c71SBrad Bishop {
FindDevicesWithCallbackFindDevicesWithCallback731e45d8c71SBrad Bishop     FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
732e45d8c71SBrad Bishop                             BusMap& busmap, const bool& powerIsOn,
733e45d8c71SBrad Bishop                             sdbusplus::asio::object_server& objServer,
734a3ca14a6SDelphine CC Chiu                             std::function<void()>&& callback) :
735e45d8c71SBrad Bishop         _i2cBuses(i2cBuses),
736e45d8c71SBrad Bishop         _busMap(busmap), _powerIsOn(powerIsOn), _objServer(objServer),
737e45d8c71SBrad Bishop         _callback(std::move(callback))
738e45d8c71SBrad Bishop     {}
~FindDevicesWithCallbackFindDevicesWithCallback739e45d8c71SBrad Bishop     ~FindDevicesWithCallback()
740e45d8c71SBrad Bishop     {
741e45d8c71SBrad Bishop         _callback();
742e45d8c71SBrad Bishop     }
runFindDevicesWithCallback743e45d8c71SBrad Bishop     void run()
744e45d8c71SBrad Bishop     {
745e45d8c71SBrad Bishop         findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
746e45d8c71SBrad Bishop     }
747e45d8c71SBrad Bishop 
748e45d8c71SBrad Bishop     const std::vector<fs::path>& _i2cBuses;
749e45d8c71SBrad Bishop     BusMap& _busMap;
750e45d8c71SBrad Bishop     const bool& _powerIsOn;
751e45d8c71SBrad Bishop     sdbusplus::asio::object_server& _objServer;
752a3ca14a6SDelphine CC Chiu     std::function<void()> _callback;
753e45d8c71SBrad Bishop };
754e45d8c71SBrad Bishop 
addFruObjectToDbus(std::vector<uint8_t> & device,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,uint32_t bus,uint32_t address,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer,std::shared_ptr<sdbusplus::asio::connection> & systemBus)755e45d8c71SBrad Bishop void addFruObjectToDbus(
756e45d8c71SBrad Bishop     std::vector<uint8_t>& device,
757e45d8c71SBrad Bishop     boost::container::flat_map<
758e45d8c71SBrad Bishop         std::pair<size_t, size_t>,
759e45d8c71SBrad Bishop         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
760e45d8c71SBrad Bishop     uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
761e45d8c71SBrad Bishop     const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
762e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
763e45d8c71SBrad Bishop {
764e45d8c71SBrad Bishop     boost::container::flat_map<std::string, std::string> formattedFRU;
7659f2162afSKumar Thangavel 
7669f2162afSKumar Thangavel     std::optional<std::string> optionalProductName = getProductName(
7679f2162afSKumar Thangavel         device, formattedFRU, bus, address, unknownBusObjectCount);
7689f2162afSKumar Thangavel     if (!optionalProductName)
769e45d8c71SBrad Bishop     {
7709f2162afSKumar Thangavel         std::cerr << "getProductName failed. product name is empty.\n";
771e45d8c71SBrad Bishop         return;
772e45d8c71SBrad Bishop     }
773e45d8c71SBrad Bishop 
774df190619SPatrick Williams     std::string productName = "/xyz/openbmc_project/FruDevice/" +
775df190619SPatrick Williams                               optionalProductName.value();
776e45d8c71SBrad Bishop 
777d79d0251SKumar Thangavel     std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
778d79d0251SKumar Thangavel     if (index.has_value())
779e45d8c71SBrad Bishop     {
780e45d8c71SBrad Bishop         productName += "_";
781d79d0251SKumar Thangavel         productName += std::to_string(++(*index));
782e45d8c71SBrad Bishop     }
783d79d0251SKumar Thangavel 
784e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
785e45d8c71SBrad Bishop         objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
786e45d8c71SBrad Bishop     dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
787e45d8c71SBrad Bishop 
788e45d8c71SBrad Bishop     for (auto& property : formattedFRU)
789e45d8c71SBrad Bishop     {
790e45d8c71SBrad Bishop         std::regex_replace(property.second.begin(), property.second.begin(),
791e45d8c71SBrad Bishop                            property.second.end(), nonAsciiRegex, "_");
792e45d8c71SBrad Bishop         if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
793e45d8c71SBrad Bishop         {
794e45d8c71SBrad Bishop             continue;
795e45d8c71SBrad Bishop         }
796df190619SPatrick Williams         std::string key = std::regex_replace(property.first, nonAsciiRegex,
797df190619SPatrick Williams                                              "_");
798e45d8c71SBrad Bishop 
799e45d8c71SBrad Bishop         if (property.first == "PRODUCT_ASSET_TAG")
800e45d8c71SBrad Bishop         {
801e45d8c71SBrad Bishop             std::string propertyName = property.first;
802e45d8c71SBrad Bishop             iface->register_property(
803e45d8c71SBrad Bishop                 key, property.second + '\0',
804e45d8c71SBrad Bishop                 [bus, address, propertyName, &dbusInterfaceMap,
805e45d8c71SBrad Bishop                  &unknownBusObjectCount, &powerIsOn, &objServer,
806e45d8c71SBrad Bishop                  &systemBus](const std::string& req, std::string& resp) {
807e45d8c71SBrad Bishop                 if (strcmp(req.c_str(), resp.c_str()) != 0)
808e45d8c71SBrad Bishop                 {
809e45d8c71SBrad Bishop                     // call the method which will update
810e45d8c71SBrad Bishop                     if (updateFRUProperty(req, bus, address, propertyName,
811e45d8c71SBrad Bishop                                           dbusInterfaceMap,
812e45d8c71SBrad Bishop                                           unknownBusObjectCount, powerIsOn,
813e45d8c71SBrad Bishop                                           objServer, systemBus))
814e45d8c71SBrad Bishop                     {
815e45d8c71SBrad Bishop                         resp = req;
816e45d8c71SBrad Bishop                     }
817e45d8c71SBrad Bishop                     else
818e45d8c71SBrad Bishop                     {
819e45d8c71SBrad Bishop                         throw std::invalid_argument(
820e45d8c71SBrad Bishop                             "FRU property update failed.");
821e45d8c71SBrad Bishop                     }
822e45d8c71SBrad Bishop                 }
823e45d8c71SBrad Bishop                 return 1;
824e45d8c71SBrad Bishop             });
825e45d8c71SBrad Bishop         }
826e45d8c71SBrad Bishop         else if (!iface->register_property(key, property.second + '\0'))
827e45d8c71SBrad Bishop         {
828e45d8c71SBrad Bishop             std::cerr << "illegal key: " << key << "\n";
829e45d8c71SBrad Bishop         }
830e45d8c71SBrad Bishop         if (debug)
831e45d8c71SBrad Bishop         {
832e45d8c71SBrad Bishop             std::cout << property.first << ": " << property.second << "\n";
833e45d8c71SBrad Bishop         }
834e45d8c71SBrad Bishop     }
835e45d8c71SBrad Bishop 
836e45d8c71SBrad Bishop     // baseboard will be 0, 0
837e45d8c71SBrad Bishop     iface->register_property("BUS", bus);
838e45d8c71SBrad Bishop     iface->register_property("ADDRESS", address);
839e45d8c71SBrad Bishop 
840e45d8c71SBrad Bishop     iface->initialize();
841e45d8c71SBrad Bishop }
842e45d8c71SBrad Bishop 
readBaseboardFRU(std::vector<uint8_t> & baseboardFRU)843e45d8c71SBrad Bishop static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
844e45d8c71SBrad Bishop {
845e45d8c71SBrad Bishop     // try to read baseboard fru from file
846e45d8c71SBrad Bishop     std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
847e45d8c71SBrad Bishop     if (baseboardFRUFile.good())
848e45d8c71SBrad Bishop     {
849e45d8c71SBrad Bishop         baseboardFRUFile.seekg(0, std::ios_base::end);
850e45d8c71SBrad Bishop         size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
851e45d8c71SBrad Bishop         baseboardFRU.resize(fileSize);
852e45d8c71SBrad Bishop         baseboardFRUFile.seekg(0, std::ios_base::beg);
8533013fb49SEd Tanous         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
8543013fb49SEd Tanous         char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
8553013fb49SEd Tanous         baseboardFRUFile.read(charOffset, fileSize);
856e45d8c71SBrad Bishop     }
857e45d8c71SBrad Bishop     else
858e45d8c71SBrad Bishop     {
859e45d8c71SBrad Bishop         return false;
860e45d8c71SBrad Bishop     }
861e45d8c71SBrad Bishop     return true;
862e45d8c71SBrad Bishop }
863e45d8c71SBrad Bishop 
writeFRU(uint8_t bus,uint8_t address,const std::vector<uint8_t> & fru)864e45d8c71SBrad Bishop bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
865e45d8c71SBrad Bishop {
866e45d8c71SBrad Bishop     boost::container::flat_map<std::string, std::string> tmp;
867e45d8c71SBrad Bishop     if (fru.size() > maxFruSize)
868e45d8c71SBrad Bishop     {
869e45d8c71SBrad Bishop         std::cerr << "Invalid fru.size() during writeFRU\n";
870e45d8c71SBrad Bishop         return false;
871e45d8c71SBrad Bishop     }
872e45d8c71SBrad Bishop     // verify legal fru by running it through fru parsing logic
873e45d8c71SBrad Bishop     if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
874e45d8c71SBrad Bishop     {
875e45d8c71SBrad Bishop         std::cerr << "Invalid fru format during writeFRU\n";
876e45d8c71SBrad Bishop         return false;
877e45d8c71SBrad Bishop     }
878e45d8c71SBrad Bishop     // baseboard fru
879e45d8c71SBrad Bishop     if (bus == 0 && address == 0)
880e45d8c71SBrad Bishop     {
881e45d8c71SBrad Bishop         std::ofstream file(baseboardFruLocation, std::ios_base::binary);
882e45d8c71SBrad Bishop         if (!file.good())
883e45d8c71SBrad Bishop         {
884e45d8c71SBrad Bishop             std::cerr << "Error opening file " << baseboardFruLocation << "\n";
885e45d8c71SBrad Bishop             throw DBusInternalError();
886e45d8c71SBrad Bishop             return false;
887e45d8c71SBrad Bishop         }
8883013fb49SEd Tanous         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
8893013fb49SEd Tanous         const char* charOffset = reinterpret_cast<const char*>(fru.data());
8903013fb49SEd Tanous         file.write(charOffset, fru.size());
891e45d8c71SBrad Bishop         return file.good();
892e45d8c71SBrad Bishop     }
893e45d8c71SBrad Bishop 
894e45d8c71SBrad Bishop     if (hasEepromFile(bus, address))
895e45d8c71SBrad Bishop     {
896e45d8c71SBrad Bishop         auto path = getEepromPath(bus, address);
897e45d8c71SBrad Bishop         int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
898e45d8c71SBrad Bishop         if (eeprom < 0)
899e45d8c71SBrad Bishop         {
900e45d8c71SBrad Bishop             std::cerr << "unable to open i2c device " << path << "\n";
901e45d8c71SBrad Bishop             throw DBusInternalError();
902e45d8c71SBrad Bishop             return false;
903e45d8c71SBrad Bishop         }
904e45d8c71SBrad Bishop 
905e45d8c71SBrad Bishop         ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
906e45d8c71SBrad Bishop         if (writtenBytes < 0)
907e45d8c71SBrad Bishop         {
908e45d8c71SBrad Bishop             std::cerr << "unable to write to i2c device " << path << "\n";
909e45d8c71SBrad Bishop             close(eeprom);
910e45d8c71SBrad Bishop             throw DBusInternalError();
911e45d8c71SBrad Bishop             return false;
912e45d8c71SBrad Bishop         }
913e45d8c71SBrad Bishop 
914e45d8c71SBrad Bishop         close(eeprom);
915e45d8c71SBrad Bishop         return true;
916e45d8c71SBrad Bishop     }
917e45d8c71SBrad Bishop 
918e45d8c71SBrad Bishop     std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
919e45d8c71SBrad Bishop 
920e45d8c71SBrad Bishop     int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
921e45d8c71SBrad Bishop     if (file < 0)
922e45d8c71SBrad Bishop     {
923e45d8c71SBrad Bishop         std::cerr << "unable to open i2c device " << i2cBus << "\n";
924e45d8c71SBrad Bishop         throw DBusInternalError();
925e45d8c71SBrad Bishop         return false;
926e45d8c71SBrad Bishop     }
927e45d8c71SBrad Bishop     if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
928e45d8c71SBrad Bishop     {
929e45d8c71SBrad Bishop         std::cerr << "unable to set device address\n";
930e45d8c71SBrad Bishop         close(file);
931e45d8c71SBrad Bishop         throw DBusInternalError();
932e45d8c71SBrad Bishop         return false;
933e45d8c71SBrad Bishop     }
934e45d8c71SBrad Bishop 
935e45d8c71SBrad Bishop     constexpr const size_t retryMax = 2;
936e45d8c71SBrad Bishop     uint16_t index = 0;
937e45d8c71SBrad Bishop     size_t retries = retryMax;
938e45d8c71SBrad Bishop     while (index < fru.size())
939e45d8c71SBrad Bishop     {
9403013fb49SEd Tanous         if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
941e45d8c71SBrad Bishop             (retries == retryMax))
942e45d8c71SBrad Bishop         {
943e45d8c71SBrad Bishop             // The 4K EEPROM only uses the A2 and A1 device address bits
944e45d8c71SBrad Bishop             // with the third bit being a memory page address bit.
945e45d8c71SBrad Bishop             if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
946e45d8c71SBrad Bishop             {
947e45d8c71SBrad Bishop                 std::cerr << "unable to set device address\n";
948e45d8c71SBrad Bishop                 close(file);
949e45d8c71SBrad Bishop                 throw DBusInternalError();
950e45d8c71SBrad Bishop                 return false;
951e45d8c71SBrad Bishop             }
952e45d8c71SBrad Bishop         }
953e45d8c71SBrad Bishop 
954e45d8c71SBrad Bishop         if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
955e45d8c71SBrad Bishop                                       fru[index]) < 0)
956e45d8c71SBrad Bishop         {
9573013fb49SEd Tanous             if ((retries--) == 0U)
958e45d8c71SBrad Bishop             {
959e45d8c71SBrad Bishop                 std::cerr << "error writing fru: " << strerror(errno) << "\n";
960e45d8c71SBrad Bishop                 close(file);
961e45d8c71SBrad Bishop                 throw DBusInternalError();
962e45d8c71SBrad Bishop                 return false;
963e45d8c71SBrad Bishop             }
964e45d8c71SBrad Bishop         }
965e45d8c71SBrad Bishop         else
966e45d8c71SBrad Bishop         {
967e45d8c71SBrad Bishop             retries = retryMax;
968e45d8c71SBrad Bishop             index++;
969e45d8c71SBrad Bishop         }
970e45d8c71SBrad Bishop         // most eeproms require 5-10ms between writes
971e45d8c71SBrad Bishop         std::this_thread::sleep_for(std::chrono::milliseconds(10));
972e45d8c71SBrad Bishop     }
973e45d8c71SBrad Bishop     close(file);
974e45d8c71SBrad Bishop     return true;
975e45d8c71SBrad Bishop }
976e45d8c71SBrad Bishop 
rescanOneBus(BusMap & busmap,uint16_t busNum,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,bool dbusCall,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer,std::shared_ptr<sdbusplus::asio::connection> & systemBus)977e45d8c71SBrad Bishop void rescanOneBus(
978213ee21fSkrishnar4     BusMap& busmap, uint16_t busNum,
979e45d8c71SBrad Bishop     boost::container::flat_map<
980e45d8c71SBrad Bishop         std::pair<size_t, size_t>,
981e45d8c71SBrad Bishop         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
982e45d8c71SBrad Bishop     bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
983e45d8c71SBrad Bishop     sdbusplus::asio::object_server& objServer,
984e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
985e45d8c71SBrad Bishop {
9866fdfac0aSYong Li     for (auto device = foundDevices.begin(); device != foundDevices.end();)
987e45d8c71SBrad Bishop     {
9886fdfac0aSYong Li         if (device->first.first == static_cast<size_t>(busNum))
989e45d8c71SBrad Bishop         {
9906fdfac0aSYong Li             objServer.remove_interface(device->second);
9916fdfac0aSYong Li             device = foundDevices.erase(device);
9926fdfac0aSYong Li         }
9936fdfac0aSYong Li         else
9946fdfac0aSYong Li         {
9956fdfac0aSYong Li             device++;
996e45d8c71SBrad Bishop         }
997e45d8c71SBrad Bishop     }
998e45d8c71SBrad Bishop 
999e45d8c71SBrad Bishop     fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1000e45d8c71SBrad Bishop     if (!fs::exists(busPath))
1001e45d8c71SBrad Bishop     {
1002e45d8c71SBrad Bishop         if (dbusCall)
1003e45d8c71SBrad Bishop         {
1004e45d8c71SBrad Bishop             std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1005e45d8c71SBrad Bishop                       << "\n";
1006e45d8c71SBrad Bishop             throw std::invalid_argument("Invalid Bus.");
1007e45d8c71SBrad Bishop         }
1008e45d8c71SBrad Bishop         return;
1009e45d8c71SBrad Bishop     }
1010e45d8c71SBrad Bishop 
1011e45d8c71SBrad Bishop     std::vector<fs::path> i2cBuses;
1012e45d8c71SBrad Bishop     i2cBuses.emplace_back(busPath);
1013e45d8c71SBrad Bishop 
1014e45d8c71SBrad Bishop     auto scan = std::make_shared<FindDevicesWithCallback>(
1015e45d8c71SBrad Bishop         i2cBuses, busmap, powerIsOn, objServer,
1016e45d8c71SBrad Bishop         [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1017e45d8c71SBrad Bishop          &objServer, &systemBus]() {
10186fdfac0aSYong Li         for (auto busIface = dbusInterfaceMap.begin();
10196fdfac0aSYong Li              busIface != dbusInterfaceMap.end();)
1020e45d8c71SBrad Bishop         {
10216fdfac0aSYong Li             if (busIface->first.first == static_cast<size_t>(busNum))
1022e45d8c71SBrad Bishop             {
10236fdfac0aSYong Li                 objServer.remove_interface(busIface->second);
10246fdfac0aSYong Li                 busIface = dbusInterfaceMap.erase(busIface);
10256fdfac0aSYong Li             }
10266fdfac0aSYong Li             else
10276fdfac0aSYong Li             {
10286fdfac0aSYong Li                 busIface++;
1029e45d8c71SBrad Bishop             }
1030e45d8c71SBrad Bishop         }
1031e45d8c71SBrad Bishop         auto found = busmap.find(busNum);
1032e45d8c71SBrad Bishop         if (found == busmap.end() || found->second == nullptr)
1033e45d8c71SBrad Bishop         {
1034e45d8c71SBrad Bishop             return;
1035e45d8c71SBrad Bishop         }
1036e45d8c71SBrad Bishop         for (auto& device : *(found->second))
1037e45d8c71SBrad Bishop         {
1038e45d8c71SBrad Bishop             addFruObjectToDbus(device.second, dbusInterfaceMap,
1039e45d8c71SBrad Bishop                                static_cast<uint32_t>(busNum), device.first,
1040e45d8c71SBrad Bishop                                unknownBusObjectCount, powerIsOn, objServer,
1041e45d8c71SBrad Bishop                                systemBus);
1042e45d8c71SBrad Bishop         }
1043e45d8c71SBrad Bishop     });
1044e45d8c71SBrad Bishop     scan->run();
1045e45d8c71SBrad Bishop }
1046e45d8c71SBrad Bishop 
rescanBusses(BusMap & busmap,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer,std::shared_ptr<sdbusplus::asio::connection> & systemBus)1047e45d8c71SBrad Bishop void rescanBusses(
1048e45d8c71SBrad Bishop     BusMap& busmap,
1049e45d8c71SBrad Bishop     boost::container::flat_map<
1050e45d8c71SBrad Bishop         std::pair<size_t, size_t>,
1051e45d8c71SBrad Bishop         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1052e45d8c71SBrad Bishop     size_t& unknownBusObjectCount, const bool& powerIsOn,
1053e45d8c71SBrad Bishop     sdbusplus::asio::object_server& objServer,
1054e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
1055e45d8c71SBrad Bishop {
1056aa497edfSEd Tanous     static boost::asio::steady_timer timer(io);
1057aa497edfSEd Tanous     timer.expires_from_now(std::chrono::seconds(1));
1058e45d8c71SBrad Bishop 
1059e45d8c71SBrad Bishop     // setup an async wait in case we get flooded with requests
10606e7cebfbSJian Zhang     timer.async_wait([&](const boost::system::error_code& ec) {
10616e7cebfbSJian Zhang         if (ec == boost::asio::error::operation_aborted)
10626e7cebfbSJian Zhang         {
10636e7cebfbSJian Zhang             return;
10646e7cebfbSJian Zhang         }
10656e7cebfbSJian Zhang 
10666e7cebfbSJian Zhang         if (ec)
10676e7cebfbSJian Zhang         {
10686e7cebfbSJian Zhang             std::cerr << "Error in timer: " << ec.message() << "\n";
10696e7cebfbSJian Zhang             return;
10706e7cebfbSJian Zhang         }
10716e7cebfbSJian Zhang 
1072e45d8c71SBrad Bishop         auto devDir = fs::path("/dev/");
1073e45d8c71SBrad Bishop         std::vector<fs::path> i2cBuses;
1074e45d8c71SBrad Bishop 
1075e45d8c71SBrad Bishop         boost::container::flat_map<size_t, fs::path> busPaths;
1076e45d8c71SBrad Bishop         if (!getI2cDevicePaths(devDir, busPaths))
1077e45d8c71SBrad Bishop         {
1078e45d8c71SBrad Bishop             std::cerr << "unable to find i2c devices\n";
1079e45d8c71SBrad Bishop             return;
1080e45d8c71SBrad Bishop         }
1081e45d8c71SBrad Bishop 
1082e45d8c71SBrad Bishop         for (const auto& busPath : busPaths)
1083e45d8c71SBrad Bishop         {
1084e45d8c71SBrad Bishop             i2cBuses.emplace_back(busPath.second);
1085e45d8c71SBrad Bishop         }
1086e45d8c71SBrad Bishop 
1087e45d8c71SBrad Bishop         busmap.clear();
1088e45d8c71SBrad Bishop         for (auto& [pair, interface] : foundDevices)
1089e45d8c71SBrad Bishop         {
1090e45d8c71SBrad Bishop             objServer.remove_interface(interface);
1091e45d8c71SBrad Bishop         }
1092e45d8c71SBrad Bishop         foundDevices.clear();
1093e45d8c71SBrad Bishop 
1094e45d8c71SBrad Bishop         auto scan = std::make_shared<FindDevicesWithCallback>(
1095e45d8c71SBrad Bishop             i2cBuses, busmap, powerIsOn, objServer, [&]() {
1096e45d8c71SBrad Bishop             for (auto& busIface : dbusInterfaceMap)
1097e45d8c71SBrad Bishop             {
1098e45d8c71SBrad Bishop                 objServer.remove_interface(busIface.second);
1099e45d8c71SBrad Bishop             }
1100e45d8c71SBrad Bishop 
1101e45d8c71SBrad Bishop             dbusInterfaceMap.clear();
1102e45d8c71SBrad Bishop             unknownBusObjectCount = 0;
1103e45d8c71SBrad Bishop 
1104e45d8c71SBrad Bishop             // todo, get this from a more sensable place
1105e45d8c71SBrad Bishop             std::vector<uint8_t> baseboardFRU;
1106e45d8c71SBrad Bishop             if (readBaseboardFRU(baseboardFRU))
1107e45d8c71SBrad Bishop             {
1108e45d8c71SBrad Bishop                 // If no device on i2c bus 0, the insertion will happen.
1109b9dd7f86SPatrick Williams                 auto bus0 = busmap.try_emplace(0,
1110b9dd7f86SPatrick Williams                                                std::make_shared<DeviceMap>());
1111e45d8c71SBrad Bishop                 bus0.first->second->emplace(0, baseboardFRU);
1112e45d8c71SBrad Bishop             }
1113e45d8c71SBrad Bishop             for (auto& devicemap : busmap)
1114e45d8c71SBrad Bishop             {
1115e45d8c71SBrad Bishop                 for (auto& device : *devicemap.second)
1116e45d8c71SBrad Bishop                 {
1117e45d8c71SBrad Bishop                     addFruObjectToDbus(device.second, dbusInterfaceMap,
1118e45d8c71SBrad Bishop                                        devicemap.first, device.first,
1119e45d8c71SBrad Bishop                                        unknownBusObjectCount, powerIsOn,
1120e45d8c71SBrad Bishop                                        objServer, systemBus);
1121e45d8c71SBrad Bishop                 }
1122e45d8c71SBrad Bishop             }
1123e45d8c71SBrad Bishop         });
1124e45d8c71SBrad Bishop         scan->run();
1125e45d8c71SBrad Bishop     });
1126e45d8c71SBrad Bishop }
1127e45d8c71SBrad Bishop 
1128e45d8c71SBrad Bishop // Details with example of Asset Tag Update
1129e45d8c71SBrad Bishop // To find location of Product Info Area asset tag as per FRU specification
1130e45d8c71SBrad Bishop // 1. Find product Info area starting offset (*8 - as header will be in
1131e45d8c71SBrad Bishop // multiple of 8 bytes).
1132e45d8c71SBrad Bishop // 2. Skip 3 bytes of product info area (like format version, area length,
1133e45d8c71SBrad Bishop // and language code).
1134e45d8c71SBrad Bishop // 3. Traverse manufacturer name, product name, product version, & product
1135e45d8c71SBrad Bishop // serial number, by reading type/length code to reach the Asset Tag.
1136e45d8c71SBrad Bishop // 4. Update the Asset Tag, reposition the product Info area in multiple of
1137e45d8c71SBrad Bishop // 8 bytes. Update the Product area length and checksum.
1138e45d8c71SBrad Bishop 
updateFRUProperty(const std::string & updatePropertyReq,uint32_t bus,uint32_t address,const std::string & propertyName,boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,size_t & unknownBusObjectCount,const bool & powerIsOn,sdbusplus::asio::object_server & objServer,std::shared_ptr<sdbusplus::asio::connection> & systemBus)1139e45d8c71SBrad Bishop bool updateFRUProperty(
1140e45d8c71SBrad Bishop     const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1141e45d8c71SBrad Bishop     const std::string& propertyName,
1142e45d8c71SBrad Bishop     boost::container::flat_map<
1143e45d8c71SBrad Bishop         std::pair<size_t, size_t>,
1144e45d8c71SBrad Bishop         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1145e45d8c71SBrad Bishop     size_t& unknownBusObjectCount, const bool& powerIsOn,
1146e45d8c71SBrad Bishop     sdbusplus::asio::object_server& objServer,
1147e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
1148e45d8c71SBrad Bishop {
1149e45d8c71SBrad Bishop     size_t updatePropertyReqLen = updatePropertyReq.length();
1150e45d8c71SBrad Bishop     if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1151e45d8c71SBrad Bishop     {
1152e45d8c71SBrad Bishop         std::cerr
1153e45d8c71SBrad Bishop             << "FRU field data cannot be of 1 char or more than 63 chars. "
1154e45d8c71SBrad Bishop                "Invalid Length "
1155e45d8c71SBrad Bishop             << updatePropertyReqLen << "\n";
1156e45d8c71SBrad Bishop         return false;
1157e45d8c71SBrad Bishop     }
1158e45d8c71SBrad Bishop 
1159e45d8c71SBrad Bishop     std::vector<uint8_t> fruData;
1160e45d8c71SBrad Bishop 
11619d6f5904SKumar Thangavel     if (!getFruData(fruData, bus, address))
1162e45d8c71SBrad Bishop     {
11639d6f5904SKumar Thangavel         std::cerr << "Failure getting FRU Data \n";
1164e45d8c71SBrad Bishop         return false;
1165e45d8c71SBrad Bishop     }
1166e45d8c71SBrad Bishop 
11674d4df5b4SAKSHAY RAVEENDRAN K     struct FruArea fruAreaParams
11684d4df5b4SAKSHAY RAVEENDRAN K     {};
1169e45d8c71SBrad Bishop 
117051b557b7SKumar Thangavel     if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
1171e45d8c71SBrad Bishop     {
1172bdfc5ec6SKumar Thangavel         std::cerr << "findFruAreaLocationAndField failed \n";
1173e45d8c71SBrad Bishop         return false;
1174e45d8c71SBrad Bishop     }
1175e45d8c71SBrad Bishop 
117651b557b7SKumar Thangavel     std::vector<uint8_t> restFRUAreaFieldsData;
117751b557b7SKumar Thangavel     if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
117851b557b7SKumar Thangavel                          restFRUAreaFieldsData))
1179e45d8c71SBrad Bishop     {
118051b557b7SKumar Thangavel         std::cerr << "copyRestFRUArea failed \n";
1181e45d8c71SBrad Bishop         return false;
1182e45d8c71SBrad Bishop     }
1183e45d8c71SBrad Bishop 
1184e45d8c71SBrad Bishop     // Push post update fru areas if any
1185e45d8c71SBrad Bishop     unsigned int nextFRUAreaLoc = 0;
1186e45d8c71SBrad Bishop     for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1187e45d8c71SBrad Bishop          nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1188e45d8c71SBrad Bishop     {
1189e45d8c71SBrad Bishop         unsigned int fruAreaLoc =
1190e45d8c71SBrad Bishop             fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
119151b557b7SKumar Thangavel         if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
1192e45d8c71SBrad Bishop             ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1193e45d8c71SBrad Bishop         {
1194e45d8c71SBrad Bishop             nextFRUAreaLoc = fruAreaLoc;
1195e45d8c71SBrad Bishop         }
1196e45d8c71SBrad Bishop     }
1197e45d8c71SBrad Bishop     std::vector<uint8_t> restFRUAreasData;
11983013fb49SEd Tanous     if (nextFRUAreaLoc != 0U)
1199e45d8c71SBrad Bishop     {
1200e45d8c71SBrad Bishop         std::copy_n(fruData.begin() + nextFRUAreaLoc,
1201e45d8c71SBrad Bishop                     fruData.size() - nextFRUAreaLoc,
1202e45d8c71SBrad Bishop                     std::back_inserter(restFRUAreasData));
1203e45d8c71SBrad Bishop     }
1204e45d8c71SBrad Bishop 
1205e45d8c71SBrad Bishop     // check FRU area size
1206e45d8c71SBrad Bishop     size_t fruAreaDataSize =
1207bdfc5ec6SKumar Thangavel         ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1208bdfc5ec6SKumar Thangavel          restFRUAreaFieldsData.size());
1209bdfc5ec6SKumar Thangavel     size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
1210e45d8c71SBrad Bishop     if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1211e45d8c71SBrad Bishop     {
1212e45d8c71SBrad Bishop #ifdef ENABLE_FRU_AREA_RESIZE
1213e45d8c71SBrad Bishop         size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1214e45d8c71SBrad Bishop         // round size to 8-byte blocks
1215df190619SPatrick Williams         newFRUAreaSize = ((newFRUAreaSize - 1) / fruBlockSize + 1) *
1216df190619SPatrick Williams                          fruBlockSize;
1217df190619SPatrick Williams         size_t newFRUDataSize = fruData.size() + newFRUAreaSize -
1218df190619SPatrick Williams                                 fruAreaParams.size;
1219e45d8c71SBrad Bishop         fruData.resize(newFRUDataSize);
1220bdfc5ec6SKumar Thangavel         fruAreaParams.size = newFRUAreaSize;
1221bdfc5ec6SKumar Thangavel         fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
1222e45d8c71SBrad Bishop #else
1223e45d8c71SBrad Bishop         std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1224e45d8c71SBrad Bishop                   << " should not be greater than available FRU area size: "
1225e45d8c71SBrad Bishop                   << fruAreaAvailableSize << "\n";
1226e45d8c71SBrad Bishop         return false;
1227e45d8c71SBrad Bishop #endif // ENABLE_FRU_AREA_RESIZE
1228e45d8c71SBrad Bishop     }
1229e45d8c71SBrad Bishop 
1230e45d8c71SBrad Bishop     // write new requested property field length and data
1231e45d8c71SBrad Bishop     constexpr uint8_t newTypeLenMask = 0xC0;
1232bdfc5ec6SKumar Thangavel     fruData[fruAreaParams.updateFieldLoc] =
1233e45d8c71SBrad Bishop         static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1234bdfc5ec6SKumar Thangavel     fruAreaParams.updateFieldLoc++;
1235e45d8c71SBrad Bishop     std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1236bdfc5ec6SKumar Thangavel               fruData.begin() + fruAreaParams.updateFieldLoc);
1237e45d8c71SBrad Bishop 
1238e45d8c71SBrad Bishop     // Copy remaining data to main fru area - post updated fru field vector
1239df190619SPatrick Williams     fruAreaParams.restFieldsLoc = fruAreaParams.updateFieldLoc +
1240df190619SPatrick Williams                                   updatePropertyReqLen;
1241df190619SPatrick Williams     size_t fruAreaDataEnd = fruAreaParams.restFieldsLoc +
1242df190619SPatrick Williams                             restFRUAreaFieldsData.size();
124351b557b7SKumar Thangavel 
1244e45d8c71SBrad Bishop     std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
124551b557b7SKumar Thangavel               fruData.begin() + fruAreaParams.restFieldsLoc);
1246e45d8c71SBrad Bishop 
1247e45d8c71SBrad Bishop     // Update final fru with new fru area length and checksum
1248e45d8c71SBrad Bishop     unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1249bdfc5ec6SKumar Thangavel         fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
1250e45d8c71SBrad Bishop 
1251e45d8c71SBrad Bishop #ifdef ENABLE_FRU_AREA_RESIZE
1252e45d8c71SBrad Bishop     ++nextFRUAreaNewLoc;
1253df190619SPatrick Williams     ssize_t nextFRUAreaOffsetDiff = (nextFRUAreaNewLoc - nextFRUAreaLoc) /
1254df190619SPatrick Williams                                     fruBlockSize;
1255e45d8c71SBrad Bishop     // Append rest FRU Areas if size changed and there were other sections after
1256e45d8c71SBrad Bishop     // updated one
1257e45d8c71SBrad Bishop     if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1258e45d8c71SBrad Bishop     {
1259e45d8c71SBrad Bishop         std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1260e45d8c71SBrad Bishop                   fruData.begin() + nextFRUAreaNewLoc);
1261e45d8c71SBrad Bishop         // Update Common Header
12626e22c877SEd Tanous         for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
12636e22c877SEd Tanous              nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1264e45d8c71SBrad Bishop         {
12656e22c877SEd Tanous             unsigned int fruAreaOffsetField =
12666e22c877SEd Tanous                 getHeaderAreaFieldOffset(nextFRUArea);
1267e45d8c71SBrad Bishop             size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
12686e22c877SEd Tanous             if (curFRUAreaOffset > fruAreaParams.end)
1269e45d8c71SBrad Bishop             {
1270e45d8c71SBrad Bishop                 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1271e45d8c71SBrad Bishop                     curFRUAreaOffset + nextFRUAreaOffsetDiff);
1272e45d8c71SBrad Bishop             }
1273e45d8c71SBrad Bishop         }
1274e45d8c71SBrad Bishop         // Calculate new checksum
1275e45d8c71SBrad Bishop         std::vector<uint8_t> headerFRUData;
1276e45d8c71SBrad Bishop         std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1277e45d8c71SBrad Bishop         size_t checksumVal = calculateChecksum(headerFRUData);
1278e45d8c71SBrad Bishop         fruData[7] = static_cast<uint8_t>(checksumVal);
1279e45d8c71SBrad Bishop         // fill zeros if FRU Area size decreased
1280e45d8c71SBrad Bishop         if (nextFRUAreaOffsetDiff < 0)
1281e45d8c71SBrad Bishop         {
1282e45d8c71SBrad Bishop             std::fill(fruData.begin() + nextFRUAreaNewLoc +
1283e45d8c71SBrad Bishop                           restFRUAreasData.size(),
1284e45d8c71SBrad Bishop                       fruData.end(), 0);
1285e45d8c71SBrad Bishop         }
1286e45d8c71SBrad Bishop     }
1287e45d8c71SBrad Bishop #else
1288e45d8c71SBrad Bishop     // this is to avoid "unused variable" warning
1289e45d8c71SBrad Bishop     (void)nextFRUAreaNewLoc;
1290e45d8c71SBrad Bishop #endif // ENABLE_FRU_AREA_RESIZE
1291e45d8c71SBrad Bishop     if (fruData.empty())
1292e45d8c71SBrad Bishop     {
1293e45d8c71SBrad Bishop         return false;
1294e45d8c71SBrad Bishop     }
1295e45d8c71SBrad Bishop 
1296e45d8c71SBrad Bishop     if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1297e45d8c71SBrad Bishop                   fruData))
1298e45d8c71SBrad Bishop     {
1299e45d8c71SBrad Bishop         return false;
1300e45d8c71SBrad Bishop     }
1301e45d8c71SBrad Bishop 
1302e45d8c71SBrad Bishop     // Rescan the bus so that GetRawFru dbus-call fetches updated values
1303e45d8c71SBrad Bishop     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1304e45d8c71SBrad Bishop                  objServer, systemBus);
1305e45d8c71SBrad Bishop     return true;
1306e45d8c71SBrad Bishop }
1307e45d8c71SBrad Bishop 
main()1308e45d8c71SBrad Bishop int main()
1309e45d8c71SBrad Bishop {
1310e45d8c71SBrad Bishop     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1311e45d8c71SBrad Bishop     sdbusplus::asio::object_server objServer(systemBus);
1312e45d8c71SBrad Bishop 
1313e45d8c71SBrad Bishop     static size_t unknownBusObjectCount = 0;
1314e45d8c71SBrad Bishop     static bool powerIsOn = false;
1315e45d8c71SBrad Bishop     auto devDir = fs::path("/dev/");
1316e45d8c71SBrad Bishop     auto matchString = std::string(R"(i2c-\d+$)");
1317e45d8c71SBrad Bishop     std::vector<fs::path> i2cBuses;
1318e45d8c71SBrad Bishop 
1319e45d8c71SBrad Bishop     if (!findFiles(devDir, matchString, i2cBuses))
1320e45d8c71SBrad Bishop     {
1321e45d8c71SBrad Bishop         std::cerr << "unable to find i2c devices\n";
1322e45d8c71SBrad Bishop         return 1;
1323e45d8c71SBrad Bishop     }
1324e45d8c71SBrad Bishop 
13252447c24dSMatt Simmering     // check for and load blocklist with initial buses.
13262447c24dSMatt Simmering     loadBlocklist(blocklistPath);
1327e45d8c71SBrad Bishop 
1328e45d8c71SBrad Bishop     systemBus->request_name("xyz.openbmc_project.FruDevice");
1329e45d8c71SBrad Bishop 
1330e45d8c71SBrad Bishop     // this is a map with keys of pair(bus number, address) and values of
1331e45d8c71SBrad Bishop     // the object on dbus
1332e45d8c71SBrad Bishop     boost::container::flat_map<std::pair<size_t, size_t>,
1333e45d8c71SBrad Bishop                                std::shared_ptr<sdbusplus::asio::dbus_interface>>
1334e45d8c71SBrad Bishop         dbusInterfaceMap;
1335e45d8c71SBrad Bishop 
1336e45d8c71SBrad Bishop     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1337e45d8c71SBrad Bishop         objServer.add_interface("/xyz/openbmc_project/FruDevice",
1338e45d8c71SBrad Bishop                                 "xyz.openbmc_project.FruDeviceManager");
1339e45d8c71SBrad Bishop 
1340e45d8c71SBrad Bishop     iface->register_method("ReScan", [&]() {
1341e45d8c71SBrad Bishop         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1342e45d8c71SBrad Bishop                      objServer, systemBus);
1343e45d8c71SBrad Bishop     });
1344e45d8c71SBrad Bishop 
1345213ee21fSkrishnar4     iface->register_method("ReScanBus", [&](uint16_t bus) {
1346e45d8c71SBrad Bishop         rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
1347e45d8c71SBrad Bishop                      powerIsOn, objServer, systemBus);
1348e45d8c71SBrad Bishop     });
1349e45d8c71SBrad Bishop 
1350e45d8c71SBrad Bishop     iface->register_method("GetRawFru", getFRUInfo);
1351e45d8c71SBrad Bishop 
1352df190619SPatrick Williams     iface->register_method("WriteFru",
1353df190619SPatrick Williams                            [&](const uint16_t bus, const uint8_t address,
1354e45d8c71SBrad Bishop                                const std::vector<uint8_t>& data) {
1355e45d8c71SBrad Bishop         if (!writeFRU(bus, address, data))
1356e45d8c71SBrad Bishop         {
1357e45d8c71SBrad Bishop             throw std::invalid_argument("Invalid Arguments.");
1358e45d8c71SBrad Bishop             return;
1359e45d8c71SBrad Bishop         }
1360e45d8c71SBrad Bishop         // schedule rescan on success
1361e45d8c71SBrad Bishop         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1362e45d8c71SBrad Bishop                      objServer, systemBus);
1363e45d8c71SBrad Bishop     });
1364e45d8c71SBrad Bishop     iface->initialize();
1365e45d8c71SBrad Bishop 
13662af39224SPatrick Williams     std::function<void(sdbusplus::message_t & message)> eventHandler =
13672af39224SPatrick Williams         [&](sdbusplus::message_t& message) {
1368e45d8c71SBrad Bishop         std::string objectName;
1369e45d8c71SBrad Bishop         boost::container::flat_map<
1370e45d8c71SBrad Bishop             std::string,
1371e45d8c71SBrad Bishop             std::variant<std::string, bool, int64_t, uint64_t, double>>
1372e45d8c71SBrad Bishop             values;
1373e45d8c71SBrad Bishop         message.read(objectName, values);
1374e45d8c71SBrad Bishop         auto findState = values.find("CurrentHostState");
1375e45d8c71SBrad Bishop         if (findState != values.end())
1376e45d8c71SBrad Bishop         {
13773b13fb4bSThu Nguyen             if (std::get<std::string>(findState->second) ==
13783b13fb4bSThu Nguyen                 "xyz.openbmc_project.State.Host.HostState.Running")
13793b13fb4bSThu Nguyen             {
13803b13fb4bSThu Nguyen                 powerIsOn = true;
13813b13fb4bSThu Nguyen             }
1382e45d8c71SBrad Bishop         }
1383e45d8c71SBrad Bishop 
1384e45d8c71SBrad Bishop         if (powerIsOn)
1385e45d8c71SBrad Bishop         {
1386e45d8c71SBrad Bishop             rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1387e45d8c71SBrad Bishop                          powerIsOn, objServer, systemBus);
1388e45d8c71SBrad Bishop         }
1389e45d8c71SBrad Bishop     };
1390e45d8c71SBrad Bishop 
13912af39224SPatrick Williams     sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
13922af39224SPatrick Williams         static_cast<sdbusplus::bus_t&>(*systemBus),
1393e45d8c71SBrad Bishop         "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
1394e45d8c71SBrad Bishop         "openbmc_project/state/"
1395e45d8c71SBrad Bishop         "host0',arg0='xyz.openbmc_project.State.Host'",
1396e45d8c71SBrad Bishop         eventHandler);
1397e45d8c71SBrad Bishop 
1398e45d8c71SBrad Bishop     int fd = inotify_init();
1399e45d8c71SBrad Bishop     inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
14003013fb49SEd Tanous     std::array<char, 4096> readBuffer{};
1401e45d8c71SBrad Bishop     // monitor for new i2c devices
1402e45d8c71SBrad Bishop     boost::asio::posix::stream_descriptor dirWatch(io, fd);
1403e45d8c71SBrad Bishop     std::function<void(const boost::system::error_code, std::size_t)>
1404b9dd7f86SPatrick Williams         watchI2cBusses = [&](const boost::system::error_code& ec,
1405e45d8c71SBrad Bishop                              std::size_t bytesTransferred) {
1406e45d8c71SBrad Bishop         if (ec)
1407e45d8c71SBrad Bishop         {
1408e45d8c71SBrad Bishop             std::cout << "Callback Error " << ec << "\n";
1409e45d8c71SBrad Bishop             return;
1410e45d8c71SBrad Bishop         }
1411e45d8c71SBrad Bishop         size_t index = 0;
1412e45d8c71SBrad Bishop         while ((index + sizeof(inotify_event)) <= bytesTransferred)
1413e45d8c71SBrad Bishop         {
14143013fb49SEd Tanous             const char* p = &readBuffer[index];
14153013fb49SEd Tanous             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
14163013fb49SEd Tanous             const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1417e45d8c71SBrad Bishop             switch (iEvent->mask)
1418e45d8c71SBrad Bishop             {
1419e45d8c71SBrad Bishop                 case IN_CREATE:
1420e45d8c71SBrad Bishop                 case IN_MOVED_TO:
1421e45d8c71SBrad Bishop                 case IN_DELETE:
1422*fc171428SEd Tanous                 {
14233013fb49SEd Tanous                     std::string_view name(&iEvent->name[0], iEvent->len);
1424e45d8c71SBrad Bishop                     if (boost::starts_with(name, "i2c"))
1425e45d8c71SBrad Bishop                     {
1426e45d8c71SBrad Bishop                         int bus = busStrToInt(name);
1427e45d8c71SBrad Bishop                         if (bus < 0)
1428e45d8c71SBrad Bishop                         {
1429df190619SPatrick Williams                             std::cerr << "Could not parse bus " << name << "\n";
1430e45d8c71SBrad Bishop                             continue;
1431e45d8c71SBrad Bishop                         }
14327fc486f5SPavanKumarIntel                         int rootBus = getRootBus(bus);
14337fc486f5SPavanKumarIntel                         if (rootBus >= 0)
14347fc486f5SPavanKumarIntel                         {
1435df190619SPatrick Williams                             rescanOneBus(busMap, static_cast<uint16_t>(rootBus),
14367fc486f5SPavanKumarIntel                                          dbusInterfaceMap, false,
14377fc486f5SPavanKumarIntel                                          unknownBusObjectCount, powerIsOn,
14387fc486f5SPavanKumarIntel                                          objServer, systemBus);
14397fc486f5SPavanKumarIntel                         }
1440213ee21fSkrishnar4                         rescanOneBus(busMap, static_cast<uint16_t>(bus),
1441e45d8c71SBrad Bishop                                      dbusInterfaceMap, false,
1442e45d8c71SBrad Bishop                                      unknownBusObjectCount, powerIsOn,
1443e45d8c71SBrad Bishop                                      objServer, systemBus);
1444e45d8c71SBrad Bishop                     }
1445e45d8c71SBrad Bishop                 }
1446*fc171428SEd Tanous                 break;
1447*fc171428SEd Tanous                 default:
1448*fc171428SEd Tanous                     break;
1449*fc171428SEd Tanous             }
1450e45d8c71SBrad Bishop             index += sizeof(inotify_event) + iEvent->len;
1451e45d8c71SBrad Bishop         }
1452e45d8c71SBrad Bishop 
1453e45d8c71SBrad Bishop         dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1454e45d8c71SBrad Bishop                                  watchI2cBusses);
1455e45d8c71SBrad Bishop     };
1456e45d8c71SBrad Bishop 
1457e45d8c71SBrad Bishop     dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
1458e45d8c71SBrad Bishop     // run the initial scan
1459e45d8c71SBrad Bishop     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1460e45d8c71SBrad Bishop                  objServer, systemBus);
1461e45d8c71SBrad Bishop 
1462e45d8c71SBrad Bishop     io.run();
1463e45d8c71SBrad Bishop     return 0;
1464e45d8c71SBrad Bishop }
1465