Whamcloud - gitweb
Add missing information to debugfs man pages and usage texts
[tools/e2fsprogs.git] / debugfs / debugfs.c
1 /*
2  * debugfs.c --- a program which allows you to attach an ext2fs
3  * filesystem and play with it.
4  *
5  * Copyright (C) 1993 Theodore Ts'o.  This file may be redistributed
6  * under the terms of the GNU Public License.
7  *
8  * Modifications by Robert Sanders <gt8134b@prism.gatech.edu>
9  */
10
11 #include "config.h"
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <stdlib.h>
15 #include <ctype.h>
16 #include <string.h>
17 #include <time.h>
18 #include <libgen.h>
19 #ifdef HAVE_GETOPT_H
20 #include <getopt.h>
21 #else
22 extern int optind;
23 extern char *optarg;
24 #endif
25 #ifdef HAVE_ERRNO_H
26 #include <errno.h>
27 #endif
28 #include <fcntl.h>
29 #ifdef HAVE_SYS_SYSMACROS_H
30 #include <sys/sysmacros.h>
31 #endif
32
33 #include "debugfs.h"
34 #include "uuid/uuid.h"
35 #include "e2p/e2p.h"
36
37 #include <ext2fs/ext2_ext_attr.h>
38
39 #include "../version.h"
40 #include "jfs_user.h"
41 #include "support/plausible.h"
42
43 #ifndef BUFSIZ
44 #define BUFSIZ 8192
45 #endif
46
47 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jbd-debug */
48 int journal_enable_debug = -1;
49 #endif
50
51 ss_request_table *extra_cmds;
52 const char *debug_prog_name;
53 int sci_idx;
54
55 ext2_filsys     current_fs;
56 quota_ctx_t     current_qctx;
57 ext2_ino_t      root, cwd;
58
59 static int debugfs_setup_tdb(const char *device_name, char *undo_file,
60                              io_manager *io_ptr)
61 {
62         errcode_t retval = ENOMEM;
63         char *tdb_dir = NULL, *tdb_file = NULL;
64         char *dev_name, *tmp_name;
65
66         /* (re)open a specific undo file */
67         if (undo_file && undo_file[0] != 0) {
68                 retval = set_undo_io_backing_manager(*io_ptr);
69                 if (retval)
70                         goto err;
71                 *io_ptr = undo_io_manager;
72                 retval = set_undo_io_backup_file(undo_file);
73                 if (retval)
74                         goto err;
75                 printf("Overwriting existing filesystem; this can be undone "
76                         "using the command:\n"
77                         "    e2undo %s %s\n\n",
78                         undo_file, device_name);
79                 return retval;
80         }
81
82         /*
83          * Configuration via a conf file would be
84          * nice
85          */
86         tdb_dir = ss_safe_getenv("E2FSPROGS_UNDO_DIR");
87         if (!tdb_dir)
88                 tdb_dir = "/var/lib/e2fsprogs";
89
90         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
91             access(tdb_dir, W_OK))
92                 return 0;
93
94         tmp_name = strdup(device_name);
95         if (!tmp_name)
96                 goto errout;
97         dev_name = basename(tmp_name);
98         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
99         if (!tdb_file) {
100                 free(tmp_name);
101                 goto errout;
102         }
103         sprintf(tdb_file, "%s/debugfs-%s.e2undo", tdb_dir, dev_name);
104         free(tmp_name);
105
106         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
107                 retval = errno;
108                 com_err("debugfs", retval,
109                         "while trying to delete %s", tdb_file);
110                 goto errout;
111         }
112
113         retval = set_undo_io_backing_manager(*io_ptr);
114         if (retval)
115                 goto errout;
116         *io_ptr = undo_io_manager;
117         retval = set_undo_io_backup_file(tdb_file);
118         if (retval)
119                 goto errout;
120         printf("Overwriting existing filesystem; this can be undone "
121                 "using the command:\n"
122                 "    e2undo %s %s\n\n", tdb_file, device_name);
123
124         free(tdb_file);
125         return 0;
126 errout:
127         free(tdb_file);
128 err:
129         com_err("debugfs", retval, "while trying to setup undo file\n");
130         return retval;
131 }
132
133 static void open_filesystem(char *device, int open_flags, blk64_t superblock,
134                             blk64_t blocksize, int catastrophic,
135                             char *data_filename, char *undo_file)
136 {
137         int     retval;
138         io_channel data_io = 0;
139         io_manager io_ptr = unix_io_manager;
140
141         if (superblock != 0 && blocksize == 0) {
142                 com_err(device, 0, "if you specify the superblock, you must also specify the block size");
143                 current_fs = NULL;
144                 return;
145         }
146
147         if (data_filename) {
148                 if ((open_flags & EXT2_FLAG_IMAGE_FILE) == 0) {
149                         com_err(device, 0,
150                                 "The -d option is only valid when reading an e2image file");
151                         current_fs = NULL;
152                         return;
153                 }
154                 retval = unix_io_manager->open(data_filename, 0, &data_io);
155                 if (retval) {
156                         com_err(data_filename, 0, "while opening data source");
157                         current_fs = NULL;
158                         return;
159                 }
160         }
161
162         if (catastrophic && (open_flags & EXT2_FLAG_RW)) {
163                 com_err(device, 0,
164                         "opening read-only because of catastrophic mode");
165                 open_flags &= ~EXT2_FLAG_RW;
166         }
167         if (catastrophic)
168                 open_flags |= EXT2_FLAG_SKIP_MMP;
169
170         if (undo_file) {
171                 retval = debugfs_setup_tdb(device, undo_file, &io_ptr);
172                 if (retval)
173                         exit(1);
174         }
175
176 try_open_again:
177         retval = ext2fs_open(device, open_flags, superblock, blocksize,
178                              io_ptr, &current_fs);
179         if (retval && !(open_flags & EXT2_FLAG_IGNORE_CSUM_ERRORS)) {
180                 open_flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
181                 printf("Checksum errors in superblock!  Retrying...\n");
182                 goto try_open_again;
183         }
184         if (retval) {
185                 com_err(device, retval, "while opening filesystem");
186                 if (retval == EXT2_ET_BAD_MAGIC)
187                         check_plausibility(device, CHECK_FS_EXIST, NULL);
188                 current_fs = NULL;
189                 return;
190         }
191         current_fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
192
193         if (catastrophic)
194                 com_err(device, 0, "catastrophic mode - not reading inode or group bitmaps");
195         else {
196                 retval = ext2fs_read_inode_bitmap(current_fs);
197                 if (retval) {
198                         com_err(device, retval, "while reading inode bitmap");
199                         goto errout;
200                 }
201                 retval = ext2fs_read_block_bitmap(current_fs);
202                 if (retval) {
203                         com_err(device, retval, "while reading block bitmap");
204                         goto errout;
205                 }
206         }
207
208         if (data_io) {
209                 retval = ext2fs_set_data_io(current_fs, data_io);
210                 if (retval) {
211                         com_err(device, retval,
212                                 "while setting data source");
213                         goto errout;
214                 }
215         }
216
217         root = cwd = EXT2_ROOT_INO;
218         return;
219
220 errout:
221         retval = ext2fs_close_free(&current_fs);
222         if (retval)
223                 com_err(device, retval, "while trying to close filesystem");
224 }
225
226 void do_open_filesys(int argc, char **argv)
227 {
228         int     c, err;
229         int     catastrophic = 0;
230         blk64_t superblock = 0;
231         blk64_t blocksize = 0;
232         int     open_flags = EXT2_FLAG_SOFTSUPP_FEATURES | EXT2_FLAG_64BITS; 
233         char    *data_filename = 0;
234         char    *undo_file = NULL;
235
236         reset_getopt();
237         while ((c = getopt(argc, argv, "iwfecb:s:d:Dz:")) != EOF) {
238                 switch (c) {
239                 case 'i':
240                         open_flags |= EXT2_FLAG_IMAGE_FILE;
241                         break;
242                 case 'w':
243 #ifdef READ_ONLY
244                         goto print_usage;
245 #else
246                         open_flags |= EXT2_FLAG_RW;
247 #endif /* READ_ONLY */
248                         break;
249                 case 'f':
250                         open_flags |= EXT2_FLAG_FORCE;
251                         break;
252                 case 'e':
253                         open_flags |= EXT2_FLAG_EXCLUSIVE;
254                         break;
255                 case 'c':
256                         catastrophic = 1;
257                         break;
258                 case 'd':
259                         data_filename = optarg;
260                         break;
261                 case 'D':
262                         open_flags |= EXT2_FLAG_DIRECT_IO;
263                         break;
264                 case 'b':
265                         blocksize = parse_ulong(optarg, argv[0],
266                                                 "block size", &err);
267                         if (err)
268                                 return;
269                         break;
270                 case 's':
271                         err = strtoblk(argv[0], optarg,
272                                        "superblock block number", &superblock);
273                         if (err)
274                                 return;
275                         break;
276                 case 'z':
277                         undo_file = optarg;
278                         break;
279                 default:
280                         goto print_usage;
281                 }
282         }
283         if (optind != argc-1) {
284                 goto print_usage;
285         }
286         if (check_fs_not_open(argv[0]))
287                 return;
288         open_filesystem(argv[optind], open_flags,
289                         superblock, blocksize, catastrophic,
290                         data_filename, undo_file);
291         return;
292
293 print_usage:
294         fprintf(stderr, "%s: Usage: open [-s superblock] [-b blocksize] "
295                 "[-d image_filename] [-z undo_file] [-c] [-i] [-f] [-e] [-D] "
296 #ifndef READ_ONLY
297                 "[-w] "
298 #endif
299                 "<device>\n", argv[0]);
300 }
301
302 void do_lcd(int argc, char **argv)
303 {
304         if (argc != 2) {
305                 com_err(argv[0], 0, "Usage: %s %s", argv[0], "<native dir>");
306                 return;
307         }
308
309         if (chdir(argv[1]) == -1) {
310                 com_err(argv[0], errno,
311                         "while trying to change native directory to %s",
312                         argv[1]);
313                 return;
314         }
315 }
316
317 static void close_filesystem(NOARGS)
318 {
319         int     retval;
320
321         if (current_fs->flags & EXT2_FLAG_IB_DIRTY) {
322                 retval = ext2fs_write_inode_bitmap(current_fs);
323                 if (retval)
324                         com_err("ext2fs_write_inode_bitmap", retval, 0);
325         }
326         if (current_fs->flags & EXT2_FLAG_BB_DIRTY) {
327                 retval = ext2fs_write_block_bitmap(current_fs);
328                 if (retval)
329                         com_err("ext2fs_write_block_bitmap", retval, 0);
330         }
331         if (current_qctx)
332                 quota_release_context(&current_qctx);
333         retval = ext2fs_close_free(&current_fs);
334         if (retval)
335                 com_err("ext2fs_close", retval, 0);
336         return;
337 }
338
339 void do_close_filesys(int argc, char **argv)
340 {
341         int     c;
342
343         if (check_fs_open(argv[0]))
344                 return;
345
346         reset_getopt();
347         while ((c = getopt (argc, argv, "a")) != EOF) {
348                 switch (c) {
349                 case 'a':
350                         current_fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
351                         break;
352                 default:
353                         goto print_usage;
354                 }
355         }
356
357         if (argc > optind) {
358         print_usage:
359                 com_err(0, 0, "Usage: close_filesys [-a]");
360                 return;
361         }
362
363         close_filesystem();
364 }
365
366 #ifndef READ_ONLY
367 void do_init_filesys(int argc, char **argv)
368 {
369         struct ext2_super_block param;
370         errcode_t       retval;
371         int             err;
372         blk64_t         blocks;
373
374         if (common_args_process(argc, argv, 3, 3, "initialize",
375                                 "<device> <blocks>", CHECK_FS_NOTOPEN))
376                 return;
377
378         memset(&param, 0, sizeof(struct ext2_super_block));
379         err = strtoblk(argv[0], argv[2], "blocks count", &blocks);
380         if (err)
381                 return;
382         ext2fs_blocks_count_set(&param, blocks);
383         retval = ext2fs_initialize(argv[1], 0, &param,
384                                    unix_io_manager, &current_fs);
385         if (retval) {
386                 com_err(argv[1], retval, "while initializing filesystem");
387                 current_fs = NULL;
388                 return;
389         }
390         root = cwd = EXT2_ROOT_INO;
391         return;
392 }
393
394 static void print_features(struct ext2_super_block * s, FILE *f)
395 {
396         int     i, j, printed=0;
397         __u32   *mask = &s->s_feature_compat, m;
398
399         fputs("Filesystem features:", f);
400         for (i=0; i <3; i++,mask++) {
401                 for (j=0,m=1; j < 32; j++, m<<=1) {
402                         if (*mask & m) {
403                                 fprintf(f, " %s", e2p_feature2string(i, m));
404                                 printed++;
405                         }
406                 }
407         }
408         if (printed == 0)
409                 fputs("(none)", f);
410         fputs("\n", f);
411 }
412 #endif /* READ_ONLY */
413
414 static void print_bg_opts(ext2_filsys fs, dgrp_t group, int mask,
415                           const char *str, int *first, FILE *f)
416 {
417         if (ext2fs_bg_flags_test(fs, group, mask)) {
418                 if (*first) {
419                         fputs("           [", f);
420                         *first = 0;
421                 } else
422                         fputs(", ", f);
423                 fputs(str, f);
424         }
425 }
426
427 void do_show_super_stats(int argc, char *argv[])
428 {
429         const char *units ="block";
430         dgrp_t  i;
431         FILE    *out;
432         int     c, header_only = 0;
433         int     numdirs = 0, first, gdt_csum;
434
435         reset_getopt();
436         while ((c = getopt (argc, argv, "h")) != EOF) {
437                 switch (c) {
438                 case 'h':
439                         header_only++;
440                         break;
441                 default:
442                         goto print_usage;
443                 }
444         }
445         if (optind != argc) {
446                 goto print_usage;
447         }
448         if (check_fs_open(argv[0]))
449                 return;
450         out = open_pager();
451
452         if (ext2fs_has_feature_bigalloc(current_fs->super))
453                 units = "cluster";
454
455         list_super2(current_fs->super, out);
456         if (ext2fs_has_feature_metadata_csum(current_fs->super) &&
457             !ext2fs_superblock_csum_verify(current_fs,
458                                            current_fs->super)) {
459                 __u32 orig_csum = current_fs->super->s_checksum;
460
461                 ext2fs_superblock_csum_set(current_fs,
462                                            current_fs->super);
463                 fprintf(out, "Expected Checksum:        0x%08x\n",
464                         current_fs->super->s_checksum);
465                 current_fs->super->s_checksum = orig_csum;
466         }
467         for (i=0; i < current_fs->group_desc_count; i++)
468                 numdirs += ext2fs_bg_used_dirs_count(current_fs, i);
469         fprintf(out, "Directories:              %d\n", numdirs);
470
471         if (header_only) {
472                 close_pager(out);
473                 return;
474         }
475
476         gdt_csum = ext2fs_has_group_desc_csum(current_fs);
477         for (i = 0; i < current_fs->group_desc_count; i++) {
478                 fprintf(out, " Group %2d: block bitmap at %llu, "
479                         "inode bitmap at %llu, "
480                         "inode table at %llu\n"
481                         "           %u free %s%s, "
482                         "%u free %s, "
483                         "%u used %s%s",
484                         i, ext2fs_block_bitmap_loc(current_fs, i),
485                         ext2fs_inode_bitmap_loc(current_fs, i),
486                         ext2fs_inode_table_loc(current_fs, i),
487                         ext2fs_bg_free_blocks_count(current_fs, i), units,
488                         ext2fs_bg_free_blocks_count(current_fs, i) != 1 ?
489                         "s" : "",
490                         ext2fs_bg_free_inodes_count(current_fs, i),
491                         ext2fs_bg_free_inodes_count(current_fs, i) != 1 ?
492                         "inodes" : "inode",
493                         ext2fs_bg_used_dirs_count(current_fs, i),
494                         ext2fs_bg_used_dirs_count(current_fs, i) != 1 ? "directories"
495                                 : "directory", gdt_csum ? ", " : "\n");
496                 if (gdt_csum)
497                         fprintf(out, "%u unused %s\n",
498                                 ext2fs_bg_itable_unused(current_fs, i),
499                                 ext2fs_bg_itable_unused(current_fs, i) != 1 ?
500                                 "inodes" : "inode");
501                 first = 1;
502                 print_bg_opts(current_fs, i, EXT2_BG_INODE_UNINIT, "Inode not init",
503                               &first, out);
504                 print_bg_opts(current_fs, i, EXT2_BG_BLOCK_UNINIT, "Block not init",
505                               &first, out);
506                 if (gdt_csum) {
507                         fprintf(out, "%sChecksum 0x%04x",
508                                 first ? "           [":", ", ext2fs_bg_checksum(current_fs, i));
509                         first = 0;
510                 }
511                 if (!first)
512                         fputs("]\n", out);
513         }
514         close_pager(out);
515         return;
516 print_usage:
517         fprintf(stderr, "%s: Usage: show_super_stats [-h]\n", argv[0]);
518 }
519
520 #ifndef READ_ONLY
521 void do_dirty_filesys(int argc EXT2FS_ATTR((unused)),
522                       char **argv EXT2FS_ATTR((unused)))
523 {
524         if (check_fs_open(argv[0]))
525                 return;
526         if (check_fs_read_write(argv[0]))
527                 return;
528
529         if (argv[1] && !strcmp(argv[1], "-clean"))
530                 current_fs->super->s_state |= EXT2_VALID_FS;
531         else
532                 current_fs->super->s_state &= ~EXT2_VALID_FS;
533         ext2fs_mark_super_dirty(current_fs);
534 }
535 #endif /* READ_ONLY */
536
537 struct list_blocks_struct {
538         FILE            *f;
539         e2_blkcnt_t     total;
540         blk64_t         first_block, last_block;
541         e2_blkcnt_t     first_bcnt, last_bcnt;
542         e2_blkcnt_t     first;
543 };
544
545 static void finish_range(struct list_blocks_struct *lb)
546 {
547         if (lb->first_block == 0)
548                 return;
549         if (lb->first)
550                 lb->first = 0;
551         else
552                 fprintf(lb->f, ", ");
553         if (lb->first_block == lb->last_block)
554                 fprintf(lb->f, "(%lld):%llu",
555                         (long long)lb->first_bcnt, lb->first_block);
556         else
557                 fprintf(lb->f, "(%lld-%lld):%llu-%llu",
558                         (long long)lb->first_bcnt, (long long)lb->last_bcnt,
559                         lb->first_block, lb->last_block);
560         lb->first_block = 0;
561 }
562
563 static int list_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)),
564                             blk64_t *blocknr, e2_blkcnt_t blockcnt,
565                             blk64_t ref_block EXT2FS_ATTR((unused)),
566                             int ref_offset EXT2FS_ATTR((unused)),
567                             void *private)
568 {
569         struct list_blocks_struct *lb = (struct list_blocks_struct *) private;
570
571         lb->total++;
572         if (blockcnt >= 0) {
573                 /*
574                  * See if we can add on to the existing range (if it exists)
575                  */
576                 if (lb->first_block &&
577                     (lb->last_block+1 == *blocknr) &&
578                     (lb->last_bcnt+1 == blockcnt)) {
579                         lb->last_block = *blocknr;
580                         lb->last_bcnt = blockcnt;
581                         return 0;
582                 }
583                 /*
584                  * Start a new range.
585                  */
586                 finish_range(lb);
587                 lb->first_block = lb->last_block = *blocknr;
588                 lb->first_bcnt = lb->last_bcnt = blockcnt;
589                 return 0;
590         }
591         /*
592          * Not a normal block.  Always force a new range.
593          */
594         finish_range(lb);
595         if (lb->first)
596                 lb->first = 0;
597         else
598                 fprintf(lb->f, ", ");
599         if (blockcnt == -1)
600                 fprintf(lb->f, "(IND):%llu", (unsigned long long) *blocknr);
601         else if (blockcnt == -2)
602                 fprintf(lb->f, "(DIND):%llu", (unsigned long long) *blocknr);
603         else if (blockcnt == -3)
604                 fprintf(lb->f, "(TIND):%llu", (unsigned long long) *blocknr);
605         return 0;
606 }
607
608 static void internal_dump_inode_extra(FILE *out,
609                                       const char *prefix EXT2FS_ATTR((unused)),
610                                       ext2_ino_t inode_num EXT2FS_ATTR((unused)),
611                                       struct ext2_inode_large *inode)
612 {
613         fprintf(out, "Size of extra inode fields: %u\n", inode->i_extra_isize);
614         if (inode->i_extra_isize > EXT2_INODE_SIZE(current_fs->super) -
615                         EXT2_GOOD_OLD_INODE_SIZE) {
616                 fprintf(stderr, "invalid inode->i_extra_isize (%u)\n",
617                                 inode->i_extra_isize);
618                 return;
619         }
620 }
621
622 static void dump_blocks(FILE *f, const char *prefix, ext2_ino_t inode)
623 {
624         struct list_blocks_struct lb;
625
626         fprintf(f, "%sBLOCKS:\n%s", prefix, prefix);
627         lb.total = 0;
628         lb.first_block = 0;
629         lb.f = f;
630         lb.first = 1;
631         ext2fs_block_iterate3(current_fs, inode, BLOCK_FLAG_READ_ONLY, NULL,
632                               list_blocks_proc, (void *)&lb);
633         finish_range(&lb);
634         if (lb.total)
635                 fprintf(f, "\n%sTOTAL: %lld\n", prefix, (long long)lb.total);
636         fprintf(f,"\n");
637 }
638
639 static int int_log10(unsigned long long arg)
640 {
641         int     l = 0;
642
643         arg = arg / 10;
644         while (arg) {
645                 l++;
646                 arg = arg / 10;
647         }
648         return l;
649 }
650
651 #define DUMP_LEAF_EXTENTS       0x01
652 #define DUMP_NODE_EXTENTS       0x02
653 #define DUMP_EXTENT_TABLE       0x04
654
655 static void dump_extents(FILE *f, const char *prefix, ext2_ino_t ino,
656                          int flags, int logical_width, int physical_width)
657 {
658         ext2_extent_handle_t    handle;
659         struct ext2fs_extent    extent;
660         struct ext2_extent_info info;
661         int                     op = EXT2_EXTENT_ROOT;
662         unsigned int            printed = 0;
663         errcode_t               errcode;
664
665         errcode = ext2fs_extent_open(current_fs, ino, &handle);
666         if (errcode)
667                 return;
668
669         if (flags & DUMP_EXTENT_TABLE)
670                 fprintf(f, "Level Entries %*s %*s Length Flags\n",
671                         (logical_width*2)+3, "Logical",
672                         (physical_width*2)+3, "Physical");
673         else
674                 fprintf(f, "%sEXTENTS:\n%s", prefix, prefix);
675
676         while (1) {
677                 errcode = ext2fs_extent_get(handle, op, &extent);
678
679                 if (errcode)
680                         break;
681
682                 op = EXT2_EXTENT_NEXT;
683
684                 if (extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT)
685                         continue;
686
687                 if (extent.e_flags & EXT2_EXTENT_FLAGS_LEAF) {
688                         if ((flags & DUMP_LEAF_EXTENTS) == 0)
689                                 continue;
690                 } else {
691                         if ((flags & DUMP_NODE_EXTENTS) == 0)
692                                 continue;
693                 }
694
695                 errcode = ext2fs_extent_get_info(handle, &info);
696                 if (errcode)
697                         continue;
698
699                 if (!(extent.e_flags & EXT2_EXTENT_FLAGS_LEAF)) {
700                         if (extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT)
701                                 continue;
702
703                         if (flags & DUMP_EXTENT_TABLE) {
704                                 fprintf(f, "%2d/%2d %3d/%3d %*llu - %*llu "
705                                         "%*llu%*s %6u\n",
706                                         info.curr_level, info.max_depth,
707                                         info.curr_entry, info.num_entries,
708                                         logical_width,
709                                         extent.e_lblk,
710                                         logical_width,
711                                         extent.e_lblk + (extent.e_len - 1),
712                                         physical_width,
713                                         extent.e_pblk,
714                                         physical_width+3, "", extent.e_len);
715                                 continue;
716                         }
717
718                         fprintf(f, "%s(ETB%d):%lld",
719                                 printed ? ", " : "", info.curr_level,
720                                 extent.e_pblk);
721                         printed = 1;
722                         continue;
723                 }
724
725                 if (flags & DUMP_EXTENT_TABLE) {
726                         fprintf(f, "%2d/%2d %3d/%3d %*llu - %*llu "
727                                 "%*llu - %*llu %6u %s\n",
728                                 info.curr_level, info.max_depth,
729                                 info.curr_entry, info.num_entries,
730                                 logical_width,
731                                 extent.e_lblk,
732                                 logical_width,
733                                 extent.e_lblk + (extent.e_len - 1),
734                                 physical_width,
735                                 extent.e_pblk,
736                                 physical_width,
737                                 extent.e_pblk + (extent.e_len - 1),
738                                 extent.e_len,
739                                 extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT ?
740                                         "Uninit" : "");
741                         continue;
742                 }
743
744                 if (extent.e_len == 0)
745                         continue;
746                 else if (extent.e_len == 1)
747                         fprintf(f,
748                                 "%s(%lld%s):%lld",
749                                 printed ? ", " : "",
750                                 extent.e_lblk,
751                                 extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT ?
752                                 "[u]" : "",
753                                 extent.e_pblk);
754                 else
755                         fprintf(f,
756                                 "%s(%lld-%lld%s):%lld-%lld",
757                                 printed ? ", " : "",
758                                 extent.e_lblk,
759                                 extent.e_lblk + (extent.e_len - 1),
760                                 extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT ?
761                                         "[u]" : "",
762                                 extent.e_pblk,
763                                 extent.e_pblk + (extent.e_len - 1));
764                 printed = 1;
765         }
766         if (printed)
767                 fprintf(f, "\n");
768         ext2fs_extent_free(handle);
769 }
770
771 static void dump_inline_data(FILE *out, const char *prefix, ext2_ino_t inode_num)
772 {
773         errcode_t retval;
774         size_t size;
775
776         retval = ext2fs_inline_data_size(current_fs, inode_num, &size);
777         if (!retval)
778                 fprintf(out, "%sSize of inline data: %zu\n", prefix, size);
779 }
780
781 static void dump_fast_link(FILE *out, ext2_ino_t inode_num,
782                            struct ext2_inode *inode, const char *prefix)
783 {
784         errcode_t retval = 0;
785         char *buf;
786         size_t size;
787
788         if (inode->i_flags & EXT4_INLINE_DATA_FL) {
789                 retval = ext2fs_inline_data_size(current_fs, inode_num, &size);
790                 if (retval)
791                         goto out;
792
793                 retval = ext2fs_get_memzero(size + 1, &buf);
794                 if (retval)
795                         goto out;
796
797                 retval = ext2fs_inline_data_get(current_fs, inode_num,
798                                                 inode, buf, &size);
799                 if (retval)
800                         goto out;
801                 fprintf(out, "%sFast link dest: \"%.*s\"\n", prefix,
802                         (int)size, buf);
803
804                 retval = ext2fs_free_mem(&buf);
805                 if (retval)
806                         goto out;
807         } else {
808                 size_t sz = EXT2_I_SIZE(inode);
809
810                 if (sz > sizeof(inode->i_block))
811                         sz = sizeof(inode->i_block);
812                 fprintf(out, "%sFast link dest: \"%.*s\"\n", prefix, (int) sz,
813                         (char *)inode->i_block);
814         }
815 out:
816         if (retval)
817                 com_err(__func__, retval, "while dumping link destination");
818 }
819
820 void internal_dump_inode(FILE *out, const char *prefix,
821                          ext2_ino_t inode_num, struct ext2_inode *inode,
822                          int do_dump_blocks)
823 {
824         const char *i_type;
825         char frag, fsize;
826         int os = current_fs->super->s_creator_os;
827         struct ext2_inode_large *large_inode;
828         int is_large_inode = 0;
829
830         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
831                 is_large_inode = 1;
832         large_inode = (struct ext2_inode_large *) inode;
833
834         if (LINUX_S_ISDIR(inode->i_mode)) i_type = "directory";
835         else if (LINUX_S_ISREG(inode->i_mode)) i_type = "regular";
836         else if (LINUX_S_ISLNK(inode->i_mode)) i_type = "symlink";
837         else if (LINUX_S_ISBLK(inode->i_mode)) i_type = "block special";
838         else if (LINUX_S_ISCHR(inode->i_mode)) i_type = "character special";
839         else if (LINUX_S_ISFIFO(inode->i_mode)) i_type = "FIFO";
840         else if (LINUX_S_ISSOCK(inode->i_mode)) i_type = "socket";
841         else i_type = "bad type";
842         fprintf(out, "%sInode: %u   Type: %s    ", prefix, inode_num, i_type);
843         fprintf(out, "%sMode:  %04o   Flags: 0x%x\n",
844                 prefix, inode->i_mode & 0777, inode->i_flags);
845         if (is_large_inode && large_inode->i_extra_isize >= 24) {
846                 fprintf(out, "%sGeneration: %u    Version: 0x%08x:%08x\n",
847                         prefix, inode->i_generation, large_inode->i_version_hi,
848                         inode->osd1.linux1.l_i_version);
849         } else {
850                 fprintf(out, "%sGeneration: %u    Version: 0x%08x\n", prefix,
851                         inode->i_generation, inode->osd1.linux1.l_i_version);
852         }
853         fprintf(out, "%sUser: %5d   Group: %5d",
854                 prefix, inode_uid(*inode), inode_gid(*inode));
855         if (is_large_inode && large_inode->i_extra_isize >= 32)
856                 fprintf(out, "   Project: %5d", large_inode->i_projid);
857         fputs("   Size: ", out);
858         if (LINUX_S_ISREG(inode->i_mode))
859                 fprintf(out, "%llu\n", EXT2_I_SIZE(inode));
860         else
861                 fprintf(out, "%d\n", inode->i_size);
862         if (os == EXT2_OS_HURD)
863                 fprintf(out,
864                         "%sFile ACL: %d    Directory ACL: %d Translator: %d\n",
865                         prefix,
866                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0,
867                         inode->osd1.hurd1.h_i_translator);
868         else
869                 fprintf(out, "%sFile ACL: %llu    Directory ACL: %d\n",
870                         prefix,
871                         inode->i_file_acl | ((long long)
872                                 (inode->osd2.linux2.l_i_file_acl_high) << 32),
873                         LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0);
874         if (os != EXT2_OS_HURD)
875                 fprintf(out, "%sLinks: %d   Blockcount: %llu\n",
876                         prefix, inode->i_links_count,
877                         (((unsigned long long)
878                           inode->osd2.linux2.l_i_blocks_hi << 32)) +
879                         inode->i_blocks);
880         else
881                 fprintf(out, "%sLinks: %d   Blockcount: %u\n",
882                         prefix, inode->i_links_count, inode->i_blocks);
883         switch (os) {
884             case EXT2_OS_HURD:
885                 frag = inode->osd2.hurd2.h_i_frag;
886                 fsize = inode->osd2.hurd2.h_i_fsize;
887                 break;
888             default:
889                 frag = fsize = 0;
890         }
891         fprintf(out, "%sFragment:  Address: %d    Number: %d    Size: %d\n",
892                 prefix, inode->i_faddr, frag, fsize);
893         if (is_large_inode && large_inode->i_extra_isize >= 24) {
894                 fprintf(out, "%s ctime: 0x%08x:%08x -- %s", prefix,
895                         inode->i_ctime, large_inode->i_ctime_extra,
896                         inode_time_to_string(inode->i_ctime,
897                                              large_inode->i_ctime_extra));
898                 fprintf(out, "%s atime: 0x%08x:%08x -- %s", prefix,
899                         inode->i_atime, large_inode->i_atime_extra,
900                         inode_time_to_string(inode->i_atime,
901                                              large_inode->i_atime_extra));
902                 fprintf(out, "%s mtime: 0x%08x:%08x -- %s", prefix,
903                         inode->i_mtime, large_inode->i_mtime_extra,
904                         inode_time_to_string(inode->i_mtime,
905                                              large_inode->i_mtime_extra));
906                 fprintf(out, "%scrtime: 0x%08x:%08x -- %s", prefix,
907                         large_inode->i_crtime, large_inode->i_crtime_extra,
908                         inode_time_to_string(large_inode->i_crtime,
909                                              large_inode->i_crtime_extra));
910                 if (inode->i_dtime)
911                         fprintf(out, "%s dtime: 0x%08x:(%08x) -- %s", prefix,
912                                 large_inode->i_dtime, large_inode->i_ctime_extra,
913                                 inode_time_to_string(inode->i_dtime,
914                                                      large_inode->i_ctime_extra));
915         } else {
916                 fprintf(out, "%sctime: 0x%08x -- %s", prefix, inode->i_ctime,
917                         time_to_string((__s32) inode->i_ctime));
918                 fprintf(out, "%satime: 0x%08x -- %s", prefix, inode->i_atime,
919                         time_to_string((__s32) inode->i_atime));
920                 fprintf(out, "%smtime: 0x%08x -- %s", prefix, inode->i_mtime,
921                         time_to_string((__s32) inode->i_mtime));
922                 if (inode->i_dtime)
923                         fprintf(out, "%sdtime: 0x%08x -- %s", prefix,
924                                 inode->i_dtime,
925                                 time_to_string((__s32) inode->i_dtime));
926         }
927         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
928                 internal_dump_inode_extra(out, prefix, inode_num,
929                                           (struct ext2_inode_large *) inode);
930         dump_inode_attributes(out, inode_num);
931         if (ext2fs_has_feature_metadata_csum(current_fs->super)) {
932                 __u32 crc = inode->i_checksum_lo;
933                 if (is_large_inode &&
934                     large_inode->i_extra_isize >=
935                                 (offsetof(struct ext2_inode_large,
936                                           i_checksum_hi) -
937                                  EXT2_GOOD_OLD_INODE_SIZE))
938                         crc |= ((__u32)large_inode->i_checksum_hi) << 16;
939                 fprintf(out, "Inode checksum: 0x%08x\n", crc);
940         }
941
942         if (LINUX_S_ISLNK(inode->i_mode) &&
943             ext2fs_inode_data_blocks(current_fs, inode) == 0)
944                 dump_fast_link(out, inode_num, inode, prefix);
945         else if (LINUX_S_ISBLK(inode->i_mode) || LINUX_S_ISCHR(inode->i_mode)) {
946                 int major, minor;
947                 const char *devnote;
948
949                 if (inode->i_block[0]) {
950                         major = (inode->i_block[0] >> 8) & 255;
951                         minor = inode->i_block[0] & 255;
952                         devnote = "";
953                 } else {
954                         major = (inode->i_block[1] & 0xfff00) >> 8;
955                         minor = ((inode->i_block[1] & 0xff) |
956                                  ((inode->i_block[1] >> 12) & 0xfff00));
957                         devnote = "(New-style) ";
958                 }
959                 fprintf(out, "%sDevice major/minor number: %02d:%02d (hex %02x:%02x)\n",
960                         devnote, major, minor, major, minor);
961         } else if (do_dump_blocks) {
962                 if (inode->i_flags & EXT4_EXTENTS_FL)
963                         dump_extents(out, prefix, inode_num,
964                                      DUMP_LEAF_EXTENTS|DUMP_NODE_EXTENTS, 0, 0);
965                 else if (inode->i_flags & EXT4_INLINE_DATA_FL)
966                         dump_inline_data(out, prefix, inode_num);
967                 else
968                         dump_blocks(out, prefix, inode_num);
969         }
970 }
971
972 static void dump_inode(ext2_ino_t inode_num, struct ext2_inode *inode)
973 {
974         FILE    *out;
975
976         out = open_pager();
977         internal_dump_inode(out, "", inode_num, inode, 1);
978         close_pager(out);
979 }
980
981 void do_stat(int argc, char *argv[])
982 {
983         ext2_ino_t      inode;
984         struct ext2_inode * inode_buf;
985
986         if (check_fs_open(argv[0]))
987                 return;
988
989         inode_buf = (struct ext2_inode *)
990                         malloc(EXT2_INODE_SIZE(current_fs->super));
991         if (!inode_buf) {
992                 fprintf(stderr, "do_stat: can't allocate buffer\n");
993                 return;
994         }
995
996         if (common_inode_args_process(argc, argv, &inode, 0)) {
997                 free(inode_buf);
998                 return;
999         }
1000
1001         if (debugfs_read_inode_full(inode, inode_buf, argv[0],
1002                                         EXT2_INODE_SIZE(current_fs->super))) {
1003                 free(inode_buf);
1004                 return;
1005         }
1006
1007         dump_inode(inode, inode_buf);
1008         free(inode_buf);
1009         return;
1010 }
1011
1012 void do_dump_extents(int argc, char **argv)
1013 {
1014         struct ext2_inode inode;
1015         ext2_ino_t      ino;
1016         FILE            *out;
1017         int             c, flags = 0;
1018         int             logical_width;
1019         int             physical_width;
1020
1021         reset_getopt();
1022         while ((c = getopt(argc, argv, "nl")) != EOF) {
1023                 switch (c) {
1024                 case 'n':
1025                         flags |= DUMP_NODE_EXTENTS;
1026                         break;
1027                 case 'l':
1028                         flags |= DUMP_LEAF_EXTENTS;
1029                         break;
1030                 }
1031         }
1032
1033         if (argc != optind + 1) {
1034                 com_err(0, 0, "Usage: dump_extents [-n] [-l] file");
1035                 return;
1036         }
1037
1038         if (flags == 0)
1039                 flags = DUMP_NODE_EXTENTS | DUMP_LEAF_EXTENTS;
1040         flags |= DUMP_EXTENT_TABLE;
1041
1042         if (check_fs_open(argv[0]))
1043                 return;
1044
1045         ino = string_to_inode(argv[optind]);
1046         if (ino == 0)
1047                 return;
1048
1049         if (debugfs_read_inode(ino, &inode, argv[0]))
1050                 return;
1051
1052         if ((inode.i_flags & EXT4_EXTENTS_FL) == 0) {
1053                 fprintf(stderr, "%s: does not uses extent block maps\n",
1054                         argv[optind]);
1055                 return;
1056         }
1057
1058         logical_width = int_log10((EXT2_I_SIZE(&inode)+current_fs->blocksize-1)/
1059                                   current_fs->blocksize) + 1;
1060         if (logical_width < 5)
1061                 logical_width = 5;
1062         physical_width = int_log10(ext2fs_blocks_count(current_fs->super)) + 1;
1063         if (physical_width < 5)
1064                 physical_width = 5;
1065
1066         out = open_pager();
1067         dump_extents(out, "", ino, flags, logical_width, physical_width);
1068         close_pager(out);
1069         return;
1070 }
1071
1072 static int print_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)),
1073                              blk64_t *blocknr,
1074                              e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1075                              blk64_t ref_block EXT2FS_ATTR((unused)),
1076                              int ref_offset EXT2FS_ATTR((unused)),
1077                              void *private EXT2FS_ATTR((unused)))
1078 {
1079         printf("%llu ", *blocknr);
1080         return 0;
1081 }
1082
1083 void do_blocks(int argc, char *argv[])
1084 {
1085         ext2_ino_t      inode;
1086
1087         if (check_fs_open(argv[0]))
1088                 return;
1089
1090         if (common_inode_args_process(argc, argv, &inode, 0)) {
1091                 return;
1092         }
1093
1094         ext2fs_block_iterate3(current_fs, inode, BLOCK_FLAG_READ_ONLY, NULL,
1095                               print_blocks_proc, NULL);
1096         fputc('\n', stdout);
1097         return;
1098 }
1099
1100 void do_chroot(int argc, char *argv[])
1101 {
1102         ext2_ino_t inode;
1103         int retval;
1104
1105         if (common_inode_args_process(argc, argv, &inode, 0))
1106                 return;
1107
1108         retval = ext2fs_check_directory(current_fs, inode);
1109         if (retval)  {
1110                 com_err(argv[1], retval, 0);
1111                 return;
1112         }
1113         root = inode;
1114 }
1115
1116 #ifndef READ_ONLY
1117 void do_clri(int argc, char *argv[])
1118 {
1119         ext2_ino_t inode;
1120         struct ext2_inode inode_buf;
1121
1122         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1123                 return;
1124
1125         if (debugfs_read_inode(inode, &inode_buf, argv[0]))
1126                 return;
1127         memset(&inode_buf, 0, sizeof(inode_buf));
1128         if (debugfs_write_inode(inode, &inode_buf, argv[0]))
1129                 return;
1130 }
1131
1132 void do_freei(int argc, char *argv[])
1133 {
1134         unsigned int    len = 1;
1135         int             err = 0;
1136         ext2_ino_t      inode;
1137
1138         if (common_args_process(argc, argv, 2, 3, argv[0], "<file> [num]",
1139                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1140                 return;
1141         if (check_fs_read_write(argv[0]))
1142                 return;
1143
1144         inode = string_to_inode(argv[1]);
1145         if (!inode)
1146                 return;
1147
1148         if (argc == 3) {
1149                 len = parse_ulong(argv[2], argv[0], "length", &err);
1150                 if (err)
1151                         return;
1152         }
1153
1154         if (len == 1 &&
1155             !ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1156                 com_err(argv[0], 0, "Warning: inode already clear");
1157         while (len-- > 0)
1158                 ext2fs_unmark_inode_bitmap2(current_fs->inode_map, inode++);
1159         ext2fs_mark_ib_dirty(current_fs);
1160 }
1161
1162 void do_seti(int argc, char *argv[])
1163 {
1164         unsigned int    len = 1;
1165         int             err = 0;
1166         ext2_ino_t      inode;
1167
1168         if (common_args_process(argc, argv, 2, 3, argv[0], "<file> [num]",
1169                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1170                 return;
1171         if (check_fs_read_write(argv[0]))
1172                 return;
1173
1174         inode = string_to_inode(argv[1]);
1175         if (!inode)
1176                 return;
1177
1178         if (argc == 3) {
1179                 len = parse_ulong(argv[2], argv[0], "length", &err);
1180                 if (err)
1181                         return;
1182         }
1183
1184         if ((len == 1) &&
1185             ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1186                 com_err(argv[0], 0, "Warning: inode already set");
1187         while (len-- > 0)
1188                 ext2fs_mark_inode_bitmap2(current_fs->inode_map, inode++);
1189         ext2fs_mark_ib_dirty(current_fs);
1190 }
1191 #endif /* READ_ONLY */
1192
1193 void do_testi(int argc, char *argv[])
1194 {
1195         ext2_ino_t inode;
1196
1197         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_BITMAPS))
1198                 return;
1199
1200         if (ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1201                 printf("Inode %u is marked in use\n", inode);
1202         else
1203                 printf("Inode %u is not in use\n", inode);
1204 }
1205
1206 #ifndef READ_ONLY
1207 void do_freeb(int argc, char *argv[])
1208 {
1209         blk64_t block;
1210         blk64_t count = 1;
1211
1212         if (common_block_args_process(argc, argv, &block, &count))
1213                 return;
1214         if (check_fs_read_write(argv[0]))
1215                 return;
1216         while (count-- > 0) {
1217                 if (!ext2fs_test_block_bitmap2(current_fs->block_map,block))
1218                         com_err(argv[0], 0, "Warning: block %llu already clear",
1219                                 block);
1220                 ext2fs_unmark_block_bitmap2(current_fs->block_map,block);
1221                 block++;
1222         }
1223         ext2fs_mark_bb_dirty(current_fs);
1224 }
1225
1226 void do_setb(int argc, char *argv[])
1227 {
1228         blk64_t block;
1229         blk64_t count = 1;
1230
1231         if (common_block_args_process(argc, argv, &block, &count))
1232                 return;
1233         if (check_fs_read_write(argv[0]))
1234                 return;
1235         while (count-- > 0) {
1236                 if (ext2fs_test_block_bitmap2(current_fs->block_map,block))
1237                         com_err(argv[0], 0, "Warning: block %llu already set",
1238                                 block);
1239                 ext2fs_mark_block_bitmap2(current_fs->block_map,block);
1240                 block++;
1241         }
1242         ext2fs_mark_bb_dirty(current_fs);
1243 }
1244 #endif /* READ_ONLY */
1245
1246 void do_testb(int argc, char *argv[])
1247 {
1248         blk64_t block;
1249         blk64_t count = 1;
1250
1251         if (common_block_args_process(argc, argv, &block, &count))
1252                 return;
1253         while (count-- > 0) {
1254                 if (ext2fs_test_block_bitmap2(current_fs->block_map,block))
1255                         printf("Block %llu marked in use\n", block);
1256                 else
1257                         printf("Block %llu not in use\n", block);
1258                 block++;
1259         }
1260 }
1261
1262 #ifndef READ_ONLY
1263 static void modify_u8(char *com, const char *prompt,
1264                       const char *format, __u8 *val)
1265 {
1266         char buf[200];
1267         unsigned long v;
1268         char *tmp;
1269
1270         sprintf(buf, format, *val);
1271         printf("%30s    [%s] ", prompt, buf);
1272         if (!fgets(buf, sizeof(buf), stdin))
1273                 return;
1274         if (buf[strlen (buf) - 1] == '\n')
1275                 buf[strlen (buf) - 1] = '\0';
1276         if (!buf[0])
1277                 return;
1278         v = strtoul(buf, &tmp, 0);
1279         if (*tmp)
1280                 com_err(com, 0, "Bad value - %s", buf);
1281         else
1282                 *val = v;
1283 }
1284
1285 static void modify_u16(char *com, const char *prompt,
1286                        const char *format, __u16 *val)
1287 {
1288         char buf[200];
1289         unsigned long v;
1290         char *tmp;
1291
1292         sprintf(buf, format, *val);
1293         printf("%30s    [%s] ", prompt, buf);
1294         if (!fgets(buf, sizeof(buf), stdin))
1295                 return;
1296         if (buf[strlen (buf) - 1] == '\n')
1297                 buf[strlen (buf) - 1] = '\0';
1298         if (!buf[0])
1299                 return;
1300         v = strtoul(buf, &tmp, 0);
1301         if (*tmp)
1302                 com_err(com, 0, "Bad value - %s", buf);
1303         else
1304                 *val = v;
1305 }
1306
1307 static void modify_u32(char *com, const char *prompt,
1308                        const char *format, __u32 *val)
1309 {
1310         char buf[200];
1311         unsigned long v;
1312         char *tmp;
1313
1314         sprintf(buf, format, *val);
1315         printf("%30s    [%s] ", prompt, buf);
1316         if (!fgets(buf, sizeof(buf), stdin))
1317                 return;
1318         if (buf[strlen (buf) - 1] == '\n')
1319                 buf[strlen (buf) - 1] = '\0';
1320         if (!buf[0])
1321                 return;
1322         v = strtoul(buf, &tmp, 0);
1323         if (*tmp)
1324                 com_err(com, 0, "Bad value - %s", buf);
1325         else
1326                 *val = v;
1327 }
1328
1329
1330 void do_modify_inode(int argc, char *argv[])
1331 {
1332         struct ext2_inode inode;
1333         ext2_ino_t      inode_num;
1334         int             i;
1335         unsigned char   *frag, *fsize;
1336         char            buf[80];
1337         int             os;
1338         const char      *hex_format = "0x%x";
1339         const char      *octal_format = "0%o";
1340         const char      *decimal_format = "%d";
1341         const char      *unsignedlong_format = "%lu";
1342
1343         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1344                 return;
1345
1346         os = current_fs->super->s_creator_os;
1347
1348         if (debugfs_read_inode(inode_num, &inode, argv[1]))
1349                 return;
1350
1351         modify_u16(argv[0], "Mode", octal_format, &inode.i_mode);
1352         modify_u16(argv[0], "User ID", decimal_format, &inode.i_uid);
1353         modify_u16(argv[0], "Group ID", decimal_format, &inode.i_gid);
1354         modify_u32(argv[0], "Size", unsignedlong_format, &inode.i_size);
1355         modify_u32(argv[0], "Creation time", decimal_format, &inode.i_ctime);
1356         modify_u32(argv[0], "Modification time", decimal_format, &inode.i_mtime);
1357         modify_u32(argv[0], "Access time", decimal_format, &inode.i_atime);
1358         modify_u32(argv[0], "Deletion time", decimal_format, &inode.i_dtime);
1359         modify_u16(argv[0], "Link count", decimal_format, &inode.i_links_count);
1360         if (os == EXT2_OS_LINUX)
1361                 modify_u16(argv[0], "Block count high", unsignedlong_format,
1362                            &inode.osd2.linux2.l_i_blocks_hi);
1363         modify_u32(argv[0], "Block count", unsignedlong_format, &inode.i_blocks);
1364         modify_u32(argv[0], "File flags", hex_format, &inode.i_flags);
1365         modify_u32(argv[0], "Generation", hex_format, &inode.i_generation);
1366 #if 0
1367         modify_u32(argv[0], "Reserved1", decimal_format, &inode.i_reserved1);
1368 #endif
1369         modify_u32(argv[0], "File acl", decimal_format, &inode.i_file_acl);
1370         if (LINUX_S_ISDIR(inode.i_mode))
1371                 modify_u32(argv[0], "Directory acl", decimal_format, &inode.i_dir_acl);
1372         else
1373                 modify_u32(argv[0], "High 32bits of size", decimal_format, &inode.i_size_high);
1374
1375         if (os == EXT2_OS_HURD)
1376                 modify_u32(argv[0], "Translator Block",
1377                             decimal_format, &inode.osd1.hurd1.h_i_translator);
1378
1379         modify_u32(argv[0], "Fragment address", decimal_format, &inode.i_faddr);
1380         switch (os) {
1381             case EXT2_OS_HURD:
1382                 frag = &inode.osd2.hurd2.h_i_frag;
1383                 fsize = &inode.osd2.hurd2.h_i_fsize;
1384                 break;
1385             default:
1386                 frag = fsize = 0;
1387         }
1388         if (frag)
1389                 modify_u8(argv[0], "Fragment number", decimal_format, frag);
1390         if (fsize)
1391                 modify_u8(argv[0], "Fragment size", decimal_format, fsize);
1392
1393         for (i=0;  i < EXT2_NDIR_BLOCKS; i++) {
1394                 sprintf(buf, "Direct Block #%d", i);
1395                 modify_u32(argv[0], buf, decimal_format, &inode.i_block[i]);
1396         }
1397         modify_u32(argv[0], "Indirect Block", decimal_format,
1398                     &inode.i_block[EXT2_IND_BLOCK]);
1399         modify_u32(argv[0], "Double Indirect Block", decimal_format,
1400                     &inode.i_block[EXT2_DIND_BLOCK]);
1401         modify_u32(argv[0], "Triple Indirect Block", decimal_format,
1402                     &inode.i_block[EXT2_TIND_BLOCK]);
1403         if (debugfs_write_inode(inode_num, &inode, argv[1]))
1404                 return;
1405 }
1406 #endif /* READ_ONLY */
1407
1408 void do_change_working_dir(int argc, char *argv[])
1409 {
1410         ext2_ino_t      inode;
1411         int             retval;
1412
1413         if (common_inode_args_process(argc, argv, &inode, 0))
1414                 return;
1415
1416         retval = ext2fs_check_directory(current_fs, inode);
1417         if (retval) {
1418                 com_err(argv[1], retval, 0);
1419                 return;
1420         }
1421         cwd = inode;
1422         return;
1423 }
1424
1425 void do_print_working_directory(int argc, char *argv[])
1426 {
1427         int     retval;
1428         char    *pathname = NULL;
1429
1430         if (common_args_process(argc, argv, 1, 1,
1431                                 "print_working_directory", "", 0))
1432                 return;
1433
1434         retval = ext2fs_get_pathname(current_fs, cwd, 0, &pathname);
1435         if (retval) {
1436                 com_err(argv[0], retval,
1437                         "while trying to get pathname of cwd");
1438         }
1439         printf("[pwd]   INODE: %6u  PATH: %s\n",
1440                cwd, pathname ? pathname : "NULL");
1441         if (pathname) {
1442                 free(pathname);
1443                 pathname = NULL;
1444         }
1445         retval = ext2fs_get_pathname(current_fs, root, 0, &pathname);
1446         if (retval) {
1447                 com_err(argv[0], retval,
1448                         "while trying to get pathname of root");
1449         }
1450         printf("[root]  INODE: %6u  PATH: %s\n",
1451                root, pathname ? pathname : "NULL");
1452         if (pathname) {
1453                 free(pathname);
1454                 pathname = NULL;
1455         }
1456         return;
1457 }
1458
1459 #ifndef READ_ONLY
1460 static void make_link(char *sourcename, char *destname)
1461 {
1462         ext2_ino_t      ino;
1463         struct ext2_inode inode;
1464         int             retval;
1465         ext2_ino_t      dir;
1466         char            *dest, *cp, *base_name;
1467
1468         /*
1469          * Get the source inode
1470          */
1471         ino = string_to_inode(sourcename);
1472         if (!ino)
1473                 return;
1474         base_name = strrchr(sourcename, '/');
1475         if (base_name)
1476                 base_name++;
1477         else
1478                 base_name = sourcename;
1479         /*
1480          * Figure out the destination.  First see if it exists and is
1481          * a directory.
1482          */
1483         if (! (retval=ext2fs_namei(current_fs, root, cwd, destname, &dir)))
1484                 dest = base_name;
1485         else {
1486                 /*
1487                  * OK, it doesn't exist.  See if it is
1488                  * '<dir>/basename' or 'basename'
1489                  */
1490                 cp = strrchr(destname, '/');
1491                 if (cp) {
1492                         *cp = 0;
1493                         dir = string_to_inode(destname);
1494                         if (!dir)
1495                                 return;
1496                         dest = cp+1;
1497                 } else {
1498                         dir = cwd;
1499                         dest = destname;
1500                 }
1501         }
1502
1503         if (debugfs_read_inode(ino, &inode, sourcename))
1504                 return;
1505
1506         retval = ext2fs_link(current_fs, dir, dest, ino,
1507                              ext2_file_type(inode.i_mode));
1508         if (retval)
1509                 com_err("make_link", retval, 0);
1510         return;
1511 }
1512
1513
1514 void do_link(int argc, char *argv[])
1515 {
1516         if (common_args_process(argc, argv, 3, 3, "link",
1517                                 "<source file> <dest_name>", CHECK_FS_RW))
1518                 return;
1519
1520         make_link(argv[1], argv[2]);
1521 }
1522
1523 static int mark_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
1524                             e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1525                             blk64_t ref_block EXT2FS_ATTR((unused)),
1526                             int ref_offset EXT2FS_ATTR((unused)),
1527                             void *private EXT2FS_ATTR((unused)))
1528 {
1529         blk64_t block;
1530
1531         block = *blocknr;
1532         ext2fs_block_alloc_stats2(fs, block, +1);
1533         return 0;
1534 }
1535
1536 void do_undel(int argc, char *argv[])
1537 {
1538         ext2_ino_t      ino;
1539         struct ext2_inode inode;
1540
1541         if (common_args_process(argc, argv, 2, 3, "undelete",
1542                                 "<inode_num> [dest_name]",
1543                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1544                 return;
1545
1546         ino = string_to_inode(argv[1]);
1547         if (!ino)
1548                 return;
1549
1550         if (debugfs_read_inode(ino, &inode, argv[1]))
1551                 return;
1552
1553         if (ext2fs_test_inode_bitmap2(current_fs->inode_map, ino)) {
1554                 com_err(argv[1], 0, "Inode is not marked as deleted");
1555                 return;
1556         }
1557
1558         /*
1559          * XXX this function doesn't handle changing the links count on the
1560          * parent directory when undeleting a directory.
1561          */
1562         inode.i_links_count = LINUX_S_ISDIR(inode.i_mode) ? 2 : 1;
1563         inode.i_dtime = 0;
1564
1565         if (debugfs_write_inode(ino, &inode, argv[0]))
1566                 return;
1567
1568         ext2fs_block_iterate3(current_fs, ino, BLOCK_FLAG_READ_ONLY, NULL,
1569                               mark_blocks_proc, NULL);
1570
1571         ext2fs_inode_alloc_stats2(current_fs, ino, +1, 0);
1572
1573         if (argc > 2)
1574                 make_link(argv[1], argv[2]);
1575 }
1576
1577 static void unlink_file_by_name(char *filename)
1578 {
1579         int             retval;
1580         ext2_ino_t      dir;
1581         char            *base_name;
1582
1583         base_name = strrchr(filename, '/');
1584         if (base_name) {
1585                 *base_name++ = '\0';
1586                 dir = string_to_inode(filename);
1587                 if (!dir)
1588                         return;
1589         } else {
1590                 dir = cwd;
1591                 base_name = filename;
1592         }
1593         retval = ext2fs_unlink(current_fs, dir, base_name, 0, 0);
1594         if (retval)
1595                 com_err("unlink_file_by_name", retval, 0);
1596         return;
1597 }
1598
1599 void do_unlink(int argc, char *argv[])
1600 {
1601         if (common_args_process(argc, argv, 2, 2, "link",
1602                                 "<pathname>", CHECK_FS_RW))
1603                 return;
1604
1605         unlink_file_by_name(argv[1]);
1606 }
1607
1608 void do_copy_inode(int argc, char *argv[])
1609 {
1610         ext2_ino_t      src_ino, dest_ino;
1611         unsigned char   buf[4096];
1612
1613         if (common_args_process(argc, argv, 3, 3, "copy_inode",
1614                                 "<source file> <dest_name>", CHECK_FS_RW))
1615                 return;
1616
1617         src_ino = string_to_inode(argv[1]);
1618         if (!src_ino)
1619                 return;
1620
1621         dest_ino = string_to_inode(argv[2]);
1622         if (!dest_ino)
1623                 return;
1624
1625         if (debugfs_read_inode_full(src_ino, (struct ext2_inode *) buf,
1626                                     argv[0], sizeof(buf)))
1627                 return;
1628
1629         if (debugfs_write_inode_full(dest_ino, (struct ext2_inode *) buf,
1630                                      argv[0], sizeof(buf)))
1631                 return;
1632 }
1633
1634 #endif /* READ_ONLY */
1635
1636 void do_find_free_block(int argc, char *argv[])
1637 {
1638         blk64_t free_blk, goal, first_free = 0;
1639         int             count;
1640         errcode_t       retval;
1641         char            *tmp;
1642
1643         if ((argc > 3) || (argc==2 && *argv[1] == '?')) {
1644                 com_err(argv[0], 0, "Usage: find_free_block [count [goal]]");
1645                 return;
1646         }
1647         if (check_fs_open(argv[0]))
1648                 return;
1649
1650         if (argc > 1) {
1651                 count = strtol(argv[1],&tmp,0);
1652                 if (*tmp) {
1653                         com_err(argv[0], 0, "Bad count - %s", argv[1]);
1654                         return;
1655                 }
1656         } else
1657                 count = 1;
1658
1659         if (argc > 2) {
1660                 goal = strtol(argv[2], &tmp, 0);
1661                 if (*tmp) {
1662                         com_err(argv[0], 0, "Bad goal - %s", argv[1]);
1663                         return;
1664                 }
1665         }
1666         else
1667                 goal = current_fs->super->s_first_data_block;
1668
1669         printf("Free blocks found: ");
1670         free_blk = goal - 1;
1671         while (count-- > 0) {
1672                 retval = ext2fs_new_block2(current_fs, free_blk + 1, 0,
1673                                            &free_blk);
1674                 if (first_free) {
1675                         if (first_free == free_blk)
1676                                 break;
1677                 } else
1678                         first_free = free_blk;
1679                 if (retval) {
1680                         com_err("ext2fs_new_block", retval, 0);
1681                         return;
1682                 } else
1683                         printf("%llu ", free_blk);
1684         }
1685         printf("\n");
1686 }
1687
1688 void do_find_free_inode(int argc, char *argv[])
1689 {
1690         ext2_ino_t      free_inode, dir;
1691         int             mode;
1692         int             retval;
1693         char            *tmp;
1694
1695         if (argc > 3 || (argc>1 && *argv[1] == '?')) {
1696                 com_err(argv[0], 0, "Usage: find_free_inode [dir [mode]]");
1697                 return;
1698         }
1699         if (check_fs_open(argv[0]))
1700                 return;
1701
1702         if (argc > 1) {
1703                 dir = strtol(argv[1], &tmp, 0);
1704                 if (*tmp) {
1705                         com_err(argv[0], 0, "Bad dir - %s", argv[1]);
1706                         return;
1707                 }
1708         }
1709         else
1710                 dir = root;
1711         if (argc > 2) {
1712                 mode = strtol(argv[2], &tmp, 0);
1713                 if (*tmp) {
1714                         com_err(argv[0], 0, "Bad mode - %s", argv[2]);
1715                         return;
1716                 }
1717         } else
1718                 mode = 010755;
1719
1720         retval = ext2fs_new_inode(current_fs, dir, mode, 0, &free_inode);
1721         if (retval)
1722                 com_err("ext2fs_new_inode", retval, 0);
1723         else
1724                 printf("Free inode found: %u\n", free_inode);
1725 }
1726
1727 #ifndef READ_ONLY
1728 void do_write(int argc, char *argv[])
1729 {
1730         errcode_t       retval;
1731
1732         if (common_args_process(argc, argv, 3, 3, "write",
1733                                 "<native file> <new file>", CHECK_FS_RW))
1734                 return;
1735
1736         retval = do_write_internal(current_fs, cwd, argv[1], argv[2], root);
1737         if (retval)
1738                 com_err(argv[0], retval, 0);
1739 }
1740
1741 void do_mknod(int argc, char *argv[])
1742 {
1743         unsigned long   major, minor;
1744         errcode_t       retval;
1745         int             nr;
1746         struct stat     st;
1747
1748         if (check_fs_open(argv[0]))
1749                 return;
1750         if (argc < 3 || argv[2][1]) {
1751         usage:
1752                 com_err(argv[0], 0, "Usage: mknod <name> [p| [c|b] <major> <minor>]");
1753                 return;
1754         }
1755
1756         minor = major = 0;
1757         switch (argv[2][0]) {
1758                 case 'p':
1759                         st.st_mode = S_IFIFO;
1760                         nr = 3;
1761                         break;
1762                 case 'c':
1763                         st.st_mode = S_IFCHR;
1764                         nr = 5;
1765                         break;
1766                 case 'b':
1767                         st.st_mode = S_IFBLK;
1768                         nr = 5;
1769                         break;
1770                 default:
1771                         nr = 0;
1772         }
1773
1774         if (nr == 5) {
1775                 major = strtoul(argv[3], argv+3, 0);
1776                 minor = strtoul(argv[4], argv+4, 0);
1777                 if (major > 65535 || minor > 65535 || argv[3][0] || argv[4][0])
1778                         nr = 0;
1779         }
1780
1781         if (argc != nr)
1782                 goto usage;
1783
1784         st.st_rdev = makedev(major, minor);
1785         retval = do_mknod_internal(current_fs, cwd, argv[1], &st);
1786         if (retval)
1787                 com_err(argv[0], retval, 0);
1788 }
1789
1790 void do_mkdir(int argc, char *argv[])
1791 {
1792         errcode_t retval;
1793
1794         if (common_args_process(argc, argv, 2, 2, "mkdir",
1795                                 "<filename>", CHECK_FS_RW))
1796                 return;
1797
1798         retval = do_mkdir_internal(current_fs, cwd, argv[1], root);
1799         if (retval)
1800                 com_err(argv[0], retval, 0);
1801
1802 }
1803
1804 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
1805                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1806                                blk64_t ref_block EXT2FS_ATTR((unused)),
1807                                int ref_offset EXT2FS_ATTR((unused)),
1808                                void *private EXT2FS_ATTR((unused)))
1809 {
1810         blk64_t block;
1811
1812         block = *blocknr;
1813         ext2fs_block_alloc_stats2(fs, block, -1);
1814         return 0;
1815 }
1816
1817 static void kill_file_by_inode(ext2_ino_t inode)
1818 {
1819         struct ext2_inode inode_buf;
1820
1821         if (debugfs_read_inode(inode, &inode_buf, 0))
1822                 return;
1823         inode_buf.i_dtime = current_fs->now ? current_fs->now : time(0);
1824         if (debugfs_write_inode(inode, &inode_buf, 0))
1825                 return;
1826         if (ext2fs_inode_has_valid_blocks2(current_fs, &inode_buf)) {
1827                 ext2fs_block_iterate3(current_fs, inode, BLOCK_FLAG_READ_ONLY,
1828                                       NULL, release_blocks_proc, NULL);
1829         }
1830         printf("\n");
1831         ext2fs_inode_alloc_stats2(current_fs, inode, -1,
1832                                   LINUX_S_ISDIR(inode_buf.i_mode));
1833 }
1834
1835
1836 void do_kill_file(int argc, char *argv[])
1837 {
1838         ext2_ino_t inode_num;
1839
1840         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1841                 return;
1842
1843         kill_file_by_inode(inode_num);
1844 }
1845
1846 void do_rm(int argc, char *argv[])
1847 {
1848         int retval;
1849         ext2_ino_t inode_num;
1850         struct ext2_inode inode;
1851
1852         if (common_args_process(argc, argv, 2, 2, "rm",
1853                                 "<filename>", CHECK_FS_RW))
1854                 return;
1855
1856         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1857         if (retval) {
1858                 com_err(argv[0], retval, "while trying to resolve filename");
1859                 return;
1860         }
1861
1862         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1863                 return;
1864
1865         if (LINUX_S_ISDIR(inode.i_mode)) {
1866                 com_err(argv[0], 0, "file is a directory");
1867                 return;
1868         }
1869
1870         --inode.i_links_count;
1871         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1872                 return;
1873
1874         unlink_file_by_name(argv[1]);
1875         if (inode.i_links_count == 0)
1876                 kill_file_by_inode(inode_num);
1877 }
1878
1879 struct rd_struct {
1880         ext2_ino_t      parent;
1881         int             empty;
1882 };
1883
1884 static int rmdir_proc(ext2_ino_t dir EXT2FS_ATTR((unused)),
1885                       int       entry EXT2FS_ATTR((unused)),
1886                       struct ext2_dir_entry *dirent,
1887                       int       offset EXT2FS_ATTR((unused)),
1888                       int       blocksize EXT2FS_ATTR((unused)),
1889                       char      *buf EXT2FS_ATTR((unused)),
1890                       void      *private)
1891 {
1892         struct rd_struct *rds = (struct rd_struct *) private;
1893
1894         if (dirent->inode == 0)
1895                 return 0;
1896         if ((ext2fs_dirent_name_len(dirent) == 1) && (dirent->name[0] == '.'))
1897                 return 0;
1898         if ((ext2fs_dirent_name_len(dirent) == 2) && (dirent->name[0] == '.') &&
1899             (dirent->name[1] == '.')) {
1900                 rds->parent = dirent->inode;
1901                 return 0;
1902         }
1903         rds->empty = 0;
1904         return 0;
1905 }
1906
1907 void do_rmdir(int argc, char *argv[])
1908 {
1909         int retval;
1910         ext2_ino_t inode_num;
1911         struct ext2_inode inode;
1912         struct rd_struct rds;
1913
1914         if (common_args_process(argc, argv, 2, 2, "rmdir",
1915                                 "<filename>", CHECK_FS_RW))
1916                 return;
1917
1918         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1919         if (retval) {
1920                 com_err(argv[0], retval, "while trying to resolve filename");
1921                 return;
1922         }
1923
1924         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1925                 return;
1926
1927         if (!LINUX_S_ISDIR(inode.i_mode)) {
1928                 com_err(argv[0], 0, "file is not a directory");
1929                 return;
1930         }
1931
1932         rds.parent = 0;
1933         rds.empty = 1;
1934
1935         retval = ext2fs_dir_iterate2(current_fs, inode_num, 0,
1936                                     0, rmdir_proc, &rds);
1937         if (retval) {
1938                 com_err(argv[0], retval, "while iterating over directory");
1939                 return;
1940         }
1941         if (rds.empty == 0) {
1942                 com_err(argv[0], 0, "directory not empty");
1943                 return;
1944         }
1945
1946         inode.i_links_count = 0;
1947         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1948                 return;
1949
1950         unlink_file_by_name(argv[1]);
1951         kill_file_by_inode(inode_num);
1952
1953         if (rds.parent) {
1954                 if (debugfs_read_inode(rds.parent, &inode, argv[0]))
1955                         return;
1956                 if (inode.i_links_count > 1)
1957                         inode.i_links_count--;
1958                 if (debugfs_write_inode(rds.parent, &inode, argv[0]))
1959                         return;
1960         }
1961 }
1962 #endif /* READ_ONLY */
1963
1964 void do_show_debugfs_params(int argc EXT2FS_ATTR((unused)),
1965                             char *argv[] EXT2FS_ATTR((unused)))
1966 {
1967         if (current_fs)
1968                 printf("Open mode: read-%s\n",
1969                        current_fs->flags & EXT2_FLAG_RW ? "write" : "only");
1970         printf("Filesystem in use: %s\n",
1971                current_fs ? current_fs->device_name : "--none--");
1972 }
1973
1974 #ifndef READ_ONLY
1975 void do_expand_dir(int argc, char *argv[])
1976 {
1977         ext2_ino_t inode;
1978         int retval;
1979
1980         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1981                 return;
1982
1983         retval = ext2fs_expand_dir(current_fs, inode);
1984         if (retval)
1985                 com_err("ext2fs_expand_dir", retval, 0);
1986         return;
1987 }
1988
1989 void do_features(int argc, char *argv[])
1990 {
1991         int     i;
1992
1993         if (check_fs_open(argv[0]))
1994                 return;
1995
1996         if ((argc != 1) && check_fs_read_write(argv[0]))
1997                 return;
1998         for (i=1; i < argc; i++) {
1999                 if (e2p_edit_feature(argv[i],
2000                                      &current_fs->super->s_feature_compat, 0))
2001                         com_err(argv[0], 0, "Unknown feature: %s\n",
2002                                 argv[i]);
2003                 else
2004                         ext2fs_mark_super_dirty(current_fs);
2005         }
2006         print_features(current_fs->super, stdout);
2007 }
2008 #endif /* READ_ONLY */
2009
2010 void do_bmap(int argc, char *argv[])
2011 {
2012         ext2_ino_t      ino;
2013         blk64_t         blk, pblk = 0;
2014         int             c, err, flags = 0, ret_flags = 0;
2015         errcode_t       errcode;
2016
2017         if (check_fs_open(argv[0]))
2018                 return;
2019
2020         reset_getopt();
2021         while ((c = getopt (argc, argv, "a")) != EOF) {
2022                 switch (c) {
2023                 case 'a':
2024                         flags |= BMAP_ALLOC;
2025                         break;
2026                 default:
2027                         goto print_usage;
2028                 }
2029         }
2030
2031         if (argc <= optind+1) {
2032         print_usage:
2033                 com_err(0, 0,
2034                         "Usage: bmap [-a] <file> logical_blk [physical_blk]");
2035                 return;
2036         }
2037
2038         ino = string_to_inode(argv[optind++]);
2039         if (!ino)
2040                 return;
2041         err = strtoblk(argv[0], argv[optind++], "logical block", &blk);
2042         if (err)
2043                 return;
2044
2045         if (argc > optind+1)
2046                 goto print_usage;
2047
2048         if (argc == optind+1) {
2049                 err = strtoblk(argv[0], argv[optind++],
2050                                "physical block", &pblk);
2051                 if (err)
2052                         return;
2053                 if (flags & BMAP_ALLOC) {
2054                         com_err(0, 0, "Can't set and allocate a block");
2055                         return;
2056                 }
2057                 flags |= BMAP_SET;
2058         }
2059
2060         errcode = ext2fs_bmap2(current_fs, ino, 0, 0, flags, blk,
2061                                &ret_flags, &pblk);
2062         if (errcode) {
2063                 com_err(argv[0], errcode,
2064                         "while mapping logical block %llu\n", blk);
2065                 return;
2066         }
2067         printf("%llu", pblk);
2068         if (ret_flags & BMAP_RET_UNINIT)
2069                 fputs(" (uninit)", stdout);
2070         fputc('\n', stdout);
2071 }
2072
2073 void do_imap(int argc, char *argv[])
2074 {
2075         ext2_ino_t      ino;
2076         unsigned long   group, block, block_nr, offset;
2077
2078         if (common_args_process(argc, argv, 2, 2, argv[0],
2079                                 "<file>", 0))
2080                 return;
2081         ino = string_to_inode(argv[1]);
2082         if (!ino)
2083                 return;
2084
2085         group = (ino - 1) / EXT2_INODES_PER_GROUP(current_fs->super);
2086         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(current_fs->super)) *
2087                 EXT2_INODE_SIZE(current_fs->super);
2088         block = offset >> EXT2_BLOCK_SIZE_BITS(current_fs->super);
2089         if (!ext2fs_inode_table_loc(current_fs, (unsigned)group)) {
2090                 com_err(argv[0], 0, "Inode table for group %lu is missing\n",
2091                         group);
2092                 return;
2093         }
2094         block_nr = ext2fs_inode_table_loc(current_fs, (unsigned)group) +
2095                 block;
2096         offset &= (EXT2_BLOCK_SIZE(current_fs->super) - 1);
2097
2098         printf("Inode %d is part of block group %lu\n"
2099                "\tlocated at block %lu, offset 0x%04lx\n", ino, group,
2100                block_nr, offset);
2101
2102 }
2103
2104 void do_idump(int argc, char *argv[])
2105 {
2106         ext2_ino_t      ino;
2107         unsigned char   *buf;
2108         errcode_t       err;
2109         int             isize;
2110
2111         if (common_args_process(argc, argv, 2, 2, argv[0],
2112                                 "<file>", 0))
2113                 return;
2114         ino = string_to_inode(argv[1]);
2115         if (!ino)
2116                 return;
2117
2118         isize = EXT2_INODE_SIZE(current_fs->super);
2119         err = ext2fs_get_mem(isize, &buf);
2120         if (err) {
2121                 com_err(argv[0], err, "while allocating memory");
2122                 return;
2123         }
2124
2125         err = ext2fs_read_inode_full(current_fs, ino,
2126                                      (struct ext2_inode *)buf, isize);
2127         if (err) {
2128                 com_err(argv[0], err, "while reading inode %d", ino);
2129                 goto err;
2130         }
2131
2132         do_byte_hexdump(stdout, buf, isize);
2133 err:
2134         ext2fs_free_mem(&buf);
2135 }
2136
2137 #ifndef READ_ONLY
2138 void do_set_current_time(int argc, char *argv[])
2139 {
2140         __s64 now;
2141
2142         if (common_args_process(argc, argv, 2, 2, argv[0],
2143                                 "<time>", 0))
2144                 return;
2145
2146         now = string_to_time(argv[1]);
2147         if (now == -1) {
2148                 com_err(argv[0], 0, "Couldn't parse argument as a time: %s\n",
2149                         argv[1]);
2150                 return;
2151
2152         } else {
2153                 printf("Setting current time to %s\n", time_to_string(now));
2154                 current_fs->now = now;
2155         }
2156 }
2157 #endif /* READ_ONLY */
2158
2159 static int find_supp_feature(__u32 *supp, int feature_type, char *name)
2160 {
2161         int compat, bit, ret;
2162         unsigned int feature_mask;
2163
2164         if (name) {
2165                 if (feature_type == E2P_FS_FEATURE)
2166                         ret = e2p_string2feature(name, &compat, &feature_mask);
2167                 else
2168                         ret = e2p_jrnl_string2feature(name, &compat,
2169                                                       &feature_mask);
2170                 if (ret)
2171                         return ret;
2172
2173                 if (!(supp[compat] & feature_mask))
2174                         return 1;
2175         } else {
2176                 for (compat = 0; compat < 3; compat++) {
2177                         for (bit = 0, feature_mask = 1; bit < 32;
2178                              bit++, feature_mask <<= 1) {
2179                                 if (supp[compat] & feature_mask) {
2180                                         if (feature_type == E2P_FS_FEATURE)
2181                                                 fprintf(stdout, " %s",
2182                                                 e2p_feature2string(compat,
2183                                                 feature_mask));
2184                                         else
2185                                                 fprintf(stdout, " %s",
2186                                                 e2p_jrnl_feature2string(compat,
2187                                                 feature_mask));
2188                                 }
2189                         }
2190                 }
2191                 fprintf(stdout, "\n");
2192         }
2193
2194         return 0;
2195 }
2196
2197 void do_supported_features(int argc, char *argv[])
2198 {
2199         int     ret;
2200         __u32   supp[3] = { EXT2_LIB_FEATURE_COMPAT_SUPP,
2201                             EXT2_LIB_FEATURE_INCOMPAT_SUPP,
2202                             EXT2_LIB_FEATURE_RO_COMPAT_SUPP };
2203         __u32   jrnl_supp[3] = { JFS_KNOWN_COMPAT_FEATURES,
2204                                  JFS_KNOWN_INCOMPAT_FEATURES,
2205                                  JFS_KNOWN_ROCOMPAT_FEATURES };
2206
2207         if (argc > 1) {
2208                 ret = find_supp_feature(supp, E2P_FS_FEATURE, argv[1]);
2209                 if (ret) {
2210                         ret = find_supp_feature(jrnl_supp, E2P_JOURNAL_FEATURE,
2211                                                 argv[1]);
2212                 }
2213                 if (ret)
2214                         com_err(argv[0], 0, "Unknown feature: %s\n", argv[1]);
2215                 else
2216                         fprintf(stdout, "Supported feature: %s\n", argv[1]);
2217         } else {
2218                 fprintf(stdout, "Supported features:");
2219                 ret = find_supp_feature(supp, E2P_FS_FEATURE, NULL);
2220                 ret = find_supp_feature(jrnl_supp, E2P_JOURNAL_FEATURE, NULL);
2221         }
2222 }
2223
2224 #ifndef READ_ONLY
2225 void do_punch(int argc, char *argv[])
2226 {
2227         ext2_ino_t      ino;
2228         blk64_t         start, end;
2229         int             err;
2230         errcode_t       errcode;
2231
2232         if (common_args_process(argc, argv, 3, 4, argv[0],
2233                                 "<file> start_blk [end_blk]",
2234                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
2235                 return;
2236
2237         ino = string_to_inode(argv[1]);
2238         if (!ino)
2239                 return;
2240         err = strtoblk(argv[0], argv[2], "logical block", &start);
2241         if (err)
2242                 return;
2243         if (argc == 4) {
2244                 err = strtoblk(argv[0], argv[3], "logical block", &end);
2245                 if (err)
2246                         return;
2247         } else
2248                 end = ~0;
2249
2250         errcode = ext2fs_punch(current_fs, ino, 0, 0, start, end);
2251
2252         if (errcode) {
2253                 com_err(argv[0], errcode,
2254                         "while truncating inode %u from %llu to %llu\n", ino,
2255                         (unsigned long long) start, (unsigned long long) end);
2256                 return;
2257         }
2258 }
2259
2260 void do_fallocate(int argc, char *argv[])
2261 {
2262         ext2_ino_t      ino;
2263         blk64_t         start, end;
2264         int             err;
2265         errcode_t       errcode;
2266
2267         if (common_args_process(argc, argv, 3, 4, argv[0],
2268                                 "<file> start_blk [end_blk]",
2269                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
2270                 return;
2271
2272         ino = string_to_inode(argv[1]);
2273         if (!ino)
2274                 return;
2275         err = strtoblk(argv[0], argv[2], "logical block", &start);
2276         if (err)
2277                 return;
2278         if (argc == 4) {
2279                 err = strtoblk(argv[0], argv[3], "logical block", &end);
2280                 if (err)
2281                         return;
2282         } else
2283                 end = ~0;
2284
2285         errcode = ext2fs_fallocate(current_fs, EXT2_FALLOCATE_INIT_BEYOND_EOF,
2286                                    ino, NULL, ~0ULL, start, end - start + 1);
2287
2288         if (errcode) {
2289                 com_err(argv[0], errcode,
2290                         "while fallocating inode %u from %llu to %llu\n", ino,
2291                         (unsigned long long) start, (unsigned long long) end);
2292                 return;
2293         }
2294 }
2295 #endif /* READ_ONLY */
2296
2297 void do_symlink(int argc, char *argv[])
2298 {
2299         errcode_t       retval;
2300
2301         if (common_args_process(argc, argv, 3, 3, "symlink",
2302                                 "<filename> <target>", CHECK_FS_RW))
2303                 return;
2304
2305         retval = do_symlink_internal(current_fs, cwd, argv[1], argv[2], root);
2306         if (retval)
2307                 com_err(argv[0], retval, 0);
2308
2309 }
2310
2311 #if CONFIG_MMP
2312 void do_dump_mmp(int argc EXT2FS_ATTR((unused)), char *argv[])
2313 {
2314         struct mmp_struct *mmp_s;
2315         unsigned long long mmp_block;
2316         time_t t;
2317         errcode_t retval = 0;
2318
2319         if (check_fs_open(argv[0]))
2320                 return;
2321
2322         if (argc > 1) {
2323                 char *end = NULL;
2324                 mmp_block = strtoull(argv[1], &end, 0);
2325                 if (end == argv[0] || mmp_block == 0) {
2326                         fprintf(stderr, "%s: invalid MMP block '%s' given\n",
2327                                 argv[0], argv[1]);
2328                         return;
2329                 }
2330         } else {
2331                 mmp_block = current_fs->super->s_mmp_block;
2332         }
2333
2334         if (mmp_block == 0) {
2335                 fprintf(stderr, "%s: MMP: not active on this filesystem.\n",
2336                         argv[0]);
2337                 return;
2338         }
2339
2340         if (current_fs->mmp_buf == NULL) {
2341                 retval = ext2fs_get_mem(current_fs->blocksize,
2342                                         &current_fs->mmp_buf);
2343                 if (retval) {
2344                         com_err(argv[0], retval, "allocating MMP buffer.\n");
2345                         return;
2346                 }
2347         }
2348
2349         mmp_s = current_fs->mmp_buf;
2350
2351         retval = ext2fs_mmp_read(current_fs, mmp_block, current_fs->mmp_buf);
2352         if (retval) {
2353                 com_err(argv[0], retval, "reading MMP block %llu.\n",
2354                         mmp_block);
2355                 return;
2356         }
2357
2358         t = mmp_s->mmp_time;
2359         fprintf(stdout, "block_number: %llu\n", current_fs->super->s_mmp_block);
2360         fprintf(stdout, "update_interval: %d\n",
2361                 current_fs->super->s_mmp_update_interval);
2362         fprintf(stdout, "check_interval: %d\n", mmp_s->mmp_check_interval);
2363         fprintf(stdout, "sequence: %08x\n", mmp_s->mmp_seq);
2364         fprintf(stdout, "time: %lld -- %s", mmp_s->mmp_time, ctime(&t));
2365         fprintf(stdout, "node_name: %s\n", mmp_s->mmp_nodename);
2366         fprintf(stdout, "device_name: %s\n", mmp_s->mmp_bdevname);
2367         fprintf(stdout, "magic: 0x%x\n", mmp_s->mmp_magic);
2368         fprintf(stdout, "checksum: 0x%08x\n", mmp_s->mmp_checksum);
2369         fprintf(stdout, "MMP is unsupported, please recompile with "
2370                         "--enable-mmp\n");
2371 }
2372 #else
2373 void do_dump_mmp(int argc EXT2FS_ATTR((unused)),
2374                  char *argv[] EXT2FS_ATTR((unused)))
2375 {
2376         fprintf(stdout, "MMP is unsupported, please recompile with "
2377                         "--enable-mmp\n");
2378 }
2379 #endif
2380
2381 static int source_file(const char *cmd_file, int ss_idx)
2382 {
2383         FILE            *f;
2384         char            buf[BUFSIZ];
2385         char            *cp;
2386         int             exit_status = 0;
2387         int             retval;
2388
2389         if (strcmp(cmd_file, "-") == 0)
2390                 f = stdin;
2391         else {
2392                 f = fopen(cmd_file, "r");
2393                 if (!f) {
2394                         perror(cmd_file);
2395                         exit(1);
2396                 }
2397         }
2398         fflush(stdout);
2399         fflush(stderr);
2400         setbuf(stdout, NULL);
2401         setbuf(stderr, NULL);
2402         while (!feof(f)) {
2403                 if (fgets(buf, sizeof(buf), f) == NULL)
2404                         break;
2405                 cp = strchr(buf, '\n');
2406                 if (cp)
2407                         *cp = 0;
2408                 cp = strchr(buf, '\r');
2409                 if (cp)
2410                         *cp = 0;
2411                 printf("debugfs: %s\n", buf);
2412                 retval = ss_execute_line(ss_idx, buf);
2413                 if (retval) {
2414                         ss_perror(ss_idx, retval, buf);
2415                         exit_status++;
2416                 }
2417         }
2418         if (f != stdin)
2419                 fclose(f);
2420         return exit_status;
2421 }
2422
2423 int main(int argc, char **argv)
2424 {
2425         int             retval;
2426         const char      *usage = 
2427                 "Usage: %s [-b blocksize] [-s superblock] [-f cmd_file] "
2428                 "[-R request] [-d data_source_device] [-i] [-n] [-D] [-V] ["
2429 #ifndef READ_ONLY
2430                 "[-w] [-z undo_file] "
2431 #endif
2432                 "[-c]] [device]";
2433         int             c;
2434         int             open_flags = EXT2_FLAG_SOFTSUPP_FEATURES | EXT2_FLAG_64BITS;
2435         char            *request = 0;
2436         int             exit_status = 0;
2437         char            *cmd_file = 0;
2438         blk64_t         superblock = 0;
2439         blk64_t         blocksize = 0;
2440         int             catastrophic = 0;
2441         char            *data_filename = 0;
2442 #ifdef READ_ONLY
2443         const char      *opt_string = "nicR:f:b:s:Vd:D";
2444 #else
2445         const char      *opt_string = "niwcR:f:b:s:Vd:Dz:";
2446         char            *undo_file = NULL;
2447 #endif
2448 #ifdef CONFIG_JBD_DEBUG
2449         char            *jbd_debug;
2450 #endif
2451
2452         if (debug_prog_name == 0)
2453 #ifdef READ_ONLY
2454                 debug_prog_name = "rdebugfs";
2455 #else
2456                 debug_prog_name = "debugfs";
2457 #endif
2458         add_error_table(&et_ext2_error_table);
2459         fprintf (stderr, "%s %s (%s)\n", debug_prog_name,
2460                  E2FSPROGS_VERSION, E2FSPROGS_DATE);
2461
2462 #ifdef CONFIG_JBD_DEBUG
2463         jbd_debug = ss_safe_getenv("DEBUGFS_JBD_DEBUG");
2464         if (jbd_debug) {
2465                 int res = sscanf(jbd_debug, "%d", &journal_enable_debug);
2466
2467                 if (res != 1) {
2468                         fprintf(stderr,
2469                                 "DEBUGFS_JBD_DEBUG \"%s\" not an integer\n\n",
2470                                 jbd_debug);
2471                         exit(1);
2472                 }
2473         }
2474 #endif
2475         while ((c = getopt (argc, argv, opt_string)) != EOF) {
2476                 switch (c) {
2477                 case 'R':
2478                         request = optarg;
2479                         break;
2480                 case 'f':
2481                         cmd_file = optarg;
2482                         break;
2483                 case 'd':
2484                         data_filename = optarg;
2485                         break;
2486                 case 'i':
2487                         open_flags |= EXT2_FLAG_IMAGE_FILE;
2488                         break;
2489                 case 'n':
2490                         open_flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2491                         break;
2492 #ifndef READ_ONLY
2493                 case 'w':
2494                         open_flags |= EXT2_FLAG_RW;
2495                         break;
2496 #endif
2497                 case 'D':
2498                         open_flags |= EXT2_FLAG_DIRECT_IO;
2499                         break;
2500                 case 'b':
2501                         blocksize = parse_ulong(optarg, argv[0],
2502                                                 "block size", 0);
2503                         break;
2504                 case 's':
2505                         retval = strtoblk(argv[0], optarg,
2506                                           "superblock block number",
2507                                           &superblock);
2508                         if (retval)
2509                                 return 1;
2510                         break;
2511                 case 'c':
2512                         catastrophic = 1;
2513                         break;
2514                 case 'V':
2515                         /* Print version number and exit */
2516                         fprintf(stderr, "\tUsing %s\n",
2517                                 error_message(EXT2_ET_BASE));
2518                         exit(0);
2519                 case 'z':
2520                         undo_file = optarg;
2521                         break;
2522                 default:
2523                         com_err(argv[0], 0, usage, debug_prog_name);
2524                         return 1;
2525                 }
2526         }
2527         if (optind < argc)
2528                 open_filesystem(argv[optind], open_flags,
2529                                 superblock, blocksize, catastrophic,
2530                                 data_filename, undo_file);
2531
2532         sci_idx = ss_create_invocation(debug_prog_name, "0.0", (char *) NULL,
2533                                        &debug_cmds, &retval);
2534         if (retval) {
2535                 ss_perror(sci_idx, retval, "creating invocation");
2536                 exit(1);
2537         }
2538         ss_get_readline(sci_idx);
2539
2540         (void) ss_add_request_table (sci_idx, &ss_std_requests, 1, &retval);
2541         if (retval) {
2542                 ss_perror(sci_idx, retval, "adding standard requests");
2543                 exit (1);
2544         }
2545         if (extra_cmds)
2546                 ss_add_request_table (sci_idx, extra_cmds, 1, &retval);
2547         if (retval) {
2548                 ss_perror(sci_idx, retval, "adding extra requests");
2549                 exit (1);
2550         }
2551         if (request) {
2552                 retval = 0;
2553                 retval = ss_execute_line(sci_idx, request);
2554                 if (retval) {
2555                         ss_perror(sci_idx, retval, request);
2556                         exit_status++;
2557                 }
2558         } else if (cmd_file) {
2559                 exit_status = source_file(cmd_file, sci_idx);
2560         } else {
2561                 ss_listen(sci_idx);
2562         }
2563
2564         ss_delete_invocation(sci_idx);
2565
2566         if (current_fs)
2567                 close_filesystem();
2568
2569         remove_error_table(&et_ext2_error_table);
2570         return exit_status;
2571 }