blob: 0b2f9fa65c6ce42be149f4d876f645319a12784f [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 Kartashev2a7e3952020-09-02 20:32:26 +0300116uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
117 std::vector<uint8_t>::const_iterator end);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300118bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530119 const std::string& assetTag, uint32_t bus, uint32_t address,
120 std::string propertyName,
121 boost::container::flat_map<
122 std::pair<size_t, size_t>,
123 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700124
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700125// Given a bus/address, produce the path in sysfs for an eeprom.
126static std::string getEepromPath(size_t bus, size_t address)
127{
128 std::stringstream output;
129 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
130 << std::setfill('0') << std::setw(4) << std::hex << address
131 << "/eeprom";
132 return output.str();
133}
134
135static bool hasEepromFile(size_t bus, size_t address)
136{
137 auto path = getEepromPath(bus, address);
138 try
139 {
140 return fs::exists(path);
141 }
142 catch (...)
143 {
144 return false;
145 }
146}
147
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700148static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800149 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700150 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700151{
152 auto result = lseek(fd, offset, SEEK_SET);
153 if (result < 0)
154 {
155 std::cerr << "failed to seek\n";
156 return -1;
157 }
158
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700159 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700160}
161
James Feist5d7f4692020-06-17 18:22:33 -0700162static int busStrToInt(const std::string& busName)
163{
164 auto findBus = busName.rfind("-");
165 if (findBus == std::string::npos)
166 {
167 return -1;
168 }
169 return std::stoi(busName.substr(findBus + 1));
170}
171
James Feist7972bb92019-11-13 15:59:24 -0800172static int getRootBus(size_t bus)
173{
174 auto ec = std::error_code();
175 auto path = std::filesystem::read_symlink(
176 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
177 std::to_string(bus) + "/mux_device"),
178 ec);
179 if (ec)
180 {
181 return -1;
182 }
183
184 std::string filename = path.filename();
185 auto findBus = filename.find("-");
186 if (findBus == std::string::npos)
187 {
188 return -1;
189 }
190 return std::stoi(filename.substr(0, findBus));
191}
192
James Feistc95cb142018-02-26 10:41:42 -0800193static bool isMuxBus(size_t bus)
194{
Ed Tanous072e25d2018-12-16 21:45:20 -0800195 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800196 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
197}
198
James Feist8a983922019-10-24 17:11:56 -0700199static void makeProbeInterface(size_t bus, size_t address)
200{
201 if (isMuxBus(bus))
202 {
203 return; // the mux buses are random, no need to publish
204 }
205 auto [it, success] = foundDevices.emplace(
206 std::make_pair(bus, address),
207 objServer.add_interface(
208 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
209 std::to_string(address),
210 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
211 if (!success)
212 {
213 return; // already added
214 }
215 it->second->register_property("Bus", bus);
216 it->second->register_property("Address", address);
217 it->second->initialize();
218}
219
Vijay Khemka2d681f62018-11-06 15:51:00 -0800220static int isDevice16Bit(int file)
221{
222 /* Get first byte */
223 int byte1 = i2c_smbus_read_byte_data(file, 0);
224 if (byte1 < 0)
225 {
226 return byte1;
227 }
228 /* Read 7 more bytes, it will read same first byte in case of
229 * 8 bit but it will read next byte in case of 16 bit
230 */
231 for (int i = 0; i < 7; i++)
232 {
233 int byte2 = i2c_smbus_read_byte_data(file, 0);
234 if (byte2 < 0)
235 {
236 return byte2;
237 }
238 if (byte2 != byte1)
239 {
240 return 1;
241 }
242 }
243 return 0;
244}
245
Xiang Liu2801a702020-01-20 14:29:34 -0800246// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
247// from_slave_buf_len bytes.
248static int i2c_smbus_write_then_read(int file, uint16_t address,
249 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
250 uint8_t* fromSlaveBuf,
251 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800252{
Xiang Liu2801a702020-01-20 14:29:34 -0800253 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
254 fromSlaveBufLen == 0)
255 {
256 return -1;
257 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800258
Xiang Liu2801a702020-01-20 14:29:34 -0800259#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
260 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
261 struct i2c_rdwr_ioctl_data rdwr;
262
263 msgs[0].addr = address;
264 msgs[0].flags = 0;
265 msgs[0].len = toSlaveBufLen;
266 msgs[0].buf = toSlaveBuf;
267 msgs[1].addr = address;
268 msgs[1].flags = I2C_M_RD;
269 msgs[1].len = fromSlaveBufLen;
270 msgs[1].buf = fromSlaveBuf;
271
272 rdwr.msgs = msgs;
273 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
274
275 int ret = ioctl(file, I2C_RDWR, &rdwr);
276
277 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
278}
279
280static int64_t readBlockData(int flag, int file, uint16_t address,
281 uint16_t offset, uint8_t len, uint8_t* buf)
282{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800283 if (flag == 0)
284 {
Xiang Liu2801a702020-01-20 14:29:34 -0800285 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
286 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800287 }
288
Xiang Liu2801a702020-01-20 14:29:34 -0800289 offset = htobe16(offset);
290 return i2c_smbus_write_then_read(
291 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800292}
293
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700294// TODO: This code is very similar to the non-eeprom version and can be merged
295// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300296static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700297{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700298 auto path = getEepromPath(bus, address);
299
300 int file = open(path.c_str(), O_RDONLY);
301 if (file < 0)
302 {
303 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700304 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700305 }
306
Patrick Venturebaba7672019-10-26 09:26:41 -0700307 std::string errorMessage = "eeprom at " + std::to_string(bus) +
308 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300309 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800310 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700311
312 close(file);
313 return device;
314}
315
316std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
317{
318 std::set<int> foundList;
319
320 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
321
322 // For each file listed under the i2c device
323 // NOTE: This should be faster than just checking for each possible address
324 // path.
325 for (const auto& p : fs::directory_iterator(path))
326 {
327 const std::string node = p.path().string();
328 std::smatch m;
329 bool found =
330 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
331
332 if (!found)
333 {
334 continue;
335 }
336 if (m.size() != 2)
337 {
338 std::cerr << "regex didn't capture\n";
339 continue;
340 }
341
342 std::ssub_match subMatch = m[1];
343 std::string addressString = subMatch.str();
344
345 std::size_t ignored;
346 const int hexBase = 16;
347 int address = std::stoi(addressString, &ignored, hexBase);
348
349 const std::string eeprom = node + "/eeprom";
350
351 try
352 {
353 if (!fs::exists(eeprom))
354 {
355 continue;
356 }
357 }
358 catch (...)
359 {
360 continue;
361 }
362
363 // There is an eeprom file at this address, it may have invalid
364 // contents, but we found it.
365 foundList.insert(address);
366
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300367 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700368 if (!device.empty())
369 {
370 devices->emplace(address, device);
371 }
372 }
373
374 return foundList;
375}
376
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300377int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700378 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800379{
James Feist3cb5fec2018-01-23 14:41:51 -0800380
James Feist26c27ad2018-07-25 15:09:40 -0700381 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700382 // NOTE: When reading the devices raw on the bus, it can interfere with
383 // the driver's ability to operate, therefore read eeproms first before
384 // scanning for devices without drivers. Several experiments were run
385 // and it was determined that if there were any devices on the bus
386 // before the eeprom was hit and read, the eeprom driver wouldn't open
387 // while the bus device was open. An experiment was not performed to see
388 // if this issue was resolved if the i2c bus device was closed, but
389 // hexdumps of the eeprom later were successful.
390
391 // Scan for i2c eeproms loaded on this bus.
392 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800393 std::set<size_t>& failedItems = failedAddresses[bus];
394
395 std::set<size_t>* rootFailures = nullptr;
396 int rootBus = getRootBus(bus);
397
398 if (rootBus >= 0)
399 {
400 rootFailures = &(failedAddresses[rootBus]);
401 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700402
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530403 constexpr int startSkipSlaveAddr = 0;
404 constexpr int endSkipSlaveAddr = 12;
405
James Feist26c27ad2018-07-25 15:09:40 -0700406 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800407 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700408 if (skipList.find(ii) != skipList.end())
409 {
410 continue;
411 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530412 // skipping since no device is present in this range
413 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
414 {
415 continue;
416 }
James Feist26c27ad2018-07-25 15:09:40 -0700417 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530418 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800419 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300420 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700421 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700422 continue;
423 }
424 // probe
425 else if (i2c_smbus_read_byte(file) < 0)
426 {
427 continue;
428 }
James Feist3cb5fec2018-01-23 14:41:51 -0800429
James Feist26c27ad2018-07-25 15:09:40 -0700430 if (DEBUG)
431 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700432 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700433 << "\n";
434 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800435
James Feist8a983922019-10-24 17:11:56 -0700436 makeProbeInterface(bus, ii);
437
James Feist7972bb92019-11-13 15:59:24 -0800438 if (failedItems.find(ii) != failedItems.end())
439 {
440 // if we failed to read it once, unlikely we can read it later
441 continue;
442 }
443
444 if (rootFailures != nullptr)
445 {
446 if (rootFailures->find(ii) != rootFailures->end())
447 {
448 continue;
449 }
450 }
451
Vijay Khemka2d681f62018-11-06 15:51:00 -0800452 /* Check for Device type if it is 8 bit or 16 bit */
453 int flag = isDevice16Bit(file);
454 if (flag < 0)
455 {
456 std::cerr << "failed to read bus " << bus << " address " << ii
457 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700458 if (powerIsOn)
459 {
460 failedItems.insert(ii);
461 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800462 continue;
463 }
464
Patrick Venturebaba7672019-10-26 09:26:41 -0700465 std::string errorMessage =
466 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300467 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300468 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800469 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700470 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700471 {
James Feist26c27ad2018-07-25 15:09:40 -0700472 continue;
473 }
James Feist26c27ad2018-07-25 15:09:40 -0700474
Patrick Venture786f1792019-08-05 16:33:44 -0700475 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800476 }
James Feist26c27ad2018-07-25 15:09:40 -0700477 return 1;
478 });
479 std::future_status status =
480 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
481 if (status == std::future_status::timeout)
482 {
483 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700484 if (powerIsOn)
485 {
486 busBlacklist.insert(bus);
487 }
James Feist444830e2019-04-05 08:38:16 -0700488 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700489 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800490 }
491
James Feist444830e2019-04-05 08:38:16 -0700492 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700493 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800494}
495
Patrick Venture11f1ff42019-08-01 10:42:12 -0700496void loadBlacklist(const char* path)
497{
498 std::ifstream blacklistStream(path);
499 if (!blacklistStream.good())
500 {
501 // File is optional.
502 std::cerr << "Cannot open blacklist file.\n\n";
503 return;
504 }
505
506 nlohmann::json data =
507 nlohmann::json::parse(blacklistStream, nullptr, false);
508 if (data.is_discarded())
509 {
510 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
511 "exiting\n";
512 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700513 }
514
515 // It's expected to have at least one field, "buses" that is an array of the
516 // buses by integer. Allow for future options to exclude further aspects,
517 // such as specific addresses or ranges.
518 if (data.type() != nlohmann::json::value_t::object)
519 {
520 std::cerr << "Illegal blacklist, expected to read dictionary\n";
521 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700522 }
523
524 // If buses field is missing, that's fine.
525 if (data.count("buses") == 1)
526 {
527 // Parse the buses array after a little validation.
528 auto buses = data.at("buses");
529 if (buses.type() != nlohmann::json::value_t::array)
530 {
531 // Buses field present but invalid, therefore this is an error.
532 std::cerr << "Invalid contents for blacklist buses field\n";
533 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700534 }
535
536 // Catch exception here for type mis-match.
537 try
538 {
539 for (const auto& bus : buses)
540 {
541 busBlacklist.insert(bus.get<size_t>());
542 }
543 }
544 catch (const nlohmann::detail::type_error& e)
545 {
546 // Type mis-match is a critical error.
547 std::cerr << "Invalid bus type: " << e.what() << "\n";
548 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700549 }
550 }
551
552 return;
553}
554
James Feista465ccc2019-02-08 12:51:01 -0800555static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700556 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800557{
James Feista465ccc2019-02-08 12:51:01 -0800558 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800559 {
James Feist5d7f4692020-06-17 18:22:33 -0700560 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800561
James Feist5d7f4692020-06-17 18:22:33 -0700562 if (bus < 0)
563 {
564 std::cerr << "Cannot translate " << i2cBus << " to int\n";
565 continue;
566 }
James Feist444830e2019-04-05 08:38:16 -0700567 if (busBlacklist.find(bus) != busBlacklist.end())
568 {
569 continue; // skip previously failed busses
570 }
James Feist3cb5fec2018-01-23 14:41:51 -0800571
James Feist0c3980a2019-12-19 11:09:27 -0800572 int rootBus = getRootBus(bus);
573 if (busBlacklist.find(rootBus) != busBlacklist.end())
574 {
575 continue;
576 }
577
James Feist3cb5fec2018-01-23 14:41:51 -0800578 auto file = open(i2cBus.c_str(), O_RDWR);
579 if (file < 0)
580 {
581 std::cerr << "unable to open i2c device " << i2cBus.string()
582 << "\n";
583 continue;
584 }
585 unsigned long funcs = 0;
586
587 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
588 {
589 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700590 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800591 << bus << "\n";
592 continue;
593 }
594 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
595 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
596 {
597 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
598 << bus << "\n";
599 continue;
600 }
James Feist98132792019-07-09 13:29:09 -0700601 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800602 device = std::make_shared<DeviceMap>();
603
Nikhil Potaded8884f12019-03-27 13:27:13 -0700604 // i2cdetect by default uses the range 0x03 to 0x77, as
605 // this is what we have tested with, use this range. Could be
606 // changed in future.
607 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800608 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700609 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800610 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700611
612 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300613 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700614
615 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800616 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700617 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800618 }
James Feist3cb5fec2018-01-23 14:41:51 -0800619 }
James Feist3cb5fec2018-01-23 14:41:51 -0800620}
621
James Feist6ebf9de2018-05-15 15:01:17 -0700622// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700623struct FindDevicesWithCallback :
624 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700625{
James Feista465ccc2019-02-08 12:51:01 -0800626 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700627 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800628 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700629 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700630 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700631 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700632 ~FindDevicesWithCallback()
633 {
634 _callback();
635 }
636 void run()
637 {
James Feist98132792019-07-09 13:29:09 -0700638 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700639 }
640
James Feista465ccc2019-02-08 12:51:01 -0800641 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800642 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700643 std::function<void(void)> _callback;
644};
645
James Feist3cb5fec2018-01-23 14:41:51 -0800646static const std::tm intelEpoch(void)
647{
James Feist98132792019-07-09 13:29:09 -0700648 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800649 val.tm_year = 1996 - 1900;
650 return val;
651}
652
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800653static char sixBitToChar(uint8_t val)
654{
655 return static_cast<char>((val & 0x3f) + ' ');
656}
657
658/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
659static const char bcdHighChars[] = {
660 ' ', '-', '.', 'X', 'X', 'X',
661};
662
663static char bcdPlusToChar(uint8_t val)
664{
665 val &= 0xf;
666 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
667}
668
669enum class DecodeState
670{
671 ok,
672 end,
673 err,
674};
675
676enum FRUDataEncoding
677{
678 binary = 0x0,
679 bcdPlus = 0x1,
680 sixBitASCII = 0x2,
681 languageDependent = 0x3,
682};
683
684/* Decode FRU data into a std::string, given an input iterator and end. If the
685 * state returned is fruDataOk, then the resulting string is the decoded FRU
686 * data. The input iterator is advanced past the data consumed.
687 *
688 * On fruDataErr, we have lost synchronisation with the length bytes, so the
689 * iterator is no longer usable.
690 */
691static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300692 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Vijay Khemka2a967082021-01-22 15:53:31 -0800693 const std::vector<uint8_t>::const_iterator& end,
694 bool isLangEng)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800695{
696 std::string value;
697 unsigned int i;
698
699 /* we need at least one byte to decode the type/len header */
700 if (iter == end)
701 {
702 std::cerr << "Truncated FRU data\n";
703 return make_pair(DecodeState::err, value);
704 }
705
706 uint8_t c = *(iter++);
707
708 /* 0xc1 is the end marker */
709 if (c == 0xc1)
710 {
711 return make_pair(DecodeState::end, value);
712 }
713
714 /* decode type/len byte */
715 uint8_t type = static_cast<uint8_t>(c >> 6);
716 uint8_t len = static_cast<uint8_t>(c & 0x3f);
717
718 /* we should have at least len bytes of data available overall */
719 if (iter + len > end)
720 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300721 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800722 return make_pair(DecodeState::err, value);
723 }
724
725 switch (type)
726 {
727 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300728 {
729 std::stringstream ss;
730 ss << std::hex << std::setfill('0');
731 for (i = 0; i < len; i++, iter++)
732 {
733 uint8_t val = static_cast<uint8_t>(*iter);
734 ss << std::setw(2) << static_cast<int>(val);
735 }
736 value = ss.str();
737 break;
738 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800739 case FRUDataEncoding::languageDependent:
740 /* For language-code dependent encodings, assume 8-bit ASCII */
741 value = std::string(iter, iter + len);
742 iter += len;
Vijay Khemka2a967082021-01-22 15:53:31 -0800743
744 /* English text is encoded in 8-bit ASCII + Latin 1. All other
745 * languages are required to use 2-byte unicode. FruDevice does not
746 * handle unicode.
747 */
748 if (!isLangEng)
749 {
750 std::cerr << "Error: Non english string is not supported \n";
751 return make_pair(DecodeState::err, value);
752 }
753
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800754 break;
755
756 case FRUDataEncoding::bcdPlus:
757 value = std::string();
758 for (i = 0; i < len; i++, iter++)
759 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300760 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800761 value.push_back(bcdPlusToChar(val >> 4));
762 value.push_back(bcdPlusToChar(val & 0xf));
763 }
764 break;
765
766 case FRUDataEncoding::sixBitASCII:
767 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300768 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800769 unsigned int accumBitLen = 0;
770 value = std::string();
771 for (i = 0; i < len; i++, iter++)
772 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300773 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800774 accumBitLen += 8;
775 while (accumBitLen >= 6)
776 {
777 value.push_back(sixBitToChar(accum & 0x3f));
778 accum >>= 6;
779 accumBitLen -= 6;
780 }
781 }
782 }
783 break;
784 }
785
786 return make_pair(DecodeState::ok, value);
787}
788
Vijay Khemka2a967082021-01-22 15:53:31 -0800789static bool checkLangEng(uint8_t lang)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300790{
791 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
792 // but we don't support that.
793 if (lang && lang != 25)
794 {
Vijay Khemka2a967082021-01-22 15:53:31 -0800795 std::cerr << "Warning: languages other than English is not "
796 "supported\n";
797 // Return language flag as non english
798 return false;
799 }
800 else
801 {
802 return true;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300803 }
804}
805
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300806resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
807 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800808{
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300809 resCodes ret = resCodes::resOK;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300810 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800811 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300812 std::cerr << "Error: trying to parse empty FRU \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300813 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800814 }
James Feist9eb0b582018-04-27 12:15:46 -0700815 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300816 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800817
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300818 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800819
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300820 // Don't parse Internal and Multirecord areas
821 for (fruAreas area = fruAreas::fruAreaChassis;
822 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800823 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300824
825 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
826 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800827 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300828 continue;
829 }
830 offset *= fruBlockSize;
831 std::vector<uint8_t>::const_iterator fruBytesIter =
832 fruBytes.begin() + offset;
833 if (fruBytesIter + fruBlockSize >= fruBytes.end())
834 {
835 std::cerr << "Not enough data to parse \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300836 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800837 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300838 // check for format version 1
839 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -0800840 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300841 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300842 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300843 }
844 ++fruBytesIter;
Vijay Khemka02618f02021-01-20 11:10:28 -0800845
846 /* Verify other area offset for overlap with current area by passing
847 * length of current area offset pointed by *fruBytesIter
848 */
849 if (!verifyOffset(fruBytes, area, *fruBytesIter))
850 {
851 return resCodes::resErr;
852 }
853
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300854 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
855 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
856 fruBytes.begin() + offset + fruAreaSize - 1;
857 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800858
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300859 uint8_t fruComputedChecksum =
860 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
861 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300862 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300863 std::stringstream ss;
864 ss << std::hex << std::setfill('0');
865 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
866 ss << "\tComputed checksum: 0x" << std::setw(2)
867 << static_cast<int>(fruComputedChecksum) << "\n";
868 ss << "\tThe read checksum: 0x" << std::setw(2)
869 << static_cast<int>(*fruBytesIterEndArea) << "\n";
870 std::cerr << ss.str();
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300871 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300872 }
873
Vijay Khemka2a967082021-01-22 15:53:31 -0800874 /* Set default language flag to true as Chassis Fru area are always
875 * encoded in English defined in Section 10 of Fru specification
876 */
877 bool isLangEng = true;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300878 switch (area)
879 {
880 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -0800881 {
882 result["CHASSIS_TYPE"] =
883 std::to_string(static_cast<int>(*fruBytesIter));
884 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300885 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300886 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800887 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300888 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -0800889 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300890 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800891 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300892 std::to_string(static_cast<int>(lang));
Vijay Khemka2a967082021-01-22 15:53:31 -0800893 isLangEng = checkLangEng(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800894 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -0800895
896 unsigned int minutes = *fruBytesIter |
897 *(fruBytesIter + 1) << 8 |
898 *(fruBytesIter + 2) << 16;
899 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700900 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800901 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700902 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800903
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700904 // Tue Nov 20 23:08:00 2018
905 char timeString[32] = {0};
906 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700907 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700908 if (bytes == 0)
909 {
910 std::cerr << "invalid time string encountered\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300911 return resCodes::resErr;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700912 }
913
914 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800915 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300916 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300917 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800918 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300919 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -0800920 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300921 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800922 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300923 std::to_string(static_cast<int>(lang));
Vijay Khemka2a967082021-01-22 15:53:31 -0800924 isLangEng = checkLangEng(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800925 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300926 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300927 break;
928 }
929 default:
930 {
931 std::cerr << "Internal error: unexpected FRU area index: "
932 << static_cast<int>(area) << " \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300933 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300934 }
935 }
936 size_t fieldIndex = 0;
937 DecodeState state;
938 do
939 {
Vijay Khemka2a967082021-01-22 15:53:31 -0800940 auto res =
941 decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300942 state = res.first;
943 std::string value = res.second;
944 std::string name;
945 if (fieldIndex < fruAreaFieldNames->size())
946 {
947 name = std::string(getFruAreaName(area)) + "_" +
948 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -0800949 }
950 else
951 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300952 name =
953 std::string(getFruAreaName(area)) + "_" +
954 FRU_CUSTOM_FIELD_NAME +
955 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -0800956 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300957
958 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -0800959 {
Ed Tanous2147e672019-02-27 13:59:56 -0800960 // Strip non null characters from the end
961 value.erase(std::find_if(value.rbegin(), value.rend(),
962 [](char ch) { return ch != 0; })
963 .base(),
964 value.end());
965
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800966 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300967 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -0800968 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300969 else if (state == DecodeState::err)
970 {
971 std::cerr << "Error while parsing " << name << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300972 ret = resCodes::resWarn;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300973 // Cancel decoding if failed to parse any of mandatory
974 // fields
975 if (fieldIndex < fruAreaFieldNames->size())
976 {
977 std::cerr << "Failed to parse mandatory field \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300978 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300979 }
980 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300981 else
982 {
983 if (fieldIndex < fruAreaFieldNames->size())
984 {
985 std::cerr << "Mandatory fields absent in FRU area "
986 << getFruAreaName(area) << " after " << name
987 << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300988 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300989 }
990 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300991 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300992 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
993 {
994 uint8_t c = *fruBytesIter;
995 if (c)
996 {
997 std::cerr << "Non-zero byte after EndOfFields in FRU area "
998 << getFruAreaName(area) << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300999 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001000 break;
1001 }
1002 }
James Feist3cb5fec2018-01-23 14:41:51 -08001003 }
1004
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001005 return ret;
James Feist3cb5fec2018-01-23 14:41:51 -08001006}
1007
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001008std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001009{
1010 auto deviceMap = busMap.find(bus);
1011 if (deviceMap == busMap.end())
1012 {
1013 throw std::invalid_argument("Invalid Bus.");
1014 }
1015 auto device = deviceMap->second->find(address);
1016 if (device == deviceMap->second->end())
1017 {
1018 throw std::invalid_argument("Invalid Address.");
1019 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001020 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001021
1022 return ret;
1023}
1024
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001025void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001026 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001027 boost::container::flat_map<
1028 std::pair<size_t, size_t>,
1029 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001030 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001031{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001032 boost::container::flat_map<std::string, std::string> formattedFRU;
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001033 resCodes res = formatFRU(device, formattedFRU);
1034 if (res == resCodes::resErr)
James Feist3cb5fec2018-01-23 14:41:51 -08001035 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001036 std::cerr << "failed to parse FRU for device at bus " << bus
Patrick Ventureb755c832019-08-07 11:09:14 -07001037 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001038 return;
1039 }
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001040 else if (res == resCodes::resWarn)
1041 {
1042 std::cerr << "there were warnings while parsing FRU for device at bus "
1043 << bus << " address " << address << "\n";
1044 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001045
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001046 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001047 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001048 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001049 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001050 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001051 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001052 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001053 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001054 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001055 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001056 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001057 {
1058 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001059 std::regex illegalObject("[^A-Za-z0-9_]");
1060 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001061 }
1062 else
1063 {
1064 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1065 UNKNOWN_BUS_OBJECT_COUNT++;
1066 }
1067
James Feist918e18c2018-02-13 15:51:07 -08001068 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001069 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001070 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001071 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001072 int highest = -1;
1073 bool found = false;
1074
James Feista465ccc2019-02-08 12:51:01 -08001075 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001076 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001077 std::string path = busIface.second->get_object_path();
1078 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001079 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001080 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001081 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001082 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001083 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001084 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001085 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001086 // This device is already added to the lower numbered bus,
1087 // do not replicate it.
1088 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001089 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001090
1091 // Check if the match named has extra information.
1092 found = true;
1093 std::smatch base_match;
1094
1095 bool match = std::regex_match(
1096 path, base_match, std::regex(productName + "_(\\d+)$"));
1097 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001098 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001099 if (base_match.size() == 2)
1100 {
1101 std::ssub_match base_sub_match = base_match[1];
1102 std::string base = base_sub_match.str();
1103
1104 int value = std::stoi(base);
1105 highest = (value > highest) ? value : highest;
1106 }
James Feist79e9c0b2018-03-15 15:21:17 -07001107 }
James Feist918e18c2018-02-13 15:51:07 -08001108 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001109 } // end searching objects
1110
1111 if (found)
1112 {
1113 // We found something with the same name. If highest was still -1,
1114 // it means this new entry will be _0.
1115 productName += "_";
1116 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001117 }
1118 }
James Feist3cb5fec2018-01-23 14:41:51 -08001119
James Feist9eb0b582018-04-27 12:15:46 -07001120 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1121 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1122 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1123
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001124 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001125 {
James Feist9eb0b582018-04-27 12:15:46 -07001126
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001127 std::regex_replace(property.second.begin(), property.second.begin(),
1128 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301129 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001130 {
1131 continue;
1132 }
1133 std::string key =
1134 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301135
1136 if (property.first == "PRODUCT_ASSET_TAG")
1137 {
1138 std::string propertyName = property.first;
1139 iface->register_property(
1140 key, property.second + '\0',
1141 [bus, address, propertyName,
1142 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1143 if (strcmp(req.c_str(), resp.c_str()))
1144 {
1145 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001146 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301147 dbusInterfaceMap))
1148 {
1149 resp = req;
1150 }
1151 else
1152 {
1153 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001154 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301155 }
1156 }
1157 return 1;
1158 });
1159 }
1160 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001161 {
1162 std::cerr << "illegal key: " << key << "\n";
1163 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001164 if (DEBUG)
1165 {
1166 std::cout << property.first << ": " << property.second << "\n";
1167 }
James Feist3cb5fec2018-01-23 14:41:51 -08001168 }
James Feist2a9d6db2018-04-27 15:48:28 -07001169
1170 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001171 iface->register_property("BUS", bus);
1172 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001173
James Feist9eb0b582018-04-27 12:15:46 -07001174 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001175}
1176
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001177static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001178{
1179 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001180 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1181 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001182 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001183 baseboardFRUFile.seekg(0, std::ios_base::end);
1184 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1185 baseboardFRU.resize(fileSize);
1186 baseboardFRUFile.seekg(0, std::ios_base::beg);
1187 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001188 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001189 }
1190 else
1191 {
1192 return false;
1193 }
1194 return true;
1195}
1196
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001197bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001198{
1199 boost::container::flat_map<std::string, std::string> tmp;
1200 if (fru.size() > MAX_FRU_SIZE)
1201 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001202 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001203 return false;
1204 }
1205 // verify legal fru by running it through fru parsing logic
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001206 if (formatFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001207 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001208 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001209 return false;
1210 }
1211 // baseboard fru
1212 if (bus == 0 && address == 0)
1213 {
1214 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1215 if (!file.good())
1216 {
1217 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1218 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001219 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001220 return false;
1221 }
James Feista465ccc2019-02-08 12:51:01 -08001222 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001223 return file.good();
1224 }
1225 else
1226 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001227 if (hasEepromFile(bus, address))
1228 {
1229 auto path = getEepromPath(bus, address);
1230 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1231 if (eeprom < 0)
1232 {
1233 std::cerr << "unable to open i2c device " << path << "\n";
1234 throw DBusInternalError();
1235 return false;
1236 }
1237
1238 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1239 if (writtenBytes < 0)
1240 {
1241 std::cerr << "unable to write to i2c device " << path << "\n";
1242 close(eeprom);
1243 throw DBusInternalError();
1244 return false;
1245 }
1246
1247 close(eeprom);
1248 return true;
1249 }
1250
James Feistb49ffc32018-05-02 11:10:43 -07001251 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1252
1253 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1254 if (file < 0)
1255 {
1256 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001257 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001258 return false;
1259 }
1260 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1261 {
1262 std::cerr << "unable to set device address\n";
1263 close(file);
James Feistddb78302018-09-06 11:45:42 -07001264 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001265 return false;
1266 }
1267
1268 constexpr const size_t RETRY_MAX = 2;
1269 uint16_t index = 0;
1270 size_t retries = RETRY_MAX;
1271 while (index < fru.size())
1272 {
1273 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1274 (retries == RETRY_MAX))
1275 {
1276 // The 4K EEPROM only uses the A2 and A1 device address bits
1277 // with the third bit being a memory page address bit.
1278 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1279 {
1280 std::cerr << "unable to set device address\n";
1281 close(file);
James Feistddb78302018-09-06 11:45:42 -07001282 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001283 return false;
1284 }
1285 }
1286
James Feist98132792019-07-09 13:29:09 -07001287 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1288 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001289 {
1290 if (!retries--)
1291 {
1292 std::cerr << "error writing fru: " << strerror(errno)
1293 << "\n";
1294 close(file);
James Feistddb78302018-09-06 11:45:42 -07001295 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001296 return false;
1297 }
1298 }
1299 else
1300 {
1301 retries = RETRY_MAX;
1302 index++;
1303 }
1304 // most eeproms require 5-10ms between writes
1305 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1306 }
1307 close(file);
1308 return true;
1309 }
1310}
1311
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001312void rescanOneBus(
1313 BusMap& busmap, uint8_t busNum,
1314 boost::container::flat_map<
1315 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001316 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1317 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001318{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001319 for (auto& [pair, interface] : foundDevices)
1320 {
1321 if (pair.first == static_cast<size_t>(busNum))
1322 {
1323 objServer.remove_interface(interface);
1324 foundDevices.erase(pair);
1325 }
1326 }
1327
James Feist5d7f4692020-06-17 18:22:33 -07001328 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1329 if (!fs::exists(busPath))
1330 {
1331 if (dbusCall)
1332 {
1333 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1334 << "\n";
1335 throw std::invalid_argument("Invalid Bus.");
1336 }
1337 return;
1338 }
1339
1340 std::vector<fs::path> i2cBuses;
1341 i2cBuses.emplace_back(busPath);
1342
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001343 auto scan = std::make_shared<FindDevicesWithCallback>(
1344 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1345 for (auto& busIface : dbusInterfaceMap)
1346 {
1347 if (busIface.first.first == static_cast<size_t>(busNum))
1348 {
1349 objServer.remove_interface(busIface.second);
1350 }
1351 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001352 auto found = busmap.find(busNum);
1353 if (found == busmap.end() || found->second == nullptr)
1354 {
1355 return;
1356 }
1357 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001358 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001359 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001360 static_cast<uint32_t>(busNum), device.first);
1361 }
1362 });
1363 scan->run();
1364}
1365
James Feist9eb0b582018-04-27 12:15:46 -07001366void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001367 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001368 boost::container::flat_map<
1369 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001370 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001371{
James Feist6ebf9de2018-05-15 15:01:17 -07001372 static boost::asio::deadline_timer timer(io);
1373 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001374
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001375 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001376 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001377 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001378 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001379
Nikhil Potaded8884f12019-03-27 13:27:13 -07001380 boost::container::flat_map<size_t, fs::path> busPaths;
1381 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001382 {
James Feist4131aea2018-03-09 09:47:30 -08001383 std::cerr << "unable to find i2c devices\n";
1384 return;
James Feist918e18c2018-02-13 15:51:07 -08001385 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001386
1387 for (auto busPath : busPaths)
1388 {
1389 i2cBuses.emplace_back(busPath.second);
1390 }
James Feist4131aea2018-03-09 09:47:30 -08001391
James Feist98132792019-07-09 13:29:09 -07001392 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001393 for (auto& [pair, interface] : foundDevices)
1394 {
1395 objServer.remove_interface(interface);
1396 }
1397 foundDevices.clear();
1398
James Feist5cb06082019-10-24 17:11:13 -07001399 auto scan =
1400 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001401 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001402 {
1403 objServer.remove_interface(busIface.second);
1404 }
James Feist4131aea2018-03-09 09:47:30 -08001405
James Feist6ebf9de2018-05-15 15:01:17 -07001406 dbusInterfaceMap.clear();
1407 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001408
James Feist6ebf9de2018-05-15 15:01:17 -07001409 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001410 std::vector<uint8_t> baseboardFRU;
1411 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001412 {
Helen Huangf69fe902021-02-19 16:18:22 +08001413 // If no device on i2c bus 0, the insertion will happen.
1414 auto bus0 =
1415 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1416 bus0.first->second->emplace(0, baseboardFRU);
James Feist6ebf9de2018-05-15 15:01:17 -07001417 }
James Feist98132792019-07-09 13:29:09 -07001418 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001419 {
James Feista465ccc2019-02-08 12:51:01 -08001420 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001421 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001422 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001423 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001424 }
1425 }
1426 });
1427 scan->run();
1428 });
James Feist918e18c2018-02-13 15:51:07 -08001429}
1430
Joshi-Mansid73b7442020-03-27 19:10:21 +05301431// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001432uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1433 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301434{
1435 constexpr int checksumMod = 256;
1436 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001437 int sum = std::accumulate(iter, end, 0);
1438 int checksum = (checksumMod - sum) & modVal;
1439 return static_cast<uint8_t>(checksum);
1440}
1441uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1442{
1443 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301444}
1445
1446// Update new fru area length &
1447// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001448// Return the offset of the area checksum byte
1449static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1450 size_t fruAreaStart,
1451 size_t fruAreaEndOfFieldsOffset,
1452 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301453{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001454 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301455
1456 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001457 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1458 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301459
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001460 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301461 size_t checksumLoc;
1462 if (!mod)
1463 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001464 traverseFRUAreaIndex += (fruBlockSize);
1465 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301466 }
1467 else
1468 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001469 traverseFRUAreaIndex += (fruBlockSize - mod);
1470 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301471 }
1472
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001473 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1474 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1475 size_t fruAreaLengthLoc = fruAreaStart + 1;
1476 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301477
1478 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001479 std::vector<uint8_t> finalFRUData;
1480 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1481 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301482
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001483 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001484 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301485}
1486
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001487static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301488{
1489 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001490 constexpr uint8_t endOfFields = 0xC1;
1491 if (fruFieldTypeLenValue == endOfFields)
1492 {
1493 return -1;
1494 }
1495 else
1496 {
1497 return fruFieldTypeLenValue & typeLenMask;
1498 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301499}
1500
1501// Details with example of Asset Tag Update
1502// To find location of Product Info Area asset tag as per FRU specification
1503// 1. Find product Info area starting offset (*8 - as header will be in
1504// multiple of 8 bytes).
1505// 2. Skip 3 bytes of product info area (like format version, area length,
1506// and language code).
1507// 3. Traverse manufacturer name, product name, product version, & product
1508// serial number, by reading type/length code to reach the Asset Tag.
1509// 4. Update the Asset Tag, reposition the product Info area in multiple of
1510// 8 bytes. Update the Product area length and checksum.
1511
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001512bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301513 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1514 std::string propertyName,
1515 boost::container::flat_map<
1516 std::pair<size_t, size_t>,
1517 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1518{
1519 size_t updatePropertyReqLen = updatePropertyReq.length();
1520 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1521 {
1522 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001523 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301524 "Invalid Length "
1525 << updatePropertyReqLen << "\n";
1526 return false;
1527 }
1528
1529 std::vector<uint8_t> fruData;
1530 try
1531 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001532 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301533 static_cast<uint8_t>(address));
1534 }
1535 catch (std::invalid_argument& e)
1536 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001537 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301538 return false;
1539 }
1540
1541 if (fruData.empty())
1542 {
1543 return false;
1544 }
1545
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001546 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301547
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001548 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301549 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001550 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001551 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001552 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1553 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301554 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001555 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001556 << " \n";
1557 return false;
1558 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001559 fruAreas fruAreaToUpdate =
1560 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1561 fruAreaOffsetFieldValue =
1562 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1563 switch (fruAreaToUpdate)
1564 {
1565 case fruAreas::fruAreaChassis:
1566 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1567 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1568 break;
1569 case fruAreas::fruAreaBoard:
1570 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1571 fruAreaFieldNames = &BOARD_FRU_AREAS;
1572 break;
1573 case fruAreas::fruAreaProduct:
1574 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1575 // i.e. version, area length and language code
1576 offset = 3;
1577 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1578 break;
1579 default:
1580 std::cerr << "Don't know how to handle property " << propertyName
1581 << " \n";
1582 return false;
1583 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001584 if (fruAreaOffsetFieldValue == 0)
1585 {
1586 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301587 return false;
1588 }
1589
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001590 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001591 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1592 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001593 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001594 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001595 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001596 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301597
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001598 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001599 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301600 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001601 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001602 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301603 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001604 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301605 break;
1606 }
1607 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001608 if (!found)
1609 {
1610 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1611 if (pos == std::string::npos)
1612 {
1613 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1614 << propertyName << "\n";
1615 return false;
1616 }
1617 std::string fieldNumStr =
1618 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1619 size_t fieldNum = std::stoi(fieldNumStr);
1620 if (fieldNum == 0)
1621 {
1622 std::cerr << "PropertyName not recognized: " << propertyName
1623 << "\n";
1624 return false;
1625 }
1626 skipToFRUUpdateField += fieldNum;
1627 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301628
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001629 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301630 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001631 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001632 if (fieldLength < 0)
1633 {
1634 break;
1635 }
1636 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301637 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001638 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301639
1640 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001641 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001642 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301643 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001644 std::cerr << "Property " << propertyName << " not present \n";
1645 return false;
1646 }
1647 fruDataIter += 1 + fieldLength;
1648 size_t restFRUFieldsLoc = fruDataIter;
1649 size_t endOfFieldsLoc = 0;
1650 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1651 {
1652 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301653 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001654 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301655 break;
1656 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001657 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301658 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001659 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301660
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001661 std::vector<uint8_t> restFRUAreaFieldsData;
1662 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001663 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001664 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301665
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001666 // Push post update fru areas if any
1667 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001668 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1669 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001670 {
1671 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001672 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001673 if ((fruAreaLoc > endOfFieldsLoc) &&
1674 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1675 {
1676 nextFRUAreaLoc = fruAreaLoc;
1677 }
1678 }
1679 std::vector<uint8_t> restFRUAreasData;
1680 if (nextFRUAreaLoc)
1681 {
1682 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1683 fruData.size() - nextFRUAreaLoc,
1684 std::back_inserter(restFRUAreasData));
1685 }
1686
1687 // check FRU area size
1688 size_t fruAreaDataSize =
1689 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1690 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1691 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1692 {
1693
1694#ifdef ENABLE_FRU_AREA_RESIZE
1695 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1696 // round size to 8-byte blocks
1697 newFRUAreaSize =
1698 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1699 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1700 fruData.resize(newFRUDataSize);
1701 fruAreaSize = newFRUAreaSize;
1702 fruAreaEnd = fruAreaStart + fruAreaSize;
1703#else
1704 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1705 << " should not be greater than available FRU area size: "
1706 << fruAreaAvailableSize << "\n";
1707 return false;
1708#endif // ENABLE_FRU_AREA_RESIZE
1709 }
1710
Joshi-Mansid73b7442020-03-27 19:10:21 +05301711 // write new requested property field length and data
1712 constexpr uint8_t newTypeLenMask = 0xC0;
1713 fruData[fruUpdateFieldLoc] =
1714 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1715 fruUpdateFieldLoc++;
1716 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1717 fruData.begin() + fruUpdateFieldLoc);
1718
1719 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001720 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1721 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001722 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1723 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301724
1725 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001726 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1727 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301728
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001729#ifdef ENABLE_FRU_AREA_RESIZE
1730 ++nextFRUAreaNewLoc;
1731 ssize_t nextFRUAreaOffsetDiff =
1732 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1733 // Append rest FRU Areas if size changed and there were other sections after
1734 // updated one
1735 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1736 {
1737 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1738 fruData.begin() + nextFRUAreaNewLoc);
1739 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001740 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1741 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001742 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001743 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001744 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1745 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1746 {
1747 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1748 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1749 }
1750 }
1751 // Calculate new checksum
1752 std::vector<uint8_t> headerFRUData;
1753 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1754 size_t checksumVal = calculateChecksum(headerFRUData);
1755 fruData[7] = static_cast<uint8_t>(checksumVal);
1756 // fill zeros if FRU Area size decreased
1757 if (nextFRUAreaOffsetDiff < 0)
1758 {
1759 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1760 restFRUAreasData.size(),
1761 fruData.end(), 0);
1762 }
1763 }
1764#else
1765 // this is to avoid "unused variable" warning
1766 (void)nextFRUAreaNewLoc;
1767#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301768 if (fruData.empty())
1769 {
1770 return false;
1771 }
1772
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001773 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301774 fruData))
1775 {
1776 return false;
1777 }
1778
1779 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1780 rescanBusses(busMap, dbusInterfaceMap);
1781 return true;
1782}
1783
James Feist98132792019-07-09 13:29:09 -07001784int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001785{
1786 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001787 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001788 std::vector<fs::path> i2cBuses;
1789
James Feista3c180a2018-08-09 16:06:04 -07001790 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001791 {
1792 std::cerr << "unable to find i2c devices\n";
1793 return 1;
1794 }
James Feist3cb5fec2018-01-23 14:41:51 -08001795
Patrick Venture11f1ff42019-08-01 10:42:12 -07001796 // check for and load blacklist with initial buses.
1797 loadBlacklist(blacklistPath);
1798
Vijay Khemka065f6d92018-12-18 10:37:47 -08001799 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001800
James Feist6ebf9de2018-05-15 15:01:17 -07001801 // this is a map with keys of pair(bus number, address) and values of
1802 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001803 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001804 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1805 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001806
James Feist9eb0b582018-04-27 12:15:46 -07001807 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1808 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1809 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001810
James Feist5cb06082019-10-24 17:11:13 -07001811 iface->register_method("ReScan",
1812 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001813
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001814 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001815 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001816 });
1817
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001818 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001819
1820 iface->register_method("WriteFru", [&](const uint8_t bus,
1821 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001822 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001823 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001824 {
James Feistddb78302018-09-06 11:45:42 -07001825 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001826 return;
1827 }
1828 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001829 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001830 });
James Feist9eb0b582018-04-27 12:15:46 -07001831 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001832
James Feist9eb0b582018-04-27 12:15:46 -07001833 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001834 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001835 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001836 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001837 std::string,
1838 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001839 values;
1840 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001841 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001842 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001843 {
James Feistcb5661d2020-06-12 15:05:01 -07001844 powerIsOn = boost::ends_with(
1845 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001846 }
James Feist6ebf9de2018-05-15 15:01:17 -07001847
James Feistcb5661d2020-06-12 15:05:01 -07001848 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001849 {
James Feist5cb06082019-10-24 17:11:13 -07001850 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001851 }
James Feist918e18c2018-02-13 15:51:07 -08001852 };
James Feist9eb0b582018-04-27 12:15:46 -07001853
1854 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001855 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001856 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001857 "openbmc_project/state/"
1858 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001859 eventHandler);
1860
James Feist4131aea2018-03-09 09:47:30 -08001861 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001862 inotify_add_watch(fd, I2C_DEV_LOCATION,
1863 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001864 std::array<char, 4096> readBuffer;
1865 std::string pendingBuffer;
1866 // monitor for new i2c devices
1867 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1868 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001869 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001870 std::size_t bytes_transferred) {
1871 if (ec)
1872 {
1873 std::cout << "Callback Error " << ec << "\n";
1874 return;
1875 }
1876 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001877 while (pendingBuffer.size() > sizeof(inotify_event))
1878 {
James Feista465ccc2019-02-08 12:51:01 -08001879 const inotify_event* iEvent =
1880 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001881 pendingBuffer.data());
1882 switch (iEvent->mask)
1883 {
James Feist9eb0b582018-04-27 12:15:46 -07001884 case IN_CREATE:
1885 case IN_MOVED_TO:
1886 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001887 std::string name(iEvent->name);
1888 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001889 {
James Feist5d7f4692020-06-17 18:22:33 -07001890 int bus = busStrToInt(name);
1891 if (bus < 0)
1892 {
1893 std::cerr << "Could not parse bus " << name
1894 << "\n";
1895 continue;
1896 }
1897 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1898 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001899 }
James Feist4131aea2018-03-09 09:47:30 -08001900 }
1901
1902 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1903 }
James Feist6ebf9de2018-05-15 15:01:17 -07001904
James Feist4131aea2018-03-09 09:47:30 -08001905 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1906 watchI2cBusses);
1907 };
1908
1909 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001910 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001911 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001912
James Feist3cb5fec2018-01-23 14:41:51 -08001913 io.run();
1914 return 0;
1915}