Whamcloud - gitweb
b57bf56a5eef1cdf420b3e8c60a65215db1a7530
[tools/e2fsprogs.git] / lib / ext2fs / getsectsize.c
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 #ifndef _LARGEFILE_SOURCE
14 #define _LARGEFILE_SOURCE
15 #endif
16 #ifndef _LARGEFILE64_SOURCE
17 #define _LARGEFILE64_SOURCE
18 #endif
19
20 #include "config.h"
21 #include <stdio.h>
22 #if HAVE_UNISTD_H
23 #include <unistd.h>
24 #endif
25 #if HAVE_ERRNO_H
26 #include <errno.h>
27 #endif
28 #include <fcntl.h>
29 #ifdef HAVE_LINUX_FD_H
30 #include <sys/ioctl.h>
31 #include <linux/fd.h>
32 #endif
33
34 #if defined(__linux__) && defined(_IO)
35 #if !defined(BLKSSZGET)
36 #define BLKSSZGET  _IO(0x12,104)/* get block device sector size */
37 #endif
38 #if !defined(BLKPBSZGET)
39 #define BLKPBSZGET _IO(0x12,123)/* get block physical sector size */
40 #endif
41 #endif
42
43 #include "ext2_fs.h"
44 #include "ext2fs.h"
45
46 /*
47  * Returns the logical sector size of a device
48  */
49 errcode_t ext2fs_get_device_sectsize(const char *file, int *sectsize)
50 {
51         int     fd;
52
53         fd = ext2fs_open_file(file, O_RDONLY, 0);
54         if (fd < 0)
55                 return errno;
56
57 #ifdef BLKSSZGET
58         if (ioctl(fd, BLKSSZGET, sectsize) >= 0) {
59                 close(fd);
60                 return 0;
61         }
62 #endif
63         *sectsize = 0;
64         close(fd);
65         return 0;
66 }
67
68 /*
69  * Return desired alignment for direct I/O
70  */
71 int ext2fs_get_dio_alignment(int fd)
72 {
73         int align = 0;
74
75 #ifdef BLKSSZGET
76         if (ioctl(fd, BLKSSZGET, &align) < 0)
77                 align = 0;
78 #endif
79
80 #ifdef _SC_PAGESIZE
81         if (align <= 0)
82                 align = sysconf(_SC_PAGESIZE);
83 #endif
84 #ifdef HAVE_GETPAGESIZE
85         if (align <= 0)
86                 align = getpagesize();
87 #endif
88         if (align <= 0)
89                 align = 4096;
90
91         return align;
92 }
93
94 /*
95  * Returns the physical sector size of a device
96  */
97 errcode_t ext2fs_get_device_phys_sectsize(const char *file, int *sectsize)
98 {
99         int     fd;
100
101         fd = ext2fs_open_file(file, O_RDONLY, 0);
102         if (fd < 0)
103                 return errno;
104
105 #ifdef BLKPBSZGET
106         if (ioctl(fd, BLKPBSZGET, sectsize) >= 0) {
107                 close(fd);
108                 return 0;
109         }
110 #endif
111         *sectsize = 0;
112         close(fd);
113         return 0;
114 }