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