blob: 4b0171932a26c5d0cf895d910d8c80e6853d0ac7 [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>
Patrick Ventureab296412020-12-30 13:39:37 -080013#include <iostream>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053014#include <numeric>
Patrick Ventureab296412020-12-30 13:39:37 -080015#include <set>
Hieu Huynh5286afe2022-10-12 11:41:12 +000016#include <sstream>
Patrick Ventureab296412020-12-30 13:39:37 -080017#include <string>
18#include <vector>
19
20extern "C"
21{
22// Include for I2C_SMBUS_BLOCK_MAX
23#include <linux/i2c.h>
24}
25
Patrick Ventureab296412020-12-30 13:39:37 -080026constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
27
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +080028std::tm intelEpoch()
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000029{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053030 std::tm val = {};
31 val.tm_year = 1996 - 1900;
Scron-Chang9e5a6752021-03-16 10:51:50 +080032 val.tm_mday = 1;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053033 return val;
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000034}
35
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053036char sixBitToChar(uint8_t val)
Patrick Ventureab296412020-12-30 13:39:37 -080037{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053038 return static_cast<char>((val & 0x3f) + ' ');
39}
40
41char bcdPlusToChar(uint8_t val)
42{
43 val &= 0xf;
44 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
45}
46
47enum FRUDataEncoding
48{
49 binary = 0x0,
50 bcdPlus = 0x1,
51 sixBitASCII = 0x2,
52 languageDependent = 0x3,
53};
54
Hieu Huynh5286afe2022-10-12 11:41:12 +000055enum MultiRecordType : uint8_t
56{
57 powerSupplyInfo = 0x00,
58 dcOutput = 0x01,
59 dcLoad = 0x02,
60 managementAccessRecord = 0x03,
61 baseCompatibilityRecord = 0x04,
62 extendedCompatibilityRecord = 0x05,
63 resvASFSMBusDeviceRecord = 0x06,
64 resvASFLegacyDeviceAlerts = 0x07,
65 resvASFRemoteControl = 0x08,
66 extendedDCOutput = 0x09,
67 extendedDCLoad = 0x0A
68};
69
70enum SubManagementAccessRecord : uint8_t
71{
72 systemManagementURL = 0x01,
73 systemName = 0x02,
74 systemPingAddress = 0x03,
75 componentManagementURL = 0x04,
76 componentName = 0x05,
77 componentPingAddress = 0x06,
78 systemUniqueID = 0x07
79};
80
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053081/* Decode FRU data into a std::string, given an input iterator and end. If the
82 * state returned is fruDataOk, then the resulting string is the decoded FRU
83 * data. The input iterator is advanced past the data consumed.
84 *
85 * On fruDataErr, we have lost synchronisation with the length bytes, so the
86 * iterator is no longer usable.
87 */
Patrick Williamsb7077432024-08-16 15:22:21 -040088std::pair<DecodeState, std::string> decodeFRUData(
Ed Tanous23e3f452025-04-08 10:37:56 -070089 std::span<const uint8_t>::const_iterator& iter,
90 std::span<const uint8_t>::const_iterator& end, bool isLangEng)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053091{
92 std::string value;
Ed Tanous3013fb42022-07-09 08:27:06 -070093 unsigned int i = 0;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053094
95 /* we need at least one byte to decode the type/len header */
96 if (iter == end)
Patrick Ventureab296412020-12-30 13:39:37 -080097 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053098 std::cerr << "Truncated FRU data\n";
99 return make_pair(DecodeState::err, value);
100 }
101
102 uint8_t c = *(iter++);
103
104 /* 0xc1 is the end marker */
105 if (c == 0xc1)
106 {
107 return make_pair(DecodeState::end, value);
108 }
109
110 /* decode type/len byte */
111 uint8_t type = static_cast<uint8_t>(c >> 6);
112 uint8_t len = static_cast<uint8_t>(c & 0x3f);
113
114 /* we should have at least len bytes of data available overall */
115 if (iter + len > end)
116 {
117 std::cerr << "FRU data field extends past end of FRU area data\n";
118 return make_pair(DecodeState::err, value);
119 }
120
121 switch (type)
122 {
123 case FRUDataEncoding::binary:
Patrick Ventureab296412020-12-30 13:39:37 -0800124 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530125 std::stringstream ss;
126 ss << std::hex << std::setfill('0');
127 for (i = 0; i < len; i++, iter++)
128 {
129 uint8_t val = static_cast<uint8_t>(*iter);
130 ss << std::setw(2) << static_cast<int>(val);
131 }
132 value = ss.str();
133 break;
Patrick Ventureab296412020-12-30 13:39:37 -0800134 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530135 case FRUDataEncoding::languageDependent:
136 /* For language-code dependent encodings, assume 8-bit ASCII */
137 value = std::string(iter, iter + len);
138 iter += len;
139
140 /* English text is encoded in 8-bit ASCII + Latin 1. All other
141 * languages are required to use 2-byte unicode. FruDevice does not
142 * handle unicode.
143 */
144 if (!isLangEng)
145 {
146 std::cerr << "Error: Non english string is not supported \n";
147 return make_pair(DecodeState::err, value);
148 }
149
150 break;
151
152 case FRUDataEncoding::bcdPlus:
153 value = std::string();
154 for (i = 0; i < len; i++, iter++)
155 {
156 uint8_t val = *iter;
157 value.push_back(bcdPlusToChar(val >> 4));
158 value.push_back(bcdPlusToChar(val & 0xf));
159 }
160 break;
161
162 case FRUDataEncoding::sixBitASCII:
163 {
164 unsigned int accum = 0;
165 unsigned int accumBitLen = 0;
166 value = std::string();
167 for (i = 0; i < len; i++, iter++)
168 {
169 accum |= *iter << accumBitLen;
170 accumBitLen += 8;
171 while (accumBitLen >= 6)
172 {
173 value.push_back(sixBitToChar(accum & 0x3f));
174 accum >>= 6;
175 accumBitLen -= 6;
176 }
177 }
178 }
179 break;
Ed Tanousfc171422024-04-04 17:18:16 -0700180
181 default:
182 {
183 return make_pair(DecodeState::err, value);
184 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530185 }
186
187 return make_pair(DecodeState::ok, value);
188}
189
190bool checkLangEng(uint8_t lang)
191{
192 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
193 // but we don't support that.
Ed Tanous3013fb42022-07-09 08:27:06 -0700194 if ((lang != 0U) && lang != 25)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530195 {
196 std::cerr << "Warning: languages other than English is not "
197 "supported\n";
198 // Return language flag as non english
Patrick Ventureab296412020-12-30 13:39:37 -0800199 return false;
200 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800201 return true;
Patrick Ventureab296412020-12-30 13:39:37 -0800202}
203
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000204/* This function verifies for other offsets to check if they are not
205 * falling under other field area
206 *
207 * fruBytes: Start of Fru data
208 * currentArea: Index of current area offset to be compared against all area
209 * offset and it is a multiple of 8 bytes as per specification
210 * len: Length of current area space and it is a multiple of 8 bytes
211 * as per specification
212 */
Ed Tanous23e3f452025-04-08 10:37:56 -0700213bool verifyOffset(std::span<const uint8_t> fruBytes, fruAreas currentArea,
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000214 uint8_t len)
215{
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000216 unsigned int fruBytesSize = fruBytes.size();
217
218 // check if Fru data has at least 8 byte header
219 if (fruBytesSize <= fruBlockSize)
220 {
221 std::cerr << "Error: trying to parse empty FRU\n";
222 return false;
223 }
224
225 // Check range of passed currentArea value
226 if (currentArea > fruAreas::fruAreaMultirecord)
227 {
228 std::cerr << "Error: Fru area is out of range\n";
229 return false;
230 }
231
232 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
233 if (currentAreaIndex > fruBytesSize)
234 {
235 std::cerr << "Error: Fru area index is out of range\n";
236 return false;
237 }
238
239 unsigned int start = fruBytes[currentAreaIndex];
240 unsigned int end = start + len;
241
242 /* Verify each offset within the range of start and end */
243 for (fruAreas area = fruAreas::fruAreaInternal;
244 area <= fruAreas::fruAreaMultirecord; ++area)
245 {
246 // skip the current offset
247 if (area == currentArea)
248 {
249 continue;
250 }
251
252 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
253 if (areaIndex > fruBytesSize)
254 {
255 std::cerr << "Error: Fru area index is out of range\n";
256 return false;
257 }
258
259 unsigned int areaOffset = fruBytes[areaIndex];
260 // if areaOffset is 0 means this area is not available so skip
261 if (areaOffset == 0)
262 {
263 continue;
264 }
265
266 // check for overlapping of current offset with given areaoffset
267 if (areaOffset == start || (areaOffset > start && areaOffset < end))
268 {
269 std::cerr << getFruAreaName(currentArea)
270 << " offset is overlapping with " << getFruAreaName(area)
271 << " offset\n";
272 return false;
273 }
274 }
275 return true;
276}
277
Hieu Huynh5286afe2022-10-12 11:41:12 +0000278static void parseMultirecordUUID(
Ed Tanous23e3f452025-04-08 10:37:56 -0700279 std::span<const uint8_t> device,
Hieu Huynh5286afe2022-10-12 11:41:12 +0000280 boost::container::flat_map<std::string, std::string>& result)
281{
282 constexpr size_t uuidDataLen = 16;
283 constexpr size_t multiRecordHeaderLen = 5;
284 /* UUID record data, plus one to skip past the sub-record type byte */
285 constexpr size_t uuidRecordData = multiRecordHeaderLen + 1;
286 constexpr size_t multiRecordEndOfListMask = 0x80;
287 /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented
288 * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD
289 * 0xEE 0xFF
290 */
291 const std::array<uint8_t, uuidDataLen> uuidCharOrder = {
292 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
Ed Tanous23e3f452025-04-08 10:37:56 -0700293 size_t offset = getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord);
294 if (offset >= device.size())
295 {
296 throw std::runtime_error("Multirecord UUID offset is out of range");
297 }
298 uint32_t areaOffset = device[offset];
Hieu Huynh5286afe2022-10-12 11:41:12 +0000299
300 if (areaOffset == 0)
301 {
302 return;
303 }
304
305 areaOffset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700306 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400307 device.begin() + areaOffset;
Hieu Huynh5286afe2022-10-12 11:41:12 +0000308
309 /* Verify area offset */
310 if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter))
311 {
312 return;
313 }
314 while (areaOffset + uuidRecordData + uuidDataLen <= device.size())
315 {
316 if ((areaOffset < device.size()) &&
317 (device[areaOffset] ==
318 (uint8_t)MultiRecordType::managementAccessRecord))
319 {
320 if ((areaOffset + multiRecordHeaderLen < device.size()) &&
321 (device[areaOffset + multiRecordHeaderLen] ==
322 (uint8_t)SubManagementAccessRecord::systemUniqueID))
323 {
324 /* Layout of UUID:
325 * source: https://www.ietf.org/rfc/rfc4122.txt
326 *
327 * UUID binary format (16 bytes):
328 * 4B-2B-2B-2B-6B (big endian)
329 *
330 * UUID string is 36 length of characters (36 bytes):
331 * 0 9 14 19 24
332 * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
333 * be be be be be
334 * be means it should be converted to big endian.
335 */
336 /* Get UUID bytes to UUID string */
337 std::stringstream tmp;
338 tmp << std::hex << std::setfill('0');
339 for (size_t i = 0; i < uuidDataLen; i++)
340 {
341 tmp << std::setw(2)
342 << static_cast<uint16_t>(
343 device[areaOffset + uuidRecordData +
344 uuidCharOrder[i]]);
345 }
346 std::string uuidStr = tmp.str();
347 result["MULTIRECORD_UUID"] =
348 uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' +
349 uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' +
350 uuidStr.substr(20, 12);
351 break;
352 }
353 }
354 if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0)
355 {
356 break;
357 }
358 areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen;
359 }
360}
361
Ed Tanous5ea38d22025-04-08 09:36:43 -0700362resCodes decodeField(
363 std::span<const uint8_t>::const_iterator& fruBytesIter,
364 std::span<const uint8_t>::const_iterator& fruBytesIterEndArea,
365 const std::vector<std::string>& fruAreaFieldNames, size_t& fieldIndex,
366 DecodeState& state, bool isLangEng, const fruAreas& area,
367 boost::container::flat_map<std::string, std::string>& result)
368{
369 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
370 state = res.first;
371 std::string value = res.second;
372 std::string name;
Ed Tanous7f2db482025-04-04 16:38:42 -0700373 bool isCustomField = false;
Ed Tanous5ea38d22025-04-08 09:36:43 -0700374 if (fieldIndex < fruAreaFieldNames.size())
375 {
376 name = std::string(getFruAreaName(area)) + "_" +
377 fruAreaFieldNames.at(fieldIndex);
378 }
379 else
380 {
Ed Tanous7f2db482025-04-04 16:38:42 -0700381 isCustomField = true;
Ed Tanous5ea38d22025-04-08 09:36:43 -0700382 name = std::string(getFruAreaName(area)) + "_" + fruCustomFieldName +
383 std::to_string(fieldIndex - fruAreaFieldNames.size() + 1);
384 }
385
386 if (state == DecodeState::ok)
387 {
388 // Strip non null characters and trailing spaces from the end
389 value.erase(
390 std::find_if(value.rbegin(), value.rend(),
391 [](char ch) { return ((ch != 0) && (ch != ' ')); })
392 .base(),
393 value.end());
Ed Tanous7f2db482025-04-04 16:38:42 -0700394 if (isCustomField)
395 {
396 // Some MAC addresses are stored in a custom field, with
397 // "MAC:" prefixed on the value. If we see that, create a
398 // new field with the decoded data
399 if (value.starts_with("MAC: "))
400 {
401 result["MAC_" + name] = value.substr(5);
402 }
403 }
Ed Tanous5ea38d22025-04-08 09:36:43 -0700404 result[name] = std::move(value);
405 ++fieldIndex;
406 }
407 else if (state == DecodeState::err)
408 {
409 std::cerr << "Error while parsing " << name << "\n";
410
411 // Cancel decoding if failed to parse any of mandatory
412 // fields
413 if (fieldIndex < fruAreaFieldNames.size())
414 {
415 std::cerr << "Failed to parse mandatory field \n";
416 return resCodes::resErr;
417 }
418 return resCodes::resWarn;
419 }
420 else
421 {
422 if (fieldIndex < fruAreaFieldNames.size())
423 {
424 std::cerr << "Mandatory fields absent in FRU area "
425 << getFruAreaName(area) << " after " << name << "\n";
426 return resCodes::resWarn;
427 }
428 }
429 return resCodes::resOK;
430}
431
Patrick Williams5a807032025-03-03 11:20:39 -0500432resCodes formatIPMIFRU(
Ed Tanous23e3f452025-04-08 10:37:56 -0700433 std::span<const uint8_t> fruBytes,
Patrick Williams5a807032025-03-03 11:20:39 -0500434 boost::container::flat_map<std::string, std::string>& result)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530435{
436 resCodes ret = resCodes::resOK;
437 if (fruBytes.size() <= fruBlockSize)
438 {
439 std::cerr << "Error: trying to parse empty FRU \n";
440 return resCodes::resErr;
441 }
442 result["Common_Format_Version"] =
443 std::to_string(static_cast<int>(*fruBytes.begin()));
444
Ed Tanous3013fb42022-07-09 08:27:06 -0700445 const std::vector<std::string>* fruAreaFieldNames = nullptr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530446
447 // Don't parse Internal and Multirecord areas
448 for (fruAreas area = fruAreas::fruAreaChassis;
449 area <= fruAreas::fruAreaProduct; ++area)
450 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530451 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
452 if (offset == 0)
453 {
454 continue;
455 }
456 offset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700457 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400458 fruBytes.begin() + offset;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530459 if (fruBytesIter + fruBlockSize >= fruBytes.end())
460 {
461 std::cerr << "Not enough data to parse \n";
462 return resCodes::resErr;
463 }
464 // check for format version 1
465 if (*fruBytesIter != 0x01)
466 {
467 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
468 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";
496 std::cerr << ss.str();
497 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 {
537 std::cerr << "invalid time string encountered\n";
538 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 {
559 std::cerr << "Internal error: unexpected FRU area index: "
560 << static_cast<int>(area) << " \n";
561 return resCodes::resErr;
562 }
563 }
564 size_t fieldIndex = 0;
Ed Tanous3013fb42022-07-09 08:27:06 -0700565 DecodeState state = DecodeState::ok;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530566 do
567 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700568 resCodes decodeRet = decodeField(fruBytesIter, fruBytesIterEndArea,
569 *fruAreaFieldNames, fieldIndex,
570 state, isLangEng, area, result);
571 if (decodeRet == resCodes::resErr)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530572 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700573 return resCodes::resErr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530574 }
Ed Tanous5ea38d22025-04-08 09:36:43 -0700575 if (decodeRet == resCodes::resWarn)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530576 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700577 ret = decodeRet;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530578 }
579 } while (state == DecodeState::ok);
580 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
581 {
582 uint8_t c = *fruBytesIter;
Ed Tanous3013fb42022-07-09 08:27:06 -0700583 if (c != 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530584 {
585 std::cerr << "Non-zero byte after EndOfFields in FRU area "
586 << getFruAreaName(area) << "\n";
587 ret = resCodes::resWarn;
588 break;
589 }
590 }
591 }
592
Hieu Huynh5286afe2022-10-12 11:41:12 +0000593 /* Parsing the Multirecord UUID */
594 parseMultirecordUUID(fruBytes, result);
595
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530596 return ret;
597}
598
599// Calculate new checksum for fru info area
Ed Tanous23e3f452025-04-08 10:37:56 -0700600uint8_t calculateChecksum(std::span<const uint8_t>::const_iterator iter,
601 std::span<const uint8_t>::const_iterator end)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530602{
603 constexpr int checksumMod = 256;
Andrew Jeffery499e7aa2021-08-02 22:18:22 +0930604 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
605 return (checksumMod - sum) % checksumMod;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530606}
607
Ed Tanous23e3f452025-04-08 10:37:56 -0700608uint8_t calculateChecksum(std::span<const uint8_t> fruAreaData)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530609{
610 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
611}
612
613// Update new fru area length &
614// Update checksum at new checksum location
615// Return the offset of the area checksum byte
Patrick Williamsb7077432024-08-16 15:22:21 -0400616unsigned int updateFRUAreaLenAndChecksum(
617 std::vector<uint8_t>& fruData, size_t fruAreaStart,
618 size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530619{
620 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
621
622 // fill zeros for any remaining unused space
623 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
624 fruData.begin() + fruAreaEndOffset, 0);
625
626 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Ed Tanous3013fb42022-07-09 08:27:06 -0700627 size_t checksumLoc = 0;
628 if (mod == 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530629 {
630 traverseFRUAreaIndex += (fruBlockSize);
631 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
632 }
633 else
634 {
635 traverseFRUAreaIndex += (fruBlockSize - mod);
636 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
637 }
638
Ed Tanous3013fb42022-07-09 08:27:06 -0700639 size_t newFRUAreaLen =
640 (traverseFRUAreaIndex / fruBlockSize) +
641 static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530642 size_t fruAreaLengthLoc = fruAreaStart + 1;
643 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
644
645 // Calculate new checksum
646 std::vector<uint8_t> finalFRUData;
647 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
648 std::back_inserter(finalFRUData));
649
650 fruData[checksumLoc] = calculateChecksum(finalFRUData);
651 return checksumLoc;
652}
653
654ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
655{
656 constexpr uint8_t typeLenMask = 0x3F;
657 constexpr uint8_t endOfFields = 0xC1;
658 if (fruFieldTypeLenValue == endOfFields)
659 {
660 return -1;
661 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800662 return fruFieldTypeLenValue & typeLenMask;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530663}
664
665bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
666{
667 // ipmi spec format version number is currently at 1, verify it
668 if (blockData[0] != fruVersion)
669 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200670 lg2::debug(
671 "FRU spec version {VERSION} not supported. Supported version is {SUPPORTED_VERSION}",
672 "VERSION", lg2::hex, blockData[0], "SUPPORTED_VERSION", lg2::hex,
673 fruVersion);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530674 return false;
675 }
676
677 // verify pad is set to 0
678 if (blockData[6] != 0x0)
679 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200680 lg2::debug("Pad value in header is non zero, value is {VALUE}", "VALUE",
681 lg2::hex, blockData[6]);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530682 return false;
683 }
684
685 // verify offsets are 0, or don't point to another offset
686 std::set<uint8_t> foundOffsets;
687 for (int ii = 1; ii < 6; ii++)
688 {
689 if (blockData[ii] == 0)
690 {
691 continue;
692 }
693 auto inserted = foundOffsets.insert(blockData[ii]);
694 if (!inserted.second)
695 {
696 return false;
697 }
698 }
699
700 // validate checksum
701 size_t sum = 0;
702 for (int jj = 0; jj < 7; jj++)
703 {
704 sum += blockData[jj];
705 }
706 sum = (256 - sum) & 0xFF;
707
708 if (sum != blockData[7])
709 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200710 lg2::debug(
711 "Checksum {CHECKSUM} is invalid. calculated checksum is {CALCULATED_CHECKSUM}",
712 "CHECKSUM", lg2::hex, blockData[7], "CALCULATED_CHECKSUM", lg2::hex,
713 sum);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530714 return false;
715 }
716 return true;
717}
718
Zev Weiss309c0b12022-02-25 01:44:12 +0000719bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
Oskar Senftbd4075f2021-10-05 23:42:43 -0400720 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
Zev Weiss1525e852022-03-22 22:27:43 +0000721 off_t& baseOffset)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400722{
Zev Weiss309c0b12022-02-25 01:44:12 +0000723 if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400724 {
725 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030726 << baseOffset << "\n";
Oskar Senftbd4075f2021-10-05 23:42:43 -0400727 return false;
728 }
729
730 // check the header checksum
731 if (validateHeader(blockData))
732 {
733 return true;
734 }
735
736 // only continue the search if we just looked at 0x0.
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030737 if (baseOffset != 0)
738 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400739 return false;
740 }
741
742 // now check for special cases where the IPMI data is at an offset
743
744 // check if blockData starts with tyanHeader
745 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
746 if (blockData.size() >= tyanHeader.size() &&
747 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
748 {
749 // look for the FRU header at offset 0x6000
750 baseOffset = 0x6000;
Zev Weiss309c0b12022-02-25 01:44:12 +0000751 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400752 }
753
Mark Kuocc2d9e22025-08-26 01:26:50 -0700754 // check if blockData starts with gigabyteHeader
755 const std::vector<uint8_t> gigabyteHeader = {'G', 'I', 'G', 'A',
756 'B', 'Y', 'T', 'E'};
757 if (blockData.size() >= gigabyteHeader.size() &&
758 std::equal(gigabyteHeader.begin(), gigabyteHeader.end(),
759 blockData.begin()))
760 {
761 // look for the FRU header at offset 0x4000
762 baseOffset = 0x4000;
763 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
764 }
765
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200766 lg2::debug("Illegal header {HEADER} base offset {OFFSET}", "HEADER",
767 errorHelp, "OFFSET", baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400768
769 return false;
770}
771
Patrick Williams5a807032025-03-03 11:20:39 -0500772std::pair<std::vector<uint8_t>, bool> readFRUContents(
773 FRUReader& reader, const std::string& errorHelp)
Patrick Ventureab296412020-12-30 13:39:37 -0800774{
Ed Tanous3013fb42022-07-09 08:27:06 -0700775 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
Zev Weiss1525e852022-03-22 22:27:43 +0000776 off_t baseOffset = 0x0;
Patrick Ventureab296412020-12-30 13:39:37 -0800777
Zev Weiss309c0b12022-02-25 01:44:12 +0000778 if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030779 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200780 return {{}, false};
Patrick Ventureab296412020-12-30 13:39:37 -0800781 }
782
783 std::vector<uint8_t> device;
Alexander Hansen5df916f2025-09-26 10:31:36 -0400784 device.insert(device.end(), blockData.begin(),
785 std::next(blockData.begin(), 8));
Patrick Ventureab296412020-12-30 13:39:37 -0800786
787 bool hasMultiRecords = false;
788 size_t fruLength = fruBlockSize; // At least FRU header is present
Vijay Khemka7792e392021-01-25 13:03:56 -0800789 unsigned int prevOffset = 0;
Patrick Ventureab296412020-12-30 13:39:37 -0800790 for (fruAreas area = fruAreas::fruAreaInternal;
791 area <= fruAreas::fruAreaMultirecord; ++area)
792 {
793 // Offset value can be 255.
794 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
795 if (areaOffset == 0)
796 {
797 continue;
798 }
799
Vijay Khemka7792e392021-01-25 13:03:56 -0800800 /* Check for offset order, as per Section 17 of FRU specification, FRU
801 * information areas are required to be in order in FRU data layout
802 * which means all offset value should be in increasing order or can be
803 * 0 if that area is not present
804 */
805 if (areaOffset <= prevOffset)
806 {
807 std::cerr << "Fru area offsets are not in required order as per "
808 "Section 17 of Fru specification\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200809 return {{}, true};
Vijay Khemka7792e392021-01-25 13:03:56 -0800810 }
811 prevOffset = areaOffset;
812
Patrick Ventureab296412020-12-30 13:39:37 -0800813 // MultiRecords are different. area is not tracking section, it's
814 // walking the common header.
815 if (area == fruAreas::fruAreaMultirecord)
816 {
817 hasMultiRecords = true;
818 break;
819 }
820
821 areaOffset *= fruBlockSize;
822
Zev Weiss309c0b12022-02-25 01:44:12 +0000823 if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800824 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400825 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030826 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200827 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800828 }
829
830 // Ignore data type (blockData is already unsigned).
831 size_t length = blockData[1] * fruBlockSize;
832 areaOffset += length;
833 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
834 }
835
836 if (hasMultiRecords)
837 {
838 // device[area count] is the index to the last area because the 0th
839 // entry is not an offset in the common header.
840 unsigned int areaOffset =
841 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
842 areaOffset *= fruBlockSize;
843
844 // the multi-area record header is 5 bytes long.
845 constexpr size_t multiRecordHeaderSize = 5;
846 constexpr uint8_t multiRecordEndOfListMask = 0x80;
847
848 // Sanity hard-limit to 64KB.
849 while (areaOffset < std::numeric_limits<uint16_t>::max())
850 {
851 // In multi-area, the area offset points to the 0th record, each
852 // record has 3 bytes of the header we care about.
Zev Weiss309c0b12022-02-25 01:44:12 +0000853 if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800854 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400855 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030856 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200857 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800858 }
859
860 // Ok, let's check the record length, which is in bytes (unsigned,
861 // up to 255, so blockData should hold uint8_t not char)
862 size_t recordLength = blockData[2];
863 areaOffset += (recordLength + multiRecordHeaderSize);
864 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
865
866 // If this is the end of the list bail.
Ed Tanous3013fb42022-07-09 08:27:06 -0700867 if ((blockData[1] & multiRecordEndOfListMask) != 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800868 {
869 break;
870 }
871 }
872 }
873
874 // You already copied these first 8 bytes (the ipmi fru header size)
875 fruLength -= std::min(fruBlockSize, fruLength);
876
877 int readOffset = fruBlockSize;
878
879 while (fruLength > 0)
880 {
881 size_t requestLength =
882 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
883
Zev Weiss309c0b12022-02-25 01:44:12 +0000884 if (reader.read(baseOffset + readOffset, requestLength,
885 blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800886 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400887 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030888 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200889 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800890 }
891
892 device.insert(device.end(), blockData.begin(),
Alexander Hansen5df916f2025-09-26 10:31:36 -0400893 std::next(blockData.begin(), requestLength));
Patrick Ventureab296412020-12-30 13:39:37 -0800894
895 readOffset += requestLength;
896 fruLength -= std::min(requestLength, fruLength);
897 }
898
Marvin Drees2b3ed302023-04-14 16:35:14 +0200899 return {device, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800900}
901
902unsigned int getHeaderAreaFieldOffset(fruAreas area)
903{
904 return static_cast<unsigned int>(area) + 1;
905}
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530906
krishnar4213ee212022-11-11 15:39:30 +0530907std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530908{
909 auto deviceMap = busMap.find(bus);
910 if (deviceMap == busMap.end())
911 {
912 throw std::invalid_argument("Invalid Bus.");
913 }
914 auto device = deviceMap->second->find(address);
915 if (device == deviceMap->second->end())
916 {
917 throw std::invalid_argument("Invalid Address.");
918 }
919 std::vector<uint8_t>& ret = device->second;
920
921 return ret;
922}
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +0530923
Marc Olberding25680e32025-10-03 12:38:10 -0700924static bool updateHeaderChecksum(std::vector<uint8_t>& fruData)
Naresh Solankicf288962025-06-06 15:26:11 +0530925{
Marc Olberding25680e32025-10-03 12:38:10 -0700926 if (fruData.size() < fruBlockSize)
Naresh Solankicf288962025-06-06 15:26:11 +0530927 {
928 lg2::debug("FRU data is too small to contain a valid header.");
929 return false;
930 }
Naresh Solankicf288962025-06-06 15:26:11 +0530931
Marc Olberding25680e32025-10-03 12:38:10 -0700932 uint8_t& checksumInBytes = fruData[7];
933 uint8_t checksum =
934 calculateChecksum({fruData.begin(), fruData.begin() + 7});
935 std::swap(checksumInBytes, checksum);
936
937 if (checksumInBytes != checksum)
Naresh Solankicf288962025-06-06 15:26:11 +0530938 {
939 lg2::debug(
940 "FRU header checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
Marc Olberding25680e32025-10-03 12:38:10 -0700941 "OLD_CHECKSUM", static_cast<int>(checksum), "NEW_CHECKSUM",
942 static_cast<int>(checksumInBytes));
Naresh Solankicf288962025-06-06 15:26:11 +0530943 }
944 return true;
945}
946
Marc Olberding25680e32025-10-03 12:38:10 -0700947bool updateAreaChecksum(std::vector<uint8_t>& fruArea)
Naresh Solankicf288962025-06-06 15:26:11 +0530948{
949 if (fruArea.size() < fruBlockSize)
950 {
951 lg2::debug("FRU area is too small to contain a valid header.");
952 return false;
953 }
954 if (fruArea.size() % fruBlockSize != 0)
955 {
956 lg2::debug("FRU area size is not a multiple of {SIZE} bytes.", "SIZE",
957 fruBlockSize);
958 return false;
959 }
960
961 uint8_t oldcksum = fruArea[fruArea.size() - 1];
962
963 fruArea[fruArea.size() - 1] =
964 0; // Reset checksum byte to 0 before recalculating
965 fruArea[fruArea.size() - 1] = calculateChecksum(fruArea);
966
967 if (oldcksum != fruArea[fruArea.size() - 1])
968 {
969 lg2::debug(
970 "FRU area checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
971 "OLD_CHECKSUM", static_cast<int>(oldcksum), "NEW_CHECKSUM",
972 static_cast<int>(fruArea[fruArea.size() - 1]));
973 }
974 return true;
975}
976
Marc Olberding25680e32025-10-03 12:38:10 -0700977static std::optional<size_t> calculateAreaSize(
978 fruAreas area, std::span<const uint8_t> fruData, size_t areaOffset)
979{
980 switch (area)
981 {
982 case fruAreas::fruAreaChassis:
983 case fruAreas::fruAreaBoard:
984 case fruAreas::fruAreaProduct:
985 if (areaOffset + 1 >= fruData.size())
986 {
987 return std::nullopt;
988 }
989 return fruData[areaOffset + 1] * fruBlockSize; // Area size in bytes
990 case fruAreas::fruAreaInternal:
991 {
992 // Internal area size: It is difference between the next area
993 // offset and current area offset
994 for (fruAreas areaIt = fruAreas::fruAreaChassis;
995 areaIt <= fruAreas::fruAreaMultirecord; ++areaIt)
996 {
997 size_t headerOffset = getHeaderAreaFieldOffset(areaIt);
998 if (headerOffset >= fruData.size())
999 {
1000 return std::nullopt;
1001 }
1002 size_t nextAreaOffset = fruData[headerOffset];
1003 if (nextAreaOffset != 0)
1004 {
1005 return nextAreaOffset * fruBlockSize - areaOffset;
1006 }
1007 }
1008 return std::nullopt;
1009 }
1010 break;
1011 case fruAreas::fruAreaMultirecord:
1012 // Multirecord area size.
1013 return fruData.size() - areaOffset; // Area size in bytes
1014 default:
1015 lg2::error("Invalid FRU area: {AREA}", "AREA",
1016 static_cast<int>(area));
1017 }
1018 return std::nullopt;
1019}
1020
1021static size_t getBlockCount(size_t byteCount)
1022{
1023 size_t blocks = (byteCount + fruBlockSize - 1) / fruBlockSize;
1024 // if we're perfectly aligned, we need another block for the checksum
1025 if ((byteCount % fruBlockSize) == 0)
1026 {
1027 blocks++;
1028 }
1029 return blocks;
1030}
1031
Naresh Solankicf288962025-06-06 15:26:11 +05301032bool disassembleFruData(std::vector<uint8_t>& fruData,
1033 std::vector<std::vector<uint8_t>>& areasData)
1034{
1035 if (fruData.size() < 8)
1036 {
1037 lg2::debug("FRU data is too small to contain a valid header.");
1038 return false;
1039 }
1040
1041 // Clear areasData before disassembling
1042 areasData.clear();
1043
1044 // Iterate through all areas & store each area data in a vector.
1045 for (fruAreas area = fruAreas::fruAreaInternal;
1046 area <= fruAreas::fruAreaMultirecord; ++area)
1047 {
1048 size_t areaOffset = fruData[getHeaderAreaFieldOffset(area)];
1049
1050 if (areaOffset == 0)
1051 {
1052 // Store empty area data for areas that are not present
1053 areasData.emplace_back();
1054 continue; // Skip areas that are not present
1055 }
1056 areaOffset *= fruBlockSize; // Convert to byte offset
Marc Olberding25680e32025-10-03 12:38:10 -07001057
1058 std::optional<size_t> areaSize =
1059 calculateAreaSize(area, fruData, areaOffset);
1060 if (!areaSize)
Naresh Solankicf288962025-06-06 15:26:11 +05301061 {
Marc Olberding25680e32025-10-03 12:38:10 -07001062 return false;
Naresh Solankicf288962025-06-06 15:26:11 +05301063 }
1064
Marc Olberding25680e32025-10-03 12:38:10 -07001065 if ((areaOffset + *areaSize) > fruData.size())
Naresh Solankicf288962025-06-06 15:26:11 +05301066 {
1067 lg2::error("Area offset + size exceeds FRU data size.");
1068 return false;
1069 }
Marc Olberding25680e32025-10-03 12:38:10 -07001070
1071 areasData.emplace_back(fruData.begin() + areaOffset,
1072 fruData.begin() + areaOffset + *areaSize);
Naresh Solankicf288962025-06-06 15:26:11 +05301073 }
Marc Olberding25680e32025-10-03 12:38:10 -07001074
Naresh Solankicf288962025-06-06 15:26:11 +05301075 return true;
1076}
1077
Marc Olberding25680e32025-10-03 12:38:10 -07001078struct FieldInfo
Naresh Solankicf288962025-06-06 15:26:11 +05301079{
Marc Olberding25680e32025-10-03 12:38:10 -07001080 size_t length;
1081 size_t index;
1082};
1083
1084static std::optional<FieldInfo> findOrCreateField(
1085 std::vector<uint8_t>& areaData, const std::string& propertyName,
1086 const fruAreas& fruAreaToUpdate)
1087{
1088 int fieldIndex = 0;
Naresh Solankicf288962025-06-06 15:26:11 +05301089 int fieldLength = 0;
Naresh Solankicf288962025-06-06 15:26:11 +05301090 std::string areaName = propertyName.substr(0, propertyName.find('_'));
1091 std::string propertyNamePrefix = areaName + "_";
Marc Olberding25680e32025-10-03 12:38:10 -07001092 const std::vector<std::string>* fruAreaFieldNames = nullptr;
Naresh Solankicf288962025-06-06 15:26:11 +05301093
1094 switch (fruAreaToUpdate)
1095 {
1096 case fruAreas::fruAreaChassis:
1097 fruAreaFieldNames = &chassisFruAreas;
1098 fieldIndex = 3;
1099 break;
1100 case fruAreas::fruAreaBoard:
1101 fruAreaFieldNames = &boardFruAreas;
1102 fieldIndex = 6;
1103 break;
1104 case fruAreas::fruAreaProduct:
1105 fruAreaFieldNames = &productFruAreas;
1106 fieldIndex = 3;
1107 break;
1108 default:
Marc Olberding25680e32025-10-03 12:38:10 -07001109 lg2::info("Invalid FRU area: {AREA}", "AREA",
1110 static_cast<int>(fruAreaToUpdate));
1111 return std::nullopt;
Naresh Solankicf288962025-06-06 15:26:11 +05301112 }
Marc Olberding25680e32025-10-03 12:38:10 -07001113
Naresh Solankicf288962025-06-06 15:26:11 +05301114 for (const auto& field : *fruAreaFieldNames)
1115 {
1116 fieldLength = getFieldLength(areaData[fieldIndex]);
1117 if (fieldLength < 0)
1118 {
Naresh Solankicf288962025-06-06 15:26:11 +05301119 areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1120 fieldLength = 0;
1121 }
1122
1123 if (propertyNamePrefix + field == propertyName)
1124 {
Marc Olberding25680e32025-10-03 12:38:10 -07001125 return FieldInfo{static_cast<size_t>(fieldLength),
1126 static_cast<size_t>(fieldIndex)};
Naresh Solankicf288962025-06-06 15:26:11 +05301127 }
1128 fieldIndex += 1 + fieldLength;
1129 }
Naresh Solankicf288962025-06-06 15:26:11 +05301130
Marc Olberding25680e32025-10-03 12:38:10 -07001131 size_t pos = propertyName.find(fruCustomFieldName);
1132 if (pos == std::string::npos)
1133 {
1134 return std::nullopt;
Naresh Solankicf288962025-06-06 15:26:11 +05301135 }
1136
Marc Olberding25680e32025-10-03 12:38:10 -07001137 // Get field after pos
1138 std::string customFieldIdx =
1139 propertyName.substr(pos + fruCustomFieldName.size());
1140
1141 // Check if customFieldIdx is a number
1142 if (!std::all_of(customFieldIdx.begin(), customFieldIdx.end(), ::isdigit))
Naresh Solankicf288962025-06-06 15:26:11 +05301143 {
Marc Olberding25680e32025-10-03 12:38:10 -07001144 return std::nullopt;
1145 }
1146
1147 size_t customFieldIndex = std::stoi(customFieldIdx);
1148
1149 // insert custom fields up to the index we want
1150 for (size_t i = 0; i < customFieldIndex; i++)
1151 {
1152 fieldLength = getFieldLength(areaData[fieldIndex]);
1153 if (fieldLength < 0)
1154 {
1155 areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1156 fieldLength = 0;
1157 }
1158 fieldIndex += 1 + fieldLength;
1159 }
1160
1161 fieldIndex -= (fieldLength + 1);
1162 fieldLength = getFieldLength(areaData[fieldIndex]);
1163 return FieldInfo{static_cast<size_t>(fieldLength),
1164 static_cast<size_t>(fieldIndex)};
1165}
1166
1167static std::optional<size_t> findEndOfFieldMarker(std::span<uint8_t> bytes)
1168{
1169 // we're skipping the checksum
1170 // this function assumes a properly sized and formatted area
1171 static uint8_t constexpr endOfFieldsByte = 0xc1;
1172 for (int index = bytes.size() - 2; index >= 0; --index)
1173 {
1174 if (bytes[index] == endOfFieldsByte)
1175 {
1176 return index;
1177 }
1178 }
1179 return std::nullopt;
1180}
1181
1182static std::optional<size_t> getNonPaddedSizeOfArea(std::span<uint8_t> bytes)
1183{
1184 if (auto endOfFields = findEndOfFieldMarker(bytes))
1185 {
1186 return *endOfFields + 1;
1187 }
1188 return std::nullopt;
1189}
1190
1191bool setField(const fruAreas& fruAreaToUpdate, std::vector<uint8_t>& areaData,
1192 const std::string& propertyName, const std::string& value)
1193{
1194 if (value.size() == 1 || value.size() > 63)
1195 {
1196 lg2::error("Invalid value {VALUE} for field {PROP}", "VALUE", value,
1197 "PROP", propertyName);
1198 return false;
1199 }
1200
1201 // This is inneficient, but the alternative requires
1202 // a bunch of complicated indexing and search to
1203 // figure out if we cross a block boundary
1204 // if we feel that this is too inneficient in the future,
1205 // we can implement that.
1206 std::vector<uint8_t> tmpBuffer = areaData;
1207
1208 auto fieldInfo =
1209 findOrCreateField(tmpBuffer, propertyName, fruAreaToUpdate);
1210
1211 if (!fieldInfo)
1212 {
1213 lg2::error("Field {FIELD} not found in area {AREA}", "FIELD",
Naresh Solankicf288962025-06-06 15:26:11 +05301214 propertyName, "AREA", getFruAreaName(fruAreaToUpdate));
1215 return false;
1216 }
Naresh Solankicf288962025-06-06 15:26:11 +05301217
Marc Olberding25680e32025-10-03 12:38:10 -07001218 auto fieldIt = tmpBuffer.begin() + fieldInfo->index;
Naresh Solankicf288962025-06-06 15:26:11 +05301219 // Erase the existing field content.
Marc Olberding25680e32025-10-03 12:38:10 -07001220 tmpBuffer.erase(fieldIt, fieldIt + fieldInfo->length + 1);
Naresh Solankicf288962025-06-06 15:26:11 +05301221 // Insert the new field value
Marc Olberding25680e32025-10-03 12:38:10 -07001222 tmpBuffer.insert(fieldIt, 0xc0 | value.size());
1223 tmpBuffer.insert_range(fieldIt + 1, value);
Naresh Solankicf288962025-06-06 15:26:11 +05301224
Marc Olberding25680e32025-10-03 12:38:10 -07001225 auto newSize = getNonPaddedSizeOfArea(tmpBuffer);
1226 auto oldSize = getNonPaddedSizeOfArea(areaData);
Naresh Solankicf288962025-06-06 15:26:11 +05301227
Marc Olberding25680e32025-10-03 12:38:10 -07001228 if (!oldSize || !newSize)
Naresh Solankicf288962025-06-06 15:26:11 +05301229 {
Marc Olberding25680e32025-10-03 12:38:10 -07001230 lg2::error("Failed to find the size of the area");
Naresh Solankicf288962025-06-06 15:26:11 +05301231 return false;
1232 }
1233
Marc Olberding25680e32025-10-03 12:38:10 -07001234 size_t newSizePadded = getBlockCount(*newSize);
Naresh Solankicf288962025-06-06 15:26:11 +05301235#ifndef ENABLE_FRU_AREA_RESIZE
Marc Olberding25680e32025-10-03 12:38:10 -07001236
1237 size_t oldSizePadded = getBlockCount(*oldSize);
1238
1239 if (newSizePadded != oldSizePadded)
Naresh Solankicf288962025-06-06 15:26:11 +05301240 {
Marc Olberding25680e32025-10-03 12:38:10 -07001241 lg2::error(
Naresh Solankicf288962025-06-06 15:26:11 +05301242 "FRU area {AREA} resize is disabled, cannot increase size from {OLD_SIZE} to {NEW_SIZE}",
1243 "AREA", getFruAreaName(fruAreaToUpdate), "OLD_SIZE",
Marc Olberding25680e32025-10-03 12:38:10 -07001244 static_cast<int>(oldSizePadded), "NEW_SIZE",
1245 static_cast<int>(newSizePadded));
Naresh Solankicf288962025-06-06 15:26:11 +05301246 return false;
1247 }
Marc Olberding25680e32025-10-03 12:38:10 -07001248#endif
1249 // Resize the buffer as per numOfBlocks & pad with zeros
1250 tmpBuffer.resize(newSizePadded * fruBlockSize, 0);
Naresh Solankicf288962025-06-06 15:26:11 +05301251
Naresh Solankicf288962025-06-06 15:26:11 +05301252 // Update the length field
Marc Olberding25680e32025-10-03 12:38:10 -07001253 tmpBuffer[1] = newSizePadded;
1254 updateAreaChecksum(tmpBuffer);
1255
1256 areaData = std::move(tmpBuffer);
Naresh Solankicf288962025-06-06 15:26:11 +05301257
1258 return true;
1259}
1260
1261bool assembleFruData(std::vector<uint8_t>& fruData,
1262 const std::vector<std::vector<uint8_t>>& areasData)
1263{
Marc Olberding25680e32025-10-03 12:38:10 -07001264 for (const auto& area : areasData)
1265 {
1266 if ((area.size() % fruBlockSize) != 0U)
1267 {
1268 lg2::error("unaligned area sent to assembleFruData");
1269 return false;
1270 }
1271 }
1272
Naresh Solankicf288962025-06-06 15:26:11 +05301273 // Clear the existing FRU data
1274 fruData.clear();
1275 fruData.resize(8); // Start with the header size
1276
1277 // Write the header
1278 fruData[0] = fruVersion; // Version
1279 fruData[1] = 0; // Internal area offset
1280 fruData[2] = 0; // Chassis area offset
1281 fruData[3] = 0; // Board area offset
1282 fruData[4] = 0; // Product area offset
1283 fruData[5] = 0; // Multirecord area offset
1284 fruData[6] = 0; // Pad
1285 fruData[7] = 0; // Checksum (to be updated later)
1286
1287 size_t writeOffset = 8; // Start writing after the header
1288
1289 for (fruAreas area = fruAreas::fruAreaInternal;
1290 area <= fruAreas::fruAreaMultirecord; ++area)
1291 {
Marc Olberding25680e32025-10-03 12:38:10 -07001292 const auto& areaBytes = areasData[static_cast<size_t>(area)];
Naresh Solankicf288962025-06-06 15:26:11 +05301293
Marc Olberding25680e32025-10-03 12:38:10 -07001294 if (areaBytes.empty())
Naresh Solankicf288962025-06-06 15:26:11 +05301295 {
1296 lg2::debug("Skipping empty area: {AREA}", "AREA",
1297 getFruAreaName(area));
1298 continue; // Skip areas that are not present
1299 }
1300
1301 // Set the area offset in the header
Marc Olberding25680e32025-10-03 12:38:10 -07001302 fruData[getHeaderAreaFieldOffset(area)] = writeOffset / fruBlockSize;
1303 fruData.append_range(areaBytes);
1304 writeOffset += areaBytes.size();
Naresh Solankicf288962025-06-06 15:26:11 +05301305 }
1306
1307 // Update the header checksum
Marc Olberding25680e32025-10-03 12:38:10 -07001308 if (!updateHeaderChecksum(fruData))
Naresh Solankicf288962025-06-06 15:26:11 +05301309 {
Marc Olberding25680e32025-10-03 12:38:10 -07001310 lg2::error("failed to update header checksum");
Naresh Solankicf288962025-06-06 15:26:11 +05301311 return false;
1312 }
Marc Olberding25680e32025-10-03 12:38:10 -07001313
Naresh Solankicf288962025-06-06 15:26:11 +05301314 return true;
1315}
1316
1317// Create a dummy area in areData variable based on specified fruArea
1318bool createDummyArea(fruAreas fruArea, std::vector<uint8_t>& areaData)
1319{
1320 uint8_t numOfFields = 0;
1321 uint8_t numOfBlocks = 0;
1322 // Clear the areaData vector
1323 areaData.clear();
1324
1325 // Set the version, length, and other fields
Marc Olberding25680e32025-10-03 12:38:10 -07001326 areaData.push_back(fruVersion); // Version 1
1327 areaData.push_back(0); // Length (to be updated later)
Naresh Solankicf288962025-06-06 15:26:11 +05301328
1329 switch (fruArea)
1330 {
1331 case fruAreas::fruAreaChassis:
1332 areaData.push_back(0x00); // Chassis type
1333 numOfFields = chassisFruAreas.size();
1334 break;
1335 case fruAreas::fruAreaBoard:
1336 areaData.push_back(0x00); // Board language code (default)
1337 areaData.insert(areaData.end(),
1338 {0x00, 0x00,
1339 0x00}); // Board manufacturer date (default)
1340 numOfFields = boardFruAreas.size();
1341 break;
1342 case fruAreas::fruAreaProduct:
1343 areaData.push_back(0x00); // Product language code (default)
1344 numOfFields = productFruAreas.size();
1345 break;
1346 default:
1347 lg2::debug("Invalid FRU area to create: {AREA}", "AREA",
1348 static_cast<int>(fruArea));
1349 return false;
1350 }
1351
1352 for (size_t i = 0; i < numOfFields; ++i)
1353 {
1354 areaData.push_back(0xc0); // Empty field type
1355 }
1356
1357 // Add EndOfFields marker
1358 areaData.push_back(0xC1);
1359 numOfBlocks = (areaData.size() + fruBlockSize - 1) /
1360 fruBlockSize; // Calculate number of blocks needed
1361 areaData.resize(numOfBlocks * fruBlockSize, 0); // Fill with zeros
1362 areaData[1] = numOfBlocks; // Update length field
Marc Olberding25680e32025-10-03 12:38:10 -07001363 updateAreaChecksum(areaData);
Naresh Solankicf288962025-06-06 15:26:11 +05301364
1365 return true;
1366}
1367
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301368// Iterate FruArea Names and find start and size of the fru area that contains
1369// the propertyName and the field start location for the property. fruAreaParams
1370// struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
1371// updated/returned if successful.
1372
1373bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
1374 const std::string& propertyName,
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301375 struct FruArea& fruAreaParams)
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301376{
1377 const std::vector<std::string>* fruAreaFieldNames = nullptr;
1378
1379 uint8_t fruAreaOffsetFieldValue = 0;
1380 size_t offset = 0;
1381 std::string areaName = propertyName.substr(0, propertyName.find('_'));
1382 std::string propertyNamePrefix = areaName + "_";
1383 auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
1384 if (it == fruAreaNames.end())
1385 {
1386 std::cerr << "Can't parse area name for property " << propertyName
1387 << " \n";
1388 return false;
1389 }
1390 fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
1391 fruAreaOffsetFieldValue =
1392 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1393 switch (fruAreaToUpdate)
1394 {
1395 case fruAreas::fruAreaChassis:
1396 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1397 fruAreaFieldNames = &chassisFruAreas;
1398 break;
1399 case fruAreas::fruAreaBoard:
1400 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1401 fruAreaFieldNames = &boardFruAreas;
1402 break;
1403 case fruAreas::fruAreaProduct:
1404 // Manufacturer name offset. Skip fixed first 3 product fru bytes
1405 // i.e. version, area length and language code
1406 offset = 3;
1407 fruAreaFieldNames = &productFruAreas;
1408 break;
1409 default:
1410 std::cerr << "Invalid PropertyName " << propertyName << " \n";
1411 return false;
1412 }
1413 if (fruAreaOffsetFieldValue == 0)
1414 {
1415 std::cerr << "FRU Area for " << propertyName << " not present \n";
1416 return false;
1417 }
1418
1419 fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
1420 fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
1421 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301422 size_t fruDataIter = fruAreaParams.start + offset;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +05301423 size_t skipToFRUUpdateField = 0;
1424 ssize_t fieldLength = 0;
1425
1426 bool found = false;
1427 for (const auto& field : *fruAreaFieldNames)
1428 {
1429 skipToFRUUpdateField++;
1430 if (propertyName == propertyNamePrefix + field)
1431 {
1432 found = true;
1433 break;
1434 }
1435 }
1436 if (!found)
1437 {
1438 std::size_t pos = propertyName.find(fruCustomFieldName);
1439 if (pos == std::string::npos)
1440 {
1441 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
1442 << propertyName << "\n";
1443 return false;
1444 }
1445 std::string fieldNumStr =
1446 propertyName.substr(pos + fruCustomFieldName.length());
1447 size_t fieldNum = std::stoi(fieldNumStr);
1448 if (fieldNum == 0)
1449 {
1450 std::cerr << "PropertyName not recognized: " << propertyName
1451 << "\n";
1452 return false;
1453 }
1454 skipToFRUUpdateField += fieldNum;
1455 }
1456
1457 for (size_t i = 1; i < skipToFRUUpdateField; i++)
1458 {
1459 if (fruDataIter < fruData.size())
1460 {
1461 fieldLength = getFieldLength(fruData[fruDataIter]);
1462
1463 if (fieldLength < 0)
1464 {
1465 break;
1466 }
1467 fruDataIter += 1 + fieldLength;
1468 }
1469 }
1470 fruAreaParams.updateFieldLoc = fruDataIter;
1471
1472 return true;
1473}
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301474
1475// Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1476// Return true for success and false for failure.
1477
1478bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1479 const std::string& propertyName,
1480 struct FruArea& fruAreaParams,
1481 std::vector<uint8_t>& restFRUAreaFieldsData)
1482{
1483 size_t fieldLoc = fruAreaParams.updateFieldLoc;
1484 size_t start = fruAreaParams.start;
1485 size_t fruAreaSize = fruAreaParams.size;
1486
1487 // Push post update fru field bytes to a vector
1488 ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1489 if (fieldLength < 0)
1490 {
1491 std::cerr << "Property " << propertyName << " not present \n";
1492 return false;
1493 }
1494
1495 size_t fruDataIter = 0;
1496 fruDataIter = fieldLoc;
1497 fruDataIter += 1 + fieldLength;
1498 size_t restFRUFieldsLoc = fruDataIter;
1499 size_t endOfFieldsLoc = 0;
1500
1501 if (fruDataIter < fruData.size())
1502 {
1503 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1504 {
1505 if (fruDataIter >= (start + fruAreaSize))
1506 {
1507 fruDataIter = start + fruAreaSize;
1508 break;
1509 }
1510 fruDataIter += 1 + fieldLength;
1511 }
1512 endOfFieldsLoc = fruDataIter;
1513 }
1514
1515 std::copy_n(fruData.begin() + restFRUFieldsLoc,
1516 endOfFieldsLoc - restFRUFieldsLoc + 1,
1517 std::back_inserter(restFRUAreaFieldsData));
1518
1519 fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1520 fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1521
1522 return true;
1523}
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301524
1525// Get all device dbus path and match path with product name using
1526// regular expression and find the device index for all devices.
1527
1528std::optional<int> findIndexForFRU(
1529 boost::container::flat_map<
1530 std::pair<size_t, size_t>,
1531 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1532 std::string& productName)
1533{
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301534 int highest = -1;
1535 bool found = false;
1536
Patrick Williamsdf190612023-05-10 07:51:34 -05001537 for (const auto& busIface : dbusInterfaceMap)
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301538 {
1539 std::string path = busIface.second->get_object_path();
1540 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1541 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301542 // Check if the match named has extra information.
1543 found = true;
1544 std::smatch baseMatch;
1545
1546 bool match = std::regex_match(path, baseMatch,
1547 std::regex(productName + "_(\\d+)$"));
1548 if (match)
1549 {
1550 if (baseMatch.size() == 2)
1551 {
1552 std::ssub_match baseSubMatch = baseMatch[1];
1553 std::string base = baseSubMatch.str();
1554
1555 int value = std::stoi(base);
1556 highest = (value > highest) ? value : highest;
1557 }
1558 }
1559 }
1560 } // end searching objects
1561
1562 if (!found)
1563 {
1564 return std::nullopt;
1565 }
1566 return highest;
1567}
Kumar Thangavel9f2162a2022-08-10 18:05:20 +05301568
1569// This function does format fru data as per IPMI format and find the
1570// productName in the formatted fru data, get that productName and return
1571// productName if found or return NULL.
1572
1573std::optional<std::string> getProductName(
1574 std::vector<uint8_t>& device,
1575 boost::container::flat_map<std::string, std::string>& formattedFRU,
1576 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1577{
1578 std::string productName;
1579
1580 resCodes res = formatIPMIFRU(device, formattedFRU);
1581 if (res == resCodes::resErr)
1582 {
1583 std::cerr << "failed to parse FRU for device at bus " << bus
1584 << " address " << address << "\n";
1585 return std::nullopt;
1586 }
1587 if (res == resCodes::resWarn)
1588 {
1589 std::cerr << "Warnings while parsing FRU for device at bus " << bus
1590 << " address " << address << "\n";
1591 }
1592
1593 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1594 // Not found under Board section or an empty string.
1595 if (productNameFind == formattedFRU.end() ||
1596 productNameFind->second.empty())
1597 {
1598 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1599 }
1600 // Found under Product section and not an empty string.
1601 if (productNameFind != formattedFRU.end() &&
1602 !productNameFind->second.empty())
1603 {
1604 productName = productNameFind->second;
1605 std::regex illegalObject("[^A-Za-z0-9_]");
1606 productName = std::regex_replace(productName, illegalObject, "_");
1607 }
1608 else
1609 {
1610 productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1611 unknownBusObjectCount++;
1612 }
1613 return productName;
1614}
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301615
1616bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1617{
1618 try
1619 {
1620 fruData = getFRUInfo(static_cast<uint16_t>(bus),
1621 static_cast<uint8_t>(address));
1622 }
1623 catch (const std::invalid_argument& e)
1624 {
1625 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
1626 return false;
1627 }
1628
1629 return !fruData.empty();
1630}
Naresh Solanki89092a92025-06-02 15:48:04 +05301631
1632bool isFieldEditable(std::string_view fieldName)
1633{
1634 if (fieldName == "PRODUCT_ASSET_TAG")
1635 {
1636 return true; // PRODUCT_ASSET_TAG is always editable.
1637 }
1638
1639 if (!ENABLE_FRU_UPDATE_PROPERTY)
1640 {
1641 return false; // If FRU update is disabled, no fields are editable.
1642 }
1643
1644 // Editable fields
1645 constexpr std::array<std::string_view, 8> editableFields = {
1646 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER", "VERSION",
1647 "SERIAL_NUMBER", "ASSET_TAG", "FRU_VERSION_ID", "INFO_AM"};
1648
1649 // Find position of first underscore
1650 std::size_t pos = fieldName.find('_');
1651 if (pos == std::string_view::npos || pos + 1 >= fieldName.size())
1652 {
1653 return false;
1654 }
1655
1656 // Extract substring after the underscore
1657 std::string_view subField = fieldName.substr(pos + 1);
1658
1659 // Trim trailing digits
1660 while (!subField.empty() && (std::isdigit(subField.back()) != 0))
1661 {
1662 subField.remove_suffix(1);
1663 }
1664
1665 // Match against editable fields
1666 return std::ranges::contains(editableFields, subField);
1667}