blob: 3a28e0f9b33f0d2381aa7801ca3e25cb94a6912f [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;
James Feist3cb5fec2018-01-23 14:41:51 -080064
Patrick Venture11f1ff42019-08-01 10:42:12 -070065constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
66
James Feista465ccc2019-02-08 12:51:01 -080067const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080068 "/etc/fru/baseboard.fru.bin";
69
James Feista465ccc2019-02-08 12:51:01 -080070const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080071
James Feista465ccc2019-02-08 12:51:01 -080072static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080073 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070074const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030075using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080076using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
77
James Feist444830e2019-04-05 08:38:16 -070078static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070079struct FindDevicesWithCallback;
80
Nikhil Potaded8884f12019-03-27 13:27:13 -070081static BusMap busMap;
82
James Feistcb5661d2020-06-12 15:05:01 -070083static bool powerIsOn = false;
84
James Feist8a983922019-10-24 17:11:56 -070085static boost::container::flat_map<
86 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
87 foundDevices;
88
James Feist7972bb92019-11-13 15:59:24 -080089static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
90
James Feist5cb06082019-10-24 17:11:13 -070091boost::asio::io_service io;
92auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
93auto objServer = sdbusplus::asio::object_server(systemBus);
94
Joshi-Mansid73b7442020-03-27 19:10:21 +053095static const std::vector<const char*> CHASSIS_FRU_AREAS = {
96 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
97
98static const std::vector<const char*> BOARD_FRU_AREAS = {
99 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
100 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
101
102static const std::vector<const char*> PRODUCT_FRU_AREAS = {
103 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION", "SERIAL_NUMBER",
104 "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
105
Patrick Venturebaba7672019-10-26 09:26:41 -0700106bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Joshi-Mansid73b7442020-03-27 19:10:21 +0530107bool updateFruProperty(
108 const std::string& assetTag, uint32_t bus, uint32_t address,
109 std::string propertyName,
110 boost::container::flat_map<
111 std::pair<size_t, size_t>,
112 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700113
Xiang Liu2801a702020-01-20 14:29:34 -0800114using ReadBlockFunc =
115 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
116 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700117
118// Read and validate FRU contents, given the flag required for raw i2c, the open
119// file handle, a read method, and a helper string for failures.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300120std::vector<uint8_t> readFruContents(int flag, int file, uint16_t address,
121 ReadBlockFunc readBlock,
122 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700123{
124 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
125
Xiang Liu2801a702020-01-20 14:29:34 -0800126 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700127 {
128 std::cerr << "failed to read " << errorHelp << "\n";
129 return {};
130 }
131
132 // check the header checksum
133 if (!validateHeader(blockData))
134 {
135 if (DEBUG)
136 {
137 std::cerr << "Illegal header " << errorHelp << "\n";
138 }
139
140 return {};
141 }
142
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300143 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700144 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
145
Patrick Venturee26395d2019-10-29 14:05:16 -0700146 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700147 int fruLength = 0;
148 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
149 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700150 // Offset value can be 255.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300151 int areaOffset = device[jj];
Patrick Venturebaba7672019-10-26 09:26:41 -0700152 if (areaOffset == 0)
153 {
154 continue;
155 }
156
Patrick Venturee26395d2019-10-29 14:05:16 -0700157 // MultiRecords are different. jj is not tracking section, it's walking
158 // the common header.
159 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
160 {
161 hasMultiRecords = true;
162 break;
163 }
164
Patrick Venturebaba7672019-10-26 09:26:41 -0700165 areaOffset *= 8;
166
Xiang Liu2801a702020-01-20 14:29:34 -0800167 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
168 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700169 {
170 std::cerr << "failed to read " << errorHelp << "\n";
171 return {};
172 }
173
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700174 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700175 int length = blockData[1] * 8;
176 areaOffset += length;
177 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
178 }
179
Patrick Venturee26395d2019-10-29 14:05:16 -0700180 if (hasMultiRecords)
181 {
182 // device[area count] is the index to the last area because the 0th
183 // entry is not an offset in the common header.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300184 int areaOffset = device[FRU_AREAS.size()];
Patrick Venturee26395d2019-10-29 14:05:16 -0700185 areaOffset *= 8;
186
187 // the multi-area record header is 5 bytes long.
188 constexpr int multiRecordHeaderSize = 5;
189 constexpr int multiRecordEndOfList = 0x80;
190
191 // Sanity hard-limit to 64KB.
192 while (areaOffset < std::numeric_limits<uint16_t>::max())
193 {
194 // In multi-area, the area offset points to the 0th record, each
195 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800196 if (readBlock(flag, file, address,
197 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700198 blockData.data()) < 0)
199 {
200 std::cerr << "failed to read " << errorHelp << "\n";
201 return {};
202 }
203
204 // Ok, let's check the record length, which is in bytes (unsigned,
205 // up to 255, so blockData should hold uint8_t not char)
206 int recordLength = blockData[2];
207 areaOffset += (recordLength + multiRecordHeaderSize);
208 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
209
210 // If this is the end of the list bail.
211 if ((blockData[1] & multiRecordEndOfList))
212 {
213 break;
214 }
215 }
216 }
217
Patrick Venturebaba7672019-10-26 09:26:41 -0700218 // You already copied these first 8 bytes (the ipmi fru header size)
219 fruLength -= 8;
220
221 int readOffset = 8;
222
223 while (fruLength > 0)
224 {
225 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
226
Xiang Liu2801a702020-01-20 14:29:34 -0800227 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700228 static_cast<uint8_t>(requestLength),
229 blockData.data()) < 0)
230 {
231 std::cerr << "failed to read " << errorHelp << "\n";
232 return {};
233 }
234
235 device.insert(device.end(), blockData.begin(),
236 blockData.begin() + requestLength);
237
238 readOffset += requestLength;
239 fruLength -= requestLength;
240 }
241
242 return device;
243}
244
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700245// Given a bus/address, produce the path in sysfs for an eeprom.
246static std::string getEepromPath(size_t bus, size_t address)
247{
248 std::stringstream output;
249 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
250 << std::setfill('0') << std::setw(4) << std::hex << address
251 << "/eeprom";
252 return output.str();
253}
254
255static bool hasEepromFile(size_t bus, size_t address)
256{
257 auto path = getEepromPath(bus, address);
258 try
259 {
260 return fs::exists(path);
261 }
262 catch (...)
263 {
264 return false;
265 }
266}
267
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700268static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800269 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700270 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700271{
272 auto result = lseek(fd, offset, SEEK_SET);
273 if (result < 0)
274 {
275 std::cerr << "failed to seek\n";
276 return -1;
277 }
278
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700279 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700280}
281
James Feist5d7f4692020-06-17 18:22:33 -0700282static int busStrToInt(const std::string& busName)
283{
284 auto findBus = busName.rfind("-");
285 if (findBus == std::string::npos)
286 {
287 return -1;
288 }
289 return std::stoi(busName.substr(findBus + 1));
290}
291
James Feist7972bb92019-11-13 15:59:24 -0800292static int getRootBus(size_t bus)
293{
294 auto ec = std::error_code();
295 auto path = std::filesystem::read_symlink(
296 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
297 std::to_string(bus) + "/mux_device"),
298 ec);
299 if (ec)
300 {
301 return -1;
302 }
303
304 std::string filename = path.filename();
305 auto findBus = filename.find("-");
306 if (findBus == std::string::npos)
307 {
308 return -1;
309 }
310 return std::stoi(filename.substr(0, findBus));
311}
312
James Feistc95cb142018-02-26 10:41:42 -0800313static bool isMuxBus(size_t bus)
314{
Ed Tanous072e25d2018-12-16 21:45:20 -0800315 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800316 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
317}
318
James Feist8a983922019-10-24 17:11:56 -0700319static void makeProbeInterface(size_t bus, size_t address)
320{
321 if (isMuxBus(bus))
322 {
323 return; // the mux buses are random, no need to publish
324 }
325 auto [it, success] = foundDevices.emplace(
326 std::make_pair(bus, address),
327 objServer.add_interface(
328 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
329 std::to_string(address),
330 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
331 if (!success)
332 {
333 return; // already added
334 }
335 it->second->register_property("Bus", bus);
336 it->second->register_property("Address", address);
337 it->second->initialize();
338}
339
Vijay Khemka2d681f62018-11-06 15:51:00 -0800340static int isDevice16Bit(int file)
341{
342 /* Get first byte */
343 int byte1 = i2c_smbus_read_byte_data(file, 0);
344 if (byte1 < 0)
345 {
346 return byte1;
347 }
348 /* Read 7 more bytes, it will read same first byte in case of
349 * 8 bit but it will read next byte in case of 16 bit
350 */
351 for (int i = 0; i < 7; i++)
352 {
353 int byte2 = i2c_smbus_read_byte_data(file, 0);
354 if (byte2 < 0)
355 {
356 return byte2;
357 }
358 if (byte2 != byte1)
359 {
360 return 1;
361 }
362 }
363 return 0;
364}
365
Xiang Liu2801a702020-01-20 14:29:34 -0800366// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
367// from_slave_buf_len bytes.
368static int i2c_smbus_write_then_read(int file, uint16_t address,
369 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
370 uint8_t* fromSlaveBuf,
371 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800372{
Xiang Liu2801a702020-01-20 14:29:34 -0800373 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
374 fromSlaveBufLen == 0)
375 {
376 return -1;
377 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800378
Xiang Liu2801a702020-01-20 14:29:34 -0800379#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
380 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
381 struct i2c_rdwr_ioctl_data rdwr;
382
383 msgs[0].addr = address;
384 msgs[0].flags = 0;
385 msgs[0].len = toSlaveBufLen;
386 msgs[0].buf = toSlaveBuf;
387 msgs[1].addr = address;
388 msgs[1].flags = I2C_M_RD;
389 msgs[1].len = fromSlaveBufLen;
390 msgs[1].buf = fromSlaveBuf;
391
392 rdwr.msgs = msgs;
393 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
394
395 int ret = ioctl(file, I2C_RDWR, &rdwr);
396
397 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
398}
399
400static int64_t readBlockData(int flag, int file, uint16_t address,
401 uint16_t offset, uint8_t len, uint8_t* buf)
402{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800403 if (flag == 0)
404 {
Xiang Liu2801a702020-01-20 14:29:34 -0800405 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
406 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800407 }
408
Xiang Liu2801a702020-01-20 14:29:34 -0800409 offset = htobe16(offset);
410 return i2c_smbus_write_then_read(
411 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800412}
413
James Feist24bae7a2019-04-03 09:50:56 -0700414bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
415{
416 // ipmi spec format version number is currently at 1, verify it
417 if (blockData[0] != 0x1)
418 {
419 return false;
420 }
421
422 // verify pad is set to 0
423 if (blockData[6] != 0x0)
424 {
425 return false;
426 }
427
428 // verify offsets are 0, or don't point to another offset
429 std::set<uint8_t> foundOffsets;
430 for (int ii = 1; ii < 6; ii++)
431 {
432 if (blockData[ii] == 0)
433 {
434 continue;
435 }
James Feist0eb40352019-04-09 14:44:04 -0700436 auto inserted = foundOffsets.insert(blockData[ii]);
437 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700438 {
439 return false;
440 }
441 }
442
443 // validate checksum
444 size_t sum = 0;
445 for (int jj = 0; jj < 7; jj++)
446 {
447 sum += blockData[jj];
448 }
449 sum = (256 - sum) & 0xFF;
450
451 if (sum != blockData[7])
452 {
453 return false;
454 }
455 return true;
456}
457
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700458// TODO: This code is very similar to the non-eeprom version and can be merged
459// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300460static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700461{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700462 auto path = getEepromPath(bus, address);
463
464 int file = open(path.c_str(), O_RDONLY);
465 if (file < 0)
466 {
467 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700468 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700469 }
470
Patrick Venturebaba7672019-10-26 09:26:41 -0700471 std::string errorMessage = "eeprom at " + std::to_string(bus) +
472 " address " + std::to_string(address);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300473 std::vector<uint8_t> device = readFruContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800474 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700475
476 close(file);
477 return device;
478}
479
480std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
481{
482 std::set<int> foundList;
483
484 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
485
486 // For each file listed under the i2c device
487 // NOTE: This should be faster than just checking for each possible address
488 // path.
489 for (const auto& p : fs::directory_iterator(path))
490 {
491 const std::string node = p.path().string();
492 std::smatch m;
493 bool found =
494 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
495
496 if (!found)
497 {
498 continue;
499 }
500 if (m.size() != 2)
501 {
502 std::cerr << "regex didn't capture\n";
503 continue;
504 }
505
506 std::ssub_match subMatch = m[1];
507 std::string addressString = subMatch.str();
508
509 std::size_t ignored;
510 const int hexBase = 16;
511 int address = std::stoi(addressString, &ignored, hexBase);
512
513 const std::string eeprom = node + "/eeprom";
514
515 try
516 {
517 if (!fs::exists(eeprom))
518 {
519 continue;
520 }
521 }
522 catch (...)
523 {
524 continue;
525 }
526
527 // There is an eeprom file at this address, it may have invalid
528 // contents, but we found it.
529 foundList.insert(address);
530
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300531 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700532 if (!device.empty())
533 {
534 devices->emplace(address, device);
535 }
536 }
537
538 return foundList;
539}
540
Patrick Venture4f47fe62019-08-08 16:30:38 -0700541int getBusFrus(int file, int first, int last, int bus,
542 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800543{
James Feist3cb5fec2018-01-23 14:41:51 -0800544
James Feist26c27ad2018-07-25 15:09:40 -0700545 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700546 // NOTE: When reading the devices raw on the bus, it can interfere with
547 // the driver's ability to operate, therefore read eeproms first before
548 // scanning for devices without drivers. Several experiments were run
549 // and it was determined that if there were any devices on the bus
550 // before the eeprom was hit and read, the eeprom driver wouldn't open
551 // while the bus device was open. An experiment was not performed to see
552 // if this issue was resolved if the i2c bus device was closed, but
553 // hexdumps of the eeprom later were successful.
554
555 // Scan for i2c eeproms loaded on this bus.
556 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800557 std::set<size_t>& failedItems = failedAddresses[bus];
558
559 std::set<size_t>* rootFailures = nullptr;
560 int rootBus = getRootBus(bus);
561
562 if (rootBus >= 0)
563 {
564 rootFailures = &(failedAddresses[rootBus]);
565 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700566
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530567 constexpr int startSkipSlaveAddr = 0;
568 constexpr int endSkipSlaveAddr = 12;
569
James Feist26c27ad2018-07-25 15:09:40 -0700570 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800571 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700572 if (skipList.find(ii) != skipList.end())
573 {
574 continue;
575 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530576 // skipping since no device is present in this range
577 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
578 {
579 continue;
580 }
James Feist26c27ad2018-07-25 15:09:40 -0700581 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530582 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800583 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700584 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700585 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700586 continue;
587 }
588 // probe
589 else if (i2c_smbus_read_byte(file) < 0)
590 {
591 continue;
592 }
James Feist3cb5fec2018-01-23 14:41:51 -0800593
James Feist26c27ad2018-07-25 15:09:40 -0700594 if (DEBUG)
595 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700596 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700597 << "\n";
598 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800599
James Feist8a983922019-10-24 17:11:56 -0700600 makeProbeInterface(bus, ii);
601
James Feist7972bb92019-11-13 15:59:24 -0800602 if (failedItems.find(ii) != failedItems.end())
603 {
604 // if we failed to read it once, unlikely we can read it later
605 continue;
606 }
607
608 if (rootFailures != nullptr)
609 {
610 if (rootFailures->find(ii) != rootFailures->end())
611 {
612 continue;
613 }
614 }
615
Vijay Khemka2d681f62018-11-06 15:51:00 -0800616 /* Check for Device type if it is 8 bit or 16 bit */
617 int flag = isDevice16Bit(file);
618 if (flag < 0)
619 {
620 std::cerr << "failed to read bus " << bus << " address " << ii
621 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700622 if (powerIsOn)
623 {
624 failedItems.insert(ii);
625 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800626 continue;
627 }
628
Patrick Venturebaba7672019-10-26 09:26:41 -0700629 std::string errorMessage =
630 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300631 std::vector<uint8_t> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800632 readFruContents(flag, file, static_cast<uint16_t>(ii),
633 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700634 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700635 {
James Feist26c27ad2018-07-25 15:09:40 -0700636 continue;
637 }
James Feist26c27ad2018-07-25 15:09:40 -0700638
Patrick Venture786f1792019-08-05 16:33:44 -0700639 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800640 }
James Feist26c27ad2018-07-25 15:09:40 -0700641 return 1;
642 });
643 std::future_status status =
644 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
645 if (status == std::future_status::timeout)
646 {
647 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700648 if (powerIsOn)
649 {
650 busBlacklist.insert(bus);
651 }
James Feist444830e2019-04-05 08:38:16 -0700652 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700653 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800654 }
655
James Feist444830e2019-04-05 08:38:16 -0700656 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700657 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800658}
659
Patrick Venture11f1ff42019-08-01 10:42:12 -0700660void loadBlacklist(const char* path)
661{
662 std::ifstream blacklistStream(path);
663 if (!blacklistStream.good())
664 {
665 // File is optional.
666 std::cerr << "Cannot open blacklist file.\n\n";
667 return;
668 }
669
670 nlohmann::json data =
671 nlohmann::json::parse(blacklistStream, nullptr, false);
672 if (data.is_discarded())
673 {
674 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
675 "exiting\n";
676 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700677 }
678
679 // It's expected to have at least one field, "buses" that is an array of the
680 // buses by integer. Allow for future options to exclude further aspects,
681 // such as specific addresses or ranges.
682 if (data.type() != nlohmann::json::value_t::object)
683 {
684 std::cerr << "Illegal blacklist, expected to read dictionary\n";
685 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700686 }
687
688 // If buses field is missing, that's fine.
689 if (data.count("buses") == 1)
690 {
691 // Parse the buses array after a little validation.
692 auto buses = data.at("buses");
693 if (buses.type() != nlohmann::json::value_t::array)
694 {
695 // Buses field present but invalid, therefore this is an error.
696 std::cerr << "Invalid contents for blacklist buses field\n";
697 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700698 }
699
700 // Catch exception here for type mis-match.
701 try
702 {
703 for (const auto& bus : buses)
704 {
705 busBlacklist.insert(bus.get<size_t>());
706 }
707 }
708 catch (const nlohmann::detail::type_error& e)
709 {
710 // Type mis-match is a critical error.
711 std::cerr << "Invalid bus type: " << e.what() << "\n";
712 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700713 }
714 }
715
716 return;
717}
718
James Feista465ccc2019-02-08 12:51:01 -0800719static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700720 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800721{
James Feista465ccc2019-02-08 12:51:01 -0800722 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800723 {
James Feist5d7f4692020-06-17 18:22:33 -0700724 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800725
James Feist5d7f4692020-06-17 18:22:33 -0700726 if (bus < 0)
727 {
728 std::cerr << "Cannot translate " << i2cBus << " to int\n";
729 continue;
730 }
James Feist444830e2019-04-05 08:38:16 -0700731 if (busBlacklist.find(bus) != busBlacklist.end())
732 {
733 continue; // skip previously failed busses
734 }
James Feist3cb5fec2018-01-23 14:41:51 -0800735
James Feist0c3980a2019-12-19 11:09:27 -0800736 int rootBus = getRootBus(bus);
737 if (busBlacklist.find(rootBus) != busBlacklist.end())
738 {
739 continue;
740 }
741
James Feist3cb5fec2018-01-23 14:41:51 -0800742 auto file = open(i2cBus.c_str(), O_RDWR);
743 if (file < 0)
744 {
745 std::cerr << "unable to open i2c device " << i2cBus.string()
746 << "\n";
747 continue;
748 }
749 unsigned long funcs = 0;
750
751 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
752 {
753 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700754 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800755 << bus << "\n";
756 continue;
757 }
758 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
759 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
760 {
761 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
762 << bus << "\n";
763 continue;
764 }
James Feist98132792019-07-09 13:29:09 -0700765 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800766 device = std::make_shared<DeviceMap>();
767
Nikhil Potaded8884f12019-03-27 13:27:13 -0700768 // i2cdetect by default uses the range 0x03 to 0x77, as
769 // this is what we have tested with, use this range. Could be
770 // changed in future.
771 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800772 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700773 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800774 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700775
776 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700777 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700778
779 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800780 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700781 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800782 }
James Feist3cb5fec2018-01-23 14:41:51 -0800783 }
James Feist3cb5fec2018-01-23 14:41:51 -0800784}
785
James Feist6ebf9de2018-05-15 15:01:17 -0700786// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700787struct FindDevicesWithCallback :
788 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700789{
James Feista465ccc2019-02-08 12:51:01 -0800790 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700791 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800792 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700793 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700794 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700795 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700796 ~FindDevicesWithCallback()
797 {
798 _callback();
799 }
800 void run()
801 {
James Feist98132792019-07-09 13:29:09 -0700802 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700803 }
804
James Feista465ccc2019-02-08 12:51:01 -0800805 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800806 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700807 std::function<void(void)> _callback;
808};
809
James Feist3cb5fec2018-01-23 14:41:51 -0800810static const std::tm intelEpoch(void)
811{
James Feist98132792019-07-09 13:29:09 -0700812 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800813 val.tm_year = 1996 - 1900;
814 return val;
815}
816
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800817static char sixBitToChar(uint8_t val)
818{
819 return static_cast<char>((val & 0x3f) + ' ');
820}
821
822/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
823static const char bcdHighChars[] = {
824 ' ', '-', '.', 'X', 'X', 'X',
825};
826
827static char bcdPlusToChar(uint8_t val)
828{
829 val &= 0xf;
830 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
831}
832
833enum class DecodeState
834{
835 ok,
836 end,
837 err,
838};
839
840enum FRUDataEncoding
841{
842 binary = 0x0,
843 bcdPlus = 0x1,
844 sixBitASCII = 0x2,
845 languageDependent = 0x3,
846};
847
848/* Decode FRU data into a std::string, given an input iterator and end. If the
849 * state returned is fruDataOk, then the resulting string is the decoded FRU
850 * data. The input iterator is advanced past the data consumed.
851 *
852 * On fruDataErr, we have lost synchronisation with the length bytes, so the
853 * iterator is no longer usable.
854 */
855static std::pair<DecodeState, std::string>
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300856 decodeFruData(std::vector<uint8_t>::const_iterator& iter,
857 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800858{
859 std::string value;
860 unsigned int i;
861
862 /* we need at least one byte to decode the type/len header */
863 if (iter == end)
864 {
865 std::cerr << "Truncated FRU data\n";
866 return make_pair(DecodeState::err, value);
867 }
868
869 uint8_t c = *(iter++);
870
871 /* 0xc1 is the end marker */
872 if (c == 0xc1)
873 {
874 return make_pair(DecodeState::end, value);
875 }
876
877 /* decode type/len byte */
878 uint8_t type = static_cast<uint8_t>(c >> 6);
879 uint8_t len = static_cast<uint8_t>(c & 0x3f);
880
881 /* we should have at least len bytes of data available overall */
882 if (iter + len > end)
883 {
884 std::cerr << "FRU data field extends past end of FRU data\n";
885 return make_pair(DecodeState::err, value);
886 }
887
888 switch (type)
889 {
890 case FRUDataEncoding::binary:
891 case FRUDataEncoding::languageDependent:
892 /* For language-code dependent encodings, assume 8-bit ASCII */
893 value = std::string(iter, iter + len);
894 iter += len;
895 break;
896
897 case FRUDataEncoding::bcdPlus:
898 value = std::string();
899 for (i = 0; i < len; i++, iter++)
900 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300901 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800902 value.push_back(bcdPlusToChar(val >> 4));
903 value.push_back(bcdPlusToChar(val & 0xf));
904 }
905 break;
906
907 case FRUDataEncoding::sixBitASCII:
908 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300909 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800910 unsigned int accumBitLen = 0;
911 value = std::string();
912 for (i = 0; i < len; i++, iter++)
913 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300914 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800915 accumBitLen += 8;
916 while (accumBitLen >= 6)
917 {
918 value.push_back(sixBitToChar(accum & 0x3f));
919 accum >>= 6;
920 accumBitLen -= 6;
921 }
922 }
923 }
924 break;
925 }
926
927 return make_pair(DecodeState::ok, value);
928}
929
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300930bool formatFru(const std::vector<uint8_t>& fruBytes,
James Feista465ccc2019-02-08 12:51:01 -0800931 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800932{
James Feistd068e932018-09-20 10:53:07 -0700933 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800934 {
935 return false;
936 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300937 std::vector<uint8_t>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700938 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800939 std::to_string(static_cast<int>(*fruAreaOffsetField));
940
James Feista465ccc2019-02-08 12:51:01 -0800941 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800942
James Feist0eb40352019-04-09 14:44:04 -0700943 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800944 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700945 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800946 if (fruAreaOffsetField >= fruBytes.end())
947 {
948 return false;
949 }
950 size_t offset = (*fruAreaOffsetField) * 8;
951
952 if (offset > 1)
953 {
954 // +2 to skip format and length
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300955 std::vector<uint8_t>::const_iterator fruBytesIter =
James Feist3cb5fec2018-01-23 14:41:51 -0800956 fruBytes.begin() + offset + 2;
957
958 if (fruBytesIter >= fruBytes.end())
959 {
960 return false;
961 }
962
963 if (area == "CHASSIS")
964 {
965 result["CHASSIS_TYPE"] =
966 std::to_string(static_cast<int>(*fruBytesIter));
967 fruBytesIter += 1;
968 fieldData = &CHASSIS_FRU_AREAS;
969 }
970 else if (area == "BOARD")
971 {
972 result["BOARD_LANGUAGE_CODE"] =
973 std::to_string(static_cast<int>(*fruBytesIter));
974 fruBytesIter += 1;
975 if (fruBytesIter >= fruBytes.end())
976 {
977 return false;
978 }
979
980 unsigned int minutes = *fruBytesIter |
981 *(fruBytesIter + 1) << 8 |
982 *(fruBytesIter + 2) << 16;
983 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700984 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800985 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700986 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800987
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700988 // Tue Nov 20 23:08:00 2018
989 char timeString[32] = {0};
990 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700991 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700992 if (bytes == 0)
993 {
994 std::cerr << "invalid time string encountered\n";
995 return false;
996 }
997
998 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800999 fruBytesIter += 3;
1000 fieldData = &BOARD_FRU_AREAS;
1001 }
1002 else if (area == "PRODUCT")
1003 {
1004 result["PRODUCT_LANGUAGE_CODE"] =
1005 std::to_string(static_cast<int>(*fruBytesIter));
1006 fruBytesIter += 1;
1007 fieldData = &PRODUCT_FRU_AREAS;
1008 }
1009 else
1010 {
1011 continue;
1012 }
James Feista465ccc2019-02-08 12:51:01 -08001013 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -08001014 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001015 auto res = decodeFruData(fruBytesIter, fruBytes.end());
1016 std::string name = area + "_" + field;
James Feist3cb5fec2018-01-23 14:41:51 -08001017
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001018 if (res.first == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001019 {
1020 break;
1021 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001022 else if (res.first == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001023 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001024 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001025 return false;
1026 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001027
1028 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001029
Ed Tanous2147e672019-02-27 13:59:56 -08001030 // Strip non null characters from the end
1031 value.erase(std::find_if(value.rbegin(), value.rend(),
1032 [](char ch) { return ch != 0; })
1033 .base(),
1034 value.end());
1035
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001036 result[name] = std::move(value);
James Feist3cb5fec2018-01-23 14:41:51 -08001037 }
1038 }
1039 }
1040
1041 return true;
1042}
1043
Nikhil Potaded8884f12019-03-27 13:27:13 -07001044std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
1045{
1046 auto deviceMap = busMap.find(bus);
1047 if (deviceMap == busMap.end())
1048 {
1049 throw std::invalid_argument("Invalid Bus.");
1050 }
1051 auto device = deviceMap->second->find(address);
1052 if (device == deviceMap->second->end())
1053 {
1054 throw std::invalid_argument("Invalid Address.");
1055 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001056 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001057
1058 return ret;
1059}
1060
James Feist3cb5fec2018-01-23 14:41:51 -08001061void AddFruObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001062 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001063 boost::container::flat_map<
1064 std::pair<size_t, size_t>,
1065 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001066 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001067{
1068 boost::container::flat_map<std::string, std::string> formattedFru;
1069 if (!formatFru(device, formattedFru))
1070 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001071 std::cerr << "failed to format fru for device at bus " << bus
1072 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001073 return;
1074 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001075
James Feist3cb5fec2018-01-23 14:41:51 -08001076 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
1077 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001078 // Not found under Board section or an empty string.
1079 if (productNameFind == formattedFru.end() ||
1080 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001081 {
1082 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
1083 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001084 // Found under Product section and not an empty string.
1085 if (productNameFind != formattedFru.end() &&
1086 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001087 {
1088 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001089 std::regex illegalObject("[^A-Za-z0-9_]");
1090 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001091 }
1092 else
1093 {
1094 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1095 UNKNOWN_BUS_OBJECT_COUNT++;
1096 }
1097
James Feist918e18c2018-02-13 15:51:07 -08001098 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001099 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001100 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001101 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001102 int highest = -1;
1103 bool found = false;
1104
James Feista465ccc2019-02-08 12:51:01 -08001105 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001106 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001107 std::string path = busIface.second->get_object_path();
1108 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001109 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001110 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -07001111 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
1112 static_cast<uint8_t>(busIface.first.second)) ==
1113 getFruInfo(static_cast<uint8_t>(bus),
1114 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001115 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001116 // This device is already added to the lower numbered bus,
1117 // do not replicate it.
1118 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001119 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001120
1121 // Check if the match named has extra information.
1122 found = true;
1123 std::smatch base_match;
1124
1125 bool match = std::regex_match(
1126 path, base_match, std::regex(productName + "_(\\d+)$"));
1127 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001128 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001129 if (base_match.size() == 2)
1130 {
1131 std::ssub_match base_sub_match = base_match[1];
1132 std::string base = base_sub_match.str();
1133
1134 int value = std::stoi(base);
1135 highest = (value > highest) ? value : highest;
1136 }
James Feist79e9c0b2018-03-15 15:21:17 -07001137 }
James Feist918e18c2018-02-13 15:51:07 -08001138 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001139 } // end searching objects
1140
1141 if (found)
1142 {
1143 // We found something with the same name. If highest was still -1,
1144 // it means this new entry will be _0.
1145 productName += "_";
1146 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001147 }
1148 }
James Feist3cb5fec2018-01-23 14:41:51 -08001149
James Feist9eb0b582018-04-27 12:15:46 -07001150 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1151 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1152 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1153
James Feista465ccc2019-02-08 12:51:01 -08001154 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001155 {
James Feist9eb0b582018-04-27 12:15:46 -07001156
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001157 std::regex_replace(property.second.begin(), property.second.begin(),
1158 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301159 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001160 {
1161 continue;
1162 }
1163 std::string key =
1164 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301165
1166 if (property.first == "PRODUCT_ASSET_TAG")
1167 {
1168 std::string propertyName = property.first;
1169 iface->register_property(
1170 key, property.second + '\0',
1171 [bus, address, propertyName,
1172 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1173 if (strcmp(req.c_str(), resp.c_str()))
1174 {
1175 // call the method which will update
1176 if (updateFruProperty(req, bus, address, propertyName,
1177 dbusInterfaceMap))
1178 {
1179 resp = req;
1180 }
1181 else
1182 {
1183 throw std::invalid_argument(
1184 "Fru property update failed.");
1185 }
1186 }
1187 return 1;
1188 });
1189 }
1190 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001191 {
1192 std::cerr << "illegal key: " << key << "\n";
1193 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001194 if (DEBUG)
1195 {
1196 std::cout << property.first << ": " << property.second << "\n";
1197 }
James Feist3cb5fec2018-01-23 14:41:51 -08001198 }
James Feist2a9d6db2018-04-27 15:48:28 -07001199
1200 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001201 iface->register_property("BUS", bus);
1202 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001203
James Feist9eb0b582018-04-27 12:15:46 -07001204 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001205}
1206
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001207static bool readBaseboardFru(std::vector<uint8_t>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001208{
1209 // try to read baseboard fru from file
1210 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1211 if (baseboardFruFile.good())
1212 {
1213 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001214 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001215 baseboardFru.resize(fileSize);
1216 baseboardFruFile.seekg(0, std::ios_base::beg);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001217 baseboardFruFile.read(reinterpret_cast<char*>(baseboardFru.data()),
1218 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001219 }
1220 else
1221 {
1222 return false;
1223 }
1224 return true;
1225}
1226
James Feista465ccc2019-02-08 12:51:01 -08001227bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001228{
1229 boost::container::flat_map<std::string, std::string> tmp;
1230 if (fru.size() > MAX_FRU_SIZE)
1231 {
1232 std::cerr << "Invalid fru.size() during writeFru\n";
1233 return false;
1234 }
1235 // verify legal fru by running it through fru parsing logic
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001236 if (!formatFru(fru, tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001237 {
1238 std::cerr << "Invalid fru format during writeFru\n";
1239 return false;
1240 }
1241 // baseboard fru
1242 if (bus == 0 && address == 0)
1243 {
1244 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1245 if (!file.good())
1246 {
1247 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1248 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001249 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001250 return false;
1251 }
James Feista465ccc2019-02-08 12:51:01 -08001252 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001253 return file.good();
1254 }
1255 else
1256 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001257 if (hasEepromFile(bus, address))
1258 {
1259 auto path = getEepromPath(bus, address);
1260 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1261 if (eeprom < 0)
1262 {
1263 std::cerr << "unable to open i2c device " << path << "\n";
1264 throw DBusInternalError();
1265 return false;
1266 }
1267
1268 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1269 if (writtenBytes < 0)
1270 {
1271 std::cerr << "unable to write to i2c device " << path << "\n";
1272 close(eeprom);
1273 throw DBusInternalError();
1274 return false;
1275 }
1276
1277 close(eeprom);
1278 return true;
1279 }
1280
James Feistb49ffc32018-05-02 11:10:43 -07001281 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1282
1283 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1284 if (file < 0)
1285 {
1286 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001287 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001288 return false;
1289 }
1290 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1291 {
1292 std::cerr << "unable to set device address\n";
1293 close(file);
James Feistddb78302018-09-06 11:45:42 -07001294 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001295 return false;
1296 }
1297
1298 constexpr const size_t RETRY_MAX = 2;
1299 uint16_t index = 0;
1300 size_t retries = RETRY_MAX;
1301 while (index < fru.size())
1302 {
1303 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1304 (retries == RETRY_MAX))
1305 {
1306 // The 4K EEPROM only uses the A2 and A1 device address bits
1307 // with the third bit being a memory page address bit.
1308 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1309 {
1310 std::cerr << "unable to set device address\n";
1311 close(file);
James Feistddb78302018-09-06 11:45:42 -07001312 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001313 return false;
1314 }
1315 }
1316
James Feist98132792019-07-09 13:29:09 -07001317 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1318 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001319 {
1320 if (!retries--)
1321 {
1322 std::cerr << "error writing fru: " << strerror(errno)
1323 << "\n";
1324 close(file);
James Feistddb78302018-09-06 11:45:42 -07001325 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001326 return false;
1327 }
1328 }
1329 else
1330 {
1331 retries = RETRY_MAX;
1332 index++;
1333 }
1334 // most eeproms require 5-10ms between writes
1335 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1336 }
1337 close(file);
1338 return true;
1339 }
1340}
1341
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001342void rescanOneBus(
1343 BusMap& busmap, uint8_t busNum,
1344 boost::container::flat_map<
1345 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001346 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1347 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001348{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001349 for (auto& [pair, interface] : foundDevices)
1350 {
1351 if (pair.first == static_cast<size_t>(busNum))
1352 {
1353 objServer.remove_interface(interface);
1354 foundDevices.erase(pair);
1355 }
1356 }
1357
James Feist5d7f4692020-06-17 18:22:33 -07001358 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1359 if (!fs::exists(busPath))
1360 {
1361 if (dbusCall)
1362 {
1363 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1364 << "\n";
1365 throw std::invalid_argument("Invalid Bus.");
1366 }
1367 return;
1368 }
1369
1370 std::vector<fs::path> i2cBuses;
1371 i2cBuses.emplace_back(busPath);
1372
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001373 auto scan = std::make_shared<FindDevicesWithCallback>(
1374 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1375 for (auto& busIface : dbusInterfaceMap)
1376 {
1377 if (busIface.first.first == static_cast<size_t>(busNum))
1378 {
1379 objServer.remove_interface(busIface.second);
1380 }
1381 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001382 auto found = busmap.find(busNum);
1383 if (found == busmap.end() || found->second == nullptr)
1384 {
1385 return;
1386 }
1387 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001388 {
1389 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1390 static_cast<uint32_t>(busNum), device.first);
1391 }
1392 });
1393 scan->run();
1394}
1395
James Feist9eb0b582018-04-27 12:15:46 -07001396void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001397 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001398 boost::container::flat_map<
1399 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001400 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001401{
James Feist6ebf9de2018-05-15 15:01:17 -07001402 static boost::asio::deadline_timer timer(io);
1403 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001404
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001405 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001406 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001407 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001408 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001409
Nikhil Potaded8884f12019-03-27 13:27:13 -07001410 boost::container::flat_map<size_t, fs::path> busPaths;
1411 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001412 {
James Feist4131aea2018-03-09 09:47:30 -08001413 std::cerr << "unable to find i2c devices\n";
1414 return;
James Feist918e18c2018-02-13 15:51:07 -08001415 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001416
1417 for (auto busPath : busPaths)
1418 {
1419 i2cBuses.emplace_back(busPath.second);
1420 }
James Feist4131aea2018-03-09 09:47:30 -08001421
James Feist98132792019-07-09 13:29:09 -07001422 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001423 for (auto& [pair, interface] : foundDevices)
1424 {
1425 objServer.remove_interface(interface);
1426 }
1427 foundDevices.clear();
1428
James Feist5cb06082019-10-24 17:11:13 -07001429 auto scan =
1430 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001431 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001432 {
1433 objServer.remove_interface(busIface.second);
1434 }
James Feist4131aea2018-03-09 09:47:30 -08001435
James Feist6ebf9de2018-05-15 15:01:17 -07001436 dbusInterfaceMap.clear();
1437 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001438
James Feist6ebf9de2018-05-15 15:01:17 -07001439 // todo, get this from a more sensable place
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001440 std::vector<uint8_t> baseboardFru;
James Feist6ebf9de2018-05-15 15:01:17 -07001441 if (readBaseboardFru(baseboardFru))
1442 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001443 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001444 baseboardDev;
1445 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001446 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001447 }
James Feist98132792019-07-09 13:29:09 -07001448 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001449 {
James Feista465ccc2019-02-08 12:51:01 -08001450 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001451 {
James Feist5cb06082019-10-24 17:11:13 -07001452 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1453 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001454 }
1455 }
1456 });
1457 scan->run();
1458 });
James Feist918e18c2018-02-13 15:51:07 -08001459}
1460
Joshi-Mansid73b7442020-03-27 19:10:21 +05301461// Calculate new checksum for fru info area
1462size_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1463{
1464 constexpr int checksumMod = 256;
1465 constexpr uint8_t modVal = 0xFF;
1466 int sum = std::accumulate(fruAreaData.begin(), fruAreaData.end(), 0);
1467 return (checksumMod - sum) & modVal;
1468}
1469
1470// Update new fru area length &
1471// Update checksum at new checksum location
1472static void updateFruAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1473 size_t fruAreaStartOffset,
1474 size_t fruAreaNoMoreFieldOffset)
1475{
1476 constexpr size_t fruAreaMultipleBytes = 8;
1477 size_t traverseFruAreaIndex = fruAreaNoMoreFieldOffset - fruAreaStartOffset;
1478
1479 // fill zeros for any remaining unused space
1480 std::fill(fruData.begin() + fruAreaNoMoreFieldOffset, fruData.end(), 0);
1481
1482 size_t mod = traverseFruAreaIndex % fruAreaMultipleBytes;
1483 size_t checksumLoc;
1484 if (!mod)
1485 {
1486 traverseFruAreaIndex += (fruAreaMultipleBytes);
1487 checksumLoc = fruAreaNoMoreFieldOffset + (fruAreaMultipleBytes - 1);
1488 }
1489 else
1490 {
1491 traverseFruAreaIndex += (fruAreaMultipleBytes - mod);
1492 checksumLoc =
1493 fruAreaNoMoreFieldOffset + (fruAreaMultipleBytes - mod - 1);
1494 }
1495
1496 size_t newFruAreaLen = (traverseFruAreaIndex / fruAreaMultipleBytes) +
1497 ((traverseFruAreaIndex % fruAreaMultipleBytes) != 0);
1498 size_t fruAreaLengthLoc = fruAreaStartOffset + 1;
1499 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFruAreaLen);
1500
1501 // Calculate new checksum
1502 std::vector<uint8_t> finalFruData;
1503 std::copy_n(fruData.begin() + fruAreaStartOffset,
1504 checksumLoc - fruAreaStartOffset,
1505 std::back_inserter(finalFruData));
1506
1507 size_t checksumVal = calculateChecksum(finalFruData);
1508
1509 fruData[checksumLoc] = static_cast<uint8_t>(checksumVal);
1510}
1511
1512static size_t getTypeLength(uint8_t fruFieldTypeLenValue)
1513{
1514 constexpr uint8_t typeLenMask = 0x3F;
1515 return fruFieldTypeLenValue & typeLenMask;
1516}
1517
1518// Details with example of Asset Tag Update
1519// To find location of Product Info Area asset tag as per FRU specification
1520// 1. Find product Info area starting offset (*8 - as header will be in
1521// multiple of 8 bytes).
1522// 2. Skip 3 bytes of product info area (like format version, area length,
1523// and language code).
1524// 3. Traverse manufacturer name, product name, product version, & product
1525// serial number, by reading type/length code to reach the Asset Tag.
1526// 4. Update the Asset Tag, reposition the product Info area in multiple of
1527// 8 bytes. Update the Product area length and checksum.
1528
1529bool updateFruProperty(
1530 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1531 std::string propertyName,
1532 boost::container::flat_map<
1533 std::pair<size_t, size_t>,
1534 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1535{
1536 size_t updatePropertyReqLen = updatePropertyReq.length();
1537 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1538 {
1539 std::cerr
1540 << "Fru field data cannot be of 1 char or more than 63 chars. "
1541 "Invalid Length "
1542 << updatePropertyReqLen << "\n";
1543 return false;
1544 }
1545
1546 std::vector<uint8_t> fruData;
1547 try
1548 {
1549 fruData = getFruInfo(static_cast<uint8_t>(bus),
1550 static_cast<uint8_t>(address));
1551 }
1552 catch (std::invalid_argument& e)
1553 {
1554 std::cerr << "Failure getting Fru Info" << e.what() << "\n";
1555 return false;
1556 }
1557
1558 if (fruData.empty())
1559 {
1560 return false;
1561 }
1562
1563 const std::vector<const char*>* fieldData;
1564
1565 constexpr size_t commonHeaderMultipleBytes = 8; // in multiple of 8 bytes
1566 uint8_t fruAreaOffsetFieldValue = 1;
1567 size_t offset = 0;
1568
1569 if (propertyName.find("CHASSIS") == 0)
1570 {
1571 constexpr size_t fruAreaOffsetField = 2;
1572 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1573
1574 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1575
1576 fieldData = &CHASSIS_FRU_AREAS;
1577 }
1578 else if (propertyName.find("BOARD") == 0)
1579 {
1580 constexpr size_t fruAreaOffsetField = 3;
1581 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1582
1583 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1584
1585 fieldData = &BOARD_FRU_AREAS;
1586 }
1587 else if (propertyName.find("PRODUCT") == 0)
1588 {
1589 constexpr size_t fruAreaOffsetField = 4;
1590 fruAreaOffsetFieldValue = fruData[fruAreaOffsetField];
1591
1592 offset = 3;
1593 // Manufacturer name offset. Skip fixed first 3 product fru bytes i.e.
1594 // version, area length and language code
1595
1596 fieldData = &PRODUCT_FRU_AREAS;
1597 }
1598 else
1599 {
1600 std::cerr << "ProperyName doesn't exist in Fru Area Vector \n";
1601 return false;
1602 }
1603
1604 size_t fruAreaStartOffset =
1605 fruAreaOffsetFieldValue * commonHeaderMultipleBytes;
1606 size_t fruDataIter = fruAreaStartOffset + offset;
1607 size_t fruUpdateFieldLoc = 0;
1608 size_t typeLength;
1609 size_t skipToFruUpdateField = 0;
1610
1611 for (auto& field : *fieldData)
1612 {
1613 skipToFruUpdateField++;
1614 if (propertyName.find(field) != std::string::npos)
1615 {
1616 break;
1617 }
1618 }
1619
1620 for (size_t i = 1; i < skipToFruUpdateField; i++)
1621 {
1622 typeLength = getTypeLength(fruData[fruDataIter]);
1623 fruUpdateFieldLoc = fruDataIter + typeLength;
1624 fruDataIter = ++fruUpdateFieldLoc;
1625 }
1626
1627 // Push post update fru field bytes to a vector
1628 typeLength = getTypeLength(fruData[fruUpdateFieldLoc]);
1629 size_t postFruUpdateFieldLoc = fruUpdateFieldLoc + typeLength;
1630 postFruUpdateFieldLoc++;
1631 skipToFruUpdateField++;
1632 fruDataIter = postFruUpdateFieldLoc;
1633 size_t endLengthLoc = 0;
1634 size_t fruFieldLoc = 0;
1635 constexpr uint8_t endLength = 0xC1;
1636 for (size_t i = fruDataIter; i < fruData.size(); i++)
1637 {
1638 typeLength = getTypeLength(fruData[fruDataIter]);
1639 fruFieldLoc = fruDataIter + typeLength;
1640 fruDataIter = ++fruFieldLoc;
1641 if (fruData[fruDataIter] == endLength)
1642 {
1643 endLengthLoc = fruDataIter;
1644 break;
1645 }
1646 }
1647 endLengthLoc++;
1648
1649 std::vector<uint8_t> postUpdatedFruData;
1650 std::copy_n(fruData.begin() + postFruUpdateFieldLoc,
1651 endLengthLoc - postFruUpdateFieldLoc,
1652 std::back_inserter(postUpdatedFruData));
1653
1654 // write new requested property field length and data
1655 constexpr uint8_t newTypeLenMask = 0xC0;
1656 fruData[fruUpdateFieldLoc] =
1657 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1658 fruUpdateFieldLoc++;
1659 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1660 fruData.begin() + fruUpdateFieldLoc);
1661
1662 // Copy remaining data to main fru area - post updated fru field vector
1663 postFruUpdateFieldLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1664 size_t fruAreaEndOffset = postFruUpdateFieldLoc + postUpdatedFruData.size();
1665 if (fruAreaEndOffset > fruData.size())
1666 {
1667 std::cerr << "Fru area offset: " << fruAreaEndOffset
1668 << "should not be greater than Fru data size: "
1669 << fruData.size() << std::endl;
1670 throw std::invalid_argument(
1671 "Fru area offset should not be greater than Fru data size");
1672 }
1673 std::copy(postUpdatedFruData.begin(), postUpdatedFruData.end(),
1674 fruData.begin() + postFruUpdateFieldLoc);
1675
1676 // Update final fru with new fru area length and checksum
1677 updateFruAreaLenAndChecksum(fruData, fruAreaStartOffset, fruAreaEndOffset);
1678
1679 if (fruData.empty())
1680 {
1681 return false;
1682 }
1683
1684 if (!writeFru(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1685 fruData))
1686 {
1687 return false;
1688 }
1689
1690 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1691 rescanBusses(busMap, dbusInterfaceMap);
1692 return true;
1693}
1694
James Feist98132792019-07-09 13:29:09 -07001695int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001696{
1697 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001698 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001699 std::vector<fs::path> i2cBuses;
1700
James Feista3c180a2018-08-09 16:06:04 -07001701 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001702 {
1703 std::cerr << "unable to find i2c devices\n";
1704 return 1;
1705 }
James Feist3cb5fec2018-01-23 14:41:51 -08001706
Patrick Venture11f1ff42019-08-01 10:42:12 -07001707 // check for and load blacklist with initial buses.
1708 loadBlacklist(blacklistPath);
1709
Vijay Khemka065f6d92018-12-18 10:37:47 -08001710 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001711
James Feist6ebf9de2018-05-15 15:01:17 -07001712 // this is a map with keys of pair(bus number, address) and values of
1713 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001714 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001715 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1716 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001717
James Feist9eb0b582018-04-27 12:15:46 -07001718 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1719 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1720 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001721
James Feist5cb06082019-10-24 17:11:13 -07001722 iface->register_method("ReScan",
1723 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001724
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001725 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001726 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001727 });
1728
Nikhil Potaded8884f12019-03-27 13:27:13 -07001729 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001730
1731 iface->register_method("WriteFru", [&](const uint8_t bus,
1732 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001733 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001734 if (!writeFru(bus, address, data))
1735 {
James Feistddb78302018-09-06 11:45:42 -07001736 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001737 return;
1738 }
1739 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001740 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001741 });
James Feist9eb0b582018-04-27 12:15:46 -07001742 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001743
James Feist9eb0b582018-04-27 12:15:46 -07001744 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001745 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001746 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001747 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001748 std::string,
1749 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001750 values;
1751 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001752 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001753 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001754 {
James Feistcb5661d2020-06-12 15:05:01 -07001755 powerIsOn = boost::ends_with(
1756 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001757 }
James Feist6ebf9de2018-05-15 15:01:17 -07001758
James Feistcb5661d2020-06-12 15:05:01 -07001759 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001760 {
James Feist5cb06082019-10-24 17:11:13 -07001761 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001762 }
James Feist918e18c2018-02-13 15:51:07 -08001763 };
James Feist9eb0b582018-04-27 12:15:46 -07001764
1765 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001766 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001767 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001768 "openbmc_project/state/"
1769 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001770 eventHandler);
1771
James Feist4131aea2018-03-09 09:47:30 -08001772 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001773 inotify_add_watch(fd, I2C_DEV_LOCATION,
1774 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001775 std::array<char, 4096> readBuffer;
1776 std::string pendingBuffer;
1777 // monitor for new i2c devices
1778 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1779 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001780 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001781 std::size_t bytes_transferred) {
1782 if (ec)
1783 {
1784 std::cout << "Callback Error " << ec << "\n";
1785 return;
1786 }
1787 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001788 while (pendingBuffer.size() > sizeof(inotify_event))
1789 {
James Feista465ccc2019-02-08 12:51:01 -08001790 const inotify_event* iEvent =
1791 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001792 pendingBuffer.data());
1793 switch (iEvent->mask)
1794 {
James Feist9eb0b582018-04-27 12:15:46 -07001795 case IN_CREATE:
1796 case IN_MOVED_TO:
1797 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001798 std::string name(iEvent->name);
1799 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001800 {
James Feist5d7f4692020-06-17 18:22:33 -07001801 int bus = busStrToInt(name);
1802 if (bus < 0)
1803 {
1804 std::cerr << "Could not parse bus " << name
1805 << "\n";
1806 continue;
1807 }
1808 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1809 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001810 }
James Feist4131aea2018-03-09 09:47:30 -08001811 }
1812
1813 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1814 }
James Feist6ebf9de2018-05-15 15:01:17 -07001815
James Feist4131aea2018-03-09 09:47:30 -08001816 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1817 watchI2cBusses);
1818 };
1819
1820 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001821 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001822 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001823
James Feist3cb5fec2018-01-23 14:41:51 -08001824 io.run();
1825 return 0;
1826}