Whamcloud - gitweb
53fbd28bf8032ea793f6e825d5e0d7ff1f15eea5
[tools/e2fsprogs.git] / lib / ext2fs / unix_io.c
1 /*
2  * unix_io.c --- This is the Unix (well, really POSIX) implementation
3  *      of the I/O manager.
4  *
5  * Implements a one-block write-through cache.
6  *
7  * Includes support for Windows NT support under Cygwin.
8  *
9  * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
10  *      2002 by Theodore Ts'o.
11  *
12  * %Begin-Header%
13  * This file may be redistributed under the terms of the GNU Library
14  * General Public License, version 2.
15  * %End-Header%
16  */
17
18 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
19 #define _XOPEN_SOURCE 600
20 #define _DARWIN_C_SOURCE
21 #define _FILE_OFFSET_BITS 64
22 #ifndef _LARGEFILE_SOURCE
23 #define _LARGEFILE_SOURCE
24 #endif
25 #ifndef _LARGEFILE64_SOURCE
26 #define _LARGEFILE64_SOURCE
27 #endif
28 #ifndef _GNU_SOURCE
29 #define _GNU_SOURCE
30 #endif
31 #endif
32
33 #include "config.h"
34 #include <stdio.h>
35 #include <string.h>
36 #if HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #if HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 #include <fcntl.h>
43 #include <time.h>
44 #ifdef __linux__
45 #include <sys/utsname.h>
46 #endif
47 #if HAVE_SYS_TYPES_H
48 #include <sys/types.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_SYS_MOUNT_H
54 #include <sys/mount.h>
55 #endif
56 #ifdef HAVE_SYS_PRCTL_H
57 #include <sys/prctl.h>
58 #else
59 #define PR_GET_DUMPABLE 3
60 #endif
61 #if HAVE_SYS_STAT_H
62 #include <sys/stat.h>
63 #endif
64 #if HAVE_SYS_RESOURCE_H
65 #include <sys/resource.h>
66 #endif
67 #if HAVE_LINUX_FALLOC_H
68 #include <linux/falloc.h>
69 #endif
70
71 #if defined(__linux__) && defined(_IO) && !defined(BLKROGET)
72 #define BLKROGET   _IO(0x12, 94) /* Get read-only status (0 = read_write).  */
73 #endif
74
75 #undef ALIGN_DEBUG
76
77 #include "ext2_fs.h"
78 #include "ext2fs.h"
79 #include "ext2fsP.h"
80
81 /*
82  * For checking structure magic numbers...
83  */
84
85 #define EXT2_CHECK_MAGIC(struct, code) \
86           if ((struct)->magic != (code)) return (code)
87
88 struct unix_cache {
89         char                    *buf;
90         unsigned long long      block;
91         int                     access_time;
92         unsigned                dirty:1;
93         unsigned                in_use:1;
94 };
95
96 #define CACHE_SIZE 8
97 #define WRITE_DIRECT_SIZE 4     /* Must be smaller than CACHE_SIZE */
98 #define READ_DIRECT_SIZE 4      /* Should be smaller than CACHE_SIZE */
99
100 struct unix_private_data {
101         int     magic;
102         int     dev;
103         int     flags;
104         int     align;
105         int     access_time;
106         ext2_loff_t offset;
107         struct unix_cache cache[CACHE_SIZE];
108         void    *bounce;
109         struct struct_io_stats io_stats;
110 };
111
112 #define IS_ALIGNED(n, align) ((((uintptr_t) n) & \
113                                ((uintptr_t) ((align)-1))) == 0)
114
115 static errcode_t unix_get_stats(io_channel channel, io_stats *stats)
116 {
117         errcode_t       retval = 0;
118
119         struct unix_private_data *data;
120
121         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
122         data = (struct unix_private_data *) channel->private_data;
123         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
124
125         if (stats)
126                 *stats = &data->io_stats;
127
128         return retval;
129 }
130
131 static char *safe_getenv(const char *arg)
132 {
133         if ((getuid() != geteuid()) || (getgid() != getegid()))
134                 return NULL;
135 #ifdef HAVE_PRCTL
136         if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) == 0)
137                 return NULL;
138 #else
139 #if (defined(linux) && defined(SYS_prctl))
140         if (syscall(SYS_prctl, PR_GET_DUMPABLE, 0, 0, 0, 0) == 0)
141                 return NULL;
142 #endif
143 #endif
144
145 #if defined(HAVE_SECURE_GETENV)
146         return secure_getenv(arg);
147 #elif defined(HAVE___SECURE_GETENV)
148         return __secure_getenv(arg);
149 #else
150         return getenv(arg);
151 #endif
152 }
153
154 /*
155  * Here are the raw I/O functions
156  */
157 static errcode_t raw_read_blk(io_channel channel,
158                               struct unix_private_data *data,
159                               unsigned long long block,
160                               int count, void *bufv)
161 {
162         errcode_t       retval;
163         ssize_t         size;
164         ext2_loff_t     location;
165         int             actual = 0;
166         unsigned char   *buf = bufv;
167         ssize_t         really_read = 0;
168
169         size = (count < 0) ? -count : count * channel->block_size;
170         data->io_stats.bytes_read += size;
171         location = ((ext2_loff_t) block * channel->block_size) + data->offset;
172
173         if (data->flags & IO_FLAG_FORCE_BOUNCE) {
174                 if (ext2fs_llseek(data->dev, location, SEEK_SET) != location) {
175                         retval = errno ? errno : EXT2_ET_LLSEEK_FAILED;
176                         goto error_out;
177                 }
178                 goto bounce_read;
179         }
180
181 #ifdef HAVE_PREAD64
182         /* Try an aligned pread */
183         if ((channel->align == 0) ||
184             (IS_ALIGNED(buf, channel->align) &&
185              IS_ALIGNED(size, channel->align))) {
186                 actual = pread64(data->dev, buf, size, location);
187                 if (actual == size)
188                         return 0;
189                 actual = 0;
190         }
191 #elif HAVE_PREAD
192         /* Try an aligned pread */
193         if ((sizeof(off_t) >= sizeof(ext2_loff_t)) &&
194             ((channel->align == 0) ||
195              (IS_ALIGNED(buf, channel->align) &&
196               IS_ALIGNED(size, channel->align)))) {
197                 actual = pread(data->dev, buf, size, location);
198                 if (actual == size)
199                         return 0;
200                 actual = 0;
201         }
202 #endif /* HAVE_PREAD */
203
204         if (ext2fs_llseek(data->dev, location, SEEK_SET) != location) {
205                 retval = errno ? errno : EXT2_ET_LLSEEK_FAILED;
206                 goto error_out;
207         }
208         if ((channel->align == 0) ||
209             (IS_ALIGNED(buf, channel->align) &&
210              IS_ALIGNED(size, channel->align))) {
211                 actual = read(data->dev, buf, size);
212                 if (actual != size) {
213                 short_read:
214                         if (actual < 0) {
215                                 retval = errno;
216                                 actual = 0;
217                         } else
218                                 retval = EXT2_ET_SHORT_READ;
219                         goto error_out;
220                 }
221                 return 0;
222         }
223
224 #ifdef ALIGN_DEBUG
225         printf("raw_read_blk: O_DIRECT fallback: %p %lu\n", buf,
226                (unsigned long) size);
227 #endif
228
229         /*
230          * The buffer or size which we're trying to read isn't aligned
231          * to the O_DIRECT rules, so we need to do this the hard way...
232          */
233 bounce_read:
234         while (size > 0) {
235                 actual = read(data->dev, data->bounce, channel->block_size);
236                 if (actual != channel->block_size) {
237                         actual = really_read;
238                         buf -= really_read;
239                         size += really_read;
240                         goto short_read;
241                 }
242                 actual = size;
243                 if (size > channel->block_size)
244                         actual = channel->block_size;
245                 memcpy(buf, data->bounce, actual);
246                 really_read += actual;
247                 size -= actual;
248                 buf += actual;
249         }
250         return 0;
251
252 error_out:
253         if (actual >= 0 && actual < size)
254                 memset((char *) buf+actual, 0, size-actual);
255         if (channel->read_error)
256                 retval = (channel->read_error)(channel, block, count, buf,
257                                                size, actual, retval);
258         return retval;
259 }
260
261 static errcode_t raw_write_blk(io_channel channel,
262                                struct unix_private_data *data,
263                                unsigned long long block,
264                                int count, const void *bufv)
265 {
266         ssize_t         size;
267         ext2_loff_t     location;
268         int             actual = 0;
269         errcode_t       retval;
270         const unsigned char *buf = bufv;
271
272         if (count == 1)
273                 size = channel->block_size;
274         else {
275                 if (count < 0)
276                         size = -count;
277                 else
278                         size = count * channel->block_size;
279         }
280         data->io_stats.bytes_written += size;
281
282         location = ((ext2_loff_t) block * channel->block_size) + data->offset;
283
284         if (data->flags & IO_FLAG_FORCE_BOUNCE) {
285                 if (ext2fs_llseek(data->dev, location, SEEK_SET) != location) {
286                         retval = errno ? errno : EXT2_ET_LLSEEK_FAILED;
287                         goto error_out;
288                 }
289                 goto bounce_write;
290         }
291
292 #ifdef HAVE_PWRITE64
293         /* Try an aligned pwrite */
294         if ((channel->align == 0) ||
295             (IS_ALIGNED(buf, channel->align) &&
296              IS_ALIGNED(size, channel->align))) {
297                 actual = pwrite64(data->dev, buf, size, location);
298                 if (actual == size)
299                         return 0;
300         }
301 #elif HAVE_PWRITE
302         /* Try an aligned pwrite */
303         if ((sizeof(off_t) >= sizeof(ext2_loff_t)) &&
304             ((channel->align == 0) ||
305              (IS_ALIGNED(buf, channel->align) &&
306               IS_ALIGNED(size, channel->align)))) {
307                 actual = pwrite(data->dev, buf, size, location);
308                 if (actual == size)
309                         return 0;
310         }
311 #endif /* HAVE_PWRITE */
312
313         if (ext2fs_llseek(data->dev, location, SEEK_SET) != location) {
314                 retval = errno ? errno : EXT2_ET_LLSEEK_FAILED;
315                 goto error_out;
316         }
317
318         if ((channel->align == 0) ||
319             (IS_ALIGNED(buf, channel->align) &&
320              IS_ALIGNED(size, channel->align))) {
321                 actual = write(data->dev, buf, size);
322                 if (actual < 0) {
323                         retval = errno;
324                         goto error_out;
325                 }
326                 if (actual != size) {
327                 short_write:
328                         retval = EXT2_ET_SHORT_WRITE;
329                         goto error_out;
330                 }
331                 return 0;
332         }
333
334 #ifdef ALIGN_DEBUG
335         printf("raw_write_blk: O_DIRECT fallback: %p %lu\n", buf,
336                (unsigned long) size);
337 #endif
338         /*
339          * The buffer or size which we're trying to write isn't aligned
340          * to the O_DIRECT rules, so we need to do this the hard way...
341          */
342 bounce_write:
343         while (size > 0) {
344                 if (size < channel->block_size) {
345                         actual = read(data->dev, data->bounce,
346                                       channel->block_size);
347                         if (actual != channel->block_size) {
348                                 if (actual < 0) {
349                                         retval = errno;
350                                         goto error_out;
351                                 }
352                                 memset((char *) data->bounce + actual, 0,
353                                        channel->block_size - actual);
354                         }
355                 }
356                 actual = size;
357                 if (size > channel->block_size)
358                         actual = channel->block_size;
359                 memcpy(data->bounce, buf, actual);
360                 if (ext2fs_llseek(data->dev, location, SEEK_SET) != location) {
361                         retval = errno ? errno : EXT2_ET_LLSEEK_FAILED;
362                         goto error_out;
363                 }
364                 actual = write(data->dev, data->bounce, channel->block_size);
365                 if (actual < 0) {
366                         retval = errno;
367                         goto error_out;
368                 }
369                 if (actual != channel->block_size)
370                         goto short_write;
371                 size -= actual;
372                 buf += actual;
373                 location += actual;
374         }
375         return 0;
376
377 error_out:
378         if (channel->write_error)
379                 retval = (channel->write_error)(channel, block, count, buf,
380                                                 size, actual, retval);
381         return retval;
382 }
383
384
385 /*
386  * Here we implement the cache functions
387  */
388
389 /* Allocate the cache buffers */
390 static errcode_t alloc_cache(io_channel channel,
391                              struct unix_private_data *data)
392 {
393         errcode_t               retval;
394         struct unix_cache       *cache;
395         int                     i;
396
397         data->access_time = 0;
398         for (i=0, cache = data->cache; i < CACHE_SIZE; i++, cache++) {
399                 cache->block = 0;
400                 cache->access_time = 0;
401                 cache->dirty = 0;
402                 cache->in_use = 0;
403                 if (cache->buf)
404                         ext2fs_free_mem(&cache->buf);
405                 retval = io_channel_alloc_buf(channel, 0, &cache->buf);
406                 if (retval)
407                         return retval;
408         }
409         if (channel->align || data->flags & IO_FLAG_FORCE_BOUNCE) {
410                 if (data->bounce)
411                         ext2fs_free_mem(&data->bounce);
412                 retval = io_channel_alloc_buf(channel, 0, &data->bounce);
413         }
414         return retval;
415 }
416
417 /* Free the cache buffers */
418 static void free_cache(struct unix_private_data *data)
419 {
420         struct unix_cache       *cache;
421         int                     i;
422
423         data->access_time = 0;
424         for (i=0, cache = data->cache; i < CACHE_SIZE; i++, cache++) {
425                 cache->block = 0;
426                 cache->access_time = 0;
427                 cache->dirty = 0;
428                 cache->in_use = 0;
429                 if (cache->buf)
430                         ext2fs_free_mem(&cache->buf);
431         }
432         if (data->bounce)
433                 ext2fs_free_mem(&data->bounce);
434 }
435
436 #ifndef NO_IO_CACHE
437 /*
438  * Try to find a block in the cache.  If the block is not found, and
439  * eldest is a non-zero pointer, then fill in eldest with the cache
440  * entry to that should be reused.
441  */
442 static struct unix_cache *find_cached_block(struct unix_private_data *data,
443                                             unsigned long long block,
444                                             struct unix_cache **eldest)
445 {
446         struct unix_cache       *cache, *unused_cache, *oldest_cache;
447         int                     i;
448
449         unused_cache = oldest_cache = 0;
450         for (i=0, cache = data->cache; i < CACHE_SIZE; i++, cache++) {
451                 if (!cache->in_use) {
452                         if (!unused_cache)
453                                 unused_cache = cache;
454                         continue;
455                 }
456                 if (cache->block == block) {
457                         cache->access_time = ++data->access_time;
458                         return cache;
459                 }
460                 if (!oldest_cache ||
461                     (cache->access_time < oldest_cache->access_time))
462                         oldest_cache = cache;
463         }
464         if (eldest)
465                 *eldest = (unused_cache) ? unused_cache : oldest_cache;
466         return 0;
467 }
468
469 /*
470  * Reuse a particular cache entry for another block.
471  */
472 static void reuse_cache(io_channel channel, struct unix_private_data *data,
473                  struct unix_cache *cache, unsigned long long block)
474 {
475         if (cache->dirty && cache->in_use)
476                 raw_write_blk(channel, data, cache->block, 1, cache->buf);
477
478         cache->in_use = 1;
479         cache->dirty = 0;
480         cache->block = block;
481         cache->access_time = ++data->access_time;
482 }
483
484 /*
485  * Flush all of the blocks in the cache
486  */
487 static errcode_t flush_cached_blocks(io_channel channel,
488                                      struct unix_private_data *data,
489                                      int invalidate)
490
491 {
492         struct unix_cache       *cache;
493         errcode_t               retval, retval2;
494         int                     i;
495
496         retval2 = 0;
497         for (i=0, cache = data->cache; i < CACHE_SIZE; i++, cache++) {
498                 if (!cache->in_use)
499                         continue;
500
501                 if (invalidate)
502                         cache->in_use = 0;
503
504                 if (!cache->dirty)
505                         continue;
506
507                 retval = raw_write_blk(channel, data,
508                                        cache->block, 1, cache->buf);
509                 if (retval)
510                         retval2 = retval;
511                 else
512                         cache->dirty = 0;
513         }
514         return retval2;
515 }
516 #endif /* NO_IO_CACHE */
517
518 #ifdef __linux__
519 #ifndef BLKDISCARDZEROES
520 #define BLKDISCARDZEROES _IO(0x12,124)
521 #endif
522 #endif
523
524 int ext2fs_open_file(const char *pathname, int flags, mode_t mode)
525 {
526         if (mode)
527 #if defined(HAVE_OPEN64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
528                 return open64(pathname, flags, mode);
529         else
530                 return open64(pathname, flags);
531 #else
532                 return open(pathname, flags, mode);
533         else
534                 return open(pathname, flags);
535 #endif
536 }
537
538 int ext2fs_stat(const char *path, ext2fs_struct_stat *buf)
539 {
540 #if defined(HAVE_FSTAT64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
541         return stat64(path, buf);
542 #else
543         return stat(path, buf);
544 #endif
545 }
546
547 int ext2fs_fstat(int fd, ext2fs_struct_stat *buf)
548 {
549 #if defined(HAVE_FSTAT64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
550         return fstat64(fd, buf);
551 #else
552         return fstat(fd, buf);
553 #endif
554 }
555
556
557 static errcode_t unix_open_channel(const char *name, int fd,
558                                    int flags, io_channel *channel,
559                                    io_manager io_mgr)
560 {
561         io_channel      io = NULL;
562         struct unix_private_data *data = NULL;
563         errcode_t       retval;
564         ext2fs_struct_stat st;
565 #ifdef __linux__
566         struct          utsname ut;
567 #endif
568
569         if (safe_getenv("UNIX_IO_FORCE_BOUNCE"))
570                 flags |= IO_FLAG_FORCE_BOUNCE;
571
572         retval = ext2fs_get_mem(sizeof(struct struct_io_channel), &io);
573         if (retval)
574                 goto cleanup;
575         memset(io, 0, sizeof(struct struct_io_channel));
576         io->magic = EXT2_ET_MAGIC_IO_CHANNEL;
577         retval = ext2fs_get_mem(sizeof(struct unix_private_data), &data);
578         if (retval)
579                 goto cleanup;
580
581         io->manager = io_mgr;
582         retval = ext2fs_get_mem(strlen(name)+1, &io->name);
583         if (retval)
584                 goto cleanup;
585
586         strcpy(io->name, name);
587         io->private_data = data;
588         io->block_size = 1024;
589         io->read_error = 0;
590         io->write_error = 0;
591         io->refcount = 1;
592
593         memset(data, 0, sizeof(struct unix_private_data));
594         data->magic = EXT2_ET_MAGIC_UNIX_IO_CHANNEL;
595         data->io_stats.num_fields = 2;
596         data->flags = flags;
597         data->dev = fd;
598
599 #if defined(O_DIRECT)
600         if (flags & IO_FLAG_DIRECT_IO)
601                 io->align = ext2fs_get_dio_alignment(data->dev);
602 #elif defined(F_NOCACHE)
603         if (flags & IO_FLAG_DIRECT_IO)
604                 io->align = 4096;
605 #endif
606
607         /*
608          * If the device is really a block device, then set the
609          * appropriate flag, otherwise we can set DISCARD_ZEROES flag
610          * because we are going to use punch hole instead of discard
611          * and if it succeed, subsequent read from sparse area returns
612          * zero.
613          */
614         if (ext2fs_fstat(data->dev, &st) == 0) {
615                 if (ext2fsP_is_disk_device(st.st_mode))
616                         io->flags |= CHANNEL_FLAGS_BLOCK_DEVICE;
617                 else
618                         io->flags |= CHANNEL_FLAGS_DISCARD_ZEROES;
619         }
620
621 #ifdef BLKDISCARDZEROES
622         {
623                 int zeroes = 0;
624                 if (ioctl(data->dev, BLKDISCARDZEROES, &zeroes) == 0 &&
625                     zeroes)
626                         io->flags |= CHANNEL_FLAGS_DISCARD_ZEROES;
627         }
628 #endif
629
630 #if defined(__CYGWIN__)
631         /*
632          * Some operating systems require that the buffers be aligned,
633          * regardless of O_DIRECT
634          */
635         if (!io->align)
636                 io->align = 512;
637 #endif
638
639 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
640         if (io->flags & CHANNEL_FLAGS_BLOCK_DEVICE) {
641                 int dio_align = ext2fs_get_dio_alignment(fd);
642
643                 if (io->align < dio_align)
644                         io->align = dio_align;
645         }
646 #endif
647
648         if ((retval = alloc_cache(io, data)))
649                 goto cleanup;
650
651 #ifdef BLKROGET
652         if (flags & IO_FLAG_RW) {
653                 int error;
654                 int readonly = 0;
655
656                 /* Is the block device actually writable? */
657                 error = ioctl(data->dev, BLKROGET, &readonly);
658                 if (!error && readonly) {
659                         retval = EPERM;
660                         goto cleanup;
661                 }
662         }
663 #endif
664
665 #ifdef __linux__
666 #undef RLIM_INFINITY
667 #if (defined(__alpha__) || ((defined(__sparc__) || defined(__mips__)) && (SIZEOF_LONG == 4)))
668 #define RLIM_INFINITY   ((unsigned long)(~0UL>>1))
669 #else
670 #define RLIM_INFINITY  (~0UL)
671 #endif
672         /*
673          * Work around a bug in 2.4.10-2.4.18 kernels where writes to
674          * block devices are wrongly getting hit by the filesize
675          * limit.  This workaround isn't perfect, since it won't work
676          * if glibc wasn't built against 2.2 header files.  (Sigh.)
677          *
678          */
679         if ((flags & IO_FLAG_RW) &&
680             (uname(&ut) == 0) &&
681             ((ut.release[0] == '2') && (ut.release[1] == '.') &&
682              (ut.release[2] == '4') && (ut.release[3] == '.') &&
683              (ut.release[4] == '1') && (ut.release[5] >= '0') &&
684              (ut.release[5] < '8')) &&
685             (ext2fs_fstat(data->dev, &st) == 0) &&
686             (ext2fsP_is_disk_device(st.st_mode))) {
687                 struct rlimit   rlim;
688
689                 rlim.rlim_cur = rlim.rlim_max = (unsigned long) RLIM_INFINITY;
690                 setrlimit(RLIMIT_FSIZE, &rlim);
691                 getrlimit(RLIMIT_FSIZE, &rlim);
692                 if (((unsigned long) rlim.rlim_cur) <
693                     ((unsigned long) rlim.rlim_max)) {
694                         rlim.rlim_cur = rlim.rlim_max;
695                         setrlimit(RLIMIT_FSIZE, &rlim);
696                 }
697         }
698 #endif
699         *channel = io;
700         return 0;
701
702 cleanup:
703         if (data) {
704                 if (data->dev >= 0)
705                         close(data->dev);
706                 free_cache(data);
707                 ext2fs_free_mem(&data);
708         }
709         if (io) {
710                 if (io->name) {
711                         ext2fs_free_mem(&io->name);
712                 }
713                 ext2fs_free_mem(&io);
714         }
715         return retval;
716 }
717
718 static errcode_t unixfd_open(const char *str_fd, int flags,
719                              io_channel *channel)
720 {
721         int fd;
722         int fd_flags;
723
724         fd = atoi(str_fd);
725 #if defined(HAVE_FCNTL)
726         fd_flags = fcntl(fd, F_GETFD);
727         if (fd_flags == -1)
728                 return -EBADF;
729
730         flags = 0;
731         if (fd_flags & O_RDWR)
732                 flags |= IO_FLAG_RW;
733         if (fd_flags & O_EXCL)
734                 flags |= IO_FLAG_EXCLUSIVE;
735 #if defined(O_DIRECT)
736         if (fd_flags & O_DIRECT)
737                 flags |= IO_FLAG_DIRECT_IO;
738 #endif
739 #endif  /* HAVE_FCNTL */
740
741         return unix_open_channel(str_fd, fd, flags, channel, unixfd_io_manager);
742 }
743
744 static errcode_t unix_open(const char *name, int flags,
745                            io_channel *channel)
746 {
747         int fd = -1;
748         int open_flags;
749
750         if (name == 0)
751                 return EXT2_ET_BAD_DEVICE_NAME;
752
753         open_flags = (flags & IO_FLAG_RW) ? O_RDWR : O_RDONLY;
754         if (flags & IO_FLAG_EXCLUSIVE)
755                 open_flags |= O_EXCL;
756 #if defined(O_DIRECT)
757         if (flags & IO_FLAG_DIRECT_IO)
758                 open_flags |= O_DIRECT;
759 #endif
760         fd = ext2fs_open_file(name, open_flags, 0);
761         if (fd < 0)
762                 return errno;
763 #if defined(F_NOCACHE) && !defined(IO_DIRECT)
764         if (flags & IO_FLAG_DIRECT_IO) {
765                 if (fcntl(fd, F_NOCACHE, 1) < 0)
766                         return errno;
767         }
768 #endif
769         return unix_open_channel(name, fd, flags, channel, unix_io_manager);
770 }
771
772 static errcode_t unix_close(io_channel channel)
773 {
774         struct unix_private_data *data;
775         errcode_t       retval = 0;
776
777         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
778         data = (struct unix_private_data *) channel->private_data;
779         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
780
781         if (--channel->refcount > 0)
782                 return 0;
783
784 #ifndef NO_IO_CACHE
785         retval = flush_cached_blocks(channel, data, 0);
786 #endif
787
788         if (close(data->dev) < 0)
789                 retval = errno;
790         free_cache(data);
791
792         ext2fs_free_mem(&channel->private_data);
793         if (channel->name)
794                 ext2fs_free_mem(&channel->name);
795         ext2fs_free_mem(&channel);
796         return retval;
797 }
798
799 static errcode_t unix_set_blksize(io_channel channel, int blksize)
800 {
801         struct unix_private_data *data;
802         errcode_t               retval;
803
804         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
805         data = (struct unix_private_data *) channel->private_data;
806         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
807
808         if (channel->block_size != blksize) {
809 #ifndef NO_IO_CACHE
810                 if ((retval = flush_cached_blocks(channel, data, 0)))
811                         return retval;
812 #endif
813
814                 channel->block_size = blksize;
815                 free_cache(data);
816                 if ((retval = alloc_cache(channel, data)))
817                         return retval;
818         }
819         return 0;
820 }
821
822 static errcode_t unix_read_blk64(io_channel channel, unsigned long long block,
823                                int count, void *buf)
824 {
825         struct unix_private_data *data;
826         struct unix_cache *cache, *reuse[READ_DIRECT_SIZE];
827         errcode_t       retval;
828         char            *cp;
829         int             i, j;
830
831         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
832         data = (struct unix_private_data *) channel->private_data;
833         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
834
835 #ifdef NO_IO_CACHE
836         return raw_read_blk(channel, data, block, count, buf);
837 #else
838         /*
839          * If we're doing an odd-sized read or a very large read,
840          * flush out the cache and then do a direct read.
841          */
842         if (count < 0 || count > WRITE_DIRECT_SIZE) {
843                 if ((retval = flush_cached_blocks(channel, data, 0)))
844                         return retval;
845                 return raw_read_blk(channel, data, block, count, buf);
846         }
847
848         cp = buf;
849         while (count > 0) {
850                 /* If it's in the cache, use it! */
851                 if ((cache = find_cached_block(data, block, &reuse[0]))) {
852 #ifdef DEBUG
853                         printf("Using cached block %lu\n", block);
854 #endif
855                         memcpy(cp, cache->buf, channel->block_size);
856                         count--;
857                         block++;
858                         cp += channel->block_size;
859                         continue;
860                 }
861                 if (count == 1) {
862                         /*
863                          * Special case where we read directly into the
864                          * cache buffer; important in the O_DIRECT case
865                          */
866                         cache = reuse[0];
867                         reuse_cache(channel, data, cache, block);
868                         if ((retval = raw_read_blk(channel, data, block, 1,
869                                                    cache->buf))) {
870                                 cache->in_use = 0;
871                                 return retval;
872                         }
873                         memcpy(cp, cache->buf, channel->block_size);
874                         return 0;
875                 }
876
877                 /*
878                  * Find the number of uncached blocks so we can do a
879                  * single read request
880                  */
881                 for (i=1; i < count; i++)
882                         if (find_cached_block(data, block+i, &reuse[i]))
883                                 break;
884 #ifdef DEBUG
885                 printf("Reading %d blocks starting at %lu\n", i, block);
886 #endif
887                 if ((retval = raw_read_blk(channel, data, block, i, cp)))
888                         return retval;
889
890                 /* Save the results in the cache */
891                 for (j=0; j < i; j++) {
892                         count--;
893                         cache = reuse[j];
894                         reuse_cache(channel, data, cache, block++);
895                         memcpy(cache->buf, cp, channel->block_size);
896                         cp += channel->block_size;
897                 }
898         }
899         return 0;
900 #endif /* NO_IO_CACHE */
901 }
902
903 static errcode_t unix_read_blk(io_channel channel, unsigned long block,
904                                int count, void *buf)
905 {
906         return unix_read_blk64(channel, block, count, buf);
907 }
908
909 static errcode_t unix_write_blk64(io_channel channel, unsigned long long block,
910                                 int count, const void *buf)
911 {
912         struct unix_private_data *data;
913         struct unix_cache *cache, *reuse;
914         errcode_t       retval = 0;
915         const char      *cp;
916         int             writethrough;
917
918         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
919         data = (struct unix_private_data *) channel->private_data;
920         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
921
922 #ifdef NO_IO_CACHE
923         return raw_write_blk(channel, data, block, count, buf);
924 #else
925         /*
926          * If we're doing an odd-sized write or a very large write,
927          * flush out the cache completely and then do a direct write.
928          */
929         if (count < 0 || count > WRITE_DIRECT_SIZE) {
930                 if ((retval = flush_cached_blocks(channel, data, 1)))
931                         return retval;
932                 return raw_write_blk(channel, data, block, count, buf);
933         }
934
935         /*
936          * For a moderate-sized multi-block write, first force a write
937          * if we're in write-through cache mode, and then fill the
938          * cache with the blocks.
939          */
940         writethrough = channel->flags & CHANNEL_FLAGS_WRITETHROUGH;
941         if (writethrough)
942                 retval = raw_write_blk(channel, data, block, count, buf);
943
944         cp = buf;
945         while (count > 0) {
946                 cache = find_cached_block(data, block, &reuse);
947                 if (!cache) {
948                         cache = reuse;
949                         reuse_cache(channel, data, cache, block);
950                 }
951                 if (cache->buf != cp)
952                         memcpy(cache->buf, cp, channel->block_size);
953                 cache->dirty = !writethrough;
954                 count--;
955                 block++;
956                 cp += channel->block_size;
957         }
958         return retval;
959 #endif /* NO_IO_CACHE */
960 }
961
962 static errcode_t unix_cache_readahead(io_channel channel,
963                                       unsigned long long block,
964                                       unsigned long long count)
965 {
966 #ifdef POSIX_FADV_WILLNEED
967         struct unix_private_data *data;
968
969         data = (struct unix_private_data *)channel->private_data;
970         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
971         return posix_fadvise(data->dev,
972                              (ext2_loff_t)block * channel->block_size + data->offset,
973                              (ext2_loff_t)count * channel->block_size,
974                              POSIX_FADV_WILLNEED);
975 #else
976         return EXT2_ET_OP_NOT_SUPPORTED;
977 #endif
978 }
979
980 static errcode_t unix_write_blk(io_channel channel, unsigned long block,
981                                 int count, const void *buf)
982 {
983         return unix_write_blk64(channel, block, count, buf);
984 }
985
986 static errcode_t unix_write_byte(io_channel channel, unsigned long offset,
987                                  int size, const void *buf)
988 {
989         struct unix_private_data *data;
990         errcode_t       retval = 0;
991         ssize_t         actual;
992
993         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
994         data = (struct unix_private_data *) channel->private_data;
995         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
996
997         if (channel->align != 0) {
998 #ifdef ALIGN_DEBUG
999                 printf("unix_write_byte: O_DIRECT fallback\n");
1000 #endif
1001                 return EXT2_ET_UNIMPLEMENTED;
1002         }
1003
1004 #ifndef NO_IO_CACHE
1005         /*
1006          * Flush out the cache completely
1007          */
1008         if ((retval = flush_cached_blocks(channel, data, 1)))
1009                 return retval;
1010 #endif
1011
1012         if (lseek(data->dev, offset + data->offset, SEEK_SET) < 0)
1013                 return errno;
1014
1015         actual = write(data->dev, buf, size);
1016         if (actual < 0)
1017                 return errno;
1018         if (actual != size)
1019                 return EXT2_ET_SHORT_WRITE;
1020
1021         return 0;
1022 }
1023
1024 /*
1025  * Flush data buffers to disk.
1026  */
1027 static errcode_t unix_flush(io_channel channel)
1028 {
1029         struct unix_private_data *data;
1030         errcode_t retval = 0;
1031
1032         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
1033         data = (struct unix_private_data *) channel->private_data;
1034         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
1035
1036 #ifndef NO_IO_CACHE
1037         retval = flush_cached_blocks(channel, data, 0);
1038 #endif
1039 #ifdef HAVE_FSYNC
1040         if (!retval && fsync(data->dev) != 0)
1041                 return errno;
1042 #endif
1043         return retval;
1044 }
1045
1046 static errcode_t unix_set_option(io_channel channel, const char *option,
1047                                  const char *arg)
1048 {
1049         struct unix_private_data *data;
1050         unsigned long long tmp;
1051         char *end;
1052
1053         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
1054         data = (struct unix_private_data *) channel->private_data;
1055         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
1056
1057         if (!strcmp(option, "offset")) {
1058                 if (!arg)
1059                         return EXT2_ET_INVALID_ARGUMENT;
1060
1061                 tmp = strtoull(arg, &end, 0);
1062                 if (*end)
1063                         return EXT2_ET_INVALID_ARGUMENT;
1064                 data->offset = tmp;
1065                 if (data->offset < 0)
1066                         return EXT2_ET_INVALID_ARGUMENT;
1067                 return 0;
1068         }
1069         return EXT2_ET_INVALID_ARGUMENT;
1070 }
1071
1072 #if defined(__linux__) && !defined(BLKDISCARD)
1073 #define BLKDISCARD              _IO(0x12,119)
1074 #endif
1075
1076 static errcode_t unix_discard(io_channel channel, unsigned long long block,
1077                               unsigned long long count)
1078 {
1079         struct unix_private_data *data;
1080         int             ret;
1081
1082         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
1083         data = (struct unix_private_data *) channel->private_data;
1084         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
1085
1086         if (channel->flags & CHANNEL_FLAGS_BLOCK_DEVICE) {
1087 #ifdef BLKDISCARD
1088                 __u64 range[2];
1089
1090                 range[0] = (__u64)(block) * channel->block_size + data->offset;
1091                 range[1] = (__u64)(count) * channel->block_size;
1092
1093                 ret = ioctl(data->dev, BLKDISCARD, &range);
1094 #else
1095                 goto unimplemented;
1096 #endif
1097         } else {
1098 #if defined(HAVE_FALLOCATE) && defined(FALLOC_FL_PUNCH_HOLE)
1099                 /*
1100                  * If we are not on block device, try to use punch hole
1101                  * to reclaim free space.
1102                  */
1103                 ret = fallocate(data->dev,
1104                                 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1105                                 (off_t)(block) * channel->block_size + data->offset,
1106                                 (off_t)(count) * channel->block_size);
1107 #else
1108                 goto unimplemented;
1109 #endif
1110         }
1111         if (ret < 0) {
1112                 if (errno == EOPNOTSUPP)
1113                         goto unimplemented;
1114                 return errno;
1115         }
1116         return 0;
1117 unimplemented:
1118         return EXT2_ET_UNIMPLEMENTED;
1119 }
1120
1121 /* parameters might not be used if OS doesn't support zeroout */
1122 #pragma GCC diagnostic push
1123 #pragma GCC diagnostic ignored "-Wunused-parameter"
1124 static errcode_t unix_zeroout(io_channel channel, unsigned long long block,
1125                               unsigned long long count)
1126 {
1127         struct unix_private_data *data;
1128         int             ret;
1129
1130         EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
1131         data = (struct unix_private_data *) channel->private_data;
1132         EXT2_CHECK_MAGIC(data, EXT2_ET_MAGIC_UNIX_IO_CHANNEL);
1133
1134         if (safe_getenv("UNIX_IO_NOZEROOUT"))
1135                 goto unimplemented;
1136
1137         if (channel->flags & CHANNEL_FLAGS_BLOCK_DEVICE) {
1138                 /* Not implemented until the BLKZEROOUT mess is fixed */
1139                 goto unimplemented;
1140         } else {
1141                 /* Regular file, try to use truncate/punch/zero. */
1142                 struct stat statbuf;
1143
1144                 if (count == 0)
1145                         return 0;
1146                 /*
1147                  * If we're trying to zero a range past the end of the file,
1148                  * extend the file size, then truncate everything.
1149                  */
1150                 ret = fstat(data->dev, &statbuf);
1151                 if (ret)
1152                         goto err;
1153                 if ((unsigned long long) statbuf.st_size <
1154                         (block + count) * channel->block_size + data->offset) {
1155                         ret = ftruncate(data->dev,
1156                                         (block + count) * channel->block_size + data->offset);
1157                         if (ret)
1158                                 goto err;
1159                 }
1160 #if defined(HAVE_FALLOCATE) && (defined(FALLOC_FL_ZERO_RANGE) || \
1161         (defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE)))
1162 #if defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE)
1163                 ret = fallocate(data->dev,
1164                                 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1165                                 (off_t)(block) * channel->block_size + data->offset,
1166                                 (off_t)(count) * channel->block_size);
1167                 if (ret == 0)
1168                         goto err;
1169 #endif
1170 #ifdef FALLOC_FL_ZERO_RANGE
1171                 ret = fallocate(data->dev,
1172                                 FALLOC_FL_ZERO_RANGE,
1173                                 (off_t)(block) * channel->block_size + data->offset,
1174                                 (off_t)(count) * channel->block_size);
1175 #endif
1176 #else
1177                 goto unimplemented;
1178 #endif /* HAVE_FALLOCATE && (ZERO_RANGE || (PUNCH_HOLE && KEEP_SIZE)) */
1179         }
1180 err:
1181         if (ret < 0) {
1182                 if (errno == EOPNOTSUPP)
1183                         goto unimplemented;
1184                 return errno;
1185         }
1186         return 0;
1187 unimplemented:
1188         return EXT2_ET_UNIMPLEMENTED;
1189 }
1190 #pragma GCC diagnostic pop
1191
1192 static struct struct_io_manager struct_unix_manager = {
1193         .magic          = EXT2_ET_MAGIC_IO_MANAGER,
1194         .name           = "Unix I/O Manager",
1195         .open           = unix_open,
1196         .close          = unix_close,
1197         .set_blksize    = unix_set_blksize,
1198         .read_blk       = unix_read_blk,
1199         .write_blk      = unix_write_blk,
1200         .flush          = unix_flush,
1201         .write_byte     = unix_write_byte,
1202         .set_option     = unix_set_option,
1203         .get_stats      = unix_get_stats,
1204         .read_blk64     = unix_read_blk64,
1205         .write_blk64    = unix_write_blk64,
1206         .discard        = unix_discard,
1207         .cache_readahead        = unix_cache_readahead,
1208         .zeroout        = unix_zeroout,
1209 };
1210
1211 io_manager unix_io_manager = &struct_unix_manager;
1212
1213 static struct struct_io_manager struct_unixfd_manager = {
1214         .magic          = EXT2_ET_MAGIC_IO_MANAGER,
1215         .name           = "Unix fd I/O Manager",
1216         .open           = unixfd_open,
1217         .close          = unix_close,
1218         .set_blksize    = unix_set_blksize,
1219         .read_blk       = unix_read_blk,
1220         .write_blk      = unix_write_blk,
1221         .flush          = unix_flush,
1222         .write_byte     = unix_write_byte,
1223         .set_option     = unix_set_option,
1224         .get_stats      = unix_get_stats,
1225         .read_blk64     = unix_read_blk64,
1226         .write_blk64    = unix_write_blk64,
1227         .discard        = unix_discard,
1228         .cache_readahead        = unix_cache_readahead,
1229         .zeroout        = unix_zeroout,
1230 };
1231
1232 io_manager unixfd_io_manager = &struct_unixfd_manager;