blob: 6eaccbef3d4d5547deb9e3e5a2046cfd7b00d6e7 [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,
Vijay Khemka2a967082021-01-22 15:53:31 -0800697 const std::vector<uint8_t>::const_iterator& end,
698 bool isLangEng)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800699{
700 std::string value;
701 unsigned int i;
702
703 /* we need at least one byte to decode the type/len header */
704 if (iter == end)
705 {
706 std::cerr << "Truncated FRU data\n";
707 return make_pair(DecodeState::err, value);
708 }
709
710 uint8_t c = *(iter++);
711
712 /* 0xc1 is the end marker */
713 if (c == 0xc1)
714 {
715 return make_pair(DecodeState::end, value);
716 }
717
718 /* decode type/len byte */
719 uint8_t type = static_cast<uint8_t>(c >> 6);
720 uint8_t len = static_cast<uint8_t>(c & 0x3f);
721
722 /* we should have at least len bytes of data available overall */
723 if (iter + len > end)
724 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300725 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800726 return make_pair(DecodeState::err, value);
727 }
728
729 switch (type)
730 {
731 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300732 {
733 std::stringstream ss;
734 ss << std::hex << std::setfill('0');
735 for (i = 0; i < len; i++, iter++)
736 {
737 uint8_t val = static_cast<uint8_t>(*iter);
738 ss << std::setw(2) << static_cast<int>(val);
739 }
740 value = ss.str();
741 break;
742 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800743 case FRUDataEncoding::languageDependent:
744 /* For language-code dependent encodings, assume 8-bit ASCII */
745 value = std::string(iter, iter + len);
746 iter += len;
Vijay Khemka2a967082021-01-22 15:53:31 -0800747
748 /* English text is encoded in 8-bit ASCII + Latin 1. All other
749 * languages are required to use 2-byte unicode. FruDevice does not
750 * handle unicode.
751 */
752 if (!isLangEng)
753 {
754 std::cerr << "Error: Non english string is not supported \n";
755 return make_pair(DecodeState::err, value);
756 }
757
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800758 break;
759
760 case FRUDataEncoding::bcdPlus:
761 value = std::string();
762 for (i = 0; i < len; i++, iter++)
763 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300764 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800765 value.push_back(bcdPlusToChar(val >> 4));
766 value.push_back(bcdPlusToChar(val & 0xf));
767 }
768 break;
769
770 case FRUDataEncoding::sixBitASCII:
771 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300772 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800773 unsigned int accumBitLen = 0;
774 value = std::string();
775 for (i = 0; i < len; i++, iter++)
776 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300777 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800778 accumBitLen += 8;
779 while (accumBitLen >= 6)
780 {
781 value.push_back(sixBitToChar(accum & 0x3f));
782 accum >>= 6;
783 accumBitLen -= 6;
784 }
785 }
786 }
787 break;
788 }
789
790 return make_pair(DecodeState::ok, value);
791}
792
Vijay Khemka2a967082021-01-22 15:53:31 -0800793static bool checkLangEng(uint8_t lang)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300794{
795 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
796 // but we don't support that.
797 if (lang && lang != 25)
798 {
Vijay Khemka2a967082021-01-22 15:53:31 -0800799 std::cerr << "Warning: languages other than English is not "
800 "supported\n";
801 // Return language flag as non english
802 return false;
803 }
804 else
805 {
806 return true;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300807 }
808}
809
Vijay Khemka02618f02021-01-20 11:10:28 -0800810/* This function verifies for other offsets to check if they are not
811 * falling under other field area
812 *
813 * fruBytes: Start of Fru data
814 * currentArea: Index of current area offset to be compared against all area
815 * offset and it is a multiple of 8 bytes as per specification
816 * len: Length of current area space and it is a multiple of 8 bytes
817 * as per specification
818 */
819static bool verifyOffset(const std::vector<uint8_t>& fruBytes,
820 fruAreas currentArea, uint8_t len)
821{
822
823 unsigned int fruBytesSize = fruBytes.size();
824
825 // check if Fru data has at least 8 byte header
826 if (fruBytesSize <= fruBlockSize)
827 {
828 std::cerr << "Error: trying to parse empty FRU\n";
829 return false;
830 }
831
832 // Check range of passed currentArea value
833 if (currentArea > fruAreas::fruAreaMultirecord)
834 {
835 std::cerr << "Error: Fru area is out of range\n";
836 return false;
837 }
838
839 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
840 if (currentAreaIndex > fruBytesSize)
841 {
842 std::cerr << "Error: Fru area index is out of range\n";
843 return false;
844 }
845
846 unsigned int start = fruBytes[currentAreaIndex];
847 unsigned int end = start + len;
848
849 /* Verify each offset within the range of start and end */
850 for (fruAreas area = fruAreas::fruAreaInternal;
851 area <= fruAreas::fruAreaMultirecord; ++area)
852 {
853 // skip the current offset
854 if (area == currentArea)
855 {
856 continue;
857 }
858
859 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
860 if (areaIndex > fruBytesSize)
861 {
862 std::cerr << "Error: Fru area index is out of range\n";
863 return false;
864 }
865
866 unsigned int areaOffset = fruBytes[areaIndex];
867 // if areaOffset is 0 means this area is not available so skip
868 if (areaOffset == 0)
869 {
870 continue;
871 }
872
873 // check for overlapping of current offset with given areaoffset
874 if (areaOffset == start || (areaOffset > start && areaOffset < end))
875 {
876 std::cerr << getFruAreaName(currentArea)
877 << " offset is overlapping with " << getFruAreaName(area)
878 << " offset\n";
879 return false;
880 }
881 }
882 return true;
883}
884
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300885resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
886 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800887{
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300888 resCodes ret = resCodes::resOK;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300889 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -0800890 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300891 std::cerr << "Error: trying to parse empty FRU \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300892 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800893 }
James Feist9eb0b582018-04-27 12:15:46 -0700894 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300895 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -0800896
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300897 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -0800898
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300899 // Don't parse Internal and Multirecord areas
900 for (fruAreas area = fruAreas::fruAreaChassis;
901 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -0800902 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300903
904 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
905 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800906 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300907 continue;
908 }
909 offset *= fruBlockSize;
910 std::vector<uint8_t>::const_iterator fruBytesIter =
911 fruBytes.begin() + offset;
912 if (fruBytesIter + fruBlockSize >= fruBytes.end())
913 {
914 std::cerr << "Not enough data to parse \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300915 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -0800916 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300917 // check for format version 1
918 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -0800919 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300920 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300921 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300922 }
923 ++fruBytesIter;
Vijay Khemka02618f02021-01-20 11:10:28 -0800924
925 /* Verify other area offset for overlap with current area by passing
926 * length of current area offset pointed by *fruBytesIter
927 */
928 if (!verifyOffset(fruBytes, area, *fruBytesIter))
929 {
930 return resCodes::resErr;
931 }
932
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300933 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
934 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
935 fruBytes.begin() + offset + fruAreaSize - 1;
936 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800937
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300938 uint8_t fruComputedChecksum =
939 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
940 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300941 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +0300942 std::stringstream ss;
943 ss << std::hex << std::setfill('0');
944 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
945 ss << "\tComputed checksum: 0x" << std::setw(2)
946 << static_cast<int>(fruComputedChecksum) << "\n";
947 ss << "\tThe read checksum: 0x" << std::setw(2)
948 << static_cast<int>(*fruBytesIterEndArea) << "\n";
949 std::cerr << ss.str();
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300950 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300951 }
952
Vijay Khemka2a967082021-01-22 15:53:31 -0800953 /* Set default language flag to true as Chassis Fru area are always
954 * encoded in English defined in Section 10 of Fru specification
955 */
956 bool isLangEng = true;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300957 switch (area)
958 {
959 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -0800960 {
961 result["CHASSIS_TYPE"] =
962 std::to_string(static_cast<int>(*fruBytesIter));
963 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300964 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300965 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800966 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300967 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -0800968 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300969 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -0800970 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300971 std::to_string(static_cast<int>(lang));
Vijay Khemka2a967082021-01-22 15:53:31 -0800972 isLangEng = checkLangEng(lang);
James Feist3cb5fec2018-01-23 14:41:51 -0800973 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -0800974
975 unsigned int minutes = *fruBytesIter |
976 *(fruBytesIter + 1) << 8 |
977 *(fruBytesIter + 2) << 16;
978 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700979 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -0800980 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700981 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -0800982
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700983 // Tue Nov 20 23:08:00 2018
984 char timeString[32] = {0};
985 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -0700986 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700987 if (bytes == 0)
988 {
989 std::cerr << "invalid time string encountered\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300990 return resCodes::resErr;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -0700991 }
992
993 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -0800994 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300995 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300996 break;
James Feist3cb5fec2018-01-23 14:41:51 -0800997 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300998 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -0800999 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001000 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001001 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001002 std::to_string(static_cast<int>(lang));
Vijay Khemka2a967082021-01-22 15:53:31 -08001003 isLangEng = checkLangEng(lang);
James Feist3cb5fec2018-01-23 14:41:51 -08001004 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001005 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001006 break;
1007 }
1008 default:
1009 {
1010 std::cerr << "Internal error: unexpected FRU area index: "
1011 << static_cast<int>(area) << " \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001012 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001013 }
1014 }
1015 size_t fieldIndex = 0;
1016 DecodeState state;
1017 do
1018 {
Vijay Khemka2a967082021-01-22 15:53:31 -08001019 auto res =
1020 decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001021 state = res.first;
1022 std::string value = res.second;
1023 std::string name;
1024 if (fieldIndex < fruAreaFieldNames->size())
1025 {
1026 name = std::string(getFruAreaName(area)) + "_" +
1027 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -08001028 }
1029 else
1030 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001031 name =
1032 std::string(getFruAreaName(area)) + "_" +
1033 FRU_CUSTOM_FIELD_NAME +
1034 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -08001035 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001036
1037 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001038 {
Ed Tanous2147e672019-02-27 13:59:56 -08001039 // Strip non null characters from the end
1040 value.erase(std::find_if(value.rbegin(), value.rend(),
1041 [](char ch) { return ch != 0; })
1042 .base(),
1043 value.end());
1044
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001045 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001046 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001047 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001048 else if (state == DecodeState::err)
1049 {
1050 std::cerr << "Error while parsing " << name << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001051 ret = resCodes::resWarn;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001052 // Cancel decoding if failed to parse any of mandatory
1053 // fields
1054 if (fieldIndex < fruAreaFieldNames->size())
1055 {
1056 std::cerr << "Failed to parse mandatory field \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001057 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001058 }
1059 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001060 else
1061 {
1062 if (fieldIndex < fruAreaFieldNames->size())
1063 {
1064 std::cerr << "Mandatory fields absent in FRU area "
1065 << getFruAreaName(area) << " after " << name
1066 << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001067 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001068 }
1069 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001070 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001071 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
1072 {
1073 uint8_t c = *fruBytesIter;
1074 if (c)
1075 {
1076 std::cerr << "Non-zero byte after EndOfFields in FRU area "
1077 << getFruAreaName(area) << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001078 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001079 break;
1080 }
1081 }
James Feist3cb5fec2018-01-23 14:41:51 -08001082 }
1083
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001084 return ret;
James Feist3cb5fec2018-01-23 14:41:51 -08001085}
1086
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001087std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001088{
1089 auto deviceMap = busMap.find(bus);
1090 if (deviceMap == busMap.end())
1091 {
1092 throw std::invalid_argument("Invalid Bus.");
1093 }
1094 auto device = deviceMap->second->find(address);
1095 if (device == deviceMap->second->end())
1096 {
1097 throw std::invalid_argument("Invalid Address.");
1098 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001099 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001100
1101 return ret;
1102}
1103
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001104void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001105 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001106 boost::container::flat_map<
1107 std::pair<size_t, size_t>,
1108 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001109 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001110{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001111 boost::container::flat_map<std::string, std::string> formattedFRU;
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001112 resCodes res = formatFRU(device, formattedFRU);
1113 if (res == resCodes::resErr)
James Feist3cb5fec2018-01-23 14:41:51 -08001114 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001115 std::cerr << "failed to parse FRU for device at bus " << bus
Patrick Ventureb755c832019-08-07 11:09:14 -07001116 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001117 return;
1118 }
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001119 else if (res == resCodes::resWarn)
1120 {
1121 std::cerr << "there were warnings while parsing FRU for device at bus "
1122 << bus << " address " << address << "\n";
1123 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001124
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001125 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001126 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001127 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001128 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001129 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001130 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001131 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001132 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001133 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001134 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001135 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001136 {
1137 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001138 std::regex illegalObject("[^A-Za-z0-9_]");
1139 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001140 }
1141 else
1142 {
1143 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1144 UNKNOWN_BUS_OBJECT_COUNT++;
1145 }
1146
James Feist918e18c2018-02-13 15:51:07 -08001147 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001148 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001149 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001150 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001151 int highest = -1;
1152 bool found = false;
1153
James Feista465ccc2019-02-08 12:51:01 -08001154 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001155 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001156 std::string path = busIface.second->get_object_path();
1157 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001158 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001159 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001160 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001161 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001162 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001163 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001164 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001165 // This device is already added to the lower numbered bus,
1166 // do not replicate it.
1167 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001168 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001169
1170 // Check if the match named has extra information.
1171 found = true;
1172 std::smatch base_match;
1173
1174 bool match = std::regex_match(
1175 path, base_match, std::regex(productName + "_(\\d+)$"));
1176 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001177 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001178 if (base_match.size() == 2)
1179 {
1180 std::ssub_match base_sub_match = base_match[1];
1181 std::string base = base_sub_match.str();
1182
1183 int value = std::stoi(base);
1184 highest = (value > highest) ? value : highest;
1185 }
James Feist79e9c0b2018-03-15 15:21:17 -07001186 }
James Feist918e18c2018-02-13 15:51:07 -08001187 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001188 } // end searching objects
1189
1190 if (found)
1191 {
1192 // We found something with the same name. If highest was still -1,
1193 // it means this new entry will be _0.
1194 productName += "_";
1195 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001196 }
1197 }
James Feist3cb5fec2018-01-23 14:41:51 -08001198
James Feist9eb0b582018-04-27 12:15:46 -07001199 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1200 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1201 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1202
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001203 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001204 {
James Feist9eb0b582018-04-27 12:15:46 -07001205
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001206 std::regex_replace(property.second.begin(), property.second.begin(),
1207 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301208 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001209 {
1210 continue;
1211 }
1212 std::string key =
1213 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301214
1215 if (property.first == "PRODUCT_ASSET_TAG")
1216 {
1217 std::string propertyName = property.first;
1218 iface->register_property(
1219 key, property.second + '\0',
1220 [bus, address, propertyName,
1221 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1222 if (strcmp(req.c_str(), resp.c_str()))
1223 {
1224 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001225 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301226 dbusInterfaceMap))
1227 {
1228 resp = req;
1229 }
1230 else
1231 {
1232 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001233 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301234 }
1235 }
1236 return 1;
1237 });
1238 }
1239 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001240 {
1241 std::cerr << "illegal key: " << key << "\n";
1242 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001243 if (DEBUG)
1244 {
1245 std::cout << property.first << ": " << property.second << "\n";
1246 }
James Feist3cb5fec2018-01-23 14:41:51 -08001247 }
James Feist2a9d6db2018-04-27 15:48:28 -07001248
1249 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001250 iface->register_property("BUS", bus);
1251 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001252
James Feist9eb0b582018-04-27 12:15:46 -07001253 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001254}
1255
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001256static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001257{
1258 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001259 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1260 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001261 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001262 baseboardFRUFile.seekg(0, std::ios_base::end);
1263 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1264 baseboardFRU.resize(fileSize);
1265 baseboardFRUFile.seekg(0, std::ios_base::beg);
1266 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001267 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001268 }
1269 else
1270 {
1271 return false;
1272 }
1273 return true;
1274}
1275
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001276bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001277{
1278 boost::container::flat_map<std::string, std::string> tmp;
1279 if (fru.size() > MAX_FRU_SIZE)
1280 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001281 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001282 return false;
1283 }
1284 // verify legal fru by running it through fru parsing logic
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001285 if (formatFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001286 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001287 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001288 return false;
1289 }
1290 // baseboard fru
1291 if (bus == 0 && address == 0)
1292 {
1293 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1294 if (!file.good())
1295 {
1296 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1297 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001298 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001299 return false;
1300 }
James Feista465ccc2019-02-08 12:51:01 -08001301 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001302 return file.good();
1303 }
1304 else
1305 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001306 if (hasEepromFile(bus, address))
1307 {
1308 auto path = getEepromPath(bus, address);
1309 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1310 if (eeprom < 0)
1311 {
1312 std::cerr << "unable to open i2c device " << path << "\n";
1313 throw DBusInternalError();
1314 return false;
1315 }
1316
1317 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1318 if (writtenBytes < 0)
1319 {
1320 std::cerr << "unable to write to i2c device " << path << "\n";
1321 close(eeprom);
1322 throw DBusInternalError();
1323 return false;
1324 }
1325
1326 close(eeprom);
1327 return true;
1328 }
1329
James Feistb49ffc32018-05-02 11:10:43 -07001330 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1331
1332 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1333 if (file < 0)
1334 {
1335 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001336 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001337 return false;
1338 }
1339 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1340 {
1341 std::cerr << "unable to set device address\n";
1342 close(file);
James Feistddb78302018-09-06 11:45:42 -07001343 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001344 return false;
1345 }
1346
1347 constexpr const size_t RETRY_MAX = 2;
1348 uint16_t index = 0;
1349 size_t retries = RETRY_MAX;
1350 while (index < fru.size())
1351 {
1352 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1353 (retries == RETRY_MAX))
1354 {
1355 // The 4K EEPROM only uses the A2 and A1 device address bits
1356 // with the third bit being a memory page address bit.
1357 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1358 {
1359 std::cerr << "unable to set device address\n";
1360 close(file);
James Feistddb78302018-09-06 11:45:42 -07001361 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001362 return false;
1363 }
1364 }
1365
James Feist98132792019-07-09 13:29:09 -07001366 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1367 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001368 {
1369 if (!retries--)
1370 {
1371 std::cerr << "error writing fru: " << strerror(errno)
1372 << "\n";
1373 close(file);
James Feistddb78302018-09-06 11:45:42 -07001374 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001375 return false;
1376 }
1377 }
1378 else
1379 {
1380 retries = RETRY_MAX;
1381 index++;
1382 }
1383 // most eeproms require 5-10ms between writes
1384 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1385 }
1386 close(file);
1387 return true;
1388 }
1389}
1390
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001391void rescanOneBus(
1392 BusMap& busmap, uint8_t busNum,
1393 boost::container::flat_map<
1394 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001395 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1396 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001397{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001398 for (auto& [pair, interface] : foundDevices)
1399 {
1400 if (pair.first == static_cast<size_t>(busNum))
1401 {
1402 objServer.remove_interface(interface);
1403 foundDevices.erase(pair);
1404 }
1405 }
1406
James Feist5d7f4692020-06-17 18:22:33 -07001407 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1408 if (!fs::exists(busPath))
1409 {
1410 if (dbusCall)
1411 {
1412 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1413 << "\n";
1414 throw std::invalid_argument("Invalid Bus.");
1415 }
1416 return;
1417 }
1418
1419 std::vector<fs::path> i2cBuses;
1420 i2cBuses.emplace_back(busPath);
1421
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001422 auto scan = std::make_shared<FindDevicesWithCallback>(
1423 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1424 for (auto& busIface : dbusInterfaceMap)
1425 {
1426 if (busIface.first.first == static_cast<size_t>(busNum))
1427 {
1428 objServer.remove_interface(busIface.second);
1429 }
1430 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001431 auto found = busmap.find(busNum);
1432 if (found == busmap.end() || found->second == nullptr)
1433 {
1434 return;
1435 }
1436 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001437 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001438 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001439 static_cast<uint32_t>(busNum), device.first);
1440 }
1441 });
1442 scan->run();
1443}
1444
James Feist9eb0b582018-04-27 12:15:46 -07001445void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001446 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001447 boost::container::flat_map<
1448 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001449 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001450{
James Feist6ebf9de2018-05-15 15:01:17 -07001451 static boost::asio::deadline_timer timer(io);
1452 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001453
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001454 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001455 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001456 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001457 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001458
Nikhil Potaded8884f12019-03-27 13:27:13 -07001459 boost::container::flat_map<size_t, fs::path> busPaths;
1460 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001461 {
James Feist4131aea2018-03-09 09:47:30 -08001462 std::cerr << "unable to find i2c devices\n";
1463 return;
James Feist918e18c2018-02-13 15:51:07 -08001464 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001465
1466 for (auto busPath : busPaths)
1467 {
1468 i2cBuses.emplace_back(busPath.second);
1469 }
James Feist4131aea2018-03-09 09:47:30 -08001470
James Feist98132792019-07-09 13:29:09 -07001471 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001472 for (auto& [pair, interface] : foundDevices)
1473 {
1474 objServer.remove_interface(interface);
1475 }
1476 foundDevices.clear();
1477
James Feist5cb06082019-10-24 17:11:13 -07001478 auto scan =
1479 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001480 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001481 {
1482 objServer.remove_interface(busIface.second);
1483 }
James Feist4131aea2018-03-09 09:47:30 -08001484
James Feist6ebf9de2018-05-15 15:01:17 -07001485 dbusInterfaceMap.clear();
1486 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001487
James Feist6ebf9de2018-05-15 15:01:17 -07001488 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001489 std::vector<uint8_t> baseboardFRU;
1490 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001491 {
Helen Huangf69fe902021-02-19 16:18:22 +08001492 // If no device on i2c bus 0, the insertion will happen.
1493 auto bus0 =
1494 busmap.try_emplace(0, std::make_shared<DeviceMap>());
1495 bus0.first->second->emplace(0, baseboardFRU);
James Feist6ebf9de2018-05-15 15:01:17 -07001496 }
James Feist98132792019-07-09 13:29:09 -07001497 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001498 {
James Feista465ccc2019-02-08 12:51:01 -08001499 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001500 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001501 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001502 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001503 }
1504 }
1505 });
1506 scan->run();
1507 });
James Feist918e18c2018-02-13 15:51:07 -08001508}
1509
Joshi-Mansid73b7442020-03-27 19:10:21 +05301510// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001511uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1512 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301513{
1514 constexpr int checksumMod = 256;
1515 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001516 int sum = std::accumulate(iter, end, 0);
1517 int checksum = (checksumMod - sum) & modVal;
1518 return static_cast<uint8_t>(checksum);
1519}
1520uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1521{
1522 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301523}
1524
1525// Update new fru area length &
1526// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001527// Return the offset of the area checksum byte
1528static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1529 size_t fruAreaStart,
1530 size_t fruAreaEndOfFieldsOffset,
1531 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301532{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001533 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301534
1535 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001536 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1537 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301538
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001539 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301540 size_t checksumLoc;
1541 if (!mod)
1542 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001543 traverseFRUAreaIndex += (fruBlockSize);
1544 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301545 }
1546 else
1547 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001548 traverseFRUAreaIndex += (fruBlockSize - mod);
1549 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301550 }
1551
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001552 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1553 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1554 size_t fruAreaLengthLoc = fruAreaStart + 1;
1555 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301556
1557 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001558 std::vector<uint8_t> finalFRUData;
1559 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1560 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301561
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001562 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001563 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301564}
1565
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001566static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301567{
1568 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001569 constexpr uint8_t endOfFields = 0xC1;
1570 if (fruFieldTypeLenValue == endOfFields)
1571 {
1572 return -1;
1573 }
1574 else
1575 {
1576 return fruFieldTypeLenValue & typeLenMask;
1577 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301578}
1579
1580// Details with example of Asset Tag Update
1581// To find location of Product Info Area asset tag as per FRU specification
1582// 1. Find product Info area starting offset (*8 - as header will be in
1583// multiple of 8 bytes).
1584// 2. Skip 3 bytes of product info area (like format version, area length,
1585// and language code).
1586// 3. Traverse manufacturer name, product name, product version, & product
1587// serial number, by reading type/length code to reach the Asset Tag.
1588// 4. Update the Asset Tag, reposition the product Info area in multiple of
1589// 8 bytes. Update the Product area length and checksum.
1590
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001591bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301592 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1593 std::string propertyName,
1594 boost::container::flat_map<
1595 std::pair<size_t, size_t>,
1596 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1597{
1598 size_t updatePropertyReqLen = updatePropertyReq.length();
1599 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1600 {
1601 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001602 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301603 "Invalid Length "
1604 << updatePropertyReqLen << "\n";
1605 return false;
1606 }
1607
1608 std::vector<uint8_t> fruData;
1609 try
1610 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001611 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301612 static_cast<uint8_t>(address));
1613 }
1614 catch (std::invalid_argument& e)
1615 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001616 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301617 return false;
1618 }
1619
1620 if (fruData.empty())
1621 {
1622 return false;
1623 }
1624
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001625 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301626
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001627 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301628 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001629 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001630 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001631 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1632 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301633 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001634 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001635 << " \n";
1636 return false;
1637 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001638 fruAreas fruAreaToUpdate =
1639 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1640 fruAreaOffsetFieldValue =
1641 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1642 switch (fruAreaToUpdate)
1643 {
1644 case fruAreas::fruAreaChassis:
1645 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1646 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1647 break;
1648 case fruAreas::fruAreaBoard:
1649 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1650 fruAreaFieldNames = &BOARD_FRU_AREAS;
1651 break;
1652 case fruAreas::fruAreaProduct:
1653 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1654 // i.e. version, area length and language code
1655 offset = 3;
1656 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1657 break;
1658 default:
1659 std::cerr << "Don't know how to handle property " << propertyName
1660 << " \n";
1661 return false;
1662 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001663 if (fruAreaOffsetFieldValue == 0)
1664 {
1665 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301666 return false;
1667 }
1668
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001669 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001670 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1671 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001672 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001673 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001674 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001675 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301676
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001677 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001678 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301679 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001680 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001681 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301682 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001683 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301684 break;
1685 }
1686 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001687 if (!found)
1688 {
1689 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1690 if (pos == std::string::npos)
1691 {
1692 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1693 << propertyName << "\n";
1694 return false;
1695 }
1696 std::string fieldNumStr =
1697 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1698 size_t fieldNum = std::stoi(fieldNumStr);
1699 if (fieldNum == 0)
1700 {
1701 std::cerr << "PropertyName not recognized: " << propertyName
1702 << "\n";
1703 return false;
1704 }
1705 skipToFRUUpdateField += fieldNum;
1706 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301707
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001708 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301709 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001710 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001711 if (fieldLength < 0)
1712 {
1713 break;
1714 }
1715 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301716 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001717 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301718
1719 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001720 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001721 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301722 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001723 std::cerr << "Property " << propertyName << " not present \n";
1724 return false;
1725 }
1726 fruDataIter += 1 + fieldLength;
1727 size_t restFRUFieldsLoc = fruDataIter;
1728 size_t endOfFieldsLoc = 0;
1729 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1730 {
1731 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301732 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001733 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301734 break;
1735 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001736 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301737 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001738 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301739
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001740 std::vector<uint8_t> restFRUAreaFieldsData;
1741 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001742 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001743 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301744
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001745 // Push post update fru areas if any
1746 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001747 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1748 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001749 {
1750 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001751 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001752 if ((fruAreaLoc > endOfFieldsLoc) &&
1753 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1754 {
1755 nextFRUAreaLoc = fruAreaLoc;
1756 }
1757 }
1758 std::vector<uint8_t> restFRUAreasData;
1759 if (nextFRUAreaLoc)
1760 {
1761 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1762 fruData.size() - nextFRUAreaLoc,
1763 std::back_inserter(restFRUAreasData));
1764 }
1765
1766 // check FRU area size
1767 size_t fruAreaDataSize =
1768 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1769 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1770 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1771 {
1772
1773#ifdef ENABLE_FRU_AREA_RESIZE
1774 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1775 // round size to 8-byte blocks
1776 newFRUAreaSize =
1777 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1778 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1779 fruData.resize(newFRUDataSize);
1780 fruAreaSize = newFRUAreaSize;
1781 fruAreaEnd = fruAreaStart + fruAreaSize;
1782#else
1783 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1784 << " should not be greater than available FRU area size: "
1785 << fruAreaAvailableSize << "\n";
1786 return false;
1787#endif // ENABLE_FRU_AREA_RESIZE
1788 }
1789
Joshi-Mansid73b7442020-03-27 19:10:21 +05301790 // write new requested property field length and data
1791 constexpr uint8_t newTypeLenMask = 0xC0;
1792 fruData[fruUpdateFieldLoc] =
1793 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1794 fruUpdateFieldLoc++;
1795 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1796 fruData.begin() + fruUpdateFieldLoc);
1797
1798 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001799 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1800 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001801 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1802 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301803
1804 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001805 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1806 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301807
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001808#ifdef ENABLE_FRU_AREA_RESIZE
1809 ++nextFRUAreaNewLoc;
1810 ssize_t nextFRUAreaOffsetDiff =
1811 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1812 // Append rest FRU Areas if size changed and there were other sections after
1813 // updated one
1814 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1815 {
1816 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1817 fruData.begin() + nextFRUAreaNewLoc);
1818 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001819 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1820 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001821 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001822 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001823 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1824 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1825 {
1826 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1827 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1828 }
1829 }
1830 // Calculate new checksum
1831 std::vector<uint8_t> headerFRUData;
1832 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1833 size_t checksumVal = calculateChecksum(headerFRUData);
1834 fruData[7] = static_cast<uint8_t>(checksumVal);
1835 // fill zeros if FRU Area size decreased
1836 if (nextFRUAreaOffsetDiff < 0)
1837 {
1838 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1839 restFRUAreasData.size(),
1840 fruData.end(), 0);
1841 }
1842 }
1843#else
1844 // this is to avoid "unused variable" warning
1845 (void)nextFRUAreaNewLoc;
1846#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301847 if (fruData.empty())
1848 {
1849 return false;
1850 }
1851
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001852 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301853 fruData))
1854 {
1855 return false;
1856 }
1857
1858 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1859 rescanBusses(busMap, dbusInterfaceMap);
1860 return true;
1861}
1862
James Feist98132792019-07-09 13:29:09 -07001863int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001864{
1865 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001866 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001867 std::vector<fs::path> i2cBuses;
1868
James Feista3c180a2018-08-09 16:06:04 -07001869 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001870 {
1871 std::cerr << "unable to find i2c devices\n";
1872 return 1;
1873 }
James Feist3cb5fec2018-01-23 14:41:51 -08001874
Patrick Venture11f1ff42019-08-01 10:42:12 -07001875 // check for and load blacklist with initial buses.
1876 loadBlacklist(blacklistPath);
1877
Vijay Khemka065f6d92018-12-18 10:37:47 -08001878 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001879
James Feist6ebf9de2018-05-15 15:01:17 -07001880 // this is a map with keys of pair(bus number, address) and values of
1881 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001882 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001883 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1884 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001885
James Feist9eb0b582018-04-27 12:15:46 -07001886 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1887 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1888 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001889
James Feist5cb06082019-10-24 17:11:13 -07001890 iface->register_method("ReScan",
1891 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07001892
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001893 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07001894 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001895 });
1896
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001897 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07001898
1899 iface->register_method("WriteFru", [&](const uint8_t bus,
1900 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08001901 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001902 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07001903 {
James Feistddb78302018-09-06 11:45:42 -07001904 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07001905 return;
1906 }
1907 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07001908 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07001909 });
James Feist9eb0b582018-04-27 12:15:46 -07001910 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001911
James Feist9eb0b582018-04-27 12:15:46 -07001912 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08001913 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08001914 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07001915 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08001916 std::string,
1917 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07001918 values;
1919 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07001920 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07001921 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08001922 {
James Feistcb5661d2020-06-12 15:05:01 -07001923 powerIsOn = boost::ends_with(
1924 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07001925 }
James Feist6ebf9de2018-05-15 15:01:17 -07001926
James Feistcb5661d2020-06-12 15:05:01 -07001927 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07001928 {
James Feist5cb06082019-10-24 17:11:13 -07001929 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001930 }
James Feist918e18c2018-02-13 15:51:07 -08001931 };
James Feist9eb0b582018-04-27 12:15:46 -07001932
1933 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08001934 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07001935 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07001936 "openbmc_project/state/"
1937 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07001938 eventHandler);
1939
James Feist4131aea2018-03-09 09:47:30 -08001940 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07001941 inotify_add_watch(fd, I2C_DEV_LOCATION,
1942 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08001943 std::array<char, 4096> readBuffer;
1944 std::string pendingBuffer;
1945 // monitor for new i2c devices
1946 boost::asio::posix::stream_descriptor dirWatch(io, fd);
1947 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08001948 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08001949 std::size_t bytes_transferred) {
1950 if (ec)
1951 {
1952 std::cout << "Callback Error " << ec << "\n";
1953 return;
1954 }
1955 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08001956 while (pendingBuffer.size() > sizeof(inotify_event))
1957 {
James Feista465ccc2019-02-08 12:51:01 -08001958 const inotify_event* iEvent =
1959 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08001960 pendingBuffer.data());
1961 switch (iEvent->mask)
1962 {
James Feist9eb0b582018-04-27 12:15:46 -07001963 case IN_CREATE:
1964 case IN_MOVED_TO:
1965 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07001966 std::string name(iEvent->name);
1967 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07001968 {
James Feist5d7f4692020-06-17 18:22:33 -07001969 int bus = busStrToInt(name);
1970 if (bus < 0)
1971 {
1972 std::cerr << "Could not parse bus " << name
1973 << "\n";
1974 continue;
1975 }
1976 rescanOneBus(busMap, static_cast<uint8_t>(bus),
1977 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07001978 }
James Feist4131aea2018-03-09 09:47:30 -08001979 }
1980
1981 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
1982 }
James Feist6ebf9de2018-05-15 15:01:17 -07001983
James Feist4131aea2018-03-09 09:47:30 -08001984 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1985 watchI2cBusses);
1986 };
1987
1988 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05001989 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07001990 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08001991
James Feist3cb5fec2018-01-23 14:41:51 -08001992 io.run();
1993 return 0;
1994}