]> git.sesse.net Git - bcachefs-tools-debian/blob - bcacheadm.c
bcacheadm: Handle missing arg in rm-dev
[bcachefs-tools-debian] / bcacheadm.c
1 /*
2  * Authors: Kent Overstreet <kmo@daterainc.com>
3  *          Gabriel de Perthuis <g2p.code@gmail.com>
4  *          Jacob Malevich <jam@datera.io>
5  *
6  * GPLv2
7  */
8
9 #include <nih/option.h>
10 #include <nih/command.h>
11 #include <nih/main.h>
12 #include <nih/logging.h>
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <errno.h>
17 #include <inttypes.h>
18 #include <limits.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <blkid.h>
24 #include <string.h>
25 #include <linux/fs.h>
26 #include <sys/ioctl.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <uuid/uuid.h>
30 #include <dirent.h>
31 #include <bcache.h> //libbcache
32
33 #define PACKAGE_NAME "bcacheadm"
34 #define PACKAGE_VERSION "1.0"
35 #define PACKAGE_BUGREPORT "bugreport"
36
37
38
39 /* make-bcache globals */
40 int bdev = -1;
41 int devs = 0;
42 char *cache_devices[MAX_DEVS];
43 int tier_mapping[MAX_DEVS];
44 unsigned replacement_policy_mapping[MAX_DEVS];
45 char *backing_devices[MAX_DEVS];
46 char *backing_dev_labels[MAX_DEVS];
47 size_t i, nr_backing_devices = 0, nr_cache_devices = 0;
48 unsigned block_size = 0;
49 unsigned btree_node_size = 0;
50 unsigned bucket_sizes[MAX_DEVS];
51 int num_bucket_sizes = 0;
52 int writeback = 0, writearound = 0, discard = 0, wipe_bcache = 0;
53 unsigned replication_set = 0;
54 char *replacement_policy = 0;
55 uint64_t data_offset = BDEV_DATA_START_DEFAULT;
56 char *label = NULL;
57 struct cache_sb *cache_set_sb = NULL;
58 const char *cache_set_uuid = 0;
59 const char *csum_type = 0;
60 char *metadata_replicas = 0;
61 char *data_replicas = 0;
62 char *tier = 0;
63
64 /* rm-dev globals */
65 bool force_remove = false;
66
67 /* Modify globals */
68 bool modify_list_attrs = false;
69 static const char *modify_set_uuid = NULL;
70 static const char *modify_dev_uuid = NULL;
71
72 /* query-dev globals */
73 bool force_csum = false;
74 bool uuid_only = false;
75 bool query_brief = false;
76
77 /* probe globals */
78 bool udev = false;
79
80 /* list globals */
81 char *cset_dir = "/sys/fs/bcache";
82 bool list_devs = false;
83 static const char *internal_uuid = NULL;
84
85 /* status globals */
86 bool status_all = false;
87
88 /* capacity globals */
89 static const char *capacity_uuid = NULL;
90 bool capacity_devs = false;
91
92 /* stats globals */
93 bool stats_all = false;
94 bool stats_list = false;
95 static const char *stats_uuid = NULL;
96 static const char *stats_dev_uuid = NULL;
97 static const char *stats_cache_num = NULL;
98 bool stats_five_min = false;
99 bool stats_hour = false;
100 bool stats_day = false;
101 bool stats_total = false;
102
103 /* set_failed globals */
104 static const char *dev_failed_uuid = NULL;
105
106 /* make-bcache option setters */
107 static int set_block_size(NihOption *option, const char *arg)
108 {
109         block_size = hatoi_validate(arg, "block size");
110         return 0;
111 }
112
113 static int set_btree_node_size(NihOption *option, const char *arg)
114 {
115         btree_node_size = hatoi_validate(arg, "btree node size");
116         return 0;
117 }
118
119 static int set_cache(NihOption *option, const char *arg)
120 {
121         bdev = 0;
122         cache_devices[nr_cache_devices] = strdup(arg);
123         if(!tier)
124                 tier_mapping[nr_cache_devices] = 0;
125         else {
126                 int ntier = atoi(tier);
127                 if(ntier == 0 || ntier == 1)
128                         tier_mapping[nr_cache_devices] = ntier;
129                 else
130                         printf("Invalid tier %s\n", tier);
131         }
132
133         if (!replacement_policy)
134                 replacement_policy_mapping[nr_cache_devices] = 0;
135         else {
136                 int i = 0;
137
138                 while (replacement_policies[i] != NULL) {
139                         if (!strcmp(replacement_policy,
140                                     replacement_policies[i])) {
141                                 replacement_policy_mapping[nr_cache_devices] = i;
142                                 break;
143                         }
144                         i++;
145                 }
146
147                 if (replacement_policies[i] == NULL)
148                         printf("Invalid replacement policy: %s\n",
149                                replacement_policy);
150         }
151
152         devs++;
153         nr_cache_devices++;
154
155         return 0;
156 }
157
158 static int set_bdev(NihOption *option, const char *arg)
159 {
160         bdev = 1;
161
162         if(label)
163                 backing_dev_labels[nr_backing_devices] = strdup(label);
164
165         backing_devices[nr_backing_devices] = strdup(arg);
166
167         nr_backing_devices++;
168         devs++;
169
170         return 0;
171 }
172
173 static int set_bucket_sizes(NihOption *option, const char *arg)
174 {
175         bucket_sizes[num_bucket_sizes]=hatoi_validate(arg, "bucket size");
176         num_bucket_sizes++;
177         return 0;
178 }
179
180 /* probe setters */
181 static int set_udev(NihOption *option, const char *arg)
182 {
183         if (strcmp("udev", arg)) {
184                 printf("Invalid output format %s\n", arg);
185                 exit(EXIT_FAILURE);
186         }
187         udev = true;
188         return 0;
189 }
190
191
192 /* options */
193 static NihOption make_bcache_options[] = {
194 //      {int shortoption, char* longoption, char* help, NihOptionGroup, char* argname, void *value, NihOptionSetter}
195         {'C', "cache",  N_("Format a cache device"), NULL, "dev", NULL, set_cache},
196         {'B', "bdev",   N_("Format a backing device"), NULL, "dev", NULL, set_bdev},
197         {'l', "label",  N_("label"), NULL, "label", &label, NULL},
198         //Only one bucket_size supported until a list of bucket sizes is parsed correctly
199         {'b', "bucket", N_("bucket size"), NULL, "size", NULL, set_bucket_sizes},
200         //Does the default setter automatically convert strings to an int?
201         {'w', "block",  N_("block size (hard sector size of SSD, often 2k"), NULL, "size", NULL, set_block_size},
202
203         {'n', "btree-node",     N_("Btree node size, default 256k"), NULL, "size", NULL, set_btree_node_size},
204
205         {'t', "tier",   N_("tier of subsequent devices"), NULL,"#", &tier, NULL},
206         {'p', "cache_replacement_policy", N_("one of (lru|fifo|random)"), NULL,"policy", &replacement_policy, NULL},
207         {'o', "data_offset", N_("data offset in sectors"), NULL,"offset", &data_offset, NULL},
208
209         {0, "cset-uuid",        N_("UUID for the cache set"),           NULL,   "uuid", &cache_set_uuid, NULL},
210         {0, "csum-type",        N_("One of (none|crc32c|crc64)"),               NULL,   "type", &csum_type, NULL },
211         {0, "replication-set",N_("replication set of subsequent devices"),      NULL,   NULL, &replication_set, NULL },
212         {0, "meta-replicas",N_("number of metadata replicas"),          NULL,   "#", &metadata_replicas, NULL},
213         {0, "data-replicas",N_("number of data replicas"),              NULL,   "#", &data_replicas, NULL },
214
215         {0, "wipe-bcache",      N_("destroy existing bcache data if present"),          NULL, NULL, &wipe_bcache, NULL},
216         {0, "discard",          N_("enable discards"),          NULL, NULL, &discard,           NULL},
217         {0, "writeback",        N_("enable writeback"),         NULL, NULL, &writeback,         NULL},
218         {0, "writearound",      N_("enable writearound"),       NULL, NULL, &writearound,       NULL},
219
220         NIH_OPTION_LAST
221 };
222
223 static NihOption probe_bcache_options[] = {
224         {'o', "udev", N_("udev"), NULL, NULL, NULL, set_udev},
225         NIH_OPTION_LAST
226 };
227
228 static NihOption bcache_register_options[] = {
229         NIH_OPTION_LAST
230 };
231
232 static NihOption bcache_unregister_options[] = {
233         NIH_OPTION_LAST
234 };
235
236 static NihOption bcache_add_device_options[] = {
237         NIH_OPTION_LAST
238 };
239
240 static NihOption bcache_rm_device_options[] = {
241         {'f', "force", N_("force cache removal"), NULL, NULL, &force_remove, NULL},
242         NIH_OPTION_LAST
243 };
244
245 static NihOption bcache_modify_options[] = {
246         {'l', "list", N_("list attributes"), NULL, NULL, &modify_list_attrs, NULL},
247         {'u', "set", N_("cacheset uuid"), NULL, "UUID", &modify_set_uuid, NULL},
248         {'d', "dev", N_("device uuid"), NULL, "UUID", &modify_dev_uuid, NULL},
249         NIH_OPTION_LAST
250 };
251
252 static NihOption query_devs_options[] = {
253         {'f', "force_csum", N_("force_csum"), NULL, NULL, &force_csum, NULL},
254         {'u', "uuid-only", N_("only print out the uuid for the devices, not the whole superblock"), NULL, NULL, &uuid_only, NULL},
255         {'b', "brief", N_("only print out the cluster,server,and disk uuids"), NULL, NULL, &query_brief, NULL},
256         NIH_OPTION_LAST
257 };
258
259 static NihOption list_cachesets_options[] = {
260         {'d', "dir", N_("directory"), NULL, NULL, &cset_dir, NULL},
261         {0, "list-devs", N_("list all devices in the cache sets as well"), NULL, NULL, &list_devs, NULL},
262         {0, "internal_uuid", N_("Show the internal UUID for the given cacheset UUID"), NULL, "UUID", &internal_uuid, NULL},
263         NIH_OPTION_LAST
264 };
265
266 static NihOption status_options[] = {
267         {'a', "all", N_("all"), NULL, NULL, &status_all, NULL},
268         NIH_OPTION_LAST
269 };
270
271 static NihOption capacity_options[] = {
272         {'u', "set", N_("cache_set UUID"), NULL, "UUID", &capacity_uuid, NULL},
273         {'d', "devs", N_("dev UUID"), NULL, NULL, &capacity_devs, NULL},
274         NIH_OPTION_LAST
275 };
276
277 static NihOption stats_options[] = {
278         {'a', "all", N_("all"), NULL, NULL, &stats_all, NULL},
279         {'l', "list", N_("list"), NULL, NULL, &stats_list, NULL},
280         {'u', "set", N_("cache_set UUID"), NULL, "UUID", &stats_uuid, NULL},
281         {'d', "dev", N_("dev UUID"), NULL, "UUID", &stats_dev_uuid, NULL},
282         {'c', "cache", N_("cache number (starts from 0)"), NULL, "CACHE#", &stats_cache_num, NULL},
283         {0, "five-min-stats", N_("stats accumulated in last 5 minutes"), NULL, NULL, &stats_five_min, NULL},
284         {0, "hour-stats", N_("stats accumulated in last hour"), NULL, NULL, &stats_hour, NULL},
285         {0, "day-stats", N_("stats accumulated in last day"), NULL, NULL, &stats_day, NULL},
286         {0, "total-stats", N_("stats accumulated in total"), NULL, NULL, &stats_total, NULL},
287         NIH_OPTION_LAST
288 };
289
290 static NihOption set_failed_options[] = {
291         {'d', "dev", N_("dev UUID"), NULL, "UUID", &dev_failed_uuid, NULL},
292         NIH_OPTION_LAST
293 };
294
295 static NihOption options[] = {
296         NIH_OPTION_LAST
297 };
298
299
300 /* commands */
301 int make_bcache(NihCommand *command, char *const *args)
302 {
303         int cache_dev_fd[devs];
304
305         int backing_dev_fd[devs];
306
307         unsigned cache_mode;
308
309         cache_set_sb = calloc(1, sizeof(*cache_set_sb) +
310                                      sizeof(struct cache_member) * devs);
311
312         uuid_generate(cache_set_sb->set_uuid.b);
313
314         if (cache_set_uuid) {
315                 if(uuid_parse(cache_set_uuid, cache_set_sb->user_uuid.b)) {
316                         fprintf(stderr, "Bad uuid\n");
317                         return -1;
318                 }
319         } else {
320                 uuid_generate(cache_set_sb->user_uuid.b);
321         }
322
323         if (label)
324                 memcpy(cache_set_sb->label, label, sizeof(cache_set_sb->label));
325
326         if (csum_type) {
327                 SET_CACHE_PREFERRED_CSUM_TYPE(cache_set_sb,
328                                 read_string_list_or_die(csum_type, csum_types,
329                                         "csum type"));
330         } else {
331                 SET_CACHE_PREFERRED_CSUM_TYPE(cache_set_sb, BCH_CSUM_CRC32C);
332         }
333
334         if (metadata_replicas) {
335                 SET_CACHE_SET_META_REPLICAS_WANT(cache_set_sb,
336                                 strtoul_or_die(metadata_replicas,
337                                         CACHE_SET_META_REPLICAS_WANT_MAX,
338                                         "meta replicas"));
339         } else {
340                 SET_CACHE_SET_META_REPLICAS_WANT(cache_set_sb, 1);
341         }
342
343         if (data_replicas) {
344                 SET_CACHE_SET_DATA_REPLICAS_WANT(cache_set_sb,
345                         strtoul_or_die(data_replicas,
346                                 CACHE_SET_DATA_REPLICAS_WANT_MAX,
347                                 "data replicas"));
348         } else {
349                 SET_CACHE_SET_DATA_REPLICAS_WANT(cache_set_sb, 1);
350         }
351
352         if (bdev == -1) {
353                 fprintf(stderr, "Please specify -C or -B\n");
354                 exit(EXIT_FAILURE);
355         }
356
357         if (!bucket_sizes[0])
358                 bucket_sizes[0] = 1024;
359
360         for (i = 0; i < nr_cache_devices; i++)
361                 next_cache_device(cache_set_sb,
362                                   replication_set,
363                                   tier_mapping[i],
364                                   replacement_policy_mapping[i],
365                                   discard);
366
367         if (!cache_set_sb->nr_in_set && !nr_backing_devices) {
368                 fprintf(stderr, "Please supply a device\n");
369                 exit(EXIT_FAILURE);
370         }
371
372         i = 0;
373         do {
374                 if (bucket_sizes[i] < block_size) {
375                         fprintf(stderr,
376                         "Bucket size cannot be smaller than block size\n");
377                         exit(EXIT_FAILURE);
378                 }
379                 i++;
380         } while (i < num_bucket_sizes);
381
382         if (!block_size) {
383                 for (i = 0; i < cache_set_sb->nr_in_set; i++)
384                         block_size = max(block_size,
385                                          get_blocksize(cache_devices[i]));
386
387                 for (i = 0; i < nr_backing_devices; i++)
388                         block_size = max(block_size,
389                                          get_blocksize(backing_devices[i]));
390         }
391
392         for (i = 0; i < cache_set_sb->nr_in_set; i++)
393                 cache_dev_fd[i] = dev_open(cache_devices[i], wipe_bcache);
394
395         for (i = 0; i < nr_backing_devices; i++)
396                 backing_dev_fd[i] = dev_open(backing_devices[i], wipe_bcache);
397
398         write_cache_sbs(cache_dev_fd, cache_set_sb, block_size,
399                         bucket_sizes, num_bucket_sizes, btree_node_size);
400
401         if (writeback)
402                 cache_mode = CACHE_MODE_WRITEBACK;
403         else if (writearound)
404                 cache_mode = CACHE_MODE_WRITEAROUND;
405         else
406                 cache_mode = CACHE_MODE_WRITETHROUGH;
407
408         for (i = 0; i < nr_backing_devices; i++)
409                 write_backingdev_sb(backing_dev_fd[i],
410                                     block_size, bucket_sizes,
411                                     cache_mode, data_offset,
412                                     backing_dev_labels[i],
413                                     cache_set_sb->user_uuid,
414                                     cache_set_sb->set_uuid);
415
416
417         return 0;
418 }
419
420 int probe_bcache(NihCommand *command, char *const *args)
421 {
422         int i;
423         char *err = NULL;
424
425         for (i = 0; args[i] != NULL; i++) {
426                 err = probe(args[i], udev);
427                 if(err) {
428                         printf("probe_bcache error: %s\n", err);
429                         return -1;
430                 }
431         }
432
433         return 0;
434 }
435
436 int bcache_register(NihCommand *command, char *const *args)
437 {
438         char *err = NULL;
439
440         err = register_bcache(args);
441         if (err) {
442                 printf("bcache_register error: %s\n", err);
443                 return -1;
444         }
445
446         return 0;
447 }
448
449 int bcache_unregister(NihCommand *command, char *const *args)
450 {
451         char *err = NULL;
452
453         err = unregister_bcache(args);
454         if (err) {
455                 printf("bcache_unregister error: %s\n", err);
456                 return -1;
457         }
458
459         return 0;
460 }
461
462 int bcache_add_devices(NihCommand *command, char *const *args)
463 {
464         char *err;
465
466         err = add_devices(args);
467         if (err) {
468                 printf("bcache_add_devices error: %s\n", err);
469                 return -1;
470         }
471
472         return 0;
473 }
474
475 int bcache_rm_device(NihCommand *command, char *const *args)
476 {
477         char *err;
478
479         if (!args[0]) {
480                 printf("Must provide a device name\n");
481                 return -1;
482         }
483
484         err = remove_device(args[0], force_remove);
485         if (err) {
486                 printf("bcache_rm_devices error: %s\n", err);
487                 return -1;
488         }
489
490         return 0;
491 }
492
493 int bcache_modify(NihCommand *command, char *const *args)
494 {
495         char *err;
496         char path[MAX_PATH];
497         char *attr = args[0];
498         char *val = NULL;
499         int fd = -1;
500
501         if (modify_list_attrs) {
502                 sysfs_attr_list();
503                 return 0;
504         }
505
506         if (!modify_set_uuid) {
507                 printf("Must provide a cacheset uuid\n");
508                 return -1;
509         }
510
511         snprintf(path, MAX_PATH, "%s/%s", cset_dir, modify_set_uuid);
512
513         if(!attr) {
514                 printf("Must provide the name of an attribute to modify\n");
515                 goto err;
516         }
517
518         enum sysfs_attr type = sysfs_attr_type(attr);
519
520         if (type == -1)
521                 goto err;
522         else if(type == INTERNAL_ATTR)
523                 strcat(path, "/internal");
524         else if(type == CACHE_ATTR) {
525                 if(modify_dev_uuid) {
526                         /* searches all cache# for a matching uuid,
527                          * path gets modified to the correct cache path */
528                         char subdir[10] = "/cache";
529                         err = find_matching_uuid(path, subdir,
530                                         modify_dev_uuid);
531                         if (err) {
532                                 printf("Failed to find "
533                                         "matching dev %s\n", err);
534                                 goto err;
535                         } else {
536                                 strcat(path, subdir);
537                         }
538                 } else {
539                         printf("Must provide a device uuid\n");
540                 }
541         }
542         /* SET_ATTRs are just in the current dir */
543
544         strcat(path, "/");
545         strcat(path, attr);
546
547         val = args[1];
548         if (!val) {
549                 printf("Must provide a value to change the attribute to\n");
550                 goto err;
551         }
552
553         fd = open(path, O_WRONLY);
554         if (fd < 0) {
555                 printf("Unable to open modify attr with path %s\n", path);
556                 goto err;
557         }
558
559         write(fd, val, strlen(val));
560
561 err:
562         if(fd)
563                 close(fd);
564         return 0;
565 }
566
567 int bcache_list_cachesets(NihCommand *command, char *const *args)
568 {
569         char *err = NULL;
570
571         if (internal_uuid) {
572                 char uuid_path[MAX_PATH];
573                 DIR *uuid_dir;
574                 char buf[MAX_PATH];
575
576                 snprintf(uuid_path, MAX_PATH, "%s/%s", cset_dir, internal_uuid);
577
578                 err = "uuid does not exist";
579                 if((uuid_dir = opendir(uuid_path)) == NULL)
580                         goto err;
581
582                 err = read_stat_dir(uuid_dir, uuid_path, "/internal/internal_uuid", buf);
583                 if (err)
584                         goto err;
585                 printf("%s", buf);
586                 return 0;
587         }
588
589         err = list_cachesets(cset_dir, list_devs);
590         if (err)
591                 goto err;
592
593         return 0;
594
595 err:
596         printf("bcache_list_cachesets error :%s\n", err);
597         return -1;
598 }
599
600 int bcache_query_devs(NihCommand *command, char *const *args)
601 {
602         int i;
603
604         if (query_brief)
605                 printf("%-10s%-40s%-40s%-40s\n", "dev name", "disk uuid",
606                                 "server uuid", "cluster uuid");
607
608         for (i = 0; args[i] != NULL; i++) {
609                 char dev_uuid[40];
610                 struct cache_sb *sb = query_dev(args[i], force_csum,
611                                 !query_brief, uuid_only, dev_uuid);
612
613                 if (!sb) {
614                         printf("error opening the superblock for %s\n",
615                                         args[i]);
616                         return -1;
617                 }
618
619                 if (uuid_only) {
620                         printf("%s\n", dev_uuid);
621                 } else if (query_brief) {
622                         char set_uuid_str[40], dev_uuid_str[40];
623                         char *clus_uuid = (char *)sb->label;
624
625                         uuid_unparse(sb->user_uuid.b, set_uuid_str);
626                         uuid_unparse(sb->disk_uuid.b, dev_uuid_str);
627                         if (!strcmp(clus_uuid, ""))
628                                 clus_uuid = "None";
629
630                         printf("%-10s%-40s%-40s%-40s\n", args[i],
631                                         dev_uuid_str,
632                                         set_uuid_str,
633                                         clus_uuid);
634                 }
635                 free(sb);
636         }
637
638         return 0;
639 }
640
641 int bcache_status(NihCommand *command, char *const *args)
642 {
643         int i, dev_count = 0, seq, cache_count = 0;
644         struct cache_sb *seq_sb = NULL;
645         char cache_path[MAX_PATH];
646         char *dev_names[MAX_DEVS];
647         char *dev_uuids[MAX_DEVS];
648         char intbuf[4];
649         char set_uuid[40];
650
651         for (i = 0; args[i] != NULL; i++) {
652                 struct cache_sb *sb = query_dev(args[i], false, false,
653                                 false, NULL);
654
655                 if (!sb) {
656                         printf("Unable to open superblock, bad path\n");
657                         return -1;
658                 }
659
660                 if (!seq_sb || sb->seq > seq) {
661                         seq = sb->seq;
662                         seq_sb = sb;
663                 } else
664                         free(sb);
665         }
666
667         if (!seq_sb) {
668                 printf("Unable to find a superblock\n");
669                 return -1;
670         } else {
671                 uuid_unparse(seq_sb->user_uuid.b, set_uuid);
672                 printf("%-50s%-15s%-4s\n", "uuid", "state", "tier");
673         }
674
675         snprintf(intbuf, 4, "%d", i);
676         snprintf(cache_path, MAX_PATH, "%s/%s/%s", cset_dir, set_uuid,
677                         "cache0");
678
679         /*
680          * Get a list of all the devices from sysfs first, then
681          * compare it to the list we get back from the most up
682          * to date superblock. If there are any devices in the superblock
683          * that are not in sysfs, print out 'missing'
684          */
685         while (true) {
686                 char buf[MAX_PATH];
687                 int len;
688                 DIR *cache_dir;
689
690                 if(((cache_dir = opendir(cache_path)) == NULL) &&
691                     cache_count > MAX_DEVS)
692                         break;
693
694                 if (cache_dir)
695                         closedir(cache_dir);
696
697                 if((len = readlink(cache_path, buf, sizeof(buf) - 1)) != -1) {
698                         struct cache_sb *sb;
699                         char dev_uuid[40];
700                         char dev_path[32];
701
702                         buf[len] = '\0';
703                         dev_names[dev_count] = dev_name(buf);
704                         snprintf(dev_path, MAX_PATH, "%s/%s", "/dev",
705                                         dev_names[dev_count]);
706                         sb = query_dev(dev_path, false, false,
707                                         true, dev_uuid);
708                         if (!sb) {
709                                 printf("error reading %s\n", dev_path);
710                                 return -1;
711                         } else
712                                 free(sb);
713
714                         dev_uuids[dev_count] = strdup(dev_uuid);
715                         dev_count++;
716                 }
717
718                 cache_path[strlen(cache_path) - strlen(intbuf)] = 0;
719                 cache_count++;
720
721                 snprintf(intbuf, 4, "%d", cache_count);
722                 strcat(cache_path, intbuf);
723         }
724
725         for (i = 0; i < seq_sb->nr_in_set; i++) {
726                 char uuid_str[40];
727                 struct cache_member *m = seq_sb->members + i;
728                 char dev_state[32];
729                 int j;
730
731                 uuid_unparse(m->uuid.b, uuid_str);
732                 snprintf(dev_state, MAX_PATH, "%s",
733                          cache_state[CACHE_STATE(m)]);
734
735                 for (j = 0; j < dev_count; j++) {
736                         if (!strcmp(uuid_str, dev_uuids[j])) {
737                                 break;
738                         } else if (j == dev_count - 1) {
739                                 if (!strcmp(cache_state[CACHE_STATE(m)], "active"))
740                                         snprintf(dev_state, MAX_PATH, "%s", "missing");
741                                 break;
742                         }
743                 }
744
745                 printf("%-50s%-15s%-4llu\n", uuid_str, dev_state,
746                                 CACHE_TIER(m));
747         }
748
749         if (seq_sb)
750                 free(seq_sb);
751         for (i = 0; i < dev_count; i++) {
752                 free(dev_names[i]);
753                 free(dev_uuids[i]);
754         }
755
756         return 0;
757 }
758
759 int bcache_capacity(NihCommand *command, char *const *args)
760 {
761         char *err = "Must provide a cacheset uuid";
762         if(!capacity_uuid)
763                 goto err;
764
765         err = bcache_get_capacity(cset_dir, capacity_uuid, capacity_devs);
766         if (err)
767                 goto err;
768
769         return 0;
770
771 err:
772         printf("bcache_capacity failed with error: %s\n", err);
773         return -1;
774
775 }
776
777 static char *stats_subdir(char* stats_dir)
778 {
779         char tmp[50] = "/";
780         char *err = NULL;
781         if(stats_dev_uuid) {
782                 strcat(tmp, "cache");
783                 err = find_matching_uuid(stats_dir, tmp, stats_dev_uuid);
784                 if(err)
785                         goto err;
786         } else if(stats_cache_num) {
787                 strcat(tmp, "cache");
788                 strcat(tmp, stats_cache_num);
789         } else if (stats_five_min)
790                 strcat(tmp, "stats_five_minute");
791         else if (stats_hour)
792                 strcat(tmp, "stats_hour");
793         else if (stats_day)
794                 strcat(tmp, "stats_day");
795         else if (stats_total)
796                 strcat(tmp, "stats_total");
797         else
798                 return err;
799
800         strcat(stats_dir, tmp);
801
802 err:
803         return err;
804 }
805
806 int bcache_stats(NihCommand *command, char *const *args)
807 {
808         int i;
809         char stats_dir[MAX_PATH];
810         DIR *dir = NULL;
811         struct dirent *ent = NULL;
812         char *err = NULL;
813         char buf[MAX_PATH];
814
815         if (stats_uuid) {
816                 snprintf(stats_dir, MAX_PATH, "%s/%s", cset_dir, stats_uuid);
817                 err = stats_subdir(stats_dir);
818                 if(err)
819                         goto err;
820
821                 dir = opendir(stats_dir);
822                 if (!dir) {
823                         err = "Failed to open dir";
824                         goto err;
825                 }
826         } else {
827                 err = "Must provide a cacheset uuid";
828                 goto err;
829         }
830
831         if(stats_list || stats_all) {
832                 while ((ent = readdir(dir)) != NULL) {
833                         err = read_stat_dir(dir, stats_dir, ent->d_name, buf);
834                         if (err)
835                                 goto err;
836                         if(stats_list)
837                                 printf("%s\n", ent->d_name);
838                         if(stats_all)
839                                 printf("\t%s\n", buf);
840                 }
841         }
842
843         for (i = 0; args[i] != NULL; i++) {
844                 err = read_stat_dir(dir, stats_dir, args[i], buf);
845                 if (err)
846                         goto err;
847                 printf("%s\n", buf);
848         }
849
850         closedir(dir);
851         return 0;
852
853 err:
854         closedir(dir);
855         printf("bcache_stats error: %s\n", err);
856         return -1;
857 }
858
859 int bcache_set_failed(NihCommand *command, char *const *args)
860 {
861         char *err = NULL;
862
863         if (!dev_failed_uuid) {
864                 printf("Pass in a dev uuid\n");
865                 return -1;
866         }
867
868         err = device_set_failed(dev_failed_uuid);
869         if (err) {
870                 printf("bcache_set_failed_ioctl error: %s\n", err);
871                 return -1;
872         }
873
874         return 0;
875 }
876
877 static NihCommand commands[] = {
878         {"format", N_("format <list of drives>"),
879                   "Format one or a list of devices with bcache datastructures."
880                   " You need to do this before you create a volume",
881                   N_("format drive[s] with bcache"),
882                   NULL, make_bcache_options, make_bcache},
883         {"probe", N_("probe <list of devices>"),
884                   "Does a blkid_probe on a device",
885                   N_("Does a blkid_probe on a device"),
886                   NULL, probe_bcache_options, probe_bcache},
887         {"register", N_("register <list of devices>"),
888                      "Registers a list of devices",
889                      N_("Registers a list of devices"),
890                      NULL, bcache_register_options, bcache_register},
891         {"unregister", N_("unregister <list of devices>"),
892                      "Unregisters a list of devices",
893                      N_("Unregisters a list of devices"),
894                      NULL, bcache_unregister_options, bcache_unregister},
895         {"add-devs", N_("add-devs --tier=# <list of devices>"),
896                 "Adds a list of devices to a cacheset",
897                 N_("Adds a list of devices to a cacheset"),
898                 NULL, bcache_add_device_options, bcache_add_devices},
899         {"rm-dev", N_("rm-dev <dev>"),
900                 "Removes a device from its cacheset",
901                 N_("Removes a device from its cacheset"),
902                 NULL, bcache_rm_device_options, bcache_rm_device},
903         {"modify", N_("modify --set=UUID (dev=UUID) name value"),
904                 "Modifies attributes related to the cacheset",
905                 N_("Modifies attributes related to the cacheset"),
906                 NULL, bcache_modify_options, bcache_modify},
907         {"list-cachesets", N_("list-cachesets"),
908                            "Lists cachesets in /sys/fs/bcache",
909                            N_("Lists cachesets in /sys/fs/bcache"),
910                            NULL, list_cachesets_options, bcache_list_cachesets},
911         {"query-devs", N_("query <list of devices>"),
912                        "Gives info about the superblock of a list of devices",
913                        N_("show superblock on each of the listed drive"),
914                        NULL, query_devs_options, bcache_query_devs},
915         {"status", N_("status <list of devices>"),
916                    "Finds the status of the most up to date superblock",
917                    N_("Finds the status of the most up to date superblock"),
918                    NULL, status_options, bcache_status},
919         {"capacity", N_("capacity --set=UUID"),
920                 "Shows the capacity of the cacheset",
921                 N_("Shows the capacity of the cacheset"),
922                 NULL, capacity_options, bcache_capacity},
923         {"stats", N_("stats <list of devices>"),
924                   "List various bcache statistics",
925                   N_("List various bcache statistics"),
926                   NULL, stats_options, bcache_stats},
927         {"set-failed", N_("set-failed --dev=UUID"),
928                 "Sets a device to the FAILED state",
929                 N_("Sets a device to the FAILED state"),
930                 NULL, set_failed_options, bcache_set_failed},
931         NIH_COMMAND_LAST
932 };
933
934
935 int main(int argc, char *argv[])
936 {
937         int ret = 0;
938         nih_main_init (argv[0]);
939
940         nih_option_set_synopsis (_("Manage bcache devices"));
941         nih_option_set_help (
942                         _("Helps you manage bcache devices"));
943
944         ret = nih_command_parser (NULL, argc, argv, options, commands);
945         if (ret < 0)
946                 exit (1);
947
948         nih_signal_reset();
949
950         return 0;
951 }