btrfs-progs: close all fs_devices before exit in some commands
[platform/upstream/btrfs-progs.git] / cmds-device.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <fcntl.h>
22 #include <sys/ioctl.h>
23 #include <errno.h>
24 #include <sys/stat.h>
25 #include <getopt.h>
26
27 #include "kerncompat.h"
28 #include "ctree.h"
29 #include "ioctl.h"
30 #include "utils.h"
31 #include "volumes.h"
32 #include "cmds-fi-usage.h"
33
34 #include "commands.h"
35
36 static const char * const device_cmd_group_usage[] = {
37         "btrfs device <command> [<args>]",
38         NULL
39 };
40
41 static const char * const cmd_device_add_usage[] = {
42         "btrfs device add [options] <device> [<device>...] <path>",
43         "Add a device to a filesystem",
44         "-K|--nodiscard    do not perform whole device TRIM",
45         "-f|--force        force overwrite existing filesystem on the disk",
46         NULL
47 };
48
49 static int cmd_device_add(int argc, char **argv)
50 {
51         char    *mntpnt;
52         int     i, fdmnt, ret=0, e;
53         DIR     *dirstream = NULL;
54         int discard = 1;
55         int force = 0;
56
57         while (1) {
58                 int c;
59                 static const struct option long_options[] = {
60                         { "nodiscard", optional_argument, NULL, 'K'},
61                         { "force", no_argument, NULL, 'f'},
62                         { NULL, 0, NULL, 0}
63                 };
64
65                 c = getopt_long(argc, argv, "Kf", long_options, NULL);
66                 if (c < 0)
67                         break;
68                 switch (c) {
69                 case 'K':
70                         discard = 0;
71                         break;
72                 case 'f':
73                         force = 1;
74                         break;
75                 default:
76                         usage(cmd_device_add_usage);
77                 }
78         }
79
80         argc = argc - optind;
81
82         if (check_argc_min(argc, 2))
83                 usage(cmd_device_add_usage);
84
85         mntpnt = argv[optind + argc - 1];
86
87         fdmnt = open_file_or_dir(mntpnt, &dirstream);
88         if (fdmnt < 0) {
89                 fprintf(stderr, "ERROR: can't access '%s'\n", mntpnt);
90                 return 1;
91         }
92
93         for (i = optind; i < optind + argc - 1; i++){
94                 struct btrfs_ioctl_vol_args ioctl_args;
95                 int     devfd, res;
96                 u64 dev_block_count = 0;
97                 int mixed = 0;
98                 char *path;
99
100                 res = test_dev_for_mkfs(argv[i], force);
101                 if (res) {
102                         ret++;
103                         continue;
104                 }
105
106                 devfd = open(argv[i], O_RDWR);
107                 if (devfd < 0) {
108                         fprintf(stderr, "ERROR: Unable to open device '%s'\n", argv[i]);
109                         ret++;
110                         continue;
111                 }
112
113                 res = btrfs_prepare_device(devfd, argv[i], 1, &dev_block_count,
114                                            0, &mixed, discard);
115                 close(devfd);
116                 if (res) {
117                         ret++;
118                         goto error_out;
119                 }
120
121                 path = canonicalize_path(argv[i]);
122                 if (!path) {
123                         fprintf(stderr,
124                                 "ERROR: Could not canonicalize pathname '%s': %s\n",
125                                 argv[i], strerror(errno));
126                         ret++;
127                         goto error_out;
128                 }
129
130                 memset(&ioctl_args, 0, sizeof(ioctl_args));
131                 strncpy_null(ioctl_args.name, path);
132                 res = ioctl(fdmnt, BTRFS_IOC_ADD_DEV, &ioctl_args);
133                 e = errno;
134                 if (res < 0) {
135                         fprintf(stderr, "ERROR: error adding the device '%s' - %s\n",
136                                 path, strerror(e));
137                         ret++;
138                 }
139                 free(path);
140         }
141
142 error_out:
143         close_file_or_dir(fdmnt, dirstream);
144         btrfs_close_all_devices();
145         return !!ret;
146 }
147
148 static int _cmd_device_remove(int argc, char **argv,
149                 const char * const *usagestr)
150 {
151         char    *mntpnt;
152         int     i, fdmnt, ret=0, e;
153         DIR     *dirstream = NULL;
154
155         if (check_argc_min(argc, 3))
156                 usage(usagestr);
157
158         mntpnt = argv[argc - 1];
159
160         fdmnt = open_file_or_dir(mntpnt, &dirstream);
161         if (fdmnt < 0) {
162                 fprintf(stderr, "ERROR: can't access '%s'\n", mntpnt);
163                 return 1;
164         }
165
166         for(i=1 ; i < argc - 1; i++ ){
167                 struct  btrfs_ioctl_vol_args arg;
168                 int     res;
169
170                 if (!is_block_device(argv[i])) {
171                         fprintf(stderr,
172                                 "ERROR: %s is not a block device\n", argv[i]);
173                         ret++;
174                         continue;
175                 }
176                 memset(&arg, 0, sizeof(arg));
177                 strncpy_null(arg.name, argv[i]);
178                 res = ioctl(fdmnt, BTRFS_IOC_RM_DEV, &arg);
179                 e = errno;
180                 if (res) {
181                         const char *msg;
182
183                         if (res > 0)
184                                 msg = btrfs_err_str(res);
185                         else
186                                 msg = strerror(e);
187                         fprintf(stderr,
188                                 "ERROR: error removing the device '%s' - %s\n",
189                                 argv[i], msg);
190                         ret++;
191                 }
192         }
193
194         close_file_or_dir(fdmnt, dirstream);
195         return !!ret;
196 }
197
198 static const char * const cmd_device_remove_usage[] = {
199         "btrfs device remove <device> [<device>...] <path>",
200         "Remove a device from a filesystem",
201         NULL
202 };
203
204 static int cmd_device_remove(int argc, char **argv)
205 {
206         return _cmd_device_remove(argc, argv, cmd_device_remove_usage);
207 }
208
209 static const char * const cmd_device_delete_usage[] = {
210         "btrfs device delete <device> [<device>...] <path>",
211         "Remove a device from a filesystem",
212         NULL
213 };
214
215 static int cmd_device_delete(int argc, char **argv)
216 {
217         return _cmd_device_remove(argc, argv, cmd_device_delete_usage);
218 }
219
220 static const char * const cmd_device_scan_usage[] = {
221         "btrfs device scan [(-d|--all-devices)|<device> [<device>...]]",
222         "Scan devices for a btrfs filesystem",
223         " -d|--all-devices (deprecated)",
224         NULL
225 };
226
227 static int cmd_device_scan(int argc, char **argv)
228 {
229         int i;
230         int devstart = 1;
231         int all = 0;
232         int ret = 0;
233
234         optind = 1;
235         while (1) {
236                 int c;
237                 static const struct option long_options[] = {
238                         { "all-devices", no_argument, NULL, 'd'},
239                         { NULL, 0, NULL, 0}
240                 };
241
242                 c = getopt_long(argc, argv, "d", long_options, NULL);
243                 if (c < 0)
244                         break;
245                 switch (c) {
246                 case 'd':
247                         all = 1;
248                         break;
249                 default:
250                         usage(cmd_device_scan_usage);
251                 }
252         }
253
254         if (all && check_argc_max(argc, 2))
255                 usage(cmd_device_scan_usage);
256
257         if (all || argc == 1) {
258                 printf("Scanning for Btrfs filesystems\n");
259                 ret = btrfs_scan_lblkid();
260                 if (ret)
261                         fprintf(stderr, "ERROR: error %d while scanning\n", ret);
262                 ret = btrfs_register_all_devices();
263                 if (ret)
264                         fprintf(stderr, "ERROR: error %d while registering\n", ret);
265                 goto out;
266         }
267
268         for( i = devstart ; i < argc ; i++ ){
269                 char *path;
270
271                 if (!is_block_device(argv[i])) {
272                         fprintf(stderr,
273                                 "ERROR: %s is not a block device\n", argv[i]);
274                         ret = 1;
275                         goto out;
276                 }
277                 path = canonicalize_path(argv[i]);
278                 if (!path) {
279                         fprintf(stderr,
280                                 "ERROR: Could not canonicalize path '%s': %s\n",
281                                 argv[i], strerror(errno));
282                         ret = 1;
283                         goto out;
284                 }
285                 printf("Scanning for Btrfs filesystems in '%s'\n", path);
286                 if (btrfs_register_one_device(path) != 0) {
287                         ret = 1;
288                         free(path);
289                         goto out;
290                 }
291                 free(path);
292         }
293
294 out:
295         btrfs_close_all_devices();
296         return !!ret;
297 }
298
299 static const char * const cmd_device_ready_usage[] = {
300         "btrfs device ready <device>",
301         "Check device to see if it has all of its devices in cache for mounting",
302         NULL
303 };
304
305 static int cmd_device_ready(int argc, char **argv)
306 {
307         struct  btrfs_ioctl_vol_args args;
308         int     fd;
309         int     ret;
310         char    *path;
311
312         if (check_argc_min(argc, 2))
313                 usage(cmd_device_ready_usage);
314
315         fd = open("/dev/btrfs-control", O_RDWR);
316         if (fd < 0) {
317                 perror("failed to open /dev/btrfs-control");
318                 return 1;
319         }
320
321         path = canonicalize_path(argv[argc - 1]);
322         if (!path) {
323                 fprintf(stderr,
324                         "ERROR: Could not canonicalize pathname '%s': %s\n",
325                         argv[argc - 1], strerror(errno));
326                 ret = 1;
327                 goto out;
328         }
329
330         if (!is_block_device(path)) {
331                 fprintf(stderr,
332                         "ERROR: %s is not a block device\n", path);
333                 ret = 1;
334                 goto out;
335         }
336
337         memset(&args, 0, sizeof(args));
338         strncpy_null(args.name, path);
339         ret = ioctl(fd, BTRFS_IOC_DEVICES_READY, &args);
340         if (ret < 0) {
341                 fprintf(stderr, "ERROR: unable to determine if the device '%s'"
342                         " is ready for mounting - %s\n", path,
343                         strerror(errno));
344                 ret = 1;
345         }
346
347 out:
348         free(path);
349         close(fd);
350         return ret;
351 }
352
353 static const char * const cmd_device_stats_usage[] = {
354         "btrfs device stats [-z] <path>|<device>",
355         "Show current device IO stats.",
356         "",
357         "-z                     show current stats and reset values to zero",
358         NULL
359 };
360
361 static int cmd_device_stats(int argc, char **argv)
362 {
363         char *dev_path;
364         struct btrfs_ioctl_fs_info_args fi_args;
365         struct btrfs_ioctl_dev_info_args *di_args = NULL;
366         int ret;
367         int fdmnt;
368         int i;
369         int c;
370         int err = 0;
371         __u64 flags = 0;
372         DIR *dirstream = NULL;
373
374         optind = 1;
375         while ((c = getopt(argc, argv, "z")) != -1) {
376                 switch (c) {
377                 case 'z':
378                         flags = BTRFS_DEV_STATS_RESET;
379                         break;
380                 case '?':
381                 default:
382                         usage(cmd_device_stats_usage);
383                 }
384         }
385
386         argc = argc - optind;
387         if (check_argc_exact(argc, 1))
388                 usage(cmd_device_stats_usage);
389
390         dev_path = argv[optind];
391
392         fdmnt = open_path_or_dev_mnt(dev_path, &dirstream);
393
394         if (fdmnt < 0) {
395                 if (errno == EINVAL)
396                         fprintf(stderr,
397                                 "ERROR: '%s' is not a mounted btrfs device\n",
398                                 dev_path);
399                 else
400                         fprintf(stderr, "ERROR: can't access '%s': %s\n",
401                                 dev_path, strerror(errno));
402                 return 1;
403         }
404
405         ret = get_fs_info(dev_path, &fi_args, &di_args);
406         if (ret) {
407                 fprintf(stderr, "ERROR: getting dev info for devstats failed: "
408                                 "%s\n", strerror(-ret));
409                 err = 1;
410                 goto out;
411         }
412         if (!fi_args.num_devices) {
413                 fprintf(stderr, "ERROR: no devices found\n");
414                 err = 1;
415                 goto out;
416         }
417
418         for (i = 0; i < fi_args.num_devices; i++) {
419                 struct btrfs_ioctl_get_dev_stats args = {0};
420                 __u8 path[BTRFS_DEVICE_PATH_NAME_MAX + 1];
421
422                 strncpy((char *)path, (char *)di_args[i].path,
423                         BTRFS_DEVICE_PATH_NAME_MAX);
424                 path[BTRFS_DEVICE_PATH_NAME_MAX] = '\0';
425
426                 args.devid = di_args[i].devid;
427                 args.nr_items = BTRFS_DEV_STAT_VALUES_MAX;
428                 args.flags = flags;
429
430                 if (ioctl(fdmnt, BTRFS_IOC_GET_DEV_STATS, &args) < 0) {
431                         fprintf(stderr,
432                                 "ERROR: ioctl(BTRFS_IOC_GET_DEV_STATS) on %s failed: %s\n",
433                                 path, strerror(errno));
434                         err = 1;
435                 } else {
436                         char *canonical_path;
437
438                         canonical_path = canonicalize_path((char *)path);
439
440                         if (args.nr_items >= BTRFS_DEV_STAT_WRITE_ERRS + 1)
441                                 printf("[%s].write_io_errs   %llu\n",
442                                        canonical_path,
443                                        (unsigned long long) args.values[
444                                         BTRFS_DEV_STAT_WRITE_ERRS]);
445                         if (args.nr_items >= BTRFS_DEV_STAT_READ_ERRS + 1)
446                                 printf("[%s].read_io_errs    %llu\n",
447                                        canonical_path,
448                                        (unsigned long long) args.values[
449                                         BTRFS_DEV_STAT_READ_ERRS]);
450                         if (args.nr_items >= BTRFS_DEV_STAT_FLUSH_ERRS + 1)
451                                 printf("[%s].flush_io_errs   %llu\n",
452                                        canonical_path,
453                                        (unsigned long long) args.values[
454                                         BTRFS_DEV_STAT_FLUSH_ERRS]);
455                         if (args.nr_items >= BTRFS_DEV_STAT_CORRUPTION_ERRS + 1)
456                                 printf("[%s].corruption_errs %llu\n",
457                                        canonical_path,
458                                        (unsigned long long) args.values[
459                                         BTRFS_DEV_STAT_CORRUPTION_ERRS]);
460                         if (args.nr_items >= BTRFS_DEV_STAT_GENERATION_ERRS + 1)
461                                 printf("[%s].generation_errs %llu\n",
462                                        canonical_path,
463                                        (unsigned long long) args.values[
464                                         BTRFS_DEV_STAT_GENERATION_ERRS]);
465
466                         free(canonical_path);
467                 }
468         }
469
470 out:
471         free(di_args);
472         close_file_or_dir(fdmnt, dirstream);
473         btrfs_close_all_devices();
474
475         return err;
476 }
477
478 const char * const cmd_device_usage_usage[] = {
479         "btrfs device usage [options] <path> [<path>..]",
480         "Show detailed information about internal allocations in devices.",
481         "-b|--raw           raw numbers in bytes",
482         "-h|--human-readable",
483         "                   human friendly numbers, base 1024 (default)",
484         "-H                 human friendly numbers, base 1000",
485         "--iec              use 1024 as a base (KiB, MiB, GiB, TiB)",
486         "--si               use 1000 as a base (kB, MB, GB, TB)",
487         "-k|--kbytes        show sizes in KiB, or kB with --si",
488         "-m|--mbytes        show sizes in MiB, or MB with --si",
489         "-g|--gbytes        show sizes in GiB, or GB with --si",
490         "-t|--tbytes        show sizes in TiB, or TB with --si",
491         NULL
492 };
493
494 static int _cmd_device_usage(int fd, char *path, unsigned unit_mode)
495 {
496         int i;
497         int ret = 0;
498         struct chunk_info *chunkinfo = NULL;
499         struct device_info *devinfo = NULL;
500         int chunkcount = 0;
501         int devcount = 0;
502
503         ret = load_chunk_and_device_info(fd, &chunkinfo, &chunkcount, &devinfo,
504                         &devcount);
505         if (ret)
506                 goto out;
507
508         for (i = 0; i < devcount; i++) {
509                 printf("%s, ID: %llu\n", devinfo[i].path, devinfo[i].devid);
510                 print_device_sizes(fd, &devinfo[i], unit_mode);
511                 print_device_chunks(fd, &devinfo[i], chunkinfo, chunkcount,
512                                 unit_mode);
513                 printf("\n");
514         }
515
516 out:
517         free(devinfo);
518         free(chunkinfo);
519
520         return ret;
521 }
522
523 int cmd_device_usage(int argc, char **argv)
524 {
525         unsigned unit_mode = UNITS_DEFAULT;
526         int ret = 0;
527         int     i, more_than_one = 0;
528
529         optind = 1;
530         while (1) {
531                 int c;
532                 static const struct option long_options[] = {
533                         { "raw", no_argument, NULL, 'b'},
534                         { "kbytes", no_argument, NULL, 'k'},
535                         { "mbytes", no_argument, NULL, 'm'},
536                         { "gbytes", no_argument, NULL, 'g'},
537                         { "tbytes", no_argument, NULL, 't'},
538                         { "si", no_argument, NULL, GETOPT_VAL_SI},
539                         { "iec", no_argument, NULL, GETOPT_VAL_IEC},
540                         { "human-readable", no_argument, NULL,
541                                 GETOPT_VAL_HUMAN_READABLE},
542                         { NULL, 0, NULL, 0 }
543                 };
544
545                 c = getopt_long(argc, argv, "bhHkmgt", long_options, NULL);
546                 if (c < 0)
547                         break;
548                 switch (c) {
549                 case 'b':
550                         unit_mode = UNITS_RAW;
551                         break;
552                 case 'k':
553                         units_set_base(&unit_mode, UNITS_KBYTES);
554                         break;
555                 case 'm':
556                         units_set_base(&unit_mode, UNITS_MBYTES);
557                         break;
558                 case 'g':
559                         units_set_base(&unit_mode, UNITS_GBYTES);
560                         break;
561                 case 't':
562                         units_set_base(&unit_mode, UNITS_TBYTES);
563                         break;
564                 case GETOPT_VAL_HUMAN_READABLE:
565                 case 'h':
566                         unit_mode = UNITS_HUMAN_BINARY;
567                         break;
568                 case 'H':
569                         unit_mode = UNITS_HUMAN_DECIMAL;
570                         break;
571                 case GETOPT_VAL_SI:
572                         units_set_mode(&unit_mode, UNITS_DECIMAL);
573                         break;
574                 case GETOPT_VAL_IEC:
575                         units_set_mode(&unit_mode, UNITS_BINARY);
576                         break;
577                 default:
578                         usage(cmd_device_usage_usage);
579                 }
580         }
581
582         if (check_argc_min(argc - optind, 1))
583                 usage(cmd_device_usage_usage);
584
585         for (i = optind; i < argc ; i++) {
586                 int fd;
587                 DIR     *dirstream = NULL;
588                 if (more_than_one)
589                         printf("\n");
590
591                 fd = open_file_or_dir(argv[i], &dirstream);
592                 if (fd < 0) {
593                         fprintf(stderr, "ERROR: can't access '%s'\n",
594                                 argv[1]);
595                         ret = 1;
596                         goto out;
597                 }
598
599                 ret = _cmd_device_usage(fd, argv[i], unit_mode);
600                 close_file_or_dir(fd, dirstream);
601
602                 if (ret)
603                         goto out;
604                 more_than_one = 1;
605         }
606 out:
607         return !!ret;
608 }
609
610 static const char device_cmd_group_info[] =
611 "manage and query devices in the filesystem";
612
613 const struct cmd_group device_cmd_group = {
614         device_cmd_group_usage, device_cmd_group_info, {
615                 { "add", cmd_device_add, cmd_device_add_usage, NULL, 0 },
616                 { "delete", cmd_device_delete, cmd_device_delete_usage, NULL,
617                         CMD_ALIAS },
618                 { "remove", cmd_device_remove, cmd_device_remove_usage, NULL, 0 },
619                 { "scan", cmd_device_scan, cmd_device_scan_usage, NULL, 0 },
620                 { "ready", cmd_device_ready, cmd_device_ready_usage, NULL, 0 },
621                 { "stats", cmd_device_stats, cmd_device_stats_usage, NULL, 0 },
622                 { "usage", cmd_device_usage,
623                         cmd_device_usage_usage, NULL, 0 },
624                 NULL_CMD_STRUCT
625         }
626 };
627
628 int cmd_device(int argc, char **argv)
629 {
630         return handle_command_group(&device_cmd_group, argc, argv);
631 }