blob: 940f8c8b62ddc1479732d3e496a3a275beeae441 [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*/
16/// \file FruUtils.cpp
17
18#include "FruUtils.hpp"
19
20#include <array>
21#include <cstdint>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053022#include <filesystem>
Patrick Ventureab296412020-12-30 13:39:37 -080023#include <iostream>
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053024#include <numeric>
Patrick Ventureab296412020-12-30 13:39:37 -080025#include <set>
26#include <string>
27#include <vector>
28
29extern "C"
30{
31// Include for I2C_SMBUS_BLOCK_MAX
32#include <linux/i2c.h>
33}
34
Ed Tanous07d467b2021-02-23 14:48:37 -080035static constexpr bool debug = false;
Patrick Ventureab296412020-12-30 13:39:37 -080036constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
37
Ed Tanous07d467b2021-02-23 14:48:37 -080038std::tm intelEpoch(void)
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000039{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053040 std::tm val = {};
41 val.tm_year = 1996 - 1900;
Scron-Chang9e5a6752021-03-16 10:51:50 +080042 val.tm_mday = 1;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053043 return val;
Vijay Khemka06d1b4a2021-02-09 18:39:11 +000044}
45
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053046char sixBitToChar(uint8_t val)
Patrick Ventureab296412020-12-30 13:39:37 -080047{
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053048 return static_cast<char>((val & 0x3f) + ' ');
49}
50
51char bcdPlusToChar(uint8_t val)
52{
53 val &= 0xf;
54 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
55}
56
57enum FRUDataEncoding
58{
59 binary = 0x0,
60 bcdPlus = 0x1,
61 sixBitASCII = 0x2,
62 languageDependent = 0x3,
63};
64
65/* Decode FRU data into a std::string, given an input iterator and end. If the
66 * state returned is fruDataOk, then the resulting string is the decoded FRU
67 * data. The input iterator is advanced past the data consumed.
68 *
69 * On fruDataErr, we have lost synchronisation with the length bytes, so the
70 * iterator is no longer usable.
71 */
72std::pair<DecodeState, std::string>
73 decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
74 const std::vector<uint8_t>::const_iterator& end,
75 bool isLangEng)
76{
77 std::string value;
78 unsigned int i;
79
80 /* we need at least one byte to decode the type/len header */
81 if (iter == end)
Patrick Ventureab296412020-12-30 13:39:37 -080082 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +053083 std::cerr << "Truncated FRU data\n";
84 return make_pair(DecodeState::err, value);
85 }
86
87 uint8_t c = *(iter++);
88
89 /* 0xc1 is the end marker */
90 if (c == 0xc1)
91 {
92 return make_pair(DecodeState::end, value);
93 }
94
95 /* decode type/len byte */
96 uint8_t type = static_cast<uint8_t>(c >> 6);
97 uint8_t len = static_cast<uint8_t>(c & 0x3f);
98
99 /* we should have at least len bytes of data available overall */
100 if (iter + len > end)
101 {
102 std::cerr << "FRU data field extends past end of FRU area data\n";
103 return make_pair(DecodeState::err, value);
104 }
105
106 switch (type)
107 {
108 case FRUDataEncoding::binary:
Patrick Ventureab296412020-12-30 13:39:37 -0800109 {
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530110 std::stringstream ss;
111 ss << std::hex << std::setfill('0');
112 for (i = 0; i < len; i++, iter++)
113 {
114 uint8_t val = static_cast<uint8_t>(*iter);
115 ss << std::setw(2) << static_cast<int>(val);
116 }
117 value = ss.str();
118 break;
Patrick Ventureab296412020-12-30 13:39:37 -0800119 }
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530120 case FRUDataEncoding::languageDependent:
121 /* For language-code dependent encodings, assume 8-bit ASCII */
122 value = std::string(iter, iter + len);
123 iter += len;
124
125 /* English text is encoded in 8-bit ASCII + Latin 1. All other
126 * languages are required to use 2-byte unicode. FruDevice does not
127 * handle unicode.
128 */
129 if (!isLangEng)
130 {
131 std::cerr << "Error: Non english string is not supported \n";
132 return make_pair(DecodeState::err, value);
133 }
134
135 break;
136
137 case FRUDataEncoding::bcdPlus:
138 value = std::string();
139 for (i = 0; i < len; i++, iter++)
140 {
141 uint8_t val = *iter;
142 value.push_back(bcdPlusToChar(val >> 4));
143 value.push_back(bcdPlusToChar(val & 0xf));
144 }
145 break;
146
147 case FRUDataEncoding::sixBitASCII:
148 {
149 unsigned int accum = 0;
150 unsigned int accumBitLen = 0;
151 value = std::string();
152 for (i = 0; i < len; i++, iter++)
153 {
154 accum |= *iter << accumBitLen;
155 accumBitLen += 8;
156 while (accumBitLen >= 6)
157 {
158 value.push_back(sixBitToChar(accum & 0x3f));
159 accum >>= 6;
160 accumBitLen -= 6;
161 }
162 }
163 }
164 break;
165 }
166
167 return make_pair(DecodeState::ok, value);
168}
169
170bool checkLangEng(uint8_t lang)
171{
172 // If Lang is not English then the encoding is defined as 2-byte UNICODE,
173 // but we don't support that.
174 if (lang && lang != 25)
175 {
176 std::cerr << "Warning: languages other than English is not "
177 "supported\n";
178 // Return language flag as non english
Patrick Ventureab296412020-12-30 13:39:37 -0800179 return false;
180 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800181 return true;
Patrick Ventureab296412020-12-30 13:39:37 -0800182}
183
Vijay Khemka06d1b4a2021-02-09 18:39:11 +0000184/* This function verifies for other offsets to check if they are not
185 * falling under other field area
186 *
187 * fruBytes: Start of Fru data
188 * currentArea: Index of current area offset to be compared against all area
189 * offset and it is a multiple of 8 bytes as per specification
190 * len: Length of current area space and it is a multiple of 8 bytes
191 * as per specification
192 */
193bool verifyOffset(const std::vector<uint8_t>& fruBytes, fruAreas currentArea,
194 uint8_t len)
195{
196
197 unsigned int fruBytesSize = fruBytes.size();
198
199 // check if Fru data has at least 8 byte header
200 if (fruBytesSize <= fruBlockSize)
201 {
202 std::cerr << "Error: trying to parse empty FRU\n";
203 return false;
204 }
205
206 // Check range of passed currentArea value
207 if (currentArea > fruAreas::fruAreaMultirecord)
208 {
209 std::cerr << "Error: Fru area is out of range\n";
210 return false;
211 }
212
213 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
214 if (currentAreaIndex > fruBytesSize)
215 {
216 std::cerr << "Error: Fru area index is out of range\n";
217 return false;
218 }
219
220 unsigned int start = fruBytes[currentAreaIndex];
221 unsigned int end = start + len;
222
223 /* Verify each offset within the range of start and end */
224 for (fruAreas area = fruAreas::fruAreaInternal;
225 area <= fruAreas::fruAreaMultirecord; ++area)
226 {
227 // skip the current offset
228 if (area == currentArea)
229 {
230 continue;
231 }
232
233 unsigned int areaIndex = getHeaderAreaFieldOffset(area);
234 if (areaIndex > fruBytesSize)
235 {
236 std::cerr << "Error: Fru area index is out of range\n";
237 return false;
238 }
239
240 unsigned int areaOffset = fruBytes[areaIndex];
241 // if areaOffset is 0 means this area is not available so skip
242 if (areaOffset == 0)
243 {
244 continue;
245 }
246
247 // check for overlapping of current offset with given areaoffset
248 if (areaOffset == start || (areaOffset > start && areaOffset < end))
249 {
250 std::cerr << getFruAreaName(currentArea)
251 << " offset is overlapping with " << getFruAreaName(area)
252 << " offset\n";
253 return false;
254 }
255 }
256 return true;
257}
258
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530259resCodes formatFRU(const std::vector<uint8_t>& fruBytes,
260 boost::container::flat_map<std::string, std::string>& result)
261{
262 resCodes ret = resCodes::resOK;
263 if (fruBytes.size() <= fruBlockSize)
264 {
265 std::cerr << "Error: trying to parse empty FRU \n";
266 return resCodes::resErr;
267 }
268 result["Common_Format_Version"] =
269 std::to_string(static_cast<int>(*fruBytes.begin()));
270
271 const std::vector<std::string>* fruAreaFieldNames;
272
273 // Don't parse Internal and Multirecord areas
274 for (fruAreas area = fruAreas::fruAreaChassis;
275 area <= fruAreas::fruAreaProduct; ++area)
276 {
277
278 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
279 if (offset == 0)
280 {
281 continue;
282 }
283 offset *= fruBlockSize;
284 std::vector<uint8_t>::const_iterator fruBytesIter =
285 fruBytes.begin() + offset;
286 if (fruBytesIter + fruBlockSize >= fruBytes.end())
287 {
288 std::cerr << "Not enough data to parse \n";
289 return resCodes::resErr;
290 }
291 // check for format version 1
292 if (*fruBytesIter != 0x01)
293 {
294 std::cerr << "Unexpected version " << *fruBytesIter << "\n";
295 return resCodes::resErr;
296 }
297 ++fruBytesIter;
298
299 /* Verify other area offset for overlap with current area by passing
300 * length of current area offset pointed by *fruBytesIter
301 */
302 if (!verifyOffset(fruBytes, area, *fruBytesIter))
303 {
304 return resCodes::resErr;
305 }
306
Andrew Jeffery65ed6642021-08-02 22:32:23 +0930307 size_t fruAreaSize = *fruBytesIter * fruBlockSize;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530308 std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
309 fruBytes.begin() + offset + fruAreaSize - 1;
310 ++fruBytesIter;
311
312 uint8_t fruComputedChecksum =
313 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
314 if (fruComputedChecksum != *fruBytesIterEndArea)
315 {
316 std::stringstream ss;
317 ss << std::hex << std::setfill('0');
318 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
319 ss << "\tComputed checksum: 0x" << std::setw(2)
320 << static_cast<int>(fruComputedChecksum) << "\n";
321 ss << "\tThe read checksum: 0x" << std::setw(2)
322 << static_cast<int>(*fruBytesIterEndArea) << "\n";
323 std::cerr << ss.str();
324 ret = resCodes::resWarn;
325 }
326
327 /* Set default language flag to true as Chassis Fru area are always
328 * encoded in English defined in Section 10 of Fru specification
329 */
330
331 bool isLangEng = true;
332 switch (area)
333 {
334 case fruAreas::fruAreaChassis:
335 {
336 result["CHASSIS_TYPE"] =
337 std::to_string(static_cast<int>(*fruBytesIter));
338 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800339 fruAreaFieldNames = &chassisFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530340 break;
341 }
342 case fruAreas::fruAreaBoard:
343 {
344 uint8_t lang = *fruBytesIter;
345 result["BOARD_LANGUAGE_CODE"] =
346 std::to_string(static_cast<int>(lang));
347 isLangEng = checkLangEng(lang);
348 fruBytesIter += 1;
349
350 unsigned int minutes = *fruBytesIter |
351 *(fruBytesIter + 1) << 8 |
352 *(fruBytesIter + 2) << 16;
353 std::tm fruTime = intelEpoch();
354 std::time_t timeValue = std::mktime(&fruTime);
355 timeValue += minutes * 60;
356 fruTime = *std::gmtime(&timeValue);
357
358 // Tue Nov 20 23:08:00 2018
359 char timeString[32] = {0};
360 auto bytes = std::strftime(timeString, sizeof(timeString),
361 "%Y-%m-%d - %H:%M:%S", &fruTime);
362 if (bytes == 0)
363 {
364 std::cerr << "invalid time string encountered\n";
365 return resCodes::resErr;
366 }
367
368 result["BOARD_MANUFACTURE_DATE"] = std::string(timeString);
369 fruBytesIter += 3;
Ed Tanous07d467b2021-02-23 14:48:37 -0800370 fruAreaFieldNames = &boardFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530371 break;
372 }
373 case fruAreas::fruAreaProduct:
374 {
375 uint8_t lang = *fruBytesIter;
376 result["PRODUCT_LANGUAGE_CODE"] =
377 std::to_string(static_cast<int>(lang));
378 isLangEng = checkLangEng(lang);
379 fruBytesIter += 1;
Ed Tanous07d467b2021-02-23 14:48:37 -0800380 fruAreaFieldNames = &productFruAreas;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530381 break;
382 }
383 default:
384 {
385 std::cerr << "Internal error: unexpected FRU area index: "
386 << static_cast<int>(area) << " \n";
387 return resCodes::resErr;
388 }
389 }
390 size_t fieldIndex = 0;
391 DecodeState state;
392 do
393 {
394 auto res =
395 decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
396 state = res.first;
397 std::string value = res.second;
398 std::string name;
399 if (fieldIndex < fruAreaFieldNames->size())
400 {
401 name = std::string(getFruAreaName(area)) + "_" +
402 fruAreaFieldNames->at(fieldIndex);
403 }
Scron-Chang77987122021-03-30 20:53:52 +0800404 else
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530405 {
406 name =
407 std::string(getFruAreaName(area)) + "_" +
Ed Tanous07d467b2021-02-23 14:48:37 -0800408 fruCustomFieldName +
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530409 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
410 }
411
412 if (state == DecodeState::ok)
413 {
414 // Strip non null characters from the end
415 value.erase(std::find_if(value.rbegin(), value.rend(),
416 [](char ch) { return ch != 0; })
417 .base(),
418 value.end());
419
420 result[name] = std::move(value);
421 ++fieldIndex;
422 }
423 else if (state == DecodeState::err)
424 {
425 std::cerr << "Error while parsing " << name << "\n";
426 ret = resCodes::resWarn;
427 // Cancel decoding if failed to parse any of mandatory
428 // fields
429 if (fieldIndex < fruAreaFieldNames->size())
430 {
431 std::cerr << "Failed to parse mandatory field \n";
432 return resCodes::resErr;
433 }
434 }
435 else
436 {
437 if (fieldIndex < fruAreaFieldNames->size())
438 {
439 std::cerr << "Mandatory fields absent in FRU area "
440 << getFruAreaName(area) << " after " << name
441 << "\n";
442 ret = resCodes::resWarn;
443 }
444 }
445 } while (state == DecodeState::ok);
446 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
447 {
448 uint8_t c = *fruBytesIter;
449 if (c)
450 {
451 std::cerr << "Non-zero byte after EndOfFields in FRU area "
452 << getFruAreaName(area) << "\n";
453 ret = resCodes::resWarn;
454 break;
455 }
456 }
457 }
458
459 return ret;
460}
461
462// Calculate new checksum for fru info area
463uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
464 std::vector<uint8_t>::const_iterator end)
465{
466 constexpr int checksumMod = 256;
Andrew Jeffery499e7aa2021-08-02 22:18:22 +0930467 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
468 return (checksumMod - sum) % checksumMod;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530469}
470
471uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
472{
473 return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
474}
475
476// Update new fru area length &
477// Update checksum at new checksum location
478// Return the offset of the area checksum byte
479unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
480 size_t fruAreaStart,
481 size_t fruAreaEndOfFieldsOffset,
482 size_t fruAreaEndOffset)
483{
484 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
485
486 // fill zeros for any remaining unused space
487 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
488 fruData.begin() + fruAreaEndOffset, 0);
489
490 size_t mod = traverseFRUAreaIndex % fruBlockSize;
491 size_t checksumLoc;
492 if (!mod)
493 {
494 traverseFRUAreaIndex += (fruBlockSize);
495 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
496 }
497 else
498 {
499 traverseFRUAreaIndex += (fruBlockSize - mod);
500 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
501 }
502
503 size_t newFRUAreaLen = (traverseFRUAreaIndex / fruBlockSize) +
504 ((traverseFRUAreaIndex % fruBlockSize) != 0);
505 size_t fruAreaLengthLoc = fruAreaStart + 1;
506 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
507
508 // Calculate new checksum
509 std::vector<uint8_t> finalFRUData;
510 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
511 std::back_inserter(finalFRUData));
512
513 fruData[checksumLoc] = calculateChecksum(finalFRUData);
514 return checksumLoc;
515}
516
517ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
518{
519 constexpr uint8_t typeLenMask = 0x3F;
520 constexpr uint8_t endOfFields = 0xC1;
521 if (fruFieldTypeLenValue == endOfFields)
522 {
523 return -1;
524 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800525 return fruFieldTypeLenValue & typeLenMask;
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530526}
527
528bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
529{
530 // ipmi spec format version number is currently at 1, verify it
531 if (blockData[0] != fruVersion)
532 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800533 if (debug)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530534 {
535 std::cerr << "FRU spec version " << (int)(blockData[0])
536 << " not supported. Supported version is "
537 << (int)(fruVersion) << "\n";
538 }
539 return false;
540 }
541
542 // verify pad is set to 0
543 if (blockData[6] != 0x0)
544 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800545 if (debug)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530546 {
547 std::cerr << "PAD value in header is non zero, value is "
548 << (int)(blockData[6]) << "\n";
549 }
550 return false;
551 }
552
553 // verify offsets are 0, or don't point to another offset
554 std::set<uint8_t> foundOffsets;
555 for (int ii = 1; ii < 6; ii++)
556 {
557 if (blockData[ii] == 0)
558 {
559 continue;
560 }
561 auto inserted = foundOffsets.insert(blockData[ii]);
562 if (!inserted.second)
563 {
564 return false;
565 }
566 }
567
568 // validate checksum
569 size_t sum = 0;
570 for (int jj = 0; jj < 7; jj++)
571 {
572 sum += blockData[jj];
573 }
574 sum = (256 - sum) & 0xFF;
575
576 if (sum != blockData[7])
577 {
Ed Tanous07d467b2021-02-23 14:48:37 -0800578 if (debug)
Kumar Thangavelc8dc4af2021-01-12 10:36:38 +0530579 {
580 std::cerr << "Checksum " << (int)(blockData[7])
581 << " is invalid. calculated checksum is " << (int)(sum)
582 << "\n";
583 }
584 return false;
585 }
586 return true;
587}
588
Oskar Senftbd4075f2021-10-05 23:42:43 -0400589bool findFRUHeader(int flag, int file, uint16_t address,
590 const ReadBlockFunc& readBlock,
591 const std::string& errorHelp,
592 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
593 uint16_t& baseOffset)
594{
595 if (readBlock(flag, file, address, baseOffset, 0x8, blockData.data()) < 0)
596 {
597 std::cerr << "failed to read " << errorHelp << " base offset "
598 << baseOffset << "\n";
599 return false;
600 }
601
602 // check the header checksum
603 if (validateHeader(blockData))
604 {
605 return true;
606 }
607
608 // only continue the search if we just looked at 0x0.
609 if (baseOffset != 0) {
610 return false;
611 }
612
613 // now check for special cases where the IPMI data is at an offset
614
615 // check if blockData starts with tyanHeader
616 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
617 if (blockData.size() >= tyanHeader.size() &&
618 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
619 {
620 // look for the FRU header at offset 0x6000
621 baseOffset = 0x6000;
622 return findFRUHeader(flag, file, address, readBlock, errorHelp,
623 blockData, baseOffset);
624 }
625
626 if (debug)
627 {
628 std::cerr << "Illegal header " << errorHelp << " base offset "
629 << baseOffset << "\n";
630 }
631
632 return false;
633}
634
Patrick Ventureab296412020-12-30 13:39:37 -0800635std::vector<uint8_t> readFRUContents(int flag, int file, uint16_t address,
Ed Tanous07d467b2021-02-23 14:48:37 -0800636 const ReadBlockFunc& readBlock,
Patrick Ventureab296412020-12-30 13:39:37 -0800637 const std::string& errorHelp)
638{
639 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData;
Oskar Senftbd4075f2021-10-05 23:42:43 -0400640 uint16_t baseOffset = 0x0;
Patrick Ventureab296412020-12-30 13:39:37 -0800641
Oskar Senftbd4075f2021-10-05 23:42:43 -0400642 if (!findFRUHeader(flag, file, address, readBlock, errorHelp,
643 blockData, baseOffset)) {
Patrick Ventureab296412020-12-30 13:39:37 -0800644 return {};
645 }
646
647 std::vector<uint8_t> device;
648 device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
649
650 bool hasMultiRecords = false;
651 size_t fruLength = fruBlockSize; // At least FRU header is present
Vijay Khemka7792e392021-01-25 13:03:56 -0800652 unsigned int prevOffset = 0;
Patrick Ventureab296412020-12-30 13:39:37 -0800653 for (fruAreas area = fruAreas::fruAreaInternal;
654 area <= fruAreas::fruAreaMultirecord; ++area)
655 {
656 // Offset value can be 255.
657 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
658 if (areaOffset == 0)
659 {
660 continue;
661 }
662
Vijay Khemka7792e392021-01-25 13:03:56 -0800663 /* Check for offset order, as per Section 17 of FRU specification, FRU
664 * information areas are required to be in order in FRU data layout
665 * which means all offset value should be in increasing order or can be
666 * 0 if that area is not present
667 */
668 if (areaOffset <= prevOffset)
669 {
670 std::cerr << "Fru area offsets are not in required order as per "
671 "Section 17 of Fru specification\n";
672 return {};
673 }
674 prevOffset = areaOffset;
675
Patrick Ventureab296412020-12-30 13:39:37 -0800676 // MultiRecords are different. area is not tracking section, it's
677 // walking the common header.
678 if (area == fruAreas::fruAreaMultirecord)
679 {
680 hasMultiRecords = true;
681 break;
682 }
683
684 areaOffset *= fruBlockSize;
685
Oskar Senftbd4075f2021-10-05 23:42:43 -0400686 if (readBlock(flag, file, address,
687 baseOffset + static_cast<uint16_t>(areaOffset),
Patrick Ventureab296412020-12-30 13:39:37 -0800688 0x2, blockData.data()) < 0)
689 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400690 std::cerr << "failed to read " << errorHelp << " base offset "
691 << baseOffset << "\n";
Patrick Ventureab296412020-12-30 13:39:37 -0800692 return {};
693 }
694
695 // Ignore data type (blockData is already unsigned).
696 size_t length = blockData[1] * fruBlockSize;
697 areaOffset += length;
698 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
699 }
700
701 if (hasMultiRecords)
702 {
703 // device[area count] is the index to the last area because the 0th
704 // entry is not an offset in the common header.
705 unsigned int areaOffset =
706 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
707 areaOffset *= fruBlockSize;
708
709 // the multi-area record header is 5 bytes long.
710 constexpr size_t multiRecordHeaderSize = 5;
711 constexpr uint8_t multiRecordEndOfListMask = 0x80;
712
713 // Sanity hard-limit to 64KB.
714 while (areaOffset < std::numeric_limits<uint16_t>::max())
715 {
716 // In multi-area, the area offset points to the 0th record, each
717 // record has 3 bytes of the header we care about.
718 if (readBlock(flag, file, address,
Oskar Senftbd4075f2021-10-05 23:42:43 -0400719 baseOffset + static_cast<uint16_t>(areaOffset), 0x3,
Patrick Ventureab296412020-12-30 13:39:37 -0800720 blockData.data()) < 0)
721 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400722 std::cerr << "failed to read " << errorHelp << " base offset "
723 << baseOffset << "\n";
Patrick Ventureab296412020-12-30 13:39:37 -0800724 return {};
725 }
726
727 // Ok, let's check the record length, which is in bytes (unsigned,
728 // up to 255, so blockData should hold uint8_t not char)
729 size_t recordLength = blockData[2];
730 areaOffset += (recordLength + multiRecordHeaderSize);
731 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
732
733 // If this is the end of the list bail.
734 if ((blockData[1] & multiRecordEndOfListMask))
735 {
736 break;
737 }
738 }
739 }
740
741 // You already copied these first 8 bytes (the ipmi fru header size)
742 fruLength -= std::min(fruBlockSize, fruLength);
743
744 int readOffset = fruBlockSize;
745
746 while (fruLength > 0)
747 {
748 size_t requestLength =
749 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
750
Oskar Senftbd4075f2021-10-05 23:42:43 -0400751 if (readBlock(flag, file, address,
752 baseOffset + static_cast<uint16_t>(readOffset),
Patrick Ventureab296412020-12-30 13:39:37 -0800753 static_cast<uint8_t>(requestLength),
754 blockData.data()) < 0)
755 {
Oskar Senftbd4075f2021-10-05 23:42:43 -0400756 std::cerr << "failed to read " << errorHelp << " base offset "
757 << baseOffset << "\n";
Patrick Ventureab296412020-12-30 13:39:37 -0800758 return {};
759 }
760
761 device.insert(device.end(), blockData.begin(),
762 blockData.begin() + requestLength);
763
764 readOffset += requestLength;
765 fruLength -= std::min(requestLength, fruLength);
766 }
767
768 return device;
769}
770
771unsigned int getHeaderAreaFieldOffset(fruAreas area)
772{
773 return static_cast<unsigned int>(area) + 1;
774}