blob: d12940318931d3bdcd9f2acddda8cae11f2b0fc3 [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
James Feist3b860982018-10-02 14:34:07 -070017#include <errno.h>
James Feist3cb5fec2018-01-23 14:41:51 -080018#include <fcntl.h>
James Feist3b860982018-10-02 14:34:07 -070019#include <sys/inotify.h>
20#include <sys/ioctl.h>
21
22#include <Utils.hpp>
23#include <boost/algorithm/string/predicate.hpp>
24#include <boost/container/flat_map.hpp>
25#include <chrono>
26#include <ctime>
James Feist3cb5fec2018-01-23 14:41:51 -080027#include <fstream>
28#include <future>
James Feist3cb5fec2018-01-23 14:41:51 -080029#include <iostream>
James Feist3f8a2782018-02-12 09:24:42 -080030#include <regex>
James Feist3b860982018-10-02 14:34:07 -070031#include <sdbusplus/asio/connection.hpp>
32#include <sdbusplus/asio/object_server.hpp>
33#include <thread>
James Feista465ccc2019-02-08 12:51:01 -080034#include <variant>
James Feist3b860982018-10-02 14:34:07 -070035
36extern "C" {
37#include <i2c/smbus.h>
38#include <linux/i2c-dev.h>
39}
James Feist3cb5fec2018-01-23 14:41:51 -080040
Ed Tanous072e25d2018-12-16 21:45:20 -080041namespace fs = std::filesystem;
James Feist3cb5fec2018-01-23 14:41:51 -080042static constexpr bool DEBUG = false;
43static size_t UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feistb49ffc32018-05-02 11:10:43 -070044constexpr size_t MAX_FRU_SIZE = 512;
45constexpr size_t MAX_EEPROM_PAGE_INDEX = 255;
James Feist26c27ad2018-07-25 15:09:40 -070046constexpr size_t busTimeoutSeconds = 5;
James Feist3cb5fec2018-01-23 14:41:51 -080047
James Feista465ccc2019-02-08 12:51:01 -080048const static constexpr char* BASEBOARD_FRU_LOCATION =
James Feist3cb5fec2018-01-23 14:41:51 -080049 "/etc/fru/baseboard.fru.bin";
50
James Feista465ccc2019-02-08 12:51:01 -080051const static constexpr char* I2C_DEV_LOCATION = "/dev";
James Feist4131aea2018-03-09 09:47:30 -080052
James Feista465ccc2019-02-08 12:51:01 -080053static constexpr std::array<const char*, 5> FRU_AREAS = {
James Feist3cb5fec2018-01-23 14:41:51 -080054 "INTERNAL", "CHASSIS", "BOARD", "PRODUCT", "MULTIRECORD"};
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -070055const static std::regex NON_ASCII_REGEX("[^\x01-\x7f]");
James Feist3cb5fec2018-01-23 14:41:51 -080056using DeviceMap = boost::container::flat_map<int, std::vector<char>>;
57using BusMap = boost::container::flat_map<int, std::shared_ptr<DeviceMap>>;
58
James Feist444830e2019-04-05 08:38:16 -070059static std::set<size_t> busBlacklist;
James Feist6ebf9de2018-05-15 15:01:17 -070060struct FindDevicesWithCallback;
61
Nikhil Potaded8884f12019-03-27 13:27:13 -070062static BusMap busMap;
63
James Feistc95cb142018-02-26 10:41:42 -080064static bool isMuxBus(size_t bus)
65{
Ed Tanous072e25d2018-12-16 21:45:20 -080066 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -080067 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
68}
69
Vijay Khemka2d681f62018-11-06 15:51:00 -080070static int isDevice16Bit(int file)
71{
72 /* Get first byte */
73 int byte1 = i2c_smbus_read_byte_data(file, 0);
74 if (byte1 < 0)
75 {
76 return byte1;
77 }
78 /* Read 7 more bytes, it will read same first byte in case of
79 * 8 bit but it will read next byte in case of 16 bit
80 */
81 for (int i = 0; i < 7; i++)
82 {
83 int byte2 = i2c_smbus_read_byte_data(file, 0);
84 if (byte2 < 0)
85 {
86 return byte2;
87 }
88 if (byte2 != byte1)
89 {
90 return 1;
91 }
92 }
93 return 0;
94}
95
96static int read_block_data(int flag, int file, uint16_t offset, uint8_t len,
James Feista465ccc2019-02-08 12:51:01 -080097 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -080098{
99 uint8_t low_addr = offset & 0xFF;
100 uint8_t high_addr = (offset >> 8) & 0xFF;
101
102 if (flag == 0)
103 {
104 return i2c_smbus_read_i2c_block_data(file, low_addr, len, buf);
105 }
106
107 /* This is for 16 bit addressing EEPROM device. First an offset
108 * needs to be written before read data from a offset
109 */
110 int ret = i2c_smbus_write_byte_data(file, 0, low_addr);
111 if (ret < 0)
112 {
113 return ret;
114 }
115
116 return i2c_smbus_read_i2c_block_data(file, high_addr, len, buf);
117}
118
James Feist24bae7a2019-04-03 09:50:56 -0700119bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
120{
121 // ipmi spec format version number is currently at 1, verify it
122 if (blockData[0] != 0x1)
123 {
124 return false;
125 }
126
127 // verify pad is set to 0
128 if (blockData[6] != 0x0)
129 {
130 return false;
131 }
132
133 // verify offsets are 0, or don't point to another offset
134 std::set<uint8_t> foundOffsets;
135 for (int ii = 1; ii < 6; ii++)
136 {
137 if (blockData[ii] == 0)
138 {
139 continue;
140 }
James Feist0eb40352019-04-09 14:44:04 -0700141 auto inserted = foundOffsets.insert(blockData[ii]);
142 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700143 {
144 return false;
145 }
146 }
147
148 // validate checksum
149 size_t sum = 0;
150 for (int jj = 0; jj < 7; jj++)
151 {
152 sum += blockData[jj];
153 }
154 sum = (256 - sum) & 0xFF;
155
156 if (sum != blockData[7])
157 {
158 return false;
159 }
160 return true;
161}
162
James Feist3cb5fec2018-01-23 14:41:51 -0800163int get_bus_frus(int file, int first, int last, int bus,
164 std::shared_ptr<DeviceMap> devices)
165{
James Feist3cb5fec2018-01-23 14:41:51 -0800166
James Feist26c27ad2018-07-25 15:09:40 -0700167 std::future<int> future = std::async(std::launch::async, [&]() {
168 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> block_data;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800169
James Feist26c27ad2018-07-25 15:09:40 -0700170 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800171 {
James Feist3cb5fec2018-01-23 14:41:51 -0800172
James Feist26c27ad2018-07-25 15:09:40 -0700173 // Set slave address
174 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800175 {
James Feist26c27ad2018-07-25 15:09:40 -0700176 std::cerr << "device at bus " << bus << "register " << ii
177 << "busy\n";
178 continue;
179 }
180 // probe
181 else if (i2c_smbus_read_byte(file) < 0)
182 {
183 continue;
184 }
James Feist3cb5fec2018-01-23 14:41:51 -0800185
James Feist26c27ad2018-07-25 15:09:40 -0700186 if (DEBUG)
187 {
188 std::cout << "something at bus " << bus << "addr " << ii
189 << "\n";
190 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800191
192 /* Check for Device type if it is 8 bit or 16 bit */
193 int flag = isDevice16Bit(file);
194 if (flag < 0)
195 {
196 std::cerr << "failed to read bus " << bus << " address " << ii
197 << "\n";
198 continue;
199 }
200
201 if (read_block_data(flag, file, 0x0, 0x8, block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700202 {
203 std::cerr << "failed to read bus " << bus << " address " << ii
204 << "\n";
205 continue;
206 }
James Feist26c27ad2018-07-25 15:09:40 -0700207
208 // check the header checksum
James Feist24bae7a2019-04-03 09:50:56 -0700209 if (validateHeader(block_data))
James Feist26c27ad2018-07-25 15:09:40 -0700210 {
211 std::vector<char> device;
212 device.insert(device.end(), block_data.begin(),
213 block_data.begin() + 8);
214
James Feist0eb40352019-04-09 14:44:04 -0700215 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
James Feist26c27ad2018-07-25 15:09:40 -0700216 {
217 auto area_offset = device[jj];
218 if (area_offset != 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800219 {
James Feist26c27ad2018-07-25 15:09:40 -0700220 area_offset *= 8;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800221 if (read_block_data(flag, file, area_offset, 0x8,
222 block_data.data()) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800223 {
224 std::cerr << "failed to read bus " << bus
225 << " address " << ii << "\n";
226 return -1;
227 }
James Feist26c27ad2018-07-25 15:09:40 -0700228 int length = block_data[1] * 8;
James Feist3cb5fec2018-01-23 14:41:51 -0800229 device.insert(device.end(), block_data.begin(),
James Feist26c27ad2018-07-25 15:09:40 -0700230 block_data.begin() + 8);
231 length -= 8;
232 area_offset += 8;
233
234 while (length > 0)
235 {
236 auto to_get = std::min(0x20, length);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800237 if (read_block_data(flag, file, area_offset, to_get,
238 block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700239 {
240 std::cerr << "failed to read bus " << bus
241 << " address " << ii << "\n";
242 return -1;
243 }
244 device.insert(device.end(), block_data.begin(),
245 block_data.begin() + to_get);
246 area_offset += to_get;
247 length -= to_get;
248 }
James Feist3cb5fec2018-01-23 14:41:51 -0800249 }
250 }
James Feist26c27ad2018-07-25 15:09:40 -0700251 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800252 }
James Feist24bae7a2019-04-03 09:50:56 -0700253 else if (DEBUG)
James Feist9945ddf2019-03-07 13:57:36 -0800254 {
James Feist24bae7a2019-04-03 09:50:56 -0700255 std::cerr << "Illegal header at bus " << bus << " address "
256 << ii << "\n";
James Feist9945ddf2019-03-07 13:57:36 -0800257 }
James Feist3cb5fec2018-01-23 14:41:51 -0800258 }
James Feist26c27ad2018-07-25 15:09:40 -0700259 return 1;
260 });
261 std::future_status status =
262 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
263 if (status == std::future_status::timeout)
264 {
265 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700266 busBlacklist.insert(bus);
267 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700268 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800269 }
270
James Feist444830e2019-04-05 08:38:16 -0700271 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700272 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800273}
274
James Feista465ccc2019-02-08 12:51:01 -0800275static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist6ebf9de2018-05-15 15:01:17 -0700276 std::shared_ptr<FindDevicesWithCallback> context,
James Feista465ccc2019-02-08 12:51:01 -0800277 boost::asio::io_service& io, BusMap& busMap)
James Feist3cb5fec2018-01-23 14:41:51 -0800278{
James Feista465ccc2019-02-08 12:51:01 -0800279 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800280 {
281 auto busnum = i2cBus.string();
282 auto lastDash = busnum.rfind(std::string("-"));
283 // delete everything before dash inclusive
284 if (lastDash != std::string::npos)
285 {
286 busnum.erase(0, lastDash + 1);
287 }
288 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700289 if (busBlacklist.find(bus) != busBlacklist.end())
290 {
291 continue; // skip previously failed busses
292 }
James Feist3cb5fec2018-01-23 14:41:51 -0800293
294 auto file = open(i2cBus.c_str(), O_RDWR);
295 if (file < 0)
296 {
297 std::cerr << "unable to open i2c device " << i2cBus.string()
298 << "\n";
299 continue;
300 }
301 unsigned long funcs = 0;
302
303 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
304 {
305 std::cerr
306 << "Error: Could not get the adapter functionality matrix bus"
307 << bus << "\n";
308 continue;
309 }
310 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
311 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
312 {
313 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
314 << bus << "\n";
315 continue;
316 }
James Feista465ccc2019-02-08 12:51:01 -0800317 auto& device = busMap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800318 device = std::make_shared<DeviceMap>();
319
Nikhil Potaded8884f12019-03-27 13:27:13 -0700320 // i2cdetect by default uses the range 0x03 to 0x77, as
321 // this is what we have tested with, use this range. Could be
322 // changed in future.
323 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800324 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700325 std::cerr << "Scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800326 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700327
328 // fd is closed in this function in case the bus locks up
329 get_bus_frus(file, 0x03, 0x77, bus, device);
330
331 if (DEBUG)
James Feistc95cb142018-02-26 10:41:42 -0800332 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700333 std::cerr << "Done scanning bus " << bus << "\n";
James Feistc95cb142018-02-26 10:41:42 -0800334 }
James Feist3cb5fec2018-01-23 14:41:51 -0800335 }
James Feist3cb5fec2018-01-23 14:41:51 -0800336}
337
James Feist6ebf9de2018-05-15 15:01:17 -0700338// this class allows an async response after all i2c devices are discovered
339struct FindDevicesWithCallback
340 : std::enable_shared_from_this<FindDevicesWithCallback>
341{
James Feista465ccc2019-02-08 12:51:01 -0800342 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
343 boost::asio::io_service& io, BusMap& busMap,
344 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700345 _i2cBuses(i2cBuses),
346 _io(io), _busMap(busMap), _callback(std::move(callback))
347 {
348 }
349 ~FindDevicesWithCallback()
350 {
351 _callback();
352 }
353 void run()
354 {
355 FindI2CDevices(_i2cBuses, shared_from_this(), _io, _busMap);
356 }
357
James Feista465ccc2019-02-08 12:51:01 -0800358 const std::vector<fs::path>& _i2cBuses;
359 boost::asio::io_service& _io;
360 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700361 std::function<void(void)> _callback;
362};
363
James Feist3cb5fec2018-01-23 14:41:51 -0800364static const std::tm intelEpoch(void)
365{
366 std::tm val = {0};
367 val.tm_year = 1996 - 1900;
368 return val;
369}
370
James Feista465ccc2019-02-08 12:51:01 -0800371bool formatFru(const std::vector<char>& fruBytes,
372 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800373{
James Feista465ccc2019-02-08 12:51:01 -0800374 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800375 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800376
James Feista465ccc2019-02-08 12:51:01 -0800377 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800378 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
379 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800380
James Feista465ccc2019-02-08 12:51:01 -0800381 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800382 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
383 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
384 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800385
James Feistd068e932018-09-20 10:53:07 -0700386 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800387 {
388 return false;
389 }
390 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700391 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800392 std::to_string(static_cast<int>(*fruAreaOffsetField));
393
James Feista465ccc2019-02-08 12:51:01 -0800394 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800395
James Feist0eb40352019-04-09 14:44:04 -0700396 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800397 {
398 fruAreaOffsetField++;
399 if (fruAreaOffsetField >= fruBytes.end())
400 {
401 return false;
402 }
403 size_t offset = (*fruAreaOffsetField) * 8;
404
405 if (offset > 1)
406 {
407 // +2 to skip format and length
408 std::vector<char>::const_iterator fruBytesIter =
409 fruBytes.begin() + offset + 2;
410
411 if (fruBytesIter >= fruBytes.end())
412 {
413 return false;
414 }
415
416 if (area == "CHASSIS")
417 {
418 result["CHASSIS_TYPE"] =
419 std::to_string(static_cast<int>(*fruBytesIter));
420 fruBytesIter += 1;
421 fieldData = &CHASSIS_FRU_AREAS;
422 }
423 else if (area == "BOARD")
424 {
425 result["BOARD_LANGUAGE_CODE"] =
426 std::to_string(static_cast<int>(*fruBytesIter));
427 fruBytesIter += 1;
428 if (fruBytesIter >= fruBytes.end())
429 {
430 return false;
431 }
432
433 unsigned int minutes = *fruBytesIter |
434 *(fruBytesIter + 1) << 8 |
435 *(fruBytesIter + 2) << 16;
436 std::tm fruTime = intelEpoch();
437 time_t timeValue = mktime(&fruTime);
438 timeValue += minutes * 60;
439 fruTime = *gmtime(&timeValue);
440
441 result["BOARD_MANUFACTURE_DATE"] = asctime(&fruTime);
442 result["BOARD_MANUFACTURE_DATE"]
443 .pop_back(); // remove trailing null
444 fruBytesIter += 3;
445 fieldData = &BOARD_FRU_AREAS;
446 }
447 else if (area == "PRODUCT")
448 {
449 result["PRODUCT_LANGUAGE_CODE"] =
450 std::to_string(static_cast<int>(*fruBytesIter));
451 fruBytesIter += 1;
452 fieldData = &PRODUCT_FRU_AREAS;
453 }
454 else
455 {
456 continue;
457 }
James Feista465ccc2019-02-08 12:51:01 -0800458 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800459 {
460 if (fruBytesIter >= fruBytes.end())
461 {
462 return false;
463 }
464
Vijay Khemka5d5de442018-11-07 10:51:25 -0800465 /* Checking for last byte C1 to indicate that no more
466 * field to be read */
Ed Tanous2147e672019-02-27 13:59:56 -0800467 if (*fruBytesIter == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800468 {
469 break;
470 }
471
Ed Tanous2147e672019-02-27 13:59:56 -0800472 size_t length = *fruBytesIter & 0x3f;
473 fruBytesIter += 1;
474
James Feist3cb5fec2018-01-23 14:41:51 -0800475 if (fruBytesIter >= fruBytes.end())
476 {
477 return false;
478 }
Ed Tanous2147e672019-02-27 13:59:56 -0800479 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800480
Ed Tanous2147e672019-02-27 13:59:56 -0800481 // Strip non null characters from the end
482 value.erase(std::find_if(value.rbegin(), value.rend(),
483 [](char ch) { return ch != 0; })
484 .base(),
485 value.end());
486
James Feist0eb40352019-04-09 14:44:04 -0700487 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800488
James Feist3cb5fec2018-01-23 14:41:51 -0800489 fruBytesIter += length;
490 if (fruBytesIter >= fruBytes.end())
491 {
492 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800493 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800494 {
495 std::cerr << c;
496 }
497 std::cerr << "\n";
498 if (DEBUG)
499 {
James Feista465ccc2019-02-08 12:51:01 -0800500 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800501 {
502 std::cerr << keyPair.first << " : "
503 << keyPair.second << "\n";
504 }
505 }
506 return false;
507 }
508 }
509 }
510 }
511
512 return true;
513}
514
Nikhil Potaded8884f12019-03-27 13:27:13 -0700515std::vector<uint8_t>& getFruInfo(const uint8_t& bus, const uint8_t& address)
516{
517 auto deviceMap = busMap.find(bus);
518 if (deviceMap == busMap.end())
519 {
520 throw std::invalid_argument("Invalid Bus.");
521 }
522 auto device = deviceMap->second->find(address);
523 if (device == deviceMap->second->end())
524 {
525 throw std::invalid_argument("Invalid Address.");
526 }
527 std::vector<uint8_t>& ret =
528 reinterpret_cast<std::vector<uint8_t>&>(device->second);
529
530 return ret;
531}
532
James Feist3cb5fec2018-01-23 14:41:51 -0800533void AddFruObjectToDbus(
James Feist9eb0b582018-04-27 12:15:46 -0700534 std::shared_ptr<sdbusplus::asio::connection> dbusConn,
James Feista465ccc2019-02-08 12:51:01 -0800535 std::vector<char>& device, sdbusplus::asio::object_server& objServer,
536 boost::container::flat_map<
537 std::pair<size_t, size_t>,
538 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700539 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800540{
541 boost::container::flat_map<std::string, std::string> formattedFru;
542 if (!formatFru(device, formattedFru))
543 {
544 std::cerr << "failed to format fru for device at bus " << std::hex
Nikhil Potaded8884f12019-03-27 13:27:13 -0700545 << bus << " address " << address << "\n";
James Feist3cb5fec2018-01-23 14:41:51 -0800546 return;
547 }
548 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
549 std::string productName;
550 if (productNameFind == formattedFru.end())
551 {
552 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
553 }
554 if (productNameFind != formattedFru.end())
555 {
556 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800557 std::regex illegalObject("[^A-Za-z0-9_]");
558 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800559 }
560 else
561 {
562 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
563 UNKNOWN_BUS_OBJECT_COUNT++;
564 }
565
James Feist918e18c2018-02-13 15:51:07 -0800566 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800567 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700568 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800569 {
James Feist79e9c0b2018-03-15 15:21:17 -0700570 size_t index = 0;
James Feista465ccc2019-02-08 12:51:01 -0800571 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800572 {
James Feist9eb0b582018-04-27 12:15:46 -0700573 if ((busIface.second->get_object_path() == productName))
James Feist918e18c2018-02-13 15:51:07 -0800574 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700575 if (isMuxBus(bus) && address == busIface.first.second &&
576 (getFruInfo(busIface.first.first, busIface.first.second) ==
577 getFruInfo(bus, address)))
James Feist79e9c0b2018-03-15 15:21:17 -0700578 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700579 // This device is already added to the lower numbered bus,
580 // do not replicate it.
581 return;
James Feist79e9c0b2018-03-15 15:21:17 -0700582 }
583 // add underscore _index for the same object path on dbus
584 std::string strIndex = std::to_string(index);
585 if (index > 0)
586 {
587 productName.substr(0, productName.size() - strIndex.size());
588 }
589 else
590 {
591 productName += "_";
592 }
593 productName += std::to_string(index++);
James Feist918e18c2018-02-13 15:51:07 -0800594 }
595 }
596 }
James Feist3cb5fec2018-01-23 14:41:51 -0800597
James Feist9eb0b582018-04-27 12:15:46 -0700598 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
599 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
600 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
601
James Feista465ccc2019-02-08 12:51:01 -0800602 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800603 {
James Feist9eb0b582018-04-27 12:15:46 -0700604
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700605 std::regex_replace(property.second.begin(), property.second.begin(),
606 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700607 if (property.second.empty())
608 {
609 continue;
610 }
611 std::string key =
612 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
613 if (!iface->register_property(key, property.second + '\0'))
614 {
615 std::cerr << "illegal key: " << key << "\n";
616 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700617 if (DEBUG)
618 {
619 std::cout << property.first << ": " << property.second << "\n";
620 }
James Feist3cb5fec2018-01-23 14:41:51 -0800621 }
James Feist2a9d6db2018-04-27 15:48:28 -0700622
623 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700624 iface->register_property("BUS", bus);
625 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700626
James Feist9eb0b582018-04-27 12:15:46 -0700627 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800628}
629
James Feista465ccc2019-02-08 12:51:01 -0800630static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800631{
632 // try to read baseboard fru from file
633 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
634 if (baseboardFruFile.good())
635 {
636 baseboardFruFile.seekg(0, std::ios_base::end);
637 std::streampos fileSize = baseboardFruFile.tellg();
638 baseboardFru.resize(fileSize);
639 baseboardFruFile.seekg(0, std::ios_base::beg);
640 baseboardFruFile.read(baseboardFru.data(), fileSize);
641 }
642 else
643 {
644 return false;
645 }
646 return true;
647}
648
James Feista465ccc2019-02-08 12:51:01 -0800649bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700650{
651 boost::container::flat_map<std::string, std::string> tmp;
652 if (fru.size() > MAX_FRU_SIZE)
653 {
654 std::cerr << "Invalid fru.size() during writeFru\n";
655 return false;
656 }
657 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -0800658 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -0700659 {
660 std::cerr << "Invalid fru format during writeFru\n";
661 return false;
662 }
663 // baseboard fru
664 if (bus == 0 && address == 0)
665 {
666 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
667 if (!file.good())
668 {
669 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
670 << "\n";
James Feistddb78302018-09-06 11:45:42 -0700671 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700672 return false;
673 }
James Feista465ccc2019-02-08 12:51:01 -0800674 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700675 return file.good();
676 }
677 else
678 {
679 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
680
681 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
682 if (file < 0)
683 {
684 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -0700685 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700686 return false;
687 }
688 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
689 {
690 std::cerr << "unable to set device address\n";
691 close(file);
James Feistddb78302018-09-06 11:45:42 -0700692 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700693 return false;
694 }
695
696 constexpr const size_t RETRY_MAX = 2;
697 uint16_t index = 0;
698 size_t retries = RETRY_MAX;
699 while (index < fru.size())
700 {
701 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
702 (retries == RETRY_MAX))
703 {
704 // The 4K EEPROM only uses the A2 and A1 device address bits
705 // with the third bit being a memory page address bit.
706 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
707 {
708 std::cerr << "unable to set device address\n";
709 close(file);
James Feistddb78302018-09-06 11:45:42 -0700710 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700711 return false;
712 }
713 }
714
715 if (i2c_smbus_write_byte_data(file, index & 0xFF, fru[index]) < 0)
716 {
717 if (!retries--)
718 {
719 std::cerr << "error writing fru: " << strerror(errno)
720 << "\n";
721 close(file);
James Feistddb78302018-09-06 11:45:42 -0700722 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700723 return false;
724 }
725 }
726 else
727 {
728 retries = RETRY_MAX;
729 index++;
730 }
731 // most eeproms require 5-10ms between writes
732 std::this_thread::sleep_for(std::chrono::milliseconds(10));
733 }
734 close(file);
735 return true;
736 }
737}
738
James Feist9eb0b582018-04-27 12:15:46 -0700739void rescanBusses(
James Feista465ccc2019-02-08 12:51:01 -0800740 boost::asio::io_service& io, BusMap& busMap,
741 boost::container::flat_map<
742 std::pair<size_t, size_t>,
743 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
744 std::shared_ptr<sdbusplus::asio::connection>& systemBus,
745 sdbusplus::asio::object_server& objServer)
James Feist918e18c2018-02-13 15:51:07 -0800746{
James Feist6ebf9de2018-05-15 15:01:17 -0700747 static boost::asio::deadline_timer timer(io);
748 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -0800749
Gunnar Mills6f0ae942018-08-31 12:38:03 -0500750 // setup an async wait in case we get flooded with requests
James Feista465ccc2019-02-08 12:51:01 -0800751 timer.async_wait([&](const boost::system::error_code& ec) {
James Feist4131aea2018-03-09 09:47:30 -0800752 auto devDir = fs::path("/dev/");
James Feist4131aea2018-03-09 09:47:30 -0800753 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -0800754
Nikhil Potaded8884f12019-03-27 13:27:13 -0700755 boost::container::flat_map<size_t, fs::path> busPaths;
756 if (!getI2cDevicePaths(devDir, busPaths))
James Feist918e18c2018-02-13 15:51:07 -0800757 {
James Feist4131aea2018-03-09 09:47:30 -0800758 std::cerr << "unable to find i2c devices\n";
759 return;
James Feist918e18c2018-02-13 15:51:07 -0800760 }
Nikhil Potaded8884f12019-03-27 13:27:13 -0700761
762 for (auto busPath : busPaths)
763 {
764 i2cBuses.emplace_back(busPath.second);
765 }
James Feist4131aea2018-03-09 09:47:30 -0800766
James Feist6ebf9de2018-05-15 15:01:17 -0700767 busMap.clear();
768 auto scan = std::make_shared<FindDevicesWithCallback>(
769 i2cBuses, io, busMap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -0800770 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700771 {
772 objServer.remove_interface(busIface.second);
773 }
James Feist4131aea2018-03-09 09:47:30 -0800774
James Feist6ebf9de2018-05-15 15:01:17 -0700775 dbusInterfaceMap.clear();
776 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -0800777
James Feist6ebf9de2018-05-15 15:01:17 -0700778 // todo, get this from a more sensable place
779 std::vector<char> baseboardFru;
780 if (readBaseboardFru(baseboardFru))
781 {
782 boost::container::flat_map<int, std::vector<char>>
783 baseboardDev;
784 baseboardDev.emplace(0, baseboardFru);
785 busMap[0] = std::make_shared<DeviceMap>(baseboardDev);
786 }
James Feista465ccc2019-02-08 12:51:01 -0800787 for (auto& devicemap : busMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700788 {
James Feista465ccc2019-02-08 12:51:01 -0800789 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -0700790 {
791 AddFruObjectToDbus(systemBus, device.second, objServer,
792 dbusInterfaceMap, devicemap.first,
793 device.first);
794 }
795 }
796 });
797 scan->run();
798 });
James Feist918e18c2018-02-13 15:51:07 -0800799}
800
James Feista465ccc2019-02-08 12:51:01 -0800801int main(int argc, char** argv)
James Feist3cb5fec2018-01-23 14:41:51 -0800802{
803 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -0800804 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -0800805 std::vector<fs::path> i2cBuses;
806
James Feista3c180a2018-08-09 16:06:04 -0700807 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -0800808 {
809 std::cerr << "unable to find i2c devices\n";
810 return 1;
811 }
James Feist3cb5fec2018-01-23 14:41:51 -0800812
813 boost::asio::io_service io;
James Feist9eb0b582018-04-27 12:15:46 -0700814 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
815 auto objServer = sdbusplus::asio::object_server(systemBus);
Vijay Khemka065f6d92018-12-18 10:37:47 -0800816 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -0800817
James Feist6ebf9de2018-05-15 15:01:17 -0700818 // this is a map with keys of pair(bus number, address) and values of
819 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -0800820 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -0700821 std::shared_ptr<sdbusplus::asio::dbus_interface>>
822 dbusInterfaceMap;
James Feist3cb5fec2018-01-23 14:41:51 -0800823
James Feist9eb0b582018-04-27 12:15:46 -0700824 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
825 objServer.add_interface("/xyz/openbmc_project/FruDevice",
826 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -0800827
828 iface->register_method("ReScan", [&]() {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700829 rescanBusses(io, busMap, dbusInterfaceMap, systemBus, objServer);
James Feist3cb5fec2018-01-23 14:41:51 -0800830 });
James Feist2a9d6db2018-04-27 15:48:28 -0700831
Nikhil Potaded8884f12019-03-27 13:27:13 -0700832 iface->register_method("GetRawFru", getFruInfo);
James Feistb49ffc32018-05-02 11:10:43 -0700833
834 iface->register_method("WriteFru", [&](const uint8_t bus,
835 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -0800836 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -0700837 if (!writeFru(bus, address, data))
838 {
James Feistddb78302018-09-06 11:45:42 -0700839 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -0700840 return;
841 }
842 // schedule rescan on success
Nikhil Potaded8884f12019-03-27 13:27:13 -0700843 rescanBusses(io, busMap, dbusInterfaceMap, systemBus, objServer);
James Feistb49ffc32018-05-02 11:10:43 -0700844 });
James Feist9eb0b582018-04-27 12:15:46 -0700845 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800846
James Feist9eb0b582018-04-27 12:15:46 -0700847 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -0800848 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -0800849 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -0700850 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -0800851 std::string,
852 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -0700853 values;
854 message.read(objectName, values);
James Feist918e18c2018-02-13 15:51:07 -0800855 auto findPgood = values.find("pgood");
856 if (findPgood != values.end())
857 {
James Feist6ebf9de2018-05-15 15:01:17 -0700858
Nikhil Potaded8884f12019-03-27 13:27:13 -0700859 rescanBusses(io, busMap, dbusInterfaceMap, systemBus,
James Feist6ebf9de2018-05-15 15:01:17 -0700860 objServer);
James Feist918e18c2018-02-13 15:51:07 -0800861 }
James Feist918e18c2018-02-13 15:51:07 -0800862 };
James Feist9eb0b582018-04-27 12:15:46 -0700863
864 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -0800865 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -0700866 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
867 "openbmc_project/Chassis/Control/"
868 "Power0',arg0='xyz.openbmc_project.Chassis.Control.Power'",
James Feist9eb0b582018-04-27 12:15:46 -0700869 eventHandler);
870
James Feist4131aea2018-03-09 09:47:30 -0800871 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -0700872 inotify_add_watch(fd, I2C_DEV_LOCATION,
873 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -0800874 std::array<char, 4096> readBuffer;
875 std::string pendingBuffer;
876 // monitor for new i2c devices
877 boost::asio::posix::stream_descriptor dirWatch(io, fd);
878 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -0800879 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -0800880 std::size_t bytes_transferred) {
881 if (ec)
882 {
883 std::cout << "Callback Error " << ec << "\n";
884 return;
885 }
886 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
887 bool devChange = false;
888 while (pendingBuffer.size() > sizeof(inotify_event))
889 {
James Feista465ccc2019-02-08 12:51:01 -0800890 const inotify_event* iEvent =
891 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -0800892 pendingBuffer.data());
893 switch (iEvent->mask)
894 {
James Feist9eb0b582018-04-27 12:15:46 -0700895 case IN_CREATE:
896 case IN_MOVED_TO:
897 case IN_DELETE:
898 if (boost::starts_with(std::string(iEvent->name),
899 "i2c"))
900 {
901 devChange = true;
902 }
James Feist4131aea2018-03-09 09:47:30 -0800903 }
904
905 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
906 }
James Feist6ebf9de2018-05-15 15:01:17 -0700907 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -0800908 {
Nikhil Potaded8884f12019-03-27 13:27:13 -0700909 rescanBusses(io, busMap, dbusInterfaceMap, systemBus,
James Feist6ebf9de2018-05-15 15:01:17 -0700910 objServer);
James Feist4131aea2018-03-09 09:47:30 -0800911 }
James Feist6ebf9de2018-05-15 15:01:17 -0700912
James Feist4131aea2018-03-09 09:47:30 -0800913 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
914 watchI2cBusses);
915 };
916
917 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -0500918 // run the initial scan
Nikhil Potaded8884f12019-03-27 13:27:13 -0700919 rescanBusses(io, busMap, dbusInterfaceMap, systemBus, objServer);
James Feist918e18c2018-02-13 15:51:07 -0800920
James Feist3cb5fec2018-01-23 14:41:51 -0800921 io.run();
922 return 0;
923}