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