blob: f2452f5c5cce1d99cf808476c79dd5f17da1079f [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
Ed Tanousfc171422024-04-04 17:18:16 -070075// TODO Refactor these to not be globals
76// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
Bonnie Lobfda2c42022-10-26 16:50:54 +080077static boost::container::flat_map<size_t, std::optional<std::set<size_t>>>
Matt Simmering2447c242023-11-09 14:18:39 -080078 busBlocklist;
James Feist6ebf9de2018-05-15 15:01:17 -070079struct FindDevicesWithCallback;
80
James Feist8a983922019-10-24 17:11:56 -070081static boost::container::flat_map<
82 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
83 foundDevices;
84
James Feist7972bb92019-11-13 15:59:24 -080085static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +000086static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
James Feist7972bb92019-11-13 15:59:24 -080087
Ed Tanous34c3e012023-03-06 13:42:00 -080088boost::asio::io_context io;
Ed Tanousfc171422024-04-04 17:18:16 -070089// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
James Feist5cb06082019-10-24 17:11:13 -070090
Andrei Kartashev2f0de172020-08-13 14:29:40 +030091bool updateFRUProperty(
Ed Tanous3013fb42022-07-09 08:27:06 -070092 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -080093 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +053094 boost::container::flat_map<
95 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +053096 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -080097 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +053098 sdbusplus::asio::object_server& objServer,
99 std::shared_ptr<sdbusplus::asio::connection>& systemBus);
Patrick Venturebaba7672019-10-26 09:26:41 -0700100
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700101// Given a bus/address, produce the path in sysfs for an eeprom.
102static std::string getEepromPath(size_t bus, size_t address)
103{
104 std::stringstream output;
105 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
106 << std::setfill('0') << std::setw(4) << std::hex << address
107 << "/eeprom";
108 return output.str();
109}
110
111static bool hasEepromFile(size_t bus, size_t address)
112{
113 auto path = getEepromPath(bus, address);
114 try
115 {
116 return fs::exists(path);
117 }
118 catch (...)
119 {
120 return false;
121 }
122}
123
Zev Weiss309c0b12022-02-25 01:44:12 +0000124static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700125{
126 auto result = lseek(fd, offset, SEEK_SET);
127 if (result < 0)
128 {
129 std::cerr << "failed to seek\n";
130 return -1;
131 }
132
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700133 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700134}
135
Ed Tanous3013fb42022-07-09 08:27:06 -0700136static int busStrToInt(const std::string_view busName)
James Feist5d7f4692020-06-17 18:22:33 -0700137{
Ed Tanous07d467b2021-02-23 14:48:37 -0800138 auto findBus = busName.rfind('-');
James Feist5d7f4692020-06-17 18:22:33 -0700139 if (findBus == std::string::npos)
140 {
141 return -1;
142 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700143 std::string_view num = busName.substr(findBus + 1);
144 int val = 0;
145 std::from_chars(num.data(), num.data() + num.size(), val);
146 return val;
James Feist5d7f4692020-06-17 18:22:33 -0700147}
148
James Feist7972bb92019-11-13 15:59:24 -0800149static int getRootBus(size_t bus)
150{
151 auto ec = std::error_code();
152 auto path = std::filesystem::read_symlink(
Patrick Williamsb7077432024-08-16 15:22:21 -0400153 std::filesystem::path(
154 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"),
James Feist7972bb92019-11-13 15:59:24 -0800155 ec);
156 if (ec)
157 {
158 return -1;
159 }
160
161 std::string filename = path.filename();
Ed Tanous07d467b2021-02-23 14:48:37 -0800162 auto findBus = filename.find('-');
James Feist7972bb92019-11-13 15:59:24 -0800163 if (findBus == std::string::npos)
164 {
165 return -1;
166 }
167 return std::stoi(filename.substr(0, findBus));
168}
169
James Feistc95cb142018-02-26 10:41:42 -0800170static bool isMuxBus(size_t bus)
171{
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700172 auto ec = std::error_code();
173 auto isSymlink =
174 is_symlink(std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
175 std::to_string(bus) + "/mux_device"),
176 ec);
177 return (!ec && isSymlink);
James Feistc95cb142018-02-26 10:41:42 -0800178}
179
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530180static void makeProbeInterface(size_t bus, size_t address,
181 sdbusplus::asio::object_server& objServer)
James Feist8a983922019-10-24 17:11:56 -0700182{
183 if (isMuxBus(bus))
184 {
185 return; // the mux buses are random, no need to publish
186 }
187 auto [it, success] = foundDevices.emplace(
188 std::make_pair(bus, address),
189 objServer.add_interface(
190 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
191 std::to_string(address),
192 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
193 if (!success)
194 {
195 return; // already added
196 }
197 it->second->register_property("Bus", bus);
198 it->second->register_property("Address", address);
199 it->second->initialize();
200}
201
Zev Weiss309c0b12022-02-25 01:44:12 +0000202static std::optional<bool> isDevice16Bit(int file)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800203{
Jae Hyun Yoof805baf2022-04-01 16:22:28 -0700204 // Set the higher data word address bits to 0. It's safe on 8-bit addressing
205 // EEPROMs because it doesn't write any actual data.
206 int ret = i2c_smbus_write_byte(file, 0);
207 if (ret < 0)
208 {
Zev Weiss309c0b12022-02-25 01:44:12 +0000209 return std::nullopt;
Jae Hyun Yoof805baf2022-04-01 16:22:28 -0700210 }
211
Vijay Khemka2d681f62018-11-06 15:51:00 -0800212 /* Get first byte */
213 int byte1 = i2c_smbus_read_byte_data(file, 0);
214 if (byte1 < 0)
215 {
Zev Weiss309c0b12022-02-25 01:44:12 +0000216 return std::nullopt;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800217 }
218 /* Read 7 more bytes, it will read same first byte in case of
219 * 8 bit but it will read next byte in case of 16 bit
220 */
221 for (int i = 0; i < 7; i++)
222 {
223 int byte2 = i2c_smbus_read_byte_data(file, 0);
224 if (byte2 < 0)
225 {
Zev Weiss309c0b12022-02-25 01:44:12 +0000226 return std::nullopt;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800227 }
228 if (byte2 != byte1)
229 {
Zev Weiss309c0b12022-02-25 01:44:12 +0000230 return true;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800231 }
232 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000233 return false;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800234}
235
Matt Simmering2447c242023-11-09 14:18:39 -0800236// Issue an I2C transaction to first write to_target_buf_len bytes,then read
237// from_target_buf_len bytes.
Patrick Williamsb7077432024-08-16 15:22:21 -0400238static int i2cSmbusWriteThenRead(
239 int file, uint16_t address, uint8_t* toTargetBuf, uint8_t toTargetBufLen,
240 uint8_t* fromTargetBuf, uint8_t fromTargetBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800241{
Matt Simmering2447c242023-11-09 14:18:39 -0800242 if (toTargetBuf == nullptr || toTargetBufLen == 0 ||
243 fromTargetBuf == nullptr || fromTargetBufLen == 0)
Xiang Liu2801a702020-01-20 14:29:34 -0800244 {
245 return -1;
246 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800247
Ed Tanous3013fb42022-07-09 08:27:06 -0700248 constexpr size_t smbusWriteThenReadMsgCount = 2;
249 std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
250 struct i2c_rdwr_ioctl_data rdwr
251 {};
Xiang Liu2801a702020-01-20 14:29:34 -0800252
253 msgs[0].addr = address;
254 msgs[0].flags = 0;
Matt Simmering2447c242023-11-09 14:18:39 -0800255 msgs[0].len = toTargetBufLen;
256 msgs[0].buf = toTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800257 msgs[1].addr = address;
258 msgs[1].flags = I2C_M_RD;
Matt Simmering2447c242023-11-09 14:18:39 -0800259 msgs[1].len = fromTargetBufLen;
260 msgs[1].buf = fromTargetBuf;
Xiang Liu2801a702020-01-20 14:29:34 -0800261
Ed Tanous3013fb42022-07-09 08:27:06 -0700262 rdwr.msgs = msgs.data();
263 rdwr.nmsgs = msgs.size();
Xiang Liu2801a702020-01-20 14:29:34 -0800264
265 int ret = ioctl(file, I2C_RDWR, &rdwr);
266
Jason M. Billsf6e4c1f2022-08-19 12:23:51 -0700267 return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
Xiang Liu2801a702020-01-20 14:29:34 -0800268}
269
Marvin Drees2b3ed302023-04-14 16:35:14 +0200270static int64_t readData(bool is16bit, bool isBytewise, int file,
271 uint16_t address, off_t offset, size_t len,
272 uint8_t* buf)
Xiang Liu2801a702020-01-20 14:29:34 -0800273{
Zev Weiss309c0b12022-02-25 01:44:12 +0000274 if (!is16bit)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800275 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200276 if (!isBytewise)
277 {
278 return i2c_smbus_read_i2c_block_data(
279 file, static_cast<uint8_t>(offset), len, buf);
280 }
281
282 std::span<uint8_t> bufspan{buf, len};
283 for (size_t i = 0; i < len; i++)
284 {
285 int byte = i2c_smbus_read_byte_data(
286 file, static_cast<uint8_t>(offset + i));
287 if (byte < 0)
288 {
289 return static_cast<int64_t>(byte);
290 }
291 bufspan[i] = static_cast<uint8_t>(byte);
292 }
293 return static_cast<int64_t>(len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800294 }
295
Xiang Liu2801a702020-01-20 14:29:34 -0800296 offset = htobe16(offset);
Ed Tanous3013fb42022-07-09 08:27:06 -0700297 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
298 uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
299 return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800300}
301
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700302// TODO: This code is very similar to the non-eeprom version and can be merged
303// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300304static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700305{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700306 auto path = getEepromPath(bus, address);
307
308 int file = open(path.c_str(), O_RDONLY);
309 if (file < 0)
310 {
311 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700312 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700313 }
314
Patrick Venturebaba7672019-10-26 09:26:41 -0700315 std::string errorMessage = "eeprom at " + std::to_string(bus) +
316 " address " + std::to_string(address);
Zev Weiss309c0b12022-02-25 01:44:12 +0000317 auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
318 return readFromEeprom(file, offset, length, outbuf);
319 };
320 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400321 std::pair<std::vector<uint8_t>, bool> pair =
322 readFRUContents(reader, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700323
324 close(file);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200325 return pair.first;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700326}
327
Bonnie Lobfda2c42022-10-26 16:50:54 +0800328std::set<size_t> findI2CEeproms(int i2cBus,
329 const std::shared_ptr<DeviceMap>& devices)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700330{
Bonnie Lobfda2c42022-10-26 16:50:54 +0800331 std::set<size_t> foundList;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700332
333 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
334
335 // For each file listed under the i2c device
336 // NOTE: This should be faster than just checking for each possible address
337 // path.
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700338 auto ec = std::error_code();
339 for (const auto& p : fs::directory_iterator(path, ec))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700340 {
Zhikui Ren8af5d3c2023-08-09 20:35:35 -0700341 if (ec)
342 {
343 std::cerr << "directory_iterator err " << ec.message() << "\n";
344 break;
345 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700346 const std::string node = p.path().string();
347 std::smatch m;
Patrick Williamsb7077432024-08-16 15:22:21 -0400348 bool found =
349 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700350
351 if (!found)
352 {
353 continue;
354 }
355 if (m.size() != 2)
356 {
357 std::cerr << "regex didn't capture\n";
358 continue;
359 }
360
361 std::ssub_match subMatch = m[1];
362 std::string addressString = subMatch.str();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800363 std::string_view addressStringView(addressString);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700364
Bonnie Lobfda2c42022-10-26 16:50:54 +0800365 size_t address = 0;
366 std::from_chars(addressStringView.begin(), addressStringView.end(),
367 address, 16);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700368
369 const std::string eeprom = node + "/eeprom";
370
371 try
372 {
373 if (!fs::exists(eeprom))
374 {
375 continue;
376 }
377 }
378 catch (...)
379 {
380 continue;
381 }
382
383 // There is an eeprom file at this address, it may have invalid
384 // contents, but we found it.
385 foundList.insert(address);
386
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300387 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700388 if (!device.empty())
389 {
390 devices->emplace(address, device);
391 }
392 }
393
394 return foundList;
395}
396
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300397int getBusFRUs(int file, int first, int last, int bus,
Jonathan Doman2418a612022-02-14 18:20:58 -0800398 std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530399 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800400{
James Feist26c27ad2018-07-25 15:09:40 -0700401 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700402 // NOTE: When reading the devices raw on the bus, it can interfere with
403 // the driver's ability to operate, therefore read eeproms first before
404 // scanning for devices without drivers. Several experiments were run
405 // and it was determined that if there were any devices on the bus
406 // before the eeprom was hit and read, the eeprom driver wouldn't open
407 // while the bus device was open. An experiment was not performed to see
408 // if this issue was resolved if the i2c bus device was closed, but
409 // hexdumps of the eeprom later were successful.
410
411 // Scan for i2c eeproms loaded on this bus.
Bonnie Lobfda2c42022-10-26 16:50:54 +0800412 std::set<size_t> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800413 std::set<size_t>& failedItems = failedAddresses[bus];
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000414 std::set<size_t>& foundItems = fruAddresses[bus];
415 foundItems.clear();
James Feist7972bb92019-11-13 15:59:24 -0800416
Matt Simmering2447c242023-11-09 14:18:39 -0800417 auto busFind = busBlocklist.find(bus);
418 if (busFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800419 {
420 if (busFind->second != std::nullopt)
421 {
422 for (const auto& address : *(busFind->second))
423 {
424 skipList.insert(address);
425 }
426 }
427 }
428
James Feist7972bb92019-11-13 15:59:24 -0800429 std::set<size_t>* rootFailures = nullptr;
430 int rootBus = getRootBus(bus);
431
432 if (rootBus >= 0)
433 {
Matt Simmering2447c242023-11-09 14:18:39 -0800434 auto rootBusFind = busBlocklist.find(rootBus);
435 if (rootBusFind != busBlocklist.end())
Bonnie Lobfda2c42022-10-26 16:50:54 +0800436 {
437 if (rootBusFind->second != std::nullopt)
438 {
439 for (const auto& rootAddress : *(rootBusFind->second))
440 {
441 skipList.insert(rootAddress);
442 }
443 }
444 }
James Feist7972bb92019-11-13 15:59:24 -0800445 rootFailures = &(failedAddresses[rootBus]);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000446 foundItems = fruAddresses[rootBus];
James Feist7972bb92019-11-13 15:59:24 -0800447 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700448
Matt Simmering2447c242023-11-09 14:18:39 -0800449 constexpr int startSkipTargetAddr = 0;
450 constexpr int endSkipTargetAddr = 12;
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530451
James Feist26c27ad2018-07-25 15:09:40 -0700452 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800453 {
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000454 if (foundItems.find(ii) != foundItems.end())
455 {
456 continue;
457 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700458 if (skipList.find(ii) != skipList.end())
459 {
460 continue;
461 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530462 // skipping since no device is present in this range
Matt Simmering2447c242023-11-09 14:18:39 -0800463 if (ii >= startSkipTargetAddr && ii <= endSkipTargetAddr)
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530464 {
465 continue;
466 }
Matt Simmering2447c242023-11-09 14:18:39 -0800467 // Set target address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530468 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800469 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300470 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700471 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700472 continue;
473 }
474 // probe
Ed Tanous07d467b2021-02-23 14:48:37 -0800475 if (i2c_smbus_read_byte(file) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700476 {
477 continue;
478 }
James Feist3cb5fec2018-01-23 14:41:51 -0800479
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200480 lg2::debug("something at bus {BUS}, addr {ADDR}", "BUS", bus,
481 "ADDR", ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800482
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530483 makeProbeInterface(bus, ii, objServer);
James Feist8a983922019-10-24 17:11:56 -0700484
James Feist7972bb92019-11-13 15:59:24 -0800485 if (failedItems.find(ii) != failedItems.end())
486 {
487 // if we failed to read it once, unlikely we can read it later
488 continue;
489 }
490
491 if (rootFailures != nullptr)
492 {
493 if (rootFailures->find(ii) != rootFailures->end())
494 {
495 continue;
496 }
497 }
498
Vijay Khemka2d681f62018-11-06 15:51:00 -0800499 /* Check for Device type if it is 8 bit or 16 bit */
Zev Weiss309c0b12022-02-25 01:44:12 +0000500 std::optional<bool> is16Bit = isDevice16Bit(file);
501 if (!is16Bit.has_value())
Vijay Khemka2d681f62018-11-06 15:51:00 -0800502 {
503 std::cerr << "failed to read bus " << bus << " address " << ii
504 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700505 if (powerIsOn)
506 {
507 failedItems.insert(ii);
508 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800509 continue;
510 }
Zev Weiss309c0b12022-02-25 01:44:12 +0000511 bool is16BitBool{*is16Bit};
Vijay Khemka2d681f62018-11-06 15:51:00 -0800512
Patrick Williamsb7077432024-08-16 15:22:21 -0400513 auto readFunc = [is16BitBool, file,
514 ii](off_t offset, size_t length, uint8_t* outbuf) {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200515 return readData(is16BitBool, false, file, ii, offset, length,
516 outbuf);
Zev Weiss309c0b12022-02-25 01:44:12 +0000517 };
518 FRUReader reader(std::move(readFunc));
Patrick Williamsb7077432024-08-16 15:22:21 -0400519 std::string errorMessage =
520 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200521 std::pair<std::vector<uint8_t>, bool> pair =
522 readFRUContents(reader, errorMessage);
523 const bool foundHeader = pair.second;
524
525 if (!foundHeader && !is16BitBool)
526 {
527 // certain FRU eeproms require bytewise reading.
528 // otherwise garbage is read. e.g. SuperMicro PWS 920P-SQ
529
Patrick Williamsb7077432024-08-16 15:22:21 -0400530 auto readFunc =
531 [is16BitBool, file,
532 ii](off_t offset, size_t length, uint8_t* outbuf) {
533 return readData(is16BitBool, true, file, ii, offset,
534 length, outbuf);
535 };
Marvin Drees2b3ed302023-04-14 16:35:14 +0200536 FRUReader readerBytewise(std::move(readFunc));
537 pair = readFRUContents(readerBytewise, errorMessage);
538 }
539
540 if (pair.first.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700541 {
James Feist26c27ad2018-07-25 15:09:40 -0700542 continue;
543 }
James Feist26c27ad2018-07-25 15:09:40 -0700544
Marvin Drees2b3ed302023-04-14 16:35:14 +0200545 devices->emplace(ii, pair.first);
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +0000546 fruAddresses[bus].insert(ii);
James Feist3cb5fec2018-01-23 14:41:51 -0800547 }
James Feist26c27ad2018-07-25 15:09:40 -0700548 return 1;
549 });
550 std::future_status status =
551 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
552 if (status == std::future_status::timeout)
553 {
554 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700555 if (powerIsOn)
556 {
Matt Simmering2447c242023-11-09 14:18:39 -0800557 busBlocklist[bus] = std::nullopt;
James Feistcb5661d2020-06-12 15:05:01 -0700558 }
James Feist444830e2019-04-05 08:38:16 -0700559 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700560 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800561 }
562
James Feist444830e2019-04-05 08:38:16 -0700563 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700564 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800565}
566
Matt Simmering2447c242023-11-09 14:18:39 -0800567void loadBlocklist(const char* path)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700568{
Matt Simmering2447c242023-11-09 14:18:39 -0800569 std::ifstream blocklistStream(path);
570 if (!blocklistStream.good())
Patrick Venture11f1ff42019-08-01 10:42:12 -0700571 {
572 // File is optional.
Matt Simmering2447c242023-11-09 14:18:39 -0800573 std::cerr << "Cannot open blocklist file.\n\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700574 return;
575 }
576
Patrick Williamsb7077432024-08-16 15:22:21 -0400577 nlohmann::json data =
578 nlohmann::json::parse(blocklistStream, nullptr, false);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700579 if (data.is_discarded())
580 {
Matt Simmering2447c242023-11-09 14:18:39 -0800581 std::cerr << "Illegal blocklist file detected, cannot validate JSON, "
Patrick Venture11f1ff42019-08-01 10:42:12 -0700582 "exiting\n";
583 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700584 }
585
586 // It's expected to have at least one field, "buses" that is an array of the
587 // buses by integer. Allow for future options to exclude further aspects,
588 // such as specific addresses or ranges.
589 if (data.type() != nlohmann::json::value_t::object)
590 {
Matt Simmering2447c242023-11-09 14:18:39 -0800591 std::cerr << "Illegal blocklist, expected to read dictionary\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700592 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700593 }
594
595 // If buses field is missing, that's fine.
596 if (data.count("buses") == 1)
597 {
598 // Parse the buses array after a little validation.
599 auto buses = data.at("buses");
600 if (buses.type() != nlohmann::json::value_t::array)
601 {
602 // Buses field present but invalid, therefore this is an error.
Matt Simmering2447c242023-11-09 14:18:39 -0800603 std::cerr << "Invalid contents for blocklist buses field\n";
Patrick Venture11f1ff42019-08-01 10:42:12 -0700604 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700605 }
606
607 // Catch exception here for type mis-match.
608 try
609 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800610 for (const auto& busIterator : buses)
Patrick Venture11f1ff42019-08-01 10:42:12 -0700611 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800612 // If bus and addresses field are missing, that's fine.
613 if (busIterator.contains("bus") &&
614 busIterator.contains("addresses"))
615 {
616 auto busData = busIterator.at("bus");
617 auto bus = busData.get<size_t>();
618
619 auto addressData = busIterator.at("addresses");
620 auto addresses =
621 addressData.get<std::set<std::string_view>>();
622
Ed Tanousfc171422024-04-04 17:18:16 -0700623 auto& block = busBlocklist[bus].emplace();
Bonnie Lobfda2c42022-10-26 16:50:54 +0800624 for (const auto& address : addresses)
625 {
626 size_t addressInt = 0;
627 std::from_chars(address.begin() + 2, address.end(),
628 addressInt, 16);
Ed Tanousfc171422024-04-04 17:18:16 -0700629 block.insert(addressInt);
Bonnie Lobfda2c42022-10-26 16:50:54 +0800630 }
631 }
632 else
633 {
Matt Simmering2447c242023-11-09 14:18:39 -0800634 busBlocklist[busIterator.get<size_t>()] = std::nullopt;
Bonnie Lobfda2c42022-10-26 16:50:54 +0800635 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700636 }
637 }
638 catch (const nlohmann::detail::type_error& e)
639 {
640 // Type mis-match is a critical error.
641 std::cerr << "Invalid bus type: " << e.what() << "\n";
642 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700643 }
644 }
Patrick Venture11f1ff42019-08-01 10:42:12 -0700645}
646
Ed Tanous07d467b2021-02-23 14:48:37 -0800647static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800648 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530649 sdbusplus::asio::object_server& objServer)
James Feist3cb5fec2018-01-23 14:41:51 -0800650{
Ed Tanous3013fb42022-07-09 08:27:06 -0700651 for (const auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800652 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700653 int bus = busStrToInt(i2cBus.string());
James Feist0c3980a2019-12-19 11:09:27 -0800654
James Feist5d7f4692020-06-17 18:22:33 -0700655 if (bus < 0)
656 {
657 std::cerr << "Cannot translate " << i2cBus << " to int\n";
658 continue;
659 }
Matt Simmering2447c242023-11-09 14:18:39 -0800660 auto busFind = busBlocklist.find(bus);
661 if (busFind != busBlocklist.end())
James Feist444830e2019-04-05 08:38:16 -0700662 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800663 if (busFind->second == std::nullopt)
664 {
665 continue; // Skip blocked busses.
666 }
James Feist444830e2019-04-05 08:38:16 -0700667 }
James Feist0c3980a2019-12-19 11:09:27 -0800668 int rootBus = getRootBus(bus);
Matt Simmering2447c242023-11-09 14:18:39 -0800669 auto rootBusFind = busBlocklist.find(rootBus);
670 if (rootBusFind != busBlocklist.end())
James Feist0c3980a2019-12-19 11:09:27 -0800671 {
Bonnie Lobfda2c42022-10-26 16:50:54 +0800672 if (rootBusFind->second == std::nullopt)
673 {
674 continue;
675 }
James Feist0c3980a2019-12-19 11:09:27 -0800676 }
677
James Feist3cb5fec2018-01-23 14:41:51 -0800678 auto file = open(i2cBus.c_str(), O_RDWR);
679 if (file < 0)
680 {
681 std::cerr << "unable to open i2c device " << i2cBus.string()
682 << "\n";
683 continue;
684 }
685 unsigned long funcs = 0;
686
687 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
688 {
689 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700690 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800691 << bus << "\n";
Zhikui Renc02d8cb2021-06-28 16:56:08 -0700692 close(file);
James Feist3cb5fec2018-01-23 14:41:51 -0800693 continue;
694 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700695 if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
696 ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
James Feist3cb5fec2018-01-23 14:41:51 -0800697 {
698 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
699 << bus << "\n";
700 continue;
701 }
James Feist98132792019-07-09 13:29:09 -0700702 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800703 device = std::make_shared<DeviceMap>();
704
Nikhil Potaded8884f12019-03-27 13:27:13 -0700705 // i2cdetect by default uses the range 0x03 to 0x77, as
706 // this is what we have tested with, use this range. Could be
707 // changed in future.
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200708 lg2::debug("Scanning bus {BUS}", "BUS", bus);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700709
710 // fd is closed in this function in case the bus locks up
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530711 getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700712
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200713 lg2::debug("Done scanning bus {BUS}", "BUS", bus);
James Feist3cb5fec2018-01-23 14:41:51 -0800714 }
James Feist3cb5fec2018-01-23 14:41:51 -0800715}
716
James Feist6ebf9de2018-05-15 15:01:17 -0700717// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700718struct FindDevicesWithCallback :
719 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700720{
James Feista465ccc2019-02-08 12:51:01 -0800721 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
Jonathan Doman2418a612022-02-14 18:20:58 -0800722 BusMap& busmap, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530723 sdbusplus::asio::object_server& objServer,
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800724 std::function<void()>&& callback) :
Patrick Williamsb7077432024-08-16 15:22:21 -0400725 _i2cBuses(i2cBuses), _busMap(busmap), _powerIsOn(powerIsOn),
726 _objServer(objServer), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700727 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700728 ~FindDevicesWithCallback()
729 {
730 _callback();
731 }
732 void run()
733 {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530734 findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
James Feist6ebf9de2018-05-15 15:01:17 -0700735 }
736
James Feista465ccc2019-02-08 12:51:01 -0800737 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800738 BusMap& _busMap;
Jonathan Doman2418a612022-02-14 18:20:58 -0800739 const bool& _powerIsOn;
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530740 sdbusplus::asio::object_server& _objServer;
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +0800741 std::function<void()> _callback;
James Feist6ebf9de2018-05-15 15:01:17 -0700742};
743
Ed Tanous07d467b2021-02-23 14:48:37 -0800744void addFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300745 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800746 boost::container::flat_map<
747 std::pair<size_t, size_t>,
748 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +0530749 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
Jonathan Doman2418a612022-02-14 18:20:58 -0800750 const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530751 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
James Feist3cb5fec2018-01-23 14:41:51 -0800752{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300753 boost::container::flat_map<std::string, std::string> formattedFRU;
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530754
755 std::optional<std::string> optionalProductName = getProductName(
756 device, formattedFRU, bus, address, unknownBusObjectCount);
757 if (!optionalProductName)
James Feist3cb5fec2018-01-23 14:41:51 -0800758 {
Kumar Thangavel9f2162a2022-08-10 18:05:20 +0530759 std::cerr << "getProductName failed. product name is empty.\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800760 return;
761 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700762
Patrick Williamsb7077432024-08-16 15:22:21 -0400763 std::string productName =
764 "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
James Feist3cb5fec2018-01-23 14:41:51 -0800765
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530766 std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
767 if (index.has_value())
James Feist918e18c2018-02-13 15:51:07 -0800768 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +0530769 productName += "_";
770 productName += std::to_string(++(*index));
James Feist918e18c2018-02-13 15:51:07 -0800771 }
James Feist3cb5fec2018-01-23 14:41:51 -0800772
James Feist9eb0b582018-04-27 12:15:46 -0700773 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
774 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
775 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
776
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300777 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800778 {
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700779 std::regex_replace(property.second.begin(), property.second.begin(),
Ed Tanous07d467b2021-02-23 14:48:37 -0800780 property.second.end(), nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530781 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -0700782 {
783 continue;
784 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400785 std::string key =
786 std::regex_replace(property.first, nonAsciiRegex, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +0530787
788 if (property.first == "PRODUCT_ASSET_TAG")
789 {
790 std::string propertyName = property.first;
791 iface->register_property(
792 key, property.second + '\0',
Kumar Thangavel41a90512021-11-24 15:44:20 +0530793 [bus, address, propertyName, &dbusInterfaceMap,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530794 &unknownBusObjectCount, &powerIsOn, &objServer,
795 &systemBus](const std::string& req, std::string& resp) {
Patrick Williamsb7077432024-08-16 15:22:21 -0400796 if (strcmp(req.c_str(), resp.c_str()) != 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +0530797 {
Patrick Williamsb7077432024-08-16 15:22:21 -0400798 // call the method which will update
799 if (updateFRUProperty(req, bus, address, propertyName,
800 dbusInterfaceMap,
801 unknownBusObjectCount, powerIsOn,
802 objServer, systemBus))
803 {
804 resp = req;
805 }
806 else
807 {
808 throw std::invalid_argument(
809 "FRU property update failed.");
810 }
Joshi-Mansid73b7442020-03-27 19:10:21 +0530811 }
Patrick Williamsb7077432024-08-16 15:22:21 -0400812 return 1;
813 });
Joshi-Mansid73b7442020-03-27 19:10:21 +0530814 }
815 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -0700816 {
817 std::cerr << "illegal key: " << key << "\n";
818 }
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200819 lg2::debug("parsed FRU property: {FIRST}: {SECOND}", "FIRST",
820 property.first, "SECOND", property.second);
James Feist3cb5fec2018-01-23 14:41:51 -0800821 }
James Feist2a9d6db2018-04-27 15:48:28 -0700822
823 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700824 iface->register_property("BUS", bus);
825 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700826
James Feist9eb0b582018-04-27 12:15:46 -0700827 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800828}
829
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300830static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -0800831{
832 // try to read baseboard fru from file
Ed Tanous07d467b2021-02-23 14:48:37 -0800833 std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300834 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -0800835 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300836 baseboardFRUFile.seekg(0, std::ios_base::end);
837 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
838 baseboardFRU.resize(fileSize);
839 baseboardFRUFile.seekg(0, std::ios_base::beg);
Ed Tanous3013fb42022-07-09 08:27:06 -0700840 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
841 char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
842 baseboardFRUFile.read(charOffset, fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -0800843 }
844 else
845 {
846 return false;
847 }
848 return true;
849}
850
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300851bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700852{
853 boost::container::flat_map<std::string, std::string> tmp;
Ed Tanous07d467b2021-02-23 14:48:37 -0800854 if (fru.size() > maxFruSize)
James Feistb49ffc32018-05-02 11:10:43 -0700855 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300856 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700857 return false;
858 }
859 // verify legal fru by running it through fru parsing logic
Michael Shen0961b112022-02-22 11:06:33 +0800860 if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -0700861 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300862 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -0700863 return false;
864 }
865 // baseboard fru
866 if (bus == 0 && address == 0)
867 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800868 std::ofstream file(baseboardFruLocation, std::ios_base::binary);
James Feistb49ffc32018-05-02 11:10:43 -0700869 if (!file.good())
870 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800871 std::cerr << "Error opening file " << baseboardFruLocation << "\n";
James Feistddb78302018-09-06 11:45:42 -0700872 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700873 return false;
874 }
Ed Tanous3013fb42022-07-09 08:27:06 -0700875 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
876 const char* charOffset = reinterpret_cast<const char*>(fru.data());
877 file.write(charOffset, fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700878 return file.good();
879 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800880
881 if (hasEepromFile(bus, address))
James Feistb49ffc32018-05-02 11:10:43 -0700882 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800883 auto path = getEepromPath(bus, address);
884 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
885 if (eeprom < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700886 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800887 std::cerr << "unable to open i2c device " << path << "\n";
888 throw DBusInternalError();
889 return false;
890 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700891
Ed Tanous07d467b2021-02-23 14:48:37 -0800892 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
893 if (writtenBytes < 0)
894 {
895 std::cerr << "unable to write to i2c device " << path << "\n";
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700896 close(eeprom);
James Feistddb78302018-09-06 11:45:42 -0700897 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700898 return false;
899 }
900
Ed Tanous07d467b2021-02-23 14:48:37 -0800901 close(eeprom);
James Feistb49ffc32018-05-02 11:10:43 -0700902 return true;
903 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800904
905 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
906
907 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
908 if (file < 0)
909 {
910 std::cerr << "unable to open i2c device " << i2cBus << "\n";
911 throw DBusInternalError();
912 return false;
913 }
914 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
915 {
916 std::cerr << "unable to set device address\n";
917 close(file);
918 throw DBusInternalError();
919 return false;
920 }
921
922 constexpr const size_t retryMax = 2;
923 uint16_t index = 0;
924 size_t retries = retryMax;
925 while (index < fru.size())
926 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700927 if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
Ed Tanous07d467b2021-02-23 14:48:37 -0800928 (retries == retryMax))
929 {
930 // The 4K EEPROM only uses the A2 and A1 device address bits
931 // with the third bit being a memory page address bit.
932 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
933 {
934 std::cerr << "unable to set device address\n";
935 close(file);
936 throw DBusInternalError();
937 return false;
938 }
939 }
940
941 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
942 fru[index]) < 0)
943 {
Ed Tanous3013fb42022-07-09 08:27:06 -0700944 if ((retries--) == 0U)
Ed Tanous07d467b2021-02-23 14:48:37 -0800945 {
946 std::cerr << "error writing fru: " << strerror(errno) << "\n";
947 close(file);
948 throw DBusInternalError();
949 return false;
950 }
951 }
952 else
953 {
954 retries = retryMax;
955 index++;
956 }
957 // most eeproms require 5-10ms between writes
958 std::this_thread::sleep_for(std::chrono::milliseconds(10));
959 }
960 close(file);
961 return true;
James Feistb49ffc32018-05-02 11:10:43 -0700962}
963
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800964void rescanOneBus(
krishnar4213ee212022-11-11 15:39:30 +0530965 BusMap& busmap, uint16_t busNum,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800966 boost::container::flat_map<
967 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -0700968 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -0800969 bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +0530970 sdbusplus::asio::object_server& objServer,
971 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800972{
Yong Li6fdfac02023-10-30 11:21:30 +0800973 for (auto device = foundDevices.begin(); device != foundDevices.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800974 {
Yong Li6fdfac02023-10-30 11:21:30 +0800975 if (device->first.first == static_cast<size_t>(busNum))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800976 {
Yong Li6fdfac02023-10-30 11:21:30 +0800977 objServer.remove_interface(device->second);
978 device = foundDevices.erase(device);
979 }
980 else
981 {
982 device++;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +0800983 }
984 }
985
James Feist5d7f4692020-06-17 18:22:33 -0700986 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
987 if (!fs::exists(busPath))
988 {
989 if (dbusCall)
990 {
991 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
992 << "\n";
993 throw std::invalid_argument("Invalid Bus.");
994 }
995 return;
996 }
997
998 std::vector<fs::path> i2cBuses;
999 i2cBuses.emplace_back(busPath);
1000
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001001 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301002 i2cBuses, busmap, powerIsOn, objServer,
1003 [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
1004 &objServer, &systemBus]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001005 for (auto busIface = dbusInterfaceMap.begin();
1006 busIface != dbusInterfaceMap.end();)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001007 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001008 if (busIface->first.first == static_cast<size_t>(busNum))
1009 {
1010 objServer.remove_interface(busIface->second);
1011 busIface = dbusInterfaceMap.erase(busIface);
1012 }
1013 else
1014 {
1015 busIface++;
1016 }
Yong Li6fdfac02023-10-30 11:21:30 +08001017 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001018 auto found = busmap.find(busNum);
1019 if (found == busmap.end() || found->second == nullptr)
Yong Li6fdfac02023-10-30 11:21:30 +08001020 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001021 return;
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001022 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001023 for (auto& device : *(found->second))
1024 {
1025 addFruObjectToDbus(device.second, dbusInterfaceMap,
1026 static_cast<uint32_t>(busNum), device.first,
1027 unknownBusObjectCount, powerIsOn, objServer,
1028 systemBus);
1029 }
1030 });
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001031 scan->run();
1032}
1033
James Feist9eb0b582018-04-27 12:15:46 -07001034void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001035 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001036 boost::container::flat_map<
1037 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301038 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001039 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)
James Feist918e18c2018-02-13 15:51:07 -08001042{
Ed Tanousaa497ed2023-02-28 13:43:41 -08001043 static boost::asio::steady_timer timer(io);
1044 timer.expires_from_now(std::chrono::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001045
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001046 // setup an async wait in case we get flooded with requests
Jian Zhang6e7cebf2022-11-29 18:30:21 +08001047 timer.async_wait([&](const boost::system::error_code& ec) {
1048 if (ec == boost::asio::error::operation_aborted)
1049 {
1050 return;
1051 }
1052
1053 if (ec)
1054 {
1055 std::cerr << "Error in timer: " << ec.message() << "\n";
1056 return;
1057 }
1058
James Feist4131aea2018-03-09 09:47:30 -08001059 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001060 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001061
Nikhil Potaded8884f12019-03-27 13:27:13 -07001062 boost::container::flat_map<size_t, fs::path> busPaths;
1063 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001064 {
James Feist4131aea2018-03-09 09:47:30 -08001065 std::cerr << "unable to find i2c devices\n";
1066 return;
James Feist918e18c2018-02-13 15:51:07 -08001067 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001068
Ed Tanous07d467b2021-02-23 14:48:37 -08001069 for (const auto& busPath : busPaths)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001070 {
1071 i2cBuses.emplace_back(busPath.second);
1072 }
James Feist4131aea2018-03-09 09:47:30 -08001073
James Feist98132792019-07-09 13:29:09 -07001074 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001075 for (auto& [pair, interface] : foundDevices)
1076 {
1077 objServer.remove_interface(interface);
1078 }
1079 foundDevices.clear();
1080
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301081 auto scan = std::make_shared<FindDevicesWithCallback>(
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301082 i2cBuses, busmap, powerIsOn, objServer, [&]() {
Patrick Williamsb7077432024-08-16 15:22:21 -04001083 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001084 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001085 objServer.remove_interface(busIface.second);
James Feist6ebf9de2018-05-15 15:01:17 -07001086 }
Patrick Williamsb7077432024-08-16 15:22:21 -04001087
1088 dbusInterfaceMap.clear();
1089 unknownBusObjectCount = 0;
1090
1091 // todo, get this from a more sensable place
1092 std::vector<uint8_t> baseboardFRU;
1093 if (readBaseboardFRU(baseboardFRU))
1094 {
1095 // If no device on i2c bus 0, the insertion will happen.
1096 auto bus0 =
1097 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1098 bus0.first->second->emplace(0, baseboardFRU);
1099 }
1100 for (auto& devicemap : busmap)
1101 {
1102 for (auto& device : *devicemap.second)
1103 {
1104 addFruObjectToDbus(device.second, dbusInterfaceMap,
1105 devicemap.first, device.first,
1106 unknownBusObjectCount, powerIsOn,
1107 objServer, systemBus);
1108 }
1109 }
1110 });
James Feist6ebf9de2018-05-15 15:01:17 -07001111 scan->run();
1112 });
James Feist918e18c2018-02-13 15:51:07 -08001113}
1114
Joshi-Mansid73b7442020-03-27 19:10:21 +05301115// Details with example of Asset Tag Update
1116// To find location of Product Info Area asset tag as per FRU specification
1117// 1. Find product Info area starting offset (*8 - as header will be in
1118// multiple of 8 bytes).
1119// 2. Skip 3 bytes of product info area (like format version, area length,
1120// and language code).
1121// 3. Traverse manufacturer name, product name, product version, & product
1122// serial number, by reading type/length code to reach the Asset Tag.
1123// 4. Update the Asset Tag, reposition the product Info area in multiple of
1124// 8 bytes. Update the Product area length and checksum.
1125
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001126bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301127 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -08001128 const std::string& propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301129 boost::container::flat_map<
1130 std::pair<size_t, size_t>,
Kumar Thangavel41a90512021-11-24 15:44:20 +05301131 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
Jonathan Doman2418a612022-02-14 18:20:58 -08001132 size_t& unknownBusObjectCount, const bool& powerIsOn,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301133 sdbusplus::asio::object_server& objServer,
1134 std::shared_ptr<sdbusplus::asio::connection>& systemBus)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301135{
1136 size_t updatePropertyReqLen = updatePropertyReq.length();
1137 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1138 {
1139 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001140 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301141 "Invalid Length "
1142 << updatePropertyReqLen << "\n";
1143 return false;
1144 }
1145
1146 std::vector<uint8_t> fruData;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301147
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301148 if (!getFruData(fruData, bus, address))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301149 {
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301150 std::cerr << "Failure getting FRU Data \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301151 return false;
1152 }
1153
AKSHAY RAVEENDRAN K4d4df5b2022-11-14 11:16:29 +00001154 struct FruArea fruAreaParams
1155 {};
Joshi-Mansid73b7442020-03-27 19:10:21 +05301156
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301157 if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301158 {
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301159 std::cerr << "findFruAreaLocationAndField failed \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301160 return false;
1161 }
1162
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301163 std::vector<uint8_t> restFRUAreaFieldsData;
1164 if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1165 restFRUAreaFieldsData))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301166 {
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301167 std::cerr << "copyRestFRUArea failed \n";
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001168 return false;
1169 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301170
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001171 // Push post update fru areas if any
1172 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001173 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1174 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001175 {
1176 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001177 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301178 if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001179 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1180 {
1181 nextFRUAreaLoc = fruAreaLoc;
1182 }
1183 }
1184 std::vector<uint8_t> restFRUAreasData;
Ed Tanous3013fb42022-07-09 08:27:06 -07001185 if (nextFRUAreaLoc != 0U)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001186 {
1187 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1188 fruData.size() - nextFRUAreaLoc,
1189 std::back_inserter(restFRUAreasData));
1190 }
1191
1192 // check FRU area size
1193 size_t fruAreaDataSize =
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301194 ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1195 restFRUAreaFieldsData.size());
1196 size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001197 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1198 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001199#ifdef ENABLE_FRU_AREA_RESIZE
1200 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1201 // round size to 8-byte blocks
Patrick Williamsb7077432024-08-16 15:22:21 -04001202 newFRUAreaSize =
1203 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1204 size_t newFRUDataSize =
1205 fruData.size() + newFRUAreaSize - fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001206 fruData.resize(newFRUDataSize);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301207 fruAreaParams.size = newFRUAreaSize;
1208 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001209#else
1210 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1211 << " should not be greater than available FRU area size: "
1212 << fruAreaAvailableSize << "\n";
1213 return false;
1214#endif // ENABLE_FRU_AREA_RESIZE
1215 }
1216
Joshi-Mansid73b7442020-03-27 19:10:21 +05301217 // write new requested property field length and data
1218 constexpr uint8_t newTypeLenMask = 0xC0;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301219 fruData[fruAreaParams.updateFieldLoc] =
Joshi-Mansid73b7442020-03-27 19:10:21 +05301220 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301221 fruAreaParams.updateFieldLoc++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301222 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301223 fruData.begin() + fruAreaParams.updateFieldLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301224
1225 // Copy remaining data to main fru area - post updated fru field vector
Patrick Williamsb7077432024-08-16 15:22:21 -04001226 fruAreaParams.restFieldsLoc =
1227 fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1228 size_t fruAreaDataEnd =
1229 fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301230
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001231 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301232 fruData.begin() + fruAreaParams.restFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301233
1234 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001235 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301236 fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301237
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001238#ifdef ENABLE_FRU_AREA_RESIZE
1239 ++nextFRUAreaNewLoc;
Patrick Williamsb7077432024-08-16 15:22:21 -04001240 ssize_t nextFRUAreaOffsetDiff =
1241 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001242 // Append rest FRU Areas if size changed and there were other sections after
1243 // updated one
1244 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1245 {
1246 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1247 fruData.begin() + nextFRUAreaNewLoc);
1248 // Update Common Header
Ed Tanous6e22c872023-02-16 15:19:28 -08001249 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1250 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001251 {
Ed Tanous6e22c872023-02-16 15:19:28 -08001252 unsigned int fruAreaOffsetField =
1253 getHeaderAreaFieldOffset(nextFRUArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001254 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
Ed Tanous6e22c872023-02-16 15:19:28 -08001255 if (curFRUAreaOffset > fruAreaParams.end)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001256 {
1257 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1258 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1259 }
1260 }
1261 // Calculate new checksum
1262 std::vector<uint8_t> headerFRUData;
1263 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1264 size_t checksumVal = calculateChecksum(headerFRUData);
1265 fruData[7] = static_cast<uint8_t>(checksumVal);
1266 // fill zeros if FRU Area size decreased
1267 if (nextFRUAreaOffsetDiff < 0)
1268 {
1269 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1270 restFRUAreasData.size(),
1271 fruData.end(), 0);
1272 }
1273 }
1274#else
1275 // this is to avoid "unused variable" warning
1276 (void)nextFRUAreaNewLoc;
1277#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301278 if (fruData.empty())
1279 {
1280 return false;
1281 }
1282
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001283 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301284 fruData))
1285 {
1286 return false;
1287 }
1288
1289 // Rescan the bus so that GetRawFru dbus-call fetches updated values
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301290 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1291 objServer, systemBus);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301292 return true;
1293}
1294
James Feist98132792019-07-09 13:29:09 -07001295int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001296{
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301297 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1298 sdbusplus::asio::object_server objServer(systemBus);
1299
Kumar Thangavel41a90512021-11-24 15:44:20 +05301300 static size_t unknownBusObjectCount = 0;
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301301 static bool powerIsOn = false;
James Feist3cb5fec2018-01-23 14:41:51 -08001302 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001303 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001304 std::vector<fs::path> i2cBuses;
1305
James Feista3c180a2018-08-09 16:06:04 -07001306 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001307 {
1308 std::cerr << "unable to find i2c devices\n";
1309 return 1;
1310 }
James Feist3cb5fec2018-01-23 14:41:51 -08001311
Matt Simmering2447c242023-11-09 14:18:39 -08001312 // check for and load blocklist with initial buses.
1313 loadBlocklist(blocklistPath);
Patrick Venture11f1ff42019-08-01 10:42:12 -07001314
Vijay Khemka065f6d92018-12-18 10:37:47 -08001315 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001316
James Feist6ebf9de2018-05-15 15:01:17 -07001317 // this is a map with keys of pair(bus number, address) and values of
1318 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001319 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001320 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1321 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001322
James Feist9eb0b582018-04-27 12:15:46 -07001323 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1324 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1325 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001326
Kumar Thangavel41a90512021-11-24 15:44:20 +05301327 iface->register_method("ReScan", [&]() {
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301328 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1329 objServer, systemBus);
Kumar Thangavel41a90512021-11-24 15:44:20 +05301330 });
James Feist2a9d6db2018-04-27 15:48:28 -07001331
krishnar4213ee212022-11-11 15:39:30 +05301332 iface->register_method("ReScanBus", [&](uint16_t bus) {
Kumar Thangavel1e8e71f2021-12-01 19:39:11 +05301333 rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301334 powerIsOn, objServer, systemBus);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001335 });
1336
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001337 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001338
Patrick Williamsb7077432024-08-16 15:22:21 -04001339 iface->register_method(
1340 "WriteFru", [&](const uint16_t bus, const uint8_t address,
1341 const std::vector<uint8_t>& data) {
1342 if (!writeFRU(bus, address, data))
1343 {
1344 throw std::invalid_argument("Invalid Arguments.");
1345 return;
1346 }
1347 // schedule rescan on success
1348 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1349 powerIsOn, objServer, systemBus);
1350 });
James Feist9eb0b582018-04-27 12:15:46 -07001351 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001352
Patrick Williams2af39222022-07-22 19:26:56 -05001353 std::function<void(sdbusplus::message_t & message)> eventHandler =
1354 [&](sdbusplus::message_t& message) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001355 std::string objectName;
1356 boost::container::flat_map<
1357 std::string,
1358 std::variant<std::string, bool, int64_t, uint64_t, double>>
1359 values;
1360 message.read(objectName, values);
1361 auto findState = values.find("CurrentHostState");
1362 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001363 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001364 if (std::get<std::string>(findState->second) ==
1365 "xyz.openbmc_project.State.Host.HostState.Running")
1366 {
1367 powerIsOn = true;
1368 }
James Feist0eeb79c2019-10-09 13:35:29 -07001369 }
James Feist6ebf9de2018-05-15 15:01:17 -07001370
Patrick Williamsb7077432024-08-16 15:22:21 -04001371 if (powerIsOn)
1372 {
1373 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1374 powerIsOn, objServer, systemBus);
1375 }
1376 };
James Feist9eb0b582018-04-27 12:15:46 -07001377
Patrick Williams2af39222022-07-22 19:26:56 -05001378 sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1379 static_cast<sdbusplus::bus_t&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001380 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001381 "openbmc_project/state/"
1382 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001383 eventHandler);
1384
James Feist4131aea2018-03-09 09:47:30 -08001385 int fd = inotify_init();
Ed Tanous07d467b2021-02-23 14:48:37 -08001386 inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
Ed Tanous3013fb42022-07-09 08:27:06 -07001387 std::array<char, 4096> readBuffer{};
James Feist4131aea2018-03-09 09:47:30 -08001388 // monitor for new i2c devices
1389 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1390 std::function<void(const boost::system::error_code, std::size_t)>
Patrick Williamsb9dd7f82023-10-20 11:20:11 -05001391 watchI2cBusses = [&](const boost::system::error_code& ec,
1392 std::size_t bytesTransferred) {
Patrick Williamsb7077432024-08-16 15:22:21 -04001393 if (ec)
James Feist4131aea2018-03-09 09:47:30 -08001394 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001395 std::cout << "Callback Error " << ec << "\n";
1396 return;
1397 }
1398 size_t index = 0;
1399 while ((index + sizeof(inotify_event)) <= bytesTransferred)
1400 {
1401 const char* p = &readBuffer[index];
1402 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1403 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1404 switch (iEvent->mask)
Ed Tanousfc171422024-04-04 17:18:16 -07001405 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001406 case IN_CREATE:
1407 case IN_MOVED_TO:
1408 case IN_DELETE:
Patrick Williamsdf190612023-05-10 07:51:34 -05001409 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001410 std::string_view name(&iEvent->name[0], iEvent->len);
1411 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001412 {
Patrick Williamsb7077432024-08-16 15:22:21 -04001413 int bus = busStrToInt(name);
1414 if (bus < 0)
1415 {
1416 std::cerr
1417 << "Could not parse bus " << name << "\n";
1418 continue;
1419 }
1420 int rootBus = getRootBus(bus);
1421 if (rootBus >= 0)
1422 {
1423 rescanOneBus(busMap,
1424 static_cast<uint16_t>(rootBus),
1425 dbusInterfaceMap, false,
1426 unknownBusObjectCount, powerIsOn,
1427 objServer, systemBus);
1428 }
1429 rescanOneBus(busMap, static_cast<uint16_t>(bus),
Kumar Thangavel41a90512021-11-24 15:44:20 +05301430 dbusInterfaceMap, false,
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301431 unknownBusObjectCount, powerIsOn,
1432 objServer, systemBus);
James Feist9eb0b582018-04-27 12:15:46 -07001433 }
Patrick Williamsdf190612023-05-10 07:51:34 -05001434 }
Ed Tanousfc171422024-04-04 17:18:16 -07001435 break;
Patrick Williamsb7077432024-08-16 15:22:21 -04001436 default:
1437 break;
1438 }
1439 index += sizeof(inotify_event) + iEvent->len;
James Feist4131aea2018-03-09 09:47:30 -08001440 }
James Feist6ebf9de2018-05-15 15:01:17 -07001441
Patrick Williamsb7077432024-08-16 15:22:21 -04001442 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1443 watchI2cBusses);
1444 };
James Feist4131aea2018-03-09 09:47:30 -08001445
1446 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001447 // run the initial scan
Kumar Thangavel7f43ea82021-12-07 17:20:16 +05301448 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1449 objServer, systemBus);
James Feist918e18c2018-02-13 15:51:07 -08001450
James Feist3cb5fec2018-01-23 14:41:51 -08001451 io.run();
1452 return 0;
1453}