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