blob: 237d001c9b4285d77d8c0e7905ae76c4ecee970d [file] [log] [blame]
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301#include "config.h"
2
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -05003#include "common_utility.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05304#include "defines.hpp"
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -05005#include "ibm_vpd_utils.hpp"
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05006#include "ipz_parser.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05307#include "keyword_vpd_parser.hpp"
Alpana Kumaria00936f2020-04-14 07:15:46 -05008#include "memory_vpd_parser.hpp"
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05009#include "parser_factory.hpp"
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -050010#include "vpd_exceptions.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053011
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050012#include <assert.h>
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -050013#include <ctype.h>
14
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053015#include <CLI/CLI.hpp>
Santosh Puranik88edeb62020-03-02 12:00:09 +053016#include <algorithm>
Alpana Kumari65b83602020-09-01 00:24:56 -050017#include <cstdarg>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053018#include <exception>
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +053019#include <filesystem>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053020#include <fstream>
Alpana Kumari2f793042020-08-18 05:51:03 -050021#include <gpiod.hpp>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053022#include <iostream>
23#include <iterator>
24#include <nlohmann/json.hpp>
Andrew Geissler280197e2020-12-08 20:51:49 -060025#include <phosphor-logging/log.hpp>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053026
27using namespace std;
28using namespace openpower::vpd;
29using namespace CLI;
30using namespace vpd::keyword::parser;
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +053031using namespace openpower::vpd::constants;
32namespace fs = filesystem;
33using json = nlohmann::json;
SunnySrivastava1984e12b1812020-05-26 02:23:11 -050034using namespace openpower::vpd::parser::factory;
SunnySrivastava1984945a02d2020-05-06 01:55:41 -050035using namespace openpower::vpd::inventory;
Alpana Kumaria00936f2020-04-14 07:15:46 -050036using namespace openpower::vpd::memory::parser;
SunnySrivastava1984e12b1812020-05-26 02:23:11 -050037using namespace openpower::vpd::parser::interface;
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -050038using namespace openpower::vpd::exceptions;
Andrew Geissler280197e2020-12-08 20:51:49 -060039using namespace phosphor::logging;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053040
Alpana Kumari65b83602020-09-01 00:24:56 -050041static const deviceTreeMap deviceTreeSystemTypeMap = {
Andrew Geissler2fe709f2021-03-25 10:59:07 -050042 {RAINIER_2U, "conf-aspeed-bmc-ibm-rainier.dtb"},
43 {RAINIER_4U, "conf-aspeed-bmc-ibm-rainier-4u.dtb"},
44 {RAINIER_1S4U, "conf-aspeed-bmc-ibm-rainier-1s4u.dtb"},
45 {EVEREST, "conf-aspeed-bmc-ibm-everest.dtb"}};
Alpana Kumari65b83602020-09-01 00:24:56 -050046
Santosh Puranik88edeb62020-03-02 12:00:09 +053047/**
Santosh Puranik85893752020-11-10 21:31:43 +053048 * @brief Returns the power state for chassis0
49 */
50static auto getPowerState()
51{
52 // TODO: How do we handle multiple chassis?
53 string powerState{};
54 auto bus = sdbusplus::bus::new_default();
55 auto properties =
56 bus.new_method_call("xyz.openbmc_project.State.Chassis",
57 "/xyz/openbmc_project/state/chassis0",
58 "org.freedesktop.DBus.Properties", "Get");
59 properties.append("xyz.openbmc_project.State.Chassis");
60 properties.append("CurrentPowerState");
61 auto result = bus.call(properties);
62 if (!result.is_method_error())
63 {
64 variant<string> val;
65 result.read(val);
66 if (auto pVal = get_if<string>(&val))
67 {
68 powerState = *pVal;
69 }
70 }
71 cout << "Power state is: " << powerState << endl;
72 return powerState;
73}
74
75/**
Santosh Puranik88edeb62020-03-02 12:00:09 +053076 * @brief Expands location codes
77 */
78static auto expandLocationCode(const string& unexpanded, const Parsed& vpdMap,
79 bool isSystemVpd)
80{
81 auto expanded{unexpanded};
82 static constexpr auto SYSTEM_OBJECT = "/system/chassis/motherboard";
83 static constexpr auto VCEN_IF = "com.ibm.ipzvpd.VCEN";
84 static constexpr auto VSYS_IF = "com.ibm.ipzvpd.VSYS";
85 size_t idx = expanded.find("fcs");
86 try
87 {
88 if (idx != string::npos)
89 {
90 string fc{};
91 string se{};
92 if (isSystemVpd)
93 {
94 const auto& fcData = vpdMap.at("VCEN").at("FC");
95 const auto& seData = vpdMap.at("VCEN").at("SE");
96 fc = string(fcData.data(), fcData.size());
97 se = string(seData.data(), seData.size());
98 }
99 else
100 {
101 fc = readBusProperty(SYSTEM_OBJECT, VCEN_IF, "FC");
102 se = readBusProperty(SYSTEM_OBJECT, VCEN_IF, "SE");
103 }
104
Alpana Kumari81671f62021-02-10 02:21:59 -0600105 // TODO: See if ND0 can be placed in the JSON
106 expanded.replace(idx, 3, fc.substr(0, 4) + ".ND0." + se);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530107 }
108 else
109 {
110 idx = expanded.find("mts");
111 if (idx != string::npos)
112 {
113 string mt{};
114 string se{};
115 if (isSystemVpd)
116 {
117 const auto& mtData = vpdMap.at("VSYS").at("TM");
118 const auto& seData = vpdMap.at("VSYS").at("SE");
119 mt = string(mtData.data(), mtData.size());
120 se = string(seData.data(), seData.size());
121 }
122 else
123 {
124 mt = readBusProperty(SYSTEM_OBJECT, VSYS_IF, "TM");
125 se = readBusProperty(SYSTEM_OBJECT, VSYS_IF, "SE");
126 }
127
128 replace(mt.begin(), mt.end(), '-', '.');
129 expanded.replace(idx, 3, mt + "." + se);
130 }
131 }
132 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500133 catch (exception& e)
Santosh Puranik88edeb62020-03-02 12:00:09 +0530134 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500135 cerr << "Failed to expand location code with exception: " << e.what()
136 << "\n";
Santosh Puranik88edeb62020-03-02 12:00:09 +0530137 }
138 return expanded;
139}
Alpana Kumari2f793042020-08-18 05:51:03 -0500140
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530141/**
142 * @brief Populate FRU specific interfaces.
143 *
144 * This is a common method which handles both
145 * ipz and keyword specific interfaces thus,
146 * reducing the code redundancy.
147 * @param[in] map - Reference to the innermost keyword-value map.
148 * @param[in] preIntrStr - Reference to the interface string.
149 * @param[out] interfaces - Reference to interface map.
150 */
151template <typename T>
152static void populateFruSpecificInterfaces(const T& map,
153 const string& preIntrStr,
154 inventory::InterfaceMap& interfaces)
155{
156 inventory::PropertyMap prop;
157
158 for (const auto& kwVal : map)
159 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500160 vector<uint8_t> vec(kwVal.second.begin(), kwVal.second.end());
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530161
162 auto kw = kwVal.first;
163
164 if (kw[0] == '#')
165 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500166 kw = string("PD_") + kw[1];
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530167 }
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -0500168 else if (isdigit(kw[0]))
169 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500170 kw = string("N_") + kw;
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -0500171 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530172 prop.emplace(move(kw), move(vec));
173 }
174
175 interfaces.emplace(preIntrStr, move(prop));
176}
177
178/**
179 * @brief Populate Interfaces.
180 *
181 * This method populates common and extra interfaces to dbus.
182 * @param[in] js - json object
183 * @param[out] interfaces - Reference to interface map
184 * @param[in] vpdMap - Reference to the parsed vpd map.
Santosh Puranik88edeb62020-03-02 12:00:09 +0530185 * @param[in] isSystemVpd - Denotes whether we are collecting the system VPD.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530186 */
187template <typename T>
188static void populateInterfaces(const nlohmann::json& js,
189 inventory::InterfaceMap& interfaces,
Santosh Puranik88edeb62020-03-02 12:00:09 +0530190 const T& vpdMap, bool isSystemVpd)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530191{
192 for (const auto& ifs : js.items())
193 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530194 string inf = ifs.key();
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530195 inventory::PropertyMap props;
196
197 for (const auto& itr : ifs.value().items())
198 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530199 const string& busProp = itr.key();
200
Alpana Kumari31970de2020-02-17 06:49:57 -0600201 if (itr.value().is_boolean())
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530202 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530203 props.emplace(busProp, itr.value().get<bool>());
204 }
205 else if (itr.value().is_string())
206 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500207 if constexpr (is_same<T, Parsed>::value)
Santosh Puranik88edeb62020-03-02 12:00:09 +0530208 {
209 if (busProp == "LocationCode" &&
210 inf == "com.ibm.ipzvpd.Location")
211 {
212 auto prop = expandLocationCode(
213 itr.value().get<string>(), vpdMap, isSystemVpd);
214 props.emplace(busProp, prop);
215 }
216 else
217 {
218 props.emplace(busProp, itr.value().get<string>());
219 }
220 }
221 else
222 {
223 props.emplace(busProp, itr.value().get<string>());
224 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530225 }
Alpana Kumari31970de2020-02-17 06:49:57 -0600226 else if (itr.value().is_object())
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530227 {
Alpana Kumari31970de2020-02-17 06:49:57 -0600228 const string& rec = itr.value().value("recordName", "");
229 const string& kw = itr.value().value("keywordName", "");
230 const string& encoding = itr.value().value("encoding", "");
231
Alpana Kumari58e22142020-05-05 00:22:12 -0500232 if constexpr (is_same<T, Parsed>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530233 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530234 if (!rec.empty() && !kw.empty() && vpdMap.count(rec) &&
235 vpdMap.at(rec).count(kw))
Alpana Kumari31970de2020-02-17 06:49:57 -0600236 {
237 auto encoded =
238 encodeKeyword(vpdMap.at(rec).at(kw), encoding);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530239 props.emplace(busProp, encoded);
Alpana Kumari31970de2020-02-17 06:49:57 -0600240 }
241 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500242 else if constexpr (is_same<T, KeywordVpdMap>::value)
Alpana Kumari31970de2020-02-17 06:49:57 -0600243 {
244 if (!kw.empty() && vpdMap.count(kw))
245 {
246 auto prop =
247 string(vpdMap.at(kw).begin(), vpdMap.at(kw).end());
248 auto encoded = encodeKeyword(prop, encoding);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530249 props.emplace(busProp, encoded);
Alpana Kumari31970de2020-02-17 06:49:57 -0600250 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530251 }
252 }
253 }
254 interfaces.emplace(inf, move(props));
255 }
256}
257
Alpana Kumari2f793042020-08-18 05:51:03 -0500258static Binary getVpdDataInVector(const nlohmann::json& js, const string& file)
Alpana Kumari58e22142020-05-05 00:22:12 -0500259{
260 uint32_t offset = 0;
261 // check if offset present?
262 for (const auto& item : js["frus"][file])
263 {
264 if (item.find("offset") != item.end())
265 {
266 offset = item["offset"];
267 }
268 }
269
270 // TODO: Figure out a better way to get max possible VPD size.
271 Binary vpdVector;
272 vpdVector.resize(65504);
273 ifstream vpdFile;
274 vpdFile.open(file, ios::binary);
275
276 vpdFile.seekg(offset, ios_base::cur);
277 vpdFile.read(reinterpret_cast<char*>(&vpdVector[0]), 65504);
278 vpdVector.resize(vpdFile.gcount());
279
280 return vpdVector;
281}
282
Alpana Kumari2f793042020-08-18 05:51:03 -0500283/* It does nothing. Just an empty function to return null
284 * at the end of variadic template args
285 */
286static string getCommand()
287{
288 return "";
289}
290
291/* This function to arrange all arguments to make command
292 */
293template <typename T, typename... Types>
294static string getCommand(T arg1, Types... args)
295{
296 string cmd = " " + arg1 + getCommand(args...);
297
298 return cmd;
299}
300
301/* This API takes arguments and run that command
302 * returns output of that command
303 */
304template <typename T, typename... Types>
305static vector<string> executeCmd(T&& path, Types... args)
306{
307 vector<string> stdOutput;
308 array<char, 128> buffer;
309
310 string cmd = path + getCommand(args...);
311
312 unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
313 if (!pipe)
314 {
315 throw runtime_error("popen() failed!");
316 }
317 while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
318 {
319 stdOutput.emplace_back(buffer.data());
320 }
321
322 return stdOutput;
323}
324
325/** This API will be called at the end of VPD collection to perform any post
326 * actions.
327 *
328 * @param[in] json - json object
329 * @param[in] file - eeprom file path
330 */
331static void postFailAction(const nlohmann::json& json, const string& file)
332{
333 if ((json["frus"][file].at(0)).find("postActionFail") ==
334 json["frus"][file].at(0).end())
335 {
336 return;
337 }
338
339 uint8_t pinValue = 0;
340 string pinName;
341
342 for (const auto& postAction :
343 (json["frus"][file].at(0))["postActionFail"].items())
344 {
345 if (postAction.key() == "pin")
346 {
347 pinName = postAction.value();
348 }
349 else if (postAction.key() == "value")
350 {
351 // Get the value to set
352 pinValue = postAction.value();
353 }
354 }
355
356 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue << endl;
357
358 try
359 {
360 gpiod::line outputLine = gpiod::find_line(pinName);
361
362 if (!outputLine)
363 {
364 cout << "Couldn't find output line:" << pinName
365 << " on GPIO. Skipping...\n";
366
367 return;
368 }
369 outputLine.request(
370 {"Disable line", ::gpiod::line_request::DIRECTION_OUTPUT, 0},
371 pinValue);
372 }
373 catch (system_error&)
374 {
375 cerr << "Failed to set post-action GPIO" << endl;
376 }
377}
378
379/** Performs any pre-action needed to get the FRU setup for collection.
380 *
381 * @param[in] json - json object
382 * @param[in] file - eeprom file path
383 */
384static void preAction(const nlohmann::json& json, const string& file)
385{
386 if ((json["frus"][file].at(0)).find("preAction") ==
387 json["frus"][file].at(0).end())
388 {
389 return;
390 }
391
392 uint8_t pinValue = 0;
393 string pinName;
394
395 for (const auto& postAction :
396 (json["frus"][file].at(0))["preAction"].items())
397 {
398 if (postAction.key() == "pin")
399 {
400 pinName = postAction.value();
401 }
402 else if (postAction.key() == "value")
403 {
404 // Get the value to set
405 pinValue = postAction.value();
406 }
407 }
408
409 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue << endl;
410 try
411 {
412 gpiod::line outputLine = gpiod::find_line(pinName);
413
414 if (!outputLine)
415 {
416 cout << "Couldn't find output line:" << pinName
417 << " on GPIO. Skipping...\n";
418
419 return;
420 }
421 outputLine.request(
422 {"FRU pre-action", ::gpiod::line_request::DIRECTION_OUTPUT, 0},
423 pinValue);
424 }
425 catch (system_error&)
426 {
427 cerr << "Failed to set pre-action GPIO" << endl;
428 return;
429 }
430
431 // Now bind the device
432 string bind = json["frus"][file].at(0).value("bind", "");
433 cout << "Binding device " << bind << endl;
434 string bindCmd = string("echo \"") + bind +
435 string("\" > /sys/bus/i2c/drivers/at24/bind");
436 cout << bindCmd << endl;
437 executeCmd(bindCmd);
438
439 // Check if device showed up (test for file)
440 if (!fs::exists(file))
441 {
442 cout << "EEPROM " << file << " does not exist. Take failure action"
443 << endl;
444 // If not, then take failure postAction
445 postFailAction(json, file);
446 }
447}
448
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530449/**
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530450 * @brief Prime the Inventory
451 * Prime the inventory by populating only the location code,
452 * type interface and the inventory object for the frus
453 * which are not system vpd fru.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530454 *
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530455 * @param[in] jsObject - Reference to vpd inventory json object
456 * @param[in] vpdMap - Reference to the parsed vpd map
457 *
458 * @returns Map of items in extraInterface.
459 */
460template <typename T>
461inventory::ObjectMap primeInventory(const nlohmann::json& jsObject,
462 const T& vpdMap)
463{
464 inventory::ObjectMap objects;
465
466 for (auto& itemFRUS : jsObject["frus"].items())
467 {
Alpana Kumari2f793042020-08-18 05:51:03 -0500468 // Take pre actions
469 preAction(jsObject, itemFRUS.key());
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530470 for (auto& itemEEPROM : itemFRUS.value())
471 {
472 inventory::InterfaceMap interfaces;
473 auto isSystemVpd = itemEEPROM.value("isSystemVpd", false);
474 inventory::Object object(itemEEPROM.at("inventoryPath"));
475
476 if (!isSystemVpd && !itemEEPROM.value("noprime", false))
477 {
Alpana Kumaricfd7a752021-02-07 23:23:01 -0600478 inventory::PropertyMap presProp;
479 presProp.emplace("Present", false);
480 interfaces.emplace("xyz.openbmc_project.Inventory.Item",
481 move(presProp));
482
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530483 if (itemEEPROM.find("extraInterfaces") != itemEEPROM.end())
484 {
485 for (const auto& eI : itemEEPROM["extraInterfaces"].items())
486 {
487 inventory::PropertyMap props;
488 if (eI.key() ==
489 openpower::vpd::constants::LOCATION_CODE_INF)
490 {
491 if constexpr (std::is_same<T, Parsed>::value)
492 {
493 for (auto& lC : eI.value().items())
494 {
495 auto propVal = expandLocationCode(
496 lC.value().get<string>(), vpdMap, true);
497
498 props.emplace(move(lC.key()),
499 move(propVal));
500 interfaces.emplace(move(eI.key()),
501 move(props));
502 }
503 }
504 }
505 else if (eI.key().find("Inventory.Item.") !=
506 string::npos)
507 {
508 interfaces.emplace(move(eI.key()), move(props));
509 }
510 }
511 }
512 objects.emplace(move(object), move(interfaces));
513 }
514 }
515 }
516 return objects;
517}
518
Alpana Kumari65b83602020-09-01 00:24:56 -0500519/**
520 * @brief This API executes command to set environment variable
521 * And then reboot the system
522 * @param[in] key -env key to set new value
523 * @param[in] value -value to set.
524 */
525void setEnvAndReboot(const string& key, const string& value)
526{
527 // set env and reboot and break.
528 executeCmd("/sbin/fw_setenv", key, value);
Andrew Geissler280197e2020-12-08 20:51:49 -0600529 log<level::INFO>("Rebooting BMC to pick up new device tree");
Alpana Kumari65b83602020-09-01 00:24:56 -0500530 // make dbus call to reboot
531 auto bus = sdbusplus::bus::new_default_system();
532 auto method = bus.new_method_call(
533 "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
534 "org.freedesktop.systemd1.Manager", "Reboot");
535 bus.call_noreply(method);
536}
537
538/*
539 * @brief This API checks for env var fitconfig.
540 * If not initialised OR updated as per the current system type,
541 * update this env var and reboot the system.
542 *
543 * @param[in] systemType IM kwd in vpd tells about which system type it is.
544 * */
545void setDevTreeEnv(const string& systemType)
546{
547 string newDeviceTree;
548
549 if (deviceTreeSystemTypeMap.find(systemType) !=
550 deviceTreeSystemTypeMap.end())
551 {
552 newDeviceTree = deviceTreeSystemTypeMap.at(systemType);
553 }
554
555 string readVarValue;
556 bool envVarFound = false;
557
558 vector<string> output = executeCmd("/sbin/fw_printenv");
559 for (const auto& entry : output)
560 {
561 size_t pos = entry.find("=");
562 string key = entry.substr(0, pos);
563 if (key != "fitconfig")
564 {
565 continue;
566 }
567
568 envVarFound = true;
569 if (pos + 1 < entry.size())
570 {
571 readVarValue = entry.substr(pos + 1);
572 if (readVarValue.find(newDeviceTree) != string::npos)
573 {
574 // fitconfig is Updated. No action needed
575 break;
576 }
577 }
578 // set env and reboot and break.
579 setEnvAndReboot(key, newDeviceTree);
580 exit(0);
581 }
582
583 // check If env var Not found
584 if (!envVarFound)
585 {
586 setEnvAndReboot("fitconfig", newDeviceTree);
587 }
588}
589
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530590/**
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500591 * @brief API to call VPD manager to write VPD to EEPROM.
592 * @param[in] Object path.
593 * @param[in] record to be updated.
594 * @param[in] keyword to be updated.
595 * @param[in] keyword data to be updated
596 */
597void updateHardware(const string& objectName, const string& recName,
598 const string& kwdName, const Binary& data)
599{
600 try
601 {
602 auto bus = sdbusplus::bus::new_default();
603 auto properties =
604 bus.new_method_call(BUSNAME, OBJPATH, IFACE, "WriteKeyword");
605 properties.append(
606 static_cast<sdbusplus::message::object_path>(objectName));
607 properties.append(recName);
608 properties.append(kwdName);
609 properties.append(data);
610 bus.call(properties);
611 }
612 catch (const sdbusplus::exception::SdBusError& e)
613 {
614 std::string what =
615 "VPDManager WriteKeyword api failed for inventory path " +
616 objectName;
617 what += " record " + recName;
618 what += " keyword " + kwdName;
619 what += " with bus error = " + std::string(e.what());
620
621 // map to hold additional data in case of logging pel
622 PelAdditionalData additionalData{};
623 additionalData.emplace("CALLOUT_INVENTORY_PATH", objectName);
624 additionalData.emplace("DESCRIPTION", what);
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500625 createPEL(additionalData, PelSeverity::WARNING, errIntfForBusFailure);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500626 }
627}
628
629/**
630 * @brief API to check if we need to restore system VPD
631 * This functionality is only applicable for IPZ VPD data.
632 * @param[in] vpdMap - IPZ vpd map
633 * @param[in] objectPath - Object path for the FRU
634 * @return EEPROMs with records and keywords updated at standby
635 */
636std::vector<RestoredEeproms> restoreSystemVPD(Parsed& vpdMap,
637 const string& objectPath)
638{
639 // the list of keywords for VSYS record is as per the S0 system. Should be
640 // updated for another type of systems
641 static std::unordered_map<std::string, std::vector<std::string>> svpdKwdMap{
642 {"VSYS", {"BR", "TM", "SE", "SU", "RB"}},
643 {"VCEN", {"FC", "SE"}},
644 {"LXR0", {"LX"}}};
645
646 // vector to hold all the EEPROMs updated at standby
647 std::vector<RestoredEeproms> updatedEeproms = {};
648
649 for (const auto& systemRecKwdPair : svpdKwdMap)
650 {
651 auto it = vpdMap.find(systemRecKwdPair.first);
652
653 // check if record is found in map we got by parser
654 if (it != vpdMap.end())
655 {
656 const auto& kwdListForRecord = systemRecKwdPair.second;
657 for (const auto& keyword : kwdListForRecord)
658 {
659 DbusPropertyMap& kwdValMap = it->second;
660 auto iterator = kwdValMap.find(keyword);
661
662 if (iterator != kwdValMap.end())
663 {
664 string& kwdValue = iterator->second;
665
666 // check bus data
667 const string& recordName = systemRecKwdPair.first;
668 const string& busValue = readBusProperty(
669 objectPath, ipzVpdInf + recordName, keyword);
670
671 if (busValue.find_first_not_of(' ') != string::npos)
672 {
673 if (kwdValue.find_first_not_of(' ') != string::npos)
674 {
675 // both the data are present, check for mismatch
676 if (busValue != kwdValue)
677 {
678 string errMsg = "VPD data mismatch on cache "
679 "and hardware for record: ";
680 errMsg += (*it).first;
681 errMsg += " and keyword: ";
682 errMsg += keyword;
683
684 // data mismatch
685 PelAdditionalData additionalData;
686 additionalData.emplace("CALLOUT_INVENTORY_PATH",
687 objectPath);
688
689 additionalData.emplace("DESCRIPTION", errMsg);
690
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500691 createPEL(additionalData, PelSeverity::WARNING,
692 errIntfForInvalidVPD);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500693 }
694 }
695 else
696 {
697 // implies hardware data is blank
698 // update the map
699 Binary busData(busValue.begin(), busValue.end());
700
701 updatedEeproms.push_back(std::make_tuple(
702 objectPath, recordName, keyword, busData));
703 }
704
705 // update the map as well, so that cache data is not
706 // updated as blank while populating VPD map on Dbus in
707 // populateDBus Api
708 kwdValue = busValue;
709 continue;
710 }
711 else if (kwdValue.find_first_not_of(' ') == string::npos)
712 {
713 string errMsg = "VPD is blank on both cache and "
714 "hardware for record: ";
715 errMsg += (*it).first;
716 errMsg += " and keyword: ";
717 errMsg += keyword;
718 errMsg += ". SSR need to update hardware VPD.";
719
720 // both the data are blanks, log PEL
721 PelAdditionalData additionalData;
722 additionalData.emplace("CALLOUT_INVENTORY_PATH",
723 objectPath);
724
725 additionalData.emplace("DESCRIPTION", errMsg);
726
727 // log PEL TODO: Block IPL
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500728 createPEL(additionalData, PelSeverity::ERROR,
729 errIntfForBlankSystemVPD);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500730 continue;
731 }
732 }
733 }
734 }
735 }
736
737 return updatedEeproms;
738}
739
740/**
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530741 * @brief Populate Dbus.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530742 * This method invokes all the populateInterface functions
743 * and notifies PIM about dbus object.
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530744 * @param[in] vpdMap - Either IPZ vpd map or Keyword vpd map based on the
745 * input.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530746 * @param[in] js - Inventory json object
747 * @param[in] filePath - Path of the vpd file
748 * @param[in] preIntrStr - Interface string
749 */
750template <typename T>
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500751static void populateDbus(T& vpdMap, nlohmann::json& js, const string& filePath)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530752{
753 inventory::InterfaceMap interfaces;
754 inventory::ObjectMap objects;
755 inventory::PropertyMap prop;
756
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500757 // map to hold all the keywords whose value has been changed at standby
758 vector<RestoredEeproms> updatedEeproms = {};
759
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500760 bool isSystemVpd = false;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530761 for (const auto& item : js["frus"][filePath])
762 {
763 const auto& objectPath = item["inventoryPath"];
764 sdbusplus::message::object_path object(objectPath);
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530765 isSystemVpd = item.value("isSystemVpd", false);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500766
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530767 // Populate the VPD keywords and the common interfaces only if we
768 // are asked to inherit that data from the VPD, else only add the
769 // extraInterfaces.
770 if (item.value("inherit", true))
771 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500772 if constexpr (is_same<T, Parsed>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530773 {
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500774 if (isSystemVpd)
775 {
776 std::vector<std::string> interfaces = {
777 motherBoardInterface};
778 // call mapper to check for object path creation
779 MapperResponse subTree =
780 getObjectSubtreeForInterfaces(pimPath, 0, interfaces);
781
782 // Skip system vpd restore if object path is not generated
783 // for motherboard, Implies first boot.
784 if (subTree.size() != 0)
785 {
786 assert(
787 (subTree.find(pimPath + std::string(objectPath)) !=
788 subTree.end()));
789
790 updatedEeproms = restoreSystemVPD(vpdMap, objectPath);
791 }
792 else
793 {
794 log<level::ERR>("No object path found");
795 }
796 }
797
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530798 // Each record in the VPD becomes an interface and all
799 // keyword within the record are properties under that
800 // interface.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530801 for (const auto& record : vpdMap)
802 {
803 populateFruSpecificInterfaces(
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500804 record.second, ipzVpdInf + record.first, interfaces);
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530805 }
806 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500807 else if constexpr (is_same<T, KeywordVpdMap>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530808 {
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500809 populateFruSpecificInterfaces(vpdMap, kwdVpdInf, interfaces);
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530810 }
Santosh Puranik88edeb62020-03-02 12:00:09 +0530811 if (js.find("commonInterfaces") != js.end())
812 {
813 populateInterfaces(js["commonInterfaces"], interfaces, vpdMap,
814 isSystemVpd);
815 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530816 }
Santosh Puranik0859eb62020-03-16 02:56:29 -0500817 else
818 {
819 // Check if we have been asked to inherit specific record(s)
Alpana Kumari58e22142020-05-05 00:22:12 -0500820 if constexpr (is_same<T, Parsed>::value)
Santosh Puranik0859eb62020-03-16 02:56:29 -0500821 {
822 if (item.find("copyRecords") != item.end())
823 {
824 for (const auto& record : item["copyRecords"])
825 {
826 const string& recordName = record;
827 if (vpdMap.find(recordName) != vpdMap.end())
828 {
829 populateFruSpecificInterfaces(
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500830 vpdMap.at(recordName), ipzVpdInf + recordName,
Santosh Puranik0859eb62020-03-16 02:56:29 -0500831 interfaces);
832 }
833 }
834 }
835 }
836 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500837 if (item.value("inheritEI", true))
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530838 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500839 // Populate interfaces and properties that are common to every FRU
840 // and additional interface that might be defined on a per-FRU
841 // basis.
842 if (item.find("extraInterfaces") != item.end())
843 {
844 populateInterfaces(item["extraInterfaces"], interfaces, vpdMap,
845 isSystemVpd);
846 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530847 }
848 objects.emplace(move(object), move(interfaces));
849 }
850
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530851 if (isSystemVpd)
852 {
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530853 vector<uint8_t> imVal;
854 if constexpr (is_same<T, Parsed>::value)
855 {
856 auto property = vpdMap.find("VSBP");
857 if (property != vpdMap.end())
858 {
859 auto value = (property->second).find("IM");
860 if (value != (property->second).end())
861 {
862 copy(value->second.begin(), value->second.end(),
863 back_inserter(imVal));
864 }
865 }
866 }
867
868 fs::path target;
869 fs::path link = INVENTORY_JSON_SYM_LINK;
870
871 ostringstream oss;
872 for (auto& i : imVal)
873 {
874 oss << setw(2) << setfill('0') << hex << static_cast<int>(i);
875 }
876 string imValStr = oss.str();
877
Andrew Geissler7c9cddf2021-03-19 10:34:31 -0500878 if ((imValStr == RAINIER_4U) || // 4U
879 (imValStr == RAINIER_1S4U))
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530880 {
881 target = INVENTORY_JSON_4U;
882 }
Alpana Kumari65b83602020-09-01 00:24:56 -0500883 else if (imValStr == RAINIER_2U) // 2U
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530884 {
885 target = INVENTORY_JSON_2U;
886 }
Santosh Puranik4641bff2020-11-30 20:26:44 +0530887 else if (imValStr == EVEREST)
888 {
889 target = INVENTORY_JSON_EVEREST;
890 }
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530891
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530892 // Create the directory for hosting the symlink
893 fs::create_directories(VPD_FILES_PATH);
894 // unlink the symlink previously created (if any)
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530895 remove(INVENTORY_JSON_SYM_LINK);
896 // create a new symlink based on the system
897 fs::create_symlink(target, link);
898
899 // Reloading the json
900 ifstream inventoryJson(link);
901 auto js = json::parse(inventoryJson);
902 inventoryJson.close();
903
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530904 inventory::ObjectMap primeObject = primeInventory(js, vpdMap);
905 objects.insert(primeObject.begin(), primeObject.end());
Alpana Kumari65b83602020-09-01 00:24:56 -0500906
907 // set the U-boot environment variable for device-tree
908 setDevTreeEnv(imValStr);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500909
910 // if system VPD has been restored at standby, update the EEPROM
911 for (const auto& item : updatedEeproms)
912 {
913 updateHardware(get<0>(item), get<1>(item), get<2>(item),
914 get<3>(item));
915 }
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530916 }
917
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530918 // Notify PIM
Sunny Srivastava6c71c9d2021-04-15 04:43:54 -0500919 common::utility::callPIM(move(objects));
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530920}
921
922int main(int argc, char** argv)
923{
924 int rc = 0;
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500925 string file{};
926 json js{};
927
928 // map to hold additional data in case of logging pel
929 PelAdditionalData additionalData{};
930
931 // this is needed to hold base fru inventory path in case there is ECC or
932 // vpd exception while parsing the file
933 std::string baseFruInventoryPath = {};
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530934
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500935 // severity for PEL
936 PelSeverity pelSeverity = PelSeverity::WARNING;
937
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530938 try
939 {
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530940 App app{"ibm-read-vpd - App to read IPZ format VPD, parse it and store "
941 "in DBUS"};
942 string file{};
943
944 app.add_option("-f, --file", file, "File containing VPD (IPZ/KEYWORD)")
Alpana Kumari2f793042020-08-18 05:51:03 -0500945 ->required();
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530946
947 CLI11_PARSE(app, argc, argv);
948
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500949 // PEL severity should be ERROR in case of any system VPD failure
950 if (file == systemVpdFilePath)
951 {
952 pelSeverity = PelSeverity::ERROR;
953 }
954
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530955 auto jsonToParse = INVENTORY_JSON_DEFAULT;
956
957 // If the symlink exists, it means it has been setup for us, switch the
958 // path
959 if (fs::exists(INVENTORY_JSON_SYM_LINK))
960 {
961 jsonToParse = INVENTORY_JSON_SYM_LINK;
962 }
963
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530964 // Make sure that the file path we get is for a supported EEPROM
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530965 ifstream inventoryJson(jsonToParse);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500966 if (!inventoryJson)
967 {
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500968 throw(VpdJsonException("Failed to access Json path", jsonToParse));
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500969 }
970
971 try
972 {
973 js = json::parse(inventoryJson);
974 }
975 catch (json::parse_error& ex)
976 {
Sunny Srivastava0746eee2021-03-22 13:36:54 -0500977 throw(VpdJsonException("Json parsing failed", jsonToParse));
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500978 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530979
980 if ((js.find("frus") == js.end()) ||
981 (js["frus"].find(file) == js["frus"].end()))
982 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500983 cout << "Device path not in JSON, ignoring" << endl;
Santosh Puranik88edeb62020-03-02 12:00:09 +0530984 return 0;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530985 }
986
Alpana Kumari2f793042020-08-18 05:51:03 -0500987 if (!fs::exists(file))
988 {
989 cout << "Device path: " << file
990 << " does not exist. Spurious udev event? Exiting." << endl;
991 return 0;
992 }
993
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500994 baseFruInventoryPath = js["frus"][file][0]["inventoryPath"];
Santosh Puranik85893752020-11-10 21:31:43 +0530995 // Check if we can read the VPD file based on the power state
996 if (js["frus"][file].at(0).value("powerOffOnly", false))
997 {
998 if ("xyz.openbmc_project.State.Chassis.PowerState.On" ==
999 getPowerState())
1000 {
1001 cout << "This VPD cannot be read when power is ON" << endl;
1002 return 0;
1003 }
1004 }
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001005
Alpana Kumari2f793042020-08-18 05:51:03 -05001006 try
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301007 {
Alpana Kumari80f15342020-06-09 07:41:02 -05001008 // check if vpd file is empty
1009 if (file.empty())
1010 {
1011 throw(VpdDataException(
1012 "VPD file is empty. Can't process with blank file."));
1013 }
1014
Alpana Kumari2f793042020-08-18 05:51:03 -05001015 Binary vpdVector = getVpdDataInVector(js, file);
1016 ParserInterface* parser = ParserFactory::getParser(move(vpdVector));
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05001017
Alpana Kumari2f793042020-08-18 05:51:03 -05001018 variant<KeywordVpdMap, Store> parseResult;
1019 parseResult = parser->parse();
1020 if (auto pVal = get_if<Store>(&parseResult))
1021 {
1022 populateDbus(pVal->getVpdMap(), js, file);
1023 }
1024 else if (auto pVal = get_if<KeywordVpdMap>(&parseResult))
1025 {
1026 populateDbus(*pVal, js, file);
1027 }
1028
1029 // release the parser object
1030 ParserFactory::freeParser(parser);
1031 }
1032 catch (exception& e)
1033 {
1034 postFailAction(js, file);
1035 throw e;
1036 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301037 }
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001038 catch (const VpdJsonException& ex)
1039 {
1040 additionalData.emplace("JSON_PATH", ex.getJsonPath());
1041 additionalData.emplace("DESCRIPTION", ex.what());
Sunny Srivastava0746eee2021-03-22 13:36:54 -05001042 createPEL(additionalData, pelSeverity, errIntfForJsonFailure);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001043
1044 cerr << ex.what() << "\n";
1045 rc = -1;
1046 }
1047 catch (const VpdEccException& ex)
1048 {
1049 additionalData.emplace("DESCRIPTION", "ECC check failed");
1050 additionalData.emplace("CALLOUT_INVENTORY_PATH",
1051 INVENTORY_PATH + baseFruInventoryPath);
Sunny Srivastava0746eee2021-03-22 13:36:54 -05001052 createPEL(additionalData, pelSeverity, errIntfForEccCheckFail);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001053
1054 cerr << ex.what() << "\n";
1055 rc = -1;
1056 }
1057 catch (const VpdDataException& ex)
1058 {
1059 additionalData.emplace("DESCRIPTION", "Invalid VPD data");
1060 additionalData.emplace("CALLOUT_INVENTORY_PATH",
1061 INVENTORY_PATH + baseFruInventoryPath);
Sunny Srivastava0746eee2021-03-22 13:36:54 -05001062 createPEL(additionalData, pelSeverity, errIntfForInvalidVPD);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001063
1064 cerr << ex.what() << "\n";
1065 rc = -1;
1066 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301067 catch (exception& e)
1068 {
1069 cerr << e.what() << "\n";
1070 rc = -1;
1071 }
1072
1073 return rc;
Alpana Kumari80f15342020-06-09 07:41:02 -05001074}