blob: 7ee7f3bd9e00d9518421343d7c0147c6fa4b4930 [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 Venturea49dc332019-10-26 08:32:02 -070018#include "Utils.hpp"
19
James Feist3b860982018-10-02 14:34:07 -070020#include <errno.h>
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>
Brad Bishop82c84bb2020-08-26 14:12:50 -040026#include <boost/asio/deadline_timer.hpp>
27#include <boost/asio/io_service.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>
30#include <sdbusplus/asio/connection.hpp>
31#include <sdbusplus/asio/object_server.hpp>
32
33#include <array>
James Feist3b860982018-10-02 14:34:07 -070034#include <chrono>
35#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070036#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080037#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070038#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080039#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070040#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080041#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070042#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080043#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070044#include <set>
45#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070046#include <string>
James Feist3b860982018-10-02 14:34:07 -070047#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080048#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080049#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070050#include <vector>
James Feist3b860982018-10-02 14:34:07 -070051
James Feist8c505da2020-05-28 10:06:33 -070052extern "C"
53{
James Feist3b860982018-10-02 14:34:07 -070054#include <i2c/smbus.h>
55#include <linux/i2c-dev.h>
56}
James Feist3cb5fec2018-01-23 14:41:51 -080057
Ed Tanous072e25d2018-12-16 21:45:20 -080058namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080059static constexpr bool DEBUG = false;
60static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070061constexpr size_t MAX_FRU_SIZE = 512;
62constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070063constexpr size_t busTimeoutSeconds = 5;
Andrei Kartashev2f0de172020-08-13 14:29:40 +030064constexpr size_t fruBlockSize = 8; // FRU areas are measured in 8-byte blocks
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 Kartashev9f0f2d12020-08-20 04:24:37 +030073enum class fruAreas
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +030074{
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030075 fruAreaInternal = 0,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +030076 fruAreaChassis,
77 fruAreaBoard,
78 fruAreaProduct,
79 fruAreaMultirecord
80};
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030081inline fruAreas operator++(fruAreas& x)
82{
83 return x = static_cast<fruAreas>(std::underlying_type<fruAreas>::type(x) +
84 1);
85}
86
87static const std::vector<std::string> FRU_AREA_NAMES = {
James Feist3cb5fec2018-01-23 14:41:51 -080088 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070089const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030090using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080091using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
92
James Feist444830e2019-04-05 08:38:16 -070093static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070094struct FindDevicesWithCallback;
95
Nikhil Potaded8884f12019-03-27 13:27:13 -070096static BusMap busMap;
97
James Feistcb5661d2020-06-12 15:05:01 -070098static bool powerIsOn = false;
99
James Feist8a983922019-10-24 17:11:56 -0700100static boost::container::flat_map<
101 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
102 foundDevices;
103
James Feist7972bb92019-11-13 15:59:24 -0800104static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
105
James Feist5cb06082019-10-24 17:11:13 -0700106boost::asio::io_service io;
107auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
108auto objServer = sdbusplus::asio::object_server(systemBus);
109
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300110static const std::vector<std::string> CHASSIS_FRU_AREAS = {"PART_NUMBER",
111 "SERIAL_NUMBER"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530112
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300113static const std::vector<std::string> BOARD_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300114 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
115 "FRU_VERSION_ID"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530116
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300117static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300118 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
119 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID"};
120
121static const std::string FRU_CUSTOM_FIELD_NAME = "INFO_AM";
Joshi-Mansid73b7442020-03-27 19:10:21 +0530122
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300123static inline unsigned int getHeaderAreaFieldOffset(fruAreas area)
124{
125 return static_cast<unsigned int>(area) + 1;
126}
127static inline const std::string& getFruAreaName(fruAreas area)
128{
129 return FRU_AREA_NAMES[static_cast<unsigned int>(area)];
130}
Patrick Venturebaba7672019-10-26 09:26:41 -0700131bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300132bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530133 const std::string& assetTag, uint32_t bus, uint32_t address,
134 std::string propertyName,
135 boost::container::flat_map<
136 std::pair<size_t, size_t>,
137 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700138
Xiang Liu2801a702020-01-20 14:29:34 -0800139using ReadBlockFunc =
140 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
141 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700142
143// Read and validate FRU contents, given the flag required for raw i2c, the open
144// file handle, a read method, and a helper string for failures.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300145std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300146 ReadBlockFunc readBlock,
147 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700148{
149 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
150
Xiang Liu2801a702020-01-20 14:29:34 -0800151 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700152 {
153 std::cerr << "failed to read " << errorHelp << "\n";
154 return {};
155 }
156
157 // check the header checksum
158 if (!validateHeader(blockData))
159 {
160 if (DEBUG)
161 {
162 std::cerr << "Illegal header " << errorHelp << "\n";
163 }
164
165 return {};
166 }
167
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300168 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700169 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
170
Patrick Venturee26395d2019-10-29 14:05:16 -0700171 bool hasMultiRecords = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300172 ssize_t fruLength = fruBlockSize; // At least FRU header is present
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300173 for (fruAreas area = fruAreas::fruAreaInternal;
174 area <= fruAreas::fruAreaMultirecord; ++area)
Patrick Venturebaba7672019-10-26 09:26:41 -0700175 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700176 // Offset value can be 255.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300177 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
Patrick Venturebaba7672019-10-26 09:26:41 -0700178 if (areaOffset == 0)
179 {
180 continue;
181 }
182
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300183 // MultiRecords are different. area is not tracking section, it's
184 // walking the common header.
185 if (area == fruAreas::fruAreaMultirecord)
Patrick Venturee26395d2019-10-29 14:05:16 -0700186 {
187 hasMultiRecords = true;
188 break;
189 }
190
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300191 areaOffset *= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700192
Xiang Liu2801a702020-01-20 14:29:34 -0800193 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
194 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700195 {
196 std::cerr << "failed to read " << errorHelp << "\n";
197 return {};
198 }
199
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700200 // Ignore data type (blockData is already unsigned).
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300201 size_t length = blockData[1] * fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700202 areaOffset += length;
203 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
204 }
205
Patrick Venturee26395d2019-10-29 14:05:16 -0700206 if (hasMultiRecords)
207 {
208 // device[area count] is the index to the last area because the 0th
209 // entry is not an offset in the common header.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300210 unsigned int areaOffset =
211 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300212 areaOffset *= fruBlockSize;
Patrick Venturee26395d2019-10-29 14:05:16 -0700213
214 // the multi-area record header is 5 bytes long.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300215 constexpr size_t multiRecordHeaderSize = 5;
216 constexpr uint8_t multiRecordEndOfListMask = 0x80;
Patrick Venturee26395d2019-10-29 14:05:16 -0700217
218 // Sanity hard-limit to 64KB.
219 while (areaOffset < std::numeric_limits<uint16_t>::max())
220 {
221 // In multi-area, the area offset points to the 0th record, each
222 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800223 if (readBlock(flag, file, address,
224 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700225 blockData.data()) < 0)
226 {
227 std::cerr << "failed to read " << errorHelp << "\n";
228 return {};
229 }
230
231 // Ok, let's check the record length, which is in bytes (unsigned,
232 // up to 255, so blockData should hold uint8_t not char)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300233 size_t recordLength = blockData[2];
Patrick Venturee26395d2019-10-29 14:05:16 -0700234 areaOffset += (recordLength + multiRecordHeaderSize);
235 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
236
237 // If this is the end of the list bail.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300238 if ((blockData[1] & multiRecordEndOfListMask))
Patrick Venturee26395d2019-10-29 14:05:16 -0700239 {
240 break;
241 }
242 }
243 }
244
Patrick Venturebaba7672019-10-26 09:26:41 -0700245 // You already copied these first 8 bytes (the ipmi fru header size)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300246 fruLength -= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700247
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300248 int readOffset = fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700249
250 while (fruLength > 0)
251 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300252 int requestLength =
253 std::min(I2C_SMBUS_BLOCK_MAX, static_cast<int>(fruLength));
Patrick Venturebaba7672019-10-26 09:26:41 -0700254
Xiang Liu2801a702020-01-20 14:29:34 -0800255 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700256 static_cast<uint8_t>(requestLength),
257 blockData.data()) < 0)
258 {
259 std::cerr << "failed to read " << errorHelp << "\n";
260 return {};
261 }
262
263 device.insert(device.end(), blockData.begin(),
264 blockData.begin() + requestLength);
265
266 readOffset += requestLength;
267 fruLength -= requestLength;
268 }
269
270 return device;
271}
272
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700273// Given a bus/address, produce the path in sysfs for an eeprom.
274static std::string getEepromPath(size_t bus, size_t address)
275{
276 std::stringstream output;
277 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
278 << std::setfill('0') << std::setw(4) << std::hex << address
279 << "/eeprom";
280 return output.str();
281}
282
283static bool hasEepromFile(size_t bus, size_t address)
284{
285 auto path = getEepromPath(bus, address);
286 try
287 {
288 return fs::exists(path);
289 }
290 catch (...)
291 {
292 return false;
293 }
294}
295
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700296static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800297 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700298 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700299{
300 auto result = lseek(fd, offset, SEEK_SET);
301 if (result < 0)
302 {
303 std::cerr << "failed to seek\n";
304 return -1;
305 }
306
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700307 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700308}
309
James Feist5d7f4692020-06-17 18:22:33 -0700310static int busStrToInt(const std::string& busName)
311{
312 auto findBus = busName.rfind("-");
313 if (findBus == std::string::npos)
314 {
315 return -1;
316 }
317 return std::stoi(busName.substr(findBus + 1));
318}
319
James Feist7972bb92019-11-13 15:59:24 -0800320static int getRootBus(size_t bus)
321{
322 auto ec = std::error_code();
323 auto path = std::filesystem::read_symlink(
324 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
325 std::to_string(bus) + "/mux_device"),
326 ec);
327 if (ec)
328 {
329 return -1;
330 }
331
332 std::string filename = path.filename();
333 auto findBus = filename.find("-");
334 if (findBus == std::string::npos)
335 {
336 return -1;
337 }
338 return std::stoi(filename.substr(0, findBus));
339}
340
James Feistc95cb142018-02-26 10:41:42 -0800341static bool isMuxBus(size_t bus)
342{
Ed Tanous072e25d2018-12-16 21:45:20 -0800343 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800344 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
345}
346
James Feist8a983922019-10-24 17:11:56 -0700347static void makeProbeInterface(size_t bus, size_t address)
348{
349 if (isMuxBus(bus))
350 {
351 return; // the mux buses are random, no need to publish
352 }
353 auto [it, success] = foundDevices.emplace(
354 std::make_pair(bus, address),
355 objServer.add_interface(
356 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
357 std::to_string(address),
358 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
359 if (!success)
360 {
361 return; // already added
362 }
363 it->second->register_property("Bus", bus);
364 it->second->register_property("Address", address);
365 it->second->initialize();
366}
367
Vijay Khemka2d681f62018-11-06 15:51:00 -0800368static int isDevice16Bit(int file)
369{
370 /* Get first byte */
371 int byte1 = i2c_smbus_read_byte_data(file, 0);
372 if (byte1 < 0)
373 {
374 return byte1;
375 }
376 /* Read 7 more bytes, it will read same first byte in case of
377 * 8 bit but it will read next byte in case of 16 bit
378 */
379 for (int i = 0; i < 7; i++)
380 {
381 int byte2 = i2c_smbus_read_byte_data(file, 0);
382 if (byte2 < 0)
383 {
384 return byte2;
385 }
386 if (byte2 != byte1)
387 {
388 return 1;
389 }
390 }
391 return 0;
392}
393
Xiang Liu2801a702020-01-20 14:29:34 -0800394// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
395// from_slave_buf_len bytes.
396static int i2c_smbus_write_then_read(int file, uint16_t address,
397 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
398 uint8_t* fromSlaveBuf,
399 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800400{
Xiang Liu2801a702020-01-20 14:29:34 -0800401 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
402 fromSlaveBufLen == 0)
403 {
404 return -1;
405 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800406
Xiang Liu2801a702020-01-20 14:29:34 -0800407#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
408 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
409 struct i2c_rdwr_ioctl_data rdwr;
410
411 msgs[0].addr = address;
412 msgs[0].flags = 0;
413 msgs[0].len = toSlaveBufLen;
414 msgs[0].buf = toSlaveBuf;
415 msgs[1].addr = address;
416 msgs[1].flags = I2C_M_RD;
417 msgs[1].len = fromSlaveBufLen;
418 msgs[1].buf = fromSlaveBuf;
419
420 rdwr.msgs = msgs;
421 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
422
423 int ret = ioctl(file, I2C_RDWR, &rdwr);
424
425 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
426}
427
428static int64_t readBlockData(int flag, int file, uint16_t address,
429 uint16_t offset, uint8_t len, uint8_t* buf)
430{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800431 if (flag == 0)
432 {
Xiang Liu2801a702020-01-20 14:29:34 -0800433 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
434 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800435 }
436
Xiang Liu2801a702020-01-20 14:29:34 -0800437 offset = htobe16(offset);
438 return i2c_smbus_write_then_read(
439 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800440}
441
James Feist24bae7a2019-04-03 09:50:56 -0700442bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
443{
444 // ipmi spec format version number is currently at 1, verify it
445 if (blockData[0] != 0x1)
446 {
447 return false;
448 }
449
450 // verify pad is set to 0
451 if (blockData[6] != 0x0)
452 {
453 return false;
454 }
455
456 // verify offsets are 0, or don't point to another offset
457 std::set<uint8_t> foundOffsets;
458 for (int ii = 1; ii < 6; ii++)
459 {
460 if (blockData[ii] == 0)
461 {
462 continue;
463 }
James Feist0eb40352019-04-09 14:44:04 -0700464 auto inserted = foundOffsets.insert(blockData[ii]);
465 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700466 {
467 return false;
468 }
469 }
470
471 // validate checksum
472 size_t sum = 0;
473 for (int jj = 0; jj < 7; jj++)
474 {
475 sum += blockData[jj];
476 }
477 sum = (256 - sum) & 0xFF;
478
479 if (sum != blockData[7])
480 {
481 return false;
482 }
483 return true;
484}
485
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700486// TODO: This code is very similar to the non-eeprom version and can be merged
487// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300488static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700489{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700490 auto path = getEepromPath(bus, address);
491
492 int file = open(path.c_str(), O_RDONLY);
493 if (file < 0)
494 {
495 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700496 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700497 }
498
Patrick Venturebaba7672019-10-26 09:26:41 -0700499 std::string errorMessage = "eeprom at " + std::to_string(bus) +
500 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300501 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800502 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700503
504 close(file);
505 return device;
506}
507
508std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
509{
510 std::set<int> foundList;
511
512 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
513
514 // For each file listed under the i2c device
515 // NOTE: This should be faster than just checking for each possible address
516 // path.
517 for (const auto& p : fs::directory_iterator(path))
518 {
519 const std::string node = p.path().string();
520 std::smatch m;
521 bool found =
522 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
523
524 if (!found)
525 {
526 continue;
527 }
528 if (m.size() != 2)
529 {
530 std::cerr << "regex didn't capture\n";
531 continue;
532 }
533
534 std::ssub_match subMatch = m[1];
535 std::string addressString = subMatch.str();
536
537 std::size_t ignored;
538 const int hexBase = 16;
539 int address = std::stoi(addressString, &ignored, hexBase);
540
541 const std::string eeprom = node + "/eeprom";
542
543 try
544 {
545 if (!fs::exists(eeprom))
546 {
547 continue;
548 }
549 }
550 catch (...)
551 {
552 continue;
553 }
554
555 // There is an eeprom file at this address, it may have invalid
556 // contents, but we found it.
557 foundList.insert(address);
558
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300559 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700560 if (!device.empty())
561 {
562 devices->emplace(address, device);
563 }
564 }
565
566 return foundList;
567}
568
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300569int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700570 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800571{
James Feist3cb5fec2018-01-23 14:41:51 -0800572
James Feist26c27ad2018-07-25 15:09:40 -0700573 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700574 // NOTE: When reading the devices raw on the bus, it can interfere with
575 // the driver's ability to operate, therefore read eeproms first before
576 // scanning for devices without drivers. Several experiments were run
577 // and it was determined that if there were any devices on the bus
578 // before the eeprom was hit and read, the eeprom driver wouldn't open
579 // while the bus device was open. An experiment was not performed to see
580 // if this issue was resolved if the i2c bus device was closed, but
581 // hexdumps of the eeprom later were successful.
582
583 // Scan for i2c eeproms loaded on this bus.
584 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800585 std::set<size_t>& failedItems = failedAddresses[bus];
586
587 std::set<size_t>* rootFailures = nullptr;
588 int rootBus = getRootBus(bus);
589
590 if (rootBus >= 0)
591 {
592 rootFailures = &(failedAddresses[rootBus]);
593 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700594
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530595 constexpr int startSkipSlaveAddr = 0;
596 constexpr int endSkipSlaveAddr = 12;
597
James Feist26c27ad2018-07-25 15:09:40 -0700598 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800599 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700600 if (skipList.find(ii) != skipList.end())
601 {
602 continue;
603 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530604 // skipping since no device is present in this range
605 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
606 {
607 continue;
608 }
James Feist26c27ad2018-07-25 15:09:40 -0700609 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530610 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800611 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700612 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700613 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700614 continue;
615 }
616 // probe
617 else if (i2c_smbus_read_byte(file) < 0)
618 {
619 continue;
620 }
James Feist3cb5fec2018-01-23 14:41:51 -0800621
James Feist26c27ad2018-07-25 15:09:40 -0700622 if (DEBUG)
623 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700624 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700625 << "\n";
626 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800627
James Feist8a983922019-10-24 17:11:56 -0700628 makeProbeInterface(bus, ii);
629
James Feist7972bb92019-11-13 15:59:24 -0800630 if (failedItems.find(ii) != failedItems.end())
631 {
632 // if we failed to read it once, unlikely we can read it later
633 continue;
634 }
635
636 if (rootFailures != nullptr)
637 {
638 if (rootFailures->find(ii) != rootFailures->end())
639 {
640 continue;
641 }
642 }
643
Vijay Khemka2d681f62018-11-06 15:51:00 -0800644 /* Check for Device type if it is 8 bit or 16 bit */
645 int flag = isDevice16Bit(file);
646 if (flag < 0)
647 {
648 std::cerr << "failed to read bus " << bus << " address " << ii
649 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700650 if (powerIsOn)
651 {
652 failedItems.insert(ii);
653 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800654 continue;
655 }
656
Patrick Venturebaba7672019-10-26 09:26:41 -0700657 std::string errorMessage =
658 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300659 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300660 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800661 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700662 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700663 {
James Feist26c27ad2018-07-25 15:09:40 -0700664 continue;
665 }
James Feist26c27ad2018-07-25 15:09:40 -0700666
Patrick Venture786f1792019-08-05 16:33:44 -0700667 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800668 }
James Feist26c27ad2018-07-25 15:09:40 -0700669 return 1;
670 });
671 std::future_status status =
672 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
673 if (status == std::future_status::timeout)
674 {
675 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700676 if (powerIsOn)
677 {
678 busBlacklist.insert(bus);
679 }
James Feist444830e2019-04-05 08:38:16 -0700680 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700681 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800682 }
683
James Feist444830e2019-04-05 08:38:16 -0700684 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700685 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800686}
687
Patrick Venture11f1ff42019-08-01 10:42:12 -0700688void loadBlacklist(const char* path)
689{
690 std::ifstream blacklistStream(path);
691 if (!blacklistStream.good())
692 {
693 // File is optional.
694 std::cerr << "Cannot open blacklist file.\n\n";
695 return;
696 }
697
698 nlohmann::json data =
699 nlohmann::json::parse(blacklistStream, nullptr, false);
700 if (data.is_discarded())
701 {
702 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
703 "exiting\n";
704 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700705 }
706
707 // It's expected to have at least one field, "buses" that is an array of the
708 // buses by integer. Allow for future options to exclude further aspects,
709 // such as specific addresses or ranges.
710 if (data.type() != nlohmann::json::value_t::object)
711 {
712 std::cerr << "Illegal blacklist, expected to read dictionary\n";
713 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700714 }
715
716 // If buses field is missing, that's fine.
717 if (data.count("buses") == 1)
718 {
719 // Parse the buses array after a little validation.
720 auto buses = data.at("buses");
721 if (buses.type() != nlohmann::json::value_t::array)
722 {
723 // Buses field present but invalid, therefore this is an error.
724 std::cerr << "Invalid contents for blacklist buses field\n";
725 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700726 }
727
728 // Catch exception here for type mis-match.
729 try
730 {
731 for (const auto& bus : buses)
732 {
733 busBlacklist.insert(bus.get<size_t>());
734 }
735 }
736 catch (const nlohmann::detail::type_error& e)
737 {
738 // Type mis-match is a critical error.
739 std::cerr << "Invalid bus type: " << e.what() << "\n";
740 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700741 }
742 }
743
744 return;
745}
746
James Feista465ccc2019-02-08 12:51:01 -0800747static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700748 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800749{
James Feista465ccc2019-02-08 12:51:01 -0800750 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800751 {
James Feist5d7f4692020-06-17 18:22:33 -0700752 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800753
James Feist5d7f4692020-06-17 18:22:33 -0700754 if (bus < 0)
755 {
756 std::cerr << "Cannot translate " << i2cBus << " to int\n";
757 continue;
758 }
James Feist444830e2019-04-05 08:38:16 -0700759 if (busBlacklist.find(bus) != busBlacklist.end())
760 {
761 continue; // skip previously failed busses
762 }
James Feist3cb5fec2018-01-23 14:41:51 -0800763
James Feist0c3980a2019-12-19 11:09:27 -0800764 int rootBus = getRootBus(bus);
765 if (busBlacklist.find(rootBus) != busBlacklist.end())
766 {
767 continue;
768 }
769
James Feist3cb5fec2018-01-23 14:41:51 -0800770 auto file = open(i2cBus.c_str(), O_RDWR);
771 if (file < 0)
772 {
773 std::cerr << "unable to open i2c device " << i2cBus.string()
774 << "\n";
775 continue;
776 }
777 unsigned long funcs = 0;
778
779 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
780 {
781 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700782 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800783 << bus << "\n";
784 continue;
785 }
786 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
787 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
788 {
789 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
790 << bus << "\n";
791 continue;
792 }
James Feist98132792019-07-09 13:29:09 -0700793 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800794 device = std::make_shared<DeviceMap>();
795
Nikhil Potaded8884f12019-03-27 13:27:13 -0700796 // i2cdetect by default uses the range 0x03 to 0x77, as
797 // this is what we have tested with, use this range. Could be
798 // changed in future.
799 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800800 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700801 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800802 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700803
804 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300805 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700806
807 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800808 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700809 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800810 }
James Feist3cb5fec2018-01-23 14:41:51 -0800811 }
James Feist3cb5fec2018-01-23 14:41:51 -0800812}
813
James Feist6ebf9de2018-05-15 15:01:17 -0700814// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700815struct FindDevicesWithCallback :
816 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700817{
James Feista465ccc2019-02-08 12:51:01 -0800818 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700819 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800820 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700821 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700822 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700823 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700824 ~FindDevicesWithCallback()
825 {
826 _callback();
827 }
828 void run()
829 {
James Feist98132792019-07-09 13:29:09 -0700830 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700831 }
832
James Feista465ccc2019-02-08 12:51:01 -0800833 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800834 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700835 std::function<void(void)> _callback;
836};
837
James Feist3cb5fec2018-01-23 14:41:51 -0800838static const std::tm intelEpoch(void)
839{
James Feist98132792019-07-09 13:29:09 -0700840 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800841 val.tm_year = 1996 - 1900;
842 return val;
843}
844
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800845static char sixBitToChar(uint8_t val)
846{
847 return static_cast<char>((val & 0x3f) + ' ');
848}
849
850/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
851static const char bcdHighChars[] = {
852 ' ', '-', '.', 'X', 'X', 'X',
853};
854
855static char bcdPlusToChar(uint8_t val)
856{
857 val &= 0xf;
858 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
859}
860
861enum class DecodeState
862{
863 ok,
864 end,
865 err,
866};
867
868enum FRUDataEncoding
869{
870 binary = 0x0,
871 bcdPlus = 0x1,
872 sixBitASCII = 0x2,
873 languageDependent = 0x3,
874};
875
876/* Decode FRU data into a std::string, given an input iterator and end. If the
877 * state returned is fruDataOk, then the resulting string is the decoded FRU
878 * data. The input iterator is advanced past the data consumed.
879 *
880 * On fruDataErr, we have lost synchronisation with the length bytes, so the
881 * iterator is no longer usable.
882 */
883static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300884 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300885 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800886{
887 std::string value;
888 unsigned int i;
889
890 /* we need at least one byte to decode the type/len header */
891 if (iter == end)
892 {
893 std::cerr << "Truncated FRU data\n";
894 return make_pair(DecodeState::err, value);
895 }
896
897 uint8_t c = *(iter++);
898
899 /* 0xc1 is the end marker */
900 if (c == 0xc1)
901 {
902 return make_pair(DecodeState::end, value);
903 }
904
905 /* decode type/len byte */
906 uint8_t type = static_cast<uint8_t>(c >> 6);
907 uint8_t len = static_cast<uint8_t>(c & 0x3f);
908
909 /* we should have at least len bytes of data available overall */
910 if (iter + len > end)
911 {
912 std::cerr << "FRU data field extends past end of FRU data\n";
913 return make_pair(DecodeState::err, value);
914 }
915
916 switch (type)
917 {
918 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300919 {
920 std::stringstream ss;
921 ss << std::hex << std::setfill('0');
922 for (i = 0; i < len; i++, iter++)
923 {
924 uint8_t val = static_cast<uint8_t>(*iter);
925 ss << std::setw(2) << static_cast<int>(val);
926 }
927 value = ss.str();
928 break;
929 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800930 case FRUDataEncoding::languageDependent:
931 /* For language-code dependent encodings, assume 8-bit ASCII */
932 value = std::string(iter, iter + len);
933 iter += len;
934 break;
935
936 case FRUDataEncoding::bcdPlus:
937 value = std::string();
938 for (i = 0; i < len; i++, iter++)
939 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300940 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800941 value.push_back(bcdPlusToChar(val >> 4));
942 value.push_back(bcdPlusToChar(val & 0xf));
943 }
944 break;
945
946 case FRUDataEncoding::sixBitASCII:
947 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300948 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800949 unsigned int accumBitLen = 0;
950 value = std::string();
951 for (i = 0; i < len; i++, iter++)
952 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300953 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800954 accumBitLen += 8;
955 while (accumBitLen >= 6)
956 {
957 value.push_back(sixBitToChar(accum & 0x3f));
958 accum >>= 6;
959 accumBitLen -= 6;
960 }
961 }
962 }
963 break;
964 }
965
966 return make_pair(DecodeState::ok, value);
967}
968
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300969bool formatFRU(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800970 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800971{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300972 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800973 {
974 return false;
975 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300976 std::vector<uint8_t>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700977 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800978 std::to_string(static_cast<int>(*fruAreaOffsetField));
979
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300980 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800981
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300982 for (const std::string& area : FRU_AREA_NAMES)
James Feist3cb5fec2018-01-23 14:41:51 -0800983 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700984 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800985 if (fruAreaOffsetField >= fruBytes.end())
986 {
987 return false;
988 }
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300989 size_t offset = (*fruAreaOffsetField) * fruBlockSize;
James Feist3cb5fec2018-01-23 14:41:51 -0800990
991 if (offset > 1)
992 {
993 // +2 to skip format and length
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300994 std::vector<uint8_t>::const_iterator fruBytesIter =
James Feist3cb5fec2018-01-23 14:41:51 -0800995 fruBytes.begin() + offset + 2;
996
997 if (fruBytesIter >= fruBytes.end())
998 {
999 return false;
1000 }
1001
1002 if (area == "CHASSIS")
1003 {
1004 result["CHASSIS_TYPE"] =
1005 std::to_string(static_cast<int>(*fruBytesIter));
1006 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001007 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001008 }
1009 else if (area == "BOARD")
1010 {
1011 result["BOARD_LANGUAGE_CODE"] =
1012 std::to_string(static_cast<int>(*fruBytesIter));
1013 fruBytesIter += 1;
1014 if (fruBytesIter >= fruBytes.end())
1015 {
1016 return false;
1017 }
1018
1019 unsigned int minutes = *fruBytesIter |
1020 *(fruBytesIter + 1) << 8 |
1021 *(fruBytesIter + 2) << 16;
1022 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001023 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001024 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001025 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001026
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001027 // Tue Nov 20 23:08:00 2018
1028 char timeString[32] = {0};
1029 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001030 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001031 if (bytes == 0)
1032 {
1033 std::cerr << "invalid time string encountered\n";
1034 return false;
1035 }
1036
1037 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001038 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001039 fruAreaFieldNames = &BOARD_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001040 }
1041 else if (area == "PRODUCT")
1042 {
1043 result["PRODUCT_LANGUAGE_CODE"] =
1044 std::to_string(static_cast<int>(*fruBytesIter));
1045 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001046 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001047 }
1048 else
1049 {
1050 continue;
1051 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001052 size_t fieldIndex = 0;
1053 DecodeState state = DecodeState::ok;
1054 while (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001055 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001056 auto res = decodeFRUData(fruBytesIter, fruBytes.end());
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001057 std::string name;
1058 if (fieldIndex < fruAreaFieldNames->size())
1059 {
1060 name = area + "_" + fruAreaFieldNames->at(fieldIndex);
1061 }
1062 else
1063 {
1064 name = area + "_" + FRU_CUSTOM_FIELD_NAME +
1065 std::to_string(fieldIndex -
1066 fruAreaFieldNames->size() + 1);
1067 }
James Feist3cb5fec2018-01-23 14:41:51 -08001068
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001069 state = res.first;
1070 if (state == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001071 {
1072 break;
1073 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001074 else if (state == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001075 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001076 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001077 return false;
1078 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001079
1080 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001081
Ed Tanous2147e672019-02-27 13:59:56 -08001082 // Strip non null characters from the end
1083 value.erase(std::find_if(value.rbegin(), value.rend(),
1084 [](char ch) { return ch != 0; })
1085 .base(),
1086 value.end());
1087
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001088 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001089 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001090 }
1091 }
1092 }
1093
1094 return true;
1095}
1096
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001097std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001098{
1099 auto deviceMap = busMap.find(bus);
1100 if (deviceMap == busMap.end())
1101 {
1102 throw std::invalid_argument("Invalid Bus.");
1103 }
1104 auto device = deviceMap->second->find(address);
1105 if (device == deviceMap->second->end())
1106 {
1107 throw std::invalid_argument("Invalid Address.");
1108 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001109 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001110
1111 return ret;
1112}
1113
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001114void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001115 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001116 boost::container::flat_map<
1117 std::pair<size_t, size_t>,
1118 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001119 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001120{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001121 boost::container::flat_map<std::string, std::string> formattedFRU;
1122 if (!formatFRU(device, formattedFRU))
James Feist3cb5fec2018-01-23 14:41:51 -08001123 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001124 std::cerr << "failed to format fru for device at bus " << bus
1125 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001126 return;
1127 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001128
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001129 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001130 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001131 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001132 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001133 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001134 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001135 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001136 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001137 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001138 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001139 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001140 {
1141 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001142 std::regex illegalObject("[^A-Za-z0-9_]");
1143 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001144 }
1145 else
1146 {
1147 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1148 UNKNOWN_BUS_OBJECT_COUNT++;
1149 }
1150
James Feist918e18c2018-02-13 15:51:07 -08001151 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001152 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001153 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001154 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001155 int highest = -1;
1156 bool found = false;
1157
James Feista465ccc2019-02-08 12:51:01 -08001158 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001159 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001160 std::string path = busIface.second->get_object_path();
1161 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001162 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001163 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001164 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001165 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001166 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001167 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001168 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001169 // This device is already added to the lower numbered bus,
1170 // do not replicate it.
1171 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001172 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001173
1174 // Check if the match named has extra information.
1175 found = true;
1176 std::smatch base_match;
1177
1178 bool match = std::regex_match(
1179 path, base_match, std::regex(productName + "_(\\d+)$"));
1180 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001181 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001182 if (base_match.size() == 2)
1183 {
1184 std::ssub_match base_sub_match = base_match[1];
1185 std::string base = base_sub_match.str();
1186
1187 int value = std::stoi(base);
1188 highest = (value > highest) ? value : highest;
1189 }
James Feist79e9c0b2018-03-15 15:21:17 -07001190 }
James Feist918e18c2018-02-13 15:51:07 -08001191 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001192 } // end searching objects
1193
1194 if (found)
1195 {
1196 // We found something with the same name. If highest was still -1,
1197 // it means this new entry will be _0.
1198 productName += "_";
1199 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001200 }
1201 }
James Feist3cb5fec2018-01-23 14:41:51 -08001202
James Feist9eb0b582018-04-27 12:15:46 -07001203 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1204 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1205 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1206
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001207 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001208 {
James Feist9eb0b582018-04-27 12:15:46 -07001209
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001210 std::regex_replace(property.second.begin(), property.second.begin(),
1211 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301212 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001213 {
1214 continue;
1215 }
1216 std::string key =
1217 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301218
1219 if (property.first == "PRODUCT_ASSET_TAG")
1220 {
1221 std::string propertyName = property.first;
1222 iface->register_property(
1223 key, property.second + '\0',
1224 [bus, address, propertyName,
1225 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1226 if (strcmp(req.c_str(), resp.c_str()))
1227 {
1228 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001229 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301230 dbusInterfaceMap))
1231 {
1232 resp = req;
1233 }
1234 else
1235 {
1236 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001237 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301238 }
1239 }
1240 return 1;
1241 });
1242 }
1243 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001244 {
1245 std::cerr << "illegal key: " << key << "\n";
1246 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001247 if (DEBUG)
1248 {
1249 std::cout << property.first << ": " << property.second << "\n";
1250 }
James Feist3cb5fec2018-01-23 14:41:51 -08001251 }
James Feist2a9d6db2018-04-27 15:48:28 -07001252
1253 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001254 iface->register_property("BUS", bus);
1255 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001256
James Feist9eb0b582018-04-27 12:15:46 -07001257 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001258}
1259
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001260static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001261{
1262 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001263 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1264 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001265 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001266 baseboardFRUFile.seekg(0, std::ios_base::end);
1267 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1268 baseboardFRU.resize(fileSize);
1269 baseboardFRUFile.seekg(0, std::ios_base::beg);
1270 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001271 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001272 }
1273 else
1274 {
1275 return false;
1276 }
1277 return true;
1278}
1279
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001280bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001281{
1282 boost::container::flat_map<std::string, std::string> tmp;
1283 if (fru.size() > MAX_FRU_SIZE)
1284 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001285 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001286 return false;
1287 }
1288 // verify legal fru by running it through fru parsing logic
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001289 if (!formatFRU(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001290 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001291 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001292 return false;
1293 }
1294 // baseboard fru
1295 if (bus == 0 && address == 0)
1296 {
1297 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1298 if (!file.good())
1299 {
1300 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1301 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001302 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001303 return false;
1304 }
James Feista465ccc2019-02-08 12:51:01 -08001305 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001306 return file.good();
1307 }
1308 else
1309 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001310 if (hasEepromFile(bus, address))
1311 {
1312 auto path = getEepromPath(bus, address);
1313 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1314 if (eeprom < 0)
1315 {
1316 std::cerr << "unable to open i2c device " << path << "\n";
1317 throw DBusInternalError();
1318 return false;
1319 }
1320
1321 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1322 if (writtenBytes < 0)
1323 {
1324 std::cerr << "unable to write to i2c device " << path << "\n";
1325 close(eeprom);
1326 throw DBusInternalError();
1327 return false;
1328 }
1329
1330 close(eeprom);
1331 return true;
1332 }
1333
James Feistb49ffc32018-05-02 11:10:43 -07001334 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1335
1336 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1337 if (file < 0)
1338 {
1339 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001340 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001341 return false;
1342 }
1343 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1344 {
1345 std::cerr << "unable to set device address\n";
1346 close(file);
James Feistddb78302018-09-06 11:45:42 -07001347 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001348 return false;
1349 }
1350
1351 constexpr const size_t RETRY_MAX = 2;
1352 uint16_t index = 0;
1353 size_t retries = RETRY_MAX;
1354 while (index < fru.size())
1355 {
1356 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1357 (retries == RETRY_MAX))
1358 {
1359 // The 4K EEPROM only uses the A2 and A1 device address bits
1360 // with the third bit being a memory page address bit.
1361 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1362 {
1363 std::cerr << "unable to set device address\n";
1364 close(file);
James Feistddb78302018-09-06 11:45:42 -07001365 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001366 return false;
1367 }
1368 }
1369
James Feist98132792019-07-09 13:29:09 -07001370 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1371 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001372 {
1373 if (!retries--)
1374 {
1375 std::cerr << "error writing fru: " << strerror(errno)
1376 << "\n";
1377 close(file);
James Feistddb78302018-09-06 11:45:42 -07001378 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001379 return false;
1380 }
1381 }
1382 else
1383 {
1384 retries = RETRY_MAX;
1385 index++;
1386 }
1387 // most eeproms require 5-10ms between writes
1388 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1389 }
1390 close(file);
1391 return true;
1392 }
1393}
1394
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001395void rescanOneBus(
1396 BusMap& busmap, uint8_t busNum,
1397 boost::container::flat_map<
1398 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001399 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1400 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001401{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001402 for (auto& [pair, interface] : foundDevices)
1403 {
1404 if (pair.first == static_cast<size_t>(busNum))
1405 {
1406 objServer.remove_interface(interface);
1407 foundDevices.erase(pair);
1408 }
1409 }
1410
James Feist5d7f4692020-06-17 18:22:33 -07001411 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1412 if (!fs::exists(busPath))
1413 {
1414 if (dbusCall)
1415 {
1416 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1417 << "\n";
1418 throw std::invalid_argument("Invalid Bus.");
1419 }
1420 return;
1421 }
1422
1423 std::vector<fs::path> i2cBuses;
1424 i2cBuses.emplace_back(busPath);
1425
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001426 auto scan = std::make_shared<FindDevicesWithCallback>(
1427 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1428 for (auto& busIface : dbusInterfaceMap)
1429 {
1430 if (busIface.first.first == static_cast<size_t>(busNum))
1431 {
1432 objServer.remove_interface(busIface.second);
1433 }
1434 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001435 auto found = busmap.find(busNum);
1436 if (found == busmap.end() || found->second == nullptr)
1437 {
1438 return;
1439 }
1440 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001441 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001442 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001443 static_cast<uint32_t>(busNum), device.first);
1444 }
1445 });
1446 scan->run();
1447}
1448
James Feist9eb0b582018-04-27 12:15:46 -07001449void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001450 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001451 boost::container::flat_map<
1452 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001453 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001454{
James Feist6ebf9de2018-05-15 15:01:17 -07001455 static boost::asio::deadline_timer timer(io);
1456 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001457
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001458 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001459 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001460 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001461 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001462
Nikhil Potaded8884f12019-03-27 13:27:13 -07001463 boost::container::flat_map<size_t, fs::path> busPaths;
1464 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001465 {
James Feist4131aea2018-03-09 09:47:30 -08001466 std::cerr << "unable to find i2c devices\n";
1467 return;
James Feist918e18c2018-02-13 15:51:07 -08001468 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001469
1470 for (auto busPath : busPaths)
1471 {
1472 i2cBuses.emplace_back(busPath.second);
1473 }
James Feist4131aea2018-03-09 09:47:30 -08001474
James Feist98132792019-07-09 13:29:09 -07001475 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001476 for (auto& [pair, interface] : foundDevices)
1477 {
1478 objServer.remove_interface(interface);
1479 }
1480 foundDevices.clear();
1481
James Feist5cb06082019-10-24 17:11:13 -07001482 auto scan =
1483 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001484 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001485 {
1486 objServer.remove_interface(busIface.second);
1487 }
James Feist4131aea2018-03-09 09:47:30 -08001488
James Feist6ebf9de2018-05-15 15:01:17 -07001489 dbusInterfaceMap.clear();
1490 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001491
James Feist6ebf9de2018-05-15 15:01:17 -07001492 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001493 std::vector<uint8_t> baseboardFRU;
1494 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001495 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001496 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001497 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001498 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001499 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001500 }
James Feist98132792019-07-09 13:29:09 -07001501 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001502 {
James Feista465ccc2019-02-08 12:51:01 -08001503 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001504 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001505 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001506 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001507 }
1508 }
1509 });
1510 scan->run();
1511 });
James Feist918e18c2018-02-13 15:51:07 -08001512}
1513
Joshi-Mansid73b7442020-03-27 19:10:21 +05301514// Calculate new checksum for fru info area
1515size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1516{
1517 constexpr int checksumMod = 256;
1518 constexpr uint8_t modVal = 0xFF;
1519 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1520 return (checksumMod - sum) & modVal;
1521}
1522
1523// Update new fru area length &
1524// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001525// Return the offset of the area checksum byte
1526static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1527 size_t fruAreaStart,
1528 size_t fruAreaEndOfFieldsOffset,
1529 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301530{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001531 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301532
1533 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001534 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1535 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301536
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001537 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301538 size_t checksumLoc;
1539 if (!mod)
1540 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001541 traverseFRUAreaIndex += (fruBlockSize);
1542 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301543 }
1544 else
1545 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001546 traverseFRUAreaIndex += (fruBlockSize - mod);
1547 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301548 }
1549
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001550 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1551 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1552 size_t fruAreaLengthLoc = fruAreaStart + 1;
1553 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301554
1555 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001556 std::vector<uint8_t> finalFRUData;
1557 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1558 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301559
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001560 size_t checksumVal = calculateChecksum(finalFRUData);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301561
1562 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001563 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301564}
1565
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001566static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301567{
1568 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001569 constexpr uint8_t endOfFields = 0xC1;
1570 if (fruFieldTypeLenValue == endOfFields)
1571 {
1572 return -1;
1573 }
1574 else
1575 {
1576 return fruFieldTypeLenValue & typeLenMask;
1577 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301578}
1579
1580// Details with example of Asset Tag Update
1581// To find location of Product Info Area asset tag as per FRU specification
1582// 1. Find product Info area starting offset (*8 - as header will be in
1583// multiple of 8 bytes).
1584// 2. Skip 3 bytes of product info area (like format version, area length,
1585// and language code).
1586// 3. Traverse manufacturer name, product name, product version, & product
1587// serial number, by reading type/length code to reach the Asset Tag.
1588// 4. Update the Asset Tag, reposition the product Info area in multiple of
1589// 8 bytes. Update the Product area length and checksum.
1590
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001591bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301592 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1593 std::string propertyName,
1594 boost::container::flat_map<
1595 std::pair<size_t, size_t>,
1596 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1597{
1598 size_t updatePropertyReqLen = updatePropertyReq.length();
1599 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1600 {
1601 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001602 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301603 "Invalid Length "
1604 << updatePropertyReqLen << "\n";
1605 return false;
1606 }
1607
1608 std::vector<uint8_t> fruData;
1609 try
1610 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001611 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301612 static_cast<uint8_t>(address));
1613 }
1614 catch (std::invalid_argument& e)
1615 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001616 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301617 return false;
1618 }
1619
1620 if (fruData.empty())
1621 {
1622 return false;
1623 }
1624
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001625 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301626
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001627 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301628 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001629 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001630 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001631 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1632 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301633 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001634 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001635 << " \n";
1636 return false;
1637 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001638 fruAreas fruAreaToUpdate =
1639 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1640 fruAreaOffsetFieldValue =
1641 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1642 switch (fruAreaToUpdate)
1643 {
1644 case fruAreas::fruAreaChassis:
1645 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1646 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1647 break;
1648 case fruAreas::fruAreaBoard:
1649 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1650 fruAreaFieldNames = &BOARD_FRU_AREAS;
1651 break;
1652 case fruAreas::fruAreaProduct:
1653 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1654 // i.e. version, area length and language code
1655 offset = 3;
1656 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1657 break;
1658 default:
1659 std::cerr << "Don't know how to handle property " << propertyName
1660 << " \n";
1661 return false;
1662 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001663 if (fruAreaOffsetFieldValue == 0)
1664 {
1665 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301666 return false;
1667 }
1668
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001669 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001670 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1671 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001672 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001673 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001674 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001675 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301676
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001677 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001678 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301679 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001680 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001681 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301682 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001683 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301684 break;
1685 }
1686 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001687 if (!found)
1688 {
1689 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1690 if (pos == std::string::npos)
1691 {
1692 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1693 << propertyName << "\n";
1694 return false;
1695 }
1696 std::string fieldNumStr =
1697 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1698 size_t fieldNum = std::stoi(fieldNumStr);
1699 if (fieldNum == 0)
1700 {
1701 std::cerr << "PropertyName not recognized: " << propertyName
1702 << "\n";
1703 return false;
1704 }
1705 skipToFRUUpdateField += fieldNum;
1706 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301707
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001708 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301709 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001710 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001711 if (fieldLength < 0)
1712 {
1713 break;
1714 }
1715 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301716 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001717 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301718
1719 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001720 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001721 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301722 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001723 std::cerr << "Property " << propertyName << " not present \n";
1724 return false;
1725 }
1726 fruDataIter += 1 + fieldLength;
1727 size_t restFRUFieldsLoc = fruDataIter;
1728 size_t endOfFieldsLoc = 0;
1729 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1730 {
1731 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301732 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001733 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301734 break;
1735 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001736 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301737 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001738 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301739
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001740 std::vector<uint8_t> restFRUAreaFieldsData;
1741 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001742 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001743 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301744
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001745 // Push post update fru areas if any
1746 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001747 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1748 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001749 {
1750 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001751 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001752 if ((fruAreaLoc > endOfFieldsLoc) &&
1753 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1754 {
1755 nextFRUAreaLoc = fruAreaLoc;
1756 }
1757 }
1758 std::vector<uint8_t> restFRUAreasData;
1759 if (nextFRUAreaLoc)
1760 {
1761 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1762 fruData.size() - nextFRUAreaLoc,
1763 std::back_inserter(restFRUAreasData));
1764 }
1765
1766 // check FRU area size
1767 size_t fruAreaDataSize =
1768 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1769 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1770 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1771 {
1772
1773#ifdef ENABLE_FRU_AREA_RESIZE
1774 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1775 // round size to 8-byte blocks
1776 newFRUAreaSize =
1777 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1778 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1779 fruData.resize(newFRUDataSize);
1780 fruAreaSize = newFRUAreaSize;
1781 fruAreaEnd = fruAreaStart + fruAreaSize;
1782#else
1783 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1784 << " should not be greater than available FRU area size: "
1785 << fruAreaAvailableSize << "\n";
1786 return false;
1787#endif // ENABLE_FRU_AREA_RESIZE
1788 }
1789
Joshi-Mansid73b7442020-03-27 19:10:21 +05301790 // write new requested property field length and data
1791 constexpr uint8_t newTypeLenMask = 0xC0;
1792 fruData[fruUpdateFieldLoc] =
1793 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1794 fruUpdateFieldLoc++;
1795 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1796 fruData.begin() + fruUpdateFieldLoc);
1797
1798 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001799 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1800 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001801 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1802 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301803
1804 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001805 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1806 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301807
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001808#ifdef ENABLE_FRU_AREA_RESIZE
1809 ++nextFRUAreaNewLoc;
1810 ssize_t nextFRUAreaOffsetDiff =
1811 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1812 // Append rest FRU Areas if size changed and there were other sections after
1813 // updated one
1814 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1815 {
1816 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1817 fruData.begin() + nextFRUAreaNewLoc);
1818 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001819 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1820 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001821 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001822 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001823 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1824 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1825 {
1826 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1827 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1828 }
1829 }
1830 // Calculate new checksum
1831 std::vector<uint8_t> headerFRUData;
1832 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1833 size_t checksumVal = calculateChecksum(headerFRUData);
1834 fruData[7] = static_cast<uint8_t>(checksumVal);
1835 // fill zeros if FRU Area size decreased
1836 if (nextFRUAreaOffsetDiff < 0)
1837 {
1838 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1839 restFRUAreasData.size(),
1840 fruData.end(), 0);
1841 }
1842 }
1843#else
1844 // this is to avoid "unused variable" warning
1845 (void)nextFRUAreaNewLoc;
1846#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301847 if (fruData.empty())
1848 {
1849 return false;
1850 }
1851
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001852 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301853 fruData))
1854 {
1855 return false;
1856 }
1857
1858 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1859 rescanBusses(busMap, dbusInterfaceMap);
1860 return true;
1861}
1862
James Feist98132792019-07-09 13:29:09 -07001863int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001864{
1865 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001866 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001867 std::vector<fs::path> i2cBuses;
1868
James Feista3c180a2018-08-09 16:06:04 -07001869 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001870 {
1871 std::cerr << "unable to find i2c devices\n";
1872 return 1;
1873 }
James Feist3cb5fec2018-01-23 14:41:51 -08001874
Patrick Venture11f1ff42019-08-01 10:42:12 -07001875 // check for and load blacklist with initial buses.
1876 loadBlacklist(blacklistPath);
1877
Vijay Khemka065f6d92018-12-18 10:37:47 -08001878 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001879
James Feist6ebf9de2018-05-15 15:01:17 -07001880 // this is a map with keys of pair(bus number, address) and values of
1881 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001882 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001883 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1884 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001885
James Feist9eb0b582018-04-27 12:15:46 -07001886 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1887 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1888 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001889
James Feist5cb06082019-10-24 17:11:13 -07001890 iface->register_method("ReScan",
1891 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001892
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001893 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001894 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001895 });
1896
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001897 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001898
1899 iface->register_method("WriteFru", [&](const uint8_t bus,
1900 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001901 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001902 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001903 {
James Feistddb78302018-09-06 11:45:42 -07001904 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001905 return;
1906 }
1907 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001908 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001909 });
James Feist9eb0b582018-04-27 12:15:46 -07001910 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001911
James Feist9eb0b582018-04-27 12:15:46 -07001912 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001913 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001914 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001915 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001916 std::string,
1917 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001918 values;
1919 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001920 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001921 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001922 {
James Feistcb5661d2020-06-12 15:05:01 -07001923 powerIsOn = boost::ends_with(
1924 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001925 }
James Feist6ebf9de2018-05-15 15:01:17 -07001926
James Feistcb5661d2020-06-12 15:05:01 -07001927 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001928 {
James Feist5cb06082019-10-24 17:11:13 -07001929 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001930 }
James Feist918e18c2018-02-13 15:51:07 -08001931 };
James Feist9eb0b582018-04-27 12:15:46 -07001932
1933 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001934 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001935 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001936 "openbmc_project/state/"
1937 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001938 eventHandler);
1939
James Feist4131aea2018-03-09 09:47:30 -08001940 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001941 inotify_add_watch(fd, I2C_DEV_LOCATION,
1942 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001943 std::array<char, 4096> readBuffer;
1944 std::string pendingBuffer;
1945 // monitor for new i2c devices
1946 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1947 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001948 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001949 std::size_t bytes_transferred) {
1950 if (ec)
1951 {
1952 std::cout << "Callback Error " << ec << "\n";
1953 return;
1954 }
1955 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001956 while (pendingBuffer.size() > sizeof(inotify_event))
1957 {
James Feista465ccc2019-02-08 12:51:01 -08001958 const inotify_event* iEvent =
1959 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001960 pendingBuffer.data());
1961 switch (iEvent->mask)
1962 {
James Feist9eb0b582018-04-27 12:15:46 -07001963 case IN_CREATE:
1964 case IN_MOVED_TO:
1965 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001966 std::string name(iEvent->name);
1967 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001968 {
James Feist5d7f4692020-06-17 18:22:33 -07001969 int bus = busStrToInt(name);
1970 if (bus < 0)
1971 {
1972 std::cerr << "Could not parse bus " << name
1973 << "\n";
1974 continue;
1975 }
1976 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1977 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001978 }
James Feist4131aea2018-03-09 09:47:30 -08001979 }
1980
1981 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1982 }
James Feist6ebf9de2018-05-15 15:01:17 -07001983
James Feist4131aea2018-03-09 09:47:30 -08001984 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1985 watchI2cBusses);
1986 };
1987
1988 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001989 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001990 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001991
James Feist3cb5fec2018-01-23 14:41:51 -08001992 io.run();
1993 return 0;
1994}