blob: 3d806a201be87e71137a6f8873e3dacab2c4b81e [file] [log] [blame]
Alexander Hansen4e1142d2025-07-25 17:07:27 +02001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
James Feist3cb5fec2018-01-23 14:41:51 -08003
Christopher Meis3cbff972025-04-09 14:07:22 +02004#include "../utils.hpp"
Brad Bishope45d8c72022-05-25 15:12:53 -04005#include "fru_utils.hpp"
Patrick Venturea49dc332019-10-26 08:32:02 -07006
James Feist3cb5fec2018-01-23 14:41:51 -08007#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -07008#include <sys/inotify.h>
9#include <sys/ioctl.h>
10
Ed Tanous34c3e012023-03-06 13:42:00 -080011#include <boost/asio/io_context.hpp>
Ed Tanousaa497ed2023-02-28 13:43:41 -080012#include <boost/asio/steady_timer.hpp>
James Feist3b860982018-10-02 14:34:07 -070013#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070014#include <nlohmann/json.hpp>
Alexander Hansenc3db2c32024-08-20 15:01:38 +020015#include <phosphor-logging/lg2.hpp>
James Feist8c505da2020-05-28 10:06:33 -070016#include <sdbusplus/asio/connection.hpp>
17#include <sdbusplus/asio/object_server.hpp>
18
19#include <array>
Ed Tanous07d467b2021-02-23 14:48:37 -080020#include <cerrno>
Ed Tanous3013fb42022-07-09 08:27:06 -070021#include <charconv>
James Feist3b860982018-10-02 14:34:07 -070022#include <chrono>
23#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070024#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080025#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070026#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080027#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070028#include <iomanip>
Patrick Venturee26395d2019-10-29 14:05:16 -070029#include <limits>
Andrew Jefferya9c58922021-06-01 09:28:59 +093030#include <map>
Bonnie Lobfda2c42022-10-26 16:50:54 +080031#include <optional>
James Feist3f8a2782018-02-12 09:24:42 -080032#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070033#include <set>
34#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070035#include <string>
James Feist3b860982018-10-02 14:34:07 -070036#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080037#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080038#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070039#include <vector>
James Feist3b860982018-10-02 14:34:07 -070040
James Feist8c505da2020-05-28 10:06:33 -070041extern "C"
42{
James Feist3b860982018-10-02 14:34:07 -070043#include <i2c/smbus.h>
44#include <linux/i2c-dev.h>
45}
James Feist3cb5fec2018-01-23 14:41:51 -080046
Ed Tanous072e25d2018-12-16 21:45:20 -080047namespace fs = std::filesystem;
Ed Tanous07d467b2021-02-23 14:48:37 -080048constexpr size_t maxFruSize = 512;
49constexpr size_t maxEepromPageIndex = 255;
ankita prasad7329a222023-07-07 09:18:10 +000050constexpr size_t busTimeoutSeconds = 10;
James Feist3cb5fec2018-01-23 14:41:51 -080051
Matt Simmering2447c242023-11-09 14:18:39 -080052constexpr const char* blocklistPath = PACKAGE_DIR "blacklist.json";
Patrick Venture11f1ff42019-08-01 10:42:12 -070053
Ed Tanous07d467b2021-02-23 14:48:37 -080054const static constexpr char* baseboardFruLocation =
James Feist3cb5fec2018-01-23 14:41:51 -080055 "/etc/fru/baseboard.fru.bin";
56
Ed Tanous07d467b2021-02-23 14:48:37 -080057const static constexpr char* i2CDevLocation = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080058
Vu Phamdac2dfc2024-11-05 12:20:42 -060059constexpr const char* fruDevice16BitDetectMode = FRU_DEVICE_16BITDETECTMODE;
60
Ed Tanousfc171422024-04-04 17:18:16 -070061// TODO Refactor these to not be globals
62// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
Bonnie Lobfda2c42022-10-26 16:50:54 +080063static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
Matt Simmering2447c242023-11-09 14:18:39 -080064 busBlocklist;
James Feist6ebf9de2018-05-15 15:01:17 -070065struct FindDevicesWithCallback;
66
James Feist8a983922019-10-24 17:11:56 -070067static boost::container::flat_map<
68 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
69 foundDevices;
70
James Feist7972bb92019-11-13 15:59:24 -080071static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +000072static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
James Feist7972bb92019-11-13 15:59:24 -080073
Ed Tanous34c3e012023-03-06 13:42:00 -080074boost::asio::io_context io;
Ed Tanousfc171422024-04-04 17:18:16 -070075// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
James Feist5cb06082019-10-24 17:11:13 -070076
Naresh Solankicf288962025-06-06 15:26:11 +053077bool updateFruProperty(
78 const std::string& propertyValue, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -080079 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +053080 boost::container::flat_map<
81 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +053082 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -080083 size_t& unknownBusObjectCount, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -070084 const std::set<size_t>& addressBlocklist,
Sora Su12e2d412025-08-22 14:23:16 +080085 sdbusplus::asio::object_server& objServer);
Patrick Venturebaba7672019-10-26 09:26:41 -070086
Patrick Venturec50e1ff2019-08-06 10:22:28 -070087// Given a bus/address, produce the path in sysfs for an eeprom.
88static std::string getEepromPath(size_t bus, size_t address)
89{
90 std::stringstream output;
91 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
92 << std::setfill('0') << std::setw(4) << std::hex << address
93 << "/eeprom";
94 return output.str();
95}
96
97static bool hasEepromFile(size_t bus, size_t address)
98{
99 auto path = getEepromPath(bus, address);
100 try
101 {
102 return fs::exists(path);
103 }
104 catch (...)
105 {
106 return false;
107 }
108}
109
Zev Weiss309c0b12022-02-25 01:44:12 +0000110static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700111{
112 auto result = lseek(fd, offset, SEEK_SET);
113 if (result < 0)
114 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200115 lg2::error("failed to seek");
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700116 return -1;
117 }
118
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700119 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700120}
121
Ed Tanous3013fb42022-07-09 08:27:06 -0700122static int busStrToInt(const std::string_view busName)
James Feist5d7f4692020-06-17 18:22:33 -0700123{
Ed Tanous07d467b2021-02-23 14:48:37 -0800124 auto findBus = busName.rfind('-');
James Feist5d7f4692020-06-17 18:22:33 -0700125 if (findBus == std::string::npos)
126 {
127 return -1;
128 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700129 std::string_view num = busName.substr(findBus + 1);
130 int val = 0;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400131 bool fullMatch = false;
132 fromCharsWrapper(num, val, fullMatch);
Ed Tanous3013fb42022-07-09 08:27:06 -0700133 return val;
James Feist5d7f4692020-06-17 18:22:33 -0700134}
135
James Feist7972bb92019-11-13 15:59:24 -0800136static int getRootBus(size_t bus)
137{
138 auto ec = std::error_code();
139 auto path = std::filesystem::read_symlink(
Patrick Williamsb7077432024-08-16 15:22:21 -0400140 std::filesystem::path(
141 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"),
James Feist7972bb92019-11-13 15:59:24 -0800142 ec);
143 if (ec)
144 {
145 return -1;
146 }
147
148 std::string filename = path.filename();
Ed Tanous07d467b2021-02-23 14:48:37 -0800149 auto findBus = filename.find('-');
James Feist7972bb92019-11-13 15:59:24 -0800150 if (findBus == std::string::npos)
151 {
152 return -1;
153 }
154 return std::stoi(filename.substr(0, findBus));
155}
156
James Feistc95cb142018-02-26 10:41:42 -0800157static bool isMuxBus(size_t bus)
158{
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700159 auto ec = std::error_code();
160 auto isSymlink =
161 is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
162 std::to_string(bus) + "/mux_device"),
163 ec);
164 return (!ec && isSymlink);
James Feistc95cb142018-02-26 10:41:42 -0800165}
166
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530167static void makeProbeInterface(size_t bus, size_t address,
168 sdbusplus::asio::object_server& objServer)
James Feist8a983922019-10-24 17:11:56 -0700169{
170 if (isMuxBus(bus))
171 {
172 return; // the mux buses are random, no need to publish
173 }
174 auto [it, success] = foundDevices.emplace(
175 std::make_pair(bus, address),
176 objServer.add_interface(
177 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
178 std::to_string(address),
179 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
180 if (!success)
181 {
182 return; // already added
183 }
184 it->second->register_property("Bus", bus);
185 it->second->register_property("Address", address);
186 it->second->initialize();
187}
188
Matt Simmering2447c242023-11-09 14:18:39 -0800189// Issue an I2C transaction to first write to_target_buf_len bytes,then read
190// from_target_buf_len bytes.
Patrick Williamsb7077432024-08-16 15:22:21 -0400191static int i2cSmbusWriteThenRead(
192 int file, uint16_t address, uint8_t* toTargetBuf, uint8_t toTargetBufLen,
193 uint8_t* fromTargetBuf, uint8_t fromTargetBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800194{
Matt Simmering2447c242023-11-09 14:18:39 -0800195 if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
196 fromTargetBuf == nullptr || fromTargetBufLen == 0)
Xiang Liu2801a702020-01-20 14:29:34 -0800197 {
198 return -1;
199 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800200
Ed Tanous3013fb42022-07-09 08:27:06 -0700201 constexpr size_t smbusWriteThenReadMsgCount = 2;
202 std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
Patrick Williamsa41f0142024-12-18 11:22:53 -0500203 struct i2c_rdwr_ioctl_data rdwr{};
Xiang Liu2801a702020-01-20 14:29:34 -0800204
205 msgs[0].addr = address;
206 msgs[0].flags = 0;
Matt Simmering2447c242023-11-09 14:18:39 -0800207 msgs[0].len = toTargetBufLen;
208 msgs[0].buf = toTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800209 msgs[1].addr = address;
210 msgs[1].flags = I2C_M_RD;
Matt Simmering2447c242023-11-09 14:18:39 -0800211 msgs[1].len = fromTargetBufLen;
212 msgs[1].buf = fromTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800213
Ed Tanous3013fb42022-07-09 08:27:06 -0700214 rdwr.msgs = msgs.data();
215 rdwr.nmsgs = msgs.size();
Xiang Liu2801a702020-01-20 14:29:34 -0800216
217 int ret = ioctl(file, I2C_RDWR, &rdwr);
218
Jason M. Billsf6e4c1f2022-08-19 12:23:51 -0700219 return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
Xiang Liu2801a702020-01-20 14:29:34 -0800220}
221
Marvin Drees2b3ed302023-04-14 16:35:14 +0200222static int64_t readData(bool is16bit, bool isBytewise, int file,
223 uint16_t address, off_t offset, size_t len,
224 uint8_t* buf)
Xiang Liu2801a702020-01-20 14:29:34 -0800225{
Zev Weiss309c0b12022-02-25 01:44:12 +0000226 if (!is16bit)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800227 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200228 if (!isBytewise)
229 {
230 return i2c_smbus_read_i2c_block_data(
231 file, static_cast<uint8_t>(offset), len, buf);
232 }
233
234 std::span<uint8_t> bufspan{buf, len};
235 for (size_t i = 0; i < len; i++)
236 {
237 int byte = i2c_smbus_read_byte_data(
238 file, static_cast<uint8_t>(offset + i));
239 if (byte < 0)
240 {
241 return static_cast<int64_t>(byte);
242 }
243 bufspan[i] = static_cast<uint8_t>(byte);
244 }
245 return static_cast<int64_t>(len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800246 }
247
Xiang Liu2801a702020-01-20 14:29:34 -0800248 offset = htobe16(offset);
Ed Tanous3013fb42022-07-09 08:27:06 -0700249 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
250 uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
251 return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800252}
253
Vu Phamdac2dfc2024-11-05 12:20:42 -0600254// Mode_1:
255// --------
256// Please refer to document docs/address_size_detection_modes.md for
257// more details and explanations.
258static std::optional<bool> isDevice16BitMode1(int file)
259{
260 // Set the higher data word address bits to 0. It's safe on 8-bit
261 // addressing EEPROMs because it doesn't write any actual data.
262 int ret = i2c_smbus_write_byte(file, 0);
263 if (ret < 0)
264 {
265 return std::nullopt;
266 }
267
268 /* Get first byte */
269 int byte1 = i2c_smbus_read_byte_data(file, 0);
270 if (byte1 < 0)
271 {
272 return std::nullopt;
273 }
274 /* Read 7 more bytes, it will read same first byte in case of
275 * 8 bit but it will read next byte in case of 16 bit
276 */
277 for (int i = 0; i < 7; i++)
278 {
279 int byte2 = i2c_smbus_read_byte_data(file, 0);
280 if (byte2 < 0)
281 {
282 return std::nullopt;
283 }
284 if (byte2 != byte1)
285 {
286 return true;
287 }
288 }
289 return false;
290}
291
292// Mode_2:
293// --------
294// Please refer to document docs/address_size_detection_modes.md for
295// more details and explanations.
296static std::optional<bool> isDevice16BitMode2(int file, uint16_t address)
297{
298 uint8_t first = 0;
299 uint8_t cur = 0;
300 uint16_t v = 0;
301 int ret = 0;
302 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
303 uint8_t* p = reinterpret_cast<uint8_t*>(&v);
304
305 /*
306 * Write 2 bytes byte0 = 0, byte1 = {0..7} and then subsequent read byte
307 * It will read same first byte in case of 8 bit but
308 * it will read next byte in case of 16 bit
309 */
310 for (int i = 0; i < 8; i++)
311 {
312 v = htobe16(i);
313
314 ret = i2cSmbusWriteThenRead(file, address, p, 2, &cur, 1);
315 if (ret < 0)
316 {
317 return std::nullopt;
318 }
319
320 if (i == 0)
321 {
322 first = cur;
323 }
324
325 if (first != cur)
326 {
327 return true;
328 }
329 }
330 return false;
331}
332
333static std::optional<bool> isDevice16Bit(int file, uint16_t address)
334{
335 std::string mode(fruDevice16BitDetectMode);
336
337 if (mode == "MODE_2")
338 {
339 return isDevice16BitMode2(file, address);
340 }
341
342 return isDevice16BitMode1(file);
343}
344
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700345// TODO: This code is very similar to the non-eeprom version and can be merged
346// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300347static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700348{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700349 auto path = getEepromPath(bus, address);
350
351 int file = open(path.c_str(), O_RDONLY);
352 if (file < 0)
353 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200354 lg2::error("Unable to open eeprom file: {PATH}", "PATH", path);
Patrick Venturebaba7672019-10-26 09:26:41 -0700355 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700356 }
357
Patrick Venturebaba7672019-10-26 09:26:41 -0700358 std::string errorMessage = "eeprom at " + std::to_string(bus) +
359 " address " + std::to_string(address);
Zev Weiss309c0b12022-02-25 01:44:12 +0000360 auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
361 return readFromEeprom(file, offset, length, outbuf);
362 };
363 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400364 std::pair<std::vector<uint8_t>, bool> pair =
365 readFRUContents(reader, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700366
367 close(file);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200368 return pair.first;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700369}
370
Bonnie Lobfda2c42022-10-26 16:50:54 +0800371std::set<size_t> findI2CEeproms(int i2cBus,
372 const std::shared_ptr<DeviceMap>& devices)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700373{
Bonnie Lobfda2c42022-10-26 16:50:54 +0800374 std::set<size_t> foundList;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700375
376 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
377
378 // For each file listed under the i2c device
379 // NOTE: This should be faster than just checking for each possible address
380 // path.
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700381 auto ec = std::error_code();
382 for (const auto& p : fs::directory_iterator(path, ec))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700383 {
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700384 if (ec)
385 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200386 lg2::error("directory_iterator err {ERR}", "ERR", ec.message());
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700387 break;
388 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700389 const std::string node = p.path().string();
390 std::smatch m;
Patrick Williamsb7077432024-08-16 15:22:21 -0400391 bool found =
392 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700393
394 if (!found)
395 {
396 continue;
397 }
398 if (m.size() != 2)
399 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200400 lg2::error("regex didn't capture");
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700401 continue;
402 }
403
404 std::ssub_match subMatch = m[1];
405 std::string addressString = subMatch.str();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800406 std::string_view addressStringView(addressString);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700407
Bonnie Lobfda2c42022-10-26 16:50:54 +0800408 size_t address = 0;
409 std::from_chars(addressStringView.begin(), addressStringView.end(),
410 address, 16);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700411
412 const std::string eeprom = node + "/eeprom";
413
414 try
415 {
416 if (!fs::exists(eeprom))
417 {
418 continue;
419 }
420 }
421 catch (...)
422 {
423 continue;
424 }
425
426 // There is an eeprom file at this address, it may have invalid
427 // contents, but we found it.
428 foundList.insert(address);
429
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300430 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700431 if (!device.empty())
432 {
433 devices->emplace(address, device);
434 }
435 }
436
437 return foundList;
438}
439
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300440int getBusFRUs(int file, int first, int last, int bus,
Jonathan Doman2418a612022-02-14 18:20:58 -0800441 std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700442 const std::set<size_t>& addressBlocklist,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530443 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800444{
James Feist26c27ad2018-07-25 15:09:40 -0700445 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700446 // NOTE: When reading the devices raw on the bus, it can interfere with
447 // the driver's ability to operate, therefore read eeproms first before
448 // scanning for devices without drivers. Several experiments were run
449 // and it was determined that if there were any devices on the bus
450 // before the eeprom was hit and read, the eeprom driver wouldn't open
451 // while the bus device was open. An experiment was not performed to see
452 // if this issue was resolved if the i2c bus device was closed, but
453 // hexdumps of the eeprom later were successful.
454
455 // Scan for i2c eeproms loaded on this bus.
Bonnie Lobfda2c42022-10-26 16:50:54 +0800456 std::set<size_t> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800457 std::set<size_t>& failedItems = failedAddresses[bus];
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000458 std::set<size_t>& foundItems = fruAddresses[bus];
459 foundItems.clear();
James Feist7972bb92019-11-13 15:59:24 -0800460
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700461 skipList.insert_range(addressBlocklist);
462
Matt Simmering2447c242023-11-09 14:18:39 -0800463 auto busFind = busBlocklist.find(bus);
464 if (busFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800465 {
466 if (busFind->second != std::nullopt)
467 {
468 for (const auto& address : *(busFind->second))
469 {
470 skipList.insert(address);
471 }
472 }
473 }
474
James Feist7972bb92019-11-13 15:59:24 -0800475 std::set<size_t>* rootFailures = nullptr;
476 int rootBus = getRootBus(bus);
477
478 if (rootBus >= 0)
479 {
Matt Simmering2447c242023-11-09 14:18:39 -0800480 auto rootBusFind = busBlocklist.find(rootBus);
481 if (rootBusFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800482 {
483 if (rootBusFind->second != std::nullopt)
484 {
485 for (const auto& rootAddress : *(rootBusFind->second))
486 {
487 skipList.insert(rootAddress);
488 }
489 }
490 }
James Feist7972bb92019-11-13 15:59:24 -0800491 rootFailures = &(failedAddresses[rootBus]);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000492 foundItems = fruAddresses[rootBus];
James Feist7972bb92019-11-13 15:59:24 -0800493 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700494
Matt Simmering2447c242023-11-09 14:18:39 -0800495 constexpr int startSkipTargetAddr = 0;
496 constexpr int endSkipTargetAddr = 12;
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530497
James Feist26c27ad2018-07-25 15:09:40 -0700498 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800499 {
Patrick Williams64599932025-05-14 07:24:20 -0400500 if (foundItems.contains(ii))
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000501 {
502 continue;
503 }
Patrick Williams64599932025-05-14 07:24:20 -0400504 if (skipList.contains(ii))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700505 {
506 continue;
507 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530508 // skipping since no device is present in this range
Matt Simmering2447c242023-11-09 14:18:39 -0800509 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530510 {
511 continue;
512 }
Matt Simmering2447c242023-11-09 14:18:39 -0800513 // Set target address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530514 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800515 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200516 lg2::error("device at bus {BUS} address {ADDR} busy", "BUS",
517 bus, "ADDR", ii);
James Feist26c27ad2018-07-25 15:09:40 -0700518 continue;
519 }
520 // probe
Ed Tanous07d467b2021-02-23 14:48:37 -0800521 if (i2c_smbus_read_byte(file) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700522 {
523 continue;
524 }
James Feist3cb5fec2018-01-23 14:41:51 -0800525
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200526 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
527 "ADDR", ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800528
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530529 makeProbeInterface(bus, ii, objServer);
James Feist8a983922019-10-24 17:11:56 -0700530
Patrick Williams64599932025-05-14 07:24:20 -0400531 if (failedItems.contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800532 {
533 // if we failed to read it once, unlikely we can read it later
534 continue;
535 }
536
537 if (rootFailures != nullptr)
538 {
Patrick Williams64599932025-05-14 07:24:20 -0400539 if (rootFailures->contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800540 {
541 continue;
542 }
543 }
544
Vijay Khemka2d681f62018-11-06 15:51:00 -0800545 /* Check for Device type if it is 8 bit or 16 bit */
Vu Phamdac2dfc2024-11-05 12:20:42 -0600546 std::optional<bool> is16Bit = isDevice16Bit(file, ii);
Zev Weiss309c0b12022-02-25 01:44:12 +0000547 if (!is16Bit.has_value())
Vijay Khemka2d681f62018-11-06 15:51:00 -0800548 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200549 lg2::error("failed to read bus {BUS} address {ADDR}", "BUS",
550 bus, "ADDR", ii);
James Feistcb5661d2020-06-12 15:05:01 -0700551 if (powerIsOn)
552 {
553 failedItems.insert(ii);
554 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800555 continue;
556 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000557 bool is16BitBool{*is16Bit};
Vijay Khemka2d681f62018-11-06 15:51:00 -0800558
Patrick Williamsb7077432024-08-16 15:22:21 -0400559 auto readFunc = [is16BitBool, file,
560 ii](off_t offset, size_t length, uint8_t* outbuf) {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200561 return readData(is16BitBool, false, file, ii, offset, length,
562 outbuf);
Zev Weiss309c0b12022-02-25 01:44:12 +0000563 };
564 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400565 std::string errorMessage =
566 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200567 std::pair<std::vector<uint8_t>, bool> pair =
568 readFRUContents(reader, errorMessage);
569 const bool foundHeader = pair.second;
570
571 if (!foundHeader && !is16BitBool)
572 {
573 // certain FRU eeproms require bytewise reading.
574 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
575
Patrick Williamsb7077432024-08-16 15:22:21 -0400576 auto readFunc =
577 [is16BitBool, file,
578 ii](off_t offset, size_t length, uint8_t* outbuf) {
579 return readData(is16BitBool, true, file, ii, offset,
580 length, outbuf);
581 };
Marvin Drees2b3ed302023-04-14 16:35:14 +0200582 FRUReader readerBytewise(std::move(readFunc));
583 pair = readFRUContents(readerBytewise, errorMessage);
584 }
585
586 if (pair.first.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700587 {
James Feist26c27ad2018-07-25 15:09:40 -0700588 continue;
589 }
James Feist26c27ad2018-07-25 15:09:40 -0700590
Marvin Drees2b3ed302023-04-14 16:35:14 +0200591 devices->emplace(ii, pair.first);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000592 fruAddresses[bus].insert(ii);
James Feist3cb5fec2018-01-23 14:41:51 -0800593 }
James Feist26c27ad2018-07-25 15:09:40 -0700594 return 1;
595 });
596 std::future_status status =
597 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
598 if (status == std::future_status::timeout)
599 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200600 lg2::error("Error reading bus {BUS}", "BUS", bus);
James Feistcb5661d2020-06-12 15:05:01 -0700601 if (powerIsOn)
602 {
Matt Simmering2447c242023-11-09 14:18:39 -0800603 busBlocklist[bus] = std::nullopt;
James Feistcb5661d2020-06-12 15:05:01 -0700604 }
James Feist444830e2019-04-05 08:38:16 -0700605 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700606 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800607 }
608
James Feist444830e2019-04-05 08:38:16 -0700609 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700610 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800611}
612
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700613struct AddressBlocklistResult
614{
615 int rc;
616 std::set<size_t> list;
617};
618
619AddressBlocklistResult loadAddressBlocklist(const nlohmann::json& data)
620{
621 auto addrIt = data.find("addresses");
622 if (addrIt == data.end())
623 {
624 return {0, std::set<size_t>()};
625 }
626
627 const auto* const addr =
628 data["addresses"].get_ptr<const nlohmann::json::array_t*>();
629
630 if (addr == nullptr)
631 {
632 lg2::error("addresses must be an array");
633 return {EINVAL, std::set<size_t>()};
634 }
635
636 std::set<size_t> addressBlocklist = {};
637
638 for (const auto& address : *addr)
639 {
640 const auto* addrS = address.get_ptr<const std::string*>();
641 if (addrS == nullptr)
642 {
643 lg2::error("address must be a string\n");
644 return {EINVAL, std::set<size_t>()};
645 }
646
647 if (!(addrS->starts_with("0x") || addrS->starts_with("0X")))
648 {
649 lg2::error("address must start with 0x or 0X\n");
650 return {EINVAL, std::set<size_t>()};
651 }
652
653 // The alternative offered here relies on undefined behavior
654 // of dereferencing iterators given by .end()
655 // this pointer access is checked above by the calls to starts_with
656 // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
657 size_t addressInt = 0;
658 auto [ptr, ec] = std::from_chars(
659 addrS->data() + 2, addrS->data() + addrS->length(), addressInt, 16);
660
661 const auto erc = std::make_error_condition(ec);
662 if (ptr != (addrS->data() + addrS->length()) || erc)
663 {
664 lg2::error("Invalid address type: {ADDR} {MSG}\n", "ADDR", *addrS,
665 "MSG", erc.message());
666 return {EINVAL, std::set<size_t>()};
667 }
668 // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
669 if (addressInt > 0x77)
670 {
671 lg2::error("Invalid address {ADDR}\n", "ADDR", *addrS);
672 return {EINVAL, std::set<size_t>()};
673 }
674
675 addressBlocklist.insert(addressInt);
676 }
677
678 return {0, addressBlocklist};
679}
680
681// once the bus blocklist is made non global,
682// return it here too.
683std::set<size_t> loadBlocklist(const char* path)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700684{
Matt Simmering2447c242023-11-09 14:18:39 -0800685 std::ifstream blocklistStream(path);
686 if (!blocklistStream.good())
Patrick Venture11f1ff42019-08-01 10:42:12 -0700687 {
688 // File is optional.
Alexander Hansen8feb0452025-09-15 14:29:20 +0200689 lg2::error("Cannot open blocklist file.\n");
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700690 return {};
Patrick Venture11f1ff42019-08-01 10:42:12 -0700691 }
692
Patrick Williamsb7077432024-08-16 15:22:21 -0400693 nlohmann::json data =
694 nlohmann::json::parse(blocklistStream, nullptr, false);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700695 if (data.is_discarded())
696 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200697 lg2::error(
698 "Illegal blocklist file detected, cannot validate JSON, exiting");
Patrick Venture11f1ff42019-08-01 10:42:12 -0700699 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700700 }
701
702 // It's expected to have at least one field, "buses" that is an array of the
703 // buses by integer. Allow for future options to exclude further aspects,
704 // such as specific addresses or ranges.
705 if (data.type() != nlohmann::json::value_t::object)
706 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200707 lg2::error("Illegal blocklist, expected to read dictionary");
Patrick Venture11f1ff42019-08-01 10:42:12 -0700708 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700709 }
710
711 // If buses field is missing, that's fine.
712 if (data.count("buses") == 1)
713 {
714 // Parse the buses array after a little validation.
715 auto buses = data.at("buses");
716 if (buses.type() != nlohmann::json::value_t::array)
717 {
718 // Buses field present but invalid, therefore this is an error.
Alexander Hansen8feb0452025-09-15 14:29:20 +0200719 lg2::error("Invalid contents for blocklist buses field");
Patrick Venture11f1ff42019-08-01 10:42:12 -0700720 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700721 }
722
723 // Catch exception here for type mis-match.
724 try
725 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800726 for (const auto& busIterator : buses)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700727 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800728 // If bus and addresses field are missing, that's fine.
729 if (busIterator.contains("bus") &&
730 busIterator.contains("addresses"))
731 {
732 auto busData = busIterator.at("bus");
733 auto bus = busData.get<size_t>();
734
735 auto addressData = busIterator.at("addresses");
736 auto addresses =
737 addressData.get<std::set<std::string_view>>();
738
Ed Tanousfc171422024-04-04 17:18:16 -0700739 auto& block = busBlocklist[bus].emplace();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800740 for (const auto& address : addresses)
741 {
742 size_t addressInt = 0;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400743 bool fullMatch = false;
744 fromCharsWrapper(address.substr(2), addressInt,
745 fullMatch, 16);
Ed Tanousfc171422024-04-04 17:18:16 -0700746 block.insert(addressInt);
Bonnie Lobfda2c42022-10-26 16:50:54 +0800747 }
748 }
749 else
750 {
Matt Simmering2447c242023-11-09 14:18:39 -0800751 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
Bonnie Lobfda2c42022-10-26 16:50:54 +0800752 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700753 }
754 }
755 catch (const nlohmann::detail::type_error& e)
756 {
757 // Type mis-match is a critical error.
Alexander Hansen8feb0452025-09-15 14:29:20 +0200758 lg2::error("Invalid bus type: {ERR}", "ERR", e.what());
Patrick Venture11f1ff42019-08-01 10:42:12 -0700759 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700760 }
761 }
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700762
763 const auto [rc, addressBlocklist] = loadAddressBlocklist(data);
764 if (rc != 0)
765 {
766 std::exit(EXIT_FAILURE);
767 }
768
769 return addressBlocklist;
Patrick Venture11f1ff42019-08-01 10:42:12 -0700770}
771
Ed Tanous07d467b2021-02-23 14:48:37 -0800772static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800773 BusMap& busmap, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700774 const std::set<size_t>& addressBlocklist,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530775 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800776{
Ed Tanous3013fb42022-07-09 08:27:06 -0700777 for (const auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800778 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700779 int bus = busStrToInt(i2cBus.string());
James Feist0c3980a2019-12-19 11:09:27 -0800780
James Feist5d7f4692020-06-17 18:22:33 -0700781 if (bus < 0)
782 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200783 lg2::error("Cannot translate {BUS} to int", "BUS", i2cBus);
James Feist5d7f4692020-06-17 18:22:33 -0700784 continue;
785 }
Matt Simmering2447c242023-11-09 14:18:39 -0800786 auto busFind = busBlocklist.find(bus);
787 if (busFind != busBlocklist.end())
James Feist444830e2019-04-05 08:38:16 -0700788 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800789 if (busFind->second == std::nullopt)
790 {
791 continue; // Skip blocked busses.
792 }
James Feist444830e2019-04-05 08:38:16 -0700793 }
James Feist0c3980a2019-12-19 11:09:27 -0800794 int rootBus = getRootBus(bus);
Matt Simmering2447c242023-11-09 14:18:39 -0800795 auto rootBusFind = busBlocklist.find(rootBus);
796 if (rootBusFind != busBlocklist.end())
James Feist0c3980a2019-12-19 11:09:27 -0800797 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800798 if (rootBusFind->second == std::nullopt)
799 {
800 continue;
801 }
James Feist0c3980a2019-12-19 11:09:27 -0800802 }
803
James Feist3cb5fec2018-01-23 14:41:51 -0800804 auto file = open(i2cBus.c_str(), O_RDWR);
805 if (file < 0)
806 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200807 lg2::error("unable to open i2c device {PATH}", "PATH",
808 i2cBus.string());
James Feist3cb5fec2018-01-23 14:41:51 -0800809 continue;
810 }
811 unsigned long funcs = 0;
812
813 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
814 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200815 lg2::error(
816 "Error: Could not get the adapter functionality matrix bus {BUS}",
817 "BUS", bus);
Zhikui Renc02d8cb2021-06-28 16:56:08 -0700818 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800819 continue;
820 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700821 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
822 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
James Feist3cb5fec2018-01-23 14:41:51 -0800823 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200824 lg2::error("Error: Can't use SMBus Receive Byte command bus {BUS}",
825 "BUS", bus);
George Liu913d07d2024-12-09 19:16:30 +0800826 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800827 continue;
828 }
James Feist98132792019-07-09 13:29:09 -0700829 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800830 device = std::make_shared<DeviceMap>();
831
Nikhil Potaded8884f12019-03-27 13:27:13 -0700832 // i2cdetect by default uses the range 0x03 to 0x77, as
833 // this is what we have tested with, use this range. Could be
834 // changed in future.
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200835 lg2::debug("Scanning bus {BUS}", "BUS", bus);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700836
837 // fd is closed in this function in case the bus locks up
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700838 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, addressBlocklist,
839 objServer);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700840
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200841 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
James Feist3cb5fec2018-01-23 14:41:51 -0800842 }
James Feist3cb5fec2018-01-23 14:41:51 -0800843}
844
James Feist6ebf9de2018-05-15 15:01:17 -0700845// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700846struct FindDevicesWithCallback :
847 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700848{
James Feista465ccc2019-02-08 12:51:01 -0800849 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800850 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530851 sdbusplus::asio::object_server& objServer,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700852 const std::set<size_t>& addressBlocklist,
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800853 std::function<void()>&& callback) :
Patrick Williamsb7077432024-08-16 15:22:21 -0400854 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700855 _objServer(objServer), _callback(std::move(callback)),
856 _addressBlocklist{addressBlocklist}
James Feist8c505da2020-05-28 10:06:33 -0700857 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700858 ~FindDevicesWithCallback()
859 {
860 _callback();
861 }
862 void run()
863 {
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700864 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _addressBlocklist,
865 _objServer);
James Feist6ebf9de2018-05-15 15:01:17 -0700866 }
867
James Feista465ccc2019-02-08 12:51:01 -0800868 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800869 BusMap& _busMap;
Jonathan Doman2418a612022-02-14 18:20:58 -0800870 const bool& _powerIsOn;
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530871 sdbusplus::asio::object_server& _objServer;
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800872 std::function<void()> _callback;
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700873 std::set<size_t> _addressBlocklist;
James Feist6ebf9de2018-05-15 15:01:17 -0700874};
875
Ed Tanous07d467b2021-02-23 14:48:37 -0800876void addFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300877 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800878 boost::container::flat_map<
879 std::pair<size_t, size_t>,
880 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +0530881 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700882 const bool& powerIsOn, const std::set<size_t>& addressBlocklist,
883 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800884{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300885 boost::container::flat_map<std::string, std::string> formattedFRU;
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530886
887 std::optional<std::string> optionalProductName = getProductName(
888 device, formattedFRU, bus, address, unknownBusObjectCount);
889 if (!optionalProductName)
James Feist3cb5fec2018-01-23 14:41:51 -0800890 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200891 lg2::error("getProductName failed. product name is empty.");
James Feist3cb5fec2018-01-23 14:41:51 -0800892 return;
893 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700894
Patrick Williamsb7077432024-08-16 15:22:21 -0400895 std::string productName =
896 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
James Feist3cb5fec2018-01-23 14:41:51 -0800897
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530898 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
899 if (index.has_value())
James Feist918e18c2018-02-13 15:51:07 -0800900 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530901 productName += "_";
902 productName += std::to_string(++(*index));
James Feist918e18c2018-02-13 15:51:07 -0800903 }
James Feist3cb5fec2018-01-23 14:41:51 -0800904
James Feist9eb0b582018-04-27 12:15:46 -0700905 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
906 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
907 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
908
Naresh Solankicf288962025-06-06 15:26:11 +0530909 if (ENABLE_FRU_UPDATE_PROPERTY)
910 {
911 iface->register_method(
912 "UpdateFruField",
913 [bus, address, &dbusInterfaceMap, &unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700914 &powerIsOn, &objServer, addressBlocklist](
915 const std::string& fieldName, const std::string& fieldValue) {
Naresh Solankicf288962025-06-06 15:26:11 +0530916 // Update the property
917 if (!updateFruProperty(fieldValue, bus, address, fieldName,
918 dbusInterfaceMap, unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700919 powerIsOn, addressBlocklist, objServer))
Naresh Solankicf288962025-06-06 15:26:11 +0530920 {
921 lg2::debug(
922 "Failed to Add Field: Name = {NAME}, Value = {VALUE}",
923 "NAME", fieldName, "VALUE", fieldValue);
924 return false;
925 }
926
927 return true;
928 });
929 }
930
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300931 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800932 {
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700933 std::regex_replace(property.second.begin(), property.second.begin(),
Ed Tanous07d467b2021-02-23 14:48:37 -0800934 property.second.end(), nonAsciiRegex, "_");
Naresh Solanki89092a92025-06-02 15:48:04 +0530935 if (property.second.empty())
James Feist9eb0b582018-04-27 12:15:46 -0700936 {
937 continue;
938 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400939 std::string key =
940 std::regex_replace(property.first, nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530941
Naresh Solanki89092a92025-06-02 15:48:04 +0530942 // Allow FRU field update if ENABLE_FRU_UPDATE_PROPERTY is set.
943 if (isFieldEditable(property.first))
Joshi-Mansid73b7442020-03-27 19:10:21 +0530944 {
945 std::string propertyName = property.first;
946 iface->register_property(
947 key, property.second + '\0',
Kumar Thangavel41a90512021-11-24 15:44:20 +0530948 [bus, address, propertyName, &dbusInterfaceMap,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700949 &unknownBusObjectCount, &powerIsOn, &objServer,
950 &addressBlocklist](const std::string& req, std::string& resp) {
Patrick Williamsb7077432024-08-16 15:22:21 -0400951 if (strcmp(req.c_str(), resp.c_str()) != 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +0530952 {
Patrick Williamsb7077432024-08-16 15:22:21 -0400953 // call the method which will update
Naresh Solankicf288962025-06-06 15:26:11 +0530954 if (updateFruProperty(req, bus, address, propertyName,
Patrick Williamsb7077432024-08-16 15:22:21 -0400955 dbusInterfaceMap,
956 unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -0700957 addressBlocklist, objServer))
Patrick Williamsb7077432024-08-16 15:22:21 -0400958 {
959 resp = req;
960 }
961 else
962 {
963 throw std::invalid_argument(
964 "FRU property update failed.");
965 }
Joshi-Mansid73b7442020-03-27 19:10:21 +0530966 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400967 return 1;
968 });
Joshi-Mansid73b7442020-03-27 19:10:21 +0530969 }
970 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -0700971 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200972 lg2::error("illegal key: {KEY}", "KEY", key);
James Feist9eb0b582018-04-27 12:15:46 -0700973 }
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200974 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
975 property.first, "SECOND", property.second);
James Feist3cb5fec2018-01-23 14:41:51 -0800976 }
James Feist2a9d6db2018-04-27 15:48:28 -0700977
978 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700979 iface->register_property("BUS", bus);
980 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700981
James Feist9eb0b582018-04-27 12:15:46 -0700982 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800983}
984
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300985static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800986{
987 // try to read baseboard fru from file
Ed Tanous07d467b2021-02-23 14:48:37 -0800988 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300989 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -0800990 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300991 baseboardFRUFile.seekg(0, std::ios_base::end);
992 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
993 baseboardFRU.resize(fileSize);
994 baseboardFRUFile.seekg(0, std::ios_base::beg);
Ed Tanous3013fb42022-07-09 08:27:06 -0700995 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
996 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
997 baseboardFRUFile.read(charOffset, fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -0800998 }
999 else
1000 {
1001 return false;
1002 }
1003 return true;
1004}
1005
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001006bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001007{
1008 boost::container::flat_map<std::string, std::string> tmp;
Ed Tanous07d467b2021-02-23 14:48:37 -08001009 if (fru.size() > maxFruSize)
James Feistb49ffc32018-05-02 11:10:43 -07001010 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001011 lg2::error("Invalid fru.size() during writeFRU");
James Feistb49ffc32018-05-02 11:10:43 -07001012 return false;
1013 }
1014 // verify legal fru by running it through fru parsing logic
Michael Shen0961b112022-02-22 11:06:33 +08001015 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001016 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001017 lg2::error("Invalid fru format during writeFRU");
James Feistb49ffc32018-05-02 11:10:43 -07001018 return false;
1019 }
1020 // baseboard fru
1021 if (bus == 0 && address == 0)
1022 {
Ed Tanous07d467b2021-02-23 14:48:37 -08001023 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
James Feistb49ffc32018-05-02 11:10:43 -07001024 if (!file.good())
1025 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001026 lg2::error("Error opening file {PATH}", "PATH",
1027 baseboardFruLocation);
James Feistddb78302018-09-06 11:45:42 -07001028 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001029 return false;
1030 }
Ed Tanous3013fb42022-07-09 08:27:06 -07001031 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1032 const char* charOffset = reinterpret_cast<const char*>(fru.data());
1033 file.write(charOffset, fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001034 return file.good();
1035 }
Ed Tanous07d467b2021-02-23 14:48:37 -08001036
1037 if (hasEepromFile(bus, address))
James Feistb49ffc32018-05-02 11:10:43 -07001038 {
Ed Tanous07d467b2021-02-23 14:48:37 -08001039 auto path = getEepromPath(bus, address);
Naresh Solanki41ee1802024-11-09 01:44:46 +05301040 off_t offset = 0;
1041
Ed Tanous07d467b2021-02-23 14:48:37 -08001042 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1043 if (eeprom < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001044 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001045 lg2::error("unable to open i2c device {PATH}", "PATH", path);
Ed Tanous07d467b2021-02-23 14:48:37 -08001046 throw DBusInternalError();
1047 return false;
1048 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001049
Naresh Solanki41ee1802024-11-09 01:44:46 +05301050 std::string errorMessage = "eeprom at " + std::to_string(bus) +
1051 " address " + std::to_string(address);
1052 auto readFunc = [eeprom](off_t offset, size_t length, uint8_t* outbuf) {
1053 return readFromEeprom(eeprom, offset, length, outbuf);
1054 };
1055 FRUReader reader(std::move(readFunc));
1056
Ed Tanous10c57652025-09-30 10:24:57 -07001057 auto sections = findFRUHeader(reader, errorMessage, 0);
1058 if (!sections)
Naresh Solanki41ee1802024-11-09 01:44:46 +05301059 {
1060 offset = 0;
1061 }
Ed Tanous10c57652025-09-30 10:24:57 -07001062 else
1063 {
1064 offset = sections->IpmiFruOffset;
1065 }
Naresh Solanki41ee1802024-11-09 01:44:46 +05301066
1067 if (lseek(eeprom, offset, SEEK_SET) < 0)
1068 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001069 lg2::error("Unable to seek to offset {OFFSET} in device: {PATH}",
1070 "OFFSET", offset, "PATH", path);
Naresh Solanki41ee1802024-11-09 01:44:46 +05301071 close(eeprom);
1072 throw DBusInternalError();
1073 }
1074
Ed Tanous07d467b2021-02-23 14:48:37 -08001075 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1076 if (writtenBytes < 0)
1077 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001078 lg2::error("unable to write to i2c device {PATH}", "PATH", path);
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001079 close(eeprom);
James Feistddb78302018-09-06 11:45:42 -07001080 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001081 return false;
1082 }
1083
Ed Tanous07d467b2021-02-23 14:48:37 -08001084 close(eeprom);
James Feistb49ffc32018-05-02 11:10:43 -07001085 return true;
1086 }
Ed Tanous07d467b2021-02-23 14:48:37 -08001087
1088 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1089
1090 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1091 if (file < 0)
1092 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001093 lg2::error("unable to open i2c device {PATH}", "PATH", i2cBus);
Ed Tanous07d467b2021-02-23 14:48:37 -08001094 throw DBusInternalError();
1095 return false;
1096 }
1097 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1098 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001099 lg2::error("unable to set device address");
Ed Tanous07d467b2021-02-23 14:48:37 -08001100 close(file);
1101 throw DBusInternalError();
1102 return false;
1103 }
1104
1105 constexpr const size_t retryMax = 2;
1106 uint16_t index = 0;
1107 size_t retries = retryMax;
1108 while (index < fru.size())
1109 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001110 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
Ed Tanous07d467b2021-02-23 14:48:37 -08001111 (retries == retryMax))
1112 {
1113 // The 4K EEPROM only uses the A2 and A1 device address bits
1114 // with the third bit being a memory page address bit.
1115 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1116 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001117 lg2::error("unable to set device address");
Ed Tanous07d467b2021-02-23 14:48:37 -08001118 close(file);
1119 throw DBusInternalError();
1120 return false;
1121 }
1122 }
1123
1124 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1125 fru[index]) < 0)
1126 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001127 if ((retries--) == 0U)
Ed Tanous07d467b2021-02-23 14:48:37 -08001128 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001129 lg2::error("error writing fru: {ERR}", "ERR", strerror(errno));
Ed Tanous07d467b2021-02-23 14:48:37 -08001130 close(file);
1131 throw DBusInternalError();
1132 return false;
1133 }
1134 }
1135 else
1136 {
1137 retries = retryMax;
1138 index++;
1139 }
1140 // most eeproms require 5-10ms between writes
1141 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1142 }
1143 close(file);
1144 return true;
James Feistb49ffc32018-05-02 11:10:43 -07001145}
1146
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001147void rescanOneBus(
krishnar4213ee212022-11-11 15:39:30 +05301148 BusMap& busmap, uint16_t busNum,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001149 boost::container::flat_map<
1150 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001151 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001152 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001153 const std::set<size_t>& addressBlocklist,
Sora Su12e2d412025-08-22 14:23:16 +08001154 sdbusplus::asio::object_server& objServer)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001155{
Yong Li6fdfac02023-10-30 11:21:30 +08001156 for (auto device = foundDevices.begin(); device != foundDevices.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001157 {
Yong Li6fdfac02023-10-30 11:21:30 +08001158 if (device->first.first == static_cast<size_t>(busNum))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001159 {
Yong Li6fdfac02023-10-30 11:21:30 +08001160 objServer.remove_interface(device->second);
1161 device = foundDevices.erase(device);
1162 }
1163 else
1164 {
1165 device++;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001166 }
1167 }
1168
James Feist5d7f4692020-06-17 18:22:33 -07001169 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1170 if (!fs::exists(busPath))
1171 {
1172 if (dbusCall)
1173 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001174 lg2::error("Unable to access i2c bus {BUS}", "BUS",
1175 static_cast<int>(busNum));
James Feist5d7f4692020-06-17 18:22:33 -07001176 throw std::invalid_argument("Invalid Bus.");
1177 }
1178 return;
1179 }
1180
1181 std::vector<fs::path> i2cBuses;
1182 i2cBuses.emplace_back(busPath);
1183
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001184 auto scan = std::make_shared<FindDevicesWithCallback>(
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001185 i2cBuses, busmap, powerIsOn, objServer, addressBlocklist,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301186 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001187 &objServer, &addressBlocklist]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001188 for (auto busIface = dbusInterfaceMap.begin();
1189 busIface != dbusInterfaceMap.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001190 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001191 if (busIface->first.first == static_cast<size_t>(busNum))
1192 {
1193 objServer.remove_interface(busIface->second);
1194 busIface = dbusInterfaceMap.erase(busIface);
1195 }
1196 else
1197 {
1198 busIface++;
1199 }
Yong Li6fdfac02023-10-30 11:21:30 +08001200 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001201 auto found = busmap.find(busNum);
1202 if (found == busmap.end() || found->second == nullptr)
Yong Li6fdfac02023-10-30 11:21:30 +08001203 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001204 return;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001205 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001206 for (auto& device : *(found->second))
1207 {
1208 addFruObjectToDbus(device.second, dbusInterfaceMap,
1209 static_cast<uint32_t>(busNum), device.first,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001210 unknownBusObjectCount, powerIsOn,
1211 addressBlocklist, objServer);
Patrick Williamsb7077432024-08-16 15:22:21 -04001212 }
1213 });
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001214 scan->run();
1215}
1216
James Feist9eb0b582018-04-27 12:15:46 -07001217void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001218 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001219 boost::container::flat_map<
1220 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301221 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001222 size_t& unknownBusObjectCount, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001223 const std::set<size_t>& addressBlocklist,
Sora Su12e2d412025-08-22 14:23:16 +08001224 sdbusplus::asio::object_server& objServer)
James Feist918e18c2018-02-13 15:51:07 -08001225{
Ed Tanousaa497ed2023-02-28 13:43:41 -08001226 static boost::asio::steady_timer timer(io);
Ed Tanousae2d4352025-02-12 15:51:48 -08001227 timer.expires_after(std::chrono::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001228
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001229 // setup an async wait in case we get flooded with requests
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001230 timer.async_wait([&](const boost::system::error_code& ec) {
1231 if (ec == boost::asio::error::operation_aborted)
1232 {
1233 return;
1234 }
1235
1236 if (ec)
1237 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001238 lg2::error("Error in timer: {ERR}", "ERR", ec.message());
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001239 return;
1240 }
1241
James Feist4131aea2018-03-09 09:47:30 -08001242 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001243 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001244
Nikhil Potaded8884f12019-03-27 13:27:13 -07001245 boost::container::flat_map<size_t, fs::path> busPaths;
1246 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001247 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001248 lg2::error("unable to find i2c devices");
James Feist4131aea2018-03-09 09:47:30 -08001249 return;
James Feist918e18c2018-02-13 15:51:07 -08001250 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001251
Ed Tanous07d467b2021-02-23 14:48:37 -08001252 for (const auto& busPath : busPaths)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001253 {
1254 i2cBuses.emplace_back(busPath.second);
1255 }
James Feist4131aea2018-03-09 09:47:30 -08001256
James Feist98132792019-07-09 13:29:09 -07001257 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001258 for (auto& [pair, interface] : foundDevices)
1259 {
1260 objServer.remove_interface(interface);
1261 }
1262 foundDevices.clear();
1263
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301264 auto scan = std::make_shared<FindDevicesWithCallback>(
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001265 i2cBuses, busmap, powerIsOn, objServer, addressBlocklist, [&]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001266 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001267 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001268 objServer.remove_interface(busIface.second);
James Feist6ebf9de2018-05-15 15:01:17 -07001269 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001270
1271 dbusInterfaceMap.clear();
1272 unknownBusObjectCount = 0;
1273
1274 // todo, get this from a more sensable place
1275 std::vector<uint8_t> baseboardFRU;
1276 if (readBaseboardFRU(baseboardFRU))
1277 {
1278 // If no device on i2c bus 0, the insertion will happen.
1279 auto bus0 =
1280 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1281 bus0.first->second->emplace(0, baseboardFRU);
1282 }
1283 for (auto& devicemap : busmap)
1284 {
1285 for (auto& device : *devicemap.second)
1286 {
1287 addFruObjectToDbus(device.second, dbusInterfaceMap,
1288 devicemap.first, device.first,
1289 unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001290 addressBlocklist, objServer);
Patrick Williamsb7077432024-08-16 15:22:21 -04001291 }
1292 }
1293 });
James Feist6ebf9de2018-05-15 15:01:17 -07001294 scan->run();
1295 });
James Feist918e18c2018-02-13 15:51:07 -08001296}
1297
Naresh Solankicf288962025-06-06 15:26:11 +05301298bool updateFruProperty(
1299 const std::string& propertyValue, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -08001300 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301301 boost::container::flat_map<
1302 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301303 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001304 size_t& unknownBusObjectCount, const bool& powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001305 const std::set<size_t>& addressBlocklist,
Sora Su12e2d412025-08-22 14:23:16 +08001306 sdbusplus::asio::object_server& objServer)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301307{
Naresh Solankicf288962025-06-06 15:26:11 +05301308 lg2::debug(
1309 "updateFruProperty called: FieldName = {NAME}, FieldValue = {VALUE}",
1310 "NAME", propertyName, "VALUE", propertyValue);
1311
Joshi-Mansid73b7442020-03-27 19:10:21 +05301312 std::vector<uint8_t> fruData;
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301313 if (!getFruData(fruData, bus, address))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301314 {
Marc Olberding25680e32025-10-03 12:38:10 -07001315 lg2::error("Failure getting FRU Data from bus {BUS}, address {ADDRESS}",
1316 "BUS", bus, "ADDRESS", address);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301317 return false;
1318 }
1319
Marc Olberding9bde15b2025-09-09 15:24:00 -07001320 bool success = updateAddProperty(propertyValue, propertyName, fruData);
1321 if (!success)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301322 {
Marc Olberding25680e32025-10-03 12:38:10 -07001323 lg2::error(
Marc Olberding9bde15b2025-09-09 15:24:00 -07001324 "Failed to update the property on bus {BUS}, address {ADDRESS}",
1325 "BUS", bus, "ADDRESS", address);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301326 return false;
1327 }
1328
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001329 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301330 fruData))
1331 {
Marc Olberding25680e32025-10-03 12:38:10 -07001332 lg2::error("Failed to write the FRU");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301333 return false;
1334 }
1335
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301336 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001337 addressBlocklist, objServer);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301338 return true;
1339}
1340
James Feist98132792019-07-09 13:29:09 -07001341int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001342{
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301343 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1344 sdbusplus::asio::object_server objServer(systemBus);
1345
Kumar Thangavel41a90512021-11-24 15:44:20 +05301346 static size_t unknownBusObjectCount = 0;
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301347 static bool powerIsOn = false;
James Feist3cb5fec2018-01-23 14:41:51 -08001348 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001349 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001350 std::vector<fs::path> i2cBuses;
1351
James Feista3c180a2018-08-09 16:06:04 -07001352 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001353 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001354 lg2::error("unable to find i2c devices");
James Feist3cb5fec2018-01-23 14:41:51 -08001355 return 1;
1356 }
James Feist3cb5fec2018-01-23 14:41:51 -08001357
Matt Simmering2447c242023-11-09 14:18:39 -08001358 // check for and load blocklist with initial buses.
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001359 // once busBlocklist is moved to be non global,
1360 // add it here
1361 auto addressBlocklist = loadBlocklist(blocklistPath);
Patrick Venture11f1ff42019-08-01 10:42:12 -07001362
Vijay Khemka065f6d92018-12-18 10:37:47 -08001363 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001364
James Feist6ebf9de2018-05-15 15:01:17 -07001365 // this is a map with keys of pair(bus number, address) and values of
1366 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001367 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001368 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1369 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001370
James Feist9eb0b582018-04-27 12:15:46 -07001371 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1372 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1373 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001374
Kumar Thangavel41a90512021-11-24 15:44:20 +05301375 iface->register_method("ReScan", [&]() {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301376 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001377 addressBlocklist, objServer);
Kumar Thangavel41a90512021-11-24 15:44:20 +05301378 });
James Feist2a9d6db2018-04-27 15:48:28 -07001379
krishnar4213ee212022-11-11 15:39:30 +05301380 iface->register_method("ReScanBus", [&](uint16_t bus) {
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301381 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001382 powerIsOn, addressBlocklist, objServer);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001383 });
1384
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001385 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001386
Patrick Williamsb7077432024-08-16 15:22:21 -04001387 iface->register_method(
1388 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1389 const std::vector<uint8_t>& data) {
1390 if (!writeFRU(bus, address, data))
1391 {
1392 throw std::invalid_argument("Invalid Arguments.");
1393 return;
1394 }
1395 // schedule rescan on success
1396 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001397 powerIsOn, addressBlocklist, objServer);
Patrick Williamsb7077432024-08-16 15:22:21 -04001398 });
James Feist9eb0b582018-04-27 12:15:46 -07001399 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001400
Patrick Williams2af39222022-07-22 19:26:56 -05001401 std::function<void(sdbusplus::message_t & message)> eventHandler =
1402 [&](sdbusplus::message_t& message) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001403 std::string objectName;
1404 boost::container::flat_map<
1405 std::string,
1406 std::variant<std::string, bool, int64_t, uint64_t, double>>
1407 values;
1408 message.read(objectName, values);
1409 auto findState = values.find("CurrentHostState");
1410 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001411 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001412 if (std::get<std::string>(findState->second) ==
1413 "xyz.openbmc_project.State.Host.HostState.Running")
1414 {
1415 powerIsOn = true;
1416 }
James Feist0eeb79c2019-10-09 13:35:29 -07001417 }
James Feist6ebf9de2018-05-15 15:01:17 -07001418
Patrick Williamsb7077432024-08-16 15:22:21 -04001419 if (powerIsOn)
1420 {
1421 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001422 powerIsOn, addressBlocklist, objServer);
Patrick Williamsb7077432024-08-16 15:22:21 -04001423 }
1424 };
James Feist9eb0b582018-04-27 12:15:46 -07001425
Patrick Williams2af39222022-07-22 19:26:56 -05001426 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1427 static_cast<sdbusplus::bus_t&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001428 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001429 "openbmc_project/state/"
1430 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001431 eventHandler);
1432
James Feist4131aea2018-03-09 09:47:30 -08001433 int fd = inotify_init();
Ed Tanous07d467b2021-02-23 14:48:37 -08001434 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
Ed Tanous3013fb42022-07-09 08:27:06 -07001435 std::array<char, 4096> readBuffer{};
James Feist4131aea2018-03-09 09:47:30 -08001436 // monitor for new i2c devices
1437 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1438 std::function<void(const boost::system::error_code, std::size_t)>
Patrick Williamsb9dd7f82023-10-20 11:20:11 -05001439 watchI2cBusses = [&](const boost::system::error_code& ec,
1440 std::size_t bytesTransferred) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001441 if (ec)
James Feist4131aea2018-03-09 09:47:30 -08001442 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001443 lg2::info("Callback Error {ERR}", "ERR", ec.message());
Patrick Williamsb7077432024-08-16 15:22:21 -04001444 return;
1445 }
1446 size_t index = 0;
1447 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1448 {
1449 const char* p = &readBuffer[index];
1450 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1451 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1452 switch (iEvent->mask)
Ed Tanousfc171422024-04-04 17:18:16 -07001453 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001454 case IN_CREATE:
1455 case IN_MOVED_TO:
1456 case IN_DELETE:
Patrick Williamsdf190612023-05-10 07:51:34 -05001457 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001458 std::string_view name(&iEvent->name[0], iEvent->len);
George Liu164af2f2025-08-21 17:16:31 +08001459 if (name.starts_with("i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001460 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001461 int bus = busStrToInt(name);
1462 if (bus < 0)
1463 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001464 lg2::error("Could not parse bus {BUS}", "BUS",
1465 name);
Patrick Williamsb7077432024-08-16 15:22:21 -04001466 continue;
1467 }
1468 int rootBus = getRootBus(bus);
1469 if (rootBus >= 0)
1470 {
1471 rescanOneBus(busMap,
1472 static_cast<uint16_t>(rootBus),
1473 dbusInterfaceMap, false,
1474 unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001475 addressBlocklist, objServer);
Patrick Williamsb7077432024-08-16 15:22:21 -04001476 }
1477 rescanOneBus(busMap, static_cast<uint16_t>(bus),
Kumar Thangavel41a90512021-11-24 15:44:20 +05301478 dbusInterfaceMap, false,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301479 unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001480 addressBlocklist, objServer);
James Feist9eb0b582018-04-27 12:15:46 -07001481 }
Patrick Williamsdf190612023-05-10 07:51:34 -05001482 }
Ed Tanousfc171422024-04-04 17:18:16 -07001483 break;
Patrick Williamsb7077432024-08-16 15:22:21 -04001484 default:
1485 break;
1486 }
1487 index += sizeof(inotify_event) + iEvent->len;
James Feist4131aea2018-03-09 09:47:30 -08001488 }
James Feist6ebf9de2018-05-15 15:01:17 -07001489
Patrick Williamsb7077432024-08-16 15:22:21 -04001490 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1491 watchI2cBusses);
1492 };
James Feist4131aea2018-03-09 09:47:30 -08001493
1494 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001495 // run the initial scan
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301496 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
Marc Olberdingcefe4bb2025-09-02 15:15:21 -07001497 addressBlocklist, objServer);
James Feist918e18c2018-02-13 15:51:07 -08001498
James Feist3cb5fec2018-01-23 14:41:51 -08001499 io.run();
1500 return 0;
1501}