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