blob: b98615d2f90f16166e93cd66f0f9f80d7d9cd391 [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 Feist6ebf9de2018-05-15 15:01:17 -070059struct FindDevicesWithCallback;
60
James Feistc95cb142018-02-26 10:41:42 -080061static bool isMuxBus(size_t bus)
62{
Ed Tanous072e25d2018-12-16 21:45:20 -080063 return is_symlink(std::filesystem::path(
James Feistc95cb142018-02-26 10:41:42 -080064 "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
65}
66
Vijay Khemka2d681f62018-11-06 15:51:00 -080067static int isDevice16Bit(int file)
68{
69 /* Get first byte */
70 int byte1 = i2c_smbus_read_byte_data(file, 0);
71 if (byte1 < 0)
72 {
73 return byte1;
74 }
75 /* Read 7 more bytes, it will read same first byte in case of
76 * 8 bit but it will read next byte in case of 16 bit
77 */
78 for (int i = 0; i < 7; i++)
79 {
80 int byte2 = i2c_smbus_read_byte_data(file, 0);
81 if (byte2 < 0)
82 {
83 return byte2;
84 }
85 if (byte2 != byte1)
86 {
87 return 1;
88 }
89 }
90 return 0;
91}
92
93static int read_block_data(int flag, int file, uint16_t offset, uint8_t len,
James Feista465ccc2019-02-08 12:51:01 -080094 uint8_t* buf)
Vijay Khemka2d681f62018-11-06 15:51:00 -080095{
96 uint8_t low_addr = offset & 0xFF;
97 uint8_t high_addr = (offset >> 8) & 0xFF;
98
99 if (flag == 0)
100 {
101 return i2c_smbus_read_i2c_block_data(file, low_addr, len, buf);
102 }
103
104 /* This is for 16 bit addressing EEPROM device. First an offset
105 * needs to be written before read data from a offset
106 */
107 int ret = i2c_smbus_write_byte_data(file, 0, low_addr);
108 if (ret < 0)
109 {
110 return ret;
111 }
112
113 return i2c_smbus_read_i2c_block_data(file, high_addr, len, buf);
114}
115
James Feist24bae7a2019-04-03 09:50:56 -0700116bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
117{
118 // ipmi spec format version number is currently at 1, verify it
119 if (blockData[0] != 0x1)
120 {
121 return false;
122 }
123
124 // verify pad is set to 0
125 if (blockData[6] != 0x0)
126 {
127 return false;
128 }
129
130 // verify offsets are 0, or don't point to another offset
131 std::set<uint8_t> foundOffsets;
132 for (int ii = 1; ii < 6; ii++)
133 {
134 if (blockData[ii] == 0)
135 {
136 continue;
137 }
138 auto [_, inserted] = foundOffsets.insert(blockData[ii]);
139 if (!inserted)
140 {
141 return false;
142 }
143 }
144
145 // validate checksum
146 size_t sum = 0;
147 for (int jj = 0; jj < 7; jj++)
148 {
149 sum += blockData[jj];
150 }
151 sum = (256 - sum) & 0xFF;
152
153 if (sum != blockData[7])
154 {
155 return false;
156 }
157 return true;
158}
159
James Feist3cb5fec2018-01-23 14:41:51 -0800160int get_bus_frus(int file, int first, int last, int bus,
161 std::shared_ptr<DeviceMap> devices)
162{
James Feist3cb5fec2018-01-23 14:41:51 -0800163
James Feist26c27ad2018-07-25 15:09:40 -0700164 std::future<int> future = std::async(std::launch::async, [&]() {
165 std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> block_data;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800166
James Feist26c27ad2018-07-25 15:09:40 -0700167 for (int ii = first; ii <= last; ii++)
James Feist3cb5fec2018-01-23 14:41:51 -0800168 {
James Feist3cb5fec2018-01-23 14:41:51 -0800169
James Feist26c27ad2018-07-25 15:09:40 -0700170 // Set slave address
171 if (ioctl(file, I2C_SLAVE_FORCE, ii) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800172 {
James Feist26c27ad2018-07-25 15:09:40 -0700173 std::cerr << "device at bus " << bus << "register " << ii
174 << "busy\n";
175 continue;
176 }
177 // probe
178 else if (i2c_smbus_read_byte(file) < 0)
179 {
180 continue;
181 }
James Feist3cb5fec2018-01-23 14:41:51 -0800182
James Feist26c27ad2018-07-25 15:09:40 -0700183 if (DEBUG)
184 {
185 std::cout << "something at bus " << bus << "addr " << ii
186 << "\n";
187 }
Vijay Khemka2d681f62018-11-06 15:51:00 -0800188
189 /* Check for Device type if it is 8 bit or 16 bit */
190 int flag = isDevice16Bit(file);
191 if (flag < 0)
192 {
193 std::cerr << "failed to read bus " << bus << " address " << ii
194 << "\n";
195 continue;
196 }
197
198 if (read_block_data(flag, file, 0x0, 0x8, block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700199 {
200 std::cerr << "failed to read bus " << bus << " address " << ii
201 << "\n";
202 continue;
203 }
James Feist26c27ad2018-07-25 15:09:40 -0700204
205 // check the header checksum
James Feist24bae7a2019-04-03 09:50:56 -0700206 if (validateHeader(block_data))
James Feist26c27ad2018-07-25 15:09:40 -0700207 {
208 std::vector<char> device;
209 device.insert(device.end(), block_data.begin(),
210 block_data.begin() + 8);
211
212 for (int jj = 1; jj <= FRU_AREAS.size(); jj++)
213 {
214 auto area_offset = device[jj];
215 if (area_offset != 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800216 {
James Feist26c27ad2018-07-25 15:09:40 -0700217 area_offset *= 8;
Vijay Khemka2d681f62018-11-06 15:51:00 -0800218 if (read_block_data(flag, file, area_offset, 0x8,
219 block_data.data()) < 0)
James Feist3cb5fec2018-01-23 14:41:51 -0800220 {
221 std::cerr << "failed to read bus " << bus
222 << " address " << ii << "\n";
223 return -1;
224 }
James Feist26c27ad2018-07-25 15:09:40 -0700225 int length = block_data[1] * 8;
James Feist3cb5fec2018-01-23 14:41:51 -0800226 device.insert(device.end(), block_data.begin(),
James Feist26c27ad2018-07-25 15:09:40 -0700227 block_data.begin() + 8);
228 length -= 8;
229 area_offset += 8;
230
231 while (length > 0)
232 {
233 auto to_get = std::min(0x20, length);
Vijay Khemka2d681f62018-11-06 15:51:00 -0800234 if (read_block_data(flag, file, area_offset, to_get,
235 block_data.data()) < 0)
James Feist26c27ad2018-07-25 15:09:40 -0700236 {
237 std::cerr << "failed to read bus " << bus
238 << " address " << ii << "\n";
239 return -1;
240 }
241 device.insert(device.end(), block_data.begin(),
242 block_data.begin() + to_get);
243 area_offset += to_get;
244 length -= to_get;
245 }
James Feist3cb5fec2018-01-23 14:41:51 -0800246 }
247 }
James Feist26c27ad2018-07-25 15:09:40 -0700248 devices->emplace(ii, device);
James Feist3cb5fec2018-01-23 14:41:51 -0800249 }
James Feist24bae7a2019-04-03 09:50:56 -0700250 else if (DEBUG)
James Feist9945ddf2019-03-07 13:57:36 -0800251 {
James Feist24bae7a2019-04-03 09:50:56 -0700252 std::cerr << "Illegal header at bus " << bus << " address "
253 << ii << "\n";
James Feist9945ddf2019-03-07 13:57:36 -0800254 }
James Feist3cb5fec2018-01-23 14:41:51 -0800255 }
James Feist26c27ad2018-07-25 15:09:40 -0700256 return 1;
257 });
258 std::future_status status =
259 future.wait_for(std::chrono::seconds(busTimeoutSeconds));
260 if (status == std::future_status::timeout)
261 {
262 std::cerr << "Error reading bus " << bus << "\n";
263 return -1;
James Feist3cb5fec2018-01-23 14:41:51 -0800264 }
265
James Feist26c27ad2018-07-25 15:09:40 -0700266 return future.get();
James Feist3cb5fec2018-01-23 14:41:51 -0800267}
268
James Feista465ccc2019-02-08 12:51:01 -0800269static void FindI2CDevices(const std::vector<fs::path>& i2cBuses,
James Feist6ebf9de2018-05-15 15:01:17 -0700270 std::shared_ptr<FindDevicesWithCallback> context,
James Feista465ccc2019-02-08 12:51:01 -0800271 boost::asio::io_service& io, BusMap& busMap)
James Feist3cb5fec2018-01-23 14:41:51 -0800272{
James Feista465ccc2019-02-08 12:51:01 -0800273 for (auto& i2cBus : i2cBuses)
James Feist3cb5fec2018-01-23 14:41:51 -0800274 {
275 auto busnum = i2cBus.string();
276 auto lastDash = busnum.rfind(std::string("-"));
277 // delete everything before dash inclusive
278 if (lastDash != std::string::npos)
279 {
280 busnum.erase(0, lastDash + 1);
281 }
282 auto bus = std::stoi(busnum);
283
284 auto file = open(i2cBus.c_str(), O_RDWR);
285 if (file < 0)
286 {
287 std::cerr << "unable to open i2c device " << i2cBus.string()
288 << "\n";
289 continue;
290 }
291 unsigned long funcs = 0;
292
293 if (ioctl(file, I2C_FUNCS, &funcs) < 0)
294 {
295 std::cerr
296 << "Error: Could not get the adapter functionality matrix bus"
297 << bus << "\n";
298 continue;
299 }
300 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE) ||
301 !(I2C_FUNC_SMBUS_READ_I2C_BLOCK))
302 {
303 std::cerr << "Error: Can't use SMBus Receive Byte command bus "
304 << bus << "\n";
305 continue;
306 }
James Feista465ccc2019-02-08 12:51:01 -0800307 auto& device = busMap[bus];
James Feist3cb5fec2018-01-23 14:41:51 -0800308 device = std::make_shared<DeviceMap>();
309
James Feistc95cb142018-02-26 10:41:42 -0800310 // don't scan muxed buses async as don't want to confuse the mux
311 if (isMuxBus(bus))
312 {
313 get_bus_frus(file, 0x03, 0x77, bus, device);
314 close(file);
315 }
316 else
317 {
James Feist6ebf9de2018-05-15 15:01:17 -0700318 io.post([file, device, bus, context] {
319 // i2cdetect by default uses the range 0x03 to 0x77, as
320 // this is
321 // what we
322 // have tested with, use this range. Could be changed in
323 // future.
324 get_bus_frus(file, 0x03, 0x77, bus, device);
325 close(file);
326 });
James Feistc95cb142018-02-26 10:41:42 -0800327 }
James Feist3cb5fec2018-01-23 14:41:51 -0800328 }
James Feist3cb5fec2018-01-23 14:41:51 -0800329}
330
James Feist6ebf9de2018-05-15 15:01:17 -0700331// this class allows an async response after all i2c devices are discovered
332struct FindDevicesWithCallback
333 : std::enable_shared_from_this<FindDevicesWithCallback>
334{
James Feista465ccc2019-02-08 12:51:01 -0800335 FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
336 boost::asio::io_service& io, BusMap& busMap,
337 std::function<void(void)>&& callback) :
James Feist6ebf9de2018-05-15 15:01:17 -0700338 _i2cBuses(i2cBuses),
339 _io(io), _busMap(busMap), _callback(std::move(callback))
340 {
341 }
342 ~FindDevicesWithCallback()
343 {
344 _callback();
345 }
346 void run()
347 {
348 FindI2CDevices(_i2cBuses, shared_from_this(), _io, _busMap);
349 }
350
James Feista465ccc2019-02-08 12:51:01 -0800351 const std::vector<fs::path>& _i2cBuses;
352 boost::asio::io_service& _io;
353 BusMap& _busMap;
James Feist6ebf9de2018-05-15 15:01:17 -0700354 std::function<void(void)> _callback;
355};
356
James Feist3cb5fec2018-01-23 14:41:51 -0800357static const std::tm intelEpoch(void)
358{
359 std::tm val = {0};
360 val.tm_year = 1996 - 1900;
361 return val;
362}
363
James Feista465ccc2019-02-08 12:51:01 -0800364bool formatFru(const std::vector<char>& fruBytes,
365 boost::container::flat_map<std::string, std::string>& result)
James Feist3cb5fec2018-01-23 14:41:51 -0800366{
James Feista465ccc2019-02-08 12:51:01 -0800367 static const std::vector<const char*> CHASSIS_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800368 "PART_NUMBER", "SERIAL_NUMBER", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800369
James Feista465ccc2019-02-08 12:51:01 -0800370 static const std::vector<const char*> BOARD_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800371 "MANUFACTURER", "PRODUCT_NAME", "SERIAL_NUMBER", "PART_NUMBER",
372 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800373
James Feista465ccc2019-02-08 12:51:01 -0800374 static const std::vector<const char*> PRODUCT_FRU_AREAS = {
Vijay Khemka5d5de442018-11-07 10:51:25 -0800375 "MANUFACTURER", "PRODUCT_NAME", "PART_NUMBER",
376 "VERSION", "SERIAL_NUMBER", "ASSET_TAG",
377 "FRU_VERSION_ID", "INFO_AM1", "INFO_AM2"};
James Feist3cb5fec2018-01-23 14:41:51 -0800378
379 size_t sum = 0;
380
James Feistd068e932018-09-20 10:53:07 -0700381 if (fruBytes.size() <= 8)
James Feist3cb5fec2018-01-23 14:41:51 -0800382 {
383 return false;
384 }
385 std::vector<char>::const_iterator fruAreaOffsetField = fruBytes.begin();
James Feist9eb0b582018-04-27 12:15:46 -0700386 result["Common_Format_Version"] =
James Feist3cb5fec2018-01-23 14:41:51 -0800387 std::to_string(static_cast<int>(*fruAreaOffsetField));
388
James Feista465ccc2019-02-08 12:51:01 -0800389 const std::vector<const char*>* fieldData;
James Feist3cb5fec2018-01-23 14:41:51 -0800390
James Feista465ccc2019-02-08 12:51:01 -0800391 for (auto& area : FRU_AREAS)
James Feist3cb5fec2018-01-23 14:41:51 -0800392 {
393 fruAreaOffsetField++;
394 if (fruAreaOffsetField >= fruBytes.end())
395 {
396 return false;
397 }
398 size_t offset = (*fruAreaOffsetField) * 8;
399
400 if (offset > 1)
401 {
402 // +2 to skip format and length
403 std::vector<char>::const_iterator fruBytesIter =
404 fruBytes.begin() + offset + 2;
405
406 if (fruBytesIter >= fruBytes.end())
407 {
408 return false;
409 }
410
411 if (area == "CHASSIS")
412 {
413 result["CHASSIS_TYPE"] =
414 std::to_string(static_cast<int>(*fruBytesIter));
415 fruBytesIter += 1;
416 fieldData = &CHASSIS_FRU_AREAS;
417 }
418 else if (area == "BOARD")
419 {
420 result["BOARD_LANGUAGE_CODE"] =
421 std::to_string(static_cast<int>(*fruBytesIter));
422 fruBytesIter += 1;
423 if (fruBytesIter >= fruBytes.end())
424 {
425 return false;
426 }
427
428 unsigned int minutes = *fruBytesIter |
429 *(fruBytesIter + 1) << 8 |
430 *(fruBytesIter + 2) << 16;
431 std::tm fruTime = intelEpoch();
432 time_t timeValue = mktime(&fruTime);
433 timeValue += minutes * 60;
434 fruTime = *gmtime(&timeValue);
435
436 result["BOARD_MANUFACTURE_DATE"] = asctime(&fruTime);
437 result["BOARD_MANUFACTURE_DATE"]
438 .pop_back(); // remove trailing null
439 fruBytesIter += 3;
440 fieldData = &BOARD_FRU_AREAS;
441 }
442 else if (area == "PRODUCT")
443 {
444 result["PRODUCT_LANGUAGE_CODE"] =
445 std::to_string(static_cast<int>(*fruBytesIter));
446 fruBytesIter += 1;
447 fieldData = &PRODUCT_FRU_AREAS;
448 }
449 else
450 {
451 continue;
452 }
James Feista465ccc2019-02-08 12:51:01 -0800453 for (auto& field : *fieldData)
James Feist3cb5fec2018-01-23 14:41:51 -0800454 {
455 if (fruBytesIter >= fruBytes.end())
456 {
457 return false;
458 }
459
Vijay Khemka5d5de442018-11-07 10:51:25 -0800460 /* Checking for last byte C1 to indicate that no more
461 * field to be read */
Ed Tanous2147e672019-02-27 13:59:56 -0800462 if (*fruBytesIter == 0xC1)
Vijay Khemka5d5de442018-11-07 10:51:25 -0800463 {
464 break;
465 }
466
Ed Tanous2147e672019-02-27 13:59:56 -0800467 size_t length = *fruBytesIter & 0x3f;
468 fruBytesIter += 1;
469
James Feist3cb5fec2018-01-23 14:41:51 -0800470 if (fruBytesIter >= fruBytes.end())
471 {
472 return false;
473 }
Ed Tanous2147e672019-02-27 13:59:56 -0800474 std::string value(fruBytesIter, fruBytesIter + length);
James Feist3cb5fec2018-01-23 14:41:51 -0800475
Ed Tanous2147e672019-02-27 13:59:56 -0800476 // Strip non null characters from the end
477 value.erase(std::find_if(value.rbegin(), value.rend(),
478 [](char ch) { return ch != 0; })
479 .base(),
480 value.end());
481
482 result[std::string(area) + "_" + field] = std::move(value);
483
James Feist3cb5fec2018-01-23 14:41:51 -0800484 fruBytesIter += length;
485 if (fruBytesIter >= fruBytes.end())
486 {
487 std::cerr << "Warning Fru Length Mismatch:\n ";
James Feista465ccc2019-02-08 12:51:01 -0800488 for (auto& c : fruBytes)
James Feist3cb5fec2018-01-23 14:41:51 -0800489 {
490 std::cerr << c;
491 }
492 std::cerr << "\n";
493 if (DEBUG)
494 {
James Feista465ccc2019-02-08 12:51:01 -0800495 for (auto& keyPair : result)
James Feist3cb5fec2018-01-23 14:41:51 -0800496 {
497 std::cerr << keyPair.first << " : "
498 << keyPair.second << "\n";
499 }
500 }
501 return false;
502 }
503 }
504 }
505 }
506
507 return true;
508}
509
510void AddFruObjectToDbus(
James Feist9eb0b582018-04-27 12:15:46 -0700511 std::shared_ptr<sdbusplus::asio::connection> dbusConn,
James Feista465ccc2019-02-08 12:51:01 -0800512 std::vector<char>& device, sdbusplus::asio::object_server& objServer,
513 boost::container::flat_map<
514 std::pair<size_t, size_t>,
515 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
James Feist13b86d62018-05-29 11:24:35 -0700516 uint32_t bus, uint32_t address)
James Feist3cb5fec2018-01-23 14:41:51 -0800517{
518 boost::container::flat_map<std::string, std::string> formattedFru;
519 if (!formatFru(device, formattedFru))
520 {
521 std::cerr << "failed to format fru for device at bus " << std::hex
522 << bus << "address " << address << "\n";
523 return;
524 }
525 auto productNameFind = formattedFru.find("BOARD_PRODUCT_NAME");
526 std::string productName;
527 if (productNameFind == formattedFru.end())
528 {
529 productNameFind = formattedFru.find("PRODUCT_PRODUCT_NAME");
530 }
531 if (productNameFind != formattedFru.end())
532 {
533 productName = productNameFind->second;
James Feist3f8a2782018-02-12 09:24:42 -0800534 std::regex illegalObject("[^A-Za-z0-9_]");
535 productName = std::regex_replace(productName, illegalObject, "_");
James Feist3cb5fec2018-01-23 14:41:51 -0800536 }
537 else
538 {
539 productName = "UNKNOWN" + std::to_string(UNKNOWN_BUS_OBJECT_COUNT);
540 UNKNOWN_BUS_OBJECT_COUNT++;
541 }
542
James Feist918e18c2018-02-13 15:51:07 -0800543 productName = "/xyz/openbmc_project/FruDevice/" + productName;
James Feist918e18c2018-02-13 15:51:07 -0800544 // avoid duplicates by checking to see if on a mux
James Feist79e9c0b2018-03-15 15:21:17 -0700545 if (bus > 0)
James Feist918e18c2018-02-13 15:51:07 -0800546 {
James Feist79e9c0b2018-03-15 15:21:17 -0700547 size_t index = 0;
James Feista465ccc2019-02-08 12:51:01 -0800548 for (auto const& busIface : dbusInterfaceMap)
James Feist918e18c2018-02-13 15:51:07 -0800549 {
James Feist9eb0b582018-04-27 12:15:46 -0700550 if ((busIface.second->get_object_path() == productName))
James Feist918e18c2018-02-13 15:51:07 -0800551 {
James Feist9eb0b582018-04-27 12:15:46 -0700552 if (isMuxBus(bus) && address == busIface.first.second)
James Feist79e9c0b2018-03-15 15:21:17 -0700553 {
554 continue;
555 }
556 // add underscore _index for the same object path on dbus
557 std::string strIndex = std::to_string(index);
558 if (index > 0)
559 {
560 productName.substr(0, productName.size() - strIndex.size());
561 }
562 else
563 {
564 productName += "_";
565 }
566 productName += std::to_string(index++);
James Feist918e18c2018-02-13 15:51:07 -0800567 }
568 }
569 }
James Feist3cb5fec2018-01-23 14:41:51 -0800570
James Feist9eb0b582018-04-27 12:15:46 -0700571 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
572 objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
573 dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
574
James Feista465ccc2019-02-08 12:51:01 -0800575 for (auto& property : formattedFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800576 {
James Feist9eb0b582018-04-27 12:15:46 -0700577
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700578 std::regex_replace(property.second.begin(), property.second.begin(),
579 property.second.end(), NON_ASCII_REGEX, "_");
James Feist9eb0b582018-04-27 12:15:46 -0700580 if (property.second.empty())
581 {
582 continue;
583 }
584 std::string key =
585 std::regex_replace(property.first, NON_ASCII_REGEX, "_");
586 if (!iface->register_property(key, property.second + '\0'))
587 {
588 std::cerr << "illegal key: " << key << "\n";
589 }
Jae Hyun Yoo3936e7a2018-03-23 17:26:16 -0700590 if (DEBUG)
591 {
592 std::cout << property.first << ": " << property.second << "\n";
593 }
James Feist3cb5fec2018-01-23 14:41:51 -0800594 }
James Feist2a9d6db2018-04-27 15:48:28 -0700595
596 // baseboard will be 0, 0
James Feist13b86d62018-05-29 11:24:35 -0700597 iface->register_property("BUS", bus);
598 iface->register_property("ADDRESS", address);
James Feist2a9d6db2018-04-27 15:48:28 -0700599
James Feist9eb0b582018-04-27 12:15:46 -0700600 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800601}
602
James Feista465ccc2019-02-08 12:51:01 -0800603static bool readBaseboardFru(std::vector<char>& baseboardFru)
James Feist3cb5fec2018-01-23 14:41:51 -0800604{
605 // try to read baseboard fru from file
606 std::ifstream baseboardFruFile(BASEBOARD_FRU_LOCATION, std::ios::binary);
607 if (baseboardFruFile.good())
608 {
609 baseboardFruFile.seekg(0, std::ios_base::end);
610 std::streampos fileSize = baseboardFruFile.tellg();
611 baseboardFru.resize(fileSize);
612 baseboardFruFile.seekg(0, std::ios_base::beg);
613 baseboardFruFile.read(baseboardFru.data(), fileSize);
614 }
615 else
616 {
617 return false;
618 }
619 return true;
620}
621
James Feista465ccc2019-02-08 12:51:01 -0800622bool writeFru(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
James Feistb49ffc32018-05-02 11:10:43 -0700623{
624 boost::container::flat_map<std::string, std::string> tmp;
625 if (fru.size() > MAX_FRU_SIZE)
626 {
627 std::cerr << "Invalid fru.size() during writeFru\n";
628 return false;
629 }
630 // verify legal fru by running it through fru parsing logic
James Feista465ccc2019-02-08 12:51:01 -0800631 if (!formatFru(reinterpret_cast<const std::vector<char>&>(fru), tmp))
James Feistb49ffc32018-05-02 11:10:43 -0700632 {
633 std::cerr << "Invalid fru format during writeFru\n";
634 return false;
635 }
636 // baseboard fru
637 if (bus == 0 && address == 0)
638 {
639 std::ofstream file(BASEBOARD_FRU_LOCATION, std::ios_base::binary);
640 if (!file.good())
641 {
642 std::cerr << "Error opening file " << BASEBOARD_FRU_LOCATION
643 << "\n";
James Feistddb78302018-09-06 11:45:42 -0700644 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700645 return false;
646 }
James Feista465ccc2019-02-08 12:51:01 -0800647 file.write(reinterpret_cast<const char*>(fru.data()), fru.size());
James Feistb49ffc32018-05-02 11:10:43 -0700648 return file.good();
649 }
650 else
651 {
652 std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
653
654 int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
655 if (file < 0)
656 {
657 std::cerr << "unable to open i2c device " << i2cBus << "\n";
James Feistddb78302018-09-06 11:45:42 -0700658 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700659 return false;
660 }
661 if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
662 {
663 std::cerr << "unable to set device address\n";
664 close(file);
James Feistddb78302018-09-06 11:45:42 -0700665 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700666 return false;
667 }
668
669 constexpr const size_t RETRY_MAX = 2;
670 uint16_t index = 0;
671 size_t retries = RETRY_MAX;
672 while (index < fru.size())
673 {
674 if ((index && ((index % (MAX_EEPROM_PAGE_INDEX + 1)) == 0)) &&
675 (retries == RETRY_MAX))
676 {
677 // The 4K EEPROM only uses the A2 and A1 device address bits
678 // with the third bit being a memory page address bit.
679 if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
680 {
681 std::cerr << "unable to set device address\n";
682 close(file);
James Feistddb78302018-09-06 11:45:42 -0700683 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700684 return false;
685 }
686 }
687
688 if (i2c_smbus_write_byte_data(file, index & 0xFF, fru[index]) < 0)
689 {
690 if (!retries--)
691 {
692 std::cerr << "error writing fru: " << strerror(errno)
693 << "\n";
694 close(file);
James Feistddb78302018-09-06 11:45:42 -0700695 throw DBusInternalError();
James Feistb49ffc32018-05-02 11:10:43 -0700696 return false;
697 }
698 }
699 else
700 {
701 retries = RETRY_MAX;
702 index++;
703 }
704 // most eeproms require 5-10ms between writes
705 std::this_thread::sleep_for(std::chrono::milliseconds(10));
706 }
707 close(file);
708 return true;
709 }
710}
711
James Feist9eb0b582018-04-27 12:15:46 -0700712void rescanBusses(
James Feista465ccc2019-02-08 12:51:01 -0800713 boost::asio::io_service& io, BusMap& busMap,
714 boost::container::flat_map<
715 std::pair<size_t, size_t>,
716 std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
717 std::shared_ptr<sdbusplus::asio::connection>& systemBus,
718 sdbusplus::asio::object_server& objServer)
James Feist918e18c2018-02-13 15:51:07 -0800719{
James Feist6ebf9de2018-05-15 15:01:17 -0700720 static boost::asio::deadline_timer timer(io);
721 timer.expires_from_now(boost::posix_time::seconds(1));
James Feist918e18c2018-02-13 15:51:07 -0800722
Gunnar Mills6f0ae942018-08-31 12:38:03 -0500723 // setup an async wait in case we get flooded with requests
James Feista465ccc2019-02-08 12:51:01 -0800724 timer.async_wait([&](const boost::system::error_code& ec) {
James Feist4131aea2018-03-09 09:47:30 -0800725 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -0800726 auto matchString = std::string(R"(i2c-\d+$)");
James Feist4131aea2018-03-09 09:47:30 -0800727 std::vector<fs::path> i2cBuses;
James Feist918e18c2018-02-13 15:51:07 -0800728
James Feista3c180a2018-08-09 16:06:04 -0700729 if (!findFiles(devDir, matchString, i2cBuses))
James Feist918e18c2018-02-13 15:51:07 -0800730 {
James Feist4131aea2018-03-09 09:47:30 -0800731 std::cerr << "unable to find i2c devices\n";
732 return;
James Feist918e18c2018-02-13 15:51:07 -0800733 }
James Feist4131aea2018-03-09 09:47:30 -0800734 // scanning muxes in reverse order seems to have adverse effects
735 // sorting this list seems to be a fix for that
736 std::sort(i2cBuses.begin(), i2cBuses.end());
James Feist4131aea2018-03-09 09:47:30 -0800737
James Feist6ebf9de2018-05-15 15:01:17 -0700738 busMap.clear();
739 auto scan = std::make_shared<FindDevicesWithCallback>(
740 i2cBuses, io, busMap, [&]() {
James Feista465ccc2019-02-08 12:51:01 -0800741 for (auto& busIface : dbusInterfaceMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700742 {
743 objServer.remove_interface(busIface.second);
744 }
James Feist4131aea2018-03-09 09:47:30 -0800745
James Feist6ebf9de2018-05-15 15:01:17 -0700746 dbusInterfaceMap.clear();
747 UNKNOWN_BUS_OBJECT_COUNT = 0;
James Feist4131aea2018-03-09 09:47:30 -0800748
James Feist6ebf9de2018-05-15 15:01:17 -0700749 // todo, get this from a more sensable place
750 std::vector<char> baseboardFru;
751 if (readBaseboardFru(baseboardFru))
752 {
753 boost::container::flat_map<int, std::vector<char>>
754 baseboardDev;
755 baseboardDev.emplace(0, baseboardFru);
756 busMap[0] = std::make_shared<DeviceMap>(baseboardDev);
757 }
James Feista465ccc2019-02-08 12:51:01 -0800758 for (auto& devicemap : busMap)
James Feist6ebf9de2018-05-15 15:01:17 -0700759 {
James Feista465ccc2019-02-08 12:51:01 -0800760 for (auto& device : *devicemap.second)
James Feist6ebf9de2018-05-15 15:01:17 -0700761 {
762 AddFruObjectToDbus(systemBus, device.second, objServer,
763 dbusInterfaceMap, devicemap.first,
764 device.first);
765 }
766 }
767 });
768 scan->run();
769 });
James Feist918e18c2018-02-13 15:51:07 -0800770}
771
James Feista465ccc2019-02-08 12:51:01 -0800772int main(int argc, char** argv)
James Feist3cb5fec2018-01-23 14:41:51 -0800773{
774 auto devDir = fs::path("/dev/");
James Feistc9dff1b2019-02-13 13:33:13 -0800775 auto matchString = std::string(R"(i2c-\d+$)");
James Feist3cb5fec2018-01-23 14:41:51 -0800776 std::vector<fs::path> i2cBuses;
777
James Feista3c180a2018-08-09 16:06:04 -0700778 if (!findFiles(devDir, matchString, i2cBuses))
James Feist3cb5fec2018-01-23 14:41:51 -0800779 {
780 std::cerr << "unable to find i2c devices\n";
781 return 1;
782 }
James Feist3cb5fec2018-01-23 14:41:51 -0800783
784 boost::asio::io_service io;
James Feist9eb0b582018-04-27 12:15:46 -0700785 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
786 auto objServer = sdbusplus::asio::object_server(systemBus);
Vijay Khemka065f6d92018-12-18 10:37:47 -0800787 systemBus->request_name("xyz.openbmc_project.FruDevice");
James Feist3cb5fec2018-01-23 14:41:51 -0800788
James Feist6ebf9de2018-05-15 15:01:17 -0700789 // this is a map with keys of pair(bus number, address) and values of
790 // the object on dbus
James Feist3cb5fec2018-01-23 14:41:51 -0800791 boost::container::flat_map<std::pair<size_t, size_t>,
James Feist9eb0b582018-04-27 12:15:46 -0700792 std::shared_ptr<sdbusplus::asio::dbus_interface>>
793 dbusInterfaceMap;
James Feist2a9d6db2018-04-27 15:48:28 -0700794 BusMap busmap;
James Feist3cb5fec2018-01-23 14:41:51 -0800795
James Feist9eb0b582018-04-27 12:15:46 -0700796 std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
797 objServer.add_interface("/xyz/openbmc_project/FruDevice",
798 "xyz.openbmc_project.FruDeviceManager");
James Feist3cb5fec2018-01-23 14:41:51 -0800799
800 iface->register_method("ReScan", [&]() {
James Feist6ebf9de2018-05-15 15:01:17 -0700801 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feist3cb5fec2018-01-23 14:41:51 -0800802 });
James Feist2a9d6db2018-04-27 15:48:28 -0700803
804 iface->register_method(
James Feista465ccc2019-02-08 12:51:01 -0800805 "GetRawFru", [&](const uint8_t& bus, const uint8_t& address) {
James Feist2a9d6db2018-04-27 15:48:28 -0700806 auto deviceMap = busmap.find(bus);
807 if (deviceMap == busmap.end())
808 {
James Feistddb78302018-09-06 11:45:42 -0700809 throw std::invalid_argument("Invalid Bus.");
James Feist2a9d6db2018-04-27 15:48:28 -0700810 }
811 auto device = deviceMap->second->find(address);
812 if (device == deviceMap->second->end())
813 {
James Feistddb78302018-09-06 11:45:42 -0700814 throw std::invalid_argument("Invalid Address.");
James Feist2a9d6db2018-04-27 15:48:28 -0700815 }
James Feista465ccc2019-02-08 12:51:01 -0800816 std::vector<uint8_t>& ret =
817 reinterpret_cast<std::vector<uint8_t>&>(device->second);
James Feist2a9d6db2018-04-27 15:48:28 -0700818 return ret;
819 });
James Feistb49ffc32018-05-02 11:10:43 -0700820
821 iface->register_method("WriteFru", [&](const uint8_t bus,
822 const uint8_t address,
James Feista465ccc2019-02-08 12:51:01 -0800823 const std::vector<uint8_t>& data) {
James Feistb49ffc32018-05-02 11:10:43 -0700824 if (!writeFru(bus, address, data))
825 {
James Feistddb78302018-09-06 11:45:42 -0700826 throw std::invalid_argument("Invalid Arguments.");
James Feistb49ffc32018-05-02 11:10:43 -0700827 return;
828 }
829 // schedule rescan on success
830 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feistb49ffc32018-05-02 11:10:43 -0700831 });
James Feist9eb0b582018-04-27 12:15:46 -0700832 iface->initialize();
James Feist3cb5fec2018-01-23 14:41:51 -0800833
James Feist9eb0b582018-04-27 12:15:46 -0700834 std::function<void(sdbusplus::message::message & message)> eventHandler =
James Feista465ccc2019-02-08 12:51:01 -0800835 [&](sdbusplus::message::message& message) {
James Feist918e18c2018-02-13 15:51:07 -0800836 std::string objectName;
James Feist9eb0b582018-04-27 12:15:46 -0700837 boost::container::flat_map<
James Feista465ccc2019-02-08 12:51:01 -0800838 std::string,
839 std::variant<std::string, bool, int64_t, uint64_t, double>>
James Feist9eb0b582018-04-27 12:15:46 -0700840 values;
841 message.read(objectName, values);
James Feist918e18c2018-02-13 15:51:07 -0800842 auto findPgood = values.find("pgood");
843 if (findPgood != values.end())
844 {
James Feist6ebf9de2018-05-15 15:01:17 -0700845
846 rescanBusses(io, busmap, dbusInterfaceMap, systemBus,
847 objServer);
James Feist918e18c2018-02-13 15:51:07 -0800848 }
James Feist918e18c2018-02-13 15:51:07 -0800849 };
James Feist9eb0b582018-04-27 12:15:46 -0700850
851 sdbusplus::bus::match::match powerMatch = sdbusplus::bus::match::match(
James Feista465ccc2019-02-08 12:51:01 -0800852 static_cast<sdbusplus::bus::bus&>(*systemBus),
James Feist7bcd3f22019-03-18 16:04:04 -0700853 "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
854 "openbmc_project/Chassis/Control/"
855 "Power0',arg0='xyz.openbmc_project.Chassis.Control.Power'",
James Feist9eb0b582018-04-27 12:15:46 -0700856 eventHandler);
857
James Feist4131aea2018-03-09 09:47:30 -0800858 int fd = inotify_init();
859 int wd = inotify_add_watch(fd, I2C_DEV_LOCATION,
860 IN_CREATE | IN_MOVED_TO | IN_DELETE);
861 std::array<char, 4096> readBuffer;
862 std::string pendingBuffer;
863 // monitor for new i2c devices
864 boost::asio::posix::stream_descriptor dirWatch(io, fd);
865 std::function<void(const boost::system::error_code, std::size_t)>
James Feista465ccc2019-02-08 12:51:01 -0800866 watchI2cBusses = [&](const boost::system::error_code& ec,
James Feist4131aea2018-03-09 09:47:30 -0800867 std::size_t bytes_transferred) {
868 if (ec)
869 {
870 std::cout << "Callback Error " << ec << "\n";
871 return;
872 }
873 pendingBuffer += std::string(readBuffer.data(), bytes_transferred);
874 bool devChange = false;
875 while (pendingBuffer.size() > sizeof(inotify_event))
876 {
James Feista465ccc2019-02-08 12:51:01 -0800877 const inotify_event* iEvent =
878 reinterpret_cast<const inotify_event*>(
James Feist4131aea2018-03-09 09:47:30 -0800879 pendingBuffer.data());
880 switch (iEvent->mask)
881 {
James Feist9eb0b582018-04-27 12:15:46 -0700882 case IN_CREATE:
883 case IN_MOVED_TO:
884 case IN_DELETE:
885 if (boost::starts_with(std::string(iEvent->name),
886 "i2c"))
887 {
888 devChange = true;
889 }
James Feist4131aea2018-03-09 09:47:30 -0800890 }
891
892 pendingBuffer.erase(0, sizeof(inotify_event) + iEvent->len);
893 }
James Feist6ebf9de2018-05-15 15:01:17 -0700894 if (devChange)
James Feist4131aea2018-03-09 09:47:30 -0800895 {
James Feist6ebf9de2018-05-15 15:01:17 -0700896 rescanBusses(io, busmap, dbusInterfaceMap, systemBus,
897 objServer);
James Feist4131aea2018-03-09 09:47:30 -0800898 }
James Feist6ebf9de2018-05-15 15:01:17 -0700899
James Feist4131aea2018-03-09 09:47:30 -0800900 dirWatch.async_read_some(boost::asio::buffer(readBuffer),
901 watchI2cBusses);
902 };
903
904 dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
Gunnar Millsb3e42fe2018-06-13 15:48:27 -0500905 // run the initial scan
James Feist6ebf9de2018-05-15 15:01:17 -0700906 rescanBusses(io, busmap, dbusInterfaceMap, systemBus, objServer);
James Feist918e18c2018-02-13 15:51:07 -0800907
James Feist3cb5fec2018-01-23 14:41:51 -0800908 io.run();
909 return 0;
910}