+/* TODO: move to libbb? */
+/* TODO: return unsigned long long, FEATURE_FDISK_BLKSIZE _can_ handle
+ * disks > 2^32 sectors
+ */
+static sector_t bb_BLKGETSIZE_sectors(int fd)
+{
+ uint64_t v64;
+ unsigned long longsectors;
+
+ if (ioctl(fd, BLKGETSIZE64, &v64) == 0) {
+ /* Got bytes, convert to 512 byte sectors */
+ v64 >>= 9;
+ if (v64 != (sector_t)v64) {
+ ret_trunc:
+ /* Not only DOS, but all other partition tables
+ * we support can't record more than 32 bit
+ * sector counts or offsets
+ */
+ bb_error_msg("device has more than 2^32 sectors, can't use all of them");
+ v64 = (uint32_t)-1L;
+ }
+ return v64;
+ }
+ /* Needs temp of type long */
+ if (ioctl(fd, BLKGETSIZE, &longsectors)) {
+ /* Perhaps this is a disk image */
+ off_t sz = lseek(fd, 0, SEEK_END);
+ longsectors = 0;
+ if (sz > 0)
+ longsectors = (uoff_t)sz / sector_size;
+ lseek(fd, 0, SEEK_SET);
+ }
+ if (sizeof(long) > sizeof(sector_t)
+ && longsectors != (sector_t)longsectors
+ ) {
+ goto ret_trunc;
+ }
+ return longsectors;
+}
+
+