blob: 4bb9418d63a7172c882c0cc38ea0715f2260a052 [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;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400132 bool fullMatch = false;
133 fromCharsWrapper(num, val, fullMatch);
Ed Tanous3013fb42022-07-09 08:27:06 -0700134 return val;
James Feist5d7f4692020-06-17 18:22:33 -0700135}
136
James Feist7972bb92019-11-13 15:59:24 -0800137static int getRootBus(size_t bus)
138{
139 auto ec = std::error_code();
140 auto path = std::filesystem::read_symlink(
Patrick Williamsb7077432024-08-16 15:22:21 -0400141 std::filesystem::path(
142 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"),
James Feist7972bb92019-11-13 15:59:24 -0800143 ec);
144 if (ec)
145 {
146 return -1;
147 }
148
149 std::string filename = path.filename();
Ed Tanous07d467b2021-02-23 14:48:37 -0800150 auto findBus = filename.find('-');
James Feist7972bb92019-11-13 15:59:24 -0800151 if (findBus == std::string::npos)
152 {
153 return -1;
154 }
155 return std::stoi(filename.substr(0, findBus));
156}
157
James Feistc95cb142018-02-26 10:41:42 -0800158static bool isMuxBus(size_t bus)
159{
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700160 auto ec = std::error_code();
161 auto isSymlink =
162 is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
163 std::to_string(bus) + "/mux_device"),
164 ec);
165 return (!ec && isSymlink);
James Feistc95cb142018-02-26 10:41:42 -0800166}
167
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530168static void makeProbeInterface(size_t bus, size_t address,
169 sdbusplus::asio::object_server& objServer)
James Feist8a983922019-10-24 17:11:56 -0700170{
171 if (isMuxBus(bus))
172 {
173 return; // the mux buses are random, no need to publish
174 }
175 auto [it, success] = foundDevices.emplace(
176 std::make_pair(bus, address),
177 objServer.add_interface(
178 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
179 std::to_string(address),
180 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
181 if (!success)
182 {
183 return; // already added
184 }
185 it->second->register_property("Bus", bus);
186 it->second->register_property("Address", address);
187 it->second->initialize();
188}
189
Matt Simmering2447c242023-11-09 14:18:39 -0800190// Issue an I2C transaction to first write to_target_buf_len bytes,then read
191// from_target_buf_len bytes.
Patrick Williamsb7077432024-08-16 15:22:21 -0400192static int i2cSmbusWriteThenRead(
193 int file, uint16_t address, uint8_t* toTargetBuf, uint8_t toTargetBufLen,
194 uint8_t* fromTargetBuf, uint8_t fromTargetBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800195{
Matt Simmering2447c242023-11-09 14:18:39 -0800196 if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
197 fromTargetBuf == nullptr || fromTargetBufLen == 0)
Xiang Liu2801a702020-01-20 14:29:34 -0800198 {
199 return -1;
200 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800201
Ed Tanous3013fb42022-07-09 08:27:06 -0700202 constexpr size_t smbusWriteThenReadMsgCount = 2;
203 std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
Patrick Williamsa41f0142024-12-18 11:22:53 -0500204 struct i2c_rdwr_ioctl_data rdwr{};
Xiang Liu2801a702020-01-20 14:29:34 -0800205
206 msgs[0].addr = address;
207 msgs[0].flags = 0;
Matt Simmering2447c242023-11-09 14:18:39 -0800208 msgs[0].len = toTargetBufLen;
209 msgs[0].buf = toTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800210 msgs[1].addr = address;
211 msgs[1].flags = I2C_M_RD;
Matt Simmering2447c242023-11-09 14:18:39 -0800212 msgs[1].len = fromTargetBufLen;
213 msgs[1].buf = fromTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800214
Ed Tanous3013fb42022-07-09 08:27:06 -0700215 rdwr.msgs = msgs.data();
216 rdwr.nmsgs = msgs.size();
Xiang Liu2801a702020-01-20 14:29:34 -0800217
218 int ret = ioctl(file, I2C_RDWR, &rdwr);
219
Jason M. Billsf6e4c1f2022-08-19 12:23:51 -0700220 return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
Xiang Liu2801a702020-01-20 14:29:34 -0800221}
222
Marvin Drees2b3ed302023-04-14 16:35:14 +0200223static int64_t readData(bool is16bit, bool isBytewise, int file,
224 uint16_t address, off_t offset, size_t len,
225 uint8_t* buf)
Xiang Liu2801a702020-01-20 14:29:34 -0800226{
Zev Weiss309c0b12022-02-25 01:44:12 +0000227 if (!is16bit)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800228 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200229 if (!isBytewise)
230 {
231 return i2c_smbus_read_i2c_block_data(
232 file, static_cast<uint8_t>(offset), len, buf);
233 }
234
235 std::span<uint8_t> bufspan{buf, len};
236 for (size_t i = 0; i < len; i++)
237 {
238 int byte = i2c_smbus_read_byte_data(
239 file, static_cast<uint8_t>(offset + i));
240 if (byte < 0)
241 {
242 return static_cast<int64_t>(byte);
243 }
244 bufspan[i] = static_cast<uint8_t>(byte);
245 }
246 return static_cast<int64_t>(len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800247 }
248
Xiang Liu2801a702020-01-20 14:29:34 -0800249 offset = htobe16(offset);
Ed Tanous3013fb42022-07-09 08:27:06 -0700250 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
251 uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
252 return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800253}
254
Vu Phamdac2dfc2024-11-05 12:20:42 -0600255// Mode_1:
256// --------
257// Please refer to document docs/address_size_detection_modes.md for
258// more details and explanations.
259static std::optional<bool> isDevice16BitMode1(int file)
260{
261 // Set the higher data word address bits to 0. It's safe on 8-bit
262 // addressing EEPROMs because it doesn't write any actual data.
263 int ret = i2c_smbus_write_byte(file, 0);
264 if (ret < 0)
265 {
266 return std::nullopt;
267 }
268
269 /* Get first byte */
270 int byte1 = i2c_smbus_read_byte_data(file, 0);
271 if (byte1 < 0)
272 {
273 return std::nullopt;
274 }
275 /* Read 7 more bytes, it will read same first byte in case of
276 * 8 bit but it will read next byte in case of 16 bit
277 */
278 for (int i = 0; i < 7; i++)
279 {
280 int byte2 = i2c_smbus_read_byte_data(file, 0);
281 if (byte2 < 0)
282 {
283 return std::nullopt;
284 }
285 if (byte2 != byte1)
286 {
287 return true;
288 }
289 }
290 return false;
291}
292
293// Mode_2:
294// --------
295// Please refer to document docs/address_size_detection_modes.md for
296// more details and explanations.
297static std::optional<bool> isDevice16BitMode2(int file, uint16_t address)
298{
299 uint8_t first = 0;
300 uint8_t cur = 0;
301 uint16_t v = 0;
302 int ret = 0;
303 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
304 uint8_t* p = reinterpret_cast<uint8_t*>(&v);
305
306 /*
307 * Write 2 bytes byte0 = 0, byte1 = {0..7} and then subsequent read byte
308 * It will read same first byte in case of 8 bit but
309 * it will read next byte in case of 16 bit
310 */
311 for (int i = 0; i < 8; i++)
312 {
313 v = htobe16(i);
314
315 ret = i2cSmbusWriteThenRead(file, address, p, 2, &cur, 1);
316 if (ret < 0)
317 {
318 return std::nullopt;
319 }
320
321 if (i == 0)
322 {
323 first = cur;
324 }
325
326 if (first != cur)
327 {
328 return true;
329 }
330 }
331 return false;
332}
333
334static std::optional<bool> isDevice16Bit(int file, uint16_t address)
335{
336 std::string mode(fruDevice16BitDetectMode);
337
338 if (mode == "MODE_2")
339 {
340 return isDevice16BitMode2(file, address);
341 }
342
343 return isDevice16BitMode1(file);
344}
345
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700346// TODO: This code is very similar to the non-eeprom version and can be merged
347// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300348static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700349{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700350 auto path = getEepromPath(bus, address);
351
352 int file = open(path.c_str(), O_RDONLY);
353 if (file < 0)
354 {
355 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700356 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700357 }
358
Patrick Venturebaba7672019-10-26 09:26:41 -0700359 std::string errorMessage = "eeprom at " + std::to_string(bus) +
360 " address " + std::to_string(address);
Zev Weiss309c0b12022-02-25 01:44:12 +0000361 auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
362 return readFromEeprom(file, offset, length, outbuf);
363 };
364 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400365 std::pair<std::vector<uint8_t>, bool> pair =
366 readFRUContents(reader, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700367
368 close(file);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200369 return pair.first;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700370}
371
Bonnie Lobfda2c42022-10-26 16:50:54 +0800372std::set<size_t> findI2CEeproms(int i2cBus,
373 const std::shared_ptr<DeviceMap>& devices)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700374{
Bonnie Lobfda2c42022-10-26 16:50:54 +0800375 std::set<size_t> foundList;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700376
377 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
378
379 // For each file listed under the i2c device
380 // NOTE: This should be faster than just checking for each possible address
381 // path.
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700382 auto ec = std::error_code();
383 for (const auto& p : fs::directory_iterator(path, ec))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700384 {
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700385 if (ec)
386 {
387 std::cerr << "directory_iterator err " << ec.message() << "\n";
388 break;
389 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700390 const std::string node = p.path().string();
391 std::smatch m;
Patrick Williamsb7077432024-08-16 15:22:21 -0400392 bool found =
393 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700394
395 if (!found)
396 {
397 continue;
398 }
399 if (m.size() != 2)
400 {
401 std::cerr << "regex didn't capture\n";
402 continue;
403 }
404
405 std::ssub_match subMatch = m[1];
406 std::string addressString = subMatch.str();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800407 std::string_view addressStringView(addressString);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700408
Bonnie Lobfda2c42022-10-26 16:50:54 +0800409 size_t address = 0;
410 std::from_chars(addressStringView.begin(), addressStringView.end(),
411 address, 16);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700412
413 const std::string eeprom = node + "/eeprom";
414
415 try
416 {
417 if (!fs::exists(eeprom))
418 {
419 continue;
420 }
421 }
422 catch (...)
423 {
424 continue;
425 }
426
427 // There is an eeprom file at this address, it may have invalid
428 // contents, but we found it.
429 foundList.insert(address);
430
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300431 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700432 if (!device.empty())
433 {
434 devices->emplace(address, device);
435 }
436 }
437
438 return foundList;
439}
440
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300441int getBusFRUs(int file, int first, int last, int bus,
Jonathan Doman2418a612022-02-14 18:20:58 -0800442 std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
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
Matt Simmering2447c242023-11-09 14:18:39 -0800461 auto busFind = busBlocklist.find(bus);
462 if (busFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800463 {
464 if (busFind->second != std::nullopt)
465 {
466 for (const auto& address : *(busFind->second))
467 {
468 skipList.insert(address);
469 }
470 }
471 }
472
James Feist7972bb92019-11-13 15:59:24 -0800473 std::set<size_t>* rootFailures = nullptr;
474 int rootBus = getRootBus(bus);
475
476 if (rootBus >= 0)
477 {
Matt Simmering2447c242023-11-09 14:18:39 -0800478 auto rootBusFind = busBlocklist.find(rootBus);
479 if (rootBusFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800480 {
481 if (rootBusFind->second != std::nullopt)
482 {
483 for (const auto& rootAddress : *(rootBusFind->second))
484 {
485 skipList.insert(rootAddress);
486 }
487 }
488 }
James Feist7972bb92019-11-13 15:59:24 -0800489 rootFailures = &(failedAddresses[rootBus]);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000490 foundItems = fruAddresses[rootBus];
James Feist7972bb92019-11-13 15:59:24 -0800491 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700492
Matt Simmering2447c242023-11-09 14:18:39 -0800493 constexpr int startSkipTargetAddr = 0;
494 constexpr int endSkipTargetAddr = 12;
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530495
James Feist26c27ad2018-07-25 15:09:40 -0700496 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800497 {
Patrick Williams64599932025-05-14 07:24:20 -0400498 if (foundItems.contains(ii))
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000499 {
500 continue;
501 }
Patrick Williams64599932025-05-14 07:24:20 -0400502 if (skipList.contains(ii))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700503 {
504 continue;
505 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530506 // skipping since no device is present in this range
Matt Simmering2447c242023-11-09 14:18:39 -0800507 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530508 {
509 continue;
510 }
Matt Simmering2447c242023-11-09 14:18:39 -0800511 // Set target address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530512 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800513 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300514 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700515 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700516 continue;
517 }
518 // probe
Ed Tanous07d467b2021-02-23 14:48:37 -0800519 if (i2c_smbus_read_byte(file) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700520 {
521 continue;
522 }
James Feist3cb5fec2018-01-23 14:41:51 -0800523
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200524 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
525 "ADDR", ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800526
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530527 makeProbeInterface(bus, ii, objServer);
James Feist8a983922019-10-24 17:11:56 -0700528
Patrick Williams64599932025-05-14 07:24:20 -0400529 if (failedItems.contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800530 {
531 // if we failed to read it once, unlikely we can read it later
532 continue;
533 }
534
535 if (rootFailures != nullptr)
536 {
Patrick Williams64599932025-05-14 07:24:20 -0400537 if (rootFailures->contains(ii))
James Feist7972bb92019-11-13 15:59:24 -0800538 {
539 continue;
540 }
541 }
542
Vijay Khemka2d681f62018-11-06 15:51:00 -0800543 /* Check for Device type if it is 8 bit or 16 bit */
Vu Phamdac2dfc2024-11-05 12:20:42 -0600544 std::optional<bool> is16Bit = isDevice16Bit(file, ii);
Zev Weiss309c0b12022-02-25 01:44:12 +0000545 if (!is16Bit.has_value())
Vijay Khemka2d681f62018-11-06 15:51:00 -0800546 {
547 std::cerr << "failed to read bus " << bus << " address " << ii
548 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700549 if (powerIsOn)
550 {
551 failedItems.insert(ii);
552 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800553 continue;
554 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000555 bool is16BitBool{*is16Bit};
Vijay Khemka2d681f62018-11-06 15:51:00 -0800556
Patrick Williamsb7077432024-08-16 15:22:21 -0400557 auto readFunc = [is16BitBool, file,
558 ii](off_t offset, size_t length, uint8_t* outbuf) {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200559 return readData(is16BitBool, false, file, ii, offset, length,
560 outbuf);
Zev Weiss309c0b12022-02-25 01:44:12 +0000561 };
562 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400563 std::string errorMessage =
564 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200565 std::pair<std::vector<uint8_t>, bool> pair =
566 readFRUContents(reader, errorMessage);
567 const bool foundHeader = pair.second;
568
569 if (!foundHeader && !is16BitBool)
570 {
571 // certain FRU eeproms require bytewise reading.
572 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
573
Patrick Williamsb7077432024-08-16 15:22:21 -0400574 auto readFunc =
575 [is16BitBool, file,
576 ii](off_t offset, size_t length, uint8_t* outbuf) {
577 return readData(is16BitBool, true, file, ii, offset,
578 length, outbuf);
579 };
Marvin Drees2b3ed302023-04-14 16:35:14 +0200580 FRUReader readerBytewise(std::move(readFunc));
581 pair = readFRUContents(readerBytewise, errorMessage);
582 }
583
584 if (pair.first.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700585 {
James Feist26c27ad2018-07-25 15:09:40 -0700586 continue;
587 }
James Feist26c27ad2018-07-25 15:09:40 -0700588
Marvin Drees2b3ed302023-04-14 16:35:14 +0200589 devices->emplace(ii, pair.first);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000590 fruAddresses[bus].insert(ii);
James Feist3cb5fec2018-01-23 14:41:51 -0800591 }
James Feist26c27ad2018-07-25 15:09:40 -0700592 return 1;
593 });
594 std::future_status status =
595 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
596 if (status == std::future_status::timeout)
597 {
598 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700599 if (powerIsOn)
600 {
Matt Simmering2447c242023-11-09 14:18:39 -0800601 busBlocklist[bus] = std::nullopt;
James Feistcb5661d2020-06-12 15:05:01 -0700602 }
James Feist444830e2019-04-05 08:38:16 -0700603 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700604 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800605 }
606
James Feist444830e2019-04-05 08:38:16 -0700607 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700608 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800609}
610
Matt Simmering2447c242023-11-09 14:18:39 -0800611void loadBlocklist(const char* path)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700612{
Matt Simmering2447c242023-11-09 14:18:39 -0800613 std::ifstream blocklistStream(path);
614 if (!blocklistStream.good())
Patrick Venture11f1ff42019-08-01 10:42:12 -0700615 {
616 // File is optional.
Matt Simmering2447c242023-11-09 14:18:39 -0800617 std::cerr << "Cannot open blocklist file.\n\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700618 return;
619 }
620
Patrick Williamsb7077432024-08-16 15:22:21 -0400621 nlohmann::json data =
622 nlohmann::json::parse(blocklistStream, nullptr, false);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700623 if (data.is_discarded())
624 {
Matt Simmering2447c242023-11-09 14:18:39 -0800625 std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
Patrick Venture11f1ff42019-08-01 10:42:12 -0700626 "exiting\n";
627 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700628 }
629
630 // It's expected to have at least one field, "buses" that is an array of the
631 // buses by integer. Allow for future options to exclude further aspects,
632 // such as specific addresses or ranges.
633 if (data.type() != nlohmann::json::value_t::object)
634 {
Matt Simmering2447c242023-11-09 14:18:39 -0800635 std::cerr << "Illegal blocklist, expected to read dictionary\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700636 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700637 }
638
639 // If buses field is missing, that's fine.
640 if (data.count("buses") == 1)
641 {
642 // Parse the buses array after a little validation.
643 auto buses = data.at("buses");
644 if (buses.type() != nlohmann::json::value_t::array)
645 {
646 // Buses field present but invalid, therefore this is an error.
Matt Simmering2447c242023-11-09 14:18:39 -0800647 std::cerr << "Invalid contents for blocklist buses field\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700648 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700649 }
650
651 // Catch exception here for type mis-match.
652 try
653 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800654 for (const auto& busIterator : buses)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700655 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800656 // If bus and addresses field are missing, that's fine.
657 if (busIterator.contains("bus") &&
658 busIterator.contains("addresses"))
659 {
660 auto busData = busIterator.at("bus");
661 auto bus = busData.get<size_t>();
662
663 auto addressData = busIterator.at("addresses");
664 auto addresses =
665 addressData.get<std::set<std::string_view>>();
666
Ed Tanousfc171422024-04-04 17:18:16 -0700667 auto& block = busBlocklist[bus].emplace();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800668 for (const auto& address : addresses)
669 {
670 size_t addressInt = 0;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400671 bool fullMatch = false;
672 fromCharsWrapper(address.substr(2), addressInt,
673 fullMatch, 16);
Ed Tanousfc171422024-04-04 17:18:16 -0700674 block.insert(addressInt);
Bonnie Lobfda2c42022-10-26 16:50:54 +0800675 }
676 }
677 else
678 {
Matt Simmering2447c242023-11-09 14:18:39 -0800679 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
Bonnie Lobfda2c42022-10-26 16:50:54 +0800680 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700681 }
682 }
683 catch (const nlohmann::detail::type_error& e)
684 {
685 // Type mis-match is a critical error.
686 std::cerr << "Invalid bus type: " << e.what() << "\n";
687 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700688 }
689 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700690}
691
Ed Tanous07d467b2021-02-23 14:48:37 -0800692static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800693 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530694 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800695{
Ed Tanous3013fb42022-07-09 08:27:06 -0700696 for (const auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800697 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700698 int bus = busStrToInt(i2cBus.string());
James Feist0c3980a2019-12-19 11:09:27 -0800699
James Feist5d7f4692020-06-17 18:22:33 -0700700 if (bus < 0)
701 {
702 std::cerr << "Cannot translate " << i2cBus << " to int\n";
703 continue;
704 }
Matt Simmering2447c242023-11-09 14:18:39 -0800705 auto busFind = busBlocklist.find(bus);
706 if (busFind != busBlocklist.end())
James Feist444830e2019-04-05 08:38:16 -0700707 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800708 if (busFind->second == std::nullopt)
709 {
710 continue; // Skip blocked busses.
711 }
James Feist444830e2019-04-05 08:38:16 -0700712 }
James Feist0c3980a2019-12-19 11:09:27 -0800713 int rootBus = getRootBus(bus);
Matt Simmering2447c242023-11-09 14:18:39 -0800714 auto rootBusFind = busBlocklist.find(rootBus);
715 if (rootBusFind != busBlocklist.end())
James Feist0c3980a2019-12-19 11:09:27 -0800716 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800717 if (rootBusFind->second == std::nullopt)
718 {
719 continue;
720 }
James Feist0c3980a2019-12-19 11:09:27 -0800721 }
722
James Feist3cb5fec2018-01-23 14:41:51 -0800723 auto file = open(i2cBus.c_str(), O_RDWR);
724 if (file < 0)
725 {
726 std::cerr << "unable to open i2c device " << i2cBus.string()
727 << "\n";
728 continue;
729 }
730 unsigned long funcs = 0;
731
732 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
733 {
734 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700735 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800736 << bus << "\n";
Zhikui Renc02d8cb2021-06-28 16:56:08 -0700737 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800738 continue;
739 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700740 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
741 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
James Feist3cb5fec2018-01-23 14:41:51 -0800742 {
743 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
744 << bus << "\n";
George Liu913d07d2024-12-09 19:16:30 +0800745 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800746 continue;
747 }
James Feist98132792019-07-09 13:29:09 -0700748 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800749 device = std::make_shared<DeviceMap>();
750
Nikhil Potaded8884f12019-03-27 13:27:13 -0700751 // i2cdetect by default uses the range 0x03 to 0x77, as
752 // this is what we have tested with, use this range. Could be
753 // changed in future.
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200754 lg2::debug("Scanning bus {BUS}", "BUS", bus);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700755
756 // fd is closed in this function in case the bus locks up
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530757 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700758
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200759 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
James Feist3cb5fec2018-01-23 14:41:51 -0800760 }
James Feist3cb5fec2018-01-23 14:41:51 -0800761}
762
James Feist6ebf9de2018-05-15 15:01:17 -0700763// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700764struct FindDevicesWithCallback :
765 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700766{
James Feista465ccc2019-02-08 12:51:01 -0800767 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800768 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530769 sdbusplus::asio::object_server& objServer,
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800770 std::function<void()>&& callback) :
Patrick Williamsb7077432024-08-16 15:22:21 -0400771 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
772 _objServer(objServer), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700773 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700774 ~FindDevicesWithCallback()
775 {
776 _callback();
777 }
778 void run()
779 {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530780 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
James Feist6ebf9de2018-05-15 15:01:17 -0700781 }
782
James Feista465ccc2019-02-08 12:51:01 -0800783 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800784 BusMap& _busMap;
Jonathan Doman2418a612022-02-14 18:20:58 -0800785 const bool& _powerIsOn;
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530786 sdbusplus::asio::object_server& _objServer;
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800787 std::function<void()> _callback;
James Feist6ebf9de2018-05-15 15:01:17 -0700788};
789
Ed Tanous07d467b2021-02-23 14:48:37 -0800790void addFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300791 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800792 boost::container::flat_map<
793 std::pair<size_t, size_t>,
794 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +0530795 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
Jonathan Doman2418a612022-02-14 18:20:58 -0800796 const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530797 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist3cb5fec2018-01-23 14:41:51 -0800798{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300799 boost::container::flat_map<std::string, std::string> formattedFRU;
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530800
801 std::optional<std::string> optionalProductName = getProductName(
802 device, formattedFRU, bus, address, unknownBusObjectCount);
803 if (!optionalProductName)
James Feist3cb5fec2018-01-23 14:41:51 -0800804 {
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530805 std::cerr << "getProductName failed. product name is empty.\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800806 return;
807 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700808
Patrick Williamsb7077432024-08-16 15:22:21 -0400809 std::string productName =
810 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
James Feist3cb5fec2018-01-23 14:41:51 -0800811
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530812 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
813 if (index.has_value())
James Feist918e18c2018-02-13 15:51:07 -0800814 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530815 productName += "_";
816 productName += std::to_string(++(*index));
James Feist918e18c2018-02-13 15:51:07 -0800817 }
James Feist3cb5fec2018-01-23 14:41:51 -0800818
James Feist9eb0b582018-04-27 12:15:46 -0700819 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
820 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
821 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
822
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300823 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800824 {
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700825 std::regex_replace(property.second.begin(), property.second.begin(),
Ed Tanous07d467b2021-02-23 14:48:37 -0800826 property.second.end(), nonAsciiRegex, "_");
Naresh Solanki89092a92025-06-02 15:48:04 +0530827 if (property.second.empty())
James Feist9eb0b582018-04-27 12:15:46 -0700828 {
829 continue;
830 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400831 std::string key =
832 std::regex_replace(property.first, nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530833
Naresh Solanki89092a92025-06-02 15:48:04 +0530834 // Allow FRU field update if ENABLE_FRU_UPDATE_PROPERTY is set.
835 if (isFieldEditable(property.first))
Joshi-Mansid73b7442020-03-27 19:10:21 +0530836 {
837 std::string propertyName = property.first;
838 iface->register_property(
839 key, property.second + '\0',
Kumar Thangavel41a90512021-11-24 15:44:20 +0530840 [bus, address, propertyName, &dbusInterfaceMap,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530841 &unknownBusObjectCount, &powerIsOn, &objServer,
842 &systemBus](const std::string& req, std::string& resp) {
Patrick Williamsb7077432024-08-16 15:22:21 -0400843 if (strcmp(req.c_str(), resp.c_str()) != 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +0530844 {
Patrick Williamsb7077432024-08-16 15:22:21 -0400845 // call the method which will update
846 if (updateFRUProperty(req, bus, address, propertyName,
847 dbusInterfaceMap,
848 unknownBusObjectCount, powerIsOn,
849 objServer, systemBus))
850 {
851 resp = req;
852 }
853 else
854 {
855 throw std::invalid_argument(
856 "FRU property update failed.");
857 }
Joshi-Mansid73b7442020-03-27 19:10:21 +0530858 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400859 return 1;
860 });
Joshi-Mansid73b7442020-03-27 19:10:21 +0530861 }
862 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -0700863 {
864 std::cerr << "illegal key: " << key << "\n";
865 }
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200866 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
867 property.first, "SECOND", property.second);
James Feist3cb5fec2018-01-23 14:41:51 -0800868 }
James Feist2a9d6db2018-04-27 15:48:28 -0700869
870 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700871 iface->register_property("BUS", bus);
872 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700873
James Feist9eb0b582018-04-27 12:15:46 -0700874 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800875}
876
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300877static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800878{
879 // try to read baseboard fru from file
Ed Tanous07d467b2021-02-23 14:48:37 -0800880 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300881 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -0800882 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300883 baseboardFRUFile.seekg(0, std::ios_base::end);
884 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
885 baseboardFRU.resize(fileSize);
886 baseboardFRUFile.seekg(0, std::ios_base::beg);
Ed Tanous3013fb42022-07-09 08:27:06 -0700887 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
888 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
889 baseboardFRUFile.read(charOffset, fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -0800890 }
891 else
892 {
893 return false;
894 }
895 return true;
896}
897
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300898bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700899{
900 boost::container::flat_map<std::string, std::string> tmp;
Ed Tanous07d467b2021-02-23 14:48:37 -0800901 if (fru.size() > maxFruSize)
James Feistb49ffc32018-05-02 11:10:43 -0700902 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300903 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700904 return false;
905 }
906 // verify legal fru by running it through fru parsing logic
Michael Shen0961b112022-02-22 11:06:33 +0800907 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -0700908 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300909 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700910 return false;
911 }
912 // baseboard fru
913 if (bus == 0 && address == 0)
914 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800915 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
James Feistb49ffc32018-05-02 11:10:43 -0700916 if (!file.good())
917 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800918 std::cerr << "Error opening file " << baseboardFruLocation << "\n";
James Feistddb78302018-09-06 11:45:42 -0700919 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700920 return false;
921 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700922 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
923 const char* charOffset = reinterpret_cast<const char*>(fru.data());
924 file.write(charOffset, fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700925 return file.good();
926 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800927
928 if (hasEepromFile(bus, address))
James Feistb49ffc32018-05-02 11:10:43 -0700929 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800930 auto path = getEepromPath(bus, address);
Naresh Solanki41ee1802024-11-09 01:44:46 +0530931 off_t offset = 0;
932
Ed Tanous07d467b2021-02-23 14:48:37 -0800933 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
934 if (eeprom < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700935 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800936 std::cerr << "unable to open i2c device " << path << "\n";
937 throw DBusInternalError();
938 return false;
939 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700940
Naresh Solanki41ee1802024-11-09 01:44:46 +0530941 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
942 std::string errorMessage = "eeprom at " + std::to_string(bus) +
943 " address " + std::to_string(address);
944 auto readFunc = [eeprom](off_t offset, size_t length, uint8_t* outbuf) {
945 return readFromEeprom(eeprom, offset, length, outbuf);
946 };
947 FRUReader reader(std::move(readFunc));
948
949 if (!findFRUHeader(reader, errorMessage, blockData, offset))
950 {
951 offset = 0;
952 }
953
954 if (lseek(eeprom, offset, SEEK_SET) < 0)
955 {
956 std::cerr << "Unable to seek to offset " << offset
957 << " in device: " << path << "\n";
958 close(eeprom);
959 throw DBusInternalError();
960 }
961
Ed Tanous07d467b2021-02-23 14:48:37 -0800962 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
963 if (writtenBytes < 0)
964 {
965 std::cerr << "unable to write to i2c device " << path << "\n";
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700966 close(eeprom);
James Feistddb78302018-09-06 11:45:42 -0700967 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700968 return false;
969 }
970
Ed Tanous07d467b2021-02-23 14:48:37 -0800971 close(eeprom);
James Feistb49ffc32018-05-02 11:10:43 -0700972 return true;
973 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800974
975 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
976
977 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
978 if (file < 0)
979 {
980 std::cerr << "unable to open i2c device " << i2cBus << "\n";
981 throw DBusInternalError();
982 return false;
983 }
984 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
985 {
986 std::cerr << "unable to set device address\n";
987 close(file);
988 throw DBusInternalError();
989 return false;
990 }
991
992 constexpr const size_t retryMax = 2;
993 uint16_t index = 0;
994 size_t retries = retryMax;
995 while (index < fru.size())
996 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700997 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
Ed Tanous07d467b2021-02-23 14:48:37 -0800998 (retries == retryMax))
999 {
1000 // The 4K EEPROM only uses the A2 and A1 device address bits
1001 // with the third bit being a memory page address bit.
1002 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1003 {
1004 std::cerr << "unable to set device address\n";
1005 close(file);
1006 throw DBusInternalError();
1007 return false;
1008 }
1009 }
1010
1011 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1012 fru[index]) < 0)
1013 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001014 if ((retries--) == 0U)
Ed Tanous07d467b2021-02-23 14:48:37 -08001015 {
1016 std::cerr << "error writing fru: " << strerror(errno) << "\n";
1017 close(file);
1018 throw DBusInternalError();
1019 return false;
1020 }
1021 }
1022 else
1023 {
1024 retries = retryMax;
1025 index++;
1026 }
1027 // most eeproms require 5-10ms between writes
1028 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1029 }
1030 close(file);
1031 return true;
James Feistb49ffc32018-05-02 11:10:43 -07001032}
1033
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001034void rescanOneBus(
krishnar4213ee212022-11-11 15:39:30 +05301035 BusMap& busmap, uint16_t busNum,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001036 boost::container::flat_map<
1037 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001038 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001039 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301040 sdbusplus::asio::object_server& objServer,
1041 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001042{
Yong Li6fdfac02023-10-30 11:21:30 +08001043 for (auto device = foundDevices.begin(); device != foundDevices.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001044 {
Yong Li6fdfac02023-10-30 11:21:30 +08001045 if (device->first.first == static_cast<size_t>(busNum))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001046 {
Yong Li6fdfac02023-10-30 11:21:30 +08001047 objServer.remove_interface(device->second);
1048 device = foundDevices.erase(device);
1049 }
1050 else
1051 {
1052 device++;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001053 }
1054 }
1055
James Feist5d7f4692020-06-17 18:22:33 -07001056 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1057 if (!fs::exists(busPath))
1058 {
1059 if (dbusCall)
1060 {
1061 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1062 << "\n";
1063 throw std::invalid_argument("Invalid Bus.");
1064 }
1065 return;
1066 }
1067
1068 std::vector<fs::path> i2cBuses;
1069 i2cBuses.emplace_back(busPath);
1070
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001071 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301072 i2cBuses, busmap, powerIsOn, objServer,
1073 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1074 &objServer, &systemBus]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001075 for (auto busIface = dbusInterfaceMap.begin();
1076 busIface != dbusInterfaceMap.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001077 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001078 if (busIface->first.first == static_cast<size_t>(busNum))
1079 {
1080 objServer.remove_interface(busIface->second);
1081 busIface = dbusInterfaceMap.erase(busIface);
1082 }
1083 else
1084 {
1085 busIface++;
1086 }
Yong Li6fdfac02023-10-30 11:21:30 +08001087 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001088 auto found = busmap.find(busNum);
1089 if (found == busmap.end() || found->second == nullptr)
Yong Li6fdfac02023-10-30 11:21:30 +08001090 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001091 return;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001092 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001093 for (auto& device : *(found->second))
1094 {
1095 addFruObjectToDbus(device.second, dbusInterfaceMap,
1096 static_cast<uint32_t>(busNum), device.first,
1097 unknownBusObjectCount, powerIsOn, objServer,
1098 systemBus);
1099 }
1100 });
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001101 scan->run();
1102}
1103
James Feist9eb0b582018-04-27 12:15:46 -07001104void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001105 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001106 boost::container::flat_map<
1107 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301108 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001109 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301110 sdbusplus::asio::object_server& objServer,
1111 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist918e18c2018-02-13 15:51:07 -08001112{
Ed Tanousaa497ed2023-02-28 13:43:41 -08001113 static boost::asio::steady_timer timer(io);
Ed Tanousae2d4352025-02-12 15:51:48 -08001114 timer.expires_after(std::chrono::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001115
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001116 // setup an async wait in case we get flooded with requests
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001117 timer.async_wait([&](const boost::system::error_code& ec) {
1118 if (ec == boost::asio::error::operation_aborted)
1119 {
1120 return;
1121 }
1122
1123 if (ec)
1124 {
1125 std::cerr << "Error in timer: " << ec.message() << "\n";
1126 return;
1127 }
1128
James Feist4131aea2018-03-09 09:47:30 -08001129 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001130 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001131
Nikhil Potaded8884f12019-03-27 13:27:13 -07001132 boost::container::flat_map<size_t, fs::path> busPaths;
1133 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001134 {
James Feist4131aea2018-03-09 09:47:30 -08001135 std::cerr << "unable to find i2c devices\n";
1136 return;
James Feist918e18c2018-02-13 15:51:07 -08001137 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001138
Ed Tanous07d467b2021-02-23 14:48:37 -08001139 for (const auto& busPath : busPaths)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001140 {
1141 i2cBuses.emplace_back(busPath.second);
1142 }
James Feist4131aea2018-03-09 09:47:30 -08001143
James Feist98132792019-07-09 13:29:09 -07001144 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001145 for (auto& [pair, interface] : foundDevices)
1146 {
1147 objServer.remove_interface(interface);
1148 }
1149 foundDevices.clear();
1150
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301151 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301152 i2cBuses, busmap, powerIsOn, objServer, [&]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001153 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001154 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001155 objServer.remove_interface(busIface.second);
James Feist6ebf9de2018-05-15 15:01:17 -07001156 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001157
1158 dbusInterfaceMap.clear();
1159 unknownBusObjectCount = 0;
1160
1161 // todo, get this from a more sensable place
1162 std::vector<uint8_t> baseboardFRU;
1163 if (readBaseboardFRU(baseboardFRU))
1164 {
1165 // If no device on i2c bus 0, the insertion will happen.
1166 auto bus0 =
1167 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1168 bus0.first->second->emplace(0, baseboardFRU);
1169 }
1170 for (auto& devicemap : busmap)
1171 {
1172 for (auto& device : *devicemap.second)
1173 {
1174 addFruObjectToDbus(device.second, dbusInterfaceMap,
1175 devicemap.first, device.first,
1176 unknownBusObjectCount, powerIsOn,
1177 objServer, systemBus);
1178 }
1179 }
1180 });
James Feist6ebf9de2018-05-15 15:01:17 -07001181 scan->run();
1182 });
James Feist918e18c2018-02-13 15:51:07 -08001183}
1184
Joshi-Mansid73b7442020-03-27 19:10:21 +05301185// Details with example of Asset Tag Update
1186// To find location of Product Info Area asset tag as per FRU specification
1187// 1. Find product Info area starting offset (*8 - as header will be in
1188// multiple of 8 bytes).
1189// 2. Skip 3 bytes of product info area (like format version, area length,
1190// and language code).
1191// 3. Traverse manufacturer name, product name, product version, & product
1192// serial number, by reading type/length code to reach the Asset Tag.
1193// 4. Update the Asset Tag, reposition the product Info area in multiple of
1194// 8 bytes. Update the Product area length and checksum.
1195
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001196bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301197 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -08001198 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301199 boost::container::flat_map<
1200 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301201 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001202 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301203 sdbusplus::asio::object_server& objServer,
1204 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301205{
1206 size_t updatePropertyReqLen = updatePropertyReq.length();
1207 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1208 {
1209 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001210 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301211 "Invalid Length "
1212 << updatePropertyReqLen << "\n";
1213 return false;
1214 }
1215
1216 std::vector<uint8_t> fruData;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301217
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301218 if (!getFruData(fruData, bus, address))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301219 {
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301220 std::cerr << "Failure getting FRU Data \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301221 return false;
1222 }
1223
Patrick Williamsa41f0142024-12-18 11:22:53 -05001224 struct FruArea fruAreaParams{};
Joshi-Mansid73b7442020-03-27 19:10:21 +05301225
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301226 if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301227 {
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301228 std::cerr << "findFruAreaLocationAndField failed \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301229 return false;
1230 }
1231
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301232 std::vector<uint8_t> restFRUAreaFieldsData;
1233 if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1234 restFRUAreaFieldsData))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301235 {
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301236 std::cerr << "copyRestFRUArea failed \n";
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001237 return false;
1238 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301239
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001240 // Push post update fru areas if any
1241 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001242 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1243 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001244 {
1245 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001246 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301247 if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001248 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1249 {
1250 nextFRUAreaLoc = fruAreaLoc;
1251 }
1252 }
1253 std::vector<uint8_t> restFRUAreasData;
Ed Tanous3013fb42022-07-09 08:27:06 -07001254 if (nextFRUAreaLoc != 0U)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001255 {
1256 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1257 fruData.size() - nextFRUAreaLoc,
1258 std::back_inserter(restFRUAreasData));
1259 }
1260
1261 // check FRU area size
1262 size_t fruAreaDataSize =
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301263 ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1264 restFRUAreaFieldsData.size());
1265 size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001266 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1267 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001268#ifdef ENABLE_FRU_AREA_RESIZE
1269 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1270 // round size to 8-byte blocks
Patrick Williamsb7077432024-08-16 15:22:21 -04001271 newFRUAreaSize =
1272 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1273 size_t newFRUDataSize =
1274 fruData.size() + newFRUAreaSize - fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001275 fruData.resize(newFRUDataSize);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301276 fruAreaParams.size = newFRUAreaSize;
1277 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001278#else
1279 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1280 << " should not be greater than available FRU area size: "
1281 << fruAreaAvailableSize << "\n";
1282 return false;
1283#endif // ENABLE_FRU_AREA_RESIZE
1284 }
1285
Joshi-Mansid73b7442020-03-27 19:10:21 +05301286 // write new requested property field length and data
1287 constexpr uint8_t newTypeLenMask = 0xC0;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301288 fruData[fruAreaParams.updateFieldLoc] =
Joshi-Mansid73b7442020-03-27 19:10:21 +05301289 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301290 fruAreaParams.updateFieldLoc++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301291 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301292 fruData.begin() + fruAreaParams.updateFieldLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301293
1294 // Copy remaining data to main fru area - post updated fru field vector
Patrick Williamsb7077432024-08-16 15:22:21 -04001295 fruAreaParams.restFieldsLoc =
1296 fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1297 size_t fruAreaDataEnd =
1298 fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301299
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001300 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301301 fruData.begin() + fruAreaParams.restFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301302
1303 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001304 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301305 fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301306
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001307#ifdef ENABLE_FRU_AREA_RESIZE
1308 ++nextFRUAreaNewLoc;
Patrick Williamsb7077432024-08-16 15:22:21 -04001309 ssize_t nextFRUAreaOffsetDiff =
1310 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001311 // Append rest FRU Areas if size changed and there were other sections after
1312 // updated one
Naresh Solanki89092a92025-06-02 15:48:04 +05301313 if ((nextFRUAreaOffsetDiff != 0) && (nextFRUAreaLoc != 0U))
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001314 {
1315 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1316 fruData.begin() + nextFRUAreaNewLoc);
1317 // Update Common Header
Ed Tanous6e22c872023-02-16 15:19:28 -08001318 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1319 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001320 {
Ed Tanous6e22c872023-02-16 15:19:28 -08001321 unsigned int fruAreaOffsetField =
1322 getHeaderAreaFieldOffset(nextFRUArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001323 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
Ed Tanous6e22c872023-02-16 15:19:28 -08001324 if (curFRUAreaOffset > fruAreaParams.end)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001325 {
1326 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1327 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1328 }
1329 }
1330 // Calculate new checksum
1331 std::vector<uint8_t> headerFRUData;
1332 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1333 size_t checksumVal = calculateChecksum(headerFRUData);
1334 fruData[7] = static_cast<uint8_t>(checksumVal);
1335 // fill zeros if FRU Area size decreased
1336 if (nextFRUAreaOffsetDiff < 0)
1337 {
1338 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1339 restFRUAreasData.size(),
1340 fruData.end(), 0);
1341 }
1342 }
1343#else
1344 // this is to avoid "unused variable" warning
1345 (void)nextFRUAreaNewLoc;
1346#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301347 if (fruData.empty())
1348 {
1349 return false;
1350 }
1351
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001352 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301353 fruData))
1354 {
1355 return false;
1356 }
1357
1358 // Rescan the bus so that GetRawFru dbus-call fetches updated values
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301359 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1360 objServer, systemBus);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301361 return true;
1362}
1363
James Feist98132792019-07-09 13:29:09 -07001364int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001365{
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301366 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1367 sdbusplus::asio::object_server objServer(systemBus);
1368
Kumar Thangavel41a90512021-11-24 15:44:20 +05301369 static size_t unknownBusObjectCount = 0;
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301370 static bool powerIsOn = false;
James Feist3cb5fec2018-01-23 14:41:51 -08001371 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001372 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001373 std::vector<fs::path> i2cBuses;
1374
James Feista3c180a2018-08-09 16:06:04 -07001375 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001376 {
1377 std::cerr << "unable to find i2c devices\n";
1378 return 1;
1379 }
James Feist3cb5fec2018-01-23 14:41:51 -08001380
Matt Simmering2447c242023-11-09 14:18:39 -08001381 // check for and load blocklist with initial buses.
1382 loadBlocklist(blocklistPath);
Patrick Venture11f1ff42019-08-01 10:42:12 -07001383
Vijay Khemka065f6d92018-12-18 10:37:47 -08001384 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001385
James Feist6ebf9de2018-05-15 15:01:17 -07001386 // this is a map with keys of pair(bus number, address) and values of
1387 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001388 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001389 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1390 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001391
James Feist9eb0b582018-04-27 12:15:46 -07001392 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1393 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1394 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001395
Kumar Thangavel41a90512021-11-24 15:44:20 +05301396 iface->register_method("ReScan", [&]() {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301397 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1398 objServer, systemBus);
Kumar Thangavel41a90512021-11-24 15:44:20 +05301399 });
James Feist2a9d6db2018-04-27 15:48:28 -07001400
krishnar4213ee212022-11-11 15:39:30 +05301401 iface->register_method("ReScanBus", [&](uint16_t bus) {
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301402 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301403 powerIsOn, objServer, systemBus);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001404 });
1405
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001406 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001407
Patrick Williamsb7077432024-08-16 15:22:21 -04001408 iface->register_method(
1409 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1410 const std::vector<uint8_t>& data) {
1411 if (!writeFRU(bus, address, data))
1412 {
1413 throw std::invalid_argument("Invalid Arguments.");
1414 return;
1415 }
1416 // schedule rescan on success
1417 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1418 powerIsOn, objServer, systemBus);
1419 });
James Feist9eb0b582018-04-27 12:15:46 -07001420 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001421
Patrick Williams2af39222022-07-22 19:26:56 -05001422 std::function<void(sdbusplus::message_t & message)> eventHandler =
1423 [&](sdbusplus::message_t& message) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001424 std::string objectName;
1425 boost::container::flat_map<
1426 std::string,
1427 std::variant<std::string, bool, int64_t, uint64_t, double>>
1428 values;
1429 message.read(objectName, values);
1430 auto findState = values.find("CurrentHostState");
1431 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001432 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001433 if (std::get<std::string>(findState->second) ==
1434 "xyz.openbmc_project.State.Host.HostState.Running")
1435 {
1436 powerIsOn = true;
1437 }
James Feist0eeb79c2019-10-09 13:35:29 -07001438 }
James Feist6ebf9de2018-05-15 15:01:17 -07001439
Patrick Williamsb7077432024-08-16 15:22:21 -04001440 if (powerIsOn)
1441 {
1442 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1443 powerIsOn, objServer, systemBus);
1444 }
1445 };
James Feist9eb0b582018-04-27 12:15:46 -07001446
Patrick Williams2af39222022-07-22 19:26:56 -05001447 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1448 static_cast<sdbusplus::bus_t&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001449 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001450 "openbmc_project/state/"
1451 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001452 eventHandler);
1453
James Feist4131aea2018-03-09 09:47:30 -08001454 int fd = inotify_init();
Ed Tanous07d467b2021-02-23 14:48:37 -08001455 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
Ed Tanous3013fb42022-07-09 08:27:06 -07001456 std::array<char, 4096> readBuffer{};
James Feist4131aea2018-03-09 09:47:30 -08001457 // monitor for new i2c devices
1458 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1459 std::function<void(const boost::system::error_code, std::size_t)>
Patrick Williamsb9dd7f82023-10-20 11:20:11 -05001460 watchI2cBusses = [&](const boost::system::error_code& ec,
1461 std::size_t bytesTransferred) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001462 if (ec)
James Feist4131aea2018-03-09 09:47:30 -08001463 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001464 std::cout << "Callback Error " << ec << "\n";
1465 return;
1466 }
1467 size_t index = 0;
1468 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1469 {
1470 const char* p = &readBuffer[index];
1471 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1472 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1473 switch (iEvent->mask)
Ed Tanousfc171422024-04-04 17:18:16 -07001474 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001475 case IN_CREATE:
1476 case IN_MOVED_TO:
1477 case IN_DELETE:
Patrick Williamsdf190612023-05-10 07:51:34 -05001478 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001479 std::string_view name(&iEvent->name[0], iEvent->len);
George Liu164af2f2025-08-21 17:16:31 +08001480 if (name.starts_with("i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001481 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001482 int bus = busStrToInt(name);
1483 if (bus < 0)
1484 {
1485 std::cerr
1486 << "Could not parse bus " << name << "\n";
1487 continue;
1488 }
1489 int rootBus = getRootBus(bus);
1490 if (rootBus >= 0)
1491 {
1492 rescanOneBus(busMap,
1493 static_cast<uint16_t>(rootBus),
1494 dbusInterfaceMap, false,
1495 unknownBusObjectCount, powerIsOn,
1496 objServer, systemBus);
1497 }
1498 rescanOneBus(busMap, static_cast<uint16_t>(bus),
Kumar Thangavel41a90512021-11-24 15:44:20 +05301499 dbusInterfaceMap, false,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301500 unknownBusObjectCount, powerIsOn,
1501 objServer, systemBus);
James Feist9eb0b582018-04-27 12:15:46 -07001502 }
Patrick Williamsdf190612023-05-10 07:51:34 -05001503 }
Ed Tanousfc171422024-04-04 17:18:16 -07001504 break;
Patrick Williamsb7077432024-08-16 15:22:21 -04001505 default:
1506 break;
1507 }
1508 index += sizeof(inotify_event) + iEvent->len;
James Feist4131aea2018-03-09 09:47:30 -08001509 }
James Feist6ebf9de2018-05-15 15:01:17 -07001510
Patrick Williamsb7077432024-08-16 15:22:21 -04001511 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1512 watchI2cBusses);
1513 };
James Feist4131aea2018-03-09 09:47:30 -08001514
1515 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001516 // run the initial scan
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301517 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1518 objServer, systemBus);
James Feist918e18c2018-02-13 15:51:07 -08001519
James Feist3cb5fec2018-01-23 14:41:51 -08001520 io.run();
1521 return 0;
1522}