75449c09a3bc94271fc29be006d564ed2eeb96b7
[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-2020 Red Hat, Inc. All rights reserved.
7  * Copyright (C) 2009-2020 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->o_direct) {
166                 log_dbg(cd, "Trying to open and read device %s with direct-io.",
167                         device_path(device));
168                 device->o_direct = 0;
169                 devfd = open(device_path(device), O_RDONLY | O_DIRECT);
170                 if (devfd >= 0) {
171                         if (device_read_test(devfd) == 0) {
172                                 device->o_direct = 1;
173                         } else {
174                                 close(devfd);
175                                 devfd = -1;
176                         }
177                 }
178         }
179
180         if (devfd < 0) {
181                 log_dbg(cd, "Trying to open device %s without direct-io.",
182                         device_path(device));
183                 devfd = open(device_path(device), O_RDONLY);
184         }
185
186         if (devfd < 0) {
187                 log_err(cd, _("Device %s does not exist or access denied."),
188                         device_path(device));
189                 return -EINVAL;
190         }
191
192         if (fstat(devfd, &st) < 0)
193                 r = -EINVAL;
194         else if (!S_ISBLK(st.st_mode))
195                 r = S_ISREG(st.st_mode) ? -ENOTBLK : -EINVAL;
196         if (r == -EINVAL) {
197                 log_err(cd, _("Device %s is not compatible."),
198                         device_path(device));
199                 close(devfd);
200                 return r;
201         }
202
203         /* Allow only increase (loop device) */
204         tmp_size = device_alignment_fd(devfd);
205         if (tmp_size > device->alignment)
206                 device->alignment = tmp_size;
207
208         tmp_size = device_block_size_fd(devfd, NULL);
209         if (tmp_size > device->block_size)
210                 device->block_size = tmp_size;
211
212         close(devfd);
213         return r;
214 }
215
216 static int _open_locked(struct crypt_device *cd, struct device *device, int flags)
217 {
218         int fd;
219
220         log_dbg(cd, "Opening locked device %s", device_path(device));
221
222         if ((flags & O_ACCMODE) != O_RDONLY && device_locked_readonly(device->lh)) {
223                 log_dbg(cd, "Cannot open locked device %s in write mode. Read lock held.", device_path(device));
224                 return -EAGAIN;
225         }
226
227         fd = open(device_path(device), flags);
228         if (fd < 0)
229                 return -errno;
230
231         if (device_locked_verify(cd, fd, device->lh)) {
232                 /* fd doesn't correspond to a locked resource */
233                 close(fd);
234                 log_dbg(cd, "Failed to verify lock resource for device %s.", device_path(device));
235                 return -EINVAL;
236         }
237
238         return fd;
239 }
240
241 /*
242  * Common wrapper for device sync.
243  */
244 void device_sync(struct crypt_device *cd, struct device *device)
245 {
246         if (!device || device->dev_fd < 0)
247                 return;
248
249         if (fsync(device->dev_fd) == -1)
250                 log_dbg(cd, "Cannot sync device %s.", device_path(device));
251 }
252
253 /*
254  * in non-locked mode returns always fd or -1
255  *
256  * in locked mode:
257  *      opened fd or one of:
258  *      -EAGAIN : requested write mode while device being locked in via shared lock
259  *      -EINVAL : invalid lock fd state
260  *      -1      : all other errors
261  */
262 static int device_open_internal(struct crypt_device *cd, struct device *device, int flags)
263 {
264         int access, devfd;
265
266         if (device->o_direct)
267                 flags |= O_DIRECT;
268
269         access = flags & O_ACCMODE;
270         if (access == O_WRONLY)
271                 access = O_RDWR;
272
273         if (access == O_RDONLY && device->ro_dev_fd >= 0) {
274                 log_dbg(cd, "Reusing open r%c fd on device %s", 'o', device_path(device));
275                 return device->ro_dev_fd;
276         } else if (access == O_RDWR && device->dev_fd >= 0) {
277                 log_dbg(cd, "Reusing open r%c fd on device %s", 'w', device_path(device));
278                 return device->dev_fd;
279         }
280
281         if (device_locked(device->lh))
282                 devfd = _open_locked(cd, device, flags);
283         else
284                 devfd = open(device_path(device), flags);
285
286         if (devfd < 0) {
287                 log_dbg(cd, "Cannot open device %s%s.",
288                         device_path(device),
289                         access != O_RDONLY ? " for write" : "");
290                 return devfd;
291         }
292
293         if (access == O_RDONLY)
294                 device->ro_dev_fd = devfd;
295         else
296                 device->dev_fd = devfd;
297
298         return devfd;
299 }
300
301 int device_open(struct crypt_device *cd, struct device *device, int flags)
302 {
303         assert(!device_locked(device->lh));
304         return device_open_internal(cd, device, flags);
305 }
306
307 int device_open_excl(struct crypt_device *cd, struct device *device, int flags)
308 {
309         const char *path;
310         struct stat st;
311
312         if (!device)
313                 return -EINVAL;
314
315         assert(!device_locked(device->lh));
316
317         if (device->dev_fd_excl < 0) {
318                 path = device_path(device);
319                 if (stat(path, &st))
320                         return -EINVAL;
321                 if (!S_ISBLK(st.st_mode))
322                         log_dbg(cd, "%s is not a block device. Can't open in exclusive mode.",
323                                 path);
324                 else {
325                         /* open(2) with O_EXCL (w/o O_CREAT) on regular file is undefined behaviour according to man page */
326                         /* coverity[toctou] */
327                         device->dev_fd_excl = open(path, O_RDONLY | O_EXCL);
328                         if (device->dev_fd_excl < 0)
329                                 return errno == EBUSY ? -EBUSY : device->dev_fd_excl;
330                         if (fstat(device->dev_fd_excl, &st) || !S_ISBLK(st.st_mode)) {
331                                 log_dbg(cd, "%s is not a block device. Can't open in exclusive mode.",
332                                         path);
333                                 close(device->dev_fd_excl);
334                                 device->dev_fd_excl = -1;
335                         } else
336                                 log_dbg(cd, "Device %s is blocked for exclusive open.", path);
337                 }
338         }
339
340         return device_open_internal(cd, device, flags);
341 }
342
343 void device_release_excl(struct crypt_device *cd, struct device *device)
344 {
345         if (device && device->dev_fd_excl >= 0) {
346                 if (close(device->dev_fd_excl))
347                         log_dbg(cd, "Failed to release exclusive handle on device %s.",
348                                 device_path(device));
349                 else
350                         log_dbg(cd, "Closed exclusive fd for %s.", device_path(device));
351                 device->dev_fd_excl = -1;
352         }
353 }
354
355 int device_open_locked(struct crypt_device *cd, struct device *device, int flags)
356 {
357         assert(!crypt_metadata_locking_enabled() || device_locked(device->lh));
358         return device_open_internal(cd, device, flags);
359 }
360
361 /* Avoid any read from device, expects direct-io to work. */
362 int device_alloc_no_check(struct device **device, const char *path)
363 {
364         struct device *dev;
365
366         if (!path) {
367                 *device = NULL;
368                 return 0;
369         }
370
371         dev = malloc(sizeof(struct device));
372         if (!dev)
373                 return -ENOMEM;
374
375         memset(dev, 0, sizeof(struct device));
376         dev->path = strdup(path);
377         if (!dev->path) {
378                 free(dev);
379                 return -ENOMEM;
380         }
381         dev->loop_fd = -1;
382         dev->ro_dev_fd = -1;
383         dev->dev_fd = -1;
384         dev->dev_fd_excl = -1;
385         dev->o_direct = 1;
386
387         *device = dev;
388         return 0;
389 }
390
391 int device_alloc(struct crypt_device *cd, struct device **device, const char *path)
392 {
393         struct device *dev;
394         int r;
395
396         r = device_alloc_no_check(&dev, path);
397         if (r < 0)
398                 return r;
399
400         if (dev) {
401                 r = device_ready(cd, dev);
402                 if (!r) {
403                         dev->init_done = 1;
404                 } else if (r == -ENOTBLK) {
405                         /* alloc loop later */
406                 } else if (r < 0) {
407                         free(dev->path);
408                         free(dev);
409                         return -ENOTBLK;
410                 }
411         }
412
413         *device = dev;
414         return 0;
415 }
416
417 void device_free(struct crypt_device *cd, struct device *device)
418 {
419         if (!device)
420                 return;
421
422         device_close(cd, device);
423
424         if (device->dev_fd_excl != -1) {
425                 log_dbg(cd, "Closed exclusive fd for %s.", device_path(device));
426                 close(device->dev_fd_excl);
427         }
428
429         if (device->loop_fd != -1) {
430                 log_dbg(cd, "Closed loop %s (%s).", device->path, device->file_path);
431                 close(device->loop_fd);
432         }
433
434         assert(!device_locked(device->lh));
435
436         free(device->file_path);
437         free(device->path);
438         free(device);
439 }
440
441 /* Get block device path */
442 const char *device_block_path(const struct device *device)
443 {
444         if (!device || !device->init_done)
445                 return NULL;
446
447         return device->path;
448 }
449
450 /* Get device-mapper name of device (if possible) */
451 const char *device_dm_name(const struct device *device)
452 {
453         const char *dmdir = dm_get_dir();
454         size_t dmdir_len = strlen(dmdir);
455
456         if (!device || !device->init_done)
457                 return NULL;
458
459         if (strncmp(device->path, dmdir, dmdir_len))
460                 return NULL;
461
462         return &device->path[dmdir_len+1];
463 }
464
465 /* Get path to device / file */
466 const char *device_path(const struct device *device)
467 {
468         if (!device)
469                 return NULL;
470
471         if (device->file_path)
472                 return device->file_path;
473
474         return device->path;
475 }
476
477 /* block device topology ioctls, introduced in 2.6.32 */
478 #ifndef BLKIOMIN
479 #define BLKIOMIN    _IO(0x12,120)
480 #define BLKIOOPT    _IO(0x12,121)
481 #define BLKALIGNOFF _IO(0x12,122)
482 #endif
483
484 void device_topology_alignment(struct crypt_device *cd,
485                                struct device *device,
486                                unsigned long *required_alignment, /* bytes */
487                                unsigned long *alignment_offset,   /* bytes */
488                                unsigned long default_alignment)
489 {
490         int dev_alignment_offset = 0;
491         unsigned int min_io_size = 0, opt_io_size = 0;
492         unsigned long temp_alignment = 0;
493         int fd;
494
495         *required_alignment = default_alignment;
496         *alignment_offset = 0;
497
498         if (!device || !device->path) //FIXME
499                 return;
500
501         fd = open(device->path, O_RDONLY);
502         if (fd == -1)
503                 return;
504
505         /* minimum io size */
506         if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
507                 log_dbg(cd, "Topology info for %s not supported, using default offset %lu bytes.",
508                         device->path, default_alignment);
509                 goto out;
510         }
511
512         /* optimal io size */
513         if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
514                 opt_io_size = min_io_size;
515
516         /* alignment offset, bogus -1 means misaligned/unknown */
517         if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
518                 dev_alignment_offset = 0;
519         *alignment_offset = (unsigned long)dev_alignment_offset;
520
521         temp_alignment = (unsigned long)min_io_size;
522
523         /* Ignore bogus opt-io that could break alignment */
524         if ((temp_alignment < (unsigned long)opt_io_size) &&
525             !((unsigned long)opt_io_size % temp_alignment))
526                 temp_alignment = (unsigned long)opt_io_size;
527
528         /* If calculated alignment is multiple of default, keep default */
529         if (temp_alignment && (default_alignment % temp_alignment))
530                 *required_alignment = temp_alignment;
531
532         log_dbg(cd, "Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
533                 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
534 out:
535         (void)close(fd);
536 }
537
538 size_t device_block_size(struct crypt_device *cd, struct device *device)
539 {
540         int fd;
541
542         if (!device)
543                 return 0;
544
545         if (device->block_size)
546                 return device->block_size;
547
548         fd = open(device->file_path ?: device->path, O_RDONLY);
549         if (fd >= 0) {
550                 device->block_size = device_block_size_fd(fd, NULL);
551                 close(fd);
552         }
553
554         if (!device->block_size)
555                 log_dbg(cd, "Cannot get block size for device %s.", device_path(device));
556
557         return device->block_size;
558 }
559
560 int device_read_ahead(struct device *device, uint32_t *read_ahead)
561 {
562         int fd, r = 0;
563         long read_ahead_long;
564
565         if (!device)
566                 return 0;
567
568         if ((fd = open(device->path, O_RDONLY)) < 0)
569                 return 0;
570
571         r = ioctl(fd, BLKRAGET, &read_ahead_long) ? 0 : 1;
572         close(fd);
573
574         if (r)
575                 *read_ahead = (uint32_t) read_ahead_long;
576
577         return r;
578 }
579
580 /* Get data size in bytes */
581 int device_size(struct device *device, uint64_t *size)
582 {
583         struct stat st;
584         int devfd, r = -EINVAL;
585
586         devfd = open(device->path, O_RDONLY);
587         if(devfd == -1)
588                 return -EINVAL;
589
590         if (fstat(devfd, &st) < 0)
591                 goto out;
592
593         if (S_ISREG(st.st_mode)) {
594                 *size = (uint64_t)st.st_size;
595                 r = 0;
596         } else if (ioctl(devfd, BLKGETSIZE64, size) >= 0)
597                 r = 0;
598 out:
599         close(devfd);
600         return r;
601 }
602
603 /* For a file, allocate the required space */
604 int device_fallocate(struct device *device, uint64_t size)
605 {
606         struct stat st;
607         int devfd, r = -EINVAL;
608
609         devfd = open(device_path(device), O_RDWR);
610         if (devfd == -1)
611                 return -EINVAL;
612
613         if (!fstat(devfd, &st) && S_ISREG(st.st_mode) &&
614             ((uint64_t)st.st_size >= size || !posix_fallocate(devfd, 0, size))) {
615                 r = 0;
616                 if (device->file_path && crypt_loop_resize(device->path))
617                         r = -EINVAL;
618         }
619
620         close(devfd);
621         return r;
622 }
623
624 int device_check_size(struct crypt_device *cd,
625                       struct device *device,
626                       uint64_t req_offset, int falloc)
627 {
628         uint64_t dev_size;
629
630         if (device_size(device, &dev_size)) {
631                 log_dbg(cd, "Cannot get device size for device %s.", device_path(device));
632                 return -EIO;
633         }
634
635         log_dbg(cd, "Device size %" PRIu64 ", offset %" PRIu64 ".", dev_size, req_offset);
636
637         if (req_offset > dev_size) {
638                 /* If it is header file, increase its size */
639                 if (falloc && !device_fallocate(device, req_offset))
640                         return 0;
641
642                 log_err(cd, _("Device %s is too small. Need at least %" PRIu64 " bytes."),
643                         device_path(device), req_offset);
644                 return -EINVAL;
645         }
646
647         return 0;
648 }
649
650 static int device_info(struct crypt_device *cd,
651                        struct device *device,
652                        enum devcheck device_check,
653                        int *readonly, uint64_t *size)
654 {
655         struct stat st;
656         int fd = -1, r, flags = 0, real_readonly;
657         uint64_t real_size;
658
659         if (!device)
660                 return -ENOTBLK;
661
662         real_readonly = 0;
663         real_size = 0;
664
665         if (stat(device->path, &st) < 0) {
666                 r = -EINVAL;
667                 goto out;
668         }
669
670         /* never wipe header on mounted device */
671         if (device_check == DEV_EXCL && S_ISBLK(st.st_mode))
672                 flags |= O_EXCL;
673
674         /* Try to open read-write to check whether it is a read-only device */
675         /* coverity[toctou] */
676         fd = open(device->path, O_RDWR | flags);
677         if (fd == -1 && errno == EROFS) {
678                 real_readonly = 1;
679                 fd = open(device->path, O_RDONLY | flags);
680         }
681
682         if (fd == -1 && device_check == DEV_EXCL && errno == EBUSY) {
683                 r = -EBUSY;
684                 goto out;
685         }
686
687         if (fd == -1) {
688                 r = errno ? -errno : -EINVAL;
689                 goto out;
690         }
691
692         r = 0;
693         if (S_ISREG(st.st_mode)) {
694                 //FIXME: add readonly check
695                 real_size = (uint64_t)st.st_size;
696                 real_size >>= SECTOR_SHIFT;
697         } else {
698                 /* If the device can be opened read-write, i.e. readonly is still 0, then
699                  * check whether BKROGET says that it is read-only. E.g. read-only loop
700                  * devices may be opened read-write but are read-only according to BLKROGET
701                  */
702                 if (real_readonly == 0 && (r = ioctl(fd, BLKROGET, &real_readonly)) < 0)
703                         goto out;
704
705                 r = ioctl(fd, BLKGETSIZE64, &real_size);
706                 if (r >= 0) {
707                         real_size >>= SECTOR_SHIFT;
708                         goto out;
709                 }
710         }
711 out:
712         if (fd != -1)
713                 close(fd);
714
715         switch (r) {
716         case 0:
717                 if (readonly)
718                         *readonly = real_readonly;
719                 if (size)
720                         *size = real_size;
721                 break;
722         case -EBUSY:
723                 log_err(cd, _("Cannot use device %s which is in use "
724                               "(already mapped or mounted)."), device_path(device));
725                 break;
726         case -EACCES:
727                 log_err(cd, _("Cannot use device %s, permission denied."), device_path(device));
728                 break;
729         default:
730                 log_err(cd, _("Cannot get info about device %s."), device_path(device));
731                 r = -EINVAL;
732         }
733
734         return r;
735 }
736
737 int device_check_access(struct crypt_device *cd,
738                         struct device *device,
739                         enum devcheck device_check)
740 {
741         return device_info(cd, device, device_check, NULL, NULL);
742 }
743
744 static int device_internal_prepare(struct crypt_device *cd, struct device *device)
745 {
746         char *loop_device = NULL, *file_path = NULL;
747         int r, loop_fd, readonly = 0;
748
749         if (device->init_done)
750                 return 0;
751
752         if (getuid() || geteuid()) {
753                 log_err(cd, _("Cannot use a loopback device, "
754                               "running as non-root user."));
755                 return -ENOTSUP;
756         }
757
758         log_dbg(cd, "Allocating a free loop device.");
759
760         /* Keep the loop open, detached on last close. */
761         loop_fd = crypt_loop_attach(&loop_device, device->path, 0, 1, &readonly);
762         if (loop_fd == -1) {
763                 log_err(cd, _("Attaching loopback device failed "
764                         "(loop device with autoclear flag is required)."));
765                 free(loop_device);
766                 return -EINVAL;
767         }
768
769         file_path = device->path;
770         device->path = loop_device;
771
772         r = device_ready(cd, device);
773         if (r < 0) {
774                 device->path = file_path;
775                 crypt_loop_detach(loop_device);
776                 free(loop_device);
777                 return r;
778         }
779
780         device->loop_fd = loop_fd;
781         device->file_path = file_path;
782         device->init_done = 1;
783
784         return 0;
785 }
786
787 int device_block_adjust(struct crypt_device *cd,
788                         struct device *device,
789                         enum devcheck device_check,
790                         uint64_t device_offset,
791                         uint64_t *size,
792                         uint32_t *flags)
793 {
794         int r, real_readonly;
795         uint64_t real_size;
796
797         if (!device)
798                 return -ENOTBLK;
799
800         r = device_internal_prepare(cd, device);
801         if (r)
802                 return r;
803
804         r = device_info(cd, device, device_check, &real_readonly, &real_size);
805         if (r)
806                 return r;
807
808         if (device_offset >= real_size) {
809                 log_err(cd, _("Requested offset is beyond real size of device %s."),
810                         device_path(device));
811                 return -EINVAL;
812         }
813
814         if (size && !*size) {
815                 *size = real_size;
816                 if (!*size) {
817                         log_err(cd, _("Device %s has zero size."), device_path(device));
818                         return -ENOTBLK;
819                 }
820                 *size -= device_offset;
821         }
822
823         /* in case of size is set by parameter */
824         if (size && ((real_size - device_offset) < *size)) {
825                 log_dbg(cd, "Device %s: offset = %" PRIu64 " requested size = %" PRIu64
826                         ", backing device size = %" PRIu64,
827                         device->path, device_offset, *size, real_size);
828                 log_err(cd, _("Device %s is too small."), device_path(device));
829                 return -EINVAL;
830         }
831
832         if (flags && real_readonly)
833                 *flags |= CRYPT_ACTIVATE_READONLY;
834
835         if (size)
836                 log_dbg(cd, "Calculated device size is %" PRIu64" sectors (%s), offset %" PRIu64 ".",
837                 *size, real_readonly ? "RO" : "RW", device_offset);
838         return 0;
839 }
840
841 size_t size_round_up(size_t size, size_t block)
842 {
843         size_t s = (size + (block - 1)) / block;
844         return s * block;
845 }
846
847 void device_disable_direct_io(struct device *device)
848 {
849         device->o_direct = 0;
850 }
851
852 int device_direct_io(const struct device *device)
853 {
854         return device->o_direct;
855 }
856
857 static dev_t device_devno(const struct device *device)
858 {
859         struct stat st;
860
861         if (stat(device->path, &st) || !S_ISBLK(st.st_mode))
862                 return 0;
863
864         return st.st_rdev;
865 }
866
867 int device_is_identical(struct device *device1, struct device *device2)
868 {
869         if (!device1 || !device2)
870                 return 0;
871
872         if (device1 == device2)
873                 return 1;
874
875         if (device1->init_done && device2->init_done)
876                 return (device_devno(device1) == device_devno(device2));
877         else if (device1->init_done || device2->init_done)
878                 return 0;
879
880         if (!strcmp(device_path(device1), device_path(device2)))
881                 return 1;
882
883         return 0;
884 }
885
886 int device_is_rotational(struct device *device)
887 {
888         struct stat st;
889
890         if (stat(device_path(device), &st) < 0)
891                 return -EINVAL;
892
893         if (!S_ISBLK(st.st_mode))
894                 return 0;
895
896         return crypt_dev_is_rotational(major(st.st_rdev), minor(st.st_rdev));
897 }
898
899 size_t device_alignment(struct device *device)
900 {
901         int devfd;
902
903         if (!device->alignment) {
904                 devfd = open(device_path(device), O_RDONLY);
905                 if (devfd != -1) {
906                         device->alignment = device_alignment_fd(devfd);
907                         close(devfd);
908                 }
909         }
910
911         return device->alignment;
912 }
913
914 void device_set_lock_handle(struct device *device, struct crypt_lock_handle *h)
915 {
916         device->lh = h;
917 }
918
919 struct crypt_lock_handle *device_get_lock_handle(struct device *device)
920 {
921         return device->lh;
922 }
923
924 int device_read_lock(struct crypt_device *cd, struct device *device)
925 {
926         if (!crypt_metadata_locking_enabled())
927                 return 0;
928
929         if (device_read_lock_internal(cd, device))
930                 return -EBUSY;
931
932         return 0;
933 }
934
935 int device_write_lock(struct crypt_device *cd, struct device *device)
936 {
937         if (!crypt_metadata_locking_enabled())
938                 return 0;
939
940         assert(!device_locked(device->lh) || !device_locked_readonly(device->lh));
941
942         return device_write_lock_internal(cd, device);
943 }
944
945 void device_read_unlock(struct crypt_device *cd, struct device *device)
946 {
947         if (!crypt_metadata_locking_enabled())
948                 return;
949
950         assert(device_locked(device->lh));
951
952         device_unlock_internal(cd, device);
953 }
954
955 void device_write_unlock(struct crypt_device *cd, struct device *device)
956 {
957         if (!crypt_metadata_locking_enabled())
958                 return;
959
960         assert(device_locked(device->lh) && !device_locked_readonly(device->lh));
961
962         device_unlock_internal(cd, device);
963 }
964
965 bool device_is_locked(struct device *device)
966 {
967         return device ? device_locked(device->lh) : 0;
968 }
969
970 void device_close(struct crypt_device *cd, struct device *device)
971 {
972         if (!device)
973                 return;
974
975         if (device->ro_dev_fd != -1) {
976                 log_dbg(cd, "Closing read only fd for %s.", device_path(device));
977                 if (close(device->ro_dev_fd))
978                         log_dbg(cd, "Failed to close read only fd for %s.", device_path(device));
979                 device->ro_dev_fd = -1;
980         }
981
982         if (device->dev_fd != -1) {
983                 log_dbg(cd, "Closing read write fd for %s.", device_path(device));
984                 if (close(device->dev_fd))
985                         log_dbg(cd, "Failed to close read write fd for %s.", device_path(device));
986                 device->dev_fd = -1;
987         }
988 }