blob: 8c33a3a1a7d0597cfaa00f91fd61329b40d7bdc6 [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
James Feist3b860982018-10-02 14:34:07 -070017#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080018#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070019#include <sys/inotify.h>
20#include <sys/ioctl.h>
21
22#include <Utils.hpp>
23#include <boost/algorithm/string/predicate.hpp>
24#include <boost/container/flat_map.hpp>
25#include <chrono>
26#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070027#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080028#include <fstream>
29#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070030#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080031#include <iostream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070032#include <nlohmann/json.hpp>
James Feist3f8a2782018-02-12 09:24:42 -080033#include <regex>
James Feist3b860982018-10-02 14:34:07 -070034#include <sdbusplus/asio/connection.hpp>
35#include <sdbusplus/asio/object_server.hpp>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070036#include <set>
37#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070038#include <string>
James Feist3b860982018-10-02 14:34:07 -070039#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080040#include <variant>
James Feist3b860982018-10-02 14:34:07 -070041
42extern "C" {
43#include <i2c/smbus.h>
44#include <linux/i2c-dev.h>
45}
James Feist3cb5fec2018-01-23 14:41:51 -080046
Ed Tanous072e25d2018-12-16 21:45:20 -080047namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080048static constexpr bool DEBUG = false;
49static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070050constexpr size_t MAX_FRU_SIZE = 512;
51constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070052constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080053
Patrick Venture11f1ff42019-08-01 10:42:12 -070054constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
55
James Feista465ccc2019-02-08 12:51:01 -080056const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080057 "/etc/fru/baseboard.fru.bin";
58
James Feista465ccc2019-02-08 12:51:01 -080059const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080060
James Feista465ccc2019-02-08 12:51:01 -080061static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080062 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070063const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080064using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
65using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
66
James Feist444830e2019-04-05 08:38:16 -070067static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070068struct FindDevicesWithCallback;
69
Nikhil Potaded8884f12019-03-27 13:27:13 -070070static BusMap busMap;
71
James Feist8a983922019-10-24 17:11:56 -070072static boost::container::flat_map<
73 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
74 foundDevices;
75
James Feist5cb06082019-10-24 17:11:13 -070076boost::asio::io_service io;
77auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
78auto objServer = sdbusplus::asio::object_server(systemBus);
79
Patrick Venturec50e1ff2019-08-06 10:22:28 -070080// Given a bus/address, produce the path in sysfs for an eeprom.
81static std::string getEepromPath(size_t bus, size_t address)
82{
83 std::stringstream output;
84 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
85 << std::setfill('0') << std::setw(4) << std::hex << address
86 << "/eeprom";
87 return output.str();
88}
89
90static bool hasEepromFile(size_t bus, size_t address)
91{
92 auto path = getEepromPath(bus, address);
93 try
94 {
95 return fs::exists(path);
96 }
97 catch (...)
98 {
99 return false;
100 }
101}
102
103static ssize_t readFromEeprom(int fd, uint16_t offset, uint8_t len,
104 uint8_t* buf)
105{
106 auto result = lseek(fd, offset, SEEK_SET);
107 if (result < 0)
108 {
109 std::cerr << "failed to seek\n";
110 return -1;
111 }
112
113 return read(fd, buf, len);
114}
115
James Feistc95cb142018-02-26 10:41:42 -0800116static bool isMuxBus(size_t bus)
117{
Ed Tanous072e25d2018-12-16 21:45:20 -0800118 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800119 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
120}
121
James Feist8a983922019-10-24 17:11:56 -0700122static void makeProbeInterface(size_t bus, size_t address)
123{
124 if (isMuxBus(bus))
125 {
126 return; // the mux buses are random, no need to publish
127 }
128 auto [it, success] = foundDevices.emplace(
129 std::make_pair(bus, address),
130 objServer.add_interface(
131 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
132 std::to_string(address),
133 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
134 if (!success)
135 {
136 return; // already added
137 }
138 it->second->register_property("Bus", bus);
139 it->second->register_property("Address", address);
140 it->second->initialize();
141}
142
Vijay Khemka2d681f62018-11-06 15:51:00 -0800143static int isDevice16Bit(int file)
144{
145 /* Get first byte */
146 int byte1 = i2c_smbus_read_byte_data(file, 0);
147 if (byte1 < 0)
148 {
149 return byte1;
150 }
151 /* Read 7 more bytes, it will read same first byte in case of
152 * 8 bit but it will read next byte in case of 16 bit
153 */
154 for (int i = 0; i < 7; i++)
155 {
156 int byte2 = i2c_smbus_read_byte_data(file, 0);
157 if (byte2 < 0)
158 {
159 return byte2;
160 }
161 if (byte2 != byte1)
162 {
163 return 1;
164 }
165 }
166 return 0;
167}
168
Patrick Venture4f47fe62019-08-08 16:30:38 -0700169static int readBlockData(int flag, int file, uint16_t offset, uint8_t len,
170 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800171{
Patrick Venture4f47fe62019-08-08 16:30:38 -0700172 uint8_t lowAddr = static_cast<uint8_t>(offset);
173 uint8_t highAddr = static_cast<uint8_t>(offset >> 8);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800174
175 if (flag == 0)
176 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700177 return i2c_smbus_read_i2c_block_data(file, lowAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800178 }
179
180 /* This is for 16 bit addressing EEPROM device. First an offset
181 * needs to be written before read data from a offset
182 */
Patrick Venture4f47fe62019-08-08 16:30:38 -0700183 int ret = i2c_smbus_write_byte_data(file, 0, lowAddr);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800184 if (ret < 0)
185 {
186 return ret;
187 }
188
Patrick Venture4f47fe62019-08-08 16:30:38 -0700189 return i2c_smbus_read_i2c_block_data(file, highAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800190}
191
James Feist24bae7a2019-04-03 09:50:56 -0700192bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
193{
194 // ipmi spec format version number is currently at 1, verify it
195 if (blockData[0] != 0x1)
196 {
197 return false;
198 }
199
200 // verify pad is set to 0
201 if (blockData[6] != 0x0)
202 {
203 return false;
204 }
205
206 // verify offsets are 0, or don't point to another offset
207 std::set<uint8_t> foundOffsets;
208 for (int ii = 1; ii < 6; ii++)
209 {
210 if (blockData[ii] == 0)
211 {
212 continue;
213 }
James Feist0eb40352019-04-09 14:44:04 -0700214 auto inserted = foundOffsets.insert(blockData[ii]);
215 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700216 {
217 return false;
218 }
219 }
220
221 // validate checksum
222 size_t sum = 0;
223 for (int jj = 0; jj < 7; jj++)
224 {
225 sum += blockData[jj];
226 }
227 sum = (256 - sum) & 0xFF;
228
229 if (sum != blockData[7])
230 {
231 return false;
232 }
233 return true;
234}
235
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700236// TODO: This code is very similar to the non-eeprom version and can be merged
237// with some tweaks.
238static std::vector<char> processEeprom(int bus, int address)
239{
240 std::vector<char> device;
Patrick Venture4f47fe62019-08-08 16:30:38 -0700241 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700242
243 auto path = getEepromPath(bus, address);
244
245 int file = open(path.c_str(), O_RDONLY);
246 if (file < 0)
247 {
248 std::cerr << "Unable to open eeprom file: " << path << "\n";
249 return device;
250 }
251
Patrick Venture4f47fe62019-08-08 16:30:38 -0700252 ssize_t readBytes = readFromEeprom(file, 0, 0x8, blockData.data());
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700253 if (readBytes < 0)
254 {
255 std::cerr << "failed to read eeprom at " << bus << " address "
256 << address << "\n";
257 close(file);
258 return device;
259 }
260
Patrick Venture4f47fe62019-08-08 16:30:38 -0700261 if (!validateHeader(blockData))
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700262 {
263 if (DEBUG)
264 {
265 std::cerr << "Illegal header at bus " << bus << " address "
266 << address << "\n";
267 }
268
269 close(file);
270 return device;
271 }
272
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700273 // Copy the IPMI Fru Header
Patrick Venture4f47fe62019-08-08 16:30:38 -0700274 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700275
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700276 int fruLength = 0;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700277 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
278 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700279 // TODO: offset can be 255, device is holding "chars" that's not good.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700280 int areaOffset = device[jj];
281 if (areaOffset == 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700282 {
283 continue;
284 }
285
Patrick Venture4f47fe62019-08-08 16:30:38 -0700286 areaOffset *= 8;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700287
Patrick Venture4f47fe62019-08-08 16:30:38 -0700288 if (readFromEeprom(file, static_cast<uint16_t>(areaOffset), 0x2,
289 blockData.data()) < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700290 {
291 std::cerr << "failed to read bus " << bus << " address " << address
292 << "\n";
293 device.clear();
294 close(file);
295 return device;
296 }
297
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700298 // Ignore data type.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700299 int length = blockData[1] * 8;
300 areaOffset += length;
301 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700302 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700303
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700304 // You already copied these first 8 bytes (the ipmi fru header size)
305 fruLength -= 8;
306
307 int readOffset = 8;
308
309 while (fruLength > 0)
310 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700311 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700312
313 if (readFromEeprom(file, static_cast<uint16_t>(readOffset),
Patrick Venture4f47fe62019-08-08 16:30:38 -0700314 static_cast<uint8_t>(requestLength),
315 blockData.data()) < 0)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700316 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700317 std::cerr << "failed to read bus " << bus << " address " << address
318 << "\n";
319 device.clear();
320 close(file);
321 return device;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700322 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700323
Patrick Venture4f47fe62019-08-08 16:30:38 -0700324 device.insert(device.end(), blockData.begin(),
325 blockData.begin() + requestLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700326
Patrick Venture4f47fe62019-08-08 16:30:38 -0700327 readOffset += requestLength;
328 fruLength -= requestLength;
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700329 }
330
331 close(file);
332 return device;
333}
334
335std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
336{
337 std::set<int> foundList;
338
339 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
340
341 // For each file listed under the i2c device
342 // NOTE: This should be faster than just checking for each possible address
343 // path.
344 for (const auto& p : fs::directory_iterator(path))
345 {
346 const std::string node = p.path().string();
347 std::smatch m;
348 bool found =
349 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
350
351 if (!found)
352 {
353 continue;
354 }
355 if (m.size() != 2)
356 {
357 std::cerr << "regex didn't capture\n";
358 continue;
359 }
360
361 std::ssub_match subMatch = m[1];
362 std::string addressString = subMatch.str();
363
364 std::size_t ignored;
365 const int hexBase = 16;
366 int address = std::stoi(addressString, &ignored, hexBase);
367
368 const std::string eeprom = node + "/eeprom";
369
370 try
371 {
372 if (!fs::exists(eeprom))
373 {
374 continue;
375 }
376 }
377 catch (...)
378 {
379 continue;
380 }
381
382 // There is an eeprom file at this address, it may have invalid
383 // contents, but we found it.
384 foundList.insert(address);
385
386 std::vector<char> device = processEeprom(i2cBus, address);
387 if (!device.empty())
388 {
389 devices->emplace(address, device);
390 }
391 }
392
393 return foundList;
394}
395
Patrick Venture4f47fe62019-08-08 16:30:38 -0700396int getBusFrus(int file, int first, int last, int bus,
397 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800398{
James Feist3cb5fec2018-01-23 14:41:51 -0800399
James Feist26c27ad2018-07-25 15:09:40 -0700400 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700401 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800402
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700403 // NOTE: When reading the devices raw on the bus, it can interfere with
404 // the driver's ability to operate, therefore read eeproms first before
405 // scanning for devices without drivers. Several experiments were run
406 // and it was determined that if there were any devices on the bus
407 // before the eeprom was hit and read, the eeprom driver wouldn't open
408 // while the bus device was open. An experiment was not performed to see
409 // if this issue was resolved if the i2c bus device was closed, but
410 // hexdumps of the eeprom later were successful.
411
412 // Scan for i2c eeproms loaded on this bus.
413 std::set<int> skipList = findI2CEeproms(bus, devices);
414
James Feist26c27ad2018-07-25 15:09:40 -0700415 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800416 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700417 if (skipList.find(ii) != skipList.end())
418 {
419 continue;
420 }
James Feist3cb5fec2018-01-23 14:41:51 -0800421
James Feist26c27ad2018-07-25 15:09:40 -0700422 // Set slave address
423 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800424 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700425 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700426 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700427 continue;
428 }
429 // probe
430 else if (i2c_smbus_read_byte(file) < 0)
431 {
432 continue;
433 }
James Feist3cb5fec2018-01-23 14:41:51 -0800434
James Feist26c27ad2018-07-25 15:09:40 -0700435 if (DEBUG)
436 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700437 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700438 << "\n";
439 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800440
James Feist8a983922019-10-24 17:11:56 -0700441 makeProbeInterface(bus, ii);
442
Vijay Khemka2d681f62018-11-06 15:51:00 -0800443 /* Check for Device type if it is 8 bit or 16 bit */
444 int flag = isDevice16Bit(file);
445 if (flag < 0)
446 {
447 std::cerr << "failed to read bus " << bus << " address " << ii
448 << "\n";
449 continue;
450 }
451
Patrick Venture4f47fe62019-08-08 16:30:38 -0700452 if (readBlockData(flag, file, 0x0, 0x8, blockData.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700453 {
454 std::cerr << "failed to read bus " << bus << " address " << ii
455 << "\n";
456 continue;
457 }
James Feist26c27ad2018-07-25 15:09:40 -0700458
459 // check the header checksum
Patrick Venture4f47fe62019-08-08 16:30:38 -0700460 if (!validateHeader(blockData))
James Feist26c27ad2018-07-25 15:09:40 -0700461 {
Patrick Venture786f1792019-08-05 16:33:44 -0700462 if (DEBUG)
James Feist26c27ad2018-07-25 15:09:40 -0700463 {
Patrick Venture786f1792019-08-05 16:33:44 -0700464 std::cerr << "Illegal header at bus " << bus << " address "
465 << ii << "\n";
466 }
467 continue;
468 }
469
470 std::vector<char> device;
Patrick Venture4f47fe62019-08-08 16:30:38 -0700471 device.insert(device.end(), blockData.begin(),
472 blockData.begin() + 8);
Patrick Venture786f1792019-08-05 16:33:44 -0700473
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700474 int fruLength = 0;
Patrick Venture786f1792019-08-05 16:33:44 -0700475 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
476 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700477 // TODO: offset can be 255, device is holding "chars" that's not
478 // good.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700479 int areaOffset = device[jj];
480 if (areaOffset == 0)
Patrick Venture786f1792019-08-05 16:33:44 -0700481 {
Patrick Venture64fd7e22019-08-05 16:38:20 -0700482 continue;
483 }
484
Patrick Venture4f47fe62019-08-08 16:30:38 -0700485 areaOffset *= 8;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700486
Patrick Venture4f47fe62019-08-08 16:30:38 -0700487 if (readBlockData(flag, file, static_cast<uint16_t>(areaOffset),
488 0x2, blockData.data()) < 0)
Patrick Venture64fd7e22019-08-05 16:38:20 -0700489 {
490 std::cerr << "failed to read bus " << bus << " address "
491 << ii << "\n";
492 return -1;
493 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700494
495 // Ignore data type.
Patrick Venture4f47fe62019-08-08 16:30:38 -0700496 int length = blockData[1] * 8;
497 areaOffset += length;
498 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700499 }
Patrick Venture64fd7e22019-08-05 16:38:20 -0700500
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700501 // You already copied these first 8 bytes (the ipmi fru header size)
502 fruLength -= 8;
503
504 int readOffset = 8;
505
506 while (fruLength > 0)
507 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700508 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700509
Patrick Venture4f47fe62019-08-08 16:30:38 -0700510 if (readBlockData(flag, file, static_cast<uint16_t>(readOffset),
511 static_cast<uint8_t>(requestLength),
512 blockData.data()) < 0)
Patrick Venture64fd7e22019-08-05 16:38:20 -0700513 {
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700514 std::cerr << "failed to read bus " << bus << " address "
515 << ii << "\n";
516 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800517 }
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700518
Patrick Venture4f47fe62019-08-08 16:30:38 -0700519 device.insert(device.end(), blockData.begin(),
520 blockData.begin() + requestLength);
Patrick Venture4cc29fc2019-08-08 13:36:18 -0700521
Patrick Venture4f47fe62019-08-08 16:30:38 -0700522 readOffset += requestLength;
523 fruLength -= requestLength;
James Feist3cb5fec2018-01-23 14:41:51 -0800524 }
Patrick Venture786f1792019-08-05 16:33:44 -0700525 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800526 }
James Feist26c27ad2018-07-25 15:09:40 -0700527 return 1;
528 });
529 std::future_status status =
530 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
531 if (status == std::future_status::timeout)
532 {
533 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700534 busBlacklist.insert(bus);
535 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700536 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800537 }
538
James Feist444830e2019-04-05 08:38:16 -0700539 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700540 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800541}
542
Patrick Venture11f1ff42019-08-01 10:42:12 -0700543void loadBlacklist(const char* path)
544{
545 std::ifstream blacklistStream(path);
546 if (!blacklistStream.good())
547 {
548 // File is optional.
549 std::cerr << "Cannot open blacklist file.\n\n";
550 return;
551 }
552
553 nlohmann::json data =
554 nlohmann::json::parse(blacklistStream, nullptr, false);
555 if (data.is_discarded())
556 {
557 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
558 "exiting\n";
559 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700560 }
561
562 // It's expected to have at least one field, "buses" that is an array of the
563 // buses by integer. Allow for future options to exclude further aspects,
564 // such as specific addresses or ranges.
565 if (data.type() != nlohmann::json::value_t::object)
566 {
567 std::cerr << "Illegal blacklist, expected to read dictionary\n";
568 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700569 }
570
571 // If buses field is missing, that's fine.
572 if (data.count("buses") == 1)
573 {
574 // Parse the buses array after a little validation.
575 auto buses = data.at("buses");
576 if (buses.type() != nlohmann::json::value_t::array)
577 {
578 // Buses field present but invalid, therefore this is an error.
579 std::cerr << "Invalid contents for blacklist buses field\n";
580 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700581 }
582
583 // Catch exception here for type mis-match.
584 try
585 {
586 for (const auto& bus : buses)
587 {
588 busBlacklist.insert(bus.get<size_t>());
589 }
590 }
591 catch (const nlohmann::detail::type_error& e)
592 {
593 // Type mis-match is a critical error.
594 std::cerr << "Invalid bus type: " << e.what() << "\n";
595 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700596 }
597 }
598
599 return;
600}
601
James Feista465ccc2019-02-08 12:51:01 -0800602static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700603 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800604{
James Feista465ccc2019-02-08 12:51:01 -0800605 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800606 {
607 auto busnum = i2cBus.string();
608 auto lastDash = busnum.rfind(std::string("-"));
609 // delete everything before dash inclusive
610 if (lastDash != std::string::npos)
611 {
612 busnum.erase(0, lastDash + 1);
613 }
614 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700615 if (busBlacklist.find(bus) != busBlacklist.end())
616 {
617 continue; // skip previously failed busses
618 }
James Feist3cb5fec2018-01-23 14:41:51 -0800619
620 auto file = open(i2cBus.c_str(), O_RDWR);
621 if (file < 0)
622 {
623 std::cerr << "unable to open i2c device " << i2cBus.string()
624 << "\n";
625 continue;
626 }
627 unsigned long funcs = 0;
628
629 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
630 {
631 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700632 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800633 << bus << "\n";
634 continue;
635 }
636 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
637 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
638 {
639 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
640 << bus << "\n";
641 continue;
642 }
James Feist98132792019-07-09 13:29:09 -0700643 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800644 device = std::make_shared<DeviceMap>();
645
Nikhil Potaded8884f12019-03-27 13:27:13 -0700646 // i2cdetect by default uses the range 0x03 to 0x77, as
647 // this is what we have tested with, use this range. Could be
648 // changed in future.
649 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800650 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700651 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800652 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700653
654 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700655 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700656
657 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800658 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700659 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800660 }
James Feist3cb5fec2018-01-23 14:41:51 -0800661 }
James Feist3cb5fec2018-01-23 14:41:51 -0800662}
663
James Feist6ebf9de2018-05-15 15:01:17 -0700664// this class allows an async response after all i2c devices are discovered
665struct FindDevicesWithCallback
666 : std::enable_shared_from_this<FindDevicesWithCallback>
667{
James Feista465ccc2019-02-08 12:51:01 -0800668 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700669 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800670 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700671 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700672 _busMap(busmap), _callback(std::move(callback))
James Feist6ebf9de2018-05-15 15:01:17 -0700673 {
674 }
675 ~FindDevicesWithCallback()
676 {
677 _callback();
678 }
679 void run()
680 {
James Feist98132792019-07-09 13:29:09 -0700681 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700682 }
683
James Feista465ccc2019-02-08 12:51:01 -0800684 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800685 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700686 std::function<void(void)> _callback;
687};
688
James Feist3cb5fec2018-01-23 14:41:51 -0800689static const std::tm intelEpoch(void)
690{
James Feist98132792019-07-09 13:29:09 -0700691 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800692 val.tm_year = 1996 - 1900;
693 return val;
694}
695
James Feista465ccc2019-02-08 12:51:01 -0800696bool formatFru(const std::vector<char>& fruBytes,
697 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800698{
James Feista465ccc2019-02-08 12:51:01 -0800699 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800700 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800701
James Feista465ccc2019-02-08 12:51:01 -0800702 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800703 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
704 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800705
James Feista465ccc2019-02-08 12:51:01 -0800706 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800707 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
708 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
709 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800710
James Feistd068e932018-09-20 10:53:07 -0700711 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800712 {
713 return false;
714 }
715 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700716 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800717 std::to_string(static_cast<int>(*fruAreaOffsetField));
718
James Feista465ccc2019-02-08 12:51:01 -0800719 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800720
James Feist0eb40352019-04-09 14:44:04 -0700721 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800722 {
723 fruAreaOffsetField++;
724 if (fruAreaOffsetField >= fruBytes.end())
725 {
726 return false;
727 }
728 size_t offset = (*fruAreaOffsetField) * 8;
729
730 if (offset > 1)
731 {
732 // +2 to skip format and length
733 std::vector<char>::const_iterator fruBytesIter =
734 fruBytes.begin() + offset + 2;
735
736 if (fruBytesIter >= fruBytes.end())
737 {
738 return false;
739 }
740
741 if (area == "CHASSIS")
742 {
743 result["CHASSIS_TYPE"] =
744 std::to_string(static_cast<int>(*fruBytesIter));
745 fruBytesIter += 1;
746 fieldData = &CHASSIS_FRU_AREAS;
747 }
748 else if (area == "BOARD")
749 {
750 result["BOARD_LANGUAGE_CODE"] =
751 std::to_string(static_cast<int>(*fruBytesIter));
752 fruBytesIter += 1;
753 if (fruBytesIter >= fruBytes.end())
754 {
755 return false;
756 }
757
758 unsigned int minutes = *fruBytesIter |
759 *(fruBytesIter + 1) << 8 |
760 *(fruBytesIter + 2) << 16;
761 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700762 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800763 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700764 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800765
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700766 // Tue Nov 20 23:08:00 2018
767 char timeString[32] = {0};
768 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700769 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700770 if (bytes == 0)
771 {
772 std::cerr << "invalid time string encountered\n";
773 return false;
774 }
775
776 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800777 fruBytesIter += 3;
778 fieldData = &BOARD_FRU_AREAS;
779 }
780 else if (area == "PRODUCT")
781 {
782 result["PRODUCT_LANGUAGE_CODE"] =
783 std::to_string(static_cast<int>(*fruBytesIter));
784 fruBytesIter += 1;
785 fieldData = &PRODUCT_FRU_AREAS;
786 }
787 else
788 {
789 continue;
790 }
James Feista465ccc2019-02-08 12:51:01 -0800791 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800792 {
793 if (fruBytesIter >= fruBytes.end())
794 {
795 return false;
796 }
797
Vijay Khemka5d5de442018-11-07 10:51:25 -0800798 /* Checking for last byte C1 to indicate that no more
799 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700800 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800801 {
802 break;
803 }
804
Ed Tanous2147e672019-02-27 13:59:56 -0800805 size_t length = *fruBytesIter & 0x3f;
806 fruBytesIter += 1;
807
James Feist3cb5fec2018-01-23 14:41:51 -0800808 if (fruBytesIter >= fruBytes.end())
809 {
810 return false;
811 }
Ed Tanous2147e672019-02-27 13:59:56 -0800812 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800813
Ed Tanous2147e672019-02-27 13:59:56 -0800814 // Strip non null characters from the end
815 value.erase(std::find_if(value.rbegin(), value.rend(),
816 [](char ch) { return ch != 0; })
817 .base(),
818 value.end());
819
James Feist0eb40352019-04-09 14:44:04 -0700820 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800821
James Feist3cb5fec2018-01-23 14:41:51 -0800822 fruBytesIter += length;
823 if (fruBytesIter >= fruBytes.end())
824 {
825 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800826 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800827 {
828 std::cerr << c;
829 }
830 std::cerr << "\n";
831 if (DEBUG)
832 {
James Feista465ccc2019-02-08 12:51:01 -0800833 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800834 {
835 std::cerr << keyPair.first << " : "
836 << keyPair.second << "\n";
837 }
838 }
839 return false;
840 }
841 }
842 }
843 }
844
845 return true;
846}
847
Nikhil Potaded8884f12019-03-27 13:27:13 -0700848std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
849{
850 auto deviceMap = busMap.find(bus);
851 if (deviceMap == busMap.end())
852 {
853 throw std::invalid_argument("Invalid Bus.");
854 }
855 auto device = deviceMap->second->find(address);
856 if (device == deviceMap->second->end())
857 {
858 throw std::invalid_argument("Invalid Address.");
859 }
860 std::vector<uint8_t>& ret =
861 reinterpret_cast<std::vector<uint8_t>&>(device->second);
862
863 return ret;
864}
865
James Feist3cb5fec2018-01-23 14:41:51 -0800866void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700867 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800868 boost::container::flat_map<
869 std::pair<size_t, size_t>,
870 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700871 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800872{
873 boost::container::flat_map<std::string, std::string> formattedFru;
874 if (!formatFru(device, formattedFru))
875 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700876 std::cerr << "failed to format fru for device at bus " << bus
877 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800878 return;
879 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700880
James Feist3cb5fec2018-01-23 14:41:51 -0800881 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
882 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700883 // Not found under Board section or an empty string.
884 if (productNameFind == formattedFru.end() ||
885 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800886 {
887 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
888 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700889 // Found under Product section and not an empty string.
890 if (productNameFind != formattedFru.end() &&
891 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800892 {
893 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800894 std::regex illegalObject("[^A-Za-z0-9_]");
895 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800896 }
897 else
898 {
899 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
900 UNKNOWN_BUS_OBJECT_COUNT++;
901 }
902
James Feist918e18c2018-02-13 15:51:07 -0800903 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800904 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700905 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800906 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700907 int highest = -1;
908 bool found = false;
909
James Feista465ccc2019-02-08 12:51:01 -0800910 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800911 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700912 std::string path = busIface.second->get_object_path();
913 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800914 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700915 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -0700916 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
917 static_cast<uint8_t>(busIface.first.second)) ==
918 getFruInfo(static_cast<uint8_t>(bus),
919 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -0700920 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700921 // This device is already added to the lower numbered bus,
922 // do not replicate it.
923 return;
James Feist79e9c0b2018-03-15 15:21:17 -0700924 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700925
926 // Check if the match named has extra information.
927 found = true;
928 std::smatch base_match;
929
930 bool match = std::regex_match(
931 path, base_match, std::regex(productName + "_(\\d+)$"));
932 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -0700933 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700934 if (base_match.size() == 2)
935 {
936 std::ssub_match base_sub_match = base_match[1];
937 std::string base = base_sub_match.str();
938
939 int value = std::stoi(base);
940 highest = (value > highest) ? value : highest;
941 }
James Feist79e9c0b2018-03-15 15:21:17 -0700942 }
James Feist918e18c2018-02-13 15:51:07 -0800943 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700944 } // end searching objects
945
946 if (found)
947 {
948 // We found something with the same name. If highest was still -1,
949 // it means this new entry will be _0.
950 productName += "_";
951 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -0800952 }
953 }
James Feist3cb5fec2018-01-23 14:41:51 -0800954
James Feist9eb0b582018-04-27 12:15:46 -0700955 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
956 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
957 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
958
James Feista465ccc2019-02-08 12:51:01 -0800959 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800960 {
James Feist9eb0b582018-04-27 12:15:46 -0700961
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700962 std::regex_replace(property.second.begin(), property.second.begin(),
963 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700964 if (property.second.empty())
965 {
966 continue;
967 }
968 std::string key =
969 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
970 if (!iface->register_property(key, property.second + '\0'))
971 {
972 std::cerr << "illegal key: " << key << "\n";
973 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700974 if (DEBUG)
975 {
976 std::cout << property.first << ": " << property.second << "\n";
977 }
James Feist3cb5fec2018-01-23 14:41:51 -0800978 }
James Feist2a9d6db2018-04-27 15:48:28 -0700979
980 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700981 iface->register_property("BUS", bus);
982 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700983
James Feist9eb0b582018-04-27 12:15:46 -0700984 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800985}
986
James Feista465ccc2019-02-08 12:51:01 -0800987static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800988{
989 // try to read baseboard fru from file
990 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
991 if (baseboardFruFile.good())
992 {
993 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -0700994 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -0800995 baseboardFru.resize(fileSize);
996 baseboardFruFile.seekg(0, std::ios_base::beg);
997 baseboardFruFile.read(baseboardFru.data(), fileSize);
998 }
999 else
1000 {
1001 return false;
1002 }
1003 return true;
1004}
1005
James Feista465ccc2019-02-08 12:51:01 -08001006bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001007{
1008 boost::container::flat_map<std::string, std::string> tmp;
1009 if (fru.size() > MAX_FRU_SIZE)
1010 {
1011 std::cerr << "Invalid fru.size() during writeFru\n";
1012 return false;
1013 }
1014 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001015 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001016 {
1017 std::cerr << "Invalid fru format during writeFru\n";
1018 return false;
1019 }
1020 // baseboard fru
1021 if (bus == 0 && address == 0)
1022 {
1023 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1024 if (!file.good())
1025 {
1026 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1027 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001028 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001029 return false;
1030 }
James Feista465ccc2019-02-08 12:51:01 -08001031 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001032 return file.good();
1033 }
1034 else
1035 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001036 if (hasEepromFile(bus, address))
1037 {
1038 auto path = getEepromPath(bus, address);
1039 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1040 if (eeprom < 0)
1041 {
1042 std::cerr << "unable to open i2c device " << path << "\n";
1043 throw DBusInternalError();
1044 return false;
1045 }
1046
1047 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1048 if (writtenBytes < 0)
1049 {
1050 std::cerr << "unable to write to i2c device " << path << "\n";
1051 close(eeprom);
1052 throw DBusInternalError();
1053 return false;
1054 }
1055
1056 close(eeprom);
1057 return true;
1058 }
1059
James Feistb49ffc32018-05-02 11:10:43 -07001060 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1061
1062 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1063 if (file < 0)
1064 {
1065 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001066 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001067 return false;
1068 }
1069 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1070 {
1071 std::cerr << "unable to set device address\n";
1072 close(file);
James Feistddb78302018-09-06 11:45:42 -07001073 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001074 return false;
1075 }
1076
1077 constexpr const size_t RETRY_MAX = 2;
1078 uint16_t index = 0;
1079 size_t retries = RETRY_MAX;
1080 while (index < fru.size())
1081 {
1082 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1083 (retries == RETRY_MAX))
1084 {
1085 // The 4K EEPROM only uses the A2 and A1 device address bits
1086 // with the third bit being a memory page address bit.
1087 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1088 {
1089 std::cerr << "unable to set device address\n";
1090 close(file);
James Feistddb78302018-09-06 11:45:42 -07001091 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001092 return false;
1093 }
1094 }
1095
James Feist98132792019-07-09 13:29:09 -07001096 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1097 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001098 {
1099 if (!retries--)
1100 {
1101 std::cerr << "error writing fru: " << strerror(errno)
1102 << "\n";
1103 close(file);
James Feistddb78302018-09-06 11:45:42 -07001104 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001105 return false;
1106 }
1107 }
1108 else
1109 {
1110 retries = RETRY_MAX;
1111 index++;
1112 }
1113 // most eeproms require 5-10ms between writes
1114 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1115 }
1116 close(file);
1117 return true;
1118 }
1119}
1120
James Feist9eb0b582018-04-27 12:15:46 -07001121void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001122 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001123 boost::container::flat_map<
1124 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001125 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001126{
James Feist6ebf9de2018-05-15 15:01:17 -07001127 static boost::asio::deadline_timer timer(io);
1128 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001129
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001130 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001131 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001132 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001133 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001134
Nikhil Potaded8884f12019-03-27 13:27:13 -07001135 boost::container::flat_map<size_t, fs::path> busPaths;
1136 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001137 {
James Feist4131aea2018-03-09 09:47:30 -08001138 std::cerr << "unable to find i2c devices\n";
1139 return;
James Feist918e18c2018-02-13 15:51:07 -08001140 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001141
1142 for (auto busPath : busPaths)
1143 {
1144 i2cBuses.emplace_back(busPath.second);
1145 }
James Feist4131aea2018-03-09 09:47:30 -08001146
James Feist98132792019-07-09 13:29:09 -07001147 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001148 for (auto& [pair, interface] : foundDevices)
1149 {
1150 objServer.remove_interface(interface);
1151 }
1152 foundDevices.clear();
1153
James Feist5cb06082019-10-24 17:11:13 -07001154 auto scan =
1155 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001156 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001157 {
1158 objServer.remove_interface(busIface.second);
1159 }
James Feist4131aea2018-03-09 09:47:30 -08001160
James Feist6ebf9de2018-05-15 15:01:17 -07001161 dbusInterfaceMap.clear();
1162 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001163
James Feist6ebf9de2018-05-15 15:01:17 -07001164 // todo, get this from a more sensable place
1165 std::vector<char> baseboardFru;
1166 if (readBaseboardFru(baseboardFru))
1167 {
1168 boost::container::flat_map<int, std::vector<char>>
1169 baseboardDev;
1170 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001171 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001172 }
James Feist98132792019-07-09 13:29:09 -07001173 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001174 {
James Feista465ccc2019-02-08 12:51:01 -08001175 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001176 {
James Feist5cb06082019-10-24 17:11:13 -07001177 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1178 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001179 }
1180 }
1181 });
1182 scan->run();
1183 });
James Feist918e18c2018-02-13 15:51:07 -08001184}
1185
James Feist98132792019-07-09 13:29:09 -07001186int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001187{
1188 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001189 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001190 std::vector<fs::path> i2cBuses;
1191
James Feista3c180a2018-08-09 16:06:04 -07001192 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001193 {
1194 std::cerr << "unable to find i2c devices\n";
1195 return 1;
1196 }
James Feist3cb5fec2018-01-23 14:41:51 -08001197
Patrick Venture11f1ff42019-08-01 10:42:12 -07001198 // check for and load blacklist with initial buses.
1199 loadBlacklist(blacklistPath);
1200
Vijay Khemka065f6d92018-12-18 10:37:47 -08001201 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001202
James Feist6ebf9de2018-05-15 15:01:17 -07001203 // this is a map with keys of pair(bus number, address) and values of
1204 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001205 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001206 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1207 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001208
James Feist9eb0b582018-04-27 12:15:46 -07001209 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1210 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1211 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001212
James Feist5cb06082019-10-24 17:11:13 -07001213 iface->register_method("ReScan",
1214 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001215
Nikhil Potaded8884f12019-03-27 13:27:13 -07001216 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001217
1218 iface->register_method("WriteFru", [&](const uint8_t bus,
1219 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001220 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001221 if (!writeFru(bus, address, data))
1222 {
James Feistddb78302018-09-06 11:45:42 -07001223 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001224 return;
1225 }
1226 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001227 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001228 });
James Feist9eb0b582018-04-27 12:15:46 -07001229 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001230
James Feist9eb0b582018-04-27 12:15:46 -07001231 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001232 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001233 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001234 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001235 std::string,
1236 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001237 values;
1238 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001239 auto findState = values.find("CurrentHostState");
1240 bool on = false;
1241 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001242 {
James Feist0eeb79c2019-10-09 13:35:29 -07001243 on = boost::ends_with(std::get<std::string>(findState->second),
1244 "Running");
1245 }
James Feist6ebf9de2018-05-15 15:01:17 -07001246
James Feist0eeb79c2019-10-09 13:35:29 -07001247 if (on)
1248 {
James Feist5cb06082019-10-24 17:11:13 -07001249 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001250 }
James Feist918e18c2018-02-13 15:51:07 -08001251 };
James Feist9eb0b582018-04-27 12:15:46 -07001252
1253 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001254 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001255 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001256 "openbmc_project/state/"
1257 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001258 eventHandler);
1259
James Feist4131aea2018-03-09 09:47:30 -08001260 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001261 inotify_add_watch(fd, I2C_DEV_LOCATION,
1262 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001263 std::array<char, 4096> readBuffer;
1264 std::string pendingBuffer;
1265 // monitor for new i2c devices
1266 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1267 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001268 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001269 std::size_t bytes_transferred) {
1270 if (ec)
1271 {
1272 std::cout << "Callback Error " << ec << "\n";
1273 return;
1274 }
1275 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1276 bool devChange = false;
1277 while (pendingBuffer.size() > sizeof(inotify_event))
1278 {
James Feista465ccc2019-02-08 12:51:01 -08001279 const inotify_event* iEvent =
1280 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001281 pendingBuffer.data());
1282 switch (iEvent->mask)
1283 {
James Feist9eb0b582018-04-27 12:15:46 -07001284 case IN_CREATE:
1285 case IN_MOVED_TO:
1286 case IN_DELETE:
1287 if (boost::starts_with(std::string(iEvent->name),
1288 "i2c"))
1289 {
1290 devChange = true;
1291 }
James Feist4131aea2018-03-09 09:47:30 -08001292 }
1293
1294 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1295 }
James Feist6ebf9de2018-05-15 15:01:17 -07001296 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001297 {
James Feist5cb06082019-10-24 17:11:13 -07001298 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001299 }
James Feist6ebf9de2018-05-15 15:01:17 -07001300
James Feist4131aea2018-03-09 09:47:30 -08001301 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1302 watchI2cBusses);
1303 };
1304
1305 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001306 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001307 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001308
James Feist3cb5fec2018-01-23 14:41:51 -08001309 io.run();
1310 return 0;
1311}