blob: 9b13a2c8712f404aee761894657622aecaa791c2 [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>
James Feist3cb5fec2018-01-23 14:41:51 -080029#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070030#include <limits>
Andrew Jefferya9c58922021-06-01 09:28:59 +093031#include <map>
Bonnie Lobfda2c42022-10-26 16:50:54 +080032#include <optional>
James Feist3f8a2782018-02-12 09:24:42 -080033#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070034#include <set>
35#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070036#include <string>
James Feist3b860982018-10-02 14:34:07 -070037#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080038#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080039#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070040#include <vector>
James Feist3b860982018-10-02 14:34:07 -070041
James Feist8c505da2020-05-28 10:06:33 -070042extern "C"
43{
James Feist3b860982018-10-02 14:34:07 -070044#include <i2c/smbus.h>
45#include <linux/i2c-dev.h>
46}
James Feist3cb5fec2018-01-23 14:41:51 -080047
Ed Tanous072e25d2018-12-16 21:45:20 -080048namespace fs = std::filesystem;
Ed Tanous07d467b2021-02-23 14:48:37 -080049constexpr size_t maxFruSize = 512;
50constexpr size_t maxEepromPageIndex = 255;
ankita prasad7329a222023-07-07 09:18:10 +000051constexpr size_t busTimeoutSeconds = 10;
James Feist3cb5fec2018-01-23 14:41:51 -080052
Matt Simmering2447c242023-11-09 14:18:39 -080053constexpr const char* blocklistPath = PACKAGE_DIR "blacklist.json";
Patrick Venture11f1ff42019-08-01 10:42:12 -070054
Ed Tanous07d467b2021-02-23 14:48:37 -080055const static constexpr char* baseboardFruLocation =
James Feist3cb5fec2018-01-23 14:41:51 -080056 "/etc/fru/baseboard.fru.bin";
57
Ed Tanous07d467b2021-02-23 14:48:37 -080058const static constexpr char* i2CDevLocation = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080059
Vu Phamdac2dfc2024-11-05 12:20:42 -060060constexpr const char* fruDevice16BitDetectMode = FRU_DEVICE_16BITDETECTMODE;
61
Ed Tanousfc171422024-04-04 17:18:16 -070062// TODO Refactor these to not be globals
63// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
Bonnie Lobfda2c42022-10-26 16:50:54 +080064static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
Matt Simmering2447c242023-11-09 14:18:39 -080065 busBlocklist;
James Feist6ebf9de2018-05-15 15:01:17 -070066struct FindDevicesWithCallback;
67
James Feist8a983922019-10-24 17:11:56 -070068static boost::container::flat_map<
69 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
70 foundDevices;
71
James Feist7972bb92019-11-13 15:59:24 -080072static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +000073static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
James Feist7972bb92019-11-13 15:59:24 -080074
Ed Tanous34c3e012023-03-06 13:42:00 -080075boost::asio::io_context io;
Ed Tanousfc171422024-04-04 17:18:16 -070076// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
James Feist5cb06082019-10-24 17:11:13 -070077
Andrei Kartashev2f0de172020-08-13 14:29:40 +030078bool updateFRUProperty(
Ed Tanous3013fb42022-07-09 08:27:06 -070079 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -080080 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +053081 boost::container::flat_map<
82 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +053083 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -080084 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +053085 sdbusplus::asio::object_server& objServer,
86 std::shared_ptr<sdbusplus::asio::connection>& systemBus);
Patrick Venturebaba7672019-10-26 09:26:41 -070087
Patrick Venturec50e1ff2019-08-06 10:22:28 -070088// Given a bus/address, produce the path in sysfs for an eeprom.
89static std::string getEepromPath(size_t bus, size_t address)
90{
91 std::stringstream output;
92 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
93 << std::setfill('0') << std::setw(4) << std::hex << address
94 << "/eeprom";
95 return output.str();
96}
97
98static bool hasEepromFile(size_t bus, size_t address)
99{
100 auto path = getEepromPath(bus, address);
101 try
102 {
103 return fs::exists(path);
104 }
105 catch (...)
106 {
107 return false;
108 }
109}
110
Zev Weiss309c0b12022-02-25 01:44:12 +0000111static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700112{
113 auto result = lseek(fd, offset, SEEK_SET);
114 if (result < 0)
115 {
116 std::cerr << "failed to seek\n";
117 return -1;
118 }
119
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700120 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700121}
122
Ed Tanous3013fb42022-07-09 08:27:06 -0700123static int busStrToInt(const std::string_view busName)
James Feist5d7f4692020-06-17 18:22:33 -0700124{
Ed Tanous07d467b2021-02-23 14:48:37 -0800125 auto findBus = busName.rfind('-');
James Feist5d7f4692020-06-17 18:22:33 -0700126 if (findBus == std::string::npos)
127 {
128 return -1;
129 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700130 std::string_view num = busName.substr(findBus + 1);
131 int val = 0;
132 std::from_chars(num.data(), num.data() + num.size(), val);
133 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 {
354 std::cerr << "Unable to open eeprom file: " << path << "\n";
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 {
386 std::cerr << "directory_iterator err " << ec.message() << "\n";
387 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 {
400 std::cerr << "regex didn't capture\n";
401 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,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530442 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800443{
James Feist26c27ad2018-07-25 15:09:40 -0700444 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700445 // NOTE: When reading the devices raw on the bus, it can interfere with
446 // the driver's ability to operate, therefore read eeproms first before
447 // scanning for devices without drivers. Several experiments were run
448 // and it was determined that if there were any devices on the bus
449 // before the eeprom was hit and read, the eeprom driver wouldn't open
450 // while the bus device was open. An experiment was not performed to see
451 // if this issue was resolved if the i2c bus device was closed, but
452 // hexdumps of the eeprom later were successful.
453
454 // Scan for i2c eeproms loaded on this bus.
Bonnie Lobfda2c42022-10-26 16:50:54 +0800455 std::set<size_t> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800456 std::set<size_t>& failedItems = failedAddresses[bus];
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000457 std::set<size_t>& foundItems = fruAddresses[bus];
458 foundItems.clear();
James Feist7972bb92019-11-13 15:59:24 -0800459
Matt Simmering2447c242023-11-09 14:18:39 -0800460 auto busFind = busBlocklist.find(bus);
461 if (busFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800462 {
463 if (busFind->second != std::nullopt)
464 {
465 for (const auto& address : *(busFind->second))
466 {
467 skipList.insert(address);
468 }
469 }
470 }
471
James Feist7972bb92019-11-13 15:59:24 -0800472 std::set<size_t>* rootFailures = nullptr;
473 int rootBus = getRootBus(bus);
474
475 if (rootBus >= 0)
476 {
Matt Simmering2447c242023-11-09 14:18:39 -0800477 auto rootBusFind = busBlocklist.find(rootBus);
478 if (rootBusFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800479 {
480 if (rootBusFind->second != std::nullopt)
481 {
482 for (const auto& rootAddress : *(rootBusFind->second))
483 {
484 skipList.insert(rootAddress);
485 }
486 }
487 }
James Feist7972bb92019-11-13 15:59:24 -0800488 rootFailures = &(failedAddresses[rootBus]);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000489 foundItems = fruAddresses[rootBus];
James Feist7972bb92019-11-13 15:59:24 -0800490 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700491
Matt Simmering2447c242023-11-09 14:18:39 -0800492 constexpr int startSkipTargetAddr = 0;
493 constexpr int endSkipTargetAddr = 12;
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530494
James Feist26c27ad2018-07-25 15:09:40 -0700495 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800496 {
Patrick Williams64599932025-05-14 07:24:20 -0400497 if (foundItems.contains(ii))
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000498 {
499 continue;
500 }
Patrick Williams64599932025-05-14 07:24:20 -0400501 if (skipList.contains(ii))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700502 {
503 continue;
504 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530505 // skipping since no device is present in this range
Matt Simmering2447c242023-11-09 14:18:39 -0800506 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530507 {
508 continue;
509 }
Matt Simmering2447c242023-11-09 14:18:39 -0800510 // Set target address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530511 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800512 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300513 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700514 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700515 continue;
516 }
517 // probe
Ed Tanous07d467b2021-02-23 14:48:37 -0800518 if (i2c_smbus_read_byte(file) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700519 {
520 continue;
521 }
James Feist3cb5fec2018-01-23 14:41:51 -0800522
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200523 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
524 "ADDR", ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800525
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530526 makeProbeInterface(bus, ii, objServer);
James Feist8a983922019-10-24 17:11:56 -0700527
Patrick Williams64599932025-05-14 07:24:20 -0400528 if (failedItems.contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800529 {
530 // if we failed to read it once, unlikely we can read it later
531 continue;
532 }
533
534 if (rootFailures != nullptr)
535 {
Patrick Williams64599932025-05-14 07:24:20 -0400536 if (rootFailures->contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800537 {
538 continue;
539 }
540 }
541
Vijay Khemka2d681f62018-11-06 15:51:00 -0800542 /* Check for Device type if it is 8 bit or 16 bit */
Vu Phamdac2dfc2024-11-05 12:20:42 -0600543 std::optional<bool> is16Bit = isDevice16Bit(file, ii);
Zev Weiss309c0b12022-02-25 01:44:12 +0000544 if (!is16Bit.has_value())
Vijay Khemka2d681f62018-11-06 15:51:00 -0800545 {
546 std::cerr << "failed to read bus " << bus << " address " << ii
547 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700548 if (powerIsOn)
549 {
550 failedItems.insert(ii);
551 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800552 continue;
553 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000554 bool is16BitBool{*is16Bit};
Vijay Khemka2d681f62018-11-06 15:51:00 -0800555
Patrick Williamsb7077432024-08-16 15:22:21 -0400556 auto readFunc = [is16BitBool, file,
557 ii](off_t offset, size_t length, uint8_t* outbuf) {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200558 return readData(is16BitBool, false, file, ii, offset, length,
559 outbuf);
Zev Weiss309c0b12022-02-25 01:44:12 +0000560 };
561 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400562 std::string errorMessage =
563 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200564 std::pair<std::vector<uint8_t>, bool> pair =
565 readFRUContents(reader, errorMessage);
566 const bool foundHeader = pair.second;
567
568 if (!foundHeader && !is16BitBool)
569 {
570 // certain FRU eeproms require bytewise reading.
571 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
572
Patrick Williamsb7077432024-08-16 15:22:21 -0400573 auto readFunc =
574 [is16BitBool, file,
575 ii](off_t offset, size_t length, uint8_t* outbuf) {
576 return readData(is16BitBool, true, file, ii, offset,
577 length, outbuf);
578 };
Marvin Drees2b3ed302023-04-14 16:35:14 +0200579 FRUReader readerBytewise(std::move(readFunc));
580 pair = readFRUContents(readerBytewise, errorMessage);
581 }
582
583 if (pair.first.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700584 {
James Feist26c27ad2018-07-25 15:09:40 -0700585 continue;
586 }
James Feist26c27ad2018-07-25 15:09:40 -0700587
Marvin Drees2b3ed302023-04-14 16:35:14 +0200588 devices->emplace(ii, pair.first);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000589 fruAddresses[bus].insert(ii);
James Feist3cb5fec2018-01-23 14:41:51 -0800590 }
James Feist26c27ad2018-07-25 15:09:40 -0700591 return 1;
592 });
593 std::future_status status =
594 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
595 if (status == std::future_status::timeout)
596 {
597 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700598 if (powerIsOn)
599 {
Matt Simmering2447c242023-11-09 14:18:39 -0800600 busBlocklist[bus] = std::nullopt;
James Feistcb5661d2020-06-12 15:05:01 -0700601 }
James Feist444830e2019-04-05 08:38:16 -0700602 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700603 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800604 }
605
James Feist444830e2019-04-05 08:38:16 -0700606 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700607 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800608}
609
Matt Simmering2447c242023-11-09 14:18:39 -0800610void loadBlocklist(const char* path)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700611{
Matt Simmering2447c242023-11-09 14:18:39 -0800612 std::ifstream blocklistStream(path);
613 if (!blocklistStream.good())
Patrick Venture11f1ff42019-08-01 10:42:12 -0700614 {
615 // File is optional.
Matt Simmering2447c242023-11-09 14:18:39 -0800616 std::cerr << "Cannot open blocklist file.\n\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700617 return;
618 }
619
Patrick Williamsb7077432024-08-16 15:22:21 -0400620 nlohmann::json data =
621 nlohmann::json::parse(blocklistStream, nullptr, false);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700622 if (data.is_discarded())
623 {
Matt Simmering2447c242023-11-09 14:18:39 -0800624 std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
Patrick Venture11f1ff42019-08-01 10:42:12 -0700625 "exiting\n";
626 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700627 }
628
629 // It's expected to have at least one field, "buses" that is an array of the
630 // buses by integer. Allow for future options to exclude further aspects,
631 // such as specific addresses or ranges.
632 if (data.type() != nlohmann::json::value_t::object)
633 {
Matt Simmering2447c242023-11-09 14:18:39 -0800634 std::cerr << "Illegal blocklist, expected to read dictionary\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700635 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700636 }
637
638 // If buses field is missing, that's fine.
639 if (data.count("buses") == 1)
640 {
641 // Parse the buses array after a little validation.
642 auto buses = data.at("buses");
643 if (buses.type() != nlohmann::json::value_t::array)
644 {
645 // Buses field present but invalid, therefore this is an error.
Matt Simmering2447c242023-11-09 14:18:39 -0800646 std::cerr << "Invalid contents for blocklist buses field\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700647 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700648 }
649
650 // Catch exception here for type mis-match.
651 try
652 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800653 for (const auto& busIterator : buses)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700654 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800655 // If bus and addresses field are missing, that's fine.
656 if (busIterator.contains("bus") &&
657 busIterator.contains("addresses"))
658 {
659 auto busData = busIterator.at("bus");
660 auto bus = busData.get<size_t>();
661
662 auto addressData = busIterator.at("addresses");
663 auto addresses =
664 addressData.get<std::set<std::string_view>>();
665
Ed Tanousfc171422024-04-04 17:18:16 -0700666 auto& block = busBlocklist[bus].emplace();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800667 for (const auto& address : addresses)
668 {
669 size_t addressInt = 0;
670 std::from_chars(address.begin() + 2, address.end(),
671 addressInt, 16);
Ed Tanousfc171422024-04-04 17:18:16 -0700672 block.insert(addressInt);
Bonnie Lobfda2c42022-10-26 16:50:54 +0800673 }
674 }
675 else
676 {
Matt Simmering2447c242023-11-09 14:18:39 -0800677 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
Bonnie Lobfda2c42022-10-26 16:50:54 +0800678 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700679 }
680 }
681 catch (const nlohmann::detail::type_error& e)
682 {
683 // Type mis-match is a critical error.
684 std::cerr << "Invalid bus type: " << e.what() << "\n";
685 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700686 }
687 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700688}
689
Ed Tanous07d467b2021-02-23 14:48:37 -0800690static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800691 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530692 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800693{
Ed Tanous3013fb42022-07-09 08:27:06 -0700694 for (const auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800695 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700696 int bus = busStrToInt(i2cBus.string());
James Feist0c3980a2019-12-19 11:09:27 -0800697
James Feist5d7f4692020-06-17 18:22:33 -0700698 if (bus < 0)
699 {
700 std::cerr << "Cannot translate " << i2cBus << " to int\n";
701 continue;
702 }
Matt Simmering2447c242023-11-09 14:18:39 -0800703 auto busFind = busBlocklist.find(bus);
704 if (busFind != busBlocklist.end())
James Feist444830e2019-04-05 08:38:16 -0700705 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800706 if (busFind->second == std::nullopt)
707 {
708 continue; // Skip blocked busses.
709 }
James Feist444830e2019-04-05 08:38:16 -0700710 }
James Feist0c3980a2019-12-19 11:09:27 -0800711 int rootBus = getRootBus(bus);
Matt Simmering2447c242023-11-09 14:18:39 -0800712 auto rootBusFind = busBlocklist.find(rootBus);
713 if (rootBusFind != busBlocklist.end())
James Feist0c3980a2019-12-19 11:09:27 -0800714 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800715 if (rootBusFind->second == std::nullopt)
716 {
717 continue;
718 }
James Feist0c3980a2019-12-19 11:09:27 -0800719 }
720
James Feist3cb5fec2018-01-23 14:41:51 -0800721 auto file = open(i2cBus.c_str(), O_RDWR);
722 if (file < 0)
723 {
724 std::cerr << "unable to open i2c device " << i2cBus.string()
725 << "\n";
726 continue;
727 }
728 unsigned long funcs = 0;
729
730 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
731 {
732 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700733 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800734 << bus << "\n";
Zhikui Renc02d8cb2021-06-28 16:56:08 -0700735 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800736 continue;
737 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700738 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
739 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
James Feist3cb5fec2018-01-23 14:41:51 -0800740 {
741 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
742 << bus << "\n";
George Liu913d07d2024-12-09 19:16:30 +0800743 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800744 continue;
745 }
James Feist98132792019-07-09 13:29:09 -0700746 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800747 device = std::make_shared<DeviceMap>();
748
Nikhil Potaded8884f12019-03-27 13:27:13 -0700749 // i2cdetect by default uses the range 0x03 to 0x77, as
750 // this is what we have tested with, use this range. Could be
751 // changed in future.
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200752 lg2::debug("Scanning bus {BUS}", "BUS", bus);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700753
754 // fd is closed in this function in case the bus locks up
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530755 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700756
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200757 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
James Feist3cb5fec2018-01-23 14:41:51 -0800758 }
James Feist3cb5fec2018-01-23 14:41:51 -0800759}
760
James Feist6ebf9de2018-05-15 15:01:17 -0700761// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700762struct FindDevicesWithCallback :
763 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700764{
James Feista465ccc2019-02-08 12:51:01 -0800765 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800766 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530767 sdbusplus::asio::object_server& objServer,
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800768 std::function<void()>&& callback) :
Patrick Williamsb7077432024-08-16 15:22:21 -0400769 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
770 _objServer(objServer), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700771 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700772 ~FindDevicesWithCallback()
773 {
774 _callback();
775 }
776 void run()
777 {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530778 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
James Feist6ebf9de2018-05-15 15:01:17 -0700779 }
780
James Feista465ccc2019-02-08 12:51:01 -0800781 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800782 BusMap& _busMap;
Jonathan Doman2418a612022-02-14 18:20:58 -0800783 const bool& _powerIsOn;
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530784 sdbusplus::asio::object_server& _objServer;
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800785 std::function<void()> _callback;
James Feist6ebf9de2018-05-15 15:01:17 -0700786};
787
Ed Tanous07d467b2021-02-23 14:48:37 -0800788void addFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300789 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800790 boost::container::flat_map<
791 std::pair<size_t, size_t>,
792 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +0530793 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
Jonathan Doman2418a612022-02-14 18:20:58 -0800794 const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530795 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist3cb5fec2018-01-23 14:41:51 -0800796{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300797 boost::container::flat_map<std::string, std::string> formattedFRU;
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530798
799 std::optional<std::string> optionalProductName = getProductName(
800 device, formattedFRU, bus, address, unknownBusObjectCount);
801 if (!optionalProductName)
James Feist3cb5fec2018-01-23 14:41:51 -0800802 {
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530803 std::cerr << "getProductName failed. product name is empty.\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800804 return;
805 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700806
Patrick Williamsb7077432024-08-16 15:22:21 -0400807 std::string productName =
808 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
James Feist3cb5fec2018-01-23 14:41:51 -0800809
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530810 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
811 if (index.has_value())
James Feist918e18c2018-02-13 15:51:07 -0800812 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530813 productName += "_";
814 productName += std::to_string(++(*index));
James Feist918e18c2018-02-13 15:51:07 -0800815 }
James Feist3cb5fec2018-01-23 14:41:51 -0800816
James Feist9eb0b582018-04-27 12:15:46 -0700817 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
818 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
819 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
820
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300821 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800822 {
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700823 std::regex_replace(property.second.begin(), property.second.begin(),
Ed Tanous07d467b2021-02-23 14:48:37 -0800824 property.second.end(), nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530825 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -0700826 {
827 continue;
828 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400829 std::string key =
830 std::regex_replace(property.first, nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530831
832 if (property.first == "PRODUCT_ASSET_TAG")
833 {
834 std::string propertyName = property.first;
835 iface->register_property(
836 key, property.second + '\0',
Kumar Thangavel41a90512021-11-24 15:44:20 +0530837 [bus, address, propertyName, &dbusInterfaceMap,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530838 &unknownBusObjectCount, &powerIsOn, &objServer,
839 &systemBus](const std::string& req, std::string& resp) {
Patrick Williamsb7077432024-08-16 15:22:21 -0400840 if (strcmp(req.c_str(), resp.c_str()) != 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +0530841 {
Patrick Williamsb7077432024-08-16 15:22:21 -0400842 // call the method which will update
843 if (updateFRUProperty(req, bus, address, propertyName,
844 dbusInterfaceMap,
845 unknownBusObjectCount, powerIsOn,
846 objServer, systemBus))
847 {
848 resp = req;
849 }
850 else
851 {
852 throw std::invalid_argument(
853 "FRU property update failed.");
854 }
Joshi-Mansid73b7442020-03-27 19:10:21 +0530855 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400856 return 1;
857 });
Joshi-Mansid73b7442020-03-27 19:10:21 +0530858 }
859 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -0700860 {
861 std::cerr << "illegal key: " << key << "\n";
862 }
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200863 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
864 property.first, "SECOND", property.second);
James Feist3cb5fec2018-01-23 14:41:51 -0800865 }
James Feist2a9d6db2018-04-27 15:48:28 -0700866
867 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700868 iface->register_property("BUS", bus);
869 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700870
James Feist9eb0b582018-04-27 12:15:46 -0700871 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800872}
873
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300874static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800875{
876 // try to read baseboard fru from file
Ed Tanous07d467b2021-02-23 14:48:37 -0800877 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300878 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -0800879 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300880 baseboardFRUFile.seekg(0, std::ios_base::end);
881 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
882 baseboardFRU.resize(fileSize);
883 baseboardFRUFile.seekg(0, std::ios_base::beg);
Ed Tanous3013fb42022-07-09 08:27:06 -0700884 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
885 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
886 baseboardFRUFile.read(charOffset, fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -0800887 }
888 else
889 {
890 return false;
891 }
892 return true;
893}
894
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300895bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700896{
897 boost::container::flat_map<std::string, std::string> tmp;
Ed Tanous07d467b2021-02-23 14:48:37 -0800898 if (fru.size() > maxFruSize)
James Feistb49ffc32018-05-02 11:10:43 -0700899 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300900 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700901 return false;
902 }
903 // verify legal fru by running it through fru parsing logic
Michael Shen0961b112022-02-22 11:06:33 +0800904 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -0700905 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300906 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700907 return false;
908 }
909 // baseboard fru
910 if (bus == 0 && address == 0)
911 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800912 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
James Feistb49ffc32018-05-02 11:10:43 -0700913 if (!file.good())
914 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800915 std::cerr << "Error opening file " << baseboardFruLocation << "\n";
James Feistddb78302018-09-06 11:45:42 -0700916 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700917 return false;
918 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700919 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
920 const char* charOffset = reinterpret_cast<const char*>(fru.data());
921 file.write(charOffset, fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700922 return file.good();
923 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800924
925 if (hasEepromFile(bus, address))
James Feistb49ffc32018-05-02 11:10:43 -0700926 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800927 auto path = getEepromPath(bus, address);
Naresh Solanki41ee1802024-11-09 01:44:46 +0530928 off_t offset = 0;
929
Ed Tanous07d467b2021-02-23 14:48:37 -0800930 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
931 if (eeprom < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700932 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800933 std::cerr << "unable to open i2c device " << path << "\n";
934 throw DBusInternalError();
935 return false;
936 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700937
Naresh Solanki41ee1802024-11-09 01:44:46 +0530938 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
939 std::string errorMessage = "eeprom at " + std::to_string(bus) +
940 " address " + std::to_string(address);
941 auto readFunc = [eeprom](off_t offset, size_t length, uint8_t* outbuf) {
942 return readFromEeprom(eeprom, offset, length, outbuf);
943 };
944 FRUReader reader(std::move(readFunc));
945
946 if (!findFRUHeader(reader, errorMessage, blockData, offset))
947 {
948 offset = 0;
949 }
950
951 if (lseek(eeprom, offset, SEEK_SET) < 0)
952 {
953 std::cerr << "Unable to seek to offset " << offset
954 << " in device: " << path << "\n";
955 close(eeprom);
956 throw DBusInternalError();
957 }
958
Ed Tanous07d467b2021-02-23 14:48:37 -0800959 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
960 if (writtenBytes < 0)
961 {
962 std::cerr << "unable to write to i2c device " << path << "\n";
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700963 close(eeprom);
James Feistddb78302018-09-06 11:45:42 -0700964 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700965 return false;
966 }
967
Ed Tanous07d467b2021-02-23 14:48:37 -0800968 close(eeprom);
James Feistb49ffc32018-05-02 11:10:43 -0700969 return true;
970 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800971
972 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
973
974 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
975 if (file < 0)
976 {
977 std::cerr << "unable to open i2c device " << i2cBus << "\n";
978 throw DBusInternalError();
979 return false;
980 }
981 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
982 {
983 std::cerr << "unable to set device address\n";
984 close(file);
985 throw DBusInternalError();
986 return false;
987 }
988
989 constexpr const size_t retryMax = 2;
990 uint16_t index = 0;
991 size_t retries = retryMax;
992 while (index < fru.size())
993 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700994 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
Ed Tanous07d467b2021-02-23 14:48:37 -0800995 (retries == retryMax))
996 {
997 // The 4K EEPROM only uses the A2 and A1 device address bits
998 // with the third bit being a memory page address bit.
999 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1000 {
1001 std::cerr << "unable to set device address\n";
1002 close(file);
1003 throw DBusInternalError();
1004 return false;
1005 }
1006 }
1007
1008 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1009 fru[index]) < 0)
1010 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001011 if ((retries--) == 0U)
Ed Tanous07d467b2021-02-23 14:48:37 -08001012 {
1013 std::cerr << "error writing fru: " << strerror(errno) << "\n";
1014 close(file);
1015 throw DBusInternalError();
1016 return false;
1017 }
1018 }
1019 else
1020 {
1021 retries = retryMax;
1022 index++;
1023 }
1024 // most eeproms require 5-10ms between writes
1025 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1026 }
1027 close(file);
1028 return true;
James Feistb49ffc32018-05-02 11:10:43 -07001029}
1030
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001031void rescanOneBus(
krishnar4213ee212022-11-11 15:39:30 +05301032 BusMap& busmap, uint16_t busNum,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001033 boost::container::flat_map<
1034 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001035 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001036 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301037 sdbusplus::asio::object_server& objServer,
1038 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001039{
Yong Li6fdfac02023-10-30 11:21:30 +08001040 for (auto device = foundDevices.begin(); device != foundDevices.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001041 {
Yong Li6fdfac02023-10-30 11:21:30 +08001042 if (device->first.first == static_cast<size_t>(busNum))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001043 {
Yong Li6fdfac02023-10-30 11:21:30 +08001044 objServer.remove_interface(device->second);
1045 device = foundDevices.erase(device);
1046 }
1047 else
1048 {
1049 device++;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001050 }
1051 }
1052
James Feist5d7f4692020-06-17 18:22:33 -07001053 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1054 if (!fs::exists(busPath))
1055 {
1056 if (dbusCall)
1057 {
1058 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1059 << "\n";
1060 throw std::invalid_argument("Invalid Bus.");
1061 }
1062 return;
1063 }
1064
1065 std::vector<fs::path> i2cBuses;
1066 i2cBuses.emplace_back(busPath);
1067
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001068 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301069 i2cBuses, busmap, powerIsOn, objServer,
1070 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1071 &objServer, &systemBus]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001072 for (auto busIface = dbusInterfaceMap.begin();
1073 busIface != dbusInterfaceMap.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001074 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001075 if (busIface->first.first == static_cast<size_t>(busNum))
1076 {
1077 objServer.remove_interface(busIface->second);
1078 busIface = dbusInterfaceMap.erase(busIface);
1079 }
1080 else
1081 {
1082 busIface++;
1083 }
Yong Li6fdfac02023-10-30 11:21:30 +08001084 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001085 auto found = busmap.find(busNum);
1086 if (found == busmap.end() || found->second == nullptr)
Yong Li6fdfac02023-10-30 11:21:30 +08001087 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001088 return;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001089 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001090 for (auto& device : *(found->second))
1091 {
1092 addFruObjectToDbus(device.second, dbusInterfaceMap,
1093 static_cast<uint32_t>(busNum), device.first,
1094 unknownBusObjectCount, powerIsOn, objServer,
1095 systemBus);
1096 }
1097 });
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001098 scan->run();
1099}
1100
James Feist9eb0b582018-04-27 12:15:46 -07001101void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001102 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001103 boost::container::flat_map<
1104 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301105 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001106 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301107 sdbusplus::asio::object_server& objServer,
1108 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist918e18c2018-02-13 15:51:07 -08001109{
Ed Tanousaa497ed2023-02-28 13:43:41 -08001110 static boost::asio::steady_timer timer(io);
Ed Tanousae2d4352025-02-12 15:51:48 -08001111 timer.expires_after(std::chrono::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001112
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001113 // setup an async wait in case we get flooded with requests
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001114 timer.async_wait([&](const boost::system::error_code& ec) {
1115 if (ec == boost::asio::error::operation_aborted)
1116 {
1117 return;
1118 }
1119
1120 if (ec)
1121 {
1122 std::cerr << "Error in timer: " << ec.message() << "\n";
1123 return;
1124 }
1125
James Feist4131aea2018-03-09 09:47:30 -08001126 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001127 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001128
Nikhil Potaded8884f12019-03-27 13:27:13 -07001129 boost::container::flat_map<size_t, fs::path> busPaths;
1130 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001131 {
James Feist4131aea2018-03-09 09:47:30 -08001132 std::cerr << "unable to find i2c devices\n";
1133 return;
James Feist918e18c2018-02-13 15:51:07 -08001134 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001135
Ed Tanous07d467b2021-02-23 14:48:37 -08001136 for (const auto& busPath : busPaths)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001137 {
1138 i2cBuses.emplace_back(busPath.second);
1139 }
James Feist4131aea2018-03-09 09:47:30 -08001140
James Feist98132792019-07-09 13:29:09 -07001141 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001142 for (auto& [pair, interface] : foundDevices)
1143 {
1144 objServer.remove_interface(interface);
1145 }
1146 foundDevices.clear();
1147
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301148 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301149 i2cBuses, busmap, powerIsOn, objServer, [&]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001150 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001151 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001152 objServer.remove_interface(busIface.second);
James Feist6ebf9de2018-05-15 15:01:17 -07001153 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001154
1155 dbusInterfaceMap.clear();
1156 unknownBusObjectCount = 0;
1157
1158 // todo, get this from a more sensable place
1159 std::vector<uint8_t> baseboardFRU;
1160 if (readBaseboardFRU(baseboardFRU))
1161 {
1162 // If no device on i2c bus 0, the insertion will happen.
1163 auto bus0 =
1164 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1165 bus0.first->second->emplace(0, baseboardFRU);
1166 }
1167 for (auto& devicemap : busmap)
1168 {
1169 for (auto& device : *devicemap.second)
1170 {
1171 addFruObjectToDbus(device.second, dbusInterfaceMap,
1172 devicemap.first, device.first,
1173 unknownBusObjectCount, powerIsOn,
1174 objServer, systemBus);
1175 }
1176 }
1177 });
James Feist6ebf9de2018-05-15 15:01:17 -07001178 scan->run();
1179 });
James Feist918e18c2018-02-13 15:51:07 -08001180}
1181
Joshi-Mansid73b7442020-03-27 19:10:21 +05301182// Details with example of Asset Tag Update
1183// To find location of Product Info Area asset tag as per FRU specification
1184// 1. Find product Info area starting offset (*8 - as header will be in
1185// multiple of 8 bytes).
1186// 2. Skip 3 bytes of product info area (like format version, area length,
1187// and language code).
1188// 3. Traverse manufacturer name, product name, product version, & product
1189// serial number, by reading type/length code to reach the Asset Tag.
1190// 4. Update the Asset Tag, reposition the product Info area in multiple of
1191// 8 bytes. Update the Product area length and checksum.
1192
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001193bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301194 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -08001195 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301196 boost::container::flat_map<
1197 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301198 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001199 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301200 sdbusplus::asio::object_server& objServer,
1201 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301202{
1203 size_t updatePropertyReqLen = updatePropertyReq.length();
1204 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1205 {
1206 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001207 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301208 "Invalid Length "
1209 << updatePropertyReqLen << "\n";
1210 return false;
1211 }
1212
1213 std::vector<uint8_t> fruData;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301214
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301215 if (!getFruData(fruData, bus, address))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301216 {
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301217 std::cerr << "Failure getting FRU Data \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301218 return false;
1219 }
1220
Patrick Williamsa41f0142024-12-18 11:22:53 -05001221 struct FruArea fruAreaParams{};
Joshi-Mansid73b7442020-03-27 19:10:21 +05301222
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301223 if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301224 {
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301225 std::cerr << "findFruAreaLocationAndField failed \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301226 return false;
1227 }
1228
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301229 std::vector<uint8_t> restFRUAreaFieldsData;
1230 if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1231 restFRUAreaFieldsData))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301232 {
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301233 std::cerr << "copyRestFRUArea failed \n";
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001234 return false;
1235 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301236
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001237 // Push post update fru areas if any
1238 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001239 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1240 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001241 {
1242 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001243 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301244 if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001245 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1246 {
1247 nextFRUAreaLoc = fruAreaLoc;
1248 }
1249 }
1250 std::vector<uint8_t> restFRUAreasData;
Ed Tanous3013fb42022-07-09 08:27:06 -07001251 if (nextFRUAreaLoc != 0U)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001252 {
1253 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1254 fruData.size() - nextFRUAreaLoc,
1255 std::back_inserter(restFRUAreasData));
1256 }
1257
1258 // check FRU area size
1259 size_t fruAreaDataSize =
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301260 ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1261 restFRUAreaFieldsData.size());
1262 size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001263 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1264 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001265#ifdef ENABLE_FRU_AREA_RESIZE
1266 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1267 // round size to 8-byte blocks
Patrick Williamsb7077432024-08-16 15:22:21 -04001268 newFRUAreaSize =
1269 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1270 size_t newFRUDataSize =
1271 fruData.size() + newFRUAreaSize - fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001272 fruData.resize(newFRUDataSize);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301273 fruAreaParams.size = newFRUAreaSize;
1274 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001275#else
1276 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1277 << " should not be greater than available FRU area size: "
1278 << fruAreaAvailableSize << "\n";
1279 return false;
1280#endif // ENABLE_FRU_AREA_RESIZE
1281 }
1282
Joshi-Mansid73b7442020-03-27 19:10:21 +05301283 // write new requested property field length and data
1284 constexpr uint8_t newTypeLenMask = 0xC0;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301285 fruData[fruAreaParams.updateFieldLoc] =
Joshi-Mansid73b7442020-03-27 19:10:21 +05301286 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301287 fruAreaParams.updateFieldLoc++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301288 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301289 fruData.begin() + fruAreaParams.updateFieldLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301290
1291 // Copy remaining data to main fru area - post updated fru field vector
Patrick Williamsb7077432024-08-16 15:22:21 -04001292 fruAreaParams.restFieldsLoc =
1293 fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1294 size_t fruAreaDataEnd =
1295 fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301296
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001297 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301298 fruData.begin() + fruAreaParams.restFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301299
1300 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001301 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301302 fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301303
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001304#ifdef ENABLE_FRU_AREA_RESIZE
1305 ++nextFRUAreaNewLoc;
Patrick Williamsb7077432024-08-16 15:22:21 -04001306 ssize_t nextFRUAreaOffsetDiff =
1307 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001308 // Append rest FRU Areas if size changed and there were other sections after
1309 // updated one
1310 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1311 {
1312 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1313 fruData.begin() + nextFRUAreaNewLoc);
1314 // Update Common Header
Ed Tanous6e22c872023-02-16 15:19:28 -08001315 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1316 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001317 {
Ed Tanous6e22c872023-02-16 15:19:28 -08001318 unsigned int fruAreaOffsetField =
1319 getHeaderAreaFieldOffset(nextFRUArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001320 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
Ed Tanous6e22c872023-02-16 15:19:28 -08001321 if (curFRUAreaOffset > fruAreaParams.end)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001322 {
1323 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1324 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1325 }
1326 }
1327 // Calculate new checksum
1328 std::vector<uint8_t> headerFRUData;
1329 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1330 size_t checksumVal = calculateChecksum(headerFRUData);
1331 fruData[7] = static_cast<uint8_t>(checksumVal);
1332 // fill zeros if FRU Area size decreased
1333 if (nextFRUAreaOffsetDiff < 0)
1334 {
1335 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1336 restFRUAreasData.size(),
1337 fruData.end(), 0);
1338 }
1339 }
1340#else
1341 // this is to avoid "unused variable" warning
1342 (void)nextFRUAreaNewLoc;
1343#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301344 if (fruData.empty())
1345 {
1346 return false;
1347 }
1348
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001349 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301350 fruData))
1351 {
1352 return false;
1353 }
1354
1355 // Rescan the bus so that GetRawFru dbus-call fetches updated values
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301356 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1357 objServer, systemBus);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301358 return true;
1359}
1360
James Feist98132792019-07-09 13:29:09 -07001361int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001362{
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301363 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1364 sdbusplus::asio::object_server objServer(systemBus);
1365
Kumar Thangavel41a90512021-11-24 15:44:20 +05301366 static size_t unknownBusObjectCount = 0;
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301367 static bool powerIsOn = false;
James Feist3cb5fec2018-01-23 14:41:51 -08001368 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001369 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001370 std::vector<fs::path> i2cBuses;
1371
James Feista3c180a2018-08-09 16:06:04 -07001372 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001373 {
1374 std::cerr << "unable to find i2c devices\n";
1375 return 1;
1376 }
James Feist3cb5fec2018-01-23 14:41:51 -08001377
Matt Simmering2447c242023-11-09 14:18:39 -08001378 // check for and load blocklist with initial buses.
1379 loadBlocklist(blocklistPath);
Patrick Venture11f1ff42019-08-01 10:42:12 -07001380
Vijay Khemka065f6d92018-12-18 10:37:47 -08001381 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001382
James Feist6ebf9de2018-05-15 15:01:17 -07001383 // this is a map with keys of pair(bus number, address) and values of
1384 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001385 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001386 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1387 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001388
James Feist9eb0b582018-04-27 12:15:46 -07001389 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1390 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1391 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001392
Kumar Thangavel41a90512021-11-24 15:44:20 +05301393 iface->register_method("ReScan", [&]() {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301394 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1395 objServer, systemBus);
Kumar Thangavel41a90512021-11-24 15:44:20 +05301396 });
James Feist2a9d6db2018-04-27 15:48:28 -07001397
krishnar4213ee212022-11-11 15:39:30 +05301398 iface->register_method("ReScanBus", [&](uint16_t bus) {
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301399 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301400 powerIsOn, objServer, systemBus);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001401 });
1402
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001403 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001404
Patrick Williamsb7077432024-08-16 15:22:21 -04001405 iface->register_method(
1406 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1407 const std::vector<uint8_t>& data) {
1408 if (!writeFRU(bus, address, data))
1409 {
1410 throw std::invalid_argument("Invalid Arguments.");
1411 return;
1412 }
1413 // schedule rescan on success
1414 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1415 powerIsOn, objServer, systemBus);
1416 });
James Feist9eb0b582018-04-27 12:15:46 -07001417 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001418
Patrick Williams2af39222022-07-22 19:26:56 -05001419 std::function<void(sdbusplus::message_t & message)> eventHandler =
1420 [&](sdbusplus::message_t& message) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001421 std::string objectName;
1422 boost::container::flat_map<
1423 std::string,
1424 std::variant<std::string, bool, int64_t, uint64_t, double>>
1425 values;
1426 message.read(objectName, values);
1427 auto findState = values.find("CurrentHostState");
1428 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001429 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001430 if (std::get<std::string>(findState->second) ==
1431 "xyz.openbmc_project.State.Host.HostState.Running")
1432 {
1433 powerIsOn = true;
1434 }
James Feist0eeb79c2019-10-09 13:35:29 -07001435 }
James Feist6ebf9de2018-05-15 15:01:17 -07001436
Patrick Williamsb7077432024-08-16 15:22:21 -04001437 if (powerIsOn)
1438 {
1439 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1440 powerIsOn, objServer, systemBus);
1441 }
1442 };
James Feist9eb0b582018-04-27 12:15:46 -07001443
Patrick Williams2af39222022-07-22 19:26:56 -05001444 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1445 static_cast<sdbusplus::bus_t&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001446 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001447 "openbmc_project/state/"
1448 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001449 eventHandler);
1450
James Feist4131aea2018-03-09 09:47:30 -08001451 int fd = inotify_init();
Ed Tanous07d467b2021-02-23 14:48:37 -08001452 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
Ed Tanous3013fb42022-07-09 08:27:06 -07001453 std::array<char, 4096> readBuffer{};
James Feist4131aea2018-03-09 09:47:30 -08001454 // monitor for new i2c devices
1455 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1456 std::function<void(const boost::system::error_code, std::size_t)>
Patrick Williamsb9dd7f82023-10-20 11:20:11 -05001457 watchI2cBusses = [&](const boost::system::error_code& ec,
1458 std::size_t bytesTransferred) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001459 if (ec)
James Feist4131aea2018-03-09 09:47:30 -08001460 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001461 std::cout << "Callback Error " << ec << "\n";
1462 return;
1463 }
1464 size_t index = 0;
1465 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1466 {
1467 const char* p = &readBuffer[index];
1468 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1469 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1470 switch (iEvent->mask)
Ed Tanousfc171422024-04-04 17:18:16 -07001471 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001472 case IN_CREATE:
1473 case IN_MOVED_TO:
1474 case IN_DELETE:
Patrick Williamsdf190612023-05-10 07:51:34 -05001475 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001476 std::string_view name(&iEvent->name[0], iEvent->len);
George Liu164af2f2025-08-21 17:16:31 +08001477 if (name.starts_with("i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001478 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001479 int bus = busStrToInt(name);
1480 if (bus < 0)
1481 {
1482 std::cerr
1483 << "Could not parse bus " << name << "\n";
1484 continue;
1485 }
1486 int rootBus = getRootBus(bus);
1487 if (rootBus >= 0)
1488 {
1489 rescanOneBus(busMap,
1490 static_cast<uint16_t>(rootBus),
1491 dbusInterfaceMap, false,
1492 unknownBusObjectCount, powerIsOn,
1493 objServer, systemBus);
1494 }
1495 rescanOneBus(busMap, static_cast<uint16_t>(bus),
Kumar Thangavel41a90512021-11-24 15:44:20 +05301496 dbusInterfaceMap, false,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301497 unknownBusObjectCount, powerIsOn,
1498 objServer, systemBus);
James Feist9eb0b582018-04-27 12:15:46 -07001499 }
Patrick Williamsdf190612023-05-10 07:51:34 -05001500 }
Ed Tanousfc171422024-04-04 17:18:16 -07001501 break;
Patrick Williamsb7077432024-08-16 15:22:21 -04001502 default:
1503 break;
1504 }
1505 index += sizeof(inotify_event) + iEvent->len;
James Feist4131aea2018-03-09 09:47:30 -08001506 }
James Feist6ebf9de2018-05-15 15:01:17 -07001507
Patrick Williamsb7077432024-08-16 15:22:21 -04001508 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1509 watchI2cBusses);
1510 };
James Feist4131aea2018-03-09 09:47:30 -08001511
1512 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001513 // run the initial scan
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301514 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1515 objServer, systemBus);
James Feist918e18c2018-02-13 15:51:07 -08001516
James Feist3cb5fec2018-01-23 14:41:51 -08001517 io.run();
1518 return 0;
1519}