1 /*
2 // Copyright (c) 2017 Intel 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 
17 #include "ADCSensor.hpp"
18 #include "Thresholds.hpp"
19 #include "Utils.hpp"
20 #include "VariantVisitors.hpp"
21 
22 #include <boost/algorithm/string/case_conv.hpp>
23 #include <boost/asio/error.hpp>
24 #include <boost/asio/io_context.hpp>
25 #include <boost/asio/post.hpp>
26 #include <boost/asio/steady_timer.hpp>
27 #include <boost/container/flat_map.hpp>
28 #include <boost/container/flat_set.hpp>
29 #include <gpiod.hpp>
30 #include <sdbusplus/asio/connection.hpp>
31 #include <sdbusplus/asio/object_server.hpp>
32 #include <sdbusplus/bus.hpp>
33 #include <sdbusplus/bus/match.hpp>
34 #include <sdbusplus/message.hpp>
35 #include <sdbusplus/message/native_types.hpp>
36 
37 #include <array>
38 #include <chrono>
39 #include <cstddef>
40 #include <filesystem>
41 #include <fstream>
42 #include <functional>
43 #include <iostream>
44 #include <memory>
45 #include <optional>
46 #include <regex>
47 #include <stdexcept>
48 #include <string>
49 #include <utility>
50 #include <variant>
51 #include <vector>
52 
53 static constexpr bool debug = false;
54 static constexpr float pollRateDefault = 0.5;
55 static constexpr float gpioBridgeSetupTimeDefault = 0.02;
56 
57 namespace fs = std::filesystem;
58 
59 static constexpr auto sensorTypes{std::to_array<const char*>({"ADC"})};
60 static std::regex inputRegex(R"(in(\d+)_input)");
61 
62 static boost::container::flat_map<size_t, bool> cpuPresence;
63 
64 enum class UpdateType
65 {
66     init,
67     cpuPresenceChange
68 };
69 
70 // filter out adc from any other voltage sensor
isAdc(const fs::path & parentPath)71 bool isAdc(const fs::path& parentPath)
72 {
73     fs::path namePath = parentPath / "name";
74 
75     std::ifstream nameFile(namePath);
76     if (!nameFile.good())
77     {
78         std::cerr << "Failure reading " << namePath.string() << "\n";
79         return false;
80     }
81 
82     std::string name;
83     std::getline(nameFile, name);
84 
85     return name == "iio_hwmon";
86 }
87 
createSensors(boost::asio::io_context & io,sdbusplus::asio::object_server & objectServer,boost::container::flat_map<std::string,std::shared_ptr<ADCSensor>> & sensors,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection,const std::shared_ptr<boost::container::flat_set<std::string>> & sensorsChanged,UpdateType updateType)88 void createSensors(
89     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
90     boost::container::flat_map<std::string, std::shared_ptr<ADCSensor>>&
91         sensors,
92     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
93     const std::shared_ptr<boost::container::flat_set<std::string>>&
94         sensorsChanged,
95     UpdateType updateType)
96 {
97     auto getter = std::make_shared<GetSensorConfiguration>(
98         dbusConnection,
99         [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
100          updateType](const ManagedObjectType& sensorConfigurations) {
101         bool firstScan = sensorsChanged == nullptr;
102         std::vector<fs::path> paths;
103         if (!findFiles(fs::path("/sys/class/hwmon"), R"(in\d+_input)", paths))
104         {
105             std::cerr << "No adc sensors in system\n";
106             return;
107         }
108 
109         // iterate through all found adc sensors, and try to match them with
110         // configuration
111         for (auto& path : paths)
112         {
113             if (!isAdc(path.parent_path()))
114             {
115                 continue;
116             }
117             std::smatch match;
118             std::string pathStr = path.string();
119 
120             std::regex_search(pathStr, match, inputRegex);
121             std::string indexStr = *(match.begin() + 1);
122 
123             // convert to 0 based
124             size_t index = std::stoul(indexStr) - 1;
125 
126             const SensorData* sensorData = nullptr;
127             const std::string* interfacePath = nullptr;
128             const std::pair<std::string, SensorBaseConfigMap>*
129                 baseConfiguration = nullptr;
130             for (const auto& [path, cfgData] : sensorConfigurations)
131             {
132                 // clear it out each loop
133                 baseConfiguration = nullptr;
134 
135                 // find base configuration
136                 for (const char* type : sensorTypes)
137                 {
138                     auto sensorBase = cfgData.find(configInterfaceName(type));
139                     if (sensorBase != cfgData.end())
140                     {
141                         baseConfiguration = &(*sensorBase);
142                         break;
143                     }
144                 }
145                 if (baseConfiguration == nullptr)
146                 {
147                     continue;
148                 }
149                 auto findIndex = baseConfiguration->second.find("Index");
150                 if (findIndex == baseConfiguration->second.end())
151                 {
152                     std::cerr << "Base configuration missing Index"
153                               << baseConfiguration->first << "\n";
154                     continue;
155                 }
156 
157                 unsigned int number = std::visit(VariantToUnsignedIntVisitor(),
158                                                  findIndex->second);
159 
160                 if (number != index)
161                 {
162                     continue;
163                 }
164 
165                 sensorData = &cfgData;
166                 interfacePath = &path.str;
167                 break;
168             }
169             if (sensorData == nullptr)
170             {
171                 if constexpr (debug)
172                 {
173                     std::cerr << "failed to find match for " << path.string()
174                               << "\n";
175                 }
176                 continue;
177             }
178 
179             if (baseConfiguration == nullptr)
180             {
181                 std::cerr << "error finding base configuration for"
182                           << path.string() << "\n";
183                 continue;
184             }
185 
186             auto findSensorName = baseConfiguration->second.find("Name");
187             if (findSensorName == baseConfiguration->second.end())
188             {
189                 std::cerr << "could not determine configuration name for "
190                           << path.string() << "\n";
191                 continue;
192             }
193             std::string sensorName =
194                 std::get<std::string>(findSensorName->second);
195 
196             // on rescans, only update sensors we were signaled by
197             auto findSensor = sensors.find(sensorName);
198             if (!firstScan && findSensor != sensors.end())
199             {
200                 bool found = false;
201                 for (auto it = sensorsChanged->begin();
202                      it != sensorsChanged->end(); it++)
203                 {
204                     if (findSensor->second &&
205                         it->ends_with(findSensor->second->name))
206                     {
207                         sensorsChanged->erase(it);
208                         findSensor->second = nullptr;
209                         found = true;
210                         break;
211                     }
212                 }
213                 if (!found)
214                 {
215                     continue;
216                 }
217             }
218 
219             auto findCPU = baseConfiguration->second.find("CPURequired");
220             if (findCPU != baseConfiguration->second.end())
221             {
222                 size_t index = std::visit(VariantToIntVisitor(),
223                                           findCPU->second);
224                 auto presenceFind = cpuPresence.find(index);
225                 if (presenceFind == cpuPresence.end())
226                 {
227                     continue; // no such cpu
228                 }
229                 if (!presenceFind->second)
230                 {
231                     continue; // cpu not installed
232                 }
233             }
234             else if (updateType == UpdateType::cpuPresenceChange)
235             {
236                 continue;
237             }
238 
239             std::vector<thresholds::Threshold> sensorThresholds;
240             if (!parseThresholdsFromConfig(*sensorData, sensorThresholds))
241             {
242                 std::cerr << "error populating thresholds for " << sensorName
243                           << "\n";
244             }
245 
246             auto findScaleFactor =
247                 baseConfiguration->second.find("ScaleFactor");
248             float scaleFactor = 1.0;
249             if (findScaleFactor != baseConfiguration->second.end())
250             {
251                 scaleFactor = std::visit(VariantToFloatVisitor(),
252                                          findScaleFactor->second);
253                 // scaleFactor is used in division
254                 if (scaleFactor == 0.0F)
255                 {
256                     scaleFactor = 1.0;
257                 }
258             }
259 
260             float pollRate = getPollRate(baseConfiguration->second,
261                                          pollRateDefault);
262             PowerState readState = getPowerState(baseConfiguration->second);
263 
264             auto& sensor = sensors[sensorName];
265             sensor = nullptr;
266 
267             std::optional<BridgeGpio> bridgeGpio;
268             for (const auto& [key, cfgMap] : *sensorData)
269             {
270                 if (key.find("BridgeGpio") != std::string::npos)
271                 {
272                     auto findName = cfgMap.find("Name");
273                     if (findName != cfgMap.end())
274                     {
275                         std::string gpioName = std::visit(
276                             VariantToStringVisitor(), findName->second);
277 
278                         int polarity = gpiod::line::ACTIVE_HIGH;
279                         auto findPolarity = cfgMap.find("Polarity");
280                         if (findPolarity != cfgMap.end())
281                         {
282                             if (std::string("Low") ==
283                                 std::visit(VariantToStringVisitor(),
284                                            findPolarity->second))
285                             {
286                                 polarity = gpiod::line::ACTIVE_LOW;
287                             }
288                         }
289 
290                         float setupTime = gpioBridgeSetupTimeDefault;
291                         auto findSetupTime = cfgMap.find("SetupTime");
292                         if (findSetupTime != cfgMap.end())
293                         {
294                             setupTime = std::visit(VariantToFloatVisitor(),
295                                                    findSetupTime->second);
296                         }
297 
298                         bridgeGpio = BridgeGpio(gpioName, polarity, setupTime);
299                     }
300 
301                     break;
302                 }
303             }
304 
305             sensor = std::make_shared<ADCSensor>(
306                 path.string(), objectServer, dbusConnection, io, sensorName,
307                 std::move(sensorThresholds), scaleFactor, pollRate, readState,
308                 *interfacePath, std::move(bridgeGpio));
309             sensor->setupRead();
310         }
311     });
312 
313     getter->getConfiguration(
314         std::vector<std::string>{sensorTypes.begin(), sensorTypes.end()});
315 }
316 
main()317 int main()
318 {
319     boost::asio::io_context io;
320     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
321     sdbusplus::asio::object_server objectServer(systemBus, true);
322     objectServer.add_manager("/xyz/openbmc_project/sensors");
323 
324     systemBus->request_name("xyz.openbmc_project.ADCSensor");
325     boost::container::flat_map<std::string, std::shared_ptr<ADCSensor>> sensors;
326     auto sensorsChanged =
327         std::make_shared<boost::container::flat_set<std::string>>();
328 
329     boost::asio::post(io, [&]() {
330         createSensors(io, objectServer, sensors, systemBus, nullptr,
331                       UpdateType::init);
332     });
333 
334     boost::asio::steady_timer filterTimer(io);
335     std::function<void(sdbusplus::message_t&)> eventHandler =
336         [&](sdbusplus::message_t& message) {
337         if (message.is_method_error())
338         {
339             std::cerr << "callback method error\n";
340             return;
341         }
342         sensorsChanged->insert(message.get_path());
343         // this implicitly cancels the timer
344         filterTimer.expires_after(std::chrono::seconds(1));
345 
346         filterTimer.async_wait([&](const boost::system::error_code& ec) {
347             if (ec == boost::asio::error::operation_aborted)
348             {
349                 /* we were canceled*/
350                 return;
351             }
352             if (ec)
353             {
354                 std::cerr << "timer error\n";
355                 return;
356             }
357             createSensors(io, objectServer, sensors, systemBus, sensorsChanged,
358                           UpdateType::init);
359         });
360     };
361 
362     boost::asio::steady_timer cpuFilterTimer(io);
363     std::function<void(sdbusplus::message_t&)> cpuPresenceHandler =
364         [&](sdbusplus::message_t& message) {
365         std::string path = message.get_path();
366         boost::to_lower(path);
367 
368         sdbusplus::message::object_path cpuPath(path);
369         std::string cpuName = cpuPath.filename();
370         if (!cpuName.starts_with("cpu"))
371         {
372             return; // not interested
373         }
374         size_t index = 0;
375         try
376         {
377             index = std::stoi(path.substr(path.size() - 1));
378         }
379         catch (const std::invalid_argument&)
380         {
381             std::cerr << "Found invalid path " << path << "\n";
382             return;
383         }
384 
385         std::string objectName;
386         boost::container::flat_map<std::string, std::variant<bool>> values;
387         message.read(objectName, values);
388         auto findPresence = values.find("Present");
389         if (findPresence != values.end())
390         {
391             cpuPresence[index] = std::get<bool>(findPresence->second);
392         }
393 
394         // this implicitly cancels the timer
395         cpuFilterTimer.expires_after(std::chrono::seconds(1));
396 
397         cpuFilterTimer.async_wait([&](const boost::system::error_code& ec) {
398             if (ec == boost::asio::error::operation_aborted)
399             {
400                 /* we were canceled*/
401                 return;
402             }
403             if (ec)
404             {
405                 std::cerr << "timer error\n";
406                 return;
407             }
408             createSensors(io, objectServer, sensors, systemBus, nullptr,
409                           UpdateType::cpuPresenceChange);
410         });
411     };
412 
413     std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
414         setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
415     matches.emplace_back(std::make_unique<sdbusplus::bus::match_t>(
416         static_cast<sdbusplus::bus_t&>(*systemBus),
417         "type='signal',member='PropertiesChanged',path_namespace='" +
418             std::string(cpuInventoryPath) +
419             "',arg0namespace='xyz.openbmc_project.Inventory.Item'",
420         cpuPresenceHandler));
421 
422     setupManufacturingModeMatch(*systemBus);
423     io.run();
424 }
425