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