1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
3
4 #include "overlay.hpp"
5
6 #include "../utils.hpp"
7 #include "devices.hpp"
8 #include "utils.hpp"
9
10 #include <boost/asio/io_context.hpp>
11 #include <boost/asio/steady_timer.hpp>
12 #include <boost/container/flat_set.hpp>
13 #include <nlohmann/json.hpp>
14 #include <phosphor-logging/lg2.hpp>
15
16 #include <filesystem>
17 #include <flat_map>
18 #include <fstream>
19 #include <iomanip>
20 #include <regex>
21 #include <string>
22
23 constexpr const char* outputDir = "/tmp/overlays";
24 constexpr const char* templateChar = "$";
25 constexpr const char* i2CDevsDir = "/sys/bus/i2c/devices";
26 constexpr const char* muxSymlinkDir = "/dev/i2c-mux";
27
28 const std::regex illegalNameRegex("[^A-Za-z0-9_]");
29
30 // helper function to make json types into string
jsonToString(const nlohmann::json & in)31 std::string jsonToString(const nlohmann::json& in)
32 {
33 if (in.type() == nlohmann::json::value_t::string)
34 {
35 return in.get<std::string>();
36 }
37 if (in.type() == nlohmann::json::value_t::array)
38 {
39 // remove brackets and comma from array
40 std::string array = in.dump();
41 array = array.substr(1, array.size() - 2);
42 std::ranges::replace(array, ',', ' ');
43 return array;
44 }
45 return in.dump();
46 }
47
deviceDirName(uint64_t bus,uint64_t address)48 static std::string deviceDirName(uint64_t bus, uint64_t address)
49 {
50 std::ostringstream name;
51 name << bus << "-" << std::hex << std::setw(4) << std::setfill('0')
52 << address;
53 return name.str();
54 }
55
linkMux(std::string_view muxName,uint64_t busIndex,uint64_t address,const std::vector<std::string> & channelNames)56 void linkMux(std::string_view muxName, uint64_t busIndex, uint64_t address,
57 const std::vector<std::string>& channelNames)
58 {
59 std::error_code ec;
60 std::filesystem::path muxSymlinkDirPath(muxSymlinkDir);
61 std::filesystem::create_directory(muxSymlinkDirPath, ec);
62 // ignore error codes here if the directory already exists
63 ec.clear();
64 std::filesystem::path linkDir = muxSymlinkDirPath / muxName;
65 std::filesystem::create_directory(linkDir, ec);
66
67 std::filesystem::path devDir(i2CDevsDir);
68 devDir /= deviceDirName(busIndex, address);
69
70 for (std::size_t channelIndex = 0; channelIndex < channelNames.size();
71 channelIndex++)
72 {
73 const std::string& channelName = channelNames[channelIndex];
74 if (channelName.empty())
75 {
76 continue;
77 }
78
79 std::filesystem::path channelPath =
80 devDir / ("channel-" + std::to_string(channelIndex));
81 if (!is_symlink(channelPath))
82 {
83 lg2::error("{PATH} for mux channel {CHANNEL} doesn't exist!",
84 "PATH", channelPath.string(), "CHANNEL", channelName);
85 continue;
86 }
87 std::filesystem::path bus = std::filesystem::read_symlink(channelPath);
88
89 std::filesystem::path fp("/dev" / bus.filename());
90 std::filesystem::path link(linkDir / channelName);
91
92 std::filesystem::create_symlink(fp, link, ec);
93 if (ec)
94 {
95 lg2::error("Failure creating symlink for {PATH} to {LINK}", "PATH",
96 fp.string(), "LINK", link.string());
97 }
98 }
99 }
100
deleteDevice(std::string_view busPath,uint64_t address,std::string_view destructor)101 static int deleteDevice(std::string_view busPath, uint64_t address,
102 std::string_view destructor)
103 {
104 std::filesystem::path deviceDestructor(busPath);
105 deviceDestructor /= destructor;
106 std::ofstream deviceFile(deviceDestructor);
107 if (!deviceFile.good())
108 {
109 lg2::error("Error writing {PATH}", "PATH", deviceDestructor.string());
110 return -1;
111 }
112 deviceFile << std::to_string(address);
113 deviceFile.close();
114 return 0;
115 }
116
createDevice(std::string_view busPath,std::string_view parameters,std::string_view constructor)117 static int createDevice(std::string_view busPath, std::string_view parameters,
118 std::string_view constructor)
119 {
120 std::filesystem::path deviceConstructor(busPath);
121 deviceConstructor /= constructor;
122 std::ofstream deviceFile(deviceConstructor);
123 if (!deviceFile.good())
124 {
125 lg2::error("Error writing {PATH}", "PATH", deviceConstructor.string());
126 return -1;
127 }
128 deviceFile << parameters;
129 deviceFile.close();
130
131 return 0;
132 }
133
deviceIsCreated(std::string_view busPath,uint64_t bus,uint64_t address,const devices::createsHWMon hasHWMonDir)134 static bool deviceIsCreated(std::string_view busPath, uint64_t bus,
135 uint64_t address,
136 const devices::createsHWMon hasHWMonDir)
137 {
138 std::filesystem::path dirPath = busPath;
139 dirPath /= deviceDirName(bus, address);
140 if (hasHWMonDir == devices::createsHWMon::hasHWMonDir)
141 {
142 dirPath /= "hwmon";
143 }
144
145 std::error_code ec;
146 // Ignore errors; anything but a clean 'true' is just fine as 'false'
147 return std::filesystem::exists(dirPath, ec);
148 }
149
buildDevice(std::string_view name,std::string_view busPath,std::string_view parameters,uint64_t bus,uint64_t address,std::string_view constructor,std::string_view destructor,const devices::createsHWMon hasHWMonDir,std::vector<std::string> channelNames,boost::asio::io_context & io,const size_t retries=5)150 static int buildDevice(
151 std::string_view name, std::string_view busPath,
152 std::string_view parameters, uint64_t bus, uint64_t address,
153 std::string_view constructor, std::string_view destructor,
154 const devices::createsHWMon hasHWMonDir,
155 std::vector<std::string> channelNames, boost::asio::io_context& io,
156 const size_t retries = 5)
157 {
158 if (retries == 0U)
159 {
160 return -1;
161 }
162
163 lg2::debug("try to build device {NAME} at bus={BUS}, address={ADDR}",
164 "NAME", name, "BUS", bus, "ADDR", address);
165
166 // If it's already instantiated, we don't need to create it again.
167 if (!deviceIsCreated(busPath, bus, address, hasHWMonDir))
168 {
169 // Try to create the device
170 createDevice(busPath, parameters, constructor);
171
172 // If it didn't work, delete it and try again in 500ms
173 if (!deviceIsCreated(busPath, bus, address, hasHWMonDir))
174 {
175 deleteDevice(busPath, address, destructor);
176
177 std::shared_ptr<boost::asio::steady_timer> createTimer =
178 std::make_shared<boost::asio::steady_timer>(io);
179 createTimer->expires_after(std::chrono::milliseconds(500));
180 createTimer->async_wait(
181 [createTimer, name, busPath, parameters, bus, address,
182 constructor, destructor, hasHWMonDir,
183 channelNames(std::move(channelNames)), retries,
184 &io](const boost::system::error_code& ec) mutable {
185 if (ec)
186 {
187 lg2::error("Timer error: {ERR}", "ERR", ec.message());
188 return -2;
189 }
190 return buildDevice(name, busPath, parameters, bus, address,
191 constructor, destructor, hasHWMonDir,
192 std::move(channelNames), io,
193 retries - 1);
194 });
195 return -1;
196 }
197 }
198
199 // Link the mux channels if needed once the device is created.
200 if (!channelNames.empty())
201 {
202 linkMux(name, bus, address, channelNames);
203 }
204
205 return 0;
206 }
207
exportDevice(const devices::ExportTemplate & exportTemplate,const nlohmann::json & configuration,boost::asio::io_context & io)208 void exportDevice(const devices::ExportTemplate& exportTemplate,
209 const nlohmann::json& configuration,
210 boost::asio::io_context& io)
211 {
212 std::string_view type = exportTemplate.type;
213 std::string parameters(exportTemplate.parameters);
214 std::string busPath(exportTemplate.busPath);
215 std::string_view constructor = exportTemplate.add;
216 std::string_view destructor = exportTemplate.remove;
217 devices::createsHWMon hasHWMonDir = exportTemplate.hasHWMonDir;
218 std::string name = "unknown";
219 std::optional<uint64_t> bus;
220 std::optional<uint64_t> address;
221 std::vector<std::string> channels;
222
223 for (auto keyPair = configuration.begin(); keyPair != configuration.end();
224 keyPair++)
225 {
226 std::string subsituteString;
227
228 if (keyPair.key() == "Name" &&
229 keyPair.value().type() == nlohmann::json::value_t::string)
230 {
231 subsituteString = std::regex_replace(
232 keyPair.value().get<std::string>(), illegalNameRegex, "_");
233 name = subsituteString;
234 }
235 else
236 {
237 subsituteString = jsonToString(keyPair.value());
238 }
239
240 if (keyPair.key() == "Bus")
241 {
242 bus = keyPair.value().get<uint64_t>();
243 }
244 else if (keyPair.key() == "Address")
245 {
246 address = keyPair.value().get<uint64_t>();
247 }
248 else if (keyPair.key() == "ChannelNames" && type.ends_with("Mux"))
249 {
250 channels = keyPair.value().get<std::vector<std::string>>();
251 }
252 replaceAll(parameters, templateChar + keyPair.key(), subsituteString);
253 replaceAll(busPath, templateChar + keyPair.key(), subsituteString);
254 }
255
256 if (!bus || !address)
257 {
258 createDevice(busPath, parameters, constructor);
259 return;
260 }
261
262 buildDevice(name, busPath, parameters, *bus, *address, constructor,
263 destructor, hasHWMonDir, std::move(channels), io);
264 }
265
loadOverlays(const nlohmann::json & systemConfiguration,boost::asio::io_context & io)266 bool loadOverlays(const nlohmann::json& systemConfiguration,
267 boost::asio::io_context& io)
268 {
269 lg2::debug("start loading device overlays");
270
271 std::filesystem::create_directory(outputDir);
272 for (auto entity = systemConfiguration.begin();
273 entity != systemConfiguration.end(); entity++)
274 {
275 auto findExposes = entity.value().find("Exposes");
276 if (findExposes == entity.value().end() ||
277 findExposes->type() != nlohmann::json::value_t::array)
278 {
279 continue;
280 }
281
282 for (const auto& configuration : *findExposes)
283 {
284 auto findStatus = configuration.find("Status");
285 // status missing is assumed to be 'okay'
286 if (findStatus != configuration.end() && *findStatus == "disabled")
287 {
288 continue;
289 }
290 auto findType = configuration.find("Type");
291 if (findType == configuration.end() ||
292 findType->type() != nlohmann::json::value_t::string)
293 {
294 continue;
295 }
296 const std::string& type = findType.value().get<std::string>();
297 const auto* device = std::ranges::find_if(
298 devices::exportTemplates,
299 [&type](const auto& tmp) { return tmp.type == type; });
300 if (device != devices::exportTemplates.end())
301 {
302 exportDevice(*device, configuration, io);
303 continue;
304 }
305
306 // Because many devices are intentionally not exportable,
307 // this error message is not printed in all situations.
308 // If wondering why your device not appearing, add your type to
309 // the exportTemplates array in the devices.hpp file.
310 lg2::debug("Device type {TYPE} not found in export map allowlist",
311 "TYPE", type);
312 }
313 }
314
315 lg2::debug("finish loading device overlays");
316
317 return true;
318 }
319