1 #include "config.h"
2
3 #include "item_updater.hpp"
4
5 #include "images.hpp"
6 #include "serialize.hpp"
7 #include "version.hpp"
8 #include "xyz/openbmc_project/Software/ExtendedVersion/server.hpp"
9 #include "xyz/openbmc_project/Software/Version/server.hpp"
10
11 #include <phosphor-logging/elog-errors.hpp>
12 #include <phosphor-logging/elog.hpp>
13 #include <phosphor-logging/lg2.hpp>
14 #include <xyz/openbmc_project/Common/error.hpp>
15 #include <xyz/openbmc_project/Software/Image/error.hpp>
16
17 #include <filesystem>
18 #include <fstream>
19 #include <queue>
20 #include <set>
21 #include <string>
22 #include <system_error>
23
24 namespace phosphor
25 {
26 namespace software
27 {
28 namespace updater
29 {
30
31 // When you see server:: you know we're referencing our base class
32 namespace server = sdbusplus::server::xyz::openbmc_project::software;
33 namespace control = sdbusplus::server::xyz::openbmc_project::control;
34
35 PHOSPHOR_LOG2_USING;
36 using namespace phosphor::logging;
37 using namespace sdbusplus::error::xyz::openbmc_project::software::image;
38 using namespace phosphor::software::image;
39 namespace fs = std::filesystem;
40 using NotAllowed = sdbusplus::error::xyz::openbmc_project::common::NotAllowed;
41
createActivation(sdbusplus::message_t & msg)42 void ItemUpdater::createActivation(sdbusplus::message_t& msg)
43 {
44 using SVersion = server::Version;
45 using VersionPurpose = SVersion::VersionPurpose;
46
47 sdbusplus::message::object_path objPath;
48 auto purpose = VersionPurpose::Unknown;
49 std::string extendedVersion;
50 std::string version;
51 std::map<std::string,
52 std::map<std::string,
53 std::variant<std::string, std::vector<std::string>>>>
54 interfaces;
55 msg.read(objPath, interfaces);
56 std::string path(std::move(objPath));
57 std::string filePath;
58 std::vector<std::string> compatibleNames;
59
60 for (const auto& intf : interfaces)
61 {
62 if (intf.first == VERSION_IFACE)
63 {
64 for (const auto& property : intf.second)
65 {
66 if (property.first == "Purpose")
67 {
68 auto value = SVersion::convertVersionPurposeFromString(
69 std::get<std::string>(property.second));
70 if (value == VersionPurpose::BMC ||
71 #ifdef HOST_BIOS_UPGRADE
72 value == VersionPurpose::Host ||
73 #endif
74 value == VersionPurpose::System)
75 {
76 purpose = value;
77 }
78 }
79 else if (property.first == "Version")
80 {
81 version = std::get<std::string>(property.second);
82 }
83 }
84 }
85 else if (intf.first == FILEPATH_IFACE)
86 {
87 for (const auto& property : intf.second)
88 {
89 if (property.first == "Path")
90 {
91 filePath = std::get<std::string>(property.second);
92 }
93 }
94 }
95 else if (intf.first == EXTENDED_VERSION_IFACE)
96 {
97 for (const auto& property : intf.second)
98 {
99 if (property.first == "ExtendedVersion")
100 {
101 extendedVersion = std::get<std::string>(property.second);
102 }
103 }
104 }
105 else if (intf.first == COMPATIBLE_IFACE)
106 {
107 for (const auto& property : intf.second)
108 {
109 if (property.first == "Names")
110 {
111 compatibleNames =
112 std::get<std::vector<std::string>>(property.second);
113 }
114 }
115 }
116 }
117 if (version.empty() || filePath.empty() ||
118 purpose == VersionPurpose::Unknown)
119 {
120 return;
121 }
122
123 // Version id is the last item in the path
124 auto pos = path.rfind('/');
125 if (pos == std::string::npos)
126 {
127 error("No version id found in object path: {PATH}", "PATH", path);
128 return;
129 }
130
131 auto versionId = path.substr(pos + 1);
132
133 if (activations.find(versionId) == activations.end())
134 {
135 verifyAndCreateObjects(versionId, path, version, purpose,
136 extendedVersion, filePath, compatibleNames);
137 }
138 return;
139 }
140
createActivationWithApplyTime(std::string & id,std::string & path,ApplyTimeIntf::RequestedApplyTimes applyTime)141 void ItemUpdater::createActivationWithApplyTime(
142 std::string& id, std::string& path,
143 ApplyTimeIntf::RequestedApplyTimes applyTime)
144 {
145 info("Creating Activation object for id: {ID}", "ID", id);
146 AssociationList associations = {};
147 // Create an association to the BMC inventory item
148 associations.emplace_back(
149 std::make_tuple(ACTIVATION_FWD_ASSOCIATION, ACTIVATION_REV_ASSOCIATION,
150 bmcInventoryPath));
151 activations.insert(std::make_pair(
152 id, std::make_unique<Activation>(
153 bus, path, *this, id, server::Activation::Activations::NotReady,
154 associations)));
155 activations[id]->applyTime = applyTime;
156 }
157
verifyAndCreateObjects(std::string & id,std::string & path,std::string & version,VersionClass::VersionPurpose purpose,std::string & extendedVersion,std::string & filePath,std::vector<std::string> & compatibleNames)158 ActivationIntf::Activations ItemUpdater::verifyAndCreateObjects(
159 std::string& id, std::string& path, std::string& version,
160 VersionClass::VersionPurpose purpose, std::string& extendedVersion,
161 std ::string& filePath, std::vector<std::string>& compatibleNames)
162 {
163 // Determine the Activation state by processing the given image dir.
164 auto activationState = server::Activation::Activations::Invalid;
165 ItemUpdater::ActivationStatus result;
166 if (purpose == VersionPurpose::BMC || purpose == VersionPurpose::System)
167 {
168 result = ItemUpdater::validateSquashFSImage(filePath);
169 }
170 else
171 {
172 result = ItemUpdater::ActivationStatus::ready;
173 }
174
175 AssociationList associations = {};
176
177 if (result == ItemUpdater::ActivationStatus::ready)
178 {
179 activationState = server::Activation::Activations::Ready;
180 // Create an association to the BMC inventory item
181 associations.emplace_back(
182 std::make_tuple(ACTIVATION_FWD_ASSOCIATION,
183 ACTIVATION_REV_ASSOCIATION, bmcInventoryPath));
184 }
185
186 auto versionPtr = std::make_unique<VersionClass>(
187 bus, path, version, purpose, extendedVersion, filePath, compatibleNames,
188 std::bind(&ItemUpdater::erase, this, std::placeholders::_1), id);
189 versionPtr->deleteObject =
190 std::make_unique<phosphor::software::manager::Delete>(
191 bus, path, *versionPtr);
192 versions.insert(std::make_pair(id, std::move(versionPtr)));
193
194 auto activation = activations.find(id);
195 if (activation == activations.end())
196 {
197 activations.insert(std::make_pair(
198 id, std::make_unique<Activation>(bus, path, *this, id,
199 activationState, associations)));
200 }
201 else
202 {
203 activation->second->activation(activationState);
204 }
205 return activationState;
206 }
207
requestActivation(std::string & id)208 bool ItemUpdater::requestActivation(std::string& id)
209 {
210 auto activation = activations.find(id);
211 if (activation == activations.end())
212 {
213 error("Activation object not found for id: {ID}", "ID", id);
214 return false;
215 }
216 activation->second->requestedActivation(
217 server::Activation::RequestedActivations::Active);
218 return true;
219 }
220
updateActivationStatus(std::string & id,ActivationIntf::Activations status)221 bool ItemUpdater::updateActivationStatus(std::string& id,
222 ActivationIntf::Activations status)
223 {
224 auto activation = activations.find(id);
225 if (activation == activations.end())
226 {
227 error("Activation object not found for id: {ID}", "ID", id);
228 return false;
229 }
230 activation->second->activation(status);
231 return true;
232 }
233
createUpdateObject(const std::string & id,const std::string & path)234 void ItemUpdater::createUpdateObject(const std::string& id,
235 const std::string& path)
236 {
237 if (updateManagers.find(id) != updateManagers.end())
238 {
239 error("UpdateManager object already exists for id: {ID}", "ID", id);
240 return;
241 }
242 updateManagers.insert(
243 std::make_pair(id, std::make_unique<UpdateManager>(ctx, path, *this)));
244 }
245
processBMCImage()246 void ItemUpdater::processBMCImage()
247 {
248 using VersionClass = phosphor::software::manager::Version;
249
250 // Check MEDIA_DIR and create if it does not exist
251 try
252 {
253 if (!fs::is_directory(MEDIA_DIR))
254 {
255 fs::create_directory(MEDIA_DIR);
256 }
257 }
258 catch (const fs::filesystem_error& e)
259 {
260 error("Failed to prepare dir: {ERROR}", "ERROR", e);
261 return;
262 }
263
264 // Functional images are mounted as rofs-<location>-functional
265 constexpr auto functionalSuffix = "-functional";
266 bool functionalFound = false;
267
268 // Read os-release from folders under /media/ to get
269 // BMC Software Versions.
270 std::error_code ec;
271 for (const auto& iter : fs::directory_iterator(MEDIA_DIR, ec))
272 {
273 auto activationState = server::Activation::Activations::Active;
274 static const auto BMC_RO_PREFIX_LEN = strlen(BMC_ROFS_PREFIX);
275
276 // Check if the BMC_RO_PREFIXis the prefix of the iter.path
277 if (0 ==
278 iter.path().native().compare(0, BMC_RO_PREFIX_LEN, BMC_ROFS_PREFIX))
279 {
280 // Get the version to calculate the id
281 fs::path releaseFile(OS_RELEASE_FILE);
282 auto osRelease = iter.path() / releaseFile.relative_path();
283 if (!fs::is_regular_file(osRelease, ec))
284 {
285 #ifdef BMC_STATIC_DUAL_IMAGE
286 // For dual image, it is possible that the secondary image is
287 // empty or contains invalid data, ignore such case.
288 info("Unable to find osRelease: {PATH}: {ERROR_MSG}", "PATH",
289 osRelease, "ERROR_MSG", ec.message());
290 #else
291 error("Failed to read osRelease: {PATH}: {ERROR_MSG}", "PATH",
292 osRelease, "ERROR_MSG", ec.message());
293
294 // Try to get the version id from the mount directory name and
295 // call to delete it as this version may be corrupted. Dynamic
296 // volumes created by the UBI layout for example have the id in
297 // the mount directory name. The worst that can happen is that
298 // erase() is called with an non-existent id and returns.
299 auto id = iter.path().native().substr(BMC_RO_PREFIX_LEN);
300 ItemUpdater::erase(id);
301 #endif
302
303 continue;
304 }
305 auto version = VersionClass::getBMCVersion(osRelease);
306 if (version.empty())
307 {
308 error("Failed to read version from osRelease: {PATH}", "PATH",
309 osRelease);
310
311 // Try to delete the version, same as above if the
312 // OS_RELEASE_FILE does not exist.
313 auto id = iter.path().native().substr(BMC_RO_PREFIX_LEN);
314 ItemUpdater::erase(id);
315
316 continue;
317 }
318
319 // The flash location is part of the mount name: rofs-<location>
320 auto flashId = iter.path().native().substr(BMC_RO_PREFIX_LEN);
321
322 auto id = VersionClass::getId(version + flashId);
323
324 // Check if the id has already been added. This can happen if the
325 // BMC partitions / devices were manually flashed with the same
326 // image.
327 if (versions.find(id) != versions.end())
328 {
329 continue;
330 }
331
332 auto functional = false;
333 if (iter.path().native().find(functionalSuffix) !=
334 std::string::npos)
335 {
336 // Set functional to true and remove the functional suffix
337 functional = true;
338 flashId.erase(flashId.length() - strlen(functionalSuffix));
339 functionalFound = true;
340 }
341
342 auto purpose = server::Version::VersionPurpose::BMC;
343 restorePurpose(flashId, purpose);
344
345 // Read os-release from /etc/ to get the BMC extended version
346 std::string extendedVersion =
347 VersionClass::getBMCExtendedVersion(osRelease);
348
349 auto path = fs::path(SOFTWARE_OBJPATH) / id;
350
351 // Create functional association and minimum ship level instance if
352 // this is the functional version
353 if (functional)
354 {
355 createFunctionalAssociation(path);
356
357 if (minimum_ship_level::enabled())
358 {
359 minimumVersionObject =
360 std::make_unique<MinimumVersion>(bus, path);
361 minimumVersionObject->minimumVersion(
362 minimum_ship_level::getMinimumVersion());
363 }
364 }
365
366 AssociationList associations;
367
368 if (activationState == server::Activation::Activations::Active)
369 {
370 // Create an association to the BMC inventory item
371 associations.emplace_back(std::make_tuple(
372 ACTIVATION_FWD_ASSOCIATION, ACTIVATION_REV_ASSOCIATION,
373 bmcInventoryPath));
374
375 // Create an active association since this image is active
376 createActiveAssociation(path);
377 }
378
379 // All updateable firmware components must expose the updateable
380 // association.
381 createUpdateableAssociation(path);
382
383 // Create Version instance for this version.
384 auto versionPtr = std::make_unique<VersionClass>(
385 bus, path, version, purpose, extendedVersion, flashId,
386 std::vector<std::string>(),
387 std::bind(&ItemUpdater::erase, this, std::placeholders::_1),
388 id);
389 if (functional)
390 {
391 versionPtr->setFunctional(true);
392 }
393 else
394 {
395 versionPtr->deleteObject =
396 std::make_unique<phosphor::software::manager::Delete>(
397 bus, path, *versionPtr);
398 }
399 versions.insert(std::make_pair(id, std::move(versionPtr)));
400
401 // Create Activation instance for this version.
402 activations.insert(std::make_pair(
403 id, std::make_unique<Activation>(
404 bus, path, *this, id, activationState, associations)));
405
406 // Create Update object for this version.
407 if (useUpdateDBusInterface)
408 {
409 createUpdateObject(id, path);
410 }
411
412 #ifdef BMC_STATIC_DUAL_IMAGE
413 uint8_t priority;
414 if ((functional && (runningImageSlot == 0)) ||
415 (!functional && (runningImageSlot == 1)))
416 {
417 priority = 0;
418 }
419 else
420 {
421 priority = 1;
422 }
423 activations.find(id)->second->redundancyPriority =
424 std::make_unique<RedundancyPriority>(
425 bus, path, *(activations.find(id)->second), priority,
426 false);
427 #else
428 // If Active, create RedundancyPriority instance for this
429 // version.
430 if (activationState == server::Activation::Activations::Active)
431 {
432 uint8_t priority = std::numeric_limits<uint8_t>::max();
433 if (!restorePriority(flashId, priority))
434 {
435 if (functional)
436 {
437 priority = 0;
438 }
439 else
440 {
441 error(
442 "Unable to restore priority from file for {VERSIONID}",
443 "VERSIONID", id);
444 }
445 }
446 activations.find(id)->second->redundancyPriority =
447 std::make_unique<RedundancyPriority>(
448 bus, path, *(activations.find(id)->second), priority,
449 false);
450 }
451 #endif
452 }
453 }
454
455 if (!functionalFound)
456 {
457 // If there is no functional version found, read the /etc/os-release and
458 // create rofs-<versionId>-functional under MEDIA_DIR, then call again
459 // processBMCImage() to create the D-Bus interface for it.
460 auto version = VersionClass::getBMCVersion(OS_RELEASE_FILE);
461 auto id = phosphor::software::manager::Version::getId(
462 version + functionalSuffix);
463 auto versionFileDir = BMC_ROFS_PREFIX + id + functionalSuffix + "/etc/";
464 try
465 {
466 if (!fs::is_directory(versionFileDir))
467 {
468 fs::create_directories(versionFileDir);
469 }
470 auto versionFilePath =
471 BMC_ROFS_PREFIX + id + functionalSuffix + OS_RELEASE_FILE;
472 fs::create_directory_symlink(OS_RELEASE_FILE, versionFilePath);
473 ItemUpdater::processBMCImage();
474 }
475 catch (const std::exception& e)
476 {
477 error("Exception during processing: {ERROR}", "ERROR", e);
478 }
479 }
480
481 mirrorUbootToAlt();
482 return;
483 }
484
erase(std::string entryId)485 void ItemUpdater::erase(std::string entryId)
486 {
487 // Find entry in versions map
488 auto it = versions.find(entryId);
489 if (it != versions.end())
490 {
491 if (it->second->isFunctional() && ACTIVE_BMC_MAX_ALLOWED > 1)
492 {
493 error(
494 "Version ({VERSIONID}) is currently running on the BMC; unable to remove.",
495 "VERSIONID", entryId);
496 return;
497 }
498 }
499
500 // First call resetUbootEnvVars() so that the BMC points to a valid image to
501 // boot from. If resetUbootEnvVars() is called after the image is actually
502 // deleted from the BMC flash, there'd be a time window where the BMC would
503 // be pointing to a non-existent image to boot from.
504 // Need to remove the entries from the activations map before that call so
505 // that resetUbootEnvVars() doesn't use the version to be deleted.
506 auto iteratorActivations = activations.find(entryId);
507 if (iteratorActivations == activations.end())
508 {
509 error(
510 "Failed to find version ({VERSIONID}) in item updater activations map; unable to remove.",
511 "VERSIONID", entryId);
512 }
513 else
514 {
515 removeAssociations(iteratorActivations->second->path);
516 iteratorActivations->second->deleteImageManagerObject();
517 this->activations.erase(entryId);
518 }
519 ItemUpdater::resetUbootEnvVars();
520
521 if (it != versions.end())
522 {
523 auto flashId = it->second->path();
524
525 // Delete version data if it has been installed on flash (path is not
526 // the upload directory)
527 if (flashId.find(IMG_UPLOAD_DIR) == std::string::npos)
528 {
529 removeReadOnlyPartition(entryId);
530 removePersistDataDirectory(flashId);
531 helper.clearEntry(flashId);
532 }
533
534 // Removing entry in versions map
535 this->versions.erase(entryId);
536 }
537
538 // Removing entry in updateManagers map
539 auto updateManagerIt = updateManagers.find(entryId);
540 if (updateManagerIt != updateManagers.end())
541 {
542 updateManagers.erase(entryId);
543 }
544
545 return;
546 }
547
deleteAll()548 void ItemUpdater::deleteAll()
549 {
550 std::vector<std::string> deletableVersions;
551
552 for (const auto& versionIt : versions)
553 {
554 if (!versionIt.second->isFunctional())
555 {
556 deletableVersions.push_back(versionIt.first);
557 }
558 }
559
560 for (const auto& deletableIt : deletableVersions)
561 {
562 ItemUpdater::erase(deletableIt);
563 }
564
565 helper.cleanup();
566 }
567
568 ItemUpdater::ActivationStatus
validateSquashFSImage(const std::string & filePath)569 ItemUpdater::validateSquashFSImage(const std::string& filePath)
570 {
571 bool valid = true;
572
573 // Record the images which are being updated
574 // First check for the fullimage, then check for images with partitions
575 imageUpdateList.push_back(bmcFullImages);
576 valid = checkImage(filePath, imageUpdateList);
577 if (!valid)
578 {
579 imageUpdateList.clear();
580 imageUpdateList.assign(bmcImages.begin(), bmcImages.end());
581 valid = checkImage(filePath, imageUpdateList);
582 if (!valid)
583 {
584 error("Failed to find the needed BMC images.");
585 return ItemUpdater::ActivationStatus::invalid;
586 }
587 }
588
589 return ItemUpdater::ActivationStatus::ready;
590 }
591
savePriority(const std::string & versionId,uint8_t value)592 void ItemUpdater::savePriority(const std::string& versionId, uint8_t value)
593 {
594 auto flashId = versions.find(versionId)->second->path();
595 storePriority(flashId, value);
596 helper.setEntry(flashId, value);
597 }
598
freePriority(uint8_t value,const std::string & versionId)599 void ItemUpdater::freePriority(uint8_t value, const std::string& versionId)
600 {
601 std::map<std::string, uint8_t> priorityMap;
602
603 // Insert the requested version and priority, it may not exist yet.
604 priorityMap.insert(std::make_pair(versionId, value));
605
606 for (const auto& intf : activations)
607 {
608 if (intf.second->redundancyPriority)
609 {
610 priorityMap.insert(std::make_pair(
611 intf.first, intf.second->redundancyPriority->priority()));
612 }
613 }
614
615 // Lambda function to compare 2 priority values, use <= to allow duplicates
616 typedef std::function<bool(std::pair<std::string, uint8_t>,
617 std::pair<std::string, uint8_t>)>
618 cmpPriority;
619 cmpPriority cmpPriorityFunc =
620 [](const std::pair<std::string, uint8_t>& priority1,
621 const std::pair<std::string, uint8_t>& priority2) {
622 return priority1.second <= priority2.second;
623 };
624
625 // Sort versions by ascending priority
626 std::set<std::pair<std::string, uint8_t>, cmpPriority> prioritySet(
627 priorityMap.begin(), priorityMap.end(), cmpPriorityFunc);
628
629 auto freePriorityValue = value;
630 for (auto& element : prioritySet)
631 {
632 if (element.first == versionId)
633 {
634 continue;
635 }
636 if (element.second == freePriorityValue)
637 {
638 ++freePriorityValue;
639 auto it = activations.find(element.first);
640 it->second->redundancyPriority->sdbusPriority(freePriorityValue);
641 }
642 }
643
644 auto lowestVersion = prioritySet.begin()->first;
645 if (value == prioritySet.begin()->second)
646 {
647 lowestVersion = versionId;
648 }
649 updateUbootEnvVars(lowestVersion);
650 }
651
reset()652 void ItemUpdater::reset()
653 {
654 phosphor::software::updater::Helper::factoryReset();
655
656 info("BMC factory reset will take effect upon reboot.");
657 }
658
removeReadOnlyPartition(const std::string & versionId)659 void ItemUpdater::removeReadOnlyPartition(const std::string& versionId)
660 {
661 auto flashId = versions.find(versionId)->second->path();
662 helper.removeVersion(flashId);
663 }
664
fieldModeEnabled(bool value)665 bool ItemUpdater::fieldModeEnabled(bool value)
666 {
667 // enabling field mode is intended to be one way: false -> true
668 if (value && !control::FieldMode::fieldModeEnabled())
669 {
670 control::FieldMode::fieldModeEnabled(value);
671
672 auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
673 SYSTEMD_INTERFACE, "StartUnit");
674 method.append("obmc-flash-bmc-setenv@fieldmode\\x3dtrue.service",
675 "replace");
676 bus.call_noreply(method);
677
678 method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
679 SYSTEMD_INTERFACE, "StopUnit");
680 method.append("usr-local.mount", "replace");
681 bus.call_noreply(method);
682
683 std::vector<std::string> usrLocal = {"usr-local.mount"};
684
685 method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
686 SYSTEMD_INTERFACE, "MaskUnitFiles");
687 method.append(usrLocal, false, true);
688 bus.call_noreply(method);
689 }
690 else if (!value && control::FieldMode::fieldModeEnabled())
691 {
692 elog<NotAllowed>(xyz::openbmc_project::common::NotAllowed::REASON(
693 "FieldMode is not allowed to be cleared"));
694 }
695
696 return control::FieldMode::fieldModeEnabled();
697 }
698
restoreFieldModeStatus()699 void ItemUpdater::restoreFieldModeStatus()
700 {
701 // The fieldmode u-boot environment variable may not exist since it is not
702 // part of the default environment, run fw_printenv with 2>&1 to ignore the
703 // error message in the journal "Error: "fieldmode" not defined"
704 std::pair<int, std::string> ret =
705 utils::execute("/sbin/fw_printenv", "-n", "fieldmode", "2>&1");
706
707 if (ret.first != 0)
708 {
709 return;
710 }
711
712 // truncate any extra characters off the end to compare against a "true" str
713 std::string result = ret.second.substr(0, 4);
714 if (result == "true")
715 {
716 ItemUpdater::fieldModeEnabled(true);
717 }
718 }
719
setBMCInventoryPath()720 void ItemUpdater::setBMCInventoryPath()
721 {
722 auto depth = 0;
723 auto mapperCall = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH,
724 MAPPER_INTERFACE, "GetSubTreePaths");
725
726 mapperCall.append(INVENTORY_PATH);
727 mapperCall.append(depth);
728 std::vector<std::string> filter = {BMC_INVENTORY_INTERFACE};
729 mapperCall.append(filter);
730
731 try
732 {
733 auto response = bus.call(mapperCall);
734
735 using ObjectPaths = std::vector<std::string>;
736 ObjectPaths result;
737 response.read(result);
738
739 if (!result.empty())
740 {
741 bmcInventoryPath = result.front();
742 }
743 }
744 catch (const sdbusplus::exception_t& e)
745 {
746 error("Error in mapper GetSubTreePath: {ERROR}", "ERROR", e);
747 return;
748 }
749
750 return;
751 }
752
createActiveAssociation(const std::string & path)753 void ItemUpdater::createActiveAssociation(const std::string& path)
754 {
755 assocs.emplace_back(
756 std::make_tuple(ACTIVE_FWD_ASSOCIATION, ACTIVE_REV_ASSOCIATION, path));
757 associations(assocs);
758 }
759
createFunctionalAssociation(const std::string & path)760 void ItemUpdater::createFunctionalAssociation(const std::string& path)
761 {
762 assocs.emplace_back(std::make_tuple(FUNCTIONAL_FWD_ASSOCIATION,
763 FUNCTIONAL_REV_ASSOCIATION, path));
764 associations(assocs);
765 }
766
createUpdateableAssociation(const std::string & path)767 void ItemUpdater::createUpdateableAssociation(const std::string& path)
768 {
769 assocs.emplace_back(std::make_tuple(UPDATEABLE_FWD_ASSOCIATION,
770 UPDATEABLE_REV_ASSOCIATION, path));
771 associations(assocs);
772 }
773
removeAssociations(const std::string & path)774 void ItemUpdater::removeAssociations(const std::string& path)
775 {
776 for (auto iter = assocs.begin(); iter != assocs.end();)
777 {
778 if (std::get<2>(*iter) == path)
779 {
780 iter = assocs.erase(iter);
781 associations(assocs);
782 }
783 else
784 {
785 ++iter;
786 }
787 }
788 }
789
isLowestPriority(uint8_t value)790 bool ItemUpdater::isLowestPriority(uint8_t value)
791 {
792 for (const auto& intf : activations)
793 {
794 if (intf.second->redundancyPriority)
795 {
796 if (intf.second->redundancyPriority->priority() < value)
797 {
798 return false;
799 }
800 }
801 }
802 return true;
803 }
804
updateUbootEnvVars(const std::string & versionId)805 void ItemUpdater::updateUbootEnvVars(const std::string& versionId)
806 {
807 auto it = versions.find(versionId);
808 if (it == versions.end())
809 {
810 return;
811 }
812 auto flashId = it->second->path();
813 helper.updateUbootVersionId(flashId);
814 }
815
resetUbootEnvVars()816 void ItemUpdater::resetUbootEnvVars()
817 {
818 decltype(activations.begin()->second->redundancyPriority->priority())
819 lowestPriority = std::numeric_limits<uint8_t>::max();
820 decltype(activations.begin()->second->versionId) lowestPriorityVersion;
821 for (const auto& intf : activations)
822 {
823 if (!intf.second->redundancyPriority)
824 {
825 // Skip this version if the redundancyPriority is not initialized.
826 continue;
827 }
828
829 if (intf.second->redundancyPriority->priority() <= lowestPriority)
830 {
831 lowestPriority = intf.second->redundancyPriority->priority();
832 lowestPriorityVersion = intf.second->versionId;
833 }
834 }
835
836 // Update the U-boot environment variable to point to the lowest priority
837 updateUbootEnvVars(lowestPriorityVersion);
838 }
839
freeSpace(const Activation & caller)840 void ItemUpdater::freeSpace([[maybe_unused]] const Activation& caller)
841 {
842 #ifdef BMC_STATIC_DUAL_IMAGE
843 // For the golden image case, always remove the version on the primary side
844 std::string versionIDtoErase;
845 for (const auto& iter : activations)
846 {
847 if (iter.second->redundancyPriority &&
848 iter.second->redundancyPriority->priority() == 0)
849 {
850 versionIDtoErase = iter.second->versionId;
851 break;
852 }
853 }
854 if (!versionIDtoErase.empty())
855 {
856 erase(versionIDtoErase);
857 }
858 else
859 {
860 warning("Failed to find version to erase");
861 }
862 #else
863 // Versions with the highest priority in front
864 std::priority_queue<std::pair<int, std::string>,
865 std::vector<std::pair<int, std::string>>,
866 std::less<std::pair<int, std::string>>>
867 versionsPQ;
868
869 std::size_t count = 0;
870 for (const auto& iter : activations)
871 {
872 if ((iter.second.get()->activation() ==
873 server::Activation::Activations::Active) ||
874 (iter.second.get()->activation() ==
875 server::Activation::Activations::Failed))
876 {
877 count++;
878 // Don't put the functional version on the queue since we can't
879 // remove the "running" BMC version.
880 // If ACTIVE_BMC_MAX_ALLOWED <= 1, there is only one active BMC,
881 // so remove functional version as well.
882 // Don't delete the the Activation object that called this function.
883 if ((versions.find(iter.second->versionId)
884 ->second->isFunctional() &&
885 ACTIVE_BMC_MAX_ALLOWED > 1) ||
886 (iter.second->versionId == caller.versionId))
887 {
888 continue;
889 }
890
891 // Failed activations don't have priority, assign them a large value
892 // for sorting purposes.
893 auto priority = 999;
894 if (iter.second.get()->activation() ==
895 server::Activation::Activations::Active &&
896 iter.second->redundancyPriority)
897 {
898 priority = iter.second->redundancyPriority.get()->priority();
899 }
900
901 versionsPQ.push(std::make_pair(priority, iter.second->versionId));
902 }
903 }
904
905 // If the number of BMC versions is over ACTIVE_BMC_MAX_ALLOWED -1,
906 // remove the highest priority one(s).
907 while ((count >= ACTIVE_BMC_MAX_ALLOWED) && (!versionsPQ.empty()))
908 {
909 erase(versionsPQ.top().second);
910 versionsPQ.pop();
911 count--;
912 }
913 #endif
914 }
915
mirrorUbootToAlt()916 void ItemUpdater::mirrorUbootToAlt()
917 {
918 helper.mirrorAlt();
919 }
920
checkImage(const std::string & filePath,const std::vector<std::string> & imageList)921 bool ItemUpdater::checkImage(const std::string& filePath,
922 const std::vector<std::string>& imageList)
923 {
924 bool valid = true;
925
926 for (auto& bmcImage : imageList)
927 {
928 fs::path file(filePath);
929 file /= bmcImage;
930 std::ifstream efile(file.c_str());
931 if (efile.good() != 1)
932 {
933 valid = false;
934 break;
935 }
936 }
937
938 return valid;
939 }
940
941 #ifdef HOST_BIOS_UPGRADE
createBIOSObject()942 void ItemUpdater::createBIOSObject()
943 {
944 std::string path = BIOS_OBJPATH;
945 // Get version id from last item in the path
946 auto pos = path.rfind('/');
947 if (pos == std::string::npos)
948 {
949 error("No version id found in object path {PATH}", "PATH", path);
950 return;
951 }
952
953 createActiveAssociation(path);
954 createFunctionalAssociation(path);
955 createUpdateableAssociation(path);
956
957 auto versionId = path.substr(pos + 1);
958 auto version = "null";
959 AssociationList assocs;
960 biosActivation = std::make_unique<Activation>(
961 bus, path, *this, versionId, server::Activation::Activations::Active,
962 assocs);
963 auto dummyErase = [](const std::string& /*entryId*/) {
964 // Do nothing;
965 };
966 biosVersion = std::make_unique<VersionClass>(
967 bus, path, version, VersionPurpose::Host, "", "",
968 std::vector<std::string>(),
969 std::bind(dummyErase, std::placeholders::_1), "");
970 biosVersion->deleteObject =
971 std::make_unique<phosphor::software::manager::Delete>(
972 bus, path, *biosVersion);
973
974 if (useUpdateDBusInterface)
975 {
976 createUpdateObject(versionId, path);
977 }
978 }
979 #endif
980
getRunningSlot()981 void ItemUpdater::getRunningSlot()
982 {
983 // Check /run/media/slot to get the slot number
984 constexpr auto slotFile = "/run/media/slot";
985 std::fstream f(slotFile, std::ios_base::in);
986 f >> runningImageSlot;
987 }
988
989 } // namespace updater
990 } // namespace software
991 } // namespace phosphor
992