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