Whamcloud - gitweb
Use BLOCK_FLAG_READ_ONLY flag in debugfs, e2image, and tune2fs
[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 <stdio.h>
12 #include <unistd.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <time.h>
17 #ifdef HAVE_GETOPT_H
18 #include <getopt.h>
19 #else 
20 extern int optind;
21 extern char *optarg;
22 #endif
23 #ifdef HAVE_ERRNO_H
24 #include <errno.h>
25 #endif
26 #include <fcntl.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include "et/com_err.h"
31 #include "ss/ss.h"
32 #include "debugfs.h"
33 #include "uuid/uuid.h"
34 #include "e2p/e2p.h"
35
36 #include <ext2fs/ext2_ext_attr.h>
37
38 #include "../version.h"
39
40 extern ss_request_table debug_cmds;
41 ss_request_table *extra_cmds;
42 char *debug_prog_name;
43
44 ext2_filsys     current_fs = NULL;
45 ext2_ino_t      root, cwd;
46
47 static void open_filesystem(char *device, int open_flags, blk_t superblock,
48                             blk_t blocksize, int catastrophic, 
49                             char *data_filename)
50 {
51         int     retval;
52         io_channel data_io = 0;
53
54         if (superblock != 0 && blocksize == 0) {
55                 com_err(device, 0, "if you specify the superblock, you must also specify the block size");
56                 current_fs = NULL;
57                 return;
58         }
59
60         if (data_filename) {
61                 if ((open_flags & EXT2_FLAG_IMAGE_FILE) == 0) {
62                         com_err(device, 0, 
63                                 "The -d option is only valid when reading an e2image file");
64                         current_fs = NULL;
65                         return;
66                 }
67                 retval = unix_io_manager->open(data_filename, 0, &data_io);
68                 if (retval) {
69                         com_err(data_filename, 0, "while opening data source");
70                         current_fs = NULL;
71                         return;
72                 }
73         }
74
75         if (catastrophic && (open_flags & EXT2_FLAG_RW)) {
76                 com_err(device, 0,
77                         "opening read-only because of catastrophic mode");
78                 open_flags &= ~EXT2_FLAG_RW;
79         }
80         
81         retval = ext2fs_open(device, open_flags, superblock, blocksize,
82                              unix_io_manager, &current_fs);
83         if (retval) {
84                 com_err(device, retval, "while opening filesystem");
85                 current_fs = NULL;
86                 return;
87         }
88
89         if (catastrophic)
90                 com_err(device, 0, "catastrophic mode - not reading inode or group bitmaps");
91         else {
92                 retval = ext2fs_read_inode_bitmap(current_fs);
93                 if (retval) {
94                         com_err(device, retval, "while reading inode bitmap");
95                         goto errout;
96                 }
97                 retval = ext2fs_read_block_bitmap(current_fs);
98                 if (retval) {
99                         com_err(device, retval, "while reading block bitmap");
100                         goto errout;
101                 }
102         }
103
104         if (data_io) {
105                 retval = ext2fs_set_data_io(current_fs, data_io);
106                 if (retval) {
107                         com_err(device, retval, 
108                                 "while setting data source");
109                         goto errout;
110                 }
111         }
112
113         root = cwd = EXT2_ROOT_INO;
114         return;
115
116 errout:
117         retval = ext2fs_close(current_fs);
118         if (retval)
119                 com_err(device, retval, "while trying to close filesystem");
120         current_fs = NULL;
121 }
122
123 void do_open_filesys(int argc, char **argv)
124 {
125         int     c, err;
126         int     catastrophic = 0;
127         blk_t   superblock = 0;
128         blk_t   blocksize = 0;
129         int     open_flags = EXT2_FLAG_SOFTSUPP_FEATURES;
130         char    *data_filename = 0;
131         
132         reset_getopt();
133         while ((c = getopt (argc, argv, "iwfecb:s:d:")) != EOF) {
134                 switch (c) {
135                 case 'i':
136                         open_flags |= EXT2_FLAG_IMAGE_FILE;
137                         break;
138                 case 'w':
139                         open_flags |= EXT2_FLAG_RW;
140                         break;
141                 case 'f':
142                         open_flags |= EXT2_FLAG_FORCE;
143                         break;
144                 case 'e':
145                         open_flags |= EXT2_FLAG_EXCLUSIVE;
146                         break;
147                 case 'c':
148                         catastrophic = 1;
149                         break;
150                 case 'd':
151                         data_filename = optarg;
152                         break;
153                 case 'b':
154                         blocksize = parse_ulong(optarg, argv[0],
155                                                 "block size", &err);
156                         if (err)
157                                 return;
158                         break;
159                 case 's':
160                         superblock = parse_ulong(optarg, argv[0],
161                                                  "superblock number", &err);
162                         if (err)
163                                 return;
164                         break;
165                 default:
166                         goto print_usage;
167                 }
168         }
169         if (optind != argc-1) {
170                 goto print_usage;
171         }
172         if (check_fs_not_open(argv[0]))
173                 return;
174         open_filesystem(argv[optind], open_flags,
175                         superblock, blocksize, catastrophic, 
176                         data_filename);
177         return;
178
179 print_usage:
180         fprintf(stderr, "%s: Usage: open [-s superblock] [-b blocksize] "
181                 "[-c] [-w] <device>\n", argv[0]);
182 }
183
184 void do_lcd(int argc, char **argv)
185 {
186         if (argc != 2) {
187                 com_err(argv[0], 0, "Usage: %s %s", argv[0], "<native dir>");
188                 return;
189         }
190
191         if (chdir(argv[1]) == -1) {
192                 com_err(argv[0], errno,
193                         "while trying to change native directory to %s",
194                         argv[1]);
195                 return;
196         }
197 }
198
199 static void close_filesystem(NOARGS)
200 {
201         int     retval;
202         
203         if (current_fs->flags & EXT2_FLAG_IB_DIRTY) {
204                 retval = ext2fs_write_inode_bitmap(current_fs);
205                 if (retval)
206                         com_err("ext2fs_write_inode_bitmap", retval, 0);
207         }
208         if (current_fs->flags & EXT2_FLAG_BB_DIRTY) {
209                 retval = ext2fs_write_block_bitmap(current_fs);
210                 if (retval)
211                         com_err("ext2fs_write_block_bitmap", retval, 0);
212         }
213         retval = ext2fs_close(current_fs);
214         if (retval)
215                 com_err("ext2fs_close", retval, 0);
216         current_fs = NULL;
217         return;
218 }
219
220 void do_close_filesys(int argc, char **argv)
221 {
222         if (common_args_process(argc, argv, 1, 1, "close_filesys", "", 0))
223                 return;
224         close_filesystem();
225 }
226
227 void do_init_filesys(int argc, char **argv)
228 {
229         struct ext2_super_block param;
230         errcode_t       retval;
231         int             err;
232         
233         if (common_args_process(argc, argv, 3, 3, "initialize",
234                                 "<device> <blocksize>", CHECK_FS_NOTOPEN))
235                 return;
236
237         memset(&param, 0, sizeof(struct ext2_super_block));
238         param.s_blocks_count = parse_ulong(argv[2], argv[0],
239                                            "blocks count", &err);
240         if (err)
241                 return;
242         retval = ext2fs_initialize(argv[1], 0, &param,
243                                    unix_io_manager, &current_fs);
244         if (retval) {
245                 com_err(argv[1], retval, "while initializing filesystem");
246                 current_fs = NULL;
247                 return;
248         }
249         root = cwd = EXT2_ROOT_INO;
250         return;
251 }
252
253 static void print_features(struct ext2_super_block * s, FILE *f)
254 {
255         int     i, j, printed=0;
256         __u32   *mask = &s->s_feature_compat, m;
257
258         fputs("Filesystem features:", f);
259         for (i=0; i <3; i++,mask++) {
260                 for (j=0,m=1; j < 32; j++, m<<=1) {
261                         if (*mask & m) {
262                                 fprintf(f, " %s", e2p_feature2string(i, m));
263                                 printed++;
264                         }
265                 }
266         }
267         if (printed == 0)
268                 fputs("(none)", f);
269         fputs("\n", f);
270 }
271
272 static void print_bg_opts(struct ext2_group_desc *gdp, int mask,
273                           const char *str, int *first, FILE *f)
274 {
275         if (gdp->bg_flags & mask) {
276                 if (*first) {
277                         fputs("           [", f);
278                         *first = 0;
279                 } else
280                         fputs(", ", f);
281                 fputs(str, f);
282         }
283 }
284
285 void do_show_super_stats(int argc, char *argv[])
286 {
287         dgrp_t  i;
288         FILE    *out;
289         struct ext2_group_desc *gdp;
290         int     c, header_only = 0;
291         int     numdirs = 0, first;
292
293         reset_getopt();
294         while ((c = getopt (argc, argv, "h")) != EOF) {
295                 switch (c) {
296                 case 'h':
297                         header_only++;
298                         break;
299                 default:
300                         goto print_usage;
301                 }
302         }
303         if (optind != argc) {
304                 goto print_usage;
305         }
306         if (check_fs_open(argv[0]))
307                 return;
308         out = open_pager();
309
310         list_super2(current_fs->super, out);
311         for (i=0; i < current_fs->group_desc_count; i++)
312                 numdirs += current_fs->group_desc[i].bg_used_dirs_count;
313         fprintf(out, "Directories:              %d\n", numdirs);
314         
315         if (header_only) {
316                 close_pager(out);
317                 return;
318         }
319         
320         gdp = &current_fs->group_desc[0];
321         for (i = 0; i < current_fs->group_desc_count; i++, gdp++) {
322                 fprintf(out, " Group %2d: block bitmap at %u, "
323                         "inode bitmap at %u, "
324                         "inode table at %u\n"
325                         "           %d free %s, "
326                         "%d free %s, "
327                         "%d used %s\n",
328                         i, gdp->bg_block_bitmap,
329                         gdp->bg_inode_bitmap, gdp->bg_inode_table,
330                         gdp->bg_free_blocks_count,
331                         gdp->bg_free_blocks_count != 1 ? "blocks" : "block",
332                         gdp->bg_free_inodes_count,
333                         gdp->bg_free_inodes_count != 1 ? "inodes" : "inode",
334                         gdp->bg_used_dirs_count,
335                         gdp->bg_used_dirs_count != 1 ? "directories"
336                                 : "directory");
337                 first = 1;
338                 print_bg_opts(gdp, EXT2_BG_INODE_UNINIT, "Inode not init",
339                               &first, out);
340                 print_bg_opts(gdp, EXT2_BG_BLOCK_UNINIT, "Block not init",
341                               &first, out);
342                 if (!first)
343                         fputs("]\n", out);
344         }
345         close_pager(out);
346         return;
347 print_usage:
348         fprintf(stderr, "%s: Usage: show_super [-h]\n", argv[0]);
349 }
350
351 void do_dirty_filesys(int argc EXT2FS_ATTR((unused)), 
352                       char **argv EXT2FS_ATTR((unused)))
353 {
354         if (check_fs_open(argv[0]))
355                 return;
356         if (check_fs_read_write(argv[0]))
357                 return;
358
359         if (argv[1] && !strcmp(argv[1], "-clean"))
360                 current_fs->super->s_state |= EXT2_VALID_FS;
361         else
362                 current_fs->super->s_state &= ~EXT2_VALID_FS;
363         ext2fs_mark_super_dirty(current_fs);
364 }
365
366 struct list_blocks_struct {
367         FILE            *f;
368         e2_blkcnt_t     total;
369         blk_t           first_block, last_block;
370         e2_blkcnt_t     first_bcnt, last_bcnt;
371         e2_blkcnt_t     first;
372 };
373
374 static void finish_range(struct list_blocks_struct *lb)
375 {
376         if (lb->first_block == 0)
377                 return;
378         if (lb->first)
379                 lb->first = 0;
380         else
381                 fprintf(lb->f, ", ");
382         if (lb->first_block == lb->last_block)
383                 fprintf(lb->f, "(%lld):%u",
384                         (long long)lb->first_bcnt, lb->first_block);
385         else
386                 fprintf(lb->f, "(%lld-%lld):%u-%u",
387                         (long long)lb->first_bcnt, (long long)lb->last_bcnt,
388                         lb->first_block, lb->last_block);
389         lb->first_block = 0;
390 }
391
392 static int list_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)), 
393                             blk_t *blocknr, e2_blkcnt_t blockcnt, 
394                             blk_t ref_block EXT2FS_ATTR((unused)),
395                             int ref_offset EXT2FS_ATTR((unused)), 
396                             void *private)
397 {
398         struct list_blocks_struct *lb = (struct list_blocks_struct *) private;
399
400         lb->total++;
401         if (blockcnt >= 0) {
402                 /*
403                  * See if we can add on to the existing range (if it exists)
404                  */
405                 if (lb->first_block &&
406                     (lb->last_block+1 == *blocknr) &&
407                     (lb->last_bcnt+1 == blockcnt)) {
408                         lb->last_block = *blocknr;
409                         lb->last_bcnt = blockcnt;
410                         return 0;
411                 }
412                 /*
413                  * Start a new range.
414                  */
415                 finish_range(lb);
416                 lb->first_block = lb->last_block = *blocknr;
417                 lb->first_bcnt = lb->last_bcnt = blockcnt;
418                 return 0;
419         }
420         /*
421          * Not a normal block.  Always force a new range.
422          */
423         finish_range(lb);
424         if (lb->first)
425                 lb->first = 0;
426         else
427                 fprintf(lb->f, ", ");
428         if (blockcnt == -1)
429                 fprintf(lb->f, "(IND):%u", *blocknr);
430         else if (blockcnt == -2)
431                 fprintf(lb->f, "(DIND):%u", *blocknr);
432         else if (blockcnt == -3)
433                 fprintf(lb->f, "(TIND):%u", *blocknr);
434         return 0;
435 }
436
437 static void dump_xattr_string(FILE *out, const char *str, int len)
438 {
439         int printable = 1;
440         int i;
441         
442         /* check is string printable? */
443         for (i = 0; i < len; i++)
444                 if (!isprint(str[i])) {
445                         printable = 0;
446                         break;
447                 }
448
449         for (i = 0; i < len; i++)
450                 if (printable)
451                         fprintf(out, "%c", (unsigned char)str[i]);
452                 else
453                         fprintf(out, "%02x ", (unsigned char)str[i]);
454 }
455
456 static void internal_dump_inode_extra(FILE *out, 
457                                       const char *prefix EXT2FS_ATTR((unused)),
458                                       ext2_ino_t inode_num EXT2FS_ATTR((unused)), 
459                                       struct ext2_inode_large *inode)
460 {
461         struct ext2_ext_attr_entry *entry;
462         __u32 *magic;
463         char *start, *end;
464         unsigned int storage_size;
465
466         fprintf(out, "Size of extra inode fields: %u\n", inode->i_extra_isize);
467         if (inode->i_extra_isize > EXT2_INODE_SIZE(current_fs->super) -
468                         EXT2_GOOD_OLD_INODE_SIZE) {
469                 fprintf(stderr, "invalid inode->i_extra_isize (%u)\n",
470                                 inode->i_extra_isize);
471                 return;
472         }
473         storage_size = EXT2_INODE_SIZE(current_fs->super) -
474                         EXT2_GOOD_OLD_INODE_SIZE -
475                         inode->i_extra_isize;
476         magic = (__u32 *)((char *)inode + EXT2_GOOD_OLD_INODE_SIZE +
477                         inode->i_extra_isize);
478         if (*magic == EXT2_EXT_ATTR_MAGIC) {
479                 fprintf(out, "Extended attributes stored in inode body: \n");
480                 end = (char *) inode + EXT2_INODE_SIZE(current_fs->super);
481                 start = (char *) magic + sizeof(__u32);
482                 entry = (struct ext2_ext_attr_entry *) start;
483                 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
484                         struct ext2_ext_attr_entry *next =
485                                 EXT2_EXT_ATTR_NEXT(entry);
486                         if (entry->e_value_size > storage_size ||
487                                         (char *) next >= end) {
488                                 fprintf(out, "invalid EA entry in inode\n");
489                                 return;
490                         }
491                         fprintf(out, "  ");
492                         dump_xattr_string(out, EXT2_EXT_ATTR_NAME(entry), 
493                                           entry->e_name_len);
494                         fprintf(out, " = \"");
495                         dump_xattr_string(out, start + entry->e_value_offs,
496                                                 entry->e_value_size);
497                         fprintf(out, "\" (%u)\n", entry->e_value_size);
498                         entry = next;
499                 }
500         }
501 }
502
503 static void dump_blocks(FILE *f, const char *prefix, ext2_ino_t inode)
504 {
505         struct list_blocks_struct lb;
506
507         fprintf(f, "%sBLOCKS:\n%s", prefix, prefix);
508         lb.total = 0;
509         lb.first_block = 0;
510         lb.f = f;
511         lb.first = 1;
512         ext2fs_block_iterate2(current_fs, inode, BLOCK_FLAG_READ_ONLY, NULL,
513                              list_blocks_proc, (void *)&lb);
514         finish_range(&lb);
515         if (lb.total)
516                 fprintf(f, "\n%sTOTAL: %lld\n", prefix, (long long)lb.total);
517         fprintf(f,"\n");
518 }
519
520
521 void internal_dump_inode(FILE *out, const char *prefix,
522                          ext2_ino_t inode_num, struct ext2_inode *inode,
523                          int do_dump_blocks)
524 {
525         const char *i_type;
526         char frag, fsize;
527         int os = current_fs->super->s_creator_os;
528         
529         if (LINUX_S_ISDIR(inode->i_mode)) i_type = "directory";
530         else if (LINUX_S_ISREG(inode->i_mode)) i_type = "regular";
531         else if (LINUX_S_ISLNK(inode->i_mode)) i_type = "symlink";
532         else if (LINUX_S_ISBLK(inode->i_mode)) i_type = "block special";
533         else if (LINUX_S_ISCHR(inode->i_mode)) i_type = "character special";
534         else if (LINUX_S_ISFIFO(inode->i_mode)) i_type = "FIFO";
535         else if (LINUX_S_ISSOCK(inode->i_mode)) i_type = "socket";
536         else i_type = "bad type";
537         fprintf(out, "%sInode: %u   Type: %s    ", prefix, inode_num, i_type);
538         fprintf(out, "%sMode:  %04o   Flags: 0x%x   Generation: %u\n",
539                 prefix, 
540                 inode->i_mode & 0777, inode->i_flags, inode->i_generation);
541         fprintf(out, "%sUser: %5d   Group: %5d   Size: ",
542                 prefix, inode_uid(*inode), inode_gid(*inode));
543         if (LINUX_S_ISREG(inode->i_mode)) {
544                 unsigned long long i_size = (inode->i_size |
545                                     ((unsigned long long)inode->i_size_high << 32));
546
547                 fprintf(out, "%llu\n", i_size);
548         } else
549                 fprintf(out, "%d\n", inode->i_size);
550         if (os == EXT2_OS_HURD)
551                 fprintf(out,
552                         "%sFile ACL: %d    Directory ACL: %d Translator: %d\n",
553                         prefix,
554                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0,
555                         inode->osd1.hurd1.h_i_translator);
556         else
557                 fprintf(out, "%sFile ACL: %d    Directory ACL: %d\n",
558                         prefix,
559                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0);
560         if (os == EXT2_OS_LINUX) 
561                 fprintf(out, "%sLinks: %d   Blockcount: %llu\n",
562                         prefix, inode->i_links_count, 
563                         (((unsigned long long) 
564                           inode->osd2.linux2.l_i_blocks_hi << 32)) + 
565                         inode->i_blocks);
566         else
567                 fprintf(out, "%sLinks: %d   Blockcount: %u\n",
568                         prefix, inode->i_links_count, inode->i_blocks);
569         switch (os) {
570             case EXT2_OS_HURD:
571                 frag = inode->osd2.hurd2.h_i_frag;
572                 fsize = inode->osd2.hurd2.h_i_fsize;
573                 break;
574             default:
575                 frag = fsize = 0;
576         }
577         fprintf(out, "%sFragment:  Address: %d    Number: %d    Size: %d\n",
578                 prefix, inode->i_faddr, frag, fsize);
579         fprintf(out, "%sctime: 0x%08x -- %s", prefix, inode->i_ctime,
580                 time_to_string(inode->i_ctime));
581         fprintf(out, "%satime: 0x%08x -- %s", prefix, inode->i_atime,
582                 time_to_string(inode->i_atime));
583         fprintf(out, "%smtime: 0x%08x -- %s", prefix, inode->i_mtime,
584                 time_to_string(inode->i_mtime));
585         if (inode->i_dtime) 
586           fprintf(out, "%sdtime: 0x%08x -- %s", prefix, inode->i_dtime,
587                   time_to_string(inode->i_dtime));
588         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
589                 internal_dump_inode_extra(out, prefix, inode_num,
590                                           (struct ext2_inode_large *) inode);
591         if (LINUX_S_ISLNK(inode->i_mode) && ext2fs_inode_data_blocks(current_fs,inode) == 0)
592                 fprintf(out, "%sFast_link_dest: %.*s\n", prefix,
593                         (int) inode->i_size, (char *)inode->i_block);
594         else if (LINUX_S_ISBLK(inode->i_mode) || LINUX_S_ISCHR(inode->i_mode)) {
595                 int major, minor;
596                 const char *devnote;
597
598                 if (inode->i_block[0]) {
599                         major = (inode->i_block[0] >> 8) & 255;
600                         minor = inode->i_block[0] & 255;
601                         devnote = "";
602                 } else {
603                         major = (inode->i_block[1] & 0xfff00) >> 8;
604                         minor = ((inode->i_block[1] & 0xff) | 
605                                  ((inode->i_block[1] >> 12) & 0xfff00));
606                         devnote = "(New-style) ";
607                 }
608                 fprintf(out, "%sDevice major/minor number: %02d:%02d (hex %02x:%02x)\n", 
609                         devnote, major, minor, major, minor);
610         }
611         else if (do_dump_blocks)
612                 dump_blocks(out, prefix, inode_num);
613 }
614
615 static void dump_inode(ext2_ino_t inode_num, struct ext2_inode *inode)
616 {
617         FILE    *out;
618         
619         out = open_pager();
620         internal_dump_inode(out, "", inode_num, inode, 1);
621         close_pager(out);
622 }
623
624 void do_stat(int argc, char *argv[])
625 {
626         ext2_ino_t      inode;
627         struct ext2_inode * inode_buf;
628
629         if (check_fs_open(argv[0]))
630                 return;
631
632         inode_buf = (struct ext2_inode *)
633                         malloc(EXT2_INODE_SIZE(current_fs->super));
634         if (!inode_buf) {
635                 fprintf(stderr, "do_stat: can't allocate buffer\n");
636                 return;
637         }
638
639         if (common_inode_args_process(argc, argv, &inode, 0)) {
640                 free(inode_buf);
641                 return;
642         }
643
644         if (debugfs_read_inode_full(inode, inode_buf, argv[0],
645                                         EXT2_INODE_SIZE(current_fs->super))) {
646                 free(inode_buf);
647                 return;
648         }
649
650         dump_inode(inode, inode_buf);
651         free(inode_buf);
652         return;
653 }
654
655 void do_chroot(int argc, char *argv[])
656 {
657         ext2_ino_t inode;
658         int retval;
659
660         if (common_inode_args_process(argc, argv, &inode, 0))
661                 return;
662
663         retval = ext2fs_check_directory(current_fs, inode);
664         if (retval)  {
665                 com_err(argv[1], retval, 0);
666                 return;
667         }
668         root = inode;
669 }
670
671 void do_clri(int argc, char *argv[])
672 {
673         ext2_ino_t inode;
674         struct ext2_inode inode_buf;
675
676         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
677                 return;
678
679         if (debugfs_read_inode(inode, &inode_buf, argv[0]))
680                 return;
681         memset(&inode_buf, 0, sizeof(inode_buf));
682         if (debugfs_write_inode(inode, &inode_buf, argv[0]))
683                 return;
684 }
685
686 void do_freei(int argc, char *argv[])
687 {
688         ext2_ino_t inode;
689
690         if (common_inode_args_process(argc, argv, &inode,
691                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
692                 return;
693
694         if (!ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
695                 com_err(argv[0], 0, "Warning: inode already clear");
696         ext2fs_unmark_inode_bitmap(current_fs->inode_map,inode);
697         ext2fs_mark_ib_dirty(current_fs);
698 }
699
700 void do_seti(int argc, char *argv[])
701 {
702         ext2_ino_t inode;
703
704         if (common_inode_args_process(argc, argv, &inode,
705                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
706                 return;
707
708         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
709                 com_err(argv[0], 0, "Warning: inode already set");
710         ext2fs_mark_inode_bitmap(current_fs->inode_map,inode);
711         ext2fs_mark_ib_dirty(current_fs);
712 }
713
714 void do_testi(int argc, char *argv[])
715 {
716         ext2_ino_t inode;
717
718         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_BITMAPS))
719                 return;
720
721         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
722                 printf("Inode %u is marked in use\n", inode);
723         else
724                 printf("Inode %u is not in use\n", inode);
725 }
726
727 void do_freeb(int argc, char *argv[])
728 {
729         blk_t block;
730         blk_t count = 1;
731
732         if (common_block_args_process(argc, argv, &block, &count))
733                 return;
734         if (check_fs_read_write(argv[0]))
735                 return;
736         while (count-- > 0) {
737                 if (!ext2fs_test_block_bitmap(current_fs->block_map,block))
738                         com_err(argv[0], 0, "Warning: block %u already clear",
739                                 block);
740                 ext2fs_unmark_block_bitmap(current_fs->block_map,block);
741                 block++;
742         }
743         ext2fs_mark_bb_dirty(current_fs);
744 }
745
746 void do_setb(int argc, char *argv[])
747 {
748         blk_t block;
749         blk_t count = 1;
750
751         if (common_block_args_process(argc, argv, &block, &count))
752                 return;
753         if (check_fs_read_write(argv[0]))
754                 return;
755         while (count-- > 0) {
756                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
757                         com_err(argv[0], 0, "Warning: block %u already set",
758                                 block);
759                 ext2fs_mark_block_bitmap(current_fs->block_map,block);
760                 block++;
761         }
762         ext2fs_mark_bb_dirty(current_fs);
763 }
764
765 void do_testb(int argc, char *argv[])
766 {
767         blk_t block;
768         blk_t count = 1;
769
770         if (common_block_args_process(argc, argv, &block, &count))
771                 return;
772         while (count-- > 0) {
773                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
774                         printf("Block %u marked in use\n", block);
775                 else
776                         printf("Block %u not in use\n", block);
777                 block++;
778         }
779 }
780
781 static void modify_u8(char *com, const char *prompt,
782                       const char *format, __u8 *val)
783 {
784         char buf[200];
785         unsigned long v;
786         char *tmp;
787
788         sprintf(buf, format, *val);
789         printf("%30s    [%s] ", prompt, buf);
790         if (!fgets(buf, sizeof(buf), stdin))
791                 return;
792         if (buf[strlen (buf) - 1] == '\n')
793                 buf[strlen (buf) - 1] = '\0';
794         if (!buf[0])
795                 return;
796         v = strtoul(buf, &tmp, 0);
797         if (*tmp)
798                 com_err(com, 0, "Bad value - %s", buf);
799         else
800                 *val = v;
801 }
802
803 static void modify_u16(char *com, const char *prompt,
804                        const char *format, __u16 *val)
805 {
806         char buf[200];
807         unsigned long v;
808         char *tmp;
809
810         sprintf(buf, format, *val);
811         printf("%30s    [%s] ", prompt, buf);
812         if (!fgets(buf, sizeof(buf), stdin))
813                 return;
814         if (buf[strlen (buf) - 1] == '\n')
815                 buf[strlen (buf) - 1] = '\0';
816         if (!buf[0])
817                 return;
818         v = strtoul(buf, &tmp, 0);
819         if (*tmp)
820                 com_err(com, 0, "Bad value - %s", buf);
821         else
822                 *val = v;
823 }
824
825 static void modify_u32(char *com, const char *prompt,
826                        const char *format, __u32 *val)
827 {
828         char buf[200];
829         unsigned long v;
830         char *tmp;
831
832         sprintf(buf, format, *val);
833         printf("%30s    [%s] ", prompt, buf);
834         if (!fgets(buf, sizeof(buf), stdin))
835                 return;
836         if (buf[strlen (buf) - 1] == '\n')
837                 buf[strlen (buf) - 1] = '\0';
838         if (!buf[0])
839                 return;
840         v = strtoul(buf, &tmp, 0);
841         if (*tmp)
842                 com_err(com, 0, "Bad value - %s", buf);
843         else
844                 *val = v;
845 }
846
847
848 void do_modify_inode(int argc, char *argv[])
849 {
850         struct ext2_inode inode;
851         ext2_ino_t      inode_num;
852         int             i;
853         unsigned char   *frag, *fsize;
854         char            buf[80];
855         int             os;
856         const char      *hex_format = "0x%x";
857         const char      *octal_format = "0%o";
858         const char      *decimal_format = "%d";
859         const char      *unsignedlong_format = "%lu";
860         
861         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
862                 return;
863
864         os = current_fs->super->s_creator_os;
865
866         if (debugfs_read_inode(inode_num, &inode, argv[1]))
867                 return;
868         
869         modify_u16(argv[0], "Mode", octal_format, &inode.i_mode);
870         modify_u16(argv[0], "User ID", decimal_format, &inode.i_uid);
871         modify_u16(argv[0], "Group ID", decimal_format, &inode.i_gid);
872         modify_u32(argv[0], "Size", unsignedlong_format, &inode.i_size);
873         modify_u32(argv[0], "Creation time", decimal_format, &inode.i_ctime);
874         modify_u32(argv[0], "Modification time", decimal_format, &inode.i_mtime);
875         modify_u32(argv[0], "Access time", decimal_format, &inode.i_atime);
876         modify_u32(argv[0], "Deletion time", decimal_format, &inode.i_dtime);
877         modify_u16(argv[0], "Link count", decimal_format, &inode.i_links_count);
878         if (os == EXT2_OS_LINUX)
879                 modify_u16(argv[0], "Block count high", unsignedlong_format, 
880                            &inode.osd2.linux2.l_i_blocks_hi);
881         modify_u32(argv[0], "Block count", unsignedlong_format, &inode.i_blocks);
882         modify_u32(argv[0], "File flags", hex_format, &inode.i_flags);
883         modify_u32(argv[0], "Generation", hex_format, &inode.i_generation);
884 #if 0
885         modify_u32(argv[0], "Reserved1", decimal_format, &inode.i_reserved1);
886 #endif
887         modify_u32(argv[0], "File acl", decimal_format, &inode.i_file_acl);
888         if (LINUX_S_ISDIR(inode.i_mode))
889                 modify_u32(argv[0], "Directory acl", decimal_format, &inode.i_dir_acl);
890         else
891                 modify_u32(argv[0], "High 32bits of size", decimal_format, &inode.i_size_high);
892
893         if (os == EXT2_OS_HURD)
894                 modify_u32(argv[0], "Translator Block",
895                             decimal_format, &inode.osd1.hurd1.h_i_translator);
896         
897         modify_u32(argv[0], "Fragment address", decimal_format, &inode.i_faddr);
898         switch (os) {
899             case EXT2_OS_HURD:
900                 frag = &inode.osd2.hurd2.h_i_frag;
901                 fsize = &inode.osd2.hurd2.h_i_fsize;
902                 break;
903             default:
904                 frag = fsize = 0;
905         }
906         if (frag)
907                 modify_u8(argv[0], "Fragment number", decimal_format, frag);
908         if (fsize)
909                 modify_u8(argv[0], "Fragment size", decimal_format, fsize);
910
911         for (i=0;  i < EXT2_NDIR_BLOCKS; i++) {
912                 sprintf(buf, "Direct Block #%d", i);
913                 modify_u32(argv[0], buf, decimal_format, &inode.i_block[i]);
914         }
915         modify_u32(argv[0], "Indirect Block", decimal_format,
916                     &inode.i_block[EXT2_IND_BLOCK]);    
917         modify_u32(argv[0], "Double Indirect Block", decimal_format,
918                     &inode.i_block[EXT2_DIND_BLOCK]);
919         modify_u32(argv[0], "Triple Indirect Block", decimal_format,
920                     &inode.i_block[EXT2_TIND_BLOCK]);
921         if (debugfs_write_inode(inode_num, &inode, argv[1]))
922                 return;
923 }
924
925 void do_change_working_dir(int argc, char *argv[])
926 {
927         ext2_ino_t      inode;
928         int             retval;
929         
930         if (common_inode_args_process(argc, argv, &inode, 0))
931                 return;
932
933         retval = ext2fs_check_directory(current_fs, inode);
934         if (retval) {
935                 com_err(argv[1], retval, 0);
936                 return;
937         }
938         cwd = inode;
939         return;
940 }
941
942 void do_print_working_directory(int argc, char *argv[])
943 {
944         int     retval;
945         char    *pathname = NULL;
946         
947         if (common_args_process(argc, argv, 1, 1,
948                                 "print_working_directory", "", 0))
949                 return;
950
951         retval = ext2fs_get_pathname(current_fs, cwd, 0, &pathname);
952         if (retval) {
953                 com_err(argv[0], retval,
954                         "while trying to get pathname of cwd");
955         }
956         printf("[pwd]   INODE: %6u  PATH: %s\n",
957                cwd, pathname ? pathname : "NULL");
958         if (pathname) {
959                 free(pathname);
960                 pathname = NULL;
961         }
962         retval = ext2fs_get_pathname(current_fs, root, 0, &pathname);
963         if (retval) {
964                 com_err(argv[0], retval,
965                         "while trying to get pathname of root");
966         }
967         printf("[root]  INODE: %6u  PATH: %s\n",
968                root, pathname ? pathname : "NULL");
969         if (pathname) {
970                 free(pathname);
971                 pathname = NULL;
972         }
973         return;
974 }
975
976 /*
977  * Given a mode, return the ext2 file type
978  */
979 static int ext2_file_type(unsigned int mode)
980 {
981         if (LINUX_S_ISREG(mode))
982                 return EXT2_FT_REG_FILE;
983
984         if (LINUX_S_ISDIR(mode))
985                 return EXT2_FT_DIR;
986         
987         if (LINUX_S_ISCHR(mode))
988                 return EXT2_FT_CHRDEV;
989         
990         if (LINUX_S_ISBLK(mode))
991                 return EXT2_FT_BLKDEV;
992         
993         if (LINUX_S_ISLNK(mode))
994                 return EXT2_FT_SYMLINK;
995
996         if (LINUX_S_ISFIFO(mode))
997                 return EXT2_FT_FIFO;
998         
999         if (LINUX_S_ISSOCK(mode))
1000                 return EXT2_FT_SOCK;
1001         
1002         return 0;
1003 }
1004
1005 static void make_link(char *sourcename, char *destname)
1006 {
1007         ext2_ino_t      ino;
1008         struct ext2_inode inode;
1009         int             retval;
1010         ext2_ino_t      dir;
1011         char            *dest, *cp, *base_name;
1012
1013         /*
1014          * Get the source inode
1015          */
1016         ino = string_to_inode(sourcename);
1017         if (!ino)
1018                 return;
1019         base_name = strrchr(sourcename, '/');
1020         if (base_name)
1021                 base_name++;
1022         else
1023                 base_name = sourcename;
1024         /*
1025          * Figure out the destination.  First see if it exists and is
1026          * a directory.  
1027          */
1028         if (! (retval=ext2fs_namei(current_fs, root, cwd, destname, &dir)))
1029                 dest = base_name;
1030         else {
1031                 /*
1032                  * OK, it doesn't exist.  See if it is
1033                  * '<dir>/basename' or 'basename'
1034                  */
1035                 cp = strrchr(destname, '/');
1036                 if (cp) {
1037                         *cp = 0;
1038                         dir = string_to_inode(destname);
1039                         if (!dir)
1040                                 return;
1041                         dest = cp+1;
1042                 } else {
1043                         dir = cwd;
1044                         dest = destname;
1045                 }
1046         }
1047
1048         if (debugfs_read_inode(ino, &inode, sourcename))
1049                 return;
1050         
1051         retval = ext2fs_link(current_fs, dir, dest, ino, 
1052                              ext2_file_type(inode.i_mode));
1053         if (retval)
1054                 com_err("make_link", retval, 0);
1055         return;
1056 }
1057
1058
1059 void do_link(int argc, char *argv[])
1060 {
1061         if (common_args_process(argc, argv, 3, 3, "link",
1062                                 "<source file> <dest_name>", CHECK_FS_RW))
1063                 return;
1064
1065         make_link(argv[1], argv[2]);
1066 }
1067
1068 static int mark_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1069                             int blockcnt EXT2FS_ATTR((unused)), 
1070                             void *private EXT2FS_ATTR((unused)))
1071 {
1072         blk_t   block;
1073
1074         block = *blocknr;
1075         ext2fs_block_alloc_stats(fs, block, +1);
1076         return 0;
1077 }
1078
1079 void do_undel(int argc, char *argv[])
1080 {
1081         ext2_ino_t      ino;
1082         struct ext2_inode inode;
1083
1084         if (common_args_process(argc, argv, 2, 3, "undelete",
1085                                 "<inode_num> [dest_name]",
1086                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1087                 return;
1088
1089         ino = string_to_inode(argv[1]);
1090         if (!ino)
1091                 return;
1092
1093         if (debugfs_read_inode(ino, &inode, argv[1]))
1094                 return;
1095
1096         if (ext2fs_test_inode_bitmap(current_fs->inode_map, ino)) {
1097                 com_err(argv[1], 0, "Inode is not marked as deleted");
1098                 return;
1099         }
1100
1101         /*
1102          * XXX this function doesn't handle changing the links count on the
1103          * parent directory when undeleting a directory.  
1104          */
1105         inode.i_links_count = LINUX_S_ISDIR(inode.i_mode) ? 2 : 1;
1106         inode.i_dtime = 0;
1107
1108         if (debugfs_write_inode(ino, &inode, argv[0]))
1109                 return;
1110
1111         ext2fs_block_iterate(current_fs, ino, BLOCK_FLAG_READ_ONLY, NULL,
1112                              mark_blocks_proc, NULL);
1113
1114         ext2fs_inode_alloc_stats2(current_fs, ino, +1, 0);
1115
1116         if (argc > 2)
1117                 make_link(argv[1], argv[2]);
1118 }
1119
1120 static void unlink_file_by_name(char *filename)
1121 {
1122         int             retval;
1123         ext2_ino_t      dir;
1124         char            *base_name;
1125         
1126         base_name = strrchr(filename, '/');
1127         if (base_name) {
1128                 *base_name++ = '\0';
1129                 dir = string_to_inode(filename);
1130                 if (!dir)
1131                         return;
1132         } else {
1133                 dir = cwd;
1134                 base_name = filename;
1135         }
1136         retval = ext2fs_unlink(current_fs, dir, base_name, 0, 0);
1137         if (retval)
1138                 com_err("unlink_file_by_name", retval, 0);
1139         return;
1140 }
1141
1142 void do_unlink(int argc, char *argv[])
1143 {
1144         if (common_args_process(argc, argv, 2, 2, "link",
1145                                 "<pathname>", CHECK_FS_RW))
1146                 return;
1147
1148         unlink_file_by_name(argv[1]);
1149 }
1150
1151 void do_find_free_block(int argc, char *argv[])
1152 {
1153         blk_t   free_blk, goal;
1154         int             count;
1155         errcode_t       retval;
1156         char            *tmp;
1157         
1158         if ((argc > 3) || (argc==2 && *argv[1] == '?')) {
1159                 com_err(argv[0], 0, "Usage: find_free_block [count [goal]]");
1160                 return;
1161         }
1162         if (check_fs_open(argv[0]))
1163                 return;
1164
1165         if (argc > 1) {
1166                 count = strtol(argv[1],&tmp,0);
1167                 if (*tmp) {
1168                         com_err(argv[0], 0, "Bad count - %s", argv[1]);
1169                         return;
1170                 }
1171         } else
1172                 count = 1;
1173
1174         if (argc > 2) {
1175                 goal = strtol(argv[2], &tmp, 0);
1176                 if (*tmp) {
1177                         com_err(argv[0], 0, "Bad goal - %s", argv[1]);
1178                         return;
1179                 }
1180         }
1181         else
1182                 goal = current_fs->super->s_first_data_block;
1183
1184         printf("Free blocks found: ");
1185         free_blk = goal - 1;    
1186         while (count-- > 0) {
1187                 retval = ext2fs_new_block(current_fs, free_blk + 1, 0,
1188                                           &free_blk);
1189                 if (retval) {
1190                         com_err("ext2fs_new_block", retval, 0);
1191                         return;
1192                 } else
1193                         printf("%u ", free_blk);
1194         }
1195         printf("\n");
1196 }
1197
1198 void do_find_free_inode(int argc, char *argv[])
1199 {
1200         ext2_ino_t      free_inode, dir;
1201         int             mode;
1202         int             retval;
1203         char            *tmp;
1204         
1205         if (argc > 3 || (argc>1 && *argv[1] == '?')) {
1206                 com_err(argv[0], 0, "Usage: find_free_inode [dir] [mode]");
1207                 return;
1208         }
1209         if (check_fs_open(argv[0]))
1210                 return;
1211
1212         if (argc > 1) {
1213                 dir = strtol(argv[1], &tmp, 0);
1214                 if (*tmp) {
1215                         com_err(argv[0], 0, "Bad dir - %s", argv[1]);
1216                         return;
1217                 }
1218         }
1219         else
1220                 dir = root;
1221         if (argc > 2) {
1222                 mode = strtol(argv[2], &tmp, 0);
1223                 if (*tmp) {
1224                         com_err(argv[0], 0, "Bad mode - %s", argv[2]);
1225                         return;
1226                 }
1227         } else
1228                 mode = 010755;
1229
1230         retval = ext2fs_new_inode(current_fs, dir, mode, 0, &free_inode);
1231         if (retval)
1232                 com_err("ext2fs_new_inode", retval, 0);
1233         else
1234                 printf("Free inode found: %u\n", free_inode);
1235 }
1236
1237 static errcode_t copy_file(int fd, ext2_ino_t newfile)
1238 {
1239         ext2_file_t     e2_file;
1240         errcode_t       retval;
1241         int             got;
1242         unsigned int    written;
1243         char            buf[8192];
1244         char            *ptr;
1245
1246         retval = ext2fs_file_open(current_fs, newfile,
1247                                   EXT2_FILE_WRITE, &e2_file);
1248         if (retval)
1249                 return retval;
1250
1251         while (1) {
1252                 got = read(fd, buf, sizeof(buf));
1253                 if (got == 0)
1254                         break;
1255                 if (got < 0) {
1256                         retval = errno;
1257                         goto fail;
1258                 }
1259                 ptr = buf;
1260                 while (got > 0) {
1261                         retval = ext2fs_file_write(e2_file, ptr,
1262                                                    got, &written);
1263                         if (retval)
1264                                 goto fail;
1265
1266                         got -= written;
1267                         ptr += written;
1268                 }
1269         }
1270         retval = ext2fs_file_close(e2_file);
1271         return retval;
1272
1273 fail:
1274         (void) ext2fs_file_close(e2_file);
1275         return retval;
1276 }
1277
1278
1279 void do_write(int argc, char *argv[])
1280 {
1281         int             fd;
1282         struct stat     statbuf;
1283         ext2_ino_t      newfile;
1284         errcode_t       retval;
1285         struct ext2_inode inode;
1286
1287         if (common_args_process(argc, argv, 3, 3, "write",
1288                                 "<native file> <new file>", CHECK_FS_RW))
1289                 return;
1290
1291         fd = open(argv[1], O_RDONLY);
1292         if (fd < 0) {
1293                 com_err(argv[1], errno, 0);
1294                 return;
1295         }
1296         if (fstat(fd, &statbuf) < 0) {
1297                 com_err(argv[1], errno, 0);
1298                 close(fd);
1299                 return;
1300         }
1301
1302         retval = ext2fs_namei(current_fs, root, cwd, argv[2], &newfile);
1303         if (retval == 0) {
1304                 com_err(argv[0], 0, "The file '%s' already exists\n", argv[2]);
1305                 close(fd);
1306                 return;
1307         }
1308
1309         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1310         if (retval) {
1311                 com_err(argv[0], retval, 0);
1312                 close(fd);
1313                 return;
1314         }
1315         printf("Allocated inode: %u\n", newfile);
1316         retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1317                              EXT2_FT_REG_FILE);
1318         if (retval == EXT2_ET_DIR_NO_SPACE) {
1319                 retval = ext2fs_expand_dir(current_fs, cwd);
1320                 if (retval) {
1321                         com_err(argv[0], retval, "while expanding directory");
1322                         return;
1323                 }
1324                 retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1325                                      EXT2_FT_REG_FILE);
1326         }
1327         if (retval) {
1328                 com_err(argv[2], retval, 0);
1329                 close(fd);
1330                 return;
1331         }
1332         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1333                 com_err(argv[0], 0, "Warning: inode already set");
1334         ext2fs_inode_alloc_stats2(current_fs, newfile, +1, 0);
1335         memset(&inode, 0, sizeof(inode));
1336         inode.i_mode = (statbuf.st_mode & ~LINUX_S_IFMT) | LINUX_S_IFREG;
1337         inode.i_atime = inode.i_ctime = inode.i_mtime = 
1338                 current_fs->now ? current_fs->now : time(0);
1339         inode.i_links_count = 1;
1340         inode.i_size = statbuf.st_size;
1341         if (debugfs_write_new_inode(newfile, &inode, argv[0])) {
1342                 close(fd);
1343                 return;
1344         }
1345         if (LINUX_S_ISREG(inode.i_mode)) {
1346                 retval = copy_file(fd, newfile);
1347                 if (retval)
1348                         com_err("copy_file", retval, 0);
1349         }
1350         close(fd);
1351 }
1352
1353 void do_mknod(int argc, char *argv[])
1354 {
1355         unsigned long   mode, major, minor;
1356         ext2_ino_t      newfile;
1357         errcode_t       retval;
1358         struct ext2_inode inode;
1359         int             filetype, nr;
1360
1361         if (check_fs_open(argv[0]))
1362                 return;
1363         if (argc < 3 || argv[2][1]) {
1364         usage:
1365                 com_err(argv[0], 0, "Usage: mknod <name> [p| [c|b] <major> <minor>]");
1366                 return;
1367         }
1368         mode = minor = major = 0;
1369         switch (argv[2][0]) {
1370                 case 'p':
1371                         mode = LINUX_S_IFIFO;
1372                         filetype = EXT2_FT_FIFO;
1373                         nr = 3;
1374                         break;
1375                 case 'c':
1376                         mode = LINUX_S_IFCHR;
1377                         filetype = EXT2_FT_CHRDEV;
1378                         nr = 5;
1379                         break;
1380                 case 'b':
1381                         mode = LINUX_S_IFBLK;
1382                         filetype = EXT2_FT_BLKDEV;
1383                         nr = 5;
1384                         break;
1385                 default:
1386                         filetype = 0;
1387                         nr = 0;
1388         }
1389         if (nr == 5) {
1390                 major = strtoul(argv[3], argv+3, 0);
1391                 minor = strtoul(argv[4], argv+4, 0);
1392                 if (major > 65535 || minor > 65535 || argv[3][0] || argv[4][0])
1393                         nr = 0;
1394         }
1395         if (argc != nr)
1396                 goto usage;
1397         if (check_fs_read_write(argv[0]))
1398                 return;
1399         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1400         if (retval) {
1401                 com_err(argv[0], retval, 0);
1402                 return;
1403         }
1404         printf("Allocated inode: %u\n", newfile);
1405         retval = ext2fs_link(current_fs, cwd, argv[1], newfile, filetype);
1406         if (retval == EXT2_ET_DIR_NO_SPACE) {
1407                 retval = ext2fs_expand_dir(current_fs, cwd);
1408                 if (retval) {
1409                         com_err(argv[0], retval, "while expanding directory");
1410                         return;
1411                 }
1412                 retval = ext2fs_link(current_fs, cwd, argv[1], newfile,
1413                                      filetype);
1414         }
1415         if (retval) {
1416                 com_err(argv[1], retval, 0);
1417                 return;
1418         }
1419         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1420                 com_err(argv[0], 0, "Warning: inode already set");
1421         ext2fs_mark_inode_bitmap(current_fs->inode_map, newfile);
1422         ext2fs_mark_ib_dirty(current_fs);
1423         memset(&inode, 0, sizeof(inode));
1424         inode.i_mode = mode;
1425         inode.i_atime = inode.i_ctime = inode.i_mtime = 
1426                 current_fs->now ? current_fs->now : time(0);
1427         if ((major < 256) && (minor < 256)) {
1428                 inode.i_block[0] = major*256+minor;
1429                 inode.i_block[1] = 0;
1430         } else {
1431                 inode.i_block[0] = 0;
1432                 inode.i_block[1] = (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
1433         }
1434         inode.i_links_count = 1;
1435         if (debugfs_write_new_inode(newfile, &inode, argv[0]))
1436                 return;
1437 }
1438
1439 void do_mkdir(int argc, char *argv[])
1440 {
1441         char    *cp;
1442         ext2_ino_t      parent;
1443         char    *name;
1444         errcode_t retval;
1445
1446         if (common_args_process(argc, argv, 2, 2, "mkdir",
1447                                 "<filename>", CHECK_FS_RW))
1448                 return;
1449
1450         cp = strrchr(argv[1], '/');
1451         if (cp) {
1452                 *cp = 0;
1453                 parent = string_to_inode(argv[1]);
1454                 if (!parent) {
1455                         com_err(argv[1], ENOENT, 0);
1456                         return;
1457                 }
1458                 name = cp+1;
1459         } else {
1460                 parent = cwd;
1461                 name = argv[1];
1462         }
1463
1464 try_again:
1465         retval = ext2fs_mkdir(current_fs, parent, 0, name);
1466         if (retval == EXT2_ET_DIR_NO_SPACE) {
1467                 retval = ext2fs_expand_dir(current_fs, parent);
1468                 if (retval) {
1469                         com_err("argv[0]", retval, "while expanding directory");
1470                         return;
1471                 }
1472                 goto try_again;
1473         }
1474         if (retval) {
1475                 com_err("ext2fs_mkdir", retval, 0);
1476                 return;
1477         }
1478
1479 }
1480
1481 static int release_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1482                                int blockcnt EXT2FS_ATTR((unused)), 
1483                                void *private EXT2FS_ATTR((unused)))
1484 {
1485         blk_t   block;
1486
1487         block = *blocknr;
1488         ext2fs_block_alloc_stats(fs, block, -1);
1489         return 0;
1490 }
1491
1492 static void kill_file_by_inode(ext2_ino_t inode)
1493 {
1494         struct ext2_inode inode_buf;
1495
1496         if (debugfs_read_inode(inode, &inode_buf, 0))
1497                 return;
1498         inode_buf.i_dtime = current_fs->now ? current_fs->now : time(0);
1499         if (debugfs_write_inode(inode, &inode_buf, 0))
1500                 return;
1501         if (!ext2fs_inode_has_valid_blocks(&inode_buf))
1502                 return;
1503
1504         ext2fs_block_iterate(current_fs, inode, BLOCK_FLAG_READ_ONLY, NULL,
1505                              release_blocks_proc, NULL);
1506         printf("\n");
1507         ext2fs_inode_alloc_stats2(current_fs, inode, -1,
1508                                   LINUX_S_ISDIR(inode_buf.i_mode));
1509 }
1510
1511
1512 void do_kill_file(int argc, char *argv[])
1513 {
1514         ext2_ino_t inode_num;
1515
1516         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1517                 return;
1518
1519         kill_file_by_inode(inode_num);
1520 }
1521
1522 void do_rm(int argc, char *argv[])
1523 {
1524         int retval;
1525         ext2_ino_t inode_num;
1526         struct ext2_inode inode;
1527
1528         if (common_args_process(argc, argv, 2, 2, "rm",
1529                                 "<filename>", CHECK_FS_RW))
1530                 return;
1531
1532         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1533         if (retval) {
1534                 com_err(argv[0], retval, "while trying to resolve filename");
1535                 return;
1536         }
1537
1538         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1539                 return;
1540
1541         if (LINUX_S_ISDIR(inode.i_mode)) {
1542                 com_err(argv[0], 0, "file is a directory");
1543                 return;
1544         }
1545
1546         --inode.i_links_count;
1547         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1548                 return;
1549
1550         unlink_file_by_name(argv[1]);
1551         if (inode.i_links_count == 0)
1552                 kill_file_by_inode(inode_num);
1553 }
1554
1555 struct rd_struct {
1556         ext2_ino_t      parent;
1557         int             empty;
1558 };
1559
1560 static int rmdir_proc(ext2_ino_t dir EXT2FS_ATTR((unused)),
1561                       int       entry EXT2FS_ATTR((unused)),
1562                       struct ext2_dir_entry *dirent,
1563                       int       offset EXT2FS_ATTR((unused)),
1564                       int       blocksize EXT2FS_ATTR((unused)),
1565                       char      *buf EXT2FS_ATTR((unused)),
1566                       void      *private)
1567 {
1568         struct rd_struct *rds = (struct rd_struct *) private;
1569
1570         if (dirent->inode == 0)
1571                 return 0;
1572         if (((dirent->name_len&0xFF) == 1) && (dirent->name[0] == '.'))
1573                 return 0;
1574         if (((dirent->name_len&0xFF) == 2) && (dirent->name[0] == '.') &&
1575             (dirent->name[1] == '.')) {
1576                 rds->parent = dirent->inode;
1577                 return 0;
1578         }
1579         rds->empty = 0;
1580         return 0;
1581 }
1582         
1583 void do_rmdir(int argc, char *argv[])
1584 {
1585         int retval;
1586         ext2_ino_t inode_num;
1587         struct ext2_inode inode;
1588         struct rd_struct rds;
1589
1590         if (common_args_process(argc, argv, 2, 2, "rmdir",
1591                                 "<filename>", CHECK_FS_RW))
1592                 return;
1593
1594         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1595         if (retval) {
1596                 com_err(argv[0], retval, "while trying to resolve filename");
1597                 return;
1598         }
1599
1600         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1601                 return;
1602
1603         if (!LINUX_S_ISDIR(inode.i_mode)) {
1604                 com_err(argv[0], 0, "file is not a directory");
1605                 return;
1606         }
1607
1608         rds.parent = 0;
1609         rds.empty = 1;
1610
1611         retval = ext2fs_dir_iterate2(current_fs, inode_num, 0,
1612                                     0, rmdir_proc, &rds);
1613         if (retval) {
1614                 com_err(argv[0], retval, "while iterating over directory");
1615                 return;
1616         }
1617         if (rds.empty == 0) {
1618                 com_err(argv[0], 0, "directory not empty");
1619                 return;
1620         }
1621
1622         inode.i_links_count = 0;
1623         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1624                 return;
1625
1626         unlink_file_by_name(argv[1]);
1627         kill_file_by_inode(inode_num);
1628
1629         if (rds.parent) {
1630                 if (debugfs_read_inode(rds.parent, &inode, argv[0]))
1631                         return;
1632                 if (inode.i_links_count > 1)
1633                         inode.i_links_count--;
1634                 if (debugfs_write_inode(rds.parent, &inode, argv[0]))
1635                         return;
1636         }
1637 }
1638
1639 void do_show_debugfs_params(int argc EXT2FS_ATTR((unused)), 
1640                             char *argv[] EXT2FS_ATTR((unused)))
1641 {
1642         FILE *out = stdout;
1643
1644         if (current_fs)
1645                 fprintf(out, "Open mode: read-%s\n",
1646                         current_fs->flags & EXT2_FLAG_RW ? "write" : "only");
1647         fprintf(out, "Filesystem in use: %s\n",
1648                 current_fs ? current_fs->device_name : "--none--");
1649 }
1650
1651 void do_expand_dir(int argc, char *argv[])
1652 {
1653         ext2_ino_t inode;
1654         int retval;
1655
1656         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1657                 return;
1658
1659         retval = ext2fs_expand_dir(current_fs, inode);
1660         if (retval)
1661                 com_err("ext2fs_expand_dir", retval, 0);
1662         return;
1663 }
1664
1665 void do_features(int argc, char *argv[])
1666 {
1667         int     i;
1668         
1669         if (check_fs_open(argv[0]))
1670                 return;
1671
1672         if ((argc != 1) && check_fs_read_write(argv[0]))
1673                 return;
1674         for (i=1; i < argc; i++) {
1675                 if (e2p_edit_feature(argv[i],
1676                                      &current_fs->super->s_feature_compat, 0))
1677                         com_err(argv[0], 0, "Unknown feature: %s\n",
1678                                 argv[i]);
1679                 else
1680                         ext2fs_mark_super_dirty(current_fs);
1681         }
1682         print_features(current_fs->super, stdout);
1683 }
1684
1685 void do_bmap(int argc, char *argv[])
1686 {
1687         ext2_ino_t      ino;
1688         blk_t           blk, pblk;
1689         int             err;
1690         errcode_t       errcode;
1691         
1692         if (common_args_process(argc, argv, 3, 3, argv[0],
1693                                 "<file> logical_blk", 0))
1694                 return;
1695
1696         ino = string_to_inode(argv[1]);
1697         if (!ino)
1698                 return;
1699         blk = parse_ulong(argv[2], argv[0], "logical_block", &err);
1700
1701         errcode = ext2fs_bmap(current_fs, ino, 0, 0, 0, blk, &pblk);
1702         if (errcode) {
1703                 com_err("argv[0]", errcode,
1704                         "while mapping logical block %u\n", blk);
1705                 return;
1706         }
1707         printf("%u\n", pblk);
1708 }
1709
1710 void do_imap(int argc, char *argv[])
1711 {
1712         ext2_ino_t      ino;
1713         unsigned long   group, block, block_nr, offset;
1714
1715         if (common_args_process(argc, argv, 2, 2, argv[0],
1716                                 "<file>", 0))
1717                 return;
1718         ino = string_to_inode(argv[1]);
1719         if (!ino)
1720                 return;
1721
1722         group = (ino - 1) / EXT2_INODES_PER_GROUP(current_fs->super);
1723         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(current_fs->super)) *
1724                 EXT2_INODE_SIZE(current_fs->super);
1725         block = offset >> EXT2_BLOCK_SIZE_BITS(current_fs->super);
1726         if (!current_fs->group_desc[(unsigned)group].bg_inode_table) {
1727                 com_err(argv[0], 0, "Inode table for group %lu is missing\n",
1728                         group);
1729                 return;
1730         }
1731         block_nr = current_fs->group_desc[(unsigned)group].bg_inode_table + 
1732                 block;
1733         offset &= (EXT2_BLOCK_SIZE(current_fs->super) - 1);
1734
1735         printf("Inode %d is part of block group %lu\n"
1736                "\tlocated at block %lu, offset 0x%04lx\n", ino, group,
1737                block_nr, offset);
1738
1739 }
1740
1741 void do_set_current_time(int argc, char *argv[])
1742 {
1743         time_t now;
1744
1745         if (common_args_process(argc, argv, 2, 2, argv[0],
1746                                 "<time>", 0))
1747                 return;
1748
1749         now = string_to_time(argv[1]);
1750         if (now == ((time_t) -1)) {
1751                 com_err(argv[0], 0, "Couldn't parse argument as a time: %s\n",
1752                         argv[1]);
1753                 return;
1754
1755         } else {
1756                 printf("Setting current time to %s\n", time_to_string(now));
1757                 current_fs->now = now;
1758         }
1759 }
1760
1761 static int source_file(const char *cmd_file, int sci_idx)
1762 {
1763         FILE            *f;
1764         char            buf[256];
1765         char            *cp;
1766         int             exit_status = 0;
1767         int             retval;
1768
1769         if (strcmp(cmd_file, "-") == 0)
1770                 f = stdin;
1771         else {
1772                 f = fopen(cmd_file, "r");
1773                 if (!f) {
1774                         perror(cmd_file);
1775                         exit(1);
1776                 }
1777         }
1778         setbuf(stdout, NULL);
1779         setbuf(stderr, NULL);
1780         while (!feof(f)) {
1781                 if (fgets(buf, sizeof(buf), f) == NULL)
1782                         break;
1783                 cp = strchr(buf, '\n');
1784                 if (cp)
1785                         *cp = 0;
1786                 cp = strchr(buf, '\r');
1787                 if (cp)
1788                         *cp = 0;
1789                 printf("debugfs: %s\n", buf);
1790                 retval = ss_execute_line(sci_idx, buf);
1791                 if (retval) {
1792                         ss_perror(sci_idx, retval, buf);
1793                         exit_status++;
1794                 }
1795         }
1796         return exit_status;
1797 }
1798
1799 int main(int argc, char **argv)
1800 {
1801         int             retval;
1802         int             sci_idx;
1803         const char      *usage = "Usage: %s [-b blocksize] [-s superblock] [-f cmd_file] [-R request] [-V] [[-w] [-c] device]";
1804         int             c;
1805         int             open_flags = EXT2_FLAG_SOFTSUPP_FEATURES;
1806         char            *request = 0;
1807         int             exit_status = 0;
1808         char            *cmd_file = 0;
1809         blk_t           superblock = 0;
1810         blk_t           blocksize = 0;
1811         int             catastrophic = 0;
1812         char            *data_filename = 0;
1813         
1814         if (debug_prog_name == 0)
1815                 debug_prog_name = "debugfs";
1816
1817         add_error_table(&et_ext2_error_table);
1818         fprintf (stderr, "%s %s (%s)\n", debug_prog_name,
1819                  E2FSPROGS_VERSION, E2FSPROGS_DATE);
1820
1821         while ((c = getopt (argc, argv, "iwcR:f:b:s:Vd:")) != EOF) {
1822                 switch (c) {
1823                 case 'R':
1824                         request = optarg;
1825                         break;
1826                 case 'f':
1827                         cmd_file = optarg;
1828                         break;
1829                 case 'd':
1830                         data_filename = optarg;
1831                         break;
1832                 case 'i':
1833                         open_flags |= EXT2_FLAG_IMAGE_FILE;
1834                         break;
1835                 case 'w':
1836                         open_flags |= EXT2_FLAG_RW;
1837                         break;
1838                 case 'b':
1839                         blocksize = parse_ulong(optarg, argv[0], 
1840                                                 "block size", 0);
1841                         break;
1842                 case 's':
1843                         superblock = parse_ulong(optarg, argv[0], 
1844                                                  "superblock number", 0);
1845                         break;
1846                 case 'c':
1847                         catastrophic = 1;
1848                         break;
1849                 case 'V':
1850                         /* Print version number and exit */
1851                         fprintf(stderr, "\tUsing %s\n",
1852                                 error_message(EXT2_ET_BASE));
1853                         exit(0);
1854                 default:
1855                         com_err(argv[0], 0, usage, debug_prog_name);
1856                         return 1;
1857                 }
1858         }
1859         if (optind < argc)
1860                 open_filesystem(argv[optind], open_flags,
1861                                 superblock, blocksize, catastrophic,
1862                                 data_filename);
1863         
1864         sci_idx = ss_create_invocation(debug_prog_name, "0.0", (char *) NULL,
1865                                        &debug_cmds, &retval);
1866         if (retval) {
1867                 ss_perror(sci_idx, retval, "creating invocation");
1868                 exit(1);
1869         }
1870         ss_get_readline(sci_idx);
1871
1872         (void) ss_add_request_table (sci_idx, &ss_std_requests, 1, &retval);
1873         if (retval) {
1874                 ss_perror(sci_idx, retval, "adding standard requests");
1875                 exit (1);
1876         }
1877         if (extra_cmds)
1878                 ss_add_request_table (sci_idx, extra_cmds, 1, &retval);
1879         if (retval) {
1880                 ss_perror(sci_idx, retval, "adding extra requests");
1881                 exit (1);
1882         }
1883         if (request) {
1884                 retval = 0;
1885                 retval = ss_execute_line(sci_idx, request);
1886                 if (retval) {
1887                         ss_perror(sci_idx, retval, request);
1888                         exit_status++;
1889                 }
1890         } else if (cmd_file) {
1891                 exit_status = source_file(cmd_file, sci_idx);
1892         } else {
1893                 ss_listen(sci_idx);
1894         }
1895
1896         if (current_fs)
1897                 close_filesystem();
1898         
1899         remove_error_table(&et_ext2_error_table);
1900         return exit_status;
1901 }