blob: 0ef02692dc6a69354c0dd628382e7182835a4cd0 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
Patrick Venturea49dc332019-10-26 08:32:02 -070017#include "Utils.hpp"
18
James Feist3b860982018-10-02 14:34:07 -070019#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080020#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070021#include <sys/inotify.h>
22#include <sys/ioctl.h>
23
James Feist3b860982018-10-02 14:34:07 -070024#include <boost/algorithm/string/predicate.hpp>
25#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070026#include <nlohmann/json.hpp>
27#include <sdbusplus/asio/connection.hpp>
28#include <sdbusplus/asio/object_server.hpp>
29
30#include <array>
James Feist3b860982018-10-02 14:34:07 -070031#include <chrono>
32#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070033#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070035#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080036#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070037#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080038#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070039#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080040#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070041#include <set>
42#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070043#include <string>
James Feist3b860982018-10-02 14:34:07 -070044#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080045#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080046#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070047#include <vector>
James Feist3b860982018-10-02 14:34:07 -070048
James Feist8c505da2020-05-28 10:06:33 -070049extern "C"
50{
James Feist3b860982018-10-02 14:34:07 -070051#include <i2c/smbus.h>
52#include <linux/i2c-dev.h>
53}
James Feist3cb5fec2018-01-23 14:41:51 -080054
Ed Tanous072e25d2018-12-16 21:45:20 -080055namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080056static constexpr bool DEBUG = false;
57static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070058constexpr size_t MAX_FRU_SIZE = 512;
59constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070060constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080061
Patrick Venture11f1ff42019-08-01 10:42:12 -070062constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
63
James Feista465ccc2019-02-08 12:51:01 -080064const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080065 "/etc/fru/baseboard.fru.bin";
66
James Feista465ccc2019-02-08 12:51:01 -080067const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080068
James Feista465ccc2019-02-08 12:51:01 -080069static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080070 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070071const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080072using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
73using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
74
James Feist444830e2019-04-05 08:38:16 -070075static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070076struct FindDevicesWithCallback;
77
Nikhil Potaded8884f12019-03-27 13:27:13 -070078static BusMap busMap;
79
James Feistcb5661d2020-06-12 15:05:01 -070080static bool powerIsOn = false;
81
James Feist8a983922019-10-24 17:11:56 -070082static boost::container::flat_map<
83 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
84 foundDevices;
85
James Feist7972bb92019-11-13 15:59:24 -080086static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
87
James Feist5cb06082019-10-24 17:11:13 -070088boost::asio::io_service io;
89auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
90auto objServer = sdbusplus::asio::object_server(systemBus);
91
Patrick Venturebaba7672019-10-26 09:26:41 -070092bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
93
Xiang Liu2801a702020-01-20 14:29:34 -080094using ReadBlockFunc =
95 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
96 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -070097
98// Read and validate FRU contents, given the flag required for raw i2c, the open
99// file handle, a read method, and a helper string for failures.
Xiang Liu2801a702020-01-20 14:29:34 -0800100std::vector<char> readFruContents(int flag, int file, uint16_t address,
101 ReadBlockFunc readBlock,
Patrick Venturebaba7672019-10-26 09:26:41 -0700102 const std::string& errorHelp)
103{
104 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
105
Xiang Liu2801a702020-01-20 14:29:34 -0800106 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700107 {
108 std::cerr << "failed to read " << errorHelp << "\n";
109 return {};
110 }
111
112 // check the header checksum
113 if (!validateHeader(blockData))
114 {
115 if (DEBUG)
116 {
117 std::cerr << "Illegal header " << errorHelp << "\n";
118 }
119
120 return {};
121 }
122
123 std::vector<char> device;
124 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
125
Patrick Venturee26395d2019-10-29 14:05:16 -0700126 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700127 int fruLength = 0;
128 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
129 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700130 // Offset value can be 255.
131 int areaOffset = static_cast<uint8_t>(device[jj]);
Patrick Venturebaba7672019-10-26 09:26:41 -0700132 if (areaOffset == 0)
133 {
134 continue;
135 }
136
Patrick Venturee26395d2019-10-29 14:05:16 -0700137 // MultiRecords are different. jj is not tracking section, it's walking
138 // the common header.
139 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
140 {
141 hasMultiRecords = true;
142 break;
143 }
144
Patrick Venturebaba7672019-10-26 09:26:41 -0700145 areaOffset *= 8;
146
Xiang Liu2801a702020-01-20 14:29:34 -0800147 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
148 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700149 {
150 std::cerr << "failed to read " << errorHelp << "\n";
151 return {};
152 }
153
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700154 // Ignore data type (blockData is already unsigned).
Patrick Venturebaba7672019-10-26 09:26:41 -0700155 int length = blockData[1] * 8;
156 areaOffset += length;
157 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
158 }
159
Patrick Venturee26395d2019-10-29 14:05:16 -0700160 if (hasMultiRecords)
161 {
162 // device[area count] is the index to the last area because the 0th
163 // entry is not an offset in the common header.
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700164 int areaOffset = static_cast<uint8_t>(device[FRU_AREAS.size()]);
Patrick Venturee26395d2019-10-29 14:05:16 -0700165 areaOffset *= 8;
166
167 // the multi-area record header is 5 bytes long.
168 constexpr int multiRecordHeaderSize = 5;
169 constexpr int multiRecordEndOfList = 0x80;
170
171 // Sanity hard-limit to 64KB.
172 while (areaOffset < std::numeric_limits<uint16_t>::max())
173 {
174 // In multi-area, the area offset points to the 0th record, each
175 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800176 if (readBlock(flag, file, address,
177 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700178 blockData.data()) < 0)
179 {
180 std::cerr << "failed to read " << errorHelp << "\n";
181 return {};
182 }
183
184 // Ok, let's check the record length, which is in bytes (unsigned,
185 // up to 255, so blockData should hold uint8_t not char)
186 int recordLength = blockData[2];
187 areaOffset += (recordLength + multiRecordHeaderSize);
188 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
189
190 // If this is the end of the list bail.
191 if ((blockData[1] & multiRecordEndOfList))
192 {
193 break;
194 }
195 }
196 }
197
Patrick Venturebaba7672019-10-26 09:26:41 -0700198 // You already copied these first 8 bytes (the ipmi fru header size)
199 fruLength -= 8;
200
201 int readOffset = 8;
202
203 while (fruLength > 0)
204 {
205 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
206
Xiang Liu2801a702020-01-20 14:29:34 -0800207 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700208 static_cast<uint8_t>(requestLength),
209 blockData.data()) < 0)
210 {
211 std::cerr << "failed to read " << errorHelp << "\n";
212 return {};
213 }
214
215 device.insert(device.end(), blockData.begin(),
216 blockData.begin() + requestLength);
217
218 readOffset += requestLength;
219 fruLength -= requestLength;
220 }
221
222 return device;
223}
224
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700225// Given a bus/address, produce the path in sysfs for an eeprom.
226static std::string getEepromPath(size_t bus, size_t address)
227{
228 std::stringstream output;
229 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
230 << std::setfill('0') << std::setw(4) << std::hex << address
231 << "/eeprom";
232 return output.str();
233}
234
235static bool hasEepromFile(size_t bus, size_t address)
236{
237 auto path = getEepromPath(bus, address);
238 try
239 {
240 return fs::exists(path);
241 }
242 catch (...)
243 {
244 return false;
245 }
246}
247
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700248static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800249 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700250 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700251{
252 auto result = lseek(fd, offset, SEEK_SET);
253 if (result < 0)
254 {
255 std::cerr << "failed to seek\n";
256 return -1;
257 }
258
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700259 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700260}
261
James Feist5d7f4692020-06-17 18:22:33 -0700262static int busStrToInt(const std::string& busName)
263{
264 auto findBus = busName.rfind("-");
265 if (findBus == std::string::npos)
266 {
267 return -1;
268 }
269 return std::stoi(busName.substr(findBus + 1));
270}
271
James Feist7972bb92019-11-13 15:59:24 -0800272static int getRootBus(size_t bus)
273{
274 auto ec = std::error_code();
275 auto path = std::filesystem::read_symlink(
276 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
277 std::to_string(bus) + "/mux_device"),
278 ec);
279 if (ec)
280 {
281 return -1;
282 }
283
284 std::string filename = path.filename();
285 auto findBus = filename.find("-");
286 if (findBus == std::string::npos)
287 {
288 return -1;
289 }
290 return std::stoi(filename.substr(0, findBus));
291}
292
James Feistc95cb142018-02-26 10:41:42 -0800293static bool isMuxBus(size_t bus)
294{
Ed Tanous072e25d2018-12-16 21:45:20 -0800295 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800296 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
297}
298
James Feist8a983922019-10-24 17:11:56 -0700299static void makeProbeInterface(size_t bus, size_t address)
300{
301 if (isMuxBus(bus))
302 {
303 return; // the mux buses are random, no need to publish
304 }
305 auto [it, success] = foundDevices.emplace(
306 std::make_pair(bus, address),
307 objServer.add_interface(
308 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
309 std::to_string(address),
310 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
311 if (!success)
312 {
313 return; // already added
314 }
315 it->second->register_property("Bus", bus);
316 it->second->register_property("Address", address);
317 it->second->initialize();
318}
319
Vijay Khemka2d681f62018-11-06 15:51:00 -0800320static int isDevice16Bit(int file)
321{
322 /* Get first byte */
323 int byte1 = i2c_smbus_read_byte_data(file, 0);
324 if (byte1 < 0)
325 {
326 return byte1;
327 }
328 /* Read 7 more bytes, it will read same first byte in case of
329 * 8 bit but it will read next byte in case of 16 bit
330 */
331 for (int i = 0; i < 7; i++)
332 {
333 int byte2 = i2c_smbus_read_byte_data(file, 0);
334 if (byte2 < 0)
335 {
336 return byte2;
337 }
338 if (byte2 != byte1)
339 {
340 return 1;
341 }
342 }
343 return 0;
344}
345
Xiang Liu2801a702020-01-20 14:29:34 -0800346// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
347// from_slave_buf_len bytes.
348static int i2c_smbus_write_then_read(int file, uint16_t address,
349 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
350 uint8_t* fromSlaveBuf,
351 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800352{
Xiang Liu2801a702020-01-20 14:29:34 -0800353 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
354 fromSlaveBufLen == 0)
355 {
356 return -1;
357 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800358
Xiang Liu2801a702020-01-20 14:29:34 -0800359#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
360 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
361 struct i2c_rdwr_ioctl_data rdwr;
362
363 msgs[0].addr = address;
364 msgs[0].flags = 0;
365 msgs[0].len = toSlaveBufLen;
366 msgs[0].buf = toSlaveBuf;
367 msgs[1].addr = address;
368 msgs[1].flags = I2C_M_RD;
369 msgs[1].len = fromSlaveBufLen;
370 msgs[1].buf = fromSlaveBuf;
371
372 rdwr.msgs = msgs;
373 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
374
375 int ret = ioctl(file, I2C_RDWR, &rdwr);
376
377 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
378}
379
380static int64_t readBlockData(int flag, int file, uint16_t address,
381 uint16_t offset, uint8_t len, uint8_t* buf)
382{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800383 if (flag == 0)
384 {
Xiang Liu2801a702020-01-20 14:29:34 -0800385 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
386 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800387 }
388
Xiang Liu2801a702020-01-20 14:29:34 -0800389 offset = htobe16(offset);
390 return i2c_smbus_write_then_read(
391 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800392}
393
James Feist24bae7a2019-04-03 09:50:56 -0700394bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
395{
396 // ipmi spec format version number is currently at 1, verify it
397 if (blockData[0] != 0x1)
398 {
399 return false;
400 }
401
402 // verify pad is set to 0
403 if (blockData[6] != 0x0)
404 {
405 return false;
406 }
407
408 // verify offsets are 0, or don't point to another offset
409 std::set<uint8_t> foundOffsets;
410 for (int ii = 1; ii < 6; ii++)
411 {
412 if (blockData[ii] == 0)
413 {
414 continue;
415 }
James Feist0eb40352019-04-09 14:44:04 -0700416 auto inserted = foundOffsets.insert(blockData[ii]);
417 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700418 {
419 return false;
420 }
421 }
422
423 // validate checksum
424 size_t sum = 0;
425 for (int jj = 0; jj < 7; jj++)
426 {
427 sum += blockData[jj];
428 }
429 sum = (256 - sum) & 0xFF;
430
431 if (sum != blockData[7])
432 {
433 return false;
434 }
435 return true;
436}
437
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700438// TODO: This code is very similar to the non-eeprom version and can be merged
439// with some tweaks.
440static std::vector<char> processEeprom(int bus, int address)
441{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700442 auto path = getEepromPath(bus, address);
443
444 int file = open(path.c_str(), O_RDONLY);
445 if (file < 0)
446 {
447 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700448 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700449 }
450
Patrick Venturebaba7672019-10-26 09:26:41 -0700451 std::string errorMessage = "eeprom at " + std::to_string(bus) +
452 " address " + std::to_string(address);
Xiang Liu2801a702020-01-20 14:29:34 -0800453 std::vector<char> device = readFruContents(
454 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700455
456 close(file);
457 return device;
458}
459
460std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
461{
462 std::set<int> foundList;
463
464 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
465
466 // For each file listed under the i2c device
467 // NOTE: This should be faster than just checking for each possible address
468 // path.
469 for (const auto& p : fs::directory_iterator(path))
470 {
471 const std::string node = p.path().string();
472 std::smatch m;
473 bool found =
474 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
475
476 if (!found)
477 {
478 continue;
479 }
480 if (m.size() != 2)
481 {
482 std::cerr << "regex didn't capture\n";
483 continue;
484 }
485
486 std::ssub_match subMatch = m[1];
487 std::string addressString = subMatch.str();
488
489 std::size_t ignored;
490 const int hexBase = 16;
491 int address = std::stoi(addressString, &ignored, hexBase);
492
493 const std::string eeprom = node + "/eeprom";
494
495 try
496 {
497 if (!fs::exists(eeprom))
498 {
499 continue;
500 }
501 }
502 catch (...)
503 {
504 continue;
505 }
506
507 // There is an eeprom file at this address, it may have invalid
508 // contents, but we found it.
509 foundList.insert(address);
510
511 std::vector<char> device = processEeprom(i2cBus, address);
512 if (!device.empty())
513 {
514 devices->emplace(address, device);
515 }
516 }
517
518 return foundList;
519}
520
Patrick Venture4f47fe62019-08-08 16:30:38 -0700521int getBusFrus(int file, int first, int last, int bus,
522 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800523{
James Feist3cb5fec2018-01-23 14:41:51 -0800524
James Feist26c27ad2018-07-25 15:09:40 -0700525 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700526 // NOTE: When reading the devices raw on the bus, it can interfere with
527 // the driver's ability to operate, therefore read eeproms first before
528 // scanning for devices without drivers. Several experiments were run
529 // and it was determined that if there were any devices on the bus
530 // before the eeprom was hit and read, the eeprom driver wouldn't open
531 // while the bus device was open. An experiment was not performed to see
532 // if this issue was resolved if the i2c bus device was closed, but
533 // hexdumps of the eeprom later were successful.
534
535 // Scan for i2c eeproms loaded on this bus.
536 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800537 std::set<size_t>& failedItems = failedAddresses[bus];
538
539 std::set<size_t>* rootFailures = nullptr;
540 int rootBus = getRootBus(bus);
541
542 if (rootBus >= 0)
543 {
544 rootFailures = &(failedAddresses[rootBus]);
545 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700546
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530547 constexpr int startSkipSlaveAddr = 0;
548 constexpr int endSkipSlaveAddr = 12;
549
James Feist26c27ad2018-07-25 15:09:40 -0700550 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800551 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700552 if (skipList.find(ii) != skipList.end())
553 {
554 continue;
555 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530556 // skipping since no device is present in this range
557 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
558 {
559 continue;
560 }
James Feist26c27ad2018-07-25 15:09:40 -0700561 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530562 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800563 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700564 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700565 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700566 continue;
567 }
568 // probe
569 else if (i2c_smbus_read_byte(file) < 0)
570 {
571 continue;
572 }
James Feist3cb5fec2018-01-23 14:41:51 -0800573
James Feist26c27ad2018-07-25 15:09:40 -0700574 if (DEBUG)
575 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700576 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700577 << "\n";
578 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800579
James Feist8a983922019-10-24 17:11:56 -0700580 makeProbeInterface(bus, ii);
581
James Feist7972bb92019-11-13 15:59:24 -0800582 if (failedItems.find(ii) != failedItems.end())
583 {
584 // if we failed to read it once, unlikely we can read it later
585 continue;
586 }
587
588 if (rootFailures != nullptr)
589 {
590 if (rootFailures->find(ii) != rootFailures->end())
591 {
592 continue;
593 }
594 }
595
Vijay Khemka2d681f62018-11-06 15:51:00 -0800596 /* Check for Device type if it is 8 bit or 16 bit */
597 int flag = isDevice16Bit(file);
598 if (flag < 0)
599 {
600 std::cerr << "failed to read bus " << bus << " address " << ii
601 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700602 if (powerIsOn)
603 {
604 failedItems.insert(ii);
605 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800606 continue;
607 }
608
Patrick Venturebaba7672019-10-26 09:26:41 -0700609 std::string errorMessage =
610 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
611 std::vector<char> device =
Xiang Liu2801a702020-01-20 14:29:34 -0800612 readFruContents(flag, file, static_cast<uint16_t>(ii),
613 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700614 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700615 {
James Feist26c27ad2018-07-25 15:09:40 -0700616 continue;
617 }
James Feist26c27ad2018-07-25 15:09:40 -0700618
Patrick Venture786f1792019-08-05 16:33:44 -0700619 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800620 }
James Feist26c27ad2018-07-25 15:09:40 -0700621 return 1;
622 });
623 std::future_status status =
624 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
625 if (status == std::future_status::timeout)
626 {
627 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700628 if (powerIsOn)
629 {
630 busBlacklist.insert(bus);
631 }
James Feist444830e2019-04-05 08:38:16 -0700632 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700633 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800634 }
635
James Feist444830e2019-04-05 08:38:16 -0700636 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700637 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800638}
639
Patrick Venture11f1ff42019-08-01 10:42:12 -0700640void loadBlacklist(const char* path)
641{
642 std::ifstream blacklistStream(path);
643 if (!blacklistStream.good())
644 {
645 // File is optional.
646 std::cerr << "Cannot open blacklist file.\n\n";
647 return;
648 }
649
650 nlohmann::json data =
651 nlohmann::json::parse(blacklistStream, nullptr, false);
652 if (data.is_discarded())
653 {
654 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
655 "exiting\n";
656 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700657 }
658
659 // It's expected to have at least one field, "buses" that is an array of the
660 // buses by integer. Allow for future options to exclude further aspects,
661 // such as specific addresses or ranges.
662 if (data.type() != nlohmann::json::value_t::object)
663 {
664 std::cerr << "Illegal blacklist, expected to read dictionary\n";
665 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700666 }
667
668 // If buses field is missing, that's fine.
669 if (data.count("buses") == 1)
670 {
671 // Parse the buses array after a little validation.
672 auto buses = data.at("buses");
673 if (buses.type() != nlohmann::json::value_t::array)
674 {
675 // Buses field present but invalid, therefore this is an error.
676 std::cerr << "Invalid contents for blacklist buses field\n";
677 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700678 }
679
680 // Catch exception here for type mis-match.
681 try
682 {
683 for (const auto& bus : buses)
684 {
685 busBlacklist.insert(bus.get<size_t>());
686 }
687 }
688 catch (const nlohmann::detail::type_error& e)
689 {
690 // Type mis-match is a critical error.
691 std::cerr << "Invalid bus type: " << e.what() << "\n";
692 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700693 }
694 }
695
696 return;
697}
698
James Feista465ccc2019-02-08 12:51:01 -0800699static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700700 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800701{
James Feista465ccc2019-02-08 12:51:01 -0800702 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800703 {
James Feist5d7f4692020-06-17 18:22:33 -0700704 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800705
James Feist5d7f4692020-06-17 18:22:33 -0700706 if (bus < 0)
707 {
708 std::cerr << "Cannot translate " << i2cBus << " to int\n";
709 continue;
710 }
James Feist444830e2019-04-05 08:38:16 -0700711 if (busBlacklist.find(bus) != busBlacklist.end())
712 {
713 continue; // skip previously failed busses
714 }
James Feist3cb5fec2018-01-23 14:41:51 -0800715
James Feist0c3980a2019-12-19 11:09:27 -0800716 int rootBus = getRootBus(bus);
717 if (busBlacklist.find(rootBus) != busBlacklist.end())
718 {
719 continue;
720 }
721
James Feist3cb5fec2018-01-23 14:41:51 -0800722 auto file = open(i2cBus.c_str(), O_RDWR);
723 if (file < 0)
724 {
725 std::cerr << "unable to open i2c device " << i2cBus.string()
726 << "\n";
727 continue;
728 }
729 unsigned long funcs = 0;
730
731 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
732 {
733 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700734 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800735 << bus << "\n";
736 continue;
737 }
738 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
739 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
740 {
741 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
742 << bus << "\n";
743 continue;
744 }
James Feist98132792019-07-09 13:29:09 -0700745 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800746 device = std::make_shared<DeviceMap>();
747
Nikhil Potaded8884f12019-03-27 13:27:13 -0700748 // i2cdetect by default uses the range 0x03 to 0x77, as
749 // this is what we have tested with, use this range. Could be
750 // changed in future.
751 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800752 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700753 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800754 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700755
756 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700757 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700758
759 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800760 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700761 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800762 }
James Feist3cb5fec2018-01-23 14:41:51 -0800763 }
James Feist3cb5fec2018-01-23 14:41:51 -0800764}
765
James Feist6ebf9de2018-05-15 15:01:17 -0700766// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700767struct FindDevicesWithCallback :
768 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700769{
James Feista465ccc2019-02-08 12:51:01 -0800770 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700771 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800772 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700773 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700774 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700775 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700776 ~FindDevicesWithCallback()
777 {
778 _callback();
779 }
780 void run()
781 {
James Feist98132792019-07-09 13:29:09 -0700782 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700783 }
784
James Feista465ccc2019-02-08 12:51:01 -0800785 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800786 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700787 std::function<void(void)> _callback;
788};
789
James Feist3cb5fec2018-01-23 14:41:51 -0800790static const std::tm intelEpoch(void)
791{
James Feist98132792019-07-09 13:29:09 -0700792 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800793 val.tm_year = 1996 - 1900;
794 return val;
795}
796
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800797static char sixBitToChar(uint8_t val)
798{
799 return static_cast<char>((val & 0x3f) + ' ');
800}
801
802/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
803static const char bcdHighChars[] = {
804 ' ', '-', '.', 'X', 'X', 'X',
805};
806
807static char bcdPlusToChar(uint8_t val)
808{
809 val &= 0xf;
810 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
811}
812
813enum class DecodeState
814{
815 ok,
816 end,
817 err,
818};
819
820enum FRUDataEncoding
821{
822 binary = 0x0,
823 bcdPlus = 0x1,
824 sixBitASCII = 0x2,
825 languageDependent = 0x3,
826};
827
828/* Decode FRU data into a std::string, given an input iterator and end. If the
829 * state returned is fruDataOk, then the resulting string is the decoded FRU
830 * data. The input iterator is advanced past the data consumed.
831 *
832 * On fruDataErr, we have lost synchronisation with the length bytes, so the
833 * iterator is no longer usable.
834 */
835static std::pair<DecodeState, std::string>
836 decodeFruData(std::vector<char>::const_iterator& iter,
837 const std::vector<char>::const_iterator& end)
838{
839 std::string value;
840 unsigned int i;
841
842 /* we need at least one byte to decode the type/len header */
843 if (iter == end)
844 {
845 std::cerr << "Truncated FRU data\n";
846 return make_pair(DecodeState::err, value);
847 }
848
849 uint8_t c = *(iter++);
850
851 /* 0xc1 is the end marker */
852 if (c == 0xc1)
853 {
854 return make_pair(DecodeState::end, value);
855 }
856
857 /* decode type/len byte */
858 uint8_t type = static_cast<uint8_t>(c >> 6);
859 uint8_t len = static_cast<uint8_t>(c & 0x3f);
860
861 /* we should have at least len bytes of data available overall */
862 if (iter + len > end)
863 {
864 std::cerr << "FRU data field extends past end of FRU data\n";
865 return make_pair(DecodeState::err, value);
866 }
867
868 switch (type)
869 {
870 case FRUDataEncoding::binary:
871 case FRUDataEncoding::languageDependent:
872 /* For language-code dependent encodings, assume 8-bit ASCII */
873 value = std::string(iter, iter + len);
874 iter += len;
875 break;
876
877 case FRUDataEncoding::bcdPlus:
878 value = std::string();
879 for (i = 0; i < len; i++, iter++)
880 {
881 uint8_t val = static_cast<uint8_t>(*iter);
882 value.push_back(bcdPlusToChar(val >> 4));
883 value.push_back(bcdPlusToChar(val & 0xf));
884 }
885 break;
886
887 case FRUDataEncoding::sixBitASCII:
888 {
889 unsigned int accum;
890 unsigned int accumBitLen = 0;
891 value = std::string();
892 for (i = 0; i < len; i++, iter++)
893 {
894 /* we need to cast to unsigned before the promotion to
895 * int, so we don't sign-extend. */
896 accum |= static_cast<unsigned char>(*iter) << accumBitLen;
897 accumBitLen += 8;
898 while (accumBitLen >= 6)
899 {
900 value.push_back(sixBitToChar(accum & 0x3f));
901 accum >>= 6;
902 accumBitLen -= 6;
903 }
904 }
905 }
906 break;
907 }
908
909 return make_pair(DecodeState::ok, value);
910}
911
James Feista465ccc2019-02-08 12:51:01 -0800912bool formatFru(const std::vector<char>& fruBytes,
913 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800914{
James Feista465ccc2019-02-08 12:51:01 -0800915 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800916 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800917
James Feista465ccc2019-02-08 12:51:01 -0800918 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800919 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
920 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800921
James Feista465ccc2019-02-08 12:51:01 -0800922 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800923 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
924 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
925 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800926
James Feistd068e932018-09-20 10:53:07 -0700927 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800928 {
929 return false;
930 }
931 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700932 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800933 std::to_string(static_cast<int>(*fruAreaOffsetField));
934
James Feista465ccc2019-02-08 12:51:01 -0800935 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800936
James Feist0eb40352019-04-09 14:44:04 -0700937 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800938 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700939 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800940 if (fruAreaOffsetField >= fruBytes.end())
941 {
942 return false;
943 }
944 size_t offset = (*fruAreaOffsetField) * 8;
945
946 if (offset > 1)
947 {
948 // +2 to skip format and length
949 std::vector<char>::const_iterator fruBytesIter =
950 fruBytes.begin() + offset + 2;
951
952 if (fruBytesIter >= fruBytes.end())
953 {
954 return false;
955 }
956
957 if (area == "CHASSIS")
958 {
959 result["CHASSIS_TYPE"] =
960 std::to_string(static_cast<int>(*fruBytesIter));
961 fruBytesIter += 1;
962 fieldData = &CHASSIS_FRU_AREAS;
963 }
964 else if (area == "BOARD")
965 {
966 result["BOARD_LANGUAGE_CODE"] =
967 std::to_string(static_cast<int>(*fruBytesIter));
968 fruBytesIter += 1;
969 if (fruBytesIter >= fruBytes.end())
970 {
971 return false;
972 }
973
974 unsigned int minutes = *fruBytesIter |
975 *(fruBytesIter + 1) << 8 |
976 *(fruBytesIter + 2) << 16;
977 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700978 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800979 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700980 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800981
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700982 // Tue Nov 20 23:08:00 2018
983 char timeString[32] = {0};
984 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700985 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700986 if (bytes == 0)
987 {
988 std::cerr << "invalid time string encountered\n";
989 return false;
990 }
991
992 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800993 fruBytesIter += 3;
994 fieldData = &BOARD_FRU_AREAS;
995 }
996 else if (area == "PRODUCT")
997 {
998 result["PRODUCT_LANGUAGE_CODE"] =
999 std::to_string(static_cast<int>(*fruBytesIter));
1000 fruBytesIter += 1;
1001 fieldData = &PRODUCT_FRU_AREAS;
1002 }
1003 else
1004 {
1005 continue;
1006 }
James Feista465ccc2019-02-08 12:51:01 -08001007 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -08001008 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001009 auto res = decodeFruData(fruBytesIter, fruBytes.end());
1010 std::string name = area + "_" + field;
James Feist3cb5fec2018-01-23 14:41:51 -08001011
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001012 if (res.first == DecodeState::end)
Vijay Khemka5d5de442018-11-07 10:51:25 -08001013 {
1014 break;
1015 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001016 else if (res.first == DecodeState::err)
James Feist3cb5fec2018-01-23 14:41:51 -08001017 {
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001018 std::cerr << "Error while parsing " << name << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001019 return false;
1020 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001021
1022 std::string value = res.second;
James Feist3cb5fec2018-01-23 14:41:51 -08001023
Ed Tanous2147e672019-02-27 13:59:56 -08001024 // Strip non null characters from the end
1025 value.erase(std::find_if(value.rbegin(), value.rend(),
1026 [](char ch) { return ch != 0; })
1027 .base(),
1028 value.end());
1029
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001030 result[name] = std::move(value);
James Feist3cb5fec2018-01-23 14:41:51 -08001031 }
1032 }
1033 }
1034
1035 return true;
1036}
1037
Nikhil Potaded8884f12019-03-27 13:27:13 -07001038std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
1039{
1040 auto deviceMap = busMap.find(bus);
1041 if (deviceMap == busMap.end())
1042 {
1043 throw std::invalid_argument("Invalid Bus.");
1044 }
1045 auto device = deviceMap->second->find(address);
1046 if (device == deviceMap->second->end())
1047 {
1048 throw std::invalid_argument("Invalid Address.");
1049 }
1050 std::vector<uint8_t>& ret =
1051 reinterpret_cast<std::vector<uint8_t>&>(device->second);
1052
1053 return ret;
1054}
1055
James Feist3cb5fec2018-01-23 14:41:51 -08001056void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -07001057 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -08001058 boost::container::flat_map<
1059 std::pair<size_t, size_t>,
1060 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001061 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001062{
1063 boost::container::flat_map<std::string, std::string> formattedFru;
1064 if (!formatFru(device, formattedFru))
1065 {
Patrick Ventureb755c832019-08-07 11:09:14 -07001066 std::cerr << "failed to format fru for device at bus " << bus
1067 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001068 return;
1069 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001070
James Feist3cb5fec2018-01-23 14:41:51 -08001071 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
1072 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001073 // Not found under Board section or an empty string.
1074 if (productNameFind == formattedFru.end() ||
1075 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001076 {
1077 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
1078 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001079 // Found under Product section and not an empty string.
1080 if (productNameFind != formattedFru.end() &&
1081 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001082 {
1083 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001084 std::regex illegalObject("[^A-Za-z0-9_]");
1085 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001086 }
1087 else
1088 {
1089 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1090 UNKNOWN_BUS_OBJECT_COUNT++;
1091 }
1092
James Feist918e18c2018-02-13 15:51:07 -08001093 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001094 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001095 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001096 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001097 int highest = -1;
1098 bool found = false;
1099
James Feista465ccc2019-02-08 12:51:01 -08001100 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001101 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001102 std::string path = busIface.second->get_object_path();
1103 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001104 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001105 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -07001106 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
1107 static_cast<uint8_t>(busIface.first.second)) ==
1108 getFruInfo(static_cast<uint8_t>(bus),
1109 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001110 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001111 // This device is already added to the lower numbered bus,
1112 // do not replicate it.
1113 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001114 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001115
1116 // Check if the match named has extra information.
1117 found = true;
1118 std::smatch base_match;
1119
1120 bool match = std::regex_match(
1121 path, base_match, std::regex(productName + "_(\\d+)$"));
1122 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001123 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001124 if (base_match.size() == 2)
1125 {
1126 std::ssub_match base_sub_match = base_match[1];
1127 std::string base = base_sub_match.str();
1128
1129 int value = std::stoi(base);
1130 highest = (value > highest) ? value : highest;
1131 }
James Feist79e9c0b2018-03-15 15:21:17 -07001132 }
James Feist918e18c2018-02-13 15:51:07 -08001133 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001134 } // end searching objects
1135
1136 if (found)
1137 {
1138 // We found something with the same name. If highest was still -1,
1139 // it means this new entry will be _0.
1140 productName += "_";
1141 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001142 }
1143 }
James Feist3cb5fec2018-01-23 14:41:51 -08001144
James Feist9eb0b582018-04-27 12:15:46 -07001145 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1146 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1147 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1148
James Feista465ccc2019-02-08 12:51:01 -08001149 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001150 {
James Feist9eb0b582018-04-27 12:15:46 -07001151
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001152 std::regex_replace(property.second.begin(), property.second.begin(),
1153 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -07001154 if (property.second.empty())
1155 {
1156 continue;
1157 }
1158 std::string key =
1159 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
1160 if (!iface->register_property(key, property.second + '\0'))
1161 {
1162 std::cerr << "illegal key: " << key << "\n";
1163 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001164 if (DEBUG)
1165 {
1166 std::cout << property.first << ": " << property.second << "\n";
1167 }
James Feist3cb5fec2018-01-23 14:41:51 -08001168 }
James Feist2a9d6db2018-04-27 15:48:28 -07001169
1170 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001171 iface->register_property("BUS", bus);
1172 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001173
James Feist9eb0b582018-04-27 12:15:46 -07001174 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001175}
1176
James Feista465ccc2019-02-08 12:51:01 -08001177static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -08001178{
1179 // try to read baseboard fru from file
1180 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1181 if (baseboardFruFile.good())
1182 {
1183 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -07001184 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -08001185 baseboardFru.resize(fileSize);
1186 baseboardFruFile.seekg(0, std::ios_base::beg);
1187 baseboardFruFile.read(baseboardFru.data(), fileSize);
1188 }
1189 else
1190 {
1191 return false;
1192 }
1193 return true;
1194}
1195
James Feista465ccc2019-02-08 12:51:01 -08001196bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001197{
1198 boost::container::flat_map<std::string, std::string> tmp;
1199 if (fru.size() > MAX_FRU_SIZE)
1200 {
1201 std::cerr << "Invalid fru.size() during writeFru\n";
1202 return false;
1203 }
1204 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001205 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001206 {
1207 std::cerr << "Invalid fru format during writeFru\n";
1208 return false;
1209 }
1210 // baseboard fru
1211 if (bus == 0 && address == 0)
1212 {
1213 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1214 if (!file.good())
1215 {
1216 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1217 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001218 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001219 return false;
1220 }
James Feista465ccc2019-02-08 12:51:01 -08001221 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001222 return file.good();
1223 }
1224 else
1225 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001226 if (hasEepromFile(bus, address))
1227 {
1228 auto path = getEepromPath(bus, address);
1229 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1230 if (eeprom < 0)
1231 {
1232 std::cerr << "unable to open i2c device " << path << "\n";
1233 throw DBusInternalError();
1234 return false;
1235 }
1236
1237 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1238 if (writtenBytes < 0)
1239 {
1240 std::cerr << "unable to write to i2c device " << path << "\n";
1241 close(eeprom);
1242 throw DBusInternalError();
1243 return false;
1244 }
1245
1246 close(eeprom);
1247 return true;
1248 }
1249
James Feistb49ffc32018-05-02 11:10:43 -07001250 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1251
1252 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1253 if (file < 0)
1254 {
1255 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001256 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001257 return false;
1258 }
1259 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1260 {
1261 std::cerr << "unable to set device address\n";
1262 close(file);
James Feistddb78302018-09-06 11:45:42 -07001263 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001264 return false;
1265 }
1266
1267 constexpr const size_t RETRY_MAX = 2;
1268 uint16_t index = 0;
1269 size_t retries = RETRY_MAX;
1270 while (index < fru.size())
1271 {
1272 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1273 (retries == RETRY_MAX))
1274 {
1275 // The 4K EEPROM only uses the A2 and A1 device address bits
1276 // with the third bit being a memory page address bit.
1277 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1278 {
1279 std::cerr << "unable to set device address\n";
1280 close(file);
James Feistddb78302018-09-06 11:45:42 -07001281 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001282 return false;
1283 }
1284 }
1285
James Feist98132792019-07-09 13:29:09 -07001286 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1287 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001288 {
1289 if (!retries--)
1290 {
1291 std::cerr << "error writing fru: " << strerror(errno)
1292 << "\n";
1293 close(file);
James Feistddb78302018-09-06 11:45:42 -07001294 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001295 return false;
1296 }
1297 }
1298 else
1299 {
1300 retries = RETRY_MAX;
1301 index++;
1302 }
1303 // most eeproms require 5-10ms between writes
1304 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1305 }
1306 close(file);
1307 return true;
1308 }
1309}
1310
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001311void rescanOneBus(
1312 BusMap& busmap, uint8_t busNum,
1313 boost::container::flat_map<
1314 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001315 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1316 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001317{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001318 for (auto& [pair, interface] : foundDevices)
1319 {
1320 if (pair.first == static_cast<size_t>(busNum))
1321 {
1322 objServer.remove_interface(interface);
1323 foundDevices.erase(pair);
1324 }
1325 }
1326
James Feist5d7f4692020-06-17 18:22:33 -07001327 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1328 if (!fs::exists(busPath))
1329 {
1330 if (dbusCall)
1331 {
1332 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1333 << "\n";
1334 throw std::invalid_argument("Invalid Bus.");
1335 }
1336 return;
1337 }
1338
1339 std::vector<fs::path> i2cBuses;
1340 i2cBuses.emplace_back(busPath);
1341
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001342 auto scan = std::make_shared<FindDevicesWithCallback>(
1343 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1344 for (auto& busIface : dbusInterfaceMap)
1345 {
1346 if (busIface.first.first == static_cast<size_t>(busNum))
1347 {
1348 objServer.remove_interface(busIface.second);
1349 }
1350 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001351 auto found = busmap.find(busNum);
1352 if (found == busmap.end() || found->second == nullptr)
1353 {
1354 return;
1355 }
1356 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001357 {
1358 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1359 static_cast<uint32_t>(busNum), device.first);
1360 }
1361 });
1362 scan->run();
1363}
1364
James Feist9eb0b582018-04-27 12:15:46 -07001365void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001366 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001367 boost::container::flat_map<
1368 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001369 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001370{
James Feist6ebf9de2018-05-15 15:01:17 -07001371 static boost::asio::deadline_timer timer(io);
1372 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001373
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001374 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001375 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001376 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001377 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001378
Nikhil Potaded8884f12019-03-27 13:27:13 -07001379 boost::container::flat_map<size_t, fs::path> busPaths;
1380 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001381 {
James Feist4131aea2018-03-09 09:47:30 -08001382 std::cerr << "unable to find i2c devices\n";
1383 return;
James Feist918e18c2018-02-13 15:51:07 -08001384 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001385
1386 for (auto busPath : busPaths)
1387 {
1388 i2cBuses.emplace_back(busPath.second);
1389 }
James Feist4131aea2018-03-09 09:47:30 -08001390
James Feist98132792019-07-09 13:29:09 -07001391 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001392 for (auto& [pair, interface] : foundDevices)
1393 {
1394 objServer.remove_interface(interface);
1395 }
1396 foundDevices.clear();
1397
James Feist5cb06082019-10-24 17:11:13 -07001398 auto scan =
1399 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001400 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001401 {
1402 objServer.remove_interface(busIface.second);
1403 }
James Feist4131aea2018-03-09 09:47:30 -08001404
James Feist6ebf9de2018-05-15 15:01:17 -07001405 dbusInterfaceMap.clear();
1406 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001407
James Feist6ebf9de2018-05-15 15:01:17 -07001408 // todo, get this from a more sensable place
1409 std::vector<char> baseboardFru;
1410 if (readBaseboardFru(baseboardFru))
1411 {
1412 boost::container::flat_map<int, std::vector<char>>
1413 baseboardDev;
1414 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001415 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001416 }
James Feist98132792019-07-09 13:29:09 -07001417 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001418 {
James Feista465ccc2019-02-08 12:51:01 -08001419 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001420 {
James Feist5cb06082019-10-24 17:11:13 -07001421 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1422 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001423 }
1424 }
1425 });
1426 scan->run();
1427 });
James Feist918e18c2018-02-13 15:51:07 -08001428}
1429
James Feist98132792019-07-09 13:29:09 -07001430int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001431{
1432 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001433 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001434 std::vector<fs::path> i2cBuses;
1435
James Feista3c180a2018-08-09 16:06:04 -07001436 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001437 {
1438 std::cerr << "unable to find i2c devices\n";
1439 return 1;
1440 }
James Feist3cb5fec2018-01-23 14:41:51 -08001441
Patrick Venture11f1ff42019-08-01 10:42:12 -07001442 // check for and load blacklist with initial buses.
1443 loadBlacklist(blacklistPath);
1444
Vijay Khemka065f6d92018-12-18 10:37:47 -08001445 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001446
James Feist6ebf9de2018-05-15 15:01:17 -07001447 // this is a map with keys of pair(bus number, address) and values of
1448 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001449 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001450 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1451 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001452
James Feist9eb0b582018-04-27 12:15:46 -07001453 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1454 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1455 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001456
James Feist5cb06082019-10-24 17:11:13 -07001457 iface->register_method("ReScan",
1458 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001459
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001460 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001461 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001462 });
1463
Nikhil Potaded8884f12019-03-27 13:27:13 -07001464 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001465
1466 iface->register_method("WriteFru", [&](const uint8_t bus,
1467 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001468 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001469 if (!writeFru(bus, address, data))
1470 {
James Feistddb78302018-09-06 11:45:42 -07001471 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001472 return;
1473 }
1474 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001475 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001476 });
James Feist9eb0b582018-04-27 12:15:46 -07001477 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001478
James Feist9eb0b582018-04-27 12:15:46 -07001479 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001480 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001481 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001482 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001483 std::string,
1484 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001485 values;
1486 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001487 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001488 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001489 {
James Feistcb5661d2020-06-12 15:05:01 -07001490 powerIsOn = boost::ends_with(
1491 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001492 }
James Feist6ebf9de2018-05-15 15:01:17 -07001493
James Feistcb5661d2020-06-12 15:05:01 -07001494 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001495 {
James Feist5cb06082019-10-24 17:11:13 -07001496 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001497 }
James Feist918e18c2018-02-13 15:51:07 -08001498 };
James Feist9eb0b582018-04-27 12:15:46 -07001499
1500 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001501 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001502 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001503 "openbmc_project/state/"
1504 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001505 eventHandler);
1506
James Feist4131aea2018-03-09 09:47:30 -08001507 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001508 inotify_add_watch(fd, I2C_DEV_LOCATION,
1509 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001510 std::array<char, 4096> readBuffer;
1511 std::string pendingBuffer;
1512 // monitor for new i2c devices
1513 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1514 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001515 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001516 std::size_t bytes_transferred) {
1517 if (ec)
1518 {
1519 std::cout << "Callback Error " << ec << "\n";
1520 return;
1521 }
1522 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001523 while (pendingBuffer.size() > sizeof(inotify_event))
1524 {
James Feista465ccc2019-02-08 12:51:01 -08001525 const inotify_event* iEvent =
1526 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001527 pendingBuffer.data());
1528 switch (iEvent->mask)
1529 {
James Feist9eb0b582018-04-27 12:15:46 -07001530 case IN_CREATE:
1531 case IN_MOVED_TO:
1532 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001533 std::string name(iEvent->name);
1534 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001535 {
James Feist5d7f4692020-06-17 18:22:33 -07001536 int bus = busStrToInt(name);
1537 if (bus < 0)
1538 {
1539 std::cerr << "Could not parse bus " << name
1540 << "\n";
1541 continue;
1542 }
1543 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1544 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001545 }
James Feist4131aea2018-03-09 09:47:30 -08001546 }
1547
1548 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1549 }
James Feist6ebf9de2018-05-15 15:01:17 -07001550
James Feist4131aea2018-03-09 09:47:30 -08001551 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1552 watchI2cBusses);
1553 };
1554
1555 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001556 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001557 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001558
James Feist3cb5fec2018-01-23 14:41:51 -08001559 io.run();
1560 return 0;
1561}