blob: 2552242d8abec376a01d517f38aac9a09d793ac8 [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*/
Brad Bishop1fb9f3f2020-08-28 08:15:13 -040016/// \file FruDevice.cpp
James Feist3cb5fec2018-01-23 14:41:51 -080017
Patrick Ventureab296412020-12-30 13:39:37 -080018#include "FruUtils.hpp"
Patrick Venturea49dc332019-10-26 08:32:02 -070019#include "Utils.hpp"
20
James Feist3b860982018-10-02 14:34:07 -070021#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080022#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070023#include <sys/inotify.h>
24#include <sys/ioctl.h>
25
James Feist3b860982018-10-02 14:34:07 -070026#include <boost/algorithm/string/predicate.hpp>
Brad Bishop82c84bb2020-08-26 14:12:50 -040027#include <boost/asio/deadline_timer.hpp>
28#include <boost/asio/io_service.hpp>
James Feist3b860982018-10-02 14:34:07 -070029#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070030#include <nlohmann/json.hpp>
31#include <sdbusplus/asio/connection.hpp>
32#include <sdbusplus/asio/object_server.hpp>
33
34#include <array>
James Feist3b860982018-10-02 14:34:07 -070035#include <chrono>
36#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070037#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080038#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070039#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080040#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070041#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080042#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070043#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080044#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070045#include <set>
46#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070047#include <string>
James Feist3b860982018-10-02 14:34:07 -070048#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080049#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080050#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070051#include <vector>
James Feist3b860982018-10-02 14:34:07 -070052
James Feist8c505da2020-05-28 10:06:33 -070053extern "C"
54{
James Feist3b860982018-10-02 14:34:07 -070055#include <i2c/smbus.h>
56#include <linux/i2c-dev.h>
57}
James Feist3cb5fec2018-01-23 14:41:51 -080058
Ed Tanous072e25d2018-12-16 21:45:20 -080059namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080060static constexpr bool DEBUG = false;
61static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070062constexpr size_t MAX_FRU_SIZE = 512;
63constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070064constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080065
Patrick Venture11f1ff42019-08-01 10:42:12 -070066constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
67
James Feista465ccc2019-02-08 12:51:01 -080068const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080069 "/etc/fru/baseboard.fru.bin";
70
James Feista465ccc2019-02-08 12:51:01 -080071const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080072
Andrei Kartashevb45324a2020-10-14 17:01:47 +030073enum class resCodes
74{
75 resOK,
76 resWarn,
77 resErr
78};
79
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030080static const std::vector<std::string> FRU_AREA_NAMES = {
James Feist3cb5fec2018-01-23 14:41:51 -080081 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070082const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030083using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080084using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
85
James Feist444830e2019-04-05 08:38:16 -070086static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070087struct FindDevicesWithCallback;
88
Nikhil Potaded8884f12019-03-27 13:27:13 -070089static BusMap busMap;
90
James Feistcb5661d2020-06-12 15:05:01 -070091static bool powerIsOn = false;
92
James Feist8a983922019-10-24 17:11:56 -070093static boost::container::flat_map<
94 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
95 foundDevices;
96
James Feist7972bb92019-11-13 15:59:24 -080097static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
98
James Feist5cb06082019-10-24 17:11:13 -070099boost::asio::io_service io;
100auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
101auto objServer = sdbusplus::asio::object_server(systemBus);
102
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300103static const std::vector<std::string> CHASSIS_FRU_AREAS = {"PART_NUMBER",
104 "SERIAL_NUMBER"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530105
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300106static const std::vector<std::string> BOARD_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300107 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
108 "FRU_VERSION_ID"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530109
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300110static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300111 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
112 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID"};
113
114static const std::string FRU_CUSTOM_FIELD_NAME = "INFO_AM";
Joshi-Mansid73b7442020-03-27 19:10:21 +0530115
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300116static inline const std::string& getFruAreaName(fruAreas area)
117{
118 return FRU_AREA_NAMES[static_cast<unsigned int>(area)];
119}
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300120uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
121 std::vector<uint8_t>::const_iterator end);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300122bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530123 const std::string& assetTag, uint32_t bus, uint32_t address,
124 std::string propertyName,
125 boost::container::flat_map<
126 std::pair<size_t, size_t>,
127 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700128
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700129// Given a bus/address, produce the path in sysfs for an eeprom.
130static std::string getEepromPath(size_t bus, size_t address)
131{
132 std::stringstream output;
133 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
134 << std::setfill('0') << std::setw(4) << std::hex << address
135 << "/eeprom";
136 return output.str();
137}
138
139static bool hasEepromFile(size_t bus, size_t address)
140{
141 auto path = getEepromPath(bus, address);
142 try
143 {
144 return fs::exists(path);
145 }
146 catch (...)
147 {
148 return false;
149 }
150}
151
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700152static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800153 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700154 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700155{
156 auto result = lseek(fd, offset, SEEK_SET);
157 if (result < 0)
158 {
159 std::cerr << "failed to seek\n";
160 return -1;
161 }
162
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700163 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700164}
165
James Feist5d7f4692020-06-17 18:22:33 -0700166static int busStrToInt(const std::string& busName)
167{
168 auto findBus = busName.rfind("-");
169 if (findBus == std::string::npos)
170 {
171 return -1;
172 }
173 return std::stoi(busName.substr(findBus + 1));
174}
175
James Feist7972bb92019-11-13 15:59:24 -0800176static int getRootBus(size_t bus)
177{
178 auto ec = std::error_code();
179 auto path = std::filesystem::read_symlink(
180 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
181 std::to_string(bus) + "/mux_device"),
182 ec);
183 if (ec)
184 {
185 return -1;
186 }
187
188 std::string filename = path.filename();
189 auto findBus = filename.find("-");
190 if (findBus == std::string::npos)
191 {
192 return -1;
193 }
194 return std::stoi(filename.substr(0, findBus));
195}
196
James Feistc95cb142018-02-26 10:41:42 -0800197static bool isMuxBus(size_t bus)
198{
Ed Tanous072e25d2018-12-16 21:45:20 -0800199 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800200 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
201}
202
James Feist8a983922019-10-24 17:11:56 -0700203static void makeProbeInterface(size_t bus, size_t address)
204{
205 if (isMuxBus(bus))
206 {
207 return; // the mux buses are random, no need to publish
208 }
209 auto [it, success] = foundDevices.emplace(
210 std::make_pair(bus, address),
211 objServer.add_interface(
212 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
213 std::to_string(address),
214 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
215 if (!success)
216 {
217 return; // already added
218 }
219 it->second->register_property("Bus", bus);
220 it->second->register_property("Address", address);
221 it->second->initialize();
222}
223
Vijay Khemka2d681f62018-11-06 15:51:00 -0800224static int isDevice16Bit(int file)
225{
226 /* Get first byte */
227 int byte1 = i2c_smbus_read_byte_data(file, 0);
228 if (byte1 < 0)
229 {
230 return byte1;
231 }
232 /* Read 7 more bytes, it will read same first byte in case of
233 * 8 bit but it will read next byte in case of 16 bit
234 */
235 for (int i = 0; i < 7; i++)
236 {
237 int byte2 = i2c_smbus_read_byte_data(file, 0);
238 if (byte2 < 0)
239 {
240 return byte2;
241 }
242 if (byte2 != byte1)
243 {
244 return 1;
245 }
246 }
247 return 0;
248}
249
Xiang Liu2801a702020-01-20 14:29:34 -0800250// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
251// from_slave_buf_len bytes.
252static int i2c_smbus_write_then_read(int file, uint16_t address,
253 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
254 uint8_t* fromSlaveBuf,
255 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800256{
Xiang Liu2801a702020-01-20 14:29:34 -0800257 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
258 fromSlaveBufLen == 0)
259 {
260 return -1;
261 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800262
Xiang Liu2801a702020-01-20 14:29:34 -0800263#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
264 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
265 struct i2c_rdwr_ioctl_data rdwr;
266
267 msgs[0].addr = address;
268 msgs[0].flags = 0;
269 msgs[0].len = toSlaveBufLen;
270 msgs[0].buf = toSlaveBuf;
271 msgs[1].addr = address;
272 msgs[1].flags = I2C_M_RD;
273 msgs[1].len = fromSlaveBufLen;
274 msgs[1].buf = fromSlaveBuf;
275
276 rdwr.msgs = msgs;
277 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
278
279 int ret = ioctl(file, I2C_RDWR, &rdwr);
280
281 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
282}
283
284static int64_t readBlockData(int flag, int file, uint16_t address,
285 uint16_t offset, uint8_t len, uint8_t* buf)
286{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800287 if (flag == 0)
288 {
Xiang Liu2801a702020-01-20 14:29:34 -0800289 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
290 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800291 }
292
Xiang Liu2801a702020-01-20 14:29:34 -0800293 offset = htobe16(offset);
294 return i2c_smbus_write_then_read(
295 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800296}
297
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700298// TODO: This code is very similar to the non-eeprom version and can be merged
299// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300300static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700301{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700302 auto path = getEepromPath(bus, address);
303
304 int file = open(path.c_str(), O_RDONLY);
305 if (file < 0)
306 {
307 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700308 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700309 }
310
Patrick Venturebaba7672019-10-26 09:26:41 -0700311 std::string errorMessage = "eeprom at " + std::to_string(bus) +
312 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300313 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800314 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700315
316 close(file);
317 return device;
318}
319
320std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
321{
322 std::set<int> foundList;
323
324 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
325
326 // For each file listed under the i2c device
327 // NOTE: This should be faster than just checking for each possible address
328 // path.
329 for (const auto& p : fs::directory_iterator(path))
330 {
331 const std::string node = p.path().string();
332 std::smatch m;
333 bool found =
334 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
335
336 if (!found)
337 {
338 continue;
339 }
340 if (m.size() != 2)
341 {
342 std::cerr << "regex didn't capture\n";
343 continue;
344 }
345
346 std::ssub_match subMatch = m[1];
347 std::string addressString = subMatch.str();
348
349 std::size_t ignored;
350 const int hexBase = 16;
351 int address = std::stoi(addressString, &ignored, hexBase);
352
353 const std::string eeprom = node + "/eeprom";
354
355 try
356 {
357 if (!fs::exists(eeprom))
358 {
359 continue;
360 }
361 }
362 catch (...)
363 {
364 continue;
365 }
366
367 // There is an eeprom file at this address, it may have invalid
368 // contents, but we found it.
369 foundList.insert(address);
370
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300371 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700372 if (!device.empty())
373 {
374 devices->emplace(address, device);
375 }
376 }
377
378 return foundList;
379}
380
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300381int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700382 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800383{
James Feist3cb5fec2018-01-23 14:41:51 -0800384
James Feist26c27ad2018-07-25 15:09:40 -0700385 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700386 // NOTE: When reading the devices raw on the bus, it can interfere with
387 // the driver's ability to operate, therefore read eeproms first before
388 // scanning for devices without drivers. Several experiments were run
389 // and it was determined that if there were any devices on the bus
390 // before the eeprom was hit and read, the eeprom driver wouldn't open
391 // while the bus device was open. An experiment was not performed to see
392 // if this issue was resolved if the i2c bus device was closed, but
393 // hexdumps of the eeprom later were successful.
394
395 // Scan for i2c eeproms loaded on this bus.
396 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800397 std::set<size_t>& failedItems = failedAddresses[bus];
398
399 std::set<size_t>* rootFailures = nullptr;
400 int rootBus = getRootBus(bus);
401
402 if (rootBus >= 0)
403 {
404 rootFailures = &(failedAddresses[rootBus]);
405 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700406
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530407 constexpr int startSkipSlaveAddr = 0;
408 constexpr int endSkipSlaveAddr = 12;
409
James Feist26c27ad2018-07-25 15:09:40 -0700410 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800411 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700412 if (skipList.find(ii) != skipList.end())
413 {
414 continue;
415 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530416 // skipping since no device is present in this range
417 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
418 {
419 continue;
420 }
James Feist26c27ad2018-07-25 15:09:40 -0700421 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530422 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800423 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300424 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700425 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700426 continue;
427 }
428 // probe
429 else if (i2c_smbus_read_byte(file) < 0)
430 {
431 continue;
432 }
James Feist3cb5fec2018-01-23 14:41:51 -0800433
James Feist26c27ad2018-07-25 15:09:40 -0700434 if (DEBUG)
435 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700436 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700437 << "\n";
438 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800439
James Feist8a983922019-10-24 17:11:56 -0700440 makeProbeInterface(bus, ii);
441
James Feist7972bb92019-11-13 15:59:24 -0800442 if (failedItems.find(ii) != failedItems.end())
443 {
444 // if we failed to read it once, unlikely we can read it later
445 continue;
446 }
447
448 if (rootFailures != nullptr)
449 {
450 if (rootFailures->find(ii) != rootFailures->end())
451 {
452 continue;
453 }
454 }
455
Vijay Khemka2d681f62018-11-06 15:51:00 -0800456 /* Check for Device type if it is 8 bit or 16 bit */
457 int flag = isDevice16Bit(file);
458 if (flag < 0)
459 {
460 std::cerr << "failed to read bus " << bus << " address " << ii
461 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700462 if (powerIsOn)
463 {
464 failedItems.insert(ii);
465 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800466 continue;
467 }
468
Patrick Venturebaba7672019-10-26 09:26:41 -0700469 std::string errorMessage =
470 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300471 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300472 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800473 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700474 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700475 {
James Feist26c27ad2018-07-25 15:09:40 -0700476 continue;
477 }
James Feist26c27ad2018-07-25 15:09:40 -0700478
Patrick Venture786f1792019-08-05 16:33:44 -0700479 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800480 }
James Feist26c27ad2018-07-25 15:09:40 -0700481 return 1;
482 });
483 std::future_status status =
484 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
485 if (status == std::future_status::timeout)
486 {
487 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700488 if (powerIsOn)
489 {
490 busBlacklist.insert(bus);
491 }
James Feist444830e2019-04-05 08:38:16 -0700492 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700493 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800494 }
495
James Feist444830e2019-04-05 08:38:16 -0700496 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700497 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800498}
499
Patrick Venture11f1ff42019-08-01 10:42:12 -0700500void loadBlacklist(const char* path)
501{
502 std::ifstream blacklistStream(path);
503 if (!blacklistStream.good())
504 {
505 // File is optional.
506 std::cerr << "Cannot open blacklist file.\n\n";
507 return;
508 }
509
510 nlohmann::json data =
511 nlohmann::json::parse(blacklistStream, nullptr, false);
512 if (data.is_discarded())
513 {
514 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
515 "exiting\n";
516 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700517 }
518
519 // It's expected to have at least one field, "buses" that is an array of the
520 // buses by integer. Allow for future options to exclude further aspects,
521 // such as specific addresses or ranges.
522 if (data.type() != nlohmann::json::value_t::object)
523 {
524 std::cerr << "Illegal blacklist, expected to read dictionary\n";
525 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700526 }
527
528 // If buses field is missing, that's fine.
529 if (data.count("buses") == 1)
530 {
531 // Parse the buses array after a little validation.
532 auto buses = data.at("buses");
533 if (buses.type() != nlohmann::json::value_t::array)
534 {
535 // Buses field present but invalid, therefore this is an error.
536 std::cerr << "Invalid contents for blacklist buses field\n";
537 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700538 }
539
540 // Catch exception here for type mis-match.
541 try
542 {
543 for (const auto& bus : buses)
544 {
545 busBlacklist.insert(bus.get<size_t>());
546 }
547 }
548 catch (const nlohmann::detail::type_error& e)
549 {
550 // Type mis-match is a critical error.
551 std::cerr << "Invalid bus type: " << e.what() << "\n";
552 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700553 }
554 }
555
556 return;
557}
558
James Feista465ccc2019-02-08 12:51:01 -0800559static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700560 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800561{
James Feista465ccc2019-02-08 12:51:01 -0800562 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800563 {
James Feist5d7f4692020-06-17 18:22:33 -0700564 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800565
James Feist5d7f4692020-06-17 18:22:33 -0700566 if (bus < 0)
567 {
568 std::cerr << "Cannot translate " << i2cBus << " to int\n";
569 continue;
570 }
James Feist444830e2019-04-05 08:38:16 -0700571 if (busBlacklist.find(bus) != busBlacklist.end())
572 {
573 continue; // skip previously failed busses
574 }
James Feist3cb5fec2018-01-23 14:41:51 -0800575
James Feist0c3980a2019-12-19 11:09:27 -0800576 int rootBus = getRootBus(bus);
577 if (busBlacklist.find(rootBus) != busBlacklist.end())
578 {
579 continue;
580 }
581
James Feist3cb5fec2018-01-23 14:41:51 -0800582 auto file = open(i2cBus.c_str(), O_RDWR);
583 if (file < 0)
584 {
585 std::cerr << "unable to open i2c device " << i2cBus.string()
586 << "\n";
587 continue;
588 }
589 unsigned long funcs = 0;
590
591 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
592 {
593 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700594 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800595 << bus << "\n";
596 continue;
597 }
598 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
599 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
600 {
601 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
602 << bus << "\n";
603 continue;
604 }
James Feist98132792019-07-09 13:29:09 -0700605 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800606 device = std::make_shared<DeviceMap>();
607
Nikhil Potaded8884f12019-03-27 13:27:13 -0700608 // i2cdetect by default uses the range 0x03 to 0x77, as
609 // this is what we have tested with, use this range. Could be
610 // changed in future.
611 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800612 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700613 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800614 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700615
616 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300617 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700618
619 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800620 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700621 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800622 }
James Feist3cb5fec2018-01-23 14:41:51 -0800623 }
James Feist3cb5fec2018-01-23 14:41:51 -0800624}
625
James Feist6ebf9de2018-05-15 15:01:17 -0700626// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700627struct FindDevicesWithCallback :
628 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700629{
James Feista465ccc2019-02-08 12:51:01 -0800630 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700631 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800632 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700633 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700634 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700635 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700636 ~FindDevicesWithCallback()
637 {
638 _callback();
639 }
640 void run()
641 {
James Feist98132792019-07-09 13:29:09 -0700642 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700643 }
644
James Feista465ccc2019-02-08 12:51:01 -0800645 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800646 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700647 std::function<void(void)> _callback;
648};
649
James Feist3cb5fec2018-01-23 14:41:51 -0800650static const std::tm intelEpoch(void)
651{
James Feist98132792019-07-09 13:29:09 -0700652 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800653 val.tm_year = 1996 - 1900;
654 return val;
655}
656
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800657static char sixBitToChar(uint8_t val)
658{
659 return static_cast<char>((val & 0x3f) + ' ');
660}
661
662/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
663static const char bcdHighChars[] = {
664 ' ', '-', '.', 'X', 'X', 'X',
665};
666
667static char bcdPlusToChar(uint8_t val)
668{
669 val &= 0xf;
670 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
671}
672
673enum class DecodeState
674{
675 ok,
676 end,
677 err,
678};
679
680enum FRUDataEncoding
681{
682 binary = 0x0,
683 bcdPlus = 0x1,
684 sixBitASCII = 0x2,
685 languageDependent = 0x3,
686};
687
688/* Decode FRU data into a std::string, given an input iterator and end. If the
689 * state returned is fruDataOk, then the resulting string is the decoded FRU
690 * data. The input iterator is advanced past the data consumed.
691 *
692 * On fruDataErr, we have lost synchronisation with the length bytes, so the
693 * iterator is no longer usable.
694 */
695static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300696 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300697 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800698{
699 std::string value;
700 unsigned int i;
701
702 /* we need at least one byte to decode the type/len header */
703 if (iter == end)
704 {
705 std::cerr << "Truncated FRU data\n";
706 return make_pair(DecodeState::err, value);
707 }
708
709 uint8_t c = *(iter++);
710
711 /* 0xc1 is the end marker */
712 if (c == 0xc1)
713 {
714 return make_pair(DecodeState::end, value);
715 }
716
717 /* decode type/len byte */
718 uint8_t type = static_cast<uint8_t>(c >> 6);
719 uint8_t len = static_cast<uint8_t>(c & 0x3f);
720
721 /* we should have at least len bytes of data available overall */
722 if (iter + len > end)
723 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300724 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800725 return make_pair(DecodeState::err, value);
726 }
727
728 switch (type)
729 {
730 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300731 {
732 std::stringstream ss;
733 ss << std::hex << std::setfill('0');
734 for (i = 0; i < len; i++, iter++)
735 {
736 uint8_t val = static_cast<uint8_t>(*iter);
737 ss << std::setw(2) << static_cast<int>(val);
738 }
739 value = ss.str();
740 break;
741 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800742 case FRUDataEncoding::languageDependent:
743 /* For language-code dependent encodings, assume 8-bit ASCII */
744 value = std::string(iter, iter + len);
745 iter += len;
746 break;
747
748 case FRUDataEncoding::bcdPlus:
749 value = std::string();
750 for (i = 0; i < len; i++, iter++)
751 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300752 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800753 value.push_back(bcdPlusToChar(val >> 4));
754 value.push_back(bcdPlusToChar(val & 0xf));
755 }
756 break;
757
758 case FRUDataEncoding::sixBitASCII:
759 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300760 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800761 unsigned int accumBitLen = 0;
762 value = std::string();
763 for (i = 0; i < len; i++, iter++)
764 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300765 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800766 accumBitLen += 8;
767 while (accumBitLen >= 6)
768 {
769 value.push_back(sixBitToChar(accum & 0x3f));
770 accum >>= 6;
771 accumBitLen -= 6;
772 }
773 }
774 }
775 break;
776 }
777
778 return make_pair(DecodeState::ok, value);
779}
780
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300781static void checkLang(uint8_t lang)
782{
783 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
784 // but we don't support that.
785 if (lang && lang != 25)
786 {
787 std::cerr << "Warning: language other then English is not "
788 "supported \n";
789 }
790}
791
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300792resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
793 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800794{
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300795 resCodes ret = resCodes::resOK;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300796 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800797 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300798 std::cerr << "Error: trying to parse empty FRU \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300799 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800800 }
James Feist9eb0b582018-04-27 12:15:46 -0700801 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300802 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800803
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300804 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800805
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300806 // Don't parse Internal and Multirecord areas
807 for (fruAreas area = fruAreas::fruAreaChassis;
808 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800809 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300810
811 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
812 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800813 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300814 continue;
815 }
816 offset *= fruBlockSize;
817 std::vector<uint8_t>::const_iterator fruBytesIter =
818 fruBytes.begin() + offset;
819 if (fruBytesIter + fruBlockSize >= fruBytes.end())
820 {
821 std::cerr << "Not enough data to parse \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300822 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800823 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300824 // check for format version 1
825 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -0800826 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300827 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300828 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300829 }
830 ++fruBytesIter;
831 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
832 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
833 fruBytes.begin() + offset + fruAreaSize - 1;
834 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800835
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300836 uint8_t fruComputedChecksum =
837 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
838 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300839 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300840 std::stringstream ss;
841 ss << std::hex << std::setfill('0');
842 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
843 ss << "\tComputed checksum: 0x" << std::setw(2)
844 << static_cast<int>(fruComputedChecksum) << "\n";
845 ss << "\tThe read checksum: 0x" << std::setw(2)
846 << static_cast<int>(*fruBytesIterEndArea) << "\n";
847 std::cerr << ss.str();
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300848 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300849 }
850
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300851 switch (area)
852 {
853 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -0800854 {
855 result["CHASSIS_TYPE"] =
856 std::to_string(static_cast<int>(*fruBytesIter));
857 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300858 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300859 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800860 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300861 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -0800862 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300863 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800864 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300865 std::to_string(static_cast<int>(lang));
866 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800867 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -0800868
869 unsigned int minutes = *fruBytesIter |
870 *(fruBytesIter + 1) << 8 |
871 *(fruBytesIter + 2) << 16;
872 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700873 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800874 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700875 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800876
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700877 // Tue Nov 20 23:08:00 2018
878 char timeString[32] = {0};
879 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700880 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700881 if (bytes == 0)
882 {
883 std::cerr << "invalid time string encountered\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300884 return resCodes::resErr;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700885 }
886
887 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800888 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300889 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300890 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800891 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300892 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -0800893 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300894 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800895 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300896 std::to_string(static_cast<int>(lang));
897 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800898 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300899 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300900 break;
901 }
902 default:
903 {
904 std::cerr << "Internal error: unexpected FRU area index: "
905 << static_cast<int>(area) << " \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300906 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300907 }
908 }
909 size_t fieldIndex = 0;
910 DecodeState state;
911 do
912 {
913 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea);
914 state = res.first;
915 std::string value = res.second;
916 std::string name;
917 if (fieldIndex < fruAreaFieldNames->size())
918 {
919 name = std::string(getFruAreaName(area)) + "_" +
920 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -0800921 }
922 else
923 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300924 name =
925 std::string(getFruAreaName(area)) + "_" +
926 FRU_CUSTOM_FIELD_NAME +
927 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -0800928 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300929
930 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -0800931 {
Ed Tanous2147e672019-02-27 13:59:56 -0800932 // Strip non null characters from the end
933 value.erase(std::find_if(value.rbegin(), value.rend(),
934 [](char ch) { return ch != 0; })
935 .base(),
936 value.end());
937
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800938 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300939 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -0800940 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300941 else if (state == DecodeState::err)
942 {
943 std::cerr << "Error while parsing " << name << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300944 ret = resCodes::resWarn;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300945 // Cancel decoding if failed to parse any of mandatory
946 // fields
947 if (fieldIndex < fruAreaFieldNames->size())
948 {
949 std::cerr << "Failed to parse mandatory field \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300950 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300951 }
952 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300953 else
954 {
955 if (fieldIndex < fruAreaFieldNames->size())
956 {
957 std::cerr << "Mandatory fields absent in FRU area "
958 << getFruAreaName(area) << " after " << name
959 << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300960 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300961 }
962 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300963 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300964 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
965 {
966 uint8_t c = *fruBytesIter;
967 if (c)
968 {
969 std::cerr << "Non-zero byte after EndOfFields in FRU area "
970 << getFruAreaName(area) << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300971 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300972 break;
973 }
974 }
James Feist3cb5fec2018-01-23 14:41:51 -0800975 }
976
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300977 return ret;
James Feist3cb5fec2018-01-23 14:41:51 -0800978}
979
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300980std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -0700981{
982 auto deviceMap = busMap.find(bus);
983 if (deviceMap == busMap.end())
984 {
985 throw std::invalid_argument("Invalid Bus.");
986 }
987 auto device = deviceMap->second->find(address);
988 if (device == deviceMap->second->end())
989 {
990 throw std::invalid_argument("Invalid Address.");
991 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300992 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -0700993
994 return ret;
995}
996
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300997void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300998 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -0800999 boost::container::flat_map<
1000 std::pair<size_t, size_t>,
1001 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001002 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001003{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001004 boost::container::flat_map<std::string, std::string> formattedFRU;
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001005 resCodes res = formatFRU(device, formattedFRU);
1006 if (res == resCodes::resErr)
James Feist3cb5fec2018-01-23 14:41:51 -08001007 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001008 std::cerr << "failed to parse FRU for device at bus " << bus
Patrick Ventureb755c832019-08-07 11:09:14 -07001009 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001010 return;
1011 }
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001012 else if (res == resCodes::resWarn)
1013 {
1014 std::cerr << "there were warnings while parsing FRU for device at bus "
1015 << bus << " address " << address << "\n";
1016 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001017
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001018 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001019 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001020 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001021 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001022 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001023 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001024 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001025 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001026 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001027 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001028 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001029 {
1030 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001031 std::regex illegalObject("[^A-Za-z0-9_]");
1032 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001033 }
1034 else
1035 {
1036 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1037 UNKNOWN_BUS_OBJECT_COUNT++;
1038 }
1039
James Feist918e18c2018-02-13 15:51:07 -08001040 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001041 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001042 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001043 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001044 int highest = -1;
1045 bool found = false;
1046
James Feista465ccc2019-02-08 12:51:01 -08001047 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001048 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001049 std::string path = busIface.second->get_object_path();
1050 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001051 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001052 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001053 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001054 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001055 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001056 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001057 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001058 // This device is already added to the lower numbered bus,
1059 // do not replicate it.
1060 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001061 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001062
1063 // Check if the match named has extra information.
1064 found = true;
1065 std::smatch base_match;
1066
1067 bool match = std::regex_match(
1068 path, base_match, std::regex(productName + "_(\\d+)$"));
1069 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001070 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001071 if (base_match.size() == 2)
1072 {
1073 std::ssub_match base_sub_match = base_match[1];
1074 std::string base = base_sub_match.str();
1075
1076 int value = std::stoi(base);
1077 highest = (value > highest) ? value : highest;
1078 }
James Feist79e9c0b2018-03-15 15:21:17 -07001079 }
James Feist918e18c2018-02-13 15:51:07 -08001080 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001081 } // end searching objects
1082
1083 if (found)
1084 {
1085 // We found something with the same name. If highest was still -1,
1086 // it means this new entry will be _0.
1087 productName += "_";
1088 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001089 }
1090 }
James Feist3cb5fec2018-01-23 14:41:51 -08001091
James Feist9eb0b582018-04-27 12:15:46 -07001092 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1093 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1094 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1095
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001096 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001097 {
James Feist9eb0b582018-04-27 12:15:46 -07001098
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001099 std::regex_replace(property.second.begin(), property.second.begin(),
1100 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301101 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001102 {
1103 continue;
1104 }
1105 std::string key =
1106 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301107
1108 if (property.first == "PRODUCT_ASSET_TAG")
1109 {
1110 std::string propertyName = property.first;
1111 iface->register_property(
1112 key, property.second + '\0',
1113 [bus, address, propertyName,
1114 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1115 if (strcmp(req.c_str(), resp.c_str()))
1116 {
1117 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001118 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301119 dbusInterfaceMap))
1120 {
1121 resp = req;
1122 }
1123 else
1124 {
1125 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001126 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301127 }
1128 }
1129 return 1;
1130 });
1131 }
1132 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001133 {
1134 std::cerr << "illegal key: " << key << "\n";
1135 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001136 if (DEBUG)
1137 {
1138 std::cout << property.first << ": " << property.second << "\n";
1139 }
James Feist3cb5fec2018-01-23 14:41:51 -08001140 }
James Feist2a9d6db2018-04-27 15:48:28 -07001141
1142 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001143 iface->register_property("BUS", bus);
1144 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001145
James Feist9eb0b582018-04-27 12:15:46 -07001146 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001147}
1148
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001149static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001150{
1151 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001152 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1153 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001154 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001155 baseboardFRUFile.seekg(0, std::ios_base::end);
1156 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1157 baseboardFRU.resize(fileSize);
1158 baseboardFRUFile.seekg(0, std::ios_base::beg);
1159 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001160 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001161 }
1162 else
1163 {
1164 return false;
1165 }
1166 return true;
1167}
1168
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001169bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001170{
1171 boost::container::flat_map<std::string, std::string> tmp;
1172 if (fru.size() > MAX_FRU_SIZE)
1173 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001174 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001175 return false;
1176 }
1177 // verify legal fru by running it through fru parsing logic
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001178 if (formatFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001179 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001180 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001181 return false;
1182 }
1183 // baseboard fru
1184 if (bus == 0 && address == 0)
1185 {
1186 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1187 if (!file.good())
1188 {
1189 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1190 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001191 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001192 return false;
1193 }
James Feista465ccc2019-02-08 12:51:01 -08001194 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001195 return file.good();
1196 }
1197 else
1198 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001199 if (hasEepromFile(bus, address))
1200 {
1201 auto path = getEepromPath(bus, address);
1202 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1203 if (eeprom < 0)
1204 {
1205 std::cerr << "unable to open i2c device " << path << "\n";
1206 throw DBusInternalError();
1207 return false;
1208 }
1209
1210 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1211 if (writtenBytes < 0)
1212 {
1213 std::cerr << "unable to write to i2c device " << path << "\n";
1214 close(eeprom);
1215 throw DBusInternalError();
1216 return false;
1217 }
1218
1219 close(eeprom);
1220 return true;
1221 }
1222
James Feistb49ffc32018-05-02 11:10:43 -07001223 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1224
1225 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1226 if (file < 0)
1227 {
1228 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001229 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001230 return false;
1231 }
1232 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1233 {
1234 std::cerr << "unable to set device address\n";
1235 close(file);
James Feistddb78302018-09-06 11:45:42 -07001236 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001237 return false;
1238 }
1239
1240 constexpr const size_t RETRY_MAX = 2;
1241 uint16_t index = 0;
1242 size_t retries = RETRY_MAX;
1243 while (index < fru.size())
1244 {
1245 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1246 (retries == RETRY_MAX))
1247 {
1248 // The 4K EEPROM only uses the A2 and A1 device address bits
1249 // with the third bit being a memory page address bit.
1250 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1251 {
1252 std::cerr << "unable to set device address\n";
1253 close(file);
James Feistddb78302018-09-06 11:45:42 -07001254 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001255 return false;
1256 }
1257 }
1258
James Feist98132792019-07-09 13:29:09 -07001259 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1260 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001261 {
1262 if (!retries--)
1263 {
1264 std::cerr << "error writing fru: " << strerror(errno)
1265 << "\n";
1266 close(file);
James Feistddb78302018-09-06 11:45:42 -07001267 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001268 return false;
1269 }
1270 }
1271 else
1272 {
1273 retries = RETRY_MAX;
1274 index++;
1275 }
1276 // most eeproms require 5-10ms between writes
1277 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1278 }
1279 close(file);
1280 return true;
1281 }
1282}
1283
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001284void rescanOneBus(
1285 BusMap& busmap, uint8_t busNum,
1286 boost::container::flat_map<
1287 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001288 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1289 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001290{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001291 for (auto& [pair, interface] : foundDevices)
1292 {
1293 if (pair.first == static_cast<size_t>(busNum))
1294 {
1295 objServer.remove_interface(interface);
1296 foundDevices.erase(pair);
1297 }
1298 }
1299
James Feist5d7f4692020-06-17 18:22:33 -07001300 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1301 if (!fs::exists(busPath))
1302 {
1303 if (dbusCall)
1304 {
1305 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1306 << "\n";
1307 throw std::invalid_argument("Invalid Bus.");
1308 }
1309 return;
1310 }
1311
1312 std::vector<fs::path> i2cBuses;
1313 i2cBuses.emplace_back(busPath);
1314
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001315 auto scan = std::make_shared<FindDevicesWithCallback>(
1316 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1317 for (auto& busIface : dbusInterfaceMap)
1318 {
1319 if (busIface.first.first == static_cast<size_t>(busNum))
1320 {
1321 objServer.remove_interface(busIface.second);
1322 }
1323 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001324 auto found = busmap.find(busNum);
1325 if (found == busmap.end() || found->second == nullptr)
1326 {
1327 return;
1328 }
1329 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001330 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001331 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001332 static_cast<uint32_t>(busNum), device.first);
1333 }
1334 });
1335 scan->run();
1336}
1337
James Feist9eb0b582018-04-27 12:15:46 -07001338void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001339 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001340 boost::container::flat_map<
1341 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001342 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001343{
James Feist6ebf9de2018-05-15 15:01:17 -07001344 static boost::asio::deadline_timer timer(io);
1345 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001346
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001347 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001348 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001349 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001350 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001351
Nikhil Potaded8884f12019-03-27 13:27:13 -07001352 boost::container::flat_map<size_t, fs::path> busPaths;
1353 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001354 {
James Feist4131aea2018-03-09 09:47:30 -08001355 std::cerr << "unable to find i2c devices\n";
1356 return;
James Feist918e18c2018-02-13 15:51:07 -08001357 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001358
1359 for (auto busPath : busPaths)
1360 {
1361 i2cBuses.emplace_back(busPath.second);
1362 }
James Feist4131aea2018-03-09 09:47:30 -08001363
James Feist98132792019-07-09 13:29:09 -07001364 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001365 for (auto& [pair, interface] : foundDevices)
1366 {
1367 objServer.remove_interface(interface);
1368 }
1369 foundDevices.clear();
1370
James Feist5cb06082019-10-24 17:11:13 -07001371 auto scan =
1372 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001373 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001374 {
1375 objServer.remove_interface(busIface.second);
1376 }
James Feist4131aea2018-03-09 09:47:30 -08001377
James Feist6ebf9de2018-05-15 15:01:17 -07001378 dbusInterfaceMap.clear();
1379 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001380
James Feist6ebf9de2018-05-15 15:01:17 -07001381 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001382 std::vector<uint8_t> baseboardFRU;
1383 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001384 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001385 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001386 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001387 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001388 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001389 }
James Feist98132792019-07-09 13:29:09 -07001390 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001391 {
James Feista465ccc2019-02-08 12:51:01 -08001392 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001393 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001394 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001395 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001396 }
1397 }
1398 });
1399 scan->run();
1400 });
James Feist918e18c2018-02-13 15:51:07 -08001401}
1402
Joshi-Mansid73b7442020-03-27 19:10:21 +05301403// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001404uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1405 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301406{
1407 constexpr int checksumMod = 256;
1408 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001409 int sum = std::accumulate(iter, end, 0);
1410 int checksum = (checksumMod - sum) & modVal;
1411 return static_cast<uint8_t>(checksum);
1412}
1413uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1414{
1415 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301416}
1417
1418// Update new fru area length &
1419// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001420// Return the offset of the area checksum byte
1421static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1422 size_t fruAreaStart,
1423 size_t fruAreaEndOfFieldsOffset,
1424 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301425{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001426 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301427
1428 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001429 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1430 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301431
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001432 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301433 size_t checksumLoc;
1434 if (!mod)
1435 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001436 traverseFRUAreaIndex += (fruBlockSize);
1437 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301438 }
1439 else
1440 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001441 traverseFRUAreaIndex += (fruBlockSize - mod);
1442 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301443 }
1444
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001445 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1446 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1447 size_t fruAreaLengthLoc = fruAreaStart + 1;
1448 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301449
1450 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001451 std::vector<uint8_t> finalFRUData;
1452 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1453 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301454
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001455 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001456 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301457}
1458
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001459static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301460{
1461 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001462 constexpr uint8_t endOfFields = 0xC1;
1463 if (fruFieldTypeLenValue == endOfFields)
1464 {
1465 return -1;
1466 }
1467 else
1468 {
1469 return fruFieldTypeLenValue & typeLenMask;
1470 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301471}
1472
1473// Details with example of Asset Tag Update
1474// To find location of Product Info Area asset tag as per FRU specification
1475// 1. Find product Info area starting offset (*8 - as header will be in
1476// multiple of 8 bytes).
1477// 2. Skip 3 bytes of product info area (like format version, area length,
1478// and language code).
1479// 3. Traverse manufacturer name, product name, product version, & product
1480// serial number, by reading type/length code to reach the Asset Tag.
1481// 4. Update the Asset Tag, reposition the product Info area in multiple of
1482// 8 bytes. Update the Product area length and checksum.
1483
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001484bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301485 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1486 std::string propertyName,
1487 boost::container::flat_map<
1488 std::pair<size_t, size_t>,
1489 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1490{
1491 size_t updatePropertyReqLen = updatePropertyReq.length();
1492 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1493 {
1494 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001495 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301496 "Invalid Length "
1497 << updatePropertyReqLen << "\n";
1498 return false;
1499 }
1500
1501 std::vector<uint8_t> fruData;
1502 try
1503 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001504 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301505 static_cast<uint8_t>(address));
1506 }
1507 catch (std::invalid_argument& e)
1508 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001509 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301510 return false;
1511 }
1512
1513 if (fruData.empty())
1514 {
1515 return false;
1516 }
1517
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001518 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301519
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001520 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301521 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001522 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001523 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001524 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1525 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301526 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001527 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001528 << " \n";
1529 return false;
1530 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001531 fruAreas fruAreaToUpdate =
1532 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1533 fruAreaOffsetFieldValue =
1534 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1535 switch (fruAreaToUpdate)
1536 {
1537 case fruAreas::fruAreaChassis:
1538 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1539 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1540 break;
1541 case fruAreas::fruAreaBoard:
1542 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1543 fruAreaFieldNames = &BOARD_FRU_AREAS;
1544 break;
1545 case fruAreas::fruAreaProduct:
1546 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1547 // i.e. version, area length and language code
1548 offset = 3;
1549 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1550 break;
1551 default:
1552 std::cerr << "Don't know how to handle property " << propertyName
1553 << " \n";
1554 return false;
1555 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001556 if (fruAreaOffsetFieldValue == 0)
1557 {
1558 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301559 return false;
1560 }
1561
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001562 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001563 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1564 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001565 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001566 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001567 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001568 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301569
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001570 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001571 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301572 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001573 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001574 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301575 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001576 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301577 break;
1578 }
1579 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001580 if (!found)
1581 {
1582 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1583 if (pos == std::string::npos)
1584 {
1585 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1586 << propertyName << "\n";
1587 return false;
1588 }
1589 std::string fieldNumStr =
1590 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1591 size_t fieldNum = std::stoi(fieldNumStr);
1592 if (fieldNum == 0)
1593 {
1594 std::cerr << "PropertyName not recognized: " << propertyName
1595 << "\n";
1596 return false;
1597 }
1598 skipToFRUUpdateField += fieldNum;
1599 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301600
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001601 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301602 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001603 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001604 if (fieldLength < 0)
1605 {
1606 break;
1607 }
1608 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301609 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001610 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301611
1612 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001613 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001614 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301615 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001616 std::cerr << "Property " << propertyName << " not present \n";
1617 return false;
1618 }
1619 fruDataIter += 1 + fieldLength;
1620 size_t restFRUFieldsLoc = fruDataIter;
1621 size_t endOfFieldsLoc = 0;
1622 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1623 {
1624 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301625 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001626 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301627 break;
1628 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001629 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301630 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001631 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301632
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001633 std::vector<uint8_t> restFRUAreaFieldsData;
1634 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001635 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001636 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301637
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001638 // Push post update fru areas if any
1639 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001640 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1641 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001642 {
1643 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001644 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001645 if ((fruAreaLoc > endOfFieldsLoc) &&
1646 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1647 {
1648 nextFRUAreaLoc = fruAreaLoc;
1649 }
1650 }
1651 std::vector<uint8_t> restFRUAreasData;
1652 if (nextFRUAreaLoc)
1653 {
1654 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1655 fruData.size() - nextFRUAreaLoc,
1656 std::back_inserter(restFRUAreasData));
1657 }
1658
1659 // check FRU area size
1660 size_t fruAreaDataSize =
1661 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1662 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1663 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1664 {
1665
1666#ifdef ENABLE_FRU_AREA_RESIZE
1667 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1668 // round size to 8-byte blocks
1669 newFRUAreaSize =
1670 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1671 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1672 fruData.resize(newFRUDataSize);
1673 fruAreaSize = newFRUAreaSize;
1674 fruAreaEnd = fruAreaStart + fruAreaSize;
1675#else
1676 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1677 << " should not be greater than available FRU area size: "
1678 << fruAreaAvailableSize << "\n";
1679 return false;
1680#endif // ENABLE_FRU_AREA_RESIZE
1681 }
1682
Joshi-Mansid73b7442020-03-27 19:10:21 +05301683 // write new requested property field length and data
1684 constexpr uint8_t newTypeLenMask = 0xC0;
1685 fruData[fruUpdateFieldLoc] =
1686 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1687 fruUpdateFieldLoc++;
1688 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1689 fruData.begin() + fruUpdateFieldLoc);
1690
1691 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001692 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1693 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001694 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1695 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301696
1697 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001698 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1699 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301700
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001701#ifdef ENABLE_FRU_AREA_RESIZE
1702 ++nextFRUAreaNewLoc;
1703 ssize_t nextFRUAreaOffsetDiff =
1704 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1705 // Append rest FRU Areas if size changed and there were other sections after
1706 // updated one
1707 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1708 {
1709 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1710 fruData.begin() + nextFRUAreaNewLoc);
1711 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001712 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1713 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001714 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001715 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001716 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1717 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1718 {
1719 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1720 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1721 }
1722 }
1723 // Calculate new checksum
1724 std::vector<uint8_t> headerFRUData;
1725 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1726 size_t checksumVal = calculateChecksum(headerFRUData);
1727 fruData[7] = static_cast<uint8_t>(checksumVal);
1728 // fill zeros if FRU Area size decreased
1729 if (nextFRUAreaOffsetDiff < 0)
1730 {
1731 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1732 restFRUAreasData.size(),
1733 fruData.end(), 0);
1734 }
1735 }
1736#else
1737 // this is to avoid "unused variable" warning
1738 (void)nextFRUAreaNewLoc;
1739#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301740 if (fruData.empty())
1741 {
1742 return false;
1743 }
1744
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001745 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301746 fruData))
1747 {
1748 return false;
1749 }
1750
1751 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1752 rescanBusses(busMap, dbusInterfaceMap);
1753 return true;
1754}
1755
James Feist98132792019-07-09 13:29:09 -07001756int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001757{
1758 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001759 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001760 std::vector<fs::path> i2cBuses;
1761
James Feista3c180a2018-08-09 16:06:04 -07001762 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001763 {
1764 std::cerr << "unable to find i2c devices\n";
1765 return 1;
1766 }
James Feist3cb5fec2018-01-23 14:41:51 -08001767
Patrick Venture11f1ff42019-08-01 10:42:12 -07001768 // check for and load blacklist with initial buses.
1769 loadBlacklist(blacklistPath);
1770
Vijay Khemka065f6d92018-12-18 10:37:47 -08001771 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001772
James Feist6ebf9de2018-05-15 15:01:17 -07001773 // this is a map with keys of pair(bus number, address) and values of
1774 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001775 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001776 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1777 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001778
James Feist9eb0b582018-04-27 12:15:46 -07001779 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1780 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1781 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001782
James Feist5cb06082019-10-24 17:11:13 -07001783 iface->register_method("ReScan",
1784 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001785
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001786 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001787 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001788 });
1789
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001790 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001791
1792 iface->register_method("WriteFru", [&](const uint8_t bus,
1793 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001794 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001795 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001796 {
James Feistddb78302018-09-06 11:45:42 -07001797 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001798 return;
1799 }
1800 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001801 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001802 });
James Feist9eb0b582018-04-27 12:15:46 -07001803 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001804
James Feist9eb0b582018-04-27 12:15:46 -07001805 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001806 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001807 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001808 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001809 std::string,
1810 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001811 values;
1812 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001813 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001814 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001815 {
James Feistcb5661d2020-06-12 15:05:01 -07001816 powerIsOn = boost::ends_with(
1817 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001818 }
James Feist6ebf9de2018-05-15 15:01:17 -07001819
James Feistcb5661d2020-06-12 15:05:01 -07001820 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001821 {
James Feist5cb06082019-10-24 17:11:13 -07001822 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001823 }
James Feist918e18c2018-02-13 15:51:07 -08001824 };
James Feist9eb0b582018-04-27 12:15:46 -07001825
1826 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001827 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001828 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001829 "openbmc_project/state/"
1830 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001831 eventHandler);
1832
James Feist4131aea2018-03-09 09:47:30 -08001833 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001834 inotify_add_watch(fd, I2C_DEV_LOCATION,
1835 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001836 std::array<char, 4096> readBuffer;
1837 std::string pendingBuffer;
1838 // monitor for new i2c devices
1839 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1840 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001841 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001842 std::size_t bytes_transferred) {
1843 if (ec)
1844 {
1845 std::cout << "Callback Error " << ec << "\n";
1846 return;
1847 }
1848 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001849 while (pendingBuffer.size() > sizeof(inotify_event))
1850 {
James Feista465ccc2019-02-08 12:51:01 -08001851 const inotify_event* iEvent =
1852 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001853 pendingBuffer.data());
1854 switch (iEvent->mask)
1855 {
James Feist9eb0b582018-04-27 12:15:46 -07001856 case IN_CREATE:
1857 case IN_MOVED_TO:
1858 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001859 std::string name(iEvent->name);
1860 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001861 {
James Feist5d7f4692020-06-17 18:22:33 -07001862 int bus = busStrToInt(name);
1863 if (bus < 0)
1864 {
1865 std::cerr << "Could not parse bus " << name
1866 << "\n";
1867 continue;
1868 }
1869 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1870 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001871 }
James Feist4131aea2018-03-09 09:47:30 -08001872 }
1873
1874 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1875 }
James Feist6ebf9de2018-05-15 15:01:17 -07001876
James Feist4131aea2018-03-09 09:47:30 -08001877 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1878 watchI2cBusses);
1879 };
1880
1881 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001882 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001883 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001884
James Feist3cb5fec2018-01-23 14:41:51 -08001885 io.run();
1886 return 0;
1887}