blob: 25960fc7fa49f4ba8b042e8712b30185eed488f9 [file] [log] [blame]
SunnySrivastava198443306542020-04-01 02:50:20 -05001#include "config.h"
2
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -05003#include "ibm_vpd_utils.hpp"
Patrick Venturec83c4dc2018-11-01 16:29:18 -07004
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -05005#include "common_utility.hpp"
SunnySrivastava1984d076da82020-03-05 05:33:35 -06006#include "defines.hpp"
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +05307#include "vpd_exceptions.hpp"
SunnySrivastava1984d076da82020-03-05 05:33:35 -06008
Alpana Kumari6bd095f2022-02-23 10:20:20 -06009#include <boost/algorithm/string.hpp>
PriyangaRamasamyc2fe40f2021-03-02 06:27:33 -060010#include <filesystem>
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +053011#include <fstream>
Alpana Kumari735dee92022-03-25 01:24:40 -050012#include <gpiod.hpp>
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +053013#include <iomanip>
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -050014#include <nlohmann/json.hpp>
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050015#include <phosphor-logging/elog-errors.hpp>
Patrick Venturec83c4dc2018-11-01 16:29:18 -070016#include <phosphor-logging/log.hpp>
PriyangaRamasamy647868e2020-09-08 17:03:19 +053017#include <regex>
Patrick Venturec83c4dc2018-11-01 16:29:18 -070018#include <sdbusplus/server.hpp>
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +053019#include <sstream>
20#include <vector>
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050021#include <xyz/openbmc_project/Common/error.hpp>
Deepak Kodihalli76794492017-02-16 23:48:18 -060022
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +053023using json = nlohmann::json;
24
Deepak Kodihalli76794492017-02-16 23:48:18 -060025namespace openpower
26{
27namespace vpd
28{
SunnySrivastava1984945a02d2020-05-06 01:55:41 -050029using namespace openpower::vpd::constants;
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -050030using namespace inventory;
31using namespace phosphor::logging;
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050032using namespace sdbusplus::xyz::openbmc_project::Common::Error;
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +053033using namespace record;
34using namespace openpower::vpd::exceptions;
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -050035using namespace common::utility;
Sunny Srivastava0746eee2021-03-22 13:36:54 -050036using Severity = openpower::vpd::constants::PelSeverity;
PriyangaRamasamyc2fe40f2021-03-02 06:27:33 -060037namespace fs = std::filesystem;
Sunny Srivastava0746eee2021-03-22 13:36:54 -050038
39// mapping of severity enum to severity interface
40static std::unordered_map<Severity, std::string> sevMap = {
41 {Severity::INFORMATIONAL,
42 "xyz.openbmc_project.Logging.Entry.Level.Informational"},
43 {Severity::DEBUG, "xyz.openbmc_project.Logging.Entry.Level.Debug"},
44 {Severity::NOTICE, "xyz.openbmc_project.Logging.Entry.Level.Notice"},
45 {Severity::WARNING, "xyz.openbmc_project.Logging.Entry.Level.Warning"},
46 {Severity::CRITICAL, "xyz.openbmc_project.Logging.Entry.Level.Critical"},
47 {Severity::EMERGENCY, "xyz.openbmc_project.Logging.Entry.Level.Emergency"},
48 {Severity::ERROR, "xyz.openbmc_project.Logging.Entry.Level.Error"},
49 {Severity::ALERT, "xyz.openbmc_project.Logging.Entry.Level.Alert"}};
50
Deepak Kodihalli76794492017-02-16 23:48:18 -060051namespace inventory
52{
53
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050054MapperResponse
55 getObjectSubtreeForInterfaces(const std::string& root, const int32_t depth,
56 const std::vector<std::string>& interfaces)
57{
58 auto bus = sdbusplus::bus::new_default();
59 auto mapperCall = bus.new_method_call(mapperDestination, mapperObjectPath,
60 mapperInterface, "GetSubTree");
61 mapperCall.append(root);
62 mapperCall.append(depth);
63 mapperCall.append(interfaces);
64
65 MapperResponse result = {};
66
67 try
68 {
69 auto response = bus.call(mapperCall);
70
71 response.read(result);
72 }
Patrick Williams8be43342021-09-02 09:33:36 -050073 catch (const sdbusplus::exception::exception& e)
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050074 {
75 log<level::ERR>("Error in mapper GetSubTree",
76 entry("ERROR=%s", e.what()));
77 }
78
79 return result;
80}
81
Deepak Kodihalli76794492017-02-16 23:48:18 -060082} // namespace inventory
83
SunnySrivastava1984f6d541e2020-02-04 12:50:40 -060084LE2ByteData readUInt16LE(Binary::const_iterator iterator)
85{
86 LE2ByteData lowByte = *iterator;
87 LE2ByteData highByte = *(iterator + 1);
88 lowByte |= (highByte << 8);
89 return lowByte;
90}
91
SunnySrivastava1984d076da82020-03-05 05:33:35 -060092/** @brief Encodes a keyword for D-Bus.
93 */
94string encodeKeyword(const string& kw, const string& encoding)
95{
96 if (encoding == "MAC")
97 {
98 string res{};
99 size_t first = kw[0];
100 res += toHex(first >> 4);
101 res += toHex(first & 0x0f);
102 for (size_t i = 1; i < kw.size(); ++i)
103 {
104 res += ":";
105 res += toHex(kw[i] >> 4);
106 res += toHex(kw[i] & 0x0f);
107 }
108 return res;
109 }
110 else if (encoding == "DATE")
111 {
112 // Date, represent as
113 // <year>-<month>-<day> <hour>:<min>
114 string res{};
115 static constexpr uint8_t skipPrefix = 3;
116
117 auto strItr = kw.begin();
118 advance(strItr, skipPrefix);
119 for_each(strItr, kw.end(), [&res](size_t c) { res += c; });
120
121 res.insert(BD_YEAR_END, 1, '-');
122 res.insert(BD_MONTH_END, 1, '-');
123 res.insert(BD_DAY_END, 1, ' ');
124 res.insert(BD_HOUR_END, 1, ':');
125
126 return res;
127 }
128 else // default to string encoding
129 {
130 return string(kw.begin(), kw.end());
131 }
132}
SunnySrivastava198443306542020-04-01 02:50:20 -0500133
134string readBusProperty(const string& obj, const string& inf, const string& prop)
135{
136 std::string propVal{};
137 std::string object = INVENTORY_PATH + obj;
138 auto bus = sdbusplus::bus::new_default();
139 auto properties = bus.new_method_call(
140 "xyz.openbmc_project.Inventory.Manager", object.c_str(),
141 "org.freedesktop.DBus.Properties", "Get");
142 properties.append(inf);
143 properties.append(prop);
144 auto result = bus.call(properties);
145 if (!result.is_method_error())
146 {
SunnySrivastava1984bca5aaa2020-04-21 05:31:04 -0500147 variant<Binary, string> val;
SunnySrivastava198443306542020-04-01 02:50:20 -0500148 result.read(val);
SunnySrivastava198443306542020-04-01 02:50:20 -0500149 if (auto pVal = get_if<Binary>(&val))
150 {
151 propVal.assign(reinterpret_cast<const char*>(pVal->data()),
152 pVal->size());
153 }
SunnySrivastava1984bca5aaa2020-04-21 05:31:04 -0500154 else if (auto pVal = get_if<string>(&val))
155 {
156 propVal.assign(pVal->data(), pVal->size());
157 }
SunnySrivastava198443306542020-04-01 02:50:20 -0500158 }
159 return propVal;
160}
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500161
162void createPEL(const std::map<std::string, std::string>& additionalData,
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500163 const Severity& sev, const std::string& errIntf)
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500164{
165 try
166 {
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500167 std::string pelSeverity =
168 "xyz.openbmc_project.Logging.Entry.Level.Error";
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500169 auto bus = sdbusplus::bus::new_default();
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500170 auto service = getService(bus, loggerObjectPath, loggerCreateInterface);
171 auto method = bus.new_method_call(service.c_str(), loggerObjectPath,
172 loggerCreateInterface, "Create");
173
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500174 auto itr = sevMap.find(sev);
175 if (itr != sevMap.end())
176 {
177 pelSeverity = itr->second;
178 }
179
180 method.append(errIntf, pelSeverity, additionalData);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500181 auto resp = bus.call(method);
182 }
Patrick Williams8be43342021-09-02 09:33:36 -0500183 catch (const sdbusplus::exception::exception& e)
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500184 {
185 throw std::runtime_error(
186 "Error in invoking D-Bus logging create interface to register PEL");
187 }
188}
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +0530189
190inventory::VPDfilepath getVpdFilePath(const string& jsonFile,
191 const std::string& ObjPath)
192{
193 ifstream inventoryJson(jsonFile);
194 const auto& jsonObject = json::parse(inventoryJson);
195 inventory::VPDfilepath filePath{};
196
197 if (jsonObject.find("frus") == jsonObject.end())
198 {
199 throw(VpdJsonException(
200 "Invalid JSON structure - frus{} object not found in ", jsonFile));
201 }
202
203 const nlohmann::json& groupFRUS =
204 jsonObject["frus"].get_ref<const nlohmann::json::object_t&>();
205 for (const auto& itemFRUS : groupFRUS.items())
206 {
207 const std::vector<nlohmann::json>& groupEEPROM =
208 itemFRUS.value().get_ref<const nlohmann::json::array_t&>();
209 for (const auto& itemEEPROM : groupEEPROM)
210 {
211 if (itemEEPROM["inventoryPath"]
212 .get_ref<const nlohmann::json::string_t&>() == ObjPath)
213 {
214 filePath = itemFRUS.key();
215 return filePath;
216 }
217 }
218 }
219
220 return filePath;
221}
222
223bool isPathInJson(const std::string& eepromPath)
224{
225 bool present = false;
226 ifstream inventoryJson(INVENTORY_JSON_SYM_LINK);
227
228 try
229 {
230 auto js = json::parse(inventoryJson);
231 if (js.find("frus") == js.end())
232 {
233 throw(VpdJsonException(
234 "Invalid JSON structure - frus{} object not found in ",
235 INVENTORY_JSON_SYM_LINK));
236 }
237 json fruJson = js["frus"];
238
239 if (fruJson.find(eepromPath) != fruJson.end())
240 {
241 present = true;
242 }
243 }
Patrick Williams8e15b932021-10-06 13:04:22 -0500244 catch (const json::parse_error& ex)
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +0530245 {
246 throw(VpdJsonException("Json Parsing failed", INVENTORY_JSON_SYM_LINK));
247 }
248 return present;
249}
250
251bool isRecKwInDbusJson(const std::string& recordName,
252 const std::string& keyword)
253{
254 ifstream propertyJson(DBUS_PROP_JSON);
255 json dbusProperty;
256 bool present = false;
257
258 if (propertyJson.is_open())
259 {
260 try
261 {
262 auto dbusPropertyJson = json::parse(propertyJson);
263 if (dbusPropertyJson.find("dbusProperties") ==
264 dbusPropertyJson.end())
265 {
266 throw(VpdJsonException("dbusProperties{} object not found in "
267 "DbusProperties json : ",
268 DBUS_PROP_JSON));
269 }
270
271 dbusProperty = dbusPropertyJson["dbusProperties"];
272 if (dbusProperty.contains(recordName))
273 {
274 const vector<string>& kwdsToPublish = dbusProperty[recordName];
275 if (find(kwdsToPublish.begin(), kwdsToPublish.end(), keyword) !=
276 kwdsToPublish.end()) // present
277 {
278 present = true;
279 }
280 }
281 }
Patrick Williams8e15b932021-10-06 13:04:22 -0500282 catch (const json::parse_error& ex)
PriyangaRamasamyc0a534f2020-08-24 21:29:18 +0530283 {
284 throw(VpdJsonException("Json Parsing failed", DBUS_PROP_JSON));
285 }
286 }
287 else
288 {
289 // If dbus properties json is not available, we assume the given
290 // record-keyword is part of dbus-properties json. So setting the bool
291 // variable to true.
292 present = true;
293 }
294 return present;
295}
296
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -0500297vpdType vpdTypeCheck(const Binary& vpdVector)
298{
299 // Read first 3 Bytes to check the 11S bar code format
300 std::string is11SFormat = "";
301 for (uint8_t i = 0; i < FORMAT_11S_LEN; i++)
302 {
303 is11SFormat += vpdVector[MEMORY_VPD_DATA_START + i];
304 }
305
306 if (vpdVector[IPZ_DATA_START] == KW_VAL_PAIR_START_TAG)
307 {
308 // IPZ VPD FORMAT
309 return vpdType::IPZ_VPD;
310 }
311 else if (vpdVector[KW_VPD_DATA_START] == KW_VPD_START_TAG)
312 {
313 // KEYWORD VPD FORMAT
314 return vpdType::KEYWORD_VPD;
315 }
316 else if (is11SFormat.compare(MEMORY_VPD_START_TAG) == 0)
317 {
318 // Memory VPD format
319 return vpdType::MEMORY_VPD;
320 }
321
322 // INVALID VPD FORMAT
323 return vpdType::INVALID_VPD_FORMAT;
324}
325
Alpana Kumarif05effd2021-04-07 07:32:53 -0500326const string getIM(const Parsed& vpdMap)
327{
328 Binary imVal;
329 auto property = vpdMap.find("VSBP");
330 if (property != vpdMap.end())
331 {
332 auto kw = (property->second).find("IM");
333 if (kw != (property->second).end())
334 {
335 copy(kw->second.begin(), kw->second.end(), back_inserter(imVal));
336 }
337 }
338
339 ostringstream oss;
340 for (auto& i : imVal)
341 {
342 oss << setw(2) << setfill('0') << hex << static_cast<int>(i);
343 }
344
345 return oss.str();
346}
347
348const string getHW(const Parsed& vpdMap)
349{
350 Binary hwVal;
351 auto prop = vpdMap.find("VINI");
352 if (prop != vpdMap.end())
353 {
354 auto kw = (prop->second).find("HW");
355 if (kw != (prop->second).end())
356 {
357 copy(kw->second.begin(), kw->second.end(), back_inserter(hwVal));
358 }
359 }
360
Alpana Kumari88d2ae82021-11-10 03:23:31 -0600361 // The planar pass only comes from the LSB of the HW keyword,
362 // where as the MSB is used for other purposes such as signifying clock
363 // termination.
364 hwVal[0] = 0x00;
365
Alpana Kumarif05effd2021-04-07 07:32:53 -0500366 ostringstream hwString;
367 for (auto& i : hwVal)
368 {
369 hwString << setw(2) << setfill('0') << hex << static_cast<int>(i);
370 }
371
372 return hwString.str();
373}
374
375string getSystemsJson(const Parsed& vpdMap)
376{
377 string jsonPath = "/usr/share/vpd/";
378 string jsonName{};
379
380 ifstream systemJson(SYSTEM_JSON);
381 if (!systemJson)
382 {
383 throw((VpdJsonException("Failed to access Json path", SYSTEM_JSON)));
384 }
385
386 try
387 {
388 auto js = json::parse(systemJson);
389
390 const string hwKeyword = getHW(vpdMap);
391 const string imKeyword = getIM(vpdMap);
392
393 if (js.find("system") == js.end())
394 {
395 throw runtime_error("Invalid systems Json");
396 }
397
398 if (js["system"].find(imKeyword) == js["system"].end())
399 {
400 throw runtime_error(
401 "Invalid system. This system type is not present "
402 "in the systemsJson. IM: " +
403 imKeyword);
404 }
405
406 if ((js["system"][imKeyword].find("constraint") !=
407 js["system"][imKeyword].end()) &&
408 (hwKeyword == js["system"][imKeyword]["constraint"]["HW"]))
409 {
410 jsonName = js["system"][imKeyword]["constraint"]["json"];
411 }
412 else if (js["system"][imKeyword].find("default") !=
413 js["system"][imKeyword].end())
414 {
415 jsonName = js["system"][imKeyword]["default"];
416 }
417 else
418 {
419 throw runtime_error(
420 "Bad System json. Neither constraint nor default found");
421 }
422
423 jsonPath += jsonName;
424 }
425
Patrick Williams8e15b932021-10-06 13:04:22 -0500426 catch (const json::parse_error& ex)
Alpana Kumarif05effd2021-04-07 07:32:53 -0500427 {
428 throw(VpdJsonException("Json Parsing failed", SYSTEM_JSON));
429 }
430 return jsonPath;
431}
432
PriyangaRamasamy647868e2020-09-08 17:03:19 +0530433void udevToGenericPath(string& file)
434{
435 // Sample udevEvent i2c path :
436 // "/sys/devices/platform/ahb/ahb:apb/ahb:apb:bus@1e78a000/1e78a480.i2c-bus/i2c-8/8-0051/8-00510/nvmem"
437 // find if the path contains the word i2c in it.
438 if (file.find("i2c") != string::npos)
439 {
440 string i2cBusAddr{};
441
442 // Every udev i2c path should have the common pattern
443 // "i2c-bus_number/bus_number-vpd_address". Search for
444 // "bus_number-vpd_address".
445 regex i2cPattern("((i2c)-[0-9]+\\/)([0-9]+-[0-9]{4})");
446 smatch match;
447 if (regex_search(file, match, i2cPattern))
448 {
449 i2cBusAddr = match.str(3);
450 }
451 else
452 {
453 cerr << "The given udev path < " << file
454 << " > doesn't match the required pattern. Skipping VPD "
455 "collection."
456 << endl;
457 exit(EXIT_SUCCESS);
458 }
459 // Forming the generic file path
460 file = i2cPathPrefix + i2cBusAddr + "/eeprom";
461 }
462 // Sample udevEvent spi path :
463 // "/sys/devices/platform/ahb/ahb:apb/1e79b000.fsi/fsi-master/fsi0/slave@00:00/00:00:00:04/spi_master/spi2/spi2.0/spi2.00/nvmem"
464 // find if the path contains the word spi in it.
465 else if (file.find("spi") != string::npos)
466 {
467 // Every udev spi path will have common pattern "spi<Digit>/", which
468 // describes the spi bus number at which the fru is connected; Followed
469 // by a slash following the vpd address of the fru. Taking the above
470 // input as a common key, we try to search for the pattern "spi<Digit>/"
471 // using regular expression.
472 regex spiPattern("((spi)[0-9]+)(\\/)");
473 string spiBus{};
474 smatch match;
475 if (regex_search(file, match, spiPattern))
476 {
477 spiBus = match.str(1);
478 }
479 else
480 {
481 cerr << "The given udev path < " << file
482 << " > doesn't match the required pattern. Skipping VPD "
483 "collection."
484 << endl;
485 exit(EXIT_SUCCESS);
486 }
487 // Forming the generic path
488 file = spiPathPrefix + spiBus + ".0/eeprom";
489 }
490 else
491 {
492 cerr << "\n The given EEPROM path < " << file
493 << " > is not valid. It's neither I2C nor "
494 "SPI path. Skipping VPD collection.."
495 << endl;
496 exit(EXIT_SUCCESS);
497 }
498}
PriyangaRamasamyc2fe40f2021-03-02 06:27:33 -0600499string getBadVpdName(const string& file)
500{
501 string badVpd = BAD_VPD_DIR;
502 if (file.find("i2c") != string::npos)
503 {
504 badVpd += "i2c-";
505 regex i2cPattern("(at24/)([0-9]+-[0-9]+)\\/");
506 smatch match;
507 if (regex_search(file, match, i2cPattern))
508 {
509 badVpd += match.str(2);
510 }
511 }
512 else if (file.find("spi") != string::npos)
513 {
514 regex spiPattern("((spi)[0-9]+)(.0)");
515 smatch match;
516 if (regex_search(file, match, spiPattern))
517 {
518 badVpd += match.str(1);
519 }
520 }
521 return badVpd;
522}
523
524void dumpBadVpd(const string& file, const Binary& vpdVector)
525{
526 fs::path badVpdDir = BAD_VPD_DIR;
527 fs::create_directory(badVpdDir);
528 string badVpdPath = getBadVpdName(file);
529 if (fs::exists(badVpdPath))
530 {
531 std::error_code ec;
532 fs::remove(badVpdPath, ec);
533 if (ec) // error code
534 {
535 string error = "Error removing the existing broken vpd in ";
536 error += badVpdPath;
537 error += ". Error code : ";
538 error += ec.value();
539 error += ". Error message : ";
540 error += ec.message();
541 throw runtime_error(error);
542 }
543 }
544 ofstream badVpdFileStream(badVpdPath, ofstream::binary);
545 if (!badVpdFileStream)
546 {
547 throw runtime_error("Failed to open bad vpd file path in /tmp/bad-vpd. "
548 "Unable to dump the broken/bad vpd file.");
549 }
550 badVpdFileStream.write(reinterpret_cast<const char*>(vpdVector.data()),
551 vpdVector.size());
552}
alpana077ce68722021-07-25 13:23:59 -0500553
554const string getKwVal(const Parsed& vpdMap, const string& rec,
555 const string& kwd)
556{
557 string kwVal{};
558
559 auto findRec = vpdMap.find(rec);
560
561 // check if record is found in map we got by parser
562 if (findRec != vpdMap.end())
563 {
564 auto findKwd = findRec->second.find(kwd);
565
566 if (findKwd != findRec->second.end())
567 {
568 kwVal = findKwd->second;
569 }
570 }
571
572 return kwVal;
573}
574
Priyanga Ramasamyc9ecf8e2021-10-08 02:28:52 -0500575string byteArrayToHexString(const Binary& vec)
576{
577 stringstream ss;
578 string hexRep = "0x";
579 ss << hexRep;
580 string str = ss.str();
581
582 // convert Decimal to Hex string
583 for (auto& v : vec)
584 {
585 ss << setfill('0') << setw(2) << hex << (int)v;
586 str = ss.str();
587 }
588 return str;
589}
590
591string getPrintableValue(const Binary& vec)
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500592{
593 string str{};
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500594
Priyanga Ramasamyc9ecf8e2021-10-08 02:28:52 -0500595 // find for a non printable value in the vector
596 const auto it = std::find_if(vec.begin(), vec.end(),
597 [](const auto& ele) { return !isprint(ele); });
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500598
Priyanga Ramasamyc9ecf8e2021-10-08 02:28:52 -0500599 if (it != vec.end()) // if the given vector has any non printable value
600 {
601 for (auto itr = it; itr != vec.end(); itr++)
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500602 {
Priyanga Ramasamyc9ecf8e2021-10-08 02:28:52 -0500603 if (*itr != 0x00)
604 {
605 str = byteArrayToHexString(vec);
606 return str;
607 }
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500608 }
Priyanga Ramasamyc9ecf8e2021-10-08 02:28:52 -0500609 str = string(vec.begin(), it);
Priyanga Ramasamy02434932021-10-07 16:26:05 -0500610 }
611 else
612 {
613 str = string(vec.begin(), vec.end());
614 }
615 return str;
616}
617
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600618/*
619 * @brief Log PEL for GPIO exception
620 *
621 * @param[in] gpioErr gpioError type exception
622 * @param[in] i2cBusAddr I2C bus and address
623 */
624void logGpioPel(const string& gpioErr, const string& i2cBusAddr)
625{
626 // Get the IIC details
627 vector<string> i2cReg;
628 boost::split(i2cReg, i2cBusAddr, boost::is_any_of("-"));
629
630 PelAdditionalData additionalData{};
631 if (i2cReg.size() == 2)
632 {
633 additionalData.emplace("CALLOUT_IIC_BUS", i2cReg[0]);
634 additionalData.emplace("CALLOUT_IIC_ADDR", "0x" + i2cReg[1]);
635 }
636
637 additionalData.emplace("DESCRIPTION", gpioErr);
638 createPEL(additionalData, PelSeverity::WARNING, errIntfForGpioError);
639}
640
Alpana Kumari735dee92022-03-25 01:24:40 -0500641void executePostFailAction(const nlohmann::json& json, const string& file)
642{
643 if ((json["frus"][file].at(0)).find("postActionFail") ==
644 json["frus"][file].at(0).end())
645 {
646 return;
647 }
648
649 uint8_t pinValue = 0;
650 string pinName;
651
652 for (const auto& postAction :
653 (json["frus"][file].at(0))["postActionFail"].items())
654 {
655 if (postAction.key() == "pin")
656 {
657 pinName = postAction.value();
658 }
659 else if (postAction.key() == "value")
660 {
661 // Get the value to set
662 pinValue = postAction.value();
663 }
664 }
665
666 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue << endl;
667
668 try
669 {
670 gpiod::line outputLine = gpiod::find_line(pinName);
671
672 if (!outputLine)
673 {
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600674 throw runtime_error(
675 "Couldn't find output line for the GPIO. Skipping "
676 "this GPIO action.");
Alpana Kumari735dee92022-03-25 01:24:40 -0500677 }
678 outputLine.request(
679 {"Disable line", ::gpiod::line_request::DIRECTION_OUTPUT, 0},
680 pinValue);
681 }
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600682 catch (const exception& e)
Alpana Kumari735dee92022-03-25 01:24:40 -0500683 {
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600684 string i2cBusAddr;
685 string errMsg = e.what();
686 errMsg += "\nGPIO: " + pinName;
687
688 if ((json["frus"][file].at(0)["postActionFail"].find(
689 "gpioI2CAddress")) !=
690 json["frus"][file].at(0)["postActionFail"].end())
691 {
692 i2cBusAddr =
693 json["frus"][file].at(0)["postActionFail"]["gpioI2CAddress"];
694 }
695
696 logGpioPel(errMsg, i2cBusAddr);
Alpana Kumari735dee92022-03-25 01:24:40 -0500697 }
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600698
699 return;
Alpana Kumari735dee92022-03-25 01:24:40 -0500700}
701
Santosh Puranik53b38ed2022-04-10 23:15:22 +0530702std::optional<bool> isPresent(const nlohmann::json& json, const string& file)
703
Alpana Kumari735dee92022-03-25 01:24:40 -0500704{
705 if ((json["frus"][file].at(0)).find("presence") !=
706 json["frus"][file].at(0).end())
707 {
708 if (((json["frus"][file].at(0)["presence"]).find("pin") !=
709 json["frus"][file].at(0)["presence"].end()) &&
710 ((json["frus"][file].at(0)["presence"]).find("value") !=
711 json["frus"][file].at(0)["presence"].end()))
712 {
713 string presPinName = json["frus"][file].at(0)["presence"]["pin"];
714 Byte presPinValue = json["frus"][file].at(0)["presence"]["value"];
715
716 try
717 {
718 gpiod::line presenceLine = gpiod::find_line(presPinName);
719
720 if (!presenceLine)
721 {
Alpana Kumari40d1c192022-03-09 21:16:02 -0600722 cerr << "Couldn't find the presence line for - "
723 << presPinName << endl;
724
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600725 throw runtime_error(
726 "Couldn't find the presence line for the "
727 "GPIO. Skipping this GPIO action.");
Alpana Kumari735dee92022-03-25 01:24:40 -0500728 }
729
730 presenceLine.request({"Read the presence line",
731 gpiod::line_request::DIRECTION_INPUT, 0});
732
733 Byte gpioData = presenceLine.get_value();
734
Santosh Puranik53b38ed2022-04-10 23:15:22 +0530735 return (gpioData == presPinValue);
Alpana Kumari735dee92022-03-25 01:24:40 -0500736 }
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600737 catch (const exception& e)
Alpana Kumari735dee92022-03-25 01:24:40 -0500738 {
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600739 string i2cBusAddr;
740 string errMsg = e.what();
741 errMsg += " GPIO : " + presPinName;
742
743 if ((json["frus"][file].at(0)["presence"])
744 .find("gpioI2CAddress") !=
745 json["frus"][file].at(0)["presence"].end())
746 {
747 i2cBusAddr =
748 json["frus"][file].at(0)["presence"]["gpioI2CAddress"];
749 }
750
751 logGpioPel(errMsg, i2cBusAddr);
Alpana Kumari40d1c192022-03-09 21:16:02 -0600752 // Take failure postAction
753 executePostFailAction(json, file);
Alpana Kumari735dee92022-03-25 01:24:40 -0500754 return false;
755 }
756 }
Alpana Kumari40d1c192022-03-09 21:16:02 -0600757 else
758 {
759 // missing required informations
760 cerr << "VPD inventory JSON missing basic informations of presence "
761 "for this FRU : ["
762 << file << "]. Executing executePostFailAction." << endl;
763
764 // Take failure postAction
765 executePostFailAction(json, file);
766
767 return false;
768 }
Alpana Kumari735dee92022-03-25 01:24:40 -0500769 }
Santosh Puranik53b38ed2022-04-10 23:15:22 +0530770 return std::optional<bool>{};
771}
772
773bool executePreAction(const nlohmann::json& json, const string& file)
774{
775 auto present = isPresent(json, file);
776 if (present && !present.value())
777 {
778 executePostFailAction(json, file);
779 return false;
780 }
Alpana Kumari735dee92022-03-25 01:24:40 -0500781
782 if ((json["frus"][file].at(0)).find("preAction") !=
783 json["frus"][file].at(0).end())
784 {
785 if (((json["frus"][file].at(0)["preAction"]).find("pin") !=
786 json["frus"][file].at(0)["preAction"].end()) &&
787 ((json["frus"][file].at(0)["preAction"]).find("value") !=
788 json["frus"][file].at(0)["preAction"].end()))
789 {
790 string pinName = json["frus"][file].at(0)["preAction"]["pin"];
791 // Get the value to set
792 Byte pinValue = json["frus"][file].at(0)["preAction"]["value"];
793
794 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue
795 << endl;
796 try
797 {
798 gpiod::line outputLine = gpiod::find_line(pinName);
799
800 if (!outputLine)
801 {
Alpana Kumari40d1c192022-03-09 21:16:02 -0600802 cerr << "Couldn't find the line for output pin - "
803 << pinName << endl;
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600804 throw runtime_error(
805 "Couldn't find output line for the GPIO. "
806 "Skipping this GPIO action.");
Alpana Kumari735dee92022-03-25 01:24:40 -0500807 }
808 outputLine.request({"FRU pre-action",
809 ::gpiod::line_request::DIRECTION_OUTPUT, 0},
810 pinValue);
811 }
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600812 catch (const exception& e)
Alpana Kumari735dee92022-03-25 01:24:40 -0500813 {
Alpana Kumari6bd095f2022-02-23 10:20:20 -0600814 string i2cBusAddr;
815 string errMsg = e.what();
816 errMsg += " GPIO : " + pinName;
817
818 if ((json["frus"][file].at(0)["preAction"])
819 .find("gpioI2CAddress") !=
820 json["frus"][file].at(0)["preAction"].end())
821 {
822 i2cBusAddr =
823 json["frus"][file].at(0)["preAction"]["gpioI2CAddress"];
824 }
825
826 logGpioPel(errMsg, i2cBusAddr);
Alpana Kumari40d1c192022-03-09 21:16:02 -0600827
828 // Take failure postAction
829 executePostFailAction(json, file);
830
Alpana Kumari735dee92022-03-25 01:24:40 -0500831 return false;
832 }
833 }
Alpana Kumari40d1c192022-03-09 21:16:02 -0600834 else
835 {
836 // missing required informations
837 cerr
838 << "VPD inventory JSON missing basic informations of preAction "
839 "for this FRU : ["
840 << file << "]. Executing executePostFailAction." << endl;
841
842 // Take failure postAction
843 executePostFailAction(json, file);
844
845 return false;
846 }
Alpana Kumari735dee92022-03-25 01:24:40 -0500847 }
848 return true;
849}
850
Priyanga Ramasamyaa8a8932022-01-27 09:12:41 -0600851void insertOrMerge(inventory::InterfaceMap& map,
852 const inventory::Interface& interface,
853 inventory::PropertyMap&& property)
854{
855 if (map.find(interface) != map.end())
856 {
857 auto& prop = map.at(interface);
858 prop.insert(property.begin(), property.end());
859 }
860 else
861 {
862 map.emplace(interface, property);
863 }
864}
Patrick Venturec83c4dc2018-11-01 16:29:18 -0700865} // namespace vpd
Alpana Kumari735dee92022-03-25 01:24:40 -0500866} // namespace openpower