blob: 3ae71b1c73dc66eb6305ef993928555fd9ea9cd3 [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
Patrick Venturec274f2f2019-10-26 09:27:23 -070024#include <array>
James Feist3b860982018-10-02 14:34:07 -070025#include <boost/algorithm/string/predicate.hpp>
26#include <boost/container/flat_map.hpp>
27#include <chrono>
28#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070029#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080030#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070031#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080032#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070033#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070035#include <limits>
Patrick Venture11f1ff42019-08-01 10:42:12 -070036#include <nlohmann/json.hpp>
James Feist3f8a2782018-02-12 09:24:42 -080037#include <regex>
James Feist3b860982018-10-02 14:34:07 -070038#include <sdbusplus/asio/connection.hpp>
39#include <sdbusplus/asio/object_server.hpp>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070040#include <set>
41#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070042#include <string>
James Feist3b860982018-10-02 14:34:07 -070043#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080044#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070045#include <vector>
James Feist3b860982018-10-02 14:34:07 -070046
47extern "C" {
48#include <i2c/smbus.h>
49#include <linux/i2c-dev.h>
50}
James Feist3cb5fec2018-01-23 14:41:51 -080051
Ed Tanous072e25d2018-12-16 21:45:20 -080052namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080053static constexpr bool DEBUG = false;
54static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070055constexpr size_t MAX_FRU_SIZE = 512;
56constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070057constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080058
Patrick Venture11f1ff42019-08-01 10:42:12 -070059constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
60
James Feista465ccc2019-02-08 12:51:01 -080061const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080062 "/etc/fru/baseboard.fru.bin";
63
James Feista465ccc2019-02-08 12:51:01 -080064const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080065
James Feista465ccc2019-02-08 12:51:01 -080066static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080067 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070068const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080069using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
70using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
71
James Feist444830e2019-04-05 08:38:16 -070072static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070073struct FindDevicesWithCallback;
74
Nikhil Potaded8884f12019-03-27 13:27:13 -070075static BusMap busMap;
76
James Feist8a983922019-10-24 17:11:56 -070077static boost::container::flat_map<
78 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
79 foundDevices;
80
James Feist7972bb92019-11-13 15:59:24 -080081static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
82
James Feist5cb06082019-10-24 17:11:13 -070083boost::asio::io_service io;
84auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
85auto objServer = sdbusplus::asio::object_server(systemBus);
86
Patrick Venturebaba7672019-10-26 09:26:41 -070087bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
88
Xiang Liu2801a702020-01-20 14:29:34 -080089using ReadBlockFunc =
90 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
91 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -070092
93// Read and validate FRU contents, given the flag required for raw i2c, the open
94// file handle, a read method, and a helper string for failures.
Xiang Liu2801a702020-01-20 14:29:34 -080095std::vector<char> readFruContents(int flag, int file, uint16_t address,
96 ReadBlockFunc readBlock,
Patrick Venturebaba7672019-10-26 09:26:41 -070097 const std::string& errorHelp)
98{
99 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
100
Xiang Liu2801a702020-01-20 14:29:34 -0800101 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700102 {
103 std::cerr << "failed to read " << errorHelp << "\n";
104 return {};
105 }
106
107 // check the header checksum
108 if (!validateHeader(blockData))
109 {
110 if (DEBUG)
111 {
112 std::cerr << "Illegal header " << errorHelp << "\n";
113 }
114
115 return {};
116 }
117
118 std::vector<char> device;
119 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
120
Patrick Venturee26395d2019-10-29 14:05:16 -0700121 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700122 int fruLength = 0;
123 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
124 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700125 // Offset value can be 255.
126 int areaOffset = static_cast<uint8_t>(device[jj]);
Patrick Venturebaba7672019-10-26 09:26:41 -0700127 if (areaOffset == 0)
128 {
129 continue;
130 }
131
Patrick Venturee26395d2019-10-29 14:05:16 -0700132 // MultiRecords are different. jj is not tracking section, it's walking
133 // the common header.
134 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
135 {
136 hasMultiRecords = true;
137 break;
138 }
139
Patrick Venturebaba7672019-10-26 09:26:41 -0700140 areaOffset *= 8;
141
Xiang Liu2801a702020-01-20 14:29:34 -0800142 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
143 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700144 {
145 std::cerr << "failed to read " << errorHelp << "\n";
146 return {};
147 }
148
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700149 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700150 int length = blockData[1] * 8;
151 areaOffset += length;
152 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
153 }
154
Patrick Venturee26395d2019-10-29 14:05:16 -0700155 if (hasMultiRecords)
156 {
157 // device[area count] is the index to the last area because the 0th
158 // entry is not an offset in the common header.
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700159 int areaOffset = static_cast<uint8_t>(device[FRU_AREAS.size()]);
Patrick Venturee26395d2019-10-29 14:05:16 -0700160 areaOffset *= 8;
161
162 // the multi-area record header is 5 bytes long.
163 constexpr int multiRecordHeaderSize = 5;
164 constexpr int multiRecordEndOfList = 0x80;
165
166 // Sanity hard-limit to 64KB.
167 while (areaOffset < std::numeric_limits<uint16_t>::max())
168 {
169 // In multi-area, the area offset points to the 0th record, each
170 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800171 if (readBlock(flag, file, address,
172 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700173 blockData.data()) < 0)
174 {
175 std::cerr << "failed to read " << errorHelp << "\n";
176 return {};
177 }
178
179 // Ok, let's check the record length, which is in bytes (unsigned,
180 // up to 255, so blockData should hold uint8_t not char)
181 int recordLength = blockData[2];
182 areaOffset += (recordLength + multiRecordHeaderSize);
183 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
184
185 // If this is the end of the list bail.
186 if ((blockData[1] & multiRecordEndOfList))
187 {
188 break;
189 }
190 }
191 }
192
Patrick Venturebaba7672019-10-26 09:26:41 -0700193 // You already copied these first 8 bytes (the ipmi fru header size)
194 fruLength -= 8;
195
196 int readOffset = 8;
197
198 while (fruLength > 0)
199 {
200 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
201
Xiang Liu2801a702020-01-20 14:29:34 -0800202 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700203 static_cast<uint8_t>(requestLength),
204 blockData.data()) < 0)
205 {
206 std::cerr << "failed to read " << errorHelp << "\n";
207 return {};
208 }
209
210 device.insert(device.end(), blockData.begin(),
211 blockData.begin() + requestLength);
212
213 readOffset += requestLength;
214 fruLength -= requestLength;
215 }
216
217 return device;
218}
219
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700220// Given a bus/address, produce the path in sysfs for an eeprom.
221static std::string getEepromPath(size_t bus, size_t address)
222{
223 std::stringstream output;
224 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
225 << std::setfill('0') << std::setw(4) << std::hex << address
226 << "/eeprom";
227 return output.str();
228}
229
230static bool hasEepromFile(size_t bus, size_t address)
231{
232 auto path = getEepromPath(bus, address);
233 try
234 {
235 return fs::exists(path);
236 }
237 catch (...)
238 {
239 return false;
240 }
241}
242
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700243static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800244 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700245 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700246{
247 auto result = lseek(fd, offset, SEEK_SET);
248 if (result < 0)
249 {
250 std::cerr << "failed to seek\n";
251 return -1;
252 }
253
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700254 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700255}
256
James Feist7972bb92019-11-13 15:59:24 -0800257static int getRootBus(size_t bus)
258{
259 auto ec = std::error_code();
260 auto path = std::filesystem::read_symlink(
261 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
262 std::to_string(bus) + "/mux_device"),
263 ec);
264 if (ec)
265 {
266 return -1;
267 }
268
269 std::string filename = path.filename();
270 auto findBus = filename.find("-");
271 if (findBus == std::string::npos)
272 {
273 return -1;
274 }
275 return std::stoi(filename.substr(0, findBus));
276}
277
James Feistc95cb142018-02-26 10:41:42 -0800278static bool isMuxBus(size_t bus)
279{
Ed Tanous072e25d2018-12-16 21:45:20 -0800280 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800281 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
282}
283
James Feist8a983922019-10-24 17:11:56 -0700284static void makeProbeInterface(size_t bus, size_t address)
285{
286 if (isMuxBus(bus))
287 {
288 return; // the mux buses are random, no need to publish
289 }
290 auto [it, success] = foundDevices.emplace(
291 std::make_pair(bus, address),
292 objServer.add_interface(
293 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
294 std::to_string(address),
295 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
296 if (!success)
297 {
298 return; // already added
299 }
300 it->second->register_property("Bus", bus);
301 it->second->register_property("Address", address);
302 it->second->initialize();
303}
304
Vijay Khemka2d681f62018-11-06 15:51:00 -0800305static int isDevice16Bit(int file)
306{
307 /* Get first byte */
308 int byte1 = i2c_smbus_read_byte_data(file, 0);
309 if (byte1 < 0)
310 {
311 return byte1;
312 }
313 /* Read 7 more bytes, it will read same first byte in case of
314 * 8 bit but it will read next byte in case of 16 bit
315 */
316 for (int i = 0; i < 7; i++)
317 {
318 int byte2 = i2c_smbus_read_byte_data(file, 0);
319 if (byte2 < 0)
320 {
321 return byte2;
322 }
323 if (byte2 != byte1)
324 {
325 return 1;
326 }
327 }
328 return 0;
329}
330
Xiang Liu2801a702020-01-20 14:29:34 -0800331// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
332// from_slave_buf_len bytes.
333static int i2c_smbus_write_then_read(int file, uint16_t address,
334 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
335 uint8_t* fromSlaveBuf,
336 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800337{
Xiang Liu2801a702020-01-20 14:29:34 -0800338 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
339 fromSlaveBufLen == 0)
340 {
341 return -1;
342 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800343
Xiang Liu2801a702020-01-20 14:29:34 -0800344#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
345 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
346 struct i2c_rdwr_ioctl_data rdwr;
347
348 msgs[0].addr = address;
349 msgs[0].flags = 0;
350 msgs[0].len = toSlaveBufLen;
351 msgs[0].buf = toSlaveBuf;
352 msgs[1].addr = address;
353 msgs[1].flags = I2C_M_RD;
354 msgs[1].len = fromSlaveBufLen;
355 msgs[1].buf = fromSlaveBuf;
356
357 rdwr.msgs = msgs;
358 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
359
360 int ret = ioctl(file, I2C_RDWR, &rdwr);
361
362 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
363}
364
365static int64_t readBlockData(int flag, int file, uint16_t address,
366 uint16_t offset, uint8_t len, uint8_t* buf)
367{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800368 if (flag == 0)
369 {
Xiang Liu2801a702020-01-20 14:29:34 -0800370 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
371 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800372 }
373
Xiang Liu2801a702020-01-20 14:29:34 -0800374 offset = htobe16(offset);
375 return i2c_smbus_write_then_read(
376 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800377}
378
James Feist24bae7a2019-04-03 09:50:56 -0700379bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
380{
381 // ipmi spec format version number is currently at 1, verify it
382 if (blockData[0] != 0x1)
383 {
384 return false;
385 }
386
387 // verify pad is set to 0
388 if (blockData[6] != 0x0)
389 {
390 return false;
391 }
392
393 // verify offsets are 0, or don't point to another offset
394 std::set<uint8_t> foundOffsets;
395 for (int ii = 1; ii < 6; ii++)
396 {
397 if (blockData[ii] == 0)
398 {
399 continue;
400 }
James Feist0eb40352019-04-09 14:44:04 -0700401 auto inserted = foundOffsets.insert(blockData[ii]);
402 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700403 {
404 return false;
405 }
406 }
407
408 // validate checksum
409 size_t sum = 0;
410 for (int jj = 0; jj < 7; jj++)
411 {
412 sum += blockData[jj];
413 }
414 sum = (256 - sum) & 0xFF;
415
416 if (sum != blockData[7])
417 {
418 return false;
419 }
420 return true;
421}
422
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700423// TODO: This code is very similar to the non-eeprom version and can be merged
424// with some tweaks.
425static std::vector<char> processEeprom(int bus, int address)
426{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700427 auto path = getEepromPath(bus, address);
428
429 int file = open(path.c_str(), O_RDONLY);
430 if (file < 0)
431 {
432 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700433 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700434 }
435
Patrick Venturebaba7672019-10-26 09:26:41 -0700436 std::string errorMessage = "eeprom at " + std::to_string(bus) +
437 " address " + std::to_string(address);
Xiang Liu2801a702020-01-20 14:29:34 -0800438 std::vector<char> device = readFruContents(
439 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700440
441 close(file);
442 return device;
443}
444
445std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
446{
447 std::set<int> foundList;
448
449 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
450
451 // For each file listed under the i2c device
452 // NOTE: This should be faster than just checking for each possible address
453 // path.
454 for (const auto& p : fs::directory_iterator(path))
455 {
456 const std::string node = p.path().string();
457 std::smatch m;
458 bool found =
459 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
460
461 if (!found)
462 {
463 continue;
464 }
465 if (m.size() != 2)
466 {
467 std::cerr << "regex didn't capture\n";
468 continue;
469 }
470
471 std::ssub_match subMatch = m[1];
472 std::string addressString = subMatch.str();
473
474 std::size_t ignored;
475 const int hexBase = 16;
476 int address = std::stoi(addressString, &ignored, hexBase);
477
478 const std::string eeprom = node + "/eeprom";
479
480 try
481 {
482 if (!fs::exists(eeprom))
483 {
484 continue;
485 }
486 }
487 catch (...)
488 {
489 continue;
490 }
491
492 // There is an eeprom file at this address, it may have invalid
493 // contents, but we found it.
494 foundList.insert(address);
495
496 std::vector<char> device = processEeprom(i2cBus, address);
497 if (!device.empty())
498 {
499 devices->emplace(address, device);
500 }
501 }
502
503 return foundList;
504}
505
Patrick Venture4f47fe62019-08-08 16:30:38 -0700506int getBusFrus(int file, int first, int last, int bus,
507 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800508{
James Feist3cb5fec2018-01-23 14:41:51 -0800509
James Feist26c27ad2018-07-25 15:09:40 -0700510 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700511 // NOTE: When reading the devices raw on the bus, it can interfere with
512 // the driver's ability to operate, therefore read eeproms first before
513 // scanning for devices without drivers. Several experiments were run
514 // and it was determined that if there were any devices on the bus
515 // before the eeprom was hit and read, the eeprom driver wouldn't open
516 // while the bus device was open. An experiment was not performed to see
517 // if this issue was resolved if the i2c bus device was closed, but
518 // hexdumps of the eeprom later were successful.
519
520 // Scan for i2c eeproms loaded on this bus.
521 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800522 std::set<size_t>& failedItems = failedAddresses[bus];
523
524 std::set<size_t>* rootFailures = nullptr;
525 int rootBus = getRootBus(bus);
526
527 if (rootBus >= 0)
528 {
529 rootFailures = &(failedAddresses[rootBus]);
530 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700531
James Feist26c27ad2018-07-25 15:09:40 -0700532 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800533 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700534 if (skipList.find(ii) != skipList.end())
535 {
536 continue;
537 }
James Feist3cb5fec2018-01-23 14:41:51 -0800538
James Feist26c27ad2018-07-25 15:09:40 -0700539 // Set slave address
540 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800541 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700542 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700543 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700544 continue;
545 }
546 // probe
547 else if (i2c_smbus_read_byte(file) < 0)
548 {
549 continue;
550 }
James Feist3cb5fec2018-01-23 14:41:51 -0800551
James Feist26c27ad2018-07-25 15:09:40 -0700552 if (DEBUG)
553 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700554 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700555 << "\n";
556 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800557
James Feist8a983922019-10-24 17:11:56 -0700558 makeProbeInterface(bus, ii);
559
James Feist7972bb92019-11-13 15:59:24 -0800560 if (failedItems.find(ii) != failedItems.end())
561 {
562 // if we failed to read it once, unlikely we can read it later
563 continue;
564 }
565
566 if (rootFailures != nullptr)
567 {
568 if (rootFailures->find(ii) != rootFailures->end())
569 {
570 continue;
571 }
572 }
573
Vijay Khemka2d681f62018-11-06 15:51:00 -0800574 /* Check for Device type if it is 8 bit or 16 bit */
575 int flag = isDevice16Bit(file);
576 if (flag < 0)
577 {
578 std::cerr << "failed to read bus " << bus << " address " << ii
579 << "\n";
James Feist7972bb92019-11-13 15:59:24 -0800580 failedItems.insert(ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800581 continue;
582 }
583
Patrick Venturebaba7672019-10-26 09:26:41 -0700584 std::string errorMessage =
585 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
586 std::vector<char> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800587 readFruContents(flag, file, static_cast<uint16_t>(ii),
588 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700589 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700590 {
James Feist26c27ad2018-07-25 15:09:40 -0700591 continue;
592 }
James Feist26c27ad2018-07-25 15:09:40 -0700593
Patrick Venture786f1792019-08-05 16:33:44 -0700594 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800595 }
James Feist26c27ad2018-07-25 15:09:40 -0700596 return 1;
597 });
598 std::future_status status =
599 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
600 if (status == std::future_status::timeout)
601 {
602 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700603 busBlacklist.insert(bus);
604 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700605 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800606 }
607
James Feist444830e2019-04-05 08:38:16 -0700608 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700609 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800610}
611
Patrick Venture11f1ff42019-08-01 10:42:12 -0700612void loadBlacklist(const char* path)
613{
614 std::ifstream blacklistStream(path);
615 if (!blacklistStream.good())
616 {
617 // File is optional.
618 std::cerr << "Cannot open blacklist file.\n\n";
619 return;
620 }
621
622 nlohmann::json data =
623 nlohmann::json::parse(blacklistStream, nullptr, false);
624 if (data.is_discarded())
625 {
626 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
627 "exiting\n";
628 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700629 }
630
631 // It's expected to have at least one field, "buses" that is an array of the
632 // buses by integer. Allow for future options to exclude further aspects,
633 // such as specific addresses or ranges.
634 if (data.type() != nlohmann::json::value_t::object)
635 {
636 std::cerr << "Illegal blacklist, expected to read dictionary\n";
637 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700638 }
639
640 // If buses field is missing, that's fine.
641 if (data.count("buses") == 1)
642 {
643 // Parse the buses array after a little validation.
644 auto buses = data.at("buses");
645 if (buses.type() != nlohmann::json::value_t::array)
646 {
647 // Buses field present but invalid, therefore this is an error.
648 std::cerr << "Invalid contents for blacklist buses field\n";
649 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700650 }
651
652 // Catch exception here for type mis-match.
653 try
654 {
655 for (const auto& bus : buses)
656 {
657 busBlacklist.insert(bus.get<size_t>());
658 }
659 }
660 catch (const nlohmann::detail::type_error& e)
661 {
662 // Type mis-match is a critical error.
663 std::cerr << "Invalid bus type: " << e.what() << "\n";
664 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700665 }
666 }
667
668 return;
669}
670
James Feista465ccc2019-02-08 12:51:01 -0800671static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700672 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800673{
James Feista465ccc2019-02-08 12:51:01 -0800674 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800675 {
676 auto busnum = i2cBus.string();
677 auto lastDash = busnum.rfind(std::string("-"));
678 // delete everything before dash inclusive
679 if (lastDash != std::string::npos)
680 {
681 busnum.erase(0, lastDash + 1);
682 }
James Feist0c3980a2019-12-19 11:09:27 -0800683
James Feist3cb5fec2018-01-23 14:41:51 -0800684 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700685 if (busBlacklist.find(bus) != busBlacklist.end())
686 {
687 continue; // skip previously failed busses
688 }
James Feist3cb5fec2018-01-23 14:41:51 -0800689
James Feist0c3980a2019-12-19 11:09:27 -0800690 int rootBus = getRootBus(bus);
691 if (busBlacklist.find(rootBus) != busBlacklist.end())
692 {
693 continue;
694 }
695
James Feist3cb5fec2018-01-23 14:41:51 -0800696 auto file = open(i2cBus.c_str(), O_RDWR);
697 if (file < 0)
698 {
699 std::cerr << "unable to open i2c device " << i2cBus.string()
700 << "\n";
701 continue;
702 }
703 unsigned long funcs = 0;
704
705 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
706 {
707 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700708 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800709 << bus << "\n";
710 continue;
711 }
712 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
713 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
714 {
715 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
716 << bus << "\n";
717 continue;
718 }
James Feist98132792019-07-09 13:29:09 -0700719 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800720 device = std::make_shared<DeviceMap>();
721
Nikhil Potaded8884f12019-03-27 13:27:13 -0700722 // i2cdetect by default uses the range 0x03 to 0x77, as
723 // this is what we have tested with, use this range. Could be
724 // changed in future.
725 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800726 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700727 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800728 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700729
730 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700731 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700732
733 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800734 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700735 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800736 }
James Feist3cb5fec2018-01-23 14:41:51 -0800737 }
James Feist3cb5fec2018-01-23 14:41:51 -0800738}
739
James Feist6ebf9de2018-05-15 15:01:17 -0700740// this class allows an async response after all i2c devices are discovered
741struct FindDevicesWithCallback
742 : std::enable_shared_from_this<FindDevicesWithCallback>
743{
James Feista465ccc2019-02-08 12:51:01 -0800744 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700745 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800746 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700747 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700748 _busMap(busmap), _callback(std::move(callback))
James Feist6ebf9de2018-05-15 15:01:17 -0700749 {
750 }
751 ~FindDevicesWithCallback()
752 {
753 _callback();
754 }
755 void run()
756 {
James Feist98132792019-07-09 13:29:09 -0700757 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700758 }
759
James Feista465ccc2019-02-08 12:51:01 -0800760 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800761 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700762 std::function<void(void)> _callback;
763};
764
James Feist3cb5fec2018-01-23 14:41:51 -0800765static const std::tm intelEpoch(void)
766{
James Feist98132792019-07-09 13:29:09 -0700767 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800768 val.tm_year = 1996 - 1900;
769 return val;
770}
771
James Feista465ccc2019-02-08 12:51:01 -0800772bool formatFru(const std::vector<char>& fruBytes,
773 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800774{
James Feista465ccc2019-02-08 12:51:01 -0800775 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800776 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800777
James Feista465ccc2019-02-08 12:51:01 -0800778 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800779 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
780 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800781
James Feista465ccc2019-02-08 12:51:01 -0800782 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800783 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
784 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
785 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800786
James Feistd068e932018-09-20 10:53:07 -0700787 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800788 {
789 return false;
790 }
791 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700792 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800793 std::to_string(static_cast<int>(*fruAreaOffsetField));
794
James Feista465ccc2019-02-08 12:51:01 -0800795 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800796
James Feist0eb40352019-04-09 14:44:04 -0700797 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800798 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700799 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800800 if (fruAreaOffsetField >= fruBytes.end())
801 {
802 return false;
803 }
804 size_t offset = (*fruAreaOffsetField) * 8;
805
806 if (offset > 1)
807 {
808 // +2 to skip format and length
809 std::vector<char>::const_iterator fruBytesIter =
810 fruBytes.begin() + offset + 2;
811
812 if (fruBytesIter >= fruBytes.end())
813 {
814 return false;
815 }
816
817 if (area == "CHASSIS")
818 {
819 result["CHASSIS_TYPE"] =
820 std::to_string(static_cast<int>(*fruBytesIter));
821 fruBytesIter += 1;
822 fieldData = &CHASSIS_FRU_AREAS;
823 }
824 else if (area == "BOARD")
825 {
826 result["BOARD_LANGUAGE_CODE"] =
827 std::to_string(static_cast<int>(*fruBytesIter));
828 fruBytesIter += 1;
829 if (fruBytesIter >= fruBytes.end())
830 {
831 return false;
832 }
833
834 unsigned int minutes = *fruBytesIter |
835 *(fruBytesIter + 1) << 8 |
836 *(fruBytesIter + 2) << 16;
837 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700838 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800839 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700840 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800841
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700842 // Tue Nov 20 23:08:00 2018
843 char timeString[32] = {0};
844 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700845 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700846 if (bytes == 0)
847 {
848 std::cerr << "invalid time string encountered\n";
849 return false;
850 }
851
852 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800853 fruBytesIter += 3;
854 fieldData = &BOARD_FRU_AREAS;
855 }
856 else if (area == "PRODUCT")
857 {
858 result["PRODUCT_LANGUAGE_CODE"] =
859 std::to_string(static_cast<int>(*fruBytesIter));
860 fruBytesIter += 1;
861 fieldData = &PRODUCT_FRU_AREAS;
862 }
863 else
864 {
865 continue;
866 }
James Feista465ccc2019-02-08 12:51:01 -0800867 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800868 {
869 if (fruBytesIter >= fruBytes.end())
870 {
871 return false;
872 }
873
Vijay Khemka5d5de442018-11-07 10:51:25 -0800874 /* Checking for last byte C1 to indicate that no more
875 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700876 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800877 {
878 break;
879 }
880
Ed Tanous2147e672019-02-27 13:59:56 -0800881 size_t length = *fruBytesIter & 0x3f;
882 fruBytesIter += 1;
883
James Feist3cb5fec2018-01-23 14:41:51 -0800884 if (fruBytesIter >= fruBytes.end())
885 {
886 return false;
887 }
Ed Tanous2147e672019-02-27 13:59:56 -0800888 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800889
Ed Tanous2147e672019-02-27 13:59:56 -0800890 // Strip non null characters from the end
891 value.erase(std::find_if(value.rbegin(), value.rend(),
892 [](char ch) { return ch != 0; })
893 .base(),
894 value.end());
895
James Feist0eb40352019-04-09 14:44:04 -0700896 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800897
James Feist3cb5fec2018-01-23 14:41:51 -0800898 fruBytesIter += length;
899 if (fruBytesIter >= fruBytes.end())
900 {
901 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800902 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800903 {
904 std::cerr << c;
905 }
906 std::cerr << "\n";
907 if (DEBUG)
908 {
James Feista465ccc2019-02-08 12:51:01 -0800909 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800910 {
911 std::cerr << keyPair.first << " : "
912 << keyPair.second << "\n";
913 }
914 }
915 return false;
916 }
917 }
918 }
919 }
920
921 return true;
922}
923
Nikhil Potaded8884f12019-03-27 13:27:13 -0700924std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
925{
926 auto deviceMap = busMap.find(bus);
927 if (deviceMap == busMap.end())
928 {
929 throw std::invalid_argument("Invalid Bus.");
930 }
931 auto device = deviceMap->second->find(address);
932 if (device == deviceMap->second->end())
933 {
934 throw std::invalid_argument("Invalid Address.");
935 }
936 std::vector<uint8_t>& ret =
937 reinterpret_cast<std::vector<uint8_t>&>(device->second);
938
939 return ret;
940}
941
James Feist3cb5fec2018-01-23 14:41:51 -0800942void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700943 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800944 boost::container::flat_map<
945 std::pair<size_t, size_t>,
946 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700947 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800948{
949 boost::container::flat_map<std::string, std::string> formattedFru;
950 if (!formatFru(device, formattedFru))
951 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700952 std::cerr << "failed to format fru for device at bus " << bus
953 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800954 return;
955 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700956
James Feist3cb5fec2018-01-23 14:41:51 -0800957 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
958 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700959 // Not found under Board section or an empty string.
960 if (productNameFind == formattedFru.end() ||
961 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800962 {
963 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
964 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700965 // Found under Product section and not an empty string.
966 if (productNameFind != formattedFru.end() &&
967 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800968 {
969 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800970 std::regex illegalObject("[^A-Za-z0-9_]");
971 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800972 }
973 else
974 {
975 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
976 UNKNOWN_BUS_OBJECT_COUNT++;
977 }
978
James Feist918e18c2018-02-13 15:51:07 -0800979 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800980 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700981 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800982 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700983 int highest = -1;
984 bool found = false;
985
James Feista465ccc2019-02-08 12:51:01 -0800986 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800987 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700988 std::string path = busIface.second->get_object_path();
989 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800990 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700991 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -0700992 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
993 static_cast<uint8_t>(busIface.first.second)) ==
994 getFruInfo(static_cast<uint8_t>(bus),
995 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -0700996 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700997 // This device is already added to the lower numbered bus,
998 // do not replicate it.
999 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001000 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001001
1002 // Check if the match named has extra information.
1003 found = true;
1004 std::smatch base_match;
1005
1006 bool match = std::regex_match(
1007 path, base_match, std::regex(productName + "_(\\d+)$"));
1008 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001009 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001010 if (base_match.size() == 2)
1011 {
1012 std::ssub_match base_sub_match = base_match[1];
1013 std::string base = base_sub_match.str();
1014
1015 int value = std::stoi(base);
1016 highest = (value > highest) ? value : highest;
1017 }
James Feist79e9c0b2018-03-15 15:21:17 -07001018 }
James Feist918e18c2018-02-13 15:51:07 -08001019 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001020 } // end searching objects
1021
1022 if (found)
1023 {
1024 // We found something with the same name. If highest was still -1,
1025 // it means this new entry will be _0.
1026 productName += "_";
1027 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001028 }
1029 }
James Feist3cb5fec2018-01-23 14:41:51 -08001030
James Feist9eb0b582018-04-27 12:15:46 -07001031 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1032 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1033 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1034
James Feista465ccc2019-02-08 12:51:01 -08001035 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001036 {
James Feist9eb0b582018-04-27 12:15:46 -07001037
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001038 std::regex_replace(property.second.begin(), property.second.begin(),
1039 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -07001040 if (property.second.empty())
1041 {
1042 continue;
1043 }
1044 std::string key =
1045 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
1046 if (!iface->register_property(key, property.second + '\0'))
1047 {
1048 std::cerr << "illegal key: " << key << "\n";
1049 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001050 if (DEBUG)
1051 {
1052 std::cout << property.first << ": " << property.second << "\n";
1053 }
James Feist3cb5fec2018-01-23 14:41:51 -08001054 }
James Feist2a9d6db2018-04-27 15:48:28 -07001055
1056 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001057 iface->register_property("BUS", bus);
1058 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001059
James Feist9eb0b582018-04-27 12:15:46 -07001060 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001061}
1062
James Feista465ccc2019-02-08 12:51:01 -08001063static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001064{
1065 // try to read baseboard fru from file
1066 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1067 if (baseboardFruFile.good())
1068 {
1069 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001070 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001071 baseboardFru.resize(fileSize);
1072 baseboardFruFile.seekg(0, std::ios_base::beg);
1073 baseboardFruFile.read(baseboardFru.data(), fileSize);
1074 }
1075 else
1076 {
1077 return false;
1078 }
1079 return true;
1080}
1081
James Feista465ccc2019-02-08 12:51:01 -08001082bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001083{
1084 boost::container::flat_map<std::string, std::string> tmp;
1085 if (fru.size() > MAX_FRU_SIZE)
1086 {
1087 std::cerr << "Invalid fru.size() during writeFru\n";
1088 return false;
1089 }
1090 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001091 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001092 {
1093 std::cerr << "Invalid fru format during writeFru\n";
1094 return false;
1095 }
1096 // baseboard fru
1097 if (bus == 0 && address == 0)
1098 {
1099 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1100 if (!file.good())
1101 {
1102 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1103 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001104 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001105 return false;
1106 }
James Feista465ccc2019-02-08 12:51:01 -08001107 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001108 return file.good();
1109 }
1110 else
1111 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001112 if (hasEepromFile(bus, address))
1113 {
1114 auto path = getEepromPath(bus, address);
1115 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1116 if (eeprom < 0)
1117 {
1118 std::cerr << "unable to open i2c device " << path << "\n";
1119 throw DBusInternalError();
1120 return false;
1121 }
1122
1123 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1124 if (writtenBytes < 0)
1125 {
1126 std::cerr << "unable to write to i2c device " << path << "\n";
1127 close(eeprom);
1128 throw DBusInternalError();
1129 return false;
1130 }
1131
1132 close(eeprom);
1133 return true;
1134 }
1135
James Feistb49ffc32018-05-02 11:10:43 -07001136 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1137
1138 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1139 if (file < 0)
1140 {
1141 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001142 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001143 return false;
1144 }
1145 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1146 {
1147 std::cerr << "unable to set device address\n";
1148 close(file);
James Feistddb78302018-09-06 11:45:42 -07001149 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001150 return false;
1151 }
1152
1153 constexpr const size_t RETRY_MAX = 2;
1154 uint16_t index = 0;
1155 size_t retries = RETRY_MAX;
1156 while (index < fru.size())
1157 {
1158 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1159 (retries == RETRY_MAX))
1160 {
1161 // The 4K EEPROM only uses the A2 and A1 device address bits
1162 // with the third bit being a memory page address bit.
1163 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1164 {
1165 std::cerr << "unable to set device address\n";
1166 close(file);
James Feistddb78302018-09-06 11:45:42 -07001167 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001168 return false;
1169 }
1170 }
1171
James Feist98132792019-07-09 13:29:09 -07001172 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1173 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001174 {
1175 if (!retries--)
1176 {
1177 std::cerr << "error writing fru: " << strerror(errno)
1178 << "\n";
1179 close(file);
James Feistddb78302018-09-06 11:45:42 -07001180 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001181 return false;
1182 }
1183 }
1184 else
1185 {
1186 retries = RETRY_MAX;
1187 index++;
1188 }
1189 // most eeproms require 5-10ms between writes
1190 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1191 }
1192 close(file);
1193 return true;
1194 }
1195}
1196
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001197void rescanOneBus(
1198 BusMap& busmap, uint8_t busNum,
1199 boost::container::flat_map<
1200 std::pair<size_t, size_t>,
1201 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1202{
1203 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1204 if (!fs::exists(busPath))
1205 {
1206 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1207 << "\n";
1208 throw std::invalid_argument("Invalid Bus.");
1209 }
1210
1211 std::vector<fs::path> i2cBuses;
1212 i2cBuses.emplace_back(busPath);
1213
1214 for (auto& [pair, interface] : foundDevices)
1215 {
1216 if (pair.first == static_cast<size_t>(busNum))
1217 {
1218 objServer.remove_interface(interface);
1219 foundDevices.erase(pair);
1220 }
1221 }
1222
1223 auto scan = std::make_shared<FindDevicesWithCallback>(
1224 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1225 for (auto& busIface : dbusInterfaceMap)
1226 {
1227 if (busIface.first.first == static_cast<size_t>(busNum))
1228 {
1229 objServer.remove_interface(busIface.second);
1230 }
1231 }
1232 auto& devicemap = busmap[busNum];
1233 for (auto& device : *devicemap)
1234 {
1235 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1236 static_cast<uint32_t>(busNum), device.first);
1237 }
1238 });
1239 scan->run();
1240}
1241
James Feist9eb0b582018-04-27 12:15:46 -07001242void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001243 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001244 boost::container::flat_map<
1245 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001246 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001247{
James Feist6ebf9de2018-05-15 15:01:17 -07001248 static boost::asio::deadline_timer timer(io);
1249 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001250
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001251 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001252 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001253 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001254 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001255
Nikhil Potaded8884f12019-03-27 13:27:13 -07001256 boost::container::flat_map<size_t, fs::path> busPaths;
1257 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001258 {
James Feist4131aea2018-03-09 09:47:30 -08001259 std::cerr << "unable to find i2c devices\n";
1260 return;
James Feist918e18c2018-02-13 15:51:07 -08001261 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001262
1263 for (auto busPath : busPaths)
1264 {
1265 i2cBuses.emplace_back(busPath.second);
1266 }
James Feist4131aea2018-03-09 09:47:30 -08001267
James Feist98132792019-07-09 13:29:09 -07001268 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001269 for (auto& [pair, interface] : foundDevices)
1270 {
1271 objServer.remove_interface(interface);
1272 }
1273 foundDevices.clear();
1274
James Feist5cb06082019-10-24 17:11:13 -07001275 auto scan =
1276 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001277 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001278 {
1279 objServer.remove_interface(busIface.second);
1280 }
James Feist4131aea2018-03-09 09:47:30 -08001281
James Feist6ebf9de2018-05-15 15:01:17 -07001282 dbusInterfaceMap.clear();
1283 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001284
James Feist6ebf9de2018-05-15 15:01:17 -07001285 // todo, get this from a more sensable place
1286 std::vector<char> baseboardFru;
1287 if (readBaseboardFru(baseboardFru))
1288 {
1289 boost::container::flat_map<int, std::vector<char>>
1290 baseboardDev;
1291 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001292 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001293 }
James Feist98132792019-07-09 13:29:09 -07001294 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001295 {
James Feista465ccc2019-02-08 12:51:01 -08001296 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001297 {
James Feist5cb06082019-10-24 17:11:13 -07001298 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1299 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001300 }
1301 }
1302 });
1303 scan->run();
1304 });
James Feist918e18c2018-02-13 15:51:07 -08001305}
1306
James Feist98132792019-07-09 13:29:09 -07001307int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001308{
1309 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001310 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001311 std::vector<fs::path> i2cBuses;
1312
James Feista3c180a2018-08-09 16:06:04 -07001313 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001314 {
1315 std::cerr << "unable to find i2c devices\n";
1316 return 1;
1317 }
James Feist3cb5fec2018-01-23 14:41:51 -08001318
Patrick Venture11f1ff42019-08-01 10:42:12 -07001319 // check for and load blacklist with initial buses.
1320 loadBlacklist(blacklistPath);
1321
Vijay Khemka065f6d92018-12-18 10:37:47 -08001322 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001323
James Feist6ebf9de2018-05-15 15:01:17 -07001324 // this is a map with keys of pair(bus number, address) and values of
1325 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001326 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001327 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1328 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001329
James Feist9eb0b582018-04-27 12:15:46 -07001330 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1331 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1332 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001333
James Feist5cb06082019-10-24 17:11:13 -07001334 iface->register_method("ReScan",
1335 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001336
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001337 iface->register_method("ReScanBus", [&](uint8_t bus) {
1338 rescanOneBus(busMap, bus, dbusInterfaceMap);
1339 });
1340
Nikhil Potaded8884f12019-03-27 13:27:13 -07001341 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001342
1343 iface->register_method("WriteFru", [&](const uint8_t bus,
1344 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001345 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001346 if (!writeFru(bus, address, data))
1347 {
James Feistddb78302018-09-06 11:45:42 -07001348 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001349 return;
1350 }
1351 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001352 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001353 });
James Feist9eb0b582018-04-27 12:15:46 -07001354 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001355
James Feist9eb0b582018-04-27 12:15:46 -07001356 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001357 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001358 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001359 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001360 std::string,
1361 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001362 values;
1363 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001364 auto findState = values.find("CurrentHostState");
1365 bool on = false;
1366 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001367 {
James Feist0eeb79c2019-10-09 13:35:29 -07001368 on = boost::ends_with(std::get<std::string>(findState->second),
1369 "Running");
1370 }
James Feist6ebf9de2018-05-15 15:01:17 -07001371
James Feist0eeb79c2019-10-09 13:35:29 -07001372 if (on)
1373 {
James Feist5cb06082019-10-24 17:11:13 -07001374 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001375 }
James Feist918e18c2018-02-13 15:51:07 -08001376 };
James Feist9eb0b582018-04-27 12:15:46 -07001377
1378 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001379 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001380 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001381 "openbmc_project/state/"
1382 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001383 eventHandler);
1384
James Feist4131aea2018-03-09 09:47:30 -08001385 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001386 inotify_add_watch(fd, I2C_DEV_LOCATION,
1387 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001388 std::array<char, 4096> readBuffer;
1389 std::string pendingBuffer;
1390 // monitor for new i2c devices
1391 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1392 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001393 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001394 std::size_t bytes_transferred) {
1395 if (ec)
1396 {
1397 std::cout << "Callback Error " << ec << "\n";
1398 return;
1399 }
1400 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1401 bool devChange = false;
1402 while (pendingBuffer.size() > sizeof(inotify_event))
1403 {
James Feista465ccc2019-02-08 12:51:01 -08001404 const inotify_event* iEvent =
1405 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001406 pendingBuffer.data());
1407 switch (iEvent->mask)
1408 {
James Feist9eb0b582018-04-27 12:15:46 -07001409 case IN_CREATE:
1410 case IN_MOVED_TO:
1411 case IN_DELETE:
1412 if (boost::starts_with(std::string(iEvent->name),
1413 "i2c"))
1414 {
1415 devChange = true;
1416 }
James Feist4131aea2018-03-09 09:47:30 -08001417 }
1418
1419 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1420 }
James Feist6ebf9de2018-05-15 15:01:17 -07001421 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001422 {
James Feist5cb06082019-10-24 17:11:13 -07001423 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001424 }
James Feist6ebf9de2018-05-15 15:01:17 -07001425
James Feist4131aea2018-03-09 09:47:30 -08001426 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1427 watchI2cBusses);
1428 };
1429
1430 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001431 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001432 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001433
James Feist3cb5fec2018-01-23 14:41:51 -08001434 io.run();
1435 return 0;
1436}