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