updated ASCII version also
[platform/upstream/cryptsetup.git] / lib / utils.c
index 4f1518d..61e654c 100644 (file)
@@ -1,3 +1,24 @@
+/*
+ * utils - miscellaneous device utilities for cryptsetup
+ *
+ * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
+ * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
+ * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * version 2 as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/ioctl.h>
 #include <fcntl.h>
-#include <termios.h>
+#include <sys/mman.h>
+#include <sys/resource.h>
 
 #include "libcryptsetup.h"
 #include "internal.h"
 
-
-struct safe_allocation {
-       size_t  size;
-       char    data[1];
-};
-
-static char *error=NULL;
-
-void set_error_va(const char *fmt, va_list va)
-{
-
-       if(error) {
-           free(error);
-           error=NULL;
-       }
-
-       if(!fmt) return;
-
-       if (vasprintf(&error, fmt, va) < 0) {
-               free(error);
-               error = NULL;
-       }
-}
-
-void set_error(const char *fmt, ...)
-{
-       va_list va;
-
-       va_start(va, fmt);
-       set_error_va(fmt, va);
-       va_end(va);
-}
-
-const char *get_error(void)
-{
-       return error;
-}
-
-void *safe_alloc(size_t size)
-{
-       struct safe_allocation *alloc;
-
-       if (!size)
-               return NULL;
-
-       alloc = malloc(size + offsetof(struct safe_allocation, data));
-       if (!alloc)
-               return NULL;
-
-       alloc->size = size;
-
-       return &alloc->data;
-}
-
-void safe_free(void *data)
-{
-       struct safe_allocation *alloc;
-
-       if (!data)
-               return;
-
-       alloc = data - offsetof(struct safe_allocation, data);
-
-       memset(data, 0, alloc->size);
-
-       alloc->size = 0x55aa55aa;
-       free(alloc);
-}
-
-void *safe_realloc(void *data, size_t size)
-{
-       void *new_data;
-
-       new_data = safe_alloc(size);
-
-       if (new_data && data) {
-               struct safe_allocation *alloc;
-
-               alloc = data - offsetof(struct safe_allocation, data);
-
-               if (size > alloc->size)
-                       size = alloc->size;
-
-               memcpy(new_data, data, size);
-       }
-
-       safe_free(data);
-       return new_data;
-}
-
-char *safe_strdup(const char *s)
-{
-       char *s2 = safe_alloc(strlen(s) + 1);
-
-       if (!s2)
-               return NULL;
-
-       return strcpy(s2, s);
-}
-
 static int get_alignment(int fd)
 {
-       int alignment = DEFAULT_ALIGNMENT;
+       int alignment = DEFAULT_MEM_ALIGNMENT;
 
 #ifdef _PC_REC_XFER_ALIGN
        alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
        if (alignment < 0)
-               alignment = DEFAULT_ALIGNMENT;
+               alignment = DEFAULT_MEM_ALIGNMENT;
 #endif
        return alignment;
 }
@@ -146,6 +68,24 @@ static void *aligned_malloc(void **base, int size, int alignment)
        return ptr;
 #endif
 }
+
+int device_read_ahead(const char *dev, uint32_t *read_ahead)
+{
+       int fd, r = 0;
+       long read_ahead_long;
+
+       if ((fd = open(dev, O_RDONLY)) < 0)
+               return 0;
+
+       r = ioctl(fd, BLKRAGET, &read_ahead_long) ? 0 : 1;
+       close(fd);
+
+       if (r)
+               *read_ahead = (uint32_t) read_ahead_long;
+
+       return r;
+}
+
 static int sector_size(int fd) 
 {
        int bsize;
@@ -166,7 +106,7 @@ int sector_size_for_device(const char *device)
        return r;
 }
 
-ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
+ssize_t write_blockwise(int fd, void *orig_buf, size_t count)
 {
        void *hangover_buf, *hangover_buf_base = NULL;
        void *buf, *buf_base = NULL;
@@ -186,7 +126,7 @@ ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
                        goto out;
                memcpy(buf, orig_buf, count);
        } else
-               buf = (void *)orig_buf;
+               buf = orig_buf;
 
        r = write(fd, buf, solid);
        if (r < 0 || r != solid)
@@ -198,26 +138,28 @@ ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
                        goto out;
 
                r = read(fd, hangover_buf, bsize);
-               if(r < 0 || r != bsize) goto out;
+               if (r < 0 || r != bsize)
+                       goto out;
 
                r = lseek(fd, -bsize, SEEK_CUR);
                if (r < 0)
                        goto out;
-               memcpy(hangover_buf, buf + solid, hangover);
+               memcpy(hangover_buf, (char*)buf + solid, hangover);
 
                r = write(fd, hangover_buf, bsize);
-               if(r < 0 || r != bsize) goto out;
-               free(hangover_buf_base);
+               if (r < 0 || r != bsize)
+                       goto out;
        }
        ret = count;
- out:
+out:
+       free(hangover_buf_base);
        if (buf != orig_buf)
                free(buf_base);
        return ret;
 }
 
 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
-       void *hangover_buf, *hangover_buf_base;
+       void *hangover_buf, *hangover_buf_base = NULL;
        void *buf, *buf_base = NULL;
        int r, hangover, solid, bsize, alignment;
        ssize_t ret = -1;
@@ -232,15 +174,13 @@ ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
        if ((long)orig_buf & (alignment - 1)) {
                buf = aligned_malloc(&buf_base, count, alignment);
                if (!buf)
-                       goto out;
+                       return -1;
        } else
                buf = orig_buf;
 
        r = read(fd, buf, solid);
-       if(r < 0 || r != solid) {
-               set_error("read failed in read_blockwise.\n");
+       if(r < 0 || r != solid)
                goto out;
-       }
 
        if (hangover) {
                hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
@@ -250,11 +190,11 @@ ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
                if (r <  0 || r != bsize)
                        goto out;
 
-               memcpy(buf + solid, hangover_buf, hangover);
-               free(hangover_buf_base);
+               memcpy((char *)buf + solid, hangover_buf, hangover);
        }
        ret = count;
- out:
+out:
+       free(hangover_buf_base);
        if (buf != orig_buf) {
                memcpy(orig_buf, buf, count);
                free(buf_base);
@@ -262,248 +202,331 @@ ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
        return ret;
 }
 
-/* 
+/*
  * Combines llseek with blockwise write. write_blockwise can already deal with short writes
  * but we also need a function to deal with short writes at the start. But this information
- * is implicitly included in the read/write offset, which can not be set to non-aligned 
+ * is implicitly included in the read/write offset, which can not be set to non-aligned
  * boundaries. Hence, we combine llseek with write.
  */
+ssize_t write_lseek_blockwise(int fd, char *buf, size_t count, off_t offset) {
+       char *frontPadBuf;
+       void *frontPadBuf_base = NULL;
+       int r, bsize, frontHang;
+       size_t innerCount = 0;
+       ssize_t ret = -1;
 
-ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
-       int bsize = sector_size(fd);
-       const char *orig_buf = buf;
-       char frontPadBuf[bsize];
-       int frontHang = offset % bsize;
-       int r;
-       int innerCount = count < bsize ? count : bsize;
-
-       if (bsize < 0)
+       if ((bsize = sector_size(fd)) < 0)
                return bsize;
 
-       lseek(fd, offset - frontHang, SEEK_SET);
-       if(offset % bsize) {
-               r = read(fd,frontPadBuf,bsize);
-               if(r < 0) return -1;
+       frontHang = offset % bsize;
+
+       if (lseek(fd, offset - frontHang, SEEK_SET) < 0)
+               goto out;
+
+       if (frontHang) {
+               frontPadBuf = aligned_malloc(&frontPadBuf_base,
+                                            bsize, get_alignment(fd));
+               if (!frontPadBuf)
+                       goto out;
 
-               memcpy(frontPadBuf+frontHang, buf, innerCount);
+               r = read(fd, frontPadBuf, bsize);
+               if (r < 0 || r != bsize)
+                       goto out;
 
-               lseek(fd, offset - frontHang, SEEK_SET);
-               r = write(fd,frontPadBuf,bsize);
-               if(r < 0) return -1;
+               innerCount = bsize - frontHang;
+               if (innerCount > count)
+                       innerCount = count;
+
+               memcpy(frontPadBuf + frontHang, buf, innerCount);
+
+               if (lseek(fd, offset - frontHang, SEEK_SET) < 0)
+                       goto out;
+
+               r = write(fd, frontPadBuf, bsize);
+               if (r < 0 || r != bsize)
+                       goto out;
 
                buf += innerCount;
                count -= innerCount;
        }
-       if(count <= 0) return buf - orig_buf;
 
-       return write_blockwise(fd, buf, count) + innerCount;
-}
+       ret = count ? write_blockwise(fd, buf, count) : 0;
+       if (ret >= 0)
+               ret += innerCount;
+out:
+       free(frontPadBuf_base);
 
-/* Password reading helpers */
+       return ret;
+}
 
-static int untimed_read(int fd, char *pass, size_t maxlen)
+int device_ready(struct crypt_device *cd, const char *device, int mode)
 {
-       ssize_t i;
-
-       i = read(fd, pass, maxlen);
-       if (i > 0) {
-               pass[i-1] = '\0';
-               i = 0;
-       } else if (i == 0) { /* EOF */
-               *pass = 0;
-               i = -1;
+       int devfd, r = 0;
+       ssize_t s;
+       struct stat st;
+       char buf[512];
+
+       if(stat(device, &st) < 0) {
+               log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
+               return -EINVAL;
        }
-       return i;
+
+       if (!S_ISBLK(st.st_mode))
+               return -ENOTBLK;
+
+       log_dbg("Trying to open and read device %s.", device);
+       devfd = open(device, mode | O_DIRECT | O_SYNC);
+       if(devfd < 0) {
+               log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
+                       (mode & O_EXCL) ? _("exclusive ") : "",
+                       (mode & O_RDWR) ? _("writable") : _("read-only"));
+               return -EINVAL;
+       }
+
+        /* Try to read first sector */
+       s = read_blockwise(devfd, buf, sizeof(buf));
+       if (s < 0 || s != sizeof(buf)) {
+               log_verbose(cd, _("Cannot read device %s.\n"), device);
+               r = -EIO;
+       }
+
+       memset(buf, 0, sizeof(buf));
+       close(devfd);
+
+       return r;
 }
 
-static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
+int device_size(const char *device, uint64_t *size)
 {
-       struct timeval t;
-       fd_set fds;
-       int failed = -1;
+       int devfd, r = 0;
 
-       FD_ZERO(&fds);
-       FD_SET(fd, &fds);
-       t.tv_sec = timeout;
-       t.tv_usec = 0;
+       devfd = open(device, O_RDONLY);
+       if(devfd == -1)
+               return -EINVAL;
 
-       if (select(fd+1, &fds, NULL, NULL, &t) > 0)
-               failed = untimed_read(fd, pass, maxlen);
-       else
-               set_error("Operation timed out");
-       return failed;
+       if (ioctl(devfd, BLKGETSIZE64, size) < 0)
+               r = -EINVAL;
+
+       close(devfd);
+       return r;
 }
 
-static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
-               long timeout)
+static int get_device_infos(const char *device, enum devcheck device_check,
+                           int *readonly, uint64_t *size)
 {
-       struct termios orig, tmp;
-       int failed = -1;
-       int infd = STDIN_FILENO, outfd;
+       struct stat st;
+       unsigned long size_small;
+       int fd, r = -1;
+       int flags = 0;
 
-       if (maxlen < 1)
-               goto out_err;
+       *readonly = 0;
+       *size = 0;
 
-       /* Read and write to /dev/tty if available */
-       if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
-               infd = STDIN_FILENO;
-               outfd = STDERR_FILENO;
+       if (stat(device, &st) < 0)
+               return -EINVAL;
+
+       /* never wipe header on mounted device */
+       if (device_check == DEV_EXCL && S_ISBLK(st.st_mode))
+               flags |= O_EXCL;
+
+       /* Try to open read-write to check whether it is a read-only device */
+       fd = open(device, O_RDWR | flags);
+       if (fd == -1 && errno == EROFS) {
+               *readonly = 1;
+               fd = open(device, O_RDONLY | flags);
        }
 
-       if (tcgetattr(infd, &orig)) {
-               set_error("Unable to get terminal");
-               goto out_err;
+       if (fd == -1 && device_check == DEV_EXCL && errno == EBUSY)
+               return -EBUSY;
+
+       if (fd == -1)
+               return -EINVAL;
+
+       /* If the device can be opened read-write, i.e. readonly is still 0, then
+        * check whether BKROGET says that it is read-only. E.g. read-only loop
+        * devices may be openend read-write but are read-only according to BLKROGET
+        */
+       if (*readonly == 0 && (r = ioctl(fd, BLKROGET, readonly)) < 0)
+               goto out;
+
+       if (ioctl(fd, BLKGETSIZE64, size) >= 0) {
+               *size >>= SECTOR_SHIFT;
+               r = 0;
+               goto out;
        }
-       memcpy(&tmp, &orig, sizeof(tmp));
-       tmp.c_lflag &= ~ECHO;
 
-       if (write(outfd, prompt, strlen(prompt)) < 0)
-               goto out_err;
+       if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
+               *size = (uint64_t)size_small;
+               r = 0;
+               goto out;
+       }
 
-       tcsetattr(infd, TCSAFLUSH, &tmp);
-       if (timeout)
-               failed = timed_read(infd, pass, maxlen, timeout);
-       else
-               failed = untimed_read(infd, pass, maxlen);
-       tcsetattr(infd, TCSAFLUSH, &orig);
-
-out_err:
-       if (!failed)
-               (void)write(outfd, "\n", 1);
-       if (infd != STDIN_FILENO)
-               close(infd);
-       return failed;
+       r = -EINVAL;
+out:
+       close(fd);
+       return r;
 }
 
-/*
- * Password reading behaviour matrix of get_key
- * 
- *                    p   v   n   h
- * -----------------+---+---+---+---
- * interactive      | Y | Y | Y | Inf
- * from fd          | N | N | Y | Inf
- * from binary file | N | N | N | Inf or options->key_size
- *
- * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
- *
- * Note: --key-file=- is interpreted as a read from a binary file (stdin)
- *
- * Returns true when more keys are available (that is when password
- * reading can be retried as for interactive terminals).
- */
-
-int get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
-            const char *key_file, int passphrase_fd, int timeout, int how2verify)
+int device_check_and_adjust(struct crypt_device *cd,
+                           const char *device,
+                           enum devcheck device_check,
+                           uint64_t *size,
+                           uint64_t *offset,
+                           uint32_t *flags)
 {
-       int fd;
-       const int verify = how2verify & CRYPT_FLAG_VERIFY;
-       const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
-       char *pass = NULL;
-       int newline_stop;
-       int read_horizon;
-
-       if(key_file && !strcmp(key_file, "-")) {
-               /* Allow binary reading from stdin */
-               fd = passphrase_fd;
-               newline_stop = 0;
-               read_horizon = 0;
-       } else if (key_file) {
-               fd = open(key_file, O_RDONLY);
-               if (fd < 0) {
-                       char buf[128];
-                       set_error("Error opening key file: %s",
-                                 strerror_r(errno, buf, 128));
-                       goto out_err;
-               }
-               newline_stop = 0;
-
-               /* This can either be 0 (LUKS) or the actually number
-                * of key bytes (default or passed by -s) */
-               read_horizon = key_size;
-       } else {
-               fd = passphrase_fd;
-               newline_stop = 1;
-               read_horizon = 0;   /* Infinite, if read from terminal or fd */
+       int r, real_readonly;
+       uint64_t real_size;
+
+       if (!device)
+               return -ENOTBLK;
+
+       r = get_device_infos(device, device_check, &real_readonly, &real_size);
+       if (r < 0) {
+               if (r == -EBUSY)
+                       log_err(cd, _("Cannot use device %s which is in use "
+                                     "(already mapped or mounted).\n"),
+                                     device);
+               else
+                       log_err(cd, _("Cannot get info about device %s.\n"),
+                               device);
+               return r;
        }
 
-       /* Interactive case */
-       if(isatty(fd)) {
-               int i;
+       if (*offset >= real_size) {
+               log_err(cd, _("Requested offset is beyond real size of device %s.\n"),
+                       device);
+               return -EINVAL;
+       }
 
-               pass = safe_alloc(512);
-               if (!pass || (i = interactive_pass(prompt, pass, 512, timeout))) {
-                       set_error("Error reading passphrase");
-                       goto out_err;
-               }
-               if (verify || verify_if_possible) {
-                       char pass_verify[512];
-                       i = interactive_pass("Verify passphrase: ", pass_verify, sizeof(pass_verify), timeout);
-                       if (i || strcmp(pass, pass_verify) != 0) {
-                               set_error("Passphrases do not match");
-                               goto out_err;
-                       }
-                       memset(pass_verify, 0, sizeof(pass_verify));
-               }
-               *passLen = strlen(pass);
-               *key = pass;
-       } else {
-               /* 
-                * This is either a fd-input or a file, in neither case we can verify the input,
-                * however we don't stop on new lines if it's a binary file.
-                */
-               int buflen, i;
-
-               if(verify) {
-                       set_error("Can't do passphrase verification on non-tty inputs");
-                       goto out_err;
+       if (!*size) {
+               *size = real_size;
+               if (!*size) {
+                       log_err(cd, _("Device %s has zero size.\n"), device);
+                       return -ENOTBLK;
                }
-               /* The following for control loop does an exhausting
-                * read on the key material file, if requested with
-                * key_size == 0, as it's done by LUKS. However, we
-                * should warn the user, if it's a non-regular file,
-                * such as /dev/random, because in this case, the loop
-                * will read forever.
-                */ 
-               if(key_file && strcmp(key_file, "-") && read_horizon == 0) {
-                       struct stat st;
-                       if(stat(key_file, &st) < 0) {
-                               set_error("Can't stat key file");
-                               goto out_err;
-                       }
-                       if(!S_ISREG(st.st_mode)) {
-                               //                              set_error("Can't do exhausting read on non regular files");
-                               // goto out_err;
-                               fprintf(stderr,"Warning: exhausting read requested, but key file is not a regular file, function might never return.\n");
-                       }
-               }
-               buflen = 0;
-               for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
-                       if(i >= buflen - 1) {
-                               buflen += 128;
-                               pass = safe_realloc(pass, buflen);
-                               if (!pass) {
-                                       set_error("Not enough memory while "
-                                                 "reading passphrase");
-                                       goto out_err;
-                               }
-                       }
-                       if(read(fd, pass + i, 1) != 1 || (newline_stop && pass[i] == '\n'))
-                               break;
+               *size -= *offset;
+       }
+
+       /* in case of size is set by parameter */
+       if ((real_size - *offset) < *size) {
+               log_dbg("Device %s: offset = %" PRIu64 " requested size = %" PRIu64
+                       ", backing device size = %" PRIu64,
+                       device, *offset, *size, real_size);
+               log_err(cd, _("Device %s is too small.\n"), device);
+               return -EINVAL;
+       }
+
+       if (device_check == DEV_SHARED) {
+               log_dbg("Checking crypt segments for device %s.", device);
+               r = crypt_sysfs_check_crypt_segment(device, *offset, *size);
+               if (r < 0) {
+                       log_err(cd, _("Cannot use device %s (crypt segments "
+                                   "overlaps or in use by another device).\n"),
+                                   device);
+                       return r;
                }
-               if(key_file)
-                       close(fd);
-               pass[i] = 0;
-               *key = pass;
-               *passLen = i;
        }
 
-       return isatty(fd); /* Return true, when password reading can be tried on interactive fds */
+       if (real_readonly)
+               *flags |= CRYPT_ACTIVATE_READONLY;
 
-out_err:
-       if(pass)
-               safe_free(pass);
-       *key = NULL;
-       *passLen = 0;
+       log_dbg("Calculated device size is %" PRIu64 " sectors (%s), offset %" PRIu64 ".",
+               *size, real_readonly ? "RO" : "RW", *offset);
        return 0;
 }
 
+/* MEMLOCK */
+#define DEFAULT_PROCESS_PRIORITY -18
+
+static int _priority;
+static int _memlock_count = 0;
+
+// return 1 if memory is locked
+int crypt_memlock_inc(struct crypt_device *ctx)
+{
+       if (!_memlock_count++) {
+               log_dbg("Locking memory.");
+               if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
+                       log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
+                       _memlock_count--;
+                       return 0;
+               }
+               errno = 0;
+               if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
+                       log_err(ctx, _("Cannot get process priority.\n"));
+               else
+                       if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
+                               log_err(ctx, _("setpriority %d failed: %s\n"),
+                                       DEFAULT_PROCESS_PRIORITY, strerror(errno));
+       }
+       return _memlock_count ? 1 : 0;
+}
+
+int crypt_memlock_dec(struct crypt_device *ctx)
+{
+       if (_memlock_count && (!--_memlock_count)) {
+               log_dbg("Unlocking memory.");
+               if (munlockall() == -1)
+                       log_err(ctx, _("Cannot unlock memory.\n"));
+               if (setpriority(PRIO_PROCESS, 0, _priority))
+                       log_err(ctx, _("setpriority %d failed: %s\n"), _priority, strerror(errno));
+       }
+       return _memlock_count ? 1 : 0;
+}
+
+/* DEVICE TOPOLOGY */
+
+/* block device topology ioctls, introduced in 2.6.32 */
+#ifndef BLKIOMIN
+#define BLKIOMIN    _IO(0x12,120)
+#define BLKIOOPT    _IO(0x12,121)
+#define BLKALIGNOFF _IO(0x12,122)
+#endif
+
+void get_topology_alignment(const char *device,
+                           unsigned long *required_alignment, /* bytes */
+                           unsigned long *alignment_offset,   /* bytes */
+                           unsigned long default_alignment)
+{
+       int dev_alignment_offset = 0;
+       unsigned int min_io_size = 0, opt_io_size = 0;
+       unsigned long temp_alignment = 0;
+       int fd;
+
+       *required_alignment = default_alignment;
+       *alignment_offset = 0;
+
+       fd = open(device, O_RDONLY);
+       if (fd == -1)
+               return;
+
+       /* minimum io size */
+       if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
+               log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
+                       device, default_alignment);
+               goto out;
+       }
+
+       /* optimal io size */
+       if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
+               opt_io_size = min_io_size;
+
+       /* alignment offset, bogus -1 means misaligned/unknown */
+       if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
+               dev_alignment_offset = 0;
+       *alignment_offset = (unsigned long)dev_alignment_offset;
+
+       temp_alignment = (unsigned long)min_io_size;
+
+       if (temp_alignment < (unsigned long)opt_io_size)
+               temp_alignment = (unsigned long)opt_io_size;
+
+       /* If calculated alignment is multiple of default, keep default */
+       if (temp_alignment && (default_alignment % temp_alignment))
+               *required_alignment = temp_alignment;
+
+       log_dbg("Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
+               min_io_size, opt_io_size, *alignment_offset, *required_alignment);
+out:
+       (void)close(fd);
+}