-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathquicklist.c
3410 lines (3027 loc) · 132 KB
/
quicklist.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* quicklist.c - A doubly linked list of listpacks
*
* Copyright (c) 2014, Matt Stancliff <matt@genges.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must start the above copyright notice,
* this quicklist of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this quicklist of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h> /* for memcpy */
#include "quicklist.h"
#include "zmalloc.h"
#include "config.h"
#include "listpack.h"
#include "util.h" /* for ll2string */
#include "lzf.h"
#include "redisassert.h"
#ifndef REDIS_STATIC
#define REDIS_STATIC static
#endif
/* Optimization levels for size-based filling.
* Note that the largest possible limit is 64k, so even if each record takes
* just one byte, it still won't overflow the 16 bit count field. */
/* 快速列表中填充因子(fill)的优化级别。
* 当 fill 为负数时,会使用这些预设的值,
* 这些值表示每个结构为 (7.0前)ziplist/(7.0)listpack 的快速列表节点的最大容量(字节数),
* 从左到右(下标 0 ~ 4)对应 fill = -1 ~ -5,注意 fill < -5 时强制等于 -5。
* 另外提一下,fill 为正数时表示的是一个结构为 listpack 的节点存储的最大元素数量。注意正数情况是元素数量而不是字节数。
* fill 默认值为 -2,即采用 8192(Bytes) 作为 listpack 节点的最大容量。
* 为什么要强调结构是 ziplist/listpack 的节点?
* 当快速列表节点的 container(容器) 字段为 PACKED(7.0之前是 ZIPLIST ) 时,采用 ziplist/listpack 存储元素,
* 若为 PLAIN(7.0之前是 NONE) 时,是利用一个 char 数组来存储一个占用空间很大的元素,该节点本身即是所存储的元素。
* 注:fill 为正数时,最大元素数量限制为64k(FILL_MAX = 2^16-1),这是为了保证 quicklistNode 中16位的 count 字段不会溢出。 */
static const size_t optimization_level[] = {4096, 8192, 16384, 32768, 65536};
/* packed_threshold is initialized to 1gb */
/* packed_threshold 默认初始化为 1GB */
static size_t packed_threshold = (1 << 30);
/* set threshold for PLAIN nodes, the real limit is 4gb */
/* 为 PLAIN 节点设置阈值,真正的最大限制可以到4GB。
* 实际上 plain 和 packed 共用同一个阈值 packed_threshold,
* 如果小于阈值则节点使用 packed 容器(listpack)存储元素,
* 大于等于阈值则节点使用 plain 容器(char 数组,或者说用一整块连续空间)存储元素。*/
#define isLargeElement(size) ((size) >= packed_threshold)
/* 设置容器阈值(packed_threshold) */
int quicklistisSetPackedThreshold(size_t sz) {
/* Don't allow threshold to be set above or even slightly below 4GB */
/* 不允许 packed_threshold 超过或者比 4GB 略小一些。
* sz > 4293918720 (4294967296 - 1048576) */
if (sz > (1ull<<32) - (1<<20)) {
return 0;
} else if (sz == 0) { /* 0 means restore threshold */
sz = (1 << 30);
}
packed_threshold = sz;
return 1;
}
/* Maximum size in bytes of any multi-element listpack.
* Larger values will live in their own isolated listpacks.
* This is used only if we're limited by record count. when we're limited by
* size, the maximum limit is bigger, but still safe.
* 8k is a recommended / default size limit */
/* 任何存储多个元素的 listpack 的最大容量(字节)。
* 超出限制值的大元素将独立存储在 listpack 中。
* 这只在被元素数量限制的情况下使用(fill 为正数的情况)。
* 当限制为字节数时(fill 为负数的情况),最大的限制可以更大,且仍然安全。
* 8k 是一个推荐/默认的容量限制 */
#define SIZE_SAFETY_LIMIT 8192
/* Maximum estimate of the listpack entry overhead.
* Although in the worst case(sz < 64), we will waste 6 bytes in one
* quicklistNode, but can avoid memory waste due to internal fragmentation
* when the listpack exceeds the size limit by a few bytes (e.g. being 16388). */
/* listapck entry 占用的 header 和 backlen 的估算最大值。
* 因为 qucklistNode 的最大长度实际上为 64k, 所以我们只要算出在插入64k的 listpack entry 的情况下,
* 它的 header 和 backlen 总共占多大(header:5, backlen:3, 所以是8)。(感谢 pr #26 中 @sundb 的解释)
* 尽管在最坏的情况下(sz < 64),我们将在一个快速列表节点中浪费6个字节,
* 但当 listpack 超过大小限制的几个字节时(例如:16388)可以避免由于内部碎片造成的内存浪费 */
#define SIZE_ESTIMATE_OVERHEAD 8
/* Minimum listpack size in bytes for attempting compression. */
/* 尝试压缩的 listpack 节点应满足的最小尺寸(字节)
* listpack 节点的字节大小低于该值时不会对 listpack 进行压缩。 */
#define MIN_COMPRESS_BYTES 48
/* Minimum size reduction in bytes to store compressed quicklistNode data.
* This also prevents us from storing compression if the compression
* resulted in a larger size than the original data. */
/* 节点压缩后应减少的最少字节数。
* 如果压缩后减少的字节数低于该值,则放弃对该节点进行压缩。 */
#define MIN_COMPRESS_IMPROVE 8
/* If not verbose testing, remove all debug printing. */
#ifndef REDIS_TEST_VERBOSE
#define D(...)
#else
#define D(...) \
do { \
printf("%s:%s:%d:\t", __FILE__, __func__, __LINE__); \
printf(__VA_ARGS__); \
printf("\n"); \
} while (0)
#endif
/* Bookmarks forward declarations */
/* Bookmarks 相关函数的前向声明 */
#define QL_MAX_BM ((1 << QL_BM_BITS)-1)
quicklistBookmark *_quicklistBookmarkFindByName(quicklist *ql, const char *name);
quicklistBookmark *_quicklistBookmarkFindByNode(quicklist *ql, quicklistNode *node);
void _quicklistBookmarkDelete(quicklist *ql, quicklistBookmark *bm);
/* Simple way to give quicklistEntry structs default values with one call. */
/* 初始化 quicklistEntry,为 quicklistEntry 结构体提供默认值 */
#define initEntry(e) \
do { \
(e)->zi = (e)->value = NULL; \
(e)->longval = -123456789; \
(e)->quicklist = NULL; \
(e)->node = NULL; \
(e)->offset = 123456789; \
(e)->sz = 0; \
} while (0)
/* Reset the quicklistIter to prevent it from being used again after
* insert, replace, or other against quicklist operation. */
/* 重置 quicklistIter,防止在 quicklist 操作后使用 */
#define resetIterator(iter) \
do { \
(iter)->current = NULL; \
(iter)->zi = NULL; \
} while (0)
/* Create a new quicklist.
* Free with quicklistRelease(). */
/* 创建一个新的 quicklist */
quicklist *quicklistCreate(void) {
struct quicklist *quicklist;
quicklist = zmalloc(sizeof(*quicklist));
quicklist->head = quicklist->tail = NULL;
quicklist->len = 0;
quicklist->count = 0;
quicklist->compress = 0;
quicklist->fill = -2;
quicklist->bookmark_count = 0;
return quicklist;
}
/* quicklist 最大压缩级别 (64 位操作系统下:2**16-1)*/
#define COMPRESS_MAX ((1 << QL_COMP_BITS)-1)
/* 设置 quicklist 的压缩深度 */
void quicklistSetCompressDepth(quicklist *quicklist, int compress) {
/* 控制压缩深度 compress 在合法范围内 */
if (compress > COMPRESS_MAX) {
compress = COMPRESS_MAX;
} else if (compress < 0) {
compress = 0;
}
quicklist->compress = compress;
}
/* quicklist 的最大填充系数 (64 位操作系统下:2**16-1)*/
#define FILL_MAX ((1 << (QL_FILL_BITS-1))-1)
void quicklistSetFill(quicklist *quicklist, int fill) {
if (fill > FILL_MAX) {
fill = FILL_MAX;
} else if (fill < -5) {
fill = -5;
}
quicklist->fill = fill;
}
/* 该函数调用上面两个函数来设置 quicklist 的填充系数和压缩深度 */
void quicklistSetOptions(quicklist *quicklist, int fill, int depth) {
quicklistSetFill(quicklist, fill);
quicklistSetCompressDepth(quicklist, depth);
}
/* Create a new quicklist with some default parameters. */
/* 创建一个新的 quicklist,并设置默认参数 */
quicklist *quicklistNew(int fill, int compress) {
quicklist *quicklist = quicklistCreate();
quicklistSetOptions(quicklist, fill, compress);
return quicklist;
}
/* 创建一个 quicklistNode */
REDIS_STATIC quicklistNode *quicklistCreateNode(void) {
quicklistNode *node;
node = zmalloc(sizeof(*node));
node->entry = NULL;
node->count = 0;
node->sz = 0;
node->next = node->prev = NULL;
node->encoding = QUICKLIST_NODE_ENCODING_RAW;
node->container = QUICKLIST_NODE_CONTAINER_PACKED;
node->recompress = 0;
node->dont_compress = 0;
return node;
}
/* Return cached quicklist count */
/* 返回 quicklist 的节点数 */
unsigned long quicklistCount(const quicklist *ql) { return ql->count; }
/* Free entire quicklist. */
/* 释放整个 quicklist */
void quicklistRelease(quicklist *quicklist) {
unsigned long len;
quicklistNode *current, *next;
current = quicklist->head;
len = quicklist->len;
/* 从头节点开始,依次释放每个节点 */
while (len--) {
next = current->next;
zfree(current->entry);
quicklist->count -= current->count;
zfree(current);
quicklist->len--;
current = next;
}
quicklistBookmarksClear(quicklist);
zfree(quicklist);
}
/* Compress the listpack in 'node' and update encoding details.
* Returns 1 if listpack compressed successfully.
* Returns 0 if compression failed or if listpack too small to compress. */
/* 压缩内部结构为 listpack 的 quicklistNode,并更新 quicklistNode 的编码信息 */
/* 返回值为1,表示压缩成功 */
/* 返回值为0,表示压缩失败或者 quicklistNode 的 listpack 太小,无法压缩 */
REDIS_STATIC int __quicklistCompressNode(quicklistNode *node) {
#ifdef REDIS_TEST
node->attempted_compress = 1;
#endif
if (node->dont_compress) return 0;
/* validate that the node is neither
* tail nor head (it has prev and next)*/
/* 验证 quicklistNode 不是头节点也不是尾节点,因为头尾节点总是不压缩的,为了更快的头尾 POP 操作 */
assert(node->prev && node->next);
node->recompress = 0;
/* Don't bother compressing small values */
/* 如果 quicklistNode 的 listpack 太小(低于48字节),则不压缩 */
if (node->sz < MIN_COMPRESS_BYTES)
return 0;
quicklistLZF *lzf = zmalloc(sizeof(*lzf) + node->sz);
/* Cancel if compression fails or doesn't compress small enough */
/* 压缩失败或者压缩后的数据大于等于原始数据大小则取消压缩,
* (quicklistLZF 结构体占用空间为 8+N,
* 所以用 lzf->sz + MIN_COMPRESS_IMPROVE(值为8) 与原数据大小 node->sz 比较判断压缩后是否变小了) */
if (((lzf->sz = lzf_compress(node->entry, node->sz, lzf->compressed,
node->sz)) == 0) ||
lzf->sz + MIN_COMPRESS_IMPROVE >= node->sz) {
/* lzf_compress aborts/rejects compression if value not compressible. */
/* 如果压缩失败,则释放内存 */
zfree(lzf);
return 0;
}
/* 重新分配内存,并将数据拷贝到新的内存中 */
lzf = zrealloc(lzf, sizeof(*lzf) + lzf->sz);
/* 释放原始数据的内存 */
zfree(node->entry);
/* 改变 quicklistNode entry 的指针指向压缩数据 lzf 并更新编码信息 */
node->entry = (unsigned char *)lzf;
node->encoding = QUICKLIST_NODE_ENCODING_LZF;
return 1;
}
/* Compress only uncompressed nodes. */
/* 压缩节点的宏,只压缩未压缩的 quicklistNode */
#define quicklistCompressNode(_node) \
do { \
if ((_node) && (_node)->encoding == QUICKLIST_NODE_ENCODING_RAW) { \
__quicklistCompressNode((_node)); \
} \
} while (0)
/* Uncompress the listpack in 'node' and update encoding details.
* Returns 1 on successful decode, 0 on failure to decode. */
/* 解压缩 quicklistNode 的被压缩过的 listpack,然后更新编码信息为 RAW
* 返回值为1表示解压成功,为0表示解压失败 */
REDIS_STATIC int __quicklistDecompressNode(quicklistNode *node) {
#ifdef REDIS_TEST
node->attempted_compress = 0;
#endif
node->recompress = 0;
/* 创建 decompressed,用于存储解压缩后的数据 */
void *decompressed = zmalloc(node->sz);
quicklistLZF *lzf = (quicklistLZF *)node->entry;
if (lzf_decompress(lzf->compressed, lzf->sz, decompressed, node->sz) == 0) {
/* Someone requested decompress, but we can't decompress. Not good. */
/* 解压缩失败,则释放 decompressed */
zfree(decompressed);
return 0;
}
/* 释放压缩数据 lzf 的内存 */
zfree(lzf);
/* 更新 quicklistNode entry 的指针指向解压缩后的数据 decompressed ,并更新编码信息 */
node->entry = decompressed;
node->encoding = QUICKLIST_NODE_ENCODING_RAW;
return 1;
}
/* Decompress only compressed nodes. */
/* 解压缩节点的宏,只解压缩已压缩的 quicklistNode */
#define quicklistDecompressNode(_node) \
do { \
if ((_node) && (_node)->encoding == QUICKLIST_NODE_ENCODING_LZF) { \
__quicklistDecompressNode((_node)); \
} \
} while (0)
/* Force node to not be immediately re-compressible */
/* 对节点进行解压,同时设置 recompress = 1,代表为了使用而解压,后面不进行压缩 */
#define quicklistDecompressNodeForUse(_node) \
do { \
if ((_node) && (_node)->encoding == QUICKLIST_NODE_ENCODING_LZF) { \
__quicklistDecompressNode((_node)); \
(_node)->recompress = 1; \
} \
} while (0)
/* Extract the raw LZF data from this quicklistNode.
* Pointer to LZF data is assigned to '*data'.
* Return value is the length of compressed LZF data. */
/* 从 quicklistNode 中提取 LZF 数据,
* 将 *data 指向 LZF 中的数据(compressed)*/
/* 返回值为 LZF 数据的长度(字节数) */
size_t quicklistGetLzf(const quicklistNode *node, void **data) {
quicklistLZF *lzf = (quicklistLZF *)node->entry;
*data = lzf->compressed;
return lzf->sz;
}
/* quicklist 的 compress 不为0,则允许压缩节点 */
#define quicklistAllowsCompression(_ql) ((_ql)->compress != 0)
/* Force 'quicklist' to meet compression guidelines set by compress depth.
* The only way to guarantee interior nodes get compressed is to iterate
* to our "interior" compress depth then compress the next node we find.
* If compress depth is larger than the entire list, we return immediately. */
/* 让 quicklist 按设置的压缩深度(quicklist->compress)进行压缩。
* 保证内部节点被压缩的唯一方法是通过迭代快速列表直到达到压缩深度,
* 然后压缩我们找到的下一个节点。
* 如果 压缩深度*2 大于整个快速列表长度,我们立即返回。
* (压缩深度:在快速列表的两端保留未压缩的节点数量) */
REDIS_STATIC void __quicklistCompress(const quicklist *quicklist,
quicklistNode *node) {
if (quicklist->len == 0) return;
/* The head and tail should never be compressed (we should not attempt to recompress them) */
/* 列表头和尾不应该被压缩(我们不应该尝试重新压缩它们) */
assert(quicklist->head->recompress == 0 && quicklist->tail->recompress == 0);
/* If length is less than our compress depth (from both sides),
* we can't compress anything. */
/* 如果列表长度小于 压缩深度*2(压缩深度为在快速列表的两端保留未压缩的节点数量,所以比较时*2),
* 则我们不需要压缩任何东西 */
if (!quicklistAllowsCompression(quicklist) ||
quicklist->len < (unsigned int)(quicklist->compress * 2))
return;
#if 0
/* Optimized cases for small depth counts */
if (quicklist->compress == 1) {
quicklistNode *h = quicklist->head, *t = quicklist->tail;
quicklistDecompressNode(h);
quicklistDecompressNode(t);
if (h != node && t != node)
quicklistCompressNode(node);
return;
} else if (quicklist->compress == 2) {
quicklistNode *h = quicklist->head, *hn = h->next, *hnn = hn->next;
quicklistNode *t = quicklist->tail, *tp = t->prev, *tpp = tp->prev;
quicklistDecompressNode(h);
quicklistDecompressNode(hn);
quicklistDecompressNode(t);
quicklistDecompressNode(tp);
if (h != node && hn != node && t != node && tp != node) {
quicklistCompressNode(node);
}
if (hnn != t) {
quicklistCompressNode(hnn);
}
if (tpp != h) {
quicklistCompressNode(tpp);
}
return;
}
#endif
/* Iterate until we reach compress depth for both sides of the list.a
* Note: because we do length checks at the *top* of this function,
* we can skip explicit null checks below. Everything exists. */
/* 迭代直到达到压缩深度,
* 注意:因为在这个函数的 *顶部* 我们已经做了长度检查,
* 所以我们可以跳过下面的空指针检查。 */
/* 注释提到的压缩深度内外与常识有些不同,
* 若压缩深度 = 3,常识上我们认为深度内会是 <= 3,
* 而我们这里把 > 3 称为深度内,<= 3 称为深度外,
* 因为我们从作用的角度来取名,深度内为可以压缩的节点,
* 而深度外为不可以压缩或需要解压的节点。
* 对于注释中的压缩深度内外做出的图解示例:
* (Head 方向) compress(压缩深度)= 2
* | <--node--> | depth 1 深度外 uncompressed
* | <--node--> | depth 2 深度外 uncompressed
* | <--node--> | depth 3 深度内 compressed or plain
* | <--node--> | depth 3 深度内 compressed or plain
* | <--node--> | depth 2 深度外 uncompressed
* | <--node--> | depth 1 深度外 uncompressed
* (Tail 方向)
* */
quicklistNode *forward = quicklist->head;
quicklistNode *reverse = quicklist->tail;
int depth = 0;
int in_depth = 0;
while (depth++ < quicklist->compress) {
/* 如果深度外的两端节点被压缩,则将它们解压 */
quicklistDecompressNode(forward);
quicklistDecompressNode(reverse);
if (forward == node || reverse == node)
in_depth = 1;
/* We passed into compress depth of opposite side of the quicklist
* so there's no need to compress anything and we can exit. */
/* 如果我们已经达到了压缩深度,则不需要压缩任何节点,可以退出。 */
if (forward == reverse || forward->next == reverse)
return;
forward = forward->next;
reverse = reverse->prev;
}
/* 如果入参 node 在压缩深度内,则压缩 node */
if (!in_depth)
quicklistCompressNode(node);
/* At this point, forward and reverse are one node beyond depth */
/* 到这里,forward 和 reverse 都是可压缩的节点 */
quicklistCompressNode(forward);
quicklistCompressNode(reverse);
}
/* 压缩 quicklist 的(listpack)节点 */
#define quicklistCompress(_ql, _node) \
do { \
if ((_node)->recompress) \
quicklistCompressNode((_node)); \
else \
__quicklistCompress((_ql), (_node)); \
} while (0)
/* If we previously used quicklistDecompressNodeForUse(), just recompress. */
/* 如果我们之前使用了 quicklistDecompressNodeForUse(),只需要重新压缩即可 */
#define quicklistRecompressOnly(_node) \
do { \
if ((_node)->recompress) \
quicklistCompressNode((_node)); \
} while (0)
/* Insert 'new_node' after 'old_node' if 'after' is 1.
* Insert 'new_node' before 'old_node' if 'after' is 0.
* Note: 'new_node' is *always* uncompressed, so if we assign it to
* head or tail, we do not need to uncompress it. */
/* 若 'after' 的值为1,在 'old_node' 之后插入 'new_node'。
* 若 'after' 的值为0,在 'old_node' 之前插入 'new_node'。
* 注意: 'new_node' 始终是未压缩的,因此我们将其分配给
* 头或者尾节点,我们不需要去解压它。 */
REDIS_STATIC void __quicklistInsertNode(quicklist *quicklist,
quicklistNode *old_node,
quicklistNode *new_node, int after) {
if (after) {
new_node->prev = old_node;
if (old_node) {
new_node->next = old_node->next;
if (old_node->next)
old_node->next->prev = new_node;
old_node->next = new_node;
}
if (quicklist->tail == old_node)
quicklist->tail = new_node;
} else {
new_node->next = old_node;
if (old_node) {
new_node->prev = old_node->prev;
if (old_node->prev)
old_node->prev->next = new_node;
old_node->prev = new_node;
}
if (quicklist->head == old_node)
quicklist->head = new_node;
}
/* If this insert creates the only element so far, initialize head/tail. */
/* 如果此次插入创建了唯一的元素,则初始化头/尾。 */
if (quicklist->len == 0) {
quicklist->head = quicklist->tail = new_node;
}
/* Update len first, so in __quicklistCompress we know exactly len */
/* 首先更新快速列表长度,以便在 __quicklistCompress 中我们能准确的知道长度 */
quicklist->len++;
if (old_node)
quicklistCompress(quicklist, old_node);
quicklistCompress(quicklist, new_node);
}
/* Wrappers for node inserting around existing node. */
/* 在现有节点周围插入节点的多个包装函数。 */
REDIS_STATIC void _quicklistInsertNodeBefore(quicklist *quicklist,
quicklistNode *old_node,
quicklistNode *new_node) {
__quicklistInsertNode(quicklist, old_node, new_node, 0);
}
REDIS_STATIC void _quicklistInsertNodeAfter(quicklist *quicklist,
quicklistNode *old_node,
quicklistNode *new_node) {
__quicklistInsertNode(quicklist, old_node, new_node, 1);
}
REDIS_STATIC int
_quicklistNodeSizeMeetsOptimizationRequirement(const size_t sz,
const int fill) {
if (fill >= 0)
return 0;
size_t offset = (-fill) - 1;
if (offset < (sizeof(optimization_level) / sizeof(*optimization_level))) {
if (sz <= optimization_level[offset]) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
#define sizeMeetsSafetyLimit(sz) ((sz) <= SIZE_SAFETY_LIMIT)
REDIS_STATIC int _quicklistNodeAllowInsert(const quicklistNode *node,
const int fill, const size_t sz) {
if (unlikely(!node))
return 0;
if (unlikely(QL_NODE_IS_PLAIN(node) || isLargeElement(sz)))
return 0;
/* Estimate how many bytes will be added to the listpack by this one entry.
* We prefer an overestimation, which would at worse lead to a few bytes
* below the lowest limit of 4k (see optimization_level).
* Note: No need to check for overflow below since both `node->sz` and
* `sz` are to be less than 1GB after the plain/large element check above. */
/* 用这个入口估计有多少字节会被添加到 listpack 中。
* 我们更加倾向于去高估,虽然糟糕的情况下会造成有几个字节
* 会低于4k(optimization_level)的最低限制。
* 注意:我们无需检查下面的溢出,因为 `node->sz` 和 `sz`
* 在 plain/large 元素检查之后都会小于 1GB。 */
size_t new_sz = node->sz + sz + SIZE_ESTIMATE_OVERHEAD;
if (likely(_quicklistNodeSizeMeetsOptimizationRequirement(new_sz, fill)))
return 1;
/* when we return 1 above we know that the limit is a size limit (which is
* safe, see comments next to optimization_level and SIZE_SAFETY_LIMIT) */
/* 当返回值为1时,我们知道这个限制是一个大小限制(这是安全的限制,
* 参考 optimization_level 和 SIZE_SAFETY_LIMIT 旁的注释)*/
else if (!sizeMeetsSafetyLimit(new_sz))
return 0;
else if ((int)node->count < fill)
return 1;
else
return 0;
}
REDIS_STATIC int _quicklistNodeAllowMerge(const quicklistNode *a,
const quicklistNode *b,
const int fill) {
if (!a || !b)
return 0;
if (unlikely(QL_NODE_IS_PLAIN(a) || QL_NODE_IS_PLAIN(b)))
return 0;
/* approximate merged listpack size (- 11 to remove one listpack
* header/trailer) */
unsigned int merge_sz = a->sz + b->sz - 11;
if (likely(_quicklistNodeSizeMeetsOptimizationRequirement(merge_sz, fill)))
return 1;
/* when we return 1 above we know that the limit is a size limit (which is
* safe, see comments next to optimization_level and SIZE_SAFETY_LIMIT) */
else if (!sizeMeetsSafetyLimit(merge_sz))
return 0;
else if ((int)(a->count + b->count) <= fill)
return 1;
else
return 0;
}
#define quicklistNodeUpdateSz(node) \
do { \
(node)->sz = lpBytes((node)->entry); \
} while (0)
static quicklistNode* __quicklistCreatePlainNode(void *value, size_t sz) {
quicklistNode *new_node = quicklistCreateNode();
new_node->entry = zmalloc(sz);
new_node->container = QUICKLIST_NODE_CONTAINER_PLAIN;
memcpy(new_node->entry, value, sz);
new_node->sz = sz;
new_node->count++;
return new_node;
}
static void __quicklistInsertPlainNode(quicklist *quicklist, quicklistNode *old_node,
void *value, size_t sz, int after) {
__quicklistInsertNode(quicklist, old_node, __quicklistCreatePlainNode(value, sz), after);
quicklist->count++;
}
/* Add new entry to head node of quicklist.
*
* Returns 0 if used existing head.
* Returns 1 if new head created. */
/* 往 quicklist 头部插入一个新 entry
* 即将一个新的 entry 添加到 quicklist 的 head 节点
*
* 如果是在现有的 head 节点插入 entry,返回 0。
* 如果创建了一个新的 head 节点插入 entry,返回 1。 */
int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
quicklistNode *orig_head = quicklist->head;
if (unlikely(isLargeElement(sz))) {
__quicklistInsertPlainNode(quicklist, quicklist->head, value, sz, 0);
return 1;
}
if (likely(
_quicklistNodeAllowInsert(quicklist->head, quicklist->fill, sz))) {
quicklist->head->entry = lpPrepend(quicklist->head->entry, value, sz);
quicklistNodeUpdateSz(quicklist->head);
} else {
quicklistNode *node = quicklistCreateNode();
node->entry = lpPrepend(lpNew(0), value, sz);
quicklistNodeUpdateSz(node);
_quicklistInsertNodeBefore(quicklist, quicklist->head, node);
}
quicklist->count++;
quicklist->head->count++;
return (orig_head != quicklist->head);
}
/* Add new entry to tail node of quicklist.
*
* Returns 0 if used existing tail.
* Returns 1 if new tail created. */
/* 往 quicklist 尾部插入一个新 entry
* 即将一个新的 entry 添加到 quicklist 的 tail 节点。
*
* 如果是在现有的 tail 节点插入 entry,返回 0。
* 如果创建了一个新的 tail 节点插入 entry,返回 1。 */
int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) {
quicklistNode *orig_tail = quicklist->tail;
if (unlikely(isLargeElement(sz))) {
__quicklistInsertPlainNode(quicklist, quicklist->tail, value, sz, 1);
return 1;
}
if (likely(
_quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) {
quicklist->tail->entry = lpAppend(quicklist->tail->entry, value, sz);
quicklistNodeUpdateSz(quicklist->tail);
} else {
quicklistNode *node = quicklistCreateNode();
node->entry = lpAppend(lpNew(0), value, sz);
quicklistNodeUpdateSz(node);
_quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
}
quicklist->count++;
quicklist->tail->count++;
return (orig_tail != quicklist->tail);
}
/* Create new node consisting of a pre-formed listpack.
* Used for loading RDBs where entire listpacks have been stored
* to be retrieved later. */
/* 使用一个已经预先形成的 listpack 创建新的快速列表节点。
* 用于从存储了整个 listpack 的 RDB 文件中进行快速列表节点的恢复。 */
void quicklistAppendListpack(quicklist *quicklist, unsigned char *zl) {
quicklistNode *node = quicklistCreateNode();
node->entry = zl;
node->count = lpLength(node->entry);
node->sz = lpBytes(zl);
_quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
quicklist->count += node->count;
}
/* Create new node consisting of a pre-formed plain node.
* Used for loading RDBs where entire plain node has been stored
* to be retrieved later.
* data - the data to add (pointer becomes the responsibility of quicklist) */
/* 使用一个已经预先形成的 plain 节点来创建快速列表的新节点。
* 用于从存储了整个 plain 节点的 RDB 文件中进行快速列表节点的恢复。
* data - 要添加的新节点数据(新节点的 entry 即为 data)
*/
void quicklistAppendPlainNode(quicklist *quicklist, unsigned char *data, size_t sz) {
quicklistNode *node = quicklistCreateNode();
node->entry = data;
node->count = 1;
node->sz = sz;
node->container = QUICKLIST_NODE_CONTAINER_PLAIN;
_quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
quicklist->count += node->count;
}
#define quicklistDeleteIfEmpty(ql, n) \
do { \
if ((n)->count == 0) { \
__quicklistDelNode((ql), (n)); \
(n) = NULL; \
} \
} while (0)
REDIS_STATIC void __quicklistDelNode(quicklist *quicklist,
quicklistNode *node) {
/* Update the bookmark if any */
/* 更新书签(如果有) */
quicklistBookmark *bm = _quicklistBookmarkFindByNode(quicklist, node);
if (bm) {
bm->node = node->next;
/* if the bookmark was to the last node, delete it. */
/* 如果书签指向快速列表的最后一个节点,将书签删除。 */
if (!bm->node)
_quicklistBookmarkDelete(quicklist, bm);
}
if (node->next)
node->next->prev = node->prev;
if (node->prev)
node->prev->next = node->next;
if (node == quicklist->tail) {
quicklist->tail = node->prev;
}
if (node == quicklist->head) {
quicklist->head = node->next;
}
/* Update len first, so in __quicklistCompress we know exactly len */
/* 首先更新快速列表长度,以便在 __quicklistCompress 中我们能准确地知道长度 */
quicklist->len--;
quicklist->count -= node->count;
/* If we deleted a node within our compress depth, we
* now have compressed nodes needing to be decompressed. */
/* 如果在压缩深度内删除了节点,现在需要将转移到压缩深度外的压缩节点进行解压。 */
__quicklistCompress(quicklist, NULL);
zfree(node->entry);
zfree(node);
}
/* Delete one entry from list given the node for the entry and a pointer
* to the entry in the node.
*
* Note: quicklistDelIndex() *requires* uncompressed nodes because you
* already had to get *p from an uncompressed node somewhere.
*
* Returns 1 if the entire node was deleted, 0 if node still exists.
* Also updates in/out param 'p' with the next offset in the listpack. */
REDIS_STATIC int quicklistDelIndex(quicklist *quicklist, quicklistNode *node,
unsigned char **p) {
int gone = 0;
if (unlikely(QL_NODE_IS_PLAIN(node))) {
__quicklistDelNode(quicklist, node);
return 1;
}
node->entry = lpDelete(node->entry, *p, p);
node->count--;
if (node->count == 0) {
gone = 1;
__quicklistDelNode(quicklist, node);
} else {
quicklistNodeUpdateSz(node);
}
quicklist->count--;
/* If we deleted the node, the original node is no longer valid */
return gone ? 1 : 0;
}
/* Delete one element represented by 'entry'
*
* 'entry' stores enough metadata to delete the proper position in
* the correct listpack in the correct quicklist node. */
void quicklistDelEntry(quicklistIter *iter, quicklistEntry *entry) {
quicklistNode *prev = entry->node->prev;
quicklistNode *next = entry->node->next;
int deleted_node = quicklistDelIndex((quicklist *)entry->quicklist,
entry->node, &entry->zi);
/* after delete, the zi is now invalid for any future usage. */
iter->zi = NULL;
/* If current node is deleted, we must update iterator node and offset. */
if (deleted_node) {
if (iter->direction == AL_START_HEAD) {
iter->current = next;
iter->offset = 0;
} else if (iter->direction == AL_START_TAIL) {
iter->current = prev;
iter->offset = -1;
}
}
/* else if (!deleted_node), no changes needed.
* we already reset iter->zi above, and the existing iter->offset
* doesn't move again because:
* - [1, 2, 3] => delete offset 1 => [1, 3]: next element still offset 1
* - [1, 2, 3] => delete offset 0 => [2, 3]: next element still offset 0
* if we deleted the last element at offset N and now
* length of this listpack is N-1, the next call into
* quicklistNext() will jump to the next node. */
}
/* Replace quicklist entry by 'data' with length 'sz'. */
void quicklistReplaceEntry(quicklistIter *iter, quicklistEntry *entry,
void *data, size_t sz)
{
quicklist* quicklist = iter->quicklist;
if (likely(!QL_NODE_IS_PLAIN(entry->node) && !isLargeElement(sz))) {
entry->node->entry = lpReplace(entry->node->entry, &entry->zi, data, sz);
quicklistNodeUpdateSz(entry->node);
/* quicklistNext() and quicklistGetIteratorEntryAtIdx() provide an uncompressed node */
quicklistCompress(quicklist, entry->node);
} else if (QL_NODE_IS_PLAIN(entry->node)) {
if (isLargeElement(sz)) {
zfree(entry->node->entry);
entry->node->entry = zmalloc(sz);
entry->node->sz = sz;
memcpy(entry->node->entry, data, sz);
quicklistCompress(quicklist, entry->node);
} else {
quicklistInsertAfter(iter, entry, data, sz);
__quicklistDelNode(quicklist, entry->node);
}
} else {
entry->node->dont_compress = 1; /* Prevent compression in quicklistInsertAfter() */
quicklistInsertAfter(iter, entry, data, sz);
if (entry->node->count == 1) {
__quicklistDelNode(quicklist, entry->node);
} else {
unsigned char *p = lpSeek(entry->node->entry, -1);
quicklistDelIndex(quicklist, entry->node, &p);
entry->node->dont_compress = 0; /* Re-enable compression */
quicklistCompress(quicklist, entry->node);
quicklistCompress(quicklist, entry->node->next);
}
}
/* In any case, we reset iterator to forbid use of iterator after insert.
* Notice: iter->current has been compressed above. */
resetIterator(iter);
}
/* Replace quicklist entry at offset 'index' by 'data' with length 'sz'.
*
* Returns 1 if replace happened.
* Returns 0 if replace failed and no changes happened. */
int quicklistReplaceAtIndex(quicklist *quicklist, long index, void *data,
size_t sz) {
quicklistEntry entry;
quicklistIter *iter = quicklistGetIteratorEntryAtIdx(quicklist, index, &entry);
if (likely(iter)) {
quicklistReplaceEntry(iter, &entry, data, sz);
quicklistReleaseIterator(iter);
return 1;
} else {
return 0;
}
}
/* Given two nodes, try to merge their listpacks.
*
* This helps us not have a quicklist with 3 element listpacks if
* our fill factor can handle much higher levels.
*
* Note: 'a' must be to the LEFT of 'b'.
*
* After calling this function, both 'a' and 'b' should be considered
* unusable. The return value from this function must be used
* instead of re-using any of the quicklistNode input arguments.
*
* Returns the input node picked to merge against or NULL if
* merging was not possible. */
REDIS_STATIC quicklistNode *_quicklistListpackMerge(quicklist *quicklist,
quicklistNode *a,
quicklistNode *b) {
D("Requested merge (a,b) (%u, %u)", a->count, b->count);
quicklistDecompressNode(a);
quicklistDecompressNode(b);
if ((lpMerge(&a->entry, &b->entry))) {
/* We merged listpacks! Now remove the unused quicklistNode. */
quicklistNode *keep = NULL, *nokeep = NULL;
if (!a->entry) {
nokeep = a;
keep = b;
} else if (!b->entry) {
nokeep = b;
keep = a;
}
keep->count = lpLength(keep->entry);
quicklistNodeUpdateSz(keep);
nokeep->count = 0;
__quicklistDelNode(quicklist, nokeep);
quicklistCompress(quicklist, keep);
return keep;
} else {
/* else, the merge returned NULL and nothing changed. */
return NULL;
}
}
/* Attempt to merge listpacks within two nodes on either side of 'center'.
*
* We attempt to merge:
* - (center->prev->prev, center->prev)
* - (center->next, center->next->next)
* - (center->prev, center)
* - (center, center->next)
*/