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