blob: 7107a965bc6eb68d71ae6c8ecb8cd33535676a78 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
Patrick Venturea49dc332019-10-26 08:32:02 -070017#include "Utils.hpp"
18
James Feist3b860982018-10-02 14:34:07 -070019#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080020#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070021#include <sys/inotify.h>
22#include <sys/ioctl.h>
23
James Feist3b860982018-10-02 14:34:07 -070024#include <boost/algorithm/string/predicate.hpp>
25#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070026#include <nlohmann/json.hpp>
27#include <sdbusplus/asio/connection.hpp>
28#include <sdbusplus/asio/object_server.hpp>
29
30#include <array>
James Feist3b860982018-10-02 14:34:07 -070031#include <chrono>
32#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070033#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070035#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080036#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070037#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080038#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070039#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080040#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070041#include <set>
42#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070043#include <string>
James Feist3b860982018-10-02 14:34:07 -070044#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080045#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070046#include <vector>
James Feist3b860982018-10-02 14:34:07 -070047
James Feist8c505da2020-05-28 10:06:33 -070048extern "C"
49{
James Feist3b860982018-10-02 14:34:07 -070050#include <i2c/smbus.h>
51#include <linux/i2c-dev.h>
52}
James Feist3cb5fec2018-01-23 14:41:51 -080053
Ed Tanous072e25d2018-12-16 21:45:20 -080054namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080055static constexpr bool DEBUG = false;
56static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070057constexpr size_t MAX_FRU_SIZE = 512;
58constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070059constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080060
Patrick Venture11f1ff42019-08-01 10:42:12 -070061constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
62
James Feista465ccc2019-02-08 12:51:01 -080063const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080064 "/etc/fru/baseboard.fru.bin";
65
James Feista465ccc2019-02-08 12:51:01 -080066const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080067
James Feista465ccc2019-02-08 12:51:01 -080068static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080069 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070070const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080071using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
72using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
73
James Feist444830e2019-04-05 08:38:16 -070074static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070075struct FindDevicesWithCallback;
76
Nikhil Potaded8884f12019-03-27 13:27:13 -070077static BusMap busMap;
78
James Feist8a983922019-10-24 17:11:56 -070079static boost::container::flat_map<
80 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
81 foundDevices;
82
James Feist7972bb92019-11-13 15:59:24 -080083static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
84
James Feist5cb06082019-10-24 17:11:13 -070085boost::asio::io_service io;
86auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
87auto objServer = sdbusplus::asio::object_server(systemBus);
88
Patrick Venturebaba7672019-10-26 09:26:41 -070089bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
90
Xiang Liu2801a702020-01-20 14:29:34 -080091using ReadBlockFunc =
92 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
93 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -070094
95// Read and validate FRU contents, given the flag required for raw i2c, the open
96// file handle, a read method, and a helper string for failures.
Xiang Liu2801a702020-01-20 14:29:34 -080097std::vector<char> readFruContents(int flag, int file, uint16_t address,
98 ReadBlockFunc readBlock,
Patrick Venturebaba7672019-10-26 09:26:41 -070099 const std::string& errorHelp)
100{
101 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
102
Xiang Liu2801a702020-01-20 14:29:34 -0800103 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700104 {
105 std::cerr << "failed to read " << errorHelp << "\n";
106 return {};
107 }
108
109 // check the header checksum
110 if (!validateHeader(blockData))
111 {
112 if (DEBUG)
113 {
114 std::cerr << "Illegal header " << errorHelp << "\n";
115 }
116
117 return {};
118 }
119
120 std::vector<char> device;
121 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
122
Patrick Venturee26395d2019-10-29 14:05:16 -0700123 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700124 int fruLength = 0;
125 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
126 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700127 // Offset value can be 255.
128 int areaOffset = static_cast<uint8_t>(device[jj]);
Patrick Venturebaba7672019-10-26 09:26:41 -0700129 if (areaOffset == 0)
130 {
131 continue;
132 }
133
Patrick Venturee26395d2019-10-29 14:05:16 -0700134 // MultiRecords are different. jj is not tracking section, it's walking
135 // the common header.
136 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
137 {
138 hasMultiRecords = true;
139 break;
140 }
141
Patrick Venturebaba7672019-10-26 09:26:41 -0700142 areaOffset *= 8;
143
Xiang Liu2801a702020-01-20 14:29:34 -0800144 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
145 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700146 {
147 std::cerr << "failed to read " << errorHelp << "\n";
148 return {};
149 }
150
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700151 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700152 int length = blockData[1] * 8;
153 areaOffset += length;
154 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
155 }
156
Patrick Venturee26395d2019-10-29 14:05:16 -0700157 if (hasMultiRecords)
158 {
159 // device[area count] is the index to the last area because the 0th
160 // entry is not an offset in the common header.
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700161 int areaOffset = static_cast<uint8_t>(device[FRU_AREAS.size()]);
Patrick Venturee26395d2019-10-29 14:05:16 -0700162 areaOffset *= 8;
163
164 // the multi-area record header is 5 bytes long.
165 constexpr int multiRecordHeaderSize = 5;
166 constexpr int multiRecordEndOfList = 0x80;
167
168 // Sanity hard-limit to 64KB.
169 while (areaOffset < std::numeric_limits<uint16_t>::max())
170 {
171 // In multi-area, the area offset points to the 0th record, each
172 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800173 if (readBlock(flag, file, address,
174 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700175 blockData.data()) < 0)
176 {
177 std::cerr << "failed to read " << errorHelp << "\n";
178 return {};
179 }
180
181 // Ok, let's check the record length, which is in bytes (unsigned,
182 // up to 255, so blockData should hold uint8_t not char)
183 int recordLength = blockData[2];
184 areaOffset += (recordLength + multiRecordHeaderSize);
185 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
186
187 // If this is the end of the list bail.
188 if ((blockData[1] & multiRecordEndOfList))
189 {
190 break;
191 }
192 }
193 }
194
Patrick Venturebaba7672019-10-26 09:26:41 -0700195 // You already copied these first 8 bytes (the ipmi fru header size)
196 fruLength -= 8;
197
198 int readOffset = 8;
199
200 while (fruLength > 0)
201 {
202 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
203
Xiang Liu2801a702020-01-20 14:29:34 -0800204 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700205 static_cast<uint8_t>(requestLength),
206 blockData.data()) < 0)
207 {
208 std::cerr << "failed to read " << errorHelp << "\n";
209 return {};
210 }
211
212 device.insert(device.end(), blockData.begin(),
213 blockData.begin() + requestLength);
214
215 readOffset += requestLength;
216 fruLength -= requestLength;
217 }
218
219 return device;
220}
221
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700222// Given a bus/address, produce the path in sysfs for an eeprom.
223static std::string getEepromPath(size_t bus, size_t address)
224{
225 std::stringstream output;
226 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
227 << std::setfill('0') << std::setw(4) << std::hex << address
228 << "/eeprom";
229 return output.str();
230}
231
232static bool hasEepromFile(size_t bus, size_t address)
233{
234 auto path = getEepromPath(bus, address);
235 try
236 {
237 return fs::exists(path);
238 }
239 catch (...)
240 {
241 return false;
242 }
243}
244
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700245static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800246 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700247 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700248{
249 auto result = lseek(fd, offset, SEEK_SET);
250 if (result < 0)
251 {
252 std::cerr << "failed to seek\n";
253 return -1;
254 }
255
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700256 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700257}
258
James Feist7972bb92019-11-13 15:59:24 -0800259static int getRootBus(size_t bus)
260{
261 auto ec = std::error_code();
262 auto path = std::filesystem::read_symlink(
263 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
264 std::to_string(bus) + "/mux_device"),
265 ec);
266 if (ec)
267 {
268 return -1;
269 }
270
271 std::string filename = path.filename();
272 auto findBus = filename.find("-");
273 if (findBus == std::string::npos)
274 {
275 return -1;
276 }
277 return std::stoi(filename.substr(0, findBus));
278}
279
James Feistc95cb142018-02-26 10:41:42 -0800280static bool isMuxBus(size_t bus)
281{
Ed Tanous072e25d2018-12-16 21:45:20 -0800282 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800283 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
284}
285
James Feist8a983922019-10-24 17:11:56 -0700286static void makeProbeInterface(size_t bus, size_t address)
287{
288 if (isMuxBus(bus))
289 {
290 return; // the mux buses are random, no need to publish
291 }
292 auto [it, success] = foundDevices.emplace(
293 std::make_pair(bus, address),
294 objServer.add_interface(
295 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
296 std::to_string(address),
297 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
298 if (!success)
299 {
300 return; // already added
301 }
302 it->second->register_property("Bus", bus);
303 it->second->register_property("Address", address);
304 it->second->initialize();
305}
306
Vijay Khemka2d681f62018-11-06 15:51:00 -0800307static int isDevice16Bit(int file)
308{
309 /* Get first byte */
310 int byte1 = i2c_smbus_read_byte_data(file, 0);
311 if (byte1 < 0)
312 {
313 return byte1;
314 }
315 /* Read 7 more bytes, it will read same first byte in case of
316 * 8 bit but it will read next byte in case of 16 bit
317 */
318 for (int i = 0; i < 7; i++)
319 {
320 int byte2 = i2c_smbus_read_byte_data(file, 0);
321 if (byte2 < 0)
322 {
323 return byte2;
324 }
325 if (byte2 != byte1)
326 {
327 return 1;
328 }
329 }
330 return 0;
331}
332
Xiang Liu2801a702020-01-20 14:29:34 -0800333// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
334// from_slave_buf_len bytes.
335static int i2c_smbus_write_then_read(int file, uint16_t address,
336 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
337 uint8_t* fromSlaveBuf,
338 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800339{
Xiang Liu2801a702020-01-20 14:29:34 -0800340 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
341 fromSlaveBufLen == 0)
342 {
343 return -1;
344 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800345
Xiang Liu2801a702020-01-20 14:29:34 -0800346#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
347 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
348 struct i2c_rdwr_ioctl_data rdwr;
349
350 msgs[0].addr = address;
351 msgs[0].flags = 0;
352 msgs[0].len = toSlaveBufLen;
353 msgs[0].buf = toSlaveBuf;
354 msgs[1].addr = address;
355 msgs[1].flags = I2C_M_RD;
356 msgs[1].len = fromSlaveBufLen;
357 msgs[1].buf = fromSlaveBuf;
358
359 rdwr.msgs = msgs;
360 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
361
362 int ret = ioctl(file, I2C_RDWR, &rdwr);
363
364 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
365}
366
367static int64_t readBlockData(int flag, int file, uint16_t address,
368 uint16_t offset, uint8_t len, uint8_t* buf)
369{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800370 if (flag == 0)
371 {
Xiang Liu2801a702020-01-20 14:29:34 -0800372 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
373 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800374 }
375
Xiang Liu2801a702020-01-20 14:29:34 -0800376 offset = htobe16(offset);
377 return i2c_smbus_write_then_read(
378 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800379}
380
James Feist24bae7a2019-04-03 09:50:56 -0700381bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
382{
383 // ipmi spec format version number is currently at 1, verify it
384 if (blockData[0] != 0x1)
385 {
386 return false;
387 }
388
389 // verify pad is set to 0
390 if (blockData[6] != 0x0)
391 {
392 return false;
393 }
394
395 // verify offsets are 0, or don't point to another offset
396 std::set<uint8_t> foundOffsets;
397 for (int ii = 1; ii < 6; ii++)
398 {
399 if (blockData[ii] == 0)
400 {
401 continue;
402 }
James Feist0eb40352019-04-09 14:44:04 -0700403 auto inserted = foundOffsets.insert(blockData[ii]);
404 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700405 {
406 return false;
407 }
408 }
409
410 // validate checksum
411 size_t sum = 0;
412 for (int jj = 0; jj < 7; jj++)
413 {
414 sum += blockData[jj];
415 }
416 sum = (256 - sum) & 0xFF;
417
418 if (sum != blockData[7])
419 {
420 return false;
421 }
422 return true;
423}
424
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700425// TODO: This code is very similar to the non-eeprom version and can be merged
426// with some tweaks.
427static std::vector<char> processEeprom(int bus, int address)
428{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700429 auto path = getEepromPath(bus, address);
430
431 int file = open(path.c_str(), O_RDONLY);
432 if (file < 0)
433 {
434 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700435 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700436 }
437
Patrick Venturebaba7672019-10-26 09:26:41 -0700438 std::string errorMessage = "eeprom at " + std::to_string(bus) +
439 " address " + std::to_string(address);
Xiang Liu2801a702020-01-20 14:29:34 -0800440 std::vector<char> device = readFruContents(
441 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700442
443 close(file);
444 return device;
445}
446
447std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
448{
449 std::set<int> foundList;
450
451 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
452
453 // For each file listed under the i2c device
454 // NOTE: This should be faster than just checking for each possible address
455 // path.
456 for (const auto& p : fs::directory_iterator(path))
457 {
458 const std::string node = p.path().string();
459 std::smatch m;
460 bool found =
461 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
462
463 if (!found)
464 {
465 continue;
466 }
467 if (m.size() != 2)
468 {
469 std::cerr << "regex didn't capture\n";
470 continue;
471 }
472
473 std::ssub_match subMatch = m[1];
474 std::string addressString = subMatch.str();
475
476 std::size_t ignored;
477 const int hexBase = 16;
478 int address = std::stoi(addressString, &ignored, hexBase);
479
480 const std::string eeprom = node + "/eeprom";
481
482 try
483 {
484 if (!fs::exists(eeprom))
485 {
486 continue;
487 }
488 }
489 catch (...)
490 {
491 continue;
492 }
493
494 // There is an eeprom file at this address, it may have invalid
495 // contents, but we found it.
496 foundList.insert(address);
497
498 std::vector<char> device = processEeprom(i2cBus, address);
499 if (!device.empty())
500 {
501 devices->emplace(address, device);
502 }
503 }
504
505 return foundList;
506}
507
Patrick Venture4f47fe62019-08-08 16:30:38 -0700508int getBusFrus(int file, int first, int last, int bus,
509 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800510{
James Feist3cb5fec2018-01-23 14:41:51 -0800511
James Feist26c27ad2018-07-25 15:09:40 -0700512 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700513 // NOTE: When reading the devices raw on the bus, it can interfere with
514 // the driver's ability to operate, therefore read eeproms first before
515 // scanning for devices without drivers. Several experiments were run
516 // and it was determined that if there were any devices on the bus
517 // before the eeprom was hit and read, the eeprom driver wouldn't open
518 // while the bus device was open. An experiment was not performed to see
519 // if this issue was resolved if the i2c bus device was closed, but
520 // hexdumps of the eeprom later were successful.
521
522 // Scan for i2c eeproms loaded on this bus.
523 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800524 std::set<size_t>& failedItems = failedAddresses[bus];
525
526 std::set<size_t>* rootFailures = nullptr;
527 int rootBus = getRootBus(bus);
528
529 if (rootBus >= 0)
530 {
531 rootFailures = &(failedAddresses[rootBus]);
532 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700533
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530534 constexpr int startSkipSlaveAddr = 0;
535 constexpr int endSkipSlaveAddr = 12;
536
James Feist26c27ad2018-07-25 15:09:40 -0700537 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800538 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700539 if (skipList.find(ii) != skipList.end())
540 {
541 continue;
542 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530543 // skipping since no device is present in this range
544 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
545 {
546 continue;
547 }
James Feist26c27ad2018-07-25 15:09:40 -0700548 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530549 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800550 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700551 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700552 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700553 continue;
554 }
555 // probe
556 else if (i2c_smbus_read_byte(file) < 0)
557 {
558 continue;
559 }
James Feist3cb5fec2018-01-23 14:41:51 -0800560
James Feist26c27ad2018-07-25 15:09:40 -0700561 if (DEBUG)
562 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700563 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700564 << "\n";
565 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800566
James Feist8a983922019-10-24 17:11:56 -0700567 makeProbeInterface(bus, ii);
568
James Feist7972bb92019-11-13 15:59:24 -0800569 if (failedItems.find(ii) != failedItems.end())
570 {
571 // if we failed to read it once, unlikely we can read it later
572 continue;
573 }
574
575 if (rootFailures != nullptr)
576 {
577 if (rootFailures->find(ii) != rootFailures->end())
578 {
579 continue;
580 }
581 }
582
Vijay Khemka2d681f62018-11-06 15:51:00 -0800583 /* Check for Device type if it is 8 bit or 16 bit */
584 int flag = isDevice16Bit(file);
585 if (flag < 0)
586 {
587 std::cerr << "failed to read bus " << bus << " address " << ii
588 << "\n";
James Feist7972bb92019-11-13 15:59:24 -0800589 failedItems.insert(ii);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800590 continue;
591 }
592
Patrick Venturebaba7672019-10-26 09:26:41 -0700593 std::string errorMessage =
594 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
595 std::vector<char> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800596 readFruContents(flag, file, static_cast<uint16_t>(ii),
597 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700598 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700599 {
James Feist26c27ad2018-07-25 15:09:40 -0700600 continue;
601 }
James Feist26c27ad2018-07-25 15:09:40 -0700602
Patrick Venture786f1792019-08-05 16:33:44 -0700603 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800604 }
James Feist26c27ad2018-07-25 15:09:40 -0700605 return 1;
606 });
607 std::future_status status =
608 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
609 if (status == std::future_status::timeout)
610 {
611 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700612 busBlacklist.insert(bus);
613 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700614 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800615 }
616
James Feist444830e2019-04-05 08:38:16 -0700617 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700618 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800619}
620
Patrick Venture11f1ff42019-08-01 10:42:12 -0700621void loadBlacklist(const char* path)
622{
623 std::ifstream blacklistStream(path);
624 if (!blacklistStream.good())
625 {
626 // File is optional.
627 std::cerr << "Cannot open blacklist file.\n\n";
628 return;
629 }
630
631 nlohmann::json data =
632 nlohmann::json::parse(blacklistStream, nullptr, false);
633 if (data.is_discarded())
634 {
635 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
636 "exiting\n";
637 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700638 }
639
640 // It's expected to have at least one field, "buses" that is an array of the
641 // buses by integer. Allow for future options to exclude further aspects,
642 // such as specific addresses or ranges.
643 if (data.type() != nlohmann::json::value_t::object)
644 {
645 std::cerr << "Illegal blacklist, expected to read dictionary\n";
646 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700647 }
648
649 // If buses field is missing, that's fine.
650 if (data.count("buses") == 1)
651 {
652 // Parse the buses array after a little validation.
653 auto buses = data.at("buses");
654 if (buses.type() != nlohmann::json::value_t::array)
655 {
656 // Buses field present but invalid, therefore this is an error.
657 std::cerr << "Invalid contents for blacklist buses field\n";
658 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700659 }
660
661 // Catch exception here for type mis-match.
662 try
663 {
664 for (const auto& bus : buses)
665 {
666 busBlacklist.insert(bus.get<size_t>());
667 }
668 }
669 catch (const nlohmann::detail::type_error& e)
670 {
671 // Type mis-match is a critical error.
672 std::cerr << "Invalid bus type: " << e.what() << "\n";
673 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700674 }
675 }
676
677 return;
678}
679
James Feista465ccc2019-02-08 12:51:01 -0800680static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700681 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800682{
James Feista465ccc2019-02-08 12:51:01 -0800683 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800684 {
685 auto busnum = i2cBus.string();
686 auto lastDash = busnum.rfind(std::string("-"));
687 // delete everything before dash inclusive
688 if (lastDash != std::string::npos)
689 {
690 busnum.erase(0, lastDash + 1);
691 }
James Feist0c3980a2019-12-19 11:09:27 -0800692
James Feist3cb5fec2018-01-23 14:41:51 -0800693 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700694 if (busBlacklist.find(bus) != busBlacklist.end())
695 {
696 continue; // skip previously failed busses
697 }
James Feist3cb5fec2018-01-23 14:41:51 -0800698
James Feist0c3980a2019-12-19 11:09:27 -0800699 int rootBus = getRootBus(bus);
700 if (busBlacklist.find(rootBus) != busBlacklist.end())
701 {
702 continue;
703 }
704
James Feist3cb5fec2018-01-23 14:41:51 -0800705 auto file = open(i2cBus.c_str(), O_RDWR);
706 if (file < 0)
707 {
708 std::cerr << "unable to open i2c device " << i2cBus.string()
709 << "\n";
710 continue;
711 }
712 unsigned long funcs = 0;
713
714 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
715 {
716 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700717 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800718 << bus << "\n";
719 continue;
720 }
721 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
722 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
723 {
724 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
725 << bus << "\n";
726 continue;
727 }
James Feist98132792019-07-09 13:29:09 -0700728 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800729 device = std::make_shared<DeviceMap>();
730
Nikhil Potaded8884f12019-03-27 13:27:13 -0700731 // i2cdetect by default uses the range 0x03 to 0x77, as
732 // this is what we have tested with, use this range. Could be
733 // changed in future.
734 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800735 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700736 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800737 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700738
739 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700740 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700741
742 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800743 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700744 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800745 }
James Feist3cb5fec2018-01-23 14:41:51 -0800746 }
James Feist3cb5fec2018-01-23 14:41:51 -0800747}
748
James Feist6ebf9de2018-05-15 15:01:17 -0700749// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700750struct FindDevicesWithCallback :
751 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700752{
James Feista465ccc2019-02-08 12:51:01 -0800753 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700754 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800755 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700756 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700757 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700758 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700759 ~FindDevicesWithCallback()
760 {
761 _callback();
762 }
763 void run()
764 {
James Feist98132792019-07-09 13:29:09 -0700765 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700766 }
767
James Feista465ccc2019-02-08 12:51:01 -0800768 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800769 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700770 std::function<void(void)> _callback;
771};
772
James Feist3cb5fec2018-01-23 14:41:51 -0800773static const std::tm intelEpoch(void)
774{
James Feist98132792019-07-09 13:29:09 -0700775 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800776 val.tm_year = 1996 - 1900;
777 return val;
778}
779
James Feista465ccc2019-02-08 12:51:01 -0800780bool formatFru(const std::vector<char>& fruBytes,
781 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800782{
James Feista465ccc2019-02-08 12:51:01 -0800783 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800784 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800785
James Feista465ccc2019-02-08 12:51:01 -0800786 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800787 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
788 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800789
James Feista465ccc2019-02-08 12:51:01 -0800790 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800791 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
792 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
793 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800794
James Feistd068e932018-09-20 10:53:07 -0700795 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800796 {
797 return false;
798 }
799 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700800 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800801 std::to_string(static_cast<int>(*fruAreaOffsetField));
802
James Feista465ccc2019-02-08 12:51:01 -0800803 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800804
James Feist0eb40352019-04-09 14:44:04 -0700805 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800806 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700807 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800808 if (fruAreaOffsetField >= fruBytes.end())
809 {
810 return false;
811 }
812 size_t offset = (*fruAreaOffsetField) * 8;
813
814 if (offset > 1)
815 {
816 // +2 to skip format and length
817 std::vector<char>::const_iterator fruBytesIter =
818 fruBytes.begin() + offset + 2;
819
820 if (fruBytesIter >= fruBytes.end())
821 {
822 return false;
823 }
824
825 if (area == "CHASSIS")
826 {
827 result["CHASSIS_TYPE"] =
828 std::to_string(static_cast<int>(*fruBytesIter));
829 fruBytesIter += 1;
830 fieldData = &CHASSIS_FRU_AREAS;
831 }
832 else if (area == "BOARD")
833 {
834 result["BOARD_LANGUAGE_CODE"] =
835 std::to_string(static_cast<int>(*fruBytesIter));
836 fruBytesIter += 1;
837 if (fruBytesIter >= fruBytes.end())
838 {
839 return false;
840 }
841
842 unsigned int minutes = *fruBytesIter |
843 *(fruBytesIter + 1) << 8 |
844 *(fruBytesIter + 2) << 16;
845 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700846 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800847 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700848 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800849
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700850 // Tue Nov 20 23:08:00 2018
851 char timeString[32] = {0};
852 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700853 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700854 if (bytes == 0)
855 {
856 std::cerr << "invalid time string encountered\n";
857 return false;
858 }
859
860 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800861 fruBytesIter += 3;
862 fieldData = &BOARD_FRU_AREAS;
863 }
864 else if (area == "PRODUCT")
865 {
866 result["PRODUCT_LANGUAGE_CODE"] =
867 std::to_string(static_cast<int>(*fruBytesIter));
868 fruBytesIter += 1;
869 fieldData = &PRODUCT_FRU_AREAS;
870 }
871 else
872 {
873 continue;
874 }
James Feista465ccc2019-02-08 12:51:01 -0800875 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800876 {
877 if (fruBytesIter >= fruBytes.end())
878 {
879 return false;
880 }
881
Vijay Khemka5d5de442018-11-07 10:51:25 -0800882 /* Checking for last byte C1 to indicate that no more
883 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700884 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800885 {
886 break;
887 }
888
Ed Tanous2147e672019-02-27 13:59:56 -0800889 size_t length = *fruBytesIter & 0x3f;
890 fruBytesIter += 1;
891
James Feist3cb5fec2018-01-23 14:41:51 -0800892 if (fruBytesIter >= fruBytes.end())
893 {
894 return false;
895 }
Ed Tanous2147e672019-02-27 13:59:56 -0800896 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800897
Ed Tanous2147e672019-02-27 13:59:56 -0800898 // Strip non null characters from the end
899 value.erase(std::find_if(value.rbegin(), value.rend(),
900 [](char ch) { return ch != 0; })
901 .base(),
902 value.end());
903
James Feist0eb40352019-04-09 14:44:04 -0700904 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800905
James Feist3cb5fec2018-01-23 14:41:51 -0800906 fruBytesIter += length;
907 if (fruBytesIter >= fruBytes.end())
908 {
909 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800910 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800911 {
912 std::cerr << c;
913 }
914 std::cerr << "\n";
915 if (DEBUG)
916 {
James Feista465ccc2019-02-08 12:51:01 -0800917 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800918 {
919 std::cerr << keyPair.first << " : "
920 << keyPair.second << "\n";
921 }
922 }
923 return false;
924 }
925 }
926 }
927 }
928
929 return true;
930}
931
Nikhil Potaded8884f12019-03-27 13:27:13 -0700932std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
933{
934 auto deviceMap = busMap.find(bus);
935 if (deviceMap == busMap.end())
936 {
937 throw std::invalid_argument("Invalid Bus.");
938 }
939 auto device = deviceMap->second->find(address);
940 if (device == deviceMap->second->end())
941 {
942 throw std::invalid_argument("Invalid Address.");
943 }
944 std::vector<uint8_t>& ret =
945 reinterpret_cast<std::vector<uint8_t>&>(device->second);
946
947 return ret;
948}
949
James Feist3cb5fec2018-01-23 14:41:51 -0800950void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700951 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800952 boost::container::flat_map<
953 std::pair<size_t, size_t>,
954 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700955 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800956{
957 boost::container::flat_map<std::string, std::string> formattedFru;
958 if (!formatFru(device, formattedFru))
959 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700960 std::cerr << "failed to format fru for device at bus " << bus
961 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800962 return;
963 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700964
James Feist3cb5fec2018-01-23 14:41:51 -0800965 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
966 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700967 // Not found under Board section or an empty string.
968 if (productNameFind == formattedFru.end() ||
969 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800970 {
971 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
972 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700973 // Found under Product section and not an empty string.
974 if (productNameFind != formattedFru.end() &&
975 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800976 {
977 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800978 std::regex illegalObject("[^A-Za-z0-9_]");
979 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800980 }
981 else
982 {
983 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
984 UNKNOWN_BUS_OBJECT_COUNT++;
985 }
986
James Feist918e18c2018-02-13 15:51:07 -0800987 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800988 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700989 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800990 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700991 int highest = -1;
992 bool found = false;
993
James Feista465ccc2019-02-08 12:51:01 -0800994 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800995 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700996 std::string path = busIface.second->get_object_path();
997 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800998 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700999 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -07001000 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
1001 static_cast<uint8_t>(busIface.first.second)) ==
1002 getFruInfo(static_cast<uint8_t>(bus),
1003 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001004 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001005 // This device is already added to the lower numbered bus,
1006 // do not replicate it.
1007 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001008 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001009
1010 // Check if the match named has extra information.
1011 found = true;
1012 std::smatch base_match;
1013
1014 bool match = std::regex_match(
1015 path, base_match, std::regex(productName + "_(\\d+)$"));
1016 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001017 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001018 if (base_match.size() == 2)
1019 {
1020 std::ssub_match base_sub_match = base_match[1];
1021 std::string base = base_sub_match.str();
1022
1023 int value = std::stoi(base);
1024 highest = (value > highest) ? value : highest;
1025 }
James Feist79e9c0b2018-03-15 15:21:17 -07001026 }
James Feist918e18c2018-02-13 15:51:07 -08001027 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001028 } // end searching objects
1029
1030 if (found)
1031 {
1032 // We found something with the same name. If highest was still -1,
1033 // it means this new entry will be _0.
1034 productName += "_";
1035 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001036 }
1037 }
James Feist3cb5fec2018-01-23 14:41:51 -08001038
James Feist9eb0b582018-04-27 12:15:46 -07001039 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1040 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1041 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1042
James Feista465ccc2019-02-08 12:51:01 -08001043 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001044 {
James Feist9eb0b582018-04-27 12:15:46 -07001045
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001046 std::regex_replace(property.second.begin(), property.second.begin(),
1047 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -07001048 if (property.second.empty())
1049 {
1050 continue;
1051 }
1052 std::string key =
1053 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
1054 if (!iface->register_property(key, property.second + '\0'))
1055 {
1056 std::cerr << "illegal key: " << key << "\n";
1057 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001058 if (DEBUG)
1059 {
1060 std::cout << property.first << ": " << property.second << "\n";
1061 }
James Feist3cb5fec2018-01-23 14:41:51 -08001062 }
James Feist2a9d6db2018-04-27 15:48:28 -07001063
1064 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001065 iface->register_property("BUS", bus);
1066 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001067
James Feist9eb0b582018-04-27 12:15:46 -07001068 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001069}
1070
James Feista465ccc2019-02-08 12:51:01 -08001071static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001072{
1073 // try to read baseboard fru from file
1074 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1075 if (baseboardFruFile.good())
1076 {
1077 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001078 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001079 baseboardFru.resize(fileSize);
1080 baseboardFruFile.seekg(0, std::ios_base::beg);
1081 baseboardFruFile.read(baseboardFru.data(), fileSize);
1082 }
1083 else
1084 {
1085 return false;
1086 }
1087 return true;
1088}
1089
James Feista465ccc2019-02-08 12:51:01 -08001090bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001091{
1092 boost::container::flat_map<std::string, std::string> tmp;
1093 if (fru.size() > MAX_FRU_SIZE)
1094 {
1095 std::cerr << "Invalid fru.size() during writeFru\n";
1096 return false;
1097 }
1098 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001099 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001100 {
1101 std::cerr << "Invalid fru format during writeFru\n";
1102 return false;
1103 }
1104 // baseboard fru
1105 if (bus == 0 && address == 0)
1106 {
1107 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1108 if (!file.good())
1109 {
1110 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1111 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001112 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001113 return false;
1114 }
James Feista465ccc2019-02-08 12:51:01 -08001115 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001116 return file.good();
1117 }
1118 else
1119 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001120 if (hasEepromFile(bus, address))
1121 {
1122 auto path = getEepromPath(bus, address);
1123 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1124 if (eeprom < 0)
1125 {
1126 std::cerr << "unable to open i2c device " << path << "\n";
1127 throw DBusInternalError();
1128 return false;
1129 }
1130
1131 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1132 if (writtenBytes < 0)
1133 {
1134 std::cerr << "unable to write to i2c device " << path << "\n";
1135 close(eeprom);
1136 throw DBusInternalError();
1137 return false;
1138 }
1139
1140 close(eeprom);
1141 return true;
1142 }
1143
James Feistb49ffc32018-05-02 11:10:43 -07001144 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1145
1146 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1147 if (file < 0)
1148 {
1149 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001150 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001151 return false;
1152 }
1153 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1154 {
1155 std::cerr << "unable to set device address\n";
1156 close(file);
James Feistddb78302018-09-06 11:45:42 -07001157 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001158 return false;
1159 }
1160
1161 constexpr const size_t RETRY_MAX = 2;
1162 uint16_t index = 0;
1163 size_t retries = RETRY_MAX;
1164 while (index < fru.size())
1165 {
1166 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1167 (retries == RETRY_MAX))
1168 {
1169 // The 4K EEPROM only uses the A2 and A1 device address bits
1170 // with the third bit being a memory page address bit.
1171 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1172 {
1173 std::cerr << "unable to set device address\n";
1174 close(file);
James Feistddb78302018-09-06 11:45:42 -07001175 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001176 return false;
1177 }
1178 }
1179
James Feist98132792019-07-09 13:29:09 -07001180 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1181 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001182 {
1183 if (!retries--)
1184 {
1185 std::cerr << "error writing fru: " << strerror(errno)
1186 << "\n";
1187 close(file);
James Feistddb78302018-09-06 11:45:42 -07001188 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001189 return false;
1190 }
1191 }
1192 else
1193 {
1194 retries = RETRY_MAX;
1195 index++;
1196 }
1197 // most eeproms require 5-10ms between writes
1198 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1199 }
1200 close(file);
1201 return true;
1202 }
1203}
1204
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001205void rescanOneBus(
1206 BusMap& busmap, uint8_t busNum,
1207 boost::container::flat_map<
1208 std::pair<size_t, size_t>,
1209 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1210{
1211 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1212 if (!fs::exists(busPath))
1213 {
1214 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1215 << "\n";
1216 throw std::invalid_argument("Invalid Bus.");
1217 }
1218
1219 std::vector<fs::path> i2cBuses;
1220 i2cBuses.emplace_back(busPath);
1221
1222 for (auto& [pair, interface] : foundDevices)
1223 {
1224 if (pair.first == static_cast<size_t>(busNum))
1225 {
1226 objServer.remove_interface(interface);
1227 foundDevices.erase(pair);
1228 }
1229 }
1230
1231 auto scan = std::make_shared<FindDevicesWithCallback>(
1232 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1233 for (auto& busIface : dbusInterfaceMap)
1234 {
1235 if (busIface.first.first == static_cast<size_t>(busNum))
1236 {
1237 objServer.remove_interface(busIface.second);
1238 }
1239 }
1240 auto& devicemap = busmap[busNum];
1241 for (auto& device : *devicemap)
1242 {
1243 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1244 static_cast<uint32_t>(busNum), device.first);
1245 }
1246 });
1247 scan->run();
1248}
1249
James Feist9eb0b582018-04-27 12:15:46 -07001250void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001251 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001252 boost::container::flat_map<
1253 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001254 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001255{
James Feist6ebf9de2018-05-15 15:01:17 -07001256 static boost::asio::deadline_timer timer(io);
1257 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001258
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001259 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001260 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001261 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001262 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001263
Nikhil Potaded8884f12019-03-27 13:27:13 -07001264 boost::container::flat_map<size_t, fs::path> busPaths;
1265 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001266 {
James Feist4131aea2018-03-09 09:47:30 -08001267 std::cerr << "unable to find i2c devices\n";
1268 return;
James Feist918e18c2018-02-13 15:51:07 -08001269 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001270
1271 for (auto busPath : busPaths)
1272 {
1273 i2cBuses.emplace_back(busPath.second);
1274 }
James Feist4131aea2018-03-09 09:47:30 -08001275
James Feist98132792019-07-09 13:29:09 -07001276 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001277 for (auto& [pair, interface] : foundDevices)
1278 {
1279 objServer.remove_interface(interface);
1280 }
1281 foundDevices.clear();
1282
James Feist5cb06082019-10-24 17:11:13 -07001283 auto scan =
1284 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001285 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001286 {
1287 objServer.remove_interface(busIface.second);
1288 }
James Feist4131aea2018-03-09 09:47:30 -08001289
James Feist6ebf9de2018-05-15 15:01:17 -07001290 dbusInterfaceMap.clear();
1291 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001292
James Feist6ebf9de2018-05-15 15:01:17 -07001293 // todo, get this from a more sensable place
1294 std::vector<char> baseboardFru;
1295 if (readBaseboardFru(baseboardFru))
1296 {
1297 boost::container::flat_map<int, std::vector<char>>
1298 baseboardDev;
1299 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001300 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001301 }
James Feist98132792019-07-09 13:29:09 -07001302 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001303 {
James Feista465ccc2019-02-08 12:51:01 -08001304 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001305 {
James Feist5cb06082019-10-24 17:11:13 -07001306 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1307 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001308 }
1309 }
1310 });
1311 scan->run();
1312 });
James Feist918e18c2018-02-13 15:51:07 -08001313}
1314
James Feist98132792019-07-09 13:29:09 -07001315int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001316{
1317 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001318 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001319 std::vector<fs::path> i2cBuses;
1320
James Feista3c180a2018-08-09 16:06:04 -07001321 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001322 {
1323 std::cerr << "unable to find i2c devices\n";
1324 return 1;
1325 }
James Feist3cb5fec2018-01-23 14:41:51 -08001326
Patrick Venture11f1ff42019-08-01 10:42:12 -07001327 // check for and load blacklist with initial buses.
1328 loadBlacklist(blacklistPath);
1329
Vijay Khemka065f6d92018-12-18 10:37:47 -08001330 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001331
James Feist6ebf9de2018-05-15 15:01:17 -07001332 // this is a map with keys of pair(bus number, address) and values of
1333 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001334 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001335 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1336 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001337
James Feist9eb0b582018-04-27 12:15:46 -07001338 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1339 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1340 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001341
James Feist5cb06082019-10-24 17:11:13 -07001342 iface->register_method("ReScan",
1343 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001344
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001345 iface->register_method("ReScanBus", [&](uint8_t bus) {
1346 rescanOneBus(busMap, bus, dbusInterfaceMap);
1347 });
1348
Nikhil Potaded8884f12019-03-27 13:27:13 -07001349 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001350
1351 iface->register_method("WriteFru", [&](const uint8_t bus,
1352 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001353 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001354 if (!writeFru(bus, address, data))
1355 {
James Feistddb78302018-09-06 11:45:42 -07001356 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001357 return;
1358 }
1359 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001360 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001361 });
James Feist9eb0b582018-04-27 12:15:46 -07001362 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001363
James Feist9eb0b582018-04-27 12:15:46 -07001364 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001365 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001366 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001367 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001368 std::string,
1369 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001370 values;
1371 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001372 auto findState = values.find("CurrentHostState");
1373 bool on = false;
1374 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001375 {
James Feist0eeb79c2019-10-09 13:35:29 -07001376 on = boost::ends_with(std::get<std::string>(findState->second),
1377 "Running");
1378 }
James Feist6ebf9de2018-05-15 15:01:17 -07001379
James Feist0eeb79c2019-10-09 13:35:29 -07001380 if (on)
1381 {
James Feist5cb06082019-10-24 17:11:13 -07001382 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001383 }
James Feist918e18c2018-02-13 15:51:07 -08001384 };
James Feist9eb0b582018-04-27 12:15:46 -07001385
1386 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001387 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001388 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001389 "openbmc_project/state/"
1390 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001391 eventHandler);
1392
James Feist4131aea2018-03-09 09:47:30 -08001393 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001394 inotify_add_watch(fd, I2C_DEV_LOCATION,
1395 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001396 std::array<char, 4096> readBuffer;
1397 std::string pendingBuffer;
1398 // monitor for new i2c devices
1399 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1400 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001401 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001402 std::size_t bytes_transferred) {
1403 if (ec)
1404 {
1405 std::cout << "Callback Error " << ec << "\n";
1406 return;
1407 }
1408 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1409 bool devChange = false;
1410 while (pendingBuffer.size() > sizeof(inotify_event))
1411 {
James Feista465ccc2019-02-08 12:51:01 -08001412 const inotify_event* iEvent =
1413 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001414 pendingBuffer.data());
1415 switch (iEvent->mask)
1416 {
James Feist9eb0b582018-04-27 12:15:46 -07001417 case IN_CREATE:
1418 case IN_MOVED_TO:
1419 case IN_DELETE:
1420 if (boost::starts_with(std::string(iEvent->name),
1421 "i2c"))
1422 {
1423 devChange = true;
1424 }
James Feist4131aea2018-03-09 09:47:30 -08001425 }
1426
1427 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1428 }
James Feist6ebf9de2018-05-15 15:01:17 -07001429 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001430 {
James Feist5cb06082019-10-24 17:11:13 -07001431 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001432 }
James Feist6ebf9de2018-05-15 15:01:17 -07001433
James Feist4131aea2018-03-09 09:47:30 -08001434 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1435 watchI2cBusses);
1436 };
1437
1438 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001439 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001440 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001441
James Feist3cb5fec2018-01-23 14:41:51 -08001442 io.run();
1443 return 0;
1444}