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
402
403
404
405
406
407
408
|
/*
* Copyright (c) 2009-Present, Redis Ltd.
* All rights reserved.
*
* Copyright (c) 2024-present, Valkey contributors.
* All rights reserved.
*/
#include "server.h"
#include "redisassert.h"
#include "entry.h"
/* Aggregates parameters for entry layout and serialization.
* Populated by setEntryWriteInfo() and consumed by needsNewAlloc() and entryWrite*(). */
typedef struct EntryWriteInfo {
int isEmbdNewVal; /* Whether value should be embedded */
int embdFieldType; /* SDS type for the field */
size_t embdFieldSize; /* Allocated size for SDS field */
size_t embdValueSize; /* Required size for new embd value (SDS_TYPE_8) */
size_t expirySize; /* Size of expiry metadata (0 if none) */
size_t newEntryAllocSize; /* Total allocation size needed for new entry */
uint32_t flags; /* Entry creation/update flags */
} EntryWriteInfo;
enum {
/* SDS aux flag. If set, it indicates that the entry has TTL metadata set. */
FIELD_SDS_AUX_BIT_ENTRY_HAS_EXPIRY = 0,
/* SDS aux flag. If set, it indicates that the entry has an embedded value
* pointer located in memory before the embedded field. If unset, the entry
* instead has an embedded value located after the embedded field. */
FIELD_SDS_AUX_BIT_ENTRY_HAS_VALUE_PTR = 1,
FIELD_SDS_AUX_BIT_ENTRY_MAX
};
static_assert(FIELD_SDS_AUX_BIT_ENTRY_MAX + SDS_TYPE_BITS < sizeof(char) * CHAR_BIT,
"too many sds bits are used for entry metadata");
/* Returns true if the entry's value is not embedded (stored by pointer). */
static inline int entryHasValuePtr(const Entry *entry) {
return sdsGetAuxBit(entryGetField(entry), FIELD_SDS_AUX_BIT_ENTRY_HAS_VALUE_PTR);
}
/* Returns true if the entry's value is embedded in the entry. */
static inline int entryHasEmbeddedValue(Entry *entry) {
return !entryHasValuePtr(entry);
}
/* Returns true if the entry has an expiration timestamp. */
int entryHasExpiry(const Entry *entry) {
return sdsGetAuxBit(entryGetField(entry), FIELD_SDS_AUX_BIT_ENTRY_HAS_EXPIRY);
}
/* Returns the location of a pointer to a separately allocated value. Only for
* an entry without an embedded value. */
static sds *entryGetValueRef(const Entry *entry) {
serverAssert(entryHasValuePtr(entry));
char *fieldHdr = sdsAllocPtr(entryGetField(entry));
char *valuePtr = fieldHdr - sizeof(sds);
return (sds *) valuePtr;
}
/* A pointer to the value pointer. If embedded or doesn't have a value, returns NULL. */
sds *entryGetValuePtrRef(const Entry *entry) {
return entryHasValuePtr(entry) ? entryGetValueRef(entry) : NULL;
}
/* Returns the sds of the entry's value. */
sds entryGetValue(const Entry *entry) {
if (entryHasValuePtr(entry)) {
return *entryGetValueRef(entry);
} else {
/* Skip field content, field null terminator and value sds8 hdr. */
size_t offset = sdslen(entryGetField(entry)) + 1 + sdsHdrSize(SDS_TYPE_8);
return (sds)((char *)entry + offset);
}
}
/* Returns the address of the entry allocation. */
void *entryGetAllocPtr(const Entry *entry) {
char *buf = sdsAllocPtr(entryGetField(entry));
if (entryHasValuePtr(entry)) buf -= sizeof(sds);
if (entryHasExpiry(entry)) buf -= sizeof(ExpireMeta);
return buf;
}
/**************************************** Entry Expiry API *****************************************/
/* Returns the entry expiration timestamp, or EB_EXPIRE_TIME_INVALID */
uint64_t entryGetExpiry(const Entry *entry) {
if (!entryHasExpiry(entry))
return EB_EXPIRE_TIME_INVALID;
ExpireMeta *expireMeta = (ExpireMeta *)entryGetAllocPtr(entry);
if (expireMeta->trash)
return EB_EXPIRE_TIME_INVALID;
return ebGetMetaExpTime(expireMeta);
}
int entryIsExpired(const Entry *entry) {
if (server.allow_access_expired)
return 0;
/* Condition remains valid even if entryGetExpiry() returns EB_EXPIRE_TIME_INVALID,
* as the constant is equivalent to (EB_EXPIRE_TIME_MAX + 1). */
uint64_t expireTime = entryGetExpiry(entry);
return (mstime_t)expireTime < commandTimeSnapshot();
}
/**************************************** Entry Expiry API - End *****************************************/
/* Calculate entry allocation size based on SDS alloc fields.
* This is used for size accounting. */
size_t entryMemUsage(Entry *entry) {
size_t size = sdsAllocSize(entryGetField(entry));
size += sdsAllocSize(entryGetValue(entry));
if (entryHasValuePtr(entry)) size += sizeof(sds);
if (entryHasExpiry(entry)) size += sizeof(ExpireMeta);
return size;
}
void entryFree(Entry *entry, size_t *usable) {
if (usable) *usable = entryMemUsage(entry);
if (entryHasValuePtr(entry))
sdsfree(entryGetValue(entry));
zfree(entryGetAllocPtr(entry));
}
/* Determine the appropriate SDS type for the field based on length and expiry.
* SDS_TYPE_5 cannot be used if expiry is present (no aux bits available). */
static inline int entryCalcFieldSdsType(size_t fieldLen, int hasExpiry) {
int sdsType = sdsReqType(fieldLen);
if (sdsType == SDS_TYPE_5 && hasExpiry) {
sdsType = SDS_TYPE_8;
}
return sdsType;
}
/* Calculate required size and layout for an entry */
static inline void setEntryWriteInfo(EntryWriteInfo *info, sds field, sds value, uint32_t flags) {
info->flags = flags;
/* Calculate expiry allocation size */
info->expirySize = (flags & ENTRY_HAS_EXPIRY) ? sizeof(ExpireMeta) : 0;
/* Calculate field allocation size */
size_t fieldLen = sdslen(field);
info->embdFieldType = entryCalcFieldSdsType(fieldLen, info->expirySize > 0);
info->embdFieldSize = sdsReqSize(fieldLen, info->embdFieldType);
info->isEmbdNewVal = 0;
/* Calculate value allocation size (Always use SDS_TYPE_8 for embedded values) */
size_t valueLen = value ? sdslen(value) : 0;
info->embdValueSize = value ? sdsReqSize(valueLen, SDS_TYPE_8) : 0;
/* Start with field and expiry */
size_t allocSize = info->embdFieldSize + info->expirySize;
if (unlikely(!value)) {
info->newEntryAllocSize = allocSize;
return;
}
/* Decide whether to embed the value or use a pointer */
if (allocSize + info->embdValueSize <= EMBED_VALUE_MAX_ALLOC_SIZE) {
/* Embed field and value (SDS_TYPE_8). Unused space in value's SDS header.
* [ExpireMeta | Field hdr "foo"\0 | Value hdr8 "bar"\0]
*/
info->isEmbdNewVal = 1;
allocSize += info->embdValueSize;
} else {
/* Embed field only (>= SDS_TYPE_8 to encode value ptr flag).
* [ExpireMeta | Value Ptr | Field hdr8 "foo"\0]
*/
info->isEmbdNewVal = 0;
allocSize += sizeof(sds);
/* Upgrade field to SDS_TYPE_8 if needed for aux bits */
if (info->embdFieldType == SDS_TYPE_5) {
info->embdFieldType = SDS_TYPE_8;
info->embdFieldSize = sdsReqSize(fieldLen, info->embdFieldType);
allocSize = info->embdFieldSize + info->expirySize + sizeof(sds);
}
}
info->newEntryAllocSize = allocSize;
}
/* Serialize the content of the entry into the provided buffer */
static Entry *entryWriteNew(EntryWriteInfo *info, sds field, sds value) {
char *fieldBuf, *buf = zmalloc(info->newEntryAllocSize);
/* Take into account expiry metadata if present */
if (info->expirySize) {
ExpireMeta *expMeta = (ExpireMeta *)buf;
expMeta->trash = 1; /* Mark as trash until added to ebuckets */
fieldBuf = buf + info->expirySize;
} else {
fieldBuf = buf;
}
/* Write value (either as pointer or embedded) */
if (value) {
if (info->isEmbdNewVal) {
/* Embed the value after the field - always copy content */
sdsnewplacement(fieldBuf + info->embdFieldSize, info->embdValueSize,
SDS_TYPE_8, value, sdslen(value));
/* Free value only if ownership was transferred */
if (info->flags & ENTRY_TAKE_VALUE)
sdsfree(value);
info->flags &= ~ENTRY_TAKE_VALUE;
} else {
/* Store value as a pointer. dup if ownership wasn't transferred */
*(sds *)fieldBuf = ((info->flags & ENTRY_TAKE_VALUE)) ? value : sdsdup(value);
info->flags &= ~ENTRY_TAKE_VALUE;
fieldBuf += sizeof(sds);
}
}
/* Write the field */
Entry *newEntry = (Entry *)sdsnewplacement(fieldBuf, info->embdFieldSize,
info->embdFieldType, field, sdslen(field));
/* Set aux bits to encode entry type */
sdsSetAuxBit(entryGetField(newEntry), FIELD_SDS_AUX_BIT_ENTRY_HAS_VALUE_PTR, !info->isEmbdNewVal);
sdsSetAuxBit(entryGetField(newEntry), FIELD_SDS_AUX_BIT_ENTRY_HAS_EXPIRY, info->expirySize > 0);
/* Verify the entry was built correctly */
debugServerAssert(entryHasValuePtr(newEntry) == !info->isEmbdNewVal);
debugServerAssert(entryHasExpiry(newEntry) == (info->expirySize > 0));
return newEntry;
}
Entry *entryCreate(sds field, sds value, uint32_t flags, size_t *usable) {
/* Calculate required size and layout */
EntryWriteInfo info;
setEntryWriteInfo(&info, field, value, flags);
/* Allocate and write the entry */
Entry *entry = entryWriteNew(&info, field, value);
/* Calculate usable size if requested */
if (usable)
*usable = entryMemUsage(entry);
return entry;
}
/* Helper: Check if we need to create a new entry allocation during update.
* Returns true if a new allocation is needed, false if we can update in-place. */
static inline int needsNewAlloc(Entry *e,
EntryWriteInfo *info,
int isUpdateValue,
int expiryAddRemove)
{
/* if we need to add/remove expiration metadata */
if (expiryAddRemove)
return 1;
/* If not updating value, no need to allocate new entry */
if (!isUpdateValue)
return 0;
/* If value embedding <> pointer changed */
if (info->isEmbdNewVal != entryHasEmbeddedValue(e))
return 1;
/* If old & new are both pointers, no need to allocate new entry */
if (!info->isEmbdNewVal)
return 0;
/* Check if new embedded value fits in old allocation */
size_t oldAllocSize = sdsAllocSize(entryGetValue(e));
size_t newReqSize = info->embdValueSize;
return !((newReqSize <= oldAllocSize) && (newReqSize >= oldAllocSize * 3 / 4));
}
/* Helper: Update entry in-place */
static Entry *entryWriteOver(Entry *e, EntryWriteInfo *info, sds value)
{
/* No need to touch expiration metadata. It's done by caller */
if (entryHasValuePtr(e)) {
/* Replace pointer value */
sds *valueRef = entryGetValueRef(e);
sdsfree(*valueRef);
*valueRef = (info->flags & ENTRY_TAKE_VALUE) ? value : sdsdup(value);
} else {
/* Update embedded value in-place - always copy content */
sds oldValue = entryGetValue(e);
/* Use the old value's allocation size */
size_t valueSize = sdsAllocSize(oldValue);
sdsnewplacement(sdsAllocPtr(oldValue), valueSize, SDS_TYPE_8, value, sdslen(value));
/* Free value only if we took ownership */
if (info->flags & ENTRY_TAKE_VALUE)
sdsfree(value);
}
info->flags &= ~ENTRY_TAKE_VALUE;
return e;
}
/* Modify the entry's value and/or reserve space for expiration metadata */
Entry *entryUpdate(Entry *entry, sds value, uint32_t flags, ssize_t *usableDiff) {
/* Check if we need to add/remove expiration metadata */
int oldHasExpiry = entryHasExpiry(entry) != 0;
int newHasExpiry = (flags & ENTRY_HAS_EXPIRY) != 0;
int expiryAddRemove = (oldHasExpiry != newHasExpiry);
int isUpdateVal = (value != NULL);
/* Early return if nothing changes */
if (!isUpdateVal && !expiryAddRemove) {
if (usableDiff)
*usableDiff = 0;
if (flags & ENTRY_TAKE_VALUE)
sdsfree(value);
return entry;
}
/* Calculate old usable size before any modifications */
size_t oldUsable = entryMemUsage(entry);
/* Get the value to use (either provided or existing) */
if (!value)
value = entryGetValue(entry);
/* Calculate required size and layout for the updated entry */
EntryWriteInfo info;
setEntryWriteInfo(&info, entryGetField(entry), value, flags);
/* Decide whether to update in-place or create a new entry */
Entry *newEntry;
size_t newUsable;
if (needsNewAlloc(entry, &info, isUpdateVal, expiryAddRemove)) {
Entry *oldEntry = entry;
/* If not updating value */
if (value == NULL) {
/* Should not flag ownership of value if not updating value */
debugServerAssert((info.flags & ENTRY_TAKE_VALUE) == 0);
/* Try reuse the existing value */
value = entryGetValue(oldEntry);
/* If value is a pointer, we can transfer it from old to new entry */
if (entryHasValuePtr(oldEntry)) {
sds *oldValuePtr = entryGetValueRef(oldEntry);
*oldValuePtr = NULL;
info.flags |= ENTRY_TAKE_VALUE;
}
}
newEntry = entryWriteNew(&info, entryGetField(oldEntry), value);
entryFree(oldEntry, NULL);
newUsable = entryMemUsage(newEntry);
} else {
/* Update in-place */
newEntry = entryWriteOver(entry, &info, value);
newUsable = entryMemUsage(newEntry);
}
/* Calculate the difference in memory usage */
if (usableDiff)
*usableDiff = (ssize_t)newUsable - (ssize_t)oldUsable;
/* Verify the entry was built correctly */
debugServerAssert(entryHasValuePtr(newEntry) == !info.isEmbdNewVal);
debugServerAssert(entryHasExpiry(newEntry) == (info.expirySize != 0));
debugServerAssert((info.flags & ENTRY_TAKE_VALUE) == 0); /* verify the flag is cleared */
serverAssert(newEntry);
return newEntry;
}
/* Defragments a hashtable entry (field-value pair) if needed, using the
* provided defrag functions. The defrag functions return NULL if the allocation
* was not moved, otherwise they return a pointer to the new memory location.
* A separate sds defrag function is needed because of the unique memory layout
* of sds strings.
* If the location of the entry changed we return the new location,
* otherwise we return NULL. */
Entry *entryDefrag(Entry *e, void *(*defragfn)(void *), sds (*sdsdefragfn)(sds)) {
if (entryHasValuePtr(e)) {
sds *valueRef = entryGetValueRef(e);
sds newValue = sdsdefragfn(*valueRef);
if (newValue) *valueRef = newValue;
}
char *allocation = entryGetAllocPtr(e);
char *newAllocation = defragfn(allocation);
if (newAllocation != NULL) {
/* Return the same offset into the new allocation as the entry's offset
* in the old allocation. */
int entryPointerOffset = (char *)e - allocation;
return (Entry *)(newAllocation + entryPointerOffset);
}
return NULL;
}
/* Used for releasing memory to OS to avoid unnecessary CoW. Called when we've
* forked and memory won't be used again. See zmadvise_dontneed() */
void entryDismissMemory(Entry *entry) {
/* Only dismiss values memory since the field size usually is small. */
if (entryHasValuePtr(entry)) {
dismissSds(*entryGetValueRef(entry));
}
}
|