xref: /openbmc/phosphor-pid-control/dbus/dbuspassive.cpp (revision 11a1edcd204b87c6258592dc47f3d04e426e66e8)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2017 Google Inc
3 
4 #include "config.h"
5 
6 #include "dbuspassive.hpp"
7 
8 #include "conf.hpp"
9 #include "dbushelper_interface.hpp"
10 #include "dbuspassiveredundancy.hpp"
11 #include "dbusutil.hpp"
12 #include "failsafeloggers/failsafe_logger_utility.hpp"
13 #include "interfaces.hpp"
14 #include "util.hpp"
15 
16 #include <systemd/sd-bus.h>
17 
18 #include <sdbusplus/bus.hpp>
19 #include <sdbusplus/message.hpp>
20 #include <xyz/openbmc_project/Sensor/Threshold/Critical/common.hpp>
21 #include <xyz/openbmc_project/Sensor/Threshold/Warning/common.hpp>
22 #include <xyz/openbmc_project/Sensor/Value/client.hpp>
23 #include <xyz/openbmc_project/State/Decorator/Availability/common.hpp>
24 #include <xyz/openbmc_project/State/Decorator/OperationalStatus/common.hpp>
25 
26 #include <chrono>
27 #include <cmath>
28 #include <cstdint>
29 #include <exception>
30 #include <limits>
31 #include <map>
32 #include <memory>
33 #include <mutex>
34 #include <set>
35 #include <string>
36 #include <utility>
37 #include <variant>
38 
39 #include "failsafeloggers/failsafe_logger.cpp"
40 
41 using SensorValue = sdbusplus::common::xyz::openbmc_project::sensor::Value;
42 using SensorThresholdWarning =
43     sdbusplus::common::xyz::openbmc_project::sensor::threshold::Warning;
44 using SensorThresholdCritical =
45     sdbusplus::common::xyz::openbmc_project::sensor::threshold::Critical;
46 using StateDecoratorAvailability =
47     sdbusplus::common::xyz::openbmc_project::state::decorator::Availability;
48 using StateDecoratorOperationalStatus = sdbusplus::common::xyz::
49     openbmc_project::state::decorator::OperationalStatus;
50 
51 namespace pid_control
52 {
53 
createDbusPassive(sdbusplus::bus_t & bus,const std::string & type,const std::string & id,std::unique_ptr<DbusHelperInterface> helper,const conf::SensorConfig * info,const std::shared_ptr<DbusPassiveRedundancy> & redundancy)54 std::unique_ptr<ReadInterface> DbusPassive::createDbusPassive(
55     sdbusplus::bus_t& bus, const std::string& type, const std::string& id,
56     std::unique_ptr<DbusHelperInterface> helper, const conf::SensorConfig* info,
57     const std::shared_ptr<DbusPassiveRedundancy>& redundancy)
58 {
59     if (helper == nullptr)
60     {
61         return nullptr;
62     }
63     if (!validType(type))
64     {
65         return nullptr;
66     }
67 
68     /* Need to get the scale and initial value */
69     /* service == busname */
70     std::string path;
71     if (info->readPath.empty())
72     {
73         path = getSensorPath(type, id);
74     }
75     else
76     {
77         path = info->readPath;
78     }
79 
80     SensorProperties settings;
81     bool failed;
82     bool objectMissing = false;
83     std::string service;
84 
85     try
86     {
87         service = helper->getService(SensorValue::interface, path);
88     }
89     catch (const std::exception& e)
90     {
91 #ifndef HANDLE_MISSING_OBJECT_PATHS
92         return nullptr;
93 #else
94         // CASE1: The sensor is not on DBus, but as it is not in the
95         // MissingIsAcceptable list, the sensor should be built with a failed
96         // state to send the zone to failsafe mode. Everything will recover if
97         // all important sensors are back to DBus. swampd will be informed
98         // through InterfacesAdded signals and the sensors will be built again.
99 
100         // CASE2: The sensor is on D-Bus (getService succeeds) but getProperties
101         // fails (e.g., D-Bus error or property fetch failure). In this case,
102         // handle-missing-object-paths does not apply. The sensor build fails,
103         // and the control loop will keep restarting until getProperties
104         // succeeds.
105 
106         // Only CASE1 may send the zone to failsafe mode if the sensor is not
107         // in MissingIsAcceptable. CASE2 results in continuous restart until
108         // recovery.
109 
110         failed = true;
111         objectMissing = true;
112         settings.value = std::numeric_limits<double>::quiet_NaN();
113         settings.unit = getSensorUnit(type);
114         settings.available = false;
115         settings.unavailableAsFailed = true;
116         if (info->ignoreDbusMinMax)
117         {
118             settings.min = 0;
119             settings.max = 0;
120         }
121         std::cerr << "DbusPassive: Sensor " << path
122                   << " is missing from D-Bus, build this sensor as failed\n";
123         return std::make_unique<DbusPassive>(
124             bus, type, id, std::move(helper), settings, failed, objectMissing,
125             path, redundancy);
126 #endif
127     }
128 
129     try
130     {
131         helper->getProperties(service, path, &settings);
132         failed = helper->thresholdsAsserted(service, path);
133     }
134     catch (const std::exception& e)
135     {
136         return nullptr;
137     }
138 
139     /* if these values are zero, they're ignored. */
140     if (info->ignoreDbusMinMax)
141     {
142         settings.min = 0;
143         settings.max = 0;
144     }
145 
146     settings.unavailableAsFailed = info->unavailableAsFailed;
147 
148     return std::make_unique<DbusPassive>(
149         bus, type, id, std::move(helper), settings, failed, objectMissing, path,
150         redundancy);
151 }
152 
DbusPassive(sdbusplus::bus_t & bus,const std::string & type,const std::string & id,std::unique_ptr<DbusHelperInterface> helper,const SensorProperties & settings,bool failed,bool objectMissing,const std::string & path,const std::shared_ptr<DbusPassiveRedundancy> & redundancy)153 DbusPassive::DbusPassive(
154     sdbusplus::bus_t& bus, const std::string& type, const std::string& id,
155     std::unique_ptr<DbusHelperInterface> helper,
156     const SensorProperties& settings, bool failed, bool objectMissing,
157     const std::string& path,
158     const std::shared_ptr<DbusPassiveRedundancy>& redundancy) :
159     ReadInterface(), _signal(bus, getMatch(path), dbusHandleSignal, this),
160     _id(id), _helper(std::move(helper)), _failed(failed),
161     _objectMissing(objectMissing), path(path), redundancy(redundancy)
162 
163 {
164     _scale = settings.scale;
165     _min = settings.min * std::pow(10.0, _scale);
166     _max = settings.max * std::pow(10.0, _scale);
167     _available = settings.available;
168     _unavailableAsFailed = settings.unavailableAsFailed;
169 
170     // Cache this type knowledge, to avoid repeated string comparison
171     _typeMargin = (type == "margin");
172     _typeFan = (type == "fan");
173 
174     // Force value to be stored, otherwise member would be uninitialized
175     updateValue(settings.value, true);
176 }
177 
read(void)178 ReadReturn DbusPassive::read(void)
179 {
180     std::lock_guard<std::mutex> guard(_lock);
181 
182     ReadReturn r = {_value, _updated, _unscaled};
183 
184     return r;
185 }
186 
setValue(double value,double unscaled)187 void DbusPassive::setValue(double value, double unscaled)
188 {
189     std::lock_guard<std::mutex> guard(_lock);
190 
191     _value = value;
192     _unscaled = unscaled;
193     _updated = std::chrono::high_resolution_clock::now();
194 }
195 
setValue(double value)196 void DbusPassive::setValue(double value)
197 {
198     // First param is scaled, second param is unscaled, assume same here
199     setValue(value, value);
200 }
201 
getFailed(void) const202 bool DbusPassive::getFailed(void) const
203 {
204     if (redundancy)
205     {
206         const std::set<std::string>& failures = redundancy->getFailed();
207         if (failures.find(path) != failures.end())
208         {
209             outputFailsafeLogWithSensor(_id, true, _id,
210                                         "The sensor path is marked redundant.");
211             return true;
212         }
213     }
214 
215     /*
216      * If handle-missing-object-paths is enabled, and the expected D-Bus object
217      * path is not exported, this sensor is created to represent that condition.
218      * Indicate this sensor has failed so the zone enters failSafe mode.
219      */
220     if (_objectMissing)
221     {
222         outputFailsafeLogWithSensor(_id, true, _id,
223                                     "The sensor D-Bus object is missing.");
224         return true;
225     }
226 
227     /*
228      * Unavailable thermal sensors, who are not present or
229      * power-state-not-matching, should not trigger the failSafe mode. For
230      * example, when a system stays at a powered-off state, its CPU Temp
231      * sensors will be unavailable, these unavailable sensors should not be
232      * treated as failed and trigger failSafe.
233      * This is important for systems whose Fans are always on.
234      */
235     if (!_typeFan && !_available && !_unavailableAsFailed)
236     {
237         return false;
238     }
239 
240     // If a reading has came in,
241     // but its value bad in some way (determined by sensor type),
242     // indicate this sensor has failed,
243     // until another value comes in that is no longer bad.
244     // This is different from the overall _failed flag,
245     // which is set and cleared by other causes.
246     if (_badReading)
247     {
248         outputFailsafeLogWithSensor(_id, true, _id,
249                                     "The sensor has bad readings.");
250         return true;
251     }
252 
253     // If a reading has came in, and it is not a bad reading,
254     // but it indicates there is no more thermal margin left,
255     // that is bad, something is wrong with the PID loops,
256     // they are not cooling the system, enable failsafe mode also.
257     if (_marginHot)
258     {
259         outputFailsafeLogWithSensor(_id, true, _id,
260                                     "The sensor has no thermal margin left.");
261         return true;
262     }
263 
264     if (_failed)
265     {
266         outputFailsafeLogWithSensor(
267             _id, true, _id, "The sensor has failed with a critical issue.");
268         return true;
269     }
270 
271     if (!_available)
272     {
273         outputFailsafeLogWithSensor(_id, true, _id,
274                                     "The sensor is unavailable.");
275         return true;
276     }
277 
278     if (!_functional)
279     {
280         outputFailsafeLogWithSensor(_id, true, _id,
281                                     "The sensor is not functional.");
282         return true;
283     }
284 
285     outputFailsafeLogWithSensor(_id, false, _id, "The sensor has recovered.");
286 
287     return false;
288 }
289 
getFailReason(void) const290 std::string DbusPassive::getFailReason(void) const
291 {
292     if (_objectMissing)
293     {
294         return "Sensor D-Bus object missing";
295     }
296     if (_badReading)
297     {
298         return "Sensor reading bad";
299     }
300     if (_marginHot)
301     {
302         return "Margin hot";
303     }
304     if (_failed)
305     {
306         return "Sensor threshold asserted";
307     }
308     if (!_available)
309     {
310         return "Sensor unavailable";
311     }
312     if (!_functional)
313     {
314         return "Sensor not functional";
315     }
316     return "Unknown";
317 }
318 
setFailed(bool value)319 void DbusPassive::setFailed(bool value)
320 {
321     _failed = value;
322 }
323 
setFunctional(bool value)324 void DbusPassive::setFunctional(bool value)
325 {
326     _functional = value;
327 }
328 
setAvailable(bool value)329 void DbusPassive::setAvailable(bool value)
330 {
331     _available = value;
332 }
333 
getScale(void)334 int64_t DbusPassive::getScale(void)
335 {
336     return _scale;
337 }
338 
getID(void)339 std::string DbusPassive::getID(void)
340 {
341     return _id;
342 }
343 
getMax(void)344 double DbusPassive::getMax(void)
345 {
346     return _max;
347 }
348 
getMin(void)349 double DbusPassive::getMin(void)
350 {
351     return _min;
352 }
353 
updateValue(double value,bool force)354 void DbusPassive::updateValue(double value, bool force)
355 {
356     _badReading = false;
357 
358     // Do not let a NAN, or other floating-point oddity, be used to update
359     // the value, as that indicates the sensor has no valid reading.
360     if (!(std::isfinite(value)))
361     {
362         _badReading = true;
363 
364         // Do not continue with a bad reading, unless caller forcing
365         if (!force)
366         {
367             return;
368         }
369     }
370 
371     value *= std::pow(10.0, _scale);
372 
373     auto unscaled = value;
374     scaleSensorReading(_min, _max, value);
375 
376     if (_typeMargin)
377     {
378         _marginHot = false;
379 
380         // Unlike an absolute temperature sensor,
381         // where 0 degrees C is a good reading,
382         // a value received of 0 (or negative) margin is worrisome,
383         // and should be flagged.
384         // Either it indicates margin not calculated properly,
385         // or somebody forgot to set the margin-zero setpoint,
386         // or the system is really overheating that much.
387         // This is a different condition from _failed
388         // and _badReading, so it merits its own flag.
389         // The sensor has not failed, the reading is good, but the zone
390         // still needs to know that it should go to failsafe mode.
391         if (unscaled <= 0.0)
392         {
393             _marginHot = true;
394         }
395     }
396 
397     setValue(value, unscaled);
398 }
399 
handleSensorValue(sdbusplus::message_t & msg,DbusPassive * owner)400 int handleSensorValue(sdbusplus::message_t& msg, DbusPassive* owner)
401 {
402     std::string msgSensor;
403     std::map<std::string, std::variant<int64_t, double, bool>> msgData;
404 
405     msg.read(msgSensor, msgData);
406 
407     if (msgSensor == SensorValue::interface)
408     {
409         auto valPropMap = msgData.find(SensorValue::property_names::value);
410         if (valPropMap != msgData.end())
411         {
412             double value =
413                 std::visit(VariantToDoubleVisitor(), valPropMap->second);
414 
415             owner->updateValue(value, false);
416         }
417     }
418     else if (msgSensor == SensorThresholdCritical::interface)
419     {
420         auto criticalAlarmLow = msgData.find(
421             SensorThresholdCritical::property_names::critical_alarm_low);
422         auto criticalAlarmHigh = msgData.find(
423             SensorThresholdCritical::property_names::critical_alarm_high);
424         if (criticalAlarmHigh == msgData.end() &&
425             criticalAlarmLow == msgData.end())
426         {
427             return 0;
428         }
429 
430         bool asserted = false;
431         if (criticalAlarmLow != msgData.end())
432         {
433             asserted = std::get<bool>(criticalAlarmLow->second);
434         }
435 
436         // checking both as in theory you could de-assert one threshold and
437         // assert the other at the same moment
438         if (!asserted && criticalAlarmHigh != msgData.end())
439         {
440             asserted = std::get<bool>(criticalAlarmHigh->second);
441         }
442         owner->setFailed(asserted);
443     }
444 #ifdef UNC_FAILSAFE
445     else if (msgSensor == SensorThresholdWarning::interface)
446     {
447         auto warningAlarmHigh = msgData.find(
448             SensorThresholdWarning::property_names::warning_alarm_high);
449         if (warningAlarmHigh == msgData.end())
450         {
451             return 0;
452         }
453 
454         bool asserted = false;
455         if (warningAlarmHigh != msgData.end())
456         {
457             asserted = std::get<bool>(warningAlarmHigh->second);
458         }
459         owner->setFailed(asserted);
460     }
461 #endif
462     else if (msgSensor == StateDecoratorAvailability::interface)
463     {
464         auto available =
465             msgData.find(StateDecoratorAvailability::property_names::available);
466         if (available == msgData.end())
467         {
468             return 0;
469         }
470         bool asserted = std::get<bool>(available->second);
471         owner->setAvailable(asserted);
472         if (!asserted)
473         {
474             // A thermal controller will continue its PID calculation and not
475             // trigger a 'failsafe' when some inputs are unavailable.
476             // So, forced to clear the value here to prevent a historical
477             // value to participate in a latter PID calculation.
478             owner->updateValue(std::numeric_limits<double>::quiet_NaN(), true);
479         }
480     }
481     else if (msgSensor == StateDecoratorOperationalStatus::interface)
482     {
483         auto functional = msgData.find(
484             StateDecoratorOperationalStatus::property_names::functional);
485         if (functional == msgData.end())
486         {
487             return 0;
488         }
489         bool asserted = std::get<bool>(functional->second);
490         owner->setFunctional(asserted);
491     }
492 
493     return 0;
494 }
495 
dbusHandleSignal(sd_bus_message * msg,void * usrData,sd_bus_error * err)496 int dbusHandleSignal(sd_bus_message* msg, void* usrData,
497                      [[maybe_unused]] sd_bus_error* err)
498 {
499     auto sdbpMsg = sdbusplus::message_t(msg);
500     DbusPassive* obj = static_cast<DbusPassive*>(usrData);
501 
502     return handleSensorValue(sdbpMsg, obj);
503 }
504 
505 } // namespace pid_control
506