-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathutils.c
1401 lines (1222 loc) · 31.2 KB
/
utils.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
/*
* Copyright (C) 2007 Oracle. All rights reserved.
* Copyright (C) 2008 Morey Roof. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include "kerncompat.h"
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/sysinfo.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <mntent.h>
#include <ctype.h>
#include <limits.h>
#include <strings.h>
#include "kernel-lib/list.h"
#include "kernel-shared/accessors.h"
#include "kernel-shared/ctree.h"
#include "kernel-shared/disk-io.h"
#include "kernel-shared/volumes.h"
#include "common/utils.h"
#include "common/device-utils.h"
#include "common/path-utils.h"
#include "common/open-utils.h"
#include "common/sysfs-utils.h"
#include "common/messages.h"
#include "common/tree-search.h"
#include "cmds/commands.h"
#include "mkfs/common.h"
static int rand_seed_initialized = 0;
static unsigned short rand_seed[3];
struct btrfs_config bconf;
struct pending_dir {
struct list_head list;
char name[PATH_MAX];
};
void btrfs_format_csum(u16 csum_type, const u8 *data, char *output)
{
int i;
int cur = 0;
const int csum_size = btrfs_csum_type_size(csum_type);
output[0] = '\0';
snprintf(output, BTRFS_CSUM_STRING_LEN, "0x");
cur += strlen("0x");
for (i = 0; i < csum_size; i++) {
snprintf(output + cur, BTRFS_CSUM_STRING_LEN - cur, "%02x",
data[i]);
cur += 2;
}
}
int get_df(int fd, struct btrfs_ioctl_space_args **sargs_ret)
{
u64 count = 0;
int ret;
struct btrfs_ioctl_space_args *sargs;
sargs = malloc(sizeof(struct btrfs_ioctl_space_args));
if (!sargs)
return -ENOMEM;
sargs->space_slots = 0;
sargs->total_spaces = 0;
ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
if (ret < 0) {
error("cannot get space info: %m");
free(sargs);
return -errno;
}
/* This really should never happen */
if (!sargs->total_spaces) {
free(sargs);
return -ENOENT;
}
count = sargs->total_spaces;
free(sargs);
sargs = malloc(sizeof(struct btrfs_ioctl_space_args) +
(count * sizeof(struct btrfs_ioctl_space_info)));
if (!sargs)
return -ENOMEM;
sargs->space_slots = count;
sargs->total_spaces = 0;
ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
if (ret < 0) {
error("cannot get space info with %llu slots: %m",
count);
free(sargs);
return -errno;
}
*sargs_ret = sargs;
return 0;
}
static u64 find_max_device_id(struct btrfs_tree_search_args *args, int nr_items)
{
struct btrfs_dev_item *dev_item;
char *buf = btrfs_tree_search_data(args, 0);
buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
+ sizeof(struct btrfs_dev_item));
buf += sizeof(struct btrfs_ioctl_search_header);
dev_item = (struct btrfs_dev_item *)buf;
return btrfs_stack_device_id(dev_item);
}
static int search_chunk_tree_for_fs_info(int fd,
struct btrfs_ioctl_fs_info_args *fi_args)
{
int ret;
int max_items;
u64 start_devid = 1;
struct btrfs_tree_search_args args;
struct btrfs_ioctl_search_key *sk;
fi_args->num_devices = 0;
max_items = BTRFS_SEARCH_ARGS_BUFSIZE
/ (sizeof(struct btrfs_ioctl_search_header)
+ sizeof(struct btrfs_dev_item));
memset(&args, 0, sizeof(args));
sk = btrfs_tree_search_sk(&args);
sk->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
sk->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
sk->min_type = BTRFS_DEV_ITEM_KEY;
sk->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
sk->max_type = BTRFS_DEV_ITEM_KEY;
sk->min_transid = 0;
sk->max_transid = (u64)-1;
sk->nr_items = max_items;
sk->max_offset = (u64)-1;
again:
sk->min_offset = start_devid;
ret = btrfs_tree_search_ioctl(fd, &args);
if (ret < 0)
return -errno;
fi_args->num_devices += (u64)sk->nr_items;
if (sk->nr_items == max_items) {
start_devid = find_max_device_id(&args, sk->nr_items) + 1;
goto again;
}
/* Get the latest max_id to stay consistent with the num_devices */
if (sk->nr_items == 0)
/*
* last tree_search returns an empty buf, use the devid of
* the last dev_item of the previous tree_search
*/
fi_args->max_id = start_devid - 1;
else
fi_args->max_id = find_max_device_id(&args, sk->nr_items);
return 0;
}
/*
* For a given path, fill in the ioctl fs_ and info_ args.
* If the path is a btrfs mountpoint, fill info for all devices.
* If the path is a btrfs device, fill in only that device.
*
* The path provided must be either on a mounted btrfs fs,
* or be a mounted btrfs device.
*
* Returns 0 on success, or a negative errno.
*/
int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
struct btrfs_ioctl_dev_info_args **di_ret)
{
int fd = -1;
int ret = 0;
int ndevs = 0;
u64 last_devid = 0;
int replacing = 0;
struct btrfs_fs_devices *fs_devices_mnt = NULL;
struct btrfs_ioctl_dev_info_args *di_args;
struct btrfs_ioctl_dev_info_args tmp;
char mp[PATH_MAX];
memset(fi_args, 0, sizeof(*fi_args));
if (path_is_block_device(path) == 1) {
struct btrfs_super_block disk_super;
/* Ensure it's mounted, then set path to the mountpoint */
fd = open(path, O_RDONLY);
if (fd < 0) {
ret = -errno;
error("cannot open %s: %m", path);
goto out;
}
ret = check_mounted_where(fd, path, mp, sizeof(mp),
&fs_devices_mnt, SBREAD_DEFAULT, false);
if (!ret) {
ret = -EINVAL;
goto out;
}
if (ret < 0)
goto out;
path = mp;
/* Only fill in this one device */
fi_args->num_devices = 1;
ret = btrfs_read_dev_super(fd, &disk_super,
BTRFS_SUPER_INFO_OFFSET, 0);
if (ret < 0) {
ret = -EIO;
goto out;
}
last_devid = btrfs_stack_device_id(&disk_super.dev_item);
fi_args->max_id = last_devid;
memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
close(fd);
}
/* at this point path must not be for a block device */
fd = btrfs_open_file_or_dir(path);
if (fd < 0) {
ret = fd;
goto out;
}
/* fill in fi_args if not just a single device */
if (fi_args->num_devices != 1) {
ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
if (ret < 0) {
ret = -errno;
goto out;
}
/*
* The fs_args->num_devices does not include seed devices
*/
ret = search_chunk_tree_for_fs_info(fd, fi_args);
if (ret)
goto out;
/*
* search_chunk_tree_for_fs_info() will lacks the devid 0
* so manual probe for it here.
*/
ret = device_get_info(fd, 0, &tmp);
if (!ret) {
fi_args->num_devices++;
ndevs++;
replacing = 1;
if (last_devid == 0)
last_devid++;
}
}
if (!fi_args->num_devices)
goto out;
di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
if (!di_args) {
ret = -errno;
goto out;
}
if (replacing)
memcpy(di_args, &tmp, sizeof(tmp));
for (; last_devid <= fi_args->max_id && ndevs < fi_args->num_devices;
last_devid++) {
ret = device_get_info(fd, last_devid, &di_args[ndevs]);
if (ret == -ENODEV)
continue;
if (ret)
goto out;
ndevs++;
}
/*
* only when the only dev we wanted to find is not there then
* let any error be returned
*/
if (fi_args->num_devices != 1) {
BUG_ON(ndevs == 0);
ret = 0;
}
out:
close(fd);
return ret;
}
int get_fsid_fd(int fd, u8 *fsid)
{
int ret;
struct btrfs_ioctl_fs_info_args args;
ret = ioctl(fd, BTRFS_IOC_FS_INFO, &args);
if (ret < 0)
return -errno;
memcpy(fsid, args.fsid, BTRFS_FSID_SIZE);
return 0;
}
int get_fsid(const char *path, u8 *fsid, int silent)
{
int ret;
int fd;
int flags = O_RDONLY;
struct stat st;
ret = stat(path, &st);
if (ret < 0) {
if (!silent)
error("failed to stat %s: %m", path);
return -errno;
}
/*
* Open in non-blocking mode in case that path is a fifo or a special
* character device where opening gets stuck (but is interruptible).
*/
if ((st.st_mode & S_IFMT) == S_IFCHR || (st.st_mode & S_IFMT) == S_IFIFO)
flags |= O_NONBLOCK;
fd = open(path, flags);
if (fd < 0) {
if (!silent)
error("failed to open %s: %m", path);
return -errno;
}
ret = get_fsid_fd(fd, fsid);
close(fd);
return ret;
}
int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
u64 dev_cnt, int mixed, int ssd)
{
u64 allowed;
u64 profile = metadata_profile | data_profile;
allowed = btrfs_bg_flags_for_device_num(dev_cnt);
if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
warning("DUP is not recommended on filesystem with multiple devices");
}
if (metadata_profile & ~allowed) {
error("unable to create FS with metadata profile %s "
"(have %llu devices but %d devices are required)",
btrfs_group_profile_str(metadata_profile), dev_cnt,
btrfs_bg_type_to_devs_min(metadata_profile));
return 1;
}
if (data_profile & ~allowed) {
error("ERROR: unable to create FS with data profile %s "
"(have %llu devices but %d devices are required)",
btrfs_group_profile_str(data_profile), dev_cnt,
btrfs_bg_type_to_devs_min(data_profile));
return 1;
}
if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
warning("RAID6 is not recommended on filesystem with 3 devices only");
}
if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
warning("RAID5 is not recommended on filesystem with 2 devices only");
}
warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
"DUP may not actually lead to 2 copies on the device, see manual page");
return 0;
}
/*
* This reads a line from the stdin and only returns non-zero if the
* first whitespace delimited token is a case insensitive match with yes
* or y.
*/
int ask_user(const char *question)
{
char buf[30] = {0,};
char *saveptr = NULL;
char *answer;
printf("%s [y/N]: ", question);
return fgets(buf, sizeof(buf) - 1, stdin) &&
(answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
(!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
}
/*
* Partial representation of a line in /proc/pid/mountinfo
*/
struct mnt_entry {
const char *root;
const char *path;
const char *options1;
const char *fstype;
const char *device;
const char *options2;
};
/*
* Find first occurrence of up an option string (as "option=") in @options,
* separated by comma. Return allocated string as "option=value"
*/
static char *find_option(const char *options, const char *option)
{
char *tmp, *ret;
tmp = strstr(options, option);
if (!tmp)
return NULL;
ret = strdup(tmp);
tmp = ret;
while (*tmp && *tmp != ',')
tmp++;
*tmp = 0;
return ret;
}
/* Match whitespace separator */
static bool is_sep(char c)
{
return c == ' ' || c == '\t';
}
/* Advance @line skipping over all non-separator chars */
static void skip_nonsep(char **line)
{
while (**line && !is_sep(**line))
(*line)++;
}
/* Advance @line skipping over all separator chars, setting them to nul char */
static void skip_sep(char **line)
{
while (**line && is_sep(**line)) {
**line = 0;
(*line)++;
}
}
static bool isoctal(char c)
{
return '0' <= c && c <= '7';
}
/*
* Validate complete escape sequence used for mangling special chars in paths,
* eg. \012 == 10 == 0xa == '\n'.
* Mandatory format: backslash and 3 octal digits.
*/
static bool valid_escape(const char *str)
{
if (*str == 0 || *str != '\\')
return false;
str++;
if (*str == 0 || is_sep(*str) || !isoctal(*str))
return false;
str++;
if (*str == 0 || is_sep(*str) || !isoctal(*str))
return false;
str++;
if (*str == 0 || is_sep(*str) || !isoctal(*str))
return false;
return true;
}
/*
* Read a path from @line, with potentially mangled special characters.
* - the input is changed in-place when unmangling is done
* - end of path is a space character (a valid space in the path is mangled)
* - line is advanced to the final separator or nul character
* - returned path is a valid string terminated by zero or whitespace separator
*/
static char *read_path(char **line)
{
char *ret = *line;
char *out = *line;
while (**line) {
if (is_sep(**line))
break;
if (valid_escape(*line)) {
char c;
(*line)++;
c = ((*(*line)++) & 0b111) << 6;
c |= ((*(*line)++) & 0b111) << 3;
c |= ((*(*line)++) & 0b111);
*out++ = c;
} else {
*out++ = *(*line)++;
}
}
/*
* Unmangled characters make the final string shorter, add the null
* terminator. Otherwise keep the line at the space separator so
* followup parsing can continue.
*/
if (out < *line)
*out = 0;
return ret;
}
/*
* Parse a line from /proc/pid/mountinfo
* Example:
272 265 0:49 /subvol /mnt/path rw,noatime shared:145 - btrfs /dev/sda1 rw,subvolid=5598,subvol=/subvol
0 1 2 3 4 5 6 7 8 9 10
* Fields related to paths and options are parsed, @line is changed in place,
* separators are replaced by nul char, paths could be unmangled.
*/
static void parse_mntinfo_line(char *line, struct mnt_entry *ent)
{
/* Skip 0 */
skip_nonsep(&line);
skip_sep(&line);
/* Skip 1 */
skip_nonsep(&line);
skip_sep(&line);
/* Skip 2 */
skip_nonsep(&line);
skip_sep(&line);
/* Read 3 */
ent->root = read_path(&line);
skip_sep(&line);
/* Read 4 */
ent->path = read_path(&line);
skip_sep(&line);
/* Read 5 */
ent->options1 = line;
skip_nonsep(&line);
skip_sep(&line);
/* Skip 6 */
skip_nonsep(&line);
skip_sep(&line);
/* Skip 7 */
skip_nonsep(&line);
skip_sep(&line);
/* Read 8 */
ent->fstype = line;
skip_nonsep(&line);
skip_sep(&line);
/* Read 9 */
ent->device = read_path(&line);
skip_sep(&line);
/* Read 10 */
ent->options2 = line;
skip_nonsep(&line);
skip_sep(&line);
}
/*
* Compare the subvolume passed with the pathname of the directory mounted in
* btrfs. The pathname inside btrfs is different from getmnt and friends, since
* it can detect bind mounts to content from the inside of the original mount.
*
* Example:
* # mount -o subvol=/vol /dev/sda2 /mnt
* # mount --bind /mnt/dir2 /othermnt
*
* # mounts
* ...
* /dev/sda2 on /mnt type btrfs (ro,relatime,ssd,space_cache,subvolid=256,subvol=/vol)
* /dev/sda2 on /othermnt type btrfs (ro,relatime,ssd,space_cache,subvolid=256,subvol=/vol)
*
* # cat /proc/self/mountinfo
*
* 38 30 0:32 /vol /mnt ro,relatime - btrfs /dev/sda2 ro,ssd,space_cache,subvolid=256,subvol=/vol
* 37 29 0:32 /vol/dir2 /othermnt ro,relatime - btrfs /dev/sda2 ro,ssd,space_cache,subvolid=256,subvol=/vol
*
* If we try to find a mount point only using subvol and subvolid from mount
* options we would get mislead to believe that /othermnt has the same content
* as /mnt.
*
* But, using mountinfo, we have the pathaname _inside_ the filesystem, so we
* can filter out the mount points with bind mounts which have different content
* from the original mounts, in this case the mount point with id 37.
*/
int find_mount_fsroot(const char *subvol, const char *subvolid, char **mount)
{
FILE *mnt;
char *buf = NULL;
int bs = 4096;
int line = 0;
int ret = 0;
bool found = false;
mnt = fopen("/proc/self/mountinfo", "r");
if (!mnt)
return -1;
buf = malloc(bs);
if (!buf) {
ret = -ENOMEM;
goto out;
}
do {
int ch;
ch = fgetc(mnt);
if (ch == -1)
break;
if (ch == '\n') {
struct mnt_entry ent;
char *opt;
const char *value;
buf[line] = 0;
parse_mntinfo_line(buf, &ent);
/* Skip unrelated mounts */
if (strcmp(ent.fstype, "btrfs") != 0)
goto nextline;
if (strlen(ent.root) != strlen(subvol))
goto nextline;
if (strcmp(ent.root, subvol) != 0)
goto nextline;
/*
* Match subvolume by id found in mountinfo and
* requested by the caller
*/
opt = find_option(ent.options2, "subvolid=");
if (!opt)
goto nextline;
value = opt + strlen("subvolid=");
if (strcmp(value, subvolid) != 0) {
free(opt);
goto nextline;
}
free(opt);
/*
* First match is in most cases the original mount, not
* a bind mount. In case there are no further bind
* mounts, return what we found in @mount. Any
* following mount that matches by path and subvolume
* id is a bind mount and we return the original mount.
*/
if (found)
goto out;
found = true;
*mount = strdup(ent.path);
ret = 0;
goto nextline;
}
/*
* Grow buffer if needed, there are 3 paths up to PATH_MAX and
* mount options are limited by page size. Often the overall
* line length does not exceed 256.
*/
if (line >= bs) {
char *tmp;
bs += 4096;
tmp = realloc(buf, bs);
if (!tmp) {
ret = -ENOMEM;
goto out;
}
buf = tmp;
}
buf[line++] = ch;
continue;
nextline:
line = 0;
} while (1);
out:
free(buf);
fclose(mnt);
return ret;
}
/*
* return 0 if a btrfs mount point is found
* return 1 if a mount point is found but not btrfs
* return <0 if something goes wrong
*/
int find_mount_root(const char *path, char **mount_root)
{
FILE *mnttab;
int fd;
struct mntent *ent;
int len;
int ret = 0;
int not_btrfs = 1;
int longest_matchlen = 0;
char *longest_match = NULL;
fd = open(path, O_RDONLY | O_NOATIME);
if (fd < 0)
return -errno;
close(fd);
mnttab = setmntent("/proc/self/mounts", "r");
if (!mnttab)
return -errno;
while ((ent = getmntent(mnttab))) {
if (path_is_in_dir(ent->mnt_dir, path)) {
len = strlen(ent->mnt_dir);
if (longest_matchlen <= len) {
free(longest_match);
longest_matchlen = len;
longest_match = strdup(ent->mnt_dir);
if (!longest_match) {
ret = -errno;
break;
}
not_btrfs = strcmp(ent->mnt_type, "btrfs");
}
}
}
endmntent(mnttab);
if (ret)
return ret;
if (!longest_match)
return -ENOENT;
if (not_btrfs) {
free(longest_match);
return 1;
}
ret = 0;
*mount_root = realpath(longest_match, NULL);
if (!*mount_root)
ret = -errno;
free(longest_match);
return ret;
}
int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
{
int level;
for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
if (!path->nodes[level])
break;
if (path->slots[level] + 1 >=
btrfs_header_nritems(path->nodes[level]))
continue;
if (level == 0)
btrfs_item_key_to_cpu(path->nodes[level], key,
path->slots[level] + 1);
else
btrfs_node_key_to_cpu(path->nodes[level], key,
path->slots[level] + 1);
return 0;
}
return 1;
}
const char* btrfs_group_type_str(u64 flag)
{
u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
BTRFS_SPACE_INFO_GLOBAL_RSV;
switch (flag & mask) {
case BTRFS_BLOCK_GROUP_DATA:
return "Data";
case BTRFS_BLOCK_GROUP_SYSTEM:
return "System";
case BTRFS_BLOCK_GROUP_METADATA:
return "Metadata";
case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
return "Data+Metadata";
case BTRFS_SPACE_INFO_GLOBAL_RSV:
return "GlobalReserve";
default:
return "unknown";
}
}
const char* btrfs_group_profile_str(u64 flag)
{
int index;
flag &= ~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_RESERVED);
if (flag & ~BTRFS_BLOCK_GROUP_PROFILE_MASK)
return "UNKNOWN";
index = btrfs_bg_flags_to_raid_index(flag);
return btrfs_raid_array[index].upper_name;
}
u64 div_factor(u64 num, int factor)
{
if (factor == 10)
return num;
num *= factor;
num /= 10;
return num;
}
/*
* Get the length of the string converted from a u64 number.
*
* Result is equal to log10(num) + 1, but without the use of math library.
*/
int count_digits(u64 num)
{
int ret = 0;
if (num == 0)
return 1;
while (num > 0) {
ret++;
num /= 10;
}
return ret;
}
const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
{
int len = strlen(mnt);
if (!len)
return full_path;
if ((strncmp(mnt, full_path, len) != 0) || ((len > 1) && (full_path[len] != '/'))) {
error("not on mount point: %s", mnt);
exit(1);
}
if (mnt[len - 1] != '/')
len += 1;
return full_path + len;
}
/* Set the seed manually */
void init_rand_seed(u64 seed)
{
int i;
/* only use the last 48 bits */
for (i = 0; i < 3; i++) {
rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
seed >>= 16;
}
rand_seed_initialized = 1;
}
static void __init_seed(void)
{
struct timeval tv;
int ret;
int fd;
if(rand_seed_initialized)
return;
/* Use urandom as primary seed source. */
fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
ret = read(fd, rand_seed, sizeof(rand_seed));
close(fd);
if (ret < sizeof(rand_seed))
goto fallback;
} else {
fallback:
/* Use time and pid as fallback seed */
warning("failed to read /dev/urandom, use time and pid as random seed");
gettimeofday(&tv, 0);
rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
}
rand_seed_initialized = 1;
}
u32 rand_u32(void)
{
__init_seed();
/*
* Don't use nrand48, its range is [0,2^31) The highest bit will always
* be 0. Use jrand48 to include the highest bit.
*/
return (u32)jrand48(rand_seed);
}
/* Return random number in range [0, upper) */
unsigned int rand_range(unsigned int upper)
{
__init_seed();
/*
* Use the full 48bits to mod, which would be more uniformly
* distributed
*/
return (unsigned int)(jrand48(rand_seed) % upper);
}
int rand_int(void)
{
return (int)(rand_u32());
}
u64 rand_u64(void)
{
u64 ret = 0;
ret += rand_u32();
ret <<= 32;
ret += rand_u32();
return ret;
}
u16 rand_u16(void)
{
return (u16)(rand_u32());
}
u8 rand_u8(void)
{
return (u8)(rand_u32());
}
/*
* Parse a boolean value from an environment variable.
*
* As long as the environment variable is not set to "0", "n" or "\0",
* it would return true.
*/
bool get_env_bool(const char *env_name)
{
char *env_value_str;
env_value_str = getenv(env_name);
if (!env_value_str)
return false;
if (env_value_str[0] == '0' || env_value_str[0] == 'n' ||
env_value_str[0] == 0)
return false;
return true;
}
void btrfs_config_init(void)
{
bconf.output_format = CMD_FORMAT_TEXT;
bconf.verbose = BTRFS_BCONF_UNSET;
INIT_LIST_HEAD(&bconf.params);
}
void bconf_be_verbose(void)
{
if (bconf.verbose == BTRFS_BCONF_UNSET)
bconf.verbose = 1;
else
bconf.verbose++;
}
void bconf_be_quiet(void)
{
bconf.verbose = BTRFS_BCONF_QUIET;
}
void bconf_add_param(const char *key, const char *value)
{
struct config_param *param;