blob: f502d63fe57324c5bfe0abeac10ae830fe98b9a0 [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 Kartashev6b3d4c52020-08-10 19:24:17 +030073enum
74{
75 fruAreaInternal = 1,
76 fruAreaChassis,
77 fruAreaBoard,
78 fruAreaProduct,
79 fruAreaMultirecord
80};
Andrei Kartashev2f0de172020-08-13 14:29:40 +030081static const std::array<std::string, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080082 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070083const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030084using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080085using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
86
James Feist444830e2019-04-05 08:38:16 -070087static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070088struct FindDevicesWithCallback;
89
Nikhil Potaded8884f12019-03-27 13:27:13 -070090static BusMap busMap;
91
James Feistcb5661d2020-06-12 15:05:01 -070092static bool powerIsOn = false;
93
James Feist8a983922019-10-24 17:11:56 -070094static boost::container::flat_map<
95 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
96 foundDevices;
97
James Feist7972bb92019-11-13 15:59:24 -080098static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
99
James Feist5cb06082019-10-24 17:11:13 -0700100boost::asio::io_service io;
101auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
102auto objServer = sdbusplus::asio::object_server(systemBus);
103
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300104static const std::vector<std::string> CHASSIS_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530105 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
106
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300107static const std::vector<std::string> BOARD_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530108 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
109 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
110
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300111static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Joshi-Mansid73b7442020-03-27 19:10:21 +0530112 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION", "SERIAL_NUMBER",
113 "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
114
Patrick Venturebaba7672019-10-26 09:26:41 -0700115bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300116bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530117 const std::string& assetTag, uint32_t bus, uint32_t address,
118 std::string propertyName,
119 boost::container::flat_map<
120 std::pair<size_t, size_t>,
121 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700122
Xiang Liu2801a702020-01-20 14:29:34 -0800123using ReadBlockFunc =
124 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
125 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700126
127// Read and validate FRU contents, given the flag required for raw i2c, the open
128// file handle, a read method, and a helper string for failures.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300129std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300130 ReadBlockFunc readBlock,
131 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700132{
133 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
134
Xiang Liu2801a702020-01-20 14:29:34 -0800135 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700136 {
137 std::cerr << "failed to read " << errorHelp << "\n";
138 return {};
139 }
140
141 // check the header checksum
142 if (!validateHeader(blockData))
143 {
144 if (DEBUG)
145 {
146 std::cerr << "Illegal header " << errorHelp << "\n";
147 }
148
149 return {};
150 }
151
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300152 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700153 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
154
Patrick Venturee26395d2019-10-29 14:05:16 -0700155 bool hasMultiRecords = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300156 ssize_t fruLength = fruBlockSize; // At least FRU header is present
Patrick Venturebaba7672019-10-26 09:26:41 -0700157 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
158 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700159 // Offset value can be 255.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300160 unsigned int areaOffset = device[jj];
Patrick Venturebaba7672019-10-26 09:26:41 -0700161 if (areaOffset == 0)
162 {
163 continue;
164 }
165
Patrick Venturee26395d2019-10-29 14:05:16 -0700166 // MultiRecords are different. jj is not tracking section, it's walking
167 // the common header.
168 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
169 {
170 hasMultiRecords = true;
171 break;
172 }
173
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300174 areaOffset *= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700175
Xiang Liu2801a702020-01-20 14:29:34 -0800176 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
177 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700178 {
179 std::cerr << "failed to read " << errorHelp << "\n";
180 return {};
181 }
182
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700183 // Ignore data type (blockData is already unsigned).
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300184 size_t length = blockData[1] * fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700185 areaOffset += length;
186 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
187 }
188
Patrick Venturee26395d2019-10-29 14:05:16 -0700189 if (hasMultiRecords)
190 {
191 // device[area count] is the index to the last area because the 0th
192 // entry is not an offset in the common header.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300193 unsigned int areaOffset = device[FRU_AREAS.size()];
194 areaOffset *= fruBlockSize;
Patrick Venturee26395d2019-10-29 14:05:16 -0700195
196 // the multi-area record header is 5 bytes long.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300197 constexpr size_t multiRecordHeaderSize = 5;
198 constexpr uint8_t multiRecordEndOfListMask = 0x80;
Patrick Venturee26395d2019-10-29 14:05:16 -0700199
200 // Sanity hard-limit to 64KB.
201 while (areaOffset < std::numeric_limits<uint16_t>::max())
202 {
203 // In multi-area, the area offset points to the 0th record, each
204 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800205 if (readBlock(flag, file, address,
206 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700207 blockData.data()) < 0)
208 {
209 std::cerr << "failed to read " << errorHelp << "\n";
210 return {};
211 }
212
213 // Ok, let's check the record length, which is in bytes (unsigned,
214 // up to 255, so blockData should hold uint8_t not char)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300215 size_t recordLength = blockData[2];
Patrick Venturee26395d2019-10-29 14:05:16 -0700216 areaOffset += (recordLength + multiRecordHeaderSize);
217 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
218
219 // If this is the end of the list bail.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300220 if ((blockData[1] & multiRecordEndOfListMask))
Patrick Venturee26395d2019-10-29 14:05:16 -0700221 {
222 break;
223 }
224 }
225 }
226
Patrick Venturebaba7672019-10-26 09:26:41 -0700227 // You already copied these first 8 bytes (the ipmi fru header size)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300228 fruLength -= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700229
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300230 int readOffset = fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700231
232 while (fruLength > 0)
233 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300234 int requestLength =
235 std::min(I2C_SMBUS_BLOCK_MAX, static_cast<int>(fruLength));
Patrick Venturebaba7672019-10-26 09:26:41 -0700236
Xiang Liu2801a702020-01-20 14:29:34 -0800237 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700238 static_cast<uint8_t>(requestLength),
239 blockData.data()) < 0)
240 {
241 std::cerr << "failed to read " << errorHelp << "\n";
242 return {};
243 }
244
245 device.insert(device.end(), blockData.begin(),
246 blockData.begin() + requestLength);
247
248 readOffset += requestLength;
249 fruLength -= requestLength;
250 }
251
252 return device;
253}
254
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700255// Given a bus/address, produce the path in sysfs for an eeprom.
256static std::string getEepromPath(size_t bus, size_t address)
257{
258 std::stringstream output;
259 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
260 << std::setfill('0') << std::setw(4) << std::hex << address
261 << "/eeprom";
262 return output.str();
263}
264
265static bool hasEepromFile(size_t bus, size_t address)
266{
267 auto path = getEepromPath(bus, address);
268 try
269 {
270 return fs::exists(path);
271 }
272 catch (...)
273 {
274 return false;
275 }
276}
277
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700278static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800279 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700280 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700281{
282 auto result = lseek(fd, offset, SEEK_SET);
283 if (result < 0)
284 {
285 std::cerr << "failed to seek\n";
286 return -1;
287 }
288
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700289 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700290}
291
James Feist5d7f4692020-06-17 18:22:33 -0700292static int busStrToInt(const std::string& busName)
293{
294 auto findBus = busName.rfind("-");
295 if (findBus == std::string::npos)
296 {
297 return -1;
298 }
299 return std::stoi(busName.substr(findBus + 1));
300}
301
James Feist7972bb92019-11-13 15:59:24 -0800302static int getRootBus(size_t bus)
303{
304 auto ec = std::error_code();
305 auto path = std::filesystem::read_symlink(
306 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
307 std::to_string(bus) + "/mux_device"),
308 ec);
309 if (ec)
310 {
311 return -1;
312 }
313
314 std::string filename = path.filename();
315 auto findBus = filename.find("-");
316 if (findBus == std::string::npos)
317 {
318 return -1;
319 }
320 return std::stoi(filename.substr(0, findBus));
321}
322
James Feistc95cb142018-02-26 10:41:42 -0800323static bool isMuxBus(size_t bus)
324{
Ed Tanous072e25d2018-12-16 21:45:20 -0800325 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800326 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
327}
328
James Feist8a983922019-10-24 17:11:56 -0700329static void makeProbeInterface(size_t bus, size_t address)
330{
331 if (isMuxBus(bus))
332 {
333 return; // the mux buses are random, no need to publish
334 }
335 auto [it, success] = foundDevices.emplace(
336 std::make_pair(bus, address),
337 objServer.add_interface(
338 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
339 std::to_string(address),
340 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
341 if (!success)
342 {
343 return; // already added
344 }
345 it->second->register_property("Bus", bus);
346 it->second->register_property("Address", address);
347 it->second->initialize();
348}
349
Vijay Khemka2d681f62018-11-06 15:51:00 -0800350static int isDevice16Bit(int file)
351{
352 /* Get first byte */
353 int byte1 = i2c_smbus_read_byte_data(file, 0);
354 if (byte1 < 0)
355 {
356 return byte1;
357 }
358 /* Read 7 more bytes, it will read same first byte in case of
359 * 8 bit but it will read next byte in case of 16 bit
360 */
361 for (int i = 0; i < 7; i++)
362 {
363 int byte2 = i2c_smbus_read_byte_data(file, 0);
364 if (byte2 < 0)
365 {
366 return byte2;
367 }
368 if (byte2 != byte1)
369 {
370 return 1;
371 }
372 }
373 return 0;
374}
375
Xiang Liu2801a702020-01-20 14:29:34 -0800376// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
377// from_slave_buf_len bytes.
378static int i2c_smbus_write_then_read(int file, uint16_t address,
379 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
380 uint8_t* fromSlaveBuf,
381 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800382{
Xiang Liu2801a702020-01-20 14:29:34 -0800383 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
384 fromSlaveBufLen == 0)
385 {
386 return -1;
387 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800388
Xiang Liu2801a702020-01-20 14:29:34 -0800389#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
390 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
391 struct i2c_rdwr_ioctl_data rdwr;
392
393 msgs[0].addr = address;
394 msgs[0].flags = 0;
395 msgs[0].len = toSlaveBufLen;
396 msgs[0].buf = toSlaveBuf;
397 msgs[1].addr = address;
398 msgs[1].flags = I2C_M_RD;
399 msgs[1].len = fromSlaveBufLen;
400 msgs[1].buf = fromSlaveBuf;
401
402 rdwr.msgs = msgs;
403 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
404
405 int ret = ioctl(file, I2C_RDWR, &rdwr);
406
407 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
408}
409
410static int64_t readBlockData(int flag, int file, uint16_t address,
411 uint16_t offset, uint8_t len, uint8_t* buf)
412{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800413 if (flag == 0)
414 {
Xiang Liu2801a702020-01-20 14:29:34 -0800415 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
416 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800417 }
418
Xiang Liu2801a702020-01-20 14:29:34 -0800419 offset = htobe16(offset);
420 return i2c_smbus_write_then_read(
421 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800422}
423
James Feist24bae7a2019-04-03 09:50:56 -0700424bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
425{
426 // ipmi spec format version number is currently at 1, verify it
427 if (blockData[0] != 0x1)
428 {
429 return false;
430 }
431
432 // verify pad is set to 0
433 if (blockData[6] != 0x0)
434 {
435 return false;
436 }
437
438 // verify offsets are 0, or don't point to another offset
439 std::set<uint8_t> foundOffsets;
440 for (int ii = 1; ii < 6; ii++)
441 {
442 if (blockData[ii] == 0)
443 {
444 continue;
445 }
James Feist0eb40352019-04-09 14:44:04 -0700446 auto inserted = foundOffsets.insert(blockData[ii]);
447 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700448 {
449 return false;
450 }
451 }
452
453 // validate checksum
454 size_t sum = 0;
455 for (int jj = 0; jj < 7; jj++)
456 {
457 sum += blockData[jj];
458 }
459 sum = (256 - sum) & 0xFF;
460
461 if (sum != blockData[7])
462 {
463 return false;
464 }
465 return true;
466}
467
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700468// TODO: This code is very similar to the non-eeprom version and can be merged
469// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300470static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700471{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700472 auto path = getEepromPath(bus, address);
473
474 int file = open(path.c_str(), O_RDONLY);
475 if (file < 0)
476 {
477 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700478 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700479 }
480
Patrick Venturebaba7672019-10-26 09:26:41 -0700481 std::string errorMessage = "eeprom at " + std::to_string(bus) +
482 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300483 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800484 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700485
486 close(file);
487 return device;
488}
489
490std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
491{
492 std::set<int> foundList;
493
494 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
495
496 // For each file listed under the i2c device
497 // NOTE: This should be faster than just checking for each possible address
498 // path.
499 for (const auto& p : fs::directory_iterator(path))
500 {
501 const std::string node = p.path().string();
502 std::smatch m;
503 bool found =
504 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
505
506 if (!found)
507 {
508 continue;
509 }
510 if (m.size() != 2)
511 {
512 std::cerr << "regex didn't capture\n";
513 continue;
514 }
515
516 std::ssub_match subMatch = m[1];
517 std::string addressString = subMatch.str();
518
519 std::size_t ignored;
520 const int hexBase = 16;
521 int address = std::stoi(addressString, &ignored, hexBase);
522
523 const std::string eeprom = node + "/eeprom";
524
525 try
526 {
527 if (!fs::exists(eeprom))
528 {
529 continue;
530 }
531 }
532 catch (...)
533 {
534 continue;
535 }
536
537 // There is an eeprom file at this address, it may have invalid
538 // contents, but we found it.
539 foundList.insert(address);
540
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300541 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700542 if (!device.empty())
543 {
544 devices->emplace(address, device);
545 }
546 }
547
548 return foundList;
549}
550
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300551int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700552 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800553{
James Feist3cb5fec2018-01-23 14:41:51 -0800554
James Feist26c27ad2018-07-25 15:09:40 -0700555 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700556 // NOTE: When reading the devices raw on the bus, it can interfere with
557 // the driver's ability to operate, therefore read eeproms first before
558 // scanning for devices without drivers. Several experiments were run
559 // and it was determined that if there were any devices on the bus
560 // before the eeprom was hit and read, the eeprom driver wouldn't open
561 // while the bus device was open. An experiment was not performed to see
562 // if this issue was resolved if the i2c bus device was closed, but
563 // hexdumps of the eeprom later were successful.
564
565 // Scan for i2c eeproms loaded on this bus.
566 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800567 std::set<size_t>& failedItems = failedAddresses[bus];
568
569 std::set<size_t>* rootFailures = nullptr;
570 int rootBus = getRootBus(bus);
571
572 if (rootBus >= 0)
573 {
574 rootFailures = &(failedAddresses[rootBus]);
575 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700576
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530577 constexpr int startSkipSlaveAddr = 0;
578 constexpr int endSkipSlaveAddr = 12;
579
James Feist26c27ad2018-07-25 15:09:40 -0700580 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800581 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700582 if (skipList.find(ii) != skipList.end())
583 {
584 continue;
585 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530586 // skipping since no device is present in this range
587 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
588 {
589 continue;
590 }
James Feist26c27ad2018-07-25 15:09:40 -0700591 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530592 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800593 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700594 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700595 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700596 continue;
597 }
598 // probe
599 else if (i2c_smbus_read_byte(file) < 0)
600 {
601 continue;
602 }
James Feist3cb5fec2018-01-23 14:41:51 -0800603
James Feist26c27ad2018-07-25 15:09:40 -0700604 if (DEBUG)
605 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700606 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700607 << "\n";
608 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800609
James Feist8a983922019-10-24 17:11:56 -0700610 makeProbeInterface(bus, ii);
611
James Feist7972bb92019-11-13 15:59:24 -0800612 if (failedItems.find(ii) != failedItems.end())
613 {
614 // if we failed to read it once, unlikely we can read it later
615 continue;
616 }
617
618 if (rootFailures != nullptr)
619 {
620 if (rootFailures->find(ii) != rootFailures->end())
621 {
622 continue;
623 }
624 }
625
Vijay Khemka2d681f62018-11-06 15:51:00 -0800626 /* Check for Device type if it is 8 bit or 16 bit */
627 int flag = isDevice16Bit(file);
628 if (flag < 0)
629 {
630 std::cerr << "failed to read bus " << bus << " address " << ii
631 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700632 if (powerIsOn)
633 {
634 failedItems.insert(ii);
635 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800636 continue;
637 }
638
Patrick Venturebaba7672019-10-26 09:26:41 -0700639 std::string errorMessage =
640 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300641 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300642 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800643 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700644 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700645 {
James Feist26c27ad2018-07-25 15:09:40 -0700646 continue;
647 }
James Feist26c27ad2018-07-25 15:09:40 -0700648
Patrick Venture786f1792019-08-05 16:33:44 -0700649 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800650 }
James Feist26c27ad2018-07-25 15:09:40 -0700651 return 1;
652 });
653 std::future_status status =
654 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
655 if (status == std::future_status::timeout)
656 {
657 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700658 if (powerIsOn)
659 {
660 busBlacklist.insert(bus);
661 }
James Feist444830e2019-04-05 08:38:16 -0700662 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700663 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800664 }
665
James Feist444830e2019-04-05 08:38:16 -0700666 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700667 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800668}
669
Patrick Venture11f1ff42019-08-01 10:42:12 -0700670void loadBlacklist(const char* path)
671{
672 std::ifstream blacklistStream(path);
673 if (!blacklistStream.good())
674 {
675 // File is optional.
676 std::cerr << "Cannot open blacklist file.\n\n";
677 return;
678 }
679
680 nlohmann::json data =
681 nlohmann::json::parse(blacklistStream, nullptr, false);
682 if (data.is_discarded())
683 {
684 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
685 "exiting\n";
686 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700687 }
688
689 // It's expected to have at least one field, "buses" that is an array of the
690 // buses by integer. Allow for future options to exclude further aspects,
691 // such as specific addresses or ranges.
692 if (data.type() != nlohmann::json::value_t::object)
693 {
694 std::cerr << "Illegal blacklist, expected to read dictionary\n";
695 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700696 }
697
698 // If buses field is missing, that's fine.
699 if (data.count("buses") == 1)
700 {
701 // Parse the buses array after a little validation.
702 auto buses = data.at("buses");
703 if (buses.type() != nlohmann::json::value_t::array)
704 {
705 // Buses field present but invalid, therefore this is an error.
706 std::cerr << "Invalid contents for blacklist buses field\n";
707 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700708 }
709
710 // Catch exception here for type mis-match.
711 try
712 {
713 for (const auto& bus : buses)
714 {
715 busBlacklist.insert(bus.get<size_t>());
716 }
717 }
718 catch (const nlohmann::detail::type_error& e)
719 {
720 // Type mis-match is a critical error.
721 std::cerr << "Invalid bus type: " << e.what() << "\n";
722 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700723 }
724 }
725
726 return;
727}
728
James Feista465ccc2019-02-08 12:51:01 -0800729static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700730 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800731{
James Feista465ccc2019-02-08 12:51:01 -0800732 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800733 {
James Feist5d7f4692020-06-17 18:22:33 -0700734 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800735
James Feist5d7f4692020-06-17 18:22:33 -0700736 if (bus < 0)
737 {
738 std::cerr << "Cannot translate " << i2cBus << " to int\n";
739 continue;
740 }
James Feist444830e2019-04-05 08:38:16 -0700741 if (busBlacklist.find(bus) != busBlacklist.end())
742 {
743 continue; // skip previously failed busses
744 }
James Feist3cb5fec2018-01-23 14:41:51 -0800745
James Feist0c3980a2019-12-19 11:09:27 -0800746 int rootBus = getRootBus(bus);
747 if (busBlacklist.find(rootBus) != busBlacklist.end())
748 {
749 continue;
750 }
751
James Feist3cb5fec2018-01-23 14:41:51 -0800752 auto file = open(i2cBus.c_str(), O_RDWR);
753 if (file < 0)
754 {
755 std::cerr << "unable to open i2c device " << i2cBus.string()
756 << "\n";
757 continue;
758 }
759 unsigned long funcs = 0;
760
761 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
762 {
763 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700764 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800765 << bus << "\n";
766 continue;
767 }
768 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
769 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
770 {
771 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
772 << bus << "\n";
773 continue;
774 }
James Feist98132792019-07-09 13:29:09 -0700775 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800776 device = std::make_shared<DeviceMap>();
777
Nikhil Potaded8884f12019-03-27 13:27:13 -0700778 // i2cdetect by default uses the range 0x03 to 0x77, as
779 // this is what we have tested with, use this range. Could be
780 // changed in future.
781 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800782 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700783 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800784 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700785
786 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300787 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700788
789 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800790 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700791 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800792 }
James Feist3cb5fec2018-01-23 14:41:51 -0800793 }
James Feist3cb5fec2018-01-23 14:41:51 -0800794}
795
James Feist6ebf9de2018-05-15 15:01:17 -0700796// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700797struct FindDevicesWithCallback :
798 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700799{
James Feista465ccc2019-02-08 12:51:01 -0800800 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700801 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800802 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700803 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700804 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700805 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700806 ~FindDevicesWithCallback()
807 {
808 _callback();
809 }
810 void run()
811 {
James Feist98132792019-07-09 13:29:09 -0700812 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700813 }
814
James Feista465ccc2019-02-08 12:51:01 -0800815 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800816 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700817 std::function<void(void)> _callback;
818};
819
James Feist3cb5fec2018-01-23 14:41:51 -0800820static const std::tm intelEpoch(void)
821{
James Feist98132792019-07-09 13:29:09 -0700822 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800823 val.tm_year = 1996 - 1900;
824 return val;
825}
826
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800827static char sixBitToChar(uint8_t val)
828{
829 return static_cast<char>((val & 0x3f) + ' ');
830}
831
832/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
833static const char bcdHighChars[] = {
834 ' ', '-', '.', 'X', 'X', 'X',
835};
836
837static char bcdPlusToChar(uint8_t val)
838{
839 val &= 0xf;
840 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
841}
842
843enum class DecodeState
844{
845 ok,
846 end,
847 err,
848};
849
850enum FRUDataEncoding
851{
852 binary = 0x0,
853 bcdPlus = 0x1,
854 sixBitASCII = 0x2,
855 languageDependent = 0x3,
856};
857
858/* Decode FRU data into a std::string, given an input iterator and end. If the
859 * state returned is fruDataOk, then the resulting string is the decoded FRU
860 * data. The input iterator is advanced past the data consumed.
861 *
862 * On fruDataErr, we have lost synchronisation with the length bytes, so the
863 * iterator is no longer usable.
864 */
865static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300866 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300867 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800868{
869 std::string value;
870 unsigned int i;
871
872 /* we need at least one byte to decode the type/len header */
873 if (iter == end)
874 {
875 std::cerr << "Truncated FRU data\n";
876 return make_pair(DecodeState::err, value);
877 }
878
879 uint8_t c = *(iter++);
880
881 /* 0xc1 is the end marker */
882 if (c == 0xc1)
883 {
884 return make_pair(DecodeState::end, value);
885 }
886
887 /* decode type/len byte */
888 uint8_t type = static_cast<uint8_t>(c >> 6);
889 uint8_t len = static_cast<uint8_t>(c & 0x3f);
890
891 /* we should have at least len bytes of data available overall */
892 if (iter + len > end)
893 {
894 std::cerr << "FRU data field extends past end of FRU data\n";
895 return make_pair(DecodeState::err, value);
896 }
897
898 switch (type)
899 {
900 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300901 {
902 std::stringstream ss;
903 ss << std::hex << std::setfill('0');
904 for (i = 0; i < len; i++, iter++)
905 {
906 uint8_t val = static_cast<uint8_t>(*iter);
907 ss << std::setw(2) << static_cast<int>(val);
908 }
909 value = ss.str();
910 break;
911 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800912 case FRUDataEncoding::languageDependent:
913 /* For language-code dependent encodings, assume 8-bit ASCII */
914 value = std::string(iter, iter + len);
915 iter += len;
916 break;
917
918 case FRUDataEncoding::bcdPlus:
919 value = std::string();
920 for (i = 0; i < len; i++, iter++)
921 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300922 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800923 value.push_back(bcdPlusToChar(val >> 4));
924 value.push_back(bcdPlusToChar(val & 0xf));
925 }
926 break;
927
928 case FRUDataEncoding::sixBitASCII:
929 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300930 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800931 unsigned int accumBitLen = 0;
932 value = std::string();
933 for (i = 0; i < len; i++, iter++)
934 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300935 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800936 accumBitLen += 8;
937 while (accumBitLen >= 6)
938 {
939 value.push_back(sixBitToChar(accum & 0x3f));
940 accum >>= 6;
941 accumBitLen -= 6;
942 }
943 }
944 }
945 break;
946 }
947
948 return make_pair(DecodeState::ok, value);
949}
950
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300951bool formatFRU(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800952 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800953{
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300954 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800955 {
956 return false;
957 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300958 std::vector<uint8_t>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700959 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800960 std::to_string(static_cast<int>(*fruAreaOffsetField));
961
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300962 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800963
James Feist0eb40352019-04-09 14:44:04 -0700964 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800965 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700966 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800967 if (fruAreaOffsetField >= fruBytes.end())
968 {
969 return false;
970 }
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300971 size_t offset = (*fruAreaOffsetField) * fruBlockSize;
James Feist3cb5fec2018-01-23 14:41:51 -0800972
973 if (offset > 1)
974 {
975 // +2 to skip format and length
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300976 std::vector<uint8_t>::const_iterator fruBytesIter =
James Feist3cb5fec2018-01-23 14:41:51 -0800977 fruBytes.begin() + offset + 2;
978
979 if (fruBytesIter >= fruBytes.end())
980 {
981 return false;
982 }
983
984 if (area == "CHASSIS")
985 {
986 result["CHASSIS_TYPE"] =
987 std::to_string(static_cast<int>(*fruBytesIter));
988 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300989 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -0800990 }
991 else if (area == "BOARD")
992 {
993 result["BOARD_LANGUAGE_CODE"] =
994 std::to_string(static_cast<int>(*fruBytesIter));
995 fruBytesIter += 1;
996 if (fruBytesIter >= fruBytes.end())
997 {
998 return false;
999 }
1000
1001 unsigned int minutes = *fruBytesIter |
1002 *(fruBytesIter + 1) << 8 |
1003 *(fruBytesIter + 2) << 16;
1004 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001005 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001006 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001007 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001008
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001009 // Tue Nov 20 23:08:00 2018
1010 char timeString[32] = {0};
1011 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001012 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001013 if (bytes == 0)
1014 {
1015 std::cerr << "invalid time string encountered\n";
1016 return false;
1017 }
1018
1019 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001020 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001021 fruAreaFieldNames = &BOARD_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001022 }
1023 else if (area == "PRODUCT")
1024 {
1025 result["PRODUCT_LANGUAGE_CODE"] =
1026 std::to_string(static_cast<int>(*fruBytesIter));
1027 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001028 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
James Feist3cb5fec2018-01-23 14:41:51 -08001029 }
1030 else
1031 {
1032 continue;
1033 }
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001034 for (auto& field : *fruAreaFieldNames)
James Feist3cb5fec2018-01-23 14:41:51 -08001035 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001036 auto res = decodeFRUData(fruBytesIter, fruBytes.end());
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001037 std::string name = area + "_" + field;
James Feist3cb5fec2018-01-23 14:41:51 -08001038
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001039 if (res.first == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001040 {
1041 break;
1042 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001043 else if (res.first == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001044 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001045 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001046 return false;
1047 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001048
1049 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001050
Ed Tanous2147e672019-02-27 13:59:56 -08001051 // Strip non null characters from the end
1052 value.erase(std::find_if(value.rbegin(), value.rend(),
1053 [](char ch) { return ch != 0; })
1054 .base(),
1055 value.end());
1056
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001057 result[name] = std::move(value);
James Feist3cb5fec2018-01-23 14:41:51 -08001058 }
1059 }
1060 }
1061
1062 return true;
1063}
1064
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001065std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001066{
1067 auto deviceMap = busMap.find(bus);
1068 if (deviceMap == busMap.end())
1069 {
1070 throw std::invalid_argument("Invalid Bus.");
1071 }
1072 auto device = deviceMap->second->find(address);
1073 if (device == deviceMap->second->end())
1074 {
1075 throw std::invalid_argument("Invalid Address.");
1076 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001077 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001078
1079 return ret;
1080}
1081
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001082void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001083 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001084 boost::container::flat_map<
1085 std::pair<size_t, size_t>,
1086 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001087 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001088{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001089 boost::container::flat_map<std::string, std::string> formattedFRU;
1090 if (!formatFRU(device, formattedFRU))
James Feist3cb5fec2018-01-23 14:41:51 -08001091 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001092 std::cerr << "failed to format fru for device at bus " << bus
1093 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001094 return;
1095 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001096
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001097 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001098 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001099 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001100 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001101 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001102 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001103 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001104 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001105 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001106 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001107 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001108 {
1109 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001110 std::regex illegalObject("[^A-Za-z0-9_]");
1111 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001112 }
1113 else
1114 {
1115 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1116 UNKNOWN_BUS_OBJECT_COUNT++;
1117 }
1118
James Feist918e18c2018-02-13 15:51:07 -08001119 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001120 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001121 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001122 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001123 int highest = -1;
1124 bool found = false;
1125
James Feista465ccc2019-02-08 12:51:01 -08001126 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001127 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001128 std::string path = busIface.second->get_object_path();
1129 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001130 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001131 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001132 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001133 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001134 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001135 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001136 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001137 // This device is already added to the lower numbered bus,
1138 // do not replicate it.
1139 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001140 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001141
1142 // Check if the match named has extra information.
1143 found = true;
1144 std::smatch base_match;
1145
1146 bool match = std::regex_match(
1147 path, base_match, std::regex(productName + "_(\\d+)$"));
1148 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001149 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001150 if (base_match.size() == 2)
1151 {
1152 std::ssub_match base_sub_match = base_match[1];
1153 std::string base = base_sub_match.str();
1154
1155 int value = std::stoi(base);
1156 highest = (value > highest) ? value : highest;
1157 }
James Feist79e9c0b2018-03-15 15:21:17 -07001158 }
James Feist918e18c2018-02-13 15:51:07 -08001159 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001160 } // end searching objects
1161
1162 if (found)
1163 {
1164 // We found something with the same name. If highest was still -1,
1165 // it means this new entry will be _0.
1166 productName += "_";
1167 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001168 }
1169 }
James Feist3cb5fec2018-01-23 14:41:51 -08001170
James Feist9eb0b582018-04-27 12:15:46 -07001171 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1172 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1173 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1174
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001175 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001176 {
James Feist9eb0b582018-04-27 12:15:46 -07001177
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001178 std::regex_replace(property.second.begin(), property.second.begin(),
1179 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301180 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001181 {
1182 continue;
1183 }
1184 std::string key =
1185 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301186
1187 if (property.first == "PRODUCT_ASSET_TAG")
1188 {
1189 std::string propertyName = property.first;
1190 iface->register_property(
1191 key, property.second + '\0',
1192 [bus, address, propertyName,
1193 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1194 if (strcmp(req.c_str(), resp.c_str()))
1195 {
1196 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001197 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301198 dbusInterfaceMap))
1199 {
1200 resp = req;
1201 }
1202 else
1203 {
1204 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001205 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301206 }
1207 }
1208 return 1;
1209 });
1210 }
1211 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001212 {
1213 std::cerr << "illegal key: " << key << "\n";
1214 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001215 if (DEBUG)
1216 {
1217 std::cout << property.first << ": " << property.second << "\n";
1218 }
James Feist3cb5fec2018-01-23 14:41:51 -08001219 }
James Feist2a9d6db2018-04-27 15:48:28 -07001220
1221 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001222 iface->register_property("BUS", bus);
1223 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001224
James Feist9eb0b582018-04-27 12:15:46 -07001225 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001226}
1227
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001228static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001229{
1230 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001231 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1232 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001233 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001234 baseboardFRUFile.seekg(0, std::ios_base::end);
1235 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1236 baseboardFRU.resize(fileSize);
1237 baseboardFRUFile.seekg(0, std::ios_base::beg);
1238 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001239 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001240 }
1241 else
1242 {
1243 return false;
1244 }
1245 return true;
1246}
1247
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001248bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001249{
1250 boost::container::flat_map<std::string, std::string> tmp;
1251 if (fru.size() > MAX_FRU_SIZE)
1252 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001253 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001254 return false;
1255 }
1256 // verify legal fru by running it through fru parsing logic
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001257 if (!formatFRU(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001258 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001259 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001260 return false;
1261 }
1262 // baseboard fru
1263 if (bus == 0 && address == 0)
1264 {
1265 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1266 if (!file.good())
1267 {
1268 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1269 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001270 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001271 return false;
1272 }
James Feista465ccc2019-02-08 12:51:01 -08001273 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001274 return file.good();
1275 }
1276 else
1277 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001278 if (hasEepromFile(bus, address))
1279 {
1280 auto path = getEepromPath(bus, address);
1281 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1282 if (eeprom < 0)
1283 {
1284 std::cerr << "unable to open i2c device " << path << "\n";
1285 throw DBusInternalError();
1286 return false;
1287 }
1288
1289 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1290 if (writtenBytes < 0)
1291 {
1292 std::cerr << "unable to write to i2c device " << path << "\n";
1293 close(eeprom);
1294 throw DBusInternalError();
1295 return false;
1296 }
1297
1298 close(eeprom);
1299 return true;
1300 }
1301
James Feistb49ffc32018-05-02 11:10:43 -07001302 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1303
1304 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1305 if (file < 0)
1306 {
1307 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001308 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001309 return false;
1310 }
1311 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1312 {
1313 std::cerr << "unable to set device address\n";
1314 close(file);
James Feistddb78302018-09-06 11:45:42 -07001315 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001316 return false;
1317 }
1318
1319 constexpr const size_t RETRY_MAX = 2;
1320 uint16_t index = 0;
1321 size_t retries = RETRY_MAX;
1322 while (index < fru.size())
1323 {
1324 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1325 (retries == RETRY_MAX))
1326 {
1327 // The 4K EEPROM only uses the A2 and A1 device address bits
1328 // with the third bit being a memory page address bit.
1329 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1330 {
1331 std::cerr << "unable to set device address\n";
1332 close(file);
James Feistddb78302018-09-06 11:45:42 -07001333 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001334 return false;
1335 }
1336 }
1337
James Feist98132792019-07-09 13:29:09 -07001338 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1339 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001340 {
1341 if (!retries--)
1342 {
1343 std::cerr << "error writing fru: " << strerror(errno)
1344 << "\n";
1345 close(file);
James Feistddb78302018-09-06 11:45:42 -07001346 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001347 return false;
1348 }
1349 }
1350 else
1351 {
1352 retries = RETRY_MAX;
1353 index++;
1354 }
1355 // most eeproms require 5-10ms between writes
1356 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1357 }
1358 close(file);
1359 return true;
1360 }
1361}
1362
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001363void rescanOneBus(
1364 BusMap& busmap, uint8_t busNum,
1365 boost::container::flat_map<
1366 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001367 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1368 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001369{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001370 for (auto& [pair, interface] : foundDevices)
1371 {
1372 if (pair.first == static_cast<size_t>(busNum))
1373 {
1374 objServer.remove_interface(interface);
1375 foundDevices.erase(pair);
1376 }
1377 }
1378
James Feist5d7f4692020-06-17 18:22:33 -07001379 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1380 if (!fs::exists(busPath))
1381 {
1382 if (dbusCall)
1383 {
1384 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1385 << "\n";
1386 throw std::invalid_argument("Invalid Bus.");
1387 }
1388 return;
1389 }
1390
1391 std::vector<fs::path> i2cBuses;
1392 i2cBuses.emplace_back(busPath);
1393
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001394 auto scan = std::make_shared<FindDevicesWithCallback>(
1395 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1396 for (auto& busIface : dbusInterfaceMap)
1397 {
1398 if (busIface.first.first == static_cast<size_t>(busNum))
1399 {
1400 objServer.remove_interface(busIface.second);
1401 }
1402 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001403 auto found = busmap.find(busNum);
1404 if (found == busmap.end() || found->second == nullptr)
1405 {
1406 return;
1407 }
1408 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001409 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001410 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001411 static_cast<uint32_t>(busNum), device.first);
1412 }
1413 });
1414 scan->run();
1415}
1416
James Feist9eb0b582018-04-27 12:15:46 -07001417void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001418 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001419 boost::container::flat_map<
1420 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001421 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001422{
James Feist6ebf9de2018-05-15 15:01:17 -07001423 static boost::asio::deadline_timer timer(io);
1424 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001425
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001426 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001427 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001428 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001429 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001430
Nikhil Potaded8884f12019-03-27 13:27:13 -07001431 boost::container::flat_map<size_t, fs::path> busPaths;
1432 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001433 {
James Feist4131aea2018-03-09 09:47:30 -08001434 std::cerr << "unable to find i2c devices\n";
1435 return;
James Feist918e18c2018-02-13 15:51:07 -08001436 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001437
1438 for (auto busPath : busPaths)
1439 {
1440 i2cBuses.emplace_back(busPath.second);
1441 }
James Feist4131aea2018-03-09 09:47:30 -08001442
James Feist98132792019-07-09 13:29:09 -07001443 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001444 for (auto& [pair, interface] : foundDevices)
1445 {
1446 objServer.remove_interface(interface);
1447 }
1448 foundDevices.clear();
1449
James Feist5cb06082019-10-24 17:11:13 -07001450 auto scan =
1451 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001452 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001453 {
1454 objServer.remove_interface(busIface.second);
1455 }
James Feist4131aea2018-03-09 09:47:30 -08001456
James Feist6ebf9de2018-05-15 15:01:17 -07001457 dbusInterfaceMap.clear();
1458 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001459
James Feist6ebf9de2018-05-15 15:01:17 -07001460 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001461 std::vector<uint8_t> baseboardFRU;
1462 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001463 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001464 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001465 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001466 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001467 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001468 }
James Feist98132792019-07-09 13:29:09 -07001469 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001470 {
James Feista465ccc2019-02-08 12:51:01 -08001471 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001472 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001473 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001474 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001475 }
1476 }
1477 });
1478 scan->run();
1479 });
James Feist918e18c2018-02-13 15:51:07 -08001480}
1481
Joshi-Mansid73b7442020-03-27 19:10:21 +05301482// Calculate new checksum for fru info area
1483size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1484{
1485 constexpr int checksumMod = 256;
1486 constexpr uint8_t modVal = 0xFF;
1487 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1488 return (checksumMod - sum) & modVal;
1489}
1490
1491// Update new fru area length &
1492// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001493// Return the offset of the area checksum byte
1494static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1495 size_t fruAreaStart,
1496 size_t fruAreaEndOfFieldsOffset,
1497 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301498{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001499 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301500
1501 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001502 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1503 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301504
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001505 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301506 size_t checksumLoc;
1507 if (!mod)
1508 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001509 traverseFRUAreaIndex += (fruBlockSize);
1510 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301511 }
1512 else
1513 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001514 traverseFRUAreaIndex += (fruBlockSize - mod);
1515 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301516 }
1517
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001518 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1519 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1520 size_t fruAreaLengthLoc = fruAreaStart + 1;
1521 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301522
1523 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001524 std::vector<uint8_t> finalFRUData;
1525 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1526 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301527
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001528 size_t checksumVal = calculateChecksum(finalFRUData);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301529
1530 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001531 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301532}
1533
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001534static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301535{
1536 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001537 constexpr uint8_t endOfFields = 0xC1;
1538 if (fruFieldTypeLenValue == endOfFields)
1539 {
1540 return -1;
1541 }
1542 else
1543 {
1544 return fruFieldTypeLenValue & typeLenMask;
1545 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301546}
1547
1548// Details with example of Asset Tag Update
1549// To find location of Product Info Area asset tag as per FRU specification
1550// 1. Find product Info area starting offset (*8 - as header will be in
1551// multiple of 8 bytes).
1552// 2. Skip 3 bytes of product info area (like format version, area length,
1553// and language code).
1554// 3. Traverse manufacturer name, product name, product version, & product
1555// serial number, by reading type/length code to reach the Asset Tag.
1556// 4. Update the Asset Tag, reposition the product Info area in multiple of
1557// 8 bytes. Update the Product area length and checksum.
1558
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001559bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301560 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1561 std::string propertyName,
1562 boost::container::flat_map<
1563 std::pair<size_t, size_t>,
1564 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1565{
1566 size_t updatePropertyReqLen = updatePropertyReq.length();
1567 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1568 {
1569 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001570 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301571 "Invalid Length "
1572 << updatePropertyReqLen << "\n";
1573 return false;
1574 }
1575
1576 std::vector<uint8_t> fruData;
1577 try
1578 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001579 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301580 static_cast<uint8_t>(address));
1581 }
1582 catch (std::invalid_argument& e)
1583 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001584 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301585 return false;
1586 }
1587
1588 if (fruData.empty())
1589 {
1590 return false;
1591 }
1592
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001593 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301594
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001595 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301596 size_t offset = 0;
1597
1598 if (propertyName.find("CHASSIS") == 0)
1599 {
1600 constexpr size_t fruAreaOffsetField = 2;
1601 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1602
1603 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1604
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001605 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301606 }
1607 else if (propertyName.find("BOARD") == 0)
1608 {
1609 constexpr size_t fruAreaOffsetField = 3;
1610 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1611
1612 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1613
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001614 fruAreaFieldNames = &BOARD_FRU_AREAS;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301615 }
1616 else if (propertyName.find("PRODUCT") == 0)
1617 {
1618 constexpr size_t fruAreaOffsetField = 4;
1619 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1620
1621 offset = 3;
1622 // Manufacturer name offset. Skip fixed first 3 product fru bytes i.e.
1623 // version, area length and language code
1624
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001625 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301626 }
1627 else
1628 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001629 std::cerr << "Don't know how to handle property " << propertyName
1630 << " \n";
1631 return false;
1632 }
1633 if (fruAreaOffsetFieldValue == 0)
1634 {
1635 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301636 return false;
1637 }
1638
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001639 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001640 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1641 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001642 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001643 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001644 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001645 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301646
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001647 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301648 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001649 skipToFRUUpdateField++;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301650 if (propertyName.find(field) != std::string::npos)
1651 {
1652 break;
1653 }
1654 }
1655
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001656 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301657 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001658 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001659 if (fieldLength < 0)
1660 {
1661 break;
1662 }
1663 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301664 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001665 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301666
1667 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001668 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001669 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301670 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001671 std::cerr << "Property " << propertyName << " not present \n";
1672 return false;
1673 }
1674 fruDataIter += 1 + fieldLength;
1675 size_t restFRUFieldsLoc = fruDataIter;
1676 size_t endOfFieldsLoc = 0;
1677 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1678 {
1679 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301680 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001681 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301682 break;
1683 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001684 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301685 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001686 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301687
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001688 std::vector<uint8_t> restFRUAreaFieldsData;
1689 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001690 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001691 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301692
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001693 // Push post update fru areas if any
1694 unsigned int nextFRUAreaLoc = 0;
1695 for (unsigned int nextFRUAreaOffsetField = fruAreaInternal;
1696 nextFRUAreaOffsetField <= fruAreaMultirecord; nextFRUAreaOffsetField++)
1697 {
1698 unsigned int fruAreaLoc =
1699 fruData[nextFRUAreaOffsetField] * fruBlockSize;
1700 if ((fruAreaLoc > endOfFieldsLoc) &&
1701 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1702 {
1703 nextFRUAreaLoc = fruAreaLoc;
1704 }
1705 }
1706 std::vector<uint8_t> restFRUAreasData;
1707 if (nextFRUAreaLoc)
1708 {
1709 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1710 fruData.size() - nextFRUAreaLoc,
1711 std::back_inserter(restFRUAreasData));
1712 }
1713
1714 // check FRU area size
1715 size_t fruAreaDataSize =
1716 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1717 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1718 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1719 {
1720
1721#ifdef ENABLE_FRU_AREA_RESIZE
1722 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1723 // round size to 8-byte blocks
1724 newFRUAreaSize =
1725 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1726 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1727 fruData.resize(newFRUDataSize);
1728 fruAreaSize = newFRUAreaSize;
1729 fruAreaEnd = fruAreaStart + fruAreaSize;
1730#else
1731 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1732 << " should not be greater than available FRU area size: "
1733 << fruAreaAvailableSize << "\n";
1734 return false;
1735#endif // ENABLE_FRU_AREA_RESIZE
1736 }
1737
Joshi-Mansid73b7442020-03-27 19:10:21 +05301738 // write new requested property field length and data
1739 constexpr uint8_t newTypeLenMask = 0xC0;
1740 fruData[fruUpdateFieldLoc] =
1741 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1742 fruUpdateFieldLoc++;
1743 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1744 fruData.begin() + fruUpdateFieldLoc);
1745
1746 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001747 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1748 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001749 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1750 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301751
1752 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001753 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1754 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301755
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001756#ifdef ENABLE_FRU_AREA_RESIZE
1757 ++nextFRUAreaNewLoc;
1758 ssize_t nextFRUAreaOffsetDiff =
1759 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1760 // Append rest FRU Areas if size changed and there were other sections after
1761 // updated one
1762 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1763 {
1764 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1765 fruData.begin() + nextFRUAreaNewLoc);
1766 // Update Common Header
1767 for (size_t fruAreaOffsetField = FRU_AREA_INTERNAL;
1768 fruAreaOffsetField <= FRU_AREA_MULTIRECORD; fruAreaOffsetField++)
1769 {
1770 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1771 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1772 {
1773 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1774 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1775 }
1776 }
1777 // Calculate new checksum
1778 std::vector<uint8_t> headerFRUData;
1779 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1780 size_t checksumVal = calculateChecksum(headerFRUData);
1781 fruData[7] = static_cast<uint8_t>(checksumVal);
1782 // fill zeros if FRU Area size decreased
1783 if (nextFRUAreaOffsetDiff < 0)
1784 {
1785 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1786 restFRUAreasData.size(),
1787 fruData.end(), 0);
1788 }
1789 }
1790#else
1791 // this is to avoid "unused variable" warning
1792 (void)nextFRUAreaNewLoc;
1793#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301794 if (fruData.empty())
1795 {
1796 return false;
1797 }
1798
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001799 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301800 fruData))
1801 {
1802 return false;
1803 }
1804
1805 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1806 rescanBusses(busMap, dbusInterfaceMap);
1807 return true;
1808}
1809
James Feist98132792019-07-09 13:29:09 -07001810int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001811{
1812 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001813 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001814 std::vector<fs::path> i2cBuses;
1815
James Feista3c180a2018-08-09 16:06:04 -07001816 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001817 {
1818 std::cerr << "unable to find i2c devices\n";
1819 return 1;
1820 }
James Feist3cb5fec2018-01-23 14:41:51 -08001821
Patrick Venture11f1ff42019-08-01 10:42:12 -07001822 // check for and load blacklist with initial buses.
1823 loadBlacklist(blacklistPath);
1824
Vijay Khemka065f6d92018-12-18 10:37:47 -08001825 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001826
James Feist6ebf9de2018-05-15 15:01:17 -07001827 // this is a map with keys of pair(bus number, address) and values of
1828 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001829 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001830 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1831 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001832
James Feist9eb0b582018-04-27 12:15:46 -07001833 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1834 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1835 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001836
James Feist5cb06082019-10-24 17:11:13 -07001837 iface->register_method("ReScan",
1838 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001839
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001840 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001841 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001842 });
1843
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001844 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001845
1846 iface->register_method("WriteFru", [&](const uint8_t bus,
1847 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001848 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001849 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001850 {
James Feistddb78302018-09-06 11:45:42 -07001851 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001852 return;
1853 }
1854 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001855 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001856 });
James Feist9eb0b582018-04-27 12:15:46 -07001857 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001858
James Feist9eb0b582018-04-27 12:15:46 -07001859 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001860 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001861 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001862 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001863 std::string,
1864 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001865 values;
1866 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001867 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001868 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001869 {
James Feistcb5661d2020-06-12 15:05:01 -07001870 powerIsOn = boost::ends_with(
1871 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001872 }
James Feist6ebf9de2018-05-15 15:01:17 -07001873
James Feistcb5661d2020-06-12 15:05:01 -07001874 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001875 {
James Feist5cb06082019-10-24 17:11:13 -07001876 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001877 }
James Feist918e18c2018-02-13 15:51:07 -08001878 };
James Feist9eb0b582018-04-27 12:15:46 -07001879
1880 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001881 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001882 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001883 "openbmc_project/state/"
1884 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001885 eventHandler);
1886
James Feist4131aea2018-03-09 09:47:30 -08001887 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001888 inotify_add_watch(fd, I2C_DEV_LOCATION,
1889 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001890 std::array<char, 4096> readBuffer;
1891 std::string pendingBuffer;
1892 // monitor for new i2c devices
1893 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1894 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001895 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001896 std::size_t bytes_transferred) {
1897 if (ec)
1898 {
1899 std::cout << "Callback Error " << ec << "\n";
1900 return;
1901 }
1902 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001903 while (pendingBuffer.size() > sizeof(inotify_event))
1904 {
James Feista465ccc2019-02-08 12:51:01 -08001905 const inotify_event* iEvent =
1906 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001907 pendingBuffer.data());
1908 switch (iEvent->mask)
1909 {
James Feist9eb0b582018-04-27 12:15:46 -07001910 case IN_CREATE:
1911 case IN_MOVED_TO:
1912 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001913 std::string name(iEvent->name);
1914 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001915 {
James Feist5d7f4692020-06-17 18:22:33 -07001916 int bus = busStrToInt(name);
1917 if (bus < 0)
1918 {
1919 std::cerr << "Could not parse bus " << name
1920 << "\n";
1921 continue;
1922 }
1923 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1924 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001925 }
James Feist4131aea2018-03-09 09:47:30 -08001926 }
1927
1928 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1929 }
James Feist6ebf9de2018-05-15 15:01:17 -07001930
James Feist4131aea2018-03-09 09:47:30 -08001931 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1932 watchI2cBusses);
1933 };
1934
1935 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001936 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001937 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001938
James Feist3cb5fec2018-01-23 14:41:51 -08001939 io.run();
1940 return 0;
1941}