blob: 874bbb133b68be3a02b3482fabaf1836a55c57f5 [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 Feistcb5661d2020-06-12 15:05:01 -070079static bool powerIsOn = false;
80
James Feist8a983922019-10-24 17:11:56 -070081static boost::container::flat_map<
82 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
83 foundDevices;
84
James Feist7972bb92019-11-13 15:59:24 -080085static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
86
James Feist5cb06082019-10-24 17:11:13 -070087boost::asio::io_service io;
88auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
89auto objServer = sdbusplus::asio::object_server(systemBus);
90
Patrick Venturebaba7672019-10-26 09:26:41 -070091bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
92
Xiang Liu2801a702020-01-20 14:29:34 -080093using ReadBlockFunc =
94 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
95 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -070096
97// Read and validate FRU contents, given the flag required for raw i2c, the open
98// file handle, a read method, and a helper string for failures.
Xiang Liu2801a702020-01-20 14:29:34 -080099std::vector<char> readFruContents(int flag, int file, uint16_t address,
100 ReadBlockFunc readBlock,
Patrick Venturebaba7672019-10-26 09:26:41 -0700101 const std::string& errorHelp)
102{
103 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
104
Xiang Liu2801a702020-01-20 14:29:34 -0800105 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700106 {
107 std::cerr << "failed to read " << errorHelp << "\n";
108 return {};
109 }
110
111 // check the header checksum
112 if (!validateHeader(blockData))
113 {
114 if (DEBUG)
115 {
116 std::cerr << "Illegal header " << errorHelp << "\n";
117 }
118
119 return {};
120 }
121
122 std::vector<char> device;
123 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
124
Patrick Venturee26395d2019-10-29 14:05:16 -0700125 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700126 int fruLength = 0;
127 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
128 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700129 // Offset value can be 255.
130 int areaOffset = static_cast<uint8_t>(device[jj]);
Patrick Venturebaba7672019-10-26 09:26:41 -0700131 if (areaOffset == 0)
132 {
133 continue;
134 }
135
Patrick Venturee26395d2019-10-29 14:05:16 -0700136 // MultiRecords are different. jj is not tracking section, it's walking
137 // the common header.
138 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
139 {
140 hasMultiRecords = true;
141 break;
142 }
143
Patrick Venturebaba7672019-10-26 09:26:41 -0700144 areaOffset *= 8;
145
Xiang Liu2801a702020-01-20 14:29:34 -0800146 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
147 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700148 {
149 std::cerr << "failed to read " << errorHelp << "\n";
150 return {};
151 }
152
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700153 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700154 int length = blockData[1] * 8;
155 areaOffset += length;
156 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
157 }
158
Patrick Venturee26395d2019-10-29 14:05:16 -0700159 if (hasMultiRecords)
160 {
161 // device[area count] is the index to the last area because the 0th
162 // entry is not an offset in the common header.
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700163 int areaOffset = static_cast<uint8_t>(device[FRU_AREAS.size()]);
Patrick Venturee26395d2019-10-29 14:05:16 -0700164 areaOffset *= 8;
165
166 // the multi-area record header is 5 bytes long.
167 constexpr int multiRecordHeaderSize = 5;
168 constexpr int multiRecordEndOfList = 0x80;
169
170 // Sanity hard-limit to 64KB.
171 while (areaOffset < std::numeric_limits<uint16_t>::max())
172 {
173 // In multi-area, the area offset points to the 0th record, each
174 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800175 if (readBlock(flag, file, address,
176 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700177 blockData.data()) < 0)
178 {
179 std::cerr << "failed to read " << errorHelp << "\n";
180 return {};
181 }
182
183 // Ok, let's check the record length, which is in bytes (unsigned,
184 // up to 255, so blockData should hold uint8_t not char)
185 int recordLength = blockData[2];
186 areaOffset += (recordLength + multiRecordHeaderSize);
187 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
188
189 // If this is the end of the list bail.
190 if ((blockData[1] & multiRecordEndOfList))
191 {
192 break;
193 }
194 }
195 }
196
Patrick Venturebaba7672019-10-26 09:26:41 -0700197 // You already copied these first 8 bytes (the ipmi fru header size)
198 fruLength -= 8;
199
200 int readOffset = 8;
201
202 while (fruLength > 0)
203 {
204 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
205
Xiang Liu2801a702020-01-20 14:29:34 -0800206 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700207 static_cast<uint8_t>(requestLength),
208 blockData.data()) < 0)
209 {
210 std::cerr << "failed to read " << errorHelp << "\n";
211 return {};
212 }
213
214 device.insert(device.end(), blockData.begin(),
215 blockData.begin() + requestLength);
216
217 readOffset += requestLength;
218 fruLength -= requestLength;
219 }
220
221 return device;
222}
223
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700224// Given a bus/address, produce the path in sysfs for an eeprom.
225static std::string getEepromPath(size_t bus, size_t address)
226{
227 std::stringstream output;
228 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
229 << std::setfill('0') << std::setw(4) << std::hex << address
230 << "/eeprom";
231 return output.str();
232}
233
234static bool hasEepromFile(size_t bus, size_t address)
235{
236 auto path = getEepromPath(bus, address);
237 try
238 {
239 return fs::exists(path);
240 }
241 catch (...)
242 {
243 return false;
244 }
245}
246
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700247static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800248 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700249 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700250{
251 auto result = lseek(fd, offset, SEEK_SET);
252 if (result < 0)
253 {
254 std::cerr << "failed to seek\n";
255 return -1;
256 }
257
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700258 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700259}
260
James Feist7972bb92019-11-13 15:59:24 -0800261static int getRootBus(size_t bus)
262{
263 auto ec = std::error_code();
264 auto path = std::filesystem::read_symlink(
265 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
266 std::to_string(bus) + "/mux_device"),
267 ec);
268 if (ec)
269 {
270 return -1;
271 }
272
273 std::string filename = path.filename();
274 auto findBus = filename.find("-");
275 if (findBus == std::string::npos)
276 {
277 return -1;
278 }
279 return std::stoi(filename.substr(0, findBus));
280}
281
James Feistc95cb142018-02-26 10:41:42 -0800282static bool isMuxBus(size_t bus)
283{
Ed Tanous072e25d2018-12-16 21:45:20 -0800284 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800285 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
286}
287
James Feist8a983922019-10-24 17:11:56 -0700288static void makeProbeInterface(size_t bus, size_t address)
289{
290 if (isMuxBus(bus))
291 {
292 return; // the mux buses are random, no need to publish
293 }
294 auto [it, success] = foundDevices.emplace(
295 std::make_pair(bus, address),
296 objServer.add_interface(
297 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
298 std::to_string(address),
299 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
300 if (!success)
301 {
302 return; // already added
303 }
304 it->second->register_property("Bus", bus);
305 it->second->register_property("Address", address);
306 it->second->initialize();
307}
308
Vijay Khemka2d681f62018-11-06 15:51:00 -0800309static int isDevice16Bit(int file)
310{
311 /* Get first byte */
312 int byte1 = i2c_smbus_read_byte_data(file, 0);
313 if (byte1 < 0)
314 {
315 return byte1;
316 }
317 /* Read 7 more bytes, it will read same first byte in case of
318 * 8 bit but it will read next byte in case of 16 bit
319 */
320 for (int i = 0; i < 7; i++)
321 {
322 int byte2 = i2c_smbus_read_byte_data(file, 0);
323 if (byte2 < 0)
324 {
325 return byte2;
326 }
327 if (byte2 != byte1)
328 {
329 return 1;
330 }
331 }
332 return 0;
333}
334
Xiang Liu2801a702020-01-20 14:29:34 -0800335// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
336// from_slave_buf_len bytes.
337static int i2c_smbus_write_then_read(int file, uint16_t address,
338 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
339 uint8_t* fromSlaveBuf,
340 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800341{
Xiang Liu2801a702020-01-20 14:29:34 -0800342 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
343 fromSlaveBufLen == 0)
344 {
345 return -1;
346 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800347
Xiang Liu2801a702020-01-20 14:29:34 -0800348#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
349 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
350 struct i2c_rdwr_ioctl_data rdwr;
351
352 msgs[0].addr = address;
353 msgs[0].flags = 0;
354 msgs[0].len = toSlaveBufLen;
355 msgs[0].buf = toSlaveBuf;
356 msgs[1].addr = address;
357 msgs[1].flags = I2C_M_RD;
358 msgs[1].len = fromSlaveBufLen;
359 msgs[1].buf = fromSlaveBuf;
360
361 rdwr.msgs = msgs;
362 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
363
364 int ret = ioctl(file, I2C_RDWR, &rdwr);
365
366 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
367}
368
369static int64_t readBlockData(int flag, int file, uint16_t address,
370 uint16_t offset, uint8_t len, uint8_t* buf)
371{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800372 if (flag == 0)
373 {
Xiang Liu2801a702020-01-20 14:29:34 -0800374 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
375 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800376 }
377
Xiang Liu2801a702020-01-20 14:29:34 -0800378 offset = htobe16(offset);
379 return i2c_smbus_write_then_read(
380 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800381}
382
James Feist24bae7a2019-04-03 09:50:56 -0700383bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
384{
385 // ipmi spec format version number is currently at 1, verify it
386 if (blockData[0] != 0x1)
387 {
388 return false;
389 }
390
391 // verify pad is set to 0
392 if (blockData[6] != 0x0)
393 {
394 return false;
395 }
396
397 // verify offsets are 0, or don't point to another offset
398 std::set<uint8_t> foundOffsets;
399 for (int ii = 1; ii < 6; ii++)
400 {
401 if (blockData[ii] == 0)
402 {
403 continue;
404 }
James Feist0eb40352019-04-09 14:44:04 -0700405 auto inserted = foundOffsets.insert(blockData[ii]);
406 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700407 {
408 return false;
409 }
410 }
411
412 // validate checksum
413 size_t sum = 0;
414 for (int jj = 0; jj < 7; jj++)
415 {
416 sum += blockData[jj];
417 }
418 sum = (256 - sum) & 0xFF;
419
420 if (sum != blockData[7])
421 {
422 return false;
423 }
424 return true;
425}
426
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700427// TODO: This code is very similar to the non-eeprom version and can be merged
428// with some tweaks.
429static std::vector<char> processEeprom(int bus, int address)
430{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700431 auto path = getEepromPath(bus, address);
432
433 int file = open(path.c_str(), O_RDONLY);
434 if (file < 0)
435 {
436 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700437 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700438 }
439
Patrick Venturebaba7672019-10-26 09:26:41 -0700440 std::string errorMessage = "eeprom at " + std::to_string(bus) +
441 " address " + std::to_string(address);
Xiang Liu2801a702020-01-20 14:29:34 -0800442 std::vector<char> device = readFruContents(
443 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700444
445 close(file);
446 return device;
447}
448
449std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
450{
451 std::set<int> foundList;
452
453 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
454
455 // For each file listed under the i2c device
456 // NOTE: This should be faster than just checking for each possible address
457 // path.
458 for (const auto& p : fs::directory_iterator(path))
459 {
460 const std::string node = p.path().string();
461 std::smatch m;
462 bool found =
463 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
464
465 if (!found)
466 {
467 continue;
468 }
469 if (m.size() != 2)
470 {
471 std::cerr << "regex didn't capture\n";
472 continue;
473 }
474
475 std::ssub_match subMatch = m[1];
476 std::string addressString = subMatch.str();
477
478 std::size_t ignored;
479 const int hexBase = 16;
480 int address = std::stoi(addressString, &ignored, hexBase);
481
482 const std::string eeprom = node + "/eeprom";
483
484 try
485 {
486 if (!fs::exists(eeprom))
487 {
488 continue;
489 }
490 }
491 catch (...)
492 {
493 continue;
494 }
495
496 // There is an eeprom file at this address, it may have invalid
497 // contents, but we found it.
498 foundList.insert(address);
499
500 std::vector<char> device = processEeprom(i2cBus, address);
501 if (!device.empty())
502 {
503 devices->emplace(address, device);
504 }
505 }
506
507 return foundList;
508}
509
Patrick Venture4f47fe62019-08-08 16:30:38 -0700510int getBusFrus(int file, int first, int last, int bus,
511 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800512{
James Feist3cb5fec2018-01-23 14:41:51 -0800513
James Feist26c27ad2018-07-25 15:09:40 -0700514 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700515 // NOTE: When reading the devices raw on the bus, it can interfere with
516 // the driver's ability to operate, therefore read eeproms first before
517 // scanning for devices without drivers. Several experiments were run
518 // and it was determined that if there were any devices on the bus
519 // before the eeprom was hit and read, the eeprom driver wouldn't open
520 // while the bus device was open. An experiment was not performed to see
521 // if this issue was resolved if the i2c bus device was closed, but
522 // hexdumps of the eeprom later were successful.
523
524 // Scan for i2c eeproms loaded on this bus.
525 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800526 std::set<size_t>& failedItems = failedAddresses[bus];
527
528 std::set<size_t>* rootFailures = nullptr;
529 int rootBus = getRootBus(bus);
530
531 if (rootBus >= 0)
532 {
533 rootFailures = &(failedAddresses[rootBus]);
534 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700535
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530536 constexpr int startSkipSlaveAddr = 0;
537 constexpr int endSkipSlaveAddr = 12;
538
James Feist26c27ad2018-07-25 15:09:40 -0700539 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800540 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700541 if (skipList.find(ii) != skipList.end())
542 {
543 continue;
544 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530545 // skipping since no device is present in this range
546 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
547 {
548 continue;
549 }
James Feist26c27ad2018-07-25 15:09:40 -0700550 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530551 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800552 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700553 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700554 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700555 continue;
556 }
557 // probe
558 else if (i2c_smbus_read_byte(file) < 0)
559 {
560 continue;
561 }
James Feist3cb5fec2018-01-23 14:41:51 -0800562
James Feist26c27ad2018-07-25 15:09:40 -0700563 if (DEBUG)
564 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700565 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700566 << "\n";
567 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800568
James Feist8a983922019-10-24 17:11:56 -0700569 makeProbeInterface(bus, ii);
570
James Feist7972bb92019-11-13 15:59:24 -0800571 if (failedItems.find(ii) != failedItems.end())
572 {
573 // if we failed to read it once, unlikely we can read it later
574 continue;
575 }
576
577 if (rootFailures != nullptr)
578 {
579 if (rootFailures->find(ii) != rootFailures->end())
580 {
581 continue;
582 }
583 }
584
Vijay Khemka2d681f62018-11-06 15:51:00 -0800585 /* Check for Device type if it is 8 bit or 16 bit */
586 int flag = isDevice16Bit(file);
587 if (flag < 0)
588 {
589 std::cerr << "failed to read bus " << bus << " address " << ii
590 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700591 if (powerIsOn)
592 {
593 failedItems.insert(ii);
594 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800595 continue;
596 }
597
Patrick Venturebaba7672019-10-26 09:26:41 -0700598 std::string errorMessage =
599 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
600 std::vector<char> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800601 readFruContents(flag, file, static_cast<uint16_t>(ii),
602 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700603 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700604 {
James Feist26c27ad2018-07-25 15:09:40 -0700605 continue;
606 }
James Feist26c27ad2018-07-25 15:09:40 -0700607
Patrick Venture786f1792019-08-05 16:33:44 -0700608 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800609 }
James Feist26c27ad2018-07-25 15:09:40 -0700610 return 1;
611 });
612 std::future_status status =
613 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
614 if (status == std::future_status::timeout)
615 {
616 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700617 if (powerIsOn)
618 {
619 busBlacklist.insert(bus);
620 }
James Feist444830e2019-04-05 08:38:16 -0700621 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700622 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800623 }
624
James Feist444830e2019-04-05 08:38:16 -0700625 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700626 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800627}
628
Patrick Venture11f1ff42019-08-01 10:42:12 -0700629void loadBlacklist(const char* path)
630{
631 std::ifstream blacklistStream(path);
632 if (!blacklistStream.good())
633 {
634 // File is optional.
635 std::cerr << "Cannot open blacklist file.\n\n";
636 return;
637 }
638
639 nlohmann::json data =
640 nlohmann::json::parse(blacklistStream, nullptr, false);
641 if (data.is_discarded())
642 {
643 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
644 "exiting\n";
645 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700646 }
647
648 // It's expected to have at least one field, "buses" that is an array of the
649 // buses by integer. Allow for future options to exclude further aspects,
650 // such as specific addresses or ranges.
651 if (data.type() != nlohmann::json::value_t::object)
652 {
653 std::cerr << "Illegal blacklist, expected to read dictionary\n";
654 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700655 }
656
657 // If buses field is missing, that's fine.
658 if (data.count("buses") == 1)
659 {
660 // Parse the buses array after a little validation.
661 auto buses = data.at("buses");
662 if (buses.type() != nlohmann::json::value_t::array)
663 {
664 // Buses field present but invalid, therefore this is an error.
665 std::cerr << "Invalid contents for blacklist buses field\n";
666 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700667 }
668
669 // Catch exception here for type mis-match.
670 try
671 {
672 for (const auto& bus : buses)
673 {
674 busBlacklist.insert(bus.get<size_t>());
675 }
676 }
677 catch (const nlohmann::detail::type_error& e)
678 {
679 // Type mis-match is a critical error.
680 std::cerr << "Invalid bus type: " << e.what() << "\n";
681 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700682 }
683 }
684
685 return;
686}
687
James Feista465ccc2019-02-08 12:51:01 -0800688static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700689 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800690{
James Feista465ccc2019-02-08 12:51:01 -0800691 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800692 {
693 auto busnum = i2cBus.string();
694 auto lastDash = busnum.rfind(std::string("-"));
695 // delete everything before dash inclusive
696 if (lastDash != std::string::npos)
697 {
698 busnum.erase(0, lastDash + 1);
699 }
James Feist0c3980a2019-12-19 11:09:27 -0800700
James Feist3cb5fec2018-01-23 14:41:51 -0800701 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700702 if (busBlacklist.find(bus) != busBlacklist.end())
703 {
704 continue; // skip previously failed busses
705 }
James Feist3cb5fec2018-01-23 14:41:51 -0800706
James Feist0c3980a2019-12-19 11:09:27 -0800707 int rootBus = getRootBus(bus);
708 if (busBlacklist.find(rootBus) != busBlacklist.end())
709 {
710 continue;
711 }
712
James Feist3cb5fec2018-01-23 14:41:51 -0800713 auto file = open(i2cBus.c_str(), O_RDWR);
714 if (file < 0)
715 {
716 std::cerr << "unable to open i2c device " << i2cBus.string()
717 << "\n";
718 continue;
719 }
720 unsigned long funcs = 0;
721
722 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
723 {
724 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700725 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800726 << bus << "\n";
727 continue;
728 }
729 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
730 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
731 {
732 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
733 << bus << "\n";
734 continue;
735 }
James Feist98132792019-07-09 13:29:09 -0700736 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800737 device = std::make_shared<DeviceMap>();
738
Nikhil Potaded8884f12019-03-27 13:27:13 -0700739 // i2cdetect by default uses the range 0x03 to 0x77, as
740 // this is what we have tested with, use this range. Could be
741 // changed in future.
742 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800743 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700744 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800745 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700746
747 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700748 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700749
750 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800751 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700752 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800753 }
James Feist3cb5fec2018-01-23 14:41:51 -0800754 }
James Feist3cb5fec2018-01-23 14:41:51 -0800755}
756
James Feist6ebf9de2018-05-15 15:01:17 -0700757// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700758struct FindDevicesWithCallback :
759 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700760{
James Feista465ccc2019-02-08 12:51:01 -0800761 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700762 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800763 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700764 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700765 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700766 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700767 ~FindDevicesWithCallback()
768 {
769 _callback();
770 }
771 void run()
772 {
James Feist98132792019-07-09 13:29:09 -0700773 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700774 }
775
James Feista465ccc2019-02-08 12:51:01 -0800776 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800777 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700778 std::function<void(void)> _callback;
779};
780
James Feist3cb5fec2018-01-23 14:41:51 -0800781static const std::tm intelEpoch(void)
782{
James Feist98132792019-07-09 13:29:09 -0700783 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800784 val.tm_year = 1996 - 1900;
785 return val;
786}
787
James Feista465ccc2019-02-08 12:51:01 -0800788bool formatFru(const std::vector<char>& fruBytes,
789 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800790{
James Feista465ccc2019-02-08 12:51:01 -0800791 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800792 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800793
James Feista465ccc2019-02-08 12:51:01 -0800794 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800795 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
796 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800797
James Feista465ccc2019-02-08 12:51:01 -0800798 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800799 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
800 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
801 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800802
James Feistd068e932018-09-20 10:53:07 -0700803 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800804 {
805 return false;
806 }
807 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700808 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800809 std::to_string(static_cast<int>(*fruAreaOffsetField));
810
James Feista465ccc2019-02-08 12:51:01 -0800811 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800812
James Feist0eb40352019-04-09 14:44:04 -0700813 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800814 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700815 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800816 if (fruAreaOffsetField >= fruBytes.end())
817 {
818 return false;
819 }
820 size_t offset = (*fruAreaOffsetField) * 8;
821
822 if (offset > 1)
823 {
824 // +2 to skip format and length
825 std::vector<char>::const_iterator fruBytesIter =
826 fruBytes.begin() + offset + 2;
827
828 if (fruBytesIter >= fruBytes.end())
829 {
830 return false;
831 }
832
833 if (area == "CHASSIS")
834 {
835 result["CHASSIS_TYPE"] =
836 std::to_string(static_cast<int>(*fruBytesIter));
837 fruBytesIter += 1;
838 fieldData = &CHASSIS_FRU_AREAS;
839 }
840 else if (area == "BOARD")
841 {
842 result["BOARD_LANGUAGE_CODE"] =
843 std::to_string(static_cast<int>(*fruBytesIter));
844 fruBytesIter += 1;
845 if (fruBytesIter >= fruBytes.end())
846 {
847 return false;
848 }
849
850 unsigned int minutes = *fruBytesIter |
851 *(fruBytesIter + 1) << 8 |
852 *(fruBytesIter + 2) << 16;
853 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700854 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800855 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700856 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800857
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700858 // Tue Nov 20 23:08:00 2018
859 char timeString[32] = {0};
860 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700861 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700862 if (bytes == 0)
863 {
864 std::cerr << "invalid time string encountered\n";
865 return false;
866 }
867
868 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800869 fruBytesIter += 3;
870 fieldData = &BOARD_FRU_AREAS;
871 }
872 else if (area == "PRODUCT")
873 {
874 result["PRODUCT_LANGUAGE_CODE"] =
875 std::to_string(static_cast<int>(*fruBytesIter));
876 fruBytesIter += 1;
877 fieldData = &PRODUCT_FRU_AREAS;
878 }
879 else
880 {
881 continue;
882 }
James Feista465ccc2019-02-08 12:51:01 -0800883 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800884 {
885 if (fruBytesIter >= fruBytes.end())
886 {
887 return false;
888 }
889
Vijay Khemka5d5de442018-11-07 10:51:25 -0800890 /* Checking for last byte C1 to indicate that no more
891 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700892 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800893 {
894 break;
895 }
896
Ed Tanous2147e672019-02-27 13:59:56 -0800897 size_t length = *fruBytesIter & 0x3f;
898 fruBytesIter += 1;
899
James Feist3cb5fec2018-01-23 14:41:51 -0800900 if (fruBytesIter >= fruBytes.end())
901 {
902 return false;
903 }
Ed Tanous2147e672019-02-27 13:59:56 -0800904 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800905
Ed Tanous2147e672019-02-27 13:59:56 -0800906 // Strip non null characters from the end
907 value.erase(std::find_if(value.rbegin(), value.rend(),
908 [](char ch) { return ch != 0; })
909 .base(),
910 value.end());
911
James Feist0eb40352019-04-09 14:44:04 -0700912 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800913
James Feist3cb5fec2018-01-23 14:41:51 -0800914 fruBytesIter += length;
915 if (fruBytesIter >= fruBytes.end())
916 {
917 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800918 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800919 {
920 std::cerr << c;
921 }
922 std::cerr << "\n";
923 if (DEBUG)
924 {
James Feista465ccc2019-02-08 12:51:01 -0800925 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800926 {
927 std::cerr << keyPair.first << " : "
928 << keyPair.second << "\n";
929 }
930 }
931 return false;
932 }
933 }
934 }
935 }
936
937 return true;
938}
939
Nikhil Potaded8884f12019-03-27 13:27:13 -0700940std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
941{
942 auto deviceMap = busMap.find(bus);
943 if (deviceMap == busMap.end())
944 {
945 throw std::invalid_argument("Invalid Bus.");
946 }
947 auto device = deviceMap->second->find(address);
948 if (device == deviceMap->second->end())
949 {
950 throw std::invalid_argument("Invalid Address.");
951 }
952 std::vector<uint8_t>& ret =
953 reinterpret_cast<std::vector<uint8_t>&>(device->second);
954
955 return ret;
956}
957
James Feist3cb5fec2018-01-23 14:41:51 -0800958void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700959 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800960 boost::container::flat_map<
961 std::pair<size_t, size_t>,
962 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700963 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800964{
965 boost::container::flat_map<std::string, std::string> formattedFru;
966 if (!formatFru(device, formattedFru))
967 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700968 std::cerr << "failed to format fru for device at bus " << bus
969 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800970 return;
971 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700972
James Feist3cb5fec2018-01-23 14:41:51 -0800973 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
974 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700975 // Not found under Board section or an empty string.
976 if (productNameFind == formattedFru.end() ||
977 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800978 {
979 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
980 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700981 // Found under Product section and not an empty string.
982 if (productNameFind != formattedFru.end() &&
983 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800984 {
985 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800986 std::regex illegalObject("[^A-Za-z0-9_]");
987 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800988 }
989 else
990 {
991 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
992 UNKNOWN_BUS_OBJECT_COUNT++;
993 }
994
James Feist918e18c2018-02-13 15:51:07 -0800995 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800996 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700997 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800998 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700999 int highest = -1;
1000 bool found = false;
1001
James Feista465ccc2019-02-08 12:51:01 -08001002 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001003 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001004 std::string path = busIface.second->get_object_path();
1005 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001006 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001007 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -07001008 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
1009 static_cast<uint8_t>(busIface.first.second)) ==
1010 getFruInfo(static_cast<uint8_t>(bus),
1011 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001012 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001013 // This device is already added to the lower numbered bus,
1014 // do not replicate it.
1015 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001016 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001017
1018 // Check if the match named has extra information.
1019 found = true;
1020 std::smatch base_match;
1021
1022 bool match = std::regex_match(
1023 path, base_match, std::regex(productName + "_(\\d+)$"));
1024 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001025 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001026 if (base_match.size() == 2)
1027 {
1028 std::ssub_match base_sub_match = base_match[1];
1029 std::string base = base_sub_match.str();
1030
1031 int value = std::stoi(base);
1032 highest = (value > highest) ? value : highest;
1033 }
James Feist79e9c0b2018-03-15 15:21:17 -07001034 }
James Feist918e18c2018-02-13 15:51:07 -08001035 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001036 } // end searching objects
1037
1038 if (found)
1039 {
1040 // We found something with the same name. If highest was still -1,
1041 // it means this new entry will be _0.
1042 productName += "_";
1043 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001044 }
1045 }
James Feist3cb5fec2018-01-23 14:41:51 -08001046
James Feist9eb0b582018-04-27 12:15:46 -07001047 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1048 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1049 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1050
James Feista465ccc2019-02-08 12:51:01 -08001051 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001052 {
James Feist9eb0b582018-04-27 12:15:46 -07001053
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001054 std::regex_replace(property.second.begin(), property.second.begin(),
1055 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -07001056 if (property.second.empty())
1057 {
1058 continue;
1059 }
1060 std::string key =
1061 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
1062 if (!iface->register_property(key, property.second + '\0'))
1063 {
1064 std::cerr << "illegal key: " << key << "\n";
1065 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001066 if (DEBUG)
1067 {
1068 std::cout << property.first << ": " << property.second << "\n";
1069 }
James Feist3cb5fec2018-01-23 14:41:51 -08001070 }
James Feist2a9d6db2018-04-27 15:48:28 -07001071
1072 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001073 iface->register_property("BUS", bus);
1074 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001075
James Feist9eb0b582018-04-27 12:15:46 -07001076 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001077}
1078
James Feista465ccc2019-02-08 12:51:01 -08001079static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001080{
1081 // try to read baseboard fru from file
1082 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1083 if (baseboardFruFile.good())
1084 {
1085 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001086 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001087 baseboardFru.resize(fileSize);
1088 baseboardFruFile.seekg(0, std::ios_base::beg);
1089 baseboardFruFile.read(baseboardFru.data(), fileSize);
1090 }
1091 else
1092 {
1093 return false;
1094 }
1095 return true;
1096}
1097
James Feista465ccc2019-02-08 12:51:01 -08001098bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001099{
1100 boost::container::flat_map<std::string, std::string> tmp;
1101 if (fru.size() > MAX_FRU_SIZE)
1102 {
1103 std::cerr << "Invalid fru.size() during writeFru\n";
1104 return false;
1105 }
1106 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001107 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001108 {
1109 std::cerr << "Invalid fru format during writeFru\n";
1110 return false;
1111 }
1112 // baseboard fru
1113 if (bus == 0 && address == 0)
1114 {
1115 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1116 if (!file.good())
1117 {
1118 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1119 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001120 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001121 return false;
1122 }
James Feista465ccc2019-02-08 12:51:01 -08001123 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001124 return file.good();
1125 }
1126 else
1127 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001128 if (hasEepromFile(bus, address))
1129 {
1130 auto path = getEepromPath(bus, address);
1131 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1132 if (eeprom < 0)
1133 {
1134 std::cerr << "unable to open i2c device " << path << "\n";
1135 throw DBusInternalError();
1136 return false;
1137 }
1138
1139 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1140 if (writtenBytes < 0)
1141 {
1142 std::cerr << "unable to write to i2c device " << path << "\n";
1143 close(eeprom);
1144 throw DBusInternalError();
1145 return false;
1146 }
1147
1148 close(eeprom);
1149 return true;
1150 }
1151
James Feistb49ffc32018-05-02 11:10:43 -07001152 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1153
1154 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1155 if (file < 0)
1156 {
1157 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001158 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001159 return false;
1160 }
1161 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1162 {
1163 std::cerr << "unable to set device address\n";
1164 close(file);
James Feistddb78302018-09-06 11:45:42 -07001165 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001166 return false;
1167 }
1168
1169 constexpr const size_t RETRY_MAX = 2;
1170 uint16_t index = 0;
1171 size_t retries = RETRY_MAX;
1172 while (index < fru.size())
1173 {
1174 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1175 (retries == RETRY_MAX))
1176 {
1177 // The 4K EEPROM only uses the A2 and A1 device address bits
1178 // with the third bit being a memory page address bit.
1179 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1180 {
1181 std::cerr << "unable to set device address\n";
1182 close(file);
James Feistddb78302018-09-06 11:45:42 -07001183 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001184 return false;
1185 }
1186 }
1187
James Feist98132792019-07-09 13:29:09 -07001188 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1189 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001190 {
1191 if (!retries--)
1192 {
1193 std::cerr << "error writing fru: " << strerror(errno)
1194 << "\n";
1195 close(file);
James Feistddb78302018-09-06 11:45:42 -07001196 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001197 return false;
1198 }
1199 }
1200 else
1201 {
1202 retries = RETRY_MAX;
1203 index++;
1204 }
1205 // most eeproms require 5-10ms between writes
1206 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1207 }
1208 close(file);
1209 return true;
1210 }
1211}
1212
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001213void rescanOneBus(
1214 BusMap& busmap, uint8_t busNum,
1215 boost::container::flat_map<
1216 std::pair<size_t, size_t>,
1217 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1218{
1219 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1220 if (!fs::exists(busPath))
1221 {
1222 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1223 << "\n";
1224 throw std::invalid_argument("Invalid Bus.");
1225 }
1226
1227 std::vector<fs::path> i2cBuses;
1228 i2cBuses.emplace_back(busPath);
1229
1230 for (auto& [pair, interface] : foundDevices)
1231 {
1232 if (pair.first == static_cast<size_t>(busNum))
1233 {
1234 objServer.remove_interface(interface);
1235 foundDevices.erase(pair);
1236 }
1237 }
1238
1239 auto scan = std::make_shared<FindDevicesWithCallback>(
1240 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1241 for (auto& busIface : dbusInterfaceMap)
1242 {
1243 if (busIface.first.first == static_cast<size_t>(busNum))
1244 {
1245 objServer.remove_interface(busIface.second);
1246 }
1247 }
1248 auto& devicemap = busmap[busNum];
1249 for (auto& device : *devicemap)
1250 {
1251 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1252 static_cast<uint32_t>(busNum), device.first);
1253 }
1254 });
1255 scan->run();
1256}
1257
James Feist9eb0b582018-04-27 12:15:46 -07001258void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001259 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001260 boost::container::flat_map<
1261 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001262 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001263{
James Feist6ebf9de2018-05-15 15:01:17 -07001264 static boost::asio::deadline_timer timer(io);
1265 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001266
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001267 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001268 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001269 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001270 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001271
Nikhil Potaded8884f12019-03-27 13:27:13 -07001272 boost::container::flat_map<size_t, fs::path> busPaths;
1273 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001274 {
James Feist4131aea2018-03-09 09:47:30 -08001275 std::cerr << "unable to find i2c devices\n";
1276 return;
James Feist918e18c2018-02-13 15:51:07 -08001277 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001278
1279 for (auto busPath : busPaths)
1280 {
1281 i2cBuses.emplace_back(busPath.second);
1282 }
James Feist4131aea2018-03-09 09:47:30 -08001283
James Feist98132792019-07-09 13:29:09 -07001284 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001285 for (auto& [pair, interface] : foundDevices)
1286 {
1287 objServer.remove_interface(interface);
1288 }
1289 foundDevices.clear();
1290
James Feist5cb06082019-10-24 17:11:13 -07001291 auto scan =
1292 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001293 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001294 {
1295 objServer.remove_interface(busIface.second);
1296 }
James Feist4131aea2018-03-09 09:47:30 -08001297
James Feist6ebf9de2018-05-15 15:01:17 -07001298 dbusInterfaceMap.clear();
1299 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001300
James Feist6ebf9de2018-05-15 15:01:17 -07001301 // todo, get this from a more sensable place
1302 std::vector<char> baseboardFru;
1303 if (readBaseboardFru(baseboardFru))
1304 {
1305 boost::container::flat_map<int, std::vector<char>>
1306 baseboardDev;
1307 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001308 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001309 }
James Feist98132792019-07-09 13:29:09 -07001310 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001311 {
James Feista465ccc2019-02-08 12:51:01 -08001312 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001313 {
James Feist5cb06082019-10-24 17:11:13 -07001314 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1315 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001316 }
1317 }
1318 });
1319 scan->run();
1320 });
James Feist918e18c2018-02-13 15:51:07 -08001321}
1322
James Feist98132792019-07-09 13:29:09 -07001323int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001324{
1325 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001326 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001327 std::vector<fs::path> i2cBuses;
1328
James Feista3c180a2018-08-09 16:06:04 -07001329 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001330 {
1331 std::cerr << "unable to find i2c devices\n";
1332 return 1;
1333 }
James Feist3cb5fec2018-01-23 14:41:51 -08001334
Patrick Venture11f1ff42019-08-01 10:42:12 -07001335 // check for and load blacklist with initial buses.
1336 loadBlacklist(blacklistPath);
1337
Vijay Khemka065f6d92018-12-18 10:37:47 -08001338 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001339
James Feist6ebf9de2018-05-15 15:01:17 -07001340 // this is a map with keys of pair(bus number, address) and values of
1341 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001342 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001343 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1344 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001345
James Feist9eb0b582018-04-27 12:15:46 -07001346 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1347 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1348 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001349
James Feist5cb06082019-10-24 17:11:13 -07001350 iface->register_method("ReScan",
1351 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001352
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001353 iface->register_method("ReScanBus", [&](uint8_t bus) {
1354 rescanOneBus(busMap, bus, dbusInterfaceMap);
1355 });
1356
Nikhil Potaded8884f12019-03-27 13:27:13 -07001357 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001358
1359 iface->register_method("WriteFru", [&](const uint8_t bus,
1360 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001361 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001362 if (!writeFru(bus, address, data))
1363 {
James Feistddb78302018-09-06 11:45:42 -07001364 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001365 return;
1366 }
1367 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001368 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001369 });
James Feist9eb0b582018-04-27 12:15:46 -07001370 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001371
James Feist9eb0b582018-04-27 12:15:46 -07001372 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001373 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001374 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001375 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001376 std::string,
1377 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001378 values;
1379 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001380 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001381 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001382 {
James Feistcb5661d2020-06-12 15:05:01 -07001383 powerIsOn = boost::ends_with(
1384 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001385 }
James Feist6ebf9de2018-05-15 15:01:17 -07001386
James Feistcb5661d2020-06-12 15:05:01 -07001387 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001388 {
James Feist5cb06082019-10-24 17:11:13 -07001389 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001390 }
James Feist918e18c2018-02-13 15:51:07 -08001391 };
James Feist9eb0b582018-04-27 12:15:46 -07001392
1393 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001394 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001395 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001396 "openbmc_project/state/"
1397 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001398 eventHandler);
1399
James Feist4131aea2018-03-09 09:47:30 -08001400 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001401 inotify_add_watch(fd, I2C_DEV_LOCATION,
1402 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001403 std::array<char, 4096> readBuffer;
1404 std::string pendingBuffer;
1405 // monitor for new i2c devices
1406 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1407 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001408 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001409 std::size_t bytes_transferred) {
1410 if (ec)
1411 {
1412 std::cout << "Callback Error " << ec << "\n";
1413 return;
1414 }
1415 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1416 bool devChange = false;
1417 while (pendingBuffer.size() > sizeof(inotify_event))
1418 {
James Feista465ccc2019-02-08 12:51:01 -08001419 const inotify_event* iEvent =
1420 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001421 pendingBuffer.data());
1422 switch (iEvent->mask)
1423 {
James Feist9eb0b582018-04-27 12:15:46 -07001424 case IN_CREATE:
1425 case IN_MOVED_TO:
1426 case IN_DELETE:
1427 if (boost::starts_with(std::string(iEvent->name),
1428 "i2c"))
1429 {
1430 devChange = true;
1431 }
James Feist4131aea2018-03-09 09:47:30 -08001432 }
1433
1434 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1435 }
James Feist6ebf9de2018-05-15 15:01:17 -07001436 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001437 {
James Feist5cb06082019-10-24 17:11:13 -07001438 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001439 }
James Feist6ebf9de2018-05-15 15:01:17 -07001440
James Feist4131aea2018-03-09 09:47:30 -08001441 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1442 watchI2cBusses);
1443 };
1444
1445 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001446 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001447 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001448
James Feist3cb5fec2018-01-23 14:41:51 -08001449 io.run();
1450 return 0;
1451}