Btrfs-progs: added ioctls and commands to resolve inodes and logical addrs
[platform/upstream/btrfs-progs.git] / btrfs.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 #define _GNU_SOURCE
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include "kerncompat.h"
23 #include "btrfs_cmds.h"
24 #include "version.h"
25
26 #define BASIC_HELP 0
27 #define ADVANCED_HELP 1
28
29 typedef int (*CommandFunction)(int argc, char **argv);
30
31 struct Command {
32         CommandFunction func;   /* function which implements the command */
33         int     nargs;          /* if == 999, any number of arguments
34                                    if >= 0, number of arguments,
35                                    if < 0, _minimum_ number of arguments */
36         char    *verb;          /* verb */
37         char    *help;          /* help lines; from the 2nd line onward they 
38                                    are automatically indented */
39         char    *adv_help;      /* advanced help message; from the 2nd line 
40                                    onward they are automatically indented */
41
42         /* the following fields are run-time filled by the program */
43         char    **cmds;         /* array of subcommands */
44         int     ncmds;          /* number of subcommand */
45 };
46
47 static struct Command commands[] = {
48
49         /*
50                 avoid short commands different for the case only
51         */
52         { do_clone, -2,
53           "subvolume snapshot", "[-r] <source> [<dest>/]<name>\n"
54                 "Create a writable/readonly snapshot of the subvolume <source> with\n"
55                 "the name <name> in the <dest> directory.",
56           NULL
57         },
58         { do_delete_subvolume, 1,
59           "subvolume delete", "<subvolume>\n"
60                 "Delete the subvolume <subvolume>.",
61           NULL
62         },
63         { do_create_subvol, 1,
64           "subvolume create", "[<dest>/]<name>\n"
65                 "Create a subvolume in <dest> (or the current directory if\n"
66                 "not passed).",
67           NULL
68         },
69         { do_subvol_list, -1, "subvolume list", "[-p] <path>\n"
70                 "List the snapshot/subvolume of a filesystem.",
71                 "[-p] <path>\n"
72                 "List the snapshot/subvolume of a filesystem.\n"
73                 "-p        print parent ID"
74         },
75         { do_set_default_subvol, 2,
76           "subvolume set-default", "<id> <path>\n"
77                 "Set the subvolume of the filesystem <path> which will be mounted\n"
78                 "as default.",
79           NULL
80         },
81         { do_find_newer, 2, "subvolume find-new", "<path> <last_gen>\n"
82                 "List the recently modified files in a filesystem.",
83           NULL
84         },
85         { do_defrag, -1,
86           "filesystem defragment", "[-vf] [-c[zlib,lzo]] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
87                 "Defragment a file or a directory.",
88                 "[-vcf] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
89                 "Defragment file data or directory metadata.\n"
90                 "-v         be verbose\n"
91                 "-c         compress the file while defragmenting\n"
92                 "-f         flush data to disk immediately after defragmenting\n"
93                 "-s start   defragment only from byte onward\n"
94                 "-l len     defragment only up to len bytes\n"
95                 "-t size    minimal size of file to be considered for defragmenting\n"
96         },
97         { do_get_default_subvol, 1, "subvolume get-default", "<path>\n"
98                 "Get the default subvolume of a filesystem."
99         },
100         { do_fssync, 1,
101           "filesystem sync", "<path>\n"
102                 "Force a sync on the filesystem <path>.",
103           NULL
104         },
105         { do_resize, 2,
106           "filesystem resize", "[+/-]<newsize>[gkm]|max <filesystem>\n"
107                 "Resize the file system. If 'max' is passed, the filesystem\n"
108                 "will occupe all available space on the device.",
109           NULL
110         },
111         { do_show_filesystem, 999,
112           "filesystem show", "[--all-devices][<uuid>|<label>]\n"
113                 "Show the info of a btrfs filesystem. If no argument\n"
114                 "is passed, info of all the btrfs filesystem are shown.",
115           NULL
116         },
117         { do_df_filesystem, 1,
118           "filesystem df", "<path>\n"
119                 "Show space usage information for a mount point.",
120           NULL
121         },
122         { do_balance, 1,
123           "filesystem balance", "<path>\n"
124                 "Balance the chunks across the device.",
125           NULL
126         },
127         { do_change_label, -1,
128           "filesystem label", "<device> [<newlabel>]\n"
129           "With one argument, get the label of filesystem on <device>.\n"
130           "If <newlabel> is passed, set the filesystem label to <newlabel>.\n"
131           "The filesystem must be unmounted.\n"
132         },
133         { do_scrub_start, -1,
134           "scrub start", "[-Bdqr] <path>|<device>\n"
135                 "Start a new scrub.",
136                 "\n-B  do not background\n"
137                 "-d  stats per device (-B only)\n"
138                 "-q  quiet\n"
139                 "-r  read only mode\n"
140         },
141         { do_scrub_cancel, 1,
142           "scrub cancel", "<path>|<device>\n"
143                 "Cancel a running scrub.",
144           NULL
145         },
146         { do_scrub_resume, -1,
147           "scrub resume", "[-Bdqr] <path>|<device>\n"
148                 "Resume previously canceled or interrupted scrub.",
149           NULL
150         },
151         { do_scrub_status, -1,
152           "scrub status", "[-d] <path>|<device>\n"
153                 "Show status of running or finished scrub.",
154           NULL
155         },
156         { do_scan, 999, 
157           "device scan", "[<device>...]\n"
158                 "Scan all device for or the passed device for a btrfs\n"
159                 "filesystem.",
160           NULL
161         },
162         { do_add_volume, -2,
163           "device add", "<device> [<device>...] <path>\n"
164                 "Add a device to a filesystem.",
165           NULL
166         },
167         { do_remove_volume, -2,
168           "device delete", "<device> [<device>...] <path>\n"
169                 "Remove a device from a filesystem.",
170           NULL
171         },
172         { do_ino_to_path, -2,
173           "inspect-internal inode-resolve", "[-v] <inode> <path>\n"
174                 "get file system paths for the given inode.",
175           NULL
176         },
177         { do_logical_to_ino, -2,
178           "inspect-internal logical-resolve", "[-v] [-P] <logical> <path>\n"
179                 "get file system paths for the given logical address.",
180           NULL
181         },
182         { 0, 0, 0, 0 }
183 };
184
185 static char *get_prgname(char *programname)
186 {
187         char    *np;
188         np = strrchr(programname,'/');
189         if(!np)
190                 np = programname;
191         else
192                 np++;
193
194         return np;
195 }
196
197 static void print_help(char *programname, struct Command *cmd, int helptype)
198 {
199         char    *pc;
200
201         printf("\t%s %s ", programname, cmd->verb );
202
203         if (helptype == ADVANCED_HELP && cmd->adv_help)
204                 for(pc = cmd->adv_help; *pc; pc++){
205                         putchar(*pc);
206                         if(*pc == '\n')
207                                 printf("\t\t");
208                 }
209         else
210                 for(pc = cmd->help; *pc; pc++){
211                         putchar(*pc);
212                         if(*pc == '\n')
213                                 printf("\t\t");
214                 }
215
216         putchar('\n');
217 }
218
219 static void help(char *np)
220 {
221         struct Command *cp;
222
223         printf("Usage:\n");
224         for( cp = commands; cp->verb; cp++ )
225                 print_help(np, cp, BASIC_HELP);
226
227         printf("\n\t%s help|--help|-h\n\t\tShow the help.\n",np);
228         printf("\n\t%s <cmd> --help\n\t\tShow detailed help for a command or\n\t\t"
229                "subset of commands.\n",np);
230         printf("\n%s\n", BTRFS_BUILD_VERSION);
231 }
232
233 static int split_command(char *cmd, char ***commands)
234 {
235         int     c, l;
236         char    *p, *s;
237
238         for( *commands = 0, l = c = 0, p = s = cmd ; ; p++, l++ ){
239                 if ( *p && *p != ' ' )
240                         continue;
241
242                 /* c + 2 so that we have room for the null */
243                 (*commands) = realloc( (*commands), sizeof(char *)*(c + 2));
244                 (*commands)[c] = strndup(s, l);
245                 c++;
246                 l = 0;
247                 s = p+1;
248                 if( !*p ) break;
249         }
250
251         (*commands)[c] = 0;
252         return c;
253 }
254
255 /*
256         This function checks if the passed command is ambiguous
257 */
258 static int check_ambiguity(struct Command *cmd, char **argv){
259         int             i;
260         struct Command  *cp;
261         /* check for ambiguity */
262         for( i = 0 ; i < cmd->ncmds ; i++ ){
263                 int match;
264                 for( match = 0, cp = commands; cp->verb; cp++ ){
265                         int     j, skip;
266                         char    *s1, *s2;
267
268                         if( cp->ncmds < i )
269                                 continue;
270
271                         for( skip = 0, j = 0 ; j < i ; j++ )
272                                 if( strcmp(cmd->cmds[j], cp->cmds[j])){
273                                         skip=1;
274                                         break;
275                                 }
276                         if(skip)
277                                 continue;
278
279                         if( !strcmp(cmd->cmds[i], cp->cmds[i]))
280                                 continue;
281                         for(s2 = cp->cmds[i], s1 = argv[i+1];
282                                 *s1 == *s2 && *s1; s1++, s2++ ) ;
283                         if( !*s1 )
284                                 match++;
285                 }
286                 if(match){
287                         int j;
288                         fprintf(stderr, "ERROR: in command '");
289                         for( j = 0 ; j <= i ; j++ )
290                                 fprintf(stderr, "%s%s",j?" ":"", argv[j+1]);
291                         fprintf(stderr, "', '%s' is ambiguous\n",argv[j]);
292                         return -2;
293                 }
294         }
295         return 0;
296 }
297
298 /*
299  * This function, compacts the program name and the command in the first
300  * element of the '*av' array
301  */
302 static int prepare_args(int *ac, char ***av, char *prgname, struct Command *cmd ){
303
304         char    **ret;
305         int     i;
306         char    *newname;
307
308         ret = (char **)malloc(sizeof(char*)*(*ac+1));
309         newname = (char*)malloc(strlen(prgname)+strlen(cmd->verb)+2);
310         if( !ret || !newname ){
311                 free(ret);
312                 free(newname);
313                 return -1;
314         }
315
316         ret[0] = newname;
317         for(i=0; i < *ac ; i++ )
318                 ret[i+1] = (*av)[i];
319
320         strcpy(newname, prgname);
321         strcat(newname, " ");
322         strcat(newname, cmd->verb);
323
324         (*ac)++;
325         *av = ret;
326
327         return 0;
328
329 }
330
331
332
333 /*
334         This function performs the following jobs:
335         - show the help if '--help' or 'help' or '-h' are passed
336         - verify that a command is not ambiguous, otherwise show which
337           part of the command is ambiguous
338         - if after a (even partial) command there is '--help' show detailed help
339           for all the matching commands
340         - if the command doesn't match show an error
341         - finally, if a command matches, they return which command matched and
342           the arguments
343
344         The function return 0 in case of help is requested; <0 in case
345         of uncorrect command; >0 in case of matching commands
346         argc, argv are the arg-counter and arg-vector (input)
347         *nargs_ is the number of the arguments after the command (output)
348         **cmd_  is the invoked command (output)
349         ***args_ are the arguments after the command
350
351 */
352 static int parse_args(int argc, char **argv,
353                       CommandFunction *func_,
354                       int *nargs_, char **cmd_, char ***args_ )
355 {
356         struct Command  *cp;
357         struct Command  *matchcmd=0;
358         char            *prgname = get_prgname(argv[0]);
359         int             i=0, helprequested=0;
360
361         if( argc < 2 || !strcmp(argv[1], "help") ||
362                 !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
363                 help(prgname);
364                 return 0;
365         }
366
367         for( cp = commands; cp->verb; cp++ )
368                 if( !cp->ncmds)
369                         cp->ncmds = split_command(cp->verb, &(cp->cmds));
370
371         for( cp = commands; cp->verb; cp++ ){
372                 int     match;
373
374                 if( argc-1 < cp->ncmds )
375                         continue;
376                 for( match = 1, i = 0 ; i < cp->ncmds ; i++ ){
377                         char    *s1, *s2;
378                         s1 = cp->cmds[i];
379                         s2 = argv[i+1];
380
381                         for(s2 = cp->cmds[i], s1 = argv[i+1];
382                                 *s1 == *s2 && *s1;
383                                 s1++, s2++ ) ;
384                         if( *s1 ){
385                                 match=0;
386                                 break;
387                         }
388                 }
389
390                 /* If you understand why this code works ...
391                         you are a genious !! */
392                 if(argc>i+1 && !strcmp(argv[i+1],"--help")){
393                         if(!helprequested)
394                                 printf("Usage:\n");
395                         print_help(prgname, cp, ADVANCED_HELP);
396                         helprequested=1;
397                         continue;
398                 }
399
400                 if(!match)
401                         continue;
402
403                 matchcmd = cp;
404                 *nargs_  = argc-matchcmd->ncmds-1;
405                 *cmd_ = matchcmd->verb;
406                 *args_ = argv+matchcmd->ncmds+1;
407                 *func_ = cp->func;
408
409                 break;
410         }
411
412         if(helprequested){
413                 printf("\n%s\n", BTRFS_BUILD_VERSION);
414                 return 0;
415         }
416
417         if(!matchcmd){
418                 fprintf( stderr, "ERROR: unknown command '%s'\n",argv[1]);
419                 help(prgname);
420                 return -1;
421         }
422
423         if(check_ambiguity(matchcmd, argv))
424                 return -2;
425
426         /* check the number of argument */
427         if (matchcmd->nargs < 0 && matchcmd->nargs < -*nargs_ ){
428                 fprintf(stderr, "ERROR: '%s' requires minimum %d arg(s)\n",
429                         matchcmd->verb, -matchcmd->nargs);
430                         return -2;
431         }
432         if(matchcmd->nargs >= 0 && matchcmd->nargs != *nargs_ && matchcmd->nargs != 999){
433                 fprintf(stderr, "ERROR: '%s' requires %d arg(s)\n",
434                         matchcmd->verb, matchcmd->nargs);
435                         return -2;
436         }
437         
438         if (prepare_args( nargs_, args_, prgname, matchcmd )){
439                 fprintf(stderr, "ERROR: not enough memory\\n");
440                 return -20;
441         }
442
443
444         return 1;
445 }
446 int main(int ac, char **av )
447 {
448
449         char            *cmd=0, **args=0;
450         int             nargs=0, r;
451         CommandFunction func=0;
452
453         r = parse_args(ac, av, &func, &nargs, &cmd, &args);
454         if( r <= 0 ){
455                 /* error or no command to parse*/
456                 exit(-r);
457         }
458
459         exit(func(nargs, args));
460
461 }
462