/*
 *  linux/fs/xip2/balloc.c, Version 1
 *
 * (C) Copyright IBM Corp. 2002,2004
 * Author(s): Carsten Otte <cotte@de.ibm.com>
 * derived from second extended filesystem (ext2)
 */

#include <linux/config.h>
#include <linux/fs.h>
#include <linux/xip2_fs.h>
#include <linux/locks.h>
#include <linux/quotaops.h>

/*
 * balloc.c contains the blocks allocation and deallocation routines
 */

unsigned long xip2_count_free_blocks (struct super_block * sb)
{
	return le32_to_cpu(sb->u.xip2_sb.s_es->s_free_blocks_count);
}

static inline int test_root(int a, int b)
{
	if (a == 0)
		return 1;
	while (1) {
		if (a == 1)
			return 1;
		if (a % b)
			return 0;
		a = a / b;
	}
}

int xip2_group_sparse(int group)
{
	return (test_root(group, 3) || test_root(group, 5) ||
		test_root(group, 7));
}

/**
 *	xip_bg_has_super - number of blocks used by the superblock in group
 *	@sb: superblock for filesystem
 *	@group: group number to check
 *
 *	Return the number of blocks used by the superblock (primary or backup)
 *	in this group.  Currently this will be only 0 or 1.
 */
int xip2_bg_has_super(struct super_block *sb, int group)
{
	if (EXT2_HAS_RO_COMPAT_FEATURE(sb,EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
	    && !xip2_group_sparse(group))
		return 0;
	return 1;
}

/**
 *	xip2_bg_num_gdb - number of blocks used by the group table in group
 *	@sb: superblock for filesystem
 *	@group: group number to check
 *
 *	Return the number of blocks used by the group descriptor table
 *	(primary or backup) in this group.  In the future there may be a
 *	different number of descriptor blocks in each group.
 */
unsigned long xip2_bg_num_gdb(struct super_block *sb, int group)
{
	if (EXT2_HAS_RO_COMPAT_FEATURE(sb,EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
	    && !xip2_group_sparse(group))
		return 0;
	return XIP2_SB(sb)->s_gdb_count;
}


void* xip2_maread (xip2_mem_area_t* mem_area, int block, int size) {
	if ((block+1)*size-1 > (unsigned long)mem_area->end -
		(unsigned long)mem_area->start) {
		return NULL;
	}
	return (void*)(mem_area->start + block*size);
}
