/* -*- C -*- */

/* fibmap.c */

/*
 * Author: Nikita Danilov <NikitaDanilov@yahoo.COM>
 * Keywords: fragmentation, FIBMAP
 *
 * This file is part of fibmap.
 *
 * Fibmap is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statfs.h>

/* kludge to avoid including kernel headers */
/* from include/asm-i386/ioctl.h */

#define _IOC_NRBITS	8
#define _IOC_TYPEBITS	8
#define _IOC_SIZEBITS	14
#define _IOC_DIRBITS	2

#define _IOC_NRSHIFT	0
#define _IOC_TYPESHIFT	(_IOC_NRSHIFT+_IOC_NRBITS)
#define _IOC_SIZESHIFT	(_IOC_TYPESHIFT+_IOC_TYPEBITS)
#define _IOC_DIRSHIFT	(_IOC_SIZESHIFT+_IOC_SIZEBITS)

#define _IOC_WRITE	1U

#define _IOC(dir,type,nr,size) \
	(((dir)  << _IOC_DIRSHIFT) | \
	 ((type) << _IOC_TYPESHIFT) | \
	 ((nr)   << _IOC_NRSHIFT) | \
	 ((size) << _IOC_SIZESHIFT))

#define _IO(type,nr)		_IOC(_IOC_NONE,(type),(nr),0)
#define FIBMAP	   _IO(0x00,1)	/* bmap access */

typedef enum {
	ok = 0,
	argc_error,
	open_error,
	stat_error,
	statfs_error,
	ioctl_error
} ret_t;

static int blocks = 0;
static int show = 0;
static int frag = 0;
static int total = 0;

static unsigned long t_blocks = 0;
static unsigned long t_frags = 0;

ret_t fibmap(char *prefix, char *path)
{
	ret_t result;
	int fd;
	int block_in_file;
	int block_tot;
	int frag_nr;
	int block_prev;

	result = ok;
	frag_nr = 0;
	block_prev = 0;
	fd = open(path, O_RDONLY);
	if (fd != -1) {
		struct stat stat;
		struct statfs statfs;

		if (fstat(fd, &stat) != -1) {
			if (fstatfs(fd, &statfs) != -1) {
				if (stat.st_size > 0) {
					block_tot = (stat.st_size + statfs.f_bsize - 1) / statfs.f_bsize;
				} else
					block_tot = 0;
			} else {
				fprintf(stderr,
					"%s: cannot statfs `%s': %s(%i)\n",
					prefix, path,
					strerror(errno), errno);
				result = statfs_error;
			}
		} else {
			fprintf (stderr, "%s: cannot stat `%s': %s(%i)\n",
				 prefix, path, strerror(errno), errno);
			result = stat_error;
		}
	} else {
		fprintf(stderr, "%s: cannot open `%s': %s(%i)\n",
			prefix, path, strerror(errno), errno);
		return open_error;
	}

	for (block_in_file = 0 ;
	     result == ok && block_in_file < block_tot ; ++ block_in_file) {
		int block;

		block = block_in_file;
		if (ioctl(fd, FIBMAP, &block) == -1) {
			fprintf (stderr, "%s: ioctl(%s) fails: %s(%i)\n",
				 prefix, path, strerror(errno), errno);
			result = ioctl_error;
		} else {
			int hit;

			if (block != 0 &&
			    block_prev != 0 && block != block_prev + 1)
				hit = 1;
			else
				hit = 0;
			if (blocks) {
				printf("B %c %i", hit ? '!' : '.', block);
				if (show)
					printf(" %s", path);
				printf("\n");
			}
			frag_nr += hit;
		}
		block_prev = block;
	}
	if (frag) {
		printf("F %u %u %f", block_tot, frag_nr,
		       block_tot ? ((double)frag_nr) / block_tot : 0.0);
		if (show)
			printf(" %s", path);
		printf("\n");
	}
	t_blocks += block_tot;
	t_frags  += frag_nr;
	close(fd);
	return result;
}

static void usage(const char *argv0)
{
	fprintf(stderr, "Usage: %s -0 -h\n", argv0);
	exit(1);
}

static ssize_t line0(char **lineptr, size_t *n, FILE *stream)
{
	return getdelim(lineptr, n, 0, stream);
}

int main(int argc, char **argv)
{
	ret_t result;
	int   ch;
	ssize_t (*line)(char **lineptr, size_t *n, FILE *stream);

	result = ok;
	line = getline;

	while ((ch = getopt(argc, argv, "b0fhpt")) != -1) {
		switch (ch) {
		case '0':
			line = line0;
			break;
		case 'p':
			show = 1;
			break;
		case 'b':
			blocks = 1;
			break;
		case 'f':
			frag = 1;
			break;
		case 't':
			total = 1;
			break;
		case 'h':
		default:
			usage(argv[0]);
			break;
		}
	}

	if (optind < argc) {
		int i;

		for (i = optind; i < argc && result == ok; ++ i)
			result = fibmap(argv[0], argv[i]);
	} else {
		char *path;
		int length;

		path = NULL;
		length = 0;
		while (line(&path, &length, stdin) != -1) {
			result = fibmap(argv[0], path);
			if (result != 0)
				break;
		}
		if (path != NULL)
			free(path);
	}
	if (result == 0 && total) {
		printf("T %u %u %f\n", t_blocks, t_frags,
		       ((double)t_frags) / t_blocks);
	}
	return result;
}

