blob: 385ea7214c46ca751e57f21cc4cffcff723ca552 [file] [log] [blame]
Alexander Hansen4e1142d2025-07-25 17:07:27 +02001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
Patrick Ventureab296412020-12-30 13:39:37 -08003
Brad Bishope45d8c72022-05-25 15:12:53 -04004#include "fru_utils.hpp"
Patrick Ventureab296412020-12-30 13:39:37 -08005
Alexander Hansenc3db2c32024-08-20 15:01:38 +02006#include <phosphor-logging/lg2.hpp>
7
Patrick Ventureab296412020-12-30 13:39:37 -08008#include <array>
Ed Tanous3013fb42022-07-09 08:27:06 -07009#include <cstddef>
Patrick Ventureab296412020-12-30 13:39:37 -080010#include <cstdint>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053011#include <filesystem>
Hieu Huynh5286afe2022-10-12 11:41:12 +000012#include <iomanip>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053013#include <numeric>
Patrick Ventureab296412020-12-30 13:39:37 -080014#include <set>
Hieu Huynh5286afe2022-10-12 11:41:12 +000015#include <sstream>
Patrick Ventureab296412020-12-30 13:39:37 -080016#include <string>
17#include <vector>
18
19extern "C"
20{
21// Include for I2C_SMBUS_BLOCK_MAX
22#include <linux/i2c.h>
23}
24
Patrick Ventureab296412020-12-30 13:39:37 -080025constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
26
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +080027std::tm intelEpoch()
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000028{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053029 std::tm val = {};
30 val.tm_year = 1996 - 1900;
Scron-Chang9e5a6752021-03-16 10:51:50 +080031 val.tm_mday = 1;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053032 return val;
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000033}
34
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053035char sixBitToChar(uint8_t val)
Patrick Ventureab296412020-12-30 13:39:37 -080036{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053037 return static_cast<char>((val & 0x3f) + ' ');
38}
39
40char bcdPlusToChar(uint8_t val)
41{
42 val &= 0xf;
43 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
44}
45
46enum FRUDataEncoding
47{
48 binary = 0x0,
49 bcdPlus = 0x1,
50 sixBitASCII = 0x2,
51 languageDependent = 0x3,
52};
53
Hieu Huynh5286afe2022-10-12 11:41:12 +000054enum MultiRecordType : uint8_t
55{
56 powerSupplyInfo = 0x00,
57 dcOutput = 0x01,
58 dcLoad = 0x02,
59 managementAccessRecord = 0x03,
60 baseCompatibilityRecord = 0x04,
61 extendedCompatibilityRecord = 0x05,
62 resvASFSMBusDeviceRecord = 0x06,
63 resvASFLegacyDeviceAlerts = 0x07,
64 resvASFRemoteControl = 0x08,
65 extendedDCOutput = 0x09,
66 extendedDCLoad = 0x0A
67};
68
69enum SubManagementAccessRecord : uint8_t
70{
71 systemManagementURL = 0x01,
72 systemName = 0x02,
73 systemPingAddress = 0x03,
74 componentManagementURL = 0x04,
75 componentName = 0x05,
76 componentPingAddress = 0x06,
77 systemUniqueID = 0x07
78};
79
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053080/* Decode FRU data into a std::string, given an input iterator and end. If the
81 * state returned is fruDataOk, then the resulting string is the decoded FRU
82 * data. The input iterator is advanced past the data consumed.
83 *
84 * On fruDataErr, we have lost synchronisation with the length bytes, so the
85 * iterator is no longer usable.
86 */
Patrick Williamsb7077432024-08-16 15:22:21 -040087std::pair<DecodeState, std::string> decodeFRUData(
Ed Tanous23e3f452025-04-08 10:37:56 -070088 std::span<const uint8_t>::const_iterator& iter,
89 std::span<const uint8_t>::const_iterator& end, bool isLangEng)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053090{
91 std::string value;
Ed Tanous3013fb42022-07-09 08:27:06 -070092 unsigned int i = 0;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053093
94 /* we need at least one byte to decode the type/len header */
95 if (iter == end)
Patrick Ventureab296412020-12-30 13:39:37 -080096 {
Alexander Hansen8feb0452025-09-15 14:29:20 +020097 lg2::error("Truncated FRU data");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053098 return make_pair(DecodeState::err, value);
99 }
100
101 uint8_t c = *(iter++);
102
103 /* 0xc1 is the end marker */
104 if (c == 0xc1)
105 {
106 return make_pair(DecodeState::end, value);
107 }
108
109 /* decode type/len byte */
110 uint8_t type = static_cast<uint8_t>(c >> 6);
111 uint8_t len = static_cast<uint8_t>(c & 0x3f);
112
113 /* we should have at least len bytes of data available overall */
114 if (iter + len > end)
115 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200116 lg2::error("FRU data field extends past end of FRU area data");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530117 return make_pair(DecodeState::err, value);
118 }
119
120 switch (type)
121 {
122 case FRUDataEncoding::binary:
Patrick Ventureab296412020-12-30 13:39:37 -0800123 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530124 std::stringstream ss;
125 ss << std::hex << std::setfill('0');
126 for (i = 0; i < len; i++, iter++)
127 {
128 uint8_t val = static_cast<uint8_t>(*iter);
129 ss << std::setw(2) << static_cast<int>(val);
130 }
131 value = ss.str();
132 break;
Patrick Ventureab296412020-12-30 13:39:37 -0800133 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530134 case FRUDataEncoding::languageDependent:
135 /* For language-code dependent encodings, assume 8-bit ASCII */
136 value = std::string(iter, iter + len);
137 iter += len;
138
139 /* English text is encoded in 8-bit ASCII + Latin 1. All other
140 * languages are required to use 2-byte unicode. FruDevice does not
141 * handle unicode.
142 */
143 if (!isLangEng)
144 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200145 lg2::error("Error: Non english string is not supported ");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530146 return make_pair(DecodeState::err, value);
147 }
148
149 break;
150
151 case FRUDataEncoding::bcdPlus:
152 value = std::string();
153 for (i = 0; i < len; i++, iter++)
154 {
155 uint8_t val = *iter;
156 value.push_back(bcdPlusToChar(val >> 4));
157 value.push_back(bcdPlusToChar(val & 0xf));
158 }
159 break;
160
161 case FRUDataEncoding::sixBitASCII:
162 {
163 unsigned int accum = 0;
164 unsigned int accumBitLen = 0;
165 value = std::string();
166 for (i = 0; i < len; i++, iter++)
167 {
168 accum |= *iter << accumBitLen;
169 accumBitLen += 8;
170 while (accumBitLen >= 6)
171 {
172 value.push_back(sixBitToChar(accum & 0x3f));
173 accum >>= 6;
174 accumBitLen -= 6;
175 }
176 }
177 }
178 break;
Ed Tanousfc171422024-04-04 17:18:16 -0700179
180 default:
181 {
182 return make_pair(DecodeState::err, value);
183 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530184 }
185
186 return make_pair(DecodeState::ok, value);
187}
188
189bool checkLangEng(uint8_t lang)
190{
191 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
192 // but we don't support that.
Ed Tanous3013fb42022-07-09 08:27:06 -0700193 if ((lang != 0U) && lang != 25)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530194 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200195 lg2::error("Warning: languages other than English is not supported");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530196 // Return language flag as non english
Patrick Ventureab296412020-12-30 13:39:37 -0800197 return false;
198 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800199 return true;
Patrick Ventureab296412020-12-30 13:39:37 -0800200}
201
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000202/* This function verifies for other offsets to check if they are not
203 * falling under other field area
204 *
205 * fruBytes: Start of Fru data
206 * currentArea: Index of current area offset to be compared against all area
207 * offset and it is a multiple of 8 bytes as per specification
208 * len: Length of current area space and it is a multiple of 8 bytes
209 * as per specification
210 */
Ed Tanous23e3f452025-04-08 10:37:56 -0700211bool verifyOffset(std::span<const uint8_t> fruBytes, fruAreas currentArea,
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000212 uint8_t len)
213{
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000214 unsigned int fruBytesSize = fruBytes.size();
215
216 // check if Fru data has at least 8 byte header
217 if (fruBytesSize <= fruBlockSize)
218 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200219 lg2::error("Error: trying to parse empty FRU");
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000220 return false;
221 }
222
223 // Check range of passed currentArea value
224 if (currentArea > fruAreas::fruAreaMultirecord)
225 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200226 lg2::error("Error: Fru area is out of range");
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000227 return false;
228 }
229
230 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
231 if (currentAreaIndex > fruBytesSize)
232 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200233 lg2::error("Error: Fru area index is out of range");
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000234 return false;
235 }
236
237 unsigned int start = fruBytes[currentAreaIndex];
238 unsigned int end = start + len;
239
240 /* Verify each offset within the range of start and end */
241 for (fruAreas area = fruAreas::fruAreaInternal;
242 area <= fruAreas::fruAreaMultirecord; ++area)
243 {
244 // skip the current offset
245 if (area == currentArea)
246 {
247 continue;
248 }
249
250 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
251 if (areaIndex > fruBytesSize)
252 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200253 lg2::error("Error: Fru area index is out of range");
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000254 return false;
255 }
256
257 unsigned int areaOffset = fruBytes[areaIndex];
258 // if areaOffset is 0 means this area is not available so skip
259 if (areaOffset == 0)
260 {
261 continue;
262 }
263
264 // check for overlapping of current offset with given areaoffset
265 if (areaOffset == start || (areaOffset > start && areaOffset < end))
266 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200267 lg2::error("{AREA1} offset is overlapping with {AREA2} offset",
268 "AREA1", getFruAreaName(currentArea), "AREA2",
269 getFruAreaName(area));
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000270 return false;
271 }
272 }
273 return true;
274}
275
Hieu Huynh5286afe2022-10-12 11:41:12 +0000276static void parseMultirecordUUID(
Ed Tanous23e3f452025-04-08 10:37:56 -0700277 std::span<const uint8_t> device,
Hieu Huynh5286afe2022-10-12 11:41:12 +0000278 boost::container::flat_map<std::string, std::string>& result)
279{
280 constexpr size_t uuidDataLen = 16;
281 constexpr size_t multiRecordHeaderLen = 5;
282 /* UUID record data, plus one to skip past the sub-record type byte */
283 constexpr size_t uuidRecordData = multiRecordHeaderLen + 1;
284 constexpr size_t multiRecordEndOfListMask = 0x80;
285 /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented
286 * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD
287 * 0xEE 0xFF
288 */
289 const std::array<uint8_t, uuidDataLen> uuidCharOrder = {
290 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
Ed Tanous23e3f452025-04-08 10:37:56 -0700291 size_t offset = getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord);
292 if (offset >= device.size())
293 {
294 throw std::runtime_error("Multirecord UUID offset is out of range");
295 }
296 uint32_t areaOffset = device[offset];
Hieu Huynh5286afe2022-10-12 11:41:12 +0000297
298 if (areaOffset == 0)
299 {
300 return;
301 }
302
303 areaOffset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700304 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400305 device.begin() + areaOffset;
Hieu Huynh5286afe2022-10-12 11:41:12 +0000306
307 /* Verify area offset */
308 if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter))
309 {
310 return;
311 }
312 while (areaOffset + uuidRecordData + uuidDataLen <= device.size())
313 {
314 if ((areaOffset < device.size()) &&
315 (device[areaOffset] ==
316 (uint8_t)MultiRecordType::managementAccessRecord))
317 {
318 if ((areaOffset + multiRecordHeaderLen < device.size()) &&
319 (device[areaOffset + multiRecordHeaderLen] ==
320 (uint8_t)SubManagementAccessRecord::systemUniqueID))
321 {
322 /* Layout of UUID:
323 * source: https://www.ietf.org/rfc/rfc4122.txt
324 *
325 * UUID binary format (16 bytes):
326 * 4B-2B-2B-2B-6B (big endian)
327 *
328 * UUID string is 36 length of characters (36 bytes):
329 * 0 9 14 19 24
330 * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
331 * be be be be be
332 * be means it should be converted to big endian.
333 */
334 /* Get UUID bytes to UUID string */
335 std::stringstream tmp;
336 tmp << std::hex << std::setfill('0');
337 for (size_t i = 0; i < uuidDataLen; i++)
338 {
339 tmp << std::setw(2)
340 << static_cast<uint16_t>(
341 device[areaOffset + uuidRecordData +
342 uuidCharOrder[i]]);
343 }
344 std::string uuidStr = tmp.str();
345 result["MULTIRECORD_UUID"] =
346 uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' +
347 uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' +
348 uuidStr.substr(20, 12);
349 break;
350 }
351 }
352 if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0)
353 {
354 break;
355 }
356 areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen;
357 }
358}
359
Ed Tanous5ea38d22025-04-08 09:36:43 -0700360resCodes decodeField(
361 std::span<const uint8_t>::const_iterator& fruBytesIter,
362 std::span<const uint8_t>::const_iterator& fruBytesIterEndArea,
363 const std::vector<std::string>& fruAreaFieldNames, size_t& fieldIndex,
364 DecodeState& state, bool isLangEng, const fruAreas& area,
365 boost::container::flat_map<std::string, std::string>& result)
366{
367 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
368 state = res.first;
369 std::string value = res.second;
370 std::string name;
Ed Tanous7f2db482025-04-04 16:38:42 -0700371 bool isCustomField = false;
Ed Tanous5ea38d22025-04-08 09:36:43 -0700372 if (fieldIndex < fruAreaFieldNames.size())
373 {
374 name = std::string(getFruAreaName(area)) + "_" +
375 fruAreaFieldNames.at(fieldIndex);
376 }
377 else
378 {
Ed Tanous7f2db482025-04-04 16:38:42 -0700379 isCustomField = true;
Ed Tanous5ea38d22025-04-08 09:36:43 -0700380 name = std::string(getFruAreaName(area)) + "_" + fruCustomFieldName +
381 std::to_string(fieldIndex - fruAreaFieldNames.size() + 1);
382 }
383
384 if (state == DecodeState::ok)
385 {
386 // Strip non null characters and trailing spaces from the end
387 value.erase(
388 std::find_if(value.rbegin(), value.rend(),
389 [](char ch) { return ((ch != 0) && (ch != ' ')); })
390 .base(),
391 value.end());
Ed Tanous7f2db482025-04-04 16:38:42 -0700392 if (isCustomField)
393 {
394 // Some MAC addresses are stored in a custom field, with
395 // "MAC:" prefixed on the value. If we see that, create a
396 // new field with the decoded data
397 if (value.starts_with("MAC: "))
398 {
399 result["MAC_" + name] = value.substr(5);
400 }
401 }
Ed Tanous5ea38d22025-04-08 09:36:43 -0700402 result[name] = std::move(value);
403 ++fieldIndex;
404 }
405 else if (state == DecodeState::err)
406 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200407 lg2::error("Error while parsing {NAME}", "NAME", name);
Ed Tanous5ea38d22025-04-08 09:36:43 -0700408
409 // Cancel decoding if failed to parse any of mandatory
410 // fields
411 if (fieldIndex < fruAreaFieldNames.size())
412 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200413 lg2::error("Failed to parse mandatory field ");
Ed Tanous5ea38d22025-04-08 09:36:43 -0700414 return resCodes::resErr;
415 }
416 return resCodes::resWarn;
417 }
418 else
419 {
420 if (fieldIndex < fruAreaFieldNames.size())
421 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200422 lg2::error(
423 "Mandatory fields absent in FRU area {AREA} after {NAME}",
424 "AREA", getFruAreaName(area), "NAME", name);
Ed Tanous5ea38d22025-04-08 09:36:43 -0700425 return resCodes::resWarn;
426 }
427 }
428 return resCodes::resOK;
429}
430
Patrick Williams5a807032025-03-03 11:20:39 -0500431resCodes formatIPMIFRU(
Ed Tanous23e3f452025-04-08 10:37:56 -0700432 std::span<const uint8_t> fruBytes,
Patrick Williams5a807032025-03-03 11:20:39 -0500433 boost::container::flat_map<std::string, std::string>& result)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530434{
435 resCodes ret = resCodes::resOK;
436 if (fruBytes.size() <= fruBlockSize)
437 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200438 lg2::error("Error: trying to parse empty FRU ");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530439 return resCodes::resErr;
440 }
441 result["Common_Format_Version"] =
442 std::to_string(static_cast<int>(*fruBytes.begin()));
443
Ed Tanous3013fb42022-07-09 08:27:06 -0700444 const std::vector<std::string>* fruAreaFieldNames = nullptr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530445
446 // Don't parse Internal and Multirecord areas
447 for (fruAreas area = fruAreas::fruAreaChassis;
448 area <= fruAreas::fruAreaProduct; ++area)
449 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530450 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
451 if (offset == 0)
452 {
453 continue;
454 }
455 offset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700456 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400457 fruBytes.begin() + offset;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530458 if (fruBytesIter + fruBlockSize >= fruBytes.end())
459 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200460 lg2::error("Not enough data to parse ");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530461 return resCodes::resErr;
462 }
463 // check for format version 1
464 if (*fruBytesIter != 0x01)
465 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200466 lg2::error("Unexpected version {VERSION}", "VERSION",
467 *fruBytesIter);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530468 return resCodes::resErr;
469 }
470 ++fruBytesIter;
471
472 /* Verify other area offset for overlap with current area by passing
473 * length of current area offset pointed by *fruBytesIter
474 */
475 if (!verifyOffset(fruBytes, area, *fruBytesIter))
476 {
477 return resCodes::resErr;
478 }
479
Andrew Jeffery65ed6642021-08-02 22:32:23 +0930480 size_t fruAreaSize = *fruBytesIter * fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700481 std::span<const uint8_t>::const_iterator fruBytesIterEndArea =
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530482 fruBytes.begin() + offset + fruAreaSize - 1;
483 ++fruBytesIter;
484
485 uint8_t fruComputedChecksum =
486 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
487 if (fruComputedChecksum != *fruBytesIterEndArea)
488 {
489 std::stringstream ss;
490 ss << std::hex << std::setfill('0');
491 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
492 ss << "\tComputed checksum: 0x" << std::setw(2)
493 << static_cast<int>(fruComputedChecksum) << "\n";
494 ss << "\tThe read checksum: 0x" << std::setw(2)
495 << static_cast<int>(*fruBytesIterEndArea) << "\n";
Alexander Hansen8feb0452025-09-15 14:29:20 +0200496 lg2::error("{ERR}", "ERR", ss.str());
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530497 ret = resCodes::resWarn;
498 }
499
500 /* Set default language flag to true as Chassis Fru area are always
501 * encoded in English defined in Section 10 of Fru specification
502 */
503
504 bool isLangEng = true;
505 switch (area)
506 {
507 case fruAreas::fruAreaChassis:
508 {
509 result["CHASSIS_TYPE"] =
510 std::to_string(static_cast<int>(*fruBytesIter));
511 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800512 fruAreaFieldNames = &chassisFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530513 break;
514 }
515 case fruAreas::fruAreaBoard:
516 {
517 uint8_t lang = *fruBytesIter;
518 result["BOARD_LANGUAGE_CODE"] =
519 std::to_string(static_cast<int>(lang));
520 isLangEng = checkLangEng(lang);
521 fruBytesIter += 1;
522
Patrick Williamsb7077432024-08-16 15:22:21 -0400523 unsigned int minutes =
524 *fruBytesIter | *(fruBytesIter + 1) << 8 |
525 *(fruBytesIter + 2) << 16;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530526 std::tm fruTime = intelEpoch();
Willy Tu3f98b5e2023-04-12 08:16:52 -0700527 std::time_t timeValue = timegm(&fruTime);
Ed Tanous3013fb42022-07-09 08:27:06 -0700528 timeValue += static_cast<long>(minutes) * 60;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530529 fruTime = *std::gmtime(&timeValue);
530
531 // Tue Nov 20 23:08:00 2018
Ed Tanous3013fb42022-07-09 08:27:06 -0700532 std::array<char, 32> timeString = {};
533 auto bytes = std::strftime(timeString.data(), timeString.size(),
Yi-Shum536665b2024-05-14 10:08:27 +0800534 "%Y%m%dT%H%M%SZ", &fruTime);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530535 if (bytes == 0)
536 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200537 lg2::error("invalid time string encountered");
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530538 return resCodes::resErr;
539 }
540
Ed Tanous3013fb42022-07-09 08:27:06 -0700541 result["BOARD_MANUFACTURE_DATE"] =
542 std::string_view(timeString.data(), bytes);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530543 fruBytesIter += 3;
Ed Tanous07d467b2021-02-23 14:48:37 -0800544 fruAreaFieldNames = &boardFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530545 break;
546 }
547 case fruAreas::fruAreaProduct:
548 {
549 uint8_t lang = *fruBytesIter;
550 result["PRODUCT_LANGUAGE_CODE"] =
551 std::to_string(static_cast<int>(lang));
552 isLangEng = checkLangEng(lang);
553 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800554 fruAreaFieldNames = &productFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530555 break;
556 }
557 default:
558 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200559 lg2::error(
560 "Internal error: unexpected FRU area index: {INDEX} ",
561 "INDEX", static_cast<int>(area));
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530562 return resCodes::resErr;
563 }
564 }
565 size_t fieldIndex = 0;
Ed Tanous3013fb42022-07-09 08:27:06 -0700566 DecodeState state = DecodeState::ok;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530567 do
568 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700569 resCodes decodeRet = decodeField(fruBytesIter, fruBytesIterEndArea,
570 *fruAreaFieldNames, fieldIndex,
571 state, isLangEng, area, result);
572 if (decodeRet == resCodes::resErr)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530573 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700574 return resCodes::resErr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530575 }
Ed Tanous5ea38d22025-04-08 09:36:43 -0700576 if (decodeRet == resCodes::resWarn)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530577 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700578 ret = decodeRet;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530579 }
580 } while (state == DecodeState::ok);
581 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
582 {
583 uint8_t c = *fruBytesIter;
Ed Tanous3013fb42022-07-09 08:27:06 -0700584 if (c != 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530585 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200586 lg2::error("Non-zero byte after EndOfFields in FRU area {AREA}",
587 "AREA", getFruAreaName(area));
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530588 ret = resCodes::resWarn;
589 break;
590 }
591 }
592 }
593
Hieu Huynh5286afe2022-10-12 11:41:12 +0000594 /* Parsing the Multirecord UUID */
595 parseMultirecordUUID(fruBytes, result);
596
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530597 return ret;
598}
599
600// Calculate new checksum for fru info area
Ed Tanous23e3f452025-04-08 10:37:56 -0700601uint8_t calculateChecksum(std::span<const uint8_t>::const_iterator iter,
602 std::span<const uint8_t>::const_iterator end)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530603{
604 constexpr int checksumMod = 256;
Andrew Jeffery499e7aa2021-08-02 22:18:22 +0930605 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
606 return (checksumMod - sum) % checksumMod;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530607}
608
Ed Tanous23e3f452025-04-08 10:37:56 -0700609uint8_t calculateChecksum(std::span<const uint8_t> fruAreaData)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530610{
611 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
612}
613
614// Update new fru area length &
615// Update checksum at new checksum location
616// Return the offset of the area checksum byte
Patrick Williamsb7077432024-08-16 15:22:21 -0400617unsigned int updateFRUAreaLenAndChecksum(
618 std::vector<uint8_t>& fruData, size_t fruAreaStart,
619 size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530620{
621 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
622
623 // fill zeros for any remaining unused space
624 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
625 fruData.begin() + fruAreaEndOffset, 0);
626
627 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Ed Tanous3013fb42022-07-09 08:27:06 -0700628 size_t checksumLoc = 0;
629 if (mod == 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530630 {
631 traverseFRUAreaIndex += (fruBlockSize);
632 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
633 }
634 else
635 {
636 traverseFRUAreaIndex += (fruBlockSize - mod);
637 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
638 }
639
Ed Tanous3013fb42022-07-09 08:27:06 -0700640 size_t newFRUAreaLen =
641 (traverseFRUAreaIndex / fruBlockSize) +
642 static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530643 size_t fruAreaLengthLoc = fruAreaStart + 1;
644 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
645
646 // Calculate new checksum
647 std::vector<uint8_t> finalFRUData;
648 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
649 std::back_inserter(finalFRUData));
650
651 fruData[checksumLoc] = calculateChecksum(finalFRUData);
652 return checksumLoc;
653}
654
655ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
656{
657 constexpr uint8_t typeLenMask = 0x3F;
658 constexpr uint8_t endOfFields = 0xC1;
659 if (fruFieldTypeLenValue == endOfFields)
660 {
661 return -1;
662 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800663 return fruFieldTypeLenValue & typeLenMask;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530664}
665
666bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
667{
668 // ipmi spec format version number is currently at 1, verify it
669 if (blockData[0] != fruVersion)
670 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200671 lg2::debug(
672 "FRU spec version {VERSION} not supported. Supported version is {SUPPORTED_VERSION}",
673 "VERSION", lg2::hex, blockData[0], "SUPPORTED_VERSION", lg2::hex,
674 fruVersion);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530675 return false;
676 }
677
678 // verify pad is set to 0
679 if (blockData[6] != 0x0)
680 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200681 lg2::debug("Pad value in header is non zero, value is {VALUE}", "VALUE",
682 lg2::hex, blockData[6]);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530683 return false;
684 }
685
686 // verify offsets are 0, or don't point to another offset
687 std::set<uint8_t> foundOffsets;
688 for (int ii = 1; ii < 6; ii++)
689 {
690 if (blockData[ii] == 0)
691 {
692 continue;
693 }
694 auto inserted = foundOffsets.insert(blockData[ii]);
695 if (!inserted.second)
696 {
697 return false;
698 }
699 }
700
701 // validate checksum
702 size_t sum = 0;
703 for (int jj = 0; jj < 7; jj++)
704 {
705 sum += blockData[jj];
706 }
707 sum = (256 - sum) & 0xFF;
708
709 if (sum != blockData[7])
710 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200711 lg2::debug(
712 "Checksum {CHECKSUM} is invalid. calculated checksum is {CALCULATED_CHECKSUM}",
713 "CHECKSUM", lg2::hex, blockData[7], "CALCULATED_CHECKSUM", lg2::hex,
714 sum);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530715 return false;
716 }
717 return true;
718}
719
Zev Weiss309c0b12022-02-25 01:44:12 +0000720bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
Oskar Senftbd4075f2021-10-05 23:42:43 -0400721 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
Zev Weiss1525e852022-03-22 22:27:43 +0000722 off_t& baseOffset)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400723{
Zev Weiss309c0b12022-02-25 01:44:12 +0000724 if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400725 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200726 lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
727 errorHelp, "OFFSET", baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400728 return false;
729 }
730
731 // check the header checksum
732 if (validateHeader(blockData))
733 {
734 return true;
735 }
736
737 // only continue the search if we just looked at 0x0.
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030738 if (baseOffset != 0)
739 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400740 return false;
741 }
742
743 // now check for special cases where the IPMI data is at an offset
744
745 // check if blockData starts with tyanHeader
746 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
747 if (blockData.size() >= tyanHeader.size() &&
748 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
749 {
750 // look for the FRU header at offset 0x6000
751 baseOffset = 0x6000;
Zev Weiss309c0b12022-02-25 01:44:12 +0000752 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400753 }
754
Mark Kuocc2d9e22025-08-26 01:26:50 -0700755 // check if blockData starts with gigabyteHeader
756 const std::vector<uint8_t> gigabyteHeader = {'G', 'I', 'G', 'A',
757 'B', 'Y', 'T', 'E'};
758 if (blockData.size() >= gigabyteHeader.size() &&
759 std::equal(gigabyteHeader.begin(), gigabyteHeader.end(),
760 blockData.begin()))
761 {
762 // look for the FRU header at offset 0x4000
763 baseOffset = 0x4000;
764 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
765 }
766
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200767 lg2::debug("Illegal header {HEADER} base offset {OFFSET}", "HEADER",
768 errorHelp, "OFFSET", baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400769
770 return false;
771}
772
Patrick Williams5a807032025-03-03 11:20:39 -0500773std::pair<std::vector<uint8_t>, bool> readFRUContents(
774 FRUReader& reader, const std::string& errorHelp)
Patrick Ventureab296412020-12-30 13:39:37 -0800775{
Ed Tanous3013fb42022-07-09 08:27:06 -0700776 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
Zev Weiss1525e852022-03-22 22:27:43 +0000777 off_t baseOffset = 0x0;
Patrick Ventureab296412020-12-30 13:39:37 -0800778
Zev Weiss309c0b12022-02-25 01:44:12 +0000779 if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030780 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200781 return {{}, false};
Patrick Ventureab296412020-12-30 13:39:37 -0800782 }
783
784 std::vector<uint8_t> device;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400785 device.insert(device.end(), blockData.begin(),
786 std::next(blockData.begin(), 8));
Patrick Ventureab296412020-12-30 13:39:37 -0800787
788 bool hasMultiRecords = false;
789 size_t fruLength = fruBlockSize; // At least FRU header is present
Vijay Khemka7792e392021-01-25 13:03:56 -0800790 unsigned int prevOffset = 0;
Patrick Ventureab296412020-12-30 13:39:37 -0800791 for (fruAreas area = fruAreas::fruAreaInternal;
792 area <= fruAreas::fruAreaMultirecord; ++area)
793 {
794 // Offset value can be 255.
795 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
796 if (areaOffset == 0)
797 {
798 continue;
799 }
800
Vijay Khemka7792e392021-01-25 13:03:56 -0800801 /* Check for offset order, as per Section 17 of FRU specification, FRU
802 * information areas are required to be in order in FRU data layout
803 * which means all offset value should be in increasing order or can be
804 * 0 if that area is not present
805 */
806 if (areaOffset <= prevOffset)
807 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200808 lg2::error(
809 "Fru area offsets are not in required order as per Section 17 of Fru specification");
Marvin Drees2b3ed302023-04-14 16:35:14 +0200810 return {{}, true};
Vijay Khemka7792e392021-01-25 13:03:56 -0800811 }
812 prevOffset = areaOffset;
813
Patrick Ventureab296412020-12-30 13:39:37 -0800814 // MultiRecords are different. area is not tracking section, it's
815 // walking the common header.
816 if (area == fruAreas::fruAreaMultirecord)
817 {
818 hasMultiRecords = true;
819 break;
820 }
821
822 areaOffset *= fruBlockSize;
823
Zev Weiss309c0b12022-02-25 01:44:12 +0000824 if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800825 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200826 lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
827 errorHelp, "OFFSET", baseOffset);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200828 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800829 }
830
831 // Ignore data type (blockData is already unsigned).
832 size_t length = blockData[1] * fruBlockSize;
833 areaOffset += length;
834 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
835 }
836
837 if (hasMultiRecords)
838 {
839 // device[area count] is the index to the last area because the 0th
840 // entry is not an offset in the common header.
841 unsigned int areaOffset =
842 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
843 areaOffset *= fruBlockSize;
844
845 // the multi-area record header is 5 bytes long.
846 constexpr size_t multiRecordHeaderSize = 5;
847 constexpr uint8_t multiRecordEndOfListMask = 0x80;
848
849 // Sanity hard-limit to 64KB.
850 while (areaOffset < std::numeric_limits<uint16_t>::max())
851 {
852 // In multi-area, the area offset points to the 0th record, each
853 // record has 3 bytes of the header we care about.
Zev Weiss309c0b12022-02-25 01:44:12 +0000854 if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800855 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200856 lg2::error("failed to read {STR} base offset {OFFSET}", "STR",
857 errorHelp, "OFFSET", baseOffset);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200858 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800859 }
860
861 // Ok, let's check the record length, which is in bytes (unsigned,
862 // up to 255, so blockData should hold uint8_t not char)
863 size_t recordLength = blockData[2];
864 areaOffset += (recordLength + multiRecordHeaderSize);
865 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
866
867 // If this is the end of the list bail.
Ed Tanous3013fb42022-07-09 08:27:06 -0700868 if ((blockData[1] & multiRecordEndOfListMask) != 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800869 {
870 break;
871 }
872 }
873 }
874
875 // You already copied these first 8 bytes (the ipmi fru header size)
876 fruLength -= std::min(fruBlockSize, fruLength);
877
878 int readOffset = fruBlockSize;
879
880 while (fruLength > 0)
881 {
882 size_t requestLength =
883 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
884
Zev Weiss309c0b12022-02-25 01:44:12 +0000885 if (reader.read(baseOffset + readOffset, requestLength,
886 blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800887 {
Alexander Hansen8feb0452025-09-15 14:29:20 +0200888 lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
889 errorHelp, "OFFSET", baseOffset);
Marvin Drees2b3ed302023-04-14 16:35:14 +0200890 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800891 }
892
893 device.insert(device.end(), blockData.begin(),
Alexander Hansen5df916f2025-09-26 10:31:36 -0400894 std::next(blockData.begin(), requestLength));
Patrick Ventureab296412020-12-30 13:39:37 -0800895
896 readOffset += requestLength;
897 fruLength -= std::min(requestLength, fruLength);
898 }
899
Marvin Drees2b3ed302023-04-14 16:35:14 +0200900 return {device, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800901}
902
903unsigned int getHeaderAreaFieldOffset(fruAreas area)
904{
905 return static_cast<unsigned int>(area) + 1;
906}
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530907
krishnar4213ee212022-11-11 15:39:30 +0530908std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530909{
910 auto deviceMap = busMap.find(bus);
911 if (deviceMap == busMap.end())
912 {
913 throw std::invalid_argument("Invalid Bus.");
914 }
915 auto device = deviceMap->second->find(address);
916 if (device == deviceMap->second->end())
917 {
918 throw std::invalid_argument("Invalid Address.");
919 }
920 std::vector<uint8_t>& ret = device->second;
921
922 return ret;
923}
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +0530924
Marc Olberding25680e32025-10-03 12:38:10 -0700925static bool updateHeaderChecksum(std::vector<uint8_t>& fruData)
Naresh Solankicf288962025-06-06 15:26:11 +0530926{
Marc Olberding25680e32025-10-03 12:38:10 -0700927 if (fruData.size() < fruBlockSize)
Naresh Solankicf288962025-06-06 15:26:11 +0530928 {
929 lg2::debug("FRU data is too small to contain a valid header.");
930 return false;
931 }
Naresh Solankicf288962025-06-06 15:26:11 +0530932
Marc Olberding25680e32025-10-03 12:38:10 -0700933 uint8_t& checksumInBytes = fruData[7];
934 uint8_t checksum =
935 calculateChecksum({fruData.begin(), fruData.begin() + 7});
936 std::swap(checksumInBytes, checksum);
937
938 if (checksumInBytes != checksum)
Naresh Solankicf288962025-06-06 15:26:11 +0530939 {
940 lg2::debug(
941 "FRU header checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
Marc Olberding25680e32025-10-03 12:38:10 -0700942 "OLD_CHECKSUM", static_cast<int>(checksum), "NEW_CHECKSUM",
943 static_cast<int>(checksumInBytes));
Naresh Solankicf288962025-06-06 15:26:11 +0530944 }
945 return true;
946}
947
Marc Olberding25680e32025-10-03 12:38:10 -0700948bool updateAreaChecksum(std::vector<uint8_t>& fruArea)
Naresh Solankicf288962025-06-06 15:26:11 +0530949{
950 if (fruArea.size() < fruBlockSize)
951 {
952 lg2::debug("FRU area is too small to contain a valid header.");
953 return false;
954 }
955 if (fruArea.size() % fruBlockSize != 0)
956 {
957 lg2::debug("FRU area size is not a multiple of {SIZE} bytes.", "SIZE",
958 fruBlockSize);
959 return false;
960 }
961
962 uint8_t oldcksum = fruArea[fruArea.size() - 1];
963
964 fruArea[fruArea.size() - 1] =
965 0; // Reset checksum byte to 0 before recalculating
966 fruArea[fruArea.size() - 1] = calculateChecksum(fruArea);
967
968 if (oldcksum != fruArea[fruArea.size() - 1])
969 {
970 lg2::debug(
971 "FRU area checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
972 "OLD_CHECKSUM", static_cast<int>(oldcksum), "NEW_CHECKSUM",
973 static_cast<int>(fruArea[fruArea.size() - 1]));
974 }
975 return true;
976}
977
Marc Olberding25680e32025-10-03 12:38:10 -0700978static std::optional<size_t> calculateAreaSize(
979 fruAreas area, std::span<const uint8_t> fruData, size_t areaOffset)
980{
981 switch (area)
982 {
983 case fruAreas::fruAreaChassis:
984 case fruAreas::fruAreaBoard:
985 case fruAreas::fruAreaProduct:
986 if (areaOffset + 1 >= fruData.size())
987 {
988 return std::nullopt;
989 }
990 return fruData[areaOffset + 1] * fruBlockSize; // Area size in bytes
991 case fruAreas::fruAreaInternal:
992 {
993 // Internal area size: It is difference between the next area
994 // offset and current area offset
995 for (fruAreas areaIt = fruAreas::fruAreaChassis;
996 areaIt <= fruAreas::fruAreaMultirecord; ++areaIt)
997 {
998 size_t headerOffset = getHeaderAreaFieldOffset(areaIt);
999 if (headerOffset >= fruData.size())
1000 {
1001 return std::nullopt;
1002 }
1003 size_t nextAreaOffset = fruData[headerOffset];
1004 if (nextAreaOffset != 0)
1005 {
1006 return nextAreaOffset * fruBlockSize - areaOffset;
1007 }
1008 }
1009 return std::nullopt;
1010 }
1011 break;
1012 case fruAreas::fruAreaMultirecord:
1013 // Multirecord area size.
1014 return fruData.size() - areaOffset; // Area size in bytes
1015 default:
1016 lg2::error("Invalid FRU area: {AREA}", "AREA",
1017 static_cast<int>(area));
1018 }
1019 return std::nullopt;
1020}
1021
1022static size_t getBlockCount(size_t byteCount)
1023{
1024 size_t blocks = (byteCount + fruBlockSize - 1) / fruBlockSize;
1025 // if we're perfectly aligned, we need another block for the checksum
1026 if ((byteCount % fruBlockSize) == 0)
1027 {
1028 blocks++;
1029 }
1030 return blocks;
1031}
1032
Naresh Solankicf288962025-06-06 15:26:11 +05301033bool disassembleFruData(std::vector<uint8_t>& fruData,
1034 std::vector<std::vector<uint8_t>>& areasData)
1035{
1036 if (fruData.size() < 8)
1037 {
1038 lg2::debug("FRU data is too small to contain a valid header.");
1039 return false;
1040 }
1041
1042 // Clear areasData before disassembling
1043 areasData.clear();
1044
1045 // Iterate through all areas & store each area data in a vector.
1046 for (fruAreas area = fruAreas::fruAreaInternal;
1047 area <= fruAreas::fruAreaMultirecord; ++area)
1048 {
1049 size_t areaOffset = fruData[getHeaderAreaFieldOffset(area)];
1050
1051 if (areaOffset == 0)
1052 {
1053 // Store empty area data for areas that are not present
1054 areasData.emplace_back();
1055 continue; // Skip areas that are not present
1056 }
1057 areaOffset *= fruBlockSize; // Convert to byte offset
Marc Olberding25680e32025-10-03 12:38:10 -07001058
1059 std::optional<size_t> areaSize =
1060 calculateAreaSize(area, fruData, areaOffset);
1061 if (!areaSize)
Naresh Solankicf288962025-06-06 15:26:11 +05301062 {
Marc Olberding25680e32025-10-03 12:38:10 -07001063 return false;
Naresh Solankicf288962025-06-06 15:26:11 +05301064 }
1065
Marc Olberding25680e32025-10-03 12:38:10 -07001066 if ((areaOffset + *areaSize) > fruData.size())
Naresh Solankicf288962025-06-06 15:26:11 +05301067 {
1068 lg2::error("Area offset + size exceeds FRU data size.");
1069 return false;
1070 }
Marc Olberding25680e32025-10-03 12:38:10 -07001071
1072 areasData.emplace_back(fruData.begin() + areaOffset,
1073 fruData.begin() + areaOffset + *areaSize);
Naresh Solankicf288962025-06-06 15:26:11 +05301074 }
Marc Olberding25680e32025-10-03 12:38:10 -07001075
Naresh Solankicf288962025-06-06 15:26:11 +05301076 return true;
1077}
1078
Marc Olberding25680e32025-10-03 12:38:10 -07001079struct FieldInfo
Naresh Solankicf288962025-06-06 15:26:11 +05301080{
Marc Olberding25680e32025-10-03 12:38:10 -07001081 size_t length;
1082 size_t index;
1083};
1084
1085static std::optional<FieldInfo> findOrCreateField(
1086 std::vector<uint8_t>& areaData, const std::string& propertyName,
1087 const fruAreas& fruAreaToUpdate)
1088{
1089 int fieldIndex = 0;
Naresh Solankicf288962025-06-06 15:26:11 +05301090 int fieldLength = 0;
Naresh Solankicf288962025-06-06 15:26:11 +05301091 std::string areaName = propertyName.substr(0, propertyName.find('_'));
1092 std::string propertyNamePrefix = areaName + "_";
Marc Olberding25680e32025-10-03 12:38:10 -07001093 const std::vector<std::string>* fruAreaFieldNames = nullptr;
Naresh Solankicf288962025-06-06 15:26:11 +05301094
1095 switch (fruAreaToUpdate)
1096 {
1097 case fruAreas::fruAreaChassis:
1098 fruAreaFieldNames = &chassisFruAreas;
1099 fieldIndex = 3;
1100 break;
1101 case fruAreas::fruAreaBoard:
1102 fruAreaFieldNames = &boardFruAreas;
1103 fieldIndex = 6;
1104 break;
1105 case fruAreas::fruAreaProduct:
1106 fruAreaFieldNames = &productFruAreas;
1107 fieldIndex = 3;
1108 break;
1109 default:
Marc Olberding25680e32025-10-03 12:38:10 -07001110 lg2::info("Invalid FRU area: {AREA}", "AREA",
1111 static_cast<int>(fruAreaToUpdate));
1112 return std::nullopt;
Naresh Solankicf288962025-06-06 15:26:11 +05301113 }
Marc Olberding25680e32025-10-03 12:38:10 -07001114
Naresh Solankicf288962025-06-06 15:26:11 +05301115 for (const auto& field : *fruAreaFieldNames)
1116 {
1117 fieldLength = getFieldLength(areaData[fieldIndex]);
1118 if (fieldLength < 0)
1119 {
Naresh Solankicf288962025-06-06 15:26:11 +05301120 areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1121 fieldLength = 0;
1122 }
1123
1124 if (propertyNamePrefix + field == propertyName)
1125 {
Marc Olberding25680e32025-10-03 12:38:10 -07001126 return FieldInfo{static_cast<size_t>(fieldLength),
1127 static_cast<size_t>(fieldIndex)};
Naresh Solankicf288962025-06-06 15:26:11 +05301128 }
1129 fieldIndex += 1 + fieldLength;
1130 }
Naresh Solankicf288962025-06-06 15:26:11 +05301131
Marc Olberding25680e32025-10-03 12:38:10 -07001132 size_t pos = propertyName.find(fruCustomFieldName);
1133 if (pos == std::string::npos)
1134 {
1135 return std::nullopt;
Naresh Solankicf288962025-06-06 15:26:11 +05301136 }
1137
Marc Olberding25680e32025-10-03 12:38:10 -07001138 // Get field after pos
1139 std::string customFieldIdx =
1140 propertyName.substr(pos + fruCustomFieldName.size());
1141
1142 // Check if customFieldIdx is a number
1143 if (!std::all_of(customFieldIdx.begin(), customFieldIdx.end(), ::isdigit))
Naresh Solankicf288962025-06-06 15:26:11 +05301144 {
Marc Olberding25680e32025-10-03 12:38:10 -07001145 return std::nullopt;
1146 }
1147
1148 size_t customFieldIndex = std::stoi(customFieldIdx);
1149
1150 // insert custom fields up to the index we want
1151 for (size_t i = 0; i < customFieldIndex; i++)
1152 {
1153 fieldLength = getFieldLength(areaData[fieldIndex]);
1154 if (fieldLength < 0)
1155 {
1156 areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1157 fieldLength = 0;
1158 }
1159 fieldIndex += 1 + fieldLength;
1160 }
1161
1162 fieldIndex -= (fieldLength + 1);
1163 fieldLength = getFieldLength(areaData[fieldIndex]);
1164 return FieldInfo{static_cast<size_t>(fieldLength),
1165 static_cast<size_t>(fieldIndex)};
1166}
1167
1168static std::optional<size_t> findEndOfFieldMarker(std::span<uint8_t> bytes)
1169{
1170 // we're skipping the checksum
1171 // this function assumes a properly sized and formatted area
1172 static uint8_t constexpr endOfFieldsByte = 0xc1;
1173 for (int index = bytes.size() - 2; index >= 0; --index)
1174 {
1175 if (bytes[index] == endOfFieldsByte)
1176 {
1177 return index;
1178 }
1179 }
1180 return std::nullopt;
1181}
1182
1183static std::optional<size_t> getNonPaddedSizeOfArea(std::span<uint8_t> bytes)
1184{
1185 if (auto endOfFields = findEndOfFieldMarker(bytes))
1186 {
1187 return *endOfFields + 1;
1188 }
1189 return std::nullopt;
1190}
1191
1192bool setField(const fruAreas& fruAreaToUpdate, std::vector<uint8_t>& areaData,
1193 const std::string& propertyName, const std::string& value)
1194{
1195 if (value.size() == 1 || value.size() > 63)
1196 {
1197 lg2::error("Invalid value {VALUE} for field {PROP}", "VALUE", value,
1198 "PROP", propertyName);
1199 return false;
1200 }
1201
1202 // This is inneficient, but the alternative requires
1203 // a bunch of complicated indexing and search to
1204 // figure out if we cross a block boundary
1205 // if we feel that this is too inneficient in the future,
1206 // we can implement that.
1207 std::vector<uint8_t> tmpBuffer = areaData;
1208
1209 auto fieldInfo =
1210 findOrCreateField(tmpBuffer, propertyName, fruAreaToUpdate);
1211
1212 if (!fieldInfo)
1213 {
1214 lg2::error("Field {FIELD} not found in area {AREA}", "FIELD",
Naresh Solankicf288962025-06-06 15:26:11 +05301215 propertyName, "AREA", getFruAreaName(fruAreaToUpdate));
1216 return false;
1217 }
Naresh Solankicf288962025-06-06 15:26:11 +05301218
Marc Olberding25680e32025-10-03 12:38:10 -07001219 auto fieldIt = tmpBuffer.begin() + fieldInfo->index;
Naresh Solankicf288962025-06-06 15:26:11 +05301220 // Erase the existing field content.
Marc Olberding25680e32025-10-03 12:38:10 -07001221 tmpBuffer.erase(fieldIt, fieldIt + fieldInfo->length + 1);
Naresh Solankicf288962025-06-06 15:26:11 +05301222 // Insert the new field value
Marc Olberding25680e32025-10-03 12:38:10 -07001223 tmpBuffer.insert(fieldIt, 0xc0 | value.size());
1224 tmpBuffer.insert_range(fieldIt + 1, value);
Naresh Solankicf288962025-06-06 15:26:11 +05301225
Marc Olberding25680e32025-10-03 12:38:10 -07001226 auto newSize = getNonPaddedSizeOfArea(tmpBuffer);
1227 auto oldSize = getNonPaddedSizeOfArea(areaData);
Naresh Solankicf288962025-06-06 15:26:11 +05301228
Marc Olberding25680e32025-10-03 12:38:10 -07001229 if (!oldSize || !newSize)
Naresh Solankicf288962025-06-06 15:26:11 +05301230 {
Marc Olberding25680e32025-10-03 12:38:10 -07001231 lg2::error("Failed to find the size of the area");
Naresh Solankicf288962025-06-06 15:26:11 +05301232 return false;
1233 }
1234
Marc Olberding25680e32025-10-03 12:38:10 -07001235 size_t newSizePadded = getBlockCount(*newSize);
Naresh Solankicf288962025-06-06 15:26:11 +05301236#ifndef ENABLE_FRU_AREA_RESIZE
Marc Olberding25680e32025-10-03 12:38:10 -07001237
1238 size_t oldSizePadded = getBlockCount(*oldSize);
1239
1240 if (newSizePadded != oldSizePadded)
Naresh Solankicf288962025-06-06 15:26:11 +05301241 {
Marc Olberding25680e32025-10-03 12:38:10 -07001242 lg2::error(
Naresh Solankicf288962025-06-06 15:26:11 +05301243 "FRU area {AREA} resize is disabled, cannot increase size from {OLD_SIZE} to {NEW_SIZE}",
1244 "AREA", getFruAreaName(fruAreaToUpdate), "OLD_SIZE",
Marc Olberding25680e32025-10-03 12:38:10 -07001245 static_cast<int>(oldSizePadded), "NEW_SIZE",
1246 static_cast<int>(newSizePadded));
Naresh Solankicf288962025-06-06 15:26:11 +05301247 return false;
1248 }
Marc Olberding25680e32025-10-03 12:38:10 -07001249#endif
1250 // Resize the buffer as per numOfBlocks & pad with zeros
1251 tmpBuffer.resize(newSizePadded * fruBlockSize, 0);
Naresh Solankicf288962025-06-06 15:26:11 +05301252
Naresh Solankicf288962025-06-06 15:26:11 +05301253 // Update the length field
Marc Olberding25680e32025-10-03 12:38:10 -07001254 tmpBuffer[1] = newSizePadded;
1255 updateAreaChecksum(tmpBuffer);
1256
1257 areaData = std::move(tmpBuffer);
Naresh Solankicf288962025-06-06 15:26:11 +05301258
1259 return true;
1260}
1261
1262bool assembleFruData(std::vector<uint8_t>& fruData,
1263 const std::vector<std::vector<uint8_t>>& areasData)
1264{
Marc Olberding25680e32025-10-03 12:38:10 -07001265 for (const auto& area : areasData)
1266 {
1267 if ((area.size() % fruBlockSize) != 0U)
1268 {
1269 lg2::error("unaligned area sent to assembleFruData");
1270 return false;
1271 }
1272 }
1273
Naresh Solankicf288962025-06-06 15:26:11 +05301274 // Clear the existing FRU data
1275 fruData.clear();
1276 fruData.resize(8); // Start with the header size
1277
1278 // Write the header
1279 fruData[0] = fruVersion; // Version
1280 fruData[1] = 0; // Internal area offset
1281 fruData[2] = 0; // Chassis area offset
1282 fruData[3] = 0; // Board area offset
1283 fruData[4] = 0; // Product area offset
1284 fruData[5] = 0; // Multirecord area offset
1285 fruData[6] = 0; // Pad
1286 fruData[7] = 0; // Checksum (to be updated later)
1287
1288 size_t writeOffset = 8; // Start writing after the header
1289
1290 for (fruAreas area = fruAreas::fruAreaInternal;
1291 area <= fruAreas::fruAreaMultirecord; ++area)
1292 {
Marc Olberding25680e32025-10-03 12:38:10 -07001293 const auto& areaBytes = areasData[static_cast<size_t>(area)];
Naresh Solankicf288962025-06-06 15:26:11 +05301294
Marc Olberding25680e32025-10-03 12:38:10 -07001295 if (areaBytes.empty())
Naresh Solankicf288962025-06-06 15:26:11 +05301296 {
1297 lg2::debug("Skipping empty area: {AREA}", "AREA",
1298 getFruAreaName(area));
1299 continue; // Skip areas that are not present
1300 }
1301
1302 // Set the area offset in the header
Marc Olberding25680e32025-10-03 12:38:10 -07001303 fruData[getHeaderAreaFieldOffset(area)] = writeOffset / fruBlockSize;
1304 fruData.append_range(areaBytes);
1305 writeOffset += areaBytes.size();
Naresh Solankicf288962025-06-06 15:26:11 +05301306 }
1307
1308 // Update the header checksum
Marc Olberding25680e32025-10-03 12:38:10 -07001309 if (!updateHeaderChecksum(fruData))
Naresh Solankicf288962025-06-06 15:26:11 +05301310 {
Marc Olberding25680e32025-10-03 12:38:10 -07001311 lg2::error("failed to update header checksum");
Naresh Solankicf288962025-06-06 15:26:11 +05301312 return false;
1313 }
Marc Olberding25680e32025-10-03 12:38:10 -07001314
Naresh Solankicf288962025-06-06 15:26:11 +05301315 return true;
1316}
1317
1318// Create a dummy area in areData variable based on specified fruArea
1319bool createDummyArea(fruAreas fruArea, std::vector<uint8_t>& areaData)
1320{
1321 uint8_t numOfFields = 0;
1322 uint8_t numOfBlocks = 0;
1323 // Clear the areaData vector
1324 areaData.clear();
1325
1326 // Set the version, length, and other fields
Marc Olberding25680e32025-10-03 12:38:10 -07001327 areaData.push_back(fruVersion); // Version 1
1328 areaData.push_back(0); // Length (to be updated later)
Naresh Solankicf288962025-06-06 15:26:11 +05301329
1330 switch (fruArea)
1331 {
1332 case fruAreas::fruAreaChassis:
1333 areaData.push_back(0x00); // Chassis type
1334 numOfFields = chassisFruAreas.size();
1335 break;
1336 case fruAreas::fruAreaBoard:
1337 areaData.push_back(0x00); // Board language code (default)
1338 areaData.insert(areaData.end(),
1339 {0x00, 0x00,
1340 0x00}); // Board manufacturer date (default)
1341 numOfFields = boardFruAreas.size();
1342 break;
1343 case fruAreas::fruAreaProduct:
1344 areaData.push_back(0x00); // Product language code (default)
1345 numOfFields = productFruAreas.size();
1346 break;
1347 default:
1348 lg2::debug("Invalid FRU area to create: {AREA}", "AREA",
1349 static_cast<int>(fruArea));
1350 return false;
1351 }
1352
1353 for (size_t i = 0; i < numOfFields; ++i)
1354 {
1355 areaData.push_back(0xc0); // Empty field type
1356 }
1357
1358 // Add EndOfFields marker
1359 areaData.push_back(0xC1);
1360 numOfBlocks = (areaData.size() + fruBlockSize - 1) /
1361 fruBlockSize; // Calculate number of blocks needed
1362 areaData.resize(numOfBlocks * fruBlockSize, 0); // Fill with zeros
1363 areaData[1] = numOfBlocks; // Update length field
Marc Olberding25680e32025-10-03 12:38:10 -07001364 updateAreaChecksum(areaData);
Naresh Solankicf288962025-06-06 15:26:11 +05301365
1366 return true;
1367}
1368
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301369// Iterate FruArea Names and find start and size of the fru area that contains
1370// the propertyName and the field start location for the property. fruAreaParams
1371// struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
1372// updated/returned if successful.
1373
1374bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
1375 const std::string& propertyName,
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301376 struct FruArea& fruAreaParams)
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301377{
1378 const std::vector<std::string>* fruAreaFieldNames = nullptr;
1379
1380 uint8_t fruAreaOffsetFieldValue = 0;
1381 size_t offset = 0;
1382 std::string areaName = propertyName.substr(0, propertyName.find('_'));
1383 std::string propertyNamePrefix = areaName + "_";
1384 auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
1385 if (it == fruAreaNames.end())
1386 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001387 lg2::error("Can't parse area name for property {PROP} ", "PROP",
1388 propertyName);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301389 return false;
1390 }
1391 fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
1392 fruAreaOffsetFieldValue =
1393 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1394 switch (fruAreaToUpdate)
1395 {
1396 case fruAreas::fruAreaChassis:
1397 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1398 fruAreaFieldNames = &chassisFruAreas;
1399 break;
1400 case fruAreas::fruAreaBoard:
1401 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1402 fruAreaFieldNames = &boardFruAreas;
1403 break;
1404 case fruAreas::fruAreaProduct:
1405 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1406 // i.e. version, area length and language code
1407 offset = 3;
1408 fruAreaFieldNames = &productFruAreas;
1409 break;
1410 default:
Alexander Hansen8feb0452025-09-15 14:29:20 +02001411 lg2::error("Invalid PropertyName {PROP}", "PROP", propertyName);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301412 return false;
1413 }
1414 if (fruAreaOffsetFieldValue == 0)
1415 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001416 lg2::error("FRU Area for {PROP} not present ", "PROP", propertyName);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301417 return false;
1418 }
1419
1420 fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
1421 fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
1422 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301423 size_t fruDataIter = fruAreaParams.start + offset;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301424 size_t skipToFRUUpdateField = 0;
1425 ssize_t fieldLength = 0;
1426
1427 bool found = false;
1428 for (const auto& field : *fruAreaFieldNames)
1429 {
1430 skipToFRUUpdateField++;
1431 if (propertyName == propertyNamePrefix + field)
1432 {
1433 found = true;
1434 break;
1435 }
1436 }
1437 if (!found)
1438 {
1439 std::size_t pos = propertyName.find(fruCustomFieldName);
1440 if (pos == std::string::npos)
1441 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001442 lg2::error("PropertyName doesn't exist in FRU Area Vectors: {PROP}",
1443 "PROP", propertyName);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301444 return false;
1445 }
1446 std::string fieldNumStr =
1447 propertyName.substr(pos + fruCustomFieldName.length());
1448 size_t fieldNum = std::stoi(fieldNumStr);
1449 if (fieldNum == 0)
1450 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001451 lg2::error("PropertyName not recognized: {PROP}", "PROP",
1452 propertyName);
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301453 return false;
1454 }
1455 skipToFRUUpdateField += fieldNum;
1456 }
1457
1458 for (size_t i = 1; i < skipToFRUUpdateField; i++)
1459 {
1460 if (fruDataIter < fruData.size())
1461 {
1462 fieldLength = getFieldLength(fruData[fruDataIter]);
1463
1464 if (fieldLength < 0)
1465 {
1466 break;
1467 }
1468 fruDataIter += 1 + fieldLength;
1469 }
1470 }
1471 fruAreaParams.updateFieldLoc = fruDataIter;
1472
1473 return true;
1474}
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301475
1476// Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1477// Return true for success and false for failure.
1478
1479bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1480 const std::string& propertyName,
1481 struct FruArea& fruAreaParams,
1482 std::vector<uint8_t>& restFRUAreaFieldsData)
1483{
1484 size_t fieldLoc = fruAreaParams.updateFieldLoc;
1485 size_t start = fruAreaParams.start;
1486 size_t fruAreaSize = fruAreaParams.size;
1487
1488 // Push post update fru field bytes to a vector
1489 ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1490 if (fieldLength < 0)
1491 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001492 lg2::error("Property {PROP} not present ", "PROP", propertyName);
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301493 return false;
1494 }
1495
1496 size_t fruDataIter = 0;
1497 fruDataIter = fieldLoc;
1498 fruDataIter += 1 + fieldLength;
1499 size_t restFRUFieldsLoc = fruDataIter;
1500 size_t endOfFieldsLoc = 0;
1501
1502 if (fruDataIter < fruData.size())
1503 {
1504 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1505 {
1506 if (fruDataIter >= (start + fruAreaSize))
1507 {
1508 fruDataIter = start + fruAreaSize;
1509 break;
1510 }
1511 fruDataIter += 1 + fieldLength;
1512 }
1513 endOfFieldsLoc = fruDataIter;
1514 }
1515
1516 std::copy_n(fruData.begin() + restFRUFieldsLoc,
1517 endOfFieldsLoc - restFRUFieldsLoc + 1,
1518 std::back_inserter(restFRUAreaFieldsData));
1519
1520 fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1521 fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1522
1523 return true;
1524}
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301525
1526// Get all device dbus path and match path with product name using
1527// regular expression and find the device index for all devices.
1528
1529std::optional<int> findIndexForFRU(
1530 boost::container::flat_map<
1531 std::pair<size_t, size_t>,
1532 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1533 std::string& productName)
1534{
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301535 int highest = -1;
1536 bool found = false;
1537
Patrick Williamsdf190612023-05-10 07:51:34 -05001538 for (const auto& busIface : dbusInterfaceMap)
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301539 {
1540 std::string path = busIface.second->get_object_path();
1541 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1542 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301543 // Check if the match named has extra information.
1544 found = true;
1545 std::smatch baseMatch;
1546
1547 bool match = std::regex_match(path, baseMatch,
1548 std::regex(productName + "_(\\d+)$"));
1549 if (match)
1550 {
1551 if (baseMatch.size() == 2)
1552 {
1553 std::ssub_match baseSubMatch = baseMatch[1];
1554 std::string base = baseSubMatch.str();
1555
1556 int value = std::stoi(base);
1557 highest = (value > highest) ? value : highest;
1558 }
1559 }
1560 }
1561 } // end searching objects
1562
1563 if (!found)
1564 {
1565 return std::nullopt;
1566 }
1567 return highest;
1568}
Kumar Thangavel9f2162a2022-08-10 18:05:20 +05301569
1570// This function does format fru data as per IPMI format and find the
1571// productName in the formatted fru data, get that productName and return
1572// productName if found or return NULL.
1573
1574std::optional<std::string> getProductName(
1575 std::vector<uint8_t>& device,
1576 boost::container::flat_map<std::string, std::string>& formattedFRU,
1577 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1578{
1579 std::string productName;
1580
1581 resCodes res = formatIPMIFRU(device, formattedFRU);
1582 if (res == resCodes::resErr)
1583 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001584 lg2::error("failed to parse FRU for device at bus {BUS} address {ADDR}",
1585 "BUS", bus, "ADDR", address);
Kumar Thangavel9f2162a2022-08-10 18:05:20 +05301586 return std::nullopt;
1587 }
1588 if (res == resCodes::resWarn)
1589 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001590 lg2::error(
1591 "Warnings while parsing FRU for device at bus {BUS} address {ADDR}",
1592 "BUS", bus, "ADDR", address);
Kumar Thangavel9f2162a2022-08-10 18:05:20 +05301593 }
1594
1595 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1596 // Not found under Board section or an empty string.
1597 if (productNameFind == formattedFRU.end() ||
1598 productNameFind->second.empty())
1599 {
1600 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1601 }
1602 // Found under Product section and not an empty string.
1603 if (productNameFind != formattedFRU.end() &&
1604 !productNameFind->second.empty())
1605 {
1606 productName = productNameFind->second;
1607 std::regex illegalObject("[^A-Za-z0-9_]");
1608 productName = std::regex_replace(productName, illegalObject, "_");
1609 }
1610 else
1611 {
1612 productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1613 unknownBusObjectCount++;
1614 }
1615 return productName;
1616}
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301617
1618bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1619{
1620 try
1621 {
1622 fruData = getFRUInfo(static_cast<uint16_t>(bus),
1623 static_cast<uint8_t>(address));
1624 }
1625 catch (const std::invalid_argument& e)
1626 {
Alexander Hansen8feb0452025-09-15 14:29:20 +02001627 lg2::error("Failure getting FRU Info: {ERR}", "ERR", e);
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301628 return false;
1629 }
1630
1631 return !fruData.empty();
1632}
Naresh Solanki89092a92025-06-02 15:48:04 +05301633
1634bool isFieldEditable(std::string_view fieldName)
1635{
1636 if (fieldName == "PRODUCT_ASSET_TAG")
1637 {
1638 return true; // PRODUCT_ASSET_TAG is always editable.
1639 }
1640
1641 if (!ENABLE_FRU_UPDATE_PROPERTY)
1642 {
1643 return false; // If FRU update is disabled, no fields are editable.
1644 }
1645
1646 // Editable fields
1647 constexpr std::array<std::string_view, 8> editableFields = {
1648 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
1649 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM"};
1650
1651 // Find position of first underscore
1652 std::size_t pos = fieldName.find('_');
1653 if (pos == std::string_view::npos || pos + 1 >= fieldName.size())
1654 {
1655 return false;
1656 }
1657
1658 // Extract substring after the underscore
1659 std::string_view subField = fieldName.substr(pos + 1);
1660
1661 // Trim trailing digits
1662 while (!subField.empty() && (std::isdigit(subField.back()) != 0))
1663 {
1664 subField.remove_suffix(1);
1665 }
1666
1667 // Match against editable fields
1668 return std::ranges::contains(editableFields, subField);
1669}