blob: cb268a9f55143ad4792f53a7f4166467e99de450 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2018 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 <Utils.hpp>
18#include <boost/container/flat_map.hpp>
19#include <ctime>
20#include <dbus/connection.hpp>
21#include <dbus/endpoint.hpp>
22#include <dbus/message.hpp>
23#include <dbus/properties.hpp>
24#include <fcntl.h>
25#include <fstream>
26#include <future>
James Feistb5320a72018-01-24 12:28:12 -080027#include <linux/i2c-dev-user.h>
James Feist3cb5fec2018-01-23 14:41:51 -080028#include <iostream>
29#include <sys/ioctl.h>
James Feist3f8a2782018-02-12 09:24:42 -080030#include <regex>
James Feist4131aea2018-03-09 09:47:30 -080031#include <sys/inotify.h>
James Feist3cb5fec2018-01-23 14:41:51 -080032
33namespace fs = std::experimental::filesystem;
34static constexpr bool DEBUG = false;
35static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
36
37const static constexpr char *BASEBOARD_FRU_LOCATION =
38 "/etc/fru/baseboard.fru.bin";
39
James Feist4131aea2018-03-09 09:47:30 -080040const static constexpr char *I2C_DEV_LOCATION = "/dev";
41
James Feist3cb5fec2018-01-23 14:41:51 -080042static constexpr std::array<const char *, 5> FRU_AREAS = {
43 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
James Feist918e18c2018-02-13 15:51:07 -080044const static constexpr char *POWER_OBJECT_NAME = "/org/openbmc/control/power0";
James Feist3cb5fec2018-01-23 14:41:51 -080045using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
46using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
47
James Feistc95cb142018-02-26 10:41:42 -080048static bool isMuxBus(size_t bus)
49{
50 return is_symlink(std::experimental::filesystem::path(
51 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
52}
53
James Feist3cb5fec2018-01-23 14:41:51 -080054int get_bus_frus(int file, int first, int last, int bus,
55 std::shared_ptr<DeviceMap> devices)
56{
57 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> block_data;
58
59 for (int ii = first; ii <= last; ii++)
60 {
61 // Set slave address
62 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
63 {
64 std::cerr << "device at bus " << bus << "register " << ii
65 << "busy\n";
66 continue;
67 }
68 // probe
69 else if (i2c_smbus_read_byte(file) < 0)
70 {
71 continue;
72 }
73
74 if (DEBUG)
75 {
76 std::cout << "something at bus " << bus << "addr " << ii << "\n";
77 }
78 if (i2c_smbus_read_i2c_block_data(file, 0x0, 0x8, block_data.data()) <
79 0)
80 {
81 std::cerr << "failed to read bus " << bus << " address " << ii
82 << "\n";
83 continue;
84 }
85 size_t sum = 0;
86 for (int jj = 0; jj < 7; jj++)
87 {
88 sum += block_data[jj];
89 }
90 sum = (256 - sum) & 0xFF;
91
92 // check the header checksum
93 if (sum == block_data[7])
94 {
95 std::vector<char> device;
96 device.insert(device.end(), block_data.begin(),
97 block_data.begin() + 8);
98
99 for (int jj = 1; jj <= FRU_AREAS.size(); jj++)
100 {
101 auto area_offset = device[jj];
102 if (area_offset != 0)
103 {
104 area_offset *= 8;
105 if (i2c_smbus_read_i2c_block_data(file, area_offset, 0x8,
106 block_data.data()) < 0)
107 {
108 std::cerr << "failed to read bus " << bus << " address "
109 << ii << "\n";
110 return -1;
111 }
112 int length = block_data[1] * 8;
113 device.insert(device.end(), block_data.begin(),
114 block_data.begin() + 8);
115 length -= 8;
116 area_offset += 8;
117
118 while (length > 0)
119 {
120 auto to_get = std::min(0x20, length);
121 if (i2c_smbus_read_i2c_block_data(
122 file, area_offset, to_get, block_data.data()) <
123 0)
124 {
125 std::cerr << "failed to read bus " << bus
126 << " address " << ii << "\n";
127 return -1;
128 }
129 device.insert(device.end(), block_data.begin(),
130 block_data.begin() + to_get);
131 area_offset += to_get;
132 length -= to_get;
133 }
134 }
135 }
136 (*devices).emplace(ii, device);
137 }
138 }
139
140 return 0;
141}
142
143static BusMap FindI2CDevices(const std::vector<fs::path> &i2cBuses)
144{
James Feist918e18c2018-02-13 15:51:07 -0800145 std::vector<std::future<void>> futures;
James Feist3cb5fec2018-01-23 14:41:51 -0800146 BusMap busMap;
147 for (auto &i2cBus : i2cBuses)
148 {
149 auto busnum = i2cBus.string();
150 auto lastDash = busnum.rfind(std::string("-"));
151 // delete everything before dash inclusive
152 if (lastDash != std::string::npos)
153 {
154 busnum.erase(0, lastDash + 1);
155 }
156 auto bus = std::stoi(busnum);
157
158 auto file = open(i2cBus.c_str(), O_RDWR);
159 if (file < 0)
160 {
161 std::cerr << "unable to open i2c device " << i2cBus.string()
162 << "\n";
163 continue;
164 }
165 unsigned long funcs = 0;
166
167 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
168 {
169 std::cerr
170 << "Error: Could not get the adapter functionality matrix bus"
171 << bus << "\n";
172 continue;
173 }
174 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
175 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
176 {
177 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
178 << bus << "\n";
179 continue;
180 }
181 auto &device = busMap[bus];
182 device = std::make_shared<DeviceMap>();
183
James Feistc95cb142018-02-26 10:41:42 -0800184 // don't scan muxed buses async as don't want to confuse the mux
185 if (isMuxBus(bus))
186 {
187 get_bus_frus(file, 0x03, 0x77, bus, device);
188 close(file);
189 }
190 else
191 {
192 // todo: call with boost asio?
193 futures.emplace_back(
194 std::async(std::launch::async, [file, device, bus] {
195 // i2cdetect by default uses the range 0x03 to 0x77, as
196 // this is
197 // what we
198 // have tested with, use this range. Could be changed in
199 // future.
200 get_bus_frus(file, 0x03, 0x77, bus, device);
201 close(file);
202 }));
203 }
James Feist3cb5fec2018-01-23 14:41:51 -0800204 }
205 for (auto &fut : futures)
206 {
207 fut.get(); // wait for all scans
208 }
209 return busMap;
210}
211
212static const std::tm intelEpoch(void)
213{
214 std::tm val = {0};
215 val.tm_year = 1996 - 1900;
216 return val;
217}
218
219bool formatFru(const std::vector<char> &fruBytes,
220 boost::container::flat_map<std::string, std::string> &result)
221{
222 static const std::vector<const char *> CHASSIS_FRU_AREAS = {
223 "PART_NUMBER", "SERIAL_NUMBER", "CHASSIS_INFO_AM1", "CHASSIS_INFO_AM2"};
224
225 static const std::vector<const char *> BOARD_FRU_AREAS = {
226 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
227 "VERSION_ID"};
228
229 static const std::vector<const char *> PRODUCT_FRU_AREAS = {
230 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
231 "PRODUCT_VERSION", "PRODUCT_SERIAL_NUMBER", "ASSET_TAG"};
232
233 size_t sum = 0;
234
235 if (fruBytes.size() < 8)
236 {
237 return false;
238 }
239 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
240 result["Common Format Version"] =
241 std::to_string(static_cast<int>(*fruAreaOffsetField));
242
243 const std::vector<const char *> *fieldData;
244
245 for (auto &area : FRU_AREAS)
246 {
247 fruAreaOffsetField++;
248 if (fruAreaOffsetField >= fruBytes.end())
249 {
250 return false;
251 }
252 size_t offset = (*fruAreaOffsetField) * 8;
253
254 if (offset > 1)
255 {
256 // +2 to skip format and length
257 std::vector<char>::const_iterator fruBytesIter =
258 fruBytes.begin() + offset + 2;
259
260 if (fruBytesIter >= fruBytes.end())
261 {
262 return false;
263 }
264
265 if (area == "CHASSIS")
266 {
267 result["CHASSIS_TYPE"] =
268 std::to_string(static_cast<int>(*fruBytesIter));
269 fruBytesIter += 1;
270 fieldData = &CHASSIS_FRU_AREAS;
271 }
272 else if (area == "BOARD")
273 {
274 result["BOARD_LANGUAGE_CODE"] =
275 std::to_string(static_cast<int>(*fruBytesIter));
276 fruBytesIter += 1;
277 if (fruBytesIter >= fruBytes.end())
278 {
279 return false;
280 }
281
282 unsigned int minutes = *fruBytesIter |
283 *(fruBytesIter + 1) << 8 |
284 *(fruBytesIter + 2) << 16;
285 std::tm fruTime = intelEpoch();
286 time_t timeValue = mktime(&fruTime);
287 timeValue += minutes * 60;
288 fruTime = *gmtime(&timeValue);
289
290 result["BOARD_MANUFACTURE_DATE"] = asctime(&fruTime);
291 result["BOARD_MANUFACTURE_DATE"]
292 .pop_back(); // remove trailing null
293 fruBytesIter += 3;
294 fieldData = &BOARD_FRU_AREAS;
295 }
296 else if (area == "PRODUCT")
297 {
298 result["PRODUCT_LANGUAGE_CODE"] =
299 std::to_string(static_cast<int>(*fruBytesIter));
300 fruBytesIter += 1;
301 fieldData = &PRODUCT_FRU_AREAS;
302 }
303 else
304 {
305 continue;
306 }
307 for (auto &field : *fieldData)
308 {
309 if (fruBytesIter >= fruBytes.end())
310 {
311 return false;
312 }
313
314 size_t length = *fruBytesIter & 0x3f;
315 fruBytesIter += 1;
316
317 if (fruBytesIter >= fruBytes.end())
318 {
319 return false;
320 }
321
322 result[std::string(area) + "_" + field] =
323 std::string(fruBytesIter, fruBytesIter + length);
324 fruBytesIter += length;
325 if (fruBytesIter >= fruBytes.end())
326 {
327 std::cerr << "Warning Fru Length Mismatch:\n ";
328 for (auto &c : fruBytes)
329 {
330 std::cerr << c;
331 }
332 std::cerr << "\n";
333 if (DEBUG)
334 {
335 for (auto &keyPair : result)
336 {
337 std::cerr << keyPair.first << " : "
338 << keyPair.second << "\n";
339 }
340 }
341 return false;
342 }
343 }
344 }
345 }
346
347 return true;
348}
349
350void AddFruObjectToDbus(
351 std::shared_ptr<dbus::connection> dbusConn, std::vector<char> &device,
352 dbus::DbusObjectServer &objServer,
353 boost::container::flat_map<std::pair<size_t, size_t>,
354 std::shared_ptr<dbus::DbusObject>>
355 &dbusObjectMap,
356 int bus, size_t address)
357{
358 boost::container::flat_map<std::string, std::string> formattedFru;
359 if (!formatFru(device, formattedFru))
360 {
361 std::cerr << "failed to format fru for device at bus " << std::hex
362 << bus << "address " << address << "\n";
363 return;
364 }
365 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
366 std::string productName;
367 if (productNameFind == formattedFru.end())
368 {
369 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
370 }
371 if (productNameFind != formattedFru.end())
372 {
373 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800374 std::regex illegalObject("[^A-Za-z0-9_]");
375 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800376 }
377 else
378 {
379 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
380 UNKNOWN_BUS_OBJECT_COUNT++;
381 }
382
James Feist918e18c2018-02-13 15:51:07 -0800383 productName = "/xyz/openbmc_project/FruDevice/" + productName;
384
385 // avoid duplicates by checking to see if on a mux
386 if (bus > 0 && isMuxBus(bus))
387 {
388 for (auto const &busObj : dbusObjectMap)
389 {
390 if ((address == busObj.first.second) &&
391 (busObj.second->object_name == productName))
392 {
393 continue;
394 }
395 }
396 }
397 auto object = objServer.add_object(productName);
James Feist3cb5fec2018-01-23 14:41:51 -0800398 dbusObjectMap[std::pair<size_t, size_t>(bus, address)] = object;
399
400 auto iface = std::make_shared<dbus::DbusInterface>(
401 "xyz.openbmc_project.FruDevice", dbusConn);
402 object->register_interface(iface);
403 for (auto &property : formattedFru)
404 {
405 iface->set_property(property.first, property.second);
406 }
407 // baseboard can set this to -1 to not set a bus / address
408 if (bus > 0)
409 {
410 std::stringstream data;
411 data << "0x" << std::hex << bus;
412 iface->set_property("BUS", data.str());
413 data.str("");
414 data << "0x" << std::hex << address;
415 iface->set_property("ADDRESS", data.str());
416 }
417}
418
419static bool readBaseboardFru(std::vector<char> &baseboardFru)
420{
421 // try to read baseboard fru from file
422 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
423 if (baseboardFruFile.good())
424 {
425 baseboardFruFile.seekg(0, std::ios_base::end);
426 std::streampos fileSize = baseboardFruFile.tellg();
427 baseboardFru.resize(fileSize);
428 baseboardFruFile.seekg(0, std::ios_base::beg);
429 baseboardFruFile.read(baseboardFru.data(), fileSize);
430 }
431 else
432 {
433 return false;
434 }
435 return true;
436}
437
James Feist918e18c2018-02-13 15:51:07 -0800438void rescanBusses(boost::container::flat_map<std::pair<size_t, size_t>,
439 std::shared_ptr<dbus::DbusObject>>
440 &dbusObjectMap,
441 std::shared_ptr<dbus::connection> systemBus,
James Feist4131aea2018-03-09 09:47:30 -0800442 dbus::DbusObjectServer &objServer,
443 std::atomic_bool &pendingCallback)
James Feist918e18c2018-02-13 15:51:07 -0800444{
James Feist918e18c2018-02-13 15:51:07 -0800445
James Feist4131aea2018-03-09 09:47:30 -0800446 do
James Feist918e18c2018-02-13 15:51:07 -0800447 {
James Feist4131aea2018-03-09 09:47:30 -0800448 auto devDir = fs::path("/dev/");
449 auto matchString = std::string("i2c*");
450 std::vector<fs::path> i2cBuses;
451 pendingCallback = false;
James Feist918e18c2018-02-13 15:51:07 -0800452
James Feist4131aea2018-03-09 09:47:30 -0800453 if (!find_files(devDir, matchString, i2cBuses, 0))
James Feist918e18c2018-02-13 15:51:07 -0800454 {
James Feist4131aea2018-03-09 09:47:30 -0800455 std::cerr << "unable to find i2c devices\n";
456 return;
James Feist918e18c2018-02-13 15:51:07 -0800457 }
James Feist4131aea2018-03-09 09:47:30 -0800458 // scanning muxes in reverse order seems to have adverse effects
459 // sorting this list seems to be a fix for that
460 std::sort(i2cBuses.begin(), i2cBuses.end());
461 BusMap busMap = FindI2CDevices(i2cBuses);
462
463 for (auto &busObj : dbusObjectMap)
464 {
465 objServer.remove_object(busObj.second);
466 }
467
468 dbusObjectMap.clear();
469 UNKNOWN_BUS_OBJECT_COUNT = 0;
470
471 for (auto &devicemap : busMap)
472 {
473 for (auto &device : *devicemap.second)
474 {
475 AddFruObjectToDbus(systemBus, device.second, objServer,
476 dbusObjectMap, devicemap.first,
477 device.first);
478 }
479 }
480 // todo, get this from a more sensable place
481 std::vector<char> baseboardFru;
482 if (readBaseboardFru(baseboardFru))
483 {
484 AddFruObjectToDbus(systemBus, baseboardFru, objServer,
485 dbusObjectMap, -1, -1);
486 }
487 } while (pendingCallback);
James Feist918e18c2018-02-13 15:51:07 -0800488}
489
James Feist3cb5fec2018-01-23 14:41:51 -0800490int main(int argc, char **argv)
491{
492 auto devDir = fs::path("/dev/");
493 auto matchString = std::string("i2c*");
494 std::vector<fs::path> i2cBuses;
495
496 if (!find_files(devDir, matchString, i2cBuses, 0))
497 {
498 std::cerr << "unable to find i2c devices\n";
499 return 1;
500 }
James Feist3cb5fec2018-01-23 14:41:51 -0800501
502 boost::asio::io_service io;
503 auto systemBus = std::make_shared<dbus::connection>(io, dbus::bus::system);
504 dbus::DbusObjectServer objServer(systemBus);
505 systemBus->request_name("com.intel.FruDevice");
506
507 // this is a map with keys of pair(bus number, adddress) and values of the
508 // object on dbus
509 boost::container::flat_map<std::pair<size_t, size_t>,
510 std::shared_ptr<dbus::DbusObject>>
511 dbusObjectMap;
512
James Feist3cb5fec2018-01-23 14:41:51 -0800513 auto iface = std::make_shared<dbus::DbusInterface>(
514 "xyz.openbmc_project.FruDeviceManager", systemBus);
James Feist3cb5fec2018-01-23 14:41:51 -0800515
James Feist918e18c2018-02-13 15:51:07 -0800516 std::atomic_bool threadRunning(false);
James Feist4131aea2018-03-09 09:47:30 -0800517 std::atomic_bool pendingCallback(false);
James Feist918e18c2018-02-13 15:51:07 -0800518 std::future<void> future;
519
James Feist3cb5fec2018-01-23 14:41:51 -0800520 iface->register_method("ReScan", [&]() {
James Feist4131aea2018-03-09 09:47:30 -0800521 bool notRunning = false;
522 if (threadRunning.compare_exchange_strong(notRunning, true))
James Feist3cb5fec2018-01-23 14:41:51 -0800523 {
James Feist918e18c2018-02-13 15:51:07 -0800524 future = std::async(std::launch::async, [&] {
James Feist4131aea2018-03-09 09:47:30 -0800525 rescanBusses(dbusObjectMap, systemBus, objServer,
526 pendingCallback);
James Feist918e18c2018-02-13 15:51:07 -0800527 threadRunning = false;
528 });
James Feist3cb5fec2018-01-23 14:41:51 -0800529 }
James Feist4131aea2018-03-09 09:47:30 -0800530 else
531 {
532 pendingCallback = true;
533 }
James Feist3cb5fec2018-01-23 14:41:51 -0800534 return std::tuple<>(); // this is a bug in boost-dbus, needs some sort
535 // of return
536 });
537
James Feist918e18c2018-02-13 15:51:07 -0800538 dbus::match powerChange(systemBus,
539 "type='signal',path_namespace='" +
540 std::string(POWER_OBJECT_NAME) + "'");
541
542 dbus::filter filter(systemBus, [](dbus::message &m) {
543 auto member = m.get_member();
544 return member == "PropertiesChanged";
545 });
546 std::function<void(boost::system::error_code, dbus::message)> eventHandler =
547 [&](boost::system::error_code ec, dbus::message s) {
548 boost::container::flat_map<std::string, dbus::dbus_variant> values;
549 std::string objectName;
550 s.unpack(objectName, values);
551 auto findPgood = values.find("pgood");
552 if (findPgood != values.end())
553 {
James Feist4131aea2018-03-09 09:47:30 -0800554 bool notRunning = false;
555 if (threadRunning.compare_exchange_strong(notRunning, true))
James Feist918e18c2018-02-13 15:51:07 -0800556 {
James Feist918e18c2018-02-13 15:51:07 -0800557 future = std::async(std::launch::async, [&] {
James Feist4131aea2018-03-09 09:47:30 -0800558 rescanBusses(dbusObjectMap, systemBus, objServer,
559 pendingCallback);
James Feist918e18c2018-02-13 15:51:07 -0800560 threadRunning = false;
561 });
562 }
James Feist4131aea2018-03-09 09:47:30 -0800563 else
564 {
565 pendingCallback = true;
566 }
James Feist918e18c2018-02-13 15:51:07 -0800567 }
568 filter.async_dispatch(eventHandler);
569
570 };
571 filter.async_dispatch(eventHandler);
James Feist4131aea2018-03-09 09:47:30 -0800572 int fd = inotify_init();
573 int wd = inotify_add_watch(fd, I2C_DEV_LOCATION,
574 IN_CREATE | IN_MOVED_TO | IN_DELETE);
575 std::array<char, 4096> readBuffer;
576 std::string pendingBuffer;
577 // monitor for new i2c devices
578 boost::asio::posix::stream_descriptor dirWatch(io, fd);
579 std::function<void(const boost::system::error_code, std::size_t)>
580 watchI2cBusses = [&](const boost::system::error_code &ec,
581 std::size_t bytes_transferred) {
582 if (ec)
583 {
584 std::cout << "Callback Error " << ec << "\n";
585 return;
586 }
587 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
588 bool devChange = false;
589 while (pendingBuffer.size() > sizeof(inotify_event))
590 {
591 const inotify_event *iEvent =
592 reinterpret_cast<const inotify_event *>(
593 pendingBuffer.data());
594 switch (iEvent->mask)
595 {
596 case IN_CREATE:
597 case IN_MOVED_TO:
598 case IN_DELETE:
599 if (boost::starts_with(std::string(iEvent->name), "i2c"))
600 {
601 devChange = true;
602 }
603 }
604
605 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
606 }
607 bool notRunning = false;
608 if (devChange &&
609 threadRunning.compare_exchange_strong(notRunning, true))
610 {
611 future = std::async(std::launch::async, [&] {
612 std::this_thread::sleep_for(std::chrono::seconds(2));
613 rescanBusses(dbusObjectMap, systemBus, objServer,
614 pendingCallback);
615 threadRunning = false;
616 });
617 }
618 else if (devChange)
619 {
620 pendingCallback = true;
621 }
622 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
623 watchI2cBusses);
624 };
625
626 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
627
628 // run the intial scan
629 rescanBusses(dbusObjectMap, systemBus, objServer, pendingCallback);
630
631 auto object = std::make_shared<dbus::DbusObject>(
632 systemBus, "/xyz/openbmc_project/FruDevice");
633 objServer.register_object(object);
634 object->register_interface(iface);
James Feist918e18c2018-02-13 15:51:07 -0800635
James Feist3cb5fec2018-01-23 14:41:51 -0800636 io.run();
637 return 0;
638}