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
17 #ifdef HAVE_LINUX_FS_H
20 #ifdef HAVE_LINUX_FD_H
21 #include <sys/ioctl.h>
24 #ifdef HAVE_SYS_DISKLABEL_H
25 #include <sys/ioctl.h>
26 #include <sys/disklabel.h>
27 #endif /* HAVE_SYS_DISKLABEL_H */
29 #include <linux/ext2_fs.h>
32 static int valid_offset (int fd, ext2_loff_t offset)
36 if (ext2fs_llseek (fd, offset, 0) < 0)
38 if (read (fd, &ch, 1) < 1)
44 * Returns the number of blocks in a partition
46 errcode_t ext2fs_get_device_size(const char *file, int blocksize,
53 ext2_loff_t high, low;
55 struct floppy_struct this_floppy;
57 #ifdef HAVE_SYS_DISKLABEL_H
62 #endif /* HAVE_SYS_DISKLABEL_H */
64 fd = open(file, O_RDONLY);
69 if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
71 *retblocks = size / (blocksize / 512);
76 if (ioctl(fd, FDGETPRM, &this_floppy) >= 0) {
78 *retblocks = this_floppy.size / (blocksize / 512);
82 #ifdef HAVE_SYS_DISKLABEL_H
83 part = strlen(file) - 1;
88 else if (ch >= 'a' && ch <= 'h')
93 if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
94 pp = &lab.d_partitions[part];
97 *retblocks = pp->p_size / (blocksize / 512);
101 #endif /* HAVE_SYS_DISKLABEL_H */
104 * OK, we couldn't figure it out by using a specialized ioctl,
105 * which is generally the best way. So do binary search to
106 * find the size of the partition.
109 for (high = 1024; valid_offset (fd, high); high *= 2)
111 while (low < high - 1)
113 const ext2_loff_t mid = (low + high) / 2;
115 if (valid_offset (fd, mid))
120 valid_offset (fd, 0);
122 *retblocks = (low + 1) / blocksize;