blob: 53d3118518bf0504aae2c47b3af40b2630ebb2c4 [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 Venturea49dc332019-10-26 08:32:02 -070018#include "Utils.hpp"
19
James Feist3b860982018-10-02 14:34:07 -070020#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080021#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070022#include <sys/inotify.h>
23#include <sys/ioctl.h>
24
James Feist3b860982018-10-02 14:34:07 -070025#include <boost/algorithm/string/predicate.hpp>
Brad Bishop82c84bb2020-08-26 14:12:50 -040026#include <boost/asio/deadline_timer.hpp>
27#include <boost/asio/io_service.hpp>
James Feist3b860982018-10-02 14:34:07 -070028#include <boost/container/flat_map.hpp>
James Feist8c505da2020-05-28 10:06:33 -070029#include <nlohmann/json.hpp>
30#include <sdbusplus/asio/connection.hpp>
31#include <sdbusplus/asio/object_server.hpp>
32
33#include <array>
James Feist3b860982018-10-02 14:34:07 -070034#include <chrono>
35#include <ctime>
Patrick Venturee3754002019-08-06 09:39:12 -070036#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080037#include <fstream>
Patrick Venturebaba7672019-10-26 09:26:41 -070038#include <functional>
James Feist3cb5fec2018-01-23 14:41:51 -080039#include <future>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070040#include <iomanip>
James Feist3cb5fec2018-01-23 14:41:51 -080041#include <iostream>
Patrick Venturee26395d2019-10-29 14:05:16 -070042#include <limits>
James Feist3f8a2782018-02-12 09:24:42 -080043#include <regex>
Patrick Venturec50e1ff2019-08-06 10:22:28 -070044#include <set>
45#include <sstream>
Patrick Venture11f1ff42019-08-01 10:42:12 -070046#include <string>
James Feist3b860982018-10-02 14:34:07 -070047#include <thread>
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +080048#include <utility>
James Feista465ccc2019-02-08 12:51:01 -080049#include <variant>
Patrick Venturec274f2f2019-10-26 09:27:23 -070050#include <vector>
James Feist3b860982018-10-02 14:34:07 -070051
James Feist8c505da2020-05-28 10:06:33 -070052extern "C"
53{
James Feist3b860982018-10-02 14:34:07 -070054#include <i2c/smbus.h>
55#include <linux/i2c-dev.h>
56}
James Feist3cb5fec2018-01-23 14:41:51 -080057
Ed Tanous072e25d2018-12-16 21:45:20 -080058namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080059static constexpr bool DEBUG = false;
60static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070061constexpr size_t MAX_FRU_SIZE = 512;
62constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070063constexpr size_t busTimeoutSeconds = 5;
Andrei Kartashev2f0de172020-08-13 14:29:40 +030064constexpr size_t fruBlockSize = 8; // FRU areas are measured in 8-byte blocks
Vijay Khemkac4732132020-12-17 12:19:10 -080065constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
James Feist3cb5fec2018-01-23 14:41:51 -080066
Patrick Venture11f1ff42019-08-01 10:42:12 -070067constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
68
James Feista465ccc2019-02-08 12:51:01 -080069const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080070 "/etc/fru/baseboard.fru.bin";
71
James Feista465ccc2019-02-08 12:51:01 -080072const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080073
Andrei Kartashevb45324a2020-10-14 17:01:47 +030074enum class resCodes
75{
76 resOK,
77 resWarn,
78 resErr
79};
80
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030081enum class fruAreas
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +030082{
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030083 fruAreaInternal = 0,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +030084 fruAreaChassis,
85 fruAreaBoard,
86 fruAreaProduct,
87 fruAreaMultirecord
88};
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +030089inline fruAreas operator++(fruAreas& x)
90{
91 return x = static_cast<fruAreas>(std::underlying_type<fruAreas>::type(x) +
92 1);
93}
94
95static const std::vector<std::string> FRU_AREA_NAMES = {
James Feist3cb5fec2018-01-23 14:41:51 -080096 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070097const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
Andrei Kartashev1c5b7062020-08-19 14:47:30 +030098using DeviceMap = boost::container::flat_map<int, std::vector<uint8_t>>;
James Feist3cb5fec2018-01-23 14:41:51 -080099using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
100
James Feist444830e2019-04-05 08:38:16 -0700101static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -0700102struct FindDevicesWithCallback;
103
Nikhil Potaded8884f12019-03-27 13:27:13 -0700104static BusMap busMap;
105
James Feistcb5661d2020-06-12 15:05:01 -0700106static bool powerIsOn = false;
107
James Feist8a983922019-10-24 17:11:56 -0700108static boost::container::flat_map<
109 std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
110 foundDevices;
111
James Feist7972bb92019-11-13 15:59:24 -0800112static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
113
James Feist5cb06082019-10-24 17:11:13 -0700114boost::asio::io_service io;
115auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
116auto objServer = sdbusplus::asio::object_server(systemBus);
117
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300118static const std::vector<std::string> CHASSIS_FRU_AREAS = {"PART_NUMBER",
119 "SERIAL_NUMBER"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530120
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300121static const std::vector<std::string> BOARD_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300122 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
123 "FRU_VERSION_ID"};
Joshi-Mansid73b7442020-03-27 19:10:21 +0530124
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300125static const std::vector<std::string> PRODUCT_FRU_AREAS = {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +0300126 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
127 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID"};
128
129static const std::string FRU_CUSTOM_FIELD_NAME = "INFO_AM";
Joshi-Mansid73b7442020-03-27 19:10:21 +0530130
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300131static inline unsigned int getHeaderAreaFieldOffset(fruAreas area)
132{
133 return static_cast<unsigned int>(area) + 1;
134}
135static inline const std::string& getFruAreaName(fruAreas area)
136{
137 return FRU_AREA_NAMES[static_cast<unsigned int>(area)];
138}
Patrick Venturebaba7672019-10-26 09:26:41 -0700139bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300140uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
141 std::vector<uint8_t>::const_iterator end);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300142bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +0530143 const std::string& assetTag, uint32_t bus, uint32_t address,
144 std::string propertyName,
145 boost::container::flat_map<
146 std::pair<size_t, size_t>,
147 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap);
Patrick Venturebaba7672019-10-26 09:26:41 -0700148
Xiang Liu2801a702020-01-20 14:29:34 -0800149using ReadBlockFunc =
150 std::function<int64_t(int flag, int file, uint16_t address, uint16_t offset,
151 uint8_t length, uint8_t* outBuf)>;
Patrick Venturebaba7672019-10-26 09:26:41 -0700152
153// Read and validate FRU contents, given the flag required for raw i2c, the open
154// file handle, a read method, and a helper string for failures.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300155std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300156 ReadBlockFunc readBlock,
157 const std::string& errorHelp)
Patrick Venturebaba7672019-10-26 09:26:41 -0700158{
159 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
160
Xiang Liu2801a702020-01-20 14:29:34 -0800161 if (readBlock(flag, file, address, 0x0, 0x8, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700162 {
163 std::cerr << "failed to read " << errorHelp << "\n";
164 return {};
165 }
166
167 // check the header checksum
168 if (!validateHeader(blockData))
169 {
170 if (DEBUG)
171 {
172 std::cerr << "Illegal header " << errorHelp << "\n";
173 }
174
175 return {};
176 }
177
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300178 std::vector<uint8_t> device;
Patrick Venturebaba7672019-10-26 09:26:41 -0700179 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
180
Patrick Venturee26395d2019-10-29 14:05:16 -0700181 bool hasMultiRecords = false;
Brad Bishopef3cdc92020-10-01 10:36:21 -0400182 size_t fruLength = fruBlockSize; // At least FRU header is present
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300183 for (fruAreas area = fruAreas::fruAreaInternal;
184 area <= fruAreas::fruAreaMultirecord; ++area)
Patrick Venturebaba7672019-10-26 09:26:41 -0700185 {
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700186 // Offset value can be 255.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300187 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
Patrick Venturebaba7672019-10-26 09:26:41 -0700188 if (areaOffset == 0)
189 {
190 continue;
191 }
192
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300193 // MultiRecords are different. area is not tracking section, it's
194 // walking the common header.
195 if (area == fruAreas::fruAreaMultirecord)
Patrick Venturee26395d2019-10-29 14:05:16 -0700196 {
197 hasMultiRecords = true;
198 break;
199 }
200
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300201 areaOffset *= fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700202
Xiang Liu2801a702020-01-20 14:29:34 -0800203 if (readBlock(flag, file, address, static_cast<uint16_t>(areaOffset),
204 0x2, blockData.data()) < 0)
Patrick Venturebaba7672019-10-26 09:26:41 -0700205 {
206 std::cerr << "failed to read " << errorHelp << "\n";
207 return {};
208 }
209
Patrick Venturef2ad76b2019-10-30 08:49:27 -0700210 // Ignore data type (blockData is already unsigned).
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300211 size_t length = blockData[1] * fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700212 areaOffset += length;
213 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
214 }
215
Patrick Venturee26395d2019-10-29 14:05:16 -0700216 if (hasMultiRecords)
217 {
218 // device[area count] is the index to the last area because the 0th
219 // entry is not an offset in the common header.
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +0300220 unsigned int areaOffset =
221 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300222 areaOffset *= fruBlockSize;
Patrick Venturee26395d2019-10-29 14:05:16 -0700223
224 // the multi-area record header is 5 bytes long.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300225 constexpr size_t multiRecordHeaderSize = 5;
226 constexpr uint8_t multiRecordEndOfListMask = 0x80;
Patrick Venturee26395d2019-10-29 14:05:16 -0700227
228 // Sanity hard-limit to 64KB.
229 while (areaOffset < std::numeric_limits<uint16_t>::max())
230 {
231 // In multi-area, the area offset points to the 0th record, each
232 // record has 3 bytes of the header we care about.
Xiang Liu2801a702020-01-20 14:29:34 -0800233 if (readBlock(flag, file, address,
234 static_cast<uint16_t>(areaOffset), 0x3,
Patrick Venturee26395d2019-10-29 14:05:16 -0700235 blockData.data()) < 0)
236 {
237 std::cerr << "failed to read " << errorHelp << "\n";
238 return {};
239 }
240
241 // Ok, let's check the record length, which is in bytes (unsigned,
242 // up to 255, so blockData should hold uint8_t not char)
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300243 size_t recordLength = blockData[2];
Patrick Venturee26395d2019-10-29 14:05:16 -0700244 areaOffset += (recordLength + multiRecordHeaderSize);
245 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
246
247 // If this is the end of the list bail.
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300248 if ((blockData[1] & multiRecordEndOfListMask))
Patrick Venturee26395d2019-10-29 14:05:16 -0700249 {
250 break;
251 }
252 }
253 }
254
Patrick Venturebaba7672019-10-26 09:26:41 -0700255 // You already copied these first 8 bytes (the ipmi fru header size)
Brad Bishopef3cdc92020-10-01 10:36:21 -0400256 fruLength -= std::min(fruBlockSize, fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700257
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300258 int readOffset = fruBlockSize;
Patrick Venturebaba7672019-10-26 09:26:41 -0700259
260 while (fruLength > 0)
261 {
Brad Bishopef3cdc92020-10-01 10:36:21 -0400262 size_t requestLength =
263 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700264
Xiang Liu2801a702020-01-20 14:29:34 -0800265 if (readBlock(flag, file, address, static_cast<uint16_t>(readOffset),
Patrick Venturebaba7672019-10-26 09:26:41 -0700266 static_cast<uint8_t>(requestLength),
267 blockData.data()) < 0)
268 {
269 std::cerr << "failed to read " << errorHelp << "\n";
270 return {};
271 }
272
273 device.insert(device.end(), blockData.begin(),
274 blockData.begin() + requestLength);
275
276 readOffset += requestLength;
Brad Bishopef3cdc92020-10-01 10:36:21 -0400277 fruLength -= std::min(requestLength, fruLength);
Patrick Venturebaba7672019-10-26 09:26:41 -0700278 }
279
280 return device;
281}
282
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700283// Given a bus/address, produce the path in sysfs for an eeprom.
284static std::string getEepromPath(size_t bus, size_t address)
285{
286 std::stringstream output;
287 output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
288 << std::setfill('0') << std::setw(4) << std::hex << address
289 << "/eeprom";
290 return output.str();
291}
292
293static bool hasEepromFile(size_t bus, size_t address)
294{
295 auto path = getEepromPath(bus, address);
296 try
297 {
298 return fs::exists(path);
299 }
300 catch (...)
301 {
302 return false;
303 }
304}
305
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700306static int64_t readFromEeprom(int flag __attribute__((unused)), int fd,
Xiang Liu2801a702020-01-20 14:29:34 -0800307 uint16_t address __attribute__((unused)),
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700308 uint16_t offset, uint8_t len, uint8_t* buf)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700309{
310 auto result = lseek(fd, offset, SEEK_SET);
311 if (result < 0)
312 {
313 std::cerr << "failed to seek\n";
314 return -1;
315 }
316
Patrick Venture3ac8e4f2019-10-28 13:07:21 -0700317 return read(fd, buf, len);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700318}
319
James Feist5d7f4692020-06-17 18:22:33 -0700320static int busStrToInt(const std::string& busName)
321{
322 auto findBus = busName.rfind("-");
323 if (findBus == std::string::npos)
324 {
325 return -1;
326 }
327 return std::stoi(busName.substr(findBus + 1));
328}
329
James Feist7972bb92019-11-13 15:59:24 -0800330static int getRootBus(size_t bus)
331{
332 auto ec = std::error_code();
333 auto path = std::filesystem::read_symlink(
334 std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
335 std::to_string(bus) + "/mux_device"),
336 ec);
337 if (ec)
338 {
339 return -1;
340 }
341
342 std::string filename = path.filename();
343 auto findBus = filename.find("-");
344 if (findBus == std::string::npos)
345 {
346 return -1;
347 }
348 return std::stoi(filename.substr(0, findBus));
349}
350
James Feistc95cb142018-02-26 10:41:42 -0800351static bool isMuxBus(size_t bus)
352{
Ed Tanous072e25d2018-12-16 21:45:20 -0800353 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -0800354 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
355}
356
James Feist8a983922019-10-24 17:11:56 -0700357static void makeProbeInterface(size_t bus, size_t address)
358{
359 if (isMuxBus(bus))
360 {
361 return; // the mux buses are random, no need to publish
362 }
363 auto [it, success] = foundDevices.emplace(
364 std::make_pair(bus, address),
365 objServer.add_interface(
366 "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
367 std::to_string(address),
368 "xyz.openbmc_project.Inventory.Item.I2CDevice"));
369 if (!success)
370 {
371 return; // already added
372 }
373 it->second->register_property("Bus", bus);
374 it->second->register_property("Address", address);
375 it->second->initialize();
376}
377
Vijay Khemka2d681f62018-11-06 15:51:00 -0800378static int isDevice16Bit(int file)
379{
380 /* Get first byte */
381 int byte1 = i2c_smbus_read_byte_data(file, 0);
382 if (byte1 < 0)
383 {
384 return byte1;
385 }
386 /* Read 7 more bytes, it will read same first byte in case of
387 * 8 bit but it will read next byte in case of 16 bit
388 */
389 for (int i = 0; i < 7; i++)
390 {
391 int byte2 = i2c_smbus_read_byte_data(file, 0);
392 if (byte2 < 0)
393 {
394 return byte2;
395 }
396 if (byte2 != byte1)
397 {
398 return 1;
399 }
400 }
401 return 0;
402}
403
Xiang Liu2801a702020-01-20 14:29:34 -0800404// Issue an I2C transaction to first write to_slave_buf_len bytes,then read
405// from_slave_buf_len bytes.
406static int i2c_smbus_write_then_read(int file, uint16_t address,
407 uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
408 uint8_t* fromSlaveBuf,
409 uint8_t fromSlaveBufLen)
Vijay Khemka2d681f62018-11-06 15:51:00 -0800410{
Xiang Liu2801a702020-01-20 14:29:34 -0800411 if (toSlaveBuf == NULL || toSlaveBufLen == 0 || fromSlaveBuf == NULL ||
412 fromSlaveBufLen == 0)
413 {
414 return -1;
415 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800416
Xiang Liu2801a702020-01-20 14:29:34 -0800417#define SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT 2
418 struct i2c_msg msgs[SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT];
419 struct i2c_rdwr_ioctl_data rdwr;
420
421 msgs[0].addr = address;
422 msgs[0].flags = 0;
423 msgs[0].len = toSlaveBufLen;
424 msgs[0].buf = toSlaveBuf;
425 msgs[1].addr = address;
426 msgs[1].flags = I2C_M_RD;
427 msgs[1].len = fromSlaveBufLen;
428 msgs[1].buf = fromSlaveBuf;
429
430 rdwr.msgs = msgs;
431 rdwr.nmsgs = SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT;
432
433 int ret = ioctl(file, I2C_RDWR, &rdwr);
434
435 return (ret == SMBUS_IOCTL_WRITE_THEN_READ_MSG_COUNT) ? ret : -1;
436}
437
438static int64_t readBlockData(int flag, int file, uint16_t address,
439 uint16_t offset, uint8_t len, uint8_t* buf)
440{
Vijay Khemka2d681f62018-11-06 15:51:00 -0800441 if (flag == 0)
442 {
Xiang Liu2801a702020-01-20 14:29:34 -0800443 return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
444 len, buf);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800445 }
446
Xiang Liu2801a702020-01-20 14:29:34 -0800447 offset = htobe16(offset);
448 return i2c_smbus_write_then_read(
449 file, address, reinterpret_cast<uint8_t*>(&offset), 2, buf, len);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800450}
451
James Feist24bae7a2019-04-03 09:50:56 -0700452bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
453{
454 // ipmi spec format version number is currently at 1, verify it
Vijay Khemkac4732132020-12-17 12:19:10 -0800455 if (blockData[0] != fruVersion)
James Feist24bae7a2019-04-03 09:50:56 -0700456 {
Vijay Khemkac4732132020-12-17 12:19:10 -0800457 if (DEBUG)
458 {
459 std::cerr << "FRU spec version " << (int)(blockData[0])
460 << " not supported. Supported version is "
461 << (int)(fruVersion) << "\n";
462 }
James Feist24bae7a2019-04-03 09:50:56 -0700463 return false;
464 }
465
466 // verify pad is set to 0
467 if (blockData[6] != 0x0)
468 {
Vijay Khemkac4732132020-12-17 12:19:10 -0800469 if (DEBUG)
470 {
471 std::cerr << "PAD value in header is non zero, value is "
472 << (int)(blockData[6]) << "\n";
473 }
James Feist24bae7a2019-04-03 09:50:56 -0700474 return false;
475 }
476
477 // verify offsets are 0, or don't point to another offset
478 std::set<uint8_t> foundOffsets;
479 for (int ii = 1; ii < 6; ii++)
480 {
481 if (blockData[ii] == 0)
482 {
483 continue;
484 }
James Feist0eb40352019-04-09 14:44:04 -0700485 auto inserted = foundOffsets.insert(blockData[ii]);
486 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700487 {
488 return false;
489 }
490 }
491
492 // validate checksum
493 size_t sum = 0;
494 for (int jj = 0; jj < 7; jj++)
495 {
496 sum += blockData[jj];
497 }
498 sum = (256 - sum) & 0xFF;
499
500 if (sum != blockData[7])
501 {
Vijay Khemkac4732132020-12-17 12:19:10 -0800502 if (DEBUG)
503 {
504 std::cerr << "Checksum " << (int)(blockData[7])
505 << " is invalid. calculated checksum is " << (int)(sum)
506 << "\n";
507 }
James Feist24bae7a2019-04-03 09:50:56 -0700508 return false;
509 }
510 return true;
511}
512
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700513// TODO: This code is very similar to the non-eeprom version and can be merged
514// with some tweaks.
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300515static std::vector<uint8_t> processEeprom(int bus, int address)
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700516{
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700517 auto path = getEepromPath(bus, address);
518
519 int file = open(path.c_str(), O_RDONLY);
520 if (file < 0)
521 {
522 std::cerr << "Unable to open eeprom file: " << path << "\n";
Patrick Venturebaba7672019-10-26 09:26:41 -0700523 return {};
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700524 }
525
Patrick Venturebaba7672019-10-26 09:26:41 -0700526 std::string errorMessage = "eeprom at " + std::to_string(bus) +
527 " address " + std::to_string(address);
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300528 std::vector<uint8_t> device = readFRUContents(
Xiang Liu2801a702020-01-20 14:29:34 -0800529 0, file, static_cast<uint16_t>(address), readFromEeprom, errorMessage);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700530
531 close(file);
532 return device;
533}
534
535std::set<int> findI2CEeproms(int i2cBus, std::shared_ptr<DeviceMap> devices)
536{
537 std::set<int> foundList;
538
539 std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
540
541 // For each file listed under the i2c device
542 // NOTE: This should be faster than just checking for each possible address
543 // path.
544 for (const auto& p : fs::directory_iterator(path))
545 {
546 const std::string node = p.path().string();
547 std::smatch m;
548 bool found =
549 std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
550
551 if (!found)
552 {
553 continue;
554 }
555 if (m.size() != 2)
556 {
557 std::cerr << "regex didn't capture\n";
558 continue;
559 }
560
561 std::ssub_match subMatch = m[1];
562 std::string addressString = subMatch.str();
563
564 std::size_t ignored;
565 const int hexBase = 16;
566 int address = std::stoi(addressString, &ignored, hexBase);
567
568 const std::string eeprom = node + "/eeprom";
569
570 try
571 {
572 if (!fs::exists(eeprom))
573 {
574 continue;
575 }
576 }
577 catch (...)
578 {
579 continue;
580 }
581
582 // There is an eeprom file at this address, it may have invalid
583 // contents, but we found it.
584 foundList.insert(address);
585
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300586 std::vector<uint8_t> device = processEeprom(i2cBus, address);
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700587 if (!device.empty())
588 {
589 devices->emplace(address, device);
590 }
591 }
592
593 return foundList;
594}
595
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300596int getBusFRUs(int file, int first, int last, int bus,
Patrick Venture4f47fe62019-08-08 16:30:38 -0700597 std::shared_ptr<DeviceMap> devices)
James Feist3cb5fec2018-01-23 14:41:51 -0800598{
James Feist3cb5fec2018-01-23 14:41:51 -0800599
James Feist26c27ad2018-07-25 15:09:40 -0700600 std::future<int> future = std::async(std::launch::async, [&]() {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700601 // NOTE: When reading the devices raw on the bus, it can interfere with
602 // the driver's ability to operate, therefore read eeproms first before
603 // scanning for devices without drivers. Several experiments were run
604 // and it was determined that if there were any devices on the bus
605 // before the eeprom was hit and read, the eeprom driver wouldn't open
606 // while the bus device was open. An experiment was not performed to see
607 // if this issue was resolved if the i2c bus device was closed, but
608 // hexdumps of the eeprom later were successful.
609
610 // Scan for i2c eeproms loaded on this bus.
611 std::set<int> skipList = findI2CEeproms(bus, devices);
James Feist7972bb92019-11-13 15:59:24 -0800612 std::set<size_t>& failedItems = failedAddresses[bus];
613
614 std::set<size_t>* rootFailures = nullptr;
615 int rootBus = getRootBus(bus);
616
617 if (rootBus >= 0)
618 {
619 rootFailures = &(failedAddresses[rootBus]);
620 }
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700621
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530622 constexpr int startSkipSlaveAddr = 0;
623 constexpr int endSkipSlaveAddr = 12;
624
James Feist26c27ad2018-07-25 15:09:40 -0700625 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800626 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -0700627 if (skipList.find(ii) != skipList.end())
628 {
629 continue;
630 }
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530631 // skipping since no device is present in this range
632 if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
633 {
634 continue;
635 }
James Feist26c27ad2018-07-25 15:09:40 -0700636 // Set slave address
Rajashekar Gade Reddyfa8d3222020-05-13 08:27:03 +0530637 if (ioctl(file, I2C_SLAVE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800638 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +0300639 std::cerr << "device at bus " << bus << " address " << ii
Patrick Venture5d8b61d2019-08-06 12:36:10 -0700640 << " busy\n";
James Feist26c27ad2018-07-25 15:09:40 -0700641 continue;
642 }
643 // probe
644 else if (i2c_smbus_read_byte(file) < 0)
645 {
646 continue;
647 }
James Feist3cb5fec2018-01-23 14:41:51 -0800648
James Feist26c27ad2018-07-25 15:09:40 -0700649 if (DEBUG)
650 {
Patrick Venture98e0cf32019-08-02 11:11:03 -0700651 std::cout << "something at bus " << bus << " addr " << ii
James Feist26c27ad2018-07-25 15:09:40 -0700652 << "\n";
653 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800654
James Feist8a983922019-10-24 17:11:56 -0700655 makeProbeInterface(bus, ii);
656
James Feist7972bb92019-11-13 15:59:24 -0800657 if (failedItems.find(ii) != failedItems.end())
658 {
659 // if we failed to read it once, unlikely we can read it later
660 continue;
661 }
662
663 if (rootFailures != nullptr)
664 {
665 if (rootFailures->find(ii) != rootFailures->end())
666 {
667 continue;
668 }
669 }
670
Vijay Khemka2d681f62018-11-06 15:51:00 -0800671 /* Check for Device type if it is 8 bit or 16 bit */
672 int flag = isDevice16Bit(file);
673 if (flag < 0)
674 {
675 std::cerr << "failed to read bus " << bus << " address " << ii
676 << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700677 if (powerIsOn)
678 {
679 failedItems.insert(ii);
680 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800681 continue;
682 }
683
Patrick Venturebaba7672019-10-26 09:26:41 -0700684 std::string errorMessage =
685 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300686 std::vector<uint8_t> device =
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300687 readFRUContents(flag, file, static_cast<uint16_t>(ii),
Xiang Liu2801a702020-01-20 14:29:34 -0800688 readBlockData, errorMessage);
Patrick Venturebaba7672019-10-26 09:26:41 -0700689 if (device.empty())
James Feist26c27ad2018-07-25 15:09:40 -0700690 {
James Feist26c27ad2018-07-25 15:09:40 -0700691 continue;
692 }
James Feist26c27ad2018-07-25 15:09:40 -0700693
Patrick Venture786f1792019-08-05 16:33:44 -0700694 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800695 }
James Feist26c27ad2018-07-25 15:09:40 -0700696 return 1;
697 });
698 std::future_status status =
699 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
700 if (status == std::future_status::timeout)
701 {
702 std::cerr << "Error reading bus " << bus << "\n";
James Feistcb5661d2020-06-12 15:05:01 -0700703 if (powerIsOn)
704 {
705 busBlacklist.insert(bus);
706 }
James Feist444830e2019-04-05 08:38:16 -0700707 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700708 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800709 }
710
James Feist444830e2019-04-05 08:38:16 -0700711 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700712 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800713}
714
Patrick Venture11f1ff42019-08-01 10:42:12 -0700715void loadBlacklist(const char* path)
716{
717 std::ifstream blacklistStream(path);
718 if (!blacklistStream.good())
719 {
720 // File is optional.
721 std::cerr << "Cannot open blacklist file.\n\n";
722 return;
723 }
724
725 nlohmann::json data =
726 nlohmann::json::parse(blacklistStream, nullptr, false);
727 if (data.is_discarded())
728 {
729 std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
730 "exiting\n";
731 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700732 }
733
734 // It's expected to have at least one field, "buses" that is an array of the
735 // buses by integer. Allow for future options to exclude further aspects,
736 // such as specific addresses or ranges.
737 if (data.type() != nlohmann::json::value_t::object)
738 {
739 std::cerr << "Illegal blacklist, expected to read dictionary\n";
740 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700741 }
742
743 // If buses field is missing, that's fine.
744 if (data.count("buses") == 1)
745 {
746 // Parse the buses array after a little validation.
747 auto buses = data.at("buses");
748 if (buses.type() != nlohmann::json::value_t::array)
749 {
750 // Buses field present but invalid, therefore this is an error.
751 std::cerr << "Invalid contents for blacklist buses field\n";
752 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700753 }
754
755 // Catch exception here for type mis-match.
756 try
757 {
758 for (const auto& bus : buses)
759 {
760 busBlacklist.insert(bus.get<size_t>());
761 }
762 }
763 catch (const nlohmann::detail::type_error& e)
764 {
765 // Type mis-match is a critical error.
766 std::cerr << "Invalid bus type: " << e.what() << "\n";
767 std::exit(EXIT_FAILURE);
Patrick Venture11f1ff42019-08-01 10:42:12 -0700768 }
769 }
770
771 return;
772}
773
James Feista465ccc2019-02-08 12:51:01 -0800774static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist98132792019-07-09 13:29:09 -0700775 BusMap& busmap)
James Feist3cb5fec2018-01-23 14:41:51 -0800776{
James Feista465ccc2019-02-08 12:51:01 -0800777 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800778 {
James Feist5d7f4692020-06-17 18:22:33 -0700779 int bus = busStrToInt(i2cBus);
James Feist0c3980a2019-12-19 11:09:27 -0800780
James Feist5d7f4692020-06-17 18:22:33 -0700781 if (bus < 0)
782 {
783 std::cerr << "Cannot translate " << i2cBus << " to int\n";
784 continue;
785 }
James Feist444830e2019-04-05 08:38:16 -0700786 if (busBlacklist.find(bus) != busBlacklist.end())
787 {
788 continue; // skip previously failed busses
789 }
James Feist3cb5fec2018-01-23 14:41:51 -0800790
James Feist0c3980a2019-12-19 11:09:27 -0800791 int rootBus = getRootBus(bus);
792 if (busBlacklist.find(rootBus) != busBlacklist.end())
793 {
794 continue;
795 }
796
James Feist3cb5fec2018-01-23 14:41:51 -0800797 auto file = open(i2cBus.c_str(), O_RDWR);
798 if (file < 0)
799 {
800 std::cerr << "unable to open i2c device " << i2cBus.string()
801 << "\n";
802 continue;
803 }
804 unsigned long funcs = 0;
805
806 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
807 {
808 std::cerr
Patrick Venture98e0cf32019-08-02 11:11:03 -0700809 << "Error: Could not get the adapter functionality matrix bus "
James Feist3cb5fec2018-01-23 14:41:51 -0800810 << bus << "\n";
811 continue;
812 }
813 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
814 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
815 {
816 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
817 << bus << "\n";
818 continue;
819 }
James Feist98132792019-07-09 13:29:09 -0700820 auto& device = busmap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800821 device = std::make_shared<DeviceMap>();
822
Nikhil Potaded8884f12019-03-27 13:27:13 -0700823 // i2cdetect by default uses the range 0x03 to 0x77, as
824 // this is what we have tested with, use this range. Could be
825 // changed in future.
826 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800827 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700828 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800829 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700830
831 // fd is closed in this function in case the bus locks up
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300832 getBusFRUs(file, 0x03, 0x77, bus, device);
Nikhil Potaded8884f12019-03-27 13:27:13 -0700833
834 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800835 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700836 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800837 }
James Feist3cb5fec2018-01-23 14:41:51 -0800838 }
James Feist3cb5fec2018-01-23 14:41:51 -0800839}
840
James Feist6ebf9de2018-05-15 15:01:17 -0700841// this class allows an async response after all i2c devices are discovered
James Feist8c505da2020-05-28 10:06:33 -0700842struct FindDevicesWithCallback :
843 std::enable_shared_from_this<FindDevicesWithCallback>
James Feist6ebf9de2018-05-15 15:01:17 -0700844{
James Feista465ccc2019-02-08 12:51:01 -0800845 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
James Feist5cb06082019-10-24 17:11:13 -0700846 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -0800847 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700848 _i2cBuses(i2cBuses),
James Feist5cb06082019-10-24 17:11:13 -0700849 _busMap(busmap), _callback(std::move(callback))
James Feist8c505da2020-05-28 10:06:33 -0700850 {}
James Feist6ebf9de2018-05-15 15:01:17 -0700851 ~FindDevicesWithCallback()
852 {
853 _callback();
854 }
855 void run()
856 {
James Feist98132792019-07-09 13:29:09 -0700857 FindI2CDevices(_i2cBuses, _busMap);
James Feist6ebf9de2018-05-15 15:01:17 -0700858 }
859
James Feista465ccc2019-02-08 12:51:01 -0800860 const std::vector<fs::path>& _i2cBuses;
James Feista465ccc2019-02-08 12:51:01 -0800861 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700862 std::function<void(void)> _callback;
863};
864
James Feist3cb5fec2018-01-23 14:41:51 -0800865static const std::tm intelEpoch(void)
866{
James Feist98132792019-07-09 13:29:09 -0700867 std::tm val = {};
James Feist3cb5fec2018-01-23 14:41:51 -0800868 val.tm_year = 1996 - 1900;
869 return val;
870}
871
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800872static char sixBitToChar(uint8_t val)
873{
874 return static_cast<char>((val & 0x3f) + ' ');
875}
876
877/* 0xd - 0xf are reserved values, but not fatal; use a placeholder char. */
878static const char bcdHighChars[] = {
879 ' ', '-', '.', 'X', 'X', 'X',
880};
881
882static char bcdPlusToChar(uint8_t val)
883{
884 val &= 0xf;
885 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
886}
887
888enum class DecodeState
889{
890 ok,
891 end,
892 err,
893};
894
895enum FRUDataEncoding
896{
897 binary = 0x0,
898 bcdPlus = 0x1,
899 sixBitASCII = 0x2,
900 languageDependent = 0x3,
901};
902
903/* Decode FRU data into a std::string, given an input iterator and end. If the
904 * state returned is fruDataOk, then the resulting string is the decoded FRU
905 * data. The input iterator is advanced past the data consumed.
906 *
907 * On fruDataErr, we have lost synchronisation with the length bytes, so the
908 * iterator is no longer usable.
909 */
910static std::pair<DecodeState, std::string>
Andrei Kartashev2f0de172020-08-13 14:29:40 +0300911 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300912 const std::vector<uint8_t>::const_iterator& end)
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800913{
914 std::string value;
915 unsigned int i;
916
917 /* we need at least one byte to decode the type/len header */
918 if (iter == end)
919 {
920 std::cerr << "Truncated FRU data\n";
921 return make_pair(DecodeState::err, value);
922 }
923
924 uint8_t c = *(iter++);
925
926 /* 0xc1 is the end marker */
927 if (c == 0xc1)
928 {
929 return make_pair(DecodeState::end, value);
930 }
931
932 /* decode type/len byte */
933 uint8_t type = static_cast<uint8_t>(c >> 6);
934 uint8_t len = static_cast<uint8_t>(c & 0x3f);
935
936 /* we should have at least len bytes of data available overall */
937 if (iter + len > end)
938 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +0300939 std::cerr << "FRU data field extends past end of FRU area data\n";
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800940 return make_pair(DecodeState::err, value);
941 }
942
943 switch (type)
944 {
945 case FRUDataEncoding::binary:
Andrei Kartashevc994c022020-08-10 18:51:49 +0300946 {
947 std::stringstream ss;
948 ss << std::hex << std::setfill('0');
949 for (i = 0; i < len; i++, iter++)
950 {
951 uint8_t val = static_cast<uint8_t>(*iter);
952 ss << std::setw(2) << static_cast<int>(val);
953 }
954 value = ss.str();
955 break;
956 }
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800957 case FRUDataEncoding::languageDependent:
958 /* For language-code dependent encodings, assume 8-bit ASCII */
959 value = std::string(iter, iter + len);
960 iter += len;
961 break;
962
963 case FRUDataEncoding::bcdPlus:
964 value = std::string();
965 for (i = 0; i < len; i++, iter++)
966 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300967 uint8_t val = *iter;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800968 value.push_back(bcdPlusToChar(val >> 4));
969 value.push_back(bcdPlusToChar(val & 0xf));
970 }
971 break;
972
973 case FRUDataEncoding::sixBitASCII:
974 {
Andrei Kartasheve707de62020-08-10 18:33:29 +0300975 unsigned int accum = 0;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800976 unsigned int accumBitLen = 0;
977 value = std::string();
978 for (i = 0; i < len; i++, iter++)
979 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +0300980 accum |= *iter << accumBitLen;
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +0800981 accumBitLen += 8;
982 while (accumBitLen >= 6)
983 {
984 value.push_back(sixBitToChar(accum & 0x3f));
985 accum >>= 6;
986 accumBitLen -= 6;
987 }
988 }
989 }
990 break;
991 }
992
993 return make_pair(DecodeState::ok, value);
994}
995
Andrei Kartashev2a7e3952020-09-02 20:32:26 +0300996static void checkLang(uint8_t lang)
997{
998 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
999 // but we don't support that.
1000 if (lang && lang != 25)
1001 {
1002 std::cerr << "Warning: language other then English is not "
1003 "supported \n";
1004 }
1005}
1006
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001007resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
1008 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -08001009{
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001010 resCodes ret = resCodes::resOK;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001011 if (fruBytes.size() <= fruBlockSize)
James Feist3cb5fec2018-01-23 14:41:51 -08001012 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001013 std::cerr << "Error: trying to parse empty FRU \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001014 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -08001015 }
James Feist9eb0b582018-04-27 12:15:46 -07001016 result["Common_Format_Version"] =
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001017 std::to_string(static_cast<int>(*fruBytes.begin()));
James Feist3cb5fec2018-01-23 14:41:51 -08001018
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001019 const std::vector<std::string>* fruAreaFieldNames;
James Feist3cb5fec2018-01-23 14:41:51 -08001020
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001021 // Don't parse Internal and Multirecord areas
1022 for (fruAreas area = fruAreas::fruAreaChassis;
1023 area <= fruAreas::fruAreaProduct; ++area)
James Feist3cb5fec2018-01-23 14:41:51 -08001024 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001025
1026 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
1027 if (offset == 0)
James Feist3cb5fec2018-01-23 14:41:51 -08001028 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001029 continue;
1030 }
1031 offset *= fruBlockSize;
1032 std::vector<uint8_t>::const_iterator fruBytesIter =
1033 fruBytes.begin() + offset;
1034 if (fruBytesIter + fruBlockSize >= fruBytes.end())
1035 {
1036 std::cerr << "Not enough data to parse \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001037 return resCodes::resErr;
James Feist3cb5fec2018-01-23 14:41:51 -08001038 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001039 // check for format version 1
1040 if (*fruBytesIter != 0x01)
James Feist3cb5fec2018-01-23 14:41:51 -08001041 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001042 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001043 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001044 }
1045 ++fruBytesIter;
1046 uint8_t fruAreaSize = *fruBytesIter * fruBlockSize;
1047 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
1048 fruBytes.begin() + offset + fruAreaSize - 1;
1049 ++fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001050
Andrei Kartashev272bafd2020-10-09 12:05:32 +03001051 uint8_t fruComputedChecksum =
1052 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
1053 if (fruComputedChecksum != *fruBytesIterEndArea)
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001054 {
Andrei Kartashev272bafd2020-10-09 12:05:32 +03001055 std::stringstream ss;
1056 ss << std::hex << std::setfill('0');
1057 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
1058 ss << "\tComputed checksum: 0x" << std::setw(2)
1059 << static_cast<int>(fruComputedChecksum) << "\n";
1060 ss << "\tThe read checksum: 0x" << std::setw(2)
1061 << static_cast<int>(*fruBytesIterEndArea) << "\n";
1062 std::cerr << ss.str();
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001063 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001064 }
1065
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001066 switch (area)
1067 {
1068 case fruAreas::fruAreaChassis:
James Feist3cb5fec2018-01-23 14:41:51 -08001069 {
1070 result["CHASSIS_TYPE"] =
1071 std::to_string(static_cast<int>(*fruBytesIter));
1072 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001073 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001074 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001075 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001076 case fruAreas::fruAreaBoard:
James Feist3cb5fec2018-01-23 14:41:51 -08001077 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001078 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001079 result["BOARD_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001080 std::to_string(static_cast<int>(lang));
1081 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -08001082 fruBytesIter += 1;
James Feist3cb5fec2018-01-23 14:41:51 -08001083
1084 unsigned int minutes = *fruBytesIter |
1085 *(fruBytesIter + 1) << 8 |
1086 *(fruBytesIter + 2) << 16;
1087 std::tm fruTime = intelEpoch();
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001088 std::time_t timeValue = std::mktime(&fruTime);
James Feist3cb5fec2018-01-23 14:41:51 -08001089 timeValue += minutes * 60;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001090 fruTime = *std::gmtime(&timeValue);
James Feist3cb5fec2018-01-23 14:41:51 -08001091
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001092 // Tue Nov 20 23:08:00 2018
1093 char timeString[32] = {0};
1094 auto bytes = std::strftime(timeString, sizeof(timeString),
Patrick Venturefff050a2019-08-13 11:44:30 -07001095 "%Y-%m-%d - %H:%M:%S", &fruTime);
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001096 if (bytes == 0)
1097 {
1098 std::cerr << "invalid time string encountered\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001099 return resCodes::resErr;
Patrick Venturee0e6f5f2019-08-12 19:00:11 -07001100 }
1101
1102 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
James Feist3cb5fec2018-01-23 14:41:51 -08001103 fruBytesIter += 3;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001104 fruAreaFieldNames = &BOARD_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001105 break;
James Feist3cb5fec2018-01-23 14:41:51 -08001106 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001107 case fruAreas::fruAreaProduct:
James Feist3cb5fec2018-01-23 14:41:51 -08001108 {
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001109 uint8_t lang = *fruBytesIter;
James Feist3cb5fec2018-01-23 14:41:51 -08001110 result["PRODUCT_LANGUAGE_CODE"] =
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001111 std::to_string(static_cast<int>(lang));
1112 checkLang(lang);
James Feist3cb5fec2018-01-23 14:41:51 -08001113 fruBytesIter += 1;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001114 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001115 break;
1116 }
1117 default:
1118 {
1119 std::cerr << "Internal error: unexpected FRU area index: "
1120 << static_cast<int>(area) << " \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001121 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001122 }
1123 }
1124 size_t fieldIndex = 0;
1125 DecodeState state;
1126 do
1127 {
1128 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea);
1129 state = res.first;
1130 std::string value = res.second;
1131 std::string name;
1132 if (fieldIndex < fruAreaFieldNames->size())
1133 {
1134 name = std::string(getFruAreaName(area)) + "_" +
1135 fruAreaFieldNames->at(fieldIndex);
James Feist3cb5fec2018-01-23 14:41:51 -08001136 }
1137 else
1138 {
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001139 name =
1140 std::string(getFruAreaName(area)) + "_" +
1141 FRU_CUSTOM_FIELD_NAME +
1142 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
James Feist3cb5fec2018-01-23 14:41:51 -08001143 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001144
1145 if (state == DecodeState::ok)
James Feist3cb5fec2018-01-23 14:41:51 -08001146 {
Ed Tanous2147e672019-02-27 13:59:56 -08001147 // Strip non null characters from the end
1148 value.erase(std::find_if(value.rbegin(), value.rend(),
1149 [](char ch) { return ch != 0; })
1150 .base(),
1151 value.end());
1152
Jeremy Kerr4e6a62f2020-06-09 11:26:40 +08001153 result[name] = std::move(value);
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001154 ++fieldIndex;
James Feist3cb5fec2018-01-23 14:41:51 -08001155 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001156 else if (state == DecodeState::err)
1157 {
1158 std::cerr << "Error while parsing " << name << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001159 ret = resCodes::resWarn;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001160 // Cancel decoding if failed to parse any of mandatory
1161 // fields
1162 if (fieldIndex < fruAreaFieldNames->size())
1163 {
1164 std::cerr << "Failed to parse mandatory field \n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001165 return resCodes::resErr;
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001166 }
1167 }
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001168 else
1169 {
1170 if (fieldIndex < fruAreaFieldNames->size())
1171 {
1172 std::cerr << "Mandatory fields absent in FRU area "
1173 << getFruAreaName(area) << " after " << name
1174 << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001175 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001176 }
1177 }
Andrei Kartashevd7b66592020-08-13 15:33:51 +03001178 } while (state == DecodeState::ok);
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001179 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
1180 {
1181 uint8_t c = *fruBytesIter;
1182 if (c)
1183 {
1184 std::cerr << "Non-zero byte after EndOfFields in FRU area "
1185 << getFruAreaName(area) << "\n";
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001186 ret = resCodes::resWarn;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001187 break;
1188 }
1189 }
James Feist3cb5fec2018-01-23 14:41:51 -08001190 }
1191
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001192 return ret;
James Feist3cb5fec2018-01-23 14:41:51 -08001193}
1194
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001195std::vector<uint8_t>& getFRUInfo(const uint8_t& bus, const uint8_t& address)
Nikhil Potaded8884f12019-03-27 13:27:13 -07001196{
1197 auto deviceMap = busMap.find(bus);
1198 if (deviceMap == busMap.end())
1199 {
1200 throw std::invalid_argument("Invalid Bus.");
1201 }
1202 auto device = deviceMap->second->find(address);
1203 if (device == deviceMap->second->end())
1204 {
1205 throw std::invalid_argument("Invalid Address.");
1206 }
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001207 std::vector<uint8_t>& ret = device->second;
Nikhil Potaded8884f12019-03-27 13:27:13 -07001208
1209 return ret;
1210}
1211
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001212void AddFRUObjectToDbus(
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001213 std::vector<uint8_t>& device,
James Feista465ccc2019-02-08 12:51:01 -08001214 boost::container::flat_map<
1215 std::pair<size_t, size_t>,
1216 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -07001217 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -08001218{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001219 boost::container::flat_map<std::string, std::string> formattedFRU;
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001220 resCodes res = formatFRU(device, formattedFRU);
1221 if (res == resCodes::resErr)
James Feist3cb5fec2018-01-23 14:41:51 -08001222 {
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001223 std::cerr << "failed to parse FRU for device at bus " << bus
Patrick Ventureb755c832019-08-07 11:09:14 -07001224 << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -08001225 return;
1226 }
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001227 else if (res == resCodes::resWarn)
1228 {
1229 std::cerr << "there were warnings while parsing FRU for device at bus "
1230 << bus << " address " << address << "\n";
1231 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001232
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001233 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001234 std::string productName;
Patrick Venture96cdaef2019-07-30 13:30:52 -07001235 // Not found under Board section or an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001236 if (productNameFind == formattedFRU.end() ||
Patrick Venture96cdaef2019-07-30 13:30:52 -07001237 productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001238 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001239 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
James Feist3cb5fec2018-01-23 14:41:51 -08001240 }
Patrick Venture96cdaef2019-07-30 13:30:52 -07001241 // Found under Product section and not an empty string.
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001242 if (productNameFind != formattedFRU.end() &&
Patrick Venture96cdaef2019-07-30 13:30:52 -07001243 !productNameFind->second.empty())
James Feist3cb5fec2018-01-23 14:41:51 -08001244 {
1245 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -08001246 std::regex illegalObject("[^A-Za-z0-9_]");
1247 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -08001248 }
1249 else
1250 {
1251 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
1252 UNKNOWN_BUS_OBJECT_COUNT++;
1253 }
1254
James Feist918e18c2018-02-13 15:51:07 -08001255 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -08001256 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -07001257 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -08001258 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001259 int highest = -1;
1260 bool found = false;
1261
James Feista465ccc2019-02-08 12:51:01 -08001262 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001263 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001264 std::string path = busIface.second->get_object_path();
1265 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
James Feist918e18c2018-02-13 15:51:07 -08001266 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001267 if (isMuxBus(bus) && address == busIface.first.second &&
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001268 (getFRUInfo(static_cast<uint8_t>(busIface.first.first),
James Feist98132792019-07-09 13:29:09 -07001269 static_cast<uint8_t>(busIface.first.second)) ==
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001270 getFRUInfo(static_cast<uint8_t>(bus),
James Feist98132792019-07-09 13:29:09 -07001271 static_cast<uint8_t>(address))))
James Feist79e9c0b2018-03-15 15:21:17 -07001272 {
Nikhil Potaded8884f12019-03-27 13:27:13 -07001273 // This device is already added to the lower numbered bus,
1274 // do not replicate it.
1275 return;
James Feist79e9c0b2018-03-15 15:21:17 -07001276 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001277
1278 // Check if the match named has extra information.
1279 found = true;
1280 std::smatch base_match;
1281
1282 bool match = std::regex_match(
1283 path, base_match, std::regex(productName + "_(\\d+)$"));
1284 if (match)
James Feist79e9c0b2018-03-15 15:21:17 -07001285 {
Patrick Venture015fb0a2019-08-16 09:33:31 -07001286 if (base_match.size() == 2)
1287 {
1288 std::ssub_match base_sub_match = base_match[1];
1289 std::string base = base_sub_match.str();
1290
1291 int value = std::stoi(base);
1292 highest = (value > highest) ? value : highest;
1293 }
James Feist79e9c0b2018-03-15 15:21:17 -07001294 }
James Feist918e18c2018-02-13 15:51:07 -08001295 }
Patrick Venture015fb0a2019-08-16 09:33:31 -07001296 } // end searching objects
1297
1298 if (found)
1299 {
1300 // We found something with the same name. If highest was still -1,
1301 // it means this new entry will be _0.
1302 productName += "_";
1303 productName += std::to_string(++highest);
James Feist918e18c2018-02-13 15:51:07 -08001304 }
1305 }
James Feist3cb5fec2018-01-23 14:41:51 -08001306
James Feist9eb0b582018-04-27 12:15:46 -07001307 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1308 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
1309 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
1310
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001311 for (auto& property : formattedFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001312 {
James Feist9eb0b582018-04-27 12:15:46 -07001313
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001314 std::regex_replace(property.second.begin(), property.second.begin(),
1315 property.second.end(), NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301316 if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
James Feist9eb0b582018-04-27 12:15:46 -07001317 {
1318 continue;
1319 }
1320 std::string key =
1321 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301322
1323 if (property.first == "PRODUCT_ASSET_TAG")
1324 {
1325 std::string propertyName = property.first;
1326 iface->register_property(
1327 key, property.second + '\0',
1328 [bus, address, propertyName,
1329 &dbusInterfaceMap](const std::string& req, std::string& resp) {
1330 if (strcmp(req.c_str(), resp.c_str()))
1331 {
1332 // call the method which will update
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001333 if (updateFRUProperty(req, bus, address, propertyName,
Joshi-Mansid73b7442020-03-27 19:10:21 +05301334 dbusInterfaceMap))
1335 {
1336 resp = req;
1337 }
1338 else
1339 {
1340 throw std::invalid_argument(
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001341 "FRU property update failed.");
Joshi-Mansid73b7442020-03-27 19:10:21 +05301342 }
1343 }
1344 return 1;
1345 });
1346 }
1347 else if (!iface->register_property(key, property.second + '\0'))
James Feist9eb0b582018-04-27 12:15:46 -07001348 {
1349 std::cerr << "illegal key: " << key << "\n";
1350 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -07001351 if (DEBUG)
1352 {
1353 std::cout << property.first << ": " << property.second << "\n";
1354 }
James Feist3cb5fec2018-01-23 14:41:51 -08001355 }
James Feist2a9d6db2018-04-27 15:48:28 -07001356
1357 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -07001358 iface->register_property("BUS", bus);
1359 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -07001360
James Feist9eb0b582018-04-27 12:15:46 -07001361 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08001362}
1363
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001364static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
James Feist3cb5fec2018-01-23 14:41:51 -08001365{
1366 // try to read baseboard fru from file
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001367 std::ifstream baseboardFRUFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
1368 if (baseboardFRUFile.good())
James Feist3cb5fec2018-01-23 14:41:51 -08001369 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001370 baseboardFRUFile.seekg(0, std::ios_base::end);
1371 size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
1372 baseboardFRU.resize(fileSize);
1373 baseboardFRUFile.seekg(0, std::ios_base::beg);
1374 baseboardFRUFile.read(reinterpret_cast<char*>(baseboardFRU.data()),
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001375 fileSize);
James Feist3cb5fec2018-01-23 14:41:51 -08001376 }
1377 else
1378 {
1379 return false;
1380 }
1381 return true;
1382}
1383
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001384bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -07001385{
1386 boost::container::flat_map<std::string, std::string> tmp;
1387 if (fru.size() > MAX_FRU_SIZE)
1388 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001389 std::cerr << "Invalid fru.size() during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001390 return false;
1391 }
1392 // verify legal fru by running it through fru parsing logic
Andrei Kartashevb45324a2020-10-14 17:01:47 +03001393 if (formatFRU(fru, tmp) != resCodes::resOK)
James Feistb49ffc32018-05-02 11:10:43 -07001394 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001395 std::cerr << "Invalid fru format during writeFRU\n";
James Feistb49ffc32018-05-02 11:10:43 -07001396 return false;
1397 }
1398 // baseboard fru
1399 if (bus == 0 && address == 0)
1400 {
1401 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
1402 if (!file.good())
1403 {
1404 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
1405 << "\n";
James Feistddb78302018-09-06 11:45:42 -07001406 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001407 return false;
1408 }
James Feista465ccc2019-02-08 12:51:01 -08001409 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -07001410 return file.good();
1411 }
1412 else
1413 {
Patrick Venturec50e1ff2019-08-06 10:22:28 -07001414 if (hasEepromFile(bus, address))
1415 {
1416 auto path = getEepromPath(bus, address);
1417 int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
1418 if (eeprom < 0)
1419 {
1420 std::cerr << "unable to open i2c device " << path << "\n";
1421 throw DBusInternalError();
1422 return false;
1423 }
1424
1425 ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
1426 if (writtenBytes < 0)
1427 {
1428 std::cerr << "unable to write to i2c device " << path << "\n";
1429 close(eeprom);
1430 throw DBusInternalError();
1431 return false;
1432 }
1433
1434 close(eeprom);
1435 return true;
1436 }
1437
James Feistb49ffc32018-05-02 11:10:43 -07001438 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
1439
1440 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1441 if (file < 0)
1442 {
1443 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -07001444 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001445 return false;
1446 }
1447 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
1448 {
1449 std::cerr << "unable to set device address\n";
1450 close(file);
James Feistddb78302018-09-06 11:45:42 -07001451 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001452 return false;
1453 }
1454
1455 constexpr const size_t RETRY_MAX = 2;
1456 uint16_t index = 0;
1457 size_t retries = RETRY_MAX;
1458 while (index < fru.size())
1459 {
1460 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
1461 (retries == RETRY_MAX))
1462 {
1463 // The 4K EEPROM only uses the A2 and A1 device address bits
1464 // with the third bit being a memory page address bit.
1465 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
1466 {
1467 std::cerr << "unable to set device address\n";
1468 close(file);
James Feistddb78302018-09-06 11:45:42 -07001469 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001470 return false;
1471 }
1472 }
1473
James Feist98132792019-07-09 13:29:09 -07001474 if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
1475 fru[index]) < 0)
James Feistb49ffc32018-05-02 11:10:43 -07001476 {
1477 if (!retries--)
1478 {
1479 std::cerr << "error writing fru: " << strerror(errno)
1480 << "\n";
1481 close(file);
James Feistddb78302018-09-06 11:45:42 -07001482 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -07001483 return false;
1484 }
1485 }
1486 else
1487 {
1488 retries = RETRY_MAX;
1489 index++;
1490 }
1491 // most eeproms require 5-10ms between writes
1492 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1493 }
1494 close(file);
1495 return true;
1496 }
1497}
1498
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001499void rescanOneBus(
1500 BusMap& busmap, uint8_t busNum,
1501 boost::container::flat_map<
1502 std::pair<size_t, size_t>,
James Feist5d7f4692020-06-17 18:22:33 -07001503 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1504 bool dbusCall)
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001505{
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001506 for (auto& [pair, interface] : foundDevices)
1507 {
1508 if (pair.first == static_cast<size_t>(busNum))
1509 {
1510 objServer.remove_interface(interface);
1511 foundDevices.erase(pair);
1512 }
1513 }
1514
James Feist5d7f4692020-06-17 18:22:33 -07001515 fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
1516 if (!fs::exists(busPath))
1517 {
1518 if (dbusCall)
1519 {
1520 std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
1521 << "\n";
1522 throw std::invalid_argument("Invalid Bus.");
1523 }
1524 return;
1525 }
1526
1527 std::vector<fs::path> i2cBuses;
1528 i2cBuses.emplace_back(busPath);
1529
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001530 auto scan = std::make_shared<FindDevicesWithCallback>(
1531 i2cBuses, busmap, [busNum, &busmap, &dbusInterfaceMap]() {
1532 for (auto& busIface : dbusInterfaceMap)
1533 {
1534 if (busIface.first.first == static_cast<size_t>(busNum))
1535 {
1536 objServer.remove_interface(busIface.second);
1537 }
1538 }
Wludzik, Jozefc1136b72020-06-24 11:58:32 +02001539 auto found = busmap.find(busNum);
1540 if (found == busmap.end() || found->second == nullptr)
1541 {
1542 return;
1543 }
1544 for (auto& device : *(found->second))
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001545 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001546 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08001547 static_cast<uint32_t>(busNum), device.first);
1548 }
1549 });
1550 scan->run();
1551}
1552
James Feist9eb0b582018-04-27 12:15:46 -07001553void rescanBusses(
James Feist5cb06082019-10-24 17:11:13 -07001554 BusMap& busmap,
James Feista465ccc2019-02-08 12:51:01 -08001555 boost::container::flat_map<
1556 std::pair<size_t, size_t>,
James Feist5cb06082019-10-24 17:11:13 -07001557 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -08001558{
James Feist6ebf9de2018-05-15 15:01:17 -07001559 static boost::asio::deadline_timer timer(io);
1560 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -08001561
Gunnar Mills6f0ae942018-08-31 12:38:03 -05001562 // setup an async wait in case we get flooded with requests
James Feist98132792019-07-09 13:29:09 -07001563 timer.async_wait([&](const boost::system::error_code&) {
James Feist4131aea2018-03-09 09:47:30 -08001564 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -08001565 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -08001566
Nikhil Potaded8884f12019-03-27 13:27:13 -07001567 boost::container::flat_map<size_t, fs::path> busPaths;
1568 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -08001569 {
James Feist4131aea2018-03-09 09:47:30 -08001570 std::cerr << "unable to find i2c devices\n";
1571 return;
James Feist918e18c2018-02-13 15:51:07 -08001572 }
Nikhil Potaded8884f12019-03-27 13:27:13 -07001573
1574 for (auto busPath : busPaths)
1575 {
1576 i2cBuses.emplace_back(busPath.second);
1577 }
James Feist4131aea2018-03-09 09:47:30 -08001578
James Feist98132792019-07-09 13:29:09 -07001579 busmap.clear();
James Feist8a983922019-10-24 17:11:56 -07001580 for (auto& [pair, interface] : foundDevices)
1581 {
1582 objServer.remove_interface(interface);
1583 }
1584 foundDevices.clear();
1585
James Feist5cb06082019-10-24 17:11:13 -07001586 auto scan =
1587 std::make_shared<FindDevicesWithCallback>(i2cBuses, busmap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -08001588 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -07001589 {
1590 objServer.remove_interface(busIface.second);
1591 }
James Feist4131aea2018-03-09 09:47:30 -08001592
James Feist6ebf9de2018-05-15 15:01:17 -07001593 dbusInterfaceMap.clear();
1594 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -08001595
James Feist6ebf9de2018-05-15 15:01:17 -07001596 // todo, get this from a more sensable place
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001597 std::vector<uint8_t> baseboardFRU;
1598 if (readBaseboardFRU(baseboardFRU))
James Feist6ebf9de2018-05-15 15:01:17 -07001599 {
Andrei Kartashev1c5b7062020-08-19 14:47:30 +03001600 boost::container::flat_map<int, std::vector<uint8_t>>
James Feist6ebf9de2018-05-15 15:01:17 -07001601 baseboardDev;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001602 baseboardDev.emplace(0, baseboardFRU);
James Feist98132792019-07-09 13:29:09 -07001603 busmap[0] = std::make_shared<DeviceMap>(baseboardDev);
James Feist6ebf9de2018-05-15 15:01:17 -07001604 }
James Feist98132792019-07-09 13:29:09 -07001605 for (auto& devicemap : busmap)
James Feist6ebf9de2018-05-15 15:01:17 -07001606 {
James Feista465ccc2019-02-08 12:51:01 -08001607 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -07001608 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001609 AddFRUObjectToDbus(device.second, dbusInterfaceMap,
James Feist5cb06082019-10-24 17:11:13 -07001610 devicemap.first, device.first);
James Feist6ebf9de2018-05-15 15:01:17 -07001611 }
1612 }
1613 });
1614 scan->run();
1615 });
James Feist918e18c2018-02-13 15:51:07 -08001616}
1617
Joshi-Mansid73b7442020-03-27 19:10:21 +05301618// Calculate new checksum for fru info area
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001619uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
1620 std::vector<uint8_t>::const_iterator end)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301621{
1622 constexpr int checksumMod = 256;
1623 constexpr uint8_t modVal = 0xFF;
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001624 int sum = std::accumulate(iter, end, 0);
1625 int checksum = (checksumMod - sum) & modVal;
1626 return static_cast<uint8_t>(checksum);
1627}
1628uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
1629{
1630 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
Joshi-Mansid73b7442020-03-27 19:10:21 +05301631}
1632
1633// Update new fru area length &
1634// Update checksum at new checksum location
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001635// Return the offset of the area checksum byte
1636static unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
1637 size_t fruAreaStart,
1638 size_t fruAreaEndOfFieldsOffset,
1639 size_t fruAreaEndOffset)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301640{
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001641 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301642
1643 // fill zeros for any remaining unused space
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001644 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
1645 fruData.begin() + fruAreaEndOffset, 0);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301646
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001647 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301648 size_t checksumLoc;
1649 if (!mod)
1650 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001651 traverseFRUAreaIndex += (fruBlockSize);
1652 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301653 }
1654 else
1655 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001656 traverseFRUAreaIndex += (fruBlockSize - mod);
1657 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301658 }
1659
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001660 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
1661 ((traverseFRUAreaIndex % fruBlockSize) != 0);
1662 size_t fruAreaLengthLoc = fruAreaStart + 1;
1663 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301664
1665 // Calculate new checksum
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001666 std::vector<uint8_t> finalFRUData;
1667 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
1668 std::back_inserter(finalFRUData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301669
Andrei Kartashev2a7e3952020-09-02 20:32:26 +03001670 fruData[checksumLoc] = calculateChecksum(finalFRUData);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001671 return checksumLoc;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301672}
1673
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001674static ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301675{
1676 constexpr uint8_t typeLenMask = 0x3F;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001677 constexpr uint8_t endOfFields = 0xC1;
1678 if (fruFieldTypeLenValue == endOfFields)
1679 {
1680 return -1;
1681 }
1682 else
1683 {
1684 return fruFieldTypeLenValue & typeLenMask;
1685 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301686}
1687
1688// Details with example of Asset Tag Update
1689// To find location of Product Info Area asset tag as per FRU specification
1690// 1. Find product Info area starting offset (*8 - as header will be in
1691// multiple of 8 bytes).
1692// 2. Skip 3 bytes of product info area (like format version, area length,
1693// and language code).
1694// 3. Traverse manufacturer name, product name, product version, & product
1695// serial number, by reading type/length code to reach the Asset Tag.
1696// 4. Update the Asset Tag, reposition the product Info area in multiple of
1697// 8 bytes. Update the Product area length and checksum.
1698
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001699bool updateFRUProperty(
Joshi-Mansid73b7442020-03-27 19:10:21 +05301700 const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1701 std::string propertyName,
1702 boost::container::flat_map<
1703 std::pair<size_t, size_t>,
1704 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap)
1705{
1706 size_t updatePropertyReqLen = updatePropertyReq.length();
1707 if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1708 {
1709 std::cerr
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001710 << "FRU field data cannot be of 1 char or more than 63 chars. "
Joshi-Mansid73b7442020-03-27 19:10:21 +05301711 "Invalid Length "
1712 << updatePropertyReqLen << "\n";
1713 return false;
1714 }
1715
1716 std::vector<uint8_t> fruData;
1717 try
1718 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001719 fruData = getFRUInfo(static_cast<uint8_t>(bus),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301720 static_cast<uint8_t>(address));
1721 }
1722 catch (std::invalid_argument& e)
1723 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001724 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301725 return false;
1726 }
1727
1728 if (fruData.empty())
1729 {
1730 return false;
1731 }
1732
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001733 const std::vector<std::string>* fruAreaFieldNames;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301734
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001735 uint8_t fruAreaOffsetFieldValue = 0;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301736 size_t offset = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001737 std::string areaName = propertyName.substr(0, propertyName.find("_"));
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001738 std::string propertyNamePrefix = areaName + "_";
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001739 auto it = std::find(FRU_AREA_NAMES.begin(), FRU_AREA_NAMES.end(), areaName);
1740 if (it == FRU_AREA_NAMES.end())
Joshi-Mansid73b7442020-03-27 19:10:21 +05301741 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001742 std::cerr << "Can't parse area name for property " << propertyName
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001743 << " \n";
1744 return false;
1745 }
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001746 fruAreas fruAreaToUpdate =
1747 static_cast<fruAreas>(it - FRU_AREA_NAMES.begin());
1748 fruAreaOffsetFieldValue =
1749 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1750 switch (fruAreaToUpdate)
1751 {
1752 case fruAreas::fruAreaChassis:
1753 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1754 fruAreaFieldNames = &CHASSIS_FRU_AREAS;
1755 break;
1756 case fruAreas::fruAreaBoard:
1757 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1758 fruAreaFieldNames = &BOARD_FRU_AREAS;
1759 break;
1760 case fruAreas::fruAreaProduct:
1761 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1762 // i.e. version, area length and language code
1763 offset = 3;
1764 fruAreaFieldNames = &PRODUCT_FRU_AREAS;
1765 break;
1766 default:
1767 std::cerr << "Don't know how to handle property " << propertyName
1768 << " \n";
1769 return false;
1770 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001771 if (fruAreaOffsetFieldValue == 0)
1772 {
1773 std::cerr << "FRU Area for " << propertyName << " not present \n";
Joshi-Mansid73b7442020-03-27 19:10:21 +05301774 return false;
1775 }
1776
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001777 size_t fruAreaStart = fruAreaOffsetFieldValue * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001778 size_t fruAreaSize = fruData[fruAreaStart + 1] * fruBlockSize;
1779 size_t fruAreaEnd = fruAreaStart + fruAreaSize;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001780 size_t fruDataIter = fruAreaStart + offset;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001781 size_t fruUpdateFieldLoc = fruDataIter;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001782 size_t skipToFRUUpdateField = 0;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001783 ssize_t fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301784
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001785 bool found = false;
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001786 for (auto& field : *fruAreaFieldNames)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301787 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001788 skipToFRUUpdateField++;
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001789 if (propertyName == propertyNamePrefix + field)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301790 {
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001791 found = true;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301792 break;
1793 }
1794 }
Andrei Kartashev6cfb7752020-08-10 19:50:33 +03001795 if (!found)
1796 {
1797 std::size_t pos = propertyName.find(FRU_CUSTOM_FIELD_NAME);
1798 if (pos == std::string::npos)
1799 {
1800 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1801 << propertyName << "\n";
1802 return false;
1803 }
1804 std::string fieldNumStr =
1805 propertyName.substr(pos + FRU_CUSTOM_FIELD_NAME.length());
1806 size_t fieldNum = std::stoi(fieldNumStr);
1807 if (fieldNum == 0)
1808 {
1809 std::cerr << "PropertyName not recognized: " << propertyName
1810 << "\n";
1811 return false;
1812 }
1813 skipToFRUUpdateField += fieldNum;
1814 }
Joshi-Mansid73b7442020-03-27 19:10:21 +05301815
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001816 for (size_t i = 1; i < skipToFRUUpdateField; i++)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301817 {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001818 fieldLength = getFieldLength(fruData[fruDataIter]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001819 if (fieldLength < 0)
1820 {
1821 break;
1822 }
1823 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301824 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001825 fruUpdateFieldLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301826
1827 // Push post update fru field bytes to a vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001828 fieldLength = getFieldLength(fruData[fruUpdateFieldLoc]);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001829 if (fieldLength < 0)
Joshi-Mansid73b7442020-03-27 19:10:21 +05301830 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001831 std::cerr << "Property " << propertyName << " not present \n";
1832 return false;
1833 }
1834 fruDataIter += 1 + fieldLength;
1835 size_t restFRUFieldsLoc = fruDataIter;
1836 size_t endOfFieldsLoc = 0;
1837 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1838 {
1839 if (fruDataIter >= (fruAreaStart + fruAreaSize))
Joshi-Mansid73b7442020-03-27 19:10:21 +05301840 {
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001841 fruDataIter = fruAreaStart + fruAreaSize;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301842 break;
1843 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001844 fruDataIter += 1 + fieldLength;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301845 }
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001846 endOfFieldsLoc = fruDataIter;
Joshi-Mansid73b7442020-03-27 19:10:21 +05301847
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001848 std::vector<uint8_t> restFRUAreaFieldsData;
1849 std::copy_n(fruData.begin() + restFRUFieldsLoc,
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001850 endOfFieldsLoc - restFRUFieldsLoc + 1,
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001851 std::back_inserter(restFRUAreaFieldsData));
Joshi-Mansid73b7442020-03-27 19:10:21 +05301852
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001853 // Push post update fru areas if any
1854 unsigned int nextFRUAreaLoc = 0;
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001855 for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1856 nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001857 {
1858 unsigned int fruAreaLoc =
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001859 fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001860 if ((fruAreaLoc > endOfFieldsLoc) &&
1861 ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1862 {
1863 nextFRUAreaLoc = fruAreaLoc;
1864 }
1865 }
1866 std::vector<uint8_t> restFRUAreasData;
1867 if (nextFRUAreaLoc)
1868 {
1869 std::copy_n(fruData.begin() + nextFRUAreaLoc,
1870 fruData.size() - nextFRUAreaLoc,
1871 std::back_inserter(restFRUAreasData));
1872 }
1873
1874 // check FRU area size
1875 size_t fruAreaDataSize =
1876 ((fruUpdateFieldLoc - fruAreaStart + 1) + restFRUAreaFieldsData.size());
1877 size_t fruAreaAvailableSize = fruAreaSize - fruAreaDataSize;
1878 if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1879 {
1880
1881#ifdef ENABLE_FRU_AREA_RESIZE
1882 size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1883 // round size to 8-byte blocks
1884 newFRUAreaSize =
1885 ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1886 size_t newFRUDataSize = fruData.size() + newFRUAreaSize - fruAreaSize;
1887 fruData.resize(newFRUDataSize);
1888 fruAreaSize = newFRUAreaSize;
1889 fruAreaEnd = fruAreaStart + fruAreaSize;
1890#else
1891 std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1892 << " should not be greater than available FRU area size: "
1893 << fruAreaAvailableSize << "\n";
1894 return false;
1895#endif // ENABLE_FRU_AREA_RESIZE
1896 }
1897
Joshi-Mansid73b7442020-03-27 19:10:21 +05301898 // write new requested property field length and data
1899 constexpr uint8_t newTypeLenMask = 0xC0;
1900 fruData[fruUpdateFieldLoc] =
1901 static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1902 fruUpdateFieldLoc++;
1903 std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1904 fruData.begin() + fruUpdateFieldLoc);
1905
1906 // Copy remaining data to main fru area - post updated fru field vector
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001907 restFRUFieldsLoc = fruUpdateFieldLoc + updatePropertyReqLen;
1908 size_t fruAreaDataEnd = restFRUFieldsLoc + restFRUAreaFieldsData.size();
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001909 std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1910 fruData.begin() + restFRUFieldsLoc);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301911
1912 // Update final fru with new fru area length and checksum
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001913 unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1914 fruData, fruAreaStart, fruAreaDataEnd, fruAreaEnd);
Joshi-Mansid73b7442020-03-27 19:10:21 +05301915
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001916#ifdef ENABLE_FRU_AREA_RESIZE
1917 ++nextFRUAreaNewLoc;
1918 ssize_t nextFRUAreaOffsetDiff =
1919 (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1920 // Append rest FRU Areas if size changed and there were other sections after
1921 // updated one
1922 if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1923 {
1924 std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1925 fruData.begin() + nextFRUAreaNewLoc);
1926 // Update Common Header
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001927 for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1928 fruArea++)
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001929 {
Andrei Kartashev9f0f2d12020-08-20 04:24:37 +03001930 unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
Andrei Kartashev6b3d4c52020-08-10 19:24:17 +03001931 size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1932 if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1933 {
1934 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1935 curFRUAreaOffset + nextFRUAreaOffsetDiff);
1936 }
1937 }
1938 // Calculate new checksum
1939 std::vector<uint8_t> headerFRUData;
1940 std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1941 size_t checksumVal = calculateChecksum(headerFRUData);
1942 fruData[7] = static_cast<uint8_t>(checksumVal);
1943 // fill zeros if FRU Area size decreased
1944 if (nextFRUAreaOffsetDiff < 0)
1945 {
1946 std::fill(fruData.begin() + nextFRUAreaNewLoc +
1947 restFRUAreasData.size(),
1948 fruData.end(), 0);
1949 }
1950 }
1951#else
1952 // this is to avoid "unused variable" warning
1953 (void)nextFRUAreaNewLoc;
1954#endif // ENABLE_FRU_AREA_RESIZE
Joshi-Mansid73b7442020-03-27 19:10:21 +05301955 if (fruData.empty())
1956 {
1957 return false;
1958 }
1959
Andrei Kartashev2f0de172020-08-13 14:29:40 +03001960 if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
Joshi-Mansid73b7442020-03-27 19:10:21 +05301961 fruData))
1962 {
1963 return false;
1964 }
1965
1966 // Rescan the bus so that GetRawFru dbus-call fetches updated values
1967 rescanBusses(busMap, dbusInterfaceMap);
1968 return true;
1969}
1970
James Feist98132792019-07-09 13:29:09 -07001971int main()
James Feist3cb5fec2018-01-23 14:41:51 -08001972{
1973 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -08001974 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -08001975 std::vector<fs::path> i2cBuses;
1976
James Feista3c180a2018-08-09 16:06:04 -07001977 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -08001978 {
1979 std::cerr << "unable to find i2c devices\n";
1980 return 1;
1981 }
James Feist3cb5fec2018-01-23 14:41:51 -08001982
Patrick Venture11f1ff42019-08-01 10:42:12 -07001983 // check for and load blacklist with initial buses.
1984 loadBlacklist(blacklistPath);
1985
Vijay Khemka065f6d92018-12-18 10:37:47 -08001986 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -08001987
James Feist6ebf9de2018-05-15 15:01:17 -07001988 // this is a map with keys of pair(bus number, address) and values of
1989 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -08001990 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -07001991 std::shared_ptr<sdbusplus::asio::dbus_interface>>
1992 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -08001993
James Feist9eb0b582018-04-27 12:15:46 -07001994 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1995 objServer.add_interface("/xyz/openbmc_project/FruDevice",
1996 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -08001997
James Feist5cb06082019-10-24 17:11:13 -07001998 iface->register_method("ReScan",
1999 [&]() { rescanBusses(busMap, dbusInterfaceMap); });
James Feist2a9d6db2018-04-27 15:48:28 -07002000
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08002001 iface->register_method("ReScanBus", [&](uint8_t bus) {
James Feist5d7f4692020-06-17 18:22:33 -07002002 rescanOneBus(busMap, bus, dbusInterfaceMap, true);
Cheng C Yangd5b87fb2020-01-23 10:10:45 +08002003 });
2004
Andrei Kartashev2f0de172020-08-13 14:29:40 +03002005 iface->register_method("GetRawFru", getFRUInfo);
James Feistb49ffc32018-05-02 11:10:43 -07002006
2007 iface->register_method("WriteFru", [&](const uint8_t bus,
2008 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -08002009 const std::vector<uint8_t>& data) {
Andrei Kartashev2f0de172020-08-13 14:29:40 +03002010 if (!writeFRU(bus, address, data))
James Feistb49ffc32018-05-02 11:10:43 -07002011 {
James Feistddb78302018-09-06 11:45:42 -07002012 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -07002013 return;
2014 }
2015 // schedule rescan on success
James Feist5cb06082019-10-24 17:11:13 -07002016 rescanBusses(busMap, dbusInterfaceMap);
James Feistb49ffc32018-05-02 11:10:43 -07002017 });
James Feist9eb0b582018-04-27 12:15:46 -07002018 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -08002019
James Feist9eb0b582018-04-27 12:15:46 -07002020 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -08002021 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -08002022 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -07002023 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -08002024 std::string,
2025 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -07002026 values;
2027 message.read(objectName, values);
James Feist0eeb79c2019-10-09 13:35:29 -07002028 auto findState = values.find("CurrentHostState");
James Feist0eeb79c2019-10-09 13:35:29 -07002029 if (findState != values.end())
James Feist918e18c2018-02-13 15:51:07 -08002030 {
James Feistcb5661d2020-06-12 15:05:01 -07002031 powerIsOn = boost::ends_with(
2032 std::get<std::string>(findState->second), "Running");
James Feist0eeb79c2019-10-09 13:35:29 -07002033 }
James Feist6ebf9de2018-05-15 15:01:17 -07002034
James Feistcb5661d2020-06-12 15:05:01 -07002035 if (powerIsOn)
James Feist0eeb79c2019-10-09 13:35:29 -07002036 {
James Feist5cb06082019-10-24 17:11:13 -07002037 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08002038 }
James Feist918e18c2018-02-13 15:51:07 -08002039 };
James Feist9eb0b582018-04-27 12:15:46 -07002040
2041 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -08002042 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -07002043 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
James Feist0eeb79c2019-10-09 13:35:29 -07002044 "openbmc_project/state/"
2045 "host0',arg0='xyz.openbmc_project.State.Host'",
James Feist9eb0b582018-04-27 12:15:46 -07002046 eventHandler);
2047
James Feist4131aea2018-03-09 09:47:30 -08002048 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -07002049 inotify_add_watch(fd, I2C_DEV_LOCATION,
2050 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -08002051 std::array<char, 4096> readBuffer;
2052 std::string pendingBuffer;
2053 // monitor for new i2c devices
2054 boost::asio::posix::stream_descriptor dirWatch(io, fd);
2055 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -08002056 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -08002057 std::size_t bytes_transferred) {
2058 if (ec)
2059 {
2060 std::cout << "Callback Error " << ec << "\n";
2061 return;
2062 }
2063 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
James Feist4131aea2018-03-09 09:47:30 -08002064 while (pendingBuffer.size() > sizeof(inotify_event))
2065 {
James Feista465ccc2019-02-08 12:51:01 -08002066 const inotify_event* iEvent =
2067 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -08002068 pendingBuffer.data());
2069 switch (iEvent->mask)
2070 {
James Feist9eb0b582018-04-27 12:15:46 -07002071 case IN_CREATE:
2072 case IN_MOVED_TO:
2073 case IN_DELETE:
James Feist5d7f4692020-06-17 18:22:33 -07002074 std::string name(iEvent->name);
2075 if (boost::starts_with(name, "i2c"))
James Feist9eb0b582018-04-27 12:15:46 -07002076 {
James Feist5d7f4692020-06-17 18:22:33 -07002077 int bus = busStrToInt(name);
2078 if (bus < 0)
2079 {
2080 std::cerr << "Could not parse bus " << name
2081 << "\n";
2082 continue;
2083 }
2084 rescanOneBus(busMap, static_cast<uint8_t>(bus),
2085 dbusInterfaceMap, false);
James Feist9eb0b582018-04-27 12:15:46 -07002086 }
James Feist4131aea2018-03-09 09:47:30 -08002087 }
2088
2089 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
2090 }
James Feist6ebf9de2018-05-15 15:01:17 -07002091
James Feist4131aea2018-03-09 09:47:30 -08002092 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
2093 watchI2cBusses);
2094 };
2095
2096 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -05002097 // run the initial scan
James Feist5cb06082019-10-24 17:11:13 -07002098 rescanBusses(busMap, dbusInterfaceMap);
James Feist918e18c2018-02-13 15:51:07 -08002099
James Feist3cb5fec2018-01-23 14:41:51 -08002100 io.run();
2101 return 0;
2102}