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