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