blob: 45d0fd90532255191e39a9f065430d3818061920 [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 Kartashev2a7e3952020-09-02 20:32:26 +0300132uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
133 std::vector<uint8_t>::const_iterator end);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300134bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530135 const std::string& assetTag, uint32_t bus, uint32_t address,
136 std::string propertyName,
137 boost::container::flat_map<
138 std::pair<size_t, size_t>,
139 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700140
Xiang Liu2801a702020-01-20 14:29:34 -0800141using ReadBlockFunc =
142 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
143 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700144
145// Read and validate FRU contents, given the flag required for raw i2c, the open
146// file handle, a read method, and a helper string for failures.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300147std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300148 ReadBlockFunc readBlock,
149 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700150{
151 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
152
Xiang Liu2801a702020-01-20 14:29:34 -0800153 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700154 {
155 std::cerr << "failed to read " << errorHelp << "\n";
156 return {};
157 }
158
159 // check the header checksum
160 if (!validateHeader(blockData))
161 {
162 if (DEBUG)
163 {
164 std::cerr << "Illegal header " << errorHelp << "\n";
165 }
166
167 return {};
168 }
169
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300170 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700171 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
172
Patrick Venturee26395d2019-10-29 14:05:16 -0700173 bool hasMultiRecords = false;
Brad Bishopef3cdc92020-10-01 10:36:21 -0400174 size_t fruLength = fruBlockSize; // At least FRU header is present
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300175 for (fruAreas area = fruAreas::fruAreaInternal;
176 area <= fruAreas::fruAreaMultirecord; ++area)
Patrick Venturebaba7672019-10-26 09:26:41 -0700177 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700178 // Offset value can be 255.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300179 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
Patrick Venturebaba7672019-10-26 09:26:41 -0700180 if (areaOffset == 0)
181 {
182 continue;
183 }
184
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300185 // MultiRecords are different. area is not tracking section, it's
186 // walking the common header.
187 if (area == fruAreas::fruAreaMultirecord)
Patrick Venturee26395d2019-10-29 14:05:16 -0700188 {
189 hasMultiRecords = true;
190 break;
191 }
192
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300193 areaOffset *= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700194
Xiang Liu2801a702020-01-20 14:29:34 -0800195 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
196 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700197 {
198 std::cerr << "failed to read " << errorHelp << "\n";
199 return {};
200 }
201
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700202 // Ignore data type (blockData is already unsigned).
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300203 size_t length = blockData[1] * fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700204 areaOffset += length;
205 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
206 }
207
Patrick Venturee26395d2019-10-29 14:05:16 -0700208 if (hasMultiRecords)
209 {
210 // device[area count] is the index to the last area because the 0th
211 // entry is not an offset in the common header.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300212 unsigned int areaOffset =
213 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300214 areaOffset *= fruBlockSize;
Patrick Venturee26395d2019-10-29 14:05:16 -0700215
216 // the multi-area record header is 5 bytes long.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300217 constexpr size_t multiRecordHeaderSize = 5;
218 constexpr uint8_t multiRecordEndOfListMask = 0x80;
Patrick Venturee26395d2019-10-29 14:05:16 -0700219
220 // Sanity hard-limit to 64KB.
221 while (areaOffset < std::numeric_limits<uint16_t>::max())
222 {
223 // In multi-area, the area offset points to the 0th record, each
224 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800225 if (readBlock(flag, file, address,
226 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700227 blockData.data()) < 0)
228 {
229 std::cerr << "failed to read " << errorHelp << "\n";
230 return {};
231 }
232
233 // Ok, let's check the record length, which is in bytes (unsigned,
234 // up to 255, so blockData should hold uint8_t not char)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300235 size_t recordLength = blockData[2];
Patrick Venturee26395d2019-10-29 14:05:16 -0700236 areaOffset += (recordLength + multiRecordHeaderSize);
237 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
238
239 // If this is the end of the list bail.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300240 if ((blockData[1] & multiRecordEndOfListMask))
Patrick Venturee26395d2019-10-29 14:05:16 -0700241 {
242 break;
243 }
244 }
245 }
246
Patrick Venturebaba7672019-10-26 09:26:41 -0700247 // You already copied these first 8 bytes (the ipmi fru header size)
Brad Bishopef3cdc92020-10-01 10:36:21 -0400248 fruLength -= std::min(fruBlockSize, fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700249
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300250 int readOffset = fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700251
252 while (fruLength > 0)
253 {
Brad Bishopef3cdc92020-10-01 10:36:21 -0400254 size_t requestLength =
255 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700256
Xiang Liu2801a702020-01-20 14:29:34 -0800257 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700258 static_cast<uint8_t>(requestLength),
259 blockData.data()) < 0)
260 {
261 std::cerr << "failed to read " << errorHelp << "\n";
262 return {};
263 }
264
265 device.insert(device.end(), blockData.begin(),
266 blockData.begin() + requestLength);
267
268 readOffset += requestLength;
Brad Bishopef3cdc92020-10-01 10:36:21 -0400269 fruLength -= std::min(requestLength, fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700270 }
271
272 return device;
273}
274
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700275// Given a bus/address, produce the path in sysfs for an eeprom.
276static std::string getEepromPath(size_t bus, size_t address)
277{
278 std::stringstream output;
279 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
280 << std::setfill('0') << std::setw(4) << std::hex << address
281 << "/eeprom";
282 return output.str();
283}
284
285static bool hasEepromFile(size_t bus, size_t address)
286{
287 auto path = getEepromPath(bus, address);
288 try
289 {
290 return fs::exists(path);
291 }
292 catch (...)
293 {
294 return false;
295 }
296}
297
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700298static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800299 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700300 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700301{
302 auto result = lseek(fd, offset, SEEK_SET);
303 if (result < 0)
304 {
305 std::cerr << "failed to seek\n";
306 return -1;
307 }
308
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700309 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700310}
311
James Feist5d7f4692020-06-17 18:22:33 -0700312static int busStrToInt(const std::string& busName)
313{
314 auto findBus = busName.rfind("-");
315 if (findBus == std::string::npos)
316 {
317 return -1;
318 }
319 return std::stoi(busName.substr(findBus + 1));
320}
321
James Feist7972bb92019-11-13 15:59:24 -0800322static int getRootBus(size_t bus)
323{
324 auto ec = std::error_code();
325 auto path = std::filesystem::read_symlink(
326 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
327 std::to_string(bus) + "/mux_device"),
328 ec);
329 if (ec)
330 {
331 return -1;
332 }
333
334 std::string filename = path.filename();
335 auto findBus = filename.find("-");
336 if (findBus == std::string::npos)
337 {
338 return -1;
339 }
340 return std::stoi(filename.substr(0, findBus));
341}
342
James Feistc95cb142018-02-26 10:41:42 -0800343static bool isMuxBus(size_t bus)
344{
Ed Tanous072e25d2018-12-16 21:45:20 -0800345 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800346 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
347}
348
James Feist8a983922019-10-24 17:11:56 -0700349static void makeProbeInterface(size_t bus, size_t address)
350{
351 if (isMuxBus(bus))
352 {
353 return; // the mux buses are random, no need to publish
354 }
355 auto [it, success] = foundDevices.emplace(
356 std::make_pair(bus, address),
357 objServer.add_interface(
358 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
359 std::to_string(address),
360 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
361 if (!success)
362 {
363 return; // already added
364 }
365 it->second->register_property("Bus", bus);
366 it->second->register_property("Address", address);
367 it->second->initialize();
368}
369
Vijay Khemka2d681f62018-11-06 15:51:00 -0800370static int isDevice16Bit(int file)
371{
372 /* Get first byte */
373 int byte1 = i2c_smbus_read_byte_data(file, 0);
374 if (byte1 < 0)
375 {
376 return byte1;
377 }
378 /* Read 7 more bytes, it will read same first byte in case of
379 * 8 bit but it will read next byte in case of 16 bit
380 */
381 for (int i = 0; i < 7; i++)
382 {
383 int byte2 = i2c_smbus_read_byte_data(file, 0);
384 if (byte2 < 0)
385 {
386 return byte2;
387 }
388 if (byte2 != byte1)
389 {
390 return 1;
391 }
392 }
393 return 0;
394}
395
Xiang Liu2801a702020-01-20 14:29:34 -0800396// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
397// from_slave_buf_len bytes.
398static int i2c_smbus_write_then_read(int file, uint16_t address,
399 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
400 uint8_t* fromSlaveBuf,
401 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800402{
Xiang Liu2801a702020-01-20 14:29:34 -0800403 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
404 fromSlaveBufLen == 0)
405 {
406 return -1;
407 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800408
Xiang Liu2801a702020-01-20 14:29:34 -0800409#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
410 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
411 struct i2c_rdwr_ioctl_data rdwr;
412
413 msgs[0].addr = address;
414 msgs[0].flags = 0;
415 msgs[0].len = toSlaveBufLen;
416 msgs[0].buf = toSlaveBuf;
417 msgs[1].addr = address;
418 msgs[1].flags = I2C_M_RD;
419 msgs[1].len = fromSlaveBufLen;
420 msgs[1].buf = fromSlaveBuf;
421
422 rdwr.msgs = msgs;
423 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
424
425 int ret = ioctl(file, I2C_RDWR, &rdwr);
426
427 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
428}
429
430static int64_t readBlockData(int flag, int file, uint16_t address,
431 uint16_t offset, uint8_t len, uint8_t* buf)
432{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800433 if (flag == 0)
434 {
Xiang Liu2801a702020-01-20 14:29:34 -0800435 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
436 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800437 }
438
Xiang Liu2801a702020-01-20 14:29:34 -0800439 offset = htobe16(offset);
440 return i2c_smbus_write_then_read(
441 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800442}
443
James Feist24bae7a2019-04-03 09:50:56 -0700444bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
445{
446 // ipmi spec format version number is currently at 1, verify it
447 if (blockData[0] != 0x1)
448 {
449 return false;
450 }
451
452 // verify pad is set to 0
453 if (blockData[6] != 0x0)
454 {
455 return false;
456 }
457
458 // verify offsets are 0, or don't point to another offset
459 std::set<uint8_t> foundOffsets;
460 for (int ii = 1; ii < 6; ii++)
461 {
462 if (blockData[ii] == 0)
463 {
464 continue;
465 }
James Feist0eb40352019-04-09 14:44:04 -0700466 auto inserted = foundOffsets.insert(blockData[ii]);
467 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700468 {
469 return false;
470 }
471 }
472
473 // validate checksum
474 size_t sum = 0;
475 for (int jj = 0; jj < 7; jj++)
476 {
477 sum += blockData[jj];
478 }
479 sum = (256 - sum) & 0xFF;
480
481 if (sum != blockData[7])
482 {
483 return false;
484 }
485 return true;
486}
487
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700488// TODO: This code is very similar to the non-eeprom version and can be merged
489// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300490static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700491{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700492 auto path = getEepromPath(bus, address);
493
494 int file = open(path.c_str(), O_RDONLY);
495 if (file < 0)
496 {
497 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700498 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700499 }
500
Patrick Venturebaba7672019-10-26 09:26:41 -0700501 std::string errorMessage = "eeprom at " + std::to_string(bus) +
502 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300503 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800504 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700505
506 close(file);
507 return device;
508}
509
510std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
511{
512 std::set<int> foundList;
513
514 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
515
516 // For each file listed under the i2c device
517 // NOTE: This should be faster than just checking for each possible address
518 // path.
519 for (const auto& p : fs::directory_iterator(path))
520 {
521 const std::string node = p.path().string();
522 std::smatch m;
523 bool found =
524 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
525
526 if (!found)
527 {
528 continue;
529 }
530 if (m.size() != 2)
531 {
532 std::cerr << "regex didn't capture\n";
533 continue;
534 }
535
536 std::ssub_match subMatch = m[1];
537 std::string addressString = subMatch.str();
538
539 std::size_t ignored;
540 const int hexBase = 16;
541 int address = std::stoi(addressString, &ignored, hexBase);
542
543 const std::string eeprom = node + "/eeprom";
544
545 try
546 {
547 if (!fs::exists(eeprom))
548 {
549 continue;
550 }
551 }
552 catch (...)
553 {
554 continue;
555 }
556
557 // There is an eeprom file at this address, it may have invalid
558 // contents, but we found it.
559 foundList.insert(address);
560
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300561 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700562 if (!device.empty())
563 {
564 devices->emplace(address, device);
565 }
566 }
567
568 return foundList;
569}
570
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300571int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700572 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800573{
James Feist3cb5fec2018-01-23 14:41:51 -0800574
James Feist26c27ad2018-07-25 15:09:40 -0700575 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700576 // NOTE: When reading the devices raw on the bus, it can interfere with
577 // the driver's ability to operate, therefore read eeproms first before
578 // scanning for devices without drivers. Several experiments were run
579 // and it was determined that if there were any devices on the bus
580 // before the eeprom was hit and read, the eeprom driver wouldn't open
581 // while the bus device was open. An experiment was not performed to see
582 // if this issue was resolved if the i2c bus device was closed, but
583 // hexdumps of the eeprom later were successful.
584
585 // Scan for i2c eeproms loaded on this bus.
586 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800587 std::set<size_t>& failedItems = failedAddresses[bus];
588
589 std::set<size_t>* rootFailures = nullptr;
590 int rootBus = getRootBus(bus);
591
592 if (rootBus >= 0)
593 {
594 rootFailures = &(failedAddresses[rootBus]);
595 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700596
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530597 constexpr int startSkipSlaveAddr = 0;
598 constexpr int endSkipSlaveAddr = 12;
599
James Feist26c27ad2018-07-25 15:09:40 -0700600 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800601 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700602 if (skipList.find(ii) != skipList.end())
603 {
604 continue;
605 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530606 // skipping since no device is present in this range
607 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
608 {
609 continue;
610 }
James Feist26c27ad2018-07-25 15:09:40 -0700611 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530612 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800613 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700614 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700615 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700616 continue;
617 }
618 // probe
619 else if (i2c_smbus_read_byte(file) < 0)
620 {
621 continue;
622 }
James Feist3cb5fec2018-01-23 14:41:51 -0800623
James Feist26c27ad2018-07-25 15:09:40 -0700624 if (DEBUG)
625 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700626 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700627 << "\n";
628 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800629
James Feist8a983922019-10-24 17:11:56 -0700630 makeProbeInterface(bus, ii);
631
James Feist7972bb92019-11-13 15:59:24 -0800632 if (failedItems.find(ii) != failedItems.end())
633 {
634 // if we failed to read it once, unlikely we can read it later
635 continue;
636 }
637
638 if (rootFailures != nullptr)
639 {
640 if (rootFailures->find(ii) != rootFailures->end())
641 {
642 continue;
643 }
644 }
645
Vijay Khemka2d681f62018-11-06 15:51:00 -0800646 /* Check for Device type if it is 8 bit or 16 bit */
647 int flag = isDevice16Bit(file);
648 if (flag < 0)
649 {
650 std::cerr << "failed to read bus " << bus << " address " << ii
651 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700652 if (powerIsOn)
653 {
654 failedItems.insert(ii);
655 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800656 continue;
657 }
658
Patrick Venturebaba7672019-10-26 09:26:41 -0700659 std::string errorMessage =
660 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300661 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300662 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800663 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700664 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700665 {
James Feist26c27ad2018-07-25 15:09:40 -0700666 continue;
667 }
James Feist26c27ad2018-07-25 15:09:40 -0700668
Patrick Venture786f1792019-08-05 16:33:44 -0700669 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800670 }
James Feist26c27ad2018-07-25 15:09:40 -0700671 return 1;
672 });
673 std::future_status status =
674 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
675 if (status == std::future_status::timeout)
676 {
677 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700678 if (powerIsOn)
679 {
680 busBlacklist.insert(bus);
681 }
James Feist444830e2019-04-05 08:38:16 -0700682 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700683 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800684 }
685
James Feist444830e2019-04-05 08:38:16 -0700686 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700687 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800688}
689
Patrick Venture11f1ff42019-08-01 10:42:12 -0700690void loadBlacklist(const char* path)
691{
692 std::ifstream blacklistStream(path);
693 if (!blacklistStream.good())
694 {
695 // File is optional.
696 std::cerr << "Cannot open blacklist file.\n\n";
697 return;
698 }
699
700 nlohmann::json data =
701 nlohmann::json::parse(blacklistStream, nullptr, false);
702 if (data.is_discarded())
703 {
704 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
705 "exiting\n";
706 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700707 }
708
709 // It's expected to have at least one field, "buses" that is an array of the
710 // buses by integer. Allow for future options to exclude further aspects,
711 // such as specific addresses or ranges.
712 if (data.type() != nlohmann::json::value_t::object)
713 {
714 std::cerr << "Illegal blacklist, expected to read dictionary\n";
715 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700716 }
717
718 // If buses field is missing, that's fine.
719 if (data.count("buses") == 1)
720 {
721 // Parse the buses array after a little validation.
722 auto buses = data.at("buses");
723 if (buses.type() != nlohmann::json::value_t::array)
724 {
725 // Buses field present but invalid, therefore this is an error.
726 std::cerr << "Invalid contents for blacklist buses field\n";
727 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700728 }
729
730 // Catch exception here for type mis-match.
731 try
732 {
733 for (const auto& bus : buses)
734 {
735 busBlacklist.insert(bus.get<size_t>());
736 }
737 }
738 catch (const nlohmann::detail::type_error& e)
739 {
740 // Type mis-match is a critical error.
741 std::cerr << "Invalid bus type: " << e.what() << "\n";
742 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700743 }
744 }
745
746 return;
747}
748
James Feista465ccc2019-02-08 12:51:01 -0800749static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700750 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800751{
James Feista465ccc2019-02-08 12:51:01 -0800752 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800753 {
James Feist5d7f4692020-06-17 18:22:33 -0700754 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800755
James Feist5d7f4692020-06-17 18:22:33 -0700756 if (bus < 0)
757 {
758 std::cerr << "Cannot translate " << i2cBus << " to int\n";
759 continue;
760 }
James Feist444830e2019-04-05 08:38:16 -0700761 if (busBlacklist.find(bus) != busBlacklist.end())
762 {
763 continue; // skip previously failed busses
764 }
James Feist3cb5fec2018-01-23 14:41:51 -0800765
James Feist0c3980a2019-12-19 11:09:27 -0800766 int rootBus = getRootBus(bus);
767 if (busBlacklist.find(rootBus) != busBlacklist.end())
768 {
769 continue;
770 }
771
James Feist3cb5fec2018-01-23 14:41:51 -0800772 auto file = open(i2cBus.c_str(), O_RDWR);
773 if (file < 0)
774 {
775 std::cerr << "unable to open i2c device " << i2cBus.string()
776 << "\n";
777 continue;
778 }
779 unsigned long funcs = 0;
780
781 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
782 {
783 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700784 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800785 << bus << "\n";
786 continue;
787 }
788 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
789 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
790 {
791 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
792 << bus << "\n";
793 continue;
794 }
James Feist98132792019-07-09 13:29:09 -0700795 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800796 device = std::make_shared<DeviceMap>();
797
Nikhil Potaded8884f12019-03-27 13:27:13 -0700798 // i2cdetect by default uses the range 0x03 to 0x77, as
799 // this is what we have tested with, use this range. Could be
800 // changed in future.
801 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800802 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700803 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800804 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700805
806 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300807 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700808
809 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800810 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700811 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800812 }
James Feist3cb5fec2018-01-23 14:41:51 -0800813 }
James Feist3cb5fec2018-01-23 14:41:51 -0800814}
815
James Feist6ebf9de2018-05-15 15:01:17 -0700816// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700817struct FindDevicesWithCallback :
818 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700819{
James Feista465ccc2019-02-08 12:51:01 -0800820 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700821 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800822 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700823 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700824 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700825 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700826 ~FindDevicesWithCallback()
827 {
828 _callback();
829 }
830 void run()
831 {
James Feist98132792019-07-09 13:29:09 -0700832 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700833 }
834
James Feista465ccc2019-02-08 12:51:01 -0800835 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800836 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700837 std::function<void(void)> _callback;
838};
839
James Feist3cb5fec2018-01-23 14:41:51 -0800840static const std::tm intelEpoch(void)
841{
James Feist98132792019-07-09 13:29:09 -0700842 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800843 val.tm_year = 1996 - 1900;
844 return val;
845}
846
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800847static char sixBitToChar(uint8_t val)
848{
849 return static_cast<char>((val & 0x3f) + ' ');
850}
851
852/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
853static const char bcdHighChars[] = {
854 ' ', '-', '.', 'X', 'X', 'X',
855};
856
857static char bcdPlusToChar(uint8_t val)
858{
859 val &= 0xf;
860 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
861}
862
863enum class DecodeState
864{
865 ok,
866 end,
867 err,
868};
869
870enum FRUDataEncoding
871{
872 binary = 0x0,
873 bcdPlus = 0x1,
874 sixBitASCII = 0x2,
875 languageDependent = 0x3,
876};
877
878/* Decode FRU data into a std::string, given an input iterator and end. If the
879 * state returned is fruDataOk, then the resulting string is the decoded FRU
880 * data. The input iterator is advanced past the data consumed.
881 *
882 * On fruDataErr, we have lost synchronisation with the length bytes, so the
883 * iterator is no longer usable.
884 */
885static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300886 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300887 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800888{
889 std::string value;
890 unsigned int i;
891
892 /* we need at least one byte to decode the type/len header */
893 if (iter == end)
894 {
895 std::cerr << "Truncated FRU data\n";
896 return make_pair(DecodeState::err, value);
897 }
898
899 uint8_t c = *(iter++);
900
901 /* 0xc1 is the end marker */
902 if (c == 0xc1)
903 {
904 return make_pair(DecodeState::end, value);
905 }
906
907 /* decode type/len byte */
908 uint8_t type = static_cast<uint8_t>(c >> 6);
909 uint8_t len = static_cast<uint8_t>(c & 0x3f);
910
911 /* we should have at least len bytes of data available overall */
912 if (iter + len > end)
913 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300914 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800915 return make_pair(DecodeState::err, value);
916 }
917
918 switch (type)
919 {
920 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300921 {
922 std::stringstream ss;
923 ss << std::hex << std::setfill('0');
924 for (i = 0; i < len; i++, iter++)
925 {
926 uint8_t val = static_cast<uint8_t>(*iter);
927 ss << std::setw(2) << static_cast<int>(val);
928 }
929 value = ss.str();
930 break;
931 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800932 case FRUDataEncoding::languageDependent:
933 /* For language-code dependent encodings, assume 8-bit ASCII */
934 value = std::string(iter, iter + len);
935 iter += len;
936 break;
937
938 case FRUDataEncoding::bcdPlus:
939 value = std::string();
940 for (i = 0; i < len; i++, iter++)
941 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300942 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800943 value.push_back(bcdPlusToChar(val >> 4));
944 value.push_back(bcdPlusToChar(val & 0xf));
945 }
946 break;
947
948 case FRUDataEncoding::sixBitASCII:
949 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300950 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800951 unsigned int accumBitLen = 0;
952 value = std::string();
953 for (i = 0; i < len; i++, iter++)
954 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300955 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800956 accumBitLen += 8;
957 while (accumBitLen >= 6)
958 {
959 value.push_back(sixBitToChar(accum & 0x3f));
960 accum >>= 6;
961 accumBitLen -= 6;
962 }
963 }
964 }
965 break;
966 }
967
968 return make_pair(DecodeState::ok, value);
969}
970
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300971static void checkLang(uint8_t lang)
972{
973 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
974 // but we don't support that.
975 if (lang && lang != 25)
976 {
977 std::cerr << "Warning: language other then English is not "
978 "supported \n";
979 }
980}
981
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300982bool formatFRU(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800983 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800984{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300985 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800986 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300987 std::cerr << "Error: trying to parse empty FRU \n";
James Feist3cb5fec2018-01-23 14:41:51 -0800988 return false;
989 }
James Feist9eb0b582018-04-27 12:15:46 -0700990 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300991 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800992
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300993 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800994
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300995 // Don't parse Internal and Multirecord areas
996 for (fruAreas area = fruAreas::fruAreaChassis;
997 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800998 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300999
1000 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
1001 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -08001002 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001003 continue;
1004 }
1005 offset *= fruBlockSize;
1006 std::vector<uint8_t>::const_iterator fruBytesIter =
1007 fruBytes.begin() + offset;
1008 if (fruBytesIter + fruBlockSize >= fruBytes.end())
1009 {
1010 std::cerr << "Not enough data to parse \n";
James Feist3cb5fec2018-01-23 14:41:51 -08001011 return false;
1012 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001013 // check for format version 1
1014 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -08001015 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001016 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
1017 return false;
1018 }
1019 ++fruBytesIter;
1020 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
1021 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
1022 fruBytes.begin() + offset + fruAreaSize - 1;
1023 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001024
Andrei Kartashev272bafd2020-10-09 12:05:32 +03001025 uint8_t fruComputedChecksum =
1026 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
1027 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001028 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +03001029 std::stringstream ss;
1030 ss << std::hex << std::setfill('0');
1031 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
1032 ss << "\tComputed checksum: 0x" << std::setw(2)
1033 << static_cast<int>(fruComputedChecksum) << "\n";
1034 ss << "\tThe read checksum: 0x" << std::setw(2)
1035 << static_cast<int>(*fruBytesIterEndArea) << "\n";
1036 std::cerr << ss.str();
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001037 return false;
1038 }
1039
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001040 switch (area)
1041 {
1042 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -08001043 {
1044 result["CHASSIS_TYPE"] =
1045 std::to_string(static_cast<int>(*fruBytesIter));
1046 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001047 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001048 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001049 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001050 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -08001051 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001052 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001053 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001054 std::to_string(static_cast<int>(lang));
1055 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -08001056 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -08001057
1058 unsigned int minutes = *fruBytesIter |
1059 *(fruBytesIter + 1) << 8 |
1060 *(fruBytesIter + 2) << 16;
1061 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001062 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001063 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001064 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001065
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001066 // Tue Nov 20 23:08:00 2018
1067 char timeString[32] = {0};
1068 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001069 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001070 if (bytes == 0)
1071 {
1072 std::cerr << "invalid time string encountered\n";
1073 return false;
1074 }
1075
1076 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001077 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001078 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001079 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001080 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001081 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -08001082 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001083 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001084 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001085 std::to_string(static_cast<int>(lang));
1086 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -08001087 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001088 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001089 break;
1090 }
1091 default:
1092 {
1093 std::cerr << "Internal error: unexpected FRU area index: "
1094 << static_cast<int>(area) << " \n";
1095 return false;
1096 }
1097 }
1098 size_t fieldIndex = 0;
1099 DecodeState state;
1100 do
1101 {
1102 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea);
1103 state = res.first;
1104 std::string value = res.second;
1105 std::string name;
1106 if (fieldIndex < fruAreaFieldNames->size())
1107 {
1108 name = std::string(getFruAreaName(area)) + "_" +
1109 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -08001110 }
1111 else
1112 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001113 name =
1114 std::string(getFruAreaName(area)) + "_" +
1115 FRU_CUSTOM_FIELD_NAME +
1116 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -08001117 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001118
1119 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001120 {
Ed Tanous2147e672019-02-27 13:59:56 -08001121 // Strip non null characters from the end
1122 value.erase(std::find_if(value.rbegin(), value.rend(),
1123 [](char ch) { return ch != 0; })
1124 .base(),
1125 value.end());
1126
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001127 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001128 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001129 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001130 else if (state == DecodeState::err)
1131 {
1132 std::cerr << "Error while parsing " << name << "\n";
1133 // Cancel decoding if failed to parse any of mandatory
1134 // fields
1135 if (fieldIndex < fruAreaFieldNames->size())
1136 {
1137 std::cerr << "Failed to parse mandatory field \n";
1138 return false;
1139 }
1140 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001141 else
1142 {
1143 if (fieldIndex < fruAreaFieldNames->size())
1144 {
1145 std::cerr << "Mandatory fields absent in FRU area "
1146 << getFruAreaName(area) << " after " << name
1147 << "\n";
1148 }
1149 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001150 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001151 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
1152 {
1153 uint8_t c = *fruBytesIter;
1154 if (c)
1155 {
1156 std::cerr << "Non-zero byte after EndOfFields in FRU area "
1157 << getFruAreaName(area) << "\n";
1158 break;
1159 }
1160 }
James Feist3cb5fec2018-01-23 14:41:51 -08001161 }
1162
1163 return true;
1164}
1165
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001166std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001167{
1168 auto deviceMap = busMap.find(bus);
1169 if (deviceMap == busMap.end())
1170 {
1171 throw std::invalid_argument("Invalid Bus.");
1172 }
1173 auto device = deviceMap->second->find(address);
1174 if (device == deviceMap->second->end())
1175 {
1176 throw std::invalid_argument("Invalid Address.");
1177 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001178 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001179
1180 return ret;
1181}
1182
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001183void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001184 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001185 boost::container::flat_map<
1186 std::pair<size_t, size_t>,
1187 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001188 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001189{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001190 boost::container::flat_map<std::string, std::string> formattedFRU;
1191 if (!formatFRU(device, formattedFRU))
James Feist3cb5fec2018-01-23 14:41:51 -08001192 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001193 std::cerr << "failed to format fru for device at bus " << bus
1194 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001195 return;
1196 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001197
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001198 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001199 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001200 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001201 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001202 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001203 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001204 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001205 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001206 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001207 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001208 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001209 {
1210 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001211 std::regex illegalObject("[^A-Za-z0-9_]");
1212 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001213 }
1214 else
1215 {
1216 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1217 UNKNOWN_BUS_OBJECT_COUNT++;
1218 }
1219
James Feist918e18c2018-02-13 15:51:07 -08001220 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001221 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001222 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001223 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001224 int highest = -1;
1225 bool found = false;
1226
James Feista465ccc2019-02-08 12:51:01 -08001227 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001228 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001229 std::string path = busIface.second->get_object_path();
1230 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001231 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001232 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001233 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001234 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001235 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001236 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001237 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001238 // This device is already added to the lower numbered bus,
1239 // do not replicate it.
1240 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001241 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001242
1243 // Check if the match named has extra information.
1244 found = true;
1245 std::smatch base_match;
1246
1247 bool match = std::regex_match(
1248 path, base_match, std::regex(productName + "_(\\d+)$"));
1249 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001250 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001251 if (base_match.size() == 2)
1252 {
1253 std::ssub_match base_sub_match = base_match[1];
1254 std::string base = base_sub_match.str();
1255
1256 int value = std::stoi(base);
1257 highest = (value > highest) ? value : highest;
1258 }
James Feist79e9c0b2018-03-15 15:21:17 -07001259 }
James Feist918e18c2018-02-13 15:51:07 -08001260 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001261 } // end searching objects
1262
1263 if (found)
1264 {
1265 // We found something with the same name. If highest was still -1,
1266 // it means this new entry will be _0.
1267 productName += "_";
1268 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001269 }
1270 }
James Feist3cb5fec2018-01-23 14:41:51 -08001271
James Feist9eb0b582018-04-27 12:15:46 -07001272 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1273 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1274 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1275
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001276 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001277 {
James Feist9eb0b582018-04-27 12:15:46 -07001278
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001279 std::regex_replace(property.second.begin(), property.second.begin(),
1280 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301281 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001282 {
1283 continue;
1284 }
1285 std::string key =
1286 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301287
1288 if (property.first == "PRODUCT_ASSET_TAG")
1289 {
1290 std::string propertyName = property.first;
1291 iface->register_property(
1292 key, property.second + '\0',
1293 [bus, address, propertyName,
1294 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1295 if (strcmp(req.c_str(), resp.c_str()))
1296 {
1297 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001298 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301299 dbusInterfaceMap))
1300 {
1301 resp = req;
1302 }
1303 else
1304 {
1305 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001306 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301307 }
1308 }
1309 return 1;
1310 });
1311 }
1312 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001313 {
1314 std::cerr << "illegal key: " << key << "\n";
1315 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001316 if (DEBUG)
1317 {
1318 std::cout << property.first << ": " << property.second << "\n";
1319 }
James Feist3cb5fec2018-01-23 14:41:51 -08001320 }
James Feist2a9d6db2018-04-27 15:48:28 -07001321
1322 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001323 iface->register_property("BUS", bus);
1324 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001325
James Feist9eb0b582018-04-27 12:15:46 -07001326 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001327}
1328
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001329static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001330{
1331 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001332 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1333 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001334 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001335 baseboardFRUFile.seekg(0, std::ios_base::end);
1336 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1337 baseboardFRU.resize(fileSize);
1338 baseboardFRUFile.seekg(0, std::ios_base::beg);
1339 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001340 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001341 }
1342 else
1343 {
1344 return false;
1345 }
1346 return true;
1347}
1348
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001349bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001350{
1351 boost::container::flat_map<std::string, std::string> tmp;
1352 if (fru.size() > MAX_FRU_SIZE)
1353 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001354 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001355 return false;
1356 }
1357 // verify legal fru by running it through fru parsing logic
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001358 if (!formatFRU(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001359 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001360 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001361 return false;
1362 }
1363 // baseboard fru
1364 if (bus == 0 && address == 0)
1365 {
1366 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1367 if (!file.good())
1368 {
1369 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1370 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001371 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001372 return false;
1373 }
James Feista465ccc2019-02-08 12:51:01 -08001374 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001375 return file.good();
1376 }
1377 else
1378 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001379 if (hasEepromFile(bus, address))
1380 {
1381 auto path = getEepromPath(bus, address);
1382 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1383 if (eeprom < 0)
1384 {
1385 std::cerr << "unable to open i2c device " << path << "\n";
1386 throw DBusInternalError();
1387 return false;
1388 }
1389
1390 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1391 if (writtenBytes < 0)
1392 {
1393 std::cerr << "unable to write to i2c device " << path << "\n";
1394 close(eeprom);
1395 throw DBusInternalError();
1396 return false;
1397 }
1398
1399 close(eeprom);
1400 return true;
1401 }
1402
James Feistb49ffc32018-05-02 11:10:43 -07001403 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1404
1405 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1406 if (file < 0)
1407 {
1408 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001409 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001410 return false;
1411 }
1412 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1413 {
1414 std::cerr << "unable to set device address\n";
1415 close(file);
James Feistddb78302018-09-06 11:45:42 -07001416 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001417 return false;
1418 }
1419
1420 constexpr const size_t RETRY_MAX = 2;
1421 uint16_t index = 0;
1422 size_t retries = RETRY_MAX;
1423 while (index < fru.size())
1424 {
1425 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1426 (retries == RETRY_MAX))
1427 {
1428 // The 4K EEPROM only uses the A2 and A1 device address bits
1429 // with the third bit being a memory page address bit.
1430 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1431 {
1432 std::cerr << "unable to set device address\n";
1433 close(file);
James Feistddb78302018-09-06 11:45:42 -07001434 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001435 return false;
1436 }
1437 }
1438
James Feist98132792019-07-09 13:29:09 -07001439 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1440 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001441 {
1442 if (!retries--)
1443 {
1444 std::cerr << "error writing fru: " << strerror(errno)
1445 << "\n";
1446 close(file);
James Feistddb78302018-09-06 11:45:42 -07001447 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001448 return false;
1449 }
1450 }
1451 else
1452 {
1453 retries = RETRY_MAX;
1454 index++;
1455 }
1456 // most eeproms require 5-10ms between writes
1457 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1458 }
1459 close(file);
1460 return true;
1461 }
1462}
1463
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001464void rescanOneBus(
1465 BusMap& busmap, uint8_t busNum,
1466 boost::container::flat_map<
1467 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001468 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1469 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001470{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001471 for (auto& [pair, interface] : foundDevices)
1472 {
1473 if (pair.first == static_cast<size_t>(busNum))
1474 {
1475 objServer.remove_interface(interface);
1476 foundDevices.erase(pair);
1477 }
1478 }
1479
James Feist5d7f4692020-06-17 18:22:33 -07001480 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1481 if (!fs::exists(busPath))
1482 {
1483 if (dbusCall)
1484 {
1485 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1486 << "\n";
1487 throw std::invalid_argument("Invalid Bus.");
1488 }
1489 return;
1490 }
1491
1492 std::vector<fs::path> i2cBuses;
1493 i2cBuses.emplace_back(busPath);
1494
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001495 auto scan = std::make_shared<FindDevicesWithCallback>(
1496 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1497 for (auto& busIface : dbusInterfaceMap)
1498 {
1499 if (busIface.first.first == static_cast<size_t>(busNum))
1500 {
1501 objServer.remove_interface(busIface.second);
1502 }
1503 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001504 auto found = busmap.find(busNum);
1505 if (found == busmap.end() || found->second == nullptr)
1506 {
1507 return;
1508 }
1509 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001510 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001511 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001512 static_cast<uint32_t>(busNum), device.first);
1513 }
1514 });
1515 scan->run();
1516}
1517
James Feist9eb0b582018-04-27 12:15:46 -07001518void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001519 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001520 boost::container::flat_map<
1521 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001522 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001523{
James Feist6ebf9de2018-05-15 15:01:17 -07001524 static boost::asio::deadline_timer timer(io);
1525 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001526
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001527 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001528 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001529 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001530 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001531
Nikhil Potaded8884f12019-03-27 13:27:13 -07001532 boost::container::flat_map<size_t, fs::path> busPaths;
1533 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001534 {
James Feist4131aea2018-03-09 09:47:30 -08001535 std::cerr << "unable to find i2c devices\n";
1536 return;
James Feist918e18c2018-02-13 15:51:07 -08001537 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001538
1539 for (auto busPath : busPaths)
1540 {
1541 i2cBuses.emplace_back(busPath.second);
1542 }
James Feist4131aea2018-03-09 09:47:30 -08001543
James Feist98132792019-07-09 13:29:09 -07001544 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001545 for (auto& [pair, interface] : foundDevices)
1546 {
1547 objServer.remove_interface(interface);
1548 }
1549 foundDevices.clear();
1550
James Feist5cb06082019-10-24 17:11:13 -07001551 auto scan =
1552 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001553 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001554 {
1555 objServer.remove_interface(busIface.second);
1556 }
James Feist4131aea2018-03-09 09:47:30 -08001557
James Feist6ebf9de2018-05-15 15:01:17 -07001558 dbusInterfaceMap.clear();
1559 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001560
James Feist6ebf9de2018-05-15 15:01:17 -07001561 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001562 std::vector<uint8_t> baseboardFRU;
1563 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001564 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001565 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001566 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001567 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001568 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001569 }
James Feist98132792019-07-09 13:29:09 -07001570 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001571 {
James Feista465ccc2019-02-08 12:51:01 -08001572 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001573 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001574 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001575 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001576 }
1577 }
1578 });
1579 scan->run();
1580 });
James Feist918e18c2018-02-13 15:51:07 -08001581}
1582
Joshi-Mansid73b7442020-03-27 19:10:21 +05301583// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001584uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1585 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301586{
1587 constexpr int checksumMod = 256;
1588 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001589 int sum = std::accumulate(iter, end, 0);
1590 int checksum = (checksumMod - sum) & modVal;
1591 return static_cast<uint8_t>(checksum);
1592}
1593uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1594{
1595 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301596}
1597
1598// Update new fru area length &
1599// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001600// Return the offset of the area checksum byte
1601static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1602 size_t fruAreaStart,
1603 size_t fruAreaEndOfFieldsOffset,
1604 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301605{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001606 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301607
1608 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001609 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1610 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301611
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001612 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301613 size_t checksumLoc;
1614 if (!mod)
1615 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001616 traverseFRUAreaIndex += (fruBlockSize);
1617 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301618 }
1619 else
1620 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001621 traverseFRUAreaIndex += (fruBlockSize - mod);
1622 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301623 }
1624
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001625 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1626 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1627 size_t fruAreaLengthLoc = fruAreaStart + 1;
1628 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301629
1630 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001631 std::vector<uint8_t> finalFRUData;
1632 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1633 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301634
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001635 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001636 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301637}
1638
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001639static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301640{
1641 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001642 constexpr uint8_t endOfFields = 0xC1;
1643 if (fruFieldTypeLenValue == endOfFields)
1644 {
1645 return -1;
1646 }
1647 else
1648 {
1649 return fruFieldTypeLenValue & typeLenMask;
1650 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301651}
1652
1653// Details with example of Asset Tag Update
1654// To find location of Product Info Area asset tag as per FRU specification
1655// 1. Find product Info area starting offset (*8 - as header will be in
1656// multiple of 8 bytes).
1657// 2. Skip 3 bytes of product info area (like format version, area length,
1658// and language code).
1659// 3. Traverse manufacturer name, product name, product version, & product
1660// serial number, by reading type/length code to reach the Asset Tag.
1661// 4. Update the Asset Tag, reposition the product Info area in multiple of
1662// 8 bytes. Update the Product area length and checksum.
1663
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001664bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301665 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1666 std::string propertyName,
1667 boost::container::flat_map<
1668 std::pair<size_t, size_t>,
1669 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1670{
1671 size_t updatePropertyReqLen = updatePropertyReq.length();
1672 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1673 {
1674 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001675 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301676 "Invalid Length "
1677 << updatePropertyReqLen << "\n";
1678 return false;
1679 }
1680
1681 std::vector<uint8_t> fruData;
1682 try
1683 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001684 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301685 static_cast<uint8_t>(address));
1686 }
1687 catch (std::invalid_argument& e)
1688 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001689 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301690 return false;
1691 }
1692
1693 if (fruData.empty())
1694 {
1695 return false;
1696 }
1697
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001698 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301699
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001700 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301701 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001702 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001703 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001704 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1705 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301706 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001707 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001708 << " \n";
1709 return false;
1710 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001711 fruAreas fruAreaToUpdate =
1712 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1713 fruAreaOffsetFieldValue =
1714 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1715 switch (fruAreaToUpdate)
1716 {
1717 case fruAreas::fruAreaChassis:
1718 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1719 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1720 break;
1721 case fruAreas::fruAreaBoard:
1722 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1723 fruAreaFieldNames = &BOARD_FRU_AREAS;
1724 break;
1725 case fruAreas::fruAreaProduct:
1726 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1727 // i.e. version, area length and language code
1728 offset = 3;
1729 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1730 break;
1731 default:
1732 std::cerr << "Don't know how to handle property " << propertyName
1733 << " \n";
1734 return false;
1735 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001736 if (fruAreaOffsetFieldValue == 0)
1737 {
1738 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301739 return false;
1740 }
1741
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001742 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001743 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1744 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001745 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001746 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001747 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001748 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301749
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001750 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001751 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301752 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001753 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001754 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301755 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001756 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301757 break;
1758 }
1759 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001760 if (!found)
1761 {
1762 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1763 if (pos == std::string::npos)
1764 {
1765 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1766 << propertyName << "\n";
1767 return false;
1768 }
1769 std::string fieldNumStr =
1770 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1771 size_t fieldNum = std::stoi(fieldNumStr);
1772 if (fieldNum == 0)
1773 {
1774 std::cerr << "PropertyName not recognized: " << propertyName
1775 << "\n";
1776 return false;
1777 }
1778 skipToFRUUpdateField += fieldNum;
1779 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301780
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001781 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301782 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001783 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001784 if (fieldLength < 0)
1785 {
1786 break;
1787 }
1788 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301789 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001790 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301791
1792 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001793 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001794 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301795 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001796 std::cerr << "Property " << propertyName << " not present \n";
1797 return false;
1798 }
1799 fruDataIter += 1 + fieldLength;
1800 size_t restFRUFieldsLoc = fruDataIter;
1801 size_t endOfFieldsLoc = 0;
1802 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1803 {
1804 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301805 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001806 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301807 break;
1808 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001809 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301810 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001811 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301812
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001813 std::vector<uint8_t> restFRUAreaFieldsData;
1814 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001815 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001816 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301817
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001818 // Push post update fru areas if any
1819 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001820 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1821 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001822 {
1823 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001824 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001825 if ((fruAreaLoc > endOfFieldsLoc) &&
1826 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1827 {
1828 nextFRUAreaLoc = fruAreaLoc;
1829 }
1830 }
1831 std::vector<uint8_t> restFRUAreasData;
1832 if (nextFRUAreaLoc)
1833 {
1834 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1835 fruData.size() - nextFRUAreaLoc,
1836 std::back_inserter(restFRUAreasData));
1837 }
1838
1839 // check FRU area size
1840 size_t fruAreaDataSize =
1841 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1842 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1843 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1844 {
1845
1846#ifdef ENABLE_FRU_AREA_RESIZE
1847 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1848 // round size to 8-byte blocks
1849 newFRUAreaSize =
1850 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1851 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1852 fruData.resize(newFRUDataSize);
1853 fruAreaSize = newFRUAreaSize;
1854 fruAreaEnd = fruAreaStart + fruAreaSize;
1855#else
1856 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1857 << " should not be greater than available FRU area size: "
1858 << fruAreaAvailableSize << "\n";
1859 return false;
1860#endif // ENABLE_FRU_AREA_RESIZE
1861 }
1862
Joshi-Mansid73b7442020-03-27 19:10:21 +05301863 // write new requested property field length and data
1864 constexpr uint8_t newTypeLenMask = 0xC0;
1865 fruData[fruUpdateFieldLoc] =
1866 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1867 fruUpdateFieldLoc++;
1868 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1869 fruData.begin() + fruUpdateFieldLoc);
1870
1871 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001872 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1873 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001874 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1875 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301876
1877 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001878 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1879 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301880
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001881#ifdef ENABLE_FRU_AREA_RESIZE
1882 ++nextFRUAreaNewLoc;
1883 ssize_t nextFRUAreaOffsetDiff =
1884 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1885 // Append rest FRU Areas if size changed and there were other sections after
1886 // updated one
1887 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1888 {
1889 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1890 fruData.begin() + nextFRUAreaNewLoc);
1891 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001892 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1893 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001894 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001895 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001896 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1897 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1898 {
1899 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1900 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1901 }
1902 }
1903 // Calculate new checksum
1904 std::vector<uint8_t> headerFRUData;
1905 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1906 size_t checksumVal = calculateChecksum(headerFRUData);
1907 fruData[7] = static_cast<uint8_t>(checksumVal);
1908 // fill zeros if FRU Area size decreased
1909 if (nextFRUAreaOffsetDiff < 0)
1910 {
1911 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1912 restFRUAreasData.size(),
1913 fruData.end(), 0);
1914 }
1915 }
1916#else
1917 // this is to avoid "unused variable" warning
1918 (void)nextFRUAreaNewLoc;
1919#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301920 if (fruData.empty())
1921 {
1922 return false;
1923 }
1924
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001925 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301926 fruData))
1927 {
1928 return false;
1929 }
1930
1931 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1932 rescanBusses(busMap, dbusInterfaceMap);
1933 return true;
1934}
1935
James Feist98132792019-07-09 13:29:09 -07001936int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001937{
1938 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001939 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001940 std::vector<fs::path> i2cBuses;
1941
James Feista3c180a2018-08-09 16:06:04 -07001942 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001943 {
1944 std::cerr << "unable to find i2c devices\n";
1945 return 1;
1946 }
James Feist3cb5fec2018-01-23 14:41:51 -08001947
Patrick Venture11f1ff42019-08-01 10:42:12 -07001948 // check for and load blacklist with initial buses.
1949 loadBlacklist(blacklistPath);
1950
Vijay Khemka065f6d92018-12-18 10:37:47 -08001951 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001952
James Feist6ebf9de2018-05-15 15:01:17 -07001953 // this is a map with keys of pair(bus number, address) and values of
1954 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001955 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001956 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1957 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001958
James Feist9eb0b582018-04-27 12:15:46 -07001959 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1960 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1961 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001962
James Feist5cb06082019-10-24 17:11:13 -07001963 iface->register_method("ReScan",
1964 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001965
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001966 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001967 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001968 });
1969
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001970 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001971
1972 iface->register_method("WriteFru", [&](const uint8_t bus,
1973 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001974 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001975 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001976 {
James Feistddb78302018-09-06 11:45:42 -07001977 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001978 return;
1979 }
1980 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001981 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001982 });
James Feist9eb0b582018-04-27 12:15:46 -07001983 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001984
James Feist9eb0b582018-04-27 12:15:46 -07001985 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001986 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001987 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001988 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001989 std::string,
1990 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001991 values;
1992 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001993 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001994 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001995 {
James Feistcb5661d2020-06-12 15:05:01 -07001996 powerIsOn = boost::ends_with(
1997 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001998 }
James Feist6ebf9de2018-05-15 15:01:17 -07001999
James Feistcb5661d2020-06-12 15:05:01 -07002000 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07002001 {
James Feist5cb06082019-10-24 17:11:13 -07002002 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08002003 }
James Feist918e18c2018-02-13 15:51:07 -08002004 };
James Feist9eb0b582018-04-27 12:15:46 -07002005
2006 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08002007 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07002008 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07002009 "openbmc_project/state/"
2010 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07002011 eventHandler);
2012
James Feist4131aea2018-03-09 09:47:30 -08002013 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07002014 inotify_add_watch(fd, I2C_DEV_LOCATION,
2015 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08002016 std::array<char, 4096> readBuffer;
2017 std::string pendingBuffer;
2018 // monitor for new i2c devices
2019 boost::asio::posix::stream_descriptor dirWatch(io, fd);
2020 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08002021 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08002022 std::size_t bytes_transferred) {
2023 if (ec)
2024 {
2025 std::cout << "Callback Error " << ec << "\n";
2026 return;
2027 }
2028 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08002029 while (pendingBuffer.size() > sizeof(inotify_event))
2030 {
James Feista465ccc2019-02-08 12:51:01 -08002031 const inotify_event* iEvent =
2032 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08002033 pendingBuffer.data());
2034 switch (iEvent->mask)
2035 {
James Feist9eb0b582018-04-27 12:15:46 -07002036 case IN_CREATE:
2037 case IN_MOVED_TO:
2038 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07002039 std::string name(iEvent->name);
2040 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07002041 {
James Feist5d7f4692020-06-17 18:22:33 -07002042 int bus = busStrToInt(name);
2043 if (bus < 0)
2044 {
2045 std::cerr << "Could not parse bus " << name
2046 << "\n";
2047 continue;
2048 }
2049 rescanOneBus(busMap, static_cast<uint8_t>(bus),
2050 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07002051 }
James Feist4131aea2018-03-09 09:47:30 -08002052 }
2053
2054 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
2055 }
James Feist6ebf9de2018-05-15 15:01:17 -07002056
James Feist4131aea2018-03-09 09:47:30 -08002057 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
2058 watchI2cBusses);
2059 };
2060
2061 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05002062 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07002063 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08002064
James Feist3cb5fec2018-01-23 14:41:51 -08002065 io.run();
2066 return 0;
2067}