-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpdp.c
1727 lines (1656 loc) · 46.8 KB
/
cpdp.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
/* cpdp.c
* WARNING! BE SURE TO UNDERSTAND WHAT'S GOING ON BEFORE USING THIS CRAP!
* This is a tool I wrote for my personal use, and one specific use case.
* I didn't plan to share it, but here it is. Use at your own responsibility.
* You may find the tool useful, who knows... or best, you could rewrite it :)
* It may be improved, of course... but have fun with my crappy code :p
* Copies files, trying to sparse and deduplicate them, and prints copy stats.
* Deduplication information comes from a database created in previous copies.
* The tool tries to deduplicate contiguous blocks, to avoid lots of extents.
* There is missing functionality and it probably needs lots of checks. For
* example, the database saves file's mtime, which may be used to see if the
* file is changed and recalculate its blocks, or to deprioritize it when
* considering the file for deduplication. But by now it does nothing.
* Note there are no locks nor version control in its grotesque database!
* @micronn Oct 2021 (oh, yeah, all-code-in-one-file, aaarrrrgghhhh)
*
* To clarify: this tool is for deduplicating large amounts of data which may
* come from a file, network... with a few files as deduplication source, and
* not for filesystems with lots of files. Just a few. Performance degrades
* considerably when the database contains many files. Compile with -O3, and
* you can also adjust MIN_SIZE_MMAP or have a process that reads the database
* every few minutes to have it in cache. As I said, this is for a specific
* use case, but it may work for you too if you know what you're doing.
*
* 20240307: This monstruosity grew a bit, and now is able to use FICLONERANGE
* which is way faster than FIDEDUPERANGE. But be sure to understand that this
* is not an atomic deduplication (if the file from which the block is being
* deduplicated changes while doing the deduplication, it may get the new data
* and produce a corrupt copy). So, this is only enabled if -c option is
* specified. You can use -c if you're sure that the source blocks are not
* being changed while this program is deduplicating.
*
* Now it is also able to punch holes when deduplicating an existing file.
*/
#define _DEFAULT_SOURCE
#ifdef __linux__
#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38)
#define _GNU_SOURCE
#define WITH_PUNCH_HOLE
#endif
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#if !defined NODEDUPE
#define WITH_DEDUPE
#ifdef __linux__
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 5, 0)
#error Deduplication only available from kernel 4.5 (use -DNODEDUPE)
#undef WITH_DEDUPE /* do not make compiler spit lots of errors */
#endif
#else
#error Deduplication only available in linux (use -DNODEDUPE)
#undef WITH_DEDUPE /* do not make compiler spit lots of errors */
#endif
#endif
#ifdef WITH_DEDUPE
#include <sys/ioctl.h>
#include <linux/fs.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define XXH_INLINE_ALL
#include "xxhash.h"
/* don't try to dedupe less than 256 KiB */
#define MIN_DEDUPE_BYTES 0x40000
/* don't queue more than 16 MiB */
#define MAX_QUEUED_BYTES 0x1000000
/* will use mmap to read blocks from db when there are > 16 MiB in blocks */
#define MIN_SIZE_MMAP 0x1000000
static int enableclone;
/* the database is just a bunch of 4K-multiple blocks
* some blocks represent file blocks (hash and block index in file)
* other blocks are directories which contain entries that represent
* information about a file, or entries that represent information
* about blocks (offset in database, block count, availability)
* the first block in the database must be a directory
* values in database are stored as little-endian
*/
struct ddir {
uint64_t next; /* offset of next ddir */
uint16_t dt; /* directory type */
uint16_t et; /* total entries */
uint16_t ef; /* free entries */
uint16_t es; /* entry size */
};
/* adds a new directory of type dt and entry size es to the fd file
* ldpos must be the offset of one directory, preferibly the last
* the directories are added at 4k offset boundaries and size multiple 4k
* pos, if not NULL, will be set to the offset of the new directory
* d, if not NULL, will be set to the directory header
* returns -1 on error
*/
int add_ddir(int fd, off_t ldpos, uint16_t dt, uint16_t es,
off_t *pos, struct ddir *d)
{
assert(es != 0);
struct stat st;
struct ddir dl, dn;
off_t npos;
size_t sz, n;
if (fstat(fd, &st) == -1) return -1;
if (st.st_size == 0) ldpos = -1;
else do {
if (pread(fd, &dl, sizeof dl, ldpos) != sizeof dl) return -1;
npos = (off_t)le64toh(dl.next);
if (npos != 0) ldpos = npos;
} while (npos != 0);
npos = st.st_size;
if ((npos & 0xFFF) != 0) npos = (npos + 0x1000) & ~((off_t)0xFFF);
dl.next = htole64((uint64_t)npos);
dn.next = 0;
dn.dt = htole16(dt);
dn.es = htole16(es);
sz = 0x1000 - sizeof dn;
while ((n = sz / es) == 0) sz += 0x1000;
dn.et = dn.ef = htole16((uint16_t)n);
sz += sizeof dn;
if (ftruncate(fd, npos + (off_t)sz) == -1)
return -1;
if (pwrite(fd, &dn, sizeof dn, npos) != sizeof dn)
return -1;
if (ldpos != -1 && pwrite(fd, &dl, sizeof dl, ldpos) != sizeof dl)
return -1;
if (pos != NULL) *pos = npos;
if (d != NULL) *d = dn;
return 0;
}
/* directory entry callback
* this is called for each directory entry in loop_ddir function
* n will start at 0 and increment by one at each call (after last item, -1)
* o is the offset of the entry in the file
* es is the entry size, e is the entry (transient memory), p is param
* return 0 to continue, another value to end loop and return value
* when last entry is passed, it will be called with n=-1, o=0, es=0, e=0, p
* for errors you may return -2 to discriminate callback error
*/
typedef off_t decallback(ssize_t n, off_t o, size_t es, void *e, void *p);
/* loops directory entries in fd and calls f for each entry that corresponds
* to the specified dt type, while f returns 0
* if end of entries is reached (but some processed), calls f with n=-1
* pos is the start directory offset
* f is the callback and p is a user parameter
* returns 0 if no entries, the callback return value, or -1 on error
*/
off_t loop_ddir(int fd, off_t pos, uint16_t dt, decallback f, void *p)
{
struct stat st;
struct ddir *dp;
char *buf = NULL;
off_t r, npos, eo;
size_t sz, es;
ssize_t n;
int ec;
if (fstat(fd, &st) == -1) return -1;
if (st.st_size == 0)
return 0;
n = 0;
do {
sz = 0x1000;
rdbig:
buf = realloc(buf, sz);
if (buf == NULL || pread(fd, buf, sz, pos) != (ssize_t)sz) {
r = -1;
goto end;
}
dp = (struct ddir *)buf;
npos = (off_t)le64toh(dp->next);
ec = le16toh(dp->et) - le16toh(dp->ef);
if (le16toh(dp->dt) == dt && ec > 0) {
es = (size_t)le16toh(dp->es);
if (es > sz) {
assert(ec == 1);
sz = es + sizeof *dp;
goto rdbig;
}
eo = (off_t)sizeof *dp;
while (ec--) {
r = f(n++, pos + eo, es, buf + eo, p);
if (r != 0)
goto end;
eo += (off_t)es;
}
}
pos = npos;
} while (npos != 0);
if (n == 0)
return 0;
r = f(-1, 0, 0, NULL, p);
end:
free(buf);
return r;
}
/* adds a directory entry of type dt to fd file
* pos is the position of a directory, preferibly the last
* es is the size of the directory entry and e is the entry
* it will add a new directory if no space for entry is found
* return -1 on error
*/
int add_dentry(int fd, off_t pos, uint16_t dt, uint16_t es, void *e)
{
assert(es != 0);
struct stat st;
struct ddir d;
off_t npos, eo;
int ec;
if (fstat(fd, &st) == -1) return -1;
if (st.st_size == 0) {
eo = 0;
pos = 0;
} else {
do {
if (pread(fd, &d, sizeof d, pos) != sizeof d)
return -1;
npos = (off_t)le64toh(d.next);
if (le16toh(d.dt) == dt
&& le16toh(d.ef) != 0
&& le16toh(d.es) == es) {
npos = -1;
break;
}
if (npos != 0) pos = npos;
} while (npos != 0);
if (npos == 0) eo = 0;
else {
ec = (le16toh(d.et) - le16toh(d.ef));
eo = (ec <= 0) ? 0 : (off_t)sizeof d + es * ec;
}
}
if (!eo) {
if (add_ddir(fd, pos, dt, es, &pos, &d) == -1) return -1;
eo = sizeof d;
}
if (pwrite(fd, e, es, pos + eo) != es) return -1;
d.ef--;
if (pwrite(fd, &d, sizeof d, pos) != sizeof d) return -1;
return 0;
}
/* adjusts len by incrementing it to a multiple of directory free space, if
* necessary. This may reduce the number of directories in a database.
* returns the adjusted len
*/
size_t normalize_dentry_len(size_t len)
{
if (len == 0) return 0;
size_t ml = ((0x1000 - sizeof(struct ddir)) / 2);
/* try multiples of free space in block if sufficient small */
/* hey, we have fast CPUs now, right? */
while (len <= ml) {
if (ml % len == 0) return len;
len++;
}
/* do not touch if more than one in a block is not possible */
return len;
}
#define DIR_FILE 0x01
struct fentry {
uint64_t mtime; /* file mtime */
uint64_t boff; /* blocks offset */
uint32_t bs; /* block size */
uint32_t bc; /* number of blocks */
char realpath[]; /* file realpath */
};
/* callback to find a fentry in loop_dentry
* compares realpath to p and returns entry offset when found
*/
static off_t find_fentry_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
struct fentry *fe = e;
if (n == -1) return 0;
if (!strncmp(fe->realpath, p, es - sizeof *fe)) return o;
return 0;
}
/* finds the entry corresponding to realpath in fd and returns its offset
* or 0 if not found; if pfe != NULL, sets value to NULL if no entry is found
* or allocates a fentry and sets it value to it when the entry is found
* returns -1 on error
*/
off_t find_fentry(int fd, const char *realpath, struct fentry **pfe)
{
assert(realpath != NULL);
off_t off = loop_ddir(fd, 0,
DIR_FILE,
find_fentry_cb, (void *)realpath);
if (pfe != NULL) {
if (off != 0 && off != -1) {
size_t len = sizeof **pfe + strlen(realpath) + 1;
if ((*pfe = malloc(len)) == NULL) return -1;
if (pread(fd, *pfe, len, off) != (ssize_t)len) {
free(*pfe);
*pfe = NULL;
return -1;
}
} else {
*pfe = NULL;
}
}
return off;
}
#define DIR_BLOCK 0x02
struct block {
uint32_t hash; /* XXH32 hash */
uint32_t idx; /* index of block in file */
};
/* uint32_t comparsion function for a, b being 32 bit little endian values
* returns -1, 0, or 1 depending on a < b, a == b, or a > b
*/
static inline int le32cmp(uint32_t a, uint32_t b)
{
a = le32toh(a);
b = le32toh(b);
return (a > b) - (b > a);
}
/* compares two blocks for qsort */
static int block_compare(const void *a, const void *b)
{
struct block ba = *((struct block *)a);
struct block bb = *((struct block *)b);
int r = le32cmp(ba.hash, bb.hash);
return (r == 0) ? le32cmp(ba.idx, bb.idx) : r;
}
#ifdef WITH_DEDUPE
/* compares uint32_t hash k with the hash in block b
*/
static int block_search(const void *k, const void *b)
{
uint32_t hk = *((uint32_t *)k);
uint32_t h = le32toh(((struct block *)b)->hash);
return (hk > h) - (h > hk);
}
#endif
struct bentry {
uint64_t boff; /* block information offset */
uint32_t bc; /* block count */
uint32_t used; /* 0 when blocks are not used */
};
/* callback to find a bentry in loop_dentry, unused, and with enough block count
* p must point to an uint32_t specifying the desired block count
* returns the offset of the bentry, or 0 if not found
*/
static off_t find_freeblocks_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
(void)es;
static off_t off = 0;
static uint32_t min;
if (n == -1) return off;
struct bentry *be = e;
uint32_t want = *((uint32_t *)p);
uint32_t curr = le32toh(be->bc);
if (n == 0) {
off = 0;
min = UINT32_MAX;
}
if (be->used == 0 && curr >= want && curr <= min) {
off = o;
min = curr;
}
return 0;
}
/* allocates bc blocks in fd and returns their start offset
* start offset will be multiple of 0x1000 so it could be mmaped
* returns -1 on error
* ERANGE if bc = 0
*/
off_t allocate_blocks(int fd, uint32_t bc)
{
struct stat st;
struct bentry be;
off_t off, boff, len;
if (bc == 0)
return errno = ERANGE, -1;
find:
if ((off = loop_ddir(fd, 0, DIR_BLOCK, find_freeblocks_cb, &bc)) == -1)
return -1;
if (off != 0) {
if (pread(fd, &be, sizeof be, off) != sizeof be) return -1;
} else {
/* file may not have any directory; add at least one entry */
be.boff = 0;
be.bc = htole32(bc);
be.used = 0;
if (add_dentry(fd, 0, DIR_BLOCK, sizeof be, &be) == -1)
return -1;
goto find;
}
/* now we should have at least one dir */
boff = (off_t)le64toh(be.boff);
if (boff == 0) {
/* this means we must allocate the blocks at the end */
if (fstat(fd, &st) == -1) return -1;
boff = st.st_size;
if ((boff & 0xFFF) != 0)
boff = (boff + 0x1000) & ~((off_t)0xFFF);
be.boff = htole64((uint64_t)boff);
len = (off_t)(bc * sizeof(struct block));
if ((len & 0xFFF) != 0) {
len = (len + 0x1000) & ~((off_t)0xFFF);
bc = (uint32_t)(len / (off_t)sizeof(struct block));
be.bc = htole32(bc);
}
if (ftruncate(fd, boff + len) == -1) return -1;
}
be.used = htole32(1);
if (pwrite(fd, &be, sizeof be, off) != sizeof be) return -1;
return boff;
}
/* callback to find a bentry in loop_dentry that refers to a specific boff
* p must point to a off_t specifying the boff to find
* returns the offset of the bentry, or 0 if not found
*/
static off_t find_bentry_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
(void)es;
struct bentry *be = (struct bentry *)e;
if (n == -1) return 0;
off_t boff = (off_t)le64toh(be->boff);
if (boff == *((off_t *)p)) return o;
return 0;
}
/* marks blocks allocated at offset boff in fd as not used
* returns -1 on error, 0 if no blocks were allocated, 1 when blocks released
*/
int release_blocks(int fd, off_t boff)
{
struct bentry be;
off_t off = loop_ddir(fd, 0, DIR_BLOCK, find_bentry_cb, &boff);
if (off == -1) return -1;
if (off == 0) return 0;
if (pread(fd, &be, sizeof be, off) != sizeof be) return -1;
be.used = 0;
if (pwrite(fd, &be, sizeof be, off) != sizeof be) return -1;
return 1;
}
struct copy_dbfiles_stat
{
int srcdfd;
int dstdfd;
char buf[4096];
};
/* callback to copy non-deleted dbfiles from db in loop_dentry
*/
static off_t copy_dbfiles_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
(void)o;
if (n == -1) return 0;
struct fentry *fe = (struct fentry *)e;
if (*fe->realpath == 0 || fe->bc == 0) return 0;
struct copy_dbfiles_stat *s = (struct copy_dbfiles_stat *)p;
uint32_t bc = le32toh(fe->bc);
off_t srcboff = (off_t)le64toh(fe->boff);
off_t dstboff = allocate_blocks(s->dstdfd, bc);
if (dstboff == -1) {
perror("allocating blocks");
return -1;
}
struct fentry *nfe = malloc(es);
if (nfe == NULL) {
perror("creating new file entry");
return -1;
}
memcpy(nfe, fe, es);
nfe->boff = htole64((uint64_t)dstboff);
ssize_t rb, wb;
size_t tb, nb;
tb = bc * sizeof(struct block);
fprintf(stderr, "%s\n", nfe->realpath);
while (tb != 0) {
nb = (tb > sizeof s->buf) ? sizeof s->buf : tb;
if ((rb = pread(s->srcdfd, s->buf, nb, srcboff)) == -1) {
perror("reading blocks");
return free(nfe), -1;
}
if ((wb = pwrite(s->dstdfd, s->buf,
(size_t)rb, dstboff)) == -1) {
perror("writing blocks");
return free(nfe), -1;
}
srcboff += wb;
dstboff += wb;
tb -= (size_t)wb;
}
if (add_dentry(s->dstdfd, 0, DIR_FILE, (uint16_t)es, nfe) == -1) {
perror("adding file entry");
return free(nfe), -1;
}
return 0;
}
/* creates a new file with the name specified in dst and writes there the
* data about non-deleted files from dfd database
* returns -1 on error
*/
int copy_dbfiles(int dfd, const char *dst)
{
struct copy_dbfiles_stat s;
s.srcdfd = dfd;
s.dstdfd = open(dst, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0666);
if (s.dstdfd == -1) {
perror("opening destination database file");
return -1;
}
if (loop_ddir(dfd, 0, DIR_FILE, copy_dbfiles_cb, &s) == -1)
return -1;
return close(s.dstdfd);
}
struct file {
struct file *prev; /* this is a doubly linked list */
struct file *next; /* and will let us rearrange it */
off_t boff; /* offset of blocks in database (0 if no) */
char *realpath; /* real path of file */
struct block *blocks; /* blocks array (NULL if not loaded) */
size_t bc; /* block count in blocks array */
time_t mtime; /* file mtime */
blksize_t bs; /* block size of blocks represented in array */
int dfd; /* database file descriptor */
int fd; /* file descriptor */
int valid; /* 0 by default, <0 not valid, >0 valid */
};
/* initializes a new file with the specified name
* it will assign the realpath corresponding to the name
* returns -1 on error
*/
int init_new_file(struct file *f, const char *name)
{
assert(f != NULL);
f->prev = f->next = NULL;
f->realpath = realpath(name, NULL);
f->boff = 0;
f->bc = 0;
f->blocks = NULL;
f->dfd = f->fd = -1;
f->valid = 0;
/* not strictly required, but set some defaults */
f->mtime = 0;
f->bs = 0;
return (f->realpath == NULL) ? -1 : 0;
}
/* loads blocks of f from its database, if necessary
* if file has blocks assigned not from database, it remains as is
* returns 1 when blocks available, 0 otherwise, -1 on error
* ERANGE when too many blocks
*/
int ensure_blocks(struct file *f)
{
assert(f != NULL);
void *p;
uint64_t s;
if (f->blocks != NULL) return 1;
if (f->boff == 0 || f->bc == 0) return 0;
if ((s = (uint64_t)f->bc * sizeof *f->blocks) > SIZE_MAX)
return errno = ERANGE, -1;
if (s < MIN_SIZE_MMAP) {
if ((p = malloc((size_t)s)) == NULL) return -1;
if (pread(f->dfd, p, (size_t)s, f->boff) != (ssize_t)s)
return free(p), -1;
} else {
p = mmap(NULL, (size_t)s,
PROT_READ, MAP_PRIVATE, f->dfd, f->boff);
if (p == MAP_FAILED) return -1;
madvise(p, (size_t)s, MADV_RANDOM);
}
f->blocks = p;
return 1;
}
/* frees loaded or assigned blocks of f
* returns -1 on error
*/
int free_blocks(struct file *f)
{
assert(f != NULL);
if (f->blocks == NULL) return 0;
size_t s = f->bc * sizeof *f->blocks;
if (f->boff != 0 && f->bc != 0 && s >= MIN_SIZE_MMAP) {
if (munmap(f->blocks, s) == -1) return -1;
} else {
free(f->blocks);
}
f->blocks = NULL;
return 1;
}
/* assigns new blocks to the specified file
* blocks should be allocated with malloc
* returns -1 on error
* ERANGE when too many blocks
* EINVAL when file has loaded blocks from db and trying to assign the
* same blocks with different block count
*/
int assign_blocks(struct file *f, blksize_t bs, size_t bc, struct block *blocks)
{
assert(f != NULL);
if ((uint64_t)bc * sizeof *blocks > SIZE_MAX)
return errno = ERANGE, -1;
if (f->blocks != blocks) {
if (free_blocks(f) == -1) return -1;
} else if (f->boff != 0 && blocks != NULL && f->bc != bc) {
errno = EINVAL;
return -1;
}
f->blocks = blocks;
f->boff = 0;
f->bs = bs;
f->bc = bc;
return 0;
}
/* adds or updates the specified file to its database
* after updating, file->blocks may point to another place
* returns -1 on error
* ERANGE when real path too long, too many blocks, or bs < 0 or too large
*/
int upsert_file(int fd, struct file *f)
{
assert(f != NULL);
assert(f->realpath != NULL);
struct fentry *fe;
off_t off, boff;
size_t blen, len;
int ub;
len = 0; /* gcc is not smart enough */
if ((off = find_fentry(fd, f->realpath, &fe)) == -1)
return -1;
if (off == 0) {
len = strlen(f->realpath) + 1 + sizeof *fe;
len = normalize_dentry_len(len);
if (len > UINT16_MAX) return errno = ERANGE, -1;
if ((fe = malloc(len)) == NULL) return -1;
memset(fe, 0, len);
strcpy(fe->realpath, f->realpath);
ub = 1;
} else {
ub = f->dfd != fd || f->boff == 0;
}
fe->mtime = htole64((uint64_t)f->mtime);
if (ub) {
if (f->bc > UINT32_MAX
|| f->bs < 0 || (uint64_t)f->bs > UINT32_MAX) {
errno = ERANGE;
goto errfe;
}
if (ensure_blocks(f) == -1)
goto errfe;
if (off != 0) {
if (release_blocks(fd, (off_t)le64toh(fe->boff)) == -1)
goto errfe;
}
fe->bs = htole32((uint32_t)f->bs);
fe->bc = htole32((uint32_t)f->bc);
if (f->blocks == NULL || f->bc == 0) {
boff = 0;
} else {
boff = allocate_blocks(fd, (uint32_t)f->bc);
if (boff == -1) goto errfe;
blen = f->bc * sizeof *f->blocks;
if (pwrite(fd, f->blocks, blen, boff) != (ssize_t)blen)
goto errfe;
}
fe->boff = htole64((uint64_t)boff);
}
if (off == 0) {
if (add_dentry(fd, 0, DIR_FILE, (uint16_t)len, fe) == -1)
goto errfe;
} else {
if (pwrite(fd, fe, sizeof *fe, off) != sizeof *fe)
goto errfe;
}
free(fe);
f->dfd = fd;
if (ub) {
if (free_blocks(f) == -1) return -1;
f->boff = boff;
if (ensure_blocks(f) == -1) return -1;
}
return 0;
errfe:
free(fe);
return -1;
}
/* frees the specified file, does nothing if f is NULL
* returns -1 on error
*/
int free_file(struct file *f)
{
if (f == NULL) return 0;
if (f->fd >= 0 && close(f->fd) == -1) return -1;
if (free_blocks(f) == -1) return -1;
free(f->realpath);
free(f);
return 0;
}
/* callback to print files in loop_dentry
*/
static off_t print_files_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
(void)n;
(void)o;
(void)p;
size_t bc;
blksize_t bs;
time_t mtime;
struct fentry *fe = (struct fentry *)e;
char buf[30];
if (fe == NULL || es <= sizeof(*fe)) return 0;
if (*fe->realpath != 0) {
bc = (size_t)le32toh(fe->bc);
bs = (blksize_t)le32toh(fe->bs);
mtime = (time_t)le64toh(fe->mtime);
if (!strftime(buf, sizeof(buf), "%Ec", localtime(&mtime))) {
strcpy(buf, "*");
}
printf("%s %3dK %9zu %s\n",
buf, (int)bs/1024, bc, fe->realpath);
}
return 0;
}
/* prints to stdout all file realpaths from fd database
* returns -1 on error
*/
int print_files(int fd)
{
return loop_ddir(fd, 0, DIR_FILE, print_files_cb, NULL) != 0 ? -1 : 0;
}
struct floadstat {
struct file *first;
struct file *last;
char *ignorefile;
int amode;
int report;
int dfd;
};
/* callback to load files in loop_dentry
* p must point to a floadstat that contains load parameters
*/
static off_t load_files_cb(ssize_t n, off_t o, size_t es, void *e, void *p)
{
(void)o;
(void)es;
if (n == -1) return 0;
char *path;
struct file *f;
struct fentry *fe = (struct fentry *)e;
struct floadstat *s = (struct floadstat *)p;
if (n == 0) s->first = s->last = NULL;
if (*fe->realpath == 0) return 0;
if (s->ignorefile != NULL && !strcmp(s->ignorefile, fe->realpath))
return 0;
if ((uint64_t)le32toh(fe->bc) * sizeof(struct block) > SIZE_MAX) {
if (s->report)
fprintf(stderr, "%s: too many blocks\n", fe->realpath);
return 0;
}
if (access(fe->realpath, s->amode) == -1) {
if (s->report)
perror(fe->realpath);
return 0;
}
if ((path = strdup(fe->realpath)) == NULL) return -1;
if ((f = malloc(sizeof *f)) == NULL) return free(path), -1;
if (s->first == NULL) f->prev = NULL, s->first = s->last = f;
else f->prev = s->last, s->last = s->last->next = f;
f->next = NULL;
f->realpath = path;
f->mtime = (time_t)le64toh(fe->mtime);
f->boff = (off_t)le64toh(fe->boff);
f->blocks = NULL;
f->bc = (size_t)le32toh(fe->bc);
f->bs = (blksize_t)le32toh(fe->bs);
f->fd = -1;
f->dfd = s->dfd;
f->valid = 0;
return 0;
}
/* loads the files from fd database that pass access with the specified amode
* if report != 0, reports access check failures
* if ignorefile != NULL, ignores the specified file (that must exist)
* returns the list of files, or NULL when no files
* you should errno = 0 and check if errno != 0 when NULL returned
*/
struct file *load_files(int fd, int amode, int report, const char *ignorefile)
{
struct floadstat s;
s.first = NULL;
s.amode = amode;
s.report = report;
s.dfd = fd;
if (ignorefile != NULL) {
if ((s.ignorefile = realpath(ignorefile, NULL)) == NULL)
return NULL;
} else s.ignorefile = NULL;
if (loop_ddir(fd, 0, DIR_FILE, load_files_cb, &s) == -1) {
while (s.first != NULL) {
s.last = s.first;
s.first = s.first->next;
free_file(s.last);
}
}
if (s.ignorefile != NULL) free(s.ignorefile);
return s.first;
}
struct xferinfo {
off_t total; /* total bytes to transfer, -1 if unknown */
off_t xfered; /* total transferred bytes */
off_t xferlast; /* total bytes transferred at last update */
off_t sparsed; /* total bytes sparsed */
double xfersec; /* bytes transferred per second */
time_t tmstart; /* time when the transfer started */
time_t tmlast; /* time of the last update */
int dstfd; /* destination file */
int nowrite; /* non-zero to disable write */
#ifdef WITH_DEDUPE
blksize_t bs; /* block size */
off_t deduped; /* total deduplicated bytes */
off_t dedup_pending; /* total bytes pending deduplication */
off_t dedup_found; /* total bytes found to deduplicate */
off_t cloneoff; /* destination offset for clone operation */
off_t cloned; /* total bytes cloned */
size_t clonemax; /* max number of bytes for clone */
size_t clonelen; /* length to clone */
char *clonedata; /* bytes to clone */
struct file *fdplist; /* start of the file list for deduplication */
struct file *fdp; /* current file from which to deduplicate */
struct file_clone_range crg;
struct file_dedupe_range *rg;
struct file_dedupe_range_info *rgi;
_Alignas(struct file_dedupe_range)
char rgbuf[sizeof(struct file_dedupe_range) +
sizeof(struct file_dedupe_range_info)];
#endif
};
/* initializes a new transfer of total bytes (-1 if unknown)
* fdp, if not NULL, must point to any element of a file list for files that
* are available for deduplication
*/
static void init_xfer(struct xferinfo *xi,
int dstfd, blksize_t bs, off_t total,
struct file *fdp)
{
xi->total = total;
xi->xfered = xi->xferlast = 0;
xi->sparsed = 0;
xi->xfersec = 0.0;
xi->tmstart = xi->tmlast = time(NULL);
xi->dstfd = dstfd;
xi->nowrite = 1;
#ifdef WITH_DEDUPE
xi->cloneoff = xi->cloned = 0;
xi->clonemax = xi->clonelen = 0;
if (enableclone && (xi->clonedata = malloc(MAX_QUEUED_BYTES)) != NULL)
xi->clonemax = MAX_QUEUED_BYTES;
else
xi->clonedata = NULL;
xi->bs = bs;
xi->deduped = xi->dedup_pending = xi->dedup_found = 0;
if (fdp != NULL) while (fdp->prev != NULL) fdp = fdp->prev;
xi->fdplist = fdp;
xi->fdp = NULL;
memset(xi->rgbuf, 0, sizeof xi->rgbuf);
xi->rg = (struct file_dedupe_range *)xi->rgbuf;
xi->rgi = &xi->rg->info[0];
xi->rg->dest_count = 1;
xi->rgi->dest_fd = dstfd;
#else
(void)bs;
(void)fdp;
#endif
}
/* prints transfer statistics to stderr
* tries to set cursor to the start of line after printing
*/
static inline void print_xferstats(struct xferinfo *xi)
{
const float mb = (float)((off_t)1<<20);
const float gb = (float)((off_t)1<<30);
fprintf(stderr, " %.2f", (float)xi->xfered / gb);
if (xi->total >= 0)
fprintf(stderr, "/%.2f", (float)xi->total / gb);
#ifdef WITH_PUNCH_HOLE
fprintf(stderr, " (S %.2f", (float)xi->sparsed / gb);
#else
fprintf(stderr, " (%c %.2f", xi->nowrite ? 's' : 'S',
(float)xi->sparsed / gb);
#endif
#ifdef WITH_DEDUPE
fprintf(stderr, ", D %.2f", (float)xi->deduped / gb);
fprintf(stderr, ", %c %.2f", xi->clonemax ? 'C' : 'c',
(float)xi->cloned / gb);
fprintf(stderr, " d %.2f", (float)xi->dedup_found / gb);
#endif
fprintf(stderr, ") GB [%.2f MB/s]", (float)xi->xfersec / mb);
fprintf(stderr, " \r");
fflush(stderr);
}
#ifdef WITH_DEDUPE
/* closes the last file in the list (searches forward only)
* returns -1 on error, 1 if a file was closed, 0 if no file closed
*/
static int close_last_file(struct file *list)
{
struct file *fc = NULL;
while (list != NULL) {
if (list->fd >= 0)
fc = list;
list = list->next;
}
if (fc != NULL) {
if (close(fc->fd) == -1) return -1;
fc->fd = -1;
return 1;
}
return 0;
}
/* validates the specified file by opening it read only, if not already open
* if file is marked as invalid, it does not try to open it another time
* if too many files were open, tries to close the last file from list onwards
* if file couldn't be opened, marks it as invalid and frees its blocks (if db)
* if file opened fine, marks it as valid (f->valid = 1)
* returns -1 on error, 0 if file invalid, 1 if file valid
*/
static int validate_file(struct file *f, struct file *list)
{
assert(f != NULL);
if (f->valid < 0)
return 0;
if (f->fd < 0) {
try_open:
if ((f->fd = open(f->realpath, O_RDONLY)) == -1) {
int olderrno = errno;
if (errno == EMFILE && close_last_file(list) == 1)
goto try_open;
if (f->boff != 0) free_blocks(f);
errno = olderrno;
f->valid = -1;
return -1;
}
}
f->valid = 1;
return 1;