1 /*
2 * getsectsize.c --- get the sector size of a device.
3 *
4 * Copyright (C) 1995, 1995 Theodore Ts'o.
5 * Copyright (C) 2003 VMware, Inc.
6 *
7 * %Begin-Header%
8 * This file may be redistributed under the terms of the GNU Library
9 * General Public License, version 2.
10 * %End-Header%
11 */
12
13 #define _LARGEFILE_SOURCE
14 #define _LARGEFILE64_SOURCE
15
16 #include <stdio.h>
17 #if HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #if HAVE_ERRNO_H
21 #include <errno.h>
22 #endif
23 #include <fcntl.h>
24 #ifdef HAVE_LINUX_FD_H
25 #include <sys/ioctl.h>
26 #include <linux/fd.h>
27 #endif
28
29 #if defined(__linux__) && defined(_IO)
30 #if !defined(BLKSSZGET)
31 #define BLKSSZGET _IO(0x12,104)/* get block device sector size */
32 #endif
33 #if !defined(BLKPBSZGET)
34 #define BLKPBSZGET _IO(0x12,123)/* get block physical sector size */
35 #endif
36 #endif
37
38 #include "ext2_fs.h"
39 #include "ext2fs.h"
40
41 /*
42 * Returns the logical sector size of a device
43 */
ext2fs_get_device_sectsize(const char * file,int * sectsize)44 errcode_t ext2fs_get_device_sectsize(const char *file, int *sectsize)
45 {
46 int fd;
47
48 fd = ext2fs_open_file(file, O_RDONLY, 0);
49 if (fd < 0)
50 return errno;
51
52 #ifdef BLKSSZGET
53 if (ioctl(fd, BLKSSZGET, sectsize) >= 0) {
54 close(fd);
55 return 0;
56 }
57 #endif
58 *sectsize = 0;
59 close(fd);
60 return 0;
61 }
62
63 /*
64 * Return desired alignment for direct I/O
65 */
ext2fs_get_dio_alignment(int fd)66 int ext2fs_get_dio_alignment(int fd)
67 {
68 int align = 0;
69
70 #ifdef BLKSSZGET
71 if (ioctl(fd, BLKSSZGET, &align) < 0)
72 align = 0;
73 #endif
74
75 #ifdef _SC_PAGESIZE
76 if (align <= 0)
77 align = sysconf(_SC_PAGESIZE);
78 #endif
79 #ifdef HAVE_GETPAGESIZE
80 if (align <= 0)
81 align = getpagesize();
82 #endif
83 if (align <= 0)
84 align = 4096;
85
86 return align;
87 }
88
89 /*
90 * Returns the physical sector size of a device
91 */
ext2fs_get_device_phys_sectsize(const char * file,int * sectsize)92 errcode_t ext2fs_get_device_phys_sectsize(const char *file, int *sectsize)
93 {
94 int fd;
95
96 fd = ext2fs_open_file(file, O_RDONLY, 0);
97 if (fd < 0)
98 return errno;
99
100 #ifdef BLKPBSZGET
101 if (ioctl(fd, BLKPBSZGET, sectsize) >= 0) {
102 close(fd);
103 return 0;
104 }
105 #endif
106 *sectsize = 0;
107 close(fd);
108 return 0;
109 }
110