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
12 #define _LARGEFILE_SOURCE
13 #define _LARGEFILE64_SOURCE
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 defined(__linux__) && defined(_IO) && !defined(BLKGETSIZE)
33 #define BLKGETSIZE _IO(0x12,96) /* return device size */
39 static int valid_offset (int fd, ext2_loff_t offset)
43 if (ext2fs_llseek (fd, offset, 0) < 0)
45 if (read (fd, &ch, 1) < 1)
51 * Returns the number of blocks in a partition
53 errcode_t ext2fs_get_device_size(const char *file, int blocksize,
60 ext2_loff_t high, low;
62 struct floppy_struct this_floppy;
64 #ifdef HAVE_SYS_DISKLABEL_H
69 #endif /* HAVE_SYS_DISKLABEL_H */
72 fd = open64(file, O_RDONLY);
74 fd = open(file, O_RDONLY);
80 if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
82 *retblocks = size / (blocksize / 512);
87 if (ioctl(fd, FDGETPRM, &this_floppy) >= 0) {
89 *retblocks = this_floppy.size / (blocksize / 512);
93 #ifdef HAVE_SYS_DISKLABEL_H
94 part = strlen(file) - 1;
99 else if (ch >= 'a' && ch <= 'h')
104 if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
105 pp = &lab.d_partitions[part];
108 *retblocks = pp->p_size / (blocksize / 512);
112 #endif /* HAVE_SYS_DISKLABEL_H */
115 * OK, we couldn't figure it out by using a specialized ioctl,
116 * which is generally the best way. So do binary search to
117 * find the size of the partition.
120 for (high = 1024; valid_offset (fd, high); high *= 2)
122 while (low < high - 1)
124 const ext2_loff_t mid = (low + high) / 2;
126 if (valid_offset (fd, mid))
131 valid_offset (fd, 0);
133 *retblocks = (low + 1) / blocksize;
138 int main(int argc, char **argv)
144 fprintf(stderr, "Usage: %s device\n", argv[0]);
148 retval = ext2fs_get_device_size(argv[1], 1024, &blocks);
150 com_err(argv[0], retval,
151 "while calling ext2fs_get_device_size");
154 printf("Device %s has %d 1k blocks.\n", argv[1], blocks);