1 /*
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 */
16 /// \file fru_utils.cpp
17
18 #include "fru_utils.hpp"
19
20 #include <phosphor-logging/lg2.hpp>
21
22 #include <array>
23 #include <cstddef>
24 #include <cstdint>
25 #include <filesystem>
26 #include <iomanip>
27 #include <iostream>
28 #include <numeric>
29 #include <set>
30 #include <sstream>
31 #include <string>
32 #include <vector>
33
34 extern "C"
35 {
36 // Include for I2C_SMBUS_BLOCK_MAX
37 #include <linux/i2c.h>
38 }
39
40 constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
41
intelEpoch()42 std::tm intelEpoch()
43 {
44 std::tm val = {};
45 val.tm_year = 1996 - 1900;
46 val.tm_mday = 1;
47 return val;
48 }
49
sixBitToChar(uint8_t val)50 char sixBitToChar(uint8_t val)
51 {
52 return static_cast<char>((val & 0x3f) + ' ');
53 }
54
bcdPlusToChar(uint8_t val)55 char bcdPlusToChar(uint8_t val)
56 {
57 val &= 0xf;
58 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
59 }
60
61 enum FRUDataEncoding
62 {
63 binary = 0x0,
64 bcdPlus = 0x1,
65 sixBitASCII = 0x2,
66 languageDependent = 0x3,
67 };
68
69 enum 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
84 enum 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
95 /* 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 */
decodeFRUData(std::span<const uint8_t>::const_iterator & iter,std::span<const uint8_t>::const_iterator & end,bool isLangEng)102 std::pair<DecodeState, std::string> decodeFRUData(
103 std::span<const uint8_t>::const_iterator& iter,
104 std::span<const uint8_t>::const_iterator& end, bool isLangEng)
105 {
106 std::string value;
107 unsigned int i = 0;
108
109 /* we need at least one byte to decode the type/len header */
110 if (iter == end)
111 {
112 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:
138 {
139 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;
148 }
149 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;
194
195 default:
196 {
197 return make_pair(DecodeState::err, value);
198 }
199 }
200
201 return make_pair(DecodeState::ok, value);
202 }
203
checkLangEng(uint8_t lang)204 bool 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.
208 if ((lang != 0U) && lang != 25)
209 {
210 std::cerr << "Warning: languages other than English is not "
211 "supported\n";
212 // Return language flag as non english
213 return false;
214 }
215 return true;
216 }
217
218 /* 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 */
verifyOffset(std::span<const uint8_t> fruBytes,fruAreas currentArea,uint8_t len)227 bool verifyOffset(std::span<const uint8_t> fruBytes, fruAreas currentArea,
228 uint8_t len)
229 {
230 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
parseMultirecordUUID(std::span<const uint8_t> device,boost::container::flat_map<std::string,std::string> & result)292 static void parseMultirecordUUID(
293 std::span<const uint8_t> device,
294 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};
307 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];
313
314 if (areaOffset == 0)
315 {
316 return;
317 }
318
319 areaOffset *= fruBlockSize;
320 std::span<const uint8_t>::const_iterator fruBytesIter =
321 device.begin() + areaOffset;
322
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
decodeField(std::span<const uint8_t>::const_iterator & fruBytesIter,std::span<const uint8_t>::const_iterator & fruBytesIterEndArea,const std::vector<std::string> & fruAreaFieldNames,size_t & fieldIndex,DecodeState & state,bool isLangEng,const fruAreas & area,boost::container::flat_map<std::string,std::string> & result)376 resCodes 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 bool isCustomField = false;
388 if (fieldIndex < fruAreaFieldNames.size())
389 {
390 name = std::string(getFruAreaName(area)) + "_" +
391 fruAreaFieldNames.at(fieldIndex);
392 }
393 else
394 {
395 isCustomField = true;
396 name = std::string(getFruAreaName(area)) + "_" + fruCustomFieldName +
397 std::to_string(fieldIndex - fruAreaFieldNames.size() + 1);
398 }
399
400 if (state == DecodeState::ok)
401 {
402 // Strip non null characters and trailing spaces from the end
403 value.erase(
404 std::find_if(value.rbegin(), value.rend(),
405 [](char ch) { return ((ch != 0) && (ch != ' ')); })
406 .base(),
407 value.end());
408 if (isCustomField)
409 {
410 // Some MAC addresses are stored in a custom field, with
411 // "MAC:" prefixed on the value. If we see that, create a
412 // new field with the decoded data
413 if (value.starts_with("MAC: "))
414 {
415 result["MAC_" + name] = value.substr(5);
416 }
417 }
418 result[name] = std::move(value);
419 ++fieldIndex;
420 }
421 else if (state == DecodeState::err)
422 {
423 std::cerr << "Error while parsing " << name << "\n";
424
425 // Cancel decoding if failed to parse any of mandatory
426 // fields
427 if (fieldIndex < fruAreaFieldNames.size())
428 {
429 std::cerr << "Failed to parse mandatory field \n";
430 return resCodes::resErr;
431 }
432 return resCodes::resWarn;
433 }
434 else
435 {
436 if (fieldIndex < fruAreaFieldNames.size())
437 {
438 std::cerr << "Mandatory fields absent in FRU area "
439 << getFruAreaName(area) << " after " << name << "\n";
440 return resCodes::resWarn;
441 }
442 }
443 return resCodes::resOK;
444 }
445
formatIPMIFRU(std::span<const uint8_t> fruBytes,boost::container::flat_map<std::string,std::string> & result)446 resCodes formatIPMIFRU(
447 std::span<const uint8_t> fruBytes,
448 boost::container::flat_map<std::string, std::string>& result)
449 {
450 resCodes ret = resCodes::resOK;
451 if (fruBytes.size() <= fruBlockSize)
452 {
453 std::cerr << "Error: trying to parse empty FRU \n";
454 return resCodes::resErr;
455 }
456 result["Common_Format_Version"] =
457 std::to_string(static_cast<int>(*fruBytes.begin()));
458
459 const std::vector<std::string>* fruAreaFieldNames = nullptr;
460
461 // Don't parse Internal and Multirecord areas
462 for (fruAreas area = fruAreas::fruAreaChassis;
463 area <= fruAreas::fruAreaProduct; ++area)
464 {
465 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
466 if (offset == 0)
467 {
468 continue;
469 }
470 offset *= fruBlockSize;
471 std::span<const uint8_t>::const_iterator fruBytesIter =
472 fruBytes.begin() + offset;
473 if (fruBytesIter + fruBlockSize >= fruBytes.end())
474 {
475 std::cerr << "Not enough data to parse \n";
476 return resCodes::resErr;
477 }
478 // check for format version 1
479 if (*fruBytesIter != 0x01)
480 {
481 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
482 return resCodes::resErr;
483 }
484 ++fruBytesIter;
485
486 /* Verify other area offset for overlap with current area by passing
487 * length of current area offset pointed by *fruBytesIter
488 */
489 if (!verifyOffset(fruBytes, area, *fruBytesIter))
490 {
491 return resCodes::resErr;
492 }
493
494 size_t fruAreaSize = *fruBytesIter * fruBlockSize;
495 std::span<const uint8_t>::const_iterator fruBytesIterEndArea =
496 fruBytes.begin() + offset + fruAreaSize - 1;
497 ++fruBytesIter;
498
499 uint8_t fruComputedChecksum =
500 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
501 if (fruComputedChecksum != *fruBytesIterEndArea)
502 {
503 std::stringstream ss;
504 ss << std::hex << std::setfill('0');
505 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
506 ss << "\tComputed checksum: 0x" << std::setw(2)
507 << static_cast<int>(fruComputedChecksum) << "\n";
508 ss << "\tThe read checksum: 0x" << std::setw(2)
509 << static_cast<int>(*fruBytesIterEndArea) << "\n";
510 std::cerr << ss.str();
511 ret = resCodes::resWarn;
512 }
513
514 /* Set default language flag to true as Chassis Fru area are always
515 * encoded in English defined in Section 10 of Fru specification
516 */
517
518 bool isLangEng = true;
519 switch (area)
520 {
521 case fruAreas::fruAreaChassis:
522 {
523 result["CHASSIS_TYPE"] =
524 std::to_string(static_cast<int>(*fruBytesIter));
525 fruBytesIter += 1;
526 fruAreaFieldNames = &chassisFruAreas;
527 break;
528 }
529 case fruAreas::fruAreaBoard:
530 {
531 uint8_t lang = *fruBytesIter;
532 result["BOARD_LANGUAGE_CODE"] =
533 std::to_string(static_cast<int>(lang));
534 isLangEng = checkLangEng(lang);
535 fruBytesIter += 1;
536
537 unsigned int minutes =
538 *fruBytesIter | *(fruBytesIter + 1) << 8 |
539 *(fruBytesIter + 2) << 16;
540 std::tm fruTime = intelEpoch();
541 std::time_t timeValue = timegm(&fruTime);
542 timeValue += static_cast<long>(minutes) * 60;
543 fruTime = *std::gmtime(&timeValue);
544
545 // Tue Nov 20 23:08:00 2018
546 std::array<char, 32> timeString = {};
547 auto bytes = std::strftime(timeString.data(), timeString.size(),
548 "%Y%m%dT%H%M%SZ", &fruTime);
549 if (bytes == 0)
550 {
551 std::cerr << "invalid time string encountered\n";
552 return resCodes::resErr;
553 }
554
555 result["BOARD_MANUFACTURE_DATE"] =
556 std::string_view(timeString.data(), bytes);
557 fruBytesIter += 3;
558 fruAreaFieldNames = &boardFruAreas;
559 break;
560 }
561 case fruAreas::fruAreaProduct:
562 {
563 uint8_t lang = *fruBytesIter;
564 result["PRODUCT_LANGUAGE_CODE"] =
565 std::to_string(static_cast<int>(lang));
566 isLangEng = checkLangEng(lang);
567 fruBytesIter += 1;
568 fruAreaFieldNames = &productFruAreas;
569 break;
570 }
571 default:
572 {
573 std::cerr << "Internal error: unexpected FRU area index: "
574 << static_cast<int>(area) << " \n";
575 return resCodes::resErr;
576 }
577 }
578 size_t fieldIndex = 0;
579 DecodeState state = DecodeState::ok;
580 do
581 {
582 resCodes decodeRet = decodeField(fruBytesIter, fruBytesIterEndArea,
583 *fruAreaFieldNames, fieldIndex,
584 state, isLangEng, area, result);
585 if (decodeRet == resCodes::resErr)
586 {
587 return resCodes::resErr;
588 }
589 if (decodeRet == resCodes::resWarn)
590 {
591 ret = decodeRet;
592 }
593 } while (state == DecodeState::ok);
594 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
595 {
596 uint8_t c = *fruBytesIter;
597 if (c != 0U)
598 {
599 std::cerr << "Non-zero byte after EndOfFields in FRU area "
600 << getFruAreaName(area) << "\n";
601 ret = resCodes::resWarn;
602 break;
603 }
604 }
605 }
606
607 /* Parsing the Multirecord UUID */
608 parseMultirecordUUID(fruBytes, result);
609
610 return ret;
611 }
612
613 // Calculate new checksum for fru info area
calculateChecksum(std::span<const uint8_t>::const_iterator iter,std::span<const uint8_t>::const_iterator end)614 uint8_t calculateChecksum(std::span<const uint8_t>::const_iterator iter,
615 std::span<const uint8_t>::const_iterator end)
616 {
617 constexpr int checksumMod = 256;
618 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
619 return (checksumMod - sum) % checksumMod;
620 }
621
calculateChecksum(std::span<const uint8_t> fruAreaData)622 uint8_t calculateChecksum(std::span<const uint8_t> fruAreaData)
623 {
624 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
625 }
626
627 // Update new fru area length &
628 // Update checksum at new checksum location
629 // Return the offset of the area checksum byte
updateFRUAreaLenAndChecksum(std::vector<uint8_t> & fruData,size_t fruAreaStart,size_t fruAreaEndOfFieldsOffset,size_t fruAreaEndOffset)630 unsigned int updateFRUAreaLenAndChecksum(
631 std::vector<uint8_t>& fruData, size_t fruAreaStart,
632 size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset)
633 {
634 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
635
636 // fill zeros for any remaining unused space
637 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
638 fruData.begin() + fruAreaEndOffset, 0);
639
640 size_t mod = traverseFRUAreaIndex % fruBlockSize;
641 size_t checksumLoc = 0;
642 if (mod == 0U)
643 {
644 traverseFRUAreaIndex += (fruBlockSize);
645 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
646 }
647 else
648 {
649 traverseFRUAreaIndex += (fruBlockSize - mod);
650 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
651 }
652
653 size_t newFRUAreaLen =
654 (traverseFRUAreaIndex / fruBlockSize) +
655 static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
656 size_t fruAreaLengthLoc = fruAreaStart + 1;
657 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
658
659 // Calculate new checksum
660 std::vector<uint8_t> finalFRUData;
661 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
662 std::back_inserter(finalFRUData));
663
664 fruData[checksumLoc] = calculateChecksum(finalFRUData);
665 return checksumLoc;
666 }
667
getFieldLength(uint8_t fruFieldTypeLenValue)668 ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
669 {
670 constexpr uint8_t typeLenMask = 0x3F;
671 constexpr uint8_t endOfFields = 0xC1;
672 if (fruFieldTypeLenValue == endOfFields)
673 {
674 return -1;
675 }
676 return fruFieldTypeLenValue & typeLenMask;
677 }
678
validateHeader(const std::array<uint8_t,I2C_SMBUS_BLOCK_MAX> & blockData)679 bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
680 {
681 // ipmi spec format version number is currently at 1, verify it
682 if (blockData[0] != fruVersion)
683 {
684 lg2::debug(
685 "FRU spec version {VERSION} not supported. Supported version is {SUPPORTED_VERSION}",
686 "VERSION", lg2::hex, blockData[0], "SUPPORTED_VERSION", lg2::hex,
687 fruVersion);
688 return false;
689 }
690
691 // verify pad is set to 0
692 if (blockData[6] != 0x0)
693 {
694 lg2::debug("Pad value in header is non zero, value is {VALUE}", "VALUE",
695 lg2::hex, blockData[6]);
696 return false;
697 }
698
699 // verify offsets are 0, or don't point to another offset
700 std::set<uint8_t> foundOffsets;
701 for (int ii = 1; ii < 6; ii++)
702 {
703 if (blockData[ii] == 0)
704 {
705 continue;
706 }
707 auto inserted = foundOffsets.insert(blockData[ii]);
708 if (!inserted.second)
709 {
710 return false;
711 }
712 }
713
714 // validate checksum
715 size_t sum = 0;
716 for (int jj = 0; jj < 7; jj++)
717 {
718 sum += blockData[jj];
719 }
720 sum = (256 - sum) & 0xFF;
721
722 if (sum != blockData[7])
723 {
724 lg2::debug(
725 "Checksum {CHECKSUM} is invalid. calculated checksum is {CALCULATED_CHECKSUM}",
726 "CHECKSUM", lg2::hex, blockData[7], "CALCULATED_CHECKSUM", lg2::hex,
727 sum);
728 return false;
729 }
730 return true;
731 }
732
findFRUHeader(FRUReader & reader,const std::string & errorHelp,std::array<uint8_t,I2C_SMBUS_BLOCK_MAX> & blockData,off_t & baseOffset)733 bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
734 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
735 off_t& baseOffset)
736 {
737 if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
738 {
739 std::cerr << "failed to read " << errorHelp << " base offset "
740 << baseOffset << "\n";
741 return false;
742 }
743
744 // check the header checksum
745 if (validateHeader(blockData))
746 {
747 return true;
748 }
749
750 // only continue the search if we just looked at 0x0.
751 if (baseOffset != 0)
752 {
753 return false;
754 }
755
756 // now check for special cases where the IPMI data is at an offset
757
758 // check if blockData starts with tyanHeader
759 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
760 if (blockData.size() >= tyanHeader.size() &&
761 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
762 {
763 // look for the FRU header at offset 0x6000
764 baseOffset = 0x6000;
765 return findFRUHeader(reader, errorHelp, blockData, baseOffset);
766 }
767
768 lg2::debug("Illegal header {HEADER} base offset {OFFSET}", "HEADER",
769 errorHelp, "OFFSET", baseOffset);
770
771 return false;
772 }
773
readFRUContents(FRUReader & reader,const std::string & errorHelp)774 std::pair<std::vector<uint8_t>, bool> readFRUContents(
775 FRUReader& reader, const std::string& errorHelp)
776 {
777 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
778 off_t baseOffset = 0x0;
779
780 if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
781 {
782 return {{}, false};
783 }
784
785 std::vector<uint8_t> device;
786 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
787
788 bool hasMultiRecords = false;
789 size_t fruLength = fruBlockSize; // At least FRU header is present
790 unsigned int prevOffset = 0;
791 for (fruAreas area = fruAreas::fruAreaInternal;
792 area <= fruAreas::fruAreaMultirecord; ++area)
793 {
794 // Offset value can be 255.
795 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
796 if (areaOffset == 0)
797 {
798 continue;
799 }
800
801 /* Check for offset order, as per Section 17 of FRU specification, FRU
802 * information areas are required to be in order in FRU data layout
803 * which means all offset value should be in increasing order or can be
804 * 0 if that area is not present
805 */
806 if (areaOffset <= prevOffset)
807 {
808 std::cerr << "Fru area offsets are not in required order as per "
809 "Section 17 of Fru specification\n";
810 return {{}, true};
811 }
812 prevOffset = areaOffset;
813
814 // MultiRecords are different. area is not tracking section, it's
815 // walking the common header.
816 if (area == fruAreas::fruAreaMultirecord)
817 {
818 hasMultiRecords = true;
819 break;
820 }
821
822 areaOffset *= fruBlockSize;
823
824 if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
825 {
826 std::cerr << "failed to read " << errorHelp << " base offset "
827 << baseOffset << "\n";
828 return {{}, true};
829 }
830
831 // Ignore data type (blockData is already unsigned).
832 size_t length = blockData[1] * fruBlockSize;
833 areaOffset += length;
834 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
835 }
836
837 if (hasMultiRecords)
838 {
839 // device[area count] is the index to the last area because the 0th
840 // entry is not an offset in the common header.
841 unsigned int areaOffset =
842 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
843 areaOffset *= fruBlockSize;
844
845 // the multi-area record header is 5 bytes long.
846 constexpr size_t multiRecordHeaderSize = 5;
847 constexpr uint8_t multiRecordEndOfListMask = 0x80;
848
849 // Sanity hard-limit to 64KB.
850 while (areaOffset < std::numeric_limits<uint16_t>::max())
851 {
852 // In multi-area, the area offset points to the 0th record, each
853 // record has 3 bytes of the header we care about.
854 if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
855 {
856 std::cerr << "failed to read " << errorHelp << " base offset "
857 << baseOffset << "\n";
858 return {{}, true};
859 }
860
861 // Ok, let's check the record length, which is in bytes (unsigned,
862 // up to 255, so blockData should hold uint8_t not char)
863 size_t recordLength = blockData[2];
864 areaOffset += (recordLength + multiRecordHeaderSize);
865 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
866
867 // If this is the end of the list bail.
868 if ((blockData[1] & multiRecordEndOfListMask) != 0)
869 {
870 break;
871 }
872 }
873 }
874
875 // You already copied these first 8 bytes (the ipmi fru header size)
876 fruLength -= std::min(fruBlockSize, fruLength);
877
878 int readOffset = fruBlockSize;
879
880 while (fruLength > 0)
881 {
882 size_t requestLength =
883 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
884
885 if (reader.read(baseOffset + readOffset, requestLength,
886 blockData.data()) < 0)
887 {
888 std::cerr << "failed to read " << errorHelp << " base offset "
889 << baseOffset << "\n";
890 return {{}, true};
891 }
892
893 device.insert(device.end(), blockData.begin(),
894 blockData.begin() + requestLength);
895
896 readOffset += requestLength;
897 fruLength -= std::min(requestLength, fruLength);
898 }
899
900 return {device, true};
901 }
902
getHeaderAreaFieldOffset(fruAreas area)903 unsigned int getHeaderAreaFieldOffset(fruAreas area)
904 {
905 return static_cast<unsigned int>(area) + 1;
906 }
907
getFRUInfo(const uint16_t & bus,const uint8_t & address)908 std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
909 {
910 auto deviceMap = busMap.find(bus);
911 if (deviceMap == busMap.end())
912 {
913 throw std::invalid_argument("Invalid Bus.");
914 }
915 auto device = deviceMap->second->find(address);
916 if (device == deviceMap->second->end())
917 {
918 throw std::invalid_argument("Invalid Address.");
919 }
920 std::vector<uint8_t>& ret = device->second;
921
922 return ret;
923 }
924
925 // Iterate FruArea Names and find start and size of the fru area that contains
926 // the propertyName and the field start location for the property. fruAreaParams
927 // struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
928 // updated/returned if successful.
929
findFruAreaLocationAndField(std::vector<uint8_t> & fruData,const std::string & propertyName,struct FruArea & fruAreaParams)930 bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
931 const std::string& propertyName,
932 struct FruArea& fruAreaParams)
933 {
934 const std::vector<std::string>* fruAreaFieldNames = nullptr;
935
936 uint8_t fruAreaOffsetFieldValue = 0;
937 size_t offset = 0;
938 std::string areaName = propertyName.substr(0, propertyName.find('_'));
939 std::string propertyNamePrefix = areaName + "_";
940 auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
941 if (it == fruAreaNames.end())
942 {
943 std::cerr << "Can't parse area name for property " << propertyName
944 << " \n";
945 return false;
946 }
947 fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
948 fruAreaOffsetFieldValue =
949 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
950 switch (fruAreaToUpdate)
951 {
952 case fruAreas::fruAreaChassis:
953 offset = 3; // chassis part number offset. Skip fixed first 3 bytes
954 fruAreaFieldNames = &chassisFruAreas;
955 break;
956 case fruAreas::fruAreaBoard:
957 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
958 fruAreaFieldNames = &boardFruAreas;
959 break;
960 case fruAreas::fruAreaProduct:
961 // Manufacturer name offset. Skip fixed first 3 product fru bytes
962 // i.e. version, area length and language code
963 offset = 3;
964 fruAreaFieldNames = &productFruAreas;
965 break;
966 default:
967 std::cerr << "Invalid PropertyName " << propertyName << " \n";
968 return false;
969 }
970 if (fruAreaOffsetFieldValue == 0)
971 {
972 std::cerr << "FRU Area for " << propertyName << " not present \n";
973 return false;
974 }
975
976 fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
977 fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
978 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
979 size_t fruDataIter = fruAreaParams.start + offset;
980 size_t skipToFRUUpdateField = 0;
981 ssize_t fieldLength = 0;
982
983 bool found = false;
984 for (const auto& field : *fruAreaFieldNames)
985 {
986 skipToFRUUpdateField++;
987 if (propertyName == propertyNamePrefix + field)
988 {
989 found = true;
990 break;
991 }
992 }
993 if (!found)
994 {
995 std::size_t pos = propertyName.find(fruCustomFieldName);
996 if (pos == std::string::npos)
997 {
998 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
999 << propertyName << "\n";
1000 return false;
1001 }
1002 std::string fieldNumStr =
1003 propertyName.substr(pos + fruCustomFieldName.length());
1004 size_t fieldNum = std::stoi(fieldNumStr);
1005 if (fieldNum == 0)
1006 {
1007 std::cerr << "PropertyName not recognized: " << propertyName
1008 << "\n";
1009 return false;
1010 }
1011 skipToFRUUpdateField += fieldNum;
1012 }
1013
1014 for (size_t i = 1; i < skipToFRUUpdateField; i++)
1015 {
1016 if (fruDataIter < fruData.size())
1017 {
1018 fieldLength = getFieldLength(fruData[fruDataIter]);
1019
1020 if (fieldLength < 0)
1021 {
1022 break;
1023 }
1024 fruDataIter += 1 + fieldLength;
1025 }
1026 }
1027 fruAreaParams.updateFieldLoc = fruDataIter;
1028
1029 return true;
1030 }
1031
1032 // Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1033 // Return true for success and false for failure.
1034
copyRestFRUArea(std::vector<uint8_t> & fruData,const std::string & propertyName,struct FruArea & fruAreaParams,std::vector<uint8_t> & restFRUAreaFieldsData)1035 bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1036 const std::string& propertyName,
1037 struct FruArea& fruAreaParams,
1038 std::vector<uint8_t>& restFRUAreaFieldsData)
1039 {
1040 size_t fieldLoc = fruAreaParams.updateFieldLoc;
1041 size_t start = fruAreaParams.start;
1042 size_t fruAreaSize = fruAreaParams.size;
1043
1044 // Push post update fru field bytes to a vector
1045 ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1046 if (fieldLength < 0)
1047 {
1048 std::cerr << "Property " << propertyName << " not present \n";
1049 return false;
1050 }
1051
1052 size_t fruDataIter = 0;
1053 fruDataIter = fieldLoc;
1054 fruDataIter += 1 + fieldLength;
1055 size_t restFRUFieldsLoc = fruDataIter;
1056 size_t endOfFieldsLoc = 0;
1057
1058 if (fruDataIter < fruData.size())
1059 {
1060 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1061 {
1062 if (fruDataIter >= (start + fruAreaSize))
1063 {
1064 fruDataIter = start + fruAreaSize;
1065 break;
1066 }
1067 fruDataIter += 1 + fieldLength;
1068 }
1069 endOfFieldsLoc = fruDataIter;
1070 }
1071
1072 std::copy_n(fruData.begin() + restFRUFieldsLoc,
1073 endOfFieldsLoc - restFRUFieldsLoc + 1,
1074 std::back_inserter(restFRUAreaFieldsData));
1075
1076 fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1077 fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1078
1079 return true;
1080 }
1081
1082 // Get all device dbus path and match path with product name using
1083 // regular expression and find the device index for all devices.
1084
findIndexForFRU(boost::container::flat_map<std::pair<size_t,size_t>,std::shared_ptr<sdbusplus::asio::dbus_interface>> & dbusInterfaceMap,std::string & productName)1085 std::optional<int> findIndexForFRU(
1086 boost::container::flat_map<
1087 std::pair<size_t, size_t>,
1088 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1089 std::string& productName)
1090 {
1091 int highest = -1;
1092 bool found = false;
1093
1094 for (const auto& busIface : dbusInterfaceMap)
1095 {
1096 std::string path = busIface.second->get_object_path();
1097 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1098 {
1099 // Check if the match named has extra information.
1100 found = true;
1101 std::smatch baseMatch;
1102
1103 bool match = std::regex_match(path, baseMatch,
1104 std::regex(productName + "_(\\d+)$"));
1105 if (match)
1106 {
1107 if (baseMatch.size() == 2)
1108 {
1109 std::ssub_match baseSubMatch = baseMatch[1];
1110 std::string base = baseSubMatch.str();
1111
1112 int value = std::stoi(base);
1113 highest = (value > highest) ? value : highest;
1114 }
1115 }
1116 }
1117 } // end searching objects
1118
1119 if (!found)
1120 {
1121 return std::nullopt;
1122 }
1123 return highest;
1124 }
1125
1126 // This function does format fru data as per IPMI format and find the
1127 // productName in the formatted fru data, get that productName and return
1128 // productName if found or return NULL.
1129
getProductName(std::vector<uint8_t> & device,boost::container::flat_map<std::string,std::string> & formattedFRU,uint32_t bus,uint32_t address,size_t & unknownBusObjectCount)1130 std::optional<std::string> getProductName(
1131 std::vector<uint8_t>& device,
1132 boost::container::flat_map<std::string, std::string>& formattedFRU,
1133 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1134 {
1135 std::string productName;
1136
1137 resCodes res = formatIPMIFRU(device, formattedFRU);
1138 if (res == resCodes::resErr)
1139 {
1140 std::cerr << "failed to parse FRU for device at bus " << bus
1141 << " address " << address << "\n";
1142 return std::nullopt;
1143 }
1144 if (res == resCodes::resWarn)
1145 {
1146 std::cerr << "Warnings while parsing FRU for device at bus " << bus
1147 << " address " << address << "\n";
1148 }
1149
1150 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1151 // Not found under Board section or an empty string.
1152 if (productNameFind == formattedFRU.end() ||
1153 productNameFind->second.empty())
1154 {
1155 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1156 }
1157 // Found under Product section and not an empty string.
1158 if (productNameFind != formattedFRU.end() &&
1159 !productNameFind->second.empty())
1160 {
1161 productName = productNameFind->second;
1162 std::regex illegalObject("[^A-Za-z0-9_]");
1163 productName = std::regex_replace(productName, illegalObject, "_");
1164 }
1165 else
1166 {
1167 productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1168 unknownBusObjectCount++;
1169 }
1170 return productName;
1171 }
1172
getFruData(std::vector<uint8_t> & fruData,uint32_t bus,uint32_t address)1173 bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1174 {
1175 try
1176 {
1177 fruData = getFRUInfo(static_cast<uint16_t>(bus),
1178 static_cast<uint8_t>(address));
1179 }
1180 catch (const std::invalid_argument& e)
1181 {
1182 std::cerr << "Failure getting FRU Info" << e.what() << "\n";
1183 return false;
1184 }
1185
1186 return !fruData.empty();
1187 }
1188