blob: 4d353d55b0af681f21d78085ecf09c299fc63d7f [file] [log] [blame]
Matthew Barth4f0d3b72020-08-27 14:32:15 -05001/**
2 * Copyright © 2020 IBM Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Matthew Bartha0dd1352021-03-09 11:10:49 -060016#include "config.h"
17
Matthew Barth4f0d3b72020-08-27 14:32:15 -050018#include "zone.hpp"
19
Matthew Barthde90fb42021-03-04 16:34:28 -060020#include "fan.hpp"
Matthew Barth216229c2020-09-24 13:47:33 -050021
Matthew Bartha0dd1352021-03-09 11:10:49 -060022#include <cereal/archives/json.hpp>
23#include <cereal/cereal.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050024#include <nlohmann/json.hpp>
25#include <phosphor-logging/log.hpp>
Matthew Barthacd737c2021-03-04 11:04:01 -060026#include <sdbusplus/bus.hpp>
Matthew Barth603ef162021-03-24 15:34:53 -050027#include <sdeventplus/event.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050028
Matthew Bartha0dd1352021-03-09 11:10:49 -060029#include <algorithm>
Matthew Barth007de092021-03-25 13:56:04 -050030#include <chrono>
Matthew Bartha0dd1352021-03-09 11:10:49 -060031#include <filesystem>
32#include <fstream>
Matthew Barth651f03a2020-08-27 16:15:11 -050033#include <iterator>
34#include <map>
35#include <numeric>
Matthew Barth651f03a2020-08-27 16:15:11 -050036#include <utility>
Matthew Barth216229c2020-09-24 13:47:33 -050037#include <vector>
Matthew Barth651f03a2020-08-27 16:15:11 -050038
Matthew Barth4f0d3b72020-08-27 14:32:15 -050039namespace phosphor::fan::control::json
40{
41
42using json = nlohmann::json;
43using namespace phosphor::logging;
Matthew Bartha0dd1352021-03-09 11:10:49 -060044namespace fs = std::filesystem;
Matthew Barth4f0d3b72020-08-27 14:32:15 -050045
Matthew Barthb584d812021-03-11 15:55:04 -060046const std::map<std::string,
47 std::map<std::string, std::function<std::function<void(Zone*)>(
48 const json&, bool)>>>
Matthew Barth216229c2020-09-24 13:47:33 -050049 Zone::_intfPropHandlers = {{thermModeIntf,
50 {{supportedProp, zone::property::supported},
51 {currentProp, zone::property::current}}}};
Matthew Barth651f03a2020-08-27 16:15:11 -050052
Matthew Barth603ef162021-03-24 15:34:53 -050053Zone::Zone(const json& jsonObj, sdbusplus::bus::bus& bus,
54 const sdeventplus::Event& event, Manager* mgr) :
Matthew Bartha0dd1352021-03-09 11:10:49 -060055 ConfigBase(jsonObj),
56 ThermalObject(bus, (fs::path{CONTROL_OBJPATH} /= getName()).c_str(), true),
Matthew Barth603ef162021-03-24 15:34:53 -050057 _manager(mgr), _incDelay(0), _floor(0), _target(0), _incDelta(0),
Matthew Barth007de092021-03-25 13:56:04 -050058 _decDelta(0), _requestTargetBase(0), _isActive(true),
59 _incTimer(event, std::bind(&Zone::incTimerExpired, this)),
60 _decTimer(event, std::bind(&Zone::decTimerExpired, this))
Matthew Barth4f0d3b72020-08-27 14:32:15 -050061{
Matthew Barthe47c9582021-03-09 14:24:02 -060062 // Increase delay is optional, defaults to 0
Matthew Barth4f0d3b72020-08-27 14:32:15 -050063 if (jsonObj.contains("increase_delay"))
64 {
Matthew Barth007de092021-03-25 13:56:04 -050065 _incDelay =
66 std::chrono::seconds(jsonObj["increase_delay"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -050067 }
Matthew Barthe47c9582021-03-09 14:24:02 -060068 setDefaultCeiling(jsonObj);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050069 setDefaultFloor(jsonObj);
70 setDecInterval(jsonObj);
Matthew Barth651f03a2020-08-27 16:15:11 -050071 // Setting properties on interfaces to be served are optional
72 if (jsonObj.contains("interfaces"))
73 {
74 setInterfaces(jsonObj);
75 }
Matthew Barth007de092021-03-25 13:56:04 -050076
Matthew Bartha4483742021-03-25 14:09:01 -050077 // Restore thermal control current mode state
78 restoreCurrentMode();
79
80 // Emit object added for this zone dbus object
81 this->emit_object_added();
82
Matthew Barth007de092021-03-25 13:56:04 -050083 // Start timer for fan target decreases
84 _decTimer.restart(_decInterval);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050085}
86
Matthew Barthde90fb42021-03-04 16:34:28 -060087void Zone::addFan(std::unique_ptr<Fan> fan)
88{
89 _fans.emplace_back(std::move(fan));
90}
91
Matthew Barth8ba715e2021-03-05 09:00:05 -060092void Zone::setTarget(uint64_t target)
93{
Matthew Barth6f787302021-03-25 15:01:01 -050094 if (_isActive && _target != target)
Matthew Barth8ba715e2021-03-05 09:00:05 -060095 {
96 _target = target;
97 for (auto& fan : _fans)
98 {
99 fan->setTarget(_target);
100 }
101 }
102}
103
104void Zone::setActiveAllow(const std::string& ident, bool isActiveAllow)
105{
106 _active[ident] = isActiveAllow;
107 if (!isActiveAllow)
108 {
109 _isActive = false;
110 }
111 else
112 {
113 // Check all entries are set to allow active fan control
114 auto actPred = [](const auto& entry) { return entry.second; };
115 _isActive = std::all_of(_active.begin(), _active.end(), actPred);
116 }
117}
118
Matthew Barth12cb1252021-03-08 16:47:30 -0600119void Zone::setFloor(uint64_t target)
120{
121 // Check all entries are set to allow floor to be set
Matthew Barth8ba715e2021-03-05 09:00:05 -0600122 auto pred = [](const auto& entry) { return entry.second; };
Matthew Barth12cb1252021-03-08 16:47:30 -0600123 if (std::all_of(_floorChange.begin(), _floorChange.end(), pred))
124 {
125 _floor = target;
126 // Floor above target, update target to floor
127 if (_target < _floor)
128 {
129 requestIncrease(_floor - _target);
130 }
131 }
132}
133
134void Zone::requestIncrease(uint64_t targetDelta)
135{
Matthew Barth2b3253e2021-03-09 14:51:16 -0600136 // Only increase when delta is higher than the current increase delta for
137 // the zone and currently under ceiling
138 if (targetDelta > _incDelta && _target < _ceiling)
139 {
140 auto requestTarget = getRequestTargetBase();
141 requestTarget = (targetDelta - _incDelta) + requestTarget;
142 _incDelta = targetDelta;
143 // Target can not go above a current ceiling
144 if (requestTarget > _ceiling)
145 {
146 requestTarget = _ceiling;
147 }
Matthew Barth8ba715e2021-03-05 09:00:05 -0600148 setTarget(requestTarget);
Matthew Barth007de092021-03-25 13:56:04 -0500149 // Restart timer countdown for fan target increase
150 _incTimer.restartOnce(_incDelay);
Matthew Barth2b3253e2021-03-09 14:51:16 -0600151 }
Matthew Barth12cb1252021-03-08 16:47:30 -0600152}
153
Matthew Barth007de092021-03-25 13:56:04 -0500154void Zone::incTimerExpired()
155{
156 // Clear increase delta when timer expires allowing additional target
157 // increase requests or target decreases to occur
158 _incDelta = 0;
159}
160
Matthew Barth45c44ea2021-03-03 13:16:14 -0600161void Zone::requestDecrease(uint64_t targetDelta)
162{
163 // Only decrease the lowest target delta requested
164 if (_decDelta == 0 || targetDelta < _decDelta)
165 {
166 _decDelta = targetDelta;
167 }
168}
169
Matthew Barth007de092021-03-25 13:56:04 -0500170void Zone::decTimerExpired()
171{
172 // Check all entries are set to allow a decrease
173 auto pred = [](auto const& entry) { return entry.second; };
174 auto decAllowed = std::all_of(_decAllowed.begin(), _decAllowed.end(), pred);
175
176 // Only decrease targets when allowed, a requested decrease target delta
177 // exists, where no requested increases exist and the increase timer is not
178 // running (i.e. not in the middle of increasing)
179 if (decAllowed && _decDelta != 0 && _incDelta == 0 &&
180 !_incTimer.isEnabled())
181 {
182 auto requestTarget = getRequestTargetBase();
183 // Request target should not start above ceiling
184 if (requestTarget > _ceiling)
185 {
186 requestTarget = _ceiling;
187 }
188 // Target can not go below the defined floor
189 if ((requestTarget < _decDelta) || (requestTarget - _decDelta < _floor))
190 {
191 requestTarget = _floor;
192 }
193 else
194 {
195 requestTarget = requestTarget - _decDelta;
196 }
197 setTarget(requestTarget);
198 }
199 // Clear decrease delta when timer expires
200 _decDelta = 0;
201 // Decrease timer is restarted since its repeating
202}
203
Matthew Bartha0dd1352021-03-09 11:10:49 -0600204void Zone::setPersisted(const std::string& intf, const std::string& prop)
205{
206 if (std::find_if(_propsPersisted[intf].begin(), _propsPersisted[intf].end(),
207 [&prop](const auto& p) { return prop == p; }) !=
208 _propsPersisted[intf].end())
209 {
210 _propsPersisted[intf].emplace_back(prop);
211 }
212}
213
214std::string Zone::current(std::string value)
215{
216 auto current = ThermalObject::current();
217 std::transform(value.begin(), value.end(), value.begin(), toupper);
218
219 auto supported = ThermalObject::supported();
220 auto isSupported =
221 std::any_of(supported.begin(), supported.end(), [&value](auto& s) {
222 std::transform(s.begin(), s.end(), s.begin(), toupper);
223 return value == s;
224 });
225
226 if (value != current && isSupported)
227 {
228 current = ThermalObject::current(value);
229 if (isPersisted("xyz.openbmc_project.Control.ThermalMode", "Current"))
230 {
231 saveCurrentMode();
232 }
233 // TODO Trigger event(s) for current mode property change
234 // auto eData =
235 // _objects[_path]["xyz.openbmc_project.Control.ThermalMode"]
236 // ["Current"];
237 // if (eData != nullptr)
238 // {
239 // sdbusplus::message::message nullMsg{nullptr};
240 // handleEvent(nullMsg, eData);
241 // }
242 }
243
244 return current;
245}
246
Matthew Barthe47c9582021-03-09 14:24:02 -0600247void Zone::setDefaultCeiling(const json& jsonObj)
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500248{
249 if (!jsonObj.contains("full_speed"))
250 {
251 log<level::ERR>("Missing required zone's full speed",
252 entry("JSON=%s", jsonObj.dump().c_str()));
253 throw std::runtime_error("Missing required zone's full speed");
254 }
Matthew Barthe47c9582021-03-09 14:24:02 -0600255 _defaultCeiling = jsonObj["full_speed"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600256 // Start with the current target set as the default
Matthew Barthe47c9582021-03-09 14:24:02 -0600257 _target = _defaultCeiling;
Matthew Barth2b3253e2021-03-09 14:51:16 -0600258 // Start with the current ceiling set as the default
259 _ceiling = _defaultCeiling;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500260}
261
262void Zone::setDefaultFloor(const json& jsonObj)
263{
264 if (!jsonObj.contains("default_floor"))
265 {
Matthew Barthe47c9582021-03-09 14:24:02 -0600266 log<level::ERR>("Missing required zone's default floor",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500267 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barthe47c9582021-03-09 14:24:02 -0600268 throw std::runtime_error("Missing required zone's default floor");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500269 }
270 _defaultFloor = jsonObj["default_floor"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600271 // Start with the current floor set as the default
272 _floor = _defaultFloor;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500273}
274
275void Zone::setDecInterval(const json& jsonObj)
276{
277 if (!jsonObj.contains("decrease_interval"))
278 {
279 log<level::ERR>("Missing required zone's decrease interval",
280 entry("JSON=%s", jsonObj.dump().c_str()));
281 throw std::runtime_error("Missing required zone's decrease interval");
282 }
Matthew Barth007de092021-03-25 13:56:04 -0500283 _decInterval =
284 std::chrono::seconds(jsonObj["decrease_interval"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500285}
286
Matthew Barth651f03a2020-08-27 16:15:11 -0500287void Zone::setInterfaces(const json& jsonObj)
288{
289 for (const auto& interface : jsonObj["interfaces"])
290 {
291 if (!interface.contains("name") || !interface.contains("properties"))
292 {
293 log<level::ERR>("Missing required zone interface attributes",
294 entry("JSON=%s", interface.dump().c_str()));
295 throw std::runtime_error(
296 "Missing required zone interface attributes");
297 }
Matthew Barth216229c2020-09-24 13:47:33 -0500298 auto propFuncs =
299 _intfPropHandlers.find(interface["name"].get<std::string>());
300 if (propFuncs == _intfPropHandlers.end())
301 {
302 // Construct list of available configurable interfaces
303 auto intfs = std::accumulate(
304 std::next(_intfPropHandlers.begin()), _intfPropHandlers.end(),
305 _intfPropHandlers.begin()->first, [](auto list, auto intf) {
306 return std::move(list) + ", " + intf.first;
307 });
308 log<level::ERR>("Configured interface not available",
309 entry("JSON=%s", interface.dump().c_str()),
310 entry("AVAILABLE_INTFS=%s", intfs.c_str()));
311 throw std::runtime_error("Configured interface not available");
312 }
313
Matthew Barth651f03a2020-08-27 16:15:11 -0500314 for (const auto& property : interface["properties"])
315 {
316 if (!property.contains("name"))
317 {
318 log<level::ERR>(
319 "Missing required interface property attributes",
320 entry("JSON=%s", property.dump().c_str()));
321 throw std::runtime_error(
322 "Missing required interface property attributes");
323 }
324 // Attribute "persist" is optional, defaults to `false`
325 auto persist = false;
326 if (property.contains("persist"))
327 {
328 persist = property["persist"].get<bool>();
329 }
330 // Property name from JSON must exactly match supported
331 // index names to functions in property namespace
Matthew Barth216229c2020-09-24 13:47:33 -0500332 auto propFunc =
333 propFuncs->second.find(property["name"].get<std::string>());
334 if (propFunc == propFuncs->second.end())
Matthew Barth651f03a2020-08-27 16:15:11 -0500335 {
Matthew Barth216229c2020-09-24 13:47:33 -0500336 // Construct list of available configurable properties
Matthew Barth651f03a2020-08-27 16:15:11 -0500337 auto props = std::accumulate(
Matthew Barth216229c2020-09-24 13:47:33 -0500338 std::next(propFuncs->second.begin()),
339 propFuncs->second.end(), propFuncs->second.begin()->first,
340 [](auto list, auto prop) {
Matthew Barth651f03a2020-08-27 16:15:11 -0500341 return std::move(list) + ", " + prop.first;
342 });
Matthew Barth216229c2020-09-24 13:47:33 -0500343 log<level::ERR>("Configured property not available",
Matthew Barth651f03a2020-08-27 16:15:11 -0500344 entry("JSON=%s", property.dump().c_str()),
345 entry("AVAILABLE_PROPS=%s", props.c_str()));
346 throw std::runtime_error(
347 "Configured property function not available");
348 }
Matthew Barthb584d812021-03-11 15:55:04 -0600349 auto propHandler = propFunc->second(property, persist);
350 // Only call non-null set property handler functions
351 if (propHandler)
352 {
353 propHandler(this);
354 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500355 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500356 }
357}
358
Matthew Bartha0dd1352021-03-09 11:10:49 -0600359bool Zone::isPersisted(const std::string& intf, const std::string& prop)
360{
361 auto it = _propsPersisted.find(intf);
362 if (it == _propsPersisted.end())
363 {
364 return false;
365 }
366
367 return std::any_of(it->second.begin(), it->second.end(),
368 [&prop](const auto& p) { return prop == p; });
369}
370
371void Zone::saveCurrentMode()
372{
373 fs::path path{CONTROL_PERSIST_ROOT_PATH};
374 // Append zone name and property description
375 path /= getName();
376 path /= "CurrentMode";
377 std::ofstream ofs(path.c_str(), std::ios::binary);
378 cereal::JSONOutputArchive oArch(ofs);
379 oArch(ThermalObject::current());
380}
381
Matthew Bartha4483742021-03-25 14:09:01 -0500382void Zone::restoreCurrentMode()
383{
384 auto current = ThermalObject::current();
385 fs::path path{CONTROL_PERSIST_ROOT_PATH};
386 path /= getName();
387 path /= "CurrentMode";
388 fs::create_directories(path.parent_path());
389
390 try
391 {
392 if (fs::exists(path))
393 {
394 std::ifstream ifs(path.c_str(), std::ios::in | std::ios::binary);
395 cereal::JSONInputArchive iArch(ifs);
396 iArch(current);
397 }
398 }
399 catch (std::exception& e)
400 {
401 log<level::ERR>(e.what());
402 fs::remove(path);
403 current = ThermalObject::current();
404 }
405
406 this->current(current);
407}
408
Matthew Barth651f03a2020-08-27 16:15:11 -0500409/**
Matthew Barth216229c2020-09-24 13:47:33 -0500410 * Properties of interfaces supported by the zone configuration that return
Matthew Barthb584d812021-03-11 15:55:04 -0600411 * a handler function that sets the zone's property value(s) and persist state.
Matthew Barth651f03a2020-08-27 16:15:11 -0500412 */
413namespace zone::property
414{
Matthew Barthb584d812021-03-11 15:55:04 -0600415// Get a set property handler function for the configured values of the
416// "Supported" property
417std::function<void(Zone*)> supported(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500418{
419 std::vector<std::string> values;
Matthew Barth216229c2020-09-24 13:47:33 -0500420 if (!jsonObj.contains("values"))
Matthew Barth651f03a2020-08-27 16:15:11 -0500421 {
Matthew Barth216229c2020-09-24 13:47:33 -0500422 log<level::ERR>(
423 "No 'values' found for \"Supported\" property, using an empty list",
424 entry("JSON=%s", jsonObj.dump().c_str()));
425 }
426 else
427 {
428 for (const auto& value : jsonObj["values"])
429 {
430 if (!value.contains("value"))
431 {
432 log<level::ERR>("No 'value' found for \"Supported\" property "
433 "entry, skipping",
434 entry("JSON=%s", value.dump().c_str()));
435 }
436 else
437 {
438 values.emplace_back(value["value"].get<std::string>());
439 }
440 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500441 }
442
Matthew Barthb584d812021-03-11 15:55:04 -0600443 return Zone::setProperty<std::vector<std::string>>(
444 Zone::thermModeIntf, Zone::supportedProp, &Zone::supported,
445 std::move(values), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500446}
447
Matthew Barthb584d812021-03-11 15:55:04 -0600448// Get a set property handler function for a configured value of the "Current"
Matthew Barth216229c2020-09-24 13:47:33 -0500449// property
Matthew Barthb584d812021-03-11 15:55:04 -0600450std::function<void(Zone*)> current(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500451{
Matthew Barth216229c2020-09-24 13:47:33 -0500452 // Use default value for "Current" property if no "value" entry given
453 if (!jsonObj.contains("value"))
454 {
Matthew Barthb584d812021-03-11 15:55:04 -0600455 log<level::INFO>("No 'value' found for \"Current\" property, "
456 "using default",
457 entry("JSON=%s", jsonObj.dump().c_str()));
458 // Set persist state of property
459 return Zone::setPropertyPersist(Zone::thermModeIntf, Zone::currentProp,
460 persist);
Matthew Barth216229c2020-09-24 13:47:33 -0500461 }
462
Matthew Barthb584d812021-03-11 15:55:04 -0600463 return Zone::setProperty<std::string>(
464 Zone::thermModeIntf, Zone::currentProp, &Zone::current,
465 jsonObj["value"].get<std::string>(), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500466}
Matthew Barthb584d812021-03-11 15:55:04 -0600467
Matthew Barth651f03a2020-08-27 16:15:11 -0500468} // namespace zone::property
469
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500470} // namespace phosphor::fan::control::json