blob: ffae574a2f76f60e52c9b82f9b7969fa5f3aa797 [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 Bishop1fb9f3f2020-08-28 08:15:13 -040016/// \file FruDevice.cpp
James Feist3cb5fec2018-01-23 14:41:51 -080017
Patrick Ventureab296412020-12-30 13:39:37 -080018#include "FruUtils.hpp"
Patrick Venturea49dc332019-10-26 08:32:02 -070019#include "Utils.hpp"
20
James Feist3b860982018-10-02 14:34:07 -070021#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080022#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070023#include <sys/inotify.h>
24#include <sys/ioctl.h>
25
James Feist3b860982018-10-02 14:34:07 -070026#include <boost/algorithm/string/predicate.hpp>
Brad Bishop82c84bb2020-08-26 14:12:50 -040027#include <boost/asio/deadline_timer.hpp>
28#include <boost/asio/io_service.hpp>
James Feist3b860982018-10-02 14:34:07 -070029#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070030#include <nlohmann/json.hpp>
31#include <sdbusplus/asio/connection.hpp>
32#include <sdbusplus/asio/object_server.hpp>
33
34#include <array>
James Feist3b860982018-10-02 14:34:07 -070035#include <chrono>
36#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070037#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080038#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070039#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080040#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070041#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080042#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070043#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080044#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070045#include <set>
46#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070047#include <string>
James Feist3b860982018-10-02 14:34:07 -070048#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080049#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080050#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070051#include <vector>
James Feist3b860982018-10-02 14:34:07 -070052
James Feist8c505da2020-05-28 10:06:33 -070053extern "C"
54{
James Feist3b860982018-10-02 14:34:07 -070055#include <i2c/smbus.h>
56#include <linux/i2c-dev.h>
57}
James Feist3cb5fec2018-01-23 14:41:51 -080058
Ed Tanous072e25d2018-12-16 21:45:20 -080059namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080060static constexpr bool DEBUG = false;
61static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070062constexpr size_t MAX_FRU_SIZE = 512;
63constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070064constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080065
Patrick Venture11f1ff42019-08-01 10:42:12 -070066constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
67
James Feista465ccc2019-02-08 12:51:01 -080068const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080069 "/etc/fru/baseboard.fru.bin";
70
James Feista465ccc2019-02-08 12:51:01 -080071const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080072
Andrei Kartashevb45324a2020-10-14 17:01:47 +030073enum class resCodes
74{
75 resOK,
76 resWarn,
77 resErr
78};
79
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030080static const std::vector<std::string> FRU_AREA_NAMES = {
James Feist3cb5fec2018-01-23 14:41:51 -080081 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070082const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030083using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080084using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
85
James Feist444830e2019-04-05 08:38:16 -070086static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070087struct FindDevicesWithCallback;
88
Nikhil Potaded8884f12019-03-27 13:27:13 -070089static BusMap busMap;
90
James Feistcb5661d2020-06-12 15:05:01 -070091static bool powerIsOn = false;
92
James Feist8a983922019-10-24 17:11:56 -070093static boost::container::flat_map<
94 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
95 foundDevices;
96
James Feist7972bb92019-11-13 15:59:24 -080097static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
98
James Feist5cb06082019-10-24 17:11:13 -070099boost::asio::io_service io;
100auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
101auto objServer = sdbusplus::asio::object_server(systemBus);
102
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300103static const std::vector<std::string> CHASSIS_FRU_AREAS = {"PART_NUMBER",
104 "SERIAL_NUMBER"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530105
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300106static const std::vector<std::string> BOARD_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300107 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
108 "FRU_VERSION_ID"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530109
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300110static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300111 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
112 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID"};
113
114static const std::string FRU_CUSTOM_FIELD_NAME = "INFO_AM";
Joshi-Mansid73b7442020-03-27 19:10:21 +0530115
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300116static inline const std::string& getFruAreaName(fruAreas area)
117{
118 return FRU_AREA_NAMES[static_cast<unsigned int>(area)];
119}
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300120uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
121 std::vector<uint8_t>::const_iterator end);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300122bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530123 const std::string& assetTag, uint32_t bus, uint32_t address,
124 std::string propertyName,
125 boost::container::flat_map<
126 std::pair<size_t, size_t>,
127 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700128
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700129// Given a bus/address, produce the path in sysfs for an eeprom.
130static std::string getEepromPath(size_t bus, size_t address)
131{
132 std::stringstream output;
133 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
134 << std::setfill('0') << std::setw(4) << std::hex << address
135 << "/eeprom";
136 return output.str();
137}
138
139static bool hasEepromFile(size_t bus, size_t address)
140{
141 auto path = getEepromPath(bus, address);
142 try
143 {
144 return fs::exists(path);
145 }
146 catch (...)
147 {
148 return false;
149 }
150}
151
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700152static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800153 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700154 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700155{
156 auto result = lseek(fd, offset, SEEK_SET);
157 if (result < 0)
158 {
159 std::cerr << "failed to seek\n";
160 return -1;
161 }
162
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700163 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700164}
165
James Feist5d7f4692020-06-17 18:22:33 -0700166static int busStrToInt(const std::string& busName)
167{
168 auto findBus = busName.rfind("-");
169 if (findBus == std::string::npos)
170 {
171 return -1;
172 }
173 return std::stoi(busName.substr(findBus + 1));
174}
175
James Feist7972bb92019-11-13 15:59:24 -0800176static int getRootBus(size_t bus)
177{
178 auto ec = std::error_code();
179 auto path = std::filesystem::read_symlink(
180 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
181 std::to_string(bus) + "/mux_device"),
182 ec);
183 if (ec)
184 {
185 return -1;
186 }
187
188 std::string filename = path.filename();
189 auto findBus = filename.find("-");
190 if (findBus == std::string::npos)
191 {
192 return -1;
193 }
194 return std::stoi(filename.substr(0, findBus));
195}
196
James Feistc95cb142018-02-26 10:41:42 -0800197static bool isMuxBus(size_t bus)
198{
Ed Tanous072e25d2018-12-16 21:45:20 -0800199 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800200 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
201}
202
James Feist8a983922019-10-24 17:11:56 -0700203static void makeProbeInterface(size_t bus, size_t address)
204{
205 if (isMuxBus(bus))
206 {
207 return; // the mux buses are random, no need to publish
208 }
209 auto [it, success] = foundDevices.emplace(
210 std::make_pair(bus, address),
211 objServer.add_interface(
212 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
213 std::to_string(address),
214 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
215 if (!success)
216 {
217 return; // already added
218 }
219 it->second->register_property("Bus", bus);
220 it->second->register_property("Address", address);
221 it->second->initialize();
222}
223
Vijay Khemka2d681f62018-11-06 15:51:00 -0800224static int isDevice16Bit(int file)
225{
226 /* Get first byte */
227 int byte1 = i2c_smbus_read_byte_data(file, 0);
228 if (byte1 < 0)
229 {
230 return byte1;
231 }
232 /* Read 7 more bytes, it will read same first byte in case of
233 * 8 bit but it will read next byte in case of 16 bit
234 */
235 for (int i = 0; i < 7; i++)
236 {
237 int byte2 = i2c_smbus_read_byte_data(file, 0);
238 if (byte2 < 0)
239 {
240 return byte2;
241 }
242 if (byte2 != byte1)
243 {
244 return 1;
245 }
246 }
247 return 0;
248}
249
Xiang Liu2801a702020-01-20 14:29:34 -0800250// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
251// from_slave_buf_len bytes.
252static int i2c_smbus_write_then_read(int file, uint16_t address,
253 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
254 uint8_t* fromSlaveBuf,
255 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800256{
Xiang Liu2801a702020-01-20 14:29:34 -0800257 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
258 fromSlaveBufLen == 0)
259 {
260 return -1;
261 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800262
Xiang Liu2801a702020-01-20 14:29:34 -0800263#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
264 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
265 struct i2c_rdwr_ioctl_data rdwr;
266
267 msgs[0].addr = address;
268 msgs[0].flags = 0;
269 msgs[0].len = toSlaveBufLen;
270 msgs[0].buf = toSlaveBuf;
271 msgs[1].addr = address;
272 msgs[1].flags = I2C_M_RD;
273 msgs[1].len = fromSlaveBufLen;
274 msgs[1].buf = fromSlaveBuf;
275
276 rdwr.msgs = msgs;
277 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
278
279 int ret = ioctl(file, I2C_RDWR, &rdwr);
280
281 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
282}
283
284static int64_t readBlockData(int flag, int file, uint16_t address,
285 uint16_t offset, uint8_t len, uint8_t* buf)
286{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800287 if (flag == 0)
288 {
Xiang Liu2801a702020-01-20 14:29:34 -0800289 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
290 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800291 }
292
Xiang Liu2801a702020-01-20 14:29:34 -0800293 offset = htobe16(offset);
294 return i2c_smbus_write_then_read(
295 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800296}
297
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700298// TODO: This code is very similar to the non-eeprom version and can be merged
299// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300300static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700301{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700302 auto path = getEepromPath(bus, address);
303
304 int file = open(path.c_str(), O_RDONLY);
305 if (file < 0)
306 {
307 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700308 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700309 }
310
Patrick Venturebaba7672019-10-26 09:26:41 -0700311 std::string errorMessage = "eeprom at " + std::to_string(bus) +
312 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300313 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800314 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700315
316 close(file);
317 return device;
318}
319
320std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
321{
322 std::set<int> foundList;
323
324 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
325
326 // For each file listed under the i2c device
327 // NOTE: This should be faster than just checking for each possible address
328 // path.
329 for (const auto& p : fs::directory_iterator(path))
330 {
331 const std::string node = p.path().string();
332 std::smatch m;
333 bool found =
334 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
335
336 if (!found)
337 {
338 continue;
339 }
340 if (m.size() != 2)
341 {
342 std::cerr << "regex didn't capture\n";
343 continue;
344 }
345
346 std::ssub_match subMatch = m[1];
347 std::string addressString = subMatch.str();
348
349 std::size_t ignored;
350 const int hexBase = 16;
351 int address = std::stoi(addressString, &ignored, hexBase);
352
353 const std::string eeprom = node + "/eeprom";
354
355 try
356 {
357 if (!fs::exists(eeprom))
358 {
359 continue;
360 }
361 }
362 catch (...)
363 {
364 continue;
365 }
366
367 // There is an eeprom file at this address, it may have invalid
368 // contents, but we found it.
369 foundList.insert(address);
370
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300371 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700372 if (!device.empty())
373 {
374 devices->emplace(address, device);
375 }
376 }
377
378 return foundList;
379}
380
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300381int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700382 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800383{
James Feist3cb5fec2018-01-23 14:41:51 -0800384
James Feist26c27ad2018-07-25 15:09:40 -0700385 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700386 // NOTE: When reading the devices raw on the bus, it can interfere with
387 // the driver's ability to operate, therefore read eeproms first before
388 // scanning for devices without drivers. Several experiments were run
389 // and it was determined that if there were any devices on the bus
390 // before the eeprom was hit and read, the eeprom driver wouldn't open
391 // while the bus device was open. An experiment was not performed to see
392 // if this issue was resolved if the i2c bus device was closed, but
393 // hexdumps of the eeprom later were successful.
394
395 // Scan for i2c eeproms loaded on this bus.
396 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800397 std::set<size_t>& failedItems = failedAddresses[bus];
398
399 std::set<size_t>* rootFailures = nullptr;
400 int rootBus = getRootBus(bus);
401
402 if (rootBus >= 0)
403 {
404 rootFailures = &(failedAddresses[rootBus]);
405 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700406
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530407 constexpr int startSkipSlaveAddr = 0;
408 constexpr int endSkipSlaveAddr = 12;
409
James Feist26c27ad2018-07-25 15:09:40 -0700410 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800411 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700412 if (skipList.find(ii) != skipList.end())
413 {
414 continue;
415 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530416 // skipping since no device is present in this range
417 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
418 {
419 continue;
420 }
James Feist26c27ad2018-07-25 15:09:40 -0700421 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530422 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800423 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300424 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700425 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700426 continue;
427 }
428 // probe
429 else if (i2c_smbus_read_byte(file) < 0)
430 {
431 continue;
432 }
James Feist3cb5fec2018-01-23 14:41:51 -0800433
James Feist26c27ad2018-07-25 15:09:40 -0700434 if (DEBUG)
435 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700436 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700437 << "\n";
438 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800439
James Feist8a983922019-10-24 17:11:56 -0700440 makeProbeInterface(bus, ii);
441
James Feist7972bb92019-11-13 15:59:24 -0800442 if (failedItems.find(ii) != failedItems.end())
443 {
444 // if we failed to read it once, unlikely we can read it later
445 continue;
446 }
447
448 if (rootFailures != nullptr)
449 {
450 if (rootFailures->find(ii) != rootFailures->end())
451 {
452 continue;
453 }
454 }
455
Vijay Khemka2d681f62018-11-06 15:51:00 -0800456 /* Check for Device type if it is 8 bit or 16 bit */
457 int flag = isDevice16Bit(file);
458 if (flag < 0)
459 {
460 std::cerr << "failed to read bus " << bus << " address " << ii
461 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700462 if (powerIsOn)
463 {
464 failedItems.insert(ii);
465 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800466 continue;
467 }
468
Patrick Venturebaba7672019-10-26 09:26:41 -0700469 std::string errorMessage =
470 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300471 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300472 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800473 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700474 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700475 {
James Feist26c27ad2018-07-25 15:09:40 -0700476 continue;
477 }
James Feist26c27ad2018-07-25 15:09:40 -0700478
Patrick Venture786f1792019-08-05 16:33:44 -0700479 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800480 }
James Feist26c27ad2018-07-25 15:09:40 -0700481 return 1;
482 });
483 std::future_status status =
484 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
485 if (status == std::future_status::timeout)
486 {
487 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700488 if (powerIsOn)
489 {
490 busBlacklist.insert(bus);
491 }
James Feist444830e2019-04-05 08:38:16 -0700492 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700493 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800494 }
495
James Feist444830e2019-04-05 08:38:16 -0700496 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700497 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800498}
499
Patrick Venture11f1ff42019-08-01 10:42:12 -0700500void loadBlacklist(const char* path)
501{
502 std::ifstream blacklistStream(path);
503 if (!blacklistStream.good())
504 {
505 // File is optional.
506 std::cerr << "Cannot open blacklist file.\n\n";
507 return;
508 }
509
510 nlohmann::json data =
511 nlohmann::json::parse(blacklistStream, nullptr, false);
512 if (data.is_discarded())
513 {
514 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
515 "exiting\n";
516 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700517 }
518
519 // It's expected to have at least one field, "buses" that is an array of the
520 // buses by integer. Allow for future options to exclude further aspects,
521 // such as specific addresses or ranges.
522 if (data.type() != nlohmann::json::value_t::object)
523 {
524 std::cerr << "Illegal blacklist, expected to read dictionary\n";
525 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700526 }
527
528 // If buses field is missing, that's fine.
529 if (data.count("buses") == 1)
530 {
531 // Parse the buses array after a little validation.
532 auto buses = data.at("buses");
533 if (buses.type() != nlohmann::json::value_t::array)
534 {
535 // Buses field present but invalid, therefore this is an error.
536 std::cerr << "Invalid contents for blacklist buses field\n";
537 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700538 }
539
540 // Catch exception here for type mis-match.
541 try
542 {
543 for (const auto& bus : buses)
544 {
545 busBlacklist.insert(bus.get<size_t>());
546 }
547 }
548 catch (const nlohmann::detail::type_error& e)
549 {
550 // Type mis-match is a critical error.
551 std::cerr << "Invalid bus type: " << e.what() << "\n";
552 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700553 }
554 }
555
556 return;
557}
558
James Feista465ccc2019-02-08 12:51:01 -0800559static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700560 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800561{
James Feista465ccc2019-02-08 12:51:01 -0800562 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800563 {
James Feist5d7f4692020-06-17 18:22:33 -0700564 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800565
James Feist5d7f4692020-06-17 18:22:33 -0700566 if (bus < 0)
567 {
568 std::cerr << "Cannot translate " << i2cBus << " to int\n";
569 continue;
570 }
James Feist444830e2019-04-05 08:38:16 -0700571 if (busBlacklist.find(bus) != busBlacklist.end())
572 {
573 continue; // skip previously failed busses
574 }
James Feist3cb5fec2018-01-23 14:41:51 -0800575
James Feist0c3980a2019-12-19 11:09:27 -0800576 int rootBus = getRootBus(bus);
577 if (busBlacklist.find(rootBus) != busBlacklist.end())
578 {
579 continue;
580 }
581
James Feist3cb5fec2018-01-23 14:41:51 -0800582 auto file = open(i2cBus.c_str(), O_RDWR);
583 if (file < 0)
584 {
585 std::cerr << "unable to open i2c device " << i2cBus.string()
586 << "\n";
587 continue;
588 }
589 unsigned long funcs = 0;
590
591 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
592 {
593 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700594 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800595 << bus << "\n";
596 continue;
597 }
598 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
599 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
600 {
601 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
602 << bus << "\n";
603 continue;
604 }
James Feist98132792019-07-09 13:29:09 -0700605 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800606 device = std::make_shared<DeviceMap>();
607
Nikhil Potaded8884f12019-03-27 13:27:13 -0700608 // i2cdetect by default uses the range 0x03 to 0x77, as
609 // this is what we have tested with, use this range. Could be
610 // changed in future.
611 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800612 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700613 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800614 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700615
616 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300617 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700618
619 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800620 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700621 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800622 }
James Feist3cb5fec2018-01-23 14:41:51 -0800623 }
James Feist3cb5fec2018-01-23 14:41:51 -0800624}
625
James Feist6ebf9de2018-05-15 15:01:17 -0700626// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700627struct FindDevicesWithCallback :
628 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700629{
James Feista465ccc2019-02-08 12:51:01 -0800630 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700631 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800632 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700633 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700634 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700635 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700636 ~FindDevicesWithCallback()
637 {
638 _callback();
639 }
640 void run()
641 {
James Feist98132792019-07-09 13:29:09 -0700642 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700643 }
644
James Feista465ccc2019-02-08 12:51:01 -0800645 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800646 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700647 std::function<void(void)> _callback;
648};
649
James Feist3cb5fec2018-01-23 14:41:51 -0800650static const std::tm intelEpoch(void)
651{
James Feist98132792019-07-09 13:29:09 -0700652 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800653 val.tm_year = 1996 - 1900;
654 return val;
655}
656
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800657static char sixBitToChar(uint8_t val)
658{
659 return static_cast<char>((val & 0x3f) + ' ');
660}
661
662/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
663static const char bcdHighChars[] = {
664 ' ', '-', '.', 'X', 'X', 'X',
665};
666
667static char bcdPlusToChar(uint8_t val)
668{
669 val &= 0xf;
670 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
671}
672
673enum class DecodeState
674{
675 ok,
676 end,
677 err,
678};
679
680enum FRUDataEncoding
681{
682 binary = 0x0,
683 bcdPlus = 0x1,
684 sixBitASCII = 0x2,
685 languageDependent = 0x3,
686};
687
688/* Decode FRU data into a std::string, given an input iterator and end. If the
689 * state returned is fruDataOk, then the resulting string is the decoded FRU
690 * data. The input iterator is advanced past the data consumed.
691 *
692 * On fruDataErr, we have lost synchronisation with the length bytes, so the
693 * iterator is no longer usable.
694 */
695static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300696 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300697 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800698{
699 std::string value;
700 unsigned int i;
701
702 /* we need at least one byte to decode the type/len header */
703 if (iter == end)
704 {
705 std::cerr << "Truncated FRU data\n";
706 return make_pair(DecodeState::err, value);
707 }
708
709 uint8_t c = *(iter++);
710
711 /* 0xc1 is the end marker */
712 if (c == 0xc1)
713 {
714 return make_pair(DecodeState::end, value);
715 }
716
717 /* decode type/len byte */
718 uint8_t type = static_cast<uint8_t>(c >> 6);
719 uint8_t len = static_cast<uint8_t>(c & 0x3f);
720
721 /* we should have at least len bytes of data available overall */
722 if (iter + len > end)
723 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300724 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800725 return make_pair(DecodeState::err, value);
726 }
727
728 switch (type)
729 {
730 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300731 {
732 std::stringstream ss;
733 ss << std::hex << std::setfill('0');
734 for (i = 0; i < len; i++, iter++)
735 {
736 uint8_t val = static_cast<uint8_t>(*iter);
737 ss << std::setw(2) << static_cast<int>(val);
738 }
739 value = ss.str();
740 break;
741 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800742 case FRUDataEncoding::languageDependent:
743 /* For language-code dependent encodings, assume 8-bit ASCII */
744 value = std::string(iter, iter + len);
745 iter += len;
746 break;
747
748 case FRUDataEncoding::bcdPlus:
749 value = std::string();
750 for (i = 0; i < len; i++, iter++)
751 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300752 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800753 value.push_back(bcdPlusToChar(val >> 4));
754 value.push_back(bcdPlusToChar(val & 0xf));
755 }
756 break;
757
758 case FRUDataEncoding::sixBitASCII:
759 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300760 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800761 unsigned int accumBitLen = 0;
762 value = std::string();
763 for (i = 0; i < len; i++, iter++)
764 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300765 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800766 accumBitLen += 8;
767 while (accumBitLen >= 6)
768 {
769 value.push_back(sixBitToChar(accum & 0x3f));
770 accum >>= 6;
771 accumBitLen -= 6;
772 }
773 }
774 }
775 break;
776 }
777
778 return make_pair(DecodeState::ok, value);
779}
780
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300781static void checkLang(uint8_t lang)
782{
783 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
784 // but we don't support that.
785 if (lang && lang != 25)
786 {
787 std::cerr << "Warning: language other then English is not "
788 "supported \n";
789 }
790}
791
Vijay Khemka02618f02021-01-20 11:10:28 -0800792/* This function verifies for other offsets to check if they are not
793 * falling under other field area
794 *
795 * fruBytes: Start of Fru data
796 * currentArea: Index of current area offset to be compared against all area
797 * offset and it is a multiple of 8 bytes as per specification
798 * len: Length of current area space and it is a multiple of 8 bytes
799 * as per specification
800 */
801static bool verifyOffset(const std::vector<uint8_t>& fruBytes,
802 fruAreas currentArea, uint8_t len)
803{
804
805 unsigned int fruBytesSize = fruBytes.size();
806
807 // check if Fru data has at least 8 byte header
808 if (fruBytesSize <= fruBlockSize)
809 {
810 std::cerr << "Error: trying to parse empty FRU\n";
811 return false;
812 }
813
814 // Check range of passed currentArea value
815 if (currentArea > fruAreas::fruAreaMultirecord)
816 {
817 std::cerr << "Error: Fru area is out of range\n";
818 return false;
819 }
820
821 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
822 if (currentAreaIndex > fruBytesSize)
823 {
824 std::cerr << "Error: Fru area index is out of range\n";
825 return false;
826 }
827
828 unsigned int start = fruBytes[currentAreaIndex];
829 unsigned int end = start + len;
830
831 /* Verify each offset within the range of start and end */
832 for (fruAreas area = fruAreas::fruAreaInternal;
833 area <= fruAreas::fruAreaMultirecord; ++area)
834 {
835 // skip the current offset
836 if (area == currentArea)
837 {
838 continue;
839 }
840
841 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
842 if (areaIndex > fruBytesSize)
843 {
844 std::cerr << "Error: Fru area index is out of range\n";
845 return false;
846 }
847
848 unsigned int areaOffset = fruBytes[areaIndex];
849 // if areaOffset is 0 means this area is not available so skip
850 if (areaOffset == 0)
851 {
852 continue;
853 }
854
855 // check for overlapping of current offset with given areaoffset
856 if (areaOffset == start || (areaOffset > start && areaOffset < end))
857 {
858 std::cerr << getFruAreaName(currentArea)
859 << " offset is overlapping with " << getFruAreaName(area)
860 << " offset\n";
861 return false;
862 }
863 }
864 return true;
865}
866
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300867resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
868 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800869{
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300870 resCodes ret = resCodes::resOK;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300871 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800872 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300873 std::cerr << "Error: trying to parse empty FRU \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300874 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800875 }
James Feist9eb0b582018-04-27 12:15:46 -0700876 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300877 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800878
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300879 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800880
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300881 // Don't parse Internal and Multirecord areas
882 for (fruAreas area = fruAreas::fruAreaChassis;
883 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800884 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300885
886 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
887 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800888 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300889 continue;
890 }
891 offset *= fruBlockSize;
892 std::vector<uint8_t>::const_iterator fruBytesIter =
893 fruBytes.begin() + offset;
894 if (fruBytesIter + fruBlockSize >= fruBytes.end())
895 {
896 std::cerr << "Not enough data to parse \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300897 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800898 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300899 // check for format version 1
900 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -0800901 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300902 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300903 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300904 }
905 ++fruBytesIter;
Vijay Khemka02618f02021-01-20 11:10:28 -0800906
907 /* Verify other area offset for overlap with current area by passing
908 * length of current area offset pointed by *fruBytesIter
909 */
910 if (!verifyOffset(fruBytes, area, *fruBytesIter))
911 {
912 return resCodes::resErr;
913 }
914
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300915 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
916 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
917 fruBytes.begin() + offset + fruAreaSize - 1;
918 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800919
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300920 uint8_t fruComputedChecksum =
921 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
922 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300923 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300924 std::stringstream ss;
925 ss << std::hex << std::setfill('0');
926 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
927 ss << "\tComputed checksum: 0x" << std::setw(2)
928 << static_cast<int>(fruComputedChecksum) << "\n";
929 ss << "\tThe read checksum: 0x" << std::setw(2)
930 << static_cast<int>(*fruBytesIterEndArea) << "\n";
931 std::cerr << ss.str();
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300932 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300933 }
934
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300935 switch (area)
936 {
937 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -0800938 {
939 result["CHASSIS_TYPE"] =
940 std::to_string(static_cast<int>(*fruBytesIter));
941 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300942 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300943 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800944 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300945 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -0800946 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300947 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800948 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300949 std::to_string(static_cast<int>(lang));
950 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800951 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -0800952
953 unsigned int minutes = *fruBytesIter |
954 *(fruBytesIter + 1) << 8 |
955 *(fruBytesIter + 2) << 16;
956 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700957 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800958 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700959 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800960
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700961 // Tue Nov 20 23:08:00 2018
962 char timeString[32] = {0};
963 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700964 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700965 if (bytes == 0)
966 {
967 std::cerr << "invalid time string encountered\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300968 return resCodes::resErr;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700969 }
970
971 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800972 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300973 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300974 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800975 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300976 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -0800977 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300978 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800979 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300980 std::to_string(static_cast<int>(lang));
981 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800982 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300983 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300984 break;
985 }
986 default:
987 {
988 std::cerr << "Internal error: unexpected FRU area index: "
989 << static_cast<int>(area) << " \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300990 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300991 }
992 }
993 size_t fieldIndex = 0;
994 DecodeState state;
995 do
996 {
997 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea);
998 state = res.first;
999 std::string value = res.second;
1000 std::string name;
1001 if (fieldIndex < fruAreaFieldNames->size())
1002 {
1003 name = std::string(getFruAreaName(area)) + "_" +
1004 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -08001005 }
1006 else
1007 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001008 name =
1009 std::string(getFruAreaName(area)) + "_" +
1010 FRU_CUSTOM_FIELD_NAME +
1011 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -08001012 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001013
1014 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001015 {
Ed Tanous2147e672019-02-27 13:59:56 -08001016 // Strip non null characters from the end
1017 value.erase(std::find_if(value.rbegin(), value.rend(),
1018 [](char ch) { return ch != 0; })
1019 .base(),
1020 value.end());
1021
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001022 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001023 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001024 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001025 else if (state == DecodeState::err)
1026 {
1027 std::cerr << "Error while parsing " << name << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001028 ret = resCodes::resWarn;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001029 // Cancel decoding if failed to parse any of mandatory
1030 // fields
1031 if (fieldIndex < fruAreaFieldNames->size())
1032 {
1033 std::cerr << "Failed to parse mandatory field \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001034 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001035 }
1036 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001037 else
1038 {
1039 if (fieldIndex < fruAreaFieldNames->size())
1040 {
1041 std::cerr << "Mandatory fields absent in FRU area "
1042 << getFruAreaName(area) << " after " << name
1043 << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001044 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001045 }
1046 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001047 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001048 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
1049 {
1050 uint8_t c = *fruBytesIter;
1051 if (c)
1052 {
1053 std::cerr << "Non-zero byte after EndOfFields in FRU area "
1054 << getFruAreaName(area) << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001055 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001056 break;
1057 }
1058 }
James Feist3cb5fec2018-01-23 14:41:51 -08001059 }
1060
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001061 return ret;
James Feist3cb5fec2018-01-23 14:41:51 -08001062}
1063
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001064std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001065{
1066 auto deviceMap = busMap.find(bus);
1067 if (deviceMap == busMap.end())
1068 {
1069 throw std::invalid_argument("Invalid Bus.");
1070 }
1071 auto device = deviceMap->second->find(address);
1072 if (device == deviceMap->second->end())
1073 {
1074 throw std::invalid_argument("Invalid Address.");
1075 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001076 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001077
1078 return ret;
1079}
1080
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001081void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001082 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001083 boost::container::flat_map<
1084 std::pair<size_t, size_t>,
1085 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001086 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001087{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001088 boost::container::flat_map<std::string, std::string> formattedFRU;
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001089 resCodes res = formatFRU(device, formattedFRU);
1090 if (res == resCodes::resErr)
James Feist3cb5fec2018-01-23 14:41:51 -08001091 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001092 std::cerr << "failed to parse FRU for device at bus " << bus
Patrick Ventureb755c832019-08-07 11:09:14 -07001093 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001094 return;
1095 }
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001096 else if (res == resCodes::resWarn)
1097 {
1098 std::cerr << "there were warnings while parsing FRU for device at bus "
1099 << bus << " address " << address << "\n";
1100 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001101
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001102 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001103 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001104 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001105 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001106 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001107 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001108 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001109 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001110 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001111 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001112 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001113 {
1114 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001115 std::regex illegalObject("[^A-Za-z0-9_]");
1116 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001117 }
1118 else
1119 {
1120 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1121 UNKNOWN_BUS_OBJECT_COUNT++;
1122 }
1123
James Feist918e18c2018-02-13 15:51:07 -08001124 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001125 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001126 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001127 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001128 int highest = -1;
1129 bool found = false;
1130
James Feista465ccc2019-02-08 12:51:01 -08001131 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001132 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001133 std::string path = busIface.second->get_object_path();
1134 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001135 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001136 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001137 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001138 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001139 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001140 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001141 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001142 // This device is already added to the lower numbered bus,
1143 // do not replicate it.
1144 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001145 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001146
1147 // Check if the match named has extra information.
1148 found = true;
1149 std::smatch base_match;
1150
1151 bool match = std::regex_match(
1152 path, base_match, std::regex(productName + "_(\\d+)$"));
1153 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001154 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001155 if (base_match.size() == 2)
1156 {
1157 std::ssub_match base_sub_match = base_match[1];
1158 std::string base = base_sub_match.str();
1159
1160 int value = std::stoi(base);
1161 highest = (value > highest) ? value : highest;
1162 }
James Feist79e9c0b2018-03-15 15:21:17 -07001163 }
James Feist918e18c2018-02-13 15:51:07 -08001164 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001165 } // end searching objects
1166
1167 if (found)
1168 {
1169 // We found something with the same name. If highest was still -1,
1170 // it means this new entry will be _0.
1171 productName += "_";
1172 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001173 }
1174 }
James Feist3cb5fec2018-01-23 14:41:51 -08001175
James Feist9eb0b582018-04-27 12:15:46 -07001176 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1177 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1178 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1179
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001180 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001181 {
James Feist9eb0b582018-04-27 12:15:46 -07001182
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001183 std::regex_replace(property.second.begin(), property.second.begin(),
1184 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301185 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001186 {
1187 continue;
1188 }
1189 std::string key =
1190 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301191
1192 if (property.first == "PRODUCT_ASSET_TAG")
1193 {
1194 std::string propertyName = property.first;
1195 iface->register_property(
1196 key, property.second + '\0',
1197 [bus, address, propertyName,
1198 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1199 if (strcmp(req.c_str(), resp.c_str()))
1200 {
1201 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001202 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301203 dbusInterfaceMap))
1204 {
1205 resp = req;
1206 }
1207 else
1208 {
1209 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001210 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301211 }
1212 }
1213 return 1;
1214 });
1215 }
1216 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001217 {
1218 std::cerr << "illegal key: " << key << "\n";
1219 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001220 if (DEBUG)
1221 {
1222 std::cout << property.first << ": " << property.second << "\n";
1223 }
James Feist3cb5fec2018-01-23 14:41:51 -08001224 }
James Feist2a9d6db2018-04-27 15:48:28 -07001225
1226 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001227 iface->register_property("BUS", bus);
1228 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001229
James Feist9eb0b582018-04-27 12:15:46 -07001230 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001231}
1232
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001233static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001234{
1235 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001236 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1237 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001238 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001239 baseboardFRUFile.seekg(0, std::ios_base::end);
1240 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1241 baseboardFRU.resize(fileSize);
1242 baseboardFRUFile.seekg(0, std::ios_base::beg);
1243 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001244 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001245 }
1246 else
1247 {
1248 return false;
1249 }
1250 return true;
1251}
1252
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001253bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001254{
1255 boost::container::flat_map<std::string, std::string> tmp;
1256 if (fru.size() > MAX_FRU_SIZE)
1257 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001258 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001259 return false;
1260 }
1261 // verify legal fru by running it through fru parsing logic
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001262 if (formatFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001263 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001264 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001265 return false;
1266 }
1267 // baseboard fru
1268 if (bus == 0 && address == 0)
1269 {
1270 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1271 if (!file.good())
1272 {
1273 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1274 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001275 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001276 return false;
1277 }
James Feista465ccc2019-02-08 12:51:01 -08001278 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001279 return file.good();
1280 }
1281 else
1282 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001283 if (hasEepromFile(bus, address))
1284 {
1285 auto path = getEepromPath(bus, address);
1286 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1287 if (eeprom < 0)
1288 {
1289 std::cerr << "unable to open i2c device " << path << "\n";
1290 throw DBusInternalError();
1291 return false;
1292 }
1293
1294 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1295 if (writtenBytes < 0)
1296 {
1297 std::cerr << "unable to write to i2c device " << path << "\n";
1298 close(eeprom);
1299 throw DBusInternalError();
1300 return false;
1301 }
1302
1303 close(eeprom);
1304 return true;
1305 }
1306
James Feistb49ffc32018-05-02 11:10:43 -07001307 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1308
1309 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1310 if (file < 0)
1311 {
1312 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001313 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001314 return false;
1315 }
1316 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1317 {
1318 std::cerr << "unable to set device address\n";
1319 close(file);
James Feistddb78302018-09-06 11:45:42 -07001320 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001321 return false;
1322 }
1323
1324 constexpr const size_t RETRY_MAX = 2;
1325 uint16_t index = 0;
1326 size_t retries = RETRY_MAX;
1327 while (index < fru.size())
1328 {
1329 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1330 (retries == RETRY_MAX))
1331 {
1332 // The 4K EEPROM only uses the A2 and A1 device address bits
1333 // with the third bit being a memory page address bit.
1334 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1335 {
1336 std::cerr << "unable to set device address\n";
1337 close(file);
James Feistddb78302018-09-06 11:45:42 -07001338 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001339 return false;
1340 }
1341 }
1342
James Feist98132792019-07-09 13:29:09 -07001343 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1344 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001345 {
1346 if (!retries--)
1347 {
1348 std::cerr << "error writing fru: " << strerror(errno)
1349 << "\n";
1350 close(file);
James Feistddb78302018-09-06 11:45:42 -07001351 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001352 return false;
1353 }
1354 }
1355 else
1356 {
1357 retries = RETRY_MAX;
1358 index++;
1359 }
1360 // most eeproms require 5-10ms between writes
1361 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1362 }
1363 close(file);
1364 return true;
1365 }
1366}
1367
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001368void rescanOneBus(
1369 BusMap& busmap, uint8_t busNum,
1370 boost::container::flat_map<
1371 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001372 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1373 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001374{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001375 for (auto& [pair, interface] : foundDevices)
1376 {
1377 if (pair.first == static_cast<size_t>(busNum))
1378 {
1379 objServer.remove_interface(interface);
1380 foundDevices.erase(pair);
1381 }
1382 }
1383
James Feist5d7f4692020-06-17 18:22:33 -07001384 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1385 if (!fs::exists(busPath))
1386 {
1387 if (dbusCall)
1388 {
1389 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1390 << "\n";
1391 throw std::invalid_argument("Invalid Bus.");
1392 }
1393 return;
1394 }
1395
1396 std::vector<fs::path> i2cBuses;
1397 i2cBuses.emplace_back(busPath);
1398
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001399 auto scan = std::make_shared<FindDevicesWithCallback>(
1400 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1401 for (auto& busIface : dbusInterfaceMap)
1402 {
1403 if (busIface.first.first == static_cast<size_t>(busNum))
1404 {
1405 objServer.remove_interface(busIface.second);
1406 }
1407 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001408 auto found = busmap.find(busNum);
1409 if (found == busmap.end() || found->second == nullptr)
1410 {
1411 return;
1412 }
1413 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001414 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001415 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001416 static_cast<uint32_t>(busNum), device.first);
1417 }
1418 });
1419 scan->run();
1420}
1421
James Feist9eb0b582018-04-27 12:15:46 -07001422void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001423 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001424 boost::container::flat_map<
1425 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001426 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001427{
James Feist6ebf9de2018-05-15 15:01:17 -07001428 static boost::asio::deadline_timer timer(io);
1429 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001430
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001431 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001432 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001433 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001434 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001435
Nikhil Potaded8884f12019-03-27 13:27:13 -07001436 boost::container::flat_map<size_t, fs::path> busPaths;
1437 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001438 {
James Feist4131aea2018-03-09 09:47:30 -08001439 std::cerr << "unable to find i2c devices\n";
1440 return;
James Feist918e18c2018-02-13 15:51:07 -08001441 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001442
1443 for (auto busPath : busPaths)
1444 {
1445 i2cBuses.emplace_back(busPath.second);
1446 }
James Feist4131aea2018-03-09 09:47:30 -08001447
James Feist98132792019-07-09 13:29:09 -07001448 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001449 for (auto& [pair, interface] : foundDevices)
1450 {
1451 objServer.remove_interface(interface);
1452 }
1453 foundDevices.clear();
1454
James Feist5cb06082019-10-24 17:11:13 -07001455 auto scan =
1456 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001457 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001458 {
1459 objServer.remove_interface(busIface.second);
1460 }
James Feist4131aea2018-03-09 09:47:30 -08001461
James Feist6ebf9de2018-05-15 15:01:17 -07001462 dbusInterfaceMap.clear();
1463 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001464
James Feist6ebf9de2018-05-15 15:01:17 -07001465 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001466 std::vector<uint8_t> baseboardFRU;
1467 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001468 {
Helen Huang9b43b772021-01-21 15:07:24 +08001469 busmap[0]->emplace(0, baseboardFRU);
James Feist6ebf9de2018-05-15 15:01:17 -07001470 }
James Feist98132792019-07-09 13:29:09 -07001471 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001472 {
James Feista465ccc2019-02-08 12:51:01 -08001473 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001474 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001475 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001476 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001477 }
1478 }
1479 });
1480 scan->run();
1481 });
James Feist918e18c2018-02-13 15:51:07 -08001482}
1483
Joshi-Mansid73b7442020-03-27 19:10:21 +05301484// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001485uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1486 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301487{
1488 constexpr int checksumMod = 256;
1489 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001490 int sum = std::accumulate(iter, end, 0);
1491 int checksum = (checksumMod - sum) & modVal;
1492 return static_cast<uint8_t>(checksum);
1493}
1494uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1495{
1496 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301497}
1498
1499// Update new fru area length &
1500// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001501// Return the offset of the area checksum byte
1502static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1503 size_t fruAreaStart,
1504 size_t fruAreaEndOfFieldsOffset,
1505 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301506{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001507 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301508
1509 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001510 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1511 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301512
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001513 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301514 size_t checksumLoc;
1515 if (!mod)
1516 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001517 traverseFRUAreaIndex += (fruBlockSize);
1518 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301519 }
1520 else
1521 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001522 traverseFRUAreaIndex += (fruBlockSize - mod);
1523 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301524 }
1525
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001526 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1527 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1528 size_t fruAreaLengthLoc = fruAreaStart + 1;
1529 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301530
1531 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001532 std::vector<uint8_t> finalFRUData;
1533 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1534 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301535
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001536 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001537 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301538}
1539
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001540static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301541{
1542 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001543 constexpr uint8_t endOfFields = 0xC1;
1544 if (fruFieldTypeLenValue == endOfFields)
1545 {
1546 return -1;
1547 }
1548 else
1549 {
1550 return fruFieldTypeLenValue & typeLenMask;
1551 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301552}
1553
1554// Details with example of Asset Tag Update
1555// To find location of Product Info Area asset tag as per FRU specification
1556// 1. Find product Info area starting offset (*8 - as header will be in
1557// multiple of 8 bytes).
1558// 2. Skip 3 bytes of product info area (like format version, area length,
1559// and language code).
1560// 3. Traverse manufacturer name, product name, product version, & product
1561// serial number, by reading type/length code to reach the Asset Tag.
1562// 4. Update the Asset Tag, reposition the product Info area in multiple of
1563// 8 bytes. Update the Product area length and checksum.
1564
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001565bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301566 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1567 std::string propertyName,
1568 boost::container::flat_map<
1569 std::pair<size_t, size_t>,
1570 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1571{
1572 size_t updatePropertyReqLen = updatePropertyReq.length();
1573 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1574 {
1575 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001576 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301577 "Invalid Length "
1578 << updatePropertyReqLen << "\n";
1579 return false;
1580 }
1581
1582 std::vector<uint8_t> fruData;
1583 try
1584 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001585 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301586 static_cast<uint8_t>(address));
1587 }
1588 catch (std::invalid_argument& e)
1589 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001590 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301591 return false;
1592 }
1593
1594 if (fruData.empty())
1595 {
1596 return false;
1597 }
1598
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001599 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301600
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001601 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301602 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001603 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001604 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001605 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1606 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301607 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001608 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001609 << " \n";
1610 return false;
1611 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001612 fruAreas fruAreaToUpdate =
1613 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1614 fruAreaOffsetFieldValue =
1615 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1616 switch (fruAreaToUpdate)
1617 {
1618 case fruAreas::fruAreaChassis:
1619 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1620 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1621 break;
1622 case fruAreas::fruAreaBoard:
1623 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1624 fruAreaFieldNames = &BOARD_FRU_AREAS;
1625 break;
1626 case fruAreas::fruAreaProduct:
1627 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1628 // i.e. version, area length and language code
1629 offset = 3;
1630 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1631 break;
1632 default:
1633 std::cerr << "Don't know how to handle property " << propertyName
1634 << " \n";
1635 return false;
1636 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001637 if (fruAreaOffsetFieldValue == 0)
1638 {
1639 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301640 return false;
1641 }
1642
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001643 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001644 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1645 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001646 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001647 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001648 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001649 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301650
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001651 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001652 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301653 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001654 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001655 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301656 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001657 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301658 break;
1659 }
1660 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001661 if (!found)
1662 {
1663 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1664 if (pos == std::string::npos)
1665 {
1666 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1667 << propertyName << "\n";
1668 return false;
1669 }
1670 std::string fieldNumStr =
1671 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1672 size_t fieldNum = std::stoi(fieldNumStr);
1673 if (fieldNum == 0)
1674 {
1675 std::cerr << "PropertyName not recognized: " << propertyName
1676 << "\n";
1677 return false;
1678 }
1679 skipToFRUUpdateField += fieldNum;
1680 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301681
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001682 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301683 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001684 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001685 if (fieldLength < 0)
1686 {
1687 break;
1688 }
1689 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301690 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001691 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301692
1693 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001694 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001695 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301696 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001697 std::cerr << "Property " << propertyName << " not present \n";
1698 return false;
1699 }
1700 fruDataIter += 1 + fieldLength;
1701 size_t restFRUFieldsLoc = fruDataIter;
1702 size_t endOfFieldsLoc = 0;
1703 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1704 {
1705 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301706 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001707 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301708 break;
1709 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001710 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301711 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001712 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301713
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001714 std::vector<uint8_t> restFRUAreaFieldsData;
1715 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001716 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001717 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301718
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001719 // Push post update fru areas if any
1720 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001721 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1722 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001723 {
1724 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001725 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001726 if ((fruAreaLoc > endOfFieldsLoc) &&
1727 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1728 {
1729 nextFRUAreaLoc = fruAreaLoc;
1730 }
1731 }
1732 std::vector<uint8_t> restFRUAreasData;
1733 if (nextFRUAreaLoc)
1734 {
1735 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1736 fruData.size() - nextFRUAreaLoc,
1737 std::back_inserter(restFRUAreasData));
1738 }
1739
1740 // check FRU area size
1741 size_t fruAreaDataSize =
1742 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1743 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1744 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1745 {
1746
1747#ifdef ENABLE_FRU_AREA_RESIZE
1748 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1749 // round size to 8-byte blocks
1750 newFRUAreaSize =
1751 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1752 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1753 fruData.resize(newFRUDataSize);
1754 fruAreaSize = newFRUAreaSize;
1755 fruAreaEnd = fruAreaStart + fruAreaSize;
1756#else
1757 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1758 << " should not be greater than available FRU area size: "
1759 << fruAreaAvailableSize << "\n";
1760 return false;
1761#endif // ENABLE_FRU_AREA_RESIZE
1762 }
1763
Joshi-Mansid73b7442020-03-27 19:10:21 +05301764 // write new requested property field length and data
1765 constexpr uint8_t newTypeLenMask = 0xC0;
1766 fruData[fruUpdateFieldLoc] =
1767 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1768 fruUpdateFieldLoc++;
1769 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1770 fruData.begin() + fruUpdateFieldLoc);
1771
1772 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001773 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1774 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001775 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1776 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301777
1778 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001779 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1780 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301781
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001782#ifdef ENABLE_FRU_AREA_RESIZE
1783 ++nextFRUAreaNewLoc;
1784 ssize_t nextFRUAreaOffsetDiff =
1785 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1786 // Append rest FRU Areas if size changed and there were other sections after
1787 // updated one
1788 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1789 {
1790 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1791 fruData.begin() + nextFRUAreaNewLoc);
1792 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001793 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1794 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001795 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001796 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001797 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1798 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1799 {
1800 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1801 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1802 }
1803 }
1804 // Calculate new checksum
1805 std::vector<uint8_t> headerFRUData;
1806 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1807 size_t checksumVal = calculateChecksum(headerFRUData);
1808 fruData[7] = static_cast<uint8_t>(checksumVal);
1809 // fill zeros if FRU Area size decreased
1810 if (nextFRUAreaOffsetDiff < 0)
1811 {
1812 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1813 restFRUAreasData.size(),
1814 fruData.end(), 0);
1815 }
1816 }
1817#else
1818 // this is to avoid "unused variable" warning
1819 (void)nextFRUAreaNewLoc;
1820#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301821 if (fruData.empty())
1822 {
1823 return false;
1824 }
1825
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001826 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301827 fruData))
1828 {
1829 return false;
1830 }
1831
1832 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1833 rescanBusses(busMap, dbusInterfaceMap);
1834 return true;
1835}
1836
James Feist98132792019-07-09 13:29:09 -07001837int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001838{
1839 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001840 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001841 std::vector<fs::path> i2cBuses;
1842
James Feista3c180a2018-08-09 16:06:04 -07001843 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001844 {
1845 std::cerr << "unable to find i2c devices\n";
1846 return 1;
1847 }
James Feist3cb5fec2018-01-23 14:41:51 -08001848
Patrick Venture11f1ff42019-08-01 10:42:12 -07001849 // check for and load blacklist with initial buses.
1850 loadBlacklist(blacklistPath);
1851
Vijay Khemka065f6d92018-12-18 10:37:47 -08001852 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001853
James Feist6ebf9de2018-05-15 15:01:17 -07001854 // this is a map with keys of pair(bus number, address) and values of
1855 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001856 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001857 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1858 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001859
James Feist9eb0b582018-04-27 12:15:46 -07001860 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1861 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1862 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001863
James Feist5cb06082019-10-24 17:11:13 -07001864 iface->register_method("ReScan",
1865 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001866
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001867 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001868 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001869 });
1870
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001871 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001872
1873 iface->register_method("WriteFru", [&](const uint8_t bus,
1874 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001875 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001876 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001877 {
James Feistddb78302018-09-06 11:45:42 -07001878 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001879 return;
1880 }
1881 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001882 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001883 });
James Feist9eb0b582018-04-27 12:15:46 -07001884 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001885
James Feist9eb0b582018-04-27 12:15:46 -07001886 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001887 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001888 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001889 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001890 std::string,
1891 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001892 values;
1893 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001894 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001895 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001896 {
James Feistcb5661d2020-06-12 15:05:01 -07001897 powerIsOn = boost::ends_with(
1898 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001899 }
James Feist6ebf9de2018-05-15 15:01:17 -07001900
James Feistcb5661d2020-06-12 15:05:01 -07001901 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001902 {
James Feist5cb06082019-10-24 17:11:13 -07001903 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001904 }
James Feist918e18c2018-02-13 15:51:07 -08001905 };
James Feist9eb0b582018-04-27 12:15:46 -07001906
1907 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001908 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001909 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001910 "openbmc_project/state/"
1911 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001912 eventHandler);
1913
James Feist4131aea2018-03-09 09:47:30 -08001914 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001915 inotify_add_watch(fd, I2C_DEV_LOCATION,
1916 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001917 std::array<char, 4096> readBuffer;
1918 std::string pendingBuffer;
1919 // monitor for new i2c devices
1920 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1921 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001922 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001923 std::size_t bytes_transferred) {
1924 if (ec)
1925 {
1926 std::cout << "Callback Error " << ec << "\n";
1927 return;
1928 }
1929 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001930 while (pendingBuffer.size() > sizeof(inotify_event))
1931 {
James Feista465ccc2019-02-08 12:51:01 -08001932 const inotify_event* iEvent =
1933 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001934 pendingBuffer.data());
1935 switch (iEvent->mask)
1936 {
James Feist9eb0b582018-04-27 12:15:46 -07001937 case IN_CREATE:
1938 case IN_MOVED_TO:
1939 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001940 std::string name(iEvent->name);
1941 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001942 {
James Feist5d7f4692020-06-17 18:22:33 -07001943 int bus = busStrToInt(name);
1944 if (bus < 0)
1945 {
1946 std::cerr << "Could not parse bus " << name
1947 << "\n";
1948 continue;
1949 }
1950 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1951 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001952 }
James Feist4131aea2018-03-09 09:47:30 -08001953 }
1954
1955 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1956 }
James Feist6ebf9de2018-05-15 15:01:17 -07001957
James Feist4131aea2018-03-09 09:47:30 -08001958 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1959 watchI2cBusses);
1960 };
1961
1962 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001963 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001964 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001965
James Feist3cb5fec2018-01-23 14:41:51 -08001966 io.run();
1967 return 0;
1968}