Whamcloud - gitweb
libext2fs: handle inline data in read/write function
[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 static void dump_inline_data(FILE *out, const char *prefix, ext2_ino_t inode_num)
735 {
736         errcode_t retval;
737         size_t size;
738
739         retval = ext2fs_inline_data_size(current_fs, inode_num, &size);
740         if (!retval)
741                 fprintf(out, "%sSize of inline data: %d", prefix, size);
742 }
743
744 void internal_dump_inode(FILE *out, const char *prefix,
745                          ext2_ino_t inode_num, struct ext2_inode *inode,
746                          int do_dump_blocks)
747 {
748         const char *i_type;
749         char frag, fsize;
750         int os = current_fs->super->s_creator_os;
751         struct ext2_inode_large *large_inode;
752         int is_large_inode = 0;
753
754         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
755                 is_large_inode = 1;
756         large_inode = (struct ext2_inode_large *) inode;
757
758         if (LINUX_S_ISDIR(inode->i_mode)) i_type = "directory";
759         else if (LINUX_S_ISREG(inode->i_mode)) i_type = "regular";
760         else if (LINUX_S_ISLNK(inode->i_mode)) i_type = "symlink";
761         else if (LINUX_S_ISBLK(inode->i_mode)) i_type = "block special";
762         else if (LINUX_S_ISCHR(inode->i_mode)) i_type = "character special";
763         else if (LINUX_S_ISFIFO(inode->i_mode)) i_type = "FIFO";
764         else if (LINUX_S_ISSOCK(inode->i_mode)) i_type = "socket";
765         else i_type = "bad type";
766         fprintf(out, "%sInode: %u   Type: %s    ", prefix, inode_num, i_type);
767         fprintf(out, "%sMode:  %04o   Flags: 0x%x\n",
768                 prefix, inode->i_mode & 0777, inode->i_flags);
769         if (is_large_inode && large_inode->i_extra_isize >= 24) {
770                 fprintf(out, "%sGeneration: %u    Version: 0x%08x:%08x\n",
771                         prefix, inode->i_generation, large_inode->i_version_hi,
772                         inode->osd1.linux1.l_i_version);
773         } else {
774                 fprintf(out, "%sGeneration: %u    Version: 0x%08x\n", prefix,
775                         inode->i_generation, inode->osd1.linux1.l_i_version);
776         }
777         fprintf(out, "%sUser: %5d   Group: %5d   Size: ",
778                 prefix, inode_uid(*inode), inode_gid(*inode));
779         if (LINUX_S_ISREG(inode->i_mode))
780                 fprintf(out, "%llu\n", EXT2_I_SIZE(inode));
781         else
782                 fprintf(out, "%d\n", inode->i_size);
783         if (os == EXT2_OS_HURD)
784                 fprintf(out,
785                         "%sFile ACL: %d    Directory ACL: %d Translator: %d\n",
786                         prefix,
787                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0,
788                         inode->osd1.hurd1.h_i_translator);
789         else
790                 fprintf(out, "%sFile ACL: %llu    Directory ACL: %d\n",
791                         prefix,
792                         inode->i_file_acl | ((long long)
793                                 (inode->osd2.linux2.l_i_file_acl_high) << 32),
794                         LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0);
795         if (os == EXT2_OS_LINUX)
796                 fprintf(out, "%sLinks: %d   Blockcount: %llu\n",
797                         prefix, inode->i_links_count,
798                         (((unsigned long long)
799                           inode->osd2.linux2.l_i_blocks_hi << 32)) +
800                         inode->i_blocks);
801         else
802                 fprintf(out, "%sLinks: %d   Blockcount: %u\n",
803                         prefix, inode->i_links_count, inode->i_blocks);
804         switch (os) {
805             case EXT2_OS_HURD:
806                 frag = inode->osd2.hurd2.h_i_frag;
807                 fsize = inode->osd2.hurd2.h_i_fsize;
808                 break;
809             default:
810                 frag = fsize = 0;
811         }
812         fprintf(out, "%sFragment:  Address: %d    Number: %d    Size: %d\n",
813                 prefix, inode->i_faddr, frag, fsize);
814         if (is_large_inode && large_inode->i_extra_isize >= 24) {
815                 fprintf(out, "%s ctime: 0x%08x:%08x -- %s", prefix,
816                         inode->i_ctime, large_inode->i_ctime_extra,
817                         time_to_string(inode->i_ctime));
818                 fprintf(out, "%s atime: 0x%08x:%08x -- %s", prefix,
819                         inode->i_atime, large_inode->i_atime_extra,
820                         time_to_string(inode->i_atime));
821                 fprintf(out, "%s mtime: 0x%08x:%08x -- %s", prefix,
822                         inode->i_mtime, large_inode->i_mtime_extra,
823                         time_to_string(inode->i_mtime));
824                 fprintf(out, "%scrtime: 0x%08x:%08x -- %s", prefix,
825                         large_inode->i_crtime, large_inode->i_crtime_extra,
826                         time_to_string(large_inode->i_crtime));
827         } else {
828                 fprintf(out, "%sctime: 0x%08x -- %s", prefix, inode->i_ctime,
829                         time_to_string(inode->i_ctime));
830                 fprintf(out, "%satime: 0x%08x -- %s", prefix, inode->i_atime,
831                         time_to_string(inode->i_atime));
832                 fprintf(out, "%smtime: 0x%08x -- %s", prefix, inode->i_mtime,
833                         time_to_string(inode->i_mtime));
834         }
835         if (inode->i_dtime)
836           fprintf(out, "%sdtime: 0x%08x -- %s", prefix, inode->i_dtime,
837                   time_to_string(inode->i_dtime));
838         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
839                 internal_dump_inode_extra(out, prefix, inode_num,
840                                           (struct ext2_inode_large *) inode);
841         dump_inode_attributes(out, inode_num);
842         if (current_fs->super->s_creator_os == EXT2_OS_LINUX &&
843             current_fs->super->s_feature_ro_compat &
844                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) {
845                 __u32 crc = inode->i_checksum_lo;
846                 if (is_large_inode &&
847                     large_inode->i_extra_isize >=
848                                 (offsetof(struct ext2_inode_large,
849                                           i_checksum_hi) -
850                                  EXT2_GOOD_OLD_INODE_SIZE))
851                         crc |= ((__u32)large_inode->i_checksum_hi) << 16;
852                 fprintf(out, "Inode checksum: 0x%08x\n", crc);
853         }
854
855         if (LINUX_S_ISLNK(inode->i_mode) && ext2fs_inode_data_blocks(current_fs,inode) == 0)
856                 fprintf(out, "%sFast_link_dest: %.*s\n", prefix,
857                         (int) inode->i_size, (char *)inode->i_block);
858         else if (LINUX_S_ISBLK(inode->i_mode) || LINUX_S_ISCHR(inode->i_mode)) {
859                 int major, minor;
860                 const char *devnote;
861
862                 if (inode->i_block[0]) {
863                         major = (inode->i_block[0] >> 8) & 255;
864                         minor = inode->i_block[0] & 255;
865                         devnote = "";
866                 } else {
867                         major = (inode->i_block[1] & 0xfff00) >> 8;
868                         minor = ((inode->i_block[1] & 0xff) |
869                                  ((inode->i_block[1] >> 12) & 0xfff00));
870                         devnote = "(New-style) ";
871                 }
872                 fprintf(out, "%sDevice major/minor number: %02d:%02d (hex %02x:%02x)\n",
873                         devnote, major, minor, major, minor);
874         } else if (do_dump_blocks) {
875                 if (inode->i_flags & EXT4_EXTENTS_FL)
876                         dump_extents(out, prefix, inode_num,
877                                      DUMP_LEAF_EXTENTS|DUMP_NODE_EXTENTS, 0, 0);
878                 else if (inode->i_flags & EXT4_INLINE_DATA_FL)
879                         dump_inline_data(out, prefix, inode_num);
880                 else
881                         dump_blocks(out, prefix, inode_num);
882         }
883 }
884
885 static void dump_inode(ext2_ino_t inode_num, struct ext2_inode *inode)
886 {
887         FILE    *out;
888
889         out = open_pager();
890         internal_dump_inode(out, "", inode_num, inode, 1);
891         close_pager(out);
892 }
893
894 void do_stat(int argc, char *argv[])
895 {
896         ext2_ino_t      inode;
897         struct ext2_inode * inode_buf;
898
899         if (check_fs_open(argv[0]))
900                 return;
901
902         inode_buf = (struct ext2_inode *)
903                         malloc(EXT2_INODE_SIZE(current_fs->super));
904         if (!inode_buf) {
905                 fprintf(stderr, "do_stat: can't allocate buffer\n");
906                 return;
907         }
908
909         if (common_inode_args_process(argc, argv, &inode, 0)) {
910                 free(inode_buf);
911                 return;
912         }
913
914         if (debugfs_read_inode_full(inode, inode_buf, argv[0],
915                                         EXT2_INODE_SIZE(current_fs->super))) {
916                 free(inode_buf);
917                 return;
918         }
919
920         dump_inode(inode, inode_buf);
921         free(inode_buf);
922         return;
923 }
924
925 void do_dump_extents(int argc, char **argv)
926 {
927         struct ext2_inode inode;
928         ext2_ino_t      ino;
929         FILE            *out;
930         int             c, flags = 0;
931         int             logical_width;
932         int             physical_width;
933
934         reset_getopt();
935         while ((c = getopt(argc, argv, "nl")) != EOF) {
936                 switch (c) {
937                 case 'n':
938                         flags |= DUMP_NODE_EXTENTS;
939                         break;
940                 case 'l':
941                         flags |= DUMP_LEAF_EXTENTS;
942                         break;
943                 }
944         }
945
946         if (argc != optind + 1) {
947                 com_err(0, 0, "Usage: dump_extents [-n] [-l] file");
948                 return;
949         }
950
951         if (flags == 0)
952                 flags = DUMP_NODE_EXTENTS | DUMP_LEAF_EXTENTS;
953         flags |= DUMP_EXTENT_TABLE;
954
955         if (check_fs_open(argv[0]))
956                 return;
957
958         ino = string_to_inode(argv[optind]);
959         if (ino == 0)
960                 return;
961
962         if (debugfs_read_inode(ino, &inode, argv[0]))
963                 return;
964
965         if ((inode.i_flags & EXT4_EXTENTS_FL) == 0) {
966                 fprintf(stderr, "%s: does not uses extent block maps\n",
967                         argv[optind]);
968                 return;
969         }
970
971         logical_width = int_log10((EXT2_I_SIZE(&inode)+current_fs->blocksize-1)/
972                                   current_fs->blocksize) + 1;
973         if (logical_width < 5)
974                 logical_width = 5;
975         physical_width = int_log10(ext2fs_blocks_count(current_fs->super)) + 1;
976         if (physical_width < 5)
977                 physical_width = 5;
978
979         out = open_pager();
980         dump_extents(out, "", ino, flags, logical_width, physical_width);
981         close_pager(out);
982         return;
983 }
984
985 static int print_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)),
986                              blk64_t *blocknr,
987                              e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
988                              blk64_t ref_block EXT2FS_ATTR((unused)),
989                              int ref_offset EXT2FS_ATTR((unused)),
990                              void *private EXT2FS_ATTR((unused)))
991 {
992         printf("%llu ", *blocknr);
993         return 0;
994 }
995
996 void do_blocks(int argc, char *argv[])
997 {
998         ext2_ino_t      inode;
999
1000         if (check_fs_open(argv[0]))
1001                 return;
1002
1003         if (common_inode_args_process(argc, argv, &inode, 0)) {
1004                 return;
1005         }
1006
1007         ext2fs_block_iterate3(current_fs, inode, BLOCK_FLAG_READ_ONLY, NULL,
1008                               print_blocks_proc, NULL);
1009         fputc('\n', stdout);
1010         return;
1011 }
1012
1013 void do_chroot(int argc, char *argv[])
1014 {
1015         ext2_ino_t inode;
1016         int retval;
1017
1018         if (common_inode_args_process(argc, argv, &inode, 0))
1019                 return;
1020
1021         retval = ext2fs_check_directory(current_fs, inode);
1022         if (retval)  {
1023                 com_err(argv[1], retval, 0);
1024                 return;
1025         }
1026         root = inode;
1027 }
1028
1029 #ifndef READ_ONLY
1030 void do_clri(int argc, char *argv[])
1031 {
1032         ext2_ino_t inode;
1033         struct ext2_inode inode_buf;
1034
1035         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1036                 return;
1037
1038         if (debugfs_read_inode(inode, &inode_buf, argv[0]))
1039                 return;
1040         memset(&inode_buf, 0, sizeof(inode_buf));
1041         if (debugfs_write_inode(inode, &inode_buf, argv[0]))
1042                 return;
1043 }
1044
1045 void do_freei(int argc, char *argv[])
1046 {
1047         unsigned int    len = 1;
1048         int             err = 0;
1049         ext2_ino_t      inode;
1050
1051         if (common_args_process(argc, argv, 2, 3, argv[0], "<file> [num]",
1052                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1053                 return;
1054         if (check_fs_read_write(argv[0]))
1055                 return;
1056
1057         inode = string_to_inode(argv[1]);
1058         if (!inode)
1059                 return;
1060
1061         if (argc == 3) {
1062                 len = parse_ulong(argv[2], argv[0], "length", &err);
1063                 if (err)
1064                         return;
1065         }
1066
1067         if (len == 1 &&
1068             !ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1069                 com_err(argv[0], 0, "Warning: inode already clear");
1070         while (len-- > 0)
1071                 ext2fs_unmark_inode_bitmap2(current_fs->inode_map, inode++);
1072         ext2fs_mark_ib_dirty(current_fs);
1073 }
1074
1075 void do_seti(int argc, char *argv[])
1076 {
1077         unsigned int    len = 1;
1078         int             err = 0;
1079         ext2_ino_t      inode;
1080
1081         if (common_args_process(argc, argv, 2, 3, argv[0], "<file> [num]",
1082                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1083                 return;
1084         if (check_fs_read_write(argv[0]))
1085                 return;
1086
1087         inode = string_to_inode(argv[1]);
1088         if (!inode)
1089                 return;
1090
1091         if (argc == 3) {
1092                 len = parse_ulong(argv[2], argv[0], "length", &err);
1093                 if (err)
1094                         return;
1095         }
1096
1097         if ((len == 1) &&
1098             ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1099                 com_err(argv[0], 0, "Warning: inode already set");
1100         while (len-- > 0)
1101                 ext2fs_mark_inode_bitmap2(current_fs->inode_map, inode++);
1102         ext2fs_mark_ib_dirty(current_fs);
1103 }
1104 #endif /* READ_ONLY */
1105
1106 void do_testi(int argc, char *argv[])
1107 {
1108         ext2_ino_t inode;
1109
1110         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_BITMAPS))
1111                 return;
1112
1113         if (ext2fs_test_inode_bitmap2(current_fs->inode_map,inode))
1114                 printf("Inode %u is marked in use\n", inode);
1115         else
1116                 printf("Inode %u is not in use\n", inode);
1117 }
1118
1119 #ifndef READ_ONLY
1120 void do_freeb(int argc, char *argv[])
1121 {
1122         blk64_t block;
1123         blk64_t count = 1;
1124
1125         if (common_block_args_process(argc, argv, &block, &count))
1126                 return;
1127         if (check_fs_read_write(argv[0]))
1128                 return;
1129         while (count-- > 0) {
1130                 if (!ext2fs_test_block_bitmap2(current_fs->block_map,block))
1131                         com_err(argv[0], 0, "Warning: block %llu already clear",
1132                                 block);
1133                 ext2fs_unmark_block_bitmap2(current_fs->block_map,block);
1134                 block++;
1135         }
1136         ext2fs_mark_bb_dirty(current_fs);
1137 }
1138
1139 void do_setb(int argc, char *argv[])
1140 {
1141         blk64_t block;
1142         blk64_t count = 1;
1143
1144         if (common_block_args_process(argc, argv, &block, &count))
1145                 return;
1146         if (check_fs_read_write(argv[0]))
1147                 return;
1148         while (count-- > 0) {
1149                 if (ext2fs_test_block_bitmap2(current_fs->block_map,block))
1150                         com_err(argv[0], 0, "Warning: block %llu already set",
1151                                 block);
1152                 ext2fs_mark_block_bitmap2(current_fs->block_map,block);
1153                 block++;
1154         }
1155         ext2fs_mark_bb_dirty(current_fs);
1156 }
1157 #endif /* READ_ONLY */
1158
1159 void do_testb(int argc, char *argv[])
1160 {
1161         blk64_t block;
1162         blk64_t count = 1;
1163
1164         if (common_block_args_process(argc, argv, &block, &count))
1165                 return;
1166         while (count-- > 0) {
1167                 if (ext2fs_test_block_bitmap2(current_fs->block_map,block))
1168                         printf("Block %llu marked in use\n", block);
1169                 else
1170                         printf("Block %llu not in use\n", block);
1171                 block++;
1172         }
1173 }
1174
1175 #ifndef READ_ONLY
1176 static void modify_u8(char *com, const char *prompt,
1177                       const char *format, __u8 *val)
1178 {
1179         char buf[200];
1180         unsigned long v;
1181         char *tmp;
1182
1183         sprintf(buf, format, *val);
1184         printf("%30s    [%s] ", prompt, buf);
1185         if (!fgets(buf, sizeof(buf), stdin))
1186                 return;
1187         if (buf[strlen (buf) - 1] == '\n')
1188                 buf[strlen (buf) - 1] = '\0';
1189         if (!buf[0])
1190                 return;
1191         v = strtoul(buf, &tmp, 0);
1192         if (*tmp)
1193                 com_err(com, 0, "Bad value - %s", buf);
1194         else
1195                 *val = v;
1196 }
1197
1198 static void modify_u16(char *com, const char *prompt,
1199                        const char *format, __u16 *val)
1200 {
1201         char buf[200];
1202         unsigned long v;
1203         char *tmp;
1204
1205         sprintf(buf, format, *val);
1206         printf("%30s    [%s] ", prompt, buf);
1207         if (!fgets(buf, sizeof(buf), stdin))
1208                 return;
1209         if (buf[strlen (buf) - 1] == '\n')
1210                 buf[strlen (buf) - 1] = '\0';
1211         if (!buf[0])
1212                 return;
1213         v = strtoul(buf, &tmp, 0);
1214         if (*tmp)
1215                 com_err(com, 0, "Bad value - %s", buf);
1216         else
1217                 *val = v;
1218 }
1219
1220 static void modify_u32(char *com, const char *prompt,
1221                        const char *format, __u32 *val)
1222 {
1223         char buf[200];
1224         unsigned long v;
1225         char *tmp;
1226
1227         sprintf(buf, format, *val);
1228         printf("%30s    [%s] ", prompt, buf);
1229         if (!fgets(buf, sizeof(buf), stdin))
1230                 return;
1231         if (buf[strlen (buf) - 1] == '\n')
1232                 buf[strlen (buf) - 1] = '\0';
1233         if (!buf[0])
1234                 return;
1235         v = strtoul(buf, &tmp, 0);
1236         if (*tmp)
1237                 com_err(com, 0, "Bad value - %s", buf);
1238         else
1239                 *val = v;
1240 }
1241
1242
1243 void do_modify_inode(int argc, char *argv[])
1244 {
1245         struct ext2_inode inode;
1246         ext2_ino_t      inode_num;
1247         int             i;
1248         unsigned char   *frag, *fsize;
1249         char            buf[80];
1250         int             os;
1251         const char      *hex_format = "0x%x";
1252         const char      *octal_format = "0%o";
1253         const char      *decimal_format = "%d";
1254         const char      *unsignedlong_format = "%lu";
1255
1256         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1257                 return;
1258
1259         os = current_fs->super->s_creator_os;
1260
1261         if (debugfs_read_inode(inode_num, &inode, argv[1]))
1262                 return;
1263
1264         modify_u16(argv[0], "Mode", octal_format, &inode.i_mode);
1265         modify_u16(argv[0], "User ID", decimal_format, &inode.i_uid);
1266         modify_u16(argv[0], "Group ID", decimal_format, &inode.i_gid);
1267         modify_u32(argv[0], "Size", unsignedlong_format, &inode.i_size);
1268         modify_u32(argv[0], "Creation time", decimal_format, &inode.i_ctime);
1269         modify_u32(argv[0], "Modification time", decimal_format, &inode.i_mtime);
1270         modify_u32(argv[0], "Access time", decimal_format, &inode.i_atime);
1271         modify_u32(argv[0], "Deletion time", decimal_format, &inode.i_dtime);
1272         modify_u16(argv[0], "Link count", decimal_format, &inode.i_links_count);
1273         if (os == EXT2_OS_LINUX)
1274                 modify_u16(argv[0], "Block count high", unsignedlong_format,
1275                            &inode.osd2.linux2.l_i_blocks_hi);
1276         modify_u32(argv[0], "Block count", unsignedlong_format, &inode.i_blocks);
1277         modify_u32(argv[0], "File flags", hex_format, &inode.i_flags);
1278         modify_u32(argv[0], "Generation", hex_format, &inode.i_generation);
1279 #if 0
1280         modify_u32(argv[0], "Reserved1", decimal_format, &inode.i_reserved1);
1281 #endif
1282         modify_u32(argv[0], "File acl", decimal_format, &inode.i_file_acl);
1283         if (LINUX_S_ISDIR(inode.i_mode))
1284                 modify_u32(argv[0], "Directory acl", decimal_format, &inode.i_dir_acl);
1285         else
1286                 modify_u32(argv[0], "High 32bits of size", decimal_format, &inode.i_size_high);
1287
1288         if (os == EXT2_OS_HURD)
1289                 modify_u32(argv[0], "Translator Block",
1290                             decimal_format, &inode.osd1.hurd1.h_i_translator);
1291
1292         modify_u32(argv[0], "Fragment address", decimal_format, &inode.i_faddr);
1293         switch (os) {
1294             case EXT2_OS_HURD:
1295                 frag = &inode.osd2.hurd2.h_i_frag;
1296                 fsize = &inode.osd2.hurd2.h_i_fsize;
1297                 break;
1298             default:
1299                 frag = fsize = 0;
1300         }
1301         if (frag)
1302                 modify_u8(argv[0], "Fragment number", decimal_format, frag);
1303         if (fsize)
1304                 modify_u8(argv[0], "Fragment size", decimal_format, fsize);
1305
1306         for (i=0;  i < EXT2_NDIR_BLOCKS; i++) {
1307                 sprintf(buf, "Direct Block #%d", i);
1308                 modify_u32(argv[0], buf, decimal_format, &inode.i_block[i]);
1309         }
1310         modify_u32(argv[0], "Indirect Block", decimal_format,
1311                     &inode.i_block[EXT2_IND_BLOCK]);
1312         modify_u32(argv[0], "Double Indirect Block", decimal_format,
1313                     &inode.i_block[EXT2_DIND_BLOCK]);
1314         modify_u32(argv[0], "Triple Indirect Block", decimal_format,
1315                     &inode.i_block[EXT2_TIND_BLOCK]);
1316         if (debugfs_write_inode(inode_num, &inode, argv[1]))
1317                 return;
1318 }
1319 #endif /* READ_ONLY */
1320
1321 void do_change_working_dir(int argc, char *argv[])
1322 {
1323         ext2_ino_t      inode;
1324         int             retval;
1325
1326         if (common_inode_args_process(argc, argv, &inode, 0))
1327                 return;
1328
1329         retval = ext2fs_check_directory(current_fs, inode);
1330         if (retval) {
1331                 com_err(argv[1], retval, 0);
1332                 return;
1333         }
1334         cwd = inode;
1335         return;
1336 }
1337
1338 void do_print_working_directory(int argc, char *argv[])
1339 {
1340         int     retval;
1341         char    *pathname = NULL;
1342
1343         if (common_args_process(argc, argv, 1, 1,
1344                                 "print_working_directory", "", 0))
1345                 return;
1346
1347         retval = ext2fs_get_pathname(current_fs, cwd, 0, &pathname);
1348         if (retval) {
1349                 com_err(argv[0], retval,
1350                         "while trying to get pathname of cwd");
1351         }
1352         printf("[pwd]   INODE: %6u  PATH: %s\n",
1353                cwd, pathname ? pathname : "NULL");
1354         if (pathname) {
1355                 free(pathname);
1356                 pathname = NULL;
1357         }
1358         retval = ext2fs_get_pathname(current_fs, root, 0, &pathname);
1359         if (retval) {
1360                 com_err(argv[0], retval,
1361                         "while trying to get pathname of root");
1362         }
1363         printf("[root]  INODE: %6u  PATH: %s\n",
1364                root, pathname ? pathname : "NULL");
1365         if (pathname) {
1366                 free(pathname);
1367                 pathname = NULL;
1368         }
1369         return;
1370 }
1371
1372 #ifndef READ_ONLY
1373 static void make_link(char *sourcename, char *destname)
1374 {
1375         ext2_ino_t      ino;
1376         struct ext2_inode inode;
1377         int             retval;
1378         ext2_ino_t      dir;
1379         char            *dest, *cp, *base_name;
1380
1381         /*
1382          * Get the source inode
1383          */
1384         ino = string_to_inode(sourcename);
1385         if (!ino)
1386                 return;
1387         base_name = strrchr(sourcename, '/');
1388         if (base_name)
1389                 base_name++;
1390         else
1391                 base_name = sourcename;
1392         /*
1393          * Figure out the destination.  First see if it exists and is
1394          * a directory.
1395          */
1396         if (! (retval=ext2fs_namei(current_fs, root, cwd, destname, &dir)))
1397                 dest = base_name;
1398         else {
1399                 /*
1400                  * OK, it doesn't exist.  See if it is
1401                  * '<dir>/basename' or 'basename'
1402                  */
1403                 cp = strrchr(destname, '/');
1404                 if (cp) {
1405                         *cp = 0;
1406                         dir = string_to_inode(destname);
1407                         if (!dir)
1408                                 return;
1409                         dest = cp+1;
1410                 } else {
1411                         dir = cwd;
1412                         dest = destname;
1413                 }
1414         }
1415
1416         if (debugfs_read_inode(ino, &inode, sourcename))
1417                 return;
1418
1419         retval = ext2fs_link(current_fs, dir, dest, ino,
1420                              ext2_file_type(inode.i_mode));
1421         if (retval)
1422                 com_err("make_link", retval, 0);
1423         return;
1424 }
1425
1426
1427 void do_link(int argc, char *argv[])
1428 {
1429         if (common_args_process(argc, argv, 3, 3, "link",
1430                                 "<source file> <dest_name>", CHECK_FS_RW))
1431                 return;
1432
1433         make_link(argv[1], argv[2]);
1434 }
1435
1436 static int mark_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
1437                             e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1438                             blk64_t ref_block EXT2FS_ATTR((unused)),
1439                             int ref_offset EXT2FS_ATTR((unused)),
1440                             void *private EXT2FS_ATTR((unused)))
1441 {
1442         blk64_t block;
1443
1444         block = *blocknr;
1445         ext2fs_block_alloc_stats2(fs, block, +1);
1446         return 0;
1447 }
1448
1449 void do_undel(int argc, char *argv[])
1450 {
1451         ext2_ino_t      ino;
1452         struct ext2_inode inode;
1453
1454         if (common_args_process(argc, argv, 2, 3, "undelete",
1455                                 "<inode_num> [dest_name]",
1456                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1457                 return;
1458
1459         ino = string_to_inode(argv[1]);
1460         if (!ino)
1461                 return;
1462
1463         if (debugfs_read_inode(ino, &inode, argv[1]))
1464                 return;
1465
1466         if (ext2fs_test_inode_bitmap2(current_fs->inode_map, ino)) {
1467                 com_err(argv[1], 0, "Inode is not marked as deleted");
1468                 return;
1469         }
1470
1471         /*
1472          * XXX this function doesn't handle changing the links count on the
1473          * parent directory when undeleting a directory.
1474          */
1475         inode.i_links_count = LINUX_S_ISDIR(inode.i_mode) ? 2 : 1;
1476         inode.i_dtime = 0;
1477
1478         if (debugfs_write_inode(ino, &inode, argv[0]))
1479                 return;
1480
1481         ext2fs_block_iterate3(current_fs, ino, BLOCK_FLAG_READ_ONLY, NULL,
1482                               mark_blocks_proc, NULL);
1483
1484         ext2fs_inode_alloc_stats2(current_fs, ino, +1, 0);
1485
1486         if (argc > 2)
1487                 make_link(argv[1], argv[2]);
1488 }
1489
1490 static void unlink_file_by_name(char *filename)
1491 {
1492         int             retval;
1493         ext2_ino_t      dir;
1494         char            *base_name;
1495
1496         base_name = strrchr(filename, '/');
1497         if (base_name) {
1498                 *base_name++ = '\0';
1499                 dir = string_to_inode(filename);
1500                 if (!dir)
1501                         return;
1502         } else {
1503                 dir = cwd;
1504                 base_name = filename;
1505         }
1506         retval = ext2fs_unlink(current_fs, dir, base_name, 0, 0);
1507         if (retval)
1508                 com_err("unlink_file_by_name", retval, 0);
1509         return;
1510 }
1511
1512 void do_unlink(int argc, char *argv[])
1513 {
1514         if (common_args_process(argc, argv, 2, 2, "link",
1515                                 "<pathname>", CHECK_FS_RW))
1516                 return;
1517
1518         unlink_file_by_name(argv[1]);
1519 }
1520 #endif /* READ_ONLY */
1521
1522 void do_find_free_block(int argc, char *argv[])
1523 {
1524         blk64_t free_blk, goal, first_free = 0;
1525         int             count;
1526         errcode_t       retval;
1527         char            *tmp;
1528
1529         if ((argc > 3) || (argc==2 && *argv[1] == '?')) {
1530                 com_err(argv[0], 0, "Usage: find_free_block [count [goal]]");
1531                 return;
1532         }
1533         if (check_fs_open(argv[0]))
1534                 return;
1535
1536         if (argc > 1) {
1537                 count = strtol(argv[1],&tmp,0);
1538                 if (*tmp) {
1539                         com_err(argv[0], 0, "Bad count - %s", argv[1]);
1540                         return;
1541                 }
1542         } else
1543                 count = 1;
1544
1545         if (argc > 2) {
1546                 goal = strtol(argv[2], &tmp, 0);
1547                 if (*tmp) {
1548                         com_err(argv[0], 0, "Bad goal - %s", argv[1]);
1549                         return;
1550                 }
1551         }
1552         else
1553                 goal = current_fs->super->s_first_data_block;
1554
1555         printf("Free blocks found: ");
1556         free_blk = goal - 1;
1557         while (count-- > 0) {
1558                 retval = ext2fs_new_block2(current_fs, free_blk + 1, 0,
1559                                            &free_blk);
1560                 if (first_free) {
1561                         if (first_free == free_blk)
1562                                 break;
1563                 } else
1564                         first_free = free_blk;
1565                 if (retval) {
1566                         com_err("ext2fs_new_block", retval, 0);
1567                         return;
1568                 } else
1569                         printf("%llu ", free_blk);
1570         }
1571         printf("\n");
1572 }
1573
1574 void do_find_free_inode(int argc, char *argv[])
1575 {
1576         ext2_ino_t      free_inode, dir;
1577         int             mode;
1578         int             retval;
1579         char            *tmp;
1580
1581         if (argc > 3 || (argc>1 && *argv[1] == '?')) {
1582                 com_err(argv[0], 0, "Usage: find_free_inode [dir] [mode]");
1583                 return;
1584         }
1585         if (check_fs_open(argv[0]))
1586                 return;
1587
1588         if (argc > 1) {
1589                 dir = strtol(argv[1], &tmp, 0);
1590                 if (*tmp) {
1591                         com_err(argv[0], 0, "Bad dir - %s", argv[1]);
1592                         return;
1593                 }
1594         }
1595         else
1596                 dir = root;
1597         if (argc > 2) {
1598                 mode = strtol(argv[2], &tmp, 0);
1599                 if (*tmp) {
1600                         com_err(argv[0], 0, "Bad mode - %s", argv[2]);
1601                         return;
1602                 }
1603         } else
1604                 mode = 010755;
1605
1606         retval = ext2fs_new_inode(current_fs, dir, mode, 0, &free_inode);
1607         if (retval)
1608                 com_err("ext2fs_new_inode", retval, 0);
1609         else
1610                 printf("Free inode found: %u\n", free_inode);
1611 }
1612
1613 #ifndef READ_ONLY
1614 static errcode_t copy_file(int fd, ext2_ino_t newfile, int bufsize, int make_holes)
1615 {
1616         ext2_file_t     e2_file;
1617         errcode_t       retval;
1618         int             got;
1619         unsigned int    written;
1620         char            *buf;
1621         char            *ptr;
1622         char            *zero_buf;
1623         int             cmp;
1624
1625         retval = ext2fs_file_open(current_fs, newfile,
1626                                   EXT2_FILE_WRITE, &e2_file);
1627         if (retval)
1628                 return retval;
1629
1630         retval = ext2fs_get_mem(bufsize, &buf);
1631         if (retval) {
1632                 com_err("copy_file", retval, "can't allocate buffer\n");
1633                 return retval;
1634         }
1635
1636         /* This is used for checking whether the whole block is zero */
1637         retval = ext2fs_get_memzero(bufsize, &zero_buf);
1638         if (retval) {
1639                 com_err("copy_file", retval, "can't allocate buffer\n");
1640                 ext2fs_free_mem(&buf);
1641                 return retval;
1642         }
1643
1644         while (1) {
1645                 got = read(fd, buf, bufsize);
1646                 if (got == 0)
1647                         break;
1648                 if (got < 0) {
1649                         retval = errno;
1650                         goto fail;
1651                 }
1652                 ptr = buf;
1653
1654                 /* Sparse copy */
1655                 if (make_holes) {
1656                         /* Check whether all is zero */
1657                         cmp = memcmp(ptr, zero_buf, got);
1658                         if (cmp == 0) {
1659                                  /* The whole block is zero, make a hole */
1660                                 retval = ext2fs_file_lseek(e2_file, got, EXT2_SEEK_CUR, NULL);
1661                                 if (retval)
1662                                         goto fail;
1663                                 got = 0;
1664                         }
1665                 }
1666
1667                 /* Normal copy */
1668                 while (got > 0) {
1669                         retval = ext2fs_file_write(e2_file, ptr,
1670                                                    got, &written);
1671                         if (retval)
1672                                 goto fail;
1673
1674                         got -= written;
1675                         ptr += written;
1676                 }
1677         }
1678         ext2fs_free_mem(&buf);
1679         ext2fs_free_mem(&zero_buf);
1680         retval = ext2fs_file_close(e2_file);
1681         return retval;
1682
1683 fail:
1684         ext2fs_free_mem(&buf);
1685         ext2fs_free_mem(&zero_buf);
1686         (void) ext2fs_file_close(e2_file);
1687         return retval;
1688 }
1689
1690 void do_write(int argc, char *argv[])
1691 {
1692         int             fd;
1693         struct stat     statbuf;
1694         ext2_ino_t      newfile;
1695         errcode_t       retval;
1696         struct ext2_inode inode;
1697         int             bufsize = IO_BUFSIZE;
1698         int             make_holes = 0;
1699
1700         if (common_args_process(argc, argv, 3, 3, "write",
1701                                 "<native file> <new file>", CHECK_FS_RW))
1702                 return;
1703
1704         fd = open(argv[1], O_RDONLY);
1705         if (fd < 0) {
1706                 com_err(argv[1], errno, 0);
1707                 return;
1708         }
1709         if (fstat(fd, &statbuf) < 0) {
1710                 com_err(argv[1], errno, 0);
1711                 close(fd);
1712                 return;
1713         }
1714
1715         retval = ext2fs_namei(current_fs, root, cwd, argv[2], &newfile);
1716         if (retval == 0) {
1717                 com_err(argv[0], 0, "The file '%s' already exists\n", argv[2]);
1718                 close(fd);
1719                 return;
1720         }
1721
1722         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1723         if (retval) {
1724                 com_err(argv[0], retval, 0);
1725                 close(fd);
1726                 return;
1727         }
1728         printf("Allocated inode: %u\n", newfile);
1729         retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1730                              EXT2_FT_REG_FILE);
1731         if (retval == EXT2_ET_DIR_NO_SPACE) {
1732                 retval = ext2fs_expand_dir(current_fs, cwd);
1733                 if (retval) {
1734                         com_err(argv[0], retval, "while expanding directory");
1735                         close(fd);
1736                         return;
1737                 }
1738                 retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1739                                      EXT2_FT_REG_FILE);
1740         }
1741         if (retval) {
1742                 com_err(argv[2], retval, 0);
1743                 close(fd);
1744                 return;
1745         }
1746         if (ext2fs_test_inode_bitmap2(current_fs->inode_map,newfile))
1747                 com_err(argv[0], 0, "Warning: inode already set");
1748         ext2fs_inode_alloc_stats2(current_fs, newfile, +1, 0);
1749         memset(&inode, 0, sizeof(inode));
1750         inode.i_mode = (statbuf.st_mode & ~LINUX_S_IFMT) | LINUX_S_IFREG;
1751         inode.i_atime = inode.i_ctime = inode.i_mtime =
1752                 current_fs->now ? current_fs->now : time(0);
1753         inode.i_links_count = 1;
1754         inode.i_size = statbuf.st_size;
1755         if (EXT2_HAS_INCOMPAT_FEATURE(current_fs->super,
1756                                       EXT4_FEATURE_INCOMPAT_INLINE_DATA)) {
1757                 inode.i_flags |= EXT4_INLINE_DATA_FL;
1758         } else if (current_fs->super->s_feature_incompat &
1759                    EXT3_FEATURE_INCOMPAT_EXTENTS) {
1760                 int i;
1761                 struct ext3_extent_header *eh;
1762
1763                 eh = (struct ext3_extent_header *) &inode.i_block[0];
1764                 eh->eh_depth = 0;
1765                 eh->eh_entries = 0;
1766                 eh->eh_magic = ext2fs_cpu_to_le16(EXT3_EXT_MAGIC);
1767                 i = (sizeof(inode.i_block) - sizeof(*eh)) /
1768                         sizeof(struct ext3_extent);
1769                 eh->eh_max = ext2fs_cpu_to_le16(i);
1770                 inode.i_flags |= EXT4_EXTENTS_FL;
1771         }
1772         if (debugfs_write_new_inode(newfile, &inode, argv[0])) {
1773                 close(fd);
1774                 return;
1775         }
1776         if (inode.i_flags & EXT4_INLINE_DATA_FL) {
1777                 retval = ext2fs_inline_data_init(current_fs, newfile);
1778                 if (retval)
1779                         return;
1780         }
1781         if (LINUX_S_ISREG(inode.i_mode)) {
1782                 if (statbuf.st_blocks < statbuf.st_size / S_BLKSIZE) {
1783                         make_holes = 1;
1784                         /*
1785                          * Use I/O blocksize as buffer size when
1786                          * copying sparse files.
1787                          */
1788                         bufsize = statbuf.st_blksize;
1789                 }
1790                 retval = copy_file(fd, newfile, bufsize, make_holes);
1791                 if (retval)
1792                         com_err("copy_file", retval, 0);
1793         }
1794         close(fd);
1795 }
1796
1797 void do_mknod(int argc, char *argv[])
1798 {
1799         unsigned long   mode, major, minor;
1800         ext2_ino_t      newfile;
1801         errcode_t       retval;
1802         struct ext2_inode inode;
1803         int             filetype, nr;
1804
1805         if (check_fs_open(argv[0]))
1806                 return;
1807         if (argc < 3 || argv[2][1]) {
1808         usage:
1809                 com_err(argv[0], 0, "Usage: mknod <name> [p| [c|b] <major> <minor>]");
1810                 return;
1811         }
1812         mode = minor = major = 0;
1813         switch (argv[2][0]) {
1814                 case 'p':
1815                         mode = LINUX_S_IFIFO;
1816                         filetype = EXT2_FT_FIFO;
1817                         nr = 3;
1818                         break;
1819                 case 'c':
1820                         mode = LINUX_S_IFCHR;
1821                         filetype = EXT2_FT_CHRDEV;
1822                         nr = 5;
1823                         break;
1824                 case 'b':
1825                         mode = LINUX_S_IFBLK;
1826                         filetype = EXT2_FT_BLKDEV;
1827                         nr = 5;
1828                         break;
1829                 default:
1830                         filetype = 0;
1831                         nr = 0;
1832         }
1833         if (nr == 5) {
1834                 major = strtoul(argv[3], argv+3, 0);
1835                 minor = strtoul(argv[4], argv+4, 0);
1836                 if (major > 65535 || minor > 65535 || argv[3][0] || argv[4][0])
1837                         nr = 0;
1838         }
1839         if (argc != nr)
1840                 goto usage;
1841         if (check_fs_read_write(argv[0]))
1842                 return;
1843         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1844         if (retval) {
1845                 com_err(argv[0], retval, 0);
1846                 return;
1847         }
1848         printf("Allocated inode: %u\n", newfile);
1849         retval = ext2fs_link(current_fs, cwd, argv[1], newfile, filetype);
1850         if (retval == EXT2_ET_DIR_NO_SPACE) {
1851                 retval = ext2fs_expand_dir(current_fs, cwd);
1852                 if (retval) {
1853                         com_err(argv[0], retval, "while expanding directory");
1854                         return;
1855                 }
1856                 retval = ext2fs_link(current_fs, cwd, argv[1], newfile,
1857                                      filetype);
1858         }
1859         if (retval) {
1860                 com_err(argv[1], retval, 0);
1861                 return;
1862         }
1863         if (ext2fs_test_inode_bitmap2(current_fs->inode_map,newfile))
1864                 com_err(argv[0], 0, "Warning: inode already set");
1865         ext2fs_inode_alloc_stats2(current_fs, newfile, +1, 0);
1866         memset(&inode, 0, sizeof(inode));
1867         inode.i_mode = mode;
1868         inode.i_atime = inode.i_ctime = inode.i_mtime =
1869                 current_fs->now ? current_fs->now : time(0);
1870         if ((major < 256) && (minor < 256)) {
1871                 inode.i_block[0] = major*256+minor;
1872                 inode.i_block[1] = 0;
1873         } else {
1874                 inode.i_block[0] = 0;
1875                 inode.i_block[1] = (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
1876         }
1877         inode.i_links_count = 1;
1878         if (debugfs_write_new_inode(newfile, &inode, argv[0]))
1879                 return;
1880 }
1881
1882 void do_mkdir(int argc, char *argv[])
1883 {
1884         char    *cp;
1885         ext2_ino_t      parent;
1886         char    *name;
1887         errcode_t retval;
1888
1889         if (common_args_process(argc, argv, 2, 2, "mkdir",
1890                                 "<filename>", CHECK_FS_RW))
1891                 return;
1892
1893         cp = strrchr(argv[1], '/');
1894         if (cp) {
1895                 *cp = 0;
1896                 parent = string_to_inode(argv[1]);
1897                 if (!parent) {
1898                         com_err(argv[1], ENOENT, 0);
1899                         return;
1900                 }
1901                 name = cp+1;
1902         } else {
1903                 parent = cwd;
1904                 name = argv[1];
1905         }
1906
1907 try_again:
1908         retval = ext2fs_mkdir(current_fs, parent, 0, name);
1909         if (retval == EXT2_ET_DIR_NO_SPACE) {
1910                 retval = ext2fs_expand_dir(current_fs, parent);
1911                 if (retval) {
1912                         com_err(argv[0], retval, "while expanding directory");
1913                         return;
1914                 }
1915                 goto try_again;
1916         }
1917         if (retval) {
1918                 com_err("ext2fs_mkdir", retval, 0);
1919                 return;
1920         }
1921
1922 }
1923
1924 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
1925                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1926                                blk64_t ref_block EXT2FS_ATTR((unused)),
1927                                int ref_offset EXT2FS_ATTR((unused)),
1928                                void *private EXT2FS_ATTR((unused)))
1929 {
1930         blk64_t block;
1931
1932         block = *blocknr;
1933         ext2fs_block_alloc_stats2(fs, block, -1);
1934         return 0;
1935 }
1936
1937 static void kill_file_by_inode(ext2_ino_t inode)
1938 {
1939         struct ext2_inode inode_buf;
1940
1941         if (debugfs_read_inode(inode, &inode_buf, 0))
1942                 return;
1943         inode_buf.i_dtime = current_fs->now ? current_fs->now : time(0);
1944         if (debugfs_write_inode(inode, &inode_buf, 0))
1945                 return;
1946         if (ext2fs_inode_has_valid_blocks2(current_fs, &inode_buf)) {
1947                 ext2fs_block_iterate3(current_fs, inode, BLOCK_FLAG_READ_ONLY,
1948                                       NULL, release_blocks_proc, NULL);
1949         }
1950         printf("\n");
1951         ext2fs_inode_alloc_stats2(current_fs, inode, -1,
1952                                   LINUX_S_ISDIR(inode_buf.i_mode));
1953 }
1954
1955
1956 void do_kill_file(int argc, char *argv[])
1957 {
1958         ext2_ino_t inode_num;
1959
1960         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1961                 return;
1962
1963         kill_file_by_inode(inode_num);
1964 }
1965
1966 void do_rm(int argc, char *argv[])
1967 {
1968         int retval;
1969         ext2_ino_t inode_num;
1970         struct ext2_inode inode;
1971
1972         if (common_args_process(argc, argv, 2, 2, "rm",
1973                                 "<filename>", CHECK_FS_RW))
1974                 return;
1975
1976         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1977         if (retval) {
1978                 com_err(argv[0], retval, "while trying to resolve filename");
1979                 return;
1980         }
1981
1982         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1983                 return;
1984
1985         if (LINUX_S_ISDIR(inode.i_mode)) {
1986                 com_err(argv[0], 0, "file is a directory");
1987                 return;
1988         }
1989
1990         --inode.i_links_count;
1991         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1992                 return;
1993
1994         unlink_file_by_name(argv[1]);
1995         if (inode.i_links_count == 0)
1996                 kill_file_by_inode(inode_num);
1997 }
1998
1999 struct rd_struct {
2000         ext2_ino_t      parent;
2001         int             empty;
2002 };
2003
2004 static int rmdir_proc(ext2_ino_t dir EXT2FS_ATTR((unused)),
2005                       int       entry EXT2FS_ATTR((unused)),
2006                       struct ext2_dir_entry *dirent,
2007                       int       offset EXT2FS_ATTR((unused)),
2008                       int       blocksize EXT2FS_ATTR((unused)),
2009                       char      *buf EXT2FS_ATTR((unused)),
2010                       void      *private)
2011 {
2012         struct rd_struct *rds = (struct rd_struct *) private;
2013
2014         if (dirent->inode == 0)
2015                 return 0;
2016         if ((ext2fs_dirent_name_len(dirent) == 1) && (dirent->name[0] == '.'))
2017                 return 0;
2018         if ((ext2fs_dirent_name_len(dirent) == 2) && (dirent->name[0] == '.') &&
2019             (dirent->name[1] == '.')) {
2020                 rds->parent = dirent->inode;
2021                 return 0;
2022         }
2023         rds->empty = 0;
2024         return 0;
2025 }
2026
2027 void do_rmdir(int argc, char *argv[])
2028 {
2029         int retval;
2030         ext2_ino_t inode_num;
2031         struct ext2_inode inode;
2032         struct rd_struct rds;
2033
2034         if (common_args_process(argc, argv, 2, 2, "rmdir",
2035                                 "<filename>", CHECK_FS_RW))
2036                 return;
2037
2038         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
2039         if (retval) {
2040                 com_err(argv[0], retval, "while trying to resolve filename");
2041                 return;
2042         }
2043
2044         if (debugfs_read_inode(inode_num, &inode, argv[0]))
2045                 return;
2046
2047         if (!LINUX_S_ISDIR(inode.i_mode)) {
2048                 com_err(argv[0], 0, "file is not a directory");
2049                 return;
2050         }
2051
2052         rds.parent = 0;
2053         rds.empty = 1;
2054
2055         retval = ext2fs_dir_iterate2(current_fs, inode_num, 0,
2056                                     0, rmdir_proc, &rds);
2057         if (retval) {
2058                 com_err(argv[0], retval, "while iterating over directory");
2059                 return;
2060         }
2061         if (rds.empty == 0) {
2062                 com_err(argv[0], 0, "directory not empty");
2063                 return;
2064         }
2065
2066         inode.i_links_count = 0;
2067         if (debugfs_write_inode(inode_num, &inode, argv[0]))
2068                 return;
2069
2070         unlink_file_by_name(argv[1]);
2071         kill_file_by_inode(inode_num);
2072
2073         if (rds.parent) {
2074                 if (debugfs_read_inode(rds.parent, &inode, argv[0]))
2075                         return;
2076                 if (inode.i_links_count > 1)
2077                         inode.i_links_count--;
2078                 if (debugfs_write_inode(rds.parent, &inode, argv[0]))
2079                         return;
2080         }
2081 }
2082 #endif /* READ_ONLY */
2083
2084 void do_show_debugfs_params(int argc EXT2FS_ATTR((unused)),
2085                             char *argv[] EXT2FS_ATTR((unused)))
2086 {
2087         if (current_fs)
2088                 printf("Open mode: read-%s\n",
2089                        current_fs->flags & EXT2_FLAG_RW ? "write" : "only");
2090         printf("Filesystem in use: %s\n",
2091                current_fs ? current_fs->device_name : "--none--");
2092 }
2093
2094 #ifndef READ_ONLY
2095 void do_expand_dir(int argc, char *argv[])
2096 {
2097         ext2_ino_t inode;
2098         int retval;
2099
2100         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
2101                 return;
2102
2103         retval = ext2fs_expand_dir(current_fs, inode);
2104         if (retval)
2105                 com_err("ext2fs_expand_dir", retval, 0);
2106         return;
2107 }
2108
2109 void do_features(int argc, char *argv[])
2110 {
2111         int     i;
2112
2113         if (check_fs_open(argv[0]))
2114                 return;
2115
2116         if ((argc != 1) && check_fs_read_write(argv[0]))
2117                 return;
2118         for (i=1; i < argc; i++) {
2119                 if (e2p_edit_feature(argv[i],
2120                                      &current_fs->super->s_feature_compat, 0))
2121                         com_err(argv[0], 0, "Unknown feature: %s\n",
2122                                 argv[i]);
2123                 else
2124                         ext2fs_mark_super_dirty(current_fs);
2125         }
2126         print_features(current_fs->super, stdout);
2127 }
2128 #endif /* READ_ONLY */
2129
2130 void do_bmap(int argc, char *argv[])
2131 {
2132         ext2_ino_t      ino;
2133         blk64_t         blk, pblk;
2134         int             err;
2135         errcode_t       errcode;
2136
2137         if (common_args_process(argc, argv, 3, 3, argv[0],
2138                                 "<file> logical_blk", 0))
2139                 return;
2140
2141         ino = string_to_inode(argv[1]);
2142         if (!ino)
2143                 return;
2144         err = strtoblk(argv[0], argv[2], "logical block", &blk);
2145         if (err)
2146                 return;
2147
2148         errcode = ext2fs_bmap2(current_fs, ino, 0, 0, 0, blk, 0, &pblk);
2149         if (errcode) {
2150                 com_err(argv[0], errcode,
2151                         "while mapping logical block %llu\n", blk);
2152                 return;
2153         }
2154         printf("%llu\n", pblk);
2155 }
2156
2157 void do_imap(int argc, char *argv[])
2158 {
2159         ext2_ino_t      ino;
2160         unsigned long   group, block, block_nr, offset;
2161
2162         if (common_args_process(argc, argv, 2, 2, argv[0],
2163                                 "<file>", 0))
2164                 return;
2165         ino = string_to_inode(argv[1]);
2166         if (!ino)
2167                 return;
2168
2169         group = (ino - 1) / EXT2_INODES_PER_GROUP(current_fs->super);
2170         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(current_fs->super)) *
2171                 EXT2_INODE_SIZE(current_fs->super);
2172         block = offset >> EXT2_BLOCK_SIZE_BITS(current_fs->super);
2173         if (!ext2fs_inode_table_loc(current_fs, (unsigned)group)) {
2174                 com_err(argv[0], 0, "Inode table for group %lu is missing\n",
2175                         group);
2176                 return;
2177         }
2178         block_nr = ext2fs_inode_table_loc(current_fs, (unsigned)group) +
2179                 block;
2180         offset &= (EXT2_BLOCK_SIZE(current_fs->super) - 1);
2181
2182         printf("Inode %d is part of block group %lu\n"
2183                "\tlocated at block %lu, offset 0x%04lx\n", ino, group,
2184                block_nr, offset);
2185
2186 }
2187
2188 #ifndef READ_ONLY
2189 void do_set_current_time(int argc, char *argv[])
2190 {
2191         time_t now;
2192
2193         if (common_args_process(argc, argv, 2, 2, argv[0],
2194                                 "<time>", 0))
2195                 return;
2196
2197         now = string_to_time(argv[1]);
2198         if (now == ((time_t) -1)) {
2199                 com_err(argv[0], 0, "Couldn't parse argument as a time: %s\n",
2200                         argv[1]);
2201                 return;
2202
2203         } else {
2204                 printf("Setting current time to %s\n", time_to_string(now));
2205                 current_fs->now = now;
2206         }
2207 }
2208 #endif /* READ_ONLY */
2209
2210 static int find_supp_feature(__u32 *supp, int feature_type, char *name)
2211 {
2212         int compat, bit, ret;
2213         unsigned int feature_mask;
2214
2215         if (name) {
2216                 if (feature_type == E2P_FS_FEATURE)
2217                         ret = e2p_string2feature(name, &compat, &feature_mask);
2218                 else
2219                         ret = e2p_jrnl_string2feature(name, &compat,
2220                                                       &feature_mask);
2221                 if (ret)
2222                         return ret;
2223
2224                 if (!(supp[compat] & feature_mask))
2225                         return 1;
2226         } else {
2227                 for (compat = 0; compat < 3; compat++) {
2228                         for (bit = 0, feature_mask = 1; bit < 32;
2229                              bit++, feature_mask <<= 1) {
2230                                 if (supp[compat] & feature_mask) {
2231                                         if (feature_type == E2P_FS_FEATURE)
2232                                                 fprintf(stdout, " %s",
2233                                                 e2p_feature2string(compat,
2234                                                 feature_mask));
2235                                         else
2236                                                 fprintf(stdout, " %s",
2237                                                 e2p_jrnl_feature2string(compat,
2238                                                 feature_mask));
2239                                 }
2240                         }
2241                 }
2242                 fprintf(stdout, "\n");
2243         }
2244
2245         return 0;
2246 }
2247
2248 void do_supported_features(int argc, char *argv[])
2249 {
2250         int     ret;
2251         __u32   supp[3] = { EXT2_LIB_FEATURE_COMPAT_SUPP,
2252                             EXT2_LIB_FEATURE_INCOMPAT_SUPP,
2253                             EXT2_LIB_FEATURE_RO_COMPAT_SUPP };
2254         __u32   jrnl_supp[3] = { JFS_KNOWN_COMPAT_FEATURES,
2255                                  JFS_KNOWN_INCOMPAT_FEATURES,
2256                                  JFS_KNOWN_ROCOMPAT_FEATURES };
2257
2258         if (argc > 1) {
2259                 ret = find_supp_feature(supp, E2P_FS_FEATURE, argv[1]);
2260                 if (ret) {
2261                         ret = find_supp_feature(jrnl_supp, E2P_JOURNAL_FEATURE,
2262                                                 argv[1]);
2263                 }
2264                 if (ret)
2265                         com_err(argv[0], 0, "Unknown feature: %s\n", argv[1]);
2266                 else
2267                         fprintf(stdout, "Supported feature: %s\n", argv[1]);
2268         } else {
2269                 fprintf(stdout, "Supported features:");
2270                 ret = find_supp_feature(supp, E2P_FS_FEATURE, NULL);
2271                 ret = find_supp_feature(jrnl_supp, E2P_JOURNAL_FEATURE, NULL);
2272         }
2273 }
2274
2275 #ifndef READ_ONLY
2276 void do_punch(int argc, char *argv[])
2277 {
2278         ext2_ino_t      ino;
2279         blk64_t         start, end;
2280         int             err;
2281         errcode_t       errcode;
2282
2283         if (common_args_process(argc, argv, 3, 4, argv[0],
2284                                 "<file> start_blk [end_blk]",
2285                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
2286                 return;
2287
2288         ino = string_to_inode(argv[1]);
2289         if (!ino)
2290                 return;
2291         err = strtoblk(argv[0], argv[2], "logical block", &start);
2292         if (err)
2293                 return;
2294         if (argc == 4) {
2295                 err = strtoblk(argv[0], argv[3], "logical block", &end);
2296                 if (err)
2297                         return;
2298         } else
2299                 end = ~0;
2300
2301         errcode = ext2fs_punch(current_fs, ino, 0, 0, start, end);
2302
2303         if (errcode) {
2304                 com_err(argv[0], errcode,
2305                         "while truncating inode %u from %llu to %llu\n", ino,
2306                         (unsigned long long) start, (unsigned long long) end);
2307                 return;
2308         }
2309 }
2310 #endif /* READ_ONLY */
2311
2312 void do_symlink(int argc, char *argv[])
2313 {
2314         char            *cp;
2315         ext2_ino_t      parent;
2316         char            *name, *target;
2317         errcode_t       retval;
2318
2319         if (common_args_process(argc, argv, 3, 3, "symlink",
2320                                 "<filename> <target>", CHECK_FS_RW))
2321                 return;
2322
2323         cp = strrchr(argv[1], '/');
2324         if (cp) {
2325                 *cp = 0;
2326                 parent = string_to_inode(argv[1]);
2327                 if (!parent) {
2328                         com_err(argv[1], ENOENT, 0);
2329                         return;
2330                 }
2331                 name = cp+1;
2332         } else {
2333                 parent = cwd;
2334                 name = argv[1];
2335         }
2336         target = argv[2];
2337
2338 try_again:
2339         retval = ext2fs_symlink(current_fs, parent, 0, name, target);
2340         if (retval == EXT2_ET_DIR_NO_SPACE) {
2341                 retval = ext2fs_expand_dir(current_fs, parent);
2342                 if (retval) {
2343                         com_err(argv[0], retval, "while expanding directory");
2344                         return;
2345                 }
2346                 goto try_again;
2347         }
2348         if (retval) {
2349                 com_err("ext2fs_symlink", retval, 0);
2350                 return;
2351         }
2352
2353 }
2354
2355 void do_dump_mmp(int argc EXT2FS_ATTR((unused)), char *argv[])
2356 {
2357 #if CONFIG_MMP
2358         struct ext2_super_block *sb;
2359         struct mmp_struct *mmp_s;
2360         time_t t;
2361         errcode_t retval = 0;
2362
2363         if (check_fs_open(argv[0]))
2364                 return;
2365
2366         sb  = current_fs->super;
2367
2368         if (current_fs->mmp_buf == NULL) {
2369                 retval = ext2fs_get_mem(current_fs->blocksize,
2370                                         &current_fs->mmp_buf);
2371                 if (retval) {
2372                         com_err(argv[0], retval, "allocating MMP buffer.\n");
2373                         return;
2374                 }
2375         }
2376
2377         mmp_s = current_fs->mmp_buf;
2378
2379         retval = ext2fs_mmp_read(current_fs, current_fs->super->s_mmp_block,
2380                                  current_fs->mmp_buf);
2381         if (retval) {
2382                 com_err(argv[0], retval, "reading MMP block.\n");
2383                 return;
2384         }
2385
2386         t = mmp_s->mmp_time;
2387         fprintf(stdout, "block_number: %llu\n", current_fs->super->s_mmp_block);
2388         fprintf(stdout, "update_interval: %d\n",
2389                 current_fs->super->s_mmp_update_interval);
2390         fprintf(stdout, "check_interval: %d\n", mmp_s->mmp_check_interval);
2391         fprintf(stdout, "sequence: %08x\n", mmp_s->mmp_seq);
2392         fprintf(stdout, "time: %lld -- %s", mmp_s->mmp_time, ctime(&t));
2393         fprintf(stdout, "node_name: %s\n", mmp_s->mmp_nodename);
2394         fprintf(stdout, "device_name: %s\n", mmp_s->mmp_bdevname);
2395         fprintf(stdout, "magic: 0x%x\n", mmp_s->mmp_magic);
2396         fprintf(stdout, "checksum: 0x%08x\n", mmp_s->mmp_checksum);
2397 #else
2398         fprintf(stdout, "MMP is unsupported, please recompile with "
2399                         "--enable-mmp\n");
2400 #endif
2401 }
2402
2403 static int source_file(const char *cmd_file, int ss_idx)
2404 {
2405         FILE            *f;
2406         char            buf[BUFSIZ];
2407         char            *cp;
2408         int             exit_status = 0;
2409         int             retval;
2410
2411         if (strcmp(cmd_file, "-") == 0)
2412                 f = stdin;
2413         else {
2414                 f = fopen(cmd_file, "r");
2415                 if (!f) {
2416                         perror(cmd_file);
2417                         exit(1);
2418                 }
2419         }
2420         fflush(stdout);
2421         fflush(stderr);
2422         setbuf(stdout, NULL);
2423         setbuf(stderr, NULL);
2424         while (!feof(f)) {
2425                 if (fgets(buf, sizeof(buf), f) == NULL)
2426                         break;
2427                 cp = strchr(buf, '\n');
2428                 if (cp)
2429                         *cp = 0;
2430                 cp = strchr(buf, '\r');
2431                 if (cp)
2432                         *cp = 0;
2433                 printf("debugfs: %s\n", buf);
2434                 retval = ss_execute_line(ss_idx, buf);
2435                 if (retval) {
2436                         ss_perror(ss_idx, retval, buf);
2437                         exit_status++;
2438                 }
2439         }
2440         if (f != stdin)
2441                 fclose(f);
2442         return exit_status;
2443 }
2444
2445 int main(int argc, char **argv)
2446 {
2447         int             retval;
2448         const char      *usage = 
2449                 "Usage: %s [-b blocksize] [-s superblock] [-f cmd_file] "
2450                 "[-R request] [-V] ["
2451 #ifndef READ_ONLY
2452                 "[-w] "
2453 #endif
2454                 "[-c] device]";
2455         int             c;
2456         int             open_flags = EXT2_FLAG_SOFTSUPP_FEATURES | EXT2_FLAG_64BITS;
2457         char            *request = 0;
2458         int             exit_status = 0;
2459         char            *cmd_file = 0;
2460         blk64_t         superblock = 0;
2461         blk64_t         blocksize = 0;
2462         int             catastrophic = 0;
2463         char            *data_filename = 0;
2464 #ifdef READ_ONLY
2465         const char      *opt_string = "nicR:f:b:s:Vd:D";
2466 #else
2467         const char      *opt_string = "niwcR:f:b:s:Vd:D";
2468 #endif
2469
2470         if (debug_prog_name == 0)
2471 #ifdef READ_ONLY
2472                 debug_prog_name = "rdebugfs";
2473 #else
2474                 debug_prog_name = "debugfs";
2475 #endif
2476         add_error_table(&et_ext2_error_table);
2477         fprintf (stderr, "%s %s (%s)\n", debug_prog_name,
2478                  E2FSPROGS_VERSION, E2FSPROGS_DATE);
2479
2480         while ((c = getopt (argc, argv, opt_string)) != EOF) {
2481                 switch (c) {
2482                 case 'R':
2483                         request = optarg;
2484                         break;
2485                 case 'f':
2486                         cmd_file = optarg;
2487                         break;
2488                 case 'd':
2489                         data_filename = optarg;
2490                         break;
2491                 case 'i':
2492                         open_flags |= EXT2_FLAG_IMAGE_FILE;
2493                         break;
2494                 case 'n':
2495                         open_flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2496                         break;
2497 #ifndef READ_ONLY
2498                 case 'w':
2499                         open_flags |= EXT2_FLAG_RW;
2500                         break;
2501 #endif
2502                 case 'D':
2503                         open_flags |= EXT2_FLAG_DIRECT_IO;
2504                         break;
2505                 case 'b':
2506                         blocksize = parse_ulong(optarg, argv[0],
2507                                                 "block size", 0);
2508                         break;
2509                 case 's':
2510                         retval = strtoblk(argv[0], optarg,
2511                                           "superblock block number",
2512                                           &superblock);
2513                         if (retval)
2514                                 return 1;
2515                         break;
2516                 case 'c':
2517                         catastrophic = 1;
2518                         break;
2519                 case 'V':
2520                         /* Print version number and exit */
2521                         fprintf(stderr, "\tUsing %s\n",
2522                                 error_message(EXT2_ET_BASE));
2523                         exit(0);
2524                 default:
2525                         com_err(argv[0], 0, usage, debug_prog_name);
2526                         return 1;
2527                 }
2528         }
2529         if (optind < argc)
2530                 open_filesystem(argv[optind], open_flags,
2531                                 superblock, blocksize, catastrophic,
2532                                 data_filename);
2533
2534         sci_idx = ss_create_invocation(debug_prog_name, "0.0", (char *) NULL,
2535                                        &debug_cmds, &retval);
2536         if (retval) {
2537                 ss_perror(sci_idx, retval, "creating invocation");
2538                 exit(1);
2539         }
2540         ss_get_readline(sci_idx);
2541
2542         (void) ss_add_request_table (sci_idx, &ss_std_requests, 1, &retval);
2543         if (retval) {
2544                 ss_perror(sci_idx, retval, "adding standard requests");
2545                 exit (1);
2546         }
2547         if (extra_cmds)
2548                 ss_add_request_table (sci_idx, extra_cmds, 1, &retval);
2549         if (retval) {
2550                 ss_perror(sci_idx, retval, "adding extra requests");
2551                 exit (1);
2552         }
2553         if (request) {
2554                 retval = 0;
2555                 retval = ss_execute_line(sci_idx, request);
2556                 if (retval) {
2557                         ss_perror(sci_idx, retval, request);
2558                         exit_status++;
2559                 }
2560         } else if (cmd_file) {
2561                 exit_status = source_file(cmd_file, sci_idx);
2562         } else {
2563                 ss_listen(sci_idx);
2564         }
2565
2566         ss_delete_invocation(sci_idx);
2567
2568         if (current_fs)
2569                 close_filesystem();
2570
2571         remove_error_table(&et_ext2_error_table);
2572         return exit_status;
2573 }