blob: 0c5c2fccd99c2ba01f4f511c149ce177a6740c14 [file] [log] [blame]
Patrick Ventureab296412020-12-30 13:39:37 -08001/*
2// Copyright (c) 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
Brad Bishope45d8c72022-05-25 15:12:53 -040016/// \file fru_utils.cpp
Patrick Ventureab296412020-12-30 13:39:37 -080017
Brad Bishope45d8c72022-05-25 15:12:53 -040018#include "fru_utils.hpp"
Patrick Ventureab296412020-12-30 13:39:37 -080019
Alexander Hansenc3db2c32024-08-20 15:01:38 +020020#include <phosphor-logging/lg2.hpp>
21
Patrick Ventureab296412020-12-30 13:39:37 -080022#include <array>
Ed Tanous3013fb42022-07-09 08:27:06 -070023#include <cstddef>
Patrick Ventureab296412020-12-30 13:39:37 -080024#include <cstdint>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053025#include <filesystem>
Hieu Huynh5286afe2022-10-12 11:41:12 +000026#include <iomanip>
Patrick Ventureab296412020-12-30 13:39:37 -080027#include <iostream>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053028#include <numeric>
Patrick Ventureab296412020-12-30 13:39:37 -080029#include <set>
Hieu Huynh5286afe2022-10-12 11:41:12 +000030#include <sstream>
Patrick Ventureab296412020-12-30 13:39:37 -080031#include <string>
32#include <vector>
33
34extern "C"
35{
36// Include for I2C_SMBUS_BLOCK_MAX
37#include <linux/i2c.h>
38}
39
Patrick Ventureab296412020-12-30 13:39:37 -080040constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
41
Delphine CC Chiua3ca14a2024-03-27 17:02:24 +080042std::tm intelEpoch()
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000043{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053044 std::tm val = {};
45 val.tm_year = 1996 - 1900;
Scron-Chang9e5a6752021-03-16 10:51:50 +080046 val.tm_mday = 1;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053047 return val;
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000048}
49
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053050char sixBitToChar(uint8_t val)
Patrick Ventureab296412020-12-30 13:39:37 -080051{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053052 return static_cast<char>((val & 0x3f) + ' ');
53}
54
55char bcdPlusToChar(uint8_t val)
56{
57 val &= 0xf;
58 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
59}
60
61enum FRUDataEncoding
62{
63 binary = 0x0,
64 bcdPlus = 0x1,
65 sixBitASCII = 0x2,
66 languageDependent = 0x3,
67};
68
Hieu Huynh5286afe2022-10-12 11:41:12 +000069enum MultiRecordType : uint8_t
70{
71 powerSupplyInfo = 0x00,
72 dcOutput = 0x01,
73 dcLoad = 0x02,
74 managementAccessRecord = 0x03,
75 baseCompatibilityRecord = 0x04,
76 extendedCompatibilityRecord = 0x05,
77 resvASFSMBusDeviceRecord = 0x06,
78 resvASFLegacyDeviceAlerts = 0x07,
79 resvASFRemoteControl = 0x08,
80 extendedDCOutput = 0x09,
81 extendedDCLoad = 0x0A
82};
83
84enum SubManagementAccessRecord : uint8_t
85{
86 systemManagementURL = 0x01,
87 systemName = 0x02,
88 systemPingAddress = 0x03,
89 componentManagementURL = 0x04,
90 componentName = 0x05,
91 componentPingAddress = 0x06,
92 systemUniqueID = 0x07
93};
94
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053095/* Decode FRU data into a std::string, given an input iterator and end. If the
96 * state returned is fruDataOk, then the resulting string is the decoded FRU
97 * data. The input iterator is advanced past the data consumed.
98 *
99 * On fruDataErr, we have lost synchronisation with the length bytes, so the
100 * iterator is no longer usable.
101 */
Patrick Williamsb7077432024-08-16 15:22:21 -0400102std::pair<DecodeState, std::string> decodeFRUData(
Ed Tanous23e3f452025-04-08 10:37:56 -0700103 std::span<const uint8_t>::const_iterator& iter,
104 std::span<const uint8_t>::const_iterator& end, bool isLangEng)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530105{
106 std::string value;
Ed Tanous3013fb42022-07-09 08:27:06 -0700107 unsigned int i = 0;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530108
109 /* we need at least one byte to decode the type/len header */
110 if (iter == end)
Patrick Ventureab296412020-12-30 13:39:37 -0800111 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530112 std::cerr << "Truncated FRU data\n";
113 return make_pair(DecodeState::err, value);
114 }
115
116 uint8_t c = *(iter++);
117
118 /* 0xc1 is the end marker */
119 if (c == 0xc1)
120 {
121 return make_pair(DecodeState::end, value);
122 }
123
124 /* decode type/len byte */
125 uint8_t type = static_cast<uint8_t>(c >> 6);
126 uint8_t len = static_cast<uint8_t>(c & 0x3f);
127
128 /* we should have at least len bytes of data available overall */
129 if (iter + len > end)
130 {
131 std::cerr << "FRU data field extends past end of FRU area data\n";
132 return make_pair(DecodeState::err, value);
133 }
134
135 switch (type)
136 {
137 case FRUDataEncoding::binary:
Patrick Ventureab296412020-12-30 13:39:37 -0800138 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530139 std::stringstream ss;
140 ss << std::hex << std::setfill('0');
141 for (i = 0; i < len; i++, iter++)
142 {
143 uint8_t val = static_cast<uint8_t>(*iter);
144 ss << std::setw(2) << static_cast<int>(val);
145 }
146 value = ss.str();
147 break;
Patrick Ventureab296412020-12-30 13:39:37 -0800148 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530149 case FRUDataEncoding::languageDependent:
150 /* For language-code dependent encodings, assume 8-bit ASCII */
151 value = std::string(iter, iter + len);
152 iter += len;
153
154 /* English text is encoded in 8-bit ASCII + Latin 1. All other
155 * languages are required to use 2-byte unicode. FruDevice does not
156 * handle unicode.
157 */
158 if (!isLangEng)
159 {
160 std::cerr << "Error: Non english string is not supported \n";
161 return make_pair(DecodeState::err, value);
162 }
163
164 break;
165
166 case FRUDataEncoding::bcdPlus:
167 value = std::string();
168 for (i = 0; i < len; i++, iter++)
169 {
170 uint8_t val = *iter;
171 value.push_back(bcdPlusToChar(val >> 4));
172 value.push_back(bcdPlusToChar(val & 0xf));
173 }
174 break;
175
176 case FRUDataEncoding::sixBitASCII:
177 {
178 unsigned int accum = 0;
179 unsigned int accumBitLen = 0;
180 value = std::string();
181 for (i = 0; i < len; i++, iter++)
182 {
183 accum |= *iter << accumBitLen;
184 accumBitLen += 8;
185 while (accumBitLen >= 6)
186 {
187 value.push_back(sixBitToChar(accum & 0x3f));
188 accum >>= 6;
189 accumBitLen -= 6;
190 }
191 }
192 }
193 break;
Ed Tanousfc171422024-04-04 17:18:16 -0700194
195 default:
196 {
197 return make_pair(DecodeState::err, value);
198 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530199 }
200
201 return make_pair(DecodeState::ok, value);
202}
203
204bool checkLangEng(uint8_t lang)
205{
206 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
207 // but we don't support that.
Ed Tanous3013fb42022-07-09 08:27:06 -0700208 if ((lang != 0U) && lang != 25)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530209 {
210 std::cerr << "Warning: languages other than English is not "
211 "supported\n";
212 // Return language flag as non english
Patrick Ventureab296412020-12-30 13:39:37 -0800213 return false;
214 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800215 return true;
Patrick Ventureab296412020-12-30 13:39:37 -0800216}
217
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000218/* This function verifies for other offsets to check if they are not
219 * falling under other field area
220 *
221 * fruBytes: Start of Fru data
222 * currentArea: Index of current area offset to be compared against all area
223 * offset and it is a multiple of 8 bytes as per specification
224 * len: Length of current area space and it is a multiple of 8 bytes
225 * as per specification
226 */
Ed Tanous23e3f452025-04-08 10:37:56 -0700227bool verifyOffset(std::span<const uint8_t> fruBytes, fruAreas currentArea,
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000228 uint8_t len)
229{
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000230 unsigned int fruBytesSize = fruBytes.size();
231
232 // check if Fru data has at least 8 byte header
233 if (fruBytesSize <= fruBlockSize)
234 {
235 std::cerr << "Error: trying to parse empty FRU\n";
236 return false;
237 }
238
239 // Check range of passed currentArea value
240 if (currentArea > fruAreas::fruAreaMultirecord)
241 {
242 std::cerr << "Error: Fru area is out of range\n";
243 return false;
244 }
245
246 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
247 if (currentAreaIndex > fruBytesSize)
248 {
249 std::cerr << "Error: Fru area index is out of range\n";
250 return false;
251 }
252
253 unsigned int start = fruBytes[currentAreaIndex];
254 unsigned int end = start + len;
255
256 /* Verify each offset within the range of start and end */
257 for (fruAreas area = fruAreas::fruAreaInternal;
258 area <= fruAreas::fruAreaMultirecord; ++area)
259 {
260 // skip the current offset
261 if (area == currentArea)
262 {
263 continue;
264 }
265
266 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
267 if (areaIndex > fruBytesSize)
268 {
269 std::cerr << "Error: Fru area index is out of range\n";
270 return false;
271 }
272
273 unsigned int areaOffset = fruBytes[areaIndex];
274 // if areaOffset is 0 means this area is not available so skip
275 if (areaOffset == 0)
276 {
277 continue;
278 }
279
280 // check for overlapping of current offset with given areaoffset
281 if (areaOffset == start || (areaOffset > start && areaOffset < end))
282 {
283 std::cerr << getFruAreaName(currentArea)
284 << " offset is overlapping with " << getFruAreaName(area)
285 << " offset\n";
286 return false;
287 }
288 }
289 return true;
290}
291
Hieu Huynh5286afe2022-10-12 11:41:12 +0000292static void parseMultirecordUUID(
Ed Tanous23e3f452025-04-08 10:37:56 -0700293 std::span<const uint8_t> device,
Hieu Huynh5286afe2022-10-12 11:41:12 +0000294 boost::container::flat_map<std::string, std::string>& result)
295{
296 constexpr size_t uuidDataLen = 16;
297 constexpr size_t multiRecordHeaderLen = 5;
298 /* UUID record data, plus one to skip past the sub-record type byte */
299 constexpr size_t uuidRecordData = multiRecordHeaderLen + 1;
300 constexpr size_t multiRecordEndOfListMask = 0x80;
301 /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented
302 * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD
303 * 0xEE 0xFF
304 */
305 const std::array<uint8_t, uuidDataLen> uuidCharOrder = {
306 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
Ed Tanous23e3f452025-04-08 10:37:56 -0700307 size_t offset = getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord);
308 if (offset >= device.size())
309 {
310 throw std::runtime_error("Multirecord UUID offset is out of range");
311 }
312 uint32_t areaOffset = device[offset];
Hieu Huynh5286afe2022-10-12 11:41:12 +0000313
314 if (areaOffset == 0)
315 {
316 return;
317 }
318
319 areaOffset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700320 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400321 device.begin() + areaOffset;
Hieu Huynh5286afe2022-10-12 11:41:12 +0000322
323 /* Verify area offset */
324 if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter))
325 {
326 return;
327 }
328 while (areaOffset + uuidRecordData + uuidDataLen <= device.size())
329 {
330 if ((areaOffset < device.size()) &&
331 (device[areaOffset] ==
332 (uint8_t)MultiRecordType::managementAccessRecord))
333 {
334 if ((areaOffset + multiRecordHeaderLen < device.size()) &&
335 (device[areaOffset + multiRecordHeaderLen] ==
336 (uint8_t)SubManagementAccessRecord::systemUniqueID))
337 {
338 /* Layout of UUID:
339 * source: https://www.ietf.org/rfc/rfc4122.txt
340 *
341 * UUID binary format (16 bytes):
342 * 4B-2B-2B-2B-6B (big endian)
343 *
344 * UUID string is 36 length of characters (36 bytes):
345 * 0 9 14 19 24
346 * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
347 * be be be be be
348 * be means it should be converted to big endian.
349 */
350 /* Get UUID bytes to UUID string */
351 std::stringstream tmp;
352 tmp << std::hex << std::setfill('0');
353 for (size_t i = 0; i < uuidDataLen; i++)
354 {
355 tmp << std::setw(2)
356 << static_cast<uint16_t>(
357 device[areaOffset + uuidRecordData +
358 uuidCharOrder[i]]);
359 }
360 std::string uuidStr = tmp.str();
361 result["MULTIRECORD_UUID"] =
362 uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' +
363 uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' +
364 uuidStr.substr(20, 12);
365 break;
366 }
367 }
368 if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0)
369 {
370 break;
371 }
372 areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen;
373 }
374}
375
Ed Tanous5ea38d22025-04-08 09:36:43 -0700376resCodes decodeField(
377 std::span<const uint8_t>::const_iterator& fruBytesIter,
378 std::span<const uint8_t>::const_iterator& fruBytesIterEndArea,
379 const std::vector<std::string>& fruAreaFieldNames, size_t& fieldIndex,
380 DecodeState& state, bool isLangEng, const fruAreas& area,
381 boost::container::flat_map<std::string, std::string>& result)
382{
383 auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
384 state = res.first;
385 std::string value = res.second;
386 std::string name;
387 if (fieldIndex < fruAreaFieldNames.size())
388 {
389 name = std::string(getFruAreaName(area)) + "_" +
390 fruAreaFieldNames.at(fieldIndex);
391 }
392 else
393 {
394 name = std::string(getFruAreaName(area)) + "_" + fruCustomFieldName +
395 std::to_string(fieldIndex - fruAreaFieldNames.size() + 1);
396 }
397
398 if (state == DecodeState::ok)
399 {
400 // Strip non null characters and trailing spaces from the end
401 value.erase(
402 std::find_if(value.rbegin(), value.rend(),
403 [](char ch) { return ((ch != 0) && (ch != ' ')); })
404 .base(),
405 value.end());
406
407 result[name] = std::move(value);
408 ++fieldIndex;
409 }
410 else if (state == DecodeState::err)
411 {
412 std::cerr << "Error while parsing " << name << "\n";
413
414 // Cancel decoding if failed to parse any of mandatory
415 // fields
416 if (fieldIndex < fruAreaFieldNames.size())
417 {
418 std::cerr << "Failed to parse mandatory field \n";
419 return resCodes::resErr;
420 }
421 return resCodes::resWarn;
422 }
423 else
424 {
425 if (fieldIndex < fruAreaFieldNames.size())
426 {
427 std::cerr << "Mandatory fields absent in FRU area "
428 << getFruAreaName(area) << " after " << name << "\n";
429 return resCodes::resWarn;
430 }
431 }
432 return resCodes::resOK;
433}
434
Patrick Williams5a807032025-03-03 11:20:39 -0500435resCodes formatIPMIFRU(
Ed Tanous23e3f452025-04-08 10:37:56 -0700436 std::span<const uint8_t> fruBytes,
Patrick Williams5a807032025-03-03 11:20:39 -0500437 boost::container::flat_map<std::string, std::string>& result)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530438{
439 resCodes ret = resCodes::resOK;
440 if (fruBytes.size() <= fruBlockSize)
441 {
442 std::cerr << "Error: trying to parse empty FRU \n";
443 return resCodes::resErr;
444 }
445 result["Common_Format_Version"] =
446 std::to_string(static_cast<int>(*fruBytes.begin()));
447
Ed Tanous3013fb42022-07-09 08:27:06 -0700448 const std::vector<std::string>* fruAreaFieldNames = nullptr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530449
450 // Don't parse Internal and Multirecord areas
451 for (fruAreas area = fruAreas::fruAreaChassis;
452 area <= fruAreas::fruAreaProduct; ++area)
453 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530454 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
455 if (offset == 0)
456 {
457 continue;
458 }
459 offset *= fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700460 std::span<const uint8_t>::const_iterator fruBytesIter =
Patrick Williamsb7077432024-08-16 15:22:21 -0400461 fruBytes.begin() + offset;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530462 if (fruBytesIter + fruBlockSize >= fruBytes.end())
463 {
464 std::cerr << "Not enough data to parse \n";
465 return resCodes::resErr;
466 }
467 // check for format version 1
468 if (*fruBytesIter != 0x01)
469 {
470 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
471 return resCodes::resErr;
472 }
473 ++fruBytesIter;
474
475 /* Verify other area offset for overlap with current area by passing
476 * length of current area offset pointed by *fruBytesIter
477 */
478 if (!verifyOffset(fruBytes, area, *fruBytesIter))
479 {
480 return resCodes::resErr;
481 }
482
Andrew Jeffery65ed6642021-08-02 22:32:23 +0930483 size_t fruAreaSize = *fruBytesIter * fruBlockSize;
Ed Tanous23e3f452025-04-08 10:37:56 -0700484 std::span<const uint8_t>::const_iterator fruBytesIterEndArea =
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530485 fruBytes.begin() + offset + fruAreaSize - 1;
486 ++fruBytesIter;
487
488 uint8_t fruComputedChecksum =
489 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
490 if (fruComputedChecksum != *fruBytesIterEndArea)
491 {
492 std::stringstream ss;
493 ss << std::hex << std::setfill('0');
494 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
495 ss << "\tComputed checksum: 0x" << std::setw(2)
496 << static_cast<int>(fruComputedChecksum) << "\n";
497 ss << "\tThe read checksum: 0x" << std::setw(2)
498 << static_cast<int>(*fruBytesIterEndArea) << "\n";
499 std::cerr << ss.str();
500 ret = resCodes::resWarn;
501 }
502
503 /* Set default language flag to true as Chassis Fru area are always
504 * encoded in English defined in Section 10 of Fru specification
505 */
506
507 bool isLangEng = true;
508 switch (area)
509 {
510 case fruAreas::fruAreaChassis:
511 {
512 result["CHASSIS_TYPE"] =
513 std::to_string(static_cast<int>(*fruBytesIter));
514 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800515 fruAreaFieldNames = &chassisFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530516 break;
517 }
518 case fruAreas::fruAreaBoard:
519 {
520 uint8_t lang = *fruBytesIter;
521 result["BOARD_LANGUAGE_CODE"] =
522 std::to_string(static_cast<int>(lang));
523 isLangEng = checkLangEng(lang);
524 fruBytesIter += 1;
525
Patrick Williamsb7077432024-08-16 15:22:21 -0400526 unsigned int minutes =
527 *fruBytesIter | *(fruBytesIter + 1) << 8 |
528 *(fruBytesIter + 2) << 16;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530529 std::tm fruTime = intelEpoch();
Willy Tu3f98b5e2023-04-12 08:16:52 -0700530 std::time_t timeValue = timegm(&fruTime);
Ed Tanous3013fb42022-07-09 08:27:06 -0700531 timeValue += static_cast<long>(minutes) * 60;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530532 fruTime = *std::gmtime(&timeValue);
533
534 // Tue Nov 20 23:08:00 2018
Ed Tanous3013fb42022-07-09 08:27:06 -0700535 std::array<char, 32> timeString = {};
536 auto bytes = std::strftime(timeString.data(), timeString.size(),
Yi-Shum536665b2024-05-14 10:08:27 +0800537 "%Y%m%dT%H%M%SZ", &fruTime);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530538 if (bytes == 0)
539 {
540 std::cerr << "invalid time string encountered\n";
541 return resCodes::resErr;
542 }
543
Ed Tanous3013fb42022-07-09 08:27:06 -0700544 result["BOARD_MANUFACTURE_DATE"] =
545 std::string_view(timeString.data(), bytes);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530546 fruBytesIter += 3;
Ed Tanous07d467b2021-02-23 14:48:37 -0800547 fruAreaFieldNames = &boardFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530548 break;
549 }
550 case fruAreas::fruAreaProduct:
551 {
552 uint8_t lang = *fruBytesIter;
553 result["PRODUCT_LANGUAGE_CODE"] =
554 std::to_string(static_cast<int>(lang));
555 isLangEng = checkLangEng(lang);
556 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800557 fruAreaFieldNames = &productFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530558 break;
559 }
560 default:
561 {
562 std::cerr << "Internal error: unexpected FRU area index: "
563 << static_cast<int>(area) << " \n";
564 return resCodes::resErr;
565 }
566 }
567 size_t fieldIndex = 0;
Ed Tanous3013fb42022-07-09 08:27:06 -0700568 DecodeState state = DecodeState::ok;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530569 do
570 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700571 resCodes decodeRet = decodeField(fruBytesIter, fruBytesIterEndArea,
572 *fruAreaFieldNames, fieldIndex,
573 state, isLangEng, area, result);
574 if (decodeRet == resCodes::resErr)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530575 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700576 return resCodes::resErr;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530577 }
Ed Tanous5ea38d22025-04-08 09:36:43 -0700578 if (decodeRet == resCodes::resWarn)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530579 {
Ed Tanous5ea38d22025-04-08 09:36:43 -0700580 ret = decodeRet;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530581 }
582 } while (state == DecodeState::ok);
583 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
584 {
585 uint8_t c = *fruBytesIter;
Ed Tanous3013fb42022-07-09 08:27:06 -0700586 if (c != 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530587 {
588 std::cerr << "Non-zero byte after EndOfFields in FRU area "
589 << getFruAreaName(area) << "\n";
590 ret = resCodes::resWarn;
591 break;
592 }
593 }
594 }
595
Hieu Huynh5286afe2022-10-12 11:41:12 +0000596 /* Parsing the Multirecord UUID */
597 parseMultirecordUUID(fruBytes, result);
598
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530599 return ret;
600}
601
602// Calculate new checksum for fru info area
Ed Tanous23e3f452025-04-08 10:37:56 -0700603uint8_t calculateChecksum(std::span<const uint8_t>::const_iterator iter,
604 std::span<const uint8_t>::const_iterator end)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530605{
606 constexpr int checksumMod = 256;
Andrew Jeffery499e7aa2021-08-02 22:18:22 +0930607 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
608 return (checksumMod - sum) % checksumMod;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530609}
610
Ed Tanous23e3f452025-04-08 10:37:56 -0700611uint8_t calculateChecksum(std::span<const uint8_t> fruAreaData)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530612{
613 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
614}
615
616// Update new fru area length &
617// Update checksum at new checksum location
618// Return the offset of the area checksum byte
Patrick Williamsb7077432024-08-16 15:22:21 -0400619unsigned int updateFRUAreaLenAndChecksum(
620 std::vector<uint8_t>& fruData, size_t fruAreaStart,
621 size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530622{
623 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
624
625 // fill zeros for any remaining unused space
626 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
627 fruData.begin() + fruAreaEndOffset, 0);
628
629 size_t mod = traverseFRUAreaIndex % fruBlockSize;
Ed Tanous3013fb42022-07-09 08:27:06 -0700630 size_t checksumLoc = 0;
631 if (mod == 0U)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530632 {
633 traverseFRUAreaIndex += (fruBlockSize);
634 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
635 }
636 else
637 {
638 traverseFRUAreaIndex += (fruBlockSize - mod);
639 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
640 }
641
Ed Tanous3013fb42022-07-09 08:27:06 -0700642 size_t newFRUAreaLen =
643 (traverseFRUAreaIndex / fruBlockSize) +
644 static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530645 size_t fruAreaLengthLoc = fruAreaStart + 1;
646 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
647
648 // Calculate new checksum
649 std::vector<uint8_t> finalFRUData;
650 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
651 std::back_inserter(finalFRUData));
652
653 fruData[checksumLoc] = calculateChecksum(finalFRUData);
654 return checksumLoc;
655}
656
657ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
658{
659 constexpr uint8_t typeLenMask = 0x3F;
660 constexpr uint8_t endOfFields = 0xC1;
661 if (fruFieldTypeLenValue == endOfFields)
662 {
663 return -1;
664 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800665 return fruFieldTypeLenValue & typeLenMask;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530666}
667
668bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
669{
670 // ipmi spec format version number is currently at 1, verify it
671 if (blockData[0] != fruVersion)
672 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200673 lg2::debug(
674 "FRU spec version {VERSION} not supported. Supported version is {SUPPORTED_VERSION}",
675 "VERSION", lg2::hex, blockData[0], "SUPPORTED_VERSION", lg2::hex,
676 fruVersion);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530677 return false;
678 }
679
680 // verify pad is set to 0
681 if (blockData[6] != 0x0)
682 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200683 lg2::debug("Pad value in header is non zero, value is {VALUE}", "VALUE",
684 lg2::hex, blockData[6]);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530685 return false;
686 }
687
688 // verify offsets are 0, or don't point to another offset
689 std::set<uint8_t> foundOffsets;
690 for (int ii = 1; ii < 6; ii++)
691 {
692 if (blockData[ii] == 0)
693 {
694 continue;
695 }
696 auto inserted = foundOffsets.insert(blockData[ii]);
697 if (!inserted.second)
698 {
699 return false;
700 }
701 }
702
703 // validate checksum
704 size_t sum = 0;
705 for (int jj = 0; jj < 7; jj++)
706 {
707 sum += blockData[jj];
708 }
709 sum = (256 - sum) & 0xFF;
710
711 if (sum != blockData[7])
712 {
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200713 lg2::debug(
714 "Checksum {CHECKSUM} is invalid. calculated checksum is {CALCULATED_CHECKSUM}",
715 "CHECKSUM", lg2::hex, blockData[7], "CALCULATED_CHECKSUM", lg2::hex,
716 sum);
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530717 return false;
718 }
719 return true;
720}
721
Zev Weiss309c0b12022-02-25 01:44:12 +0000722bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
Oskar Senftbd4075f2021-10-05 23:42:43 -0400723 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
Zev Weiss1525e852022-03-22 22:27:43 +0000724 off_t& baseOffset)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400725{
Zev Weiss309c0b12022-02-25 01:44:12 +0000726 if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
Oskar Senftbd4075f2021-10-05 23:42:43 -0400727 {
728 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030729 << baseOffset << "\n";
Oskar Senftbd4075f2021-10-05 23:42:43 -0400730 return false;
731 }
732
733 // check the header checksum
734 if (validateHeader(blockData))
735 {
736 return true;
737 }
738
739 // only continue the search if we just looked at 0x0.
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030740 if (baseOffset != 0)
741 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400742 return false;
743 }
744
745 // now check for special cases where the IPMI data is at an offset
746
747 // check if blockData starts with tyanHeader
748 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
749 if (blockData.size() >= tyanHeader.size() &&
750 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
751 {
752 // look for the FRU header at offset 0x6000
753 baseOffset = 0x6000;
Zev Weiss309c0b12022-02-25 01:44:12 +0000754 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400755 }
756
Alexander Hansenc3db2c32024-08-20 15:01:38 +0200757 lg2::debug("Illegal header {HEADER} base offset {OFFSET}", "HEADER",
758 errorHelp, "OFFSET", baseOffset);
Oskar Senftbd4075f2021-10-05 23:42:43 -0400759
760 return false;
761}
762
Patrick Williams5a807032025-03-03 11:20:39 -0500763std::pair<std::vector<uint8_t>, bool> readFRUContents(
764 FRUReader& reader, const std::string& errorHelp)
Patrick Ventureab296412020-12-30 13:39:37 -0800765{
Ed Tanous3013fb42022-07-09 08:27:06 -0700766 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
Zev Weiss1525e852022-03-22 22:27:43 +0000767 off_t baseOffset = 0x0;
Patrick Ventureab296412020-12-30 13:39:37 -0800768
Zev Weiss309c0b12022-02-25 01:44:12 +0000769 if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030770 {
Marvin Drees2b3ed302023-04-14 16:35:14 +0200771 return {{}, false};
Patrick Ventureab296412020-12-30 13:39:37 -0800772 }
773
774 std::vector<uint8_t> device;
775 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
776
777 bool hasMultiRecords = false;
778 size_t fruLength = fruBlockSize; // At least FRU header is present
Vijay Khemka7792e392021-01-25 13:03:56 -0800779 unsigned int prevOffset = 0;
Patrick Ventureab296412020-12-30 13:39:37 -0800780 for (fruAreas area = fruAreas::fruAreaInternal;
781 area <= fruAreas::fruAreaMultirecord; ++area)
782 {
783 // Offset value can be 255.
784 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
785 if (areaOffset == 0)
786 {
787 continue;
788 }
789
Vijay Khemka7792e392021-01-25 13:03:56 -0800790 /* Check for offset order, as per Section 17 of FRU specification, FRU
791 * information areas are required to be in order in FRU data layout
792 * which means all offset value should be in increasing order or can be
793 * 0 if that area is not present
794 */
795 if (areaOffset <= prevOffset)
796 {
797 std::cerr << "Fru area offsets are not in required order as per "
798 "Section 17 of Fru specification\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200799 return {{}, true};
Vijay Khemka7792e392021-01-25 13:03:56 -0800800 }
801 prevOffset = areaOffset;
802
Patrick Ventureab296412020-12-30 13:39:37 -0800803 // MultiRecords are different. area is not tracking section, it's
804 // walking the common header.
805 if (area == fruAreas::fruAreaMultirecord)
806 {
807 hasMultiRecords = true;
808 break;
809 }
810
811 areaOffset *= fruBlockSize;
812
Zev Weiss309c0b12022-02-25 01:44:12 +0000813 if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800814 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400815 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030816 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200817 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800818 }
819
820 // Ignore data type (blockData is already unsigned).
821 size_t length = blockData[1] * fruBlockSize;
822 areaOffset += length;
823 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
824 }
825
826 if (hasMultiRecords)
827 {
828 // device[area count] is the index to the last area because the 0th
829 // entry is not an offset in the common header.
830 unsigned int areaOffset =
831 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
832 areaOffset *= fruBlockSize;
833
834 // the multi-area record header is 5 bytes long.
835 constexpr size_t multiRecordHeaderSize = 5;
836 constexpr uint8_t multiRecordEndOfListMask = 0x80;
837
838 // Sanity hard-limit to 64KB.
839 while (areaOffset < std::numeric_limits<uint16_t>::max())
840 {
841 // In multi-area, the area offset points to the 0th record, each
842 // record has 3 bytes of the header we care about.
Zev Weiss309c0b12022-02-25 01:44:12 +0000843 if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800844 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400845 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030846 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200847 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800848 }
849
850 // Ok, let's check the record length, which is in bytes (unsigned,
851 // up to 255, so blockData should hold uint8_t not char)
852 size_t recordLength = blockData[2];
853 areaOffset += (recordLength + multiRecordHeaderSize);
854 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
855
856 // If this is the end of the list bail.
Ed Tanous3013fb42022-07-09 08:27:06 -0700857 if ((blockData[1] & multiRecordEndOfListMask) != 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800858 {
859 break;
860 }
861 }
862 }
863
864 // You already copied these first 8 bytes (the ipmi fru header size)
865 fruLength -= std::min(fruBlockSize, fruLength);
866
867 int readOffset = fruBlockSize;
868
869 while (fruLength > 0)
870 {
871 size_t requestLength =
872 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
873
Zev Weiss309c0b12022-02-25 01:44:12 +0000874 if (reader.read(baseOffset + readOffset, requestLength,
875 blockData.data()) < 0)
Patrick Ventureab296412020-12-30 13:39:37 -0800876 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400877 std::cerr << "failed to read " << errorHelp << " base offset "
Andrew Jefferyf8ae2ba2022-03-25 15:13:55 +1030878 << baseOffset << "\n";
Marvin Drees2b3ed302023-04-14 16:35:14 +0200879 return {{}, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800880 }
881
882 device.insert(device.end(), blockData.begin(),
883 blockData.begin() + requestLength);
884
885 readOffset += requestLength;
886 fruLength -= std::min(requestLength, fruLength);
887 }
888
Marvin Drees2b3ed302023-04-14 16:35:14 +0200889 return {device, true};
Patrick Ventureab296412020-12-30 13:39:37 -0800890}
891
892unsigned int getHeaderAreaFieldOffset(fruAreas area)
893{
894 return static_cast<unsigned int>(area) + 1;
895}
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530896
krishnar4213ee212022-11-11 15:39:30 +0530897std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
Kumar Thangavel7135f3d2022-02-04 12:14:24 +0530898{
899 auto deviceMap = busMap.find(bus);
900 if (deviceMap == busMap.end())
901 {
902 throw std::invalid_argument("Invalid Bus.");
903 }
904 auto device = deviceMap->second->find(address);
905 if (device == deviceMap->second->end())
906 {
907 throw std::invalid_argument("Invalid Address.");
908 }
909 std::vector<uint8_t>& ret = device->second;
910
911 return ret;
912}
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +0530913
914// Iterate FruArea Names and find start and size of the fru area that contains
915// the propertyName and the field start location for the property. fruAreaParams
916// struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
917// updated/returned if successful.
918
919bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
920 const std::string& propertyName,
Kumar Thangavel51b557b2022-09-13 13:40:47 +0530921 struct FruArea& fruAreaParams)
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +0530922{
923 const std::vector<std::string>* fruAreaFieldNames = nullptr;
924
925 uint8_t fruAreaOffsetFieldValue = 0;
926 size_t offset = 0;
927 std::string areaName = propertyName.substr(0, propertyName.find('_'));
928 std::string propertyNamePrefix = areaName + "_";
929 auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
930 if (it == fruAreaNames.end())
931 {
932 std::cerr << "Can't parse area name for property " << propertyName
933 << " \n";
934 return false;
935 }
936 fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
937 fruAreaOffsetFieldValue =
938 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
939 switch (fruAreaToUpdate)
940 {
941 case fruAreas::fruAreaChassis:
942 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
943 fruAreaFieldNames = &chassisFruAreas;
944 break;
945 case fruAreas::fruAreaBoard:
946 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
947 fruAreaFieldNames = &boardFruAreas;
948 break;
949 case fruAreas::fruAreaProduct:
950 // Manufacturer name offset. Skip fixed first 3 product fru bytes
951 // i.e. version, area length and language code
952 offset = 3;
953 fruAreaFieldNames = &productFruAreas;
954 break;
955 default:
956 std::cerr << "Invalid PropertyName " << propertyName << " \n";
957 return false;
958 }
959 if (fruAreaOffsetFieldValue == 0)
960 {
961 std::cerr << "FRU Area for " << propertyName << " not present \n";
962 return false;
963 }
964
965 fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
966 fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
967 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
Kumar Thangavel51b557b2022-09-13 13:40:47 +0530968 size_t fruDataIter = fruAreaParams.start + offset;
Kumar Thangavelbdfc5ec2022-08-29 22:23:00 +0530969 size_t skipToFRUUpdateField = 0;
970 ssize_t fieldLength = 0;
971
972 bool found = false;
973 for (const auto& field : *fruAreaFieldNames)
974 {
975 skipToFRUUpdateField++;
976 if (propertyName == propertyNamePrefix + field)
977 {
978 found = true;
979 break;
980 }
981 }
982 if (!found)
983 {
984 std::size_t pos = propertyName.find(fruCustomFieldName);
985 if (pos == std::string::npos)
986 {
987 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
988 << propertyName << "\n";
989 return false;
990 }
991 std::string fieldNumStr =
992 propertyName.substr(pos + fruCustomFieldName.length());
993 size_t fieldNum = std::stoi(fieldNumStr);
994 if (fieldNum == 0)
995 {
996 std::cerr << "PropertyName not recognized: " << propertyName
997 << "\n";
998 return false;
999 }
1000 skipToFRUUpdateField += fieldNum;
1001 }
1002
1003 for (size_t i = 1; i < skipToFRUUpdateField; i++)
1004 {
1005 if (fruDataIter < fruData.size())
1006 {
1007 fieldLength = getFieldLength(fruData[fruDataIter]);
1008
1009 if (fieldLength < 0)
1010 {
1011 break;
1012 }
1013 fruDataIter += 1 + fieldLength;
1014 }
1015 }
1016 fruAreaParams.updateFieldLoc = fruDataIter;
1017
1018 return true;
1019}
Kumar Thangavel51b557b2022-09-13 13:40:47 +05301020
1021// Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1022// Return true for success and false for failure.
1023
1024bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1025 const std::string& propertyName,
1026 struct FruArea& fruAreaParams,
1027 std::vector<uint8_t>& restFRUAreaFieldsData)
1028{
1029 size_t fieldLoc = fruAreaParams.updateFieldLoc;
1030 size_t start = fruAreaParams.start;
1031 size_t fruAreaSize = fruAreaParams.size;
1032
1033 // Push post update fru field bytes to a vector
1034 ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1035 if (fieldLength < 0)
1036 {
1037 std::cerr << "Property " << propertyName << " not present \n";
1038 return false;
1039 }
1040
1041 size_t fruDataIter = 0;
1042 fruDataIter = fieldLoc;
1043 fruDataIter += 1 + fieldLength;
1044 size_t restFRUFieldsLoc = fruDataIter;
1045 size_t endOfFieldsLoc = 0;
1046
1047 if (fruDataIter < fruData.size())
1048 {
1049 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1050 {
1051 if (fruDataIter >= (start + fruAreaSize))
1052 {
1053 fruDataIter = start + fruAreaSize;
1054 break;
1055 }
1056 fruDataIter += 1 + fieldLength;
1057 }
1058 endOfFieldsLoc = fruDataIter;
1059 }
1060
1061 std::copy_n(fruData.begin() + restFRUFieldsLoc,
1062 endOfFieldsLoc - restFRUFieldsLoc + 1,
1063 std::back_inserter(restFRUAreaFieldsData));
1064
1065 fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1066 fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1067
1068 return true;
1069}
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301070
1071// Get all device dbus path and match path with product name using
1072// regular expression and find the device index for all devices.
1073
1074std::optional<int> findIndexForFRU(
1075 boost::container::flat_map<
1076 std::pair<size_t, size_t>,
1077 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1078 std::string& productName)
1079{
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301080 int highest = -1;
1081 bool found = false;
1082
Patrick Williamsdf190612023-05-10 07:51:34 -05001083 for (const auto& busIface : dbusInterfaceMap)
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301084 {
1085 std::string path = busIface.second->get_object_path();
1086 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1087 {
Kumar Thangaveld79d0252022-08-24 14:26:01 +05301088 // Check if the match named has extra information.
1089 found = true;
1090 std::smatch baseMatch;
1091
1092 bool match = std::regex_match(path, baseMatch,
1093 std::regex(productName + "_(\\d+)$"));
1094 if (match)
1095 {
1096 if (baseMatch.size() == 2)
1097 {
1098 std::ssub_match baseSubMatch = baseMatch[1];
1099 std::string base = baseSubMatch.str();
1100
1101 int value = std::stoi(base);
1102 highest = (value > highest) ? value : highest;
1103 }
1104 }
1105 }
1106 } // end searching objects
1107
1108 if (!found)
1109 {
1110 return std::nullopt;
1111 }
1112 return highest;
1113}
Kumar Thangavel9f2162a2022-08-10 18:05:20 +05301114
1115// This function does format fru data as per IPMI format and find the
1116// productName in the formatted fru data, get that productName and return
1117// productName if found or return NULL.
1118
1119std::optional<std::string> getProductName(
1120 std::vector<uint8_t>& device,
1121 boost::container::flat_map<std::string, std::string>& formattedFRU,
1122 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1123{
1124 std::string productName;
1125
1126 resCodes res = formatIPMIFRU(device, formattedFRU);
1127 if (res == resCodes::resErr)
1128 {
1129 std::cerr << "failed to parse FRU for device at bus " << bus
1130 << " address " << address << "\n";
1131 return std::nullopt;
1132 }
1133 if (res == resCodes::resWarn)
1134 {
1135 std::cerr << "Warnings while parsing FRU for device at bus " << bus
1136 << " address " << address << "\n";
1137 }
1138
1139 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1140 // Not found under Board section or an empty string.
1141 if (productNameFind == formattedFRU.end() ||
1142 productNameFind->second.empty())
1143 {
1144 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1145 }
1146 // Found under Product section and not an empty string.
1147 if (productNameFind != formattedFRU.end() &&
1148 !productNameFind->second.empty())
1149 {
1150 productName = productNameFind->second;
1151 std::regex illegalObject("[^A-Za-z0-9_]");
1152 productName = std::regex_replace(productName, illegalObject, "_");
1153 }
1154 else
1155 {
1156 productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1157 unknownBusObjectCount++;
1158 }
1159 return productName;
1160}
Kumar Thangavel9d6f5902022-08-26 16:52:14 +05301161
1162bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1163{
1164 try
1165 {
1166 fruData = getFRUInfo(static_cast<uint16_t>(bus),
1167 static_cast<uint8_t>(address));
1168 }
1169 catch (const std::invalid_argument& e)
1170 {
1171 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
1172 return false;
1173 }
1174
1175 return !fruData.empty();
1176}