blob: 4b6d7c2e10e233b7069d9625e5589690f16b48b4 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
Patrick Venturea49dc332019-10-26 08:32:02 -070017#include "Utils.hpp"
18
James Feist3b860982018-10-02 14:34:07 -070019#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080020#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070021#include <sys/inotify.h>
22#include <sys/ioctl.h>
23
Patrick Venturec274f2f2019-10-26 09:27:23 -070024#include <array>
James Feist3b860982018-10-02 14:34:07 -070025#include <boost/algorithm/string/predicate.hpp>
26#include <boost/container/flat_map.hpp>
27#include <chrono>
28#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070029#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080030#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070031#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080032#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070033#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080034#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070035#include <limits>
Patrick Venture11f1ff42019-08-01 10:42:12 -070036#include <nlohmann/json.hpp>
James Feist3f8a2782018-02-12 09:24:42 -080037#include <regex>
James Feist3b860982018-10-02 14:34:07 -070038#include <sdbusplus/asio/connection.hpp>
39#include <sdbusplus/asio/object_server.hpp>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070040#include <set>
41#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070042#include <string>
James Feist3b860982018-10-02 14:34:07 -070043#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080044#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070045#include <vector>
James Feist3b860982018-10-02 14:34:07 -070046
47extern "C" {
48#include <i2c/smbus.h>
49#include <linux/i2c-dev.h>
50}
James Feist3cb5fec2018-01-23 14:41:51 -080051
Ed Tanous072e25d2018-12-16 21:45:20 -080052namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080053static constexpr bool DEBUG = false;
54static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070055constexpr size_t MAX_FRU_SIZE = 512;
56constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070057constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080058
Patrick Venture11f1ff42019-08-01 10:42:12 -070059constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
60
James Feista465ccc2019-02-08 12:51:01 -080061const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080062 "/etc/fru/baseboard.fru.bin";
63
James Feista465ccc2019-02-08 12:51:01 -080064const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080065
James Feista465ccc2019-02-08 12:51:01 -080066static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080067 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070068const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080069using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
70using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
71
James Feist444830e2019-04-05 08:38:16 -070072static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070073struct FindDevicesWithCallback;
74
Nikhil Potaded8884f12019-03-27 13:27:13 -070075static BusMap busMap;
76
James Feist8a983922019-10-24 17:11:56 -070077static boost::container::flat_map<
78 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
79 foundDevices;
80
James Feist5cb06082019-10-24 17:11:13 -070081boost::asio::io_service io;
82auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
83auto objServer = sdbusplus::asio::object_server(systemBus);
84
Patrick Venturebaba7672019-10-26 09:26:41 -070085bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
86
87using ReadBlockFunc = std::function<int64_t(int flag, int file, uint16_t offset,
88 uint8_t length, uint8_t* outBuf)>;
89
90// Read and validate FRU contents, given the flag required for raw i2c, the open
91// file handle, a read method, and a helper string for failures.
92std::vector<char> readFruContents(int flag, int file, ReadBlockFunc readBlock,
93 const std::string& errorHelp)
94{
95 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
96
97 if (readBlock(flag, file, 0x0, 0x8, blockData.data()) < 0)
98 {
99 std::cerr << "failed to read " << errorHelp << "\n";
100 return {};
101 }
102
103 // check the header checksum
104 if (!validateHeader(blockData))
105 {
106 if (DEBUG)
107 {
108 std::cerr << "Illegal header " << errorHelp << "\n";
109 }
110
111 return {};
112 }
113
114 std::vector<char> device;
115 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
116
Patrick Venturee26395d2019-10-29 14:05:16 -0700117 bool hasMultiRecords = false;
Patrick Venturebaba7672019-10-26 09:26:41 -0700118 int fruLength = 0;
119 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
120 {
121 // TODO: offset can be 255, device is holding "chars" that's not
122 // good.
123 int areaOffset = device[jj];
124 if (areaOffset == 0)
125 {
126 continue;
127 }
128
Patrick Venturee26395d2019-10-29 14:05:16 -0700129 // MultiRecords are different. jj is not tracking section, it's walking
130 // the common header.
131 if (std::string(FRU_AREAS[jj - 1]) == std::string("MULTIRECORD"))
132 {
133 hasMultiRecords = true;
134 break;
135 }
136
Patrick Venturebaba7672019-10-26 09:26:41 -0700137 areaOffset *= 8;
138
139 if (readBlock(flag, file, static_cast<uint16_t>(areaOffset), 0x2,
140 blockData.data()) < 0)
141 {
142 std::cerr << "failed to read " << errorHelp << "\n";
143 return {};
144 }
145
146 // Ignore data type.
147 int length = blockData[1] * 8;
148 areaOffset += length;
149 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
150 }
151
Patrick Venturee26395d2019-10-29 14:05:16 -0700152 if (hasMultiRecords)
153 {
154 // device[area count] is the index to the last area because the 0th
155 // entry is not an offset in the common header.
156 int areaOffset = device[FRU_AREAS.size()];
157 areaOffset *= 8;
158
159 // the multi-area record header is 5 bytes long.
160 constexpr int multiRecordHeaderSize = 5;
161 constexpr int multiRecordEndOfList = 0x80;
162
163 // Sanity hard-limit to 64KB.
164 while (areaOffset < std::numeric_limits<uint16_t>::max())
165 {
166 // In multi-area, the area offset points to the 0th record, each
167 // record has 3 bytes of the header we care about.
168 if (readBlock(flag, file, static_cast<uint16_t>(areaOffset), 0x3,
169 blockData.data()) < 0)
170 {
171 std::cerr << "failed to read " << errorHelp << "\n";
172 return {};
173 }
174
175 // Ok, let's check the record length, which is in bytes (unsigned,
176 // up to 255, so blockData should hold uint8_t not char)
177 int recordLength = blockData[2];
178 areaOffset += (recordLength + multiRecordHeaderSize);
179 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
180
181 // If this is the end of the list bail.
182 if ((blockData[1] & multiRecordEndOfList))
183 {
184 break;
185 }
186 }
187 }
188
Patrick Venturebaba7672019-10-26 09:26:41 -0700189 // You already copied these first 8 bytes (the ipmi fru header size)
190 fruLength -= 8;
191
192 int readOffset = 8;
193
194 while (fruLength > 0)
195 {
196 int requestLength = std::min(I2C_SMBUS_BLOCK_MAX, fruLength);
197
198 if (readBlock(flag, file, static_cast<uint16_t>(readOffset),
199 static_cast<uint8_t>(requestLength),
200 blockData.data()) < 0)
201 {
202 std::cerr << "failed to read " << errorHelp << "\n";
203 return {};
204 }
205
206 device.insert(device.end(), blockData.begin(),
207 blockData.begin() + requestLength);
208
209 readOffset += requestLength;
210 fruLength -= requestLength;
211 }
212
213 return device;
214}
215
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700216// Given a bus/address, produce the path in sysfs for an eeprom.
217static std::string getEepromPath(size_t bus, size_t address)
218{
219 std::stringstream output;
220 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
221 << std::setfill('0') << std::setw(4) << std::hex << address
222 << "/eeprom";
223 return output.str();
224}
225
226static bool hasEepromFile(size_t bus, size_t address)
227{
228 auto path = getEepromPath(bus, address);
229 try
230 {
231 return fs::exists(path);
232 }
233 catch (...)
234 {
235 return false;
236 }
237}
238
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700239static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
240 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700241{
242 auto result = lseek(fd, offset, SEEK_SET);
243 if (result < 0)
244 {
245 std::cerr << "failed to seek\n";
246 return -1;
247 }
248
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700249 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700250}
251
James Feistc95cb142018-02-26 10:41:42 -0800252static bool isMuxBus(size_t bus)
253{
Ed Tanous072e25d2018-12-16 21:45:20 -0800254 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800255 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
256}
257
James Feist8a983922019-10-24 17:11:56 -0700258static void makeProbeInterface(size_t bus, size_t address)
259{
260 if (isMuxBus(bus))
261 {
262 return; // the mux buses are random, no need to publish
263 }
264 auto [it, success] = foundDevices.emplace(
265 std::make_pair(bus, address),
266 objServer.add_interface(
267 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
268 std::to_string(address),
269 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
270 if (!success)
271 {
272 return; // already added
273 }
274 it->second->register_property("Bus", bus);
275 it->second->register_property("Address", address);
276 it->second->initialize();
277}
278
Vijay Khemka2d681f62018-11-06 15:51:00 -0800279static int isDevice16Bit(int file)
280{
281 /* Get first byte */
282 int byte1 = i2c_smbus_read_byte_data(file, 0);
283 if (byte1 < 0)
284 {
285 return byte1;
286 }
287 /* Read 7 more bytes, it will read same first byte in case of
288 * 8 bit but it will read next byte in case of 16 bit
289 */
290 for (int i = 0; i < 7; i++)
291 {
292 int byte2 = i2c_smbus_read_byte_data(file, 0);
293 if (byte2 < 0)
294 {
295 return byte2;
296 }
297 if (byte2 != byte1)
298 {
299 return 1;
300 }
301 }
302 return 0;
303}
304
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700305static int64_t readBlockData(int flag, int file, uint16_t offset, uint8_t len,
306 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800307{
Patrick Venture4f47fe62019-08-08 16:30:38 -0700308 uint8_t lowAddr = static_cast<uint8_t>(offset);
309 uint8_t highAddr = static_cast<uint8_t>(offset >> 8);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800310
311 if (flag == 0)
312 {
Patrick Venture4f47fe62019-08-08 16:30:38 -0700313 return i2c_smbus_read_i2c_block_data(file, lowAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800314 }
315
316 /* This is for 16 bit addressing EEPROM device. First an offset
317 * needs to be written before read data from a offset
318 */
Patrick Venture4f47fe62019-08-08 16:30:38 -0700319 int ret = i2c_smbus_write_byte_data(file, 0, lowAddr);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800320 if (ret < 0)
321 {
322 return ret;
323 }
324
Patrick Venture4f47fe62019-08-08 16:30:38 -0700325 return i2c_smbus_read_i2c_block_data(file, highAddr, len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800326}
327
James Feist24bae7a2019-04-03 09:50:56 -0700328bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
329{
330 // ipmi spec format version number is currently at 1, verify it
331 if (blockData[0] != 0x1)
332 {
333 return false;
334 }
335
336 // verify pad is set to 0
337 if (blockData[6] != 0x0)
338 {
339 return false;
340 }
341
342 // verify offsets are 0, or don't point to another offset
343 std::set<uint8_t> foundOffsets;
344 for (int ii = 1; ii < 6; ii++)
345 {
346 if (blockData[ii] == 0)
347 {
348 continue;
349 }
James Feist0eb40352019-04-09 14:44:04 -0700350 auto inserted = foundOffsets.insert(blockData[ii]);
351 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700352 {
353 return false;
354 }
355 }
356
357 // validate checksum
358 size_t sum = 0;
359 for (int jj = 0; jj < 7; jj++)
360 {
361 sum += blockData[jj];
362 }
363 sum = (256 - sum) & 0xFF;
364
365 if (sum != blockData[7])
366 {
367 return false;
368 }
369 return true;
370}
371
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700372// TODO: This code is very similar to the non-eeprom version and can be merged
373// with some tweaks.
374static std::vector<char> processEeprom(int bus, int address)
375{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700376 auto path = getEepromPath(bus, address);
377
378 int file = open(path.c_str(), O_RDONLY);
379 if (file < 0)
380 {
381 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700382 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700383 }
384
Patrick Venturebaba7672019-10-26 09:26:41 -0700385 std::string errorMessage = "eeprom at " + std::to_string(bus) +
386 " address " + std::to_string(address);
387 std::vector<char> device =
388 readFruContents(0, file, readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700389
390 close(file);
391 return device;
392}
393
394std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
395{
396 std::set<int> foundList;
397
398 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
399
400 // For each file listed under the i2c device
401 // NOTE: This should be faster than just checking for each possible address
402 // path.
403 for (const auto& p : fs::directory_iterator(path))
404 {
405 const std::string node = p.path().string();
406 std::smatch m;
407 bool found =
408 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
409
410 if (!found)
411 {
412 continue;
413 }
414 if (m.size() != 2)
415 {
416 std::cerr << "regex didn't capture\n";
417 continue;
418 }
419
420 std::ssub_match subMatch = m[1];
421 std::string addressString = subMatch.str();
422
423 std::size_t ignored;
424 const int hexBase = 16;
425 int address = std::stoi(addressString, &ignored, hexBase);
426
427 const std::string eeprom = node + "/eeprom";
428
429 try
430 {
431 if (!fs::exists(eeprom))
432 {
433 continue;
434 }
435 }
436 catch (...)
437 {
438 continue;
439 }
440
441 // There is an eeprom file at this address, it may have invalid
442 // contents, but we found it.
443 foundList.insert(address);
444
445 std::vector<char> device = processEeprom(i2cBus, address);
446 if (!device.empty())
447 {
448 devices->emplace(address, device);
449 }
450 }
451
452 return foundList;
453}
454
Patrick Venture4f47fe62019-08-08 16:30:38 -0700455int getBusFrus(int file, int first, int last, int bus,
456 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800457{
James Feist3cb5fec2018-01-23 14:41:51 -0800458
James Feist26c27ad2018-07-25 15:09:40 -0700459 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700460 // NOTE: When reading the devices raw on the bus, it can interfere with
461 // the driver's ability to operate, therefore read eeproms first before
462 // scanning for devices without drivers. Several experiments were run
463 // and it was determined that if there were any devices on the bus
464 // before the eeprom was hit and read, the eeprom driver wouldn't open
465 // while the bus device was open. An experiment was not performed to see
466 // if this issue was resolved if the i2c bus device was closed, but
467 // hexdumps of the eeprom later were successful.
468
469 // Scan for i2c eeproms loaded on this bus.
470 std::set<int> skipList = findI2CEeproms(bus, devices);
471
James Feist26c27ad2018-07-25 15:09:40 -0700472 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800473 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700474 if (skipList.find(ii) != skipList.end())
475 {
476 continue;
477 }
James Feist3cb5fec2018-01-23 14:41:51 -0800478
James Feist26c27ad2018-07-25 15:09:40 -0700479 // Set slave address
480 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800481 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700482 std::cerr << "device at bus " << bus << " register " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700483 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700484 continue;
485 }
486 // probe
487 else if (i2c_smbus_read_byte(file) < 0)
488 {
489 continue;
490 }
James Feist3cb5fec2018-01-23 14:41:51 -0800491
James Feist26c27ad2018-07-25 15:09:40 -0700492 if (DEBUG)
493 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700494 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700495 << "\n";
496 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800497
James Feist8a983922019-10-24 17:11:56 -0700498 makeProbeInterface(bus, ii);
499
Vijay Khemka2d681f62018-11-06 15:51:00 -0800500 /* Check for Device type if it is 8 bit or 16 bit */
501 int flag = isDevice16Bit(file);
502 if (flag < 0)
503 {
504 std::cerr << "failed to read bus " << bus << " address " << ii
505 << "\n";
506 continue;
507 }
508
Patrick Venturebaba7672019-10-26 09:26:41 -0700509 std::string errorMessage =
510 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
511 std::vector<char> device =
512 readFruContents(flag, file, readBlockData, errorMessage);
513 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700514 {
James Feist26c27ad2018-07-25 15:09:40 -0700515 continue;
516 }
James Feist26c27ad2018-07-25 15:09:40 -0700517
Patrick Venture786f1792019-08-05 16:33:44 -0700518 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800519 }
James Feist26c27ad2018-07-25 15:09:40 -0700520 return 1;
521 });
522 std::future_status status =
523 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
524 if (status == std::future_status::timeout)
525 {
526 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700527 busBlacklist.insert(bus);
528 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700529 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800530 }
531
James Feist444830e2019-04-05 08:38:16 -0700532 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700533 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800534}
535
Patrick Venture11f1ff42019-08-01 10:42:12 -0700536void loadBlacklist(const char* path)
537{
538 std::ifstream blacklistStream(path);
539 if (!blacklistStream.good())
540 {
541 // File is optional.
542 std::cerr << "Cannot open blacklist file.\n\n";
543 return;
544 }
545
546 nlohmann::json data =
547 nlohmann::json::parse(blacklistStream, nullptr, false);
548 if (data.is_discarded())
549 {
550 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
551 "exiting\n";
552 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700553 }
554
555 // It's expected to have at least one field, "buses" that is an array of the
556 // buses by integer. Allow for future options to exclude further aspects,
557 // such as specific addresses or ranges.
558 if (data.type() != nlohmann::json::value_t::object)
559 {
560 std::cerr << "Illegal blacklist, expected to read dictionary\n";
561 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700562 }
563
564 // If buses field is missing, that's fine.
565 if (data.count("buses") == 1)
566 {
567 // Parse the buses array after a little validation.
568 auto buses = data.at("buses");
569 if (buses.type() != nlohmann::json::value_t::array)
570 {
571 // Buses field present but invalid, therefore this is an error.
572 std::cerr << "Invalid contents for blacklist buses field\n";
573 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700574 }
575
576 // Catch exception here for type mis-match.
577 try
578 {
579 for (const auto& bus : buses)
580 {
581 busBlacklist.insert(bus.get<size_t>());
582 }
583 }
584 catch (const nlohmann::detail::type_error& e)
585 {
586 // Type mis-match is a critical error.
587 std::cerr << "Invalid bus type: " << e.what() << "\n";
588 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700589 }
590 }
591
592 return;
593}
594
James Feista465ccc2019-02-08 12:51:01 -0800595static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700596 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800597{
James Feista465ccc2019-02-08 12:51:01 -0800598 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800599 {
600 auto busnum = i2cBus.string();
601 auto lastDash = busnum.rfind(std::string("-"));
602 // delete everything before dash inclusive
603 if (lastDash != std::string::npos)
604 {
605 busnum.erase(0, lastDash + 1);
606 }
607 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700608 if (busBlacklist.find(bus) != busBlacklist.end())
609 {
610 continue; // skip previously failed busses
611 }
James Feist3cb5fec2018-01-23 14:41:51 -0800612
613 auto file = open(i2cBus.c_str(), O_RDWR);
614 if (file < 0)
615 {
616 std::cerr << "unable to open i2c device " << i2cBus.string()
617 << "\n";
618 continue;
619 }
620 unsigned long funcs = 0;
621
622 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
623 {
624 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700625 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800626 << bus << "\n";
627 continue;
628 }
629 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
630 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
631 {
632 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
633 << bus << "\n";
634 continue;
635 }
James Feist98132792019-07-09 13:29:09 -0700636 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800637 device = std::make_shared<DeviceMap>();
638
Nikhil Potaded8884f12019-03-27 13:27:13 -0700639 // i2cdetect by default uses the range 0x03 to 0x77, as
640 // this is what we have tested with, use this range. Could be
641 // changed in future.
642 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800643 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700644 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800645 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700646
647 // fd is closed in this function in case the bus locks up
Patrick Venture4f47fe62019-08-08 16:30:38 -0700648 getBusFrus(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700649
650 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800651 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700652 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800653 }
James Feist3cb5fec2018-01-23 14:41:51 -0800654 }
James Feist3cb5fec2018-01-23 14:41:51 -0800655}
656
James Feist6ebf9de2018-05-15 15:01:17 -0700657// this class allows an async response after all i2c devices are discovered
658struct FindDevicesWithCallback
659 : std::enable_shared_from_this<FindDevicesWithCallback>
660{
James Feista465ccc2019-02-08 12:51:01 -0800661 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700662 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800663 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700664 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700665 _busMap(busmap), _callback(std::move(callback))
James Feist6ebf9de2018-05-15 15:01:17 -0700666 {
667 }
668 ~FindDevicesWithCallback()
669 {
670 _callback();
671 }
672 void run()
673 {
James Feist98132792019-07-09 13:29:09 -0700674 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700675 }
676
James Feista465ccc2019-02-08 12:51:01 -0800677 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800678 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700679 std::function<void(void)> _callback;
680};
681
James Feist3cb5fec2018-01-23 14:41:51 -0800682static const std::tm intelEpoch(void)
683{
James Feist98132792019-07-09 13:29:09 -0700684 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800685 val.tm_year = 1996 - 1900;
686 return val;
687}
688
James Feista465ccc2019-02-08 12:51:01 -0800689bool formatFru(const std::vector<char>& fruBytes,
690 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800691{
James Feista465ccc2019-02-08 12:51:01 -0800692 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800693 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800694
James Feista465ccc2019-02-08 12:51:01 -0800695 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800696 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
697 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800698
James Feista465ccc2019-02-08 12:51:01 -0800699 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800700 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
701 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
702 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800703
James Feistd068e932018-09-20 10:53:07 -0700704 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800705 {
706 return false;
707 }
708 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700709 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800710 std::to_string(static_cast<int>(*fruAreaOffsetField));
711
James Feista465ccc2019-02-08 12:51:01 -0800712 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800713
James Feist0eb40352019-04-09 14:44:04 -0700714 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800715 {
Patrick Venture4b7a7452019-10-28 08:41:02 -0700716 ++fruAreaOffsetField;
James Feist3cb5fec2018-01-23 14:41:51 -0800717 if (fruAreaOffsetField >= fruBytes.end())
718 {
719 return false;
720 }
721 size_t offset = (*fruAreaOffsetField) * 8;
722
723 if (offset > 1)
724 {
725 // +2 to skip format and length
726 std::vector<char>::const_iterator fruBytesIter =
727 fruBytes.begin() + offset + 2;
728
729 if (fruBytesIter >= fruBytes.end())
730 {
731 return false;
732 }
733
734 if (area == "CHASSIS")
735 {
736 result["CHASSIS_TYPE"] =
737 std::to_string(static_cast<int>(*fruBytesIter));
738 fruBytesIter += 1;
739 fieldData = &CHASSIS_FRU_AREAS;
740 }
741 else if (area == "BOARD")
742 {
743 result["BOARD_LANGUAGE_CODE"] =
744 std::to_string(static_cast<int>(*fruBytesIter));
745 fruBytesIter += 1;
746 if (fruBytesIter >= fruBytes.end())
747 {
748 return false;
749 }
750
751 unsigned int minutes = *fruBytesIter |
752 *(fruBytesIter + 1) << 8 |
753 *(fruBytesIter + 2) << 16;
754 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700755 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800756 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700757 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800758
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700759 // Tue Nov 20 23:08:00 2018
760 char timeString[32] = {0};
761 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700762 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700763 if (bytes == 0)
764 {
765 std::cerr << "invalid time string encountered\n";
766 return false;
767 }
768
769 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800770 fruBytesIter += 3;
771 fieldData = &BOARD_FRU_AREAS;
772 }
773 else if (area == "PRODUCT")
774 {
775 result["PRODUCT_LANGUAGE_CODE"] =
776 std::to_string(static_cast<int>(*fruBytesIter));
777 fruBytesIter += 1;
778 fieldData = &PRODUCT_FRU_AREAS;
779 }
780 else
781 {
782 continue;
783 }
James Feista465ccc2019-02-08 12:51:01 -0800784 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800785 {
786 if (fruBytesIter >= fruBytes.end())
787 {
788 return false;
789 }
790
Vijay Khemka5d5de442018-11-07 10:51:25 -0800791 /* Checking for last byte C1 to indicate that no more
792 * field to be read */
James Feist98132792019-07-09 13:29:09 -0700793 if (static_cast<uint8_t>(*fruBytesIter) == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800794 {
795 break;
796 }
797
Ed Tanous2147e672019-02-27 13:59:56 -0800798 size_t length = *fruBytesIter & 0x3f;
799 fruBytesIter += 1;
800
James Feist3cb5fec2018-01-23 14:41:51 -0800801 if (fruBytesIter >= fruBytes.end())
802 {
803 return false;
804 }
Ed Tanous2147e672019-02-27 13:59:56 -0800805 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800806
Ed Tanous2147e672019-02-27 13:59:56 -0800807 // Strip non null characters from the end
808 value.erase(std::find_if(value.rbegin(), value.rend(),
809 [](char ch) { return ch != 0; })
810 .base(),
811 value.end());
812
James Feist0eb40352019-04-09 14:44:04 -0700813 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800814
James Feist3cb5fec2018-01-23 14:41:51 -0800815 fruBytesIter += length;
816 if (fruBytesIter >= fruBytes.end())
817 {
818 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800819 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800820 {
821 std::cerr << c;
822 }
823 std::cerr << "\n";
824 if (DEBUG)
825 {
James Feista465ccc2019-02-08 12:51:01 -0800826 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800827 {
828 std::cerr << keyPair.first << " : "
829 << keyPair.second << "\n";
830 }
831 }
832 return false;
833 }
834 }
835 }
836 }
837
838 return true;
839}
840
Nikhil Potaded8884f12019-03-27 13:27:13 -0700841std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
842{
843 auto deviceMap = busMap.find(bus);
844 if (deviceMap == busMap.end())
845 {
846 throw std::invalid_argument("Invalid Bus.");
847 }
848 auto device = deviceMap->second->find(address);
849 if (device == deviceMap->second->end())
850 {
851 throw std::invalid_argument("Invalid Address.");
852 }
853 std::vector<uint8_t>& ret =
854 reinterpret_cast<std::vector<uint8_t>&>(device->second);
855
856 return ret;
857}
858
James Feist3cb5fec2018-01-23 14:41:51 -0800859void AddFruObjectToDbus(
James Feist5cb06082019-10-24 17:11:13 -0700860 std::vector<char>& device,
James Feista465ccc2019-02-08 12:51:01 -0800861 boost::container::flat_map<
862 std::pair<size_t, size_t>,
863 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700864 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800865{
866 boost::container::flat_map<std::string, std::string> formattedFru;
867 if (!formatFru(device, formattedFru))
868 {
Patrick Ventureb755c832019-08-07 11:09:14 -0700869 std::cerr << "failed to format fru for device at bus " << bus
870 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800871 return;
872 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700873
James Feist3cb5fec2018-01-23 14:41:51 -0800874 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
875 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -0700876 // Not found under Board section or an empty string.
877 if (productNameFind == formattedFru.end() ||
878 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800879 {
880 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
881 }
Patrick Venture96cdaef2019-07-30 13:30:52 -0700882 // Found under Product section and not an empty string.
883 if (productNameFind != formattedFru.end() &&
884 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -0800885 {
886 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800887 std::regex illegalObject("[^A-Za-z0-9_]");
888 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800889 }
890 else
891 {
892 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
893 UNKNOWN_BUS_OBJECT_COUNT++;
894 }
895
James Feist918e18c2018-02-13 15:51:07 -0800896 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800897 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700898 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800899 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700900 int highest = -1;
901 bool found = false;
902
James Feista465ccc2019-02-08 12:51:01 -0800903 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800904 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700905 std::string path = busIface.second->get_object_path();
906 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -0800907 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700908 if (isMuxBus(bus) && address == busIface.first.second &&
James Feist98132792019-07-09 13:29:09 -0700909 (getFruInfo(static_cast<uint8_t>(busIface.first.first),
910 static_cast<uint8_t>(busIface.first.second)) ==
911 getFruInfo(static_cast<uint8_t>(bus),
912 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -0700913 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700914 // This device is already added to the lower numbered bus,
915 // do not replicate it.
916 return;
James Feist79e9c0b2018-03-15 15:21:17 -0700917 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700918
919 // Check if the match named has extra information.
920 found = true;
921 std::smatch base_match;
922
923 bool match = std::regex_match(
924 path, base_match, std::regex(productName + "_(\\d+)$"));
925 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -0700926 {
Patrick Venture015fb0a2019-08-16 09:33:31 -0700927 if (base_match.size() == 2)
928 {
929 std::ssub_match base_sub_match = base_match[1];
930 std::string base = base_sub_match.str();
931
932 int value = std::stoi(base);
933 highest = (value > highest) ? value : highest;
934 }
James Feist79e9c0b2018-03-15 15:21:17 -0700935 }
James Feist918e18c2018-02-13 15:51:07 -0800936 }
Patrick Venture015fb0a2019-08-16 09:33:31 -0700937 } // end searching objects
938
939 if (found)
940 {
941 // We found something with the same name. If highest was still -1,
942 // it means this new entry will be _0.
943 productName += "_";
944 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -0800945 }
946 }
James Feist3cb5fec2018-01-23 14:41:51 -0800947
James Feist9eb0b582018-04-27 12:15:46 -0700948 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
949 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
950 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
951
James Feista465ccc2019-02-08 12:51:01 -0800952 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800953 {
James Feist9eb0b582018-04-27 12:15:46 -0700954
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700955 std::regex_replace(property.second.begin(), property.second.begin(),
956 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700957 if (property.second.empty())
958 {
959 continue;
960 }
961 std::string key =
962 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
963 if (!iface->register_property(key, property.second + '\0'))
964 {
965 std::cerr << "illegal key: " << key << "\n";
966 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700967 if (DEBUG)
968 {
969 std::cout << property.first << ": " << property.second << "\n";
970 }
James Feist3cb5fec2018-01-23 14:41:51 -0800971 }
James Feist2a9d6db2018-04-27 15:48:28 -0700972
973 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700974 iface->register_property("BUS", bus);
975 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700976
James Feist9eb0b582018-04-27 12:15:46 -0700977 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800978}
979
James Feista465ccc2019-02-08 12:51:01 -0800980static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800981{
982 // try to read baseboard fru from file
983 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
984 if (baseboardFruFile.good())
985 {
986 baseboardFruFile.seekg(0, std::ios_base::end);
James Feist98132792019-07-09 13:29:09 -0700987 size_t fileSize = static_cast<size_t>(baseboardFruFile.tellg());
James Feist3cb5fec2018-01-23 14:41:51 -0800988 baseboardFru.resize(fileSize);
989 baseboardFruFile.seekg(0, std::ios_base::beg);
990 baseboardFruFile.read(baseboardFru.data(), fileSize);
991 }
992 else
993 {
994 return false;
995 }
996 return true;
997}
998
James Feista465ccc2019-02-08 12:51:01 -0800999bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001000{
1001 boost::container::flat_map<std::string, std::string> tmp;
1002 if (fru.size() > MAX_FRU_SIZE)
1003 {
1004 std::cerr << "Invalid fru.size() during writeFru\n";
1005 return false;
1006 }
1007 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -08001008 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -07001009 {
1010 std::cerr << "Invalid fru format during writeFru\n";
1011 return false;
1012 }
1013 // baseboard fru
1014 if (bus == 0 && address == 0)
1015 {
1016 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1017 if (!file.good())
1018 {
1019 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1020 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001021 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001022 return false;
1023 }
James Feista465ccc2019-02-08 12:51:01 -08001024 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001025 return file.good();
1026 }
1027 else
1028 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001029 if (hasEepromFile(bus, address))
1030 {
1031 auto path = getEepromPath(bus, address);
1032 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1033 if (eeprom < 0)
1034 {
1035 std::cerr << "unable to open i2c device " << path << "\n";
1036 throw DBusInternalError();
1037 return false;
1038 }
1039
1040 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1041 if (writtenBytes < 0)
1042 {
1043 std::cerr << "unable to write to i2c device " << path << "\n";
1044 close(eeprom);
1045 throw DBusInternalError();
1046 return false;
1047 }
1048
1049 close(eeprom);
1050 return true;
1051 }
1052
James Feistb49ffc32018-05-02 11:10:43 -07001053 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1054
1055 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1056 if (file < 0)
1057 {
1058 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001059 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001060 return false;
1061 }
1062 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1063 {
1064 std::cerr << "unable to set device address\n";
1065 close(file);
James Feistddb78302018-09-06 11:45:42 -07001066 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001067 return false;
1068 }
1069
1070 constexpr const size_t RETRY_MAX = 2;
1071 uint16_t index = 0;
1072 size_t retries = RETRY_MAX;
1073 while (index < fru.size())
1074 {
1075 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1076 (retries == RETRY_MAX))
1077 {
1078 // The 4K EEPROM only uses the A2 and A1 device address bits
1079 // with the third bit being a memory page address bit.
1080 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1081 {
1082 std::cerr << "unable to set device address\n";
1083 close(file);
James Feistddb78302018-09-06 11:45:42 -07001084 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001085 return false;
1086 }
1087 }
1088
James Feist98132792019-07-09 13:29:09 -07001089 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1090 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001091 {
1092 if (!retries--)
1093 {
1094 std::cerr << "error writing fru: " << strerror(errno)
1095 << "\n";
1096 close(file);
James Feistddb78302018-09-06 11:45:42 -07001097 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001098 return false;
1099 }
1100 }
1101 else
1102 {
1103 retries = RETRY_MAX;
1104 index++;
1105 }
1106 // most eeproms require 5-10ms between writes
1107 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1108 }
1109 close(file);
1110 return true;
1111 }
1112}
1113
James Feist9eb0b582018-04-27 12:15:46 -07001114void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001115 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001116 boost::container::flat_map<
1117 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001118 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001119{
James Feist6ebf9de2018-05-15 15:01:17 -07001120 static boost::asio::deadline_timer timer(io);
1121 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001122
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001123 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001124 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001125 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001126 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001127
Nikhil Potaded8884f12019-03-27 13:27:13 -07001128 boost::container::flat_map<size_t, fs::path> busPaths;
1129 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001130 {
James Feist4131aea2018-03-09 09:47:30 -08001131 std::cerr << "unable to find i2c devices\n";
1132 return;
James Feist918e18c2018-02-13 15:51:07 -08001133 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001134
1135 for (auto busPath : busPaths)
1136 {
1137 i2cBuses.emplace_back(busPath.second);
1138 }
James Feist4131aea2018-03-09 09:47:30 -08001139
James Feist98132792019-07-09 13:29:09 -07001140 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001141 for (auto& [pair, interface] : foundDevices)
1142 {
1143 objServer.remove_interface(interface);
1144 }
1145 foundDevices.clear();
1146
James Feist5cb06082019-10-24 17:11:13 -07001147 auto scan =
1148 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001149 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001150 {
1151 objServer.remove_interface(busIface.second);
1152 }
James Feist4131aea2018-03-09 09:47:30 -08001153
James Feist6ebf9de2018-05-15 15:01:17 -07001154 dbusInterfaceMap.clear();
1155 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001156
James Feist6ebf9de2018-05-15 15:01:17 -07001157 // todo, get this from a more sensable place
1158 std::vector<char> baseboardFru;
1159 if (readBaseboardFru(baseboardFru))
1160 {
1161 boost::container::flat_map<int, std::vector<char>>
1162 baseboardDev;
1163 baseboardDev.emplace(0, baseboardFru);
James Feist98132792019-07-09 13:29:09 -07001164 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001165 }
James Feist98132792019-07-09 13:29:09 -07001166 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001167 {
James Feista465ccc2019-02-08 12:51:01 -08001168 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001169 {
James Feist5cb06082019-10-24 17:11:13 -07001170 AddFruObjectToDbus(device.second, dbusInterfaceMap,
1171 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001172 }
1173 }
1174 });
1175 scan->run();
1176 });
James Feist918e18c2018-02-13 15:51:07 -08001177}
1178
James Feist98132792019-07-09 13:29:09 -07001179int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001180{
1181 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001182 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001183 std::vector<fs::path> i2cBuses;
1184
James Feista3c180a2018-08-09 16:06:04 -07001185 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001186 {
1187 std::cerr << "unable to find i2c devices\n";
1188 return 1;
1189 }
James Feist3cb5fec2018-01-23 14:41:51 -08001190
Patrick Venture11f1ff42019-08-01 10:42:12 -07001191 // check for and load blacklist with initial buses.
1192 loadBlacklist(blacklistPath);
1193
Vijay Khemka065f6d92018-12-18 10:37:47 -08001194 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001195
James Feist6ebf9de2018-05-15 15:01:17 -07001196 // this is a map with keys of pair(bus number, address) and values of
1197 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001198 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001199 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1200 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001201
James Feist9eb0b582018-04-27 12:15:46 -07001202 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1203 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1204 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001205
James Feist5cb06082019-10-24 17:11:13 -07001206 iface->register_method("ReScan",
1207 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001208
Nikhil Potaded8884f12019-03-27 13:27:13 -07001209 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001210
1211 iface->register_method("WriteFru", [&](const uint8_t bus,
1212 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001213 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -07001214 if (!writeFru(bus, address, data))
1215 {
James Feistddb78302018-09-06 11:45:42 -07001216 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001217 return;
1218 }
1219 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001220 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001221 });
James Feist9eb0b582018-04-27 12:15:46 -07001222 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001223
James Feist9eb0b582018-04-27 12:15:46 -07001224 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001225 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001226 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001227 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001228 std::string,
1229 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001230 values;
1231 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001232 auto findState = values.find("CurrentHostState");
1233 bool on = false;
1234 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001235 {
James Feist0eeb79c2019-10-09 13:35:29 -07001236 on = boost::ends_with(std::get<std::string>(findState->second),
1237 "Running");
1238 }
James Feist6ebf9de2018-05-15 15:01:17 -07001239
James Feist0eeb79c2019-10-09 13:35:29 -07001240 if (on)
1241 {
James Feist5cb06082019-10-24 17:11:13 -07001242 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001243 }
James Feist918e18c2018-02-13 15:51:07 -08001244 };
James Feist9eb0b582018-04-27 12:15:46 -07001245
1246 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001247 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001248 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001249 "openbmc_project/state/"
1250 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001251 eventHandler);
1252
James Feist4131aea2018-03-09 09:47:30 -08001253 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001254 inotify_add_watch(fd, I2C_DEV_LOCATION,
1255 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001256 std::array<char, 4096> readBuffer;
1257 std::string pendingBuffer;
1258 // monitor for new i2c devices
1259 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1260 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001261 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001262 std::size_t bytes_transferred) {
1263 if (ec)
1264 {
1265 std::cout << "Callback Error " << ec << "\n";
1266 return;
1267 }
1268 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
1269 bool devChange = false;
1270 while (pendingBuffer.size() > sizeof(inotify_event))
1271 {
James Feista465ccc2019-02-08 12:51:01 -08001272 const inotify_event* iEvent =
1273 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001274 pendingBuffer.data());
1275 switch (iEvent->mask)
1276 {
James Feist9eb0b582018-04-27 12:15:46 -07001277 case IN_CREATE:
1278 case IN_MOVED_TO:
1279 case IN_DELETE:
1280 if (boost::starts_with(std::string(iEvent->name),
1281 "i2c"))
1282 {
1283 devChange = true;
1284 }
James Feist4131aea2018-03-09 09:47:30 -08001285 }
1286
1287 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1288 }
James Feist6ebf9de2018-05-15 15:01:17 -07001289 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -08001290 {
James Feist5cb06082019-10-24 17:11:13 -07001291 rescanBusses(busMap, dbusInterfaceMap);
James Feist4131aea2018-03-09 09:47:30 -08001292 }
James Feist6ebf9de2018-05-15 15:01:17 -07001293
James Feist4131aea2018-03-09 09:47:30 -08001294 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1295 watchI2cBusses);
1296 };
1297
1298 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001299 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001300 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001301
James Feist3cb5fec2018-01-23 14:41:51 -08001302 io.run();
1303 return 0;
1304}