blob: 61d4020adea463534119175c809d052bab686736 [file] [log] [blame]
Zev Weiss309c0b12022-02-25 01:44:12 +00001/*
2// Copyright (c) 2022 Equinix, Inc.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
17#include "fru_reader.hpp"
18
19#include <cstring>
20
21ssize_t FRUReader::read(off_t start, size_t len, uint8_t* outbuf)
22{
23 size_t done = 0;
24 size_t remaining = len;
25 size_t cursor = start;
26 while (done < len)
27 {
28 if (eof.has_value() && cursor >= eof.value())
29 {
30 break;
31 }
32
Ed Tanous3013fb42022-07-09 08:27:06 -070033 const uint8_t* blkData = nullptr;
34 size_t available = 0;
Zev Weiss309c0b12022-02-25 01:44:12 +000035 size_t blk = cursor / cacheBlockSize;
36 size_t blkOffset = cursor % cacheBlockSize;
37 auto findBlk = cache.find(blk);
38 if (findBlk == cache.end())
39 {
40 // miss, populate cache
41 uint8_t* newData = cache[blk].data();
Patrick Williamsb7077432024-08-16 15:22:21 -040042 int64_t ret =
43 readFunc(blk * cacheBlockSize, cacheBlockSize, newData);
Zev Weiss309c0b12022-02-25 01:44:12 +000044
45 // if we've reached the end of the eeprom, record its size
46 if (ret >= 0 && static_cast<size_t>(ret) < cacheBlockSize)
47 {
48 eof = (blk * cacheBlockSize) + ret;
49 }
50
51 if (ret <= 0)
52 {
53 // don't leave empty blocks in the cache
54 cache.erase(blk);
Ed Tanous3013fb42022-07-09 08:27:06 -070055 return done != 0U ? done : ret;
Zev Weiss309c0b12022-02-25 01:44:12 +000056 }
57
58 blkData = newData;
59 available = ret;
60 }
61 else
62 {
63 // hit, use cached data
64 blkData = findBlk->second.data();
65
66 // if the hit is to the block containing the (previously
67 // discovered on the miss that populated it) end of the eeprom,
68 // don't copy spurious bytes past the end
69 if (eof.has_value() && (eof.value() / cacheBlockSize == blk))
70 {
71 available = eof.value() % cacheBlockSize;
72 }
73 else
74 {
75 available = cacheBlockSize;
76 }
77 }
78
79 size_t toCopy = (blkOffset >= available)
80 ? 0
81 : std::min(available - blkOffset, remaining);
82
Ed Tanous3013fb42022-07-09 08:27:06 -070083 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
Zev Weiss309c0b12022-02-25 01:44:12 +000084 memcpy(outbuf + done, blkData + blkOffset, toCopy);
85 cursor += toCopy;
86 done += toCopy;
87 remaining -= toCopy;
88 }
89
90 return done;
91}