blob: 7272327d6b5ba4b795ff373d5bbc368ffbba7fcf [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 Feist3cb5fec2018-01-23 14:41:51 -080031
32namespace fs = std::experimental::filesystem;
33static constexpr bool DEBUG = false;
34static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
35
36const static constexpr char *BASEBOARD_FRU_LOCATION =
37 "/etc/fru/baseboard.fru.bin";
38
39static constexpr std::array<const char *, 5> FRU_AREAS = {
40 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
41
42using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
43using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
44
45int get_bus_frus(int file, int first, int last, int bus,
46 std::shared_ptr<DeviceMap> devices)
47{
48 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> block_data;
49
50 for (int ii = first; ii <= last; ii++)
51 {
52 // Set slave address
53 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
54 {
55 std::cerr << "device at bus " << bus << "register " << ii
56 << "busy\n";
57 continue;
58 }
59 // probe
60 else if (i2c_smbus_read_byte(file) < 0)
61 {
62 continue;
63 }
64
65 if (DEBUG)
66 {
67 std::cout << "something at bus " << bus << "addr " << ii << "\n";
68 }
69 if (i2c_smbus_read_i2c_block_data(file, 0x0, 0x8, block_data.data()) <
70 0)
71 {
72 std::cerr << "failed to read bus " << bus << " address " << ii
73 << "\n";
74 continue;
75 }
76 size_t sum = 0;
77 for (int jj = 0; jj < 7; jj++)
78 {
79 sum += block_data[jj];
80 }
81 sum = (256 - sum) & 0xFF;
82
83 // check the header checksum
84 if (sum == block_data[7])
85 {
86 std::vector<char> device;
87 device.insert(device.end(), block_data.begin(),
88 block_data.begin() + 8);
89
90 for (int jj = 1; jj <= FRU_AREAS.size(); jj++)
91 {
92 auto area_offset = device[jj];
93 if (area_offset != 0)
94 {
95 area_offset *= 8;
96 if (i2c_smbus_read_i2c_block_data(file, area_offset, 0x8,
97 block_data.data()) < 0)
98 {
99 std::cerr << "failed to read bus " << bus << " address "
100 << ii << "\n";
101 return -1;
102 }
103 int length = block_data[1] * 8;
104 device.insert(device.end(), block_data.begin(),
105 block_data.begin() + 8);
106 length -= 8;
107 area_offset += 8;
108
109 while (length > 0)
110 {
111 auto to_get = std::min(0x20, length);
112 if (i2c_smbus_read_i2c_block_data(
113 file, area_offset, to_get, block_data.data()) <
114 0)
115 {
116 std::cerr << "failed to read bus " << bus
117 << " address " << ii << "\n";
118 return -1;
119 }
120 device.insert(device.end(), block_data.begin(),
121 block_data.begin() + to_get);
122 area_offset += to_get;
123 length -= to_get;
124 }
125 }
126 }
127 (*devices).emplace(ii, device);
128 }
129 }
130
131 return 0;
132}
133
134static BusMap FindI2CDevices(const std::vector<fs::path> &i2cBuses)
135{
136 static std::vector<std::future<void>> futures;
137 BusMap busMap;
138 for (auto &i2cBus : i2cBuses)
139 {
140 auto busnum = i2cBus.string();
141 auto lastDash = busnum.rfind(std::string("-"));
142 // delete everything before dash inclusive
143 if (lastDash != std::string::npos)
144 {
145 busnum.erase(0, lastDash + 1);
146 }
147 auto bus = std::stoi(busnum);
148
149 auto file = open(i2cBus.c_str(), O_RDWR);
150 if (file < 0)
151 {
152 std::cerr << "unable to open i2c device " << i2cBus.string()
153 << "\n";
154 continue;
155 }
156 unsigned long funcs = 0;
157
158 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
159 {
160 std::cerr
161 << "Error: Could not get the adapter functionality matrix bus"
162 << bus << "\n";
163 continue;
164 }
165 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
166 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
167 {
168 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
169 << bus << "\n";
170 continue;
171 }
172 auto &device = busMap[bus];
173 device = std::make_shared<DeviceMap>();
174
175 // todo: call with boost asio?
176 futures.emplace_back(
177 std::async(std::launch::async, [file, device, bus] {
178 // i2cdetect by default uses the range 0x03 to 0x77, as this is
179 // what we
180 // have tested with, use this range. Could be changed in
181 // future.
182 get_bus_frus(file, 0x03, 0x77, bus, device);
183 close(file);
184 }));
185 }
186 for (auto &fut : futures)
187 {
188 fut.get(); // wait for all scans
189 }
190 return busMap;
191}
192
193static const std::tm intelEpoch(void)
194{
195 std::tm val = {0};
196 val.tm_year = 1996 - 1900;
197 return val;
198}
199
200bool formatFru(const std::vector<char> &fruBytes,
201 boost::container::flat_map<std::string, std::string> &result)
202{
203 static const std::vector<const char *> CHASSIS_FRU_AREAS = {
204 "PART_NUMBER", "SERIAL_NUMBER", "CHASSIS_INFO_AM1", "CHASSIS_INFO_AM2"};
205
206 static const std::vector<const char *> BOARD_FRU_AREAS = {
207 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
208 "VERSION_ID"};
209
210 static const std::vector<const char *> PRODUCT_FRU_AREAS = {
211 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
212 "PRODUCT_VERSION", "PRODUCT_SERIAL_NUMBER", "ASSET_TAG"};
213
214 size_t sum = 0;
215
216 if (fruBytes.size() < 8)
217 {
218 return false;
219 }
220 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
221 result["Common Format Version"] =
222 std::to_string(static_cast<int>(*fruAreaOffsetField));
223
224 const std::vector<const char *> *fieldData;
225
226 for (auto &area : FRU_AREAS)
227 {
228 fruAreaOffsetField++;
229 if (fruAreaOffsetField >= fruBytes.end())
230 {
231 return false;
232 }
233 size_t offset = (*fruAreaOffsetField) * 8;
234
235 if (offset > 1)
236 {
237 // +2 to skip format and length
238 std::vector<char>::const_iterator fruBytesIter =
239 fruBytes.begin() + offset + 2;
240
241 if (fruBytesIter >= fruBytes.end())
242 {
243 return false;
244 }
245
246 if (area == "CHASSIS")
247 {
248 result["CHASSIS_TYPE"] =
249 std::to_string(static_cast<int>(*fruBytesIter));
250 fruBytesIter += 1;
251 fieldData = &CHASSIS_FRU_AREAS;
252 }
253 else if (area == "BOARD")
254 {
255 result["BOARD_LANGUAGE_CODE"] =
256 std::to_string(static_cast<int>(*fruBytesIter));
257 fruBytesIter += 1;
258 if (fruBytesIter >= fruBytes.end())
259 {
260 return false;
261 }
262
263 unsigned int minutes = *fruBytesIter |
264 *(fruBytesIter + 1) << 8 |
265 *(fruBytesIter + 2) << 16;
266 std::tm fruTime = intelEpoch();
267 time_t timeValue = mktime(&fruTime);
268 timeValue += minutes * 60;
269 fruTime = *gmtime(&timeValue);
270
271 result["BOARD_MANUFACTURE_DATE"] = asctime(&fruTime);
272 result["BOARD_MANUFACTURE_DATE"]
273 .pop_back(); // remove trailing null
274 fruBytesIter += 3;
275 fieldData = &BOARD_FRU_AREAS;
276 }
277 else if (area == "PRODUCT")
278 {
279 result["PRODUCT_LANGUAGE_CODE"] =
280 std::to_string(static_cast<int>(*fruBytesIter));
281 fruBytesIter += 1;
282 fieldData = &PRODUCT_FRU_AREAS;
283 }
284 else
285 {
286 continue;
287 }
288 for (auto &field : *fieldData)
289 {
290 if (fruBytesIter >= fruBytes.end())
291 {
292 return false;
293 }
294
295 size_t length = *fruBytesIter & 0x3f;
296 fruBytesIter += 1;
297
298 if (fruBytesIter >= fruBytes.end())
299 {
300 return false;
301 }
302
303 result[std::string(area) + "_" + field] =
304 std::string(fruBytesIter, fruBytesIter + length);
305 fruBytesIter += length;
306 if (fruBytesIter >= fruBytes.end())
307 {
308 std::cerr << "Warning Fru Length Mismatch:\n ";
309 for (auto &c : fruBytes)
310 {
311 std::cerr << c;
312 }
313 std::cerr << "\n";
314 if (DEBUG)
315 {
316 for (auto &keyPair : result)
317 {
318 std::cerr << keyPair.first << " : "
319 << keyPair.second << "\n";
320 }
321 }
322 return false;
323 }
324 }
325 }
326 }
327
328 return true;
329}
330
331void AddFruObjectToDbus(
332 std::shared_ptr<dbus::connection> dbusConn, std::vector<char> &device,
333 dbus::DbusObjectServer &objServer,
334 boost::container::flat_map<std::pair<size_t, size_t>,
335 std::shared_ptr<dbus::DbusObject>>
336 &dbusObjectMap,
337 int bus, size_t address)
338{
339 boost::container::flat_map<std::string, std::string> formattedFru;
340 if (!formatFru(device, formattedFru))
341 {
342 std::cerr << "failed to format fru for device at bus " << std::hex
343 << bus << "address " << address << "\n";
344 return;
345 }
346 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
347 std::string productName;
348 if (productNameFind == formattedFru.end())
349 {
350 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
351 }
352 if (productNameFind != formattedFru.end())
353 {
354 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800355 std::regex illegalObject("[^A-Za-z0-9_]");
356 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800357 }
358 else
359 {
360 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
361 UNKNOWN_BUS_OBJECT_COUNT++;
362 }
363
364 auto object =
365 objServer.add_object("/xyz/openbmc_project/FruDevice/" + productName);
366 dbusObjectMap[std::pair<size_t, size_t>(bus, address)] = object;
367
368 auto iface = std::make_shared<dbus::DbusInterface>(
369 "xyz.openbmc_project.FruDevice", dbusConn);
370 object->register_interface(iface);
371 for (auto &property : formattedFru)
372 {
373 iface->set_property(property.first, property.second);
374 }
375 // baseboard can set this to -1 to not set a bus / address
376 if (bus > 0)
377 {
378 std::stringstream data;
379 data << "0x" << std::hex << bus;
380 iface->set_property("BUS", data.str());
381 data.str("");
382 data << "0x" << std::hex << address;
383 iface->set_property("ADDRESS", data.str());
384 }
385}
386
387static bool readBaseboardFru(std::vector<char> &baseboardFru)
388{
389 // try to read baseboard fru from file
390 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
391 if (baseboardFruFile.good())
392 {
393 baseboardFruFile.seekg(0, std::ios_base::end);
394 std::streampos fileSize = baseboardFruFile.tellg();
395 baseboardFru.resize(fileSize);
396 baseboardFruFile.seekg(0, std::ios_base::beg);
397 baseboardFruFile.read(baseboardFru.data(), fileSize);
398 }
399 else
400 {
401 return false;
402 }
403 return true;
404}
405
406int main(int argc, char **argv)
407{
408 auto devDir = fs::path("/dev/");
409 auto matchString = std::string("i2c*");
410 std::vector<fs::path> i2cBuses;
411
412 if (!find_files(devDir, matchString, i2cBuses, 0))
413 {
414 std::cerr << "unable to find i2c devices\n";
415 return 1;
416 }
417 BusMap busMap = FindI2CDevices(i2cBuses);
418
419 boost::asio::io_service io;
420 auto systemBus = std::make_shared<dbus::connection>(io, dbus::bus::system);
421 dbus::DbusObjectServer objServer(systemBus);
422 systemBus->request_name("com.intel.FruDevice");
423
424 // this is a map with keys of pair(bus number, adddress) and values of the
425 // object on dbus
426 boost::container::flat_map<std::pair<size_t, size_t>,
427 std::shared_ptr<dbus::DbusObject>>
428 dbusObjectMap;
429
430 for (auto &devicemap : busMap)
431 {
432 for (auto &device : *devicemap.second)
433 {
434 AddFruObjectToDbus(systemBus, device.second, objServer,
435 dbusObjectMap, devicemap.first, device.first);
436 }
437 }
438
439 std::vector<char> baseboardFru;
440 if (readBaseboardFru(baseboardFru))
441 {
442 AddFruObjectToDbus(systemBus, baseboardFru, objServer, dbusObjectMap,
443 -1, -1);
444 }
445
446 auto object = std::make_shared<dbus::DbusObject>(
447 systemBus, "/xyz/openbmc_project/FruDevice");
448 objServer.register_object(object);
449 auto iface = std::make_shared<dbus::DbusInterface>(
450 "xyz.openbmc_project.FruDeviceManager", systemBus);
451 object->register_interface(iface);
452
453 iface->register_method("ReScan", [&]() {
454 busMap = FindI2CDevices(i2cBuses);
455
456 for (auto &busObj : dbusObjectMap)
457 {
458 objServer.remove_object(busObj.second);
459 }
460 dbusObjectMap.clear();
461 UNKNOWN_BUS_OBJECT_COUNT = 0;
462
463 for (auto &devicemap : busMap)
464 {
465 for (auto &device : *devicemap.second)
466 {
467 AddFruObjectToDbus(systemBus, device.second, objServer,
468 dbusObjectMap, devicemap.first,
469 device.first);
470 }
471 }
472
473 return std::tuple<>(); // this is a bug in boost-dbus, needs some sort
474 // of return
475 });
476
477 io.run();
478 return 0;
479}