Debian Codegraph @

faketape/faketape-lib.h

raw symbols SCIP
1 /*
2 * Copyright (c) 2024
3 * Tim Woodall. All rights reserved
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
19 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
26 *
27 * SPDX short identifier: BSD-2-Clause
28 */
29
30 #pragma once
31
32 #include <cstdint>
33 #include <memory>
34 #include <thread>
35 #include <vector>
36 #include <condition_variable>
37 #include <mutex>
38 #include <chrono>
39 #include <unistd.h>
40 #include <iostream>
41 #include <stdio.h>
42 #include <sys/types.h>
43 #include <string>
44 #include <bit>
45
46 #define DEBUG(tape, f) do { if (tape.debug) *tape.debug << f << std::endl; } while(0)
47
48 #if defined(__GNUC__) || defined(__clang__)
49 constexpr std::uint32_t byteswap32(std::uint32_t x) noexcept {
50 return __builtin_bswap32(x);
51 }
52 constexpr std::uint64_t byteswap64(std::uint64_t x) noexcept {
53 return __builtin_bswap64(x);
54 }
55 #else
56 constexpr std::uint32_t byteswap32(std::uint32_t x) noexcept {
57 return ((x & 0x000000FFu) << 24) |
58 ((x & 0x0000FF00u) << 8) |
59 ((x & 0x00FF0000u) >> 8) |
60 ((x & 0xFF000000u) >> 24);
61 }
62 constexpr std::uint64_t byteswap64(std::uint64_t x) noexcept {
63 return ((x & 0x00000000000000FFull) << 56) |
64 ((x & 0x000000000000FF00ull) << 40) |
65 ((x & 0x0000000000FF0000ull) << 24) |
66 ((x & 0x00000000FF000000ull) << 8) |
67 ((x & 0x000000FF00000000ull) >> 8) |
68 ((x & 0x0000FF0000000000ull) >> 24) |
69 ((x & 0x00FF000000000000ull) >> 40) |
70 ((x & 0xFF00000000000000ull) >> 56);
71 }
72 #endif
73
74 class le_uint32_t {
75 private:
76 uint32_t data;
77 public:
78 constexpr le_uint32_t() = default;
79 constexpr le_uint32_t(std::uint32_t v)
80 : data(std::endian::native == std::endian::little ? v
81 : byteswap32(v)) {}
82
83 constexpr operator std::uint32_t() const {
84 return std::endian::native == std::endian::little ? data
85 : byteswap32(data);
86 }
87 };
88 static_assert(sizeof(le_uint32_t) == sizeof(uint32_t));
89
90 class le_uint64_t {
91 private:
92 uint64_t data;
93 public:
94 constexpr le_uint64_t() = default;
95 constexpr le_uint64_t(std::uint64_t v)
96 : data(std::endian::native == std::endian::little ? v
97 : byteswap64(v)) {}
98
99 constexpr operator std::uint64_t() const {
100 return std::endian::native == std::endian::little ? data
101 : byteswap64(data);
102 }
103 constexpr le_uint64_t& operator+=(uint64_t rhs) {
104 uint64_t host = *this;
105 host += rhs;
106 *this = host;
107 return *this;
108 }
109
110 constexpr le_uint64_t& operator|=(uint64_t rhs) {
111 uint64_t host = *this;
112 host |= rhs;
113 *this = host;
114 return *this;
115 }
116 };
117 class le_int64_t {
118 private:
119 int64_t data;
120 public:
121 constexpr le_int64_t() = default;
122 constexpr le_int64_t(std::int64_t v)
123 : data(std::endian::native == std::endian::little ? v
124 : byteswap64(v)) {}
125
126 constexpr operator std::int64_t() const {
127 return std::endian::native == std::endian::little ? data
128 : byteswap64(data);
129 }
130 };
131 static_assert(sizeof(le_uint64_t) == sizeof(uint64_t));
132 static_assert(sizeof(le_int64_t) == sizeof(int64_t));
133
134 /*
135 * Data is stored on disk as a single file "tape" of repeated 4K BlockTable containing record indices followed by the record data for each index.
136 *
137 * The first BlockTable has 1011 index entries, it also holds the tape position. Re-opening a file behaves like a non-rewinding tape.
138 * Subsequent BlockTables have 1019 index entries.
139 * Each index entry is a 32 bits value meaning as follows:
140 * 00000000 00...00 (All bits zero) indicates an EOF marker (a read of this block returns a size zero to the reader). The data is a 64bit blockcount of the file.
141 * 0000000x xx...xx 1 to 2^25-1 indicates records of 1-2^25-1 (inclusive) bytes of data. (Data is zlib compressed even if the compressed data is bigger than the original)
142 * 00000010 xx...xx 2^25 to 2^25+2^24-1 indicates a block of all bytes zero of size 1 to 2^24. No data is written.
143 *
144 * All other values are currently unused and assumed unused.
145 */
146 struct FakeTapeTimer;
147 class FakeTape {
148 public:
149 /* Exposed for tests - there is no reason to use these */
150 static constexpr int recsPerBlock = 1019;
151 static constexpr int recsInFirstBlock = 1011;
152 void trace(bool s) { trace_ = s; }
153 bool trace() { return trace_; }
154 std::unique_ptr<std::ostream> debug;
155
156 enum class Response : char {
157 OK = 'A',
158 ERROR = 'E',
159 FATAL = 'F'
160 };
161
162 private:
163 bool trace_ = false;
164 #pragma pack(push,1)
165 struct BlockTable {
166 public:
167 static constexpr size_t max_block_size = 1<<24; /* 16 MB */
168
169 le_uint32_t crc = 0;
170 le_uint32_t count = 0;
171 le_uint64_t prevSize = 0; /* MSB of this indicates whether the previous block contains an EOF marker */
172 le_uint32_t prevCount = 0;
173 bool zeroblock(uint32_t idx) const {
174 return recdata.size_[idx] & zeroBlockFlag;
175 }
176 uint32_t size(uint32_t idx) const {
177 uint32_t s = recdata.size_[idx];
178 if (zeroblock(idx))
179 return (s&zeroSizeMask)+1;
180 else
181 return s;
182 }
183 uint32_t disksize(uint32_t idx) const {
184 if (zeroblock(idx))
185 return 0;
186 if (size(idx))
187 return size(idx);
188 return sizeof(uint64_t);
189 }
190 void setsize(uint32_t idx, uint32_t sz, bool zeroblock) {
191 /* sz=0 is invalid when zeroblock is true. We do not check for this case */
192 if (zeroblock) {
193 sz -= 1;
194 sz |= zeroBlockFlag;
195 }
196 recdata.size_[idx] = sz;
197 }
198 uint32_t maxblocks() { return (prevSize?sizeof(recdata.size_):sizeof(recdata.firstblock.size_))/sizeof(uint32_t); }
199 private:
200 static constexpr int zeroSizeMask = (1<<24)-1;
201 static constexpr int zeroBlockFlag = 1<<25;
202 public:
203 union {
204 friend struct BlockTable;
205 private:
206 le_uint32_t size_[recsPerBlock] = {0};
207 public:
208 struct {
209 friend struct BlockTable;
210 private:
211 le_uint32_t size_[recsInFirstBlock];
212 public:
213 le_uint32_t cbt_index;
214 le_uint32_t filenum;
215 le_uint64_t fileblock;
216 le_uint64_t blockno;
217 le_int64_t blockTablePos;
218 } firstblock;
219 } recdata;
220 static_assert(sizeof(recdata.size_) == sizeof(recdata.firstblock));
221 };
222 #pragma pack(pop)
223 static_assert(sizeof(BlockTable)==4096);
224
225 BlockTable cbt; /* The current block table we are accessing the tape in */
226 uint32_t cbt_index; /* index into size - a read from the tape reads this block */
227 uint64_t block = 0;
228 uint32_t filenum = 0;
229 uint64_t fileblock = 0;
230 int fd = -1;
231 bool writing = false;
232 bool written = false;
233
234 static size_t max_block_size;
235
236 /*
237 * A tape consists of a BlockTable followed by count blocks
238 * each block is of size[n]
239 * A new blocktable is found after each 1023 blocks.
240 * Zero sized blocks are allowed
241 * prevSize is the size of the previous block including the BlockTable.
242 */
243
244 struct worker_context {
245 std::thread t;
246 std::vector<uint8_t> in;
247 std::vector<uint8_t> out;
248 Response response;
249 std::condition_variable block_written;
250 size_t size;
251 };
252 static constexpr size_t maxWorkers = 3;
253 worker_context context[maxWorkers];
254
255 /* note that these do not wrap and need to be used modulo maxworkers */
256 size_t inBufIdx = 0; /* place to queue jobs in context */
257 size_t joinIdx = 0; /* Threads that need joining */
258 size_t writeBufIdx = 0; /* next job to write to disk */
259 void worker(size_t);
260 std::mutex filemutex;
261 std::condition_variable block_written;
262
263 std::unique_ptr<FakeTapeTimer> writeDataImpl_time;
264 std::unique_ptr<FakeTapeTimer> writeDataImpl_wait_time;
265
266 static uint32_t crc32(const BlockTable*);
267 /* these should never fail - only a corrupted file or a bug */
268 bool readBlockTable();
269 bool seekBlockTable();
270 bool writeBlockTable();
271 bool writeNewBlockTable();
272 /* These can fail, for example seeking past the end of the file */
273 Response advanceOneBlock();
274 Response reverseOneBlock();
275 Response blockSeekFwd(size_t);
276 Response blockSeekBwd(size_t);
277 Response closefd(const char* wmsg);
278 Response writeDataImpl(const uint8_t* data, size_t size, bool async);
279 Response join();
280 public:
281 ~FakeTape() { close(); }
282 Response open(const std::string& filename, int flags);
283 void close();
284 Response rewind();
285 Response erase();
286 size_t getPos() const { return block; }
287 uint32_t getFileNo() const { return filenum; }
288 size_t getFileBlock() const { return fileblock; }
289 Response blockSeek(size_t offset);
290 Response writeData(const uint8_t* data, size_t size);
291 Response writeDataAsync(const uint8_t* data, size_t size);
292 Response sync();
293 Response readData(uint8_t* data, size_t maxlen, size_t* readlen);
294 Response fsr(size_t count);
295 Response bsr(size_t count);
296
297 static Response setMaxBlockSize(size_t v) {
298 if (v == (size_t)-1) v = BlockTable::max_block_size;
299 if (v > BlockTable::max_block_size)
300 return Response::ERROR;
301 max_block_size = v;
302 return Response::OK;
303 }
304 static size_t getMaxBlockSize() { return max_block_size; }
305
306 off_t getDiskPosForTest() const { return lseek(fd, 0, SEEK_CUR); }
307 };
308
309 struct FakeTapeTimer {
310 long long us = 0;
311 long long operator+=(long long e) { return us += e; }
312 FakeTape& tape;
313 const std::string name;
314 FakeTapeTimer(FakeTape& tape_, const std::string n) : tape(tape_), name(n) {}
315 ~FakeTapeTimer() {
316 if(tape.trace()) DEBUG(tape, name << " " << us / 1000000.0);
317 }
318 };
319
320 struct CalcTime {
321 FakeTapeTimer& t_;
322 std::chrono::time_point<std::chrono::high_resolution_clock> s_;
323
324 CalcTime(FakeTapeTimer& timer) : t_(timer) { s_ = std::chrono::high_resolution_clock::now(); }
325 ~CalcTime() {
326 auto e = std::chrono::high_resolution_clock::now() - s_;
327 t_ += std::chrono::duration_cast<std::chrono::microseconds>(e).count();
328 }
329 };
330
331 /* vim: set sw=8 sts=8 ts=8 noexpandtab: */