This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
cache.c
402 lines (335 loc) · 10.3 KB
/
cache.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#include <sys/time.h>
#include "cache.h"
#include "compression.h"
#include "storage.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "storage/buf.h"
#include "storage/bufmgr.h"
#include "utils/catcache.h"
#include "utils/hsearch.h"
#include "utils/rel.h"
/* TODO: make it configurable via GUC variable */
#define CACHE_SIZE 16
/* TODO: concatenate headers and put this definition in it */
#define MIN(a, b) ((a) < (b) ? (a) : (b))
typedef struct
{
Oid relid;
BlockNumber blockno;
} PageId;
typedef struct
{
PageId key;
CacheEntry entry;
} PageIdCacheEntry;
/* Timestamp */
typedef unsigned long long TS;
typedef struct
{
PageId key;
bool pinned; /* cache entry cannot be evicted when true */
TS ts; /* timestamp for LRU */
uint32 nblocks; /* number of postgres blocks */
TransactionId xid; /* transaction created block */
BlockNumber blocks[CRYO_BLCKSZ / BLCKSZ]; /* cache block numbers *
* for SeqScanIterator */
char data[CRYO_BLCKSZ];
} CacheEntryHeader;
/* Cache itself */
CacheEntryHeader cache[CACHE_SIZE];
/* Hashtable for quick cache lookups by (relid, blockno) key */
HTAB *pagemap;
void
cryo_init_cache(void)
{
HASHCTL hash_ctl;
/* Initialize hash tables used to track TIDs */
memset(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(PageId);
hash_ctl.entrysize = sizeof(PageIdCacheEntry);
hash_ctl.hcxt = CacheMemoryContext;
pagemap =
hash_create("pg_cryogen cache",
CACHE_SIZE,
&hash_ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
}
/*
* Return current UNIX time in microseconds
*/
static TS
get_current_timestamp_ms(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (TS)(tv.tv_sec) * 1000 +
(TS)(tv.tv_usec) / 1000;
}
/*
* Read and reassemble compressed data from the buffer manager starting
* with `block` and decompress it.
*
* Possible return values:
* CRYO_ERR_SUCCESS: success;
* CRYO_ERR_WRONG_STARTING_BLOCK: specified blockno is not a starting
* block of cryo page;
* CRYO_ERR_DECOMPRESSION_FAILED: decompression failure;
* CRYO_ERR_EMPTY_BLOCK: specified block is empty.
*
* XXX Move visibility check here to avoid unnecessary i/o.
*/
static CryoError
cryo_read_decompress(Relation rel, SeqScanIterator *iter, BlockNumber block,
CacheEntryHeader *entry)
{
CryoPageHeader *page;
CompressionMethod method;
Buffer buf;
Buffer vmbuf = InvalidBuffer;
char *compressed, *p;
Size compressed_size, size;
uint8 vmflags;
BlockNumber first_block = block;
buf = ReadBuffer(rel, block);
page = (CryoPageHeader *) BufferGetPage(buf);
if (PageIsNew(page))
{
ReleaseBuffer(buf);
return CRYO_ERR_EMPTY_BLOCK;
}
/*
* In case of brin index bitmap scan can try to read data not from the
* first page.
*/
if (page->first != block)
{
ReleaseBuffer(buf);
return CRYO_ERR_WRONG_STARTING_BLOCK;
}
size = compressed_size = ((CryoFirstPageHeader *) page)->compressed_size;
method = ((CryoFirstPageHeader *) page)->compression_method;
p = compressed = palloc(compressed_size);
entry->blocks[entry->nblocks++] = block;
/*
* Check whether page is frozen.
*
* XXX We don't actually write FrozenTransactionId into page header as this
* would require entire page copy to WAL (due to Generic WAL), and VACUUM
* would be very write heavy. Instead we just write frozen bit into
* visibility map.
*/
vmflags = visibilitymap_get_status(rel, block, &vmbuf);
entry->xid = (vmflags & VISIBILITYMAP_ALL_FROZEN) ?
FrozenTransactionId : ((CryoFirstPageHeader *) page)->created_xid;
if (BufferIsValid(vmbuf))
ReleaseBuffer(vmbuf);
while (true)
{
Size content_size = BLCKSZ - CryoPageHeaderSize(page, block);
Size l = MIN(content_size, size);
char *page_content = ((char *) page) + CryoPageHeaderSize(page, block);
memcpy(p, page_content, l);
p += l;
size -= l;
block = page->next;
ReleaseBuffer(buf);
if (size == 0)
break;
/* read the next block */
if (!BlockNumberIsValid(block))
break;
buf = ReadBuffer(rel, block);
page = (CryoPageHeader *) BufferGetPage(buf);
Assert(page->first == first_block);
cryo_seqscan_iter_exclude(iter, block, false);
entry->blocks[entry->nblocks++] = block;
}
if (!cryo_decompress(method, compressed, compressed_size, entry->data))
return CRYO_ERR_DECOMPRESSION_FAILED;
return CRYO_ERR_SUCCESS;
}
static PageIdCacheEntry *
allocate_cache_slot(PageId *pageId)
{
int i;
CacheEntry new_entry = InvalidCacheEntry;
TS min_ts = -1; /* max unsigned long long */
int min_ts_pos = InvalidCacheEntry;
PageIdCacheEntry *item;
/* find an available spot in the cache or evict old cache entry */
for (i = 0; i < CACHE_SIZE; ++i)
{
if (cache[i].pinned)
continue;
if (cache[i].ts == 0)
{
new_entry = i;
break;
}
if (cache[i].ts < min_ts)
min_ts_pos = i;
}
if (new_entry == InvalidCacheEntry)
{
if (min_ts_pos == InvalidCacheEntry)
return NULL;
/*
* We didn't manage to find uninitialized cache entries. But we
* found least recently used one. We also need to remove the old
* record from pagemap.
*/
elog(DEBUG1,
"pg_cryogen: evicted cache entry for (%i, %i)",
cache[min_ts_pos].key.relid,
cache[min_ts_pos].key.blockno);
hash_search(pagemap, &cache[min_ts_pos].key, HASH_REMOVE, NULL);
new_entry = min_ts_pos;
}
/* cache entry is not found, load data from disk */
item = hash_search(pagemap, pageId, HASH_ENTER, NULL);
item->key.relid = pageId->relid;
item->key.blockno = pageId->blockno;
item->entry = new_entry;
return item;
}
static inline void
mark_cached_blocks_read(SeqScanIterator *iter, BlockNumber *blocks, uint nblocks)
{
int i;
for (i = 0; i < nblocks; ++i)
cryo_seqscan_iter_exclude(iter, blocks[i], true);
}
CryoError
cryo_read_data(Relation rel, SeqScanIterator *iter, BlockNumber blockno,
CacheEntry *result)
{
bool found;
PageId pageId = {
.relid = RelationGetRelid(rel),
.blockno = blockno
};
PageIdCacheEntry *item;
/* TODO: do not rely on RelationGetNumberOfBlocks; refer to metapage */
if (RelationGetNumberOfBlocks(rel) <= blockno || blockno == CRYO_META_PAGE)
{
*result = InvalidCacheEntry;
return CRYO_ERR_WRONG_STARTING_BLOCK;
}
/* check with hashtable */
item = hash_search(pagemap, &pageId, HASH_FIND, &found);
/* TODO: rewrite condition */
if (!found || item->entry == InvalidCacheEntry || cache[item->entry].ts == 0)
{
CryoError err;
/* find an available slot in the cache */
item = allocate_cache_slot(&pageId);
if (!item)
return CRYO_ERR_CACHE_IS_FULL;
/* load cryo block */
cache[item->entry].ts = get_current_timestamp_ms();
cache[item->entry].key = item->key;
cache[item->entry].pinned = false;
cache[item->entry].nblocks = 0;
err = cryo_read_decompress(rel, iter, blockno, &cache[item->entry]);
if (err != CRYO_ERR_SUCCESS)
{
*result = item->entry = InvalidCacheEntry;
return err;
}
}
else
{
mark_cached_blocks_read(iter,
cache[item->entry].blocks,
cache[item->entry].nblocks);
}
*result = item->entry;
return CRYO_ERR_SUCCESS;
}
CacheEntry
cryo_cache_allocate(Relation rel, BlockNumber blockno)
{
bool found;
PageId pageId = {
.relid = RelationGetRelid(rel),
.blockno = blockno
};
PageIdCacheEntry *item;
/* check with hashtable */
item = hash_search(pagemap, &pageId, HASH_FIND, &found);
if (!found || item->entry == InvalidCacheEntry)
{
/* find an available slot in the cache */
item = allocate_cache_slot(&pageId);
if (!item)
elog(ERROR, "pg_cryogen: %s", cryo_cache_err(CRYO_ERR_CACHE_IS_FULL));
}
cache[item->entry].ts = get_current_timestamp_ms();
cache[item->entry].key = item->key;
cache[item->entry].pinned = true;
return item->entry;
}
void
cryo_cache_release(CacheEntry entry)
{
PageIdCacheEntry *item;
bool found;
CacheEntryHeader *slot = &cache[entry];
if (!slot->pinned)
elog(ERROR, "pg_cryogen: trying to release read-only cache entry");
item = hash_search(pagemap, &slot->key, HASH_REMOVE, &found);
if (!found || item->entry == InvalidCacheEntry)
elog(ERROR, "pg_cryogen: invalid cache entry");
slot->ts = 0;
slot->pinned = false;
}
void
cryo_cache_invalidate_relation(Oid relid)
{
int i;
for (i = 0; i < CACHE_SIZE; ++i)
{
if (cache[i].key.relid == relid)
{
hash_search(pagemap, &cache[i].key, HASH_REMOVE, NULL);
cache[i].ts = 0;
}
}
}
uint32
cryo_cache_get_pg_nblocks(CacheEntry entry)
{
return cache[entry].nblocks;
}
char *
cryo_cache_get_data(CacheEntry entry)
{
CacheEntryHeader *header = &cache[entry];
/* TODO: check that entry is valid */
/* update usage timestamp for LRU */
header->ts = get_current_timestamp_ms();
return header->data;
}
TransactionId
cryo_cache_get_xid(CacheEntry entry)
{
return cache[entry].xid;
}
char *
cryo_cache_err(CryoError err)
{
switch (err)
{
case CRYO_ERR_SUCCESS:
return "success";
case CRYO_ERR_WRONG_STARTING_BLOCK:
return "wrong starting block number";
case CRYO_ERR_DECOMPRESSION_FAILED:
return "decompression failed";
case CRYO_ERR_CACHE_IS_FULL:
return "cannot allocate cache slot; all slots are locked for modification";
default:
return "unknown error";
}
}