fix target system names
[openadk.git] / tools / adk / dkgetsz.c
blobb8315be70b1bdeb47f09bc3ca63b48ae22c44746
1 /*-
2 * Copyright © 2010
3 * Waldemar Brodkorb <wbx@openadk.org>
4 * Thorsten Glaser <tg@mirbsd.org>
6 * Provided that these terms and disclaimer and all copyright notices
7 * are retained or reproduced in an accompanying document, permission
8 * is granted to deal in this work without restriction, including un‐
9 * limited rights to use, publicly perform, distribute, sell, modify,
10 * merge, give away, or sublicence.
12 * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
13 * the utmost extent permitted by applicable law, neither express nor
14 * implied; without malicious intent or gross negligence. In no event
15 * may a licensor, author or contributor be held liable for indirect,
16 * direct, other damage, loss, or other issues arising in any way out
17 * of dealing in the work, even if advised of the possibility of such
18 * damage or existence of a defect, except proven that it results out
19 * of said person’s immediate fault when using the work as intended.
21 * Alternatively, this work may be distributed under the terms of the
22 * General Public License, any version, as published by the Free Soft-
23 * ware Foundation.
25 * Display the size of a block device (e.g. USB stick, CF/SF/MMC card
26 * or hard disc) in 512-byte sectors.
29 #define _FILE_OFFSET_BITS 64
31 #include <sys/param.h>
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/mount.h>
36 #if defined(__APPLE__)
37 #include <sys/disk.h>
38 #endif
40 #if defined(DIOCGDINFO)
41 #include <sys/disklabel.h>
42 #endif
44 #include <err.h>
45 #include <fcntl.h>
46 #include <stdio.h>
47 #include <unistd.h>
49 unsigned long long numsecs(int);
51 int
52 main(int argc, char *argv[]) {
53 int fd;
55 if (argc != 2)
56 errx(255, "Syntax: dkgetsz /dev/sda");
58 if ((fd = open(argv[1], O_RDONLY)) == -1)
59 err(1, "open");
60 printf("%llu\n", numsecs(fd));
61 close(fd);
62 return (0);
65 unsigned long long
66 numsecs(int fd)
68 #if defined(BLKGETSIZE) || defined(DKIOCGETBLOCKCOUNT)
70 * note: BLKGETSIZE64 returns bytes, not sectors, but the return
71 * type is size_t which is 32 bits on an ILP32 platform, so it
72 * fails interestingly here… thus we use BLKGETSIZE instead.
74 #if defined(DKIOCGETBLOCKCOUNT)
75 uint64_t nsecs;
76 #define THEIOCTL DKIOCGETBLOCKCOUNT
77 #define STRIOCTL "DKIOCGETBLOCKCOUNT"
78 #else
79 unsigned long nsecs;
80 #define THEIOCTL BLKGETSIZE
81 #define STRIOCTL "BLKGETSIZE"
82 #endif
83 if (ioctl(fd, THEIOCTL, &nsecs) == -1)
84 err(1, "ioctl %s", STRIOCTL);
85 return ((unsigned long long)nsecs);
86 #elif defined(DIOCGDINFO)
87 struct disklabel dl;
89 if (ioctl(fd, DIOCGDINFO, &dl) == -1)
90 err(1, "ioctl DIOCGDINFO");
91 return ((unsigned long long)dl.d_secperunit);
92 #else
93 #warning PLEASE DO IMPLEMENT numsecs FOR THIS PLATFORM.
94 #endif