blob: 8db1b4e8284715865551d8ccde6059620a079e48 [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{
250 if (!jsonObj.contains("full_speed"))
251 {
252 log<level::ERR>("Missing required zone's full speed",
253 entry("JSON=%s", jsonObj.dump().c_str()));
254 throw std::runtime_error("Missing required zone's full speed");
255 }
Matthew Barthe47c9582021-03-09 14:24:02 -0600256 _defaultCeiling = jsonObj["full_speed"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600257 // Start with the current target set as the default
Matthew Barthe47c9582021-03-09 14:24:02 -0600258 _target = _defaultCeiling;
Matthew Barth2b3253e2021-03-09 14:51:16 -0600259 // Start with the current ceiling set as the default
260 _ceiling = _defaultCeiling;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500261}
262
263void Zone::setDefaultFloor(const json& jsonObj)
264{
265 if (!jsonObj.contains("default_floor"))
266 {
Matthew Barthe47c9582021-03-09 14:24:02 -0600267 log<level::ERR>("Missing required zone's default floor",
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500268 entry("JSON=%s", jsonObj.dump().c_str()));
Matthew Barthe47c9582021-03-09 14:24:02 -0600269 throw std::runtime_error("Missing required zone's default floor");
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500270 }
271 _defaultFloor = jsonObj["default_floor"].get<uint64_t>();
Matthew Barth12cb1252021-03-08 16:47:30 -0600272 // Start with the current floor set as the default
273 _floor = _defaultFloor;
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500274}
275
276void Zone::setDecInterval(const json& jsonObj)
277{
278 if (!jsonObj.contains("decrease_interval"))
279 {
280 log<level::ERR>("Missing required zone's decrease interval",
281 entry("JSON=%s", jsonObj.dump().c_str()));
282 throw std::runtime_error("Missing required zone's decrease interval");
283 }
Matthew Barth007de092021-03-25 13:56:04 -0500284 _decInterval =
285 std::chrono::seconds(jsonObj["decrease_interval"].get<uint64_t>());
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500286}
287
Matthew Barth651f03a2020-08-27 16:15:11 -0500288void Zone::setInterfaces(const json& jsonObj)
289{
290 for (const auto& interface : jsonObj["interfaces"])
291 {
292 if (!interface.contains("name") || !interface.contains("properties"))
293 {
294 log<level::ERR>("Missing required zone interface attributes",
295 entry("JSON=%s", interface.dump().c_str()));
296 throw std::runtime_error(
297 "Missing required zone interface attributes");
298 }
Matthew Barth216229c2020-09-24 13:47:33 -0500299 auto propFuncs =
300 _intfPropHandlers.find(interface["name"].get<std::string>());
301 if (propFuncs == _intfPropHandlers.end())
302 {
303 // Construct list of available configurable interfaces
304 auto intfs = std::accumulate(
305 std::next(_intfPropHandlers.begin()), _intfPropHandlers.end(),
306 _intfPropHandlers.begin()->first, [](auto list, auto intf) {
307 return std::move(list) + ", " + intf.first;
308 });
309 log<level::ERR>("Configured interface not available",
310 entry("JSON=%s", interface.dump().c_str()),
311 entry("AVAILABLE_INTFS=%s", intfs.c_str()));
312 throw std::runtime_error("Configured interface not available");
313 }
314
Matthew Barth651f03a2020-08-27 16:15:11 -0500315 for (const auto& property : interface["properties"])
316 {
317 if (!property.contains("name"))
318 {
319 log<level::ERR>(
320 "Missing required interface property attributes",
321 entry("JSON=%s", property.dump().c_str()));
322 throw std::runtime_error(
323 "Missing required interface property attributes");
324 }
325 // Attribute "persist" is optional, defaults to `false`
326 auto persist = false;
327 if (property.contains("persist"))
328 {
329 persist = property["persist"].get<bool>();
330 }
331 // Property name from JSON must exactly match supported
332 // index names to functions in property namespace
Matthew Barth216229c2020-09-24 13:47:33 -0500333 auto propFunc =
334 propFuncs->second.find(property["name"].get<std::string>());
335 if (propFunc == propFuncs->second.end())
Matthew Barth651f03a2020-08-27 16:15:11 -0500336 {
Matthew Barth216229c2020-09-24 13:47:33 -0500337 // Construct list of available configurable properties
Matthew Barth651f03a2020-08-27 16:15:11 -0500338 auto props = std::accumulate(
Matthew Barth216229c2020-09-24 13:47:33 -0500339 std::next(propFuncs->second.begin()),
340 propFuncs->second.end(), propFuncs->second.begin()->first,
341 [](auto list, auto prop) {
Matthew Barth651f03a2020-08-27 16:15:11 -0500342 return std::move(list) + ", " + prop.first;
343 });
Matthew Barth216229c2020-09-24 13:47:33 -0500344 log<level::ERR>("Configured property not available",
Matthew Barth651f03a2020-08-27 16:15:11 -0500345 entry("JSON=%s", property.dump().c_str()),
346 entry("AVAILABLE_PROPS=%s", props.c_str()));
347 throw std::runtime_error(
348 "Configured property function not available");
349 }
Matthew Barthb584d812021-03-11 15:55:04 -0600350 auto propHandler = propFunc->second(property, persist);
351 // Only call non-null set property handler functions
352 if (propHandler)
353 {
354 propHandler(this);
355 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500356 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500357 }
358}
359
Matthew Bartha0dd1352021-03-09 11:10:49 -0600360bool Zone::isPersisted(const std::string& intf, const std::string& prop)
361{
362 auto it = _propsPersisted.find(intf);
363 if (it == _propsPersisted.end())
364 {
365 return false;
366 }
367
368 return std::any_of(it->second.begin(), it->second.end(),
369 [&prop](const auto& p) { return prop == p; });
370}
371
372void Zone::saveCurrentMode()
373{
374 fs::path path{CONTROL_PERSIST_ROOT_PATH};
375 // Append zone name and property description
376 path /= getName();
377 path /= "CurrentMode";
378 std::ofstream ofs(path.c_str(), std::ios::binary);
379 cereal::JSONOutputArchive oArch(ofs);
380 oArch(ThermalObject::current());
381}
382
Matthew Bartha4483742021-03-25 14:09:01 -0500383void Zone::restoreCurrentMode()
384{
385 auto current = ThermalObject::current();
386 fs::path path{CONTROL_PERSIST_ROOT_PATH};
387 path /= getName();
388 path /= "CurrentMode";
389 fs::create_directories(path.parent_path());
390
391 try
392 {
393 if (fs::exists(path))
394 {
395 std::ifstream ifs(path.c_str(), std::ios::in | std::ios::binary);
396 cereal::JSONInputArchive iArch(ifs);
397 iArch(current);
398 }
399 }
400 catch (std::exception& e)
401 {
402 log<level::ERR>(e.what());
403 fs::remove(path);
404 current = ThermalObject::current();
405 }
406
407 this->current(current);
408}
409
Matthew Barth651f03a2020-08-27 16:15:11 -0500410/**
Matthew Barth216229c2020-09-24 13:47:33 -0500411 * Properties of interfaces supported by the zone configuration that return
Matthew Barthb584d812021-03-11 15:55:04 -0600412 * a handler function that sets the zone's property value(s) and persist state.
Matthew Barth651f03a2020-08-27 16:15:11 -0500413 */
414namespace zone::property
415{
Matthew Barthb584d812021-03-11 15:55:04 -0600416// Get a set property handler function for the configured values of the
417// "Supported" property
418std::function<void(Zone*)> supported(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500419{
420 std::vector<std::string> values;
Matthew Barth216229c2020-09-24 13:47:33 -0500421 if (!jsonObj.contains("values"))
Matthew Barth651f03a2020-08-27 16:15:11 -0500422 {
Matthew Barth216229c2020-09-24 13:47:33 -0500423 log<level::ERR>(
424 "No 'values' found for \"Supported\" property, using an empty list",
425 entry("JSON=%s", jsonObj.dump().c_str()));
426 }
427 else
428 {
429 for (const auto& value : jsonObj["values"])
430 {
431 if (!value.contains("value"))
432 {
433 log<level::ERR>("No 'value' found for \"Supported\" property "
434 "entry, skipping",
435 entry("JSON=%s", value.dump().c_str()));
436 }
437 else
438 {
439 values.emplace_back(value["value"].get<std::string>());
440 }
441 }
Matthew Barth651f03a2020-08-27 16:15:11 -0500442 }
443
Matthew Barthb584d812021-03-11 15:55:04 -0600444 return Zone::setProperty<std::vector<std::string>>(
445 Zone::thermModeIntf, Zone::supportedProp, &Zone::supported,
446 std::move(values), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500447}
448
Matthew Barthb584d812021-03-11 15:55:04 -0600449// Get a set property handler function for a configured value of the "Current"
Matthew Barth216229c2020-09-24 13:47:33 -0500450// property
Matthew Barthb584d812021-03-11 15:55:04 -0600451std::function<void(Zone*)> current(const json& jsonObj, bool persist)
Matthew Barth651f03a2020-08-27 16:15:11 -0500452{
Matthew Barth216229c2020-09-24 13:47:33 -0500453 // Use default value for "Current" property if no "value" entry given
454 if (!jsonObj.contains("value"))
455 {
Matthew Barthb584d812021-03-11 15:55:04 -0600456 log<level::INFO>("No 'value' found for \"Current\" property, "
457 "using default",
458 entry("JSON=%s", jsonObj.dump().c_str()));
459 // Set persist state of property
460 return Zone::setPropertyPersist(Zone::thermModeIntf, Zone::currentProp,
461 persist);
Matthew Barth216229c2020-09-24 13:47:33 -0500462 }
463
Matthew Barthb584d812021-03-11 15:55:04 -0600464 return Zone::setProperty<std::string>(
465 Zone::thermModeIntf, Zone::currentProp, &Zone::current,
466 jsonObj["value"].get<std::string>(), persist);
Matthew Barth651f03a2020-08-27 16:15:11 -0500467}
Matthew Barthb584d812021-03-11 15:55:04 -0600468
Matthew Barth651f03a2020-08-27 16:15:11 -0500469} // namespace zone::property
470
Matthew Barth4f0d3b72020-08-27 14:32:15 -0500471} // namespace phosphor::fan::control::json