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