blob: 7a46311273dad2cd805f3add080a914f23354473 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
Patrick Venturea49dc332019-10-26 08:32:02 -070017#include "Utils.hpp"
18
James Feist3b860982018-10-02 14:34:07 -070019#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080020#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070021#include <sys/inotify.h>
22#include <sys/ioctl.h>
23
Patrick Venturec274f2f2019-10-26 09:27:23 -070024#include <array>
James Feist3b860982018-10-02 14:34:07 -070025#include <boost/algorithm/string/predicate.hpp>
26#include <boost/container/flat_map.hpp>
27#include <chrono>
28#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070029#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080030#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070031#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080032#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070033#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <iostream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070035#include <nlohmann/json.hpp>
James Feist3f8a2782018-02-12 09:24:42 -080036#include <regex>
James Feist3b860982018-10-02 14:34:07 -070037#include <sdbusplus/asio/connection.hpp>
38#include <sdbusplus/asio/object_server.hpp>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070039#include <set>
40#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070041#include <string>
James Feist3b860982018-10-02 14:34:07 -070042#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080043#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070044#include <vector>
James Feist3b860982018-10-02 14:34:07 -070045
46extern "C" {
47#include <i2c/smbus.h>
48#include <linux/i2c-dev.h>
49}
James Feist3cb5fec2018-01-23 14:41:51 -080050
Ed Tanous072e25d2018-12-16 21:45:20 -080051namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080052static constexpr bool DEBUG = false;
53static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070054constexpr size_t MAX_FRU_SIZE = 512;
55constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070056constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080057
Patrick Venture11f1ff42019-08-01 10:42:12 -070058constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
59
James Feista465ccc2019-02-08 12:51:01 -080060const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080061 "/etc/fru/baseboard.fru.bin";
62
James Feista465ccc2019-02-08 12:51:01 -080063const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080064
James Feista465ccc2019-02-08 12:51:01 -080065static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080066 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070067const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080068using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
69using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
70
James Feist444830e2019-04-05 08:38:16 -070071static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070072struct FindDevicesWithCallback;
73
Nikhil Potaded8884f12019-03-27 13:27:13 -070074static BusMap busMap;
75
James Feist8a983922019-10-24 17:11:56 -070076static boost::container::flat_map<
77 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
78 foundDevices;
79
James Feist5cb06082019-10-24 17:11:13 -070080boost::asio::io_service io;
81auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
82auto objServer = sdbusplus::asio::object_server(systemBus);
83
Patrick Venturebaba7672019-10-26 09:26:41 -070084bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
85
86using ReadBlockFunc = std::function<int64_t(int flag, int file, uint16_t offset,
87 uint8_t length, uint8_t* outBuf)>;
88
89// Read and validate FRU contents, given the flag required for raw i2c, the open
90// file handle, a read method, and a helper string for failures.
91std::vector<char> readFruContents(int flag, int file, ReadBlockFunc readBlock,
92 const std::string& errorHelp)
93{
94 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
95
96 if (readBlock(flag, file, 0x0, 0x8, blockData.data()) < 0)
97 {
98 std::cerr << "failed to read " << errorHelp << "\n";
99 return {};
100 }
101
102 // check the header checksum
103 if (!validateHeader(blockData))
104 {
105 if (DEBUG)
106 {
107 std::cerr << "Illegal header " << errorHelp << "\n";
108 }
109
110 return {};
111 }
112
113 std::vector<char> device;
114 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
115
116 int fruLength = 0;
117 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
118 {
119 // TODO: offset can be 255, device is holding "chars" that's not
120 // good.
121 int areaOffset = device[jj];
122 if (areaOffset == 0)
123 {
124 continue;
125 }
126
127 areaOffset *= 8;
128
129 if (readBlock(flag, file, static_cast<uint16_t>(areaOffset), 0x2,
130 blockData.data()) < 0)
131 {
132 std::cerr << "failed to read " << errorHelp << "\n";
133 return {};
134 }
135
136 // Ignore data type.
137 int length = blockData[1] * 8;
138 areaOffset += length;
139 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
140 }
141
142 // You already copied these first 8 bytes (the ipmi fru header size)
143 fruLength -= 8;
144
145 int readOffset = 8;
146
147 while (fruLength > 0)
148 {
149 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
150
151 if (readBlock(flag, file, static_cast<uint16_t>(readOffset),
152 static_cast<uint8_t>(requestLength),
153 blockData.data()) < 0)
154 {
155 std::cerr << "failed to read " << errorHelp << "\n";
156 return {};
157 }
158
159 device.insert(device.end(), blockData.begin(),
160 blockData.begin() + requestLength);
161
162 readOffset += requestLength;
163 fruLength -= requestLength;
164 }
165
166 return device;
167}
168
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700169// Given a bus/address, produce the path in sysfs for an eeprom.
170static std::string getEepromPath(size_t bus, size_t address)
171{
172 std::stringstream output;
173 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
174 << std::setfill('0') << std::setw(4) << std::hex << address
175 << "/eeprom";
176 return output.str();
177}
178
179static bool hasEepromFile(size_t bus, size_t address)
180{
181 auto path = getEepromPath(bus, address);
182 try
183 {
184 return fs::exists(path);
185 }
186 catch (...)
187 {
188 return false;
189 }
190}
191
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700192static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
193 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700194{
195 auto result = lseek(fd, offset, SEEK_SET);
196 if (result < 0)
197 {
198 std::cerr << "failed to seek\n";
199 return -1;
200 }
201
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700202 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700203}
204
James Feistc95cb142018-02-26 10:41:42 -0800205static bool isMuxBus(size_t bus)
206{
Ed Tanous072e25d2018-12-16 21:45:20 -0800207 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800208 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
209}
210
James Feist8a983922019-10-24 17:11:56 -0700211static void makeProbeInterface(size_t bus, size_t address)
212{
213 if (isMuxBus(bus))
214 {
215 return; // the mux buses are random, no need to publish
216 }
217 auto [it, success] = foundDevices.emplace(
218 std::make_pair(bus, address),
219 objServer.add_interface(
220 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
221 std::to_string(address),
222 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
223 if (!success)
224 {
225 return; // already added
226 }
227 it->second->register_property("Bus", bus);
228 it->second->register_property("Address", address);
229 it->second->initialize();
230}
231
Vijay Khemka2d681f62018-11-06 15:51:00 -0800232static int isDevice16Bit(int file)
233{
234 /* Get first byte */
235 int byte1 = i2c_smbus_read_byte_data(file, 0);
236 if (byte1 < 0)
237 {
238 return byte1;
239 }
240 /* Read 7 more bytes, it will read same first byte in case of
241 * 8 bit but it will read next byte in case of 16 bit
242 */
243 for (int i = 0; i < 7; i++)
244 {
245 int byte2 = i2c_smbus_read_byte_data(file, 0);
246 if (byte2 < 0)
247 {
248 return byte2;
249 }
250 if (byte2 != byte1)
251 {
252 return 1;
253 }
254 }
255 return 0;
256}
257
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700258static int64_t readBlockData(int flag, int file, uint16_t offset, uint8_t len,
259 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800260{
Patrick Venture4f47fe62019-08-08 16:30:38 -0700261 uint8_t lowAddr = static_cast<uint8_t>(offset);
262 uint8_t highAddr = static_cast<uint8_t>(offset >> 8);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800263
264 if (flag == 0)
265 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700266 return i2c_smbus_read_i2c_block_data(file, lowAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800267 }
268
269 /* This is for 16 bit addressing EEPROM device. First an offset
270 * needs to be written before read data from a offset
271 */
Patrick Venture4f47fe62019-08-08 16:30:38 -0700272 int ret = i2c_smbus_write_byte_data(file, 0, lowAddr);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800273 if (ret < 0)
274 {
275 return ret;
276 }
277
Patrick Venture4f47fe62019-08-08 16:30:38 -0700278 return i2c_smbus_read_i2c_block_data(file, highAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800279}
280
James Feist24bae7a2019-04-03 09:50:56 -0700281bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
282{
283 // ipmi spec format version number is currently at 1, verify it
284 if (blockData[0] != 0x1)
285 {
286 return false;
287 }
288
289 // verify pad is set to 0
290 if (blockData[6] != 0x0)
291 {
292 return false;
293 }
294
295 // verify offsets are 0, or don't point to another offset
296 std::set<uint8_t> foundOffsets;
297 for (int ii = 1; ii < 6; ii++)
298 {
299 if (blockData[ii] == 0)
300 {
301 continue;
302 }
James Feist0eb40352019-04-09 14:44:04 -0700303 auto inserted = foundOffsets.insert(blockData[ii]);
304 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700305 {
306 return false;
307 }
308 }
309
310 // validate checksum
311 size_t sum = 0;
312 for (int jj = 0; jj < 7; jj++)
313 {
314 sum += blockData[jj];
315 }
316 sum = (256 - sum) & 0xFF;
317
318 if (sum != blockData[7])
319 {
320 return false;
321 }
322 return true;
323}
324
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700325// TODO: This code is very similar to the non-eeprom version and can be merged
326// with some tweaks.
327static std::vector<char> processEeprom(int bus, int address)
328{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700329 auto path = getEepromPath(bus, address);
330
331 int file = open(path.c_str(), O_RDONLY);
332 if (file < 0)
333 {
334 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700335 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700336 }
337
Patrick Venturebaba7672019-10-26 09:26:41 -0700338 std::string errorMessage = "eeprom at " + std::to_string(bus) +
339 " address " + std::to_string(address);
340 std::vector<char> device =
341 readFruContents(0, file, readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700342
343 close(file);
344 return device;
345}
346
347std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
348{
349 std::set<int> foundList;
350
351 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
352
353 // For each file listed under the i2c device
354 // NOTE: This should be faster than just checking for each possible address
355 // path.
356 for (const auto& p : fs::directory_iterator(path))
357 {
358 const std::string node = p.path().string();
359 std::smatch m;
360 bool found =
361 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
362
363 if (!found)
364 {
365 continue;
366 }
367 if (m.size() != 2)
368 {
369 std::cerr << "regex didn't capture\n";
370 continue;
371 }
372
373 std::ssub_match subMatch = m[1];
374 std::string addressString = subMatch.str();
375
376 std::size_t ignored;
377 const int hexBase = 16;
378 int address = std::stoi(addressString, &ignored, hexBase);
379
380 const std::string eeprom = node + "/eeprom";
381
382 try
383 {
384 if (!fs::exists(eeprom))
385 {
386 continue;
387 }
388 }
389 catch (...)
390 {
391 continue;
392 }
393
394 // There is an eeprom file at this address, it may have invalid
395 // contents, but we found it.
396 foundList.insert(address);
397
398 std::vector<char> device = processEeprom(i2cBus, address);
399 if (!device.empty())
400 {
401 devices->emplace(address, device);
402 }
403 }
404
405 return foundList;
406}
407
Patrick Venture4f47fe62019-08-08 16:30:38 -0700408int getBusFrus(int file, int first, int last, int bus,
409 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800410{
James Feist3cb5fec2018-01-23 14:41:51 -0800411
James Feist26c27ad2018-07-25 15:09:40 -0700412 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700413 // NOTE: When reading the devices raw on the bus, it can interfere with
414 // the driver's ability to operate, therefore read eeproms first before
415 // scanning for devices without drivers. Several experiments were run
416 // and it was determined that if there were any devices on the bus
417 // before the eeprom was hit and read, the eeprom driver wouldn't open
418 // while the bus device was open. An experiment was not performed to see
419 // if this issue was resolved if the i2c bus device was closed, but
420 // hexdumps of the eeprom later were successful.
421
422 // Scan for i2c eeproms loaded on this bus.
423 std::set<int> skipList = findI2CEeproms(bus, devices);
424
James Feist26c27ad2018-07-25 15:09:40 -0700425 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800426 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700427 if (skipList.find(ii) != skipList.end())
428 {
429 continue;
430 }
James Feist3cb5fec2018-01-23 14:41:51 -0800431
James Feist26c27ad2018-07-25 15:09:40 -0700432 // Set slave address
433 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800434 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700435 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700436 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700437 continue;
438 }
439 // probe
440 else if (i2c_smbus_read_byte(file) < 0)
441 {
442 continue;
443 }
James Feist3cb5fec2018-01-23 14:41:51 -0800444
James Feist26c27ad2018-07-25 15:09:40 -0700445 if (DEBUG)
446 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700447 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700448 << "\n";
449 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800450
James Feist8a983922019-10-24 17:11:56 -0700451 makeProbeInterface(bus, ii);
452
Vijay Khemka2d681f62018-11-06 15:51:00 -0800453 /* Check for Device type if it is 8 bit or 16 bit */
454 int flag = isDevice16Bit(file);
455 if (flag < 0)
456 {
457 std::cerr << "failed to read bus " << bus << " address " << ii
458 << "\n";
459 continue;
460 }
461
Patrick Venturebaba7672019-10-26 09:26:41 -0700462 std::string errorMessage =
463 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
464 std::vector<char> device =
465 readFruContents(flag, file, readBlockData, errorMessage);
466 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700467 {
James Feist26c27ad2018-07-25 15:09:40 -0700468 continue;
469 }
James Feist26c27ad2018-07-25 15:09:40 -0700470
Patrick Venture786f1792019-08-05 16:33:44 -0700471 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800472 }
James Feist26c27ad2018-07-25 15:09:40 -0700473 return 1;
474 });
475 std::future_status status =
476 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
477 if (status == std::future_status::timeout)
478 {
479 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700480 busBlacklist.insert(bus);
481 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700482 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800483 }
484
James Feist444830e2019-04-05 08:38:16 -0700485 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700486 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800487}
488
Patrick Venture11f1ff42019-08-01 10:42:12 -0700489void loadBlacklist(const char* path)
490{
491 std::ifstream blacklistStream(path);
492 if (!blacklistStream.good())
493 {
494 // File is optional.
495 std::cerr << "Cannot open blacklist file.\n\n";
496 return;
497 }
498
499 nlohmann::json data =
500 nlohmann::json::parse(blacklistStream, nullptr, false);
501 if (data.is_discarded())
502 {
503 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
504 "exiting\n";
505 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700506 }
507
508 // It's expected to have at least one field, "buses" that is an array of the
509 // buses by integer. Allow for future options to exclude further aspects,
510 // such as specific addresses or ranges.
511 if (data.type() != nlohmann::json::value_t::object)
512 {
513 std::cerr << "Illegal blacklist, expected to read dictionary\n";
514 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700515 }
516
517 // If buses field is missing, that's fine.
518 if (data.count("buses") == 1)
519 {
520 // Parse the buses array after a little validation.
521 auto buses = data.at("buses");
522 if (buses.type() != nlohmann::json::value_t::array)
523 {
524 // Buses field present but invalid, therefore this is an error.
525 std::cerr << "Invalid contents for blacklist buses field\n";
526 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700527 }
528
529 // Catch exception here for type mis-match.
530 try
531 {
532 for (const auto& bus : buses)
533 {
534 busBlacklist.insert(bus.get<size_t>());
535 }
536 }
537 catch (const nlohmann::detail::type_error& e)
538 {
539 // Type mis-match is a critical error.
540 std::cerr << "Invalid bus type: " << e.what() << "\n";
541 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700542 }
543 }
544
545 return;
546}
547
James Feista465ccc2019-02-08 12:51:01 -0800548static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700549 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800550{
James Feista465ccc2019-02-08 12:51:01 -0800551 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800552 {
553 auto busnum = i2cBus.string();
554 auto lastDash = busnum.rfind(std::string("-"));
555 // delete everything before dash inclusive
556 if (lastDash != std::string::npos)
557 {
558 busnum.erase(0, lastDash + 1);
559 }
560 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700561 if (busBlacklist.find(bus) != busBlacklist.end())
562 {
563 continue; // skip previously failed busses
564 }
James Feist3cb5fec2018-01-23 14:41:51 -0800565
566 auto file = open(i2cBus.c_str(), O_RDWR);
567 if (file < 0)
568 {
569 std::cerr << "unable to open i2c device " << i2cBus.string()
570 << "\n";
571 continue;
572 }
573 unsigned long funcs = 0;
574
575 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
576 {
577 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700578 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800579 << bus << "\n";
580 continue;
581 }
582 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
583 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
584 {
585 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
586 << bus << "\n";
587 continue;
588 }
James Feist98132792019-07-09 13:29:09 -0700589 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800590 device = std::make_shared<DeviceMap>();
591
Nikhil Potaded8884f12019-03-27 13:27:13 -0700592 // i2cdetect by default uses the range 0x03 to 0x77, as
593 // this is what we have tested with, use this range. Could be
594 // changed in future.
595 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800596 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700597 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800598 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700599
600 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700601 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700602
603 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800604 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700605 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800606 }
James Feist3cb5fec2018-01-23 14:41:51 -0800607 }
James Feist3cb5fec2018-01-23 14:41:51 -0800608}
609
James Feist6ebf9de2018-05-15 15:01:17 -0700610// this class allows an async response after all i2c devices are discovered
611struct FindDevicesWithCallback
612 : std::enable_shared_from_this<FindDevicesWithCallback>
613{
James Feista465ccc2019-02-08 12:51:01 -0800614 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700615 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800616 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700617 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700618 _busMap(busmap), _callback(std::move(callback))
James Feist6ebf9de2018-05-15 15:01:17 -0700619 {
620 }
621 ~FindDevicesWithCallback()
622 {
623 _callback();
624 }
625 void run()
626 {
James Feist98132792019-07-09 13:29:09 -0700627 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700628 }
629
James Feista465ccc2019-02-08 12:51:01 -0800630 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800631 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700632 std::function<void(void)> _callback;
633};
634
James Feist3cb5fec2018-01-23 14:41:51 -0800635static const std::tm intelEpoch(void)
636{
James Feist98132792019-07-09 13:29:09 -0700637 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800638 val.tm_year = 1996 - 1900;
639 return val;
640}
641
James Feista465ccc2019-02-08 12:51:01 -0800642bool formatFru(const std::vector<char>& fruBytes,
643 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800644{
James Feista465ccc2019-02-08 12:51:01 -0800645 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800646 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800647
James Feista465ccc2019-02-08 12:51:01 -0800648 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800649 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
650 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800651
James Feista465ccc2019-02-08 12:51:01 -0800652 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800653 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
654 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
655 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800656
James Feistd068e932018-09-20 10:53:07 -0700657 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800658 {
659 return false;
660 }
661 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700662 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800663 std::to_string(static_cast<int>(*fruAreaOffsetField));
664
James Feista465ccc2019-02-08 12:51:01 -0800665 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800666
James Feist0eb40352019-04-09 14:44:04 -0700667 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800668 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700669 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800670 if (fruAreaOffsetField >= fruBytes.end())
671 {
672 return false;
673 }
674 size_t offset = (*fruAreaOffsetField) * 8;
675
676 if (offset > 1)
677 {
678 // +2 to skip format and length
679 std::vector<char>::const_iterator fruBytesIter =
680 fruBytes.begin() + offset + 2;
681
682 if (fruBytesIter >= fruBytes.end())
683 {
684 return false;
685 }
686
687 if (area == "CHASSIS")
688 {
689 result["CHASSIS_TYPE"] =
690 std::to_string(static_cast<int>(*fruBytesIter));
691 fruBytesIter += 1;
692 fieldData = &CHASSIS_FRU_AREAS;
693 }
694 else if (area == "BOARD")
695 {
696 result["BOARD_LANGUAGE_CODE"] =
697 std::to_string(static_cast<int>(*fruBytesIter));
698 fruBytesIter += 1;
699 if (fruBytesIter >= fruBytes.end())
700 {
701 return false;
702 }
703
704 unsigned int minutes = *fruBytesIter |
705 *(fruBytesIter + 1) << 8 |
706 *(fruBytesIter + 2) << 16;
707 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700708 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800709 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700710 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800711
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700712 // Tue Nov 20 23:08:00 2018
713 char timeString[32] = {0};
714 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700715 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700716 if (bytes == 0)
717 {
718 std::cerr << "invalid time string encountered\n";
719 return false;
720 }
721
722 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800723 fruBytesIter += 3;
724 fieldData = &BOARD_FRU_AREAS;
725 }
726 else if (area == "PRODUCT")
727 {
728 result["PRODUCT_LANGUAGE_CODE"] =
729 std::to_string(static_cast<int>(*fruBytesIter));
730 fruBytesIter += 1;
731 fieldData = &PRODUCT_FRU_AREAS;
732 }
733 else
734 {
735 continue;
736 }
James Feista465ccc2019-02-08 12:51:01 -0800737 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800738 {
739 if (fruBytesIter >= fruBytes.end())
740 {
741 return false;
742 }
743
Vijay Khemka5d5de442018-11-07 10:51:25 -0800744 /* Checking for last byte C1 to indicate that no more
745 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700746 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800747 {
748 break;
749 }
750
Ed Tanous2147e672019-02-27 13:59:56 -0800751 size_t length = *fruBytesIter & 0x3f;
752 fruBytesIter += 1;
753
James Feist3cb5fec2018-01-23 14:41:51 -0800754 if (fruBytesIter >= fruBytes.end())
755 {
756 return false;
757 }
Ed Tanous2147e672019-02-27 13:59:56 -0800758 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800759
Ed Tanous2147e672019-02-27 13:59:56 -0800760 // Strip non null characters from the end
761 value.erase(std::find_if(value.rbegin(), value.rend(),
762 [](char ch) { return ch != 0; })
763 .base(),
764 value.end());
765
James Feist0eb40352019-04-09 14:44:04 -0700766 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800767
James Feist3cb5fec2018-01-23 14:41:51 -0800768 fruBytesIter += length;
769 if (fruBytesIter >= fruBytes.end())
770 {
771 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800772 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800773 {
774 std::cerr << c;
775 }
776 std::cerr << "\n";
777 if (DEBUG)
778 {
James Feista465ccc2019-02-08 12:51:01 -0800779 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800780 {
781 std::cerr << keyPair.first << " : "
782 << keyPair.second << "\n";
783 }
784 }
785 return false;
786 }
787 }
788 }
789 }
790
791 return true;
792}
793
Nikhil Potaded8884f12019-03-27 13:27:13 -0700794std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
795{
796 auto deviceMap = busMap.find(bus);
797 if (deviceMap == busMap.end())
798 {
799 throw std::invalid_argument("Invalid Bus.");
800 }
801 auto device = deviceMap->second->find(address);
802 if (device == deviceMap->second->end())
803 {
804 throw std::invalid_argument("Invalid Address.");
805 }
806 std::vector<uint8_t>& ret =
807 reinterpret_cast<std::vector<uint8_t>&>(device->second);
808
809 return ret;
810}
811
James Feist3cb5fec2018-01-23 14:41:51 -0800812void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700813 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800814 boost::container::flat_map<
815 std::pair<size_t, size_t>,
816 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700817 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800818{
819 boost::container::flat_map<std::string, std::string> formattedFru;
820 if (!formatFru(device, formattedFru))
821 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700822 std::cerr << "failed to format fru for device at bus " << bus
823 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800824 return;
825 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700826
James Feist3cb5fec2018-01-23 14:41:51 -0800827 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
828 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700829 // Not found under Board section or an empty string.
830 if (productNameFind == formattedFru.end() ||
831 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800832 {
833 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
834 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700835 // Found under Product section and not an empty string.
836 if (productNameFind != formattedFru.end() &&
837 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800838 {
839 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800840 std::regex illegalObject("[^A-Za-z0-9_]");
841 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800842 }
843 else
844 {
845 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
846 UNKNOWN_BUS_OBJECT_COUNT++;
847 }
848
James Feist918e18c2018-02-13 15:51:07 -0800849 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800850 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700851 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800852 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700853 int highest = -1;
854 bool found = false;
855
James Feista465ccc2019-02-08 12:51:01 -0800856 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800857 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700858 std::string path = busIface.second->get_object_path();
859 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800860 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700861 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -0700862 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
863 static_cast<uint8_t>(busIface.first.second)) ==
864 getFruInfo(static_cast<uint8_t>(bus),
865 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -0700866 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700867 // This device is already added to the lower numbered bus,
868 // do not replicate it.
869 return;
James Feist79e9c0b2018-03-15 15:21:17 -0700870 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700871
872 // Check if the match named has extra information.
873 found = true;
874 std::smatch base_match;
875
876 bool match = std::regex_match(
877 path, base_match, std::regex(productName + "_(\\d+)$"));
878 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -0700879 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700880 if (base_match.size() == 2)
881 {
882 std::ssub_match base_sub_match = base_match[1];
883 std::string base = base_sub_match.str();
884
885 int value = std::stoi(base);
886 highest = (value > highest) ? value : highest;
887 }
James Feist79e9c0b2018-03-15 15:21:17 -0700888 }
James Feist918e18c2018-02-13 15:51:07 -0800889 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700890 } // end searching objects
891
892 if (found)
893 {
894 // We found something with the same name. If highest was still -1,
895 // it means this new entry will be _0.
896 productName += "_";
897 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -0800898 }
899 }
James Feist3cb5fec2018-01-23 14:41:51 -0800900
James Feist9eb0b582018-04-27 12:15:46 -0700901 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
902 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
903 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
904
James Feista465ccc2019-02-08 12:51:01 -0800905 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800906 {
James Feist9eb0b582018-04-27 12:15:46 -0700907
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700908 std::regex_replace(property.second.begin(), property.second.begin(),
909 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700910 if (property.second.empty())
911 {
912 continue;
913 }
914 std::string key =
915 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
916 if (!iface->register_property(key, property.second + '\0'))
917 {
918 std::cerr << "illegal key: " << key << "\n";
919 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700920 if (DEBUG)
921 {
922 std::cout << property.first << ": " << property.second << "\n";
923 }
James Feist3cb5fec2018-01-23 14:41:51 -0800924 }
James Feist2a9d6db2018-04-27 15:48:28 -0700925
926 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700927 iface->register_property("BUS", bus);
928 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700929
James Feist9eb0b582018-04-27 12:15:46 -0700930 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800931}
932
James Feista465ccc2019-02-08 12:51:01 -0800933static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800934{
935 // try to read baseboard fru from file
936 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
937 if (baseboardFruFile.good())
938 {
939 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -0700940 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -0800941 baseboardFru.resize(fileSize);
942 baseboardFruFile.seekg(0, std::ios_base::beg);
943 baseboardFruFile.read(baseboardFru.data(), fileSize);
944 }
945 else
946 {
947 return false;
948 }
949 return true;
950}
951
James Feista465ccc2019-02-08 12:51:01 -0800952bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700953{
954 boost::container::flat_map<std::string, std::string> tmp;
955 if (fru.size() > MAX_FRU_SIZE)
956 {
957 std::cerr << "Invalid fru.size() during writeFru\n";
958 return false;
959 }
960 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -0800961 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -0700962 {
963 std::cerr << "Invalid fru format during writeFru\n";
964 return false;
965 }
966 // baseboard fru
967 if (bus == 0 && address == 0)
968 {
969 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
970 if (!file.good())
971 {
972 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
973 << "\n";
James Feistddb78302018-09-06 11:45:42 -0700974 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700975 return false;
976 }
James Feista465ccc2019-02-08 12:51:01 -0800977 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700978 return file.good();
979 }
980 else
981 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700982 if (hasEepromFile(bus, address))
983 {
984 auto path = getEepromPath(bus, address);
985 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
986 if (eeprom < 0)
987 {
988 std::cerr << "unable to open i2c device " << path << "\n";
989 throw DBusInternalError();
990 return false;
991 }
992
993 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
994 if (writtenBytes < 0)
995 {
996 std::cerr << "unable to write to i2c device " << path << "\n";
997 close(eeprom);
998 throw DBusInternalError();
999 return false;
1000 }
1001
1002 close(eeprom);
1003 return true;
1004 }
1005
James Feistb49ffc32018-05-02 11:10:43 -07001006 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1007
1008 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1009 if (file < 0)
1010 {
1011 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001012 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001013 return false;
1014 }
1015 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1016 {
1017 std::cerr << "unable to set device address\n";
1018 close(file);
James Feistddb78302018-09-06 11:45:42 -07001019 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001020 return false;
1021 }
1022
1023 constexpr const size_t RETRY_MAX = 2;
1024 uint16_t index = 0;
1025 size_t retries = RETRY_MAX;
1026 while (index < fru.size())
1027 {
1028 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1029 (retries == RETRY_MAX))
1030 {
1031 // The 4K EEPROM only uses the A2 and A1 device address bits
1032 // with the third bit being a memory page address bit.
1033 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1034 {
1035 std::cerr << "unable to set device address\n";
1036 close(file);
James Feistddb78302018-09-06 11:45:42 -07001037 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001038 return false;
1039 }
1040 }
1041
James Feist98132792019-07-09 13:29:09 -07001042 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1043 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001044 {
1045 if (!retries--)
1046 {
1047 std::cerr << "error writing fru: " << strerror(errno)
1048 << "\n";
1049 close(file);
James Feistddb78302018-09-06 11:45:42 -07001050 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001051 return false;
1052 }
1053 }
1054 else
1055 {
1056 retries = RETRY_MAX;
1057 index++;
1058 }
1059 // most eeproms require 5-10ms between writes
1060 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1061 }
1062 close(file);
1063 return true;
1064 }
1065}
1066
James Feist9eb0b582018-04-27 12:15:46 -07001067void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001068 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001069 boost::container::flat_map<
1070 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001071 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001072{
James Feist6ebf9de2018-05-15 15:01:17 -07001073 static boost::asio::deadline_timer timer(io);
1074 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001075
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001076 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001077 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001078 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001079 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001080
Nikhil Potaded8884f12019-03-27 13:27:13 -07001081 boost::container::flat_map<size_t, fs::path> busPaths;
1082 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001083 {
James Feist4131aea2018-03-09 09:47:30 -08001084 std::cerr << "unable to find i2c devices\n";
1085 return;
James Feist918e18c2018-02-13 15:51:07 -08001086 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001087
1088 for (auto busPath : busPaths)
1089 {
1090 i2cBuses.emplace_back(busPath.second);
1091 }
James Feist4131aea2018-03-09 09:47:30 -08001092
James Feist98132792019-07-09 13:29:09 -07001093 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001094 for (auto& [pair, interface] : foundDevices)
1095 {
1096 objServer.remove_interface(interface);
1097 }
1098 foundDevices.clear();
1099
James Feist5cb06082019-10-24 17:11:13 -07001100 auto scan =
1101 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001102 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001103 {
1104 objServer.remove_interface(busIface.second);
1105 }
James Feist4131aea2018-03-09 09:47:30 -08001106
James Feist6ebf9de2018-05-15 15:01:17 -07001107 dbusInterfaceMap.clear();
1108 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001109
James Feist6ebf9de2018-05-15 15:01:17 -07001110 // todo, get this from a more sensable place
1111 std::vector<char> baseboardFru;
1112 if (readBaseboardFru(baseboardFru))
1113 {
1114 boost::container::flat_map<int, std::vector<char>>
1115 baseboardDev;
1116 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001117 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001118 }
James Feist98132792019-07-09 13:29:09 -07001119 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001120 {
James Feista465ccc2019-02-08 12:51:01 -08001121 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001122 {
James Feist5cb06082019-10-24 17:11:13 -07001123 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1124 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001125 }
1126 }
1127 });
1128 scan->run();
1129 });
James Feist918e18c2018-02-13 15:51:07 -08001130}
1131
James Feist98132792019-07-09 13:29:09 -07001132int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001133{
1134 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001135 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001136 std::vector<fs::path> i2cBuses;
1137
James Feista3c180a2018-08-09 16:06:04 -07001138 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001139 {
1140 std::cerr << "unable to find i2c devices\n";
1141 return 1;
1142 }
James Feist3cb5fec2018-01-23 14:41:51 -08001143
Patrick Venture11f1ff42019-08-01 10:42:12 -07001144 // check for and load blacklist with initial buses.
1145 loadBlacklist(blacklistPath);
1146
Vijay Khemka065f6d92018-12-18 10:37:47 -08001147 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001148
James Feist6ebf9de2018-05-15 15:01:17 -07001149 // this is a map with keys of pair(bus number, address) and values of
1150 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001151 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001152 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1153 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001154
James Feist9eb0b582018-04-27 12:15:46 -07001155 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1156 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1157 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001158
James Feist5cb06082019-10-24 17:11:13 -07001159 iface->register_method("ReScan",
1160 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001161
Nikhil Potaded8884f12019-03-27 13:27:13 -07001162 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001163
1164 iface->register_method("WriteFru", [&](const uint8_t bus,
1165 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001166 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001167 if (!writeFru(bus, address, data))
1168 {
James Feistddb78302018-09-06 11:45:42 -07001169 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001170 return;
1171 }
1172 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001173 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001174 });
James Feist9eb0b582018-04-27 12:15:46 -07001175 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001176
James Feist9eb0b582018-04-27 12:15:46 -07001177 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001178 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001179 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001180 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001181 std::string,
1182 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001183 values;
1184 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001185 auto findState = values.find("CurrentHostState");
1186 bool on = false;
1187 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001188 {
James Feist0eeb79c2019-10-09 13:35:29 -07001189 on = boost::ends_with(std::get<std::string>(findState->second),
1190 "Running");
1191 }
James Feist6ebf9de2018-05-15 15:01:17 -07001192
James Feist0eeb79c2019-10-09 13:35:29 -07001193 if (on)
1194 {
James Feist5cb06082019-10-24 17:11:13 -07001195 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001196 }
James Feist918e18c2018-02-13 15:51:07 -08001197 };
James Feist9eb0b582018-04-27 12:15:46 -07001198
1199 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001200 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001201 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001202 "openbmc_project/state/"
1203 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001204 eventHandler);
1205
James Feist4131aea2018-03-09 09:47:30 -08001206 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001207 inotify_add_watch(fd, I2C_DEV_LOCATION,
1208 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001209 std::array<char, 4096> readBuffer;
1210 std::string pendingBuffer;
1211 // monitor for new i2c devices
1212 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1213 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001214 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001215 std::size_t bytes_transferred) {
1216 if (ec)
1217 {
1218 std::cout << "Callback Error " << ec << "\n";
1219 return;
1220 }
1221 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1222 bool devChange = false;
1223 while (pendingBuffer.size() > sizeof(inotify_event))
1224 {
James Feista465ccc2019-02-08 12:51:01 -08001225 const inotify_event* iEvent =
1226 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001227 pendingBuffer.data());
1228 switch (iEvent->mask)
1229 {
James Feist9eb0b582018-04-27 12:15:46 -07001230 case IN_CREATE:
1231 case IN_MOVED_TO:
1232 case IN_DELETE:
1233 if (boost::starts_with(std::string(iEvent->name),
1234 "i2c"))
1235 {
1236 devChange = true;
1237 }
James Feist4131aea2018-03-09 09:47:30 -08001238 }
1239
1240 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1241 }
James Feist6ebf9de2018-05-15 15:01:17 -07001242 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001243 {
James Feist5cb06082019-10-24 17:11:13 -07001244 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001245 }
James Feist6ebf9de2018-05-15 15:01:17 -07001246
James Feist4131aea2018-03-09 09:47:30 -08001247 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1248 watchI2cBusses);
1249 };
1250
1251 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001252 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001253 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001254
James Feist3cb5fec2018-01-23 14:41:51 -08001255 io.run();
1256 return 0;
1257}