blob: b92116e9bed10ef17ae19a5023480e57b677dcb1 [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 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300912 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800913 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 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300974 std::cerr << "Error: trying to parse empty FRU \n";
James Feist3cb5fec2018-01-23 14:41:51 -0800975 return false;
976 }
James Feist9eb0b582018-04-27 12:15:46 -0700977 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300978 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800979
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300980 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800981
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300982 // Don't parse Internal and Multirecord areas
983 for (fruAreas area = fruAreas::fruAreaChassis;
984 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800985 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300986
987 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
988 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800989 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300990 continue;
991 }
992 offset *= fruBlockSize;
993 std::vector<uint8_t>::const_iterator fruBytesIter =
994 fruBytes.begin() + offset;
995 if (fruBytesIter + fruBlockSize >= fruBytes.end())
996 {
997 std::cerr << "Not enough data to parse \n";
James Feist3cb5fec2018-01-23 14:41:51 -0800998 return false;
999 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001000 // check for format version 1
1001 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -08001002 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001003 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
1004 return false;
1005 }
1006 ++fruBytesIter;
1007 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
1008 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
1009 fruBytes.begin() + offset + fruAreaSize - 1;
1010 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001011
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001012 switch (area)
1013 {
1014 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -08001015 {
1016 result["CHASSIS_TYPE"] =
1017 std::to_string(static_cast<int>(*fruBytesIter));
1018 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001019 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001020 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001021 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001022 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -08001023 {
1024 result["BOARD_LANGUAGE_CODE"] =
1025 std::to_string(static_cast<int>(*fruBytesIter));
1026 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -08001027
1028 unsigned int minutes = *fruBytesIter |
1029 *(fruBytesIter + 1) << 8 |
1030 *(fruBytesIter + 2) << 16;
1031 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001032 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001033 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001034 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001035
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001036 // Tue Nov 20 23:08:00 2018
1037 char timeString[32] = {0};
1038 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001039 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001040 if (bytes == 0)
1041 {
1042 std::cerr << "invalid time string encountered\n";
1043 return false;
1044 }
1045
1046 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001047 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001048 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001049 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001050 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001051 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -08001052 {
1053 result["PRODUCT_LANGUAGE_CODE"] =
1054 std::to_string(static_cast<int>(*fruBytesIter));
1055 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001056 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001057 break;
1058 }
1059 default:
1060 {
1061 std::cerr << "Internal error: unexpected FRU area index: "
1062 << static_cast<int>(area) << " \n";
1063 return false;
1064 }
1065 }
1066 size_t fieldIndex = 0;
1067 DecodeState state;
1068 do
1069 {
1070 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea);
1071 state = res.first;
1072 std::string value = res.second;
1073 std::string name;
1074 if (fieldIndex < fruAreaFieldNames->size())
1075 {
1076 name = std::string(getFruAreaName(area)) + "_" +
1077 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -08001078 }
1079 else
1080 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001081 name =
1082 std::string(getFruAreaName(area)) + "_" +
1083 FRU_CUSTOM_FIELD_NAME +
1084 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -08001085 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001086
1087 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001088 {
Ed Tanous2147e672019-02-27 13:59:56 -08001089 // Strip non null characters from the end
1090 value.erase(std::find_if(value.rbegin(), value.rend(),
1091 [](char ch) { return ch != 0; })
1092 .base(),
1093 value.end());
1094
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001095 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001096 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001097 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001098 else if (state == DecodeState::err)
1099 {
1100 std::cerr << "Error while parsing " << name << "\n";
1101 // Cancel decoding if failed to parse any of mandatory
1102 // fields
1103 if (fieldIndex < fruAreaFieldNames->size())
1104 {
1105 std::cerr << "Failed to parse mandatory field \n";
1106 return false;
1107 }
1108 }
1109 } while (state == DecodeState::ok);
James Feist3cb5fec2018-01-23 14:41:51 -08001110 }
1111
1112 return true;
1113}
1114
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001115std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001116{
1117 auto deviceMap = busMap.find(bus);
1118 if (deviceMap == busMap.end())
1119 {
1120 throw std::invalid_argument("Invalid Bus.");
1121 }
1122 auto device = deviceMap->second->find(address);
1123 if (device == deviceMap->second->end())
1124 {
1125 throw std::invalid_argument("Invalid Address.");
1126 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001127 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001128
1129 return ret;
1130}
1131
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001132void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001133 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001134 boost::container::flat_map<
1135 std::pair<size_t, size_t>,
1136 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001137 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001138{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001139 boost::container::flat_map<std::string, std::string> formattedFRU;
1140 if (!formatFRU(device, formattedFRU))
James Feist3cb5fec2018-01-23 14:41:51 -08001141 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001142 std::cerr << "failed to format fru for device at bus " << bus
1143 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001144 return;
1145 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001146
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001147 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001148 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001149 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001150 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001151 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001152 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001153 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001154 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001155 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001156 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001157 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001158 {
1159 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001160 std::regex illegalObject("[^A-Za-z0-9_]");
1161 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001162 }
1163 else
1164 {
1165 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1166 UNKNOWN_BUS_OBJECT_COUNT++;
1167 }
1168
James Feist918e18c2018-02-13 15:51:07 -08001169 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001170 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001171 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001172 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001173 int highest = -1;
1174 bool found = false;
1175
James Feista465ccc2019-02-08 12:51:01 -08001176 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001177 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001178 std::string path = busIface.second->get_object_path();
1179 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001180 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001181 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001182 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001183 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001184 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001185 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001186 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001187 // This device is already added to the lower numbered bus,
1188 // do not replicate it.
1189 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001190 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001191
1192 // Check if the match named has extra information.
1193 found = true;
1194 std::smatch base_match;
1195
1196 bool match = std::regex_match(
1197 path, base_match, std::regex(productName + "_(\\d+)$"));
1198 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001199 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001200 if (base_match.size() == 2)
1201 {
1202 std::ssub_match base_sub_match = base_match[1];
1203 std::string base = base_sub_match.str();
1204
1205 int value = std::stoi(base);
1206 highest = (value > highest) ? value : highest;
1207 }
James Feist79e9c0b2018-03-15 15:21:17 -07001208 }
James Feist918e18c2018-02-13 15:51:07 -08001209 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001210 } // end searching objects
1211
1212 if (found)
1213 {
1214 // We found something with the same name. If highest was still -1,
1215 // it means this new entry will be _0.
1216 productName += "_";
1217 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001218 }
1219 }
James Feist3cb5fec2018-01-23 14:41:51 -08001220
James Feist9eb0b582018-04-27 12:15:46 -07001221 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1222 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1223 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1224
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001225 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001226 {
James Feist9eb0b582018-04-27 12:15:46 -07001227
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001228 std::regex_replace(property.second.begin(), property.second.begin(),
1229 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301230 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001231 {
1232 continue;
1233 }
1234 std::string key =
1235 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301236
1237 if (property.first == "PRODUCT_ASSET_TAG")
1238 {
1239 std::string propertyName = property.first;
1240 iface->register_property(
1241 key, property.second + '\0',
1242 [bus, address, propertyName,
1243 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1244 if (strcmp(req.c_str(), resp.c_str()))
1245 {
1246 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001247 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301248 dbusInterfaceMap))
1249 {
1250 resp = req;
1251 }
1252 else
1253 {
1254 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001255 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301256 }
1257 }
1258 return 1;
1259 });
1260 }
1261 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001262 {
1263 std::cerr << "illegal key: " << key << "\n";
1264 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001265 if (DEBUG)
1266 {
1267 std::cout << property.first << ": " << property.second << "\n";
1268 }
James Feist3cb5fec2018-01-23 14:41:51 -08001269 }
James Feist2a9d6db2018-04-27 15:48:28 -07001270
1271 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001272 iface->register_property("BUS", bus);
1273 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001274
James Feist9eb0b582018-04-27 12:15:46 -07001275 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001276}
1277
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001278static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001279{
1280 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001281 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1282 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001283 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001284 baseboardFRUFile.seekg(0, std::ios_base::end);
1285 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1286 baseboardFRU.resize(fileSize);
1287 baseboardFRUFile.seekg(0, std::ios_base::beg);
1288 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001289 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001290 }
1291 else
1292 {
1293 return false;
1294 }
1295 return true;
1296}
1297
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001298bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001299{
1300 boost::container::flat_map<std::string, std::string> tmp;
1301 if (fru.size() > MAX_FRU_SIZE)
1302 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001303 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001304 return false;
1305 }
1306 // verify legal fru by running it through fru parsing logic
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001307 if (!formatFRU(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001308 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001309 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001310 return false;
1311 }
1312 // baseboard fru
1313 if (bus == 0 && address == 0)
1314 {
1315 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1316 if (!file.good())
1317 {
1318 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1319 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001320 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001321 return false;
1322 }
James Feista465ccc2019-02-08 12:51:01 -08001323 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001324 return file.good();
1325 }
1326 else
1327 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001328 if (hasEepromFile(bus, address))
1329 {
1330 auto path = getEepromPath(bus, address);
1331 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1332 if (eeprom < 0)
1333 {
1334 std::cerr << "unable to open i2c device " << path << "\n";
1335 throw DBusInternalError();
1336 return false;
1337 }
1338
1339 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1340 if (writtenBytes < 0)
1341 {
1342 std::cerr << "unable to write to i2c device " << path << "\n";
1343 close(eeprom);
1344 throw DBusInternalError();
1345 return false;
1346 }
1347
1348 close(eeprom);
1349 return true;
1350 }
1351
James Feistb49ffc32018-05-02 11:10:43 -07001352 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1353
1354 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1355 if (file < 0)
1356 {
1357 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001358 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001359 return false;
1360 }
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 constexpr const size_t RETRY_MAX = 2;
1370 uint16_t index = 0;
1371 size_t retries = RETRY_MAX;
1372 while (index < fru.size())
1373 {
1374 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1375 (retries == RETRY_MAX))
1376 {
1377 // The 4K EEPROM only uses the A2 and A1 device address bits
1378 // with the third bit being a memory page address bit.
1379 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1380 {
1381 std::cerr << "unable to set device address\n";
1382 close(file);
James Feistddb78302018-09-06 11:45:42 -07001383 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001384 return false;
1385 }
1386 }
1387
James Feist98132792019-07-09 13:29:09 -07001388 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1389 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001390 {
1391 if (!retries--)
1392 {
1393 std::cerr << "error writing fru: " << strerror(errno)
1394 << "\n";
1395 close(file);
James Feistddb78302018-09-06 11:45:42 -07001396 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001397 return false;
1398 }
1399 }
1400 else
1401 {
1402 retries = RETRY_MAX;
1403 index++;
1404 }
1405 // most eeproms require 5-10ms between writes
1406 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1407 }
1408 close(file);
1409 return true;
1410 }
1411}
1412
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001413void rescanOneBus(
1414 BusMap& busmap, uint8_t busNum,
1415 boost::container::flat_map<
1416 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001417 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1418 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001419{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001420 for (auto& [pair, interface] : foundDevices)
1421 {
1422 if (pair.first == static_cast<size_t>(busNum))
1423 {
1424 objServer.remove_interface(interface);
1425 foundDevices.erase(pair);
1426 }
1427 }
1428
James Feist5d7f4692020-06-17 18:22:33 -07001429 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1430 if (!fs::exists(busPath))
1431 {
1432 if (dbusCall)
1433 {
1434 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1435 << "\n";
1436 throw std::invalid_argument("Invalid Bus.");
1437 }
1438 return;
1439 }
1440
1441 std::vector<fs::path> i2cBuses;
1442 i2cBuses.emplace_back(busPath);
1443
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001444 auto scan = std::make_shared<FindDevicesWithCallback>(
1445 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1446 for (auto& busIface : dbusInterfaceMap)
1447 {
1448 if (busIface.first.first == static_cast<size_t>(busNum))
1449 {
1450 objServer.remove_interface(busIface.second);
1451 }
1452 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001453 auto found = busmap.find(busNum);
1454 if (found == busmap.end() || found->second == nullptr)
1455 {
1456 return;
1457 }
1458 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001459 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001460 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001461 static_cast<uint32_t>(busNum), device.first);
1462 }
1463 });
1464 scan->run();
1465}
1466
James Feist9eb0b582018-04-27 12:15:46 -07001467void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001468 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001469 boost::container::flat_map<
1470 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001471 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001472{
James Feist6ebf9de2018-05-15 15:01:17 -07001473 static boost::asio::deadline_timer timer(io);
1474 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001475
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001476 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001477 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001478 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001479 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001480
Nikhil Potaded8884f12019-03-27 13:27:13 -07001481 boost::container::flat_map<size_t, fs::path> busPaths;
1482 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001483 {
James Feist4131aea2018-03-09 09:47:30 -08001484 std::cerr << "unable to find i2c devices\n";
1485 return;
James Feist918e18c2018-02-13 15:51:07 -08001486 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001487
1488 for (auto busPath : busPaths)
1489 {
1490 i2cBuses.emplace_back(busPath.second);
1491 }
James Feist4131aea2018-03-09 09:47:30 -08001492
James Feist98132792019-07-09 13:29:09 -07001493 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001494 for (auto& [pair, interface] : foundDevices)
1495 {
1496 objServer.remove_interface(interface);
1497 }
1498 foundDevices.clear();
1499
James Feist5cb06082019-10-24 17:11:13 -07001500 auto scan =
1501 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001502 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001503 {
1504 objServer.remove_interface(busIface.second);
1505 }
James Feist4131aea2018-03-09 09:47:30 -08001506
James Feist6ebf9de2018-05-15 15:01:17 -07001507 dbusInterfaceMap.clear();
1508 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001509
James Feist6ebf9de2018-05-15 15:01:17 -07001510 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001511 std::vector<uint8_t> baseboardFRU;
1512 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001513 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001514 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001515 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001516 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001517 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001518 }
James Feist98132792019-07-09 13:29:09 -07001519 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001520 {
James Feista465ccc2019-02-08 12:51:01 -08001521 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001522 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001523 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001524 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001525 }
1526 }
1527 });
1528 scan->run();
1529 });
James Feist918e18c2018-02-13 15:51:07 -08001530}
1531
Joshi-Mansid73b7442020-03-27 19:10:21 +05301532// Calculate new checksum for fru info area
1533size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1534{
1535 constexpr int checksumMod = 256;
1536 constexpr uint8_t modVal = 0xFF;
1537 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1538 return (checksumMod - sum) & modVal;
1539}
1540
1541// Update new fru area length &
1542// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001543// Return the offset of the area checksum byte
1544static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1545 size_t fruAreaStart,
1546 size_t fruAreaEndOfFieldsOffset,
1547 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301548{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001549 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301550
1551 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001552 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1553 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301554
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001555 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301556 size_t checksumLoc;
1557 if (!mod)
1558 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001559 traverseFRUAreaIndex += (fruBlockSize);
1560 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301561 }
1562 else
1563 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001564 traverseFRUAreaIndex += (fruBlockSize - mod);
1565 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301566 }
1567
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001568 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1569 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1570 size_t fruAreaLengthLoc = fruAreaStart + 1;
1571 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301572
1573 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001574 std::vector<uint8_t> finalFRUData;
1575 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1576 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301577
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001578 size_t checksumVal = calculateChecksum(finalFRUData);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301579
1580 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001581 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301582}
1583
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001584static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301585{
1586 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001587 constexpr uint8_t endOfFields = 0xC1;
1588 if (fruFieldTypeLenValue == endOfFields)
1589 {
1590 return -1;
1591 }
1592 else
1593 {
1594 return fruFieldTypeLenValue & typeLenMask;
1595 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301596}
1597
1598// Details with example of Asset Tag Update
1599// To find location of Product Info Area asset tag as per FRU specification
1600// 1. Find product Info area starting offset (*8 - as header will be in
1601// multiple of 8 bytes).
1602// 2. Skip 3 bytes of product info area (like format version, area length,
1603// and language code).
1604// 3. Traverse manufacturer name, product name, product version, & product
1605// serial number, by reading type/length code to reach the Asset Tag.
1606// 4. Update the Asset Tag, reposition the product Info area in multiple of
1607// 8 bytes. Update the Product area length and checksum.
1608
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001609bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301610 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1611 std::string propertyName,
1612 boost::container::flat_map<
1613 std::pair<size_t, size_t>,
1614 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1615{
1616 size_t updatePropertyReqLen = updatePropertyReq.length();
1617 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1618 {
1619 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001620 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301621 "Invalid Length "
1622 << updatePropertyReqLen << "\n";
1623 return false;
1624 }
1625
1626 std::vector<uint8_t> fruData;
1627 try
1628 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001629 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301630 static_cast<uint8_t>(address));
1631 }
1632 catch (std::invalid_argument& e)
1633 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001634 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301635 return false;
1636 }
1637
1638 if (fruData.empty())
1639 {
1640 return false;
1641 }
1642
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001643 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301644
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001645 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301646 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001647 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001648 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001649 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1650 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301651 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001652 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001653 << " \n";
1654 return false;
1655 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001656 fruAreas fruAreaToUpdate =
1657 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1658 fruAreaOffsetFieldValue =
1659 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1660 switch (fruAreaToUpdate)
1661 {
1662 case fruAreas::fruAreaChassis:
1663 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1664 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1665 break;
1666 case fruAreas::fruAreaBoard:
1667 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1668 fruAreaFieldNames = &BOARD_FRU_AREAS;
1669 break;
1670 case fruAreas::fruAreaProduct:
1671 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1672 // i.e. version, area length and language code
1673 offset = 3;
1674 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1675 break;
1676 default:
1677 std::cerr << "Don't know how to handle property " << propertyName
1678 << " \n";
1679 return false;
1680 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001681 if (fruAreaOffsetFieldValue == 0)
1682 {
1683 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301684 return false;
1685 }
1686
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001687 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001688 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1689 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001690 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001691 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001692 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001693 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301694
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001695 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001696 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301697 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001698 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001699 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301700 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001701 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301702 break;
1703 }
1704 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001705 if (!found)
1706 {
1707 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1708 if (pos == std::string::npos)
1709 {
1710 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1711 << propertyName << "\n";
1712 return false;
1713 }
1714 std::string fieldNumStr =
1715 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1716 size_t fieldNum = std::stoi(fieldNumStr);
1717 if (fieldNum == 0)
1718 {
1719 std::cerr << "PropertyName not recognized: " << propertyName
1720 << "\n";
1721 return false;
1722 }
1723 skipToFRUUpdateField += fieldNum;
1724 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301725
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001726 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301727 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001728 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001729 if (fieldLength < 0)
1730 {
1731 break;
1732 }
1733 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301734 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001735 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301736
1737 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001738 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001739 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301740 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001741 std::cerr << "Property " << propertyName << " not present \n";
1742 return false;
1743 }
1744 fruDataIter += 1 + fieldLength;
1745 size_t restFRUFieldsLoc = fruDataIter;
1746 size_t endOfFieldsLoc = 0;
1747 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1748 {
1749 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301750 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001751 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301752 break;
1753 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001754 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301755 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001756 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301757
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001758 std::vector<uint8_t> restFRUAreaFieldsData;
1759 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001760 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001761 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301762
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001763 // Push post update fru areas if any
1764 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001765 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1766 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001767 {
1768 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001769 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001770 if ((fruAreaLoc > endOfFieldsLoc) &&
1771 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1772 {
1773 nextFRUAreaLoc = fruAreaLoc;
1774 }
1775 }
1776 std::vector<uint8_t> restFRUAreasData;
1777 if (nextFRUAreaLoc)
1778 {
1779 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1780 fruData.size() - nextFRUAreaLoc,
1781 std::back_inserter(restFRUAreasData));
1782 }
1783
1784 // check FRU area size
1785 size_t fruAreaDataSize =
1786 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1787 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1788 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1789 {
1790
1791#ifdef ENABLE_FRU_AREA_RESIZE
1792 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1793 // round size to 8-byte blocks
1794 newFRUAreaSize =
1795 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1796 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1797 fruData.resize(newFRUDataSize);
1798 fruAreaSize = newFRUAreaSize;
1799 fruAreaEnd = fruAreaStart + fruAreaSize;
1800#else
1801 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1802 << " should not be greater than available FRU area size: "
1803 << fruAreaAvailableSize << "\n";
1804 return false;
1805#endif // ENABLE_FRU_AREA_RESIZE
1806 }
1807
Joshi-Mansid73b7442020-03-27 19:10:21 +05301808 // write new requested property field length and data
1809 constexpr uint8_t newTypeLenMask = 0xC0;
1810 fruData[fruUpdateFieldLoc] =
1811 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1812 fruUpdateFieldLoc++;
1813 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1814 fruData.begin() + fruUpdateFieldLoc);
1815
1816 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001817 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1818 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001819 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1820 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301821
1822 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001823 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1824 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301825
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001826#ifdef ENABLE_FRU_AREA_RESIZE
1827 ++nextFRUAreaNewLoc;
1828 ssize_t nextFRUAreaOffsetDiff =
1829 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1830 // Append rest FRU Areas if size changed and there were other sections after
1831 // updated one
1832 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1833 {
1834 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1835 fruData.begin() + nextFRUAreaNewLoc);
1836 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001837 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1838 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001839 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001840 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001841 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1842 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1843 {
1844 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1845 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1846 }
1847 }
1848 // Calculate new checksum
1849 std::vector<uint8_t> headerFRUData;
1850 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1851 size_t checksumVal = calculateChecksum(headerFRUData);
1852 fruData[7] = static_cast<uint8_t>(checksumVal);
1853 // fill zeros if FRU Area size decreased
1854 if (nextFRUAreaOffsetDiff < 0)
1855 {
1856 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1857 restFRUAreasData.size(),
1858 fruData.end(), 0);
1859 }
1860 }
1861#else
1862 // this is to avoid "unused variable" warning
1863 (void)nextFRUAreaNewLoc;
1864#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301865 if (fruData.empty())
1866 {
1867 return false;
1868 }
1869
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001870 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301871 fruData))
1872 {
1873 return false;
1874 }
1875
1876 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1877 rescanBusses(busMap, dbusInterfaceMap);
1878 return true;
1879}
1880
James Feist98132792019-07-09 13:29:09 -07001881int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001882{
1883 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001884 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001885 std::vector<fs::path> i2cBuses;
1886
James Feista3c180a2018-08-09 16:06:04 -07001887 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001888 {
1889 std::cerr << "unable to find i2c devices\n";
1890 return 1;
1891 }
James Feist3cb5fec2018-01-23 14:41:51 -08001892
Patrick Venture11f1ff42019-08-01 10:42:12 -07001893 // check for and load blacklist with initial buses.
1894 loadBlacklist(blacklistPath);
1895
Vijay Khemka065f6d92018-12-18 10:37:47 -08001896 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001897
James Feist6ebf9de2018-05-15 15:01:17 -07001898 // this is a map with keys of pair(bus number, address) and values of
1899 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001900 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001901 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1902 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001903
James Feist9eb0b582018-04-27 12:15:46 -07001904 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1905 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1906 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001907
James Feist5cb06082019-10-24 17:11:13 -07001908 iface->register_method("ReScan",
1909 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001910
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001911 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001912 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001913 });
1914
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001915 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001916
1917 iface->register_method("WriteFru", [&](const uint8_t bus,
1918 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001919 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001920 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001921 {
James Feistddb78302018-09-06 11:45:42 -07001922 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001923 return;
1924 }
1925 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001926 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001927 });
James Feist9eb0b582018-04-27 12:15:46 -07001928 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001929
James Feist9eb0b582018-04-27 12:15:46 -07001930 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001931 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001932 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001933 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001934 std::string,
1935 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001936 values;
1937 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001938 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001939 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001940 {
James Feistcb5661d2020-06-12 15:05:01 -07001941 powerIsOn = boost::ends_with(
1942 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001943 }
James Feist6ebf9de2018-05-15 15:01:17 -07001944
James Feistcb5661d2020-06-12 15:05:01 -07001945 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001946 {
James Feist5cb06082019-10-24 17:11:13 -07001947 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001948 }
James Feist918e18c2018-02-13 15:51:07 -08001949 };
James Feist9eb0b582018-04-27 12:15:46 -07001950
1951 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001952 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001953 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001954 "openbmc_project/state/"
1955 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001956 eventHandler);
1957
James Feist4131aea2018-03-09 09:47:30 -08001958 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001959 inotify_add_watch(fd, I2C_DEV_LOCATION,
1960 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001961 std::array<char, 4096> readBuffer;
1962 std::string pendingBuffer;
1963 // monitor for new i2c devices
1964 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1965 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001966 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001967 std::size_t bytes_transferred) {
1968 if (ec)
1969 {
1970 std::cout << "Callback Error " << ec << "\n";
1971 return;
1972 }
1973 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001974 while (pendingBuffer.size() > sizeof(inotify_event))
1975 {
James Feista465ccc2019-02-08 12:51:01 -08001976 const inotify_event* iEvent =
1977 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001978 pendingBuffer.data());
1979 switch (iEvent->mask)
1980 {
James Feist9eb0b582018-04-27 12:15:46 -07001981 case IN_CREATE:
1982 case IN_MOVED_TO:
1983 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001984 std::string name(iEvent->name);
1985 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001986 {
James Feist5d7f4692020-06-17 18:22:33 -07001987 int bus = busStrToInt(name);
1988 if (bus < 0)
1989 {
1990 std::cerr << "Could not parse bus " << name
1991 << "\n";
1992 continue;
1993 }
1994 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1995 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001996 }
James Feist4131aea2018-03-09 09:47:30 -08001997 }
1998
1999 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
2000 }
James Feist6ebf9de2018-05-15 15:01:17 -07002001
James Feist4131aea2018-03-09 09:47:30 -08002002 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
2003 watchI2cBusses);
2004 };
2005
2006 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05002007 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07002008 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08002009
James Feist3cb5fec2018-01-23 14:41:51 -08002010 io.run();
2011 return 0;
2012}