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
8
* GNU Lesser General Public License.
12
#define _LARGEFILE_SOURCE
13
#define _LARGEFILE64_SOURCE
23
#ifdef HAVE_LINUX_FD_H
24
#include <sys/ioctl.h>
26
#endif /* HAVE_LINUX_FD_H */
27
#ifdef HAVE_SYS_DISKLABEL_H
28
#include <sys/ioctl.h>
29
#include <sys/disklabel.h>
31
#endif /* HAVE_SYS_DISKLABEL_H */
35
#if defined(__linux__) && defined(_IO) && !defined(BLKGETSIZE)
36
#define BLKGETSIZE _IO(0x12,96) /* return device size */
40
#include <sys/ioctl.h>
43
#define BLKGETSIZE DKIOCGETBLOCKCOUNT32
44
#endif /* APPLE_DARWIN */
46
static int valid_offset(int fd, blkid_loff_t offset)
50
if (blkid_llseek(fd, offset, 0) < 0)
52
if (read(fd, &ch, 1) < 1)
58
* Returns the number of blocks in a partition
60
blkid_loff_t blkid_get_dev_size(int fd)
65
blkid_loff_t high, low;
67
struct floppy_struct this_floppy;
69
#ifdef HAVE_SYS_DISKLABEL_H
75
#endif /* HAVE_SYS_DISKLABEL_H */
78
if (ioctl(fd, BLKGETSIZE, &size) >= 0)
79
return (blkid_loff_t)size << 9;
82
if (ioctl(fd, FDGETPRM, &this_floppy) >= 0)
83
return (blkid_loff_t)this_floppy.size << 9;
85
#ifdef HAVE_SYS_DISKLABEL_H
88
* This should work in theory but I haven't tested it. Anyone
89
* on a BSD system want to test this for me? In the meantime,
90
* binary search mechanism should work just fine.
92
if ((fstat(fd, &st) >= 0) && S_ISBLK(st.st_mode))
93
part = st.st_rdev & 7;
94
if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
95
pp = &lab.d_partitions[part];
97
return pp->p_size << 9;
100
#endif /* HAVE_SYS_DISKLABEL_H */
103
* OK, we couldn't figure it out by using a specialized ioctl,
104
* which is generally the best way. So do binary search to
105
* find the size of the partition.
108
for (high = 1024; valid_offset(fd, high); high *= 2)
110
while (low < high - 1)
112
const blkid_loff_t mid = (low + high) / 2;
114
if (valid_offset(fd, mid))
123
int main(int argc, char **argv)
129
fprintf(stderr, "Usage: %s device\n"
130
"Determine the size of a device\n", argv[0]);
134
if ((fd = open(argv[1], O_RDONLY)) < 0)
137
bytes = blkid_get_dev_size(fd);
138
printf("Device %s has %Ld 1k blocks.\n", argv[1], bytes >> 10);