blob: 08aa91acf098105dbc7c9a9c038cf17db9812e81 [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 Barth9403a212021-05-17 09:31:50 -050021#include "sdbusplus.hpp"
Matthew Barth216229c2020-09-24 13:47:33 -050022
Matthew Bartha0dd1352021-03-09 11:10:49 -060023#include <cereal/archives/json.hpp>
24#include <cereal/cereal.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050025#include <nlohmann/json.hpp>
26#include <phosphor-logging/log.hpp>
Matthew Barthacd737c2021-03-04 11:04:01 -060027#include <sdbusplus/bus.hpp>
Matthew Barth603ef162021-03-24 15:34:53 -050028#include <sdeventplus/event.hpp>
Matthew Barth4f0d3b72020-08-27 14:32:15 -050029
Matthew Bartha0dd1352021-03-09 11:10:49 -060030#include <algorithm>
Matthew Barth007de092021-03-25 13:56:04 -050031#include <chrono>
Matthew Bartha0dd1352021-03-09 11:10:49 -060032#include <filesystem>
33#include <fstream>
Matthew Barth651f03a2020-08-27 16:15:11 -050034#include <iterator>
35#include <map>
36#include <numeric>
Matthew Barth651f03a2020-08-27 16:15:11 -050037#include <utility>
Matthew Barth216229c2020-09-24 13:47:33 -050038#include <vector>
Matthew Barth651f03a2020-08-27 16:15:11 -050039
Matthew Barth4f0d3b72020-08-27 14:32:15 -050040namespace phosphor::fan::control::json
41{
42
43using json = nlohmann::json;
44using namespace phosphor::logging;
Matthew Bartha0dd1352021-03-09 11:10:49 -060045namespace fs = std::filesystem;
Matthew Barth4f0d3b72020-08-27 14:32:15 -050046
Matthew Barthb584d812021-03-11 15:55:04 -060047const std::map<std::string,
48 std::map<std::string, std::function<std::function<void(Zone*)>(
49 const json&, bool)>>>
Matthew Barth216229c2020-09-24 13:47:33 -050050 Zone::_intfPropHandlers = {{thermModeIntf,
51 {{supportedProp, zone::property::supported},
52 {currentProp, zone::property::current}}}};
Matthew Barth651f03a2020-08-27 16:15:11 -050053
Matthew Barth9403a212021-05-17 09:31:50 -050054Zone::Zone(const json& jsonObj, const sdeventplus::Event& event, Manager* mgr) :
Matthew Bartha0dd1352021-03-09 11:10:49 -060055 ConfigBase(jsonObj),
Matthew Barth9403a212021-05-17 09:31:50 -050056 ThermalObject(util::SDBusPlus::getBus(),
57 (fs::path{CONTROL_OBJPATH} /= getName()).c_str(), true),
Matthew Barth603ef162021-03-24 15:34:53 -050058 _manager(mgr), _incDelay(0), _floor(0), _target(0), _incDelta(0),
Matthew Barth007de092021-03-25 13:56:04 -050059 _decDelta(0), _requestTargetBase(0), _isActive(true),
60 _incTimer(event, std::bind(&Zone::incTimerExpired, this)),
61 _decTimer(event, std::bind(&Zone::decTimerExpired, this))
Matthew Barth4f0d3b72020-08-27 14:32:15 -050062{
Matthew Barthe47c9582021-03-09 14:24:02 -060063 // Increase delay is optional, defaults to 0
Matthew Barth4f0d3b72020-08-27 14:32:15 -050064 if (jsonObj.contains("increase_delay"))
65 {
Matthew Barth007de092021-03-25 13:56:04 -050066 _incDelay =
67 std::chrono::seconds(jsonObj["increase_delay"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -050068 }
Matthew Barthe47c9582021-03-09 14:24:02 -060069 setDefaultCeiling(jsonObj);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050070 setDefaultFloor(jsonObj);
71 setDecInterval(jsonObj);
Matthew Barth651f03a2020-08-27 16:15:11 -050072 // Setting properties on interfaces to be served are optional
73 if (jsonObj.contains("interfaces"))
74 {
75 setInterfaces(jsonObj);
76 }
Matthew Barth007de092021-03-25 13:56:04 -050077
Matthew Bartha4483742021-03-25 14:09:01 -050078 // Restore thermal control current mode state
79 restoreCurrentMode();
80
81 // Emit object added for this zone dbus object
82 this->emit_object_added();
83
Matthew Barth007de092021-03-25 13:56:04 -050084 // Start timer for fan target decreases
85 _decTimer.restart(_decInterval);
Matthew Barth4f0d3b72020-08-27 14:32:15 -050086}
87
Matthew Barthde90fb42021-03-04 16:34:28 -060088void Zone::addFan(std::unique_ptr<Fan> fan)
89{
90 _fans.emplace_back(std::move(fan));
91}
92
Matthew Barth8ba715e2021-03-05 09:00:05 -060093void Zone::setTarget(uint64_t target)
94{
Matthew Barth6f787302021-03-25 15:01:01 -050095 if (_isActive && _target != target)
Matthew Barth8ba715e2021-03-05 09:00:05 -060096 {
97 _target = target;
98 for (auto& fan : _fans)
99 {
100 fan->setTarget(_target);
101 }
102 }
103}
104
105void Zone::setActiveAllow(const std::string& ident, bool isActiveAllow)
106{
107 _active[ident] = isActiveAllow;
108 if (!isActiveAllow)
109 {
110 _isActive = false;
111 }
112 else
113 {
114 // Check all entries are set to allow active fan control
115 auto actPred = [](const auto& entry) { return entry.second; };
116 _isActive = std::all_of(_active.begin(), _active.end(), actPred);
117 }
118}
119
Matthew Barth12cb1252021-03-08 16:47:30 -0600120void Zone::setFloor(uint64_t target)
121{
122 // Check all entries are set to allow floor to be set
Matthew Barth8ba715e2021-03-05 09:00:05 -0600123 auto pred = [](const auto& entry) { return entry.second; };
Matthew Barth12cb1252021-03-08 16:47:30 -0600124 if (std::all_of(_floorChange.begin(), _floorChange.end(), pred))
125 {
126 _floor = target;
127 // Floor above target, update target to floor
128 if (_target < _floor)
129 {
130 requestIncrease(_floor - _target);
131 }
132 }
133}
134
135void Zone::requestIncrease(uint64_t targetDelta)
136{
Matthew Barth2b3253e2021-03-09 14:51:16 -0600137 // Only increase when delta is higher than the current increase delta for
138 // the zone and currently under ceiling
139 if (targetDelta > _incDelta && _target < _ceiling)
140 {
141 auto requestTarget = getRequestTargetBase();
142 requestTarget = (targetDelta - _incDelta) + requestTarget;
143 _incDelta = targetDelta;
144 // Target can not go above a current ceiling
145 if (requestTarget > _ceiling)
146 {
147 requestTarget = _ceiling;
148 }
Matthew Barth8ba715e2021-03-05 09:00:05 -0600149 setTarget(requestTarget);
Matthew Barth007de092021-03-25 13:56:04 -0500150 // Restart timer countdown for fan target increase
151 _incTimer.restartOnce(_incDelay);
Matthew Barth2b3253e2021-03-09 14:51:16 -0600152 }
Matthew Barth12cb1252021-03-08 16:47:30 -0600153}
154
Matthew Barth007de092021-03-25 13:56:04 -0500155void Zone::incTimerExpired()
156{
157 // Clear increase delta when timer expires allowing additional target
158 // increase requests or target decreases to occur
159 _incDelta = 0;
160}
161
Matthew Barth45c44ea2021-03-03 13:16:14 -0600162void Zone::requestDecrease(uint64_t targetDelta)
163{
164 // Only decrease the lowest target delta requested
165 if (_decDelta == 0 || targetDelta < _decDelta)
166 {
167 _decDelta = targetDelta;
168 }
169}
170
Matthew Barth007de092021-03-25 13:56:04 -0500171void Zone::decTimerExpired()
172{
173 // Check all entries are set to allow a decrease
174 auto pred = [](auto const& entry) { return entry.second; };
175 auto decAllowed = std::all_of(_decAllowed.begin(), _decAllowed.end(), pred);
176
177 // Only decrease targets when allowed, a requested decrease target delta
178 // exists, where no requested increases exist and the increase timer is not
179 // running (i.e. not in the middle of increasing)
180 if (decAllowed && _decDelta != 0 && _incDelta == 0 &&
181 !_incTimer.isEnabled())
182 {
183 auto requestTarget = getRequestTargetBase();
184 // Request target should not start above ceiling
185 if (requestTarget > _ceiling)
186 {
187 requestTarget = _ceiling;
188 }
189 // Target can not go below the defined floor
190 if ((requestTarget < _decDelta) || (requestTarget - _decDelta < _floor))
191 {
192 requestTarget = _floor;
193 }
194 else
195 {
196 requestTarget = requestTarget - _decDelta;
197 }
198 setTarget(requestTarget);
199 }
200 // Clear decrease delta when timer expires
201 _decDelta = 0;
202 // Decrease timer is restarted since its repeating
203}
204
Matthew Bartha0dd1352021-03-09 11:10:49 -0600205void Zone::setPersisted(const std::string& intf, const std::string& prop)
206{
207 if (std::find_if(_propsPersisted[intf].begin(), _propsPersisted[intf].end(),
208 [&prop](const auto& p) { return prop == p; }) !=
209 _propsPersisted[intf].end())
210 {
211 _propsPersisted[intf].emplace_back(prop);
212 }
213}
214
215std::string Zone::current(std::string value)
216{
217 auto current = ThermalObject::current();
218 std::transform(value.begin(), value.end(), value.begin(), toupper);
219
220 auto supported = ThermalObject::supported();
221 auto isSupported =
222 std::any_of(supported.begin(), supported.end(), [&value](auto& s) {
223 std::transform(s.begin(), s.end(), s.begin(), toupper);
224 return value == s;
225 });
226
227 if (value != current && isSupported)
228 {
229 current = ThermalObject::current(value);
230 if (isPersisted("xyz.openbmc_project.Control.ThermalMode", "Current"))
231 {
232 saveCurrentMode();
233 }
234 // TODO Trigger event(s) for current mode property change
235 // auto eData =
236 // _objects[_path]["xyz.openbmc_project.Control.ThermalMode"]
237 // ["Current"];
238 // if (eData != nullptr)
239 // {
240 // sdbusplus::message::message nullMsg{nullptr};
241 // handleEvent(nullMsg, eData);
242 // }
243 }
244
245 return current;
246}
247
Matthew Barthe47c9582021-03-09 14:24:02 -0600248void Zone::setDefaultCeiling(const json& jsonObj)
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500249{
Matthew Barth5606ec82021-05-17 12:08:52 -0500250 // TODO Remove "full_speed" after configs replaced with "default_ceiling"
251 if (!jsonObj.contains("full_speed") && !jsonObj.contains("default_ceiling"))
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500252 {
Matthew Barth5606ec82021-05-17 12:08:52 -0500253 log<level::ERR>("Missing required zone's default ceiling",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500254 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barth5606ec82021-05-17 12:08:52 -0500255 throw std::runtime_error("Missing required zone's default ceiling");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500256 }
Matthew Barth5606ec82021-05-17 12:08:52 -0500257 if (jsonObj.contains("full_speed"))
258 {
259 _defaultCeiling = jsonObj["full_speed"].get<uint64_t>();
260 }
261 else
262 {
263 _defaultCeiling = jsonObj["default_ceiling"].get<uint64_t>();
264 }
Matthew Barth12cb1252021-03-08 16:47:30 -0600265 // Start with the current target set as the default
Matthew Barthe47c9582021-03-09 14:24:02 -0600266 _target = _defaultCeiling;
Matthew Barth2b3253e2021-03-09 14:51:16 -0600267 // Start with the current ceiling set as the default
268 _ceiling = _defaultCeiling;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500269}
270
271void Zone::setDefaultFloor(const json& jsonObj)
272{
273 if (!jsonObj.contains("default_floor"))
274 {
Matthew Barthe47c9582021-03-09 14:24:02 -0600275 log<level::ERR>("Missing required zone's default floor",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500276 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barthe47c9582021-03-09 14:24:02 -0600277 throw std::runtime_error("Missing required zone's default floor");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500278 }
279 _defaultFloor = jsonObj["default_floor"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600280 // Start with the current floor set as the default
281 _floor = _defaultFloor;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500282}
283
284void Zone::setDecInterval(const json& jsonObj)
285{
286 if (!jsonObj.contains("decrease_interval"))
287 {
288 log<level::ERR>("Missing required zone's decrease interval",
289 entry("JSON=%s", jsonObj.dump().c_str()));
290 throw std::runtime_error("Missing required zone's decrease interval");
291 }
Matthew Barth007de092021-03-25 13:56:04 -0500292 _decInterval =
293 std::chrono::seconds(jsonObj["decrease_interval"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500294}
295
Matthew Barth651f03a2020-08-27 16:15:11 -0500296void Zone::setInterfaces(const json& jsonObj)
297{
298 for (const auto& interface : jsonObj["interfaces"])
299 {
300 if (!interface.contains("name") || !interface.contains("properties"))
301 {
302 log<level::ERR>("Missing required zone interface attributes",
303 entry("JSON=%s", interface.dump().c_str()));
304 throw std::runtime_error(
305 "Missing required zone interface attributes");
306 }
Matthew Barth216229c2020-09-24 13:47:33 -0500307 auto propFuncs =
308 _intfPropHandlers.find(interface["name"].get<std::string>());
309 if (propFuncs == _intfPropHandlers.end())
310 {
311 // Construct list of available configurable interfaces
312 auto intfs = std::accumulate(
313 std::next(_intfPropHandlers.begin()), _intfPropHandlers.end(),
314 _intfPropHandlers.begin()->first, [](auto list, auto intf) {
315 return std::move(list) + ", " + intf.first;
316 });
317 log<level::ERR>("Configured interface not available",
318 entry("JSON=%s", interface.dump().c_str()),
319 entry("AVAILABLE_INTFS=%s", intfs.c_str()));
320 throw std::runtime_error("Configured interface not available");
321 }
322
Matthew Barth651f03a2020-08-27 16:15:11 -0500323 for (const auto& property : interface["properties"])
324 {
325 if (!property.contains("name"))
326 {
327 log<level::ERR>(
328 "Missing required interface property attributes",
329 entry("JSON=%s", property.dump().c_str()));
330 throw std::runtime_error(
331 "Missing required interface property attributes");
332 }
333 // Attribute "persist" is optional, defaults to `false`
334 auto persist = false;
335 if (property.contains("persist"))
336 {
337 persist = property["persist"].get<bool>();
338 }
339 // Property name from JSON must exactly match supported
340 // index names to functions in property namespace
Matthew Barth216229c2020-09-24 13:47:33 -0500341 auto propFunc =
342 propFuncs->second.find(property["name"].get<std::string>());
343 if (propFunc == propFuncs->second.end())
Matthew Barth651f03a2020-08-27 16:15:11 -0500344 {
Matthew Barth216229c2020-09-24 13:47:33 -0500345 // Construct list of available configurable properties
Matthew Barth651f03a2020-08-27 16:15:11 -0500346 auto props = std::accumulate(
Matthew Barth216229c2020-09-24 13:47:33 -0500347 std::next(propFuncs->second.begin()),
348 propFuncs->second.end(), propFuncs->second.begin()->first,
349 [](auto list, auto prop) {
Matthew Barth651f03a2020-08-27 16:15:11 -0500350 return std::move(list) + ", " + prop.first;
351 });
Matthew Barth216229c2020-09-24 13:47:33 -0500352 log<level::ERR>("Configured property not available",
Matthew Barth651f03a2020-08-27 16:15:11 -0500353 entry("JSON=%s", property.dump().c_str()),
354 entry("AVAILABLE_PROPS=%s", props.c_str()));
355 throw std::runtime_error(
356 "Configured property function not available");
357 }
Matthew Barthb584d812021-03-11 15:55:04 -0600358 auto propHandler = propFunc->second(property, persist);
359 // Only call non-null set property handler functions
360 if (propHandler)
361 {
362 propHandler(this);
363 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500364 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500365 }
366}
367
Matthew Bartha0dd1352021-03-09 11:10:49 -0600368bool Zone::isPersisted(const std::string& intf, const std::string& prop)
369{
370 auto it = _propsPersisted.find(intf);
371 if (it == _propsPersisted.end())
372 {
373 return false;
374 }
375
376 return std::any_of(it->second.begin(), it->second.end(),
377 [&prop](const auto& p) { return prop == p; });
378}
379
380void Zone::saveCurrentMode()
381{
382 fs::path path{CONTROL_PERSIST_ROOT_PATH};
383 // Append zone name and property description
384 path /= getName();
385 path /= "CurrentMode";
386 std::ofstream ofs(path.c_str(), std::ios::binary);
387 cereal::JSONOutputArchive oArch(ofs);
388 oArch(ThermalObject::current());
389}
390
Matthew Bartha4483742021-03-25 14:09:01 -0500391void Zone::restoreCurrentMode()
392{
393 auto current = ThermalObject::current();
394 fs::path path{CONTROL_PERSIST_ROOT_PATH};
395 path /= getName();
396 path /= "CurrentMode";
397 fs::create_directories(path.parent_path());
398
399 try
400 {
401 if (fs::exists(path))
402 {
403 std::ifstream ifs(path.c_str(), std::ios::in | std::ios::binary);
404 cereal::JSONInputArchive iArch(ifs);
405 iArch(current);
406 }
407 }
408 catch (std::exception& e)
409 {
410 log<level::ERR>(e.what());
411 fs::remove(path);
412 current = ThermalObject::current();
413 }
414
415 this->current(current);
416}
417
Matthew Barth651f03a2020-08-27 16:15:11 -0500418/**
Matthew Barth216229c2020-09-24 13:47:33 -0500419 * Properties of interfaces supported by the zone configuration that return
Matthew Barthb584d812021-03-11 15:55:04 -0600420 * a handler function that sets the zone's property value(s) and persist state.
Matthew Barth651f03a2020-08-27 16:15:11 -0500421 */
422namespace zone::property
423{
Matthew Barthb584d812021-03-11 15:55:04 -0600424// Get a set property handler function for the configured values of the
425// "Supported" property
426std::function<void(Zone*)> supported(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500427{
428 std::vector<std::string> values;
Matthew Barth216229c2020-09-24 13:47:33 -0500429 if (!jsonObj.contains("values"))
Matthew Barth651f03a2020-08-27 16:15:11 -0500430 {
Matthew Barth216229c2020-09-24 13:47:33 -0500431 log<level::ERR>(
432 "No 'values' found for \"Supported\" property, using an empty list",
433 entry("JSON=%s", jsonObj.dump().c_str()));
434 }
435 else
436 {
437 for (const auto& value : jsonObj["values"])
438 {
439 if (!value.contains("value"))
440 {
441 log<level::ERR>("No 'value' found for \"Supported\" property "
442 "entry, skipping",
443 entry("JSON=%s", value.dump().c_str()));
444 }
445 else
446 {
447 values.emplace_back(value["value"].get<std::string>());
448 }
449 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500450 }
451
Matthew Barthb584d812021-03-11 15:55:04 -0600452 return Zone::setProperty<std::vector<std::string>>(
453 Zone::thermModeIntf, Zone::supportedProp, &Zone::supported,
454 std::move(values), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500455}
456
Matthew Barthb584d812021-03-11 15:55:04 -0600457// Get a set property handler function for a configured value of the "Current"
Matthew Barth216229c2020-09-24 13:47:33 -0500458// property
Matthew Barthb584d812021-03-11 15:55:04 -0600459std::function<void(Zone*)> current(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500460{
Matthew Barth216229c2020-09-24 13:47:33 -0500461 // Use default value for "Current" property if no "value" entry given
462 if (!jsonObj.contains("value"))
463 {
Matthew Barthb584d812021-03-11 15:55:04 -0600464 log<level::INFO>("No 'value' found for \"Current\" property, "
465 "using default",
466 entry("JSON=%s", jsonObj.dump().c_str()));
467 // Set persist state of property
468 return Zone::setPropertyPersist(Zone::thermModeIntf, Zone::currentProp,
469 persist);
Matthew Barth216229c2020-09-24 13:47:33 -0500470 }
471
Matthew Barthb584d812021-03-11 15:55:04 -0600472 return Zone::setProperty<std::string>(
473 Zone::thermModeIntf, Zone::currentProp, &Zone::current,
474 jsonObj["value"].get<std::string>(), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500475}
Matthew Barthb584d812021-03-11 15:55:04 -0600476
Matthew Barth651f03a2020-08-27 16:15:11 -0500477} // namespace zone::property
478
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500479} // namespace phosphor::fan::control::json