btrfs-progs: Fix up memory leakage
[platform/upstream/btrfs-progs.git] / cmds-filesystem.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 <sys/ioctl.h>
22 #include <errno.h>
23 #include <uuid/uuid.h>
24 #include <ctype.h>
25
26 #include "kerncompat.h"
27 #include "ctree.h"
28 #include "ioctl.h"
29 #include "utils.h"
30 #include "volumes.h"
31
32 #include "version.h"
33
34 #include "commands.h"
35 #include "btrfslabel.h"
36
37 static const char * const filesystem_cmd_group_usage[] = {
38         "btrfs filesystem [<group>] <command> [<args>]",
39         NULL
40 };
41
42 static const char * const cmd_df_usage[] = {
43         "btrfs filesystem df <path>",
44         "Show space usage information for a mount point",
45         NULL
46 };
47
48 static int cmd_df(int argc, char **argv)
49 {
50         struct btrfs_ioctl_space_args *sargs, *sargs_orig;
51         u64 count = 0, i;
52         int ret;
53         int fd;
54         int e;
55         char *path;
56
57         if (check_argc_exact(argc, 2))
58                 usage(cmd_df_usage);
59
60         path = argv[1];
61
62         fd = open_file_or_dir(path);
63         if (fd < 0) {
64                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
65                 return 12;
66         }
67
68         sargs_orig = sargs = malloc(sizeof(struct btrfs_ioctl_space_args));
69         if (!sargs)
70                 return -ENOMEM;
71
72         sargs->space_slots = 0;
73         sargs->total_spaces = 0;
74
75         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
76         e = errno;
77         if (ret) {
78                 fprintf(stderr, "ERROR: couldn't get space info on '%s' - %s\n",
79                         path, strerror(e));
80                 close(fd);
81                 free(sargs);
82                 return ret;
83         }
84         if (!sargs->total_spaces) {
85                 close(fd);
86                 free(sargs);
87                 return 0;
88         }
89
90         count = sargs->total_spaces;
91
92         sargs = realloc(sargs, sizeof(struct btrfs_ioctl_space_args) +
93                         (count * sizeof(struct btrfs_ioctl_space_info)));
94         if (!sargs) {
95                 close(fd);
96                 free(sargs_orig);
97                 return -ENOMEM;
98         }
99
100         sargs->space_slots = count;
101         sargs->total_spaces = 0;
102
103         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
104         e = errno;
105         if (ret) {
106                 fprintf(stderr, "ERROR: couldn't get space info on '%s' - %s\n",
107                         path, strerror(e));
108                 close(fd);
109                 free(sargs);
110                 return ret;
111         }
112
113         for (i = 0; i < sargs->total_spaces; i++) {
114                 char description[80];
115                 char *total_bytes;
116                 char *used_bytes;
117                 int written = 0;
118                 u64 flags = sargs->spaces[i].flags;
119
120                 memset(description, 0, 80);
121
122                 if (flags & BTRFS_BLOCK_GROUP_DATA) {
123                         if (flags & BTRFS_BLOCK_GROUP_METADATA) {
124                                 snprintf(description, 14, "%s",
125                                          "Data+Metadata");
126                                 written += 13;
127                         } else {
128                                 snprintf(description, 5, "%s", "Data");
129                                 written += 4;
130                         }
131                 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM) {
132                         snprintf(description, 7, "%s", "System");
133                         written += 6;
134                 } else if (flags & BTRFS_BLOCK_GROUP_METADATA) {
135                         snprintf(description, 9, "%s", "Metadata");
136                         written += 8;
137                 }
138
139                 if (flags & BTRFS_BLOCK_GROUP_RAID0) {
140                         snprintf(description+written, 8, "%s", ", RAID0");
141                         written += 7;
142                 } else if (flags & BTRFS_BLOCK_GROUP_RAID1) {
143                         snprintf(description+written, 8, "%s", ", RAID1");
144                         written += 7;
145                 } else if (flags & BTRFS_BLOCK_GROUP_DUP) {
146                         snprintf(description+written, 6, "%s", ", DUP");
147                         written += 5;
148                 } else if (flags & BTRFS_BLOCK_GROUP_RAID10) {
149                         snprintf(description+written, 9, "%s", ", RAID10");
150                         written += 8;
151                 }
152
153                 total_bytes = pretty_sizes(sargs->spaces[i].total_bytes);
154                 used_bytes = pretty_sizes(sargs->spaces[i].used_bytes);
155                 printf("%s: total=%s, used=%s\n", description, total_bytes,
156                        used_bytes);
157         }
158         close(fd);
159         free(sargs);
160
161         return 0;
162 }
163
164 static int uuid_search(struct btrfs_fs_devices *fs_devices, char *search)
165 {
166         char uuidbuf[37];
167         struct list_head *cur;
168         struct btrfs_device *device;
169         int search_len = strlen(search);
170
171         search_len = min(search_len, 37);
172         uuid_unparse(fs_devices->fsid, uuidbuf);
173         if (!strncmp(uuidbuf, search, search_len))
174                 return 1;
175
176         list_for_each(cur, &fs_devices->devices) {
177                 device = list_entry(cur, struct btrfs_device, dev_list);
178                 if ((device->label && strcmp(device->label, search) == 0) ||
179                     strcmp(device->name, search) == 0)
180                         return 1;
181         }
182         return 0;
183 }
184
185 static void print_one_uuid(struct btrfs_fs_devices *fs_devices)
186 {
187         char uuidbuf[37];
188         struct list_head *cur;
189         struct btrfs_device *device;
190         char *super_bytes_used;
191         u64 devs_found = 0;
192         u64 total;
193
194         uuid_unparse(fs_devices->fsid, uuidbuf);
195         device = list_entry(fs_devices->devices.next, struct btrfs_device,
196                             dev_list);
197         if (device->label && device->label[0])
198                 printf("Label: '%s' ", device->label);
199         else
200                 printf("Label: none ");
201
202         super_bytes_used = pretty_sizes(device->super_bytes_used);
203
204         total = device->total_devs;
205         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
206                (unsigned long long)total, super_bytes_used);
207
208         free(super_bytes_used);
209
210         list_for_each(cur, &fs_devices->devices) {
211                 char *total_bytes;
212                 char *bytes_used;
213                 device = list_entry(cur, struct btrfs_device, dev_list);
214                 total_bytes = pretty_sizes(device->total_bytes);
215                 bytes_used = pretty_sizes(device->bytes_used);
216                 printf("\tdevid %4llu size %s used %s path %s\n",
217                        (unsigned long long)device->devid,
218                        total_bytes, bytes_used, device->name);
219                 free(total_bytes);
220                 free(bytes_used);
221                 devs_found++;
222         }
223         if (devs_found < total) {
224                 printf("\t*** Some devices missing\n");
225         }
226         printf("\n");
227 }
228
229 static const char * const cmd_show_usage[] = {
230         "btrfs filesystem show [--all-devices] [<uuid>|<label>]",
231         "Show the structure of a filesystem",
232         "If no argument is given, structure of all present filesystems is shown.",
233         NULL
234 };
235
236 static int cmd_show(int argc, char **argv)
237 {
238         struct list_head *all_uuids;
239         struct btrfs_fs_devices *fs_devices;
240         struct list_head *cur_uuid;
241         char *search = 0;
242         int ret;
243         int checklist = 1;
244         int searchstart = 1;
245
246         if( argc > 1 && !strcmp(argv[1],"--all-devices")){
247                 checklist = 0;
248                 searchstart += 1;
249         }
250
251         if (check_argc_max(argc, searchstart + 1))
252                 usage(cmd_show_usage);
253
254         if(checklist)
255                 ret = btrfs_scan_block_devices(0);
256         else
257                 ret = btrfs_scan_one_dir("/dev", 0);
258
259         if (ret){
260                 fprintf(stderr, "ERROR: error %d while scanning\n", ret);
261                 return 18;
262         }
263         
264         if(searchstart < argc)
265                 search = argv[searchstart];
266
267         all_uuids = btrfs_scanned_uuids();
268         list_for_each(cur_uuid, all_uuids) {
269                 fs_devices = list_entry(cur_uuid, struct btrfs_fs_devices,
270                                         list);
271                 if (search && uuid_search(fs_devices, search) == 0)
272                         continue;
273                 print_one_uuid(fs_devices);
274         }
275         printf("%s\n", BTRFS_BUILD_VERSION);
276         return 0;
277 }
278
279 static const char * const cmd_sync_usage[] = {
280         "btrfs filesystem sync <path>",
281         "Force a sync on a filesystem",
282         NULL
283 };
284
285 static int cmd_sync(int argc, char **argv)
286 {
287         int     fd, res, e;
288         char    *path;
289
290         if (check_argc_exact(argc, 2))
291                 usage(cmd_sync_usage);
292
293         path = argv[1];
294
295         fd = open_file_or_dir(path);
296         if (fd < 0) {
297                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
298                 return 12;
299         }
300
301         printf("FSSync '%s'\n", path);
302         res = ioctl(fd, BTRFS_IOC_SYNC);
303         e = errno;
304         close(fd);
305         if( res < 0 ){
306                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
307                         path, strerror(e));
308                 return 16;
309         }
310
311         return 0;
312 }
313
314 static u64 parse_size(char *s)
315 {
316         int len = strlen(s);
317         char c;
318         u64 mult = 1;
319
320         if (!isdigit(s[len - 1])) {
321                 c = tolower(s[len - 1]);
322                 switch (c) {
323                 case 'g':
324                         mult *= 1024;
325                 case 'm':
326                         mult *= 1024;
327                 case 'k':
328                         mult *= 1024;
329                 case 'b':
330                         break;
331                 default:
332                         fprintf(stderr, "Unknown size descriptor %c\n", c);
333                         exit(1);
334                 }
335                 s[len - 1] = '\0';
336         }
337         return atoll(s) * mult;
338 }
339
340 static int parse_compress_type(char *s)
341 {
342         if (strcmp(optarg, "zlib") == 0)
343                 return BTRFS_COMPRESS_ZLIB;
344         else if (strcmp(optarg, "lzo") == 0)
345                 return BTRFS_COMPRESS_LZO;
346         else {
347                 fprintf(stderr, "Unknown compress type %s\n", s);
348                 exit(1);
349         };
350 }
351
352 static const char * const cmd_defrag_usage[] = {
353         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
354         "Defragment a file or a directory",
355         "",
356         "-v             be verbose",
357         "-c[zlib,lzo]   compress the file while defragmenting",
358         "-f             flush data to disk immediately after defragmenting",
359         "-s start       defragment only from byte onward",
360         "-l len         defragment only up to len bytes",
361         "-t size        minimal size of file to be considered for defragmenting",
362         NULL
363 };
364
365 static int cmd_defrag(int argc, char **argv)
366 {
367         int fd;
368         int flush = 0;
369         u64 start = 0;
370         u64 len = (u64)-1;
371         u32 thresh = 0;
372         int i;
373         int errors = 0;
374         int ret = 0;
375         int verbose = 0;
376         int fancy_ioctl = 0;
377         struct btrfs_ioctl_defrag_range_args range;
378         int e=0;
379         int compress_type = BTRFS_COMPRESS_NONE;
380
381         optind = 1;
382         while(1) {
383                 int c = getopt(argc, argv, "vc::fs:l:t:");
384                 if (c < 0)
385                         break;
386
387                 switch(c) {
388                 case 'c':
389                         compress_type = BTRFS_COMPRESS_ZLIB;
390                         if (optarg)
391                                 compress_type = parse_compress_type(optarg);
392                         fancy_ioctl = 1;
393                         break;
394                 case 'f':
395                         flush = 1;
396                         fancy_ioctl = 1;
397                         break;
398                 case 'v':
399                         verbose = 1;
400                         break;
401                 case 's':
402                         start = parse_size(optarg);
403                         fancy_ioctl = 1;
404                         break;
405                 case 'l':
406                         len = parse_size(optarg);
407                         fancy_ioctl = 1;
408                         break;
409                 case 't':
410                         thresh = parse_size(optarg);
411                         fancy_ioctl = 1;
412                         break;
413                 default:
414                         usage(cmd_defrag_usage);
415                 }
416         }
417
418         if (check_argc_min(argc - optind, 1))
419                 usage(cmd_defrag_usage);
420
421         memset(&range, 0, sizeof(range));
422         range.start = start;
423         range.len = len;
424         range.extent_thresh = thresh;
425         if (compress_type) {
426                 range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
427                 range.compress_type = compress_type;
428         }
429         if (flush)
430                 range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
431
432         for (i = optind; i < argc; i++) {
433                 if (verbose)
434                         printf("%s\n", argv[i]);
435                 fd = open_file_or_dir(argv[i]);
436                 if (fd < 0) {
437                         fprintf(stderr, "failed to open %s\n", argv[i]);
438                         perror("open:");
439                         errors++;
440                         continue;
441                 }
442                 if (!fancy_ioctl) {
443                         ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
444                         e=errno;
445                 } else {
446                         ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, &range);
447                         if (ret && errno == ENOTTY) {
448                                 fprintf(stderr, "ERROR: defrag range ioctl not "
449                                         "supported in this kernel, please try "
450                                         "without any options.\n");
451                                 errors++;
452                                 close(fd);
453                                 break;
454                         }
455                 }
456                 if (ret) {
457                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
458                                 argv[i], strerror(e));
459                         errors++;
460                 }
461                 close(fd);
462         }
463         if (verbose)
464                 printf("%s\n", BTRFS_BUILD_VERSION);
465         if (errors) {
466                 fprintf(stderr, "total %d failures\n", errors);
467                 exit(1);
468         }
469
470         return errors + 20;
471 }
472
473 static const char * const cmd_resize_usage[] = {
474         "btrfs filesystem resize [devid:][+/-]<newsize>[gkm]|[devid:]max <path>",
475         "Resize a filesystem",
476         "If 'max' is passed, the filesystem will occupy all available space",
477         "on the device 'devid'.",
478         NULL
479 };
480
481 static int cmd_resize(int argc, char **argv)
482 {
483         struct btrfs_ioctl_vol_args     args;
484         int     fd, res, len, e;
485         char    *amount, *path;
486
487         if (check_argc_exact(argc, 3))
488                 usage(cmd_resize_usage);
489
490         amount = argv[1];
491         path = argv[2];
492
493         fd = open_file_or_dir(path);
494         if (fd < 0) {
495                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
496                 return 12;
497         }
498         len = strlen(amount);
499         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
500                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
501                         amount);
502                 return 14;
503         }
504
505         printf("Resize '%s' of '%s'\n", path, amount);
506         strncpy(args.name, amount, BTRFS_PATH_NAME_MAX);
507         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
508         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
509         e = errno;
510         close(fd);
511         if( res < 0 ){
512                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
513                         path, strerror(e));
514                 return 30;
515         }
516         return 0;
517 }
518
519 static const char * const cmd_label_usage[] = {
520         "btrfs filesystem label <device> [<newlabel>]",
521         "Get or change the label of an unmounted filesystem",
522         "With one argument, get the label of filesystem on <device>.",
523         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
524         NULL
525 };
526
527 static int cmd_label(int argc, char **argv)
528 {
529         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
530                 usage(cmd_label_usage);
531
532         if (argc > 2)
533                 return set_label(argv[1], argv[2]);
534         else
535                 return get_label(argv[1]);
536 }
537
538 const struct cmd_group filesystem_cmd_group = {
539         filesystem_cmd_group_usage, NULL, {
540                 { "df", cmd_df, cmd_df_usage, NULL, 0 },
541                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
542                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
543                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
544                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
545                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
546                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
547                 { 0, 0, 0, 0, 0 },
548         }
549 };
550
551 int cmd_filesystem(int argc, char **argv)
552 {
553         return handle_command_group(&filesystem_cmd_group, argc, argv);
554 }