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