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