blob: 76da2d3b08493b64109d7293058256853568feaf [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*/
16
Patrick Venturea49dc332019-10-26 08:32:02 -070017#include "Utils.hpp"
18
James Feist3b860982018-10-02 14:34:07 -070019#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080020#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070021#include <sys/inotify.h>
22#include <sys/ioctl.h>
23
James Feist3b860982018-10-02 14:34:07 -070024#include <boost/algorithm/string/predicate.hpp>
25#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070026#include <nlohmann/json.hpp>
27#include <sdbusplus/asio/connection.hpp>
28#include <sdbusplus/asio/object_server.hpp>
29
30#include <array>
James Feist3b860982018-10-02 14:34:07 -070031#include <chrono>
32#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070033#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070035#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080036#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070037#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080038#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070039#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080040#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070041#include <set>
42#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070043#include <string>
James Feist3b860982018-10-02 14:34:07 -070044#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080045#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080046#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070047#include <vector>
James Feist3b860982018-10-02 14:34:07 -070048
James Feist8c505da2020-05-28 10:06:33 -070049extern "C"
50{
James Feist3b860982018-10-02 14:34:07 -070051#include <i2c/smbus.h>
52#include <linux/i2c-dev.h>
53}
James Feist3cb5fec2018-01-23 14:41:51 -080054
Ed Tanous072e25d2018-12-16 21:45:20 -080055namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080056static constexpr bool DEBUG = false;
57static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070058constexpr size_t MAX_FRU_SIZE = 512;
59constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070060constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080061
Patrick Venture11f1ff42019-08-01 10:42:12 -070062constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
63
James Feista465ccc2019-02-08 12:51:01 -080064const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080065 "/etc/fru/baseboard.fru.bin";
66
James Feista465ccc2019-02-08 12:51:01 -080067const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080068
James Feista465ccc2019-02-08 12:51:01 -080069static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080070 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070071const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030072using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080073using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
74
James Feist444830e2019-04-05 08:38:16 -070075static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070076struct FindDevicesWithCallback;
77
Nikhil Potaded8884f12019-03-27 13:27:13 -070078static BusMap busMap;
79
James Feistcb5661d2020-06-12 15:05:01 -070080static bool powerIsOn = false;
81
James Feist8a983922019-10-24 17:11:56 -070082static boost::container::flat_map<
83 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
84 foundDevices;
85
James Feist7972bb92019-11-13 15:59:24 -080086static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
87
James Feist5cb06082019-10-24 17:11:13 -070088boost::asio::io_service io;
89auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
90auto objServer = sdbusplus::asio::object_server(systemBus);
91
Joshi-Mansid73b7442020-03-27 19:10:21 +053092static const std::vector<const char*> CHASSIS_FRU_AREAS = {
93 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
94
95static const std::vector<const char*> BOARD_FRU_AREAS = {
96 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
97 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
98
99static const std::vector<const char*> PRODUCT_FRU_AREAS = {
100 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION", "SERIAL_NUMBER",
101 "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
102
Patrick Venturebaba7672019-10-26 09:26:41 -0700103bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Joshi-Mansid73b7442020-03-27 19:10:21 +0530104bool updateFruProperty(
105 const std::string& assetTag, uint32_t bus, uint32_t address,
106 std::string propertyName,
107 boost::container::flat_map<
108 std::pair<size_t, size_t>,
109 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700110
Xiang Liu2801a702020-01-20 14:29:34 -0800111using ReadBlockFunc =
112 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
113 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700114
115// Read and validate FRU contents, given the flag required for raw i2c, the open
116// file handle, a read method, and a helper string for failures.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300117std::vector<uint8_t> readFruContents(int flag, int file, uint16_t address,
118 ReadBlockFunc readBlock,
119 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700120{
121 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
122
Xiang Liu2801a702020-01-20 14:29:34 -0800123 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700124 {
125 std::cerr << "failed to read " << errorHelp << "\n";
126 return {};
127 }
128
129 // check the header checksum
130 if (!validateHeader(blockData))
131 {
132 if (DEBUG)
133 {
134 std::cerr << "Illegal header " << errorHelp << "\n";
135 }
136
137 return {};
138 }
139
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300140 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700141 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
142
Patrick Venturee26395d2019-10-29 14:05:16 -0700143 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700144 int fruLength = 0;
145 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
146 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700147 // Offset value can be 255.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300148 int areaOffset = device[jj];
Patrick Venturebaba7672019-10-26 09:26:41 -0700149 if (areaOffset == 0)
150 {
151 continue;
152 }
153
Patrick Venturee26395d2019-10-29 14:05:16 -0700154 // MultiRecords are different. jj is not tracking section, it's walking
155 // the common header.
156 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
157 {
158 hasMultiRecords = true;
159 break;
160 }
161
Patrick Venturebaba7672019-10-26 09:26:41 -0700162 areaOffset *= 8;
163
Xiang Liu2801a702020-01-20 14:29:34 -0800164 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
165 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700166 {
167 std::cerr << "failed to read " << errorHelp << "\n";
168 return {};
169 }
170
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700171 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700172 int length = blockData[1] * 8;
173 areaOffset += length;
174 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
175 }
176
Patrick Venturee26395d2019-10-29 14:05:16 -0700177 if (hasMultiRecords)
178 {
179 // device[area count] is the index to the last area because the 0th
180 // entry is not an offset in the common header.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300181 int areaOffset = device[FRU_AREAS.size()];
Patrick Venturee26395d2019-10-29 14:05:16 -0700182 areaOffset *= 8;
183
184 // the multi-area record header is 5 bytes long.
185 constexpr int multiRecordHeaderSize = 5;
186 constexpr int multiRecordEndOfList = 0x80;
187
188 // Sanity hard-limit to 64KB.
189 while (areaOffset < std::numeric_limits<uint16_t>::max())
190 {
191 // In multi-area, the area offset points to the 0th record, each
192 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800193 if (readBlock(flag, file, address,
194 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700195 blockData.data()) < 0)
196 {
197 std::cerr << "failed to read " << errorHelp << "\n";
198 return {};
199 }
200
201 // Ok, let's check the record length, which is in bytes (unsigned,
202 // up to 255, so blockData should hold uint8_t not char)
203 int recordLength = blockData[2];
204 areaOffset += (recordLength + multiRecordHeaderSize);
205 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
206
207 // If this is the end of the list bail.
208 if ((blockData[1] & multiRecordEndOfList))
209 {
210 break;
211 }
212 }
213 }
214
Patrick Venturebaba7672019-10-26 09:26:41 -0700215 // You already copied these first 8 bytes (the ipmi fru header size)
216 fruLength -= 8;
217
218 int readOffset = 8;
219
220 while (fruLength > 0)
221 {
222 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
223
Xiang Liu2801a702020-01-20 14:29:34 -0800224 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700225 static_cast<uint8_t>(requestLength),
226 blockData.data()) < 0)
227 {
228 std::cerr << "failed to read " << errorHelp << "\n";
229 return {};
230 }
231
232 device.insert(device.end(), blockData.begin(),
233 blockData.begin() + requestLength);
234
235 readOffset += requestLength;
236 fruLength -= requestLength;
237 }
238
239 return device;
240}
241
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700242// Given a bus/address, produce the path in sysfs for an eeprom.
243static std::string getEepromPath(size_t bus, size_t address)
244{
245 std::stringstream output;
246 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
247 << std::setfill('0') << std::setw(4) << std::hex << address
248 << "/eeprom";
249 return output.str();
250}
251
252static bool hasEepromFile(size_t bus, size_t address)
253{
254 auto path = getEepromPath(bus, address);
255 try
256 {
257 return fs::exists(path);
258 }
259 catch (...)
260 {
261 return false;
262 }
263}
264
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700265static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800266 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700267 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700268{
269 auto result = lseek(fd, offset, SEEK_SET);
270 if (result < 0)
271 {
272 std::cerr << "failed to seek\n";
273 return -1;
274 }
275
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700276 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700277}
278
James Feist5d7f4692020-06-17 18:22:33 -0700279static int busStrToInt(const std::string& busName)
280{
281 auto findBus = busName.rfind("-");
282 if (findBus == std::string::npos)
283 {
284 return -1;
285 }
286 return std::stoi(busName.substr(findBus + 1));
287}
288
James Feist7972bb92019-11-13 15:59:24 -0800289static int getRootBus(size_t bus)
290{
291 auto ec = std::error_code();
292 auto path = std::filesystem::read_symlink(
293 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
294 std::to_string(bus) + "/mux_device"),
295 ec);
296 if (ec)
297 {
298 return -1;
299 }
300
301 std::string filename = path.filename();
302 auto findBus = filename.find("-");
303 if (findBus == std::string::npos)
304 {
305 return -1;
306 }
307 return std::stoi(filename.substr(0, findBus));
308}
309
James Feistc95cb142018-02-26 10:41:42 -0800310static bool isMuxBus(size_t bus)
311{
Ed Tanous072e25d2018-12-16 21:45:20 -0800312 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800313 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
314}
315
James Feist8a983922019-10-24 17:11:56 -0700316static void makeProbeInterface(size_t bus, size_t address)
317{
318 if (isMuxBus(bus))
319 {
320 return; // the mux buses are random, no need to publish
321 }
322 auto [it, success] = foundDevices.emplace(
323 std::make_pair(bus, address),
324 objServer.add_interface(
325 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
326 std::to_string(address),
327 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
328 if (!success)
329 {
330 return; // already added
331 }
332 it->second->register_property("Bus", bus);
333 it->second->register_property("Address", address);
334 it->second->initialize();
335}
336
Vijay Khemka2d681f62018-11-06 15:51:00 -0800337static int isDevice16Bit(int file)
338{
339 /* Get first byte */
340 int byte1 = i2c_smbus_read_byte_data(file, 0);
341 if (byte1 < 0)
342 {
343 return byte1;
344 }
345 /* Read 7 more bytes, it will read same first byte in case of
346 * 8 bit but it will read next byte in case of 16 bit
347 */
348 for (int i = 0; i < 7; i++)
349 {
350 int byte2 = i2c_smbus_read_byte_data(file, 0);
351 if (byte2 < 0)
352 {
353 return byte2;
354 }
355 if (byte2 != byte1)
356 {
357 return 1;
358 }
359 }
360 return 0;
361}
362
Xiang Liu2801a702020-01-20 14:29:34 -0800363// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
364// from_slave_buf_len bytes.
365static int i2c_smbus_write_then_read(int file, uint16_t address,
366 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
367 uint8_t* fromSlaveBuf,
368 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800369{
Xiang Liu2801a702020-01-20 14:29:34 -0800370 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
371 fromSlaveBufLen == 0)
372 {
373 return -1;
374 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800375
Xiang Liu2801a702020-01-20 14:29:34 -0800376#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
377 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
378 struct i2c_rdwr_ioctl_data rdwr;
379
380 msgs[0].addr = address;
381 msgs[0].flags = 0;
382 msgs[0].len = toSlaveBufLen;
383 msgs[0].buf = toSlaveBuf;
384 msgs[1].addr = address;
385 msgs[1].flags = I2C_M_RD;
386 msgs[1].len = fromSlaveBufLen;
387 msgs[1].buf = fromSlaveBuf;
388
389 rdwr.msgs = msgs;
390 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
391
392 int ret = ioctl(file, I2C_RDWR, &rdwr);
393
394 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
395}
396
397static int64_t readBlockData(int flag, int file, uint16_t address,
398 uint16_t offset, uint8_t len, uint8_t* buf)
399{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800400 if (flag == 0)
401 {
Xiang Liu2801a702020-01-20 14:29:34 -0800402 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
403 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800404 }
405
Xiang Liu2801a702020-01-20 14:29:34 -0800406 offset = htobe16(offset);
407 return i2c_smbus_write_then_read(
408 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800409}
410
James Feist24bae7a2019-04-03 09:50:56 -0700411bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
412{
413 // ipmi spec format version number is currently at 1, verify it
414 if (blockData[0] != 0x1)
415 {
416 return false;
417 }
418
419 // verify pad is set to 0
420 if (blockData[6] != 0x0)
421 {
422 return false;
423 }
424
425 // verify offsets are 0, or don't point to another offset
426 std::set<uint8_t> foundOffsets;
427 for (int ii = 1; ii < 6; ii++)
428 {
429 if (blockData[ii] == 0)
430 {
431 continue;
432 }
James Feist0eb40352019-04-09 14:44:04 -0700433 auto inserted = foundOffsets.insert(blockData[ii]);
434 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700435 {
436 return false;
437 }
438 }
439
440 // validate checksum
441 size_t sum = 0;
442 for (int jj = 0; jj < 7; jj++)
443 {
444 sum += blockData[jj];
445 }
446 sum = (256 - sum) & 0xFF;
447
448 if (sum != blockData[7])
449 {
450 return false;
451 }
452 return true;
453}
454
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700455// TODO: This code is very similar to the non-eeprom version and can be merged
456// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300457static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700458{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700459 auto path = getEepromPath(bus, address);
460
461 int file = open(path.c_str(), O_RDONLY);
462 if (file < 0)
463 {
464 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700465 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700466 }
467
Patrick Venturebaba7672019-10-26 09:26:41 -0700468 std::string errorMessage = "eeprom at " + std::to_string(bus) +
469 " address " + std::to_string(address);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300470 std::vector<uint8_t> device = readFruContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800471 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700472
473 close(file);
474 return device;
475}
476
477std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
478{
479 std::set<int> foundList;
480
481 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
482
483 // For each file listed under the i2c device
484 // NOTE: This should be faster than just checking for each possible address
485 // path.
486 for (const auto& p : fs::directory_iterator(path))
487 {
488 const std::string node = p.path().string();
489 std::smatch m;
490 bool found =
491 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
492
493 if (!found)
494 {
495 continue;
496 }
497 if (m.size() != 2)
498 {
499 std::cerr << "regex didn't capture\n";
500 continue;
501 }
502
503 std::ssub_match subMatch = m[1];
504 std::string addressString = subMatch.str();
505
506 std::size_t ignored;
507 const int hexBase = 16;
508 int address = std::stoi(addressString, &ignored, hexBase);
509
510 const std::string eeprom = node + "/eeprom";
511
512 try
513 {
514 if (!fs::exists(eeprom))
515 {
516 continue;
517 }
518 }
519 catch (...)
520 {
521 continue;
522 }
523
524 // There is an eeprom file at this address, it may have invalid
525 // contents, but we found it.
526 foundList.insert(address);
527
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300528 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700529 if (!device.empty())
530 {
531 devices->emplace(address, device);
532 }
533 }
534
535 return foundList;
536}
537
Patrick Venture4f47fe62019-08-08 16:30:38 -0700538int getBusFrus(int file, int first, int last, int bus,
539 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800540{
James Feist3cb5fec2018-01-23 14:41:51 -0800541
James Feist26c27ad2018-07-25 15:09:40 -0700542 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700543 // NOTE: When reading the devices raw on the bus, it can interfere with
544 // the driver's ability to operate, therefore read eeproms first before
545 // scanning for devices without drivers. Several experiments were run
546 // and it was determined that if there were any devices on the bus
547 // before the eeprom was hit and read, the eeprom driver wouldn't open
548 // while the bus device was open. An experiment was not performed to see
549 // if this issue was resolved if the i2c bus device was closed, but
550 // hexdumps of the eeprom later were successful.
551
552 // Scan for i2c eeproms loaded on this bus.
553 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800554 std::set<size_t>& failedItems = failedAddresses[bus];
555
556 std::set<size_t>* rootFailures = nullptr;
557 int rootBus = getRootBus(bus);
558
559 if (rootBus >= 0)
560 {
561 rootFailures = &(failedAddresses[rootBus]);
562 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700563
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530564 constexpr int startSkipSlaveAddr = 0;
565 constexpr int endSkipSlaveAddr = 12;
566
James Feist26c27ad2018-07-25 15:09:40 -0700567 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800568 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700569 if (skipList.find(ii) != skipList.end())
570 {
571 continue;
572 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530573 // skipping since no device is present in this range
574 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
575 {
576 continue;
577 }
James Feist26c27ad2018-07-25 15:09:40 -0700578 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530579 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800580 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700581 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700582 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700583 continue;
584 }
585 // probe
586 else if (i2c_smbus_read_byte(file) < 0)
587 {
588 continue;
589 }
James Feist3cb5fec2018-01-23 14:41:51 -0800590
James Feist26c27ad2018-07-25 15:09:40 -0700591 if (DEBUG)
592 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700593 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700594 << "\n";
595 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800596
James Feist8a983922019-10-24 17:11:56 -0700597 makeProbeInterface(bus, ii);
598
James Feist7972bb92019-11-13 15:59:24 -0800599 if (failedItems.find(ii) != failedItems.end())
600 {
601 // if we failed to read it once, unlikely we can read it later
602 continue;
603 }
604
605 if (rootFailures != nullptr)
606 {
607 if (rootFailures->find(ii) != rootFailures->end())
608 {
609 continue;
610 }
611 }
612
Vijay Khemka2d681f62018-11-06 15:51:00 -0800613 /* Check for Device type if it is 8 bit or 16 bit */
614 int flag = isDevice16Bit(file);
615 if (flag < 0)
616 {
617 std::cerr << "failed to read bus " << bus << " address " << ii
618 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700619 if (powerIsOn)
620 {
621 failedItems.insert(ii);
622 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800623 continue;
624 }
625
Patrick Venturebaba7672019-10-26 09:26:41 -0700626 std::string errorMessage =
627 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300628 std::vector<uint8_t> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800629 readFruContents(flag, file, static_cast<uint16_t>(ii),
630 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700631 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700632 {
James Feist26c27ad2018-07-25 15:09:40 -0700633 continue;
634 }
James Feist26c27ad2018-07-25 15:09:40 -0700635
Patrick Venture786f1792019-08-05 16:33:44 -0700636 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800637 }
James Feist26c27ad2018-07-25 15:09:40 -0700638 return 1;
639 });
640 std::future_status status =
641 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
642 if (status == std::future_status::timeout)
643 {
644 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700645 if (powerIsOn)
646 {
647 busBlacklist.insert(bus);
648 }
James Feist444830e2019-04-05 08:38:16 -0700649 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700650 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800651 }
652
James Feist444830e2019-04-05 08:38:16 -0700653 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700654 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800655}
656
Patrick Venture11f1ff42019-08-01 10:42:12 -0700657void loadBlacklist(const char* path)
658{
659 std::ifstream blacklistStream(path);
660 if (!blacklistStream.good())
661 {
662 // File is optional.
663 std::cerr << "Cannot open blacklist file.\n\n";
664 return;
665 }
666
667 nlohmann::json data =
668 nlohmann::json::parse(blacklistStream, nullptr, false);
669 if (data.is_discarded())
670 {
671 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
672 "exiting\n";
673 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700674 }
675
676 // It's expected to have at least one field, "buses" that is an array of the
677 // buses by integer. Allow for future options to exclude further aspects,
678 // such as specific addresses or ranges.
679 if (data.type() != nlohmann::json::value_t::object)
680 {
681 std::cerr << "Illegal blacklist, expected to read dictionary\n";
682 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700683 }
684
685 // If buses field is missing, that's fine.
686 if (data.count("buses") == 1)
687 {
688 // Parse the buses array after a little validation.
689 auto buses = data.at("buses");
690 if (buses.type() != nlohmann::json::value_t::array)
691 {
692 // Buses field present but invalid, therefore this is an error.
693 std::cerr << "Invalid contents for blacklist buses field\n";
694 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700695 }
696
697 // Catch exception here for type mis-match.
698 try
699 {
700 for (const auto& bus : buses)
701 {
702 busBlacklist.insert(bus.get<size_t>());
703 }
704 }
705 catch (const nlohmann::detail::type_error& e)
706 {
707 // Type mis-match is a critical error.
708 std::cerr << "Invalid bus type: " << e.what() << "\n";
709 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700710 }
711 }
712
713 return;
714}
715
James Feista465ccc2019-02-08 12:51:01 -0800716static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700717 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800718{
James Feista465ccc2019-02-08 12:51:01 -0800719 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800720 {
James Feist5d7f4692020-06-17 18:22:33 -0700721 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800722
James Feist5d7f4692020-06-17 18:22:33 -0700723 if (bus < 0)
724 {
725 std::cerr << "Cannot translate " << i2cBus << " to int\n";
726 continue;
727 }
James Feist444830e2019-04-05 08:38:16 -0700728 if (busBlacklist.find(bus) != busBlacklist.end())
729 {
730 continue; // skip previously failed busses
731 }
James Feist3cb5fec2018-01-23 14:41:51 -0800732
James Feist0c3980a2019-12-19 11:09:27 -0800733 int rootBus = getRootBus(bus);
734 if (busBlacklist.find(rootBus) != busBlacklist.end())
735 {
736 continue;
737 }
738
James Feist3cb5fec2018-01-23 14:41:51 -0800739 auto file = open(i2cBus.c_str(), O_RDWR);
740 if (file < 0)
741 {
742 std::cerr << "unable to open i2c device " << i2cBus.string()
743 << "\n";
744 continue;
745 }
746 unsigned long funcs = 0;
747
748 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
749 {
750 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700751 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800752 << bus << "\n";
753 continue;
754 }
755 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
756 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
757 {
758 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
759 << bus << "\n";
760 continue;
761 }
James Feist98132792019-07-09 13:29:09 -0700762 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800763 device = std::make_shared<DeviceMap>();
764
Nikhil Potaded8884f12019-03-27 13:27:13 -0700765 // i2cdetect by default uses the range 0x03 to 0x77, as
766 // this is what we have tested with, use this range. Could be
767 // changed in future.
768 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800769 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700770 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800771 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700772
773 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700774 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700775
776 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800777 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700778 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800779 }
James Feist3cb5fec2018-01-23 14:41:51 -0800780 }
James Feist3cb5fec2018-01-23 14:41:51 -0800781}
782
James Feist6ebf9de2018-05-15 15:01:17 -0700783// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700784struct FindDevicesWithCallback :
785 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700786{
James Feista465ccc2019-02-08 12:51:01 -0800787 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700788 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800789 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700790 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700791 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700792 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700793 ~FindDevicesWithCallback()
794 {
795 _callback();
796 }
797 void run()
798 {
James Feist98132792019-07-09 13:29:09 -0700799 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700800 }
801
James Feista465ccc2019-02-08 12:51:01 -0800802 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800803 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700804 std::function<void(void)> _callback;
805};
806
James Feist3cb5fec2018-01-23 14:41:51 -0800807static const std::tm intelEpoch(void)
808{
James Feist98132792019-07-09 13:29:09 -0700809 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800810 val.tm_year = 1996 - 1900;
811 return val;
812}
813
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800814static char sixBitToChar(uint8_t val)
815{
816 return static_cast<char>((val & 0x3f) + ' ');
817}
818
819/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
820static const char bcdHighChars[] = {
821 ' ', '-', '.', 'X', 'X', 'X',
822};
823
824static char bcdPlusToChar(uint8_t val)
825{
826 val &= 0xf;
827 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
828}
829
830enum class DecodeState
831{
832 ok,
833 end,
834 err,
835};
836
837enum FRUDataEncoding
838{
839 binary = 0x0,
840 bcdPlus = 0x1,
841 sixBitASCII = 0x2,
842 languageDependent = 0x3,
843};
844
845/* Decode FRU data into a std::string, given an input iterator and end. If the
846 * state returned is fruDataOk, then the resulting string is the decoded FRU
847 * data. The input iterator is advanced past the data consumed.
848 *
849 * On fruDataErr, we have lost synchronisation with the length bytes, so the
850 * iterator is no longer usable.
851 */
852static std::pair<DecodeState, std::string>
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300853 decodeFruData(std::vector<uint8_t>::const_iterator& iter,
854 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800855{
856 std::string value;
857 unsigned int i;
858
859 /* we need at least one byte to decode the type/len header */
860 if (iter == end)
861 {
862 std::cerr << "Truncated FRU data\n";
863 return make_pair(DecodeState::err, value);
864 }
865
866 uint8_t c = *(iter++);
867
868 /* 0xc1 is the end marker */
869 if (c == 0xc1)
870 {
871 return make_pair(DecodeState::end, value);
872 }
873
874 /* decode type/len byte */
875 uint8_t type = static_cast<uint8_t>(c >> 6);
876 uint8_t len = static_cast<uint8_t>(c & 0x3f);
877
878 /* we should have at least len bytes of data available overall */
879 if (iter + len > end)
880 {
881 std::cerr << "FRU data field extends past end of FRU data\n";
882 return make_pair(DecodeState::err, value);
883 }
884
885 switch (type)
886 {
887 case FRUDataEncoding::binary:
888 case FRUDataEncoding::languageDependent:
889 /* For language-code dependent encodings, assume 8-bit ASCII */
890 value = std::string(iter, iter + len);
891 iter += len;
892 break;
893
894 case FRUDataEncoding::bcdPlus:
895 value = std::string();
896 for (i = 0; i < len; i++, iter++)
897 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300898 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800899 value.push_back(bcdPlusToChar(val >> 4));
900 value.push_back(bcdPlusToChar(val & 0xf));
901 }
902 break;
903
904 case FRUDataEncoding::sixBitASCII:
905 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300906 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800907 unsigned int accumBitLen = 0;
908 value = std::string();
909 for (i = 0; i < len; i++, iter++)
910 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300911 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800912 accumBitLen += 8;
913 while (accumBitLen >= 6)
914 {
915 value.push_back(sixBitToChar(accum & 0x3f));
916 accum >>= 6;
917 accumBitLen -= 6;
918 }
919 }
920 }
921 break;
922 }
923
924 return make_pair(DecodeState::ok, value);
925}
926
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300927bool formatFru(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800928 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800929{
James Feistd068e932018-09-20 10:53:07 -0700930 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800931 {
932 return false;
933 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300934 std::vector<uint8_t>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700935 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800936 std::to_string(static_cast<int>(*fruAreaOffsetField));
937
James Feista465ccc2019-02-08 12:51:01 -0800938 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800939
James Feist0eb40352019-04-09 14:44:04 -0700940 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800941 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700942 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800943 if (fruAreaOffsetField >= fruBytes.end())
944 {
945 return false;
946 }
947 size_t offset = (*fruAreaOffsetField) * 8;
948
949 if (offset > 1)
950 {
951 // +2 to skip format and length
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300952 std::vector<uint8_t>::const_iterator fruBytesIter =
James Feist3cb5fec2018-01-23 14:41:51 -0800953 fruBytes.begin() + offset + 2;
954
955 if (fruBytesIter >= fruBytes.end())
956 {
957 return false;
958 }
959
960 if (area == "CHASSIS")
961 {
962 result["CHASSIS_TYPE"] =
963 std::to_string(static_cast<int>(*fruBytesIter));
964 fruBytesIter += 1;
965 fieldData = &CHASSIS_FRU_AREAS;
966 }
967 else if (area == "BOARD")
968 {
969 result["BOARD_LANGUAGE_CODE"] =
970 std::to_string(static_cast<int>(*fruBytesIter));
971 fruBytesIter += 1;
972 if (fruBytesIter >= fruBytes.end())
973 {
974 return false;
975 }
976
977 unsigned int minutes = *fruBytesIter |
978 *(fruBytesIter + 1) << 8 |
979 *(fruBytesIter + 2) << 16;
980 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700981 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800982 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700983 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800984
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700985 // Tue Nov 20 23:08:00 2018
986 char timeString[32] = {0};
987 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700988 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700989 if (bytes == 0)
990 {
991 std::cerr << "invalid time string encountered\n";
992 return false;
993 }
994
995 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800996 fruBytesIter += 3;
997 fieldData = &BOARD_FRU_AREAS;
998 }
999 else if (area == "PRODUCT")
1000 {
1001 result["PRODUCT_LANGUAGE_CODE"] =
1002 std::to_string(static_cast<int>(*fruBytesIter));
1003 fruBytesIter += 1;
1004 fieldData = &PRODUCT_FRU_AREAS;
1005 }
1006 else
1007 {
1008 continue;
1009 }
James Feista465ccc2019-02-08 12:51:01 -08001010 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -08001011 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001012 auto res = decodeFruData(fruBytesIter, fruBytes.end());
1013 std::string name = area + "_" + field;
James Feist3cb5fec2018-01-23 14:41:51 -08001014
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001015 if (res.first == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001016 {
1017 break;
1018 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001019 else if (res.first == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001020 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001021 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001022 return false;
1023 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001024
1025 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001026
Ed Tanous2147e672019-02-27 13:59:56 -08001027 // Strip non null characters from the end
1028 value.erase(std::find_if(value.rbegin(), value.rend(),
1029 [](char ch) { return ch != 0; })
1030 .base(),
1031 value.end());
1032
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001033 result[name] = std::move(value);
James Feist3cb5fec2018-01-23 14:41:51 -08001034 }
1035 }
1036 }
1037
1038 return true;
1039}
1040
Nikhil Potaded8884f12019-03-27 13:27:13 -07001041std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
1042{
1043 auto deviceMap = busMap.find(bus);
1044 if (deviceMap == busMap.end())
1045 {
1046 throw std::invalid_argument("Invalid Bus.");
1047 }
1048 auto device = deviceMap->second->find(address);
1049 if (device == deviceMap->second->end())
1050 {
1051 throw std::invalid_argument("Invalid Address.");
1052 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001053 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001054
1055 return ret;
1056}
1057
James Feist3cb5fec2018-01-23 14:41:51 -08001058void AddFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001059 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001060 boost::container::flat_map<
1061 std::pair<size_t, size_t>,
1062 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001063 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001064{
1065 boost::container::flat_map<std::string, std::string> formattedFru;
1066 if (!formatFru(device, formattedFru))
1067 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001068 std::cerr << "failed to format fru for device at bus " << bus
1069 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001070 return;
1071 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001072
James Feist3cb5fec2018-01-23 14:41:51 -08001073 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
1074 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001075 // Not found under Board section or an empty string.
1076 if (productNameFind == formattedFru.end() ||
1077 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001078 {
1079 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
1080 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001081 // Found under Product section and not an empty string.
1082 if (productNameFind != formattedFru.end() &&
1083 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001084 {
1085 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001086 std::regex illegalObject("[^A-Za-z0-9_]");
1087 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001088 }
1089 else
1090 {
1091 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1092 UNKNOWN_BUS_OBJECT_COUNT++;
1093 }
1094
James Feist918e18c2018-02-13 15:51:07 -08001095 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001096 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001097 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001098 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001099 int highest = -1;
1100 bool found = false;
1101
James Feista465ccc2019-02-08 12:51:01 -08001102 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001103 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001104 std::string path = busIface.second->get_object_path();
1105 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001106 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001107 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -07001108 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
1109 static_cast<uint8_t>(busIface.first.second)) ==
1110 getFruInfo(static_cast<uint8_t>(bus),
1111 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001112 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001113 // This device is already added to the lower numbered bus,
1114 // do not replicate it.
1115 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001116 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001117
1118 // Check if the match named has extra information.
1119 found = true;
1120 std::smatch base_match;
1121
1122 bool match = std::regex_match(
1123 path, base_match, std::regex(productName + "_(\\d+)$"));
1124 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001125 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001126 if (base_match.size() == 2)
1127 {
1128 std::ssub_match base_sub_match = base_match[1];
1129 std::string base = base_sub_match.str();
1130
1131 int value = std::stoi(base);
1132 highest = (value > highest) ? value : highest;
1133 }
James Feist79e9c0b2018-03-15 15:21:17 -07001134 }
James Feist918e18c2018-02-13 15:51:07 -08001135 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001136 } // end searching objects
1137
1138 if (found)
1139 {
1140 // We found something with the same name. If highest was still -1,
1141 // it means this new entry will be _0.
1142 productName += "_";
1143 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001144 }
1145 }
James Feist3cb5fec2018-01-23 14:41:51 -08001146
James Feist9eb0b582018-04-27 12:15:46 -07001147 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1148 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1149 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1150
James Feista465ccc2019-02-08 12:51:01 -08001151 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001152 {
James Feist9eb0b582018-04-27 12:15:46 -07001153
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001154 std::regex_replace(property.second.begin(), property.second.begin(),
1155 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301156 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001157 {
1158 continue;
1159 }
1160 std::string key =
1161 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301162
1163 if (property.first == "PRODUCT_ASSET_TAG")
1164 {
1165 std::string propertyName = property.first;
1166 iface->register_property(
1167 key, property.second + '\0',
1168 [bus, address, propertyName,
1169 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1170 if (strcmp(req.c_str(), resp.c_str()))
1171 {
1172 // call the method which will update
1173 if (updateFruProperty(req, bus, address, propertyName,
1174 dbusInterfaceMap))
1175 {
1176 resp = req;
1177 }
1178 else
1179 {
1180 throw std::invalid_argument(
1181 "Fru property update failed.");
1182 }
1183 }
1184 return 1;
1185 });
1186 }
1187 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001188 {
1189 std::cerr << "illegal key: " << key << "\n";
1190 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001191 if (DEBUG)
1192 {
1193 std::cout << property.first << ": " << property.second << "\n";
1194 }
James Feist3cb5fec2018-01-23 14:41:51 -08001195 }
James Feist2a9d6db2018-04-27 15:48:28 -07001196
1197 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001198 iface->register_property("BUS", bus);
1199 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001200
James Feist9eb0b582018-04-27 12:15:46 -07001201 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001202}
1203
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001204static bool readBaseboardFru(std::vector<uint8_t>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001205{
1206 // try to read baseboard fru from file
1207 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1208 if (baseboardFruFile.good())
1209 {
1210 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001211 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001212 baseboardFru.resize(fileSize);
1213 baseboardFruFile.seekg(0, std::ios_base::beg);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001214 baseboardFruFile.read(reinterpret_cast<char*>(baseboardFru.data()),
1215 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001216 }
1217 else
1218 {
1219 return false;
1220 }
1221 return true;
1222}
1223
James Feista465ccc2019-02-08 12:51:01 -08001224bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001225{
1226 boost::container::flat_map<std::string, std::string> tmp;
1227 if (fru.size() > MAX_FRU_SIZE)
1228 {
1229 std::cerr << "Invalid fru.size() during writeFru\n";
1230 return false;
1231 }
1232 // verify legal fru by running it through fru parsing logic
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001233 if (!formatFru(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001234 {
1235 std::cerr << "Invalid fru format during writeFru\n";
1236 return false;
1237 }
1238 // baseboard fru
1239 if (bus == 0 && address == 0)
1240 {
1241 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1242 if (!file.good())
1243 {
1244 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1245 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001246 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001247 return false;
1248 }
James Feista465ccc2019-02-08 12:51:01 -08001249 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001250 return file.good();
1251 }
1252 else
1253 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001254 if (hasEepromFile(bus, address))
1255 {
1256 auto path = getEepromPath(bus, address);
1257 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1258 if (eeprom < 0)
1259 {
1260 std::cerr << "unable to open i2c device " << path << "\n";
1261 throw DBusInternalError();
1262 return false;
1263 }
1264
1265 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1266 if (writtenBytes < 0)
1267 {
1268 std::cerr << "unable to write to i2c device " << path << "\n";
1269 close(eeprom);
1270 throw DBusInternalError();
1271 return false;
1272 }
1273
1274 close(eeprom);
1275 return true;
1276 }
1277
James Feistb49ffc32018-05-02 11:10:43 -07001278 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1279
1280 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1281 if (file < 0)
1282 {
1283 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001284 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001285 return false;
1286 }
1287 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1288 {
1289 std::cerr << "unable to set device address\n";
1290 close(file);
James Feistddb78302018-09-06 11:45:42 -07001291 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001292 return false;
1293 }
1294
1295 constexpr const size_t RETRY_MAX = 2;
1296 uint16_t index = 0;
1297 size_t retries = RETRY_MAX;
1298 while (index < fru.size())
1299 {
1300 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1301 (retries == RETRY_MAX))
1302 {
1303 // The 4K EEPROM only uses the A2 and A1 device address bits
1304 // with the third bit being a memory page address bit.
1305 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1306 {
1307 std::cerr << "unable to set device address\n";
1308 close(file);
James Feistddb78302018-09-06 11:45:42 -07001309 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001310 return false;
1311 }
1312 }
1313
James Feist98132792019-07-09 13:29:09 -07001314 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1315 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001316 {
1317 if (!retries--)
1318 {
1319 std::cerr << "error writing fru: " << strerror(errno)
1320 << "\n";
1321 close(file);
James Feistddb78302018-09-06 11:45:42 -07001322 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001323 return false;
1324 }
1325 }
1326 else
1327 {
1328 retries = RETRY_MAX;
1329 index++;
1330 }
1331 // most eeproms require 5-10ms between writes
1332 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1333 }
1334 close(file);
1335 return true;
1336 }
1337}
1338
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001339void rescanOneBus(
1340 BusMap& busmap, uint8_t busNum,
1341 boost::container::flat_map<
1342 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001343 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1344 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001345{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001346 for (auto& [pair, interface] : foundDevices)
1347 {
1348 if (pair.first == static_cast<size_t>(busNum))
1349 {
1350 objServer.remove_interface(interface);
1351 foundDevices.erase(pair);
1352 }
1353 }
1354
James Feist5d7f4692020-06-17 18:22:33 -07001355 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1356 if (!fs::exists(busPath))
1357 {
1358 if (dbusCall)
1359 {
1360 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1361 << "\n";
1362 throw std::invalid_argument("Invalid Bus.");
1363 }
1364 return;
1365 }
1366
1367 std::vector<fs::path> i2cBuses;
1368 i2cBuses.emplace_back(busPath);
1369
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001370 auto scan = std::make_shared<FindDevicesWithCallback>(
1371 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1372 for (auto& busIface : dbusInterfaceMap)
1373 {
1374 if (busIface.first.first == static_cast<size_t>(busNum))
1375 {
1376 objServer.remove_interface(busIface.second);
1377 }
1378 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001379 auto found = busmap.find(busNum);
1380 if (found == busmap.end() || found->second == nullptr)
1381 {
1382 return;
1383 }
1384 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001385 {
1386 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1387 static_cast<uint32_t>(busNum), device.first);
1388 }
1389 });
1390 scan->run();
1391}
1392
James Feist9eb0b582018-04-27 12:15:46 -07001393void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001394 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001395 boost::container::flat_map<
1396 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001397 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001398{
James Feist6ebf9de2018-05-15 15:01:17 -07001399 static boost::asio::deadline_timer timer(io);
1400 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001401
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001402 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001403 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001404 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001405 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001406
Nikhil Potaded8884f12019-03-27 13:27:13 -07001407 boost::container::flat_map<size_t, fs::path> busPaths;
1408 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001409 {
James Feist4131aea2018-03-09 09:47:30 -08001410 std::cerr << "unable to find i2c devices\n";
1411 return;
James Feist918e18c2018-02-13 15:51:07 -08001412 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001413
1414 for (auto busPath : busPaths)
1415 {
1416 i2cBuses.emplace_back(busPath.second);
1417 }
James Feist4131aea2018-03-09 09:47:30 -08001418
James Feist98132792019-07-09 13:29:09 -07001419 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001420 for (auto& [pair, interface] : foundDevices)
1421 {
1422 objServer.remove_interface(interface);
1423 }
1424 foundDevices.clear();
1425
James Feist5cb06082019-10-24 17:11:13 -07001426 auto scan =
1427 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001428 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001429 {
1430 objServer.remove_interface(busIface.second);
1431 }
James Feist4131aea2018-03-09 09:47:30 -08001432
James Feist6ebf9de2018-05-15 15:01:17 -07001433 dbusInterfaceMap.clear();
1434 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001435
James Feist6ebf9de2018-05-15 15:01:17 -07001436 // todo, get this from a more sensable place
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001437 std::vector<uint8_t> baseboardFru;
James Feist6ebf9de2018-05-15 15:01:17 -07001438 if (readBaseboardFru(baseboardFru))
1439 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001440 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001441 baseboardDev;
1442 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001443 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001444 }
James Feist98132792019-07-09 13:29:09 -07001445 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001446 {
James Feista465ccc2019-02-08 12:51:01 -08001447 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001448 {
James Feist5cb06082019-10-24 17:11:13 -07001449 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1450 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001451 }
1452 }
1453 });
1454 scan->run();
1455 });
James Feist918e18c2018-02-13 15:51:07 -08001456}
1457
Joshi-Mansid73b7442020-03-27 19:10:21 +05301458// Calculate new checksum for fru info area
1459size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1460{
1461 constexpr int checksumMod = 256;
1462 constexpr uint8_t modVal = 0xFF;
1463 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1464 return (checksumMod - sum) & modVal;
1465}
1466
1467// Update new fru area length &
1468// Update checksum at new checksum location
1469static void updateFruAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1470 size_t fruAreaStartOffset,
1471 size_t fruAreaNoMoreFieldOffset)
1472{
1473 constexpr size_t fruAreaMultipleBytes = 8;
1474 size_t traverseFruAreaIndex = fruAreaNoMoreFieldOffset - fruAreaStartOffset;
1475
1476 // fill zeros for any remaining unused space
1477 std::fill(fruData.begin() + fruAreaNoMoreFieldOffset, fruData.end(), 0);
1478
1479 size_t mod = traverseFruAreaIndex % fruAreaMultipleBytes;
1480 size_t checksumLoc;
1481 if (!mod)
1482 {
1483 traverseFruAreaIndex += (fruAreaMultipleBytes);
1484 checksumLoc = fruAreaNoMoreFieldOffset + (fruAreaMultipleBytes - 1);
1485 }
1486 else
1487 {
1488 traverseFruAreaIndex += (fruAreaMultipleBytes - mod);
1489 checksumLoc =
1490 fruAreaNoMoreFieldOffset + (fruAreaMultipleBytes - mod - 1);
1491 }
1492
1493 size_t newFruAreaLen = (traverseFruAreaIndex / fruAreaMultipleBytes) +
1494 ((traverseFruAreaIndex % fruAreaMultipleBytes) != 0);
1495 size_t fruAreaLengthLoc = fruAreaStartOffset + 1;
1496 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFruAreaLen);
1497
1498 // Calculate new checksum
1499 std::vector<uint8_t> finalFruData;
1500 std::copy_n(fruData.begin() + fruAreaStartOffset,
1501 checksumLoc - fruAreaStartOffset,
1502 std::back_inserter(finalFruData));
1503
1504 size_t checksumVal = calculateChecksum(finalFruData);
1505
1506 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
1507}
1508
1509static size_t getTypeLength(uint8_t fruFieldTypeLenValue)
1510{
1511 constexpr uint8_t typeLenMask = 0x3F;
1512 return fruFieldTypeLenValue & typeLenMask;
1513}
1514
1515// Details with example of Asset Tag Update
1516// To find location of Product Info Area asset tag as per FRU specification
1517// 1. Find product Info area starting offset (*8 - as header will be in
1518// multiple of 8 bytes).
1519// 2. Skip 3 bytes of product info area (like format version, area length,
1520// and language code).
1521// 3. Traverse manufacturer name, product name, product version, & product
1522// serial number, by reading type/length code to reach the Asset Tag.
1523// 4. Update the Asset Tag, reposition the product Info area in multiple of
1524// 8 bytes. Update the Product area length and checksum.
1525
1526bool updateFruProperty(
1527 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1528 std::string propertyName,
1529 boost::container::flat_map<
1530 std::pair<size_t, size_t>,
1531 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1532{
1533 size_t updatePropertyReqLen = updatePropertyReq.length();
1534 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1535 {
1536 std::cerr
1537 << "Fru field data cannot be of 1 char or more than 63 chars. "
1538 "Invalid Length "
1539 << updatePropertyReqLen << "\n";
1540 return false;
1541 }
1542
1543 std::vector<uint8_t> fruData;
1544 try
1545 {
1546 fruData = getFruInfo(static_cast<uint8_t>(bus),
1547 static_cast<uint8_t>(address));
1548 }
1549 catch (std::invalid_argument& e)
1550 {
1551 std::cerr << "Failure getting Fru Info" << e.what() << "\n";
1552 return false;
1553 }
1554
1555 if (fruData.empty())
1556 {
1557 return false;
1558 }
1559
1560 const std::vector<const char*>* fieldData;
1561
1562 constexpr size_t commonHeaderMultipleBytes = 8; // in multiple of 8 bytes
1563 uint8_t fruAreaOffsetFieldValue = 1;
1564 size_t offset = 0;
1565
1566 if (propertyName.find("CHASSIS") == 0)
1567 {
1568 constexpr size_t fruAreaOffsetField = 2;
1569 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1570
1571 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1572
1573 fieldData = &CHASSIS_FRU_AREAS;
1574 }
1575 else if (propertyName.find("BOARD") == 0)
1576 {
1577 constexpr size_t fruAreaOffsetField = 3;
1578 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1579
1580 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1581
1582 fieldData = &BOARD_FRU_AREAS;
1583 }
1584 else if (propertyName.find("PRODUCT") == 0)
1585 {
1586 constexpr size_t fruAreaOffsetField = 4;
1587 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1588
1589 offset = 3;
1590 // Manufacturer name offset. Skip fixed first 3 product fru bytes i.e.
1591 // version, area length and language code
1592
1593 fieldData = &PRODUCT_FRU_AREAS;
1594 }
1595 else
1596 {
1597 std::cerr << "ProperyName doesn't exist in Fru Area Vector \n";
1598 return false;
1599 }
1600
1601 size_t fruAreaStartOffset =
1602 fruAreaOffsetFieldValue * commonHeaderMultipleBytes;
1603 size_t fruDataIter = fruAreaStartOffset + offset;
1604 size_t fruUpdateFieldLoc = 0;
1605 size_t typeLength;
1606 size_t skipToFruUpdateField = 0;
1607
1608 for (auto& field : *fieldData)
1609 {
1610 skipToFruUpdateField++;
1611 if (propertyName.find(field) != std::string::npos)
1612 {
1613 break;
1614 }
1615 }
1616
1617 for (size_t i = 1; i < skipToFruUpdateField; i++)
1618 {
1619 typeLength = getTypeLength(fruData[fruDataIter]);
1620 fruUpdateFieldLoc = fruDataIter + typeLength;
1621 fruDataIter = ++fruUpdateFieldLoc;
1622 }
1623
1624 // Push post update fru field bytes to a vector
1625 typeLength = getTypeLength(fruData[fruUpdateFieldLoc]);
1626 size_t postFruUpdateFieldLoc = fruUpdateFieldLoc + typeLength;
1627 postFruUpdateFieldLoc++;
1628 skipToFruUpdateField++;
1629 fruDataIter = postFruUpdateFieldLoc;
1630 size_t endLengthLoc = 0;
1631 size_t fruFieldLoc = 0;
1632 constexpr uint8_t endLength = 0xC1;
1633 for (size_t i = fruDataIter; i < fruData.size(); i++)
1634 {
1635 typeLength = getTypeLength(fruData[fruDataIter]);
1636 fruFieldLoc = fruDataIter + typeLength;
1637 fruDataIter = ++fruFieldLoc;
1638 if (fruData[fruDataIter] == endLength)
1639 {
1640 endLengthLoc = fruDataIter;
1641 break;
1642 }
1643 }
1644 endLengthLoc++;
1645
1646 std::vector<uint8_t> postUpdatedFruData;
1647 std::copy_n(fruData.begin() + postFruUpdateFieldLoc,
1648 endLengthLoc - postFruUpdateFieldLoc,
1649 std::back_inserter(postUpdatedFruData));
1650
1651 // write new requested property field length and data
1652 constexpr uint8_t newTypeLenMask = 0xC0;
1653 fruData[fruUpdateFieldLoc] =
1654 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1655 fruUpdateFieldLoc++;
1656 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1657 fruData.begin() + fruUpdateFieldLoc);
1658
1659 // Copy remaining data to main fru area - post updated fru field vector
1660 postFruUpdateFieldLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1661 size_t fruAreaEndOffset = postFruUpdateFieldLoc + postUpdatedFruData.size();
1662 if (fruAreaEndOffset > fruData.size())
1663 {
1664 std::cerr << "Fru area offset: " << fruAreaEndOffset
1665 << "should not be greater than Fru data size: "
1666 << fruData.size() << std::endl;
1667 throw std::invalid_argument(
1668 "Fru area offset should not be greater than Fru data size");
1669 }
1670 std::copy(postUpdatedFruData.begin(), postUpdatedFruData.end(),
1671 fruData.begin() + postFruUpdateFieldLoc);
1672
1673 // Update final fru with new fru area length and checksum
1674 updateFruAreaLenAndChecksum(fruData, fruAreaStartOffset, fruAreaEndOffset);
1675
1676 if (fruData.empty())
1677 {
1678 return false;
1679 }
1680
1681 if (!writeFru(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1682 fruData))
1683 {
1684 return false;
1685 }
1686
1687 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1688 rescanBusses(busMap, dbusInterfaceMap);
1689 return true;
1690}
1691
James Feist98132792019-07-09 13:29:09 -07001692int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001693{
1694 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001695 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001696 std::vector<fs::path> i2cBuses;
1697
James Feista3c180a2018-08-09 16:06:04 -07001698 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001699 {
1700 std::cerr << "unable to find i2c devices\n";
1701 return 1;
1702 }
James Feist3cb5fec2018-01-23 14:41:51 -08001703
Patrick Venture11f1ff42019-08-01 10:42:12 -07001704 // check for and load blacklist with initial buses.
1705 loadBlacklist(blacklistPath);
1706
Vijay Khemka065f6d92018-12-18 10:37:47 -08001707 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001708
James Feist6ebf9de2018-05-15 15:01:17 -07001709 // this is a map with keys of pair(bus number, address) and values of
1710 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001711 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001712 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1713 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001714
James Feist9eb0b582018-04-27 12:15:46 -07001715 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1716 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1717 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001718
James Feist5cb06082019-10-24 17:11:13 -07001719 iface->register_method("ReScan",
1720 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001721
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001722 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001723 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001724 });
1725
Nikhil Potaded8884f12019-03-27 13:27:13 -07001726 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001727
1728 iface->register_method("WriteFru", [&](const uint8_t bus,
1729 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001730 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001731 if (!writeFru(bus, address, data))
1732 {
James Feistddb78302018-09-06 11:45:42 -07001733 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001734 return;
1735 }
1736 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001737 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001738 });
James Feist9eb0b582018-04-27 12:15:46 -07001739 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001740
James Feist9eb0b582018-04-27 12:15:46 -07001741 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001742 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001743 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001744 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001745 std::string,
1746 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001747 values;
1748 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001749 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001750 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001751 {
James Feistcb5661d2020-06-12 15:05:01 -07001752 powerIsOn = boost::ends_with(
1753 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001754 }
James Feist6ebf9de2018-05-15 15:01:17 -07001755
James Feistcb5661d2020-06-12 15:05:01 -07001756 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001757 {
James Feist5cb06082019-10-24 17:11:13 -07001758 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001759 }
James Feist918e18c2018-02-13 15:51:07 -08001760 };
James Feist9eb0b582018-04-27 12:15:46 -07001761
1762 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001763 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001764 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001765 "openbmc_project/state/"
1766 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001767 eventHandler);
1768
James Feist4131aea2018-03-09 09:47:30 -08001769 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001770 inotify_add_watch(fd, I2C_DEV_LOCATION,
1771 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001772 std::array<char, 4096> readBuffer;
1773 std::string pendingBuffer;
1774 // monitor for new i2c devices
1775 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1776 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001777 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001778 std::size_t bytes_transferred) {
1779 if (ec)
1780 {
1781 std::cout << "Callback Error " << ec << "\n";
1782 return;
1783 }
1784 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001785 while (pendingBuffer.size() > sizeof(inotify_event))
1786 {
James Feista465ccc2019-02-08 12:51:01 -08001787 const inotify_event* iEvent =
1788 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001789 pendingBuffer.data());
1790 switch (iEvent->mask)
1791 {
James Feist9eb0b582018-04-27 12:15:46 -07001792 case IN_CREATE:
1793 case IN_MOVED_TO:
1794 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001795 std::string name(iEvent->name);
1796 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001797 {
James Feist5d7f4692020-06-17 18:22:33 -07001798 int bus = busStrToInt(name);
1799 if (bus < 0)
1800 {
1801 std::cerr << "Could not parse bus " << name
1802 << "\n";
1803 continue;
1804 }
1805 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1806 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001807 }
James Feist4131aea2018-03-09 09:47:30 -08001808 }
1809
1810 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1811 }
James Feist6ebf9de2018-05-15 15:01:17 -07001812
James Feist4131aea2018-03-09 09:47:30 -08001813 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1814 watchI2cBusses);
1815 };
1816
1817 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001818 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001819 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001820
James Feist3cb5fec2018-01-23 14:41:51 -08001821 io.run();
1822 return 0;
1823}