blob: f7be420b658a35900368ab3d66ca40915f8a2087 [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>
31#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070032#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080033#include <iostream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070034#include <nlohmann/json.hpp>
James Feist3f8a2782018-02-12 09:24:42 -080035#include <regex>
James Feist3b860982018-10-02 14:34:07 -070036#include <sdbusplus/asio/connection.hpp>
37#include <sdbusplus/asio/object_server.hpp>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070038#include <set>
39#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070040#include <string>
James Feist3b860982018-10-02 14:34:07 -070041#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080042#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070043#include <vector>
James Feist3b860982018-10-02 14:34:07 -070044
45extern "C" {
46#include <i2c/smbus.h>
47#include <linux/i2c-dev.h>
48}
James Feist3cb5fec2018-01-23 14:41:51 -080049
Ed Tanous072e25d2018-12-16 21:45:20 -080050namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080051static constexpr bool DEBUG = false;
52static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070053constexpr size_t MAX_FRU_SIZE = 512;
54constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070055constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080056
Patrick Venture11f1ff42019-08-01 10:42:12 -070057constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
58
James Feista465ccc2019-02-08 12:51:01 -080059const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080060 "/etc/fru/baseboard.fru.bin";
61
James Feista465ccc2019-02-08 12:51:01 -080062const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080063
James Feista465ccc2019-02-08 12:51:01 -080064static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080065 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070066const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080067using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
68using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
69
James Feist444830e2019-04-05 08:38:16 -070070static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070071struct FindDevicesWithCallback;
72
Nikhil Potaded8884f12019-03-27 13:27:13 -070073static BusMap busMap;
74
James Feist8a983922019-10-24 17:11:56 -070075static boost::container::flat_map<
76 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
77 foundDevices;
78
James Feist5cb06082019-10-24 17:11:13 -070079boost::asio::io_service io;
80auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
81auto objServer = sdbusplus::asio::object_server(systemBus);
82
Patrick Venturec50e1ff2019-08-06 10:22:28 -070083// Given a bus/address, produce the path in sysfs for an eeprom.
84static std::string getEepromPath(size_t bus, size_t address)
85{
86 std::stringstream output;
87 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
88 << std::setfill('0') << std::setw(4) << std::hex << address
89 << "/eeprom";
90 return output.str();
91}
92
93static bool hasEepromFile(size_t bus, size_t address)
94{
95 auto path = getEepromPath(bus, address);
96 try
97 {
98 return fs::exists(path);
99 }
100 catch (...)
101 {
102 return false;
103 }
104}
105
Patrick Venturef0f97ce2019-10-26 08:38:43 -0700106static int readFromEeprom(int flag __attribute__((unused)), int fd,
107 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700108{
109 auto result = lseek(fd, offset, SEEK_SET);
110 if (result < 0)
111 {
112 std::cerr << "failed to seek\n";
113 return -1;
114 }
115
Patrick Venturef0f97ce2019-10-26 08:38:43 -0700116 return static_cast<int>(read(fd, buf, len));
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700117}
118
James Feistc95cb142018-02-26 10:41:42 -0800119static bool isMuxBus(size_t bus)
120{
Ed Tanous072e25d2018-12-16 21:45:20 -0800121 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800122 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
123}
124
James Feist8a983922019-10-24 17:11:56 -0700125static void makeProbeInterface(size_t bus, size_t address)
126{
127 if (isMuxBus(bus))
128 {
129 return; // the mux buses are random, no need to publish
130 }
131 auto [it, success] = foundDevices.emplace(
132 std::make_pair(bus, address),
133 objServer.add_interface(
134 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
135 std::to_string(address),
136 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
137 if (!success)
138 {
139 return; // already added
140 }
141 it->second->register_property("Bus", bus);
142 it->second->register_property("Address", address);
143 it->second->initialize();
144}
145
Vijay Khemka2d681f62018-11-06 15:51:00 -0800146static int isDevice16Bit(int file)
147{
148 /* Get first byte */
149 int byte1 = i2c_smbus_read_byte_data(file, 0);
150 if (byte1 < 0)
151 {
152 return byte1;
153 }
154 /* Read 7 more bytes, it will read same first byte in case of
155 * 8 bit but it will read next byte in case of 16 bit
156 */
157 for (int i = 0; i < 7; i++)
158 {
159 int byte2 = i2c_smbus_read_byte_data(file, 0);
160 if (byte2 < 0)
161 {
162 return byte2;
163 }
164 if (byte2 != byte1)
165 {
166 return 1;
167 }
168 }
169 return 0;
170}
171
Patrick Venture4f47fe62019-08-08 16:30:38 -0700172static int readBlockData(int flag, int file, uint16_t offset, uint8_t len,
173 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800174{
Patrick Venture4f47fe62019-08-08 16:30:38 -0700175 uint8_t lowAddr = static_cast<uint8_t>(offset);
176 uint8_t highAddr = static_cast<uint8_t>(offset >> 8);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800177
178 if (flag == 0)
179 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700180 return i2c_smbus_read_i2c_block_data(file, lowAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800181 }
182
183 /* This is for 16 bit addressing EEPROM device. First an offset
184 * needs to be written before read data from a offset
185 */
Patrick Venture4f47fe62019-08-08 16:30:38 -0700186 int ret = i2c_smbus_write_byte_data(file, 0, lowAddr);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800187 if (ret < 0)
188 {
189 return ret;
190 }
191
Patrick Venture4f47fe62019-08-08 16:30:38 -0700192 return i2c_smbus_read_i2c_block_data(file, highAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800193}
194
James Feist24bae7a2019-04-03 09:50:56 -0700195bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
196{
197 // ipmi spec format version number is currently at 1, verify it
198 if (blockData[0] != 0x1)
199 {
200 return false;
201 }
202
203 // verify pad is set to 0
204 if (blockData[6] != 0x0)
205 {
206 return false;
207 }
208
209 // verify offsets are 0, or don't point to another offset
210 std::set<uint8_t> foundOffsets;
211 for (int ii = 1; ii < 6; ii++)
212 {
213 if (blockData[ii] == 0)
214 {
215 continue;
216 }
James Feist0eb40352019-04-09 14:44:04 -0700217 auto inserted = foundOffsets.insert(blockData[ii]);
218 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700219 {
220 return false;
221 }
222 }
223
224 // validate checksum
225 size_t sum = 0;
226 for (int jj = 0; jj < 7; jj++)
227 {
228 sum += blockData[jj];
229 }
230 sum = (256 - sum) & 0xFF;
231
232 if (sum != blockData[7])
233 {
234 return false;
235 }
236 return true;
237}
238
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700239// TODO: This code is very similar to the non-eeprom version and can be merged
240// with some tweaks.
241static std::vector<char> processEeprom(int bus, int address)
242{
243 std::vector<char> device;
Patrick Venture4f47fe62019-08-08 16:30:38 -0700244 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700245
246 auto path = getEepromPath(bus, address);
247
248 int file = open(path.c_str(), O_RDONLY);
249 if (file < 0)
250 {
251 std::cerr << "Unable to open eeprom file: " << path << "\n";
252 return device;
253 }
254
Patrick Venturef0f97ce2019-10-26 08:38:43 -0700255 int readBytes = readFromEeprom(0, file, 0, 0x8, blockData.data());
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700256 if (readBytes < 0)
257 {
258 std::cerr << "failed to read eeprom at " << bus << " address "
259 << address << "\n";
260 close(file);
261 return device;
262 }
263
Patrick Venture4f47fe62019-08-08 16:30:38 -0700264 if (!validateHeader(blockData))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700265 {
266 if (DEBUG)
267 {
268 std::cerr << "Illegal header at bus " << bus << " address "
269 << address << "\n";
270 }
271
272 close(file);
273 return device;
274 }
275
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700276 // Copy the IPMI Fru Header
Patrick Venture4f47fe62019-08-08 16:30:38 -0700277 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700278
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700279 int fruLength = 0;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700280 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
281 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700282 // TODO: offset can be 255, device is holding "chars" that's not good.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700283 int areaOffset = device[jj];
284 if (areaOffset == 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700285 {
286 continue;
287 }
288
Patrick Venture4f47fe62019-08-08 16:30:38 -0700289 areaOffset *= 8;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700290
Patrick Venturef0f97ce2019-10-26 08:38:43 -0700291 if (readFromEeprom(0, file, static_cast<uint16_t>(areaOffset), 0x2,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700292 blockData.data()) < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700293 {
294 std::cerr << "failed to read bus " << bus << " address " << address
295 << "\n";
296 device.clear();
297 close(file);
298 return device;
299 }
300
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700301 // Ignore data type.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700302 int length = blockData[1] * 8;
303 areaOffset += length;
304 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700305 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700306
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700307 // You already copied these first 8 bytes (the ipmi fru header size)
308 fruLength -= 8;
309
310 int readOffset = 8;
311
312 while (fruLength > 0)
313 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700314 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700315
Patrick Venturef0f97ce2019-10-26 08:38:43 -0700316 if (readFromEeprom(0, file, static_cast<uint16_t>(readOffset),
Patrick Venture4f47fe62019-08-08 16:30:38 -0700317 static_cast<uint8_t>(requestLength),
318 blockData.data()) < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700319 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700320 std::cerr << "failed to read bus " << bus << " address " << address
321 << "\n";
322 device.clear();
323 close(file);
324 return device;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700325 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700326
Patrick Venture4f47fe62019-08-08 16:30:38 -0700327 device.insert(device.end(), blockData.begin(),
328 blockData.begin() + requestLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700329
Patrick Venture4f47fe62019-08-08 16:30:38 -0700330 readOffset += requestLength;
331 fruLength -= requestLength;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700332 }
333
334 close(file);
335 return device;
336}
337
338std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
339{
340 std::set<int> foundList;
341
342 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
343
344 // For each file listed under the i2c device
345 // NOTE: This should be faster than just checking for each possible address
346 // path.
347 for (const auto& p : fs::directory_iterator(path))
348 {
349 const std::string node = p.path().string();
350 std::smatch m;
351 bool found =
352 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
353
354 if (!found)
355 {
356 continue;
357 }
358 if (m.size() != 2)
359 {
360 std::cerr << "regex didn't capture\n";
361 continue;
362 }
363
364 std::ssub_match subMatch = m[1];
365 std::string addressString = subMatch.str();
366
367 std::size_t ignored;
368 const int hexBase = 16;
369 int address = std::stoi(addressString, &ignored, hexBase);
370
371 const std::string eeprom = node + "/eeprom";
372
373 try
374 {
375 if (!fs::exists(eeprom))
376 {
377 continue;
378 }
379 }
380 catch (...)
381 {
382 continue;
383 }
384
385 // There is an eeprom file at this address, it may have invalid
386 // contents, but we found it.
387 foundList.insert(address);
388
389 std::vector<char> device = processEeprom(i2cBus, address);
390 if (!device.empty())
391 {
392 devices->emplace(address, device);
393 }
394 }
395
396 return foundList;
397}
398
Patrick Venture4f47fe62019-08-08 16:30:38 -0700399int getBusFrus(int file, int first, int last, int bus,
400 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800401{
James Feist3cb5fec2018-01-23 14:41:51 -0800402
James Feist26c27ad2018-07-25 15:09:40 -0700403 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700404 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800405
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700406 // NOTE: When reading the devices raw on the bus, it can interfere with
407 // the driver's ability to operate, therefore read eeproms first before
408 // scanning for devices without drivers. Several experiments were run
409 // and it was determined that if there were any devices on the bus
410 // before the eeprom was hit and read, the eeprom driver wouldn't open
411 // while the bus device was open. An experiment was not performed to see
412 // if this issue was resolved if the i2c bus device was closed, but
413 // hexdumps of the eeprom later were successful.
414
415 // Scan for i2c eeproms loaded on this bus.
416 std::set<int> skipList = findI2CEeproms(bus, devices);
417
James Feist26c27ad2018-07-25 15:09:40 -0700418 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800419 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700420 if (skipList.find(ii) != skipList.end())
421 {
422 continue;
423 }
James Feist3cb5fec2018-01-23 14:41:51 -0800424
James Feist26c27ad2018-07-25 15:09:40 -0700425 // Set slave address
426 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800427 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700428 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700429 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700430 continue;
431 }
432 // probe
433 else if (i2c_smbus_read_byte(file) < 0)
434 {
435 continue;
436 }
James Feist3cb5fec2018-01-23 14:41:51 -0800437
James Feist26c27ad2018-07-25 15:09:40 -0700438 if (DEBUG)
439 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700440 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700441 << "\n";
442 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800443
James Feist8a983922019-10-24 17:11:56 -0700444 makeProbeInterface(bus, ii);
445
Vijay Khemka2d681f62018-11-06 15:51:00 -0800446 /* Check for Device type if it is 8 bit or 16 bit */
447 int flag = isDevice16Bit(file);
448 if (flag < 0)
449 {
450 std::cerr << "failed to read bus " << bus << " address " << ii
451 << "\n";
452 continue;
453 }
454
Patrick Venture4f47fe62019-08-08 16:30:38 -0700455 if (readBlockData(flag, file, 0x0, 0x8, blockData.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700456 {
457 std::cerr << "failed to read bus " << bus << " address " << ii
458 << "\n";
459 continue;
460 }
James Feist26c27ad2018-07-25 15:09:40 -0700461
462 // check the header checksum
Patrick Venture4f47fe62019-08-08 16:30:38 -0700463 if (!validateHeader(blockData))
James Feist26c27ad2018-07-25 15:09:40 -0700464 {
Patrick Venture786f1792019-08-05 16:33:44 -0700465 if (DEBUG)
James Feist26c27ad2018-07-25 15:09:40 -0700466 {
Patrick Venture786f1792019-08-05 16:33:44 -0700467 std::cerr << "Illegal header at bus " << bus << " address "
468 << ii << "\n";
469 }
470 continue;
471 }
472
473 std::vector<char> device;
Patrick Venture4f47fe62019-08-08 16:30:38 -0700474 device.insert(device.end(), blockData.begin(),
475 blockData.begin() + 8);
Patrick Venture786f1792019-08-05 16:33:44 -0700476
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700477 int fruLength = 0;
Patrick Venture786f1792019-08-05 16:33:44 -0700478 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
479 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700480 // TODO: offset can be 255, device is holding "chars" that's not
481 // good.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700482 int areaOffset = device[jj];
483 if (areaOffset == 0)
Patrick Venture786f1792019-08-05 16:33:44 -0700484 {
Patrick Venture64fd7e22019-08-05 16:38:20 -0700485 continue;
486 }
487
Patrick Venture4f47fe62019-08-08 16:30:38 -0700488 areaOffset *= 8;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700489
Patrick Venture4f47fe62019-08-08 16:30:38 -0700490 if (readBlockData(flag, file, static_cast<uint16_t>(areaOffset),
491 0x2, blockData.data()) < 0)
Patrick Venture64fd7e22019-08-05 16:38:20 -0700492 {
493 std::cerr << "failed to read bus " << bus << " address "
494 << ii << "\n";
495 return -1;
496 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700497
498 // Ignore data type.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700499 int length = blockData[1] * 8;
500 areaOffset += length;
501 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700502 }
Patrick Venture64fd7e22019-08-05 16:38:20 -0700503
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700504 // You already copied these first 8 bytes (the ipmi fru header size)
505 fruLength -= 8;
506
507 int readOffset = 8;
508
509 while (fruLength > 0)
510 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700511 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700512
Patrick Venture4f47fe62019-08-08 16:30:38 -0700513 if (readBlockData(flag, file, static_cast<uint16_t>(readOffset),
514 static_cast<uint8_t>(requestLength),
515 blockData.data()) < 0)
Patrick Venture64fd7e22019-08-05 16:38:20 -0700516 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700517 std::cerr << "failed to read bus " << bus << " address "
518 << ii << "\n";
519 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800520 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700521
Patrick Venture4f47fe62019-08-08 16:30:38 -0700522 device.insert(device.end(), blockData.begin(),
523 blockData.begin() + requestLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700524
Patrick Venture4f47fe62019-08-08 16:30:38 -0700525 readOffset += requestLength;
526 fruLength -= requestLength;
James Feist3cb5fec2018-01-23 14:41:51 -0800527 }
Patrick Venture786f1792019-08-05 16:33:44 -0700528 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800529 }
James Feist26c27ad2018-07-25 15:09:40 -0700530 return 1;
531 });
532 std::future_status status =
533 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
534 if (status == std::future_status::timeout)
535 {
536 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700537 busBlacklist.insert(bus);
538 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700539 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800540 }
541
James Feist444830e2019-04-05 08:38:16 -0700542 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700543 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800544}
545
Patrick Venture11f1ff42019-08-01 10:42:12 -0700546void loadBlacklist(const char* path)
547{
548 std::ifstream blacklistStream(path);
549 if (!blacklistStream.good())
550 {
551 // File is optional.
552 std::cerr << "Cannot open blacklist file.\n\n";
553 return;
554 }
555
556 nlohmann::json data =
557 nlohmann::json::parse(blacklistStream, nullptr, false);
558 if (data.is_discarded())
559 {
560 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
561 "exiting\n";
562 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700563 }
564
565 // It's expected to have at least one field, "buses" that is an array of the
566 // buses by integer. Allow for future options to exclude further aspects,
567 // such as specific addresses or ranges.
568 if (data.type() != nlohmann::json::value_t::object)
569 {
570 std::cerr << "Illegal blacklist, expected to read dictionary\n";
571 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700572 }
573
574 // If buses field is missing, that's fine.
575 if (data.count("buses") == 1)
576 {
577 // Parse the buses array after a little validation.
578 auto buses = data.at("buses");
579 if (buses.type() != nlohmann::json::value_t::array)
580 {
581 // Buses field present but invalid, therefore this is an error.
582 std::cerr << "Invalid contents for blacklist buses field\n";
583 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700584 }
585
586 // Catch exception here for type mis-match.
587 try
588 {
589 for (const auto& bus : buses)
590 {
591 busBlacklist.insert(bus.get<size_t>());
592 }
593 }
594 catch (const nlohmann::detail::type_error& e)
595 {
596 // Type mis-match is a critical error.
597 std::cerr << "Invalid bus type: " << e.what() << "\n";
598 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700599 }
600 }
601
602 return;
603}
604
James Feista465ccc2019-02-08 12:51:01 -0800605static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700606 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800607{
James Feista465ccc2019-02-08 12:51:01 -0800608 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800609 {
610 auto busnum = i2cBus.string();
611 auto lastDash = busnum.rfind(std::string("-"));
612 // delete everything before dash inclusive
613 if (lastDash != std::string::npos)
614 {
615 busnum.erase(0, lastDash + 1);
616 }
617 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700618 if (busBlacklist.find(bus) != busBlacklist.end())
619 {
620 continue; // skip previously failed busses
621 }
James Feist3cb5fec2018-01-23 14:41:51 -0800622
623 auto file = open(i2cBus.c_str(), O_RDWR);
624 if (file < 0)
625 {
626 std::cerr << "unable to open i2c device " << i2cBus.string()
627 << "\n";
628 continue;
629 }
630 unsigned long funcs = 0;
631
632 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
633 {
634 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700635 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800636 << bus << "\n";
637 continue;
638 }
639 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
640 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
641 {
642 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
643 << bus << "\n";
644 continue;
645 }
James Feist98132792019-07-09 13:29:09 -0700646 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800647 device = std::make_shared<DeviceMap>();
648
Nikhil Potaded8884f12019-03-27 13:27:13 -0700649 // i2cdetect by default uses the range 0x03 to 0x77, as
650 // this is what we have tested with, use this range. Could be
651 // changed in future.
652 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800653 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700654 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800655 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700656
657 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700658 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700659
660 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800661 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700662 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800663 }
James Feist3cb5fec2018-01-23 14:41:51 -0800664 }
James Feist3cb5fec2018-01-23 14:41:51 -0800665}
666
James Feist6ebf9de2018-05-15 15:01:17 -0700667// this class allows an async response after all i2c devices are discovered
668struct FindDevicesWithCallback
669 : std::enable_shared_from_this<FindDevicesWithCallback>
670{
James Feista465ccc2019-02-08 12:51:01 -0800671 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700672 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800673 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700674 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700675 _busMap(busmap), _callback(std::move(callback))
James Feist6ebf9de2018-05-15 15:01:17 -0700676 {
677 }
678 ~FindDevicesWithCallback()
679 {
680 _callback();
681 }
682 void run()
683 {
James Feist98132792019-07-09 13:29:09 -0700684 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700685 }
686
James Feista465ccc2019-02-08 12:51:01 -0800687 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800688 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700689 std::function<void(void)> _callback;
690};
691
James Feist3cb5fec2018-01-23 14:41:51 -0800692static const std::tm intelEpoch(void)
693{
James Feist98132792019-07-09 13:29:09 -0700694 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800695 val.tm_year = 1996 - 1900;
696 return val;
697}
698
James Feista465ccc2019-02-08 12:51:01 -0800699bool formatFru(const std::vector<char>& fruBytes,
700 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800701{
James Feista465ccc2019-02-08 12:51:01 -0800702 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800703 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800704
James Feista465ccc2019-02-08 12:51:01 -0800705 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800706 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
707 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800708
James Feista465ccc2019-02-08 12:51:01 -0800709 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800710 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
711 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
712 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800713
James Feistd068e932018-09-20 10:53:07 -0700714 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800715 {
716 return false;
717 }
718 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700719 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800720 std::to_string(static_cast<int>(*fruAreaOffsetField));
721
James Feista465ccc2019-02-08 12:51:01 -0800722 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800723
James Feist0eb40352019-04-09 14:44:04 -0700724 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800725 {
726 fruAreaOffsetField++;
727 if (fruAreaOffsetField >= fruBytes.end())
728 {
729 return false;
730 }
731 size_t offset = (*fruAreaOffsetField) * 8;
732
733 if (offset > 1)
734 {
735 // +2 to skip format and length
736 std::vector<char>::const_iterator fruBytesIter =
737 fruBytes.begin() + offset + 2;
738
739 if (fruBytesIter >= fruBytes.end())
740 {
741 return false;
742 }
743
744 if (area == "CHASSIS")
745 {
746 result["CHASSIS_TYPE"] =
747 std::to_string(static_cast<int>(*fruBytesIter));
748 fruBytesIter += 1;
749 fieldData = &CHASSIS_FRU_AREAS;
750 }
751 else if (area == "BOARD")
752 {
753 result["BOARD_LANGUAGE_CODE"] =
754 std::to_string(static_cast<int>(*fruBytesIter));
755 fruBytesIter += 1;
756 if (fruBytesIter >= fruBytes.end())
757 {
758 return false;
759 }
760
761 unsigned int minutes = *fruBytesIter |
762 *(fruBytesIter + 1) << 8 |
763 *(fruBytesIter + 2) << 16;
764 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700765 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800766 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700767 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800768
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700769 // Tue Nov 20 23:08:00 2018
770 char timeString[32] = {0};
771 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700772 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700773 if (bytes == 0)
774 {
775 std::cerr << "invalid time string encountered\n";
776 return false;
777 }
778
779 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800780 fruBytesIter += 3;
781 fieldData = &BOARD_FRU_AREAS;
782 }
783 else if (area == "PRODUCT")
784 {
785 result["PRODUCT_LANGUAGE_CODE"] =
786 std::to_string(static_cast<int>(*fruBytesIter));
787 fruBytesIter += 1;
788 fieldData = &PRODUCT_FRU_AREAS;
789 }
790 else
791 {
792 continue;
793 }
James Feista465ccc2019-02-08 12:51:01 -0800794 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800795 {
796 if (fruBytesIter >= fruBytes.end())
797 {
798 return false;
799 }
800
Vijay Khemka5d5de442018-11-07 10:51:25 -0800801 /* Checking for last byte C1 to indicate that no more
802 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700803 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800804 {
805 break;
806 }
807
Ed Tanous2147e672019-02-27 13:59:56 -0800808 size_t length = *fruBytesIter & 0x3f;
809 fruBytesIter += 1;
810
James Feist3cb5fec2018-01-23 14:41:51 -0800811 if (fruBytesIter >= fruBytes.end())
812 {
813 return false;
814 }
Ed Tanous2147e672019-02-27 13:59:56 -0800815 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800816
Ed Tanous2147e672019-02-27 13:59:56 -0800817 // Strip non null characters from the end
818 value.erase(std::find_if(value.rbegin(), value.rend(),
819 [](char ch) { return ch != 0; })
820 .base(),
821 value.end());
822
James Feist0eb40352019-04-09 14:44:04 -0700823 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800824
James Feist3cb5fec2018-01-23 14:41:51 -0800825 fruBytesIter += length;
826 if (fruBytesIter >= fruBytes.end())
827 {
828 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800829 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800830 {
831 std::cerr << c;
832 }
833 std::cerr << "\n";
834 if (DEBUG)
835 {
James Feista465ccc2019-02-08 12:51:01 -0800836 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800837 {
838 std::cerr << keyPair.first << " : "
839 << keyPair.second << "\n";
840 }
841 }
842 return false;
843 }
844 }
845 }
846 }
847
848 return true;
849}
850
Nikhil Potaded8884f12019-03-27 13:27:13 -0700851std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
852{
853 auto deviceMap = busMap.find(bus);
854 if (deviceMap == busMap.end())
855 {
856 throw std::invalid_argument("Invalid Bus.");
857 }
858 auto device = deviceMap->second->find(address);
859 if (device == deviceMap->second->end())
860 {
861 throw std::invalid_argument("Invalid Address.");
862 }
863 std::vector<uint8_t>& ret =
864 reinterpret_cast<std::vector<uint8_t>&>(device->second);
865
866 return ret;
867}
868
James Feist3cb5fec2018-01-23 14:41:51 -0800869void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700870 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800871 boost::container::flat_map<
872 std::pair<size_t, size_t>,
873 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700874 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800875{
876 boost::container::flat_map<std::string, std::string> formattedFru;
877 if (!formatFru(device, formattedFru))
878 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700879 std::cerr << "failed to format fru for device at bus " << bus
880 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800881 return;
882 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700883
James Feist3cb5fec2018-01-23 14:41:51 -0800884 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
885 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700886 // Not found under Board section or an empty string.
887 if (productNameFind == formattedFru.end() ||
888 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800889 {
890 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
891 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700892 // Found under Product section and not an empty string.
893 if (productNameFind != formattedFru.end() &&
894 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800895 {
896 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800897 std::regex illegalObject("[^A-Za-z0-9_]");
898 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800899 }
900 else
901 {
902 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
903 UNKNOWN_BUS_OBJECT_COUNT++;
904 }
905
James Feist918e18c2018-02-13 15:51:07 -0800906 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800907 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700908 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800909 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700910 int highest = -1;
911 bool found = false;
912
James Feista465ccc2019-02-08 12:51:01 -0800913 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800914 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700915 std::string path = busIface.second->get_object_path();
916 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800917 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700918 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -0700919 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
920 static_cast<uint8_t>(busIface.first.second)) ==
921 getFruInfo(static_cast<uint8_t>(bus),
922 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -0700923 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700924 // This device is already added to the lower numbered bus,
925 // do not replicate it.
926 return;
James Feist79e9c0b2018-03-15 15:21:17 -0700927 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700928
929 // Check if the match named has extra information.
930 found = true;
931 std::smatch base_match;
932
933 bool match = std::regex_match(
934 path, base_match, std::regex(productName + "_(\\d+)$"));
935 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -0700936 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700937 if (base_match.size() == 2)
938 {
939 std::ssub_match base_sub_match = base_match[1];
940 std::string base = base_sub_match.str();
941
942 int value = std::stoi(base);
943 highest = (value > highest) ? value : highest;
944 }
James Feist79e9c0b2018-03-15 15:21:17 -0700945 }
James Feist918e18c2018-02-13 15:51:07 -0800946 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700947 } // end searching objects
948
949 if (found)
950 {
951 // We found something with the same name. If highest was still -1,
952 // it means this new entry will be _0.
953 productName += "_";
954 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -0800955 }
956 }
James Feist3cb5fec2018-01-23 14:41:51 -0800957
James Feist9eb0b582018-04-27 12:15:46 -0700958 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
959 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
960 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
961
James Feista465ccc2019-02-08 12:51:01 -0800962 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800963 {
James Feist9eb0b582018-04-27 12:15:46 -0700964
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700965 std::regex_replace(property.second.begin(), property.second.begin(),
966 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700967 if (property.second.empty())
968 {
969 continue;
970 }
971 std::string key =
972 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
973 if (!iface->register_property(key, property.second + '\0'))
974 {
975 std::cerr << "illegal key: " << key << "\n";
976 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700977 if (DEBUG)
978 {
979 std::cout << property.first << ": " << property.second << "\n";
980 }
James Feist3cb5fec2018-01-23 14:41:51 -0800981 }
James Feist2a9d6db2018-04-27 15:48:28 -0700982
983 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700984 iface->register_property("BUS", bus);
985 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700986
James Feist9eb0b582018-04-27 12:15:46 -0700987 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800988}
989
James Feista465ccc2019-02-08 12:51:01 -0800990static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800991{
992 // try to read baseboard fru from file
993 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
994 if (baseboardFruFile.good())
995 {
996 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -0700997 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -0800998 baseboardFru.resize(fileSize);
999 baseboardFruFile.seekg(0, std::ios_base::beg);
1000 baseboardFruFile.read(baseboardFru.data(), fileSize);
1001 }
1002 else
1003 {
1004 return false;
1005 }
1006 return true;
1007}
1008
James Feista465ccc2019-02-08 12:51:01 -08001009bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001010{
1011 boost::container::flat_map<std::string, std::string> tmp;
1012 if (fru.size() > MAX_FRU_SIZE)
1013 {
1014 std::cerr << "Invalid fru.size() during writeFru\n";
1015 return false;
1016 }
1017 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001018 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001019 {
1020 std::cerr << "Invalid fru format during writeFru\n";
1021 return false;
1022 }
1023 // baseboard fru
1024 if (bus == 0 && address == 0)
1025 {
1026 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1027 if (!file.good())
1028 {
1029 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1030 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001031 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001032 return false;
1033 }
James Feista465ccc2019-02-08 12:51:01 -08001034 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001035 return file.good();
1036 }
1037 else
1038 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001039 if (hasEepromFile(bus, address))
1040 {
1041 auto path = getEepromPath(bus, address);
1042 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1043 if (eeprom < 0)
1044 {
1045 std::cerr << "unable to open i2c device " << path << "\n";
1046 throw DBusInternalError();
1047 return false;
1048 }
1049
1050 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1051 if (writtenBytes < 0)
1052 {
1053 std::cerr << "unable to write to i2c device " << path << "\n";
1054 close(eeprom);
1055 throw DBusInternalError();
1056 return false;
1057 }
1058
1059 close(eeprom);
1060 return true;
1061 }
1062
James Feistb49ffc32018-05-02 11:10:43 -07001063 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1064
1065 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1066 if (file < 0)
1067 {
1068 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001069 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001070 return false;
1071 }
1072 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1073 {
1074 std::cerr << "unable to set device address\n";
1075 close(file);
James Feistddb78302018-09-06 11:45:42 -07001076 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001077 return false;
1078 }
1079
1080 constexpr const size_t RETRY_MAX = 2;
1081 uint16_t index = 0;
1082 size_t retries = RETRY_MAX;
1083 while (index < fru.size())
1084 {
1085 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1086 (retries == RETRY_MAX))
1087 {
1088 // The 4K EEPROM only uses the A2 and A1 device address bits
1089 // with the third bit being a memory page address bit.
1090 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1091 {
1092 std::cerr << "unable to set device address\n";
1093 close(file);
James Feistddb78302018-09-06 11:45:42 -07001094 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001095 return false;
1096 }
1097 }
1098
James Feist98132792019-07-09 13:29:09 -07001099 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1100 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001101 {
1102 if (!retries--)
1103 {
1104 std::cerr << "error writing fru: " << strerror(errno)
1105 << "\n";
1106 close(file);
James Feistddb78302018-09-06 11:45:42 -07001107 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001108 return false;
1109 }
1110 }
1111 else
1112 {
1113 retries = RETRY_MAX;
1114 index++;
1115 }
1116 // most eeproms require 5-10ms between writes
1117 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1118 }
1119 close(file);
1120 return true;
1121 }
1122}
1123
James Feist9eb0b582018-04-27 12:15:46 -07001124void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001125 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001126 boost::container::flat_map<
1127 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001128 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001129{
James Feist6ebf9de2018-05-15 15:01:17 -07001130 static boost::asio::deadline_timer timer(io);
1131 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001132
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001133 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001134 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001135 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001136 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001137
Nikhil Potaded8884f12019-03-27 13:27:13 -07001138 boost::container::flat_map<size_t, fs::path> busPaths;
1139 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001140 {
James Feist4131aea2018-03-09 09:47:30 -08001141 std::cerr << "unable to find i2c devices\n";
1142 return;
James Feist918e18c2018-02-13 15:51:07 -08001143 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001144
1145 for (auto busPath : busPaths)
1146 {
1147 i2cBuses.emplace_back(busPath.second);
1148 }
James Feist4131aea2018-03-09 09:47:30 -08001149
James Feist98132792019-07-09 13:29:09 -07001150 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001151 for (auto& [pair, interface] : foundDevices)
1152 {
1153 objServer.remove_interface(interface);
1154 }
1155 foundDevices.clear();
1156
James Feist5cb06082019-10-24 17:11:13 -07001157 auto scan =
1158 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001159 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001160 {
1161 objServer.remove_interface(busIface.second);
1162 }
James Feist4131aea2018-03-09 09:47:30 -08001163
James Feist6ebf9de2018-05-15 15:01:17 -07001164 dbusInterfaceMap.clear();
1165 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001166
James Feist6ebf9de2018-05-15 15:01:17 -07001167 // todo, get this from a more sensable place
1168 std::vector<char> baseboardFru;
1169 if (readBaseboardFru(baseboardFru))
1170 {
1171 boost::container::flat_map<int, std::vector<char>>
1172 baseboardDev;
1173 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001174 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001175 }
James Feist98132792019-07-09 13:29:09 -07001176 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001177 {
James Feista465ccc2019-02-08 12:51:01 -08001178 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001179 {
James Feist5cb06082019-10-24 17:11:13 -07001180 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1181 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001182 }
1183 }
1184 });
1185 scan->run();
1186 });
James Feist918e18c2018-02-13 15:51:07 -08001187}
1188
James Feist98132792019-07-09 13:29:09 -07001189int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001190{
1191 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001192 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001193 std::vector<fs::path> i2cBuses;
1194
James Feista3c180a2018-08-09 16:06:04 -07001195 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001196 {
1197 std::cerr << "unable to find i2c devices\n";
1198 return 1;
1199 }
James Feist3cb5fec2018-01-23 14:41:51 -08001200
Patrick Venture11f1ff42019-08-01 10:42:12 -07001201 // check for and load blacklist with initial buses.
1202 loadBlacklist(blacklistPath);
1203
Vijay Khemka065f6d92018-12-18 10:37:47 -08001204 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001205
James Feist6ebf9de2018-05-15 15:01:17 -07001206 // this is a map with keys of pair(bus number, address) and values of
1207 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001208 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001209 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1210 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001211
James Feist9eb0b582018-04-27 12:15:46 -07001212 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1213 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1214 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001215
James Feist5cb06082019-10-24 17:11:13 -07001216 iface->register_method("ReScan",
1217 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001218
Nikhil Potaded8884f12019-03-27 13:27:13 -07001219 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001220
1221 iface->register_method("WriteFru", [&](const uint8_t bus,
1222 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001223 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001224 if (!writeFru(bus, address, data))
1225 {
James Feistddb78302018-09-06 11:45:42 -07001226 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001227 return;
1228 }
1229 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001230 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001231 });
James Feist9eb0b582018-04-27 12:15:46 -07001232 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001233
James Feist9eb0b582018-04-27 12:15:46 -07001234 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001235 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001236 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001237 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001238 std::string,
1239 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001240 values;
1241 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001242 auto findState = values.find("CurrentHostState");
1243 bool on = false;
1244 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001245 {
James Feist0eeb79c2019-10-09 13:35:29 -07001246 on = boost::ends_with(std::get<std::string>(findState->second),
1247 "Running");
1248 }
James Feist6ebf9de2018-05-15 15:01:17 -07001249
James Feist0eeb79c2019-10-09 13:35:29 -07001250 if (on)
1251 {
James Feist5cb06082019-10-24 17:11:13 -07001252 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001253 }
James Feist918e18c2018-02-13 15:51:07 -08001254 };
James Feist9eb0b582018-04-27 12:15:46 -07001255
1256 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001257 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001258 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001259 "openbmc_project/state/"
1260 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001261 eventHandler);
1262
James Feist4131aea2018-03-09 09:47:30 -08001263 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001264 inotify_add_watch(fd, I2C_DEV_LOCATION,
1265 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001266 std::array<char, 4096> readBuffer;
1267 std::string pendingBuffer;
1268 // monitor for new i2c devices
1269 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1270 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001271 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001272 std::size_t bytes_transferred) {
1273 if (ec)
1274 {
1275 std::cout << "Callback Error " << ec << "\n";
1276 return;
1277 }
1278 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1279 bool devChange = false;
1280 while (pendingBuffer.size() > sizeof(inotify_event))
1281 {
James Feista465ccc2019-02-08 12:51:01 -08001282 const inotify_event* iEvent =
1283 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001284 pendingBuffer.data());
1285 switch (iEvent->mask)
1286 {
James Feist9eb0b582018-04-27 12:15:46 -07001287 case IN_CREATE:
1288 case IN_MOVED_TO:
1289 case IN_DELETE:
1290 if (boost::starts_with(std::string(iEvent->name),
1291 "i2c"))
1292 {
1293 devChange = true;
1294 }
James Feist4131aea2018-03-09 09:47:30 -08001295 }
1296
1297 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1298 }
James Feist6ebf9de2018-05-15 15:01:17 -07001299 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001300 {
James Feist5cb06082019-10-24 17:11:13 -07001301 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001302 }
James Feist6ebf9de2018-05-15 15:01:17 -07001303
James Feist4131aea2018-03-09 09:47:30 -08001304 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1305 watchI2cBusses);
1306 };
1307
1308 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001309 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001310 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001311
James Feist3cb5fec2018-01-23 14:41:51 -08001312 io.run();
1313 return 0;
1314}