forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
falloc.go
1970 lines (1664 loc) · 45.7 KB
/
falloc.go
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
// Copyright 2014 The lldb Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The storage space management.
package lldb
import (
"bytes"
"errors"
"fmt"
"io"
"sort"
"strings"
"camlistore.org/third_party/github.com/cznic/bufs"
"camlistore.org/third_party/github.com/cznic/mathutil"
"camlistore.org/third_party/github.com/cznic/zappy"
)
const (
maxBuf = maxRq + 20 // bufs,Buffers.Alloc
)
// Options are passed to the NewAllocator to amend some configuration. The
// compatibility promise is the same as of struct types in the Go standard
// library - introducing changes can be made only by adding new exported
// fields, which is backward compatible as long as client code uses field names
// to assign values of imported struct types literals.
//
// NOTE: No options are currently defined.
type Options struct{}
// AllocStats record statistics about a Filer. It can be optionally filled by
// Allocator.Verify, if successful.
type AllocStats struct {
Handles int64 // total valid handles in use
Compression int64 // number of compressed blocks
TotalAtoms int64 // total number of atoms == AllocAtoms + FreeAtoms
AllocBytes int64 // bytes allocated (after decompression, if/where used)
AllocAtoms int64 // atoms allocated/used, including relocation atoms
Relocations int64 // number of relocated used blocks
FreeAtoms int64 // atoms unused
AllocMap map[int64]int64 // allocated block size in atoms -> count of such blocks
FreeMap map[int64]int64 // free block size in atoms -> count of such blocks
}
/*
Allocator implements "raw" storage space management (allocation and
deallocation) for a low level of a DB engine. The storage is an abstraction
provided by a Filer.
The terms MUST or MUST NOT, if/where used in the documentation of Allocator,
written in all caps as seen here, are a requirement for any possible
alternative implementations aiming for compatibility with this one.
Filer file
A Filer file, or simply 'file', is a linear, contiguous sequence of blocks.
Blocks may be either free (currently unused) or allocated (currently used).
Some blocks may eventually become virtual in a sense as they may not be
realized in the storage (sparse files).
Free Lists Table
File starts with a FLT. This table records heads of 14 doubly linked free
lists. The zero based index (I) vs minimal size of free blocks in that list,
except the last one which registers free blocks of size 4112+ atoms:
MinSize == 2^I
For example 0 -> 1, 1 -> 2, ... 12 -> 4096.
Each entry in the FLT is 8 bytes in netwtork order, MSB MUST be zero, ie. the
slot value is effectively only 7 bytes. The value is the handle of the head of
the respective doubly linked free list. The FLT size is 14*8 == 112(0x70)
bytes. If the free blocks list for any particular size is empty, the respective
FLT slot is zero. Sizes of free blocks in one list MUST NOT overlap with sizes
of free lists in other list. For example, even though a free block of size 2
technically is of minimal size >= 1, it MUST NOT be put to the list for slot 0
(minimal size 1), but in slot 1( minimal size 2).
slot 0: sizes [1, 2)
slot 1: sizes [2, 4)
slot 2: sizes [4, 8)
...
slot 11: sizes [2048, 4096)
slot 12: sizes [4096, 4112)
slot 13: sizes [4112, inf)
The last FLT slot collects all free blocks bigger than its minimal size. That
still respects the 'no overlap' invariant.
File blocks
A block is a linear, contiguous sequence of atoms. The first and last atoms of
a block provide information about, for example, whether the block is free or
used, what is the size of the block, etc. Details are discussed elsewhere. The
first block of a file starts immediately after FLT, ie. at file offset
112(0x70).
Block atoms
An atom is a fixed size piece of a block (and thus of a file too); it is 16
bytes long. A consequence is that for a valid file:
filesize == 0 (mod 16)
The first atom of the first block is considered to be atom #1.
Block handles
A handle is an integer referring to a block. The reference is the number of the
atom the block starts with. Put in other way:
handle == offset/16 - 6
offset == 16 * (handle + 6)
`offset` is the offset of the first byte of the block, measured in bytes
- as in fseek(3). Handle has type `int64`, but only the lower 7 bytes may be
nonzero while referring to a block, both in code as well as when persisted in
the the file's internal bookkeeping structures - see 'Block types' bellow. So a
handle is effectively only `uint56`. This also means that the maximum usable
size of a file is 2^56 atoms. That is 2^60 bytes == 1 exabyte (10^18 bytes).
Nil handles
A handle with numeric value of '0' refers to no block.
Zero padding
A padding is used to round-up a block size to be a whole number of atoms. Any
padding, if present, MUST be all zero bytes. Note that the size of padding is
in [0, 15].
Content wiping
When a block is deallocated, its data content is not wiped as the added
overhead may be substantial while not necessarily needed. Client code should
however overwrite the content of any block having sensitive data with eg. zeros
(good compression) - before deallocating the block.
Block tags
Every block is tagged in its first byte (a head tag) and last byte (tail tag).
Block types are:
1. Short content used block (head tags 0x00-0xFB)
2. Long content used block (head tag 0xFC)
3. Relocated used block (head tag 0xFD)
4. Short, single atom, free block (head tag 0xFE)
5. Long free block (head tag 0xFF)
Note: Relocated used block, 3. above (head tag 0xFD) MUST NOT refer to blocks
other then 1. or 2. above (head tags 0x00-0xFC).
Content blocks
Used blocks (head tags 0x00-0xFC) tail tag distinguish used/unused block and if
content is compressed or not.
Content compression
The tail flag of an used block is one of
CC == 0 // Content is not compressed.
CC == 1 // Content is in zappy compression format.
If compression of written content is enabled, there are two cases: If
compressed size < original size then the compressed content should be written
if it will save at least one atom of the block. If compressed size >= original
size then the compressed content should not be used.
It's recommended to use compression. For example the BTrees implementation
assumes compression is used. Using compression may cause a slowdown in some
cases while it may as well cause a speedup.
Short content block
Short content block carries content of length between N == 0(0x00) and N ==
251(0xFB) bytes.
|<-first atom start ... last atom end->|
+---++-- ... --+-- ... --++------+
| 0 || 1... | 0x*...0x*E || 0x*F |
+---++-- ... --+-- ... --++------+
| N || content | padding || CC |
+---++-- ... --+-- ... --++------+
A == (N+1)/16 + 1 // The number of atoms in the block [1, 16]
padding == 15 - (N+1)%16 // Length of the zero padding
Long content block
Long content block carries content of length between N == 252(0xFC) and N ==
65787(0x100FB) bytes.
|<-first atom start ... last atom end->|
+------++------+-- ... --+-- ... --++------+
| 0 || 1..2 | 3... | 0x*...0x*E || 0x*F |
+------++------+-- ... --+-- ... --++------+
| 0xFC || M | content | padding || CC |
+------++------+-- ... --+-- ... --++------+
A == (N+3)/16 + 1 // The number of atoms in the block [16, 4112]
M == N % 0x10000 // Stored as 2 bytes in network byte order
padding == 15 - (N+3)%16 // Length of the zero padding
Relocated used block
Relocated block allows to permanently assign a handle to some content and
resize the content anytime afterwards without having to update all the possible
existing references; the handle can be constant while the content size may be
dynamic. When relocating a block, any space left by the original block content,
above this single atom block, MUST be reclaimed.
Relocations MUST point only to a used short or long block == blocks with tags
0x00...0xFC.
+------++------+---------++----+
| 0 || 1..7 | 8...14 || 15 |
+------++------+---------++----+
| 0xFD || H | padding || 0 |
+------++------+---------++----+
H is the handle of the relocated block in network byte order.
Free blocks
Free blocks are the result of space deallocation. Free blocks are organized in
one or more doubly linked lists, abstracted by the FLT interface. Free blocks
MUST be "registered" by putting them in such list. Allocator MUST reuse a big
enough free block, if such exists, before growing the file size. When a free
block is created by deallocation or reallocation it MUST be joined with any
adjacently existing free blocks before "registering". If the resulting free
block is now a last block of a file, the free block MUST be discarded and the
file size MUST be truncated accordingly instead. Put differently, there MUST
NOT ever be a free block at the file end.
A single free atom
Is an unused block of size 1 atom.
+------++------+--------++------+
| 0 || 1..7 | 8...14 || 15 |
+------++------+--------++------+
| 0xFE || P | N || 0xFE |
+------++------+--------++------+
P and N, stored in network byte order, are the previous and next free block
handles in the doubly linked list to which this free block belongs.
A long unused block
Is an unused block of size > 1 atom.
+------++------+-------+---------+- ... -+----------++------+
| 0 || 1..7 | 8..14 | 15...21 | | Z-7..Z-1 || Z |
+------++------+-------+---------+- ... -+----------++------+
| 0xFF || S | P | N | Leak | S || 0xFF |
+------++------+-------+---------+- ... -+----------++------+
Z == 16 * S - 1
S is the size of this unused block in atoms. P and N are the previous and next
free block handles in the doubly linked list to which this free block belongs.
Leak contains any data the block had before deallocating this block. See also
the subtitle 'Content wiping' above. S, P and N are stored in network byte
order. Large free blocks may trigger a consideration of file hole punching of
the Leak field - for some value of 'large'.
Note: Allocator methods vs CRUD[1]:
Alloc [C]reate
Get [R]ead
Realloc [U]pdate
Free [D]elete
Note: No Allocator method returns io.EOF.
[1]: http://en.wikipedia.org/wiki/Create,_read,_update_and_delete
*/
type Allocator struct {
f Filer
flt flt
Compress bool // enables content compression
cache cache
m map[int64]*node
lru lst
expHit int64
expMiss int64
cacheSz int
hit uint16
miss uint16
}
// NewAllocator returns a new Allocator. To open an existing file, pass its
// Filer. To create a "new" file, pass a Filer which file is of zero size.
func NewAllocator(f Filer, opts *Options) (a *Allocator, err error) {
if opts == nil { // Enforce *Options is always passed
return nil, errors.New("NewAllocator: nil opts passed")
}
a = &Allocator{
f: f,
cacheSz: 10,
}
a.cinit()
switch x := f.(type) {
case *RollbackFiler:
x.afterRollback = func() error {
a.cinit()
return a.flt.load(a.f, 0)
}
case *ACIDFiler0:
x.RollbackFiler.afterRollback = func() error {
a.cinit()
return a.flt.load(a.f, 0)
}
}
sz, err := f.Size()
if err != nil {
return
}
a.flt.init()
if sz == 0 {
var b [fltSz]byte
if err = a.f.BeginUpdate(); err != nil {
return
}
if _, err = f.WriteAt(b[:], 0); err != nil {
a.f.Rollback()
return
}
return a, a.f.EndUpdate()
}
return a, a.flt.load(f, 0)
}
// CacheStats reports cache statistics.
//
//TODO return a struct perhaps.
func (a *Allocator) CacheStats() (buffersUsed, buffersTotal int, bytesUsed, bytesTotal, hits, misses int64) {
buffersUsed = len(a.m)
buffersTotal = buffersUsed + len(a.cache)
bytesUsed = a.lru.size()
bytesTotal = bytesUsed + a.cache.size()
hits = a.expHit
misses = a.expMiss
return
}
func (a *Allocator) cinit() {
for h, n := range a.m {
a.cache.put(a.lru.remove(n))
delete(a.m, h)
}
if a.m == nil {
a.m = map[int64]*node{}
}
}
func (a *Allocator) cadd(b []byte, h int64) {
if len(a.m) < a.cacheSz {
n := a.cache.get(len(b))
n.h = h
copy(n.b, b)
a.m[h] = a.lru.pushFront(n)
return
}
// cache full
delete(a.m, a.cache.put(a.lru.removeBack()).h)
n := a.cache.get(len(b))
n.h = h
copy(n.b, b)
a.m[h] = a.lru.pushFront(n)
return
}
func (a *Allocator) cfree(h int64) {
n, ok := a.m[h]
if !ok { // must have been evicted
return
}
a.cache.put(a.lru.remove(n))
delete(a.m, h)
}
// Alloc allocates storage space for b and returns the handle of the new block
// with content set to b or an error, if any. The returned handle is valid only
// while the block is used - until the block is deallocated. No two valid
// handles share the same value within the same Filer, but any value of a
// handle not referring to any used block may become valid any time as a result
// of Alloc.
//
// Invoking Alloc on an empty Allocator is guaranteed to return handle with
// value 1. The intended use of content of handle 1 is a root "directory" of
// other data held by an Allocator.
//
// Passing handles not obtained initially from Alloc or not anymore valid to
// any other Allocator methods can result in an irreparably corrupted database.
func (a *Allocator) Alloc(b []byte) (handle int64, err error) {
buf := bufs.GCache.Get(zappy.MaxEncodedLen(len(b)))
defer bufs.GCache.Put(buf)
buf, _, cc, err := a.makeUsedBlock(buf, b)
if err != nil {
return
}
if handle, err = a.alloc(buf, cc); err == nil {
a.cadd(b, handle)
}
return
}
func (a *Allocator) alloc(b []byte, cc byte) (h int64, err error) {
rqAtoms := n2atoms(len(b))
if h = a.flt.find(rqAtoms); h == 0 { // must grow
var sz int64
if sz, err = a.f.Size(); err != nil {
return
}
h = off2h(sz)
err = a.writeUsedBlock(h, cc, b)
return
}
// Handle is the first item of a free blocks list.
tag, s, prev, next, err := a.nfo(h)
if err != nil {
return
}
if tag != tagFreeShort && tag != tagFreeLong {
err = &ErrILSEQ{Type: ErrExpFreeTag, Off: h2off(h), Arg: int64(tag)}
return
}
if prev != 0 {
err = &ErrILSEQ{Type: ErrHead, Off: h2off(h), Arg: prev}
return
}
if s < int64(rqAtoms) {
err = &ErrILSEQ{Type: ErrSmall, Arg: int64(rqAtoms), Arg2: s, Off: h2off(h)}
return
}
if err = a.unlink(h, s, prev, next); err != nil {
return
}
if s > int64(rqAtoms) {
freeH := h + int64(rqAtoms)
freeAtoms := s - int64(rqAtoms)
if err = a.link(freeH, freeAtoms); err != nil {
return
}
}
return h, a.writeUsedBlock(h, cc, b)
}
// Free deallocates the block referred to by handle or returns an error, if
// any.
//
// After Free succeeds, handle is invalid and must not be used.
//
// Handle must have been obtained initially from Alloc and must be still valid,
// otherwise a database may get irreparably corrupted.
func (a *Allocator) Free(handle int64) (err error) {
if handle <= 0 || handle > maxHandle {
return &ErrINVAL{"Allocator.Free: handle out of limits", handle}
}
a.cfree(handle)
return a.free(handle, 0, true)
}
func (a *Allocator) free(h, from int64, acceptRelocs bool) (err error) {
tag, atoms, _, n, err := a.nfo(h)
if err != nil {
return
}
switch tag {
default:
// nop
case tagUsedLong:
// nop
case tagUsedRelocated:
if !acceptRelocs {
return &ErrILSEQ{Type: ErrUnexpReloc, Off: h2off(h), Arg: h2off(from)}
}
if err = a.free(n, h, false); err != nil {
return
}
case tagFreeShort, tagFreeLong:
return &ErrINVAL{"Allocator.Free: attempt to free a free block at off", h2off(h)}
}
return a.free2(h, atoms)
}
func (a *Allocator) free2(h, atoms int64) (err error) {
sz, err := a.f.Size()
if err != nil {
return
}
ltag, latoms, lp, ln, err := a.leftNfo(h)
if err != nil {
return
}
if ltag != tagFreeShort && ltag != tagFreeLong {
latoms = 0
}
var rtag byte
var ratoms, rp, rn int64
isTail := h2off(h)+atoms*16 == sz
if !isTail {
if rtag, ratoms, rp, rn, err = a.nfo(h + atoms); err != nil {
return
}
}
if rtag != tagFreeShort && rtag != tagFreeLong {
ratoms = 0
}
switch {
case latoms == 0 && ratoms == 0:
// -> isolated <-
if isTail { // cut tail
return a.f.Truncate(h2off(h))
}
return a.link(h, atoms)
case latoms == 0 && ratoms != 0:
// right join ->
if err = a.unlink(h+atoms, ratoms, rp, rn); err != nil {
return
}
return a.link(h, atoms+ratoms)
case latoms != 0 && ratoms == 0:
// <- left join
if err = a.unlink(h-latoms, latoms, lp, ln); err != nil {
return
}
if isTail {
return a.f.Truncate(h2off(h - latoms))
}
return a.link(h-latoms, latoms+atoms)
}
// case latoms != 0 && ratoms != 0:
// <- middle join ->
lh, rh := h-latoms, h+atoms
if err = a.unlink(lh, latoms, lp, ln); err != nil {
return
}
// Prev unlink may have invalidated rp or rn
if _, _, rp, rn, err = a.nfo(rh); err != nil {
return
}
if err = a.unlink(rh, ratoms, rp, rn); err != nil {
return
}
return a.link(h-latoms, latoms+atoms+ratoms)
}
// Add a free block h to the appropriate free list
func (a *Allocator) link(h, atoms int64) (err error) {
if err = a.makeFree(h, atoms, 0, a.flt.head(atoms)); err != nil {
return
}
return a.flt.setHead(h, atoms, a.f)
}
// Remove free block h from the free list
func (a *Allocator) unlink(h, atoms, p, n int64) (err error) {
switch {
case p == 0 && n == 0:
// single item list, must be head
return a.flt.setHead(0, atoms, a.f)
case p == 0 && n != 0:
// head of list (has next item[s])
if err = a.prev(n, 0); err != nil {
return
}
// new head
return a.flt.setHead(n, atoms, a.f)
case p != 0 && n == 0:
// last item in list
return a.next(p, 0)
}
// case p != 0 && n != 0:
// intermediate item in a list
if err = a.next(p, n); err != nil {
return
}
return a.prev(n, p)
}
//TODO remove ?
// Return len(slice) == n, reuse src if possible.
func need(n int, src []byte) []byte {
if cap(src) < n {
bufs.GCache.Put(src)
return bufs.GCache.Get(n)
}
return src[:n]
}
// Get returns the data content of a block referred to by handle or an error if
// any. The returned slice may be a sub-slice of buf if buf was large enough
// to hold the entire content. Otherwise, a newly allocated slice will be
// returned. It is valid to pass a nil buf.
//
// If the content was stored using compression then it is transparently
// returned decompressed.
//
// Handle must have been obtained initially from Alloc and must be still valid,
// otherwise invalid data may be returned without detecting the error.
func (a *Allocator) Get(buf []byte, handle int64) (b []byte, err error) {
buf = buf[:cap(buf)]
if n, ok := a.m[handle]; ok {
a.lru.moveToFront(n)
b = need(len(n.b), buf)
copy(b, n.b)
a.expHit++
a.hit++
return
}
a.expMiss++
a.miss++
if a.miss > 10 && len(a.m) < 500 {
if 100*a.hit/a.miss < 95 {
a.cacheSz++
}
a.hit, a.miss = 0, 0
}
defer func(h int64) {
if err == nil {
a.cadd(b, h)
}
}(handle)
first := bufs.GCache.Get(16)
defer bufs.GCache.Put(first)
relocated := false
relocSrc := handle
reloc:
if handle <= 0 || handle > maxHandle {
return nil, &ErrINVAL{"Allocator.Get: handle out of limits", handle}
}
off := h2off(handle)
if err = a.read(first, off); err != nil {
return
}
switch tag := first[0]; tag {
default:
dlen := int(tag)
atoms := n2atoms(dlen)
switch atoms {
case 1:
switch tag := first[15]; tag {
default:
return nil, &ErrILSEQ{Type: ErrTailTag, Off: off, Arg: int64(tag)}
case tagNotCompressed:
b = need(dlen, buf)
copy(b, first[1:])
return
case tagCompressed:
return zappy.Decode(buf, first[1:dlen+1])
}
default:
cc := bufs.GCache.Get(1)
defer bufs.GCache.Put(cc)
dlen := int(tag)
atoms := n2atoms(dlen)
tailOff := off + 16*int64(atoms) - 1
if err = a.read(cc, tailOff); err != nil {
return
}
switch tag := cc[0]; tag {
default:
return nil, &ErrILSEQ{Type: ErrTailTag, Off: off, Arg: int64(tag)}
case tagNotCompressed:
b = need(dlen, buf)
off += 1
if err = a.read(b, off); err != nil {
b = buf[:0]
}
return
case tagCompressed:
zbuf := bufs.GCache.Get(dlen)
defer bufs.GCache.Put(zbuf)
off += 1
if err = a.read(zbuf, off); err != nil {
return buf[:0], err
}
return zappy.Decode(buf, zbuf)
}
}
case 0:
return buf[:0], nil
case tagUsedLong:
cc := bufs.GCache.Get(1)
defer bufs.GCache.Put(cc)
dlen := m2n(int(first[1])<<8 | int(first[2]))
atoms := n2atoms(dlen)
tailOff := off + 16*int64(atoms) - 1
if err = a.read(cc, tailOff); err != nil {
return
}
switch tag := cc[0]; tag {
default:
return nil, &ErrILSEQ{Type: ErrTailTag, Off: off, Arg: int64(tag)}
case tagNotCompressed:
b = need(dlen, buf)
off += 3
if err = a.read(b, off); err != nil {
b = buf[:0]
}
return
case tagCompressed:
zbuf := bufs.GCache.Get(dlen)
defer bufs.GCache.Put(zbuf)
off += 3
if err = a.read(zbuf, off); err != nil {
return buf[:0], err
}
return zappy.Decode(buf, zbuf)
}
case tagFreeShort, tagFreeLong:
return nil, &ErrILSEQ{Type: ErrExpUsedTag, Off: off, Arg: int64(tag)}
case tagUsedRelocated:
if relocated {
return nil, &ErrILSEQ{Type: ErrUnexpReloc, Off: off, Arg: relocSrc}
}
handle = b2h(first[1:])
relocated = true
goto reloc
}
}
var reallocTestHook bool
// Realloc sets the content of a block referred to by handle or returns an
// error, if any.
//
// Handle must have been obtained initially from Alloc and must be still valid,
// otherwise a database may get irreparably corrupted.
func (a *Allocator) Realloc(handle int64, b []byte) (err error) {
if handle <= 0 || handle > maxHandle {
return &ErrINVAL{"Realloc: handle out of limits", handle}
}
a.cfree(handle)
if err = a.realloc(handle, b); err != nil {
return
}
if reallocTestHook {
if err = cacheAudit(a.m, &a.lru); err != nil {
return
}
}
a.cadd(b, handle)
return
}
func (a *Allocator) realloc(handle int64, b []byte) (err error) {
var dlen, needAtoms0 int
b8 := bufs.GCache.Get(8)
defer bufs.GCache.Put(b8)
dst := bufs.GCache.Get(zappy.MaxEncodedLen(len(b)))
defer bufs.GCache.Put(dst)
b, needAtoms0, cc, err := a.makeUsedBlock(dst, b)
if err != nil {
return
}
needAtoms := int64(needAtoms0)
off := h2off(handle)
if err = a.read(b8[:], off); err != nil {
return
}
switch tag := b8[0]; tag {
default:
dlen = int(b8[0])
case tagUsedLong:
dlen = m2n(int(b8[1])<<8 | int(b8[2]))
case tagUsedRelocated:
if err = a.free(b2h(b8[1:]), handle, false); err != nil {
return err
}
dlen = 0
case tagFreeShort, tagFreeLong:
return &ErrINVAL{"Allocator.Realloc: invalid handle", handle}
}
atoms := int64(n2atoms(dlen))
retry:
switch {
case needAtoms < atoms:
// in place shrink
if err = a.writeUsedBlock(handle, cc, b); err != nil {
return
}
fh, fa := handle+needAtoms, atoms-needAtoms
sz, err := a.f.Size()
if err != nil {
return err
}
if h2off(fh)+16*fa == sz {
return a.f.Truncate(h2off(fh))
}
return a.free2(fh, fa)
case needAtoms == atoms:
// in place replace
return a.writeUsedBlock(handle, cc, b)
}
// case needAtoms > atoms:
// in place extend or relocate
var sz int64
if sz, err = a.f.Size(); err != nil {
return
}
off = h2off(handle)
switch {
case off+atoms*16 == sz:
// relocating tail block - shortcut
return a.writeUsedBlock(handle, cc, b)
default:
if off+atoms*16 < sz {
// handle is not a tail block, check right neighbour
rh := handle + atoms
rtag, ratoms, p, n, e := a.nfo(rh)
if e != nil {
return e
}
if rtag == tagFreeShort || rtag == tagFreeLong {
// Right neighbour is a free block
if needAtoms <= atoms+ratoms {
// can expand in place
if err = a.unlink(rh, ratoms, p, n); err != nil {
return
}
atoms += ratoms
goto retry
}
}
}
}
if atoms > 1 {
if err = a.realloc(handle, nil); err != nil {
return
}
}
var newH int64
if newH, err = a.alloc(b, cc); err != nil {
return err
}
rb := bufs.GCache.Cget(16)
defer bufs.GCache.Put(rb)
rb[0] = tagUsedRelocated
h2b(rb[1:], newH)
if err = a.writeAt(rb[:], h2off(handle)); err != nil {
return
}
return a.writeUsedBlock(newH, cc, b)
}
func (a *Allocator) writeAt(b []byte, off int64) (err error) {
var n int
if n, err = a.f.WriteAt(b, off); err != nil {
return
}
if n != len(b) {
err = io.ErrShortWrite
}
return
}
func (a *Allocator) write(off int64, b ...[]byte) (err error) {
rq := 0
for _, part := range b {
rq += len(part)
}
buf := bufs.GCache.Get(rq)
defer bufs.GCache.Put(buf)
buf = buf[:0]
for _, part := range b {
buf = append(buf, part...)
}
return a.writeAt(buf, off)
}
func (a *Allocator) read(b []byte, off int64) (err error) {
var rn int
if rn, err = a.f.ReadAt(b, off); rn != len(b) {
return &ErrILSEQ{Type: ErrOther, Off: off, More: err}
}
return nil
}
// nfo returns h's tag. If it's a free block then return also (s)ize (in
// atoms), (p)rev and (n)ext. If it's a used block then only (s)ize is returned
// (again in atoms). If it's a used relocate block then (n)ext is set to the
// relocation target handle.
func (a *Allocator) nfo(h int64) (tag byte, s, p, n int64, err error) {
off := h2off(h)
rq := int64(22)
sz, err := a.f.Size()
if err != nil {
return
}
if off+rq >= sz {
if rq = sz - off; rq < 15 {
err = io.ErrUnexpectedEOF
return
}
}
buf := bufs.GCache.Get(22)
defer bufs.GCache.Put(buf)
if err = a.read(buf[:rq], off); err != nil {
return
}
switch tag = buf[0]; tag {
default:
s = int64(n2atoms(int(tag)))
case tagUsedLong:
s = int64(n2atoms(m2n(int(buf[1])<<8 | int(buf[2]))))
case tagFreeLong:
if rq < 22 {
err = io.ErrUnexpectedEOF
return
}
s, p, n = b2h(buf[1:]), b2h(buf[8:]), b2h(buf[15:])
case tagUsedRelocated:
s, n = 1, b2h(buf[1:])
case tagFreeShort:
s, p, n = 1, b2h(buf[1:]), b2h(buf[8:])