1 /**
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  */
16 #include "device_callouts.hpp"
17 
18 #include "paths.hpp"
19 
20 #include <fstream>
21 #include <phosphor-logging/log.hpp>
22 #include <regex>
23 
24 namespace openpower::pels::device_callouts
25 {
26 
27 constexpr auto debugFilePath = "/etc/phosphor-logging/";
28 constexpr auto calloutFileSuffix = "_dev_callouts.json";
29 
30 namespace fs = std::filesystem;
31 using namespace phosphor::logging;
32 
33 namespace util
34 {
35 
36 fs::path getJSONFilename(const std::vector<std::string>& compatibleList)
37 {
38     std::vector<std::string> names{compatibleList};
39     auto basePath = getPELReadOnlyDataPath();
40     fs::path fullPath;
41 
42     // Find an entry in the list of compatible system names that
43     // matches a filename we have.
44 
45     // Also match on just _dev_callouts.json, which may be present
46     // when it's known that compatibleList won't be correct.
47     names.push_back("");
48 
49     for (const auto& name : names)
50     {
51         fs::path filename = name + calloutFileSuffix;
52 
53         // Check the debug path first
54         fs::path path{fs::path{debugFilePath} / filename};
55 
56         if (fs::exists(path))
57         {
58             log<level::INFO>("Found device callout debug file");
59             fullPath = path;
60             break;
61         }
62 
63         path = basePath / filename;
64 
65         if (fs::exists(path))
66         {
67             fullPath = path;
68             break;
69         }
70     }
71 
72     if (fullPath.empty())
73     {
74         throw std::invalid_argument(
75             "No JSON dev path callout file for this system");
76     }
77 
78     return fullPath;
79 }
80 
81 /**
82  * @brief Reads the callout JSON into an object based on the
83  *        compatible system names list.
84  *
85  * @param[in] compatibleList - The list of compatible names for this
86  *                             system.
87  *
88  * @return nlohmann::json - The JSON object
89  */
90 nlohmann::json loadJSON(const std::vector<std::string>& compatibleList)
91 {
92     auto filename = getJSONFilename(compatibleList);
93     std::ifstream file{filename};
94     return nlohmann::json::parse(file);
95 }
96 
97 std::tuple<size_t, uint8_t> getI2CSearchKeys(const std::string& devPath)
98 {
99     std::smatch match;
100 
101     // Look for i2c-A/A-00BB
102     // where A = bus number and BB = address
103     std::regex regex{"i2c-[0-9]+/([0-9]+)-00([0-9a-f]{2})"};
104 
105     regex_search(devPath, match, regex);
106 
107     if (match.size() != 3)
108     {
109         std::string msg = "Could not get I2C bus and address from " + devPath;
110         throw std::invalid_argument{msg.c_str()};
111     }
112 
113     size_t bus = std::stoul(match[1].str(), nullptr, 0);
114 
115     // An I2C bus on a CFAM has everything greater than the 10s digit
116     // as the CFAM number, so strip it off.  Like:
117     //    112 = cfam1 bus 12
118     //    1001 = cfam10 bus 1
119     bus = bus % 100;
120 
121     uint8_t address = std::stoul(match[2].str(), nullptr, 16);
122 
123     return {bus, address};
124 }
125 
126 std::string getFSISearchKeys(const std::string& devPath)
127 {
128     std::string links;
129     std::smatch match;
130     auto search = devPath;
131 
132     // Look for slave@XX:
133     // where XX = link number in hex
134     std::regex regex{"slave@([0-9a-f]{2}):"};
135 
136     // Find all links in the path and separate them with hyphens.
137     while (regex_search(search, match, regex))
138     {
139         // Convert to an int first to handle a hex number like "0a"
140         // though in reality there won't be more than links 0 - 9.
141         auto linkNum = std::stoul(match[1].str(), nullptr, 16);
142         links += std::to_string(linkNum) + '-';
143 
144         search = match.suffix();
145     }
146 
147     if (links.empty())
148     {
149         std::string msg = "Could not get FSI links from " + devPath;
150         throw std::invalid_argument{msg.c_str()};
151     }
152 
153     // Remove the trailing '-'
154     links.pop_back();
155 
156     return links;
157 }
158 
159 std::tuple<std::string, std::tuple<size_t, uint8_t>>
160     getFSII2CSearchKeys(const std::string& devPath)
161 {
162     // This combines the FSI and i2C search keys
163 
164     auto links = getFSISearchKeys(devPath);
165     auto busAndAddr = getI2CSearchKeys(devPath);
166 
167     return {std::move(links), std::move(busAndAddr)};
168 }
169 
170 size_t getSPISearchKeys(const std::string& devPath)
171 {
172     std::smatch match;
173 
174     // Look for spi_master/spiX/ where X is the SPI bus/port number
175     // Note: This doesn't distinguish between multiple chips on
176     // the same port as no need for it yet.
177     std::regex regex{"spi_master/spi(\\d+)/"};
178 
179     regex_search(devPath, match, regex);
180 
181     if (match.size() != 2)
182     {
183         std::string msg = "Could not get SPI bus from " + devPath;
184         throw std::invalid_argument{msg.c_str()};
185     }
186 
187     size_t port = std::stoul(match[1].str());
188 
189     return port;
190 }
191 
192 std::tuple<std::string, size_t> getFSISPISearchKeys(const std::string& devPath)
193 {
194 
195     // Combine the FSI and SPI search keys.
196     auto links = getFSISearchKeys(devPath);
197     auto bus = getSPISearchKeys(devPath);
198 
199     return {std::move(links), std::move(bus)};
200 }
201 
202 /**
203  * @brief Pull the callouts out of the JSON callout array passed in
204  *
205  * Create a vector of Callout objects based on the JSON.
206  *
207  * This will also fill in the 'debug' member on the first callout
208  * in the list, which could contain things like the I2C address and
209  * bus extracted from the device path.
210  *
211  * The callouts are in the order they should be added to the PEL.
212  *
213  * @param[in] calloutJSON - The Callouts JSON array to extract from
214  * @param[in] debug - The debug message to add to the first callout
215  *
216  * @return std::vector<Callout> - The Callout objects
217  */
218 std::vector<Callout> extractCallouts(const nlohmann::json& calloutJSON,
219                                      const std::string& debug)
220 {
221     std::vector<Callout> callouts;
222     bool addDebug = true;
223 
224     // The JSON element passed in is the array of callouts
225     if (!calloutJSON.is_array())
226     {
227         throw std::runtime_error(
228             "Dev path callout JSON entry doesn't contain a 'Callouts' array");
229     }
230 
231     for (auto& callout : calloutJSON)
232     {
233         Callout c;
234 
235         // Add any debug data to the first callout
236         if (addDebug && !debug.empty())
237         {
238             addDebug = false;
239             c.debug = debug;
240         }
241 
242         try
243         {
244             c.locationCode = callout.at("LocationCode").get<std::string>();
245             c.name = callout.at("Name").get<std::string>();
246             c.priority = callout.at("Priority").get<std::string>();
247 
248             if (callout.contains("MRU"))
249             {
250                 c.mru = callout.at("MRU").get<std::string>();
251             }
252         }
253         catch (const nlohmann::json::out_of_range& e)
254         {
255             std::string msg =
256                 "Callout entry missing either LocationCode, Name, or Priority "
257                 "properties: " +
258                 callout.dump();
259             throw std::runtime_error(msg.c_str());
260         }
261 
262         callouts.push_back(c);
263     }
264 
265     return callouts;
266 }
267 
268 /**
269  * @brief Looks up the callouts in the JSON using the I2C keys.
270  *
271  * @param[in] i2cBus - The I2C bus
272  * @param[in] i2cAddress - The I2C address
273  * @param[in] calloutJSON - The JSON containing the callouts
274  *
275  * @return std::vector<Callout> - The callouts
276  */
277 std::vector<device_callouts::Callout>
278     calloutI2C(size_t i2cBus, uint8_t i2cAddress,
279                const nlohmann::json& calloutJSON)
280 {
281     auto busString = std::to_string(i2cBus);
282     auto addrString = std::to_string(i2cAddress);
283 
284     try
285     {
286         const auto& callouts =
287             calloutJSON.at("I2C").at(busString).at(addrString).at("Callouts");
288 
289         auto dest = calloutJSON.at("I2C")
290                         .at(busString)
291                         .at(addrString)
292                         .at("Dest")
293                         .get<std::string>();
294 
295         std::string msg = "I2C: bus: " + busString + " address: " + addrString +
296                           " dest: " + dest;
297 
298         return extractCallouts(callouts, msg);
299     }
300     catch (const nlohmann::json::out_of_range& e)
301     {
302         std::string msg = "Problem looking up I2C callouts on " + busString +
303                           " " + addrString + ": " + std::string{e.what()};
304         throw std::invalid_argument(msg.c_str());
305     }
306 }
307 
308 /**
309  * @brief Looks up the callouts in the JSON for this I2C path.
310  *
311  * @param[in] devPath - The device path
312  * @param[in] calloutJSON - The JSON containing the callouts
313  *
314  * @return std::vector<Callout> - The callouts
315  */
316 std::vector<device_callouts::Callout>
317     calloutI2CUsingPath(const std::string& devPath,
318                         const nlohmann::json& calloutJSON)
319 {
320     auto [bus, address] = getI2CSearchKeys(devPath);
321 
322     return calloutI2C(bus, address, calloutJSON);
323 }
324 
325 /**
326  * @brief Looks up the callouts in the JSON for this FSI path.
327  *
328  * @param[in] devPath - The device path
329  * @param[in] calloutJSON - The JSON containing the callouts
330  *
331  * @return std::vector<Callout> - The callouts
332  */
333 std::vector<device_callouts::Callout>
334     calloutFSI(const std::string& devPath, const nlohmann::json& calloutJSON)
335 {
336     auto links = getFSISearchKeys(devPath);
337 
338     try
339     {
340         const auto& callouts = calloutJSON.at("FSI").at(links).at("Callouts");
341 
342         auto dest =
343             calloutJSON.at("FSI").at(links).at("Dest").get<std::string>();
344 
345         std::string msg = "FSI: links: " + links + " dest: " + dest;
346 
347         return extractCallouts(callouts, msg);
348     }
349     catch (const nlohmann::json::out_of_range& e)
350     {
351         std::string msg = "Problem looking up FSI callouts on " + links + ": " +
352                           std::string{e.what()};
353         throw std::invalid_argument(msg.c_str());
354     }
355 }
356 
357 /**
358  * @brief Looks up the callouts in the JSON for this FSI-I2C path.
359  *
360  * @param[in] devPath - The device path
361  * @param[in] calloutJSON - The JSON containing the callouts
362  *
363  * @return std::vector<Callout> - The callouts
364  */
365 std::vector<device_callouts::Callout>
366     calloutFSII2C(const std::string& devPath, const nlohmann::json& calloutJSON)
367 {
368     auto linksAndI2C = getFSII2CSearchKeys(devPath);
369     auto links = std::get<std::string>(linksAndI2C);
370     const auto& busAndAddr = std::get<1>(linksAndI2C);
371 
372     auto busString = std::to_string(std::get<size_t>(busAndAddr));
373     auto addrString = std::to_string(std::get<uint8_t>(busAndAddr));
374 
375     try
376     {
377         auto& callouts = calloutJSON.at("FSI-I2C")
378                              .at(links)
379                              .at(busString)
380                              .at(addrString)
381                              .at("Callouts");
382 
383         auto dest = calloutJSON.at("FSI-I2C")
384                         .at(links)
385                         .at(busString)
386                         .at(addrString)
387                         .at("Dest")
388                         .get<std::string>();
389 
390         std::string msg = "FSI-I2C: links: " + links + " bus: " + busString +
391                           " addr: " + addrString + " dest: " + dest;
392 
393         return extractCallouts(callouts, msg);
394     }
395     catch (const nlohmann::json::out_of_range& e)
396     {
397         std::string msg = "Problem looking up FSI-I2C callouts on " + links +
398                           " " + busString + " " + addrString + ": " + e.what();
399         throw std::invalid_argument(msg.c_str());
400     }
401 }
402 
403 /**
404  * @brief Looks up the callouts in the JSON for this FSI-SPI path.
405  *
406  * @param[in] devPath - The device path
407  * @param[in] calloutJSON - The JSON containing the callouts
408  *
409  * @return std::vector<Callout> - The callouts
410  */
411 std::vector<device_callouts::Callout>
412     calloutFSISPI(const std::string& devPath, const nlohmann::json& calloutJSON)
413 {
414     auto linksAndSPI = getFSISPISearchKeys(devPath);
415     auto links = std::get<std::string>(linksAndSPI);
416     auto busString = std::to_string(std::get<size_t>(linksAndSPI));
417 
418     try
419     {
420         auto& callouts =
421             calloutJSON.at("FSI-SPI").at(links).at(busString).at("Callouts");
422 
423         auto dest = calloutJSON.at("FSI-SPI")
424                         .at(links)
425                         .at(busString)
426                         .at("Dest")
427                         .get<std::string>();
428 
429         std::string msg = "FSI-SPI: links: " + links + " bus: " + busString +
430                           " dest: " + dest;
431 
432         return extractCallouts(callouts, msg);
433     }
434     catch (const nlohmann::json::out_of_range& e)
435     {
436         std::string msg = "Problem looking up FSI-SPI callouts on " + links +
437                           " " + busString + ": " + std::string{e.what()};
438         throw std::invalid_argument(msg.c_str());
439     }
440 }
441 
442 /**
443  * @brief Returns the callouts from the JSON based on the input
444  *        device path.
445  *
446  * @param[in] devPath - The device path
447  * @param[in] json - The callout JSON
448  *
449  * @return std::vector<Callout> - The list of callouts
450  */
451 std::vector<device_callouts::Callout> findCallouts(const std::string& devPath,
452                                                    const nlohmann::json& json)
453 {
454     std::vector<Callout> callouts;
455     fs::path path;
456 
457     // Gives the /sys/devices/platform/ path
458     try
459     {
460         path = fs::canonical(devPath);
461     }
462     catch (const fs::filesystem_error& e)
463     {
464         // Path not there, still try to do the callout
465         path = devPath;
466     }
467 
468     switch (util::getCalloutType(path))
469     {
470         case util::CalloutType::i2c:
471             callouts = calloutI2CUsingPath(path, json);
472             break;
473         case util::CalloutType::fsi:
474             callouts = calloutFSI(path, json);
475             break;
476         case util::CalloutType::fsii2c:
477             callouts = calloutFSII2C(path, json);
478             break;
479         case util::CalloutType::fsispi:
480             callouts = calloutFSISPI(path, json);
481             break;
482         default:
483             std::string msg =
484                 "Could not get callout type from device path: " + path.string();
485             throw std::invalid_argument{msg.c_str()};
486             break;
487     }
488 
489     return callouts;
490 }
491 
492 CalloutType getCalloutType(const std::string& devPath)
493 {
494     if ((devPath.find("fsi-master") != std::string::npos) &&
495         (devPath.find("i2c-") != std::string::npos))
496     {
497         return CalloutType::fsii2c;
498     }
499 
500     if ((devPath.find("fsi-master") != std::string::npos) &&
501         (devPath.find("spi") != std::string::npos))
502     {
503         return CalloutType::fsispi;
504     }
505 
506     // Treat anything else FSI related as plain FSI
507     if (devPath.find("fsi-master") != std::string::npos)
508     {
509         return CalloutType::fsi;
510     }
511 
512     if (devPath.find("i2c-bus/i2c-") != std::string::npos)
513     {
514         return CalloutType::i2c;
515     }
516 
517     return CalloutType::unknown;
518 }
519 
520 } // namespace util
521 
522 std::vector<Callout> getCallouts(const std::string& devPath,
523                                  const std::vector<std::string>& compatibleList)
524 {
525     auto json = util::loadJSON(compatibleList);
526     return util::findCallouts(devPath, json);
527 }
528 
529 std::vector<Callout>
530     getI2CCallouts(size_t i2cBus, uint8_t i2cAddress,
531                    const std::vector<std::string>& compatibleList)
532 {
533     auto json = util::loadJSON(compatibleList);
534     return util::calloutI2C(i2cBus, i2cAddress, json);
535 }
536 
537 } // namespace openpower::pels::device_callouts
538