fru-device: add FRUReader EEPROM cache
This doesn't provide a huge benefit currently, but is a preparatory step
for adding support for a wider variety of FRU format parsers. If
parsers for multiple formats are interested in reading the same areas of
an EEPROM, the caching provided by this abstraction avoids the redundant
bus traffic of all of them re-reading the same bytes over and over.
Tested: on an ASRock Rack romed8hm3, fru-device successfully recognizes
and parses the baseboard FRU EEPROM as it did prior to this patch.
Signed-off-by: Zev Weiss <zev@bewilderbeest.net>
Change-Id: I0d774508bc29dbda346309fe7fe42dbdf97bee43
diff --git a/include/fru_reader.hpp b/include/fru_reader.hpp
new file mode 100644
index 0000000..b1d21d8
--- /dev/null
+++ b/include/fru_reader.hpp
@@ -0,0 +1,62 @@
+/*
+// Copyright (c) 2022 Equinix, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+*/
+
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <optional>
+#include <utility>
+
+extern "C"
+{
+// For I2C_SMBUS_BLOCK_MAX
+#include <linux/i2c.h>
+}
+
+// A function to read up to I2C_SMBUS_BLOCK_MAX bytes of FRU data. Returns
+// negative on error, or the number of bytes read otherwise, which may be (but
+// is not guaranteed to be) less than len if the read would go beyond the end
+// of the FRU.
+using ReadBlockFunc =
+ std::function<int64_t(off_t offset, size_t len, uint8_t* outbuf)>;
+
+// A caching wrapper around a ReadBlockFunc
+class FRUReader
+{
+ public:
+ FRUReader(ReadBlockFunc readFunc) : readFunc(std::move(readFunc))
+ {}
+ // The ::read() operation here is analogous to ReadBlockFunc (with the same
+ // return value semantics), but is not subject to SMBus block size
+ // limitations; it can read as much data as needed in a single call.
+ ssize_t read(off_t start, size_t len, uint8_t* outbuf);
+
+ private:
+ static constexpr size_t cacheBlockSize = 32;
+ static_assert(cacheBlockSize <= I2C_SMBUS_BLOCK_MAX);
+ using CacheBlock = std::array<uint8_t, cacheBlockSize>;
+
+ // indexed by block number (byte number / block size)
+ using Cache = std::map<uint32_t, CacheBlock>;
+
+ ReadBlockFunc readFunc;
+ Cache cache;
+
+ // byte offset of the end of the FRU (if readFunc has reported it)
+ std::optional<size_t> eof;
+};