1 /* SPDX-License-Identifier: BSD-3-Clause 2 * Copyright (C) 2015 Intel Corporation. 3 * All rights reserved. 4 */ 5 6 #include "spdk/stdinc.h" 7 8 #include "spdk/fd.h" 9 10 #ifdef __linux__ 11 #include <linux/fs.h> 12 #endif 13 14 #ifdef __FreeBSD__ 15 #include <sys/disk.h> 16 #endif 17 18 static uint64_t 19 dev_get_size(int fd) 20 { 21 #if defined(DIOCGMEDIASIZE) /* FreeBSD */ 22 off_t size; 23 24 if (ioctl(fd, DIOCGMEDIASIZE, &size) == 0) { 25 return size; 26 } 27 #elif defined(__linux__) && defined(BLKGETSIZE64) 28 uint64_t size; 29 30 if (ioctl(fd, BLKGETSIZE64, &size) == 0) { 31 return size; 32 } 33 #endif 34 35 return 0; 36 } 37 38 uint32_t 39 spdk_fd_get_blocklen(int fd) 40 { 41 #if defined(DIOCGSECTORSIZE) /* FreeBSD */ 42 uint32_t blocklen; 43 44 if (ioctl(fd, DIOCGSECTORSIZE, &blocklen) == 0) { 45 return blocklen; 46 } 47 #elif defined(DKIOCGETBLOCKSIZE) 48 uint32_t blocklen; 49 50 if (ioctl(fd, DKIOCGETBLOCKSIZE, &blocklen) == 0) { 51 return blocklen; 52 } 53 #elif defined(__linux__) && defined(BLKSSZGET) 54 uint32_t blocklen; 55 56 if (ioctl(fd, BLKSSZGET, &blocklen) == 0) { 57 return blocklen; 58 } 59 #endif 60 61 return 0; 62 } 63 64 uint64_t 65 spdk_fd_get_size(int fd) 66 { 67 struct stat st; 68 69 if (fstat(fd, &st) != 0) { 70 return 0; 71 } 72 73 if (S_ISLNK(st.st_mode)) { 74 return 0; 75 } 76 77 if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) { 78 return dev_get_size(fd); 79 } else if (S_ISREG(st.st_mode)) { 80 return st.st_size; 81 } 82 83 /* Not REG, CHR or BLK */ 84 return 0; 85 } 86