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 <array> 21 #include <cstddef> 22 #include <cstdint> 23 #include <filesystem> 24 #include <iomanip> 25 #include <iostream> 26 #include <numeric> 27 #include <set> 28 #include <sstream> 29 #include <string> 30 #include <vector> 31 32 extern "C" 33 { 34 // Include for I2C_SMBUS_BLOCK_MAX 35 #include <linux/i2c.h> 36 } 37 38 static constexpr bool debug = false; 39 constexpr size_t fruVersion = 1; // Current FRU spec version number is 1 40 41 std::tm intelEpoch() 42 { 43 std::tm val = {}; 44 val.tm_year = 1996 - 1900; 45 val.tm_mday = 1; 46 return val; 47 } 48 49 char sixBitToChar(uint8_t val) 50 { 51 return static_cast<char>((val & 0x3f) + ' '); 52 } 53 54 char bcdPlusToChar(uint8_t val) 55 { 56 val &= 0xf; 57 return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10]; 58 } 59 60 enum FRUDataEncoding 61 { 62 binary = 0x0, 63 bcdPlus = 0x1, 64 sixBitASCII = 0x2, 65 languageDependent = 0x3, 66 }; 67 68 enum MultiRecordType : uint8_t 69 { 70 powerSupplyInfo = 0x00, 71 dcOutput = 0x01, 72 dcLoad = 0x02, 73 managementAccessRecord = 0x03, 74 baseCompatibilityRecord = 0x04, 75 extendedCompatibilityRecord = 0x05, 76 resvASFSMBusDeviceRecord = 0x06, 77 resvASFLegacyDeviceAlerts = 0x07, 78 resvASFRemoteControl = 0x08, 79 extendedDCOutput = 0x09, 80 extendedDCLoad = 0x0A 81 }; 82 83 enum SubManagementAccessRecord : uint8_t 84 { 85 systemManagementURL = 0x01, 86 systemName = 0x02, 87 systemPingAddress = 0x03, 88 componentManagementURL = 0x04, 89 componentName = 0x05, 90 componentPingAddress = 0x06, 91 systemUniqueID = 0x07 92 }; 93 94 /* Decode FRU data into a std::string, given an input iterator and end. If the 95 * state returned is fruDataOk, then the resulting string is the decoded FRU 96 * data. The input iterator is advanced past the data consumed. 97 * 98 * On fruDataErr, we have lost synchronisation with the length bytes, so the 99 * iterator is no longer usable. 100 */ 101 std::pair<DecodeState, std::string> decodeFRUData( 102 std::vector<uint8_t>::const_iterator& iter, 103 const std::vector<uint8_t>::const_iterator& end, bool isLangEng) 104 { 105 std::string value; 106 unsigned int i = 0; 107 108 /* we need at least one byte to decode the type/len header */ 109 if (iter == end) 110 { 111 std::cerr << "Truncated FRU data\n"; 112 return make_pair(DecodeState::err, value); 113 } 114 115 uint8_t c = *(iter++); 116 117 /* 0xc1 is the end marker */ 118 if (c == 0xc1) 119 { 120 return make_pair(DecodeState::end, value); 121 } 122 123 /* decode type/len byte */ 124 uint8_t type = static_cast<uint8_t>(c >> 6); 125 uint8_t len = static_cast<uint8_t>(c & 0x3f); 126 127 /* we should have at least len bytes of data available overall */ 128 if (iter + len > end) 129 { 130 std::cerr << "FRU data field extends past end of FRU area data\n"; 131 return make_pair(DecodeState::err, value); 132 } 133 134 switch (type) 135 { 136 case FRUDataEncoding::binary: 137 { 138 std::stringstream ss; 139 ss << std::hex << std::setfill('0'); 140 for (i = 0; i < len; i++, iter++) 141 { 142 uint8_t val = static_cast<uint8_t>(*iter); 143 ss << std::setw(2) << static_cast<int>(val); 144 } 145 value = ss.str(); 146 break; 147 } 148 case FRUDataEncoding::languageDependent: 149 /* For language-code dependent encodings, assume 8-bit ASCII */ 150 value = std::string(iter, iter + len); 151 iter += len; 152 153 /* English text is encoded in 8-bit ASCII + Latin 1. All other 154 * languages are required to use 2-byte unicode. FruDevice does not 155 * handle unicode. 156 */ 157 if (!isLangEng) 158 { 159 std::cerr << "Error: Non english string is not supported \n"; 160 return make_pair(DecodeState::err, value); 161 } 162 163 break; 164 165 case FRUDataEncoding::bcdPlus: 166 value = std::string(); 167 for (i = 0; i < len; i++, iter++) 168 { 169 uint8_t val = *iter; 170 value.push_back(bcdPlusToChar(val >> 4)); 171 value.push_back(bcdPlusToChar(val & 0xf)); 172 } 173 break; 174 175 case FRUDataEncoding::sixBitASCII: 176 { 177 unsigned int accum = 0; 178 unsigned int accumBitLen = 0; 179 value = std::string(); 180 for (i = 0; i < len; i++, iter++) 181 { 182 accum |= *iter << accumBitLen; 183 accumBitLen += 8; 184 while (accumBitLen >= 6) 185 { 186 value.push_back(sixBitToChar(accum & 0x3f)); 187 accum >>= 6; 188 accumBitLen -= 6; 189 } 190 } 191 } 192 break; 193 194 default: 195 { 196 return make_pair(DecodeState::err, value); 197 } 198 } 199 200 return make_pair(DecodeState::ok, value); 201 } 202 203 bool checkLangEng(uint8_t lang) 204 { 205 // If Lang is not English then the encoding is defined as 2-byte UNICODE, 206 // but we don't support that. 207 if ((lang != 0U) && lang != 25) 208 { 209 std::cerr << "Warning: languages other than English is not " 210 "supported\n"; 211 // Return language flag as non english 212 return false; 213 } 214 return true; 215 } 216 217 /* This function verifies for other offsets to check if they are not 218 * falling under other field area 219 * 220 * fruBytes: Start of Fru data 221 * currentArea: Index of current area offset to be compared against all area 222 * offset and it is a multiple of 8 bytes as per specification 223 * len: Length of current area space and it is a multiple of 8 bytes 224 * as per specification 225 */ 226 bool verifyOffset(const std::vector<uint8_t>& fruBytes, fruAreas currentArea, 227 uint8_t len) 228 { 229 unsigned int fruBytesSize = fruBytes.size(); 230 231 // check if Fru data has at least 8 byte header 232 if (fruBytesSize <= fruBlockSize) 233 { 234 std::cerr << "Error: trying to parse empty FRU\n"; 235 return false; 236 } 237 238 // Check range of passed currentArea value 239 if (currentArea > fruAreas::fruAreaMultirecord) 240 { 241 std::cerr << "Error: Fru area is out of range\n"; 242 return false; 243 } 244 245 unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea); 246 if (currentAreaIndex > fruBytesSize) 247 { 248 std::cerr << "Error: Fru area index is out of range\n"; 249 return false; 250 } 251 252 unsigned int start = fruBytes[currentAreaIndex]; 253 unsigned int end = start + len; 254 255 /* Verify each offset within the range of start and end */ 256 for (fruAreas area = fruAreas::fruAreaInternal; 257 area <= fruAreas::fruAreaMultirecord; ++area) 258 { 259 // skip the current offset 260 if (area == currentArea) 261 { 262 continue; 263 } 264 265 unsigned int areaIndex = getHeaderAreaFieldOffset(area); 266 if (areaIndex > fruBytesSize) 267 { 268 std::cerr << "Error: Fru area index is out of range\n"; 269 return false; 270 } 271 272 unsigned int areaOffset = fruBytes[areaIndex]; 273 // if areaOffset is 0 means this area is not available so skip 274 if (areaOffset == 0) 275 { 276 continue; 277 } 278 279 // check for overlapping of current offset with given areaoffset 280 if (areaOffset == start || (areaOffset > start && areaOffset < end)) 281 { 282 std::cerr << getFruAreaName(currentArea) 283 << " offset is overlapping with " << getFruAreaName(area) 284 << " offset\n"; 285 return false; 286 } 287 } 288 return true; 289 } 290 291 static void parseMultirecordUUID( 292 const std::vector<uint8_t>& device, 293 boost::container::flat_map<std::string, std::string>& result) 294 { 295 constexpr size_t uuidDataLen = 16; 296 constexpr size_t multiRecordHeaderLen = 5; 297 /* UUID record data, plus one to skip past the sub-record type byte */ 298 constexpr size_t uuidRecordData = multiRecordHeaderLen + 1; 299 constexpr size_t multiRecordEndOfListMask = 0x80; 300 /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented 301 * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD 302 * 0xEE 0xFF 303 */ 304 const std::array<uint8_t, uuidDataLen> uuidCharOrder = { 305 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15}; 306 uint32_t areaOffset = 307 device.at(getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)); 308 309 if (areaOffset == 0) 310 { 311 return; 312 } 313 314 areaOffset *= fruBlockSize; 315 std::vector<uint8_t>::const_iterator fruBytesIter = 316 device.begin() + areaOffset; 317 318 /* Verify area offset */ 319 if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter)) 320 { 321 return; 322 } 323 while (areaOffset + uuidRecordData + uuidDataLen <= device.size()) 324 { 325 if ((areaOffset < device.size()) && 326 (device[areaOffset] == 327 (uint8_t)MultiRecordType::managementAccessRecord)) 328 { 329 if ((areaOffset + multiRecordHeaderLen < device.size()) && 330 (device[areaOffset + multiRecordHeaderLen] == 331 (uint8_t)SubManagementAccessRecord::systemUniqueID)) 332 { 333 /* Layout of UUID: 334 * source: https://www.ietf.org/rfc/rfc4122.txt 335 * 336 * UUID binary format (16 bytes): 337 * 4B-2B-2B-2B-6B (big endian) 338 * 339 * UUID string is 36 length of characters (36 bytes): 340 * 0 9 14 19 24 341 * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 342 * be be be be be 343 * be means it should be converted to big endian. 344 */ 345 /* Get UUID bytes to UUID string */ 346 std::stringstream tmp; 347 tmp << std::hex << std::setfill('0'); 348 for (size_t i = 0; i < uuidDataLen; i++) 349 { 350 tmp << std::setw(2) 351 << static_cast<uint16_t>( 352 device[areaOffset + uuidRecordData + 353 uuidCharOrder[i]]); 354 } 355 std::string uuidStr = tmp.str(); 356 result["MULTIRECORD_UUID"] = 357 uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' + 358 uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' + 359 uuidStr.substr(20, 12); 360 break; 361 } 362 } 363 if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0) 364 { 365 break; 366 } 367 areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen; 368 } 369 } 370 371 resCodes 372 formatIPMIFRU(const std::vector<uint8_t>& fruBytes, 373 boost::container::flat_map<std::string, std::string>& result) 374 { 375 resCodes ret = resCodes::resOK; 376 if (fruBytes.size() <= fruBlockSize) 377 { 378 std::cerr << "Error: trying to parse empty FRU \n"; 379 return resCodes::resErr; 380 } 381 result["Common_Format_Version"] = 382 std::to_string(static_cast<int>(*fruBytes.begin())); 383 384 const std::vector<std::string>* fruAreaFieldNames = nullptr; 385 386 // Don't parse Internal and Multirecord areas 387 for (fruAreas area = fruAreas::fruAreaChassis; 388 area <= fruAreas::fruAreaProduct; ++area) 389 { 390 size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area)); 391 if (offset == 0) 392 { 393 continue; 394 } 395 offset *= fruBlockSize; 396 std::vector<uint8_t>::const_iterator fruBytesIter = 397 fruBytes.begin() + offset; 398 if (fruBytesIter + fruBlockSize >= fruBytes.end()) 399 { 400 std::cerr << "Not enough data to parse \n"; 401 return resCodes::resErr; 402 } 403 // check for format version 1 404 if (*fruBytesIter != 0x01) 405 { 406 std::cerr << "Unexpected version " << *fruBytesIter << "\n"; 407 return resCodes::resErr; 408 } 409 ++fruBytesIter; 410 411 /* Verify other area offset for overlap with current area by passing 412 * length of current area offset pointed by *fruBytesIter 413 */ 414 if (!verifyOffset(fruBytes, area, *fruBytesIter)) 415 { 416 return resCodes::resErr; 417 } 418 419 size_t fruAreaSize = *fruBytesIter * fruBlockSize; 420 std::vector<uint8_t>::const_iterator fruBytesIterEndArea = 421 fruBytes.begin() + offset + fruAreaSize - 1; 422 ++fruBytesIter; 423 424 uint8_t fruComputedChecksum = 425 calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea); 426 if (fruComputedChecksum != *fruBytesIterEndArea) 427 { 428 std::stringstream ss; 429 ss << std::hex << std::setfill('0'); 430 ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n"; 431 ss << "\tComputed checksum: 0x" << std::setw(2) 432 << static_cast<int>(fruComputedChecksum) << "\n"; 433 ss << "\tThe read checksum: 0x" << std::setw(2) 434 << static_cast<int>(*fruBytesIterEndArea) << "\n"; 435 std::cerr << ss.str(); 436 ret = resCodes::resWarn; 437 } 438 439 /* Set default language flag to true as Chassis Fru area are always 440 * encoded in English defined in Section 10 of Fru specification 441 */ 442 443 bool isLangEng = true; 444 switch (area) 445 { 446 case fruAreas::fruAreaChassis: 447 { 448 result["CHASSIS_TYPE"] = 449 std::to_string(static_cast<int>(*fruBytesIter)); 450 fruBytesIter += 1; 451 fruAreaFieldNames = &chassisFruAreas; 452 break; 453 } 454 case fruAreas::fruAreaBoard: 455 { 456 uint8_t lang = *fruBytesIter; 457 result["BOARD_LANGUAGE_CODE"] = 458 std::to_string(static_cast<int>(lang)); 459 isLangEng = checkLangEng(lang); 460 fruBytesIter += 1; 461 462 unsigned int minutes = 463 *fruBytesIter | *(fruBytesIter + 1) << 8 | 464 *(fruBytesIter + 2) << 16; 465 std::tm fruTime = intelEpoch(); 466 std::time_t timeValue = timegm(&fruTime); 467 timeValue += static_cast<long>(minutes) * 60; 468 fruTime = *std::gmtime(&timeValue); 469 470 // Tue Nov 20 23:08:00 2018 471 std::array<char, 32> timeString = {}; 472 auto bytes = std::strftime(timeString.data(), timeString.size(), 473 "%Y%m%dT%H%M%SZ", &fruTime); 474 if (bytes == 0) 475 { 476 std::cerr << "invalid time string encountered\n"; 477 return resCodes::resErr; 478 } 479 480 result["BOARD_MANUFACTURE_DATE"] = 481 std::string_view(timeString.data(), bytes); 482 fruBytesIter += 3; 483 fruAreaFieldNames = &boardFruAreas; 484 break; 485 } 486 case fruAreas::fruAreaProduct: 487 { 488 uint8_t lang = *fruBytesIter; 489 result["PRODUCT_LANGUAGE_CODE"] = 490 std::to_string(static_cast<int>(lang)); 491 isLangEng = checkLangEng(lang); 492 fruBytesIter += 1; 493 fruAreaFieldNames = &productFruAreas; 494 break; 495 } 496 default: 497 { 498 std::cerr << "Internal error: unexpected FRU area index: " 499 << static_cast<int>(area) << " \n"; 500 return resCodes::resErr; 501 } 502 } 503 size_t fieldIndex = 0; 504 DecodeState state = DecodeState::ok; 505 do 506 { 507 auto res = 508 decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng); 509 state = res.first; 510 std::string value = res.second; 511 std::string name; 512 if (fieldIndex < fruAreaFieldNames->size()) 513 { 514 name = std::string(getFruAreaName(area)) + "_" + 515 fruAreaFieldNames->at(fieldIndex); 516 } 517 else 518 { 519 name = 520 std::string(getFruAreaName(area)) + "_" + 521 fruCustomFieldName + 522 std::to_string(fieldIndex - fruAreaFieldNames->size() + 1); 523 } 524 525 if (state == DecodeState::ok) 526 { 527 // Strip non null characters from the end 528 value.erase(std::find_if(value.rbegin(), value.rend(), 529 [](char ch) { return ch != 0; }) 530 .base(), 531 value.end()); 532 533 result[name] = std::move(value); 534 ++fieldIndex; 535 } 536 else if (state == DecodeState::err) 537 { 538 std::cerr << "Error while parsing " << name << "\n"; 539 ret = resCodes::resWarn; 540 // Cancel decoding if failed to parse any of mandatory 541 // fields 542 if (fieldIndex < fruAreaFieldNames->size()) 543 { 544 std::cerr << "Failed to parse mandatory field \n"; 545 return resCodes::resErr; 546 } 547 } 548 else 549 { 550 if (fieldIndex < fruAreaFieldNames->size()) 551 { 552 std::cerr 553 << "Mandatory fields absent in FRU area " 554 << getFruAreaName(area) << " after " << name << "\n"; 555 ret = resCodes::resWarn; 556 } 557 } 558 } while (state == DecodeState::ok); 559 for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++) 560 { 561 uint8_t c = *fruBytesIter; 562 if (c != 0U) 563 { 564 std::cerr << "Non-zero byte after EndOfFields in FRU area " 565 << getFruAreaName(area) << "\n"; 566 ret = resCodes::resWarn; 567 break; 568 } 569 } 570 } 571 572 /* Parsing the Multirecord UUID */ 573 parseMultirecordUUID(fruBytes, result); 574 575 return ret; 576 } 577 578 // Calculate new checksum for fru info area 579 uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter, 580 std::vector<uint8_t>::const_iterator end) 581 { 582 constexpr int checksumMod = 256; 583 uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0)); 584 return (checksumMod - sum) % checksumMod; 585 } 586 587 uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData) 588 { 589 return calculateChecksum(fruAreaData.begin(), fruAreaData.end()); 590 } 591 592 // Update new fru area length & 593 // Update checksum at new checksum location 594 // Return the offset of the area checksum byte 595 unsigned int updateFRUAreaLenAndChecksum( 596 std::vector<uint8_t>& fruData, size_t fruAreaStart, 597 size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset) 598 { 599 size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart; 600 601 // fill zeros for any remaining unused space 602 std::fill(fruData.begin() + fruAreaEndOfFieldsOffset, 603 fruData.begin() + fruAreaEndOffset, 0); 604 605 size_t mod = traverseFRUAreaIndex % fruBlockSize; 606 size_t checksumLoc = 0; 607 if (mod == 0U) 608 { 609 traverseFRUAreaIndex += (fruBlockSize); 610 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1); 611 } 612 else 613 { 614 traverseFRUAreaIndex += (fruBlockSize - mod); 615 checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1); 616 } 617 618 size_t newFRUAreaLen = 619 (traverseFRUAreaIndex / fruBlockSize) + 620 static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0); 621 size_t fruAreaLengthLoc = fruAreaStart + 1; 622 fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen); 623 624 // Calculate new checksum 625 std::vector<uint8_t> finalFRUData; 626 std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart, 627 std::back_inserter(finalFRUData)); 628 629 fruData[checksumLoc] = calculateChecksum(finalFRUData); 630 return checksumLoc; 631 } 632 633 ssize_t getFieldLength(uint8_t fruFieldTypeLenValue) 634 { 635 constexpr uint8_t typeLenMask = 0x3F; 636 constexpr uint8_t endOfFields = 0xC1; 637 if (fruFieldTypeLenValue == endOfFields) 638 { 639 return -1; 640 } 641 return fruFieldTypeLenValue & typeLenMask; 642 } 643 644 bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData) 645 { 646 // ipmi spec format version number is currently at 1, verify it 647 if (blockData[0] != fruVersion) 648 { 649 if (debug) 650 { 651 std::cerr << "FRU spec version " << (int)(blockData[0]) 652 << " not supported. Supported version is " 653 << (int)(fruVersion) << "\n"; 654 } 655 return false; 656 } 657 658 // verify pad is set to 0 659 if (blockData[6] != 0x0) 660 { 661 if (debug) 662 { 663 std::cerr << "PAD value in header is non zero, value is " 664 << (int)(blockData[6]) << "\n"; 665 } 666 return false; 667 } 668 669 // verify offsets are 0, or don't point to another offset 670 std::set<uint8_t> foundOffsets; 671 for (int ii = 1; ii < 6; ii++) 672 { 673 if (blockData[ii] == 0) 674 { 675 continue; 676 } 677 auto inserted = foundOffsets.insert(blockData[ii]); 678 if (!inserted.second) 679 { 680 return false; 681 } 682 } 683 684 // validate checksum 685 size_t sum = 0; 686 for (int jj = 0; jj < 7; jj++) 687 { 688 sum += blockData[jj]; 689 } 690 sum = (256 - sum) & 0xFF; 691 692 if (sum != blockData[7]) 693 { 694 if (debug) 695 { 696 std::cerr << "Checksum " << (int)(blockData[7]) 697 << " is invalid. calculated checksum is " << (int)(sum) 698 << "\n"; 699 } 700 return false; 701 } 702 return true; 703 } 704 705 bool findFRUHeader(FRUReader& reader, const std::string& errorHelp, 706 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData, 707 off_t& baseOffset) 708 { 709 if (reader.read(baseOffset, 0x8, blockData.data()) < 0) 710 { 711 std::cerr << "failed to read " << errorHelp << " base offset " 712 << baseOffset << "\n"; 713 return false; 714 } 715 716 // check the header checksum 717 if (validateHeader(blockData)) 718 { 719 return true; 720 } 721 722 // only continue the search if we just looked at 0x0. 723 if (baseOffset != 0) 724 { 725 return false; 726 } 727 728 // now check for special cases where the IPMI data is at an offset 729 730 // check if blockData starts with tyanHeader 731 const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'}; 732 if (blockData.size() >= tyanHeader.size() && 733 std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin())) 734 { 735 // look for the FRU header at offset 0x6000 736 baseOffset = 0x6000; 737 return findFRUHeader(reader, errorHelp, blockData, baseOffset); 738 } 739 740 if (debug) 741 { 742 std::cerr << "Illegal header " << errorHelp << " base offset " 743 << baseOffset << "\n"; 744 } 745 746 return false; 747 } 748 749 std::pair<std::vector<uint8_t>, bool> 750 readFRUContents(FRUReader& reader, const std::string& errorHelp) 751 { 752 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{}; 753 off_t baseOffset = 0x0; 754 755 if (!findFRUHeader(reader, errorHelp, blockData, baseOffset)) 756 { 757 return {{}, false}; 758 } 759 760 std::vector<uint8_t> device; 761 device.insert(device.end(), blockData.begin(), blockData.begin() + 8); 762 763 bool hasMultiRecords = false; 764 size_t fruLength = fruBlockSize; // At least FRU header is present 765 unsigned int prevOffset = 0; 766 for (fruAreas area = fruAreas::fruAreaInternal; 767 area <= fruAreas::fruAreaMultirecord; ++area) 768 { 769 // Offset value can be 255. 770 unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)]; 771 if (areaOffset == 0) 772 { 773 continue; 774 } 775 776 /* Check for offset order, as per Section 17 of FRU specification, FRU 777 * information areas are required to be in order in FRU data layout 778 * which means all offset value should be in increasing order or can be 779 * 0 if that area is not present 780 */ 781 if (areaOffset <= prevOffset) 782 { 783 std::cerr << "Fru area offsets are not in required order as per " 784 "Section 17 of Fru specification\n"; 785 return {{}, true}; 786 } 787 prevOffset = areaOffset; 788 789 // MultiRecords are different. area is not tracking section, it's 790 // walking the common header. 791 if (area == fruAreas::fruAreaMultirecord) 792 { 793 hasMultiRecords = true; 794 break; 795 } 796 797 areaOffset *= fruBlockSize; 798 799 if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0) 800 { 801 std::cerr << "failed to read " << errorHelp << " base offset " 802 << baseOffset << "\n"; 803 return {{}, true}; 804 } 805 806 // Ignore data type (blockData is already unsigned). 807 size_t length = blockData[1] * fruBlockSize; 808 areaOffset += length; 809 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength; 810 } 811 812 if (hasMultiRecords) 813 { 814 // device[area count] is the index to the last area because the 0th 815 // entry is not an offset in the common header. 816 unsigned int areaOffset = 817 device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)]; 818 areaOffset *= fruBlockSize; 819 820 // the multi-area record header is 5 bytes long. 821 constexpr size_t multiRecordHeaderSize = 5; 822 constexpr uint8_t multiRecordEndOfListMask = 0x80; 823 824 // Sanity hard-limit to 64KB. 825 while (areaOffset < std::numeric_limits<uint16_t>::max()) 826 { 827 // In multi-area, the area offset points to the 0th record, each 828 // record has 3 bytes of the header we care about. 829 if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0) 830 { 831 std::cerr << "failed to read " << errorHelp << " base offset " 832 << baseOffset << "\n"; 833 return {{}, true}; 834 } 835 836 // Ok, let's check the record length, which is in bytes (unsigned, 837 // up to 255, so blockData should hold uint8_t not char) 838 size_t recordLength = blockData[2]; 839 areaOffset += (recordLength + multiRecordHeaderSize); 840 fruLength = (areaOffset > fruLength) ? areaOffset : fruLength; 841 842 // If this is the end of the list bail. 843 if ((blockData[1] & multiRecordEndOfListMask) != 0) 844 { 845 break; 846 } 847 } 848 } 849 850 // You already copied these first 8 bytes (the ipmi fru header size) 851 fruLength -= std::min(fruBlockSize, fruLength); 852 853 int readOffset = fruBlockSize; 854 855 while (fruLength > 0) 856 { 857 size_t requestLength = 858 std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength); 859 860 if (reader.read(baseOffset + readOffset, requestLength, 861 blockData.data()) < 0) 862 { 863 std::cerr << "failed to read " << errorHelp << " base offset " 864 << baseOffset << "\n"; 865 return {{}, true}; 866 } 867 868 device.insert(device.end(), blockData.begin(), 869 blockData.begin() + requestLength); 870 871 readOffset += requestLength; 872 fruLength -= std::min(requestLength, fruLength); 873 } 874 875 return {device, true}; 876 } 877 878 unsigned int getHeaderAreaFieldOffset(fruAreas area) 879 { 880 return static_cast<unsigned int>(area) + 1; 881 } 882 883 std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address) 884 { 885 auto deviceMap = busMap.find(bus); 886 if (deviceMap == busMap.end()) 887 { 888 throw std::invalid_argument("Invalid Bus."); 889 } 890 auto device = deviceMap->second->find(address); 891 if (device == deviceMap->second->end()) 892 { 893 throw std::invalid_argument("Invalid Address."); 894 } 895 std::vector<uint8_t>& ret = device->second; 896 897 return ret; 898 } 899 900 // Iterate FruArea Names and find start and size of the fru area that contains 901 // the propertyName and the field start location for the property. fruAreaParams 902 // struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets 903 // updated/returned if successful. 904 905 bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData, 906 const std::string& propertyName, 907 struct FruArea& fruAreaParams) 908 { 909 const std::vector<std::string>* fruAreaFieldNames = nullptr; 910 911 uint8_t fruAreaOffsetFieldValue = 0; 912 size_t offset = 0; 913 std::string areaName = propertyName.substr(0, propertyName.find('_')); 914 std::string propertyNamePrefix = areaName + "_"; 915 auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName); 916 if (it == fruAreaNames.end()) 917 { 918 std::cerr << "Can't parse area name for property " << propertyName 919 << " \n"; 920 return false; 921 } 922 fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin()); 923 fruAreaOffsetFieldValue = 924 fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)]; 925 switch (fruAreaToUpdate) 926 { 927 case fruAreas::fruAreaChassis: 928 offset = 3; // chassis part number offset. Skip fixed first 3 bytes 929 fruAreaFieldNames = &chassisFruAreas; 930 break; 931 case fruAreas::fruAreaBoard: 932 offset = 6; // board manufacturer offset. Skip fixed first 6 bytes 933 fruAreaFieldNames = &boardFruAreas; 934 break; 935 case fruAreas::fruAreaProduct: 936 // Manufacturer name offset. Skip fixed first 3 product fru bytes 937 // i.e. version, area length and language code 938 offset = 3; 939 fruAreaFieldNames = &productFruAreas; 940 break; 941 default: 942 std::cerr << "Invalid PropertyName " << propertyName << " \n"; 943 return false; 944 } 945 if (fruAreaOffsetFieldValue == 0) 946 { 947 std::cerr << "FRU Area for " << propertyName << " not present \n"; 948 return false; 949 } 950 951 fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize; 952 fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize; 953 fruAreaParams.end = fruAreaParams.start + fruAreaParams.size; 954 size_t fruDataIter = fruAreaParams.start + offset; 955 size_t skipToFRUUpdateField = 0; 956 ssize_t fieldLength = 0; 957 958 bool found = false; 959 for (const auto& field : *fruAreaFieldNames) 960 { 961 skipToFRUUpdateField++; 962 if (propertyName == propertyNamePrefix + field) 963 { 964 found = true; 965 break; 966 } 967 } 968 if (!found) 969 { 970 std::size_t pos = propertyName.find(fruCustomFieldName); 971 if (pos == std::string::npos) 972 { 973 std::cerr << "PropertyName doesn't exist in FRU Area Vectors: " 974 << propertyName << "\n"; 975 return false; 976 } 977 std::string fieldNumStr = 978 propertyName.substr(pos + fruCustomFieldName.length()); 979 size_t fieldNum = std::stoi(fieldNumStr); 980 if (fieldNum == 0) 981 { 982 std::cerr << "PropertyName not recognized: " << propertyName 983 << "\n"; 984 return false; 985 } 986 skipToFRUUpdateField += fieldNum; 987 } 988 989 for (size_t i = 1; i < skipToFRUUpdateField; i++) 990 { 991 if (fruDataIter < fruData.size()) 992 { 993 fieldLength = getFieldLength(fruData[fruDataIter]); 994 995 if (fieldLength < 0) 996 { 997 break; 998 } 999 fruDataIter += 1 + fieldLength; 1000 } 1001 } 1002 fruAreaParams.updateFieldLoc = fruDataIter; 1003 1004 return true; 1005 } 1006 1007 // Copy the FRU Area fields and properties into restFRUAreaFieldsData vector. 1008 // Return true for success and false for failure. 1009 1010 bool copyRestFRUArea(std::vector<uint8_t>& fruData, 1011 const std::string& propertyName, 1012 struct FruArea& fruAreaParams, 1013 std::vector<uint8_t>& restFRUAreaFieldsData) 1014 { 1015 size_t fieldLoc = fruAreaParams.updateFieldLoc; 1016 size_t start = fruAreaParams.start; 1017 size_t fruAreaSize = fruAreaParams.size; 1018 1019 // Push post update fru field bytes to a vector 1020 ssize_t fieldLength = getFieldLength(fruData[fieldLoc]); 1021 if (fieldLength < 0) 1022 { 1023 std::cerr << "Property " << propertyName << " not present \n"; 1024 return false; 1025 } 1026 1027 size_t fruDataIter = 0; 1028 fruDataIter = fieldLoc; 1029 fruDataIter += 1 + fieldLength; 1030 size_t restFRUFieldsLoc = fruDataIter; 1031 size_t endOfFieldsLoc = 0; 1032 1033 if (fruDataIter < fruData.size()) 1034 { 1035 while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0) 1036 { 1037 if (fruDataIter >= (start + fruAreaSize)) 1038 { 1039 fruDataIter = start + fruAreaSize; 1040 break; 1041 } 1042 fruDataIter += 1 + fieldLength; 1043 } 1044 endOfFieldsLoc = fruDataIter; 1045 } 1046 1047 std::copy_n(fruData.begin() + restFRUFieldsLoc, 1048 endOfFieldsLoc - restFRUFieldsLoc + 1, 1049 std::back_inserter(restFRUAreaFieldsData)); 1050 1051 fruAreaParams.restFieldsLoc = restFRUFieldsLoc; 1052 fruAreaParams.restFieldsEnd = endOfFieldsLoc; 1053 1054 return true; 1055 } 1056 1057 // Get all device dbus path and match path with product name using 1058 // regular expression and find the device index for all devices. 1059 1060 std::optional<int> findIndexForFRU( 1061 boost::container::flat_map< 1062 std::pair<size_t, size_t>, 1063 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap, 1064 std::string& productName) 1065 { 1066 int highest = -1; 1067 bool found = false; 1068 1069 for (const auto& busIface : dbusInterfaceMap) 1070 { 1071 std::string path = busIface.second->get_object_path(); 1072 if (std::regex_match(path, std::regex(productName + "(_\\d+|)$"))) 1073 { 1074 // Check if the match named has extra information. 1075 found = true; 1076 std::smatch baseMatch; 1077 1078 bool match = std::regex_match(path, baseMatch, 1079 std::regex(productName + "_(\\d+)$")); 1080 if (match) 1081 { 1082 if (baseMatch.size() == 2) 1083 { 1084 std::ssub_match baseSubMatch = baseMatch[1]; 1085 std::string base = baseSubMatch.str(); 1086 1087 int value = std::stoi(base); 1088 highest = (value > highest) ? value : highest; 1089 } 1090 } 1091 } 1092 } // end searching objects 1093 1094 if (!found) 1095 { 1096 return std::nullopt; 1097 } 1098 return highest; 1099 } 1100 1101 // This function does format fru data as per IPMI format and find the 1102 // productName in the formatted fru data, get that productName and return 1103 // productName if found or return NULL. 1104 1105 std::optional<std::string> getProductName( 1106 std::vector<uint8_t>& device, 1107 boost::container::flat_map<std::string, std::string>& formattedFRU, 1108 uint32_t bus, uint32_t address, size_t& unknownBusObjectCount) 1109 { 1110 std::string productName; 1111 1112 resCodes res = formatIPMIFRU(device, formattedFRU); 1113 if (res == resCodes::resErr) 1114 { 1115 std::cerr << "failed to parse FRU for device at bus " << bus 1116 << " address " << address << "\n"; 1117 return std::nullopt; 1118 } 1119 if (res == resCodes::resWarn) 1120 { 1121 std::cerr << "Warnings while parsing FRU for device at bus " << bus 1122 << " address " << address << "\n"; 1123 } 1124 1125 auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME"); 1126 // Not found under Board section or an empty string. 1127 if (productNameFind == formattedFRU.end() || 1128 productNameFind->second.empty()) 1129 { 1130 productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME"); 1131 } 1132 // Found under Product section and not an empty string. 1133 if (productNameFind != formattedFRU.end() && 1134 !productNameFind->second.empty()) 1135 { 1136 productName = productNameFind->second; 1137 std::regex illegalObject("[^A-Za-z0-9_]"); 1138 productName = std::regex_replace(productName, illegalObject, "_"); 1139 } 1140 else 1141 { 1142 productName = "UNKNOWN" + std::to_string(unknownBusObjectCount); 1143 unknownBusObjectCount++; 1144 } 1145 return productName; 1146 } 1147 1148 bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address) 1149 { 1150 try 1151 { 1152 fruData = getFRUInfo(static_cast<uint16_t>(bus), 1153 static_cast<uint8_t>(address)); 1154 } 1155 catch (const std::invalid_argument& e) 1156 { 1157 std::cerr << "Failure getting FRU Info" << e.what() << "\n"; 1158 return false; 1159 } 1160 1161 return !fruData.empty(); 1162 } 1163