blob: 74704d23d8ffc6938938d3a7f50ab311648c42f3 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
Brad Bishope45d8c72022-05-25 15:12:53 -040016/// \file fru_device.cpp
James Feist3cb5fec2018-01-23 14:41:51 -080017
Brad Bishope45d8c72022-05-25 15:12:53 -040018#include "fru_utils.hpp"
19#include "utils.hpp"
Patrick Venturea49dc332019-10-26 08:32:02 -070020
James Feist3cb5fec2018-01-23 14:41:51 -080021#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070022#include <sys/inotify.h>
23#include <sys/ioctl.h>
24
James Feist3b860982018-10-02 14:34:07 -070025#include <boost/algorithm/string/predicate.hpp>
Ed Tanous34c3e012023-03-06 13:42:00 -080026#include <boost/asio/io_context.hpp>
Ed Tanousaa497ed2023-02-28 13:43:41 -080027#include <boost/asio/steady_timer.hpp>
James Feist3b860982018-10-02 14:34:07 -070028#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070029#include <nlohmann/json.hpp>
Alexander Hansenc3db2c32024-08-20 15:01:38 +020030#include <phosphor-logging/lg2.hpp>
James Feist8c505da2020-05-28 10:06:33 -070031#include <sdbusplus/asio/connection.hpp>
32#include <sdbusplus/asio/object_server.hpp>
33
34#include <array>
Ed Tanous07d467b2021-02-23 14:48:37 -080035#include <cerrno>
Ed Tanous3013fb42022-07-09 08:27:06 -070036#include <charconv>
James Feist3b860982018-10-02 14:34:07 -070037#include <chrono>
38#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070039#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080040#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070041#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080042#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070043#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080044#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070045#include <limits>
Andrew Jefferya9c58922021-06-01 09:28:59 +093046#include <map>
Bonnie Lobfda2c42022-10-26 16:50:54 +080047#include <optional>
James Feist3f8a2782018-02-12 09:24:42 -080048#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070049#include <set>
50#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070051#include <string>
James Feist3b860982018-10-02 14:34:07 -070052#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080053#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080054#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070055#include <vector>
James Feist3b860982018-10-02 14:34:07 -070056
James Feist8c505da2020-05-28 10:06:33 -070057extern "C"
58{
James Feist3b860982018-10-02 14:34:07 -070059#include <i2c/smbus.h>
60#include <linux/i2c-dev.h>
61}
James Feist3cb5fec2018-01-23 14:41:51 -080062
Ed Tanous072e25d2018-12-16 21:45:20 -080063namespace fs = std::filesystem;
Ed Tanous07d467b2021-02-23 14:48:37 -080064constexpr size_t maxFruSize = 512;
65constexpr size_t maxEepromPageIndex = 255;
ankita prasad7329a222023-07-07 09:18:10 +000066constexpr size_t busTimeoutSeconds = 10;
James Feist3cb5fec2018-01-23 14:41:51 -080067
Matt Simmering2447c242023-11-09 14:18:39 -080068constexpr const char* blocklistPath = PACKAGE_DIR "blacklist.json";
Patrick Venture11f1ff42019-08-01 10:42:12 -070069
Ed Tanous07d467b2021-02-23 14:48:37 -080070const static constexpr char* baseboardFruLocation =
James Feist3cb5fec2018-01-23 14:41:51 -080071 "/etc/fru/baseboard.fru.bin";
72
Ed Tanous07d467b2021-02-23 14:48:37 -080073const static constexpr char* i2CDevLocation = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080074
Vu Phamdac2dfc2024-11-05 12:20:42 -060075constexpr const char* fruDevice16BitDetectMode = FRU_DEVICE_16BITDETECTMODE;
76
Ed Tanousfc171422024-04-04 17:18:16 -070077// TODO Refactor these to not be globals
78// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
Bonnie Lobfda2c42022-10-26 16:50:54 +080079static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
Matt Simmering2447c242023-11-09 14:18:39 -080080 busBlocklist;
James Feist6ebf9de2018-05-15 15:01:17 -070081struct FindDevicesWithCallback;
82
James Feist8a983922019-10-24 17:11:56 -070083static boost::container::flat_map<
84 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
85 foundDevices;
86
James Feist7972bb92019-11-13 15:59:24 -080087static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +000088static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
James Feist7972bb92019-11-13 15:59:24 -080089
Ed Tanous34c3e012023-03-06 13:42:00 -080090boost::asio::io_context io;
Ed Tanousfc171422024-04-04 17:18:16 -070091// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
James Feist5cb06082019-10-24 17:11:13 -070092
Andrei Kartashev2f0de172020-08-13 14:29:40 +030093bool updateFRUProperty(
Ed Tanous3013fb42022-07-09 08:27:06 -070094 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -080095 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +053096 boost::container::flat_map<
97 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +053098 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -080099 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530100 sdbusplus::asio::object_server& objServer,
101 std::shared_ptr<sdbusplus::asio::connection>& systemBus);
Patrick Venturebaba7672019-10-26 09:26:41 -0700102
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700103// Given a bus/address, produce the path in sysfs for an eeprom.
104static std::string getEepromPath(size_t bus, size_t address)
105{
106 std::stringstream output;
107 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
108 << std::setfill('0') << std::setw(4) << std::hex << address
109 << "/eeprom";
110 return output.str();
111}
112
113static bool hasEepromFile(size_t bus, size_t address)
114{
115 auto path = getEepromPath(bus, address);
116 try
117 {
118 return fs::exists(path);
119 }
120 catch (...)
121 {
122 return false;
123 }
124}
125
Zev Weiss309c0b12022-02-25 01:44:12 +0000126static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700127{
128 auto result = lseek(fd, offset, SEEK_SET);
129 if (result < 0)
130 {
131 std::cerr << "failed to seek\n";
132 return -1;
133 }
134
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700135 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700136}
137
Ed Tanous3013fb42022-07-09 08:27:06 -0700138static int busStrToInt(const std::string_view busName)
James Feist5d7f4692020-06-17 18:22:33 -0700139{
Ed Tanous07d467b2021-02-23 14:48:37 -0800140 auto findBus = busName.rfind('-');
James Feist5d7f4692020-06-17 18:22:33 -0700141 if (findBus == std::string::npos)
142 {
143 return -1;
144 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700145 std::string_view num = busName.substr(findBus + 1);
146 int val = 0;
147 std::from_chars(num.data(), num.data() + num.size(), val);
148 return val;
James Feist5d7f4692020-06-17 18:22:33 -0700149}
150
James Feist7972bb92019-11-13 15:59:24 -0800151static int getRootBus(size_t bus)
152{
153 auto ec = std::error_code();
154 auto path = std::filesystem::read_symlink(
Patrick Williamsb7077432024-08-16 15:22:21 -0400155 std::filesystem::path(
156 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"),
James Feist7972bb92019-11-13 15:59:24 -0800157 ec);
158 if (ec)
159 {
160 return -1;
161 }
162
163 std::string filename = path.filename();
Ed Tanous07d467b2021-02-23 14:48:37 -0800164 auto findBus = filename.find('-');
James Feist7972bb92019-11-13 15:59:24 -0800165 if (findBus == std::string::npos)
166 {
167 return -1;
168 }
169 return std::stoi(filename.substr(0, findBus));
170}
171
James Feistc95cb142018-02-26 10:41:42 -0800172static bool isMuxBus(size_t bus)
173{
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700174 auto ec = std::error_code();
175 auto isSymlink =
176 is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
177 std::to_string(bus) + "/mux_device"),
178 ec);
179 return (!ec && isSymlink);
James Feistc95cb142018-02-26 10:41:42 -0800180}
181
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530182static void makeProbeInterface(size_t bus, size_t address,
183 sdbusplus::asio::object_server& objServer)
James Feist8a983922019-10-24 17:11:56 -0700184{
185 if (isMuxBus(bus))
186 {
187 return; // the mux buses are random, no need to publish
188 }
189 auto [it, success] = foundDevices.emplace(
190 std::make_pair(bus, address),
191 objServer.add_interface(
192 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
193 std::to_string(address),
194 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
195 if (!success)
196 {
197 return; // already added
198 }
199 it->second->register_property("Bus", bus);
200 it->second->register_property("Address", address);
201 it->second->initialize();
202}
203
Matt Simmering2447c242023-11-09 14:18:39 -0800204// Issue an I2C transaction to first write to_target_buf_len bytes,then read
205// from_target_buf_len bytes.
Patrick Williamsb7077432024-08-16 15:22:21 -0400206static int i2cSmbusWriteThenRead(
207 int file, uint16_t address, uint8_t* toTargetBuf, uint8_t toTargetBufLen,
208 uint8_t* fromTargetBuf, uint8_t fromTargetBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800209{
Matt Simmering2447c242023-11-09 14:18:39 -0800210 if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
211 fromTargetBuf == nullptr || fromTargetBufLen == 0)
Xiang Liu2801a702020-01-20 14:29:34 -0800212 {
213 return -1;
214 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800215
Ed Tanous3013fb42022-07-09 08:27:06 -0700216 constexpr size_t smbusWriteThenReadMsgCount = 2;
217 std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
Patrick Williamsa41f0142024-12-18 11:22:53 -0500218 struct i2c_rdwr_ioctl_data rdwr{};
Xiang Liu2801a702020-01-20 14:29:34 -0800219
220 msgs[0].addr = address;
221 msgs[0].flags = 0;
Matt Simmering2447c242023-11-09 14:18:39 -0800222 msgs[0].len = toTargetBufLen;
223 msgs[0].buf = toTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800224 msgs[1].addr = address;
225 msgs[1].flags = I2C_M_RD;
Matt Simmering2447c242023-11-09 14:18:39 -0800226 msgs[1].len = fromTargetBufLen;
227 msgs[1].buf = fromTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800228
Ed Tanous3013fb42022-07-09 08:27:06 -0700229 rdwr.msgs = msgs.data();
230 rdwr.nmsgs = msgs.size();
Xiang Liu2801a702020-01-20 14:29:34 -0800231
232 int ret = ioctl(file, I2C_RDWR, &rdwr);
233
Jason M. Billsf6e4c1f2022-08-19 12:23:51 -0700234 return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
Xiang Liu2801a702020-01-20 14:29:34 -0800235}
236
Marvin Drees2b3ed302023-04-14 16:35:14 +0200237static int64_t readData(bool is16bit, bool isBytewise, int file,
238 uint16_t address, off_t offset, size_t len,
239 uint8_t* buf)
Xiang Liu2801a702020-01-20 14:29:34 -0800240{
Zev Weiss309c0b12022-02-25 01:44:12 +0000241 if (!is16bit)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800242 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200243 if (!isBytewise)
244 {
245 return i2c_smbus_read_i2c_block_data(
246 file, static_cast<uint8_t>(offset), len, buf);
247 }
248
249 std::span<uint8_t> bufspan{buf, len};
250 for (size_t i = 0; i < len; i++)
251 {
252 int byte = i2c_smbus_read_byte_data(
253 file, static_cast<uint8_t>(offset + i));
254 if (byte < 0)
255 {
256 return static_cast<int64_t>(byte);
257 }
258 bufspan[i] = static_cast<uint8_t>(byte);
259 }
260 return static_cast<int64_t>(len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800261 }
262
Xiang Liu2801a702020-01-20 14:29:34 -0800263 offset = htobe16(offset);
Ed Tanous3013fb42022-07-09 08:27:06 -0700264 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
265 uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
266 return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800267}
268
Vu Phamdac2dfc2024-11-05 12:20:42 -0600269// Mode_1:
270// --------
271// Please refer to document docs/address_size_detection_modes.md for
272// more details and explanations.
273static std::optional<bool> isDevice16BitMode1(int file)
274{
275 // Set the higher data word address bits to 0. It's safe on 8-bit
276 // addressing EEPROMs because it doesn't write any actual data.
277 int ret = i2c_smbus_write_byte(file, 0);
278 if (ret < 0)
279 {
280 return std::nullopt;
281 }
282
283 /* Get first byte */
284 int byte1 = i2c_smbus_read_byte_data(file, 0);
285 if (byte1 < 0)
286 {
287 return std::nullopt;
288 }
289 /* Read 7 more bytes, it will read same first byte in case of
290 * 8 bit but it will read next byte in case of 16 bit
291 */
292 for (int i = 0; i < 7; i++)
293 {
294 int byte2 = i2c_smbus_read_byte_data(file, 0);
295 if (byte2 < 0)
296 {
297 return std::nullopt;
298 }
299 if (byte2 != byte1)
300 {
301 return true;
302 }
303 }
304 return false;
305}
306
307// Mode_2:
308// --------
309// Please refer to document docs/address_size_detection_modes.md for
310// more details and explanations.
311static std::optional<bool> isDevice16BitMode2(int file, uint16_t address)
312{
313 uint8_t first = 0;
314 uint8_t cur = 0;
315 uint16_t v = 0;
316 int ret = 0;
317 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
318 uint8_t* p = reinterpret_cast<uint8_t*>(&v);
319
320 /*
321 * Write 2 bytes byte0 = 0, byte1 = {0..7} and then subsequent read byte
322 * It will read same first byte in case of 8 bit but
323 * it will read next byte in case of 16 bit
324 */
325 for (int i = 0; i < 8; i++)
326 {
327 v = htobe16(i);
328
329 ret = i2cSmbusWriteThenRead(file, address, p, 2, &cur, 1);
330 if (ret < 0)
331 {
332 return std::nullopt;
333 }
334
335 if (i == 0)
336 {
337 first = cur;
338 }
339
340 if (first != cur)
341 {
342 return true;
343 }
344 }
345 return false;
346}
347
348static std::optional<bool> isDevice16Bit(int file, uint16_t address)
349{
350 std::string mode(fruDevice16BitDetectMode);
351
352 if (mode == "MODE_2")
353 {
354 return isDevice16BitMode2(file, address);
355 }
356
357 return isDevice16BitMode1(file);
358}
359
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700360// TODO: This code is very similar to the non-eeprom version and can be merged
361// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300362static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700363{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700364 auto path = getEepromPath(bus, address);
365
366 int file = open(path.c_str(), O_RDONLY);
367 if (file < 0)
368 {
369 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700370 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700371 }
372
Patrick Venturebaba7672019-10-26 09:26:41 -0700373 std::string errorMessage = "eeprom at " + std::to_string(bus) +
374 " address " + std::to_string(address);
Zev Weiss309c0b12022-02-25 01:44:12 +0000375 auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
376 return readFromEeprom(file, offset, length, outbuf);
377 };
378 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400379 std::pair<std::vector<uint8_t>, bool> pair =
380 readFRUContents(reader, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700381
382 close(file);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200383 return pair.first;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700384}
385
Bonnie Lobfda2c42022-10-26 16:50:54 +0800386std::set<size_t> findI2CEeproms(int i2cBus,
387 const std::shared_ptr<DeviceMap>& devices)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700388{
Bonnie Lobfda2c42022-10-26 16:50:54 +0800389 std::set<size_t> foundList;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700390
391 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
392
393 // For each file listed under the i2c device
394 // NOTE: This should be faster than just checking for each possible address
395 // path.
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700396 auto ec = std::error_code();
397 for (const auto& p : fs::directory_iterator(path, ec))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700398 {
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700399 if (ec)
400 {
401 std::cerr << "directory_iterator err " << ec.message() << "\n";
402 break;
403 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700404 const std::string node = p.path().string();
405 std::smatch m;
Patrick Williamsb7077432024-08-16 15:22:21 -0400406 bool found =
407 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700408
409 if (!found)
410 {
411 continue;
412 }
413 if (m.size() != 2)
414 {
415 std::cerr << "regex didn't capture\n";
416 continue;
417 }
418
419 std::ssub_match subMatch = m[1];
420 std::string addressString = subMatch.str();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800421 std::string_view addressStringView(addressString);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700422
Bonnie Lobfda2c42022-10-26 16:50:54 +0800423 size_t address = 0;
424 std::from_chars(addressStringView.begin(), addressStringView.end(),
425 address, 16);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700426
427 const std::string eeprom = node + "/eeprom";
428
429 try
430 {
431 if (!fs::exists(eeprom))
432 {
433 continue;
434 }
435 }
436 catch (...)
437 {
438 continue;
439 }
440
441 // There is an eeprom file at this address, it may have invalid
442 // contents, but we found it.
443 foundList.insert(address);
444
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300445 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700446 if (!device.empty())
447 {
448 devices->emplace(address, device);
449 }
450 }
451
452 return foundList;
453}
454
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300455int getBusFRUs(int file, int first, int last, int bus,
Jonathan Doman2418a612022-02-14 18:20:58 -0800456 std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530457 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800458{
James Feist26c27ad2018-07-25 15:09:40 -0700459 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700460 // NOTE: When reading the devices raw on the bus, it can interfere with
461 // the driver's ability to operate, therefore read eeproms first before
462 // scanning for devices without drivers. Several experiments were run
463 // and it was determined that if there were any devices on the bus
464 // before the eeprom was hit and read, the eeprom driver wouldn't open
465 // while the bus device was open. An experiment was not performed to see
466 // if this issue was resolved if the i2c bus device was closed, but
467 // hexdumps of the eeprom later were successful.
468
469 // Scan for i2c eeproms loaded on this bus.
Bonnie Lobfda2c42022-10-26 16:50:54 +0800470 std::set<size_t> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800471 std::set<size_t>& failedItems = failedAddresses[bus];
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000472 std::set<size_t>& foundItems = fruAddresses[bus];
473 foundItems.clear();
James Feist7972bb92019-11-13 15:59:24 -0800474
Matt Simmering2447c242023-11-09 14:18:39 -0800475 auto busFind = busBlocklist.find(bus);
476 if (busFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800477 {
478 if (busFind->second != std::nullopt)
479 {
480 for (const auto& address : *(busFind->second))
481 {
482 skipList.insert(address);
483 }
484 }
485 }
486
James Feist7972bb92019-11-13 15:59:24 -0800487 std::set<size_t>* rootFailures = nullptr;
488 int rootBus = getRootBus(bus);
489
490 if (rootBus >= 0)
491 {
Matt Simmering2447c242023-11-09 14:18:39 -0800492 auto rootBusFind = busBlocklist.find(rootBus);
493 if (rootBusFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800494 {
495 if (rootBusFind->second != std::nullopt)
496 {
497 for (const auto& rootAddress : *(rootBusFind->second))
498 {
499 skipList.insert(rootAddress);
500 }
501 }
502 }
James Feist7972bb92019-11-13 15:59:24 -0800503 rootFailures = &(failedAddresses[rootBus]);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000504 foundItems = fruAddresses[rootBus];
James Feist7972bb92019-11-13 15:59:24 -0800505 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700506
Matt Simmering2447c242023-11-09 14:18:39 -0800507 constexpr int startSkipTargetAddr = 0;
508 constexpr int endSkipTargetAddr = 12;
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530509
James Feist26c27ad2018-07-25 15:09:40 -0700510 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800511 {
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000512 if (foundItems.find(ii) != foundItems.end())
513 {
514 continue;
515 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700516 if (skipList.find(ii) != skipList.end())
517 {
518 continue;
519 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530520 // skipping since no device is present in this range
Matt Simmering2447c242023-11-09 14:18:39 -0800521 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530522 {
523 continue;
524 }
Matt Simmering2447c242023-11-09 14:18:39 -0800525 // Set target address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530526 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800527 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300528 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700529 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700530 continue;
531 }
532 // probe
Ed Tanous07d467b2021-02-23 14:48:37 -0800533 if (i2c_smbus_read_byte(file) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700534 {
535 continue;
536 }
James Feist3cb5fec2018-01-23 14:41:51 -0800537
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200538 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
539 "ADDR", ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800540
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530541 makeProbeInterface(bus, ii, objServer);
James Feist8a983922019-10-24 17:11:56 -0700542
James Feist7972bb92019-11-13 15:59:24 -0800543 if (failedItems.find(ii) != failedItems.end())
544 {
545 // if we failed to read it once, unlikely we can read it later
546 continue;
547 }
548
549 if (rootFailures != nullptr)
550 {
551 if (rootFailures->find(ii) != rootFailures->end())
552 {
553 continue;
554 }
555 }
556
Vijay Khemka2d681f62018-11-06 15:51:00 -0800557 /* Check for Device type if it is 8 bit or 16 bit */
Vu Phamdac2dfc2024-11-05 12:20:42 -0600558 std::optional<bool> is16Bit = isDevice16Bit(file, ii);
Zev Weiss309c0b12022-02-25 01:44:12 +0000559 if (!is16Bit.has_value())
Vijay Khemka2d681f62018-11-06 15:51:00 -0800560 {
561 std::cerr << "failed to read bus " << bus << " address " << ii
562 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700563 if (powerIsOn)
564 {
565 failedItems.insert(ii);
566 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800567 continue;
568 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000569 bool is16BitBool{*is16Bit};
Vijay Khemka2d681f62018-11-06 15:51:00 -0800570
Patrick Williamsb7077432024-08-16 15:22:21 -0400571 auto readFunc = [is16BitBool, file,
572 ii](off_t offset, size_t length, uint8_t* outbuf) {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200573 return readData(is16BitBool, false, file, ii, offset, length,
574 outbuf);
Zev Weiss309c0b12022-02-25 01:44:12 +0000575 };
576 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400577 std::string errorMessage =
578 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200579 std::pair<std::vector<uint8_t>, bool> pair =
580 readFRUContents(reader, errorMessage);
581 const bool foundHeader = pair.second;
582
583 if (!foundHeader && !is16BitBool)
584 {
585 // certain FRU eeproms require bytewise reading.
586 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
587
Patrick Williamsb7077432024-08-16 15:22:21 -0400588 auto readFunc =
589 [is16BitBool, file,
590 ii](off_t offset, size_t length, uint8_t* outbuf) {
591 return readData(is16BitBool, true, file, ii, offset,
592 length, outbuf);
593 };
Marvin Drees2b3ed302023-04-14 16:35:14 +0200594 FRUReader readerBytewise(std::move(readFunc));
595 pair = readFRUContents(readerBytewise, errorMessage);
596 }
597
598 if (pair.first.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700599 {
James Feist26c27ad2018-07-25 15:09:40 -0700600 continue;
601 }
James Feist26c27ad2018-07-25 15:09:40 -0700602
Marvin Drees2b3ed302023-04-14 16:35:14 +0200603 devices->emplace(ii, pair.first);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000604 fruAddresses[bus].insert(ii);
James Feist3cb5fec2018-01-23 14:41:51 -0800605 }
James Feist26c27ad2018-07-25 15:09:40 -0700606 return 1;
607 });
608 std::future_status status =
609 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
610 if (status == std::future_status::timeout)
611 {
612 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700613 if (powerIsOn)
614 {
Matt Simmering2447c242023-11-09 14:18:39 -0800615 busBlocklist[bus] = std::nullopt;
James Feistcb5661d2020-06-12 15:05:01 -0700616 }
James Feist444830e2019-04-05 08:38:16 -0700617 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700618 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800619 }
620
James Feist444830e2019-04-05 08:38:16 -0700621 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700622 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800623}
624
Matt Simmering2447c242023-11-09 14:18:39 -0800625void loadBlocklist(const char* path)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700626{
Matt Simmering2447c242023-11-09 14:18:39 -0800627 std::ifstream blocklistStream(path);
628 if (!blocklistStream.good())
Patrick Venture11f1ff42019-08-01 10:42:12 -0700629 {
630 // File is optional.
Matt Simmering2447c242023-11-09 14:18:39 -0800631 std::cerr << "Cannot open blocklist file.\n\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700632 return;
633 }
634
Patrick Williamsb7077432024-08-16 15:22:21 -0400635 nlohmann::json data =
636 nlohmann::json::parse(blocklistStream, nullptr, false);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700637 if (data.is_discarded())
638 {
Matt Simmering2447c242023-11-09 14:18:39 -0800639 std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
Patrick Venture11f1ff42019-08-01 10:42:12 -0700640 "exiting\n";
641 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700642 }
643
644 // It's expected to have at least one field, "buses" that is an array of the
645 // buses by integer. Allow for future options to exclude further aspects,
646 // such as specific addresses or ranges.
647 if (data.type() != nlohmann::json::value_t::object)
648 {
Matt Simmering2447c242023-11-09 14:18:39 -0800649 std::cerr << "Illegal blocklist, expected to read dictionary\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700650 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700651 }
652
653 // If buses field is missing, that's fine.
654 if (data.count("buses") == 1)
655 {
656 // Parse the buses array after a little validation.
657 auto buses = data.at("buses");
658 if (buses.type() != nlohmann::json::value_t::array)
659 {
660 // Buses field present but invalid, therefore this is an error.
Matt Simmering2447c242023-11-09 14:18:39 -0800661 std::cerr << "Invalid contents for blocklist buses field\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700662 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700663 }
664
665 // Catch exception here for type mis-match.
666 try
667 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800668 for (const auto& busIterator : buses)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700669 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800670 // If bus and addresses field are missing, that's fine.
671 if (busIterator.contains("bus") &&
672 busIterator.contains("addresses"))
673 {
674 auto busData = busIterator.at("bus");
675 auto bus = busData.get<size_t>();
676
677 auto addressData = busIterator.at("addresses");
678 auto addresses =
679 addressData.get<std::set<std::string_view>>();
680
Ed Tanousfc171422024-04-04 17:18:16 -0700681 auto& block = busBlocklist[bus].emplace();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800682 for (const auto& address : addresses)
683 {
684 size_t addressInt = 0;
685 std::from_chars(address.begin() + 2, address.end(),
686 addressInt, 16);
Ed Tanousfc171422024-04-04 17:18:16 -0700687 block.insert(addressInt);
Bonnie Lobfda2c42022-10-26 16:50:54 +0800688 }
689 }
690 else
691 {
Matt Simmering2447c242023-11-09 14:18:39 -0800692 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
Bonnie Lobfda2c42022-10-26 16:50:54 +0800693 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700694 }
695 }
696 catch (const nlohmann::detail::type_error& e)
697 {
698 // Type mis-match is a critical error.
699 std::cerr << "Invalid bus type: " << e.what() << "\n";
700 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700701 }
702 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700703}
704
Ed Tanous07d467b2021-02-23 14:48:37 -0800705static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800706 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530707 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800708{
Ed Tanous3013fb42022-07-09 08:27:06 -0700709 for (const auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800710 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700711 int bus = busStrToInt(i2cBus.string());
James Feist0c3980a2019-12-19 11:09:27 -0800712
James Feist5d7f4692020-06-17 18:22:33 -0700713 if (bus < 0)
714 {
715 std::cerr << "Cannot translate " << i2cBus << " to int\n";
716 continue;
717 }
Matt Simmering2447c242023-11-09 14:18:39 -0800718 auto busFind = busBlocklist.find(bus);
719 if (busFind != busBlocklist.end())
James Feist444830e2019-04-05 08:38:16 -0700720 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800721 if (busFind->second == std::nullopt)
722 {
723 continue; // Skip blocked busses.
724 }
James Feist444830e2019-04-05 08:38:16 -0700725 }
James Feist0c3980a2019-12-19 11:09:27 -0800726 int rootBus = getRootBus(bus);
Matt Simmering2447c242023-11-09 14:18:39 -0800727 auto rootBusFind = busBlocklist.find(rootBus);
728 if (rootBusFind != busBlocklist.end())
James Feist0c3980a2019-12-19 11:09:27 -0800729 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800730 if (rootBusFind->second == std::nullopt)
731 {
732 continue;
733 }
James Feist0c3980a2019-12-19 11:09:27 -0800734 }
735
James Feist3cb5fec2018-01-23 14:41:51 -0800736 auto file = open(i2cBus.c_str(), O_RDWR);
737 if (file < 0)
738 {
739 std::cerr << "unable to open i2c device " << i2cBus.string()
740 << "\n";
741 continue;
742 }
743 unsigned long funcs = 0;
744
745 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
746 {
747 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700748 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800749 << bus << "\n";
Zhikui Renc02d8cb2021-06-28 16:56:08 -0700750 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800751 continue;
752 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700753 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
754 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
James Feist3cb5fec2018-01-23 14:41:51 -0800755 {
756 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
757 << bus << "\n";
George Liu913d07d2024-12-09 19:16:30 +0800758 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800759 continue;
760 }
James Feist98132792019-07-09 13:29:09 -0700761 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800762 device = std::make_shared<DeviceMap>();
763
Nikhil Potaded8884f12019-03-27 13:27:13 -0700764 // i2cdetect by default uses the range 0x03 to 0x77, as
765 // this is what we have tested with, use this range. Could be
766 // changed in future.
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200767 lg2::debug("Scanning bus {BUS}", "BUS", bus);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700768
769 // fd is closed in this function in case the bus locks up
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530770 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700771
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200772 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
James Feist3cb5fec2018-01-23 14:41:51 -0800773 }
James Feist3cb5fec2018-01-23 14:41:51 -0800774}
775
James Feist6ebf9de2018-05-15 15:01:17 -0700776// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700777struct FindDevicesWithCallback :
778 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700779{
James Feista465ccc2019-02-08 12:51:01 -0800780 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800781 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530782 sdbusplus::asio::object_server& objServer,
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800783 std::function<void()>&& callback) :
Patrick Williamsb7077432024-08-16 15:22:21 -0400784 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
785 _objServer(objServer), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700786 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700787 ~FindDevicesWithCallback()
788 {
789 _callback();
790 }
791 void run()
792 {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530793 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
James Feist6ebf9de2018-05-15 15:01:17 -0700794 }
795
James Feista465ccc2019-02-08 12:51:01 -0800796 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800797 BusMap& _busMap;
Jonathan Doman2418a612022-02-14 18:20:58 -0800798 const bool& _powerIsOn;
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530799 sdbusplus::asio::object_server& _objServer;
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800800 std::function<void()> _callback;
James Feist6ebf9de2018-05-15 15:01:17 -0700801};
802
Ed Tanous07d467b2021-02-23 14:48:37 -0800803void addFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300804 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800805 boost::container::flat_map<
806 std::pair<size_t, size_t>,
807 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +0530808 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
Jonathan Doman2418a612022-02-14 18:20:58 -0800809 const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530810 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist3cb5fec2018-01-23 14:41:51 -0800811{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300812 boost::container::flat_map<std::string, std::string> formattedFRU;
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530813
814 std::optional<std::string> optionalProductName = getProductName(
815 device, formattedFRU, bus, address, unknownBusObjectCount);
816 if (!optionalProductName)
James Feist3cb5fec2018-01-23 14:41:51 -0800817 {
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530818 std::cerr << "getProductName failed. product name is empty.\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800819 return;
820 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700821
Patrick Williamsb7077432024-08-16 15:22:21 -0400822 std::string productName =
823 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
James Feist3cb5fec2018-01-23 14:41:51 -0800824
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530825 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
826 if (index.has_value())
James Feist918e18c2018-02-13 15:51:07 -0800827 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530828 productName += "_";
829 productName += std::to_string(++(*index));
James Feist918e18c2018-02-13 15:51:07 -0800830 }
James Feist3cb5fec2018-01-23 14:41:51 -0800831
James Feist9eb0b582018-04-27 12:15:46 -0700832 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
833 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
834 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
835
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300836 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800837 {
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700838 std::regex_replace(property.second.begin(), property.second.begin(),
Ed Tanous07d467b2021-02-23 14:48:37 -0800839 property.second.end(), nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530840 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -0700841 {
842 continue;
843 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400844 std::string key =
845 std::regex_replace(property.first, nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530846
847 if (property.first == "PRODUCT_ASSET_TAG")
848 {
849 std::string propertyName = property.first;
850 iface->register_property(
851 key, property.second + '\0',
Kumar Thangavel41a90512021-11-24 15:44:20 +0530852 [bus, address, propertyName, &dbusInterfaceMap,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530853 &unknownBusObjectCount, &powerIsOn, &objServer,
854 &systemBus](const std::string& req, std::string& resp) {
Patrick Williamsb7077432024-08-16 15:22:21 -0400855 if (strcmp(req.c_str(), resp.c_str()) != 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +0530856 {
Patrick Williamsb7077432024-08-16 15:22:21 -0400857 // call the method which will update
858 if (updateFRUProperty(req, bus, address, propertyName,
859 dbusInterfaceMap,
860 unknownBusObjectCount, powerIsOn,
861 objServer, systemBus))
862 {
863 resp = req;
864 }
865 else
866 {
867 throw std::invalid_argument(
868 "FRU property update failed.");
869 }
Joshi-Mansid73b7442020-03-27 19:10:21 +0530870 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400871 return 1;
872 });
Joshi-Mansid73b7442020-03-27 19:10:21 +0530873 }
874 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -0700875 {
876 std::cerr << "illegal key: " << key << "\n";
877 }
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200878 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
879 property.first, "SECOND", property.second);
James Feist3cb5fec2018-01-23 14:41:51 -0800880 }
James Feist2a9d6db2018-04-27 15:48:28 -0700881
882 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700883 iface->register_property("BUS", bus);
884 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700885
James Feist9eb0b582018-04-27 12:15:46 -0700886 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800887}
888
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300889static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800890{
891 // try to read baseboard fru from file
Ed Tanous07d467b2021-02-23 14:48:37 -0800892 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300893 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -0800894 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300895 baseboardFRUFile.seekg(0, std::ios_base::end);
896 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
897 baseboardFRU.resize(fileSize);
898 baseboardFRUFile.seekg(0, std::ios_base::beg);
Ed Tanous3013fb42022-07-09 08:27:06 -0700899 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
900 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
901 baseboardFRUFile.read(charOffset, fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -0800902 }
903 else
904 {
905 return false;
906 }
907 return true;
908}
909
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300910bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700911{
912 boost::container::flat_map<std::string, std::string> tmp;
Ed Tanous07d467b2021-02-23 14:48:37 -0800913 if (fru.size() > maxFruSize)
James Feistb49ffc32018-05-02 11:10:43 -0700914 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300915 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700916 return false;
917 }
918 // verify legal fru by running it through fru parsing logic
Michael Shen0961b112022-02-22 11:06:33 +0800919 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -0700920 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300921 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700922 return false;
923 }
924 // baseboard fru
925 if (bus == 0 && address == 0)
926 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800927 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
James Feistb49ffc32018-05-02 11:10:43 -0700928 if (!file.good())
929 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800930 std::cerr << "Error opening file " << baseboardFruLocation << "\n";
James Feistddb78302018-09-06 11:45:42 -0700931 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700932 return false;
933 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700934 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
935 const char* charOffset = reinterpret_cast<const char*>(fru.data());
936 file.write(charOffset, fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700937 return file.good();
938 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800939
940 if (hasEepromFile(bus, address))
James Feistb49ffc32018-05-02 11:10:43 -0700941 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800942 auto path = getEepromPath(bus, address);
Naresh Solanki41ee1802024-11-09 01:44:46 +0530943 off_t offset = 0;
944
Ed Tanous07d467b2021-02-23 14:48:37 -0800945 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
946 if (eeprom < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700947 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800948 std::cerr << "unable to open i2c device " << path << "\n";
949 throw DBusInternalError();
950 return false;
951 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700952
Naresh Solanki41ee1802024-11-09 01:44:46 +0530953 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
954 std::string errorMessage = "eeprom at " + std::to_string(bus) +
955 " address " + std::to_string(address);
956 auto readFunc = [eeprom](off_t offset, size_t length, uint8_t* outbuf) {
957 return readFromEeprom(eeprom, offset, length, outbuf);
958 };
959 FRUReader reader(std::move(readFunc));
960
961 if (!findFRUHeader(reader, errorMessage, blockData, offset))
962 {
963 offset = 0;
964 }
965
966 if (lseek(eeprom, offset, SEEK_SET) < 0)
967 {
968 std::cerr << "Unable to seek to offset " << offset
969 << " in device: " << path << "\n";
970 close(eeprom);
971 throw DBusInternalError();
972 }
973
Ed Tanous07d467b2021-02-23 14:48:37 -0800974 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
975 if (writtenBytes < 0)
976 {
977 std::cerr << "unable to write to i2c device " << path << "\n";
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700978 close(eeprom);
James Feistddb78302018-09-06 11:45:42 -0700979 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700980 return false;
981 }
982
Ed Tanous07d467b2021-02-23 14:48:37 -0800983 close(eeprom);
James Feistb49ffc32018-05-02 11:10:43 -0700984 return true;
985 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800986
987 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
988
989 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
990 if (file < 0)
991 {
992 std::cerr << "unable to open i2c device " << i2cBus << "\n";
993 throw DBusInternalError();
994 return false;
995 }
996 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
997 {
998 std::cerr << "unable to set device address\n";
999 close(file);
1000 throw DBusInternalError();
1001 return false;
1002 }
1003
1004 constexpr const size_t retryMax = 2;
1005 uint16_t index = 0;
1006 size_t retries = retryMax;
1007 while (index < fru.size())
1008 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001009 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
Ed Tanous07d467b2021-02-23 14:48:37 -08001010 (retries == retryMax))
1011 {
1012 // The 4K EEPROM only uses the A2 and A1 device address bits
1013 // with the third bit being a memory page address bit.
1014 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1015 {
1016 std::cerr << "unable to set device address\n";
1017 close(file);
1018 throw DBusInternalError();
1019 return false;
1020 }
1021 }
1022
1023 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1024 fru[index]) < 0)
1025 {
Ed Tanous3013fb42022-07-09 08:27:06 -07001026 if ((retries--) == 0U)
Ed Tanous07d467b2021-02-23 14:48:37 -08001027 {
1028 std::cerr << "error writing fru: " << strerror(errno) << "\n";
1029 close(file);
1030 throw DBusInternalError();
1031 return false;
1032 }
1033 }
1034 else
1035 {
1036 retries = retryMax;
1037 index++;
1038 }
1039 // most eeproms require 5-10ms between writes
1040 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1041 }
1042 close(file);
1043 return true;
James Feistb49ffc32018-05-02 11:10:43 -07001044}
1045
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001046void rescanOneBus(
krishnar4213ee212022-11-11 15:39:30 +05301047 BusMap& busmap, uint16_t busNum,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001048 boost::container::flat_map<
1049 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001050 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001051 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301052 sdbusplus::asio::object_server& objServer,
1053 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001054{
Yong Li6fdfac02023-10-30 11:21:30 +08001055 for (auto device = foundDevices.begin(); device != foundDevices.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001056 {
Yong Li6fdfac02023-10-30 11:21:30 +08001057 if (device->first.first == static_cast<size_t>(busNum))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001058 {
Yong Li6fdfac02023-10-30 11:21:30 +08001059 objServer.remove_interface(device->second);
1060 device = foundDevices.erase(device);
1061 }
1062 else
1063 {
1064 device++;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001065 }
1066 }
1067
James Feist5d7f4692020-06-17 18:22:33 -07001068 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1069 if (!fs::exists(busPath))
1070 {
1071 if (dbusCall)
1072 {
1073 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1074 << "\n";
1075 throw std::invalid_argument("Invalid Bus.");
1076 }
1077 return;
1078 }
1079
1080 std::vector<fs::path> i2cBuses;
1081 i2cBuses.emplace_back(busPath);
1082
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001083 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301084 i2cBuses, busmap, powerIsOn, objServer,
1085 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1086 &objServer, &systemBus]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001087 for (auto busIface = dbusInterfaceMap.begin();
1088 busIface != dbusInterfaceMap.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001089 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001090 if (busIface->first.first == static_cast<size_t>(busNum))
1091 {
1092 objServer.remove_interface(busIface->second);
1093 busIface = dbusInterfaceMap.erase(busIface);
1094 }
1095 else
1096 {
1097 busIface++;
1098 }
Yong Li6fdfac02023-10-30 11:21:30 +08001099 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001100 auto found = busmap.find(busNum);
1101 if (found == busmap.end() || found->second == nullptr)
Yong Li6fdfac02023-10-30 11:21:30 +08001102 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001103 return;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001104 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001105 for (auto& device : *(found->second))
1106 {
1107 addFruObjectToDbus(device.second, dbusInterfaceMap,
1108 static_cast<uint32_t>(busNum), device.first,
1109 unknownBusObjectCount, powerIsOn, objServer,
1110 systemBus);
1111 }
1112 });
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001113 scan->run();
1114}
1115
James Feist9eb0b582018-04-27 12:15:46 -07001116void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001117 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001118 boost::container::flat_map<
1119 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301120 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001121 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301122 sdbusplus::asio::object_server& objServer,
1123 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist918e18c2018-02-13 15:51:07 -08001124{
Ed Tanousaa497ed2023-02-28 13:43:41 -08001125 static boost::asio::steady_timer timer(io);
Ed Tanousae2d4352025-02-12 15:51:48 -08001126 timer.expires_after(std::chrono::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001127
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001128 // setup an async wait in case we get flooded with requests
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001129 timer.async_wait([&](const boost::system::error_code& ec) {
1130 if (ec == boost::asio::error::operation_aborted)
1131 {
1132 return;
1133 }
1134
1135 if (ec)
1136 {
1137 std::cerr << "Error in timer: " << ec.message() << "\n";
1138 return;
1139 }
1140
James Feist4131aea2018-03-09 09:47:30 -08001141 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001142 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001143
Nikhil Potaded8884f12019-03-27 13:27:13 -07001144 boost::container::flat_map<size_t, fs::path> busPaths;
1145 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001146 {
James Feist4131aea2018-03-09 09:47:30 -08001147 std::cerr << "unable to find i2c devices\n";
1148 return;
James Feist918e18c2018-02-13 15:51:07 -08001149 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001150
Ed Tanous07d467b2021-02-23 14:48:37 -08001151 for (const auto& busPath : busPaths)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001152 {
1153 i2cBuses.emplace_back(busPath.second);
1154 }
James Feist4131aea2018-03-09 09:47:30 -08001155
James Feist98132792019-07-09 13:29:09 -07001156 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001157 for (auto& [pair, interface] : foundDevices)
1158 {
1159 objServer.remove_interface(interface);
1160 }
1161 foundDevices.clear();
1162
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301163 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301164 i2cBuses, busmap, powerIsOn, objServer, [&]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001165 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001166 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001167 objServer.remove_interface(busIface.second);
James Feist6ebf9de2018-05-15 15:01:17 -07001168 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001169
1170 dbusInterfaceMap.clear();
1171 unknownBusObjectCount = 0;
1172
1173 // todo, get this from a more sensable place
1174 std::vector<uint8_t> baseboardFRU;
1175 if (readBaseboardFRU(baseboardFRU))
1176 {
1177 // If no device on i2c bus 0, the insertion will happen.
1178 auto bus0 =
1179 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1180 bus0.first->second->emplace(0, baseboardFRU);
1181 }
1182 for (auto& devicemap : busmap)
1183 {
1184 for (auto& device : *devicemap.second)
1185 {
1186 addFruObjectToDbus(device.second, dbusInterfaceMap,
1187 devicemap.first, device.first,
1188 unknownBusObjectCount, powerIsOn,
1189 objServer, systemBus);
1190 }
1191 }
1192 });
James Feist6ebf9de2018-05-15 15:01:17 -07001193 scan->run();
1194 });
James Feist918e18c2018-02-13 15:51:07 -08001195}
1196
Joshi-Mansid73b7442020-03-27 19:10:21 +05301197// Details with example of Asset Tag Update
1198// To find location of Product Info Area asset tag as per FRU specification
1199// 1. Find product Info area starting offset (*8 - as header will be in
1200// multiple of 8 bytes).
1201// 2. Skip 3 bytes of product info area (like format version, area length,
1202// and language code).
1203// 3. Traverse manufacturer name, product name, product version, & product
1204// serial number, by reading type/length code to reach the Asset Tag.
1205// 4. Update the Asset Tag, reposition the product Info area in multiple of
1206// 8 bytes. Update the Product area length and checksum.
1207
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001208bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301209 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -08001210 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301211 boost::container::flat_map<
1212 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301213 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001214 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301215 sdbusplus::asio::object_server& objServer,
1216 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301217{
1218 size_t updatePropertyReqLen = updatePropertyReq.length();
1219 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1220 {
1221 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001222 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301223 "Invalid Length "
1224 << updatePropertyReqLen << "\n";
1225 return false;
1226 }
1227
1228 std::vector<uint8_t> fruData;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301229
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301230 if (!getFruData(fruData, bus, address))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301231 {
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301232 std::cerr << "Failure getting FRU Data \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301233 return false;
1234 }
1235
Patrick Williamsa41f0142024-12-18 11:22:53 -05001236 struct FruArea fruAreaParams{};
Joshi-Mansid73b7442020-03-27 19:10:21 +05301237
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301238 if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301239 {
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301240 std::cerr << "findFruAreaLocationAndField failed \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301241 return false;
1242 }
1243
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301244 std::vector<uint8_t> restFRUAreaFieldsData;
1245 if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1246 restFRUAreaFieldsData))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301247 {
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301248 std::cerr << "copyRestFRUArea failed \n";
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001249 return false;
1250 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301251
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001252 // Push post update fru areas if any
1253 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001254 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1255 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001256 {
1257 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001258 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301259 if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001260 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1261 {
1262 nextFRUAreaLoc = fruAreaLoc;
1263 }
1264 }
1265 std::vector<uint8_t> restFRUAreasData;
Ed Tanous3013fb42022-07-09 08:27:06 -07001266 if (nextFRUAreaLoc != 0U)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001267 {
1268 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1269 fruData.size() - nextFRUAreaLoc,
1270 std::back_inserter(restFRUAreasData));
1271 }
1272
1273 // check FRU area size
1274 size_t fruAreaDataSize =
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301275 ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1276 restFRUAreaFieldsData.size());
1277 size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001278 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1279 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001280#ifdef ENABLE_FRU_AREA_RESIZE
1281 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1282 // round size to 8-byte blocks
Patrick Williamsb7077432024-08-16 15:22:21 -04001283 newFRUAreaSize =
1284 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1285 size_t newFRUDataSize =
1286 fruData.size() + newFRUAreaSize - fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001287 fruData.resize(newFRUDataSize);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301288 fruAreaParams.size = newFRUAreaSize;
1289 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001290#else
1291 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1292 << " should not be greater than available FRU area size: "
1293 << fruAreaAvailableSize << "\n";
1294 return false;
1295#endif // ENABLE_FRU_AREA_RESIZE
1296 }
1297
Joshi-Mansid73b7442020-03-27 19:10:21 +05301298 // write new requested property field length and data
1299 constexpr uint8_t newTypeLenMask = 0xC0;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301300 fruData[fruAreaParams.updateFieldLoc] =
Joshi-Mansid73b7442020-03-27 19:10:21 +05301301 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301302 fruAreaParams.updateFieldLoc++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301303 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301304 fruData.begin() + fruAreaParams.updateFieldLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301305
1306 // Copy remaining data to main fru area - post updated fru field vector
Patrick Williamsb7077432024-08-16 15:22:21 -04001307 fruAreaParams.restFieldsLoc =
1308 fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1309 size_t fruAreaDataEnd =
1310 fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301311
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001312 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301313 fruData.begin() + fruAreaParams.restFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301314
1315 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001316 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301317 fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301318
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001319#ifdef ENABLE_FRU_AREA_RESIZE
1320 ++nextFRUAreaNewLoc;
Patrick Williamsb7077432024-08-16 15:22:21 -04001321 ssize_t nextFRUAreaOffsetDiff =
1322 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001323 // Append rest FRU Areas if size changed and there were other sections after
1324 // updated one
1325 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1326 {
1327 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1328 fruData.begin() + nextFRUAreaNewLoc);
1329 // Update Common Header
Ed Tanous6e22c872023-02-16 15:19:28 -08001330 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1331 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001332 {
Ed Tanous6e22c872023-02-16 15:19:28 -08001333 unsigned int fruAreaOffsetField =
1334 getHeaderAreaFieldOffset(nextFRUArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001335 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
Ed Tanous6e22c872023-02-16 15:19:28 -08001336 if (curFRUAreaOffset > fruAreaParams.end)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001337 {
1338 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1339 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1340 }
1341 }
1342 // Calculate new checksum
1343 std::vector<uint8_t> headerFRUData;
1344 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1345 size_t checksumVal = calculateChecksum(headerFRUData);
1346 fruData[7] = static_cast<uint8_t>(checksumVal);
1347 // fill zeros if FRU Area size decreased
1348 if (nextFRUAreaOffsetDiff < 0)
1349 {
1350 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1351 restFRUAreasData.size(),
1352 fruData.end(), 0);
1353 }
1354 }
1355#else
1356 // this is to avoid "unused variable" warning
1357 (void)nextFRUAreaNewLoc;
1358#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301359 if (fruData.empty())
1360 {
1361 return false;
1362 }
1363
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001364 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301365 fruData))
1366 {
1367 return false;
1368 }
1369
1370 // Rescan the bus so that GetRawFru dbus-call fetches updated values
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301371 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1372 objServer, systemBus);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301373 return true;
1374}
1375
James Feist98132792019-07-09 13:29:09 -07001376int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001377{
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301378 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1379 sdbusplus::asio::object_server objServer(systemBus);
1380
Kumar Thangavel41a90512021-11-24 15:44:20 +05301381 static size_t unknownBusObjectCount = 0;
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301382 static bool powerIsOn = false;
James Feist3cb5fec2018-01-23 14:41:51 -08001383 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001384 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001385 std::vector<fs::path> i2cBuses;
1386
James Feista3c180a2018-08-09 16:06:04 -07001387 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001388 {
1389 std::cerr << "unable to find i2c devices\n";
1390 return 1;
1391 }
James Feist3cb5fec2018-01-23 14:41:51 -08001392
Matt Simmering2447c242023-11-09 14:18:39 -08001393 // check for and load blocklist with initial buses.
1394 loadBlocklist(blocklistPath);
Patrick Venture11f1ff42019-08-01 10:42:12 -07001395
Vijay Khemka065f6d92018-12-18 10:37:47 -08001396 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001397
James Feist6ebf9de2018-05-15 15:01:17 -07001398 // this is a map with keys of pair(bus number, address) and values of
1399 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001400 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001401 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1402 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001403
James Feist9eb0b582018-04-27 12:15:46 -07001404 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1405 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1406 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001407
Kumar Thangavel41a90512021-11-24 15:44:20 +05301408 iface->register_method("ReScan", [&]() {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301409 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1410 objServer, systemBus);
Kumar Thangavel41a90512021-11-24 15:44:20 +05301411 });
James Feist2a9d6db2018-04-27 15:48:28 -07001412
krishnar4213ee212022-11-11 15:39:30 +05301413 iface->register_method("ReScanBus", [&](uint16_t bus) {
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301414 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301415 powerIsOn, objServer, systemBus);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001416 });
1417
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001418 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001419
Patrick Williamsb7077432024-08-16 15:22:21 -04001420 iface->register_method(
1421 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1422 const std::vector<uint8_t>& data) {
1423 if (!writeFRU(bus, address, data))
1424 {
1425 throw std::invalid_argument("Invalid Arguments.");
1426 return;
1427 }
1428 // schedule rescan on success
1429 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1430 powerIsOn, objServer, systemBus);
1431 });
James Feist9eb0b582018-04-27 12:15:46 -07001432 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001433
Patrick Williams2af39222022-07-22 19:26:56 -05001434 std::function<void(sdbusplus::message_t & message)> eventHandler =
1435 [&](sdbusplus::message_t& message) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001436 std::string objectName;
1437 boost::container::flat_map<
1438 std::string,
1439 std::variant<std::string, bool, int64_t, uint64_t, double>>
1440 values;
1441 message.read(objectName, values);
1442 auto findState = values.find("CurrentHostState");
1443 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001444 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001445 if (std::get<std::string>(findState->second) ==
1446 "xyz.openbmc_project.State.Host.HostState.Running")
1447 {
1448 powerIsOn = true;
1449 }
James Feist0eeb79c2019-10-09 13:35:29 -07001450 }
James Feist6ebf9de2018-05-15 15:01:17 -07001451
Patrick Williamsb7077432024-08-16 15:22:21 -04001452 if (powerIsOn)
1453 {
1454 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1455 powerIsOn, objServer, systemBus);
1456 }
1457 };
James Feist9eb0b582018-04-27 12:15:46 -07001458
Patrick Williams2af39222022-07-22 19:26:56 -05001459 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1460 static_cast<sdbusplus::bus_t&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001461 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001462 "openbmc_project/state/"
1463 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001464 eventHandler);
1465
James Feist4131aea2018-03-09 09:47:30 -08001466 int fd = inotify_init();
Ed Tanous07d467b2021-02-23 14:48:37 -08001467 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
Ed Tanous3013fb42022-07-09 08:27:06 -07001468 std::array<char, 4096> readBuffer{};
James Feist4131aea2018-03-09 09:47:30 -08001469 // monitor for new i2c devices
1470 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1471 std::function<void(const boost::system::error_code, std::size_t)>
Patrick Williamsb9dd7f82023-10-20 11:20:11 -05001472 watchI2cBusses = [&](const boost::system::error_code& ec,
1473 std::size_t bytesTransferred) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001474 if (ec)
James Feist4131aea2018-03-09 09:47:30 -08001475 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001476 std::cout << "Callback Error " << ec << "\n";
1477 return;
1478 }
1479 size_t index = 0;
1480 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1481 {
1482 const char* p = &readBuffer[index];
1483 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1484 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1485 switch (iEvent->mask)
Ed Tanousfc171422024-04-04 17:18:16 -07001486 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001487 case IN_CREATE:
1488 case IN_MOVED_TO:
1489 case IN_DELETE:
Patrick Williamsdf190612023-05-10 07:51:34 -05001490 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001491 std::string_view name(&iEvent->name[0], iEvent->len);
1492 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001493 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001494 int bus = busStrToInt(name);
1495 if (bus < 0)
1496 {
1497 std::cerr
1498 << "Could not parse bus " << name << "\n";
1499 continue;
1500 }
1501 int rootBus = getRootBus(bus);
1502 if (rootBus >= 0)
1503 {
1504 rescanOneBus(busMap,
1505 static_cast<uint16_t>(rootBus),
1506 dbusInterfaceMap, false,
1507 unknownBusObjectCount, powerIsOn,
1508 objServer, systemBus);
1509 }
1510 rescanOneBus(busMap, static_cast<uint16_t>(bus),
Kumar Thangavel41a90512021-11-24 15:44:20 +05301511 dbusInterfaceMap, false,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301512 unknownBusObjectCount, powerIsOn,
1513 objServer, systemBus);
James Feist9eb0b582018-04-27 12:15:46 -07001514 }
Patrick Williamsdf190612023-05-10 07:51:34 -05001515 }
Ed Tanousfc171422024-04-04 17:18:16 -07001516 break;
Patrick Williamsb7077432024-08-16 15:22:21 -04001517 default:
1518 break;
1519 }
1520 index += sizeof(inotify_event) + iEvent->len;
James Feist4131aea2018-03-09 09:47:30 -08001521 }
James Feist6ebf9de2018-05-15 15:01:17 -07001522
Patrick Williamsb7077432024-08-16 15:22:21 -04001523 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1524 watchI2cBusses);
1525 };
James Feist4131aea2018-03-09 09:47:30 -08001526
1527 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001528 // run the initial scan
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301529 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1530 objServer, systemBus);
James Feist918e18c2018-02-13 15:51:07 -08001531
James Feist3cb5fec2018-01-23 14:41:51 -08001532 io.run();
1533 return 0;
1534}