blob: 3c42515f0156aa6371067ed261271e8cefe1967e [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
James Feistc95cb142018-02-26 10:41:42 -080062static bool isMuxBus(size_t bus)
63{
Ed Tanous072e25d2018-12-16 21:45:20 -080064 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -080065 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
66}
67
Vijay Khemka2d681f62018-11-06 15:51:00 -080068static int isDevice16Bit(int file)
69{
70 /* Get first byte */
71 int byte1 = i2c_smbus_read_byte_data(file, 0);
72 if (byte1 < 0)
73 {
74 return byte1;
75 }
76 /* Read 7 more bytes, it will read same first byte in case of
77 * 8 bit but it will read next byte in case of 16 bit
78 */
79 for (int i = 0; i < 7; i++)
80 {
81 int byte2 = i2c_smbus_read_byte_data(file, 0);
82 if (byte2 < 0)
83 {
84 return byte2;
85 }
86 if (byte2 != byte1)
87 {
88 return 1;
89 }
90 }
91 return 0;
92}
93
94static int read_block_data(int flag, int file, uint16_t offset, uint8_t len,
James Feista465ccc2019-02-08 12:51:01 -080095 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -080096{
97 uint8_t low_addr = offset & 0xFF;
98 uint8_t high_addr = (offset >> 8) & 0xFF;
99
100 if (flag == 0)
101 {
102 return i2c_smbus_read_i2c_block_data(file, low_addr, len, buf);
103 }
104
105 /* This is for 16 bit addressing EEPROM device. First an offset
106 * needs to be written before read data from a offset
107 */
108 int ret = i2c_smbus_write_byte_data(file, 0, low_addr);
109 if (ret < 0)
110 {
111 return ret;
112 }
113
114 return i2c_smbus_read_i2c_block_data(file, high_addr, len, buf);
115}
116
James Feist24bae7a2019-04-03 09:50:56 -0700117bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
118{
119 // ipmi spec format version number is currently at 1, verify it
120 if (blockData[0] != 0x1)
121 {
122 return false;
123 }
124
125 // verify pad is set to 0
126 if (blockData[6] != 0x0)
127 {
128 return false;
129 }
130
131 // verify offsets are 0, or don't point to another offset
132 std::set<uint8_t> foundOffsets;
133 for (int ii = 1; ii < 6; ii++)
134 {
135 if (blockData[ii] == 0)
136 {
137 continue;
138 }
James Feist0eb40352019-04-09 14:44:04 -0700139 auto inserted = foundOffsets.insert(blockData[ii]);
140 if (!inserted.second)
James Feist24bae7a2019-04-03 09:50:56 -0700141 {
142 return false;
143 }
144 }
145
146 // validate checksum
147 size_t sum = 0;
148 for (int jj = 0; jj < 7; jj++)
149 {
150 sum += blockData[jj];
151 }
152 sum = (256 - sum) & 0xFF;
153
154 if (sum != blockData[7])
155 {
156 return false;
157 }
158 return true;
159}
160
James Feist3cb5fec2018-01-23 14:41:51 -0800161int get_bus_frus(int file, int first, int last, int bus,
162 std::shared_ptr<DeviceMap> devices)
163{
James Feist3cb5fec2018-01-23 14:41:51 -0800164
James Feist26c27ad2018-07-25 15:09:40 -0700165 std::future<int> future = std::async(std::launch::async, [&]() {
166 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> block_data;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800167
James Feist26c27ad2018-07-25 15:09:40 -0700168 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800169 {
James Feist3cb5fec2018-01-23 14:41:51 -0800170
James Feist26c27ad2018-07-25 15:09:40 -0700171 // Set slave address
172 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800173 {
James Feist26c27ad2018-07-25 15:09:40 -0700174 std::cerr << "device at bus " << bus << "register " << ii
175 << "busy\n";
176 continue;
177 }
178 // probe
179 else if (i2c_smbus_read_byte(file) < 0)
180 {
181 continue;
182 }
James Feist3cb5fec2018-01-23 14:41:51 -0800183
James Feist26c27ad2018-07-25 15:09:40 -0700184 if (DEBUG)
185 {
186 std::cout << "something at bus " << bus << "addr " << ii
187 << "\n";
188 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800189
190 /* Check for Device type if it is 8 bit or 16 bit */
191 int flag = isDevice16Bit(file);
192 if (flag < 0)
193 {
194 std::cerr << "failed to read bus " << bus << " address " << ii
195 << "\n";
196 continue;
197 }
198
199 if (read_block_data(flag, file, 0x0, 0x8, block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700200 {
201 std::cerr << "failed to read bus " << bus << " address " << ii
202 << "\n";
203 continue;
204 }
James Feist26c27ad2018-07-25 15:09:40 -0700205
206 // check the header checksum
James Feist24bae7a2019-04-03 09:50:56 -0700207 if (validateHeader(block_data))
James Feist26c27ad2018-07-25 15:09:40 -0700208 {
209 std::vector<char> device;
210 device.insert(device.end(), block_data.begin(),
211 block_data.begin() + 8);
212
James Feist0eb40352019-04-09 14:44:04 -0700213 for (size_t jj = 1; jj <= FRU_AREAS.size(); jj++)
James Feist26c27ad2018-07-25 15:09:40 -0700214 {
215 auto area_offset = device[jj];
216 if (area_offset != 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800217 {
James Feist26c27ad2018-07-25 15:09:40 -0700218 area_offset *= 8;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800219 if (read_block_data(flag, file, area_offset, 0x8,
220 block_data.data()) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800221 {
222 std::cerr << "failed to read bus " << bus
223 << " address " << ii << "\n";
224 return -1;
225 }
James Feist26c27ad2018-07-25 15:09:40 -0700226 int length = block_data[1] * 8;
James Feist3cb5fec2018-01-23 14:41:51 -0800227 device.insert(device.end(), block_data.begin(),
James Feist26c27ad2018-07-25 15:09:40 -0700228 block_data.begin() + 8);
229 length -= 8;
230 area_offset += 8;
231
232 while (length > 0)
233 {
234 auto to_get = std::min(0x20, length);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800235 if (read_block_data(flag, file, area_offset, to_get,
236 block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700237 {
238 std::cerr << "failed to read bus " << bus
239 << " address " << ii << "\n";
240 return -1;
241 }
242 device.insert(device.end(), block_data.begin(),
243 block_data.begin() + to_get);
244 area_offset += to_get;
245 length -= to_get;
246 }
James Feist3cb5fec2018-01-23 14:41:51 -0800247 }
248 }
James Feist26c27ad2018-07-25 15:09:40 -0700249 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800250 }
James Feist24bae7a2019-04-03 09:50:56 -0700251 else if (DEBUG)
James Feist9945ddf2019-03-07 13:57:36 -0800252 {
James Feist24bae7a2019-04-03 09:50:56 -0700253 std::cerr << "Illegal header at bus " << bus << " address "
254 << ii << "\n";
James Feist9945ddf2019-03-07 13:57:36 -0800255 }
James Feist3cb5fec2018-01-23 14:41:51 -0800256 }
James Feist26c27ad2018-07-25 15:09:40 -0700257 return 1;
258 });
259 std::future_status status =
260 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
261 if (status == std::future_status::timeout)
262 {
263 std::cerr << "Error reading bus " << bus << "\n";
James Feist444830e2019-04-05 08:38:16 -0700264 busBlacklist.insert(bus);
265 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700266 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800267 }
268
James Feist444830e2019-04-05 08:38:16 -0700269 close(file);
James Feist26c27ad2018-07-25 15:09:40 -0700270 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800271}
272
James Feista465ccc2019-02-08 12:51:01 -0800273static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist6ebf9de2018-05-15 15:01:17 -0700274 std::shared_ptr<FindDevicesWithCallback> context,
James Feista465ccc2019-02-08 12:51:01 -0800275 boost::asio::io_service& io, BusMap& busMap)
James Feist3cb5fec2018-01-23 14:41:51 -0800276{
James Feista465ccc2019-02-08 12:51:01 -0800277 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800278 {
279 auto busnum = i2cBus.string();
280 auto lastDash = busnum.rfind(std::string("-"));
281 // delete everything before dash inclusive
282 if (lastDash != std::string::npos)
283 {
284 busnum.erase(0, lastDash + 1);
285 }
286 auto bus = std::stoi(busnum);
James Feist444830e2019-04-05 08:38:16 -0700287 if (busBlacklist.find(bus) != busBlacklist.end())
288 {
289 continue; // skip previously failed busses
290 }
James Feist3cb5fec2018-01-23 14:41:51 -0800291
292 auto file = open(i2cBus.c_str(), O_RDWR);
293 if (file < 0)
294 {
295 std::cerr << "unable to open i2c device " << i2cBus.string()
296 << "\n";
297 continue;
298 }
299 unsigned long funcs = 0;
300
301 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
302 {
303 std::cerr
304 << "Error: Could not get the adapter functionality matrix bus"
305 << bus << "\n";
306 continue;
307 }
308 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
309 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
310 {
311 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
312 << bus << "\n";
313 continue;
314 }
James Feista465ccc2019-02-08 12:51:01 -0800315 auto& device = busMap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800316 device = std::make_shared<DeviceMap>();
317
James Feist444830e2019-04-05 08:38:16 -0700318 auto callback = [file, device, bus, context]() {
319 // i2cdetect by default uses the range 0x03 to 0x77, as
320 // this is what we have tested with, use this range. Could be
321 // changed in future.
322 if (DEBUG)
323 {
324 std::cerr << "Scanning bus " << bus << "\n";
325 }
326
327 // fd is closed in this function in case the bus locks up
328 get_bus_frus(file, 0x03, 0x77, bus, device);
329
330 if (DEBUG)
331 {
332 std::cerr << "Done scanning bus " << bus << "\n";
333 }
334 };
James Feistc95cb142018-02-26 10:41:42 -0800335 // don't scan muxed buses async as don't want to confuse the mux
336 if (isMuxBus(bus))
337 {
James Feist444830e2019-04-05 08:38:16 -0700338 callback();
James Feistc95cb142018-02-26 10:41:42 -0800339 }
340 else
341 {
James Feist444830e2019-04-05 08:38:16 -0700342 io.post(callback);
James Feistc95cb142018-02-26 10:41:42 -0800343 }
James Feist3cb5fec2018-01-23 14:41:51 -0800344 }
James Feist3cb5fec2018-01-23 14:41:51 -0800345}
346
James Feist6ebf9de2018-05-15 15:01:17 -0700347// this class allows an async response after all i2c devices are discovered
348struct FindDevicesWithCallback
349 : std::enable_shared_from_this<FindDevicesWithCallback>
350{
James Feista465ccc2019-02-08 12:51:01 -0800351 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
352 boost::asio::io_service& io, BusMap& busMap,
353 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700354 _i2cBuses(i2cBuses),
355 _io(io), _busMap(busMap), _callback(std::move(callback))
356 {
357 }
358 ~FindDevicesWithCallback()
359 {
360 _callback();
361 }
362 void run()
363 {
364 FindI2CDevices(_i2cBuses, shared_from_this(), _io, _busMap);
365 }
366
James Feista465ccc2019-02-08 12:51:01 -0800367 const std::vector<fs::path>& _i2cBuses;
368 boost::asio::io_service& _io;
369 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700370 std::function<void(void)> _callback;
371};
372
James Feist3cb5fec2018-01-23 14:41:51 -0800373static const std::tm intelEpoch(void)
374{
375 std::tm val = {0};
376 val.tm_year = 1996 - 1900;
377 return val;
378}
379
James Feista465ccc2019-02-08 12:51:01 -0800380bool formatFru(const std::vector<char>& fruBytes,
381 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800382{
James Feista465ccc2019-02-08 12:51:01 -0800383 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800384 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800385
James Feista465ccc2019-02-08 12:51:01 -0800386 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800387 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
388 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800389
James Feista465ccc2019-02-08 12:51:01 -0800390 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800391 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
392 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
393 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800394
James Feistd068e932018-09-20 10:53:07 -0700395 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800396 {
397 return false;
398 }
399 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700400 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800401 std::to_string(static_cast<int>(*fruAreaOffsetField));
402
James Feista465ccc2019-02-08 12:51:01 -0800403 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800404
James Feist0eb40352019-04-09 14:44:04 -0700405 for (const std::string& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800406 {
407 fruAreaOffsetField++;
408 if (fruAreaOffsetField >= fruBytes.end())
409 {
410 return false;
411 }
412 size_t offset = (*fruAreaOffsetField) * 8;
413
414 if (offset > 1)
415 {
416 // +2 to skip format and length
417 std::vector<char>::const_iterator fruBytesIter =
418 fruBytes.begin() + offset + 2;
419
420 if (fruBytesIter >= fruBytes.end())
421 {
422 return false;
423 }
424
425 if (area == "CHASSIS")
426 {
427 result["CHASSIS_TYPE"] =
428 std::to_string(static_cast<int>(*fruBytesIter));
429 fruBytesIter += 1;
430 fieldData = &CHASSIS_FRU_AREAS;
431 }
432 else if (area == "BOARD")
433 {
434 result["BOARD_LANGUAGE_CODE"] =
435 std::to_string(static_cast<int>(*fruBytesIter));
436 fruBytesIter += 1;
437 if (fruBytesIter >= fruBytes.end())
438 {
439 return false;
440 }
441
442 unsigned int minutes = *fruBytesIter |
443 *(fruBytesIter + 1) << 8 |
444 *(fruBytesIter + 2) << 16;
445 std::tm fruTime = intelEpoch();
446 time_t timeValue = mktime(&fruTime);
447 timeValue += minutes * 60;
448 fruTime = *gmtime(&timeValue);
449
450 result["BOARD_MANUFACTURE_DATE"] = asctime(&fruTime);
451 result["BOARD_MANUFACTURE_DATE"]
452 .pop_back(); // remove trailing null
453 fruBytesIter += 3;
454 fieldData = &BOARD_FRU_AREAS;
455 }
456 else if (area == "PRODUCT")
457 {
458 result["PRODUCT_LANGUAGE_CODE"] =
459 std::to_string(static_cast<int>(*fruBytesIter));
460 fruBytesIter += 1;
461 fieldData = &PRODUCT_FRU_AREAS;
462 }
463 else
464 {
465 continue;
466 }
James Feista465ccc2019-02-08 12:51:01 -0800467 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800468 {
469 if (fruBytesIter >= fruBytes.end())
470 {
471 return false;
472 }
473
Vijay Khemka5d5de442018-11-07 10:51:25 -0800474 /* Checking for last byte C1 to indicate that no more
475 * field to be read */
Ed Tanous2147e672019-02-27 13:59:56 -0800476 if (*fruBytesIter == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800477 {
478 break;
479 }
480
Ed Tanous2147e672019-02-27 13:59:56 -0800481 size_t length = *fruBytesIter & 0x3f;
482 fruBytesIter += 1;
483
James Feist3cb5fec2018-01-23 14:41:51 -0800484 if (fruBytesIter >= fruBytes.end())
485 {
486 return false;
487 }
Ed Tanous2147e672019-02-27 13:59:56 -0800488 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800489
Ed Tanous2147e672019-02-27 13:59:56 -0800490 // Strip non null characters from the end
491 value.erase(std::find_if(value.rbegin(), value.rend(),
492 [](char ch) { return ch != 0; })
493 .base(),
494 value.end());
495
James Feist0eb40352019-04-09 14:44:04 -0700496 result[area + "_" + field] = std::move(value);
Ed Tanous2147e672019-02-27 13:59:56 -0800497
James Feist3cb5fec2018-01-23 14:41:51 -0800498 fruBytesIter += length;
499 if (fruBytesIter >= fruBytes.end())
500 {
501 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800502 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800503 {
504 std::cerr << c;
505 }
506 std::cerr << "\n";
507 if (DEBUG)
508 {
James Feista465ccc2019-02-08 12:51:01 -0800509 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800510 {
511 std::cerr << keyPair.first << " : "
512 << keyPair.second << "\n";
513 }
514 }
515 return false;
516 }
517 }
518 }
519 }
520
521 return true;
522}
523
524void AddFruObjectToDbus(
James Feist9eb0b582018-04-27 12:15:46 -0700525 std::shared_ptr<sdbusplus::asio::connection> dbusConn,
James Feista465ccc2019-02-08 12:51:01 -0800526 std::vector<char>& device, sdbusplus::asio::object_server& objServer,
527 boost::container::flat_map<
528 std::pair<size_t, size_t>,
529 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700530 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800531{
532 boost::container::flat_map<std::string, std::string> formattedFru;
533 if (!formatFru(device, formattedFru))
534 {
535 std::cerr << "failed to format fru for device at bus " << std::hex
536 << bus << "address " << address << "\n";
537 return;
538 }
539 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
540 std::string productName;
541 if (productNameFind == formattedFru.end())
542 {
543 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
544 }
545 if (productNameFind != formattedFru.end())
546 {
547 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800548 std::regex illegalObject("[^A-Za-z0-9_]");
549 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800550 }
551 else
552 {
553 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
554 UNKNOWN_BUS_OBJECT_COUNT++;
555 }
556
James Feist918e18c2018-02-13 15:51:07 -0800557 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800558 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700559 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800560 {
James Feist79e9c0b2018-03-15 15:21:17 -0700561 size_t index = 0;
James Feista465ccc2019-02-08 12:51:01 -0800562 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800563 {
James Feist9eb0b582018-04-27 12:15:46 -0700564 if ((busIface.second->get_object_path() == productName))
James Feist918e18c2018-02-13 15:51:07 -0800565 {
James Feist9eb0b582018-04-27 12:15:46 -0700566 if (isMuxBus(bus) && address == busIface.first.second)
James Feist79e9c0b2018-03-15 15:21:17 -0700567 {
568 continue;
569 }
570 // add underscore _index for the same object path on dbus
571 std::string strIndex = std::to_string(index);
572 if (index > 0)
573 {
574 productName.substr(0, productName.size() - strIndex.size());
575 }
576 else
577 {
578 productName += "_";
579 }
580 productName += std::to_string(index++);
James Feist918e18c2018-02-13 15:51:07 -0800581 }
582 }
583 }
James Feist3cb5fec2018-01-23 14:41:51 -0800584
James Feist9eb0b582018-04-27 12:15:46 -0700585 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
586 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
587 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
588
James Feista465ccc2019-02-08 12:51:01 -0800589 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800590 {
James Feist9eb0b582018-04-27 12:15:46 -0700591
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700592 std::regex_replace(property.second.begin(), property.second.begin(),
593 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700594 if (property.second.empty())
595 {
596 continue;
597 }
598 std::string key =
599 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
600 if (!iface->register_property(key, property.second + '\0'))
601 {
602 std::cerr << "illegal key: " << key << "\n";
603 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700604 if (DEBUG)
605 {
606 std::cout << property.first << ": " << property.second << "\n";
607 }
James Feist3cb5fec2018-01-23 14:41:51 -0800608 }
James Feist2a9d6db2018-04-27 15:48:28 -0700609
610 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700611 iface->register_property("BUS", bus);
612 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700613
James Feist9eb0b582018-04-27 12:15:46 -0700614 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800615}
616
James Feista465ccc2019-02-08 12:51:01 -0800617static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800618{
619 // try to read baseboard fru from file
620 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
621 if (baseboardFruFile.good())
622 {
623 baseboardFruFile.seekg(0, std::ios_base::end);
624 std::streampos fileSize = baseboardFruFile.tellg();
625 baseboardFru.resize(fileSize);
626 baseboardFruFile.seekg(0, std::ios_base::beg);
627 baseboardFruFile.read(baseboardFru.data(), fileSize);
628 }
629 else
630 {
631 return false;
632 }
633 return true;
634}
635
James Feista465ccc2019-02-08 12:51:01 -0800636bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700637{
638 boost::container::flat_map<std::string, std::string> tmp;
639 if (fru.size() > MAX_FRU_SIZE)
640 {
641 std::cerr << "Invalid fru.size() during writeFru\n";
642 return false;
643 }
644 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -0800645 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -0700646 {
647 std::cerr << "Invalid fru format during writeFru\n";
648 return false;
649 }
650 // baseboard fru
651 if (bus == 0 && address == 0)
652 {
653 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
654 if (!file.good())
655 {
656 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
657 << "\n";
James Feistddb78302018-09-06 11:45:42 -0700658 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700659 return false;
660 }
James Feista465ccc2019-02-08 12:51:01 -0800661 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700662 return file.good();
663 }
664 else
665 {
666 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
667
668 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
669 if (file < 0)
670 {
671 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -0700672 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700673 return false;
674 }
675 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
676 {
677 std::cerr << "unable to set device address\n";
678 close(file);
James Feistddb78302018-09-06 11:45:42 -0700679 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700680 return false;
681 }
682
683 constexpr const size_t RETRY_MAX = 2;
684 uint16_t index = 0;
685 size_t retries = RETRY_MAX;
686 while (index < fru.size())
687 {
688 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
689 (retries == RETRY_MAX))
690 {
691 // The 4K EEPROM only uses the A2 and A1 device address bits
692 // with the third bit being a memory page address bit.
693 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
694 {
695 std::cerr << "unable to set device address\n";
696 close(file);
James Feistddb78302018-09-06 11:45:42 -0700697 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700698 return false;
699 }
700 }
701
702 if (i2c_smbus_write_byte_data(file, index & 0xFF, fru[index]) < 0)
703 {
704 if (!retries--)
705 {
706 std::cerr << "error writing fru: " << strerror(errno)
707 << "\n";
708 close(file);
James Feistddb78302018-09-06 11:45:42 -0700709 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700710 return false;
711 }
712 }
713 else
714 {
715 retries = RETRY_MAX;
716 index++;
717 }
718 // most eeproms require 5-10ms between writes
719 std::this_thread::sleep_for(std::chrono::milliseconds(10));
720 }
721 close(file);
722 return true;
723 }
724}
725
James Feist9eb0b582018-04-27 12:15:46 -0700726void rescanBusses(
James Feista465ccc2019-02-08 12:51:01 -0800727 boost::asio::io_service& io, BusMap& busMap,
728 boost::container::flat_map<
729 std::pair<size_t, size_t>,
730 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
731 std::shared_ptr<sdbusplus::asio::connection>& systemBus,
732 sdbusplus::asio::object_server& objServer)
James Feist918e18c2018-02-13 15:51:07 -0800733{
James Feist6ebf9de2018-05-15 15:01:17 -0700734 static boost::asio::deadline_timer timer(io);
735 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -0800736
Gunnar Mills6f0ae942018-08-31 12:38:03 -0500737 // setup an async wait in case we get flooded with requests
James Feista465ccc2019-02-08 12:51:01 -0800738 timer.async_wait([&](const boost::system::error_code& ec) {
James Feist4131aea2018-03-09 09:47:30 -0800739 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -0800740 auto matchString = std::string(R"(i2c-\d+$)");
James Feist4131aea2018-03-09 09:47:30 -0800741 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -0800742
James Feista3c180a2018-08-09 16:06:04 -0700743 if (!findFiles(devDir, matchString, i2cBuses))
James Feist918e18c2018-02-13 15:51:07 -0800744 {
James Feist4131aea2018-03-09 09:47:30 -0800745 std::cerr << "unable to find i2c devices\n";
746 return;
James Feist918e18c2018-02-13 15:51:07 -0800747 }
James Feist4131aea2018-03-09 09:47:30 -0800748 // scanning muxes in reverse order seems to have adverse effects
749 // sorting this list seems to be a fix for that
750 std::sort(i2cBuses.begin(), i2cBuses.end());
James Feist4131aea2018-03-09 09:47:30 -0800751
James Feist6ebf9de2018-05-15 15:01:17 -0700752 busMap.clear();
753 auto scan = std::make_shared<FindDevicesWithCallback>(
754 i2cBuses, io, busMap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -0800755 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700756 {
757 objServer.remove_interface(busIface.second);
758 }
James Feist4131aea2018-03-09 09:47:30 -0800759
James Feist6ebf9de2018-05-15 15:01:17 -0700760 dbusInterfaceMap.clear();
761 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -0800762
James Feist6ebf9de2018-05-15 15:01:17 -0700763 // todo, get this from a more sensable place
764 std::vector<char> baseboardFru;
765 if (readBaseboardFru(baseboardFru))
766 {
767 boost::container::flat_map<int, std::vector<char>>
768 baseboardDev;
769 baseboardDev.emplace(0, baseboardFru);
770 busMap[0] = std::make_shared<DeviceMap>(baseboardDev);
771 }
James Feista465ccc2019-02-08 12:51:01 -0800772 for (auto& devicemap : busMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700773 {
James Feista465ccc2019-02-08 12:51:01 -0800774 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -0700775 {
776 AddFruObjectToDbus(systemBus, device.second, objServer,
777 dbusInterfaceMap, devicemap.first,
778 device.first);
779 }
780 }
781 });
782 scan->run();
783 });
James Feist918e18c2018-02-13 15:51:07 -0800784}
785
James Feista465ccc2019-02-08 12:51:01 -0800786int main(int argc, char** argv)
James Feist3cb5fec2018-01-23 14:41:51 -0800787{
788 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -0800789 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -0800790 std::vector<fs::path> i2cBuses;
791
James Feista3c180a2018-08-09 16:06:04 -0700792 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -0800793 {
794 std::cerr << "unable to find i2c devices\n";
795 return 1;
796 }
James Feist3cb5fec2018-01-23 14:41:51 -0800797
798 boost::asio::io_service io;
James Feist9eb0b582018-04-27 12:15:46 -0700799 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
800 auto objServer = sdbusplus::asio::object_server(systemBus);
Vijay Khemka065f6d92018-12-18 10:37:47 -0800801 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -0800802
James Feist6ebf9de2018-05-15 15:01:17 -0700803 // this is a map with keys of pair(bus number, address) and values of
804 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -0800805 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -0700806 std::shared_ptr<sdbusplus::asio::dbus_interface>>
807 dbusInterfaceMap;
James Feist2a9d6db2018-04-27 15:48:28 -0700808 BusMap busmap;
James Feist3cb5fec2018-01-23 14:41:51 -0800809
James Feist9eb0b582018-04-27 12:15:46 -0700810 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
811 objServer.add_interface("/xyz/openbmc_project/FruDevice",
812 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -0800813
814 iface->register_method("ReScan", [&]() {
James Feist6ebf9de2018-05-15 15:01:17 -0700815 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feist3cb5fec2018-01-23 14:41:51 -0800816 });
James Feist2a9d6db2018-04-27 15:48:28 -0700817
818 iface->register_method(
James Feista465ccc2019-02-08 12:51:01 -0800819 "GetRawFru", [&](const uint8_t& bus, const uint8_t& address) {
James Feist2a9d6db2018-04-27 15:48:28 -0700820 auto deviceMap = busmap.find(bus);
821 if (deviceMap == busmap.end())
822 {
James Feistddb78302018-09-06 11:45:42 -0700823 throw std::invalid_argument("Invalid Bus.");
James Feist2a9d6db2018-04-27 15:48:28 -0700824 }
825 auto device = deviceMap->second->find(address);
826 if (device == deviceMap->second->end())
827 {
James Feistddb78302018-09-06 11:45:42 -0700828 throw std::invalid_argument("Invalid Address.");
James Feist2a9d6db2018-04-27 15:48:28 -0700829 }
James Feista465ccc2019-02-08 12:51:01 -0800830 std::vector<uint8_t>& ret =
831 reinterpret_cast<std::vector<uint8_t>&>(device->second);
James Feist2a9d6db2018-04-27 15:48:28 -0700832 return ret;
833 });
James Feistb49ffc32018-05-02 11:10:43 -0700834
835 iface->register_method("WriteFru", [&](const uint8_t bus,
836 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -0800837 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -0700838 if (!writeFru(bus, address, data))
839 {
James Feistddb78302018-09-06 11:45:42 -0700840 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -0700841 return;
842 }
843 // schedule rescan on success
844 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feistb49ffc32018-05-02 11:10:43 -0700845 });
James Feist9eb0b582018-04-27 12:15:46 -0700846 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800847
James Feist9eb0b582018-04-27 12:15:46 -0700848 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -0800849 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -0800850 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -0700851 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -0800852 std::string,
853 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -0700854 values;
855 message.read(objectName, values);
James Feist918e18c2018-02-13 15:51:07 -0800856 auto findPgood = values.find("pgood");
857 if (findPgood != values.end())
858 {
James Feist6ebf9de2018-05-15 15:01:17 -0700859
860 rescanBusses(io, busmap, dbusInterfaceMap, systemBus,
861 objServer);
James Feist918e18c2018-02-13 15:51:07 -0800862 }
James Feist918e18c2018-02-13 15:51:07 -0800863 };
James Feist9eb0b582018-04-27 12:15:46 -0700864
865 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -0800866 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -0700867 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
868 "openbmc_project/Chassis/Control/"
869 "Power0',arg0='xyz.openbmc_project.Chassis.Control.Power'",
James Feist9eb0b582018-04-27 12:15:46 -0700870 eventHandler);
871
James Feist4131aea2018-03-09 09:47:30 -0800872 int fd = inotify_init();
James Feist0eb40352019-04-09 14:44:04 -0700873 inotify_add_watch(fd, I2C_DEV_LOCATION,
874 IN_CREATE | IN_MOVED_TO | IN_DELETE);
James Feist4131aea2018-03-09 09:47:30 -0800875 std::array<char, 4096> readBuffer;
876 std::string pendingBuffer;
877 // monitor for new i2c devices
878 boost::asio::posix::stream_descriptor dirWatch(io, fd);
879 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -0800880 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -0800881 std::size_t bytes_transferred) {
882 if (ec)
883 {
884 std::cout << "Callback Error " << ec << "\n";
885 return;
886 }
887 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
888 bool devChange = false;
889 while (pendingBuffer.size() > sizeof(inotify_event))
890 {
James Feista465ccc2019-02-08 12:51:01 -0800891 const inotify_event* iEvent =
892 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -0800893 pendingBuffer.data());
894 switch (iEvent->mask)
895 {
James Feist9eb0b582018-04-27 12:15:46 -0700896 case IN_CREATE:
897 case IN_MOVED_TO:
898 case IN_DELETE:
899 if (boost::starts_with(std::string(iEvent->name),
900 "i2c"))
901 {
902 devChange = true;
903 }
James Feist4131aea2018-03-09 09:47:30 -0800904 }
905
906 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
907 }
James Feist6ebf9de2018-05-15 15:01:17 -0700908 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -0800909 {
James Feist6ebf9de2018-05-15 15:01:17 -0700910 rescanBusses(io, busmap, dbusInterfaceMap, systemBus,
911 objServer);
James Feist4131aea2018-03-09 09:47:30 -0800912 }
James Feist6ebf9de2018-05-15 15:01:17 -0700913
James Feist4131aea2018-03-09 09:47:30 -0800914 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
915 watchI2cBusses);
916 };
917
918 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -0500919 // run the initial scan
James Feist6ebf9de2018-05-15 15:01:17 -0700920 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feist918e18c2018-02-13 15:51:07 -0800921
James Feist3cb5fec2018-01-23 14:41:51 -0800922 io.run();
923 return 0;
924}