blob: e3e6322fca6ddecb16f73aa7b93a3ebbd793003f [file] [log] [blame]
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301#include "config.h"
2
3#include "defines.hpp"
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05004#include "ipz_parser.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05305#include "keyword_vpd_parser.hpp"
Alpana Kumaria00936f2020-04-14 07:15:46 -05006#include "memory_vpd_parser.hpp"
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05007#include "parser_factory.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05308#include "utils.hpp"
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05009#include "vpd_exceptions.hpp"
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053010
SunnySrivastava19849094d4f2020-08-05 09:32:29 -050011#include <assert.h>
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -050012#include <ctype.h>
13
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053014#include <CLI/CLI.hpp>
Santosh Puranik88edeb62020-03-02 12:00:09 +053015#include <algorithm>
Alpana Kumari65b83602020-09-01 00:24:56 -050016#include <cstdarg>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053017#include <exception>
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +053018#include <filesystem>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053019#include <fstream>
Alpana Kumari2f793042020-08-18 05:51:03 -050020#include <gpiod.hpp>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053021#include <iostream>
22#include <iterator>
23#include <nlohmann/json.hpp>
Andrew Geissler280197e2020-12-08 20:51:49 -060024#include <phosphor-logging/log.hpp>
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053025
26using namespace std;
27using namespace openpower::vpd;
28using namespace CLI;
29using namespace vpd::keyword::parser;
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +053030using namespace openpower::vpd::constants;
31namespace fs = filesystem;
32using json = nlohmann::json;
SunnySrivastava1984e12b1812020-05-26 02:23:11 -050033using namespace openpower::vpd::parser::factory;
SunnySrivastava1984945a02d2020-05-06 01:55:41 -050034using namespace openpower::vpd::inventory;
Alpana Kumaria00936f2020-04-14 07:15:46 -050035using namespace openpower::vpd::memory::parser;
SunnySrivastava1984e12b1812020-05-26 02:23:11 -050036using namespace openpower::vpd::parser::interface;
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -050037using namespace openpower::vpd::exceptions;
Andrew Geissler280197e2020-12-08 20:51:49 -060038using namespace phosphor::logging;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +053039
Alpana Kumari65b83602020-09-01 00:24:56 -050040static const deviceTreeMap deviceTreeSystemTypeMap = {
Santosh Puranik4641bff2020-11-30 20:26:44 +053041 {RAINIER_2U, "conf@aspeed-bmc-ibm-rainier.dtb"},
42 {RAINIER_4U, "conf@aspeed-bmc-ibm-rainier-4u.dtb"},
43 {EVEREST, "conf@aspeed-bmc-ibm-everest.dtb"}};
Alpana Kumari65b83602020-09-01 00:24:56 -050044
Santosh Puranik88edeb62020-03-02 12:00:09 +053045/**
Santosh Puranik85893752020-11-10 21:31:43 +053046 * @brief Returns the power state for chassis0
47 */
48static auto getPowerState()
49{
50 // TODO: How do we handle multiple chassis?
51 string powerState{};
52 auto bus = sdbusplus::bus::new_default();
53 auto properties =
54 bus.new_method_call("xyz.openbmc_project.State.Chassis",
55 "/xyz/openbmc_project/state/chassis0",
56 "org.freedesktop.DBus.Properties", "Get");
57 properties.append("xyz.openbmc_project.State.Chassis");
58 properties.append("CurrentPowerState");
59 auto result = bus.call(properties);
60 if (!result.is_method_error())
61 {
62 variant<string> val;
63 result.read(val);
64 if (auto pVal = get_if<string>(&val))
65 {
66 powerState = *pVal;
67 }
68 }
69 cout << "Power state is: " << powerState << endl;
70 return powerState;
71}
72
73/**
Santosh Puranik88edeb62020-03-02 12:00:09 +053074 * @brief Expands location codes
75 */
76static auto expandLocationCode(const string& unexpanded, const Parsed& vpdMap,
77 bool isSystemVpd)
78{
79 auto expanded{unexpanded};
80 static constexpr auto SYSTEM_OBJECT = "/system/chassis/motherboard";
81 static constexpr auto VCEN_IF = "com.ibm.ipzvpd.VCEN";
82 static constexpr auto VSYS_IF = "com.ibm.ipzvpd.VSYS";
83 size_t idx = expanded.find("fcs");
84 try
85 {
86 if (idx != string::npos)
87 {
88 string fc{};
89 string se{};
90 if (isSystemVpd)
91 {
92 const auto& fcData = vpdMap.at("VCEN").at("FC");
93 const auto& seData = vpdMap.at("VCEN").at("SE");
94 fc = string(fcData.data(), fcData.size());
95 se = string(seData.data(), seData.size());
96 }
97 else
98 {
99 fc = readBusProperty(SYSTEM_OBJECT, VCEN_IF, "FC");
100 se = readBusProperty(SYSTEM_OBJECT, VCEN_IF, "SE");
101 }
102
Alpana Kumari81671f62021-02-10 02:21:59 -0600103 // TODO: See if ND0 can be placed in the JSON
104 expanded.replace(idx, 3, fc.substr(0, 4) + ".ND0." + se);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530105 }
106 else
107 {
108 idx = expanded.find("mts");
109 if (idx != string::npos)
110 {
111 string mt{};
112 string se{};
113 if (isSystemVpd)
114 {
115 const auto& mtData = vpdMap.at("VSYS").at("TM");
116 const auto& seData = vpdMap.at("VSYS").at("SE");
117 mt = string(mtData.data(), mtData.size());
118 se = string(seData.data(), seData.size());
119 }
120 else
121 {
122 mt = readBusProperty(SYSTEM_OBJECT, VSYS_IF, "TM");
123 se = readBusProperty(SYSTEM_OBJECT, VSYS_IF, "SE");
124 }
125
126 replace(mt.begin(), mt.end(), '-', '.');
127 expanded.replace(idx, 3, mt + "." + se);
128 }
129 }
130 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500131 catch (exception& e)
Santosh Puranik88edeb62020-03-02 12:00:09 +0530132 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500133 cerr << "Failed to expand location code with exception: " << e.what()
134 << "\n";
Santosh Puranik88edeb62020-03-02 12:00:09 +0530135 }
136 return expanded;
137}
Alpana Kumari2f793042020-08-18 05:51:03 -0500138
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530139/**
140 * @brief Populate FRU specific interfaces.
141 *
142 * This is a common method which handles both
143 * ipz and keyword specific interfaces thus,
144 * reducing the code redundancy.
145 * @param[in] map - Reference to the innermost keyword-value map.
146 * @param[in] preIntrStr - Reference to the interface string.
147 * @param[out] interfaces - Reference to interface map.
148 */
149template <typename T>
150static void populateFruSpecificInterfaces(const T& map,
151 const string& preIntrStr,
152 inventory::InterfaceMap& interfaces)
153{
154 inventory::PropertyMap prop;
155
156 for (const auto& kwVal : map)
157 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500158 vector<uint8_t> vec(kwVal.second.begin(), kwVal.second.end());
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530159
160 auto kw = kwVal.first;
161
162 if (kw[0] == '#')
163 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500164 kw = string("PD_") + kw[1];
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530165 }
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -0500166 else if (isdigit(kw[0]))
167 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500168 kw = string("N_") + kw;
Alpana Kumari8ea3f6d2020-04-02 00:26:07 -0500169 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530170 prop.emplace(move(kw), move(vec));
171 }
172
173 interfaces.emplace(preIntrStr, move(prop));
174}
175
176/**
177 * @brief Populate Interfaces.
178 *
179 * This method populates common and extra interfaces to dbus.
180 * @param[in] js - json object
181 * @param[out] interfaces - Reference to interface map
182 * @param[in] vpdMap - Reference to the parsed vpd map.
Santosh Puranik88edeb62020-03-02 12:00:09 +0530183 * @param[in] isSystemVpd - Denotes whether we are collecting the system VPD.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530184 */
185template <typename T>
186static void populateInterfaces(const nlohmann::json& js,
187 inventory::InterfaceMap& interfaces,
Santosh Puranik88edeb62020-03-02 12:00:09 +0530188 const T& vpdMap, bool isSystemVpd)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530189{
190 for (const auto& ifs : js.items())
191 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530192 string inf = ifs.key();
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530193 inventory::PropertyMap props;
194
195 for (const auto& itr : ifs.value().items())
196 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530197 const string& busProp = itr.key();
198
Alpana Kumari31970de2020-02-17 06:49:57 -0600199 if (itr.value().is_boolean())
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530200 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530201 props.emplace(busProp, itr.value().get<bool>());
202 }
203 else if (itr.value().is_string())
204 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500205 if constexpr (is_same<T, Parsed>::value)
Santosh Puranik88edeb62020-03-02 12:00:09 +0530206 {
207 if (busProp == "LocationCode" &&
208 inf == "com.ibm.ipzvpd.Location")
209 {
210 auto prop = expandLocationCode(
211 itr.value().get<string>(), vpdMap, isSystemVpd);
212 props.emplace(busProp, prop);
213 }
214 else
215 {
216 props.emplace(busProp, itr.value().get<string>());
217 }
218 }
219 else
220 {
221 props.emplace(busProp, itr.value().get<string>());
222 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530223 }
Alpana Kumari31970de2020-02-17 06:49:57 -0600224 else if (itr.value().is_object())
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530225 {
Alpana Kumari31970de2020-02-17 06:49:57 -0600226 const string& rec = itr.value().value("recordName", "");
227 const string& kw = itr.value().value("keywordName", "");
228 const string& encoding = itr.value().value("encoding", "");
229
Alpana Kumari58e22142020-05-05 00:22:12 -0500230 if constexpr (is_same<T, Parsed>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530231 {
Santosh Puranik88edeb62020-03-02 12:00:09 +0530232 if (!rec.empty() && !kw.empty() && vpdMap.count(rec) &&
233 vpdMap.at(rec).count(kw))
Alpana Kumari31970de2020-02-17 06:49:57 -0600234 {
235 auto encoded =
236 encodeKeyword(vpdMap.at(rec).at(kw), encoding);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530237 props.emplace(busProp, encoded);
Alpana Kumari31970de2020-02-17 06:49:57 -0600238 }
239 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500240 else if constexpr (is_same<T, KeywordVpdMap>::value)
Alpana Kumari31970de2020-02-17 06:49:57 -0600241 {
242 if (!kw.empty() && vpdMap.count(kw))
243 {
244 auto prop =
245 string(vpdMap.at(kw).begin(), vpdMap.at(kw).end());
246 auto encoded = encodeKeyword(prop, encoding);
Santosh Puranik88edeb62020-03-02 12:00:09 +0530247 props.emplace(busProp, encoded);
Alpana Kumari31970de2020-02-17 06:49:57 -0600248 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530249 }
250 }
251 }
252 interfaces.emplace(inf, move(props));
253 }
254}
255
Alpana Kumari2f793042020-08-18 05:51:03 -0500256static Binary getVpdDataInVector(const nlohmann::json& js, const string& file)
Alpana Kumari58e22142020-05-05 00:22:12 -0500257{
258 uint32_t offset = 0;
259 // check if offset present?
260 for (const auto& item : js["frus"][file])
261 {
262 if (item.find("offset") != item.end())
263 {
264 offset = item["offset"];
265 }
266 }
267
268 // TODO: Figure out a better way to get max possible VPD size.
269 Binary vpdVector;
270 vpdVector.resize(65504);
271 ifstream vpdFile;
272 vpdFile.open(file, ios::binary);
273
274 vpdFile.seekg(offset, ios_base::cur);
275 vpdFile.read(reinterpret_cast<char*>(&vpdVector[0]), 65504);
276 vpdVector.resize(vpdFile.gcount());
277
278 return vpdVector;
279}
280
Alpana Kumari2f793042020-08-18 05:51:03 -0500281/* It does nothing. Just an empty function to return null
282 * at the end of variadic template args
283 */
284static string getCommand()
285{
286 return "";
287}
288
289/* This function to arrange all arguments to make command
290 */
291template <typename T, typename... Types>
292static string getCommand(T arg1, Types... args)
293{
294 string cmd = " " + arg1 + getCommand(args...);
295
296 return cmd;
297}
298
299/* This API takes arguments and run that command
300 * returns output of that command
301 */
302template <typename T, typename... Types>
303static vector<string> executeCmd(T&& path, Types... args)
304{
305 vector<string> stdOutput;
306 array<char, 128> buffer;
307
308 string cmd = path + getCommand(args...);
309
310 unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
311 if (!pipe)
312 {
313 throw runtime_error("popen() failed!");
314 }
315 while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
316 {
317 stdOutput.emplace_back(buffer.data());
318 }
319
320 return stdOutput;
321}
322
323/** This API will be called at the end of VPD collection to perform any post
324 * actions.
325 *
326 * @param[in] json - json object
327 * @param[in] file - eeprom file path
328 */
329static void postFailAction(const nlohmann::json& json, const string& file)
330{
331 if ((json["frus"][file].at(0)).find("postActionFail") ==
332 json["frus"][file].at(0).end())
333 {
334 return;
335 }
336
337 uint8_t pinValue = 0;
338 string pinName;
339
340 for (const auto& postAction :
341 (json["frus"][file].at(0))["postActionFail"].items())
342 {
343 if (postAction.key() == "pin")
344 {
345 pinName = postAction.value();
346 }
347 else if (postAction.key() == "value")
348 {
349 // Get the value to set
350 pinValue = postAction.value();
351 }
352 }
353
354 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue << endl;
355
356 try
357 {
358 gpiod::line outputLine = gpiod::find_line(pinName);
359
360 if (!outputLine)
361 {
362 cout << "Couldn't find output line:" << pinName
363 << " on GPIO. Skipping...\n";
364
365 return;
366 }
367 outputLine.request(
368 {"Disable line", ::gpiod::line_request::DIRECTION_OUTPUT, 0},
369 pinValue);
370 }
371 catch (system_error&)
372 {
373 cerr << "Failed to set post-action GPIO" << endl;
374 }
375}
376
377/** Performs any pre-action needed to get the FRU setup for collection.
378 *
379 * @param[in] json - json object
380 * @param[in] file - eeprom file path
381 */
382static void preAction(const nlohmann::json& json, const string& file)
383{
384 if ((json["frus"][file].at(0)).find("preAction") ==
385 json["frus"][file].at(0).end())
386 {
387 return;
388 }
389
390 uint8_t pinValue = 0;
391 string pinName;
392
393 for (const auto& postAction :
394 (json["frus"][file].at(0))["preAction"].items())
395 {
396 if (postAction.key() == "pin")
397 {
398 pinName = postAction.value();
399 }
400 else if (postAction.key() == "value")
401 {
402 // Get the value to set
403 pinValue = postAction.value();
404 }
405 }
406
407 cout << "Setting GPIO: " << pinName << " to " << (int)pinValue << endl;
408 try
409 {
410 gpiod::line outputLine = gpiod::find_line(pinName);
411
412 if (!outputLine)
413 {
414 cout << "Couldn't find output line:" << pinName
415 << " on GPIO. Skipping...\n";
416
417 return;
418 }
419 outputLine.request(
420 {"FRU pre-action", ::gpiod::line_request::DIRECTION_OUTPUT, 0},
421 pinValue);
422 }
423 catch (system_error&)
424 {
425 cerr << "Failed to set pre-action GPIO" << endl;
426 return;
427 }
428
429 // Now bind the device
430 string bind = json["frus"][file].at(0).value("bind", "");
431 cout << "Binding device " << bind << endl;
432 string bindCmd = string("echo \"") + bind +
433 string("\" > /sys/bus/i2c/drivers/at24/bind");
434 cout << bindCmd << endl;
435 executeCmd(bindCmd);
436
437 // Check if device showed up (test for file)
438 if (!fs::exists(file))
439 {
440 cout << "EEPROM " << file << " does not exist. Take failure action"
441 << endl;
442 // If not, then take failure postAction
443 postFailAction(json, file);
444 }
445}
446
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530447/**
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530448 * @brief Prime the Inventory
449 * Prime the inventory by populating only the location code,
450 * type interface and the inventory object for the frus
451 * which are not system vpd fru.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530452 *
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530453 * @param[in] jsObject - Reference to vpd inventory json object
454 * @param[in] vpdMap - Reference to the parsed vpd map
455 *
456 * @returns Map of items in extraInterface.
457 */
458template <typename T>
459inventory::ObjectMap primeInventory(const nlohmann::json& jsObject,
460 const T& vpdMap)
461{
462 inventory::ObjectMap objects;
463
464 for (auto& itemFRUS : jsObject["frus"].items())
465 {
Alpana Kumari2f793042020-08-18 05:51:03 -0500466 // Take pre actions
467 preAction(jsObject, itemFRUS.key());
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530468 for (auto& itemEEPROM : itemFRUS.value())
469 {
470 inventory::InterfaceMap interfaces;
471 auto isSystemVpd = itemEEPROM.value("isSystemVpd", false);
472 inventory::Object object(itemEEPROM.at("inventoryPath"));
473
474 if (!isSystemVpd && !itemEEPROM.value("noprime", false))
475 {
Alpana Kumaricfd7a752021-02-07 23:23:01 -0600476 inventory::PropertyMap presProp;
477 presProp.emplace("Present", false);
478 interfaces.emplace("xyz.openbmc_project.Inventory.Item",
479 move(presProp));
480
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530481 if (itemEEPROM.find("extraInterfaces") != itemEEPROM.end())
482 {
483 for (const auto& eI : itemEEPROM["extraInterfaces"].items())
484 {
485 inventory::PropertyMap props;
486 if (eI.key() ==
487 openpower::vpd::constants::LOCATION_CODE_INF)
488 {
489 if constexpr (std::is_same<T, Parsed>::value)
490 {
491 for (auto& lC : eI.value().items())
492 {
493 auto propVal = expandLocationCode(
494 lC.value().get<string>(), vpdMap, true);
495
496 props.emplace(move(lC.key()),
497 move(propVal));
498 interfaces.emplace(move(eI.key()),
499 move(props));
500 }
501 }
502 }
503 else if (eI.key().find("Inventory.Item.") !=
504 string::npos)
505 {
506 interfaces.emplace(move(eI.key()), move(props));
507 }
508 }
509 }
510 objects.emplace(move(object), move(interfaces));
511 }
512 }
513 }
514 return objects;
515}
516
Alpana Kumari65b83602020-09-01 00:24:56 -0500517/**
518 * @brief This API executes command to set environment variable
519 * And then reboot the system
520 * @param[in] key -env key to set new value
521 * @param[in] value -value to set.
522 */
523void setEnvAndReboot(const string& key, const string& value)
524{
525 // set env and reboot and break.
526 executeCmd("/sbin/fw_setenv", key, value);
Andrew Geissler280197e2020-12-08 20:51:49 -0600527 log<level::INFO>("Rebooting BMC to pick up new device tree");
Alpana Kumari65b83602020-09-01 00:24:56 -0500528 // make dbus call to reboot
529 auto bus = sdbusplus::bus::new_default_system();
530 auto method = bus.new_method_call(
531 "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
532 "org.freedesktop.systemd1.Manager", "Reboot");
533 bus.call_noreply(method);
534}
535
536/*
537 * @brief This API checks for env var fitconfig.
538 * If not initialised OR updated as per the current system type,
539 * update this env var and reboot the system.
540 *
541 * @param[in] systemType IM kwd in vpd tells about which system type it is.
542 * */
543void setDevTreeEnv(const string& systemType)
544{
545 string newDeviceTree;
546
547 if (deviceTreeSystemTypeMap.find(systemType) !=
548 deviceTreeSystemTypeMap.end())
549 {
550 newDeviceTree = deviceTreeSystemTypeMap.at(systemType);
551 }
552
553 string readVarValue;
554 bool envVarFound = false;
555
556 vector<string> output = executeCmd("/sbin/fw_printenv");
557 for (const auto& entry : output)
558 {
559 size_t pos = entry.find("=");
560 string key = entry.substr(0, pos);
561 if (key != "fitconfig")
562 {
563 continue;
564 }
565
566 envVarFound = true;
567 if (pos + 1 < entry.size())
568 {
569 readVarValue = entry.substr(pos + 1);
570 if (readVarValue.find(newDeviceTree) != string::npos)
571 {
572 // fitconfig is Updated. No action needed
573 break;
574 }
575 }
576 // set env and reboot and break.
577 setEnvAndReboot(key, newDeviceTree);
578 exit(0);
579 }
580
581 // check If env var Not found
582 if (!envVarFound)
583 {
584 setEnvAndReboot("fitconfig", newDeviceTree);
585 }
586}
587
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530588/**
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500589 * @brief API to call VPD manager to write VPD to EEPROM.
590 * @param[in] Object path.
591 * @param[in] record to be updated.
592 * @param[in] keyword to be updated.
593 * @param[in] keyword data to be updated
594 */
595void updateHardware(const string& objectName, const string& recName,
596 const string& kwdName, const Binary& data)
597{
598 try
599 {
600 auto bus = sdbusplus::bus::new_default();
601 auto properties =
602 bus.new_method_call(BUSNAME, OBJPATH, IFACE, "WriteKeyword");
603 properties.append(
604 static_cast<sdbusplus::message::object_path>(objectName));
605 properties.append(recName);
606 properties.append(kwdName);
607 properties.append(data);
608 bus.call(properties);
609 }
610 catch (const sdbusplus::exception::SdBusError& e)
611 {
612 std::string what =
613 "VPDManager WriteKeyword api failed for inventory path " +
614 objectName;
615 what += " record " + recName;
616 what += " keyword " + kwdName;
617 what += " with bus error = " + std::string(e.what());
618
619 // map to hold additional data in case of logging pel
620 PelAdditionalData additionalData{};
621 additionalData.emplace("CALLOUT_INVENTORY_PATH", objectName);
622 additionalData.emplace("DESCRIPTION", what);
623 createPEL(additionalData, errIntfForBusFailure);
624 }
625}
626
627/**
628 * @brief API to check if we need to restore system VPD
629 * This functionality is only applicable for IPZ VPD data.
630 * @param[in] vpdMap - IPZ vpd map
631 * @param[in] objectPath - Object path for the FRU
632 * @return EEPROMs with records and keywords updated at standby
633 */
634std::vector<RestoredEeproms> restoreSystemVPD(Parsed& vpdMap,
635 const string& objectPath)
636{
637 // the list of keywords for VSYS record is as per the S0 system. Should be
638 // updated for another type of systems
639 static std::unordered_map<std::string, std::vector<std::string>> svpdKwdMap{
640 {"VSYS", {"BR", "TM", "SE", "SU", "RB"}},
641 {"VCEN", {"FC", "SE"}},
642 {"LXR0", {"LX"}}};
643
644 // vector to hold all the EEPROMs updated at standby
645 std::vector<RestoredEeproms> updatedEeproms = {};
646
647 for (const auto& systemRecKwdPair : svpdKwdMap)
648 {
649 auto it = vpdMap.find(systemRecKwdPair.first);
650
651 // check if record is found in map we got by parser
652 if (it != vpdMap.end())
653 {
654 const auto& kwdListForRecord = systemRecKwdPair.second;
655 for (const auto& keyword : kwdListForRecord)
656 {
657 DbusPropertyMap& kwdValMap = it->second;
658 auto iterator = kwdValMap.find(keyword);
659
660 if (iterator != kwdValMap.end())
661 {
662 string& kwdValue = iterator->second;
663
664 // check bus data
665 const string& recordName = systemRecKwdPair.first;
666 const string& busValue = readBusProperty(
667 objectPath, ipzVpdInf + recordName, keyword);
668
669 if (busValue.find_first_not_of(' ') != string::npos)
670 {
671 if (kwdValue.find_first_not_of(' ') != string::npos)
672 {
673 // both the data are present, check for mismatch
674 if (busValue != kwdValue)
675 {
676 string errMsg = "VPD data mismatch on cache "
677 "and hardware for record: ";
678 errMsg += (*it).first;
679 errMsg += " and keyword: ";
680 errMsg += keyword;
681
682 // data mismatch
683 PelAdditionalData additionalData;
684 additionalData.emplace("CALLOUT_INVENTORY_PATH",
685 objectPath);
686
687 additionalData.emplace("DESCRIPTION", errMsg);
688
689 createPEL(additionalData, errIntfForInvalidVPD);
690 }
691 }
692 else
693 {
694 // implies hardware data is blank
695 // update the map
696 Binary busData(busValue.begin(), busValue.end());
697
698 updatedEeproms.push_back(std::make_tuple(
699 objectPath, recordName, keyword, busData));
700 }
701
702 // update the map as well, so that cache data is not
703 // updated as blank while populating VPD map on Dbus in
704 // populateDBus Api
705 kwdValue = busValue;
706 continue;
707 }
708 else if (kwdValue.find_first_not_of(' ') == string::npos)
709 {
710 string errMsg = "VPD is blank on both cache and "
711 "hardware for record: ";
712 errMsg += (*it).first;
713 errMsg += " and keyword: ";
714 errMsg += keyword;
715 errMsg += ". SSR need to update hardware VPD.";
716
717 // both the data are blanks, log PEL
718 PelAdditionalData additionalData;
719 additionalData.emplace("CALLOUT_INVENTORY_PATH",
720 objectPath);
721
722 additionalData.emplace("DESCRIPTION", errMsg);
723
724 // log PEL TODO: Block IPL
725 createPEL(additionalData, errIntfForBlankSystemVPD);
726 continue;
727 }
728 }
729 }
730 }
731 }
732
733 return updatedEeproms;
734}
735
736/**
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530737 * @brief Populate Dbus.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530738 * This method invokes all the populateInterface functions
739 * and notifies PIM about dbus object.
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530740 * @param[in] vpdMap - Either IPZ vpd map or Keyword vpd map based on the
741 * input.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530742 * @param[in] js - Inventory json object
743 * @param[in] filePath - Path of the vpd file
744 * @param[in] preIntrStr - Interface string
745 */
746template <typename T>
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500747static void populateDbus(T& vpdMap, nlohmann::json& js, const string& filePath)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530748{
749 inventory::InterfaceMap interfaces;
750 inventory::ObjectMap objects;
751 inventory::PropertyMap prop;
752
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500753 // map to hold all the keywords whose value has been changed at standby
754 vector<RestoredEeproms> updatedEeproms = {};
755
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500756 bool isSystemVpd = false;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530757 for (const auto& item : js["frus"][filePath])
758 {
759 const auto& objectPath = item["inventoryPath"];
760 sdbusplus::message::object_path object(objectPath);
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530761 isSystemVpd = item.value("isSystemVpd", false);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500762
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530763 // Populate the VPD keywords and the common interfaces only if we
764 // are asked to inherit that data from the VPD, else only add the
765 // extraInterfaces.
766 if (item.value("inherit", true))
767 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500768 if constexpr (is_same<T, Parsed>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530769 {
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500770 if (isSystemVpd)
771 {
772 std::vector<std::string> interfaces = {
773 motherBoardInterface};
774 // call mapper to check for object path creation
775 MapperResponse subTree =
776 getObjectSubtreeForInterfaces(pimPath, 0, interfaces);
777
778 // Skip system vpd restore if object path is not generated
779 // for motherboard, Implies first boot.
780 if (subTree.size() != 0)
781 {
782 assert(
783 (subTree.find(pimPath + std::string(objectPath)) !=
784 subTree.end()));
785
786 updatedEeproms = restoreSystemVPD(vpdMap, objectPath);
787 }
788 else
789 {
790 log<level::ERR>("No object path found");
791 }
792 }
793
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530794 // Each record in the VPD becomes an interface and all
795 // keyword within the record are properties under that
796 // interface.
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530797 for (const auto& record : vpdMap)
798 {
799 populateFruSpecificInterfaces(
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500800 record.second, ipzVpdInf + record.first, interfaces);
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530801 }
802 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500803 else if constexpr (is_same<T, KeywordVpdMap>::value)
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530804 {
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500805 populateFruSpecificInterfaces(vpdMap, kwdVpdInf, interfaces);
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530806 }
Santosh Puranik88edeb62020-03-02 12:00:09 +0530807 if (js.find("commonInterfaces") != js.end())
808 {
809 populateInterfaces(js["commonInterfaces"], interfaces, vpdMap,
810 isSystemVpd);
811 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530812 }
Santosh Puranik0859eb62020-03-16 02:56:29 -0500813 else
814 {
815 // Check if we have been asked to inherit specific record(s)
Alpana Kumari58e22142020-05-05 00:22:12 -0500816 if constexpr (is_same<T, Parsed>::value)
Santosh Puranik0859eb62020-03-16 02:56:29 -0500817 {
818 if (item.find("copyRecords") != item.end())
819 {
820 for (const auto& record : item["copyRecords"])
821 {
822 const string& recordName = record;
823 if (vpdMap.find(recordName) != vpdMap.end())
824 {
825 populateFruSpecificInterfaces(
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500826 vpdMap.at(recordName), ipzVpdInf + recordName,
Santosh Puranik0859eb62020-03-16 02:56:29 -0500827 interfaces);
828 }
829 }
830 }
831 }
832 }
Alpana Kumari58e22142020-05-05 00:22:12 -0500833 if (item.value("inheritEI", true))
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530834 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500835 // Populate interfaces and properties that are common to every FRU
836 // and additional interface that might be defined on a per-FRU
837 // basis.
838 if (item.find("extraInterfaces") != item.end())
839 {
840 populateInterfaces(item["extraInterfaces"], interfaces, vpdMap,
841 isSystemVpd);
842 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530843 }
844 objects.emplace(move(object), move(interfaces));
845 }
846
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530847 if (isSystemVpd)
848 {
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530849 vector<uint8_t> imVal;
850 if constexpr (is_same<T, Parsed>::value)
851 {
852 auto property = vpdMap.find("VSBP");
853 if (property != vpdMap.end())
854 {
855 auto value = (property->second).find("IM");
856 if (value != (property->second).end())
857 {
858 copy(value->second.begin(), value->second.end(),
859 back_inserter(imVal));
860 }
861 }
862 }
863
864 fs::path target;
865 fs::path link = INVENTORY_JSON_SYM_LINK;
866
867 ostringstream oss;
868 for (auto& i : imVal)
869 {
870 oss << setw(2) << setfill('0') << hex << static_cast<int>(i);
871 }
872 string imValStr = oss.str();
873
Alpana Kumari65b83602020-09-01 00:24:56 -0500874 if (imValStr == RAINIER_4U) // 4U
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530875 {
876 target = INVENTORY_JSON_4U;
877 }
Alpana Kumari65b83602020-09-01 00:24:56 -0500878 else if (imValStr == RAINIER_2U) // 2U
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530879 {
880 target = INVENTORY_JSON_2U;
881 }
Santosh Puranik4641bff2020-11-30 20:26:44 +0530882 else if (imValStr == EVEREST)
883 {
884 target = INVENTORY_JSON_EVEREST;
885 }
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530886
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530887 // Create the directory for hosting the symlink
888 fs::create_directories(VPD_FILES_PATH);
889 // unlink the symlink previously created (if any)
PriyangaRamasamy83a1d5d2020-04-30 19:15:43 +0530890 remove(INVENTORY_JSON_SYM_LINK);
891 // create a new symlink based on the system
892 fs::create_symlink(target, link);
893
894 // Reloading the json
895 ifstream inventoryJson(link);
896 auto js = json::parse(inventoryJson);
897 inventoryJson.close();
898
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530899 inventory::ObjectMap primeObject = primeInventory(js, vpdMap);
900 objects.insert(primeObject.begin(), primeObject.end());
Alpana Kumari65b83602020-09-01 00:24:56 -0500901
902 // set the U-boot environment variable for device-tree
903 setDevTreeEnv(imValStr);
SunnySrivastava19849094d4f2020-08-05 09:32:29 -0500904
905 // if system VPD has been restored at standby, update the EEPROM
906 for (const auto& item : updatedEeproms)
907 {
908 updateHardware(get<0>(item), get<1>(item), get<2>(item),
909 get<3>(item));
910 }
PriyangaRamasamy8e140a12020-04-13 19:24:03 +0530911 }
912
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530913 // Notify PIM
914 inventory::callPIM(move(objects));
915}
916
917int main(int argc, char** argv)
918{
919 int rc = 0;
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500920 string file{};
921 json js{};
922
923 // map to hold additional data in case of logging pel
924 PelAdditionalData additionalData{};
925
926 // this is needed to hold base fru inventory path in case there is ECC or
927 // vpd exception while parsing the file
928 std::string baseFruInventoryPath = {};
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530929
930 try
931 {
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530932 App app{"ibm-read-vpd - App to read IPZ format VPD, parse it and store "
933 "in DBUS"};
934 string file{};
935
936 app.add_option("-f, --file", file, "File containing VPD (IPZ/KEYWORD)")
Alpana Kumari2f793042020-08-18 05:51:03 -0500937 ->required();
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530938
939 CLI11_PARSE(app, argc, argv);
940
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530941 auto jsonToParse = INVENTORY_JSON_DEFAULT;
942
943 // If the symlink exists, it means it has been setup for us, switch the
944 // path
945 if (fs::exists(INVENTORY_JSON_SYM_LINK))
946 {
947 jsonToParse = INVENTORY_JSON_SYM_LINK;
948 }
949
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530950 // Make sure that the file path we get is for a supported EEPROM
Santosh Puranik0246a4d2020-11-04 16:57:39 +0530951 ifstream inventoryJson(jsonToParse);
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500952 if (!inventoryJson)
953 {
954 throw(
955 (VpdJsonException("Failed to access Json path", jsonToParse)));
956 }
957
958 try
959 {
960 js = json::parse(inventoryJson);
961 }
962 catch (json::parse_error& ex)
963 {
964 throw((VpdJsonException("Json parsing failed", jsonToParse)));
965 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530966
967 if ((js.find("frus") == js.end()) ||
968 (js["frus"].find(file) == js["frus"].end()))
969 {
Alpana Kumari58e22142020-05-05 00:22:12 -0500970 cout << "Device path not in JSON, ignoring" << endl;
Santosh Puranik88edeb62020-03-02 12:00:09 +0530971 return 0;
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +0530972 }
973
Alpana Kumari2f793042020-08-18 05:51:03 -0500974 if (!fs::exists(file))
975 {
976 cout << "Device path: " << file
977 << " does not exist. Spurious udev event? Exiting." << endl;
978 return 0;
979 }
980
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500981 baseFruInventoryPath = js["frus"][file][0]["inventoryPath"];
Santosh Puranik85893752020-11-10 21:31:43 +0530982 // Check if we can read the VPD file based on the power state
983 if (js["frus"][file].at(0).value("powerOffOnly", false))
984 {
985 if ("xyz.openbmc_project.State.Chassis.PowerState.On" ==
986 getPowerState())
987 {
988 cout << "This VPD cannot be read when power is ON" << endl;
989 return 0;
990 }
991 }
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -0500992
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500993 Binary vpdVector = getVpdDataInVector(js, file);
Alpana Kumari65b83602020-09-01 00:24:56 -0500994 ParserInterface* parser = ParserFactory::getParser(move(vpdVector));
SunnySrivastava1984e12b1812020-05-26 02:23:11 -0500995
996 variant<KeywordVpdMap, Store> parseResult;
997 parseResult = parser->parse();
998
Alpana Kumari2f793042020-08-18 05:51:03 -0500999 try
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301000 {
Alpana Kumari2f793042020-08-18 05:51:03 -05001001 Binary vpdVector = getVpdDataInVector(js, file);
1002 ParserInterface* parser = ParserFactory::getParser(move(vpdVector));
SunnySrivastava1984e12b1812020-05-26 02:23:11 -05001003
Alpana Kumari2f793042020-08-18 05:51:03 -05001004 variant<KeywordVpdMap, Store> parseResult;
1005 parseResult = parser->parse();
1006 if (auto pVal = get_if<Store>(&parseResult))
1007 {
1008 populateDbus(pVal->getVpdMap(), js, file);
1009 }
1010 else if (auto pVal = get_if<KeywordVpdMap>(&parseResult))
1011 {
1012 populateDbus(*pVal, js, file);
1013 }
1014
1015 // release the parser object
1016 ParserFactory::freeParser(parser);
1017 }
1018 catch (exception& e)
1019 {
1020 postFailAction(js, file);
1021 throw e;
1022 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301023 }
SunnySrivastava1984a20be8e2020-08-26 02:00:50 -05001024 catch (const VpdJsonException& ex)
1025 {
1026 additionalData.emplace("JSON_PATH", ex.getJsonPath());
1027 additionalData.emplace("DESCRIPTION", ex.what());
1028 createPEL(additionalData, errIntfForJsonFailure);
1029
1030 cerr << ex.what() << "\n";
1031 rc = -1;
1032 }
1033 catch (const VpdEccException& ex)
1034 {
1035 additionalData.emplace("DESCRIPTION", "ECC check failed");
1036 additionalData.emplace("CALLOUT_INVENTORY_PATH",
1037 INVENTORY_PATH + baseFruInventoryPath);
1038 createPEL(additionalData, errIntfForEccCheckFail);
1039
1040 cerr << ex.what() << "\n";
1041 rc = -1;
1042 }
1043 catch (const VpdDataException& ex)
1044 {
1045 additionalData.emplace("DESCRIPTION", "Invalid VPD data");
1046 additionalData.emplace("CALLOUT_INVENTORY_PATH",
1047 INVENTORY_PATH + baseFruInventoryPath);
1048 createPEL(additionalData, errIntfForInvalidVPD);
1049
1050 cerr << ex.what() << "\n";
1051 rc = -1;
1052 }
PriyangaRamasamyabb87ed2019-11-19 17:25:35 +05301053 catch (exception& e)
1054 {
1055 cerr << e.what() << "\n";
1056 rc = -1;
1057 }
1058
1059 return rc;
1060}