e2fsprogs/lib/ext2fs/getsize.c

125 lines
2.4 KiB
C
Raw Normal View History

1997-04-26 17:58:21 +04:00
/*
* getsize.c --- get the size of a partition.
*
1997-04-29 20:17:09 +04:00
* Copyright (C) 1995, 1995 Theodore Ts'o.
*
* %Begin-Header%
* This file may be redistributed under the terms of the GNU Public
* License.
* %End-Header%
1997-04-26 17:58:21 +04:00
*/
#include <stdio.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#ifdef HAVE_LINUX_FS_H
#include <linux/fs.h>
#endif
#ifdef HAVE_LINUX_FD_H
#include <sys/ioctl.h>
#include <linux/fd.h>
#endif
#ifdef HAVE_SYS_DISKLABEL_H
#include <sys/ioctl.h>
#include <sys/disklabel.h>
#endif /* HAVE_SYS_DISKLABEL_H */
#include <linux/ext2_fs.h>
#include "ext2fs.h"
static int valid_offset (int fd, ext2_loff_t offset)
{
char ch;
1997-04-29 20:17:09 +04:00
if (ext2fs_llseek (fd, offset, 0) < 0)
1997-04-26 17:58:21 +04:00
return 0;
if (read (fd, &ch, 1) < 1)
return 0;
return 1;
}
/*
* Returns the number of blocks in a partition
*/
errcode_t ext2fs_get_device_size(const char *file, int blocksize,
blk_t *retblocks)
{
int fd;
#ifdef BLKGETSIZE
1997-04-29 20:17:09 +04:00
long size;
#endif
1997-04-26 17:58:21 +04:00
ext2_loff_t high, low;
#ifdef FDGETPRM
struct floppy_struct this_floppy;
#endif
#ifdef HAVE_SYS_DISKLABEL_H
1997-04-29 20:17:09 +04:00
int part;
1997-04-26 17:58:21 +04:00
struct disklabel lab;
struct partition *pp;
char ch;
#endif /* HAVE_SYS_DISKLABEL_H */
1997-04-26 18:48:50 +04:00
fd = open(file, O_RDONLY);
1997-04-26 17:58:21 +04:00
if (fd < 0)
return errno;
#ifdef BLKGETSIZE
if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
close(fd);
*retblocks = size / (blocksize / 512);
return 0;
}
#endif
#ifdef FDGETPRM
if (ioctl(fd, FDGETPRM, &this_floppy) >= 0) {
close(fd);
*retblocks = this_floppy.size / (blocksize / 512);
return 0;
}
#endif
#ifdef HAVE_SYS_DISKLABEL_H
1997-04-29 20:17:09 +04:00
part = strlen(file) - 1;
if (part >= 0) {
ch = file[part];
1997-04-26 17:58:21 +04:00
if (isdigit(ch))
1997-04-29 20:17:09 +04:00
part = 0;
1997-04-26 17:58:21 +04:00
else if (ch >= 'a' && ch <= 'h')
1997-04-29 20:17:09 +04:00
part = ch - 'a';
1997-04-26 17:58:21 +04:00
else
1997-04-29 20:17:09 +04:00
part = -1;
1997-04-26 17:58:21 +04:00
}
1997-04-29 20:17:09 +04:00
if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
pp = &lab.d_partitions[part];
1997-04-26 17:58:21 +04:00
if (pp->p_size) {
close(fd);
*retblocks = pp->p_size / (blocksize / 512);
return 0;
}
}
#endif /* HAVE_SYS_DISKLABEL_H */
/*
* OK, we couldn't figure it out by using a specialized ioctl,
1997-04-29 20:17:09 +04:00
* which is generally the best way. So do binary search to
1997-04-26 17:58:21 +04:00
* find the size of the partition.
*/
low = 0;
for (high = 1024; valid_offset (fd, high); high *= 2)
low = high;
while (low < high - 1)
{
const ext2_loff_t mid = (low + high) / 2;
if (valid_offset (fd, mid))
low = mid;
else
high = mid;
}
valid_offset (fd, 0);
close(fd);
*retblocks = (low + 1) / blocksize;
return 0;
}