blob: 45e87595231fb9fde10ba15f0fb86be85062547b [file] [log] [blame]
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +05301#include "config.h"
2
Sunny Srivastava867ee752025-04-15 12:24:23 +05303#include "ibm_handler.hpp"
4
Anupama B R56e45372025-06-19 12:54:44 -05005#include "listener.hpp"
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +05306#include "parser.hpp"
7
Sunny Srivastava78a50422025-04-25 11:17:56 +05308#include <utility/common_utility.hpp>
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +05309#include <utility/dbus_utility.hpp>
10#include <utility/json_utility.hpp>
11#include <utility/vpd_specific_utility.hpp>
12
Sunny Srivastava867ee752025-04-15 12:24:23 +053013namespace vpd
14{
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +053015IbmHandler::IbmHandler(
16 std::shared_ptr<Worker>& o_worker,
17 std::shared_ptr<BackupAndRestore>& o_backupAndRestoreObj,
18 const std::shared_ptr<sdbusplus::asio::dbus_interface>& i_iFace,
19 const std::shared_ptr<boost::asio::io_context>& i_ioCon,
20 const std::shared_ptr<sdbusplus::asio::connection>& i_asioConnection) :
21 m_worker(o_worker), m_backupAndRestoreObj(o_backupAndRestoreObj),
22 m_interface(i_iFace), m_ioContext(i_ioCon),
23 m_asioConnection(i_asioConnection)
24{
25 if (dbusUtility::isChassisPowerOn())
26 {
27 // At power on, less number of FRU(s) needs collection. we can scale
28 // down the threads to reduce CPU utilization.
29 m_worker = std::make_shared<Worker>(INVENTORY_JSON_DEFAULT,
30 constants::VALUE_1);
31 }
32 else
33 {
34 // Initialize with default configuration
35 m_worker = std::make_shared<Worker>(INVENTORY_JSON_DEFAULT);
36 }
37
38 // Set up minimal things that is needed before bus name is claimed.
Sunny Srivastava78a50422025-04-25 11:17:56 +053039 performInitialSetup();
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +053040
41 if (!m_sysCfgJsonObj.empty() &&
42 jsonUtility::isBackupAndRestoreRequired(m_sysCfgJsonObj))
43 {
44 try
45 {
46 m_backupAndRestoreObj =
47 std::make_shared<BackupAndRestore>(m_sysCfgJsonObj);
48 }
49 catch (const std::exception& l_ex)
50 {
51 logging::logMessage("Back up and restore instantiation failed. {" +
52 std::string(l_ex.what()) + "}");
53
54 EventLogger::createSyncPel(
55 EventLogger::getErrorType(l_ex), types::SeverityType::Warning,
56 __FILE__, __FUNCTION__, 0, EventLogger::getErrorMsg(l_ex),
57 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
58 }
59 }
60
Anupama B Rc7565ed2025-06-19 02:08:39 -050061 // Instantiate Listener object
Anupama B R56e45372025-06-19 12:54:44 -050062 m_eventListener = std::make_shared<Listener>(m_worker, m_asioConnection);
63 m_eventListener->registerAssetTagChangeCallback();
64 m_eventListener->registerHostStateChangeCallback();
Souvik Roy5c3a1562025-07-02 01:39:44 -050065 m_eventListener->registerPresenceChangeCallback();
Anupama B Rc7565ed2025-06-19 02:08:39 -050066
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +053067 // set async timer to detect if system VPD is published on D-Bus.
68 SetTimerToDetectSVPDOnDbus();
69
70 // set async timer to detect if VPD collection is done.
71 SetTimerToDetectVpdCollectionStatus();
72
73 // Instantiate GpioMonitor class
74 m_gpioMonitor =
75 std::make_shared<GpioMonitor>(m_sysCfgJsonObj, m_worker, m_ioContext);
76}
77
Sunny Srivastavac74c8ef2025-04-16 12:45:27 +053078void IbmHandler::SetTimerToDetectSVPDOnDbus()
79{
80 try
81 {
82 static boost::asio::steady_timer timer(*m_ioContext);
83
84 // timer for 2 seconds
85 auto asyncCancelled = timer.expires_after(std::chrono::seconds(2));
86
87 (asyncCancelled == 0) ? logging::logMessage("Timer started")
88 : logging::logMessage("Timer re-started");
89
90 timer.async_wait([this](const boost::system::error_code& ec) {
91 if (ec == boost::asio::error::operation_aborted)
92 {
93 throw std::runtime_error(
94 std::string(__FUNCTION__) +
95 ": Timer to detect system VPD collection status was aborted.");
96 }
97
98 if (ec)
99 {
100 throw std::runtime_error(
101 std::string(__FUNCTION__) +
102 ": Timer to detect System VPD collection failed");
103 }
104
105 if (m_worker->isSystemVPDOnDBus())
106 {
107 // cancel the timer
108 timer.cancel();
109
110 // Triggering FRU VPD collection. Setting status to "In
111 // Progress".
112 m_interface->set_property("CollectionStatus",
113 std::string("InProgress"));
114 m_worker->collectFrusFromJson();
115 }
116 });
117 }
118 catch (const std::exception& l_ex)
119 {
120 EventLogger::createAsyncPel(
121 EventLogger::getErrorType(l_ex), types::SeverityType::Critical,
122 __FILE__, __FUNCTION__, 0,
123 std::string("Collection for FRUs failed with reason:") +
124 EventLogger::getErrorMsg(l_ex),
125 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
126 }
127}
128
129void IbmHandler::SetTimerToDetectVpdCollectionStatus()
130{
131 // Keeping max retry for 2 minutes. TODO: Make it configurable based on
132 // system type.
133 static constexpr auto MAX_RETRY = 12;
134
135 static boost::asio::steady_timer l_timer(*m_ioContext);
136 static uint8_t l_timerRetry = 0;
137
138 auto l_asyncCancelled = l_timer.expires_after(std::chrono::seconds(10));
139
140 (l_asyncCancelled == 0)
141 ? logging::logMessage("Collection Timer started")
142 : logging::logMessage("Collection Timer re-started");
143
144 l_timer.async_wait([this](const boost::system::error_code& ec) {
145 if (ec == boost::asio::error::operation_aborted)
146 {
147 throw std::runtime_error(
148 "Timer to detect thread collection status was aborted");
149 }
150
151 if (ec)
152 {
153 throw std::runtime_error(
154 "Timer to detect thread collection failed");
155 }
156
157 if (m_worker->isAllFruCollectionDone())
158 {
159 // cancel the timer
160 l_timer.cancel();
161 processFailedEeproms();
162
163 // update VPD for powerVS system.
164 ConfigurePowerVsSystem();
165
166 std::cout << "m_worker->isSystemVPDOnDBus() completed" << std::endl;
167 m_interface->set_property("CollectionStatus",
168 std::string("Completed"));
169
170 if (m_backupAndRestoreObj)
171 {
172 m_backupAndRestoreObj->backupAndRestore();
173 }
174 }
175 else
176 {
177 auto l_threadCount = m_worker->getActiveThreadCount();
178 if (l_timerRetry == MAX_RETRY)
179 {
180 l_timer.cancel();
181 logging::logMessage("Taking too long. Active thread = " +
182 std::to_string(l_threadCount));
183 }
184 else
185 {
186 l_timerRetry++;
187 logging::logMessage("Collection is in progress for [" +
188 std::to_string(l_threadCount) + "] FRUs.");
189
190 SetTimerToDetectVpdCollectionStatus();
191 }
192 }
193 });
194}
195
196void IbmHandler::checkAndUpdatePowerVsVpd(
197 const nlohmann::json& i_powerVsJsonObj,
198 std::vector<std::string>& o_failedPathList)
199{
200 for (const auto& [l_fruPath, l_recJson] : i_powerVsJsonObj.items())
201 {
202 nlohmann::json l_sysCfgJsonObj{};
203 if (m_worker.get() != nullptr)
204 {
205 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
206 }
207
208 // The utility method will handle emty JSON case. No explicit
209 // handling required here.
210 auto l_inventoryPath = jsonUtility::getInventoryObjPathFromJson(
211 l_sysCfgJsonObj, l_fruPath);
212
213 // Mark it as failed if inventory path not found in JSON.
214 if (l_inventoryPath.empty())
215 {
216 o_failedPathList.push_back(l_fruPath);
217 continue;
218 }
219
220 // check if the FRU is present
221 if (!dbusUtility::isInventoryPresent(l_inventoryPath))
222 {
223 logging::logMessage(
224 "Inventory not present, skip updating part number. Path: " +
225 l_inventoryPath);
226 continue;
227 }
228
229 // check if the FRU needs CCIN check before updating PN.
230 if (l_recJson.contains("CCIN"))
231 {
232 const auto& l_ccinFromDbus =
233 vpdSpecificUtility::getCcinFromDbus(l_inventoryPath);
234
235 // Not an ideal situation as CCIN can't be empty.
236 if (l_ccinFromDbus.empty())
237 {
238 o_failedPathList.push_back(l_fruPath);
239 continue;
240 }
241
242 std::vector<std::string> l_ccinListFromJson = l_recJson["CCIN"];
243
244 if (find(l_ccinListFromJson.begin(), l_ccinListFromJson.end(),
245 l_ccinFromDbus) == l_ccinListFromJson.end())
246 {
247 // Don't update PN in this case.
248 continue;
249 }
250 }
251
252 for (const auto& [l_recordName, l_kwdJson] : l_recJson.items())
253 {
254 // Record name can't be CCIN, skip processing as it is there for PN
255 // update based on CCIN check.
256 if (l_recordName == constants::kwdCCIN)
257 {
258 continue;
259 }
260
261 for (const auto& [l_kwdName, l_kwdValue] : l_kwdJson.items())
262 {
263 // Is value of type array.
264 if (!l_kwdValue.is_array())
265 {
266 o_failedPathList.push_back(l_fruPath);
267 continue;
268 }
269
270 // Get current FRU Part number.
271 auto l_retVal = dbusUtility::readDbusProperty(
272 constants::pimServiceName, l_inventoryPath,
273 constants::viniInf, constants::kwdFN);
274
275 auto l_ptrToFn = std::get_if<types::BinaryVector>(&l_retVal);
276
277 if (!l_ptrToFn)
278 {
279 o_failedPathList.push_back(l_fruPath);
280 continue;
281 }
282
283 types::BinaryVector l_binaryKwdValue =
284 l_kwdValue.get<types::BinaryVector>();
285 if (l_binaryKwdValue == (*l_ptrToFn))
286 {
287 continue;
288 }
289
290 // Update part number only if required.
291 std::shared_ptr<Parser> l_parserObj =
292 std::make_shared<Parser>(l_fruPath, l_sysCfgJsonObj);
293 if (l_parserObj->updateVpdKeyword(std::make_tuple(
294 l_recordName, l_kwdName, l_binaryKwdValue)) ==
295 constants::FAILURE)
296 {
297 o_failedPathList.push_back(l_fruPath);
298 continue;
299 }
300
301 // update the Asset interface Spare part number explicitly.
302 if (!dbusUtility::callPIM(types::ObjectMap{
303 {l_inventoryPath,
304 {{constants::assetInf,
305 {{"SparePartNumber",
306 std::string(l_binaryKwdValue.begin(),
307 l_binaryKwdValue.end())}}}}}}))
308 {
309 logging::logMessage(
310 "Updating Spare Part Number under Asset interface failed for path [" +
311 l_inventoryPath + "]");
312 }
313
314 // Just needed for logging.
315 std::string l_initialPartNum((*l_ptrToFn).begin(),
316 (*l_ptrToFn).end());
317 std::string l_finalPartNum(l_binaryKwdValue.begin(),
318 l_binaryKwdValue.end());
319 logging::logMessage(
320 "FRU Part number updated for path [" + l_inventoryPath +
321 "]" + "From [" + l_initialPartNum + "]" + " to [" +
322 l_finalPartNum + "]");
323 }
324 }
325 }
326}
327
328void IbmHandler::ConfigurePowerVsSystem()
329{
330 std::vector<std::string> l_failedPathList;
331 try
332 {
333 types::BinaryVector l_imValue = dbusUtility::getImFromDbus();
334 if (l_imValue.empty())
335 {
336 throw DbusException("Invalid IM value read from Dbus");
337 }
338
339 if (!vpdSpecificUtility::isPowerVsConfiguration(l_imValue))
340 {
341 // TODO: Should booting be blocked in case of some
342 // misconfigurations?
343 return;
344 }
345
346 const nlohmann::json& l_powerVsJsonObj =
347 jsonUtility::getPowerVsJson(l_imValue);
348
349 if (l_powerVsJsonObj.empty())
350 {
351 throw std::runtime_error("PowerVS Json not found");
352 }
353
354 checkAndUpdatePowerVsVpd(l_powerVsJsonObj, l_failedPathList);
355
356 if (!l_failedPathList.empty())
357 {
358 throw std::runtime_error(
359 "Part number update failed for following paths: ");
360 }
361 }
362 catch (const std::exception& l_ex)
363 {
364 // TODO log appropriate PEL
365 }
366}
367
368void IbmHandler::processFailedEeproms()
369{
370 if (m_worker.get() != nullptr)
371 {
372 // TODO:
373 // - iterate through list of EEPROMs for which thread creation has
374 // failed
375 // - For each failed EEPROM, trigger VPD collection
376 m_worker->getFailedEepromPaths().clear();
377 }
378}
Sunny Srivastava380efbb2025-04-25 10:28:30 +0530379
Sunny Srivastava78a50422025-04-25 11:17:56 +0530380void IbmHandler::primeSystemBlueprint()
381{
382 if (m_sysCfgJsonObj.empty())
383 {
384 return;
385 }
386
387 const nlohmann::json& l_listOfFrus =
388 m_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
389
390 for (const auto& l_itemFRUS : l_listOfFrus.items())
391 {
392 const std::string& l_vpdFilePath = l_itemFRUS.key();
393
394 if (l_vpdFilePath == SYSTEM_VPD_FILE_PATH)
395 {
396 continue;
397 }
398
399 // Prime the inventry for FRUs which
400 // are not present/processing had some error.
401 if (m_worker.get() != nullptr &&
402 !m_worker->primeInventory(l_vpdFilePath))
403 {
404 logging::logMessage(
405 "Priming of inventory failed for FRU " + l_vpdFilePath);
406 }
407 }
408}
409
410void IbmHandler::enableMuxChips()
411{
412 if (m_sysCfgJsonObj.empty())
413 {
414 // config JSON should not be empty at this point of execution.
415 throw std::runtime_error("Config JSON is empty. Can't enable muxes");
416 return;
417 }
418
419 if (!m_sysCfgJsonObj.contains("muxes"))
420 {
421 logging::logMessage("No mux defined for the system in config JSON");
422 return;
423 }
424
425 // iterate over each MUX detail and enable them.
426 for (const auto& item : m_sysCfgJsonObj["muxes"])
427 {
428 if (item.contains("holdidlepath"))
429 {
430 std::string cmd = "echo 0 > ";
431 cmd += item["holdidlepath"];
432
433 logging::logMessage("Enabling mux with command = " + cmd);
434
435 commonUtility::executeCmd(cmd);
436 continue;
437 }
438
439 logging::logMessage(
440 "Mux Entry does not have hold idle path. Can't enable the mux");
441 }
442}
443
444void IbmHandler::performInitialSetup()
445{
446 try
447 {
Anupama B R281e2d42025-05-05 10:05:13 -0500448 if (m_worker.get() == nullptr)
449 {
450 throw std::runtime_error(
451 "Worker object not found. Can't perform initial setup.");
452 }
453
454 m_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
Sunny Srivastava78a50422025-04-25 11:17:56 +0530455 if (!dbusUtility::isChassisPowerOn())
456 {
Anupama B R281e2d42025-05-05 10:05:13 -0500457 m_worker->setDeviceTreeAndJson();
458
459 // Since the above function setDeviceTreeAndJson can change the json
460 // which is used, we would need to reacquire the json object again
461 // here.
Sunny Srivastava78a50422025-04-25 11:17:56 +0530462 m_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
Anupama B R281e2d42025-05-05 10:05:13 -0500463
Anupama B Rec7f8862025-05-23 01:21:01 -0500464 if (isPrimingRequired())
465 {
466 primeSystemBlueprint();
467 }
Sunny Srivastava78a50422025-04-25 11:17:56 +0530468 }
469
470 // Enable all mux which are used for connecting to the i2c on the
471 // pcie slots for pcie cards. These are not enabled by kernel due to
472 // an issue seen with Castello cards, where the i2c line hangs on a
473 // probe.
474 enableMuxChips();
475
476 // Nothing needs to be done. Service restarted or BMC re-booted for
477 // some reason at system power on.
Sunny Srivastava78a50422025-04-25 11:17:56 +0530478 }
479 catch (const std::exception& l_ex)
480 {
481 // Any issue in system's inital set up is handled in this catch. Error
482 // will not propogate to manager.
483 EventLogger::createSyncPel(
484 EventLogger::getErrorType(l_ex), types::SeverityType::Critical,
485 __FILE__, __FUNCTION__, 0, EventLogger::getErrorMsg(l_ex),
486 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
487 }
488}
489
Anupama B Rec7f8862025-05-23 01:21:01 -0500490bool IbmHandler::isPrimingRequired() const noexcept
491{
492 try
493 {
494 // get all object paths under PIM
495 const auto l_objectPaths = dbusUtility::GetSubTreePaths(
496 constants::systemInvPath, 0,
497 std::vector<std::string>{constants::vpdCollectionInterface});
498
499 const nlohmann::json& l_listOfFrus =
500 m_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
501
502 size_t l_invPathCount = 0;
503
504 for (const auto& l_itemFRUS : l_listOfFrus.items())
505 {
506 for (const auto& l_Fru : l_itemFRUS.value())
507 {
508 if (l_Fru.contains("ccin") || (l_Fru.contains("noprime") &&
509 l_Fru.value("noprime", false)))
510 {
511 continue;
512 }
513
514 l_invPathCount += 1;
515 }
516 }
517 return ((l_objectPaths.size() >= l_invPathCount) ? false : true);
518 }
519 catch (const std::exception& l_ex)
520 {
521 logging::logMessage(
522 "Error while checking is priming required or not, error: " +
523 std::string(l_ex.what()));
524 }
525
526 // In case of any error, perform priming, as it's unclear whether priming is
527 // required.
528 return true;
529}
Sunny Srivastava867ee752025-04-15 12:24:23 +0530530} // namespace vpd