Merge branch 'upstream' into tizen
[platform/upstream/cryptsetup.git] / lib / utils_device.c
1 /*
2  * device backend utilities
3  *
4  * Copyright (C) 2004 Jana Saout <jana@saout.de>
5  * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2021 Red Hat, Inc. All rights reserved.
7  * Copyright (C) 2009-2021 Milan Broz
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include <assert.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/ioctl.h>
31 #include <linux/fs.h>
32 #include <unistd.h>
33 #ifdef HAVE_SYS_SYSMACROS_H
34 # include <sys/sysmacros.h>     /* for major, minor */
35 #endif
36 #ifdef HAVE_SYS_STATVFS_H
37 # include <sys/statvfs.h>
38 #endif
39 #include "internal.h"
40 #include "utils_device_locking.h"
41
42 struct device {
43         char *path;
44
45         char *file_path;
46         int loop_fd;
47
48         int ro_dev_fd;
49         int dev_fd;
50         int dev_fd_excl;
51
52         struct crypt_lock_handle *lh;
53
54         unsigned int o_direct:1;
55         unsigned int init_done:1; /* path is bdev or loop already initialized */
56
57         /* cached values */
58         size_t alignment;
59         size_t block_size;
60 };
61
62 static size_t device_fs_block_size_fd(int fd)
63 {
64         size_t page_size = crypt_getpagesize();
65
66 #ifdef HAVE_SYS_STATVFS_H
67         struct statvfs buf;
68
69         /*
70          * NOTE: some filesystems (NFS) returns bogus blocksize (1MB).
71          * Page-size io should always work and avoids increasing IO beyond aligned LUKS header.
72          */
73         if (!fstatvfs(fd, &buf) && buf.f_bsize && buf.f_bsize <= page_size)
74                 return (size_t)buf.f_bsize;
75 #endif
76         return page_size;
77 }
78
79 static size_t device_block_size_fd(int fd, size_t *min_size)
80 {
81         struct stat st;
82         size_t bsize;
83         int arg;
84
85         if (fstat(fd, &st) < 0)
86                 return 0;
87
88         if (S_ISREG(st.st_mode))
89                 bsize = device_fs_block_size_fd(fd);
90         else {
91                 if (ioctl(fd, BLKSSZGET, &arg) < 0)
92                         bsize = crypt_getpagesize();
93                 else
94                         bsize = (size_t)arg;
95         }
96
97         if (!min_size)
98                 return bsize;
99
100         if (S_ISREG(st.st_mode)) {
101                 /* file can be empty as well */
102                 if (st.st_size > (ssize_t)bsize)
103                         *min_size = bsize;
104                 else
105                         *min_size = st.st_size;
106         } else {
107                 /* block device must have at least one block */
108                 *min_size = bsize;
109         }
110
111         return bsize;
112 }
113
114 static size_t device_alignment_fd(int devfd)
115 {
116         long alignment = DEFAULT_MEM_ALIGNMENT;
117
118 #ifdef _PC_REC_XFER_ALIGN
119         alignment = fpathconf(devfd, _PC_REC_XFER_ALIGN);
120         if (alignment < 0)
121                 alignment = DEFAULT_MEM_ALIGNMENT;
122 #endif
123         return (size_t)alignment;
124 }
125
126 static int device_read_test(int devfd)
127 {
128         char buffer[512];
129         int r = -EIO;
130         size_t minsize = 0, blocksize, alignment;
131
132         blocksize = device_block_size_fd(devfd, &minsize);
133         alignment = device_alignment_fd(devfd);
134
135         if (!blocksize || !alignment)
136                 return -EINVAL;
137
138         if (minsize == 0)
139                 return 0;
140
141         if (minsize > sizeof(buffer))
142                 minsize = sizeof(buffer);
143
144         if (read_blockwise(devfd, blocksize, alignment, buffer, minsize) == (ssize_t)minsize)
145                 r = 0;
146
147         crypt_safe_memzero(buffer, sizeof(buffer));
148         return r;
149 }
150
151 /*
152  * The direct-io is always preferred. The header is usually mapped to the same
153  * device and can be accessed when the rest of device is mapped to data device.
154  * Using direct-io ensures that we do not mess with data in cache.
155  * (But proper alignment should prevent this in the first place.)
156  * The read test is needed to detect broken configurations (seen with remote
157  * block devices) that allow open with direct-io but then fails on read.
158  */
159 static int device_ready(struct crypt_device *cd, struct device *device)
160 {
161         int devfd = -1, r = 0;
162         struct stat st;
163         size_t tmp_size;
164
165         if (!device)
166                 return -EINVAL;
167
168         if (device->o_direct) {
169                 log_dbg(cd, "Trying to open and read device %s with direct-io.",
170                         device_path(device));
171                 device->o_direct = 0;
172                 devfd = open(device_path(device), O_RDONLY | O_DIRECT);
173                 if (devfd >= 0) {
174                         if (device_read_test(devfd) == 0) {
175                                 device->o_direct = 1;
176                         } else {
177                                 close(devfd);
178                                 devfd = -1;
179                         }
180                 }
181         }
182
183         if (devfd < 0) {
184                 log_dbg(cd, "Trying to open device %s without direct-io.",
185                         device_path(device));
186                 devfd = open(device_path(device), O_RDONLY);
187         }
188
189         if (devfd < 0) {
190                 log_err(cd, _("Device %s does not exist or access denied."),
191                         device_path(device));
192                 return -EINVAL;
193         }
194
195         if (fstat(devfd, &st) < 0)
196                 r = -EINVAL;
197         else if (!S_ISBLK(st.st_mode))
198                 r = S_ISREG(st.st_mode) ? -ENOTBLK : -EINVAL;
199         if (r == -EINVAL) {
200                 log_err(cd, _("Device %s is not compatible."),
201                         device_path(device));
202                 close(devfd);
203                 return r;
204         }
205
206         /* Allow only increase (loop device) */
207         tmp_size = device_alignment_fd(devfd);
208         if (tmp_size > device->alignment)
209                 device->alignment = tmp_size;
210
211         tmp_size = device_block_size_fd(devfd, NULL);
212         if (tmp_size > device->block_size)
213                 device->block_size = tmp_size;
214
215         close(devfd);
216         return r;
217 }
218
219 static int _open_locked(struct crypt_device *cd, struct device *device, int flags)
220 {
221         int fd;
222
223         if (!device)
224                 return -EINVAL;
225
226         log_dbg(cd, "Opening locked device %s", device_path(device));
227
228         if ((flags & O_ACCMODE) != O_RDONLY && device_locked_readonly(device->lh)) {
229                 log_dbg(cd, "Cannot open locked device %s in write mode. Read lock held.", device_path(device));
230                 return -EAGAIN;
231         }
232
233         fd = open(device_path(device), flags);
234         if (fd < 0)
235                 return -errno;
236
237         if (device_locked_verify(cd, fd, device->lh)) {
238                 /* fd doesn't correspond to a locked resource */
239                 close(fd);
240                 log_dbg(cd, "Failed to verify lock resource for device %s.", device_path(device));
241                 return -EINVAL;
242         }
243
244         return fd;
245 }
246
247 /*
248  * Common wrapper for device sync.
249  */
250 void device_sync(struct crypt_device *cd, struct device *device)
251 {
252         if (!device || device->dev_fd < 0)
253                 return;
254
255         if (fsync(device->dev_fd) == -1)
256                 log_dbg(cd, "Cannot sync device %s.", device_path(device));
257 }
258
259 /*
260  * in non-locked mode returns always fd or -1
261  *
262  * in locked mode:
263  *      opened fd or one of:
264  *      -EAGAIN : requested write mode while device being locked in via shared lock
265  *      -EINVAL : invalid lock fd state
266  *      -1      : all other errors
267  */
268 static int device_open_internal(struct crypt_device *cd, struct device *device, int flags)
269 {
270         int access, devfd;
271
272         if (device->o_direct)
273                 flags |= O_DIRECT;
274
275         access = flags & O_ACCMODE;
276         if (access == O_WRONLY)
277                 access = O_RDWR;
278
279         if (access == O_RDONLY && device->ro_dev_fd >= 0) {
280                 log_dbg(cd, "Reusing open r%c fd on device %s", 'o', device_path(device));
281                 return device->ro_dev_fd;
282         } else if (access == O_RDWR && device->dev_fd >= 0) {
283                 log_dbg(cd, "Reusing open r%c fd on device %s", 'w', device_path(device));
284                 return device->dev_fd;
285         }
286
287         if (device_locked(device->lh))
288                 devfd = _open_locked(cd, device, flags);
289         else
290                 devfd = open(device_path(device), flags);
291
292         if (devfd < 0) {
293                 log_dbg(cd, "Cannot open device %s%s.",
294                         device_path(device),
295                         access != O_RDONLY ? " for write" : "");
296                 return devfd;
297         }
298
299         if (access == O_RDONLY)
300                 device->ro_dev_fd = devfd;
301         else
302                 device->dev_fd = devfd;
303
304         return devfd;
305 }
306
307 int device_open(struct crypt_device *cd, struct device *device, int flags)
308 {
309         if (!device)
310                 return -EINVAL;
311
312         assert(!device_locked(device->lh));
313         return device_open_internal(cd, device, flags);
314 }
315
316 int device_open_excl(struct crypt_device *cd, struct device *device, int flags)
317 {
318         const char *path;
319         struct stat st;
320
321         if (!device)
322                 return -EINVAL;
323
324         assert(!device_locked(device->lh));
325
326         if (device->dev_fd_excl < 0) {
327                 path = device_path(device);
328                 if (stat(path, &st))
329                         return -EINVAL;
330                 if (!S_ISBLK(st.st_mode))
331                         log_dbg(cd, "%s is not a block device. Can't open in exclusive mode.",
332                                 path);
333                 else {
334                         /* open(2) with O_EXCL (w/o O_CREAT) on regular file is undefined behaviour according to man page */
335                         /* coverity[toctou] */
336                         device->dev_fd_excl = open(path, O_RDONLY | O_EXCL);
337                         if (device->dev_fd_excl < 0)
338                                 return errno == EBUSY ? -EBUSY : device->dev_fd_excl;
339                         if (fstat(device->dev_fd_excl, &st) || !S_ISBLK(st.st_mode)) {
340                                 log_dbg(cd, "%s is not a block device. Can't open in exclusive mode.",
341                                         path);
342                                 close(device->dev_fd_excl);
343                                 device->dev_fd_excl = -1;
344                         } else
345                                 log_dbg(cd, "Device %s is blocked for exclusive open.", path);
346                 }
347         }
348
349         return device_open_internal(cd, device, flags);
350 }
351
352 void device_release_excl(struct crypt_device *cd, struct device *device)
353 {
354         if (device && device->dev_fd_excl >= 0) {
355                 if (close(device->dev_fd_excl))
356                         log_dbg(cd, "Failed to release exclusive handle on device %s.",
357                                 device_path(device));
358                 else
359                         log_dbg(cd, "Closed exclusive fd for %s.", device_path(device));
360                 device->dev_fd_excl = -1;
361         }
362 }
363
364 int device_open_locked(struct crypt_device *cd, struct device *device, int flags)
365 {
366         if (!device)
367                 return -EINVAL;
368
369         assert(!crypt_metadata_locking_enabled() || device_locked(device->lh));
370         return device_open_internal(cd, device, flags);
371 }
372
373 /* Avoid any read from device, expects direct-io to work. */
374 int device_alloc_no_check(struct device **device, const char *path)
375 {
376         struct device *dev;
377
378         if (!path) {
379                 *device = NULL;
380                 return 0;
381         }
382
383         dev = malloc(sizeof(struct device));
384         if (!dev)
385                 return -ENOMEM;
386
387         memset(dev, 0, sizeof(struct device));
388         dev->path = strdup(path);
389         if (!dev->path) {
390                 free(dev);
391                 return -ENOMEM;
392         }
393         dev->loop_fd = -1;
394         dev->ro_dev_fd = -1;
395         dev->dev_fd = -1;
396         dev->dev_fd_excl = -1;
397         dev->o_direct = 1;
398
399         *device = dev;
400         return 0;
401 }
402
403 int device_alloc(struct crypt_device *cd, struct device **device, const char *path)
404 {
405         struct device *dev;
406         int r;
407
408         r = device_alloc_no_check(&dev, path);
409         if (r < 0)
410                 return r;
411
412         if (dev) {
413                 r = device_ready(cd, dev);
414                 if (!r) {
415                         dev->init_done = 1;
416                 } else if (r == -ENOTBLK) {
417                         /* alloc loop later */
418                 } else if (r < 0) {
419                         free(dev->path);
420                         free(dev);
421                         return -ENOTBLK;
422                 }
423         }
424
425         *device = dev;
426         return 0;
427 }
428
429 void device_free(struct crypt_device *cd, struct device *device)
430 {
431         if (!device)
432                 return;
433
434         device_close(cd, device);
435
436         if (device->dev_fd_excl != -1) {
437                 log_dbg(cd, "Closed exclusive fd for %s.", device_path(device));
438                 close(device->dev_fd_excl);
439         }
440
441         if (device->loop_fd != -1) {
442                 log_dbg(cd, "Closed loop %s (%s).", device->path, device->file_path);
443                 close(device->loop_fd);
444         }
445
446         assert(!device_locked(device->lh));
447
448         free(device->file_path);
449         free(device->path);
450         free(device);
451 }
452
453 /* Get block device path */
454 const char *device_block_path(const struct device *device)
455 {
456         if (!device || !device->init_done)
457                 return NULL;
458
459         return device->path;
460 }
461
462 /* Get device-mapper name of device (if possible) */
463 const char *device_dm_name(const struct device *device)
464 {
465         const char *dmdir = dm_get_dir();
466         size_t dmdir_len = strlen(dmdir);
467
468         if (!device || !device->init_done)
469                 return NULL;
470
471         if (strncmp(device->path, dmdir, dmdir_len))
472                 return NULL;
473
474         return &device->path[dmdir_len+1];
475 }
476
477 /* Get path to device / file */
478 const char *device_path(const struct device *device)
479 {
480         if (!device)
481                 return NULL;
482
483         if (device->file_path)
484                 return device->file_path;
485
486         return device->path;
487 }
488
489 /* block device topology ioctls, introduced in 2.6.32 */
490 #ifndef BLKIOMIN
491 #define BLKIOMIN    _IO(0x12,120)
492 #define BLKIOOPT    _IO(0x12,121)
493 #define BLKALIGNOFF _IO(0x12,122)
494 #endif
495
496 void device_topology_alignment(struct crypt_device *cd,
497                                struct device *device,
498                                unsigned long *required_alignment, /* bytes */
499                                unsigned long *alignment_offset,   /* bytes */
500                                unsigned long default_alignment)
501 {
502         int dev_alignment_offset = 0;
503         unsigned int min_io_size = 0, opt_io_size = 0;
504         unsigned long temp_alignment = 0;
505         int fd;
506
507         *required_alignment = default_alignment;
508         *alignment_offset = 0;
509
510         if (!device || !device->path) //FIXME
511                 return;
512
513         fd = open(device->path, O_RDONLY);
514         if (fd == -1)
515                 return;
516
517         /* minimum io size */
518         if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
519                 log_dbg(cd, "Topology info for %s not supported, using default offset %lu bytes.",
520                         device->path, default_alignment);
521                 goto out;
522         }
523
524         /* optimal io size */
525         if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
526                 opt_io_size = min_io_size;
527
528         /* alignment offset, bogus -1 means misaligned/unknown */
529         if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
530                 dev_alignment_offset = 0;
531         *alignment_offset = (unsigned long)dev_alignment_offset;
532
533         temp_alignment = (unsigned long)min_io_size;
534
535         /*
536          * Ignore bogus opt-io that could break alignment.
537          * Also real opt_io_size should be aligned to minimal page size (4k).
538          * Some bogus USB enclosures reports wrong data here.
539          */
540         if ((temp_alignment < (unsigned long)opt_io_size) &&
541             !((unsigned long)opt_io_size % temp_alignment) && !MISALIGNED_4K(opt_io_size))
542                 temp_alignment = (unsigned long)opt_io_size;
543         else if (opt_io_size && (opt_io_size != min_io_size))
544                 log_err(cd, _("Ignoring bogus optimal-io size for data device (%u bytes)."), opt_io_size);
545
546         /* If calculated alignment is multiple of default, keep default */
547         if (temp_alignment && (default_alignment % temp_alignment))
548                 *required_alignment = temp_alignment;
549
550         log_dbg(cd, "Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
551                 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
552 out:
553         (void)close(fd);
554 }
555
556 size_t device_block_size(struct crypt_device *cd, struct device *device)
557 {
558         int fd;
559
560         if (!device)
561                 return 0;
562
563         if (device->block_size)
564                 return device->block_size;
565
566         fd = open(device->file_path ?: device->path, O_RDONLY);
567         if (fd >= 0) {
568                 device->block_size = device_block_size_fd(fd, NULL);
569                 close(fd);
570         }
571
572         if (!device->block_size)
573                 log_dbg(cd, "Cannot get block size for device %s.", device_path(device));
574
575         return device->block_size;
576 }
577
578 int device_read_ahead(struct device *device, uint32_t *read_ahead)
579 {
580         int fd, r = 0;
581         long read_ahead_long;
582
583         if (!device)
584                 return 0;
585
586         if ((fd = open(device->path, O_RDONLY)) < 0)
587                 return 0;
588
589         r = ioctl(fd, BLKRAGET, &read_ahead_long) ? 0 : 1;
590         close(fd);
591
592         if (r)
593                 *read_ahead = (uint32_t) read_ahead_long;
594
595         return r;
596 }
597
598 /* Get data size in bytes */
599 int device_size(struct device *device, uint64_t *size)
600 {
601         struct stat st;
602         int devfd, r = -EINVAL;
603
604         if (!device)
605                 return -EINVAL;
606
607         devfd = open(device->path, O_RDONLY);
608         if (devfd == -1)
609                 return -EINVAL;
610
611         if (fstat(devfd, &st) < 0)
612                 goto out;
613
614         if (S_ISREG(st.st_mode)) {
615                 *size = (uint64_t)st.st_size;
616                 r = 0;
617         } else if (ioctl(devfd, BLKGETSIZE64, size) >= 0)
618                 r = 0;
619 out:
620         close(devfd);
621         return r;
622 }
623
624 /* For a file, allocate the required space */
625 int device_fallocate(struct device *device, uint64_t size)
626 {
627         struct stat st;
628         int devfd, r = -EINVAL;
629
630         if (!device)
631                 return -EINVAL;
632
633         devfd = open(device_path(device), O_RDWR);
634         if (devfd == -1)
635                 return -EINVAL;
636
637         if (!fstat(devfd, &st) && S_ISREG(st.st_mode) &&
638             ((uint64_t)st.st_size >= size || !posix_fallocate(devfd, 0, size))) {
639                 r = 0;
640                 if (device->file_path && crypt_loop_resize(device->path))
641                         r = -EINVAL;
642         }
643
644         close(devfd);
645         return r;
646 }
647
648 int device_check_size(struct crypt_device *cd,
649                       struct device *device,
650                       uint64_t req_offset, int falloc)
651 {
652         uint64_t dev_size;
653
654         if (device_size(device, &dev_size)) {
655                 log_dbg(cd, "Cannot get device size for device %s.", device_path(device));
656                 return -EIO;
657         }
658
659         log_dbg(cd, "Device size %" PRIu64 ", offset %" PRIu64 ".", dev_size, req_offset);
660
661         if (req_offset > dev_size) {
662                 /* If it is header file, increase its size */
663                 if (falloc && !device_fallocate(device, req_offset))
664                         return 0;
665
666                 log_err(cd, _("Device %s is too small. Need at least %" PRIu64 " bytes."),
667                         device_path(device), req_offset);
668                 return -EINVAL;
669         }
670
671         return 0;
672 }
673
674 static int device_info(struct crypt_device *cd,
675                        struct device *device,
676                        enum devcheck device_check,
677                        int *readonly, uint64_t *size)
678 {
679         struct stat st;
680         int fd = -1, r, flags = 0, real_readonly;
681         uint64_t real_size;
682
683         if (!device)
684                 return -ENOTBLK;
685
686         real_readonly = 0;
687         real_size = 0;
688
689         if (stat(device->path, &st) < 0) {
690                 r = -EINVAL;
691                 goto out;
692         }
693
694         /* never wipe header on mounted device */
695         if (device_check == DEV_EXCL && S_ISBLK(st.st_mode))
696                 flags |= O_EXCL;
697
698         /* Try to open read-write to check whether it is a read-only device */
699         /* coverity[toctou] */
700         fd = open(device->path, O_RDWR | flags);
701         if (fd == -1 && errno == EROFS) {
702                 real_readonly = 1;
703                 fd = open(device->path, O_RDONLY | flags);
704         }
705
706         if (fd == -1 && device_check == DEV_EXCL && errno == EBUSY) {
707                 r = -EBUSY;
708                 goto out;
709         }
710
711         if (fd == -1) {
712                 r = errno ? -errno : -EINVAL;
713                 goto out;
714         }
715
716         r = 0;
717         if (S_ISREG(st.st_mode)) {
718                 //FIXME: add readonly check
719                 real_size = (uint64_t)st.st_size;
720                 real_size >>= SECTOR_SHIFT;
721         } else {
722                 /* If the device can be opened read-write, i.e. readonly is still 0, then
723                  * check whether BKROGET says that it is read-only. E.g. read-only loop
724                  * devices may be opened read-write but are read-only according to BLKROGET
725                  */
726                 if (real_readonly == 0 && (r = ioctl(fd, BLKROGET, &real_readonly)) < 0)
727                         goto out;
728
729                 r = ioctl(fd, BLKGETSIZE64, &real_size);
730                 if (r >= 0) {
731                         real_size >>= SECTOR_SHIFT;
732                         goto out;
733                 }
734         }
735 out:
736         if (fd != -1)
737                 close(fd);
738
739         switch (r) {
740         case 0:
741                 if (readonly)
742                         *readonly = real_readonly;
743                 if (size)
744                         *size = real_size;
745                 break;
746         case -EBUSY:
747                 log_err(cd, _("Cannot use device %s which is in use "
748                               "(already mapped or mounted)."), device_path(device));
749                 break;
750         case -EACCES:
751                 log_err(cd, _("Cannot use device %s, permission denied."), device_path(device));
752                 break;
753         default:
754                 log_err(cd, _("Cannot get info about device %s."), device_path(device));
755                 r = -EINVAL;
756         }
757
758         return r;
759 }
760
761 int device_check_access(struct crypt_device *cd,
762                         struct device *device,
763                         enum devcheck device_check)
764 {
765         return device_info(cd, device, device_check, NULL, NULL);
766 }
767
768 static int device_internal_prepare(struct crypt_device *cd, struct device *device)
769 {
770         char *loop_device = NULL, *file_path = NULL;
771         int r, loop_fd, readonly = 0;
772
773         if (device->init_done)
774                 return 0;
775
776         if (getuid() || geteuid()) {
777                 log_err(cd, _("Cannot use a loopback device, "
778                               "running as non-root user."));
779                 return -ENOTSUP;
780         }
781
782         log_dbg(cd, "Allocating a free loop device.");
783
784         /* Keep the loop open, detached on last close. */
785         loop_fd = crypt_loop_attach(&loop_device, device->path, 0, 1, &readonly);
786         if (loop_fd == -1) {
787                 log_err(cd, _("Attaching loopback device failed "
788                         "(loop device with autoclear flag is required)."));
789                 free(loop_device);
790                 return -EINVAL;
791         }
792
793         file_path = device->path;
794         device->path = loop_device;
795
796         r = device_ready(cd, device);
797         if (r < 0) {
798                 device->path = file_path;
799                 crypt_loop_detach(loop_device);
800                 free(loop_device);
801                 return r;
802         }
803
804         device->loop_fd = loop_fd;
805         device->file_path = file_path;
806         device->init_done = 1;
807
808         return 0;
809 }
810
811 int device_block_adjust(struct crypt_device *cd,
812                         struct device *device,
813                         enum devcheck device_check,
814                         uint64_t device_offset,
815                         uint64_t *size,
816                         uint32_t *flags)
817 {
818         int r, real_readonly;
819         uint64_t real_size;
820
821         if (!device)
822                 return -ENOTBLK;
823
824         r = device_internal_prepare(cd, device);
825         if (r)
826                 return r;
827
828         r = device_info(cd, device, device_check, &real_readonly, &real_size);
829         if (r)
830                 return r;
831
832         if (device_offset >= real_size) {
833                 log_err(cd, _("Requested offset is beyond real size of device %s."),
834                         device_path(device));
835                 return -EINVAL;
836         }
837
838         if (size && !*size) {
839                 *size = real_size;
840                 if (!*size) {
841                         log_err(cd, _("Device %s has zero size."), device_path(device));
842                         return -ENOTBLK;
843                 }
844                 *size -= device_offset;
845         }
846
847         /* in case of size is set by parameter */
848         if (size && ((real_size - device_offset) < *size)) {
849                 log_dbg(cd, "Device %s: offset = %" PRIu64 " requested size = %" PRIu64
850                         ", backing device size = %" PRIu64,
851                         device->path, device_offset, *size, real_size);
852                 log_err(cd, _("Device %s is too small."), device_path(device));
853                 return -EINVAL;
854         }
855
856         if (flags && real_readonly)
857                 *flags |= CRYPT_ACTIVATE_READONLY;
858
859         if (size)
860                 log_dbg(cd, "Calculated device size is %" PRIu64" sectors (%s), offset %" PRIu64 ".",
861                 *size, real_readonly ? "RO" : "RW", device_offset);
862         return 0;
863 }
864
865 size_t size_round_up(size_t size, size_t block)
866 {
867         size_t s = (size + (block - 1)) / block;
868         return s * block;
869 }
870
871 void device_disable_direct_io(struct device *device)
872 {
873         if (device)
874                 device->o_direct = 0;
875 }
876
877 int device_direct_io(const struct device *device)
878 {
879         return device ? device->o_direct : 0;
880 }
881
882 static int device_compare_path(const char *path1, const char *path2)
883 {
884         struct stat st_path1, st_path2;
885
886         if (stat(path1, &st_path1 ) < 0 || stat(path2, &st_path2 ) < 0)
887                 return -EINVAL;
888
889         if (S_ISBLK(st_path1.st_mode) && S_ISBLK(st_path2.st_mode))
890                 return (st_path1.st_rdev == st_path2.st_rdev) ? 1 : 0;
891
892         if (S_ISREG(st_path1.st_mode) && S_ISREG(st_path2.st_mode))
893                 return (st_path1.st_ino == st_path2.st_ino &&
894                         st_path1.st_dev == st_path2.st_dev) ? 1 : 0;
895
896         return 0;
897 }
898
899 int device_is_identical(struct device *device1, struct device *device2)
900 {
901         if (!device1 || !device2)
902                 return 0;
903
904         if (device1 == device2)
905                 return 1;
906
907         if (!strcmp(device_path(device1), device_path(device2)))
908                 return 1;
909
910         return device_compare_path(device_path(device1), device_path(device2));
911 }
912
913 int device_is_rotational(struct device *device)
914 {
915         struct stat st;
916
917         if (!device)
918                 return -EINVAL;
919
920         if (stat(device_path(device), &st) < 0)
921                 return -EINVAL;
922
923         if (!S_ISBLK(st.st_mode))
924                 return 0;
925
926         return crypt_dev_is_rotational(major(st.st_rdev), minor(st.st_rdev));
927 }
928
929 size_t device_alignment(struct device *device)
930 {
931         int devfd;
932
933         if (!device)
934                 return -EINVAL;
935
936         if (!device->alignment) {
937                 devfd = open(device_path(device), O_RDONLY);
938                 if (devfd != -1) {
939                         device->alignment = device_alignment_fd(devfd);
940                         close(devfd);
941                 }
942         }
943
944         return device->alignment;
945 }
946
947 void device_set_lock_handle(struct device *device, struct crypt_lock_handle *h)
948 {
949         if (device)
950                 device->lh = h;
951 }
952
953 struct crypt_lock_handle *device_get_lock_handle(struct device *device)
954 {
955         return device ? device->lh : NULL;
956 }
957
958 int device_read_lock(struct crypt_device *cd, struct device *device)
959 {
960         if (!device || !crypt_metadata_locking_enabled())
961                 return 0;
962
963         if (device_read_lock_internal(cd, device))
964                 return -EBUSY;
965
966         return 0;
967 }
968
969 int device_write_lock(struct crypt_device *cd, struct device *device)
970 {
971         if (!device || !crypt_metadata_locking_enabled())
972                 return 0;
973
974         assert(!device_locked(device->lh) || !device_locked_readonly(device->lh));
975
976         return device_write_lock_internal(cd, device);
977 }
978
979 void device_read_unlock(struct crypt_device *cd, struct device *device)
980 {
981         if (!device || !crypt_metadata_locking_enabled())
982                 return;
983
984         assert(device_locked(device->lh));
985
986         device_unlock_internal(cd, device);
987 }
988
989 void device_write_unlock(struct crypt_device *cd, struct device *device)
990 {
991         if (!device || !crypt_metadata_locking_enabled())
992                 return;
993
994         assert(device_locked(device->lh) && !device_locked_readonly(device->lh));
995
996         device_unlock_internal(cd, device);
997 }
998
999 bool device_is_locked(struct device *device)
1000 {
1001         return device ? device_locked(device->lh) : 0;
1002 }
1003
1004 void device_close(struct crypt_device *cd, struct device *device)
1005 {
1006         if (!device)
1007                 return;
1008
1009         if (device->ro_dev_fd != -1) {
1010                 log_dbg(cd, "Closing read only fd for %s.", device_path(device));
1011                 if (close(device->ro_dev_fd))
1012                         log_dbg(cd, "Failed to close read only fd for %s.", device_path(device));
1013                 device->ro_dev_fd = -1;
1014         }
1015
1016         if (device->dev_fd != -1) {
1017                 log_dbg(cd, "Closing read write fd for %s.", device_path(device));
1018                 if (close(device->dev_fd))
1019                         log_dbg(cd, "Failed to close read write fd for %s.", device_path(device));
1020                 device->dev_fd = -1;
1021         }
1022 }