1 /** 2 * Copyright © 2016 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 */ 16 #include "config.h" 17 18 #include "mainloop.hpp" 19 20 #include "env.hpp" 21 #include "fan_pwm.hpp" 22 #include "fan_speed.hpp" 23 #include "hwmon.hpp" 24 #include "hwmonio.hpp" 25 #include "sensor.hpp" 26 #include "sensorset.hpp" 27 #include "sysfs.hpp" 28 #include "targets.hpp" 29 #include "thresholds.hpp" 30 31 #include <cassert> 32 #include <cstdlib> 33 #include <functional> 34 #include <iostream> 35 #include <memory> 36 #include <phosphor-logging/elog-errors.hpp> 37 #include <sstream> 38 #include <string> 39 #include <unordered_set> 40 #include <xyz/openbmc_project/Sensor/Device/error.hpp> 41 42 using namespace phosphor::logging; 43 44 // Initialization for Warning Objects 45 decltype(Thresholds<WarningObject>::setLo) Thresholds<WarningObject>::setLo = 46 &WarningObject::warningLow; 47 decltype(Thresholds<WarningObject>::setHi) Thresholds<WarningObject>::setHi = 48 &WarningObject::warningHigh; 49 decltype(Thresholds<WarningObject>::getLo) Thresholds<WarningObject>::getLo = 50 &WarningObject::warningLow; 51 decltype(Thresholds<WarningObject>::getHi) Thresholds<WarningObject>::getHi = 52 &WarningObject::warningHigh; 53 decltype( 54 Thresholds<WarningObject>::alarmLo) Thresholds<WarningObject>::alarmLo = 55 &WarningObject::warningAlarmLow; 56 decltype( 57 Thresholds<WarningObject>::alarmHi) Thresholds<WarningObject>::alarmHi = 58 &WarningObject::warningAlarmHigh; 59 60 // Initialization for Critical Objects 61 decltype(Thresholds<CriticalObject>::setLo) Thresholds<CriticalObject>::setLo = 62 &CriticalObject::criticalLow; 63 decltype(Thresholds<CriticalObject>::setHi) Thresholds<CriticalObject>::setHi = 64 &CriticalObject::criticalHigh; 65 decltype(Thresholds<CriticalObject>::getLo) Thresholds<CriticalObject>::getLo = 66 &CriticalObject::criticalLow; 67 decltype(Thresholds<CriticalObject>::getHi) Thresholds<CriticalObject>::getHi = 68 &CriticalObject::criticalHigh; 69 decltype( 70 Thresholds<CriticalObject>::alarmLo) Thresholds<CriticalObject>::alarmLo = 71 &CriticalObject::criticalAlarmLow; 72 decltype( 73 Thresholds<CriticalObject>::alarmHi) Thresholds<CriticalObject>::alarmHi = 74 &CriticalObject::criticalAlarmHigh; 75 76 std::string MainLoop::getID(SensorSet::container_t::const_reference sensor) 77 { 78 std::string id; 79 80 /* 81 * Check if the value of the MODE_<item><X> env variable for the sensor 82 * is set. If it is, then read the from the <item><X>_<mode> 83 * file. The name of the DBUS object would be the value of the env 84 * variable LABEL_<item><mode value>. If the MODE_<item><X> env variable 85 * doesn't exist, then the name of DBUS object is the value of the env 86 * variable LABEL_<item><X>. 87 * 88 * For example, if MODE_temp1 = "label", then code reads the temp1_label 89 * file. If it has a 5 in it, then it will use the following entry to 90 * name the object: LABEL_temp5 = "My DBus object name". 91 * 92 */ 93 auto mode = env::getEnv("MODE", sensor.first); 94 if (!mode.empty()) 95 { 96 id = env::getIndirectID(_hwmonRoot + '/' + _instance + '/', mode, 97 sensor.first); 98 99 if (id.empty()) 100 { 101 return id; 102 } 103 } 104 105 // Use the ID we looked up above if there was one, 106 // otherwise use the standard one. 107 id = (id.empty()) ? sensor.first.second : id; 108 109 return id; 110 } 111 112 SensorIdentifiers 113 MainLoop::getIdentifiers(SensorSet::container_t::const_reference sensor) 114 { 115 std::string id = getID(sensor); 116 std::string label; 117 118 if (!id.empty()) 119 { 120 // Ignore inputs without a label. 121 label = env::getEnv("LABEL", sensor.first.first, id); 122 } 123 124 return std::make_tuple(std::move(id), std::move(label)); 125 } 126 127 /** 128 * Reads the environment parameters of a sensor and creates an object with 129 * atleast the `Value` interface, otherwise returns without creating the object. 130 * If the `Value` interface is successfully created, by reading the sensor's 131 * corresponding sysfs file's value, the additional interfaces for the sensor 132 * are created and the InterfacesAdded signal is emitted. The object's state 133 * data is then returned for sensor state monitoring within the main loop. 134 */ 135 std::optional<ObjectStateData> 136 MainLoop::getObject(SensorSet::container_t::const_reference sensor) 137 { 138 auto properties = getIdentifiers(sensor); 139 if (std::get<sensorID>(properties).empty() || 140 std::get<sensorLabel>(properties).empty()) 141 { 142 return {}; 143 } 144 145 hwmon::Attributes attrs; 146 if (!hwmon::getAttributes(sensor.first.first, attrs)) 147 { 148 return {}; 149 } 150 151 /* Note: The sensor objects all share the same ioAccess object. */ 152 auto sensorObj = 153 std::make_unique<sensor::Sensor>(sensor.first, &_ioAccess, _devPath); 154 155 // Get list of return codes for removing sensors on device 156 auto devRmRCs = env::getEnv("REMOVERCS"); 157 // Add sensor removal return codes defined at the device level 158 sensorObj->addRemoveRCs(devRmRCs); 159 160 std::string objectPath{_root}; 161 objectPath.append(1, '/'); 162 objectPath.append(hwmon::getNamespace(attrs)); 163 objectPath.append(1, '/'); 164 objectPath.append(std::get<sensorLabel>(properties)); 165 166 ObjectInfo info(&_bus, std::move(objectPath), InterfaceMap()); 167 RetryIO retryIO(hwmonio::retries, hwmonio::delay); 168 if (_rmSensors.find(sensor.first) != _rmSensors.end()) 169 { 170 // When adding a sensor that was purposely removed, 171 // don't retry on errors when reading its value 172 std::get<size_t>(retryIO) = 0; 173 } 174 auto valueInterface = static_cast<std::shared_ptr<ValueObject>>(nullptr); 175 try 176 { 177 // Add status interface based on _fault file being present 178 sensorObj->addStatus(info); 179 valueInterface = sensorObj->addValue(retryIO, info); 180 } 181 catch (const std::system_error& e) 182 { 183 auto file = 184 sysfs::make_sysfs_path(_ioAccess.path(), sensor.first.first, 185 sensor.first.second, hwmon::entry::cinput); 186 #ifndef REMOVE_ON_FAIL 187 // Check sensorAdjusts for sensor removal RCs 188 auto& sAdjusts = sensorObj->getAdjusts(); 189 if (sAdjusts.rmRCs.count(e.code().value()) > 0) 190 { 191 // Return code found in sensor return code removal list 192 if (_rmSensors.find(sensor.first) == _rmSensors.end()) 193 { 194 // Trace for sensor not already removed from dbus 195 log<level::INFO>("Sensor not added to dbus for read fail", 196 entry("FILE=%s", file.c_str()), 197 entry("RC=%d", e.code().value())); 198 _rmSensors[std::move(sensor.first)] = std::move(sensor.second); 199 } 200 return {}; 201 } 202 #endif 203 using namespace sdbusplus::xyz::openbmc_project::Sensor::Device::Error; 204 report<ReadFailure>( 205 xyz::openbmc_project::Sensor::Device::ReadFailure::CALLOUT_ERRNO( 206 e.code().value()), 207 xyz::openbmc_project::Sensor::Device::ReadFailure:: 208 CALLOUT_DEVICE_PATH(_devPath.c_str())); 209 210 log<level::INFO>("Logging failing sysfs file", 211 entry("FILE=%s", file.c_str())); 212 #ifdef REMOVE_ON_FAIL 213 return {}; /* skip adding this sensor for now. */ 214 #else 215 exit(EXIT_FAILURE); 216 #endif 217 } 218 auto sensorValue = valueInterface->value(); 219 int64_t scale = 0; 220 // scale the thresholds only if we're using doubles 221 if constexpr (std::is_same<SensorValueType, double>::value) 222 { 223 scale = sensorObj->getScale(); 224 } 225 addThreshold<WarningObject>(sensor.first.first, 226 std::get<sensorID>(properties), sensorValue, 227 info, scale); 228 addThreshold<CriticalObject>(sensor.first.first, 229 std::get<sensorID>(properties), sensorValue, 230 info, scale); 231 232 auto target = 233 addTarget<hwmon::FanSpeed>(sensor.first, _ioAccess, _devPath, info); 234 if (target) 235 { 236 target->enable(); 237 } 238 addTarget<hwmon::FanPwm>(sensor.first, _ioAccess, _devPath, info); 239 240 // All the interfaces have been created. Go ahead 241 // and emit InterfacesAdded. 242 valueInterface->emit_object_added(); 243 244 // Save sensor object specifications 245 _sensorObjects[sensor.first] = std::move(sensorObj); 246 247 return std::make_pair(std::move(std::get<sensorLabel>(properties)), 248 std::move(info)); 249 } 250 251 MainLoop::MainLoop(sdbusplus::bus::bus&& bus, const std::string& param, 252 const std::string& path, const std::string& devPath, 253 const char* prefix, const char* root) : 254 _bus(std::move(bus)), 255 _manager(_bus, root), _pathParam(param), _hwmonRoot(), _instance(), 256 _devPath(devPath), _prefix(prefix), _root(root), _state(), _ioAccess(path), 257 _event(sdeventplus::Event::get_default()), 258 _timer(_event, std::bind(&MainLoop::read, this)) 259 { 260 // Strip off any trailing slashes. 261 std::string p = path; 262 while (!p.empty() && p.back() == '/') 263 { 264 p.pop_back(); 265 } 266 267 // Given the furthest right /, set instance to 268 // the basename, and hwmonRoot to the leading path. 269 auto n = p.rfind('/'); 270 if (n != std::string::npos) 271 { 272 _instance.assign(p.substr(n + 1)); 273 _hwmonRoot.assign(p.substr(0, n)); 274 } 275 276 assert(!_instance.empty()); 277 assert(!_hwmonRoot.empty()); 278 } 279 280 void MainLoop::shutdown() noexcept 281 { 282 _event.exit(0); 283 } 284 285 void MainLoop::run() 286 { 287 init(); 288 289 std::function<void()> callback(std::bind(&MainLoop::read, this)); 290 try 291 { 292 _timer.restart(std::chrono::microseconds(_interval)); 293 294 // TODO: Issue#6 - Optionally look at polling interval sysfs entry. 295 296 // TODO: Issue#7 - Should probably periodically check the SensorSet 297 // for new entries. 298 299 _bus.attach_event(_event.get(), SD_EVENT_PRIORITY_IMPORTANT); 300 _event.loop(); 301 } 302 catch (const std::exception& e) 303 { 304 log<level::ERR>("Error in sysfs polling loop", 305 entry("ERROR=%s", e.what())); 306 throw; 307 } 308 } 309 310 void MainLoop::init() 311 { 312 // Check sysfs for available sensors. 313 auto sensors = std::make_unique<SensorSet>(_hwmonRoot + '/' + _instance); 314 315 for (const auto& i : *sensors) 316 { 317 auto object = getObject(i); 318 if (object) 319 { 320 // Construct the SensorSet value 321 // std::tuple<SensorSet::mapped_type, 322 // std::string(Sensor Label), 323 // ObjectInfo> 324 auto value = 325 std::make_tuple(std::move(i.second), std::move((*object).first), 326 std::move((*object).second)); 327 328 _state[std::move(i.first)] = std::move(value); 329 } 330 } 331 332 /* If there are no sensors specified by labels, exit. */ 333 if (0 == _state.size()) 334 { 335 exit(0); 336 } 337 338 { 339 std::stringstream ss; 340 ss << _prefix << "-" 341 << std::to_string(std::hash<std::string>{}(_devPath + _pathParam)) 342 << ".Hwmon1"; 343 344 _bus.request_name(ss.str().c_str()); 345 } 346 347 { 348 auto interval = env::getEnv("INTERVAL"); 349 if (!interval.empty()) 350 { 351 _interval = std::strtoull(interval.c_str(), NULL, 10); 352 } 353 } 354 } 355 356 void MainLoop::read() 357 { 358 // TODO: Issue#3 - Need to make calls to the dbus sensor cache here to 359 // ensure the objects all exist? 360 361 // Iterate through all the sensors. 362 for (auto& i : _state) 363 { 364 auto& attrs = std::get<0>(i.second); 365 if (attrs.find(hwmon::entry::input) != attrs.end()) 366 { 367 // Read value from sensor. 368 std::string input = hwmon::entry::cinput; 369 if (i.first.first == "pwm") 370 { 371 input = ""; 372 } 373 374 try 375 { 376 int64_t value; 377 auto& objInfo = std::get<ObjectInfo>(i.second); 378 auto& obj = std::get<InterfaceMap>(objInfo); 379 380 auto it = obj.find(InterfaceType::STATUS); 381 if (it != obj.end()) 382 { 383 auto fault = _ioAccess.read( 384 i.first.first, i.first.second, hwmon::entry::fault, 385 hwmonio::retries, hwmonio::delay); 386 auto statusIface = 387 std::any_cast<std::shared_ptr<StatusObject>>( 388 it->second); 389 if (!statusIface->functional((fault == 0) ? true : false)) 390 { 391 continue; 392 } 393 } 394 395 // Retry for up to a second if device is busy 396 // or has a transient error. 397 std::unique_ptr<sensor::Sensor>& sensor = 398 _sensorObjects[i.first]; 399 400 { 401 // RAII object for GPIO unlock / lock 402 sensor::GpioLock gpioLock(sensor->getGpio()); 403 404 value = _ioAccess.read(i.first.first, i.first.second, input, 405 hwmonio::retries, hwmonio::delay); 406 407 value = sensor->adjustValue(value); 408 } 409 410 for (auto& iface : obj) 411 { 412 auto valueIface = std::shared_ptr<ValueObject>(); 413 auto warnIface = std::shared_ptr<WarningObject>(); 414 auto critIface = std::shared_ptr<CriticalObject>(); 415 416 switch (iface.first) 417 { 418 case InterfaceType::VALUE: 419 valueIface = 420 std::any_cast<std::shared_ptr<ValueObject>>( 421 iface.second); 422 valueIface->value(value); 423 break; 424 case InterfaceType::WARN: 425 checkThresholds<WarningObject>(iface.second, value); 426 break; 427 case InterfaceType::CRIT: 428 checkThresholds<CriticalObject>(iface.second, 429 value); 430 break; 431 default: 432 break; 433 } 434 } 435 } 436 catch (const std::system_error& e) 437 { 438 auto file = sysfs::make_sysfs_path( 439 _ioAccess.path(), i.first.first, i.first.second, 440 hwmon::entry::cinput); 441 #ifndef REMOVE_ON_FAIL 442 // Check sensorAdjusts for sensor removal RCs 443 auto& sAdjusts = _sensorObjects[i.first]->getAdjusts(); 444 if (sAdjusts.rmRCs.count(e.code().value()) > 0) 445 { 446 // Return code found in sensor return code removal list 447 if (_rmSensors.find(i.first) == _rmSensors.end()) 448 { 449 // Trace for sensor not already removed from dbus 450 log<level::INFO>( 451 "Remove sensor from dbus for read fail", 452 entry("FILE=%s", file.c_str()), 453 entry("RC=%d", e.code().value())); 454 // Mark this sensor to be removed from dbus 455 _rmSensors[i.first] = std::get<0>(i.second); 456 } 457 continue; 458 } 459 #endif 460 using namespace sdbusplus::xyz::openbmc_project::Sensor:: 461 Device::Error; 462 report<ReadFailure>( 463 xyz::openbmc_project::Sensor::Device::ReadFailure:: 464 CALLOUT_ERRNO(e.code().value()), 465 xyz::openbmc_project::Sensor::Device::ReadFailure:: 466 CALLOUT_DEVICE_PATH(_devPath.c_str())); 467 468 log<level::INFO>("Logging failing sysfs file", 469 entry("FILE=%s", file.c_str())); 470 471 #ifdef REMOVE_ON_FAIL 472 _rmSensors[i.first] = std::get<0>(i.second); 473 #else 474 exit(EXIT_FAILURE); 475 #endif 476 } 477 } 478 } 479 480 // Remove any sensors marked for removal 481 for (const auto& i : _rmSensors) 482 { 483 // Remove sensor object from dbus using emit_object_removed() 484 auto& objInfo = std::get<ObjectInfo>(_state[i.first]); 485 auto& objPath = std::get<std::string>(objInfo); 486 _bus.emit_object_removed(objPath.c_str()); 487 // Erase sensor object info 488 _state.erase(i.first); 489 } 490 491 #ifndef REMOVE_ON_FAIL 492 // Attempt to add any sensors that were removed 493 auto it = _rmSensors.begin(); 494 while (it != _rmSensors.end()) 495 { 496 if (_state.find(it->first) == _state.end()) 497 { 498 SensorSet::container_t::value_type ssValueType = 499 std::make_pair(it->first, it->second); 500 auto object = getObject(ssValueType); 501 if (object) 502 { 503 // Construct the SensorSet value 504 // std::tuple<SensorSet::mapped_type, 505 // std::string(Sensor Label), 506 // ObjectInfo> 507 auto value = std::make_tuple(std::move(ssValueType.second), 508 std::move((*object).first), 509 std::move((*object).second)); 510 511 _state[std::move(ssValueType.first)] = std::move(value); 512 513 // Sensor object added, erase entry from removal list 514 auto file = sysfs::make_sysfs_path( 515 _ioAccess.path(), it->first.first, it->first.second, 516 hwmon::entry::cinput); 517 log<level::INFO>("Added sensor to dbus after successful read", 518 entry("FILE=%s", file.c_str())); 519 it = _rmSensors.erase(it); 520 } 521 else 522 { 523 ++it; 524 } 525 } 526 else 527 { 528 // Sanity check to remove sensors that were re-added 529 it = _rmSensors.erase(it); 530 } 531 } 532 #endif 533 } 534 535 // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 536