blob: 010ee2668f538692e4ee0091c88ea05115137d2a [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 Kartashev2f0de172020-08-13 14:29:40 +0300110static const std::vector<std::string> CHASSIS_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530111 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
112
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300113static const std::vector<std::string> BOARD_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530114 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
115 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
116
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300117static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530118 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION", "SERIAL_NUMBER",
119 "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
120
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300121static inline unsigned int getHeaderAreaFieldOffset(fruAreas area)
122{
123 return static_cast<unsigned int>(area) + 1;
124}
125static inline const std::string& getFruAreaName(fruAreas area)
126{
127 return FRU_AREA_NAMES[static_cast<unsigned int>(area)];
128}
Patrick Venturebaba7672019-10-26 09:26:41 -0700129bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300130bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530131 const std::string& assetTag, uint32_t bus, uint32_t address,
132 std::string propertyName,
133 boost::container::flat_map<
134 std::pair<size_t, size_t>,
135 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700136
Xiang Liu2801a702020-01-20 14:29:34 -0800137using ReadBlockFunc =
138 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
139 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700140
141// Read and validate FRU contents, given the flag required for raw i2c, the open
142// file handle, a read method, and a helper string for failures.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300143std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300144 ReadBlockFunc readBlock,
145 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700146{
147 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
148
Xiang Liu2801a702020-01-20 14:29:34 -0800149 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700150 {
151 std::cerr << "failed to read " << errorHelp << "\n";
152 return {};
153 }
154
155 // check the header checksum
156 if (!validateHeader(blockData))
157 {
158 if (DEBUG)
159 {
160 std::cerr << "Illegal header " << errorHelp << "\n";
161 }
162
163 return {};
164 }
165
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300166 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700167 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
168
Patrick Venturee26395d2019-10-29 14:05:16 -0700169 bool hasMultiRecords = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300170 ssize_t fruLength = fruBlockSize; // At least FRU header is present
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300171 for (fruAreas area = fruAreas::fruAreaInternal;
172 area <= fruAreas::fruAreaMultirecord; ++area)
Patrick Venturebaba7672019-10-26 09:26:41 -0700173 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700174 // Offset value can be 255.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300175 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
Patrick Venturebaba7672019-10-26 09:26:41 -0700176 if (areaOffset == 0)
177 {
178 continue;
179 }
180
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300181 // MultiRecords are different. area is not tracking section, it's
182 // walking the common header.
183 if (area == fruAreas::fruAreaMultirecord)
Patrick Venturee26395d2019-10-29 14:05:16 -0700184 {
185 hasMultiRecords = true;
186 break;
187 }
188
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300189 areaOffset *= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700190
Xiang Liu2801a702020-01-20 14:29:34 -0800191 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
192 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700193 {
194 std::cerr << "failed to read " << errorHelp << "\n";
195 return {};
196 }
197
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700198 // Ignore data type (blockData is already unsigned).
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300199 size_t length = blockData[1] * fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700200 areaOffset += length;
201 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
202 }
203
Patrick Venturee26395d2019-10-29 14:05:16 -0700204 if (hasMultiRecords)
205 {
206 // device[area count] is the index to the last area because the 0th
207 // entry is not an offset in the common header.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300208 unsigned int areaOffset =
209 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300210 areaOffset *= fruBlockSize;
Patrick Venturee26395d2019-10-29 14:05:16 -0700211
212 // the multi-area record header is 5 bytes long.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300213 constexpr size_t multiRecordHeaderSize = 5;
214 constexpr uint8_t multiRecordEndOfListMask = 0x80;
Patrick Venturee26395d2019-10-29 14:05:16 -0700215
216 // Sanity hard-limit to 64KB.
217 while (areaOffset < std::numeric_limits<uint16_t>::max())
218 {
219 // In multi-area, the area offset points to the 0th record, each
220 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800221 if (readBlock(flag, file, address,
222 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700223 blockData.data()) < 0)
224 {
225 std::cerr << "failed to read " << errorHelp << "\n";
226 return {};
227 }
228
229 // Ok, let's check the record length, which is in bytes (unsigned,
230 // up to 255, so blockData should hold uint8_t not char)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300231 size_t recordLength = blockData[2];
Patrick Venturee26395d2019-10-29 14:05:16 -0700232 areaOffset += (recordLength + multiRecordHeaderSize);
233 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
234
235 // If this is the end of the list bail.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300236 if ((blockData[1] & multiRecordEndOfListMask))
Patrick Venturee26395d2019-10-29 14:05:16 -0700237 {
238 break;
239 }
240 }
241 }
242
Patrick Venturebaba7672019-10-26 09:26:41 -0700243 // You already copied these first 8 bytes (the ipmi fru header size)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300244 fruLength -= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700245
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300246 int readOffset = fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700247
248 while (fruLength > 0)
249 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300250 int requestLength =
251 std::min(I2C_SMBUS_BLOCK_MAX, static_cast<int>(fruLength));
Patrick Venturebaba7672019-10-26 09:26:41 -0700252
Xiang Liu2801a702020-01-20 14:29:34 -0800253 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700254 static_cast<uint8_t>(requestLength),
255 blockData.data()) < 0)
256 {
257 std::cerr << "failed to read " << errorHelp << "\n";
258 return {};
259 }
260
261 device.insert(device.end(), blockData.begin(),
262 blockData.begin() + requestLength);
263
264 readOffset += requestLength;
265 fruLength -= requestLength;
266 }
267
268 return device;
269}
270
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700271// Given a bus/address, produce the path in sysfs for an eeprom.
272static std::string getEepromPath(size_t bus, size_t address)
273{
274 std::stringstream output;
275 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
276 << std::setfill('0') << std::setw(4) << std::hex << address
277 << "/eeprom";
278 return output.str();
279}
280
281static bool hasEepromFile(size_t bus, size_t address)
282{
283 auto path = getEepromPath(bus, address);
284 try
285 {
286 return fs::exists(path);
287 }
288 catch (...)
289 {
290 return false;
291 }
292}
293
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700294static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800295 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700296 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700297{
298 auto result = lseek(fd, offset, SEEK_SET);
299 if (result < 0)
300 {
301 std::cerr << "failed to seek\n";
302 return -1;
303 }
304
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700305 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700306}
307
James Feist5d7f4692020-06-17 18:22:33 -0700308static int busStrToInt(const std::string& busName)
309{
310 auto findBus = busName.rfind("-");
311 if (findBus == std::string::npos)
312 {
313 return -1;
314 }
315 return std::stoi(busName.substr(findBus + 1));
316}
317
James Feist7972bb92019-11-13 15:59:24 -0800318static int getRootBus(size_t bus)
319{
320 auto ec = std::error_code();
321 auto path = std::filesystem::read_symlink(
322 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
323 std::to_string(bus) + "/mux_device"),
324 ec);
325 if (ec)
326 {
327 return -1;
328 }
329
330 std::string filename = path.filename();
331 auto findBus = filename.find("-");
332 if (findBus == std::string::npos)
333 {
334 return -1;
335 }
336 return std::stoi(filename.substr(0, findBus));
337}
338
James Feistc95cb142018-02-26 10:41:42 -0800339static bool isMuxBus(size_t bus)
340{
Ed Tanous072e25d2018-12-16 21:45:20 -0800341 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800342 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
343}
344
James Feist8a983922019-10-24 17:11:56 -0700345static void makeProbeInterface(size_t bus, size_t address)
346{
347 if (isMuxBus(bus))
348 {
349 return; // the mux buses are random, no need to publish
350 }
351 auto [it, success] = foundDevices.emplace(
352 std::make_pair(bus, address),
353 objServer.add_interface(
354 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
355 std::to_string(address),
356 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
357 if (!success)
358 {
359 return; // already added
360 }
361 it->second->register_property("Bus", bus);
362 it->second->register_property("Address", address);
363 it->second->initialize();
364}
365
Vijay Khemka2d681f62018-11-06 15:51:00 -0800366static int isDevice16Bit(int file)
367{
368 /* Get first byte */
369 int byte1 = i2c_smbus_read_byte_data(file, 0);
370 if (byte1 < 0)
371 {
372 return byte1;
373 }
374 /* Read 7 more bytes, it will read same first byte in case of
375 * 8 bit but it will read next byte in case of 16 bit
376 */
377 for (int i = 0; i < 7; i++)
378 {
379 int byte2 = i2c_smbus_read_byte_data(file, 0);
380 if (byte2 < 0)
381 {
382 return byte2;
383 }
384 if (byte2 != byte1)
385 {
386 return 1;
387 }
388 }
389 return 0;
390}
391
Xiang Liu2801a702020-01-20 14:29:34 -0800392// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
393// from_slave_buf_len bytes.
394static int i2c_smbus_write_then_read(int file, uint16_t address,
395 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
396 uint8_t* fromSlaveBuf,
397 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800398{
Xiang Liu2801a702020-01-20 14:29:34 -0800399 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
400 fromSlaveBufLen == 0)
401 {
402 return -1;
403 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800404
Xiang Liu2801a702020-01-20 14:29:34 -0800405#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
406 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
407 struct i2c_rdwr_ioctl_data rdwr;
408
409 msgs[0].addr = address;
410 msgs[0].flags = 0;
411 msgs[0].len = toSlaveBufLen;
412 msgs[0].buf = toSlaveBuf;
413 msgs[1].addr = address;
414 msgs[1].flags = I2C_M_RD;
415 msgs[1].len = fromSlaveBufLen;
416 msgs[1].buf = fromSlaveBuf;
417
418 rdwr.msgs = msgs;
419 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
420
421 int ret = ioctl(file, I2C_RDWR, &rdwr);
422
423 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
424}
425
426static int64_t readBlockData(int flag, int file, uint16_t address,
427 uint16_t offset, uint8_t len, uint8_t* buf)
428{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800429 if (flag == 0)
430 {
Xiang Liu2801a702020-01-20 14:29:34 -0800431 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
432 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800433 }
434
Xiang Liu2801a702020-01-20 14:29:34 -0800435 offset = htobe16(offset);
436 return i2c_smbus_write_then_read(
437 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800438}
439
James Feist24bae7a2019-04-03 09:50:56 -0700440bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
441{
442 // ipmi spec format version number is currently at 1, verify it
443 if (blockData[0] != 0x1)
444 {
445 return false;
446 }
447
448 // verify pad is set to 0
449 if (blockData[6] != 0x0)
450 {
451 return false;
452 }
453
454 // verify offsets are 0, or don't point to another offset
455 std::set<uint8_t> foundOffsets;
456 for (int ii = 1; ii < 6; ii++)
457 {
458 if (blockData[ii] == 0)
459 {
460 continue;
461 }
James Feist0eb40352019-04-09 14:44:04 -0700462 auto inserted = foundOffsets.insert(blockData[ii]);
463 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700464 {
465 return false;
466 }
467 }
468
469 // validate checksum
470 size_t sum = 0;
471 for (int jj = 0; jj < 7; jj++)
472 {
473 sum += blockData[jj];
474 }
475 sum = (256 - sum) & 0xFF;
476
477 if (sum != blockData[7])
478 {
479 return false;
480 }
481 return true;
482}
483
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700484// TODO: This code is very similar to the non-eeprom version and can be merged
485// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300486static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700487{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700488 auto path = getEepromPath(bus, address);
489
490 int file = open(path.c_str(), O_RDONLY);
491 if (file < 0)
492 {
493 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700494 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700495 }
496
Patrick Venturebaba7672019-10-26 09:26:41 -0700497 std::string errorMessage = "eeprom at " + std::to_string(bus) +
498 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300499 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800500 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700501
502 close(file);
503 return device;
504}
505
506std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
507{
508 std::set<int> foundList;
509
510 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
511
512 // For each file listed under the i2c device
513 // NOTE: This should be faster than just checking for each possible address
514 // path.
515 for (const auto& p : fs::directory_iterator(path))
516 {
517 const std::string node = p.path().string();
518 std::smatch m;
519 bool found =
520 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
521
522 if (!found)
523 {
524 continue;
525 }
526 if (m.size() != 2)
527 {
528 std::cerr << "regex didn't capture\n";
529 continue;
530 }
531
532 std::ssub_match subMatch = m[1];
533 std::string addressString = subMatch.str();
534
535 std::size_t ignored;
536 const int hexBase = 16;
537 int address = std::stoi(addressString, &ignored, hexBase);
538
539 const std::string eeprom = node + "/eeprom";
540
541 try
542 {
543 if (!fs::exists(eeprom))
544 {
545 continue;
546 }
547 }
548 catch (...)
549 {
550 continue;
551 }
552
553 // There is an eeprom file at this address, it may have invalid
554 // contents, but we found it.
555 foundList.insert(address);
556
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300557 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700558 if (!device.empty())
559 {
560 devices->emplace(address, device);
561 }
562 }
563
564 return foundList;
565}
566
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300567int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700568 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800569{
James Feist3cb5fec2018-01-23 14:41:51 -0800570
James Feist26c27ad2018-07-25 15:09:40 -0700571 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700572 // NOTE: When reading the devices raw on the bus, it can interfere with
573 // the driver's ability to operate, therefore read eeproms first before
574 // scanning for devices without drivers. Several experiments were run
575 // and it was determined that if there were any devices on the bus
576 // before the eeprom was hit and read, the eeprom driver wouldn't open
577 // while the bus device was open. An experiment was not performed to see
578 // if this issue was resolved if the i2c bus device was closed, but
579 // hexdumps of the eeprom later were successful.
580
581 // Scan for i2c eeproms loaded on this bus.
582 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800583 std::set<size_t>& failedItems = failedAddresses[bus];
584
585 std::set<size_t>* rootFailures = nullptr;
586 int rootBus = getRootBus(bus);
587
588 if (rootBus >= 0)
589 {
590 rootFailures = &(failedAddresses[rootBus]);
591 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700592
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530593 constexpr int startSkipSlaveAddr = 0;
594 constexpr int endSkipSlaveAddr = 12;
595
James Feist26c27ad2018-07-25 15:09:40 -0700596 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800597 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700598 if (skipList.find(ii) != skipList.end())
599 {
600 continue;
601 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530602 // skipping since no device is present in this range
603 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
604 {
605 continue;
606 }
James Feist26c27ad2018-07-25 15:09:40 -0700607 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530608 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800609 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700610 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700611 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700612 continue;
613 }
614 // probe
615 else if (i2c_smbus_read_byte(file) < 0)
616 {
617 continue;
618 }
James Feist3cb5fec2018-01-23 14:41:51 -0800619
James Feist26c27ad2018-07-25 15:09:40 -0700620 if (DEBUG)
621 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700622 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700623 << "\n";
624 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800625
James Feist8a983922019-10-24 17:11:56 -0700626 makeProbeInterface(bus, ii);
627
James Feist7972bb92019-11-13 15:59:24 -0800628 if (failedItems.find(ii) != failedItems.end())
629 {
630 // if we failed to read it once, unlikely we can read it later
631 continue;
632 }
633
634 if (rootFailures != nullptr)
635 {
636 if (rootFailures->find(ii) != rootFailures->end())
637 {
638 continue;
639 }
640 }
641
Vijay Khemka2d681f62018-11-06 15:51:00 -0800642 /* Check for Device type if it is 8 bit or 16 bit */
643 int flag = isDevice16Bit(file);
644 if (flag < 0)
645 {
646 std::cerr << "failed to read bus " << bus << " address " << ii
647 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700648 if (powerIsOn)
649 {
650 failedItems.insert(ii);
651 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800652 continue;
653 }
654
Patrick Venturebaba7672019-10-26 09:26:41 -0700655 std::string errorMessage =
656 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300657 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300658 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800659 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700660 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700661 {
James Feist26c27ad2018-07-25 15:09:40 -0700662 continue;
663 }
James Feist26c27ad2018-07-25 15:09:40 -0700664
Patrick Venture786f1792019-08-05 16:33:44 -0700665 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800666 }
James Feist26c27ad2018-07-25 15:09:40 -0700667 return 1;
668 });
669 std::future_status status =
670 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
671 if (status == std::future_status::timeout)
672 {
673 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700674 if (powerIsOn)
675 {
676 busBlacklist.insert(bus);
677 }
James Feist444830e2019-04-05 08:38:16 -0700678 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700679 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800680 }
681
James Feist444830e2019-04-05 08:38:16 -0700682 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700683 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800684}
685
Patrick Venture11f1ff42019-08-01 10:42:12 -0700686void loadBlacklist(const char* path)
687{
688 std::ifstream blacklistStream(path);
689 if (!blacklistStream.good())
690 {
691 // File is optional.
692 std::cerr << "Cannot open blacklist file.\n\n";
693 return;
694 }
695
696 nlohmann::json data =
697 nlohmann::json::parse(blacklistStream, nullptr, false);
698 if (data.is_discarded())
699 {
700 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
701 "exiting\n";
702 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700703 }
704
705 // It's expected to have at least one field, "buses" that is an array of the
706 // buses by integer. Allow for future options to exclude further aspects,
707 // such as specific addresses or ranges.
708 if (data.type() != nlohmann::json::value_t::object)
709 {
710 std::cerr << "Illegal blacklist, expected to read dictionary\n";
711 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700712 }
713
714 // If buses field is missing, that's fine.
715 if (data.count("buses") == 1)
716 {
717 // Parse the buses array after a little validation.
718 auto buses = data.at("buses");
719 if (buses.type() != nlohmann::json::value_t::array)
720 {
721 // Buses field present but invalid, therefore this is an error.
722 std::cerr << "Invalid contents for blacklist buses field\n";
723 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700724 }
725
726 // Catch exception here for type mis-match.
727 try
728 {
729 for (const auto& bus : buses)
730 {
731 busBlacklist.insert(bus.get<size_t>());
732 }
733 }
734 catch (const nlohmann::detail::type_error& e)
735 {
736 // Type mis-match is a critical error.
737 std::cerr << "Invalid bus type: " << e.what() << "\n";
738 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700739 }
740 }
741
742 return;
743}
744
James Feista465ccc2019-02-08 12:51:01 -0800745static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700746 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800747{
James Feista465ccc2019-02-08 12:51:01 -0800748 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800749 {
James Feist5d7f4692020-06-17 18:22:33 -0700750 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800751
James Feist5d7f4692020-06-17 18:22:33 -0700752 if (bus < 0)
753 {
754 std::cerr << "Cannot translate " << i2cBus << " to int\n";
755 continue;
756 }
James Feist444830e2019-04-05 08:38:16 -0700757 if (busBlacklist.find(bus) != busBlacklist.end())
758 {
759 continue; // skip previously failed busses
760 }
James Feist3cb5fec2018-01-23 14:41:51 -0800761
James Feist0c3980a2019-12-19 11:09:27 -0800762 int rootBus = getRootBus(bus);
763 if (busBlacklist.find(rootBus) != busBlacklist.end())
764 {
765 continue;
766 }
767
James Feist3cb5fec2018-01-23 14:41:51 -0800768 auto file = open(i2cBus.c_str(), O_RDWR);
769 if (file < 0)
770 {
771 std::cerr << "unable to open i2c device " << i2cBus.string()
772 << "\n";
773 continue;
774 }
775 unsigned long funcs = 0;
776
777 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
778 {
779 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700780 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800781 << bus << "\n";
782 continue;
783 }
784 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
785 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
786 {
787 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
788 << bus << "\n";
789 continue;
790 }
James Feist98132792019-07-09 13:29:09 -0700791 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800792 device = std::make_shared<DeviceMap>();
793
Nikhil Potaded8884f12019-03-27 13:27:13 -0700794 // i2cdetect by default uses the range 0x03 to 0x77, as
795 // this is what we have tested with, use this range. Could be
796 // changed in future.
797 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800798 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700799 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800800 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700801
802 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300803 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700804
805 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800806 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700807 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800808 }
James Feist3cb5fec2018-01-23 14:41:51 -0800809 }
James Feist3cb5fec2018-01-23 14:41:51 -0800810}
811
James Feist6ebf9de2018-05-15 15:01:17 -0700812// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700813struct FindDevicesWithCallback :
814 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700815{
James Feista465ccc2019-02-08 12:51:01 -0800816 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700817 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800818 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700819 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700820 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700821 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700822 ~FindDevicesWithCallback()
823 {
824 _callback();
825 }
826 void run()
827 {
James Feist98132792019-07-09 13:29:09 -0700828 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700829 }
830
James Feista465ccc2019-02-08 12:51:01 -0800831 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800832 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700833 std::function<void(void)> _callback;
834};
835
James Feist3cb5fec2018-01-23 14:41:51 -0800836static const std::tm intelEpoch(void)
837{
James Feist98132792019-07-09 13:29:09 -0700838 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800839 val.tm_year = 1996 - 1900;
840 return val;
841}
842
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800843static char sixBitToChar(uint8_t val)
844{
845 return static_cast<char>((val & 0x3f) + ' ');
846}
847
848/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
849static const char bcdHighChars[] = {
850 ' ', '-', '.', 'X', 'X', 'X',
851};
852
853static char bcdPlusToChar(uint8_t val)
854{
855 val &= 0xf;
856 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
857}
858
859enum class DecodeState
860{
861 ok,
862 end,
863 err,
864};
865
866enum FRUDataEncoding
867{
868 binary = 0x0,
869 bcdPlus = 0x1,
870 sixBitASCII = 0x2,
871 languageDependent = 0x3,
872};
873
874/* Decode FRU data into a std::string, given an input iterator and end. If the
875 * state returned is fruDataOk, then the resulting string is the decoded FRU
876 * data. The input iterator is advanced past the data consumed.
877 *
878 * On fruDataErr, we have lost synchronisation with the length bytes, so the
879 * iterator is no longer usable.
880 */
881static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300882 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300883 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800884{
885 std::string value;
886 unsigned int i;
887
888 /* we need at least one byte to decode the type/len header */
889 if (iter == end)
890 {
891 std::cerr << "Truncated FRU data\n";
892 return make_pair(DecodeState::err, value);
893 }
894
895 uint8_t c = *(iter++);
896
897 /* 0xc1 is the end marker */
898 if (c == 0xc1)
899 {
900 return make_pair(DecodeState::end, value);
901 }
902
903 /* decode type/len byte */
904 uint8_t type = static_cast<uint8_t>(c >> 6);
905 uint8_t len = static_cast<uint8_t>(c & 0x3f);
906
907 /* we should have at least len bytes of data available overall */
908 if (iter + len > end)
909 {
910 std::cerr << "FRU data field extends past end of FRU data\n";
911 return make_pair(DecodeState::err, value);
912 }
913
914 switch (type)
915 {
916 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300917 {
918 std::stringstream ss;
919 ss << std::hex << std::setfill('0');
920 for (i = 0; i < len; i++, iter++)
921 {
922 uint8_t val = static_cast<uint8_t>(*iter);
923 ss << std::setw(2) << static_cast<int>(val);
924 }
925 value = ss.str();
926 break;
927 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800928 case FRUDataEncoding::languageDependent:
929 /* For language-code dependent encodings, assume 8-bit ASCII */
930 value = std::string(iter, iter + len);
931 iter += len;
932 break;
933
934 case FRUDataEncoding::bcdPlus:
935 value = std::string();
936 for (i = 0; i < len; i++, iter++)
937 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300938 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800939 value.push_back(bcdPlusToChar(val >> 4));
940 value.push_back(bcdPlusToChar(val & 0xf));
941 }
942 break;
943
944 case FRUDataEncoding::sixBitASCII:
945 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300946 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800947 unsigned int accumBitLen = 0;
948 value = std::string();
949 for (i = 0; i < len; i++, iter++)
950 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300951 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800952 accumBitLen += 8;
953 while (accumBitLen >= 6)
954 {
955 value.push_back(sixBitToChar(accum & 0x3f));
956 accum >>= 6;
957 accumBitLen -= 6;
958 }
959 }
960 }
961 break;
962 }
963
964 return make_pair(DecodeState::ok, value);
965}
966
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300967bool formatFRU(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800968 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800969{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300970 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800971 {
972 return false;
973 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300974 std::vector<uint8_t>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700975 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800976 std::to_string(static_cast<int>(*fruAreaOffsetField));
977
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300978 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800979
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300980 for (const std::string& area : FRU_AREA_NAMES)
James Feist3cb5fec2018-01-23 14:41:51 -0800981 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700982 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800983 if (fruAreaOffsetField >= fruBytes.end())
984 {
985 return false;
986 }
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300987 size_t offset = (*fruAreaOffsetField) * fruBlockSize;
James Feist3cb5fec2018-01-23 14:41:51 -0800988
989 if (offset > 1)
990 {
991 // +2 to skip format and length
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300992 std::vector<uint8_t>::const_iterator fruBytesIter =
James Feist3cb5fec2018-01-23 14:41:51 -0800993 fruBytes.begin() + offset + 2;
994
995 if (fruBytesIter >= fruBytes.end())
996 {
997 return false;
998 }
999
1000 if (area == "CHASSIS")
1001 {
1002 result["CHASSIS_TYPE"] =
1003 std::to_string(static_cast<int>(*fruBytesIter));
1004 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001005 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001006 }
1007 else if (area == "BOARD")
1008 {
1009 result["BOARD_LANGUAGE_CODE"] =
1010 std::to_string(static_cast<int>(*fruBytesIter));
1011 fruBytesIter += 1;
1012 if (fruBytesIter >= fruBytes.end())
1013 {
1014 return false;
1015 }
1016
1017 unsigned int minutes = *fruBytesIter |
1018 *(fruBytesIter + 1) << 8 |
1019 *(fruBytesIter + 2) << 16;
1020 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001021 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001022 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001023 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001024
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001025 // Tue Nov 20 23:08:00 2018
1026 char timeString[32] = {0};
1027 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001028 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001029 if (bytes == 0)
1030 {
1031 std::cerr << "invalid time string encountered\n";
1032 return false;
1033 }
1034
1035 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001036 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001037 fruAreaFieldNames = &BOARD_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001038 }
1039 else if (area == "PRODUCT")
1040 {
1041 result["PRODUCT_LANGUAGE_CODE"] =
1042 std::to_string(static_cast<int>(*fruBytesIter));
1043 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001044 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001045 }
1046 else
1047 {
1048 continue;
1049 }
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001050 for (auto& field : *fruAreaFieldNames)
James Feist3cb5fec2018-01-23 14:41:51 -08001051 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001052 auto res = decodeFRUData(fruBytesIter, fruBytes.end());
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001053 std::string name = area + "_" + field;
James Feist3cb5fec2018-01-23 14:41:51 -08001054
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001055 if (res.first == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001056 {
1057 break;
1058 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001059 else if (res.first == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001060 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001061 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001062 return false;
1063 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001064
1065 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001066
Ed Tanous2147e672019-02-27 13:59:56 -08001067 // Strip non null characters from the end
1068 value.erase(std::find_if(value.rbegin(), value.rend(),
1069 [](char ch) { return ch != 0; })
1070 .base(),
1071 value.end());
1072
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001073 result[name] = std::move(value);
James Feist3cb5fec2018-01-23 14:41:51 -08001074 }
1075 }
1076 }
1077
1078 return true;
1079}
1080
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001081std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001082{
1083 auto deviceMap = busMap.find(bus);
1084 if (deviceMap == busMap.end())
1085 {
1086 throw std::invalid_argument("Invalid Bus.");
1087 }
1088 auto device = deviceMap->second->find(address);
1089 if (device == deviceMap->second->end())
1090 {
1091 throw std::invalid_argument("Invalid Address.");
1092 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001093 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001094
1095 return ret;
1096}
1097
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001098void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001099 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001100 boost::container::flat_map<
1101 std::pair<size_t, size_t>,
1102 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001103 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001104{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001105 boost::container::flat_map<std::string, std::string> formattedFRU;
1106 if (!formatFRU(device, formattedFRU))
James Feist3cb5fec2018-01-23 14:41:51 -08001107 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001108 std::cerr << "failed to format fru for device at bus " << bus
1109 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001110 return;
1111 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001112
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001113 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001114 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001115 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001116 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001117 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001118 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001119 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001120 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001121 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001122 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001123 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001124 {
1125 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001126 std::regex illegalObject("[^A-Za-z0-9_]");
1127 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001128 }
1129 else
1130 {
1131 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1132 UNKNOWN_BUS_OBJECT_COUNT++;
1133 }
1134
James Feist918e18c2018-02-13 15:51:07 -08001135 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001136 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001137 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001138 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001139 int highest = -1;
1140 bool found = false;
1141
James Feista465ccc2019-02-08 12:51:01 -08001142 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001143 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001144 std::string path = busIface.second->get_object_path();
1145 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001146 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001147 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001148 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001149 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001150 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001151 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001152 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001153 // This device is already added to the lower numbered bus,
1154 // do not replicate it.
1155 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001156 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001157
1158 // Check if the match named has extra information.
1159 found = true;
1160 std::smatch base_match;
1161
1162 bool match = std::regex_match(
1163 path, base_match, std::regex(productName + "_(\\d+)$"));
1164 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001165 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001166 if (base_match.size() == 2)
1167 {
1168 std::ssub_match base_sub_match = base_match[1];
1169 std::string base = base_sub_match.str();
1170
1171 int value = std::stoi(base);
1172 highest = (value > highest) ? value : highest;
1173 }
James Feist79e9c0b2018-03-15 15:21:17 -07001174 }
James Feist918e18c2018-02-13 15:51:07 -08001175 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001176 } // end searching objects
1177
1178 if (found)
1179 {
1180 // We found something with the same name. If highest was still -1,
1181 // it means this new entry will be _0.
1182 productName += "_";
1183 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001184 }
1185 }
James Feist3cb5fec2018-01-23 14:41:51 -08001186
James Feist9eb0b582018-04-27 12:15:46 -07001187 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1188 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1189 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1190
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001191 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001192 {
James Feist9eb0b582018-04-27 12:15:46 -07001193
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001194 std::regex_replace(property.second.begin(), property.second.begin(),
1195 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301196 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001197 {
1198 continue;
1199 }
1200 std::string key =
1201 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301202
1203 if (property.first == "PRODUCT_ASSET_TAG")
1204 {
1205 std::string propertyName = property.first;
1206 iface->register_property(
1207 key, property.second + '\0',
1208 [bus, address, propertyName,
1209 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1210 if (strcmp(req.c_str(), resp.c_str()))
1211 {
1212 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001213 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301214 dbusInterfaceMap))
1215 {
1216 resp = req;
1217 }
1218 else
1219 {
1220 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001221 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301222 }
1223 }
1224 return 1;
1225 });
1226 }
1227 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001228 {
1229 std::cerr << "illegal key: " << key << "\n";
1230 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001231 if (DEBUG)
1232 {
1233 std::cout << property.first << ": " << property.second << "\n";
1234 }
James Feist3cb5fec2018-01-23 14:41:51 -08001235 }
James Feist2a9d6db2018-04-27 15:48:28 -07001236
1237 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001238 iface->register_property("BUS", bus);
1239 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001240
James Feist9eb0b582018-04-27 12:15:46 -07001241 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001242}
1243
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001244static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001245{
1246 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001247 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1248 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001249 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001250 baseboardFRUFile.seekg(0, std::ios_base::end);
1251 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1252 baseboardFRU.resize(fileSize);
1253 baseboardFRUFile.seekg(0, std::ios_base::beg);
1254 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001255 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001256 }
1257 else
1258 {
1259 return false;
1260 }
1261 return true;
1262}
1263
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001264bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001265{
1266 boost::container::flat_map<std::string, std::string> tmp;
1267 if (fru.size() > MAX_FRU_SIZE)
1268 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001269 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001270 return false;
1271 }
1272 // verify legal fru by running it through fru parsing logic
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001273 if (!formatFRU(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001274 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001275 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001276 return false;
1277 }
1278 // baseboard fru
1279 if (bus == 0 && address == 0)
1280 {
1281 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1282 if (!file.good())
1283 {
1284 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1285 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001286 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001287 return false;
1288 }
James Feista465ccc2019-02-08 12:51:01 -08001289 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001290 return file.good();
1291 }
1292 else
1293 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001294 if (hasEepromFile(bus, address))
1295 {
1296 auto path = getEepromPath(bus, address);
1297 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1298 if (eeprom < 0)
1299 {
1300 std::cerr << "unable to open i2c device " << path << "\n";
1301 throw DBusInternalError();
1302 return false;
1303 }
1304
1305 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1306 if (writtenBytes < 0)
1307 {
1308 std::cerr << "unable to write to i2c device " << path << "\n";
1309 close(eeprom);
1310 throw DBusInternalError();
1311 return false;
1312 }
1313
1314 close(eeprom);
1315 return true;
1316 }
1317
James Feistb49ffc32018-05-02 11:10:43 -07001318 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1319
1320 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1321 if (file < 0)
1322 {
1323 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001324 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001325 return false;
1326 }
1327 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1328 {
1329 std::cerr << "unable to set device address\n";
1330 close(file);
James Feistddb78302018-09-06 11:45:42 -07001331 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001332 return false;
1333 }
1334
1335 constexpr const size_t RETRY_MAX = 2;
1336 uint16_t index = 0;
1337 size_t retries = RETRY_MAX;
1338 while (index < fru.size())
1339 {
1340 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1341 (retries == RETRY_MAX))
1342 {
1343 // The 4K EEPROM only uses the A2 and A1 device address bits
1344 // with the third bit being a memory page address bit.
1345 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1346 {
1347 std::cerr << "unable to set device address\n";
1348 close(file);
James Feistddb78302018-09-06 11:45:42 -07001349 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001350 return false;
1351 }
1352 }
1353
James Feist98132792019-07-09 13:29:09 -07001354 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1355 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001356 {
1357 if (!retries--)
1358 {
1359 std::cerr << "error writing fru: " << strerror(errno)
1360 << "\n";
1361 close(file);
James Feistddb78302018-09-06 11:45:42 -07001362 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001363 return false;
1364 }
1365 }
1366 else
1367 {
1368 retries = RETRY_MAX;
1369 index++;
1370 }
1371 // most eeproms require 5-10ms between writes
1372 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1373 }
1374 close(file);
1375 return true;
1376 }
1377}
1378
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001379void rescanOneBus(
1380 BusMap& busmap, uint8_t busNum,
1381 boost::container::flat_map<
1382 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001383 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1384 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001385{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001386 for (auto& [pair, interface] : foundDevices)
1387 {
1388 if (pair.first == static_cast<size_t>(busNum))
1389 {
1390 objServer.remove_interface(interface);
1391 foundDevices.erase(pair);
1392 }
1393 }
1394
James Feist5d7f4692020-06-17 18:22:33 -07001395 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1396 if (!fs::exists(busPath))
1397 {
1398 if (dbusCall)
1399 {
1400 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1401 << "\n";
1402 throw std::invalid_argument("Invalid Bus.");
1403 }
1404 return;
1405 }
1406
1407 std::vector<fs::path> i2cBuses;
1408 i2cBuses.emplace_back(busPath);
1409
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001410 auto scan = std::make_shared<FindDevicesWithCallback>(
1411 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1412 for (auto& busIface : dbusInterfaceMap)
1413 {
1414 if (busIface.first.first == static_cast<size_t>(busNum))
1415 {
1416 objServer.remove_interface(busIface.second);
1417 }
1418 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001419 auto found = busmap.find(busNum);
1420 if (found == busmap.end() || found->second == nullptr)
1421 {
1422 return;
1423 }
1424 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001425 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001426 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001427 static_cast<uint32_t>(busNum), device.first);
1428 }
1429 });
1430 scan->run();
1431}
1432
James Feist9eb0b582018-04-27 12:15:46 -07001433void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001434 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001435 boost::container::flat_map<
1436 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001437 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001438{
James Feist6ebf9de2018-05-15 15:01:17 -07001439 static boost::asio::deadline_timer timer(io);
1440 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001441
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001442 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001443 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001444 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001445 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001446
Nikhil Potaded8884f12019-03-27 13:27:13 -07001447 boost::container::flat_map<size_t, fs::path> busPaths;
1448 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001449 {
James Feist4131aea2018-03-09 09:47:30 -08001450 std::cerr << "unable to find i2c devices\n";
1451 return;
James Feist918e18c2018-02-13 15:51:07 -08001452 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001453
1454 for (auto busPath : busPaths)
1455 {
1456 i2cBuses.emplace_back(busPath.second);
1457 }
James Feist4131aea2018-03-09 09:47:30 -08001458
James Feist98132792019-07-09 13:29:09 -07001459 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001460 for (auto& [pair, interface] : foundDevices)
1461 {
1462 objServer.remove_interface(interface);
1463 }
1464 foundDevices.clear();
1465
James Feist5cb06082019-10-24 17:11:13 -07001466 auto scan =
1467 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001468 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001469 {
1470 objServer.remove_interface(busIface.second);
1471 }
James Feist4131aea2018-03-09 09:47:30 -08001472
James Feist6ebf9de2018-05-15 15:01:17 -07001473 dbusInterfaceMap.clear();
1474 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001475
James Feist6ebf9de2018-05-15 15:01:17 -07001476 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001477 std::vector<uint8_t> baseboardFRU;
1478 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001479 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001480 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001481 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001482 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001483 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001484 }
James Feist98132792019-07-09 13:29:09 -07001485 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001486 {
James Feista465ccc2019-02-08 12:51:01 -08001487 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001488 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001489 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001490 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001491 }
1492 }
1493 });
1494 scan->run();
1495 });
James Feist918e18c2018-02-13 15:51:07 -08001496}
1497
Joshi-Mansid73b7442020-03-27 19:10:21 +05301498// Calculate new checksum for fru info area
1499size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1500{
1501 constexpr int checksumMod = 256;
1502 constexpr uint8_t modVal = 0xFF;
1503 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1504 return (checksumMod - sum) & modVal;
1505}
1506
1507// Update new fru area length &
1508// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001509// Return the offset of the area checksum byte
1510static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1511 size_t fruAreaStart,
1512 size_t fruAreaEndOfFieldsOffset,
1513 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301514{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001515 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301516
1517 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001518 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1519 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301520
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001521 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301522 size_t checksumLoc;
1523 if (!mod)
1524 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001525 traverseFRUAreaIndex += (fruBlockSize);
1526 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301527 }
1528 else
1529 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001530 traverseFRUAreaIndex += (fruBlockSize - mod);
1531 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301532 }
1533
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001534 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1535 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1536 size_t fruAreaLengthLoc = fruAreaStart + 1;
1537 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301538
1539 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001540 std::vector<uint8_t> finalFRUData;
1541 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1542 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301543
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001544 size_t checksumVal = calculateChecksum(finalFRUData);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301545
1546 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001547 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301548}
1549
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001550static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301551{
1552 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001553 constexpr uint8_t endOfFields = 0xC1;
1554 if (fruFieldTypeLenValue == endOfFields)
1555 {
1556 return -1;
1557 }
1558 else
1559 {
1560 return fruFieldTypeLenValue & typeLenMask;
1561 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301562}
1563
1564// Details with example of Asset Tag Update
1565// To find location of Product Info Area asset tag as per FRU specification
1566// 1. Find product Info area starting offset (*8 - as header will be in
1567// multiple of 8 bytes).
1568// 2. Skip 3 bytes of product info area (like format version, area length,
1569// and language code).
1570// 3. Traverse manufacturer name, product name, product version, & product
1571// serial number, by reading type/length code to reach the Asset Tag.
1572// 4. Update the Asset Tag, reposition the product Info area in multiple of
1573// 8 bytes. Update the Product area length and checksum.
1574
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001575bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301576 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1577 std::string propertyName,
1578 boost::container::flat_map<
1579 std::pair<size_t, size_t>,
1580 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1581{
1582 size_t updatePropertyReqLen = updatePropertyReq.length();
1583 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1584 {
1585 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001586 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301587 "Invalid Length "
1588 << updatePropertyReqLen << "\n";
1589 return false;
1590 }
1591
1592 std::vector<uint8_t> fruData;
1593 try
1594 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001595 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301596 static_cast<uint8_t>(address));
1597 }
1598 catch (std::invalid_argument& e)
1599 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001600 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301601 return false;
1602 }
1603
1604 if (fruData.empty())
1605 {
1606 return false;
1607 }
1608
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001609 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301610
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001611 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301612 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001613 std::string areaName = propertyName.substr(0, propertyName.find("_"));
1614 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1615 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301616 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001617 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001618 << " \n";
1619 return false;
1620 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001621 fruAreas fruAreaToUpdate =
1622 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1623 fruAreaOffsetFieldValue =
1624 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1625 switch (fruAreaToUpdate)
1626 {
1627 case fruAreas::fruAreaChassis:
1628 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1629 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1630 break;
1631 case fruAreas::fruAreaBoard:
1632 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1633 fruAreaFieldNames = &BOARD_FRU_AREAS;
1634 break;
1635 case fruAreas::fruAreaProduct:
1636 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1637 // i.e. version, area length and language code
1638 offset = 3;
1639 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1640 break;
1641 default:
1642 std::cerr << "Don't know how to handle property " << propertyName
1643 << " \n";
1644 return false;
1645 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001646 if (fruAreaOffsetFieldValue == 0)
1647 {
1648 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301649 return false;
1650 }
1651
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001652 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001653 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1654 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001655 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001656 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001657 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001658 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301659
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001660 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301661 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001662 skipToFRUUpdateField++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301663 if (propertyName.find(field) != std::string::npos)
1664 {
1665 break;
1666 }
1667 }
1668
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001669 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301670 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001671 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001672 if (fieldLength < 0)
1673 {
1674 break;
1675 }
1676 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301677 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001678 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301679
1680 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001681 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001682 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301683 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001684 std::cerr << "Property " << propertyName << " not present \n";
1685 return false;
1686 }
1687 fruDataIter += 1 + fieldLength;
1688 size_t restFRUFieldsLoc = fruDataIter;
1689 size_t endOfFieldsLoc = 0;
1690 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1691 {
1692 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301693 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001694 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301695 break;
1696 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001697 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301698 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001699 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301700
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001701 std::vector<uint8_t> restFRUAreaFieldsData;
1702 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001703 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001704 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301705
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001706 // Push post update fru areas if any
1707 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001708 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1709 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001710 {
1711 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001712 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001713 if ((fruAreaLoc > endOfFieldsLoc) &&
1714 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1715 {
1716 nextFRUAreaLoc = fruAreaLoc;
1717 }
1718 }
1719 std::vector<uint8_t> restFRUAreasData;
1720 if (nextFRUAreaLoc)
1721 {
1722 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1723 fruData.size() - nextFRUAreaLoc,
1724 std::back_inserter(restFRUAreasData));
1725 }
1726
1727 // check FRU area size
1728 size_t fruAreaDataSize =
1729 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1730 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1731 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1732 {
1733
1734#ifdef ENABLE_FRU_AREA_RESIZE
1735 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1736 // round size to 8-byte blocks
1737 newFRUAreaSize =
1738 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1739 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1740 fruData.resize(newFRUDataSize);
1741 fruAreaSize = newFRUAreaSize;
1742 fruAreaEnd = fruAreaStart + fruAreaSize;
1743#else
1744 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1745 << " should not be greater than available FRU area size: "
1746 << fruAreaAvailableSize << "\n";
1747 return false;
1748#endif // ENABLE_FRU_AREA_RESIZE
1749 }
1750
Joshi-Mansid73b7442020-03-27 19:10:21 +05301751 // write new requested property field length and data
1752 constexpr uint8_t newTypeLenMask = 0xC0;
1753 fruData[fruUpdateFieldLoc] =
1754 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1755 fruUpdateFieldLoc++;
1756 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1757 fruData.begin() + fruUpdateFieldLoc);
1758
1759 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001760 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1761 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001762 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1763 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301764
1765 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001766 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1767 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301768
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001769#ifdef ENABLE_FRU_AREA_RESIZE
1770 ++nextFRUAreaNewLoc;
1771 ssize_t nextFRUAreaOffsetDiff =
1772 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1773 // Append rest FRU Areas if size changed and there were other sections after
1774 // updated one
1775 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1776 {
1777 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1778 fruData.begin() + nextFRUAreaNewLoc);
1779 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001780 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1781 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001782 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001783 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001784 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1785 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1786 {
1787 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1788 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1789 }
1790 }
1791 // Calculate new checksum
1792 std::vector<uint8_t> headerFRUData;
1793 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1794 size_t checksumVal = calculateChecksum(headerFRUData);
1795 fruData[7] = static_cast<uint8_t>(checksumVal);
1796 // fill zeros if FRU Area size decreased
1797 if (nextFRUAreaOffsetDiff < 0)
1798 {
1799 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1800 restFRUAreasData.size(),
1801 fruData.end(), 0);
1802 }
1803 }
1804#else
1805 // this is to avoid "unused variable" warning
1806 (void)nextFRUAreaNewLoc;
1807#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301808 if (fruData.empty())
1809 {
1810 return false;
1811 }
1812
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001813 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301814 fruData))
1815 {
1816 return false;
1817 }
1818
1819 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1820 rescanBusses(busMap, dbusInterfaceMap);
1821 return true;
1822}
1823
James Feist98132792019-07-09 13:29:09 -07001824int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001825{
1826 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001827 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001828 std::vector<fs::path> i2cBuses;
1829
James Feista3c180a2018-08-09 16:06:04 -07001830 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001831 {
1832 std::cerr << "unable to find i2c devices\n";
1833 return 1;
1834 }
James Feist3cb5fec2018-01-23 14:41:51 -08001835
Patrick Venture11f1ff42019-08-01 10:42:12 -07001836 // check for and load blacklist with initial buses.
1837 loadBlacklist(blacklistPath);
1838
Vijay Khemka065f6d92018-12-18 10:37:47 -08001839 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001840
James Feist6ebf9de2018-05-15 15:01:17 -07001841 // this is a map with keys of pair(bus number, address) and values of
1842 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001843 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001844 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1845 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001846
James Feist9eb0b582018-04-27 12:15:46 -07001847 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1848 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1849 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001850
James Feist5cb06082019-10-24 17:11:13 -07001851 iface->register_method("ReScan",
1852 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001853
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001854 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001855 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001856 });
1857
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001858 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001859
1860 iface->register_method("WriteFru", [&](const uint8_t bus,
1861 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001862 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001863 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001864 {
James Feistddb78302018-09-06 11:45:42 -07001865 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001866 return;
1867 }
1868 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001869 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001870 });
James Feist9eb0b582018-04-27 12:15:46 -07001871 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001872
James Feist9eb0b582018-04-27 12:15:46 -07001873 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001874 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001875 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001876 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001877 std::string,
1878 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001879 values;
1880 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001881 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001882 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001883 {
James Feistcb5661d2020-06-12 15:05:01 -07001884 powerIsOn = boost::ends_with(
1885 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001886 }
James Feist6ebf9de2018-05-15 15:01:17 -07001887
James Feistcb5661d2020-06-12 15:05:01 -07001888 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001889 {
James Feist5cb06082019-10-24 17:11:13 -07001890 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001891 }
James Feist918e18c2018-02-13 15:51:07 -08001892 };
James Feist9eb0b582018-04-27 12:15:46 -07001893
1894 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001895 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001896 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001897 "openbmc_project/state/"
1898 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001899 eventHandler);
1900
James Feist4131aea2018-03-09 09:47:30 -08001901 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001902 inotify_add_watch(fd, I2C_DEV_LOCATION,
1903 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001904 std::array<char, 4096> readBuffer;
1905 std::string pendingBuffer;
1906 // monitor for new i2c devices
1907 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1908 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001909 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001910 std::size_t bytes_transferred) {
1911 if (ec)
1912 {
1913 std::cout << "Callback Error " << ec << "\n";
1914 return;
1915 }
1916 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001917 while (pendingBuffer.size() > sizeof(inotify_event))
1918 {
James Feista465ccc2019-02-08 12:51:01 -08001919 const inotify_event* iEvent =
1920 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001921 pendingBuffer.data());
1922 switch (iEvent->mask)
1923 {
James Feist9eb0b582018-04-27 12:15:46 -07001924 case IN_CREATE:
1925 case IN_MOVED_TO:
1926 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001927 std::string name(iEvent->name);
1928 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001929 {
James Feist5d7f4692020-06-17 18:22:33 -07001930 int bus = busStrToInt(name);
1931 if (bus < 0)
1932 {
1933 std::cerr << "Could not parse bus " << name
1934 << "\n";
1935 continue;
1936 }
1937 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1938 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001939 }
James Feist4131aea2018-03-09 09:47:30 -08001940 }
1941
1942 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1943 }
James Feist6ebf9de2018-05-15 15:01:17 -07001944
James Feist4131aea2018-03-09 09:47:30 -08001945 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1946 watchI2cBusses);
1947 };
1948
1949 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001950 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001951 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001952
James Feist3cb5fec2018-01-23 14:41:51 -08001953 io.run();
1954 return 0;
1955}