2 * getsize.c --- get the size of a partition.
4 * Copyright (C) 1995, 1995 Theodore Ts'o.
7 * This file may be redistributed under the terms of the GNU Public
20 #ifdef HAVE_LINUX_FS_H
23 #ifdef HAVE_LINUX_FD_H
24 #include <sys/ioctl.h>
27 #ifdef HAVE_SYS_DISKLABEL_H
28 #include <sys/ioctl.h>
29 #include <sys/disklabel.h>
30 #endif /* HAVE_SYS_DISKLABEL_H */
32 #if EXT2_FLAT_INCLUDES
35 #include <linux/ext2_fs.h>
40 static int valid_offset (int fd, ext2_loff_t offset)
44 if (ext2fs_llseek (fd, offset, 0) < 0)
46 if (read (fd, &ch, 1) < 1)
52 * Returns the number of blocks in a partition
54 errcode_t ext2fs_get_device_size(const char *file, int blocksize,
61 ext2_loff_t high, low;
63 struct floppy_struct this_floppy;
65 #ifdef HAVE_SYS_DISKLABEL_H
70 #endif /* HAVE_SYS_DISKLABEL_H */
72 fd = open(file, O_RDONLY);
77 if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
79 *retblocks = size / (blocksize / 512);
84 if (ioctl(fd, FDGETPRM, &this_floppy) >= 0) {
86 *retblocks = this_floppy.size / (blocksize / 512);
90 #ifdef HAVE_SYS_DISKLABEL_H
91 part = strlen(file) - 1;
96 else if (ch >= 'a' && ch <= 'h')
101 if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
102 pp = &lab.d_partitions[part];
105 *retblocks = pp->p_size / (blocksize / 512);
109 #endif /* HAVE_SYS_DISKLABEL_H */
112 * OK, we couldn't figure it out by using a specialized ioctl,
113 * which is generally the best way. So do binary search to
114 * find the size of the partition.
117 for (high = 1024; valid_offset (fd, high); high *= 2)
119 while (low < high - 1)
121 const ext2_loff_t mid = (low + high) / 2;
123 if (valid_offset (fd, mid))
128 valid_offset (fd, 0);
130 *retblocks = (low + 1) / blocksize;