Get rid of O_ATOMIC
[fio.git] / filesetup.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <dirent.h>
6 #include <libgen.h>
7 #include <sys/stat.h>
8
9 #include "fio.h"
10 #include "smalloc.h"
11 #include "filehash.h"
12 #include "options.h"
13 #include "os/os.h"
14 #include "hash.h"
15 #include "lib/axmap.h"
16 #include "rwlock.h"
17 #include "zbd.h"
18
19 #ifdef CONFIG_LINUX_FALLOCATE
20 #include <linux/falloc.h>
21 #endif
22
23 static FLIST_HEAD(filename_list);
24
25 /*
26  * List entry for filename_list
27  */
28 struct file_name {
29         struct flist_head list;
30         char *filename;
31 };
32
33 static inline void clear_error(struct thread_data *td)
34 {
35         td->error = 0;
36         td->verror[0] = '\0';
37 }
38
39 static int native_fallocate(struct thread_data *td, struct fio_file *f)
40 {
41         bool success;
42
43         success = fio_fallocate(f, 0, f->real_file_size);
44         dprint(FD_FILE, "native fallocate of file %s size %llu was "
45                         "%ssuccessful\n", f->file_name,
46                         (unsigned long long) f->real_file_size,
47                         !success ? "un": "");
48
49         if (success)
50                 return false;
51
52         if (errno == ENOSYS)
53                 dprint(FD_FILE, "native fallocate is not implemented\n");
54
55         return true;
56 }
57
58 static void fallocate_file(struct thread_data *td, struct fio_file *f)
59 {
60         if (td->o.fill_device)
61                 return;
62
63         switch (td->o.fallocate_mode) {
64         case FIO_FALLOCATE_NATIVE:
65                 native_fallocate(td, f);
66                 break;
67         case FIO_FALLOCATE_NONE:
68                 break;
69 #ifdef CONFIG_POSIX_FALLOCATE
70         case FIO_FALLOCATE_POSIX: {
71                 int r;
72
73                 dprint(FD_FILE, "posix_fallocate file %s size %llu\n",
74                                  f->file_name,
75                                  (unsigned long long) f->real_file_size);
76
77                 r = posix_fallocate(f->fd, 0, f->real_file_size);
78                 if (r > 0)
79                         log_err("fio: posix_fallocate fails: %s\n", strerror(r));
80                 break;
81                 }
82 #endif /* CONFIG_POSIX_FALLOCATE */
83 #ifdef CONFIG_LINUX_FALLOCATE
84         case FIO_FALLOCATE_KEEP_SIZE: {
85                 int r;
86
87                 dprint(FD_FILE, "fallocate(FALLOC_FL_KEEP_SIZE) "
88                                 "file %s size %llu\n", f->file_name,
89                                 (unsigned long long) f->real_file_size);
90
91                 r = fallocate(f->fd, FALLOC_FL_KEEP_SIZE, 0, f->real_file_size);
92                 if (r != 0)
93                         td_verror(td, errno, "fallocate");
94
95                 break;
96                 }
97 #endif /* CONFIG_LINUX_FALLOCATE */
98         case FIO_FALLOCATE_TRUNCATE: {
99                 int r;
100
101                 dprint(FD_FILE, "ftruncate file %s size %llu\n",
102                                 f->file_name,
103                                 (unsigned long long) f->real_file_size);
104                 r = ftruncate(f->fd, f->real_file_size);
105                 if (r != 0)
106                         td_verror(td, errno, "ftruncate");
107
108                 break;
109         }
110         default:
111                 log_err("fio: unknown fallocate mode: %d\n", td->o.fallocate_mode);
112                 assert(0);
113         }
114 }
115
116 /*
117  * Leaves f->fd open on success, caller must close
118  */
119 static int extend_file(struct thread_data *td, struct fio_file *f)
120 {
121         int new_layout = 0, unlink_file = 0, flags;
122         unsigned long long left;
123         unsigned long long bs;
124         char *b = NULL;
125
126         if (read_only) {
127                 log_err("fio: refusing extend of file due to read-only\n");
128                 return 0;
129         }
130
131         /*
132          * check if we need to lay the file out complete again. fio
133          * does that for operations involving reads, or for writes
134          * where overwrite is set
135          */
136         if (td_read(td) ||
137            (td_write(td) && td->o.overwrite && !td->o.file_append) ||
138             (td_write(td) && td_ioengine_flagged(td, FIO_NOEXTEND)))
139                 new_layout = 1;
140         if (td_write(td) && !td->o.overwrite && !td->o.file_append)
141                 unlink_file = 1;
142
143         if (unlink_file || new_layout) {
144                 int ret;
145
146                 dprint(FD_FILE, "layout unlink %s\n", f->file_name);
147
148                 ret = td_io_unlink_file(td, f);
149                 if (ret != 0 && ret != ENOENT) {
150                         td_verror(td, errno, "unlink");
151                         return 1;
152                 }
153         }
154
155         flags = O_WRONLY;
156         if (td->o.allow_create)
157                 flags |= O_CREAT;
158         if (new_layout)
159                 flags |= O_TRUNC;
160
161 #ifdef WIN32
162         flags |= _O_BINARY;
163 #endif
164
165         dprint(FD_FILE, "open file %s, flags %x\n", f->file_name, flags);
166         f->fd = open(f->file_name, flags, 0644);
167         if (f->fd < 0) {
168                 int err = errno;
169
170                 if (err == ENOENT && !td->o.allow_create)
171                         log_err("fio: file creation disallowed by "
172                                         "allow_file_create=0\n");
173                 else
174                         td_verror(td, err, "open");
175                 return 1;
176         }
177
178         fallocate_file(td, f);
179
180         /*
181          * If our jobs don't require regular files initially, we're done.
182          */
183         if (!new_layout)
184                 goto done;
185
186         /*
187          * The size will be -1ULL when fill_device is used, so don't truncate
188          * or fallocate this file, just write it
189          */
190         if (!td->o.fill_device) {
191                 dprint(FD_FILE, "truncate file %s, size %llu\n", f->file_name,
192                                         (unsigned long long) f->real_file_size);
193                 if (ftruncate(f->fd, f->real_file_size) == -1) {
194                         if (errno != EFBIG) {
195                                 td_verror(td, errno, "ftruncate");
196                                 goto err;
197                         }
198                 }
199         }
200
201         left = f->real_file_size;
202         bs = td->o.max_bs[DDIR_WRITE];
203         if (bs > left)
204                 bs = left;
205
206         b = malloc(bs);
207         if (!b) {
208                 td_verror(td, errno, "malloc");
209                 goto err;
210         }
211
212         while (left && !td->terminate) {
213                 ssize_t r;
214
215                 if (bs > left)
216                         bs = left;
217
218                 fill_io_buffer(td, b, bs, bs);
219
220                 r = write(f->fd, b, bs);
221
222                 if (r > 0) {
223                         left -= r;
224                         continue;
225                 } else {
226                         if (r < 0) {
227                                 int __e = errno;
228
229                                 if (__e == ENOSPC || __e == EDQUOT) {
230                                         const char *__e_name;
231                                         if (td->o.fill_device)
232                                                 break;
233                                         if (__e == ENOSPC)
234                                                 __e_name = "ENOSPC";
235                                         else
236                                                 __e_name = "EDQUOT";
237                                         log_info("fio: %s on laying out "
238                                                  "file, stopping\n", __e_name);
239                                 }
240                                 td_verror(td, errno, "write");
241                         } else
242                                 td_verror(td, EIO, "write");
243
244                         goto err;
245                 }
246         }
247
248         if (td->terminate) {
249                 dprint(FD_FILE, "terminate unlink %s\n", f->file_name);
250                 td_io_unlink_file(td, f);
251         } else if (td->o.create_fsync) {
252                 if (fsync(f->fd) < 0) {
253                         td_verror(td, errno, "fsync");
254                         goto err;
255                 }
256         }
257         if (td->o.fill_device && !td_write(td)) {
258                 fio_file_clear_size_known(f);
259                 if (td_io_get_file_size(td, f))
260                         goto err;
261                 if (f->io_size > f->real_file_size)
262                         f->io_size = f->real_file_size;
263         }
264
265         free(b);
266 done:
267         return 0;
268 err:
269         close(f->fd);
270         f->fd = -1;
271         if (b)
272                 free(b);
273         return 1;
274 }
275
276 static bool pre_read_file(struct thread_data *td, struct fio_file *f)
277 {
278         int r, did_open = 0, old_runstate;
279         unsigned long long left;
280         unsigned long long bs;
281         bool ret = true;
282         char *b;
283
284         if (td_ioengine_flagged(td, FIO_PIPEIO) ||
285             td_ioengine_flagged(td, FIO_NOIO))
286                 return true;
287
288         if (f->filetype == FIO_TYPE_CHAR)
289                 return true;
290
291         if (!fio_file_open(f)) {
292                 if (td->io_ops->open_file(td, f)) {
293                         log_err("fio: cannot pre-read, failed to open file\n");
294                         return false;
295                 }
296                 did_open = 1;
297         }
298
299         old_runstate = td_bump_runstate(td, TD_PRE_READING);
300
301         left = f->io_size;
302         bs = td->o.max_bs[DDIR_READ];
303         if (bs > left)
304                 bs = left;
305
306         b = malloc(bs);
307         if (!b) {
308                 td_verror(td, errno, "malloc");
309                 ret = false;
310                 goto error;
311         }
312         memset(b, 0, bs);
313
314         if (lseek(f->fd, f->file_offset, SEEK_SET) < 0) {
315                 td_verror(td, errno, "lseek");
316                 log_err("fio: failed to lseek pre-read file\n");
317                 ret = false;
318                 goto error;
319         }
320
321         while (left && !td->terminate) {
322                 if (bs > left)
323                         bs = left;
324
325                 r = read(f->fd, b, bs);
326
327                 if (r == (int) bs) {
328                         left -= bs;
329                         continue;
330                 } else {
331                         td_verror(td, EIO, "pre_read");
332                         break;
333                 }
334         }
335
336 error:
337         td_restore_runstate(td, old_runstate);
338
339         if (did_open)
340                 td->io_ops->close_file(td, f);
341
342         free(b);
343         return ret;
344 }
345
346 /*
347  * Generic function to prepopulate regular file with data.
348  * Useful if you want to make sure I/O engine has data to read.
349  * Leaves f->fd open on success, caller must close.
350  */
351 int generic_prepopulate_file(struct thread_data *td, struct fio_file *f)
352 {
353         int flags;
354         unsigned long long left, bs;
355         char *b = NULL;
356
357         /* generic function for regular files only */
358         assert(f->filetype == FIO_TYPE_FILE);
359
360         if (read_only) {
361                 log_err("fio: refusing to write a file due to read-only\n");
362                 return 0;
363         }
364
365         flags = O_WRONLY;
366         if (td->o.allow_create)
367                 flags |= O_CREAT;
368
369 #ifdef WIN32
370         flags |= _O_BINARY;
371 #endif
372
373         dprint(FD_FILE, "open file %s, flags %x\n", f->file_name, flags);
374         f->fd = open(f->file_name, flags, 0644);
375         if (f->fd < 0) {
376                 int err = errno;
377
378                 if (err == ENOENT && !td->o.allow_create)
379                         log_err("fio: file creation disallowed by "
380                                         "allow_file_create=0\n");
381                 else
382                         td_verror(td, err, "open");
383                 return 1;
384         }
385
386         left = f->real_file_size;
387         bs = td->o.max_bs[DDIR_WRITE];
388         if (bs > left)
389                 bs = left;
390
391         b = malloc(bs);
392         if (!b) {
393                 td_verror(td, errno, "malloc");
394                 goto err;
395         }
396
397         while (left && !td->terminate) {
398                 ssize_t r;
399
400                 if (bs > left)
401                         bs = left;
402
403                 fill_io_buffer(td, b, bs, bs);
404
405                 r = write(f->fd, b, bs);
406
407                 if (r > 0) {
408                         left -= r;
409                 } else {
410                         td_verror(td, errno, "write");
411                         goto err;
412                 }
413         }
414
415         if (td->terminate) {
416                 dprint(FD_FILE, "terminate unlink %s\n", f->file_name);
417                 td_io_unlink_file(td, f);
418         } else if (td->o.create_fsync) {
419                 if (fsync(f->fd) < 0) {
420                         td_verror(td, errno, "fsync");
421                         goto err;
422                 }
423         }
424
425         free(b);
426         return 0;
427 err:
428         close(f->fd);
429         f->fd = -1;
430         if (b)
431                 free(b);
432         return 1;
433 }
434
435 unsigned long long get_rand_file_size(struct thread_data *td)
436 {
437         unsigned long long ret, sized;
438         uint64_t frand_max;
439         uint64_t r;
440
441         frand_max = rand_max(&td->file_size_state);
442         r = __rand(&td->file_size_state);
443         sized = td->o.file_size_high - td->o.file_size_low;
444         ret = (unsigned long long) ((double) sized * (r / (frand_max + 1.0)));
445         ret += td->o.file_size_low;
446         ret -= (ret % td->o.rw_min_bs);
447         return ret;
448 }
449
450 static int file_size(struct thread_data *td, struct fio_file *f)
451 {
452         struct stat st;
453
454         if (stat(f->file_name, &st) == -1) {
455                 td_verror(td, errno, "fstat");
456                 return 1;
457         }
458
459         f->real_file_size = st.st_size;
460         return 0;
461 }
462
463 static int bdev_size(struct thread_data *td, struct fio_file *f)
464 {
465         unsigned long long bytes = 0;
466         int r;
467
468         if (td->io_ops->open_file(td, f)) {
469                 log_err("fio: failed opening blockdev %s for size check\n",
470                         f->file_name);
471                 return 1;
472         }
473
474         r = blockdev_size(f, &bytes);
475         if (r) {
476                 td_verror(td, r, "blockdev_size");
477                 goto err;
478         }
479
480         if (!bytes) {
481                 log_err("%s: zero sized block device?\n", f->file_name);
482                 goto err;
483         }
484
485         f->real_file_size = bytes;
486         td->io_ops->close_file(td, f);
487         return 0;
488 err:
489         td->io_ops->close_file(td, f);
490         return 1;
491 }
492
493 static int char_size(struct thread_data *td, struct fio_file *f)
494 {
495 #ifdef FIO_HAVE_CHARDEV_SIZE
496         unsigned long long bytes = 0;
497         int r;
498
499         if (td->io_ops->open_file(td, f)) {
500                 log_err("fio: failed opening chardev %s for size check\n",
501                         f->file_name);
502                 return 1;
503         }
504
505         r = chardev_size(f, &bytes);
506         if (r) {
507                 td_verror(td, r, "chardev_size");
508                 goto err;
509         }
510
511         if (!bytes) {
512                 log_err("%s: zero sized char device?\n", f->file_name);
513                 goto err;
514         }
515
516         f->real_file_size = bytes;
517         td->io_ops->close_file(td, f);
518         return 0;
519 err:
520         td->io_ops->close_file(td, f);
521         return 1;
522 #else
523         f->real_file_size = -1ULL;
524         return 0;
525 #endif
526 }
527
528 static int get_file_size(struct thread_data *td, struct fio_file *f)
529 {
530         int ret = 0;
531
532         if (fio_file_size_known(f))
533                 return 0;
534
535         if (f->filetype == FIO_TYPE_FILE)
536                 ret = file_size(td, f);
537         else if (f->filetype == FIO_TYPE_BLOCK)
538                 ret = bdev_size(td, f);
539         else if (f->filetype == FIO_TYPE_CHAR)
540                 ret = char_size(td, f);
541         else {
542                 f->real_file_size = -1;
543                 log_info("%s: failed to get file size of %s\n", td->o.name,
544                                         f->file_name);
545                 return 1; /* avoid offset extends end error message */
546         }
547
548         /*
549          * Leave ->real_file_size with 0 since it could be expectation
550          * of initial setup for regular files.
551          */
552         if (ret)
553                 return ret;
554
555         /*
556          * ->file_offset normally hasn't been initialized yet, so this
557          * is basically always false unless ->real_file_size is -1, but
558          * if ->real_file_size is -1 this message doesn't make sense.
559          * As a result, this message is basically useless.
560          */
561         if (f->file_offset > f->real_file_size) {
562                 log_err("%s: offset extends end (%llu > %llu)\n", td->o.name,
563                                         (unsigned long long) f->file_offset,
564                                         (unsigned long long) f->real_file_size);
565                 return 1;
566         }
567
568         fio_file_set_size_known(f);
569         return 0;
570 }
571
572 static int __file_invalidate_cache(struct thread_data *td, struct fio_file *f,
573                                    unsigned long long off,
574                                    unsigned long long len)
575 {
576         int errval = 0, ret = 0;
577
578 #ifdef CONFIG_ESX
579         return 0;
580 #endif
581
582         if (len == -1ULL)
583                 len = f->io_size;
584         if (off == -1ULL)
585                 off = f->file_offset;
586
587         if (len == -1ULL || off == -1ULL)
588                 return 0;
589
590         if (td->io_ops->invalidate) {
591                 dprint(FD_IO, "invalidate %s cache %s\n", td->io_ops->name,
592                         f->file_name);
593                 ret = td->io_ops->invalidate(td, f);
594                 if (ret < 0)
595                         errval = -ret;
596         } else if (td_ioengine_flagged(td, FIO_DISKLESSIO)) {
597                 dprint(FD_IO, "invalidate not supported by ioengine %s\n",
598                        td->io_ops->name);
599         } else if (f->filetype == FIO_TYPE_FILE) {
600                 dprint(FD_IO, "declare unneeded cache %s: %llu/%llu\n",
601                         f->file_name, off, len);
602                 ret = posix_fadvise(f->fd, off, len, POSIX_FADV_DONTNEED);
603                 if (ret)
604                         errval = ret;
605         } else if (f->filetype == FIO_TYPE_BLOCK) {
606                 int retry_count = 0;
607
608                 dprint(FD_IO, "drop page cache %s\n", f->file_name);
609                 ret = blockdev_invalidate_cache(f);
610                 while (ret < 0 && errno == EAGAIN && retry_count++ < 25) {
611                         /*
612                          * Linux multipath devices reject ioctl while
613                          * the maps are being updated. That window can
614                          * last tens of milliseconds; we'll try up to
615                          * a quarter of a second.
616                          */
617                         usleep(10000);
618                         ret = blockdev_invalidate_cache(f);
619                 }
620                 if (ret < 0 && errno == EACCES && geteuid()) {
621                         if (!fio_did_warn(FIO_WARN_ROOT_FLUSH)) {
622                                 log_err("fio: only root may flush block "
623                                         "devices. Cache flush bypassed!\n");
624                         }
625                 }
626                 if (ret < 0)
627                         errval = errno;
628         } else if (f->filetype == FIO_TYPE_CHAR ||
629                    f->filetype == FIO_TYPE_PIPE) {
630                 dprint(FD_IO, "invalidate not supported %s\n", f->file_name);
631         }
632
633         /*
634          * Cache flushing isn't a fatal condition, and we know it will
635          * happen on some platforms where we don't have the proper
636          * function to flush eg block device caches. So just warn and
637          * continue on our way.
638          */
639         if (errval)
640                 log_info("fio: cache invalidation of %s failed: %s\n",
641                          f->file_name, strerror(errval));
642
643         return 0;
644
645 }
646
647 int file_invalidate_cache(struct thread_data *td, struct fio_file *f)
648 {
649         if (!fio_file_open(f))
650                 return 0;
651
652         return __file_invalidate_cache(td, f, -1ULL, -1ULL);
653 }
654
655 int generic_close_file(struct thread_data fio_unused *td, struct fio_file *f)
656 {
657         int ret = 0;
658
659         dprint(FD_FILE, "fd close %s\n", f->file_name);
660
661         remove_file_hash(f);
662
663         if (close(f->fd) < 0)
664                 ret = errno;
665
666         f->fd = -1;
667
668         if (f->shadow_fd != -1) {
669                 close(f->shadow_fd);
670                 f->shadow_fd = -1;
671         }
672
673         f->engine_pos = 0;
674         return ret;
675 }
676
677 int file_lookup_open(struct fio_file *f, int flags)
678 {
679         struct fio_file *__f;
680         int from_hash;
681
682         __f = lookup_file_hash(f->file_name);
683         if (__f) {
684                 dprint(FD_FILE, "found file in hash %s\n", f->file_name);
685                 f->lock = __f->lock;
686                 from_hash = 1;
687         } else {
688                 dprint(FD_FILE, "file not found in hash %s\n", f->file_name);
689                 from_hash = 0;
690         }
691
692 #ifdef WIN32
693         flags |= _O_BINARY;
694 #endif
695
696         f->fd = open(f->file_name, flags, 0600);
697         return from_hash;
698 }
699
700 static int file_close_shadow_fds(struct thread_data *td)
701 {
702         struct fio_file *f;
703         int num_closed = 0;
704         unsigned int i;
705
706         for_each_file(td, f, i) {
707                 if (f->shadow_fd == -1)
708                         continue;
709
710                 close(f->shadow_fd);
711                 f->shadow_fd = -1;
712                 num_closed++;
713         }
714
715         return num_closed;
716 }
717
718 int generic_open_file(struct thread_data *td, struct fio_file *f)
719 {
720         int is_std = 0;
721         int flags = 0;
722         int from_hash = 0;
723
724         dprint(FD_FILE, "fd open %s\n", f->file_name);
725
726         if (!strcmp(f->file_name, "-")) {
727                 if (td_rw(td)) {
728                         log_err("fio: can't read/write to stdin/out\n");
729                         return 1;
730                 }
731                 is_std = 1;
732
733                 /*
734                  * move output logging to stderr, if we are writing to stdout
735                  */
736                 if (td_write(td))
737                         f_out = stderr;
738         }
739
740         if (td_trim(td))
741                 goto skip_flags;
742         if (td->o.odirect)
743                 flags |= OS_O_DIRECT;
744         flags |= td->o.sync_io;
745         if (td->o.create_on_open && td->o.allow_create)
746                 flags |= O_CREAT;
747 skip_flags:
748         if (f->filetype != FIO_TYPE_FILE)
749                 flags |= FIO_O_NOATIME;
750
751 open_again:
752         if (td_write(td)) {
753                 if (!read_only)
754                         flags |= O_RDWR;
755
756                 if (f->filetype == FIO_TYPE_FILE && td->o.allow_create)
757                         flags |= O_CREAT;
758
759                 if (is_std)
760                         f->fd = dup(STDOUT_FILENO);
761                 else
762                         from_hash = file_lookup_open(f, flags);
763         } else if (td_read(td)) {
764                 if (td_ioengine_flagged(td, FIO_RO_NEEDS_RW_OPEN) && !read_only)
765                         flags |= O_RDWR;
766                 else
767                         flags |= O_RDONLY;
768
769                 if (is_std)
770                         f->fd = dup(STDIN_FILENO);
771                 else
772                         from_hash = file_lookup_open(f, flags);
773         } else if (td_trim(td)) {
774                 assert(!td_rw(td)); /* should have matched above */
775                 if (!read_only)
776                         flags |= O_RDWR;
777                 from_hash = file_lookup_open(f, flags);
778         }
779
780         if (f->fd == -1) {
781                 char buf[FIO_VERROR_SIZE];
782                 int __e = errno;
783
784                 if (__e == EPERM && (flags & FIO_O_NOATIME)) {
785                         flags &= ~FIO_O_NOATIME;
786                         goto open_again;
787                 }
788                 if (__e == EMFILE && file_close_shadow_fds(td))
789                         goto open_again;
790
791                 snprintf(buf, sizeof(buf), "open(%s)", f->file_name);
792
793                 if (__e == EINVAL && (flags & OS_O_DIRECT)) {
794                         log_err("fio: looks like your file system does not " \
795                                 "support direct=1/buffered=0\n");
796                 }
797
798                 td_verror(td, __e, buf);
799                 return 1;
800         }
801
802         if (!from_hash && f->fd != -1) {
803                 if (add_file_hash(f)) {
804                         int fio_unused ret;
805
806                         /*
807                          * Stash away descriptor for later close. This is to
808                          * work-around a "feature" on Linux, where a close of
809                          * an fd that has been opened for write will trigger
810                          * udev to call blkid to check partitions, fs id, etc.
811                          * That pollutes the device cache, which can slow down
812                          * unbuffered accesses.
813                          */
814                         if (f->shadow_fd == -1)
815                                 f->shadow_fd = f->fd;
816                         else {
817                                 /*
818                                  * OK to ignore, we haven't done anything
819                                  * with it
820                                  */
821                                 ret = generic_close_file(td, f);
822                         }
823                         goto open_again;
824                 }
825         }
826
827         return 0;
828 }
829
830 /*
831  * This function i.e. get_file_size() is the default .get_file_size
832  * implementation of majority of I/O engines.
833  */
834 int generic_get_file_size(struct thread_data *td, struct fio_file *f)
835 {
836         return get_file_size(td, f);
837 }
838
839 /*
840  * open/close all files, so that ->real_file_size gets set
841  */
842 static int get_file_sizes(struct thread_data *td)
843 {
844         struct fio_file *f;
845         unsigned int i;
846         int err = 0;
847
848         for_each_file(td, f, i) {
849                 dprint(FD_FILE, "get file size for %p/%d/%s\n", f, i,
850                                                                 f->file_name);
851
852                 if (td_io_get_file_size(td, f)) {
853                         if (td->error != ENOENT) {
854                                 log_err("%s\n", td->verror);
855                                 err = 1;
856                                 break;
857                         }
858                         clear_error(td);
859                 }
860
861                 /*
862                  * There are corner cases where we end up with -1 for
863                  * ->real_file_size due to unsupported file type, etc.
864                  * We then just set to size option value divided by number
865                  * of files, similar to the way file ->io_size is set.
866                  * stat(2) failure doesn't set ->real_file_size to -1.
867                  */
868                 if (f->real_file_size == -1ULL && td->o.size)
869                         f->real_file_size = td->o.size / td->o.nr_files;
870         }
871
872         return err;
873 }
874
875 struct fio_mount {
876         struct flist_head list;
877         const char *base;
878         char __base[256];
879         unsigned int key;
880 };
881
882 /*
883  * Get free number of bytes for each file on each unique mount.
884  */
885 static unsigned long long get_fs_free_counts(struct thread_data *td)
886 {
887         struct flist_head *n, *tmp;
888         unsigned long long ret = 0;
889         struct fio_mount *fm;
890         FLIST_HEAD(list);
891         struct fio_file *f;
892         unsigned int i;
893
894         for_each_file(td, f, i) {
895                 struct stat sb;
896                 char buf[256];
897
898                 if (f->filetype == FIO_TYPE_BLOCK || f->filetype == FIO_TYPE_CHAR) {
899                         if (f->real_file_size != -1ULL)
900                                 ret += f->real_file_size;
901                         continue;
902                 } else if (f->filetype != FIO_TYPE_FILE)
903                         continue;
904
905                 snprintf(buf, FIO_ARRAY_SIZE(buf), "%s", f->file_name);
906
907                 if (stat(buf, &sb) < 0) {
908                         if (errno != ENOENT)
909                                 break;
910                         strcpy(buf, ".");
911                         if (stat(buf, &sb) < 0)
912                                 break;
913                 }
914
915                 fm = NULL;
916                 flist_for_each(n, &list) {
917                         fm = flist_entry(n, struct fio_mount, list);
918                         if (fm->key == sb.st_dev)
919                                 break;
920
921                         fm = NULL;
922                 }
923
924                 if (fm)
925                         continue;
926
927                 fm = calloc(1, sizeof(*fm));
928                 snprintf(fm->__base, FIO_ARRAY_SIZE(fm->__base), "%s", buf);
929                 fm->base = basename(fm->__base);
930                 fm->key = sb.st_dev;
931                 flist_add(&fm->list, &list);
932         }
933
934         flist_for_each_safe(n, tmp, &list) {
935                 unsigned long long sz;
936
937                 fm = flist_entry(n, struct fio_mount, list);
938                 flist_del(&fm->list);
939
940                 sz = get_fs_free_size(fm->base);
941                 if (sz && sz != -1ULL)
942                         ret += sz;
943
944                 free(fm);
945         }
946
947         return ret;
948 }
949
950 uint64_t get_start_offset(struct thread_data *td, struct fio_file *f)
951 {
952         bool align = false;
953         struct thread_options *o = &td->o;
954         unsigned long long align_bs;
955         unsigned long long offset;
956         unsigned long long increment;
957
958         if (o->file_append && f->filetype == FIO_TYPE_FILE)
959                 return f->real_file_size;
960
961         if (o->offset_increment_percent) {
962                 assert(!o->offset_increment);
963                 increment = o->offset_increment_percent * f->real_file_size / 100;
964                 align = true;
965         } else
966                 increment = o->offset_increment;
967
968         if (o->start_offset_percent > 0) {
969                 /* calculate the raw offset */
970                 offset = (f->real_file_size * o->start_offset_percent / 100) +
971                         (td->subjob_number * increment);
972
973                 align = true;
974         } else {
975                 /* start_offset_percent not set */
976                 offset = o->start_offset +
977                                 td->subjob_number * increment;
978         }
979
980         if (align) {
981                 /*
982                  * if offset_align is provided, use it
983                  */
984                 if (fio_option_is_set(o, start_offset_align)) {
985                         align_bs = o->start_offset_align;
986                 } else {
987                         /* else take the minimum block size */
988                         align_bs = td_min_bs(td);
989                 }
990
991                 /*
992                  * block align the offset at the next available boundary at
993                  * ceiling(offset / align_bs) * align_bs
994                  */
995                 offset = (offset / align_bs + (offset % align_bs != 0)) * align_bs;
996         }
997
998         return offset;
999 }
1000
1001 /*
1002  * Find longest path component that exists and return its length
1003  */
1004 int longest_existing_path(char *path) {
1005         char buf[PATH_MAX];
1006         bool done;
1007         char *buf_pos;
1008         int offset;
1009 #ifdef WIN32
1010         DWORD dwAttr;
1011 #else
1012         struct stat sb;
1013 #endif
1014
1015         sprintf(buf, "%s", path);
1016         done = false;
1017         while (!done) {
1018                 buf_pos = strrchr(buf, FIO_OS_PATH_SEPARATOR);
1019                 if (!buf_pos) {
1020                         offset = 0;
1021                         break;
1022                 }
1023
1024                 *(buf_pos + 1) = '\0';
1025
1026 #ifdef WIN32
1027                 dwAttr = GetFileAttributesA(buf);
1028                 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1029                         done = true;
1030                 }
1031 #else
1032                 if (stat(buf, &sb) == 0)
1033                         done = true;
1034 #endif
1035                 if (done)
1036                         offset = buf_pos - buf;
1037                 else
1038                         *buf_pos = '\0';
1039         }
1040
1041         return offset;
1042 }
1043
1044 static bool create_work_dirs(struct thread_data *td, const char *fname)
1045 {
1046         char path[PATH_MAX];
1047         char *start, *end;
1048         int offset;
1049
1050         snprintf(path, PATH_MAX, "%s", fname);
1051         start = path;
1052
1053         offset = longest_existing_path(path);
1054         end = start + offset;
1055         while ((end = strchr(end, FIO_OS_PATH_SEPARATOR)) != NULL) {
1056                 if (end == start) {
1057                         end++;
1058                         continue;
1059                 }
1060                 *end = '\0';
1061                 errno = 0;
1062                 if (fio_mkdir(path, 0700) && errno != EEXIST) {
1063                         log_err("fio: failed to create dir (%s): %s\n",
1064                                 start, strerror(errno));
1065                         return false;
1066                 }
1067                 *end = FIO_OS_PATH_SEPARATOR;
1068                 end++;
1069         }
1070         td->flags |= TD_F_DIRS_CREATED;
1071         return true;
1072 }
1073
1074 /*
1075  * Open the files and setup files sizes, creating files if necessary.
1076  */
1077 int setup_files(struct thread_data *td)
1078 {
1079         unsigned long long total_size, extend_size;
1080         struct thread_options *o = &td->o;
1081         struct fio_file *f;
1082         unsigned int i, nr_fs_extra = 0;
1083         int err = 0, need_extend;
1084         int old_state;
1085         const unsigned long long bs = td_min_bs(td);
1086         uint64_t fs = 0;
1087
1088         dprint(FD_FILE, "setup files\n");
1089
1090         old_state = td_bump_runstate(td, TD_SETTING_UP);
1091
1092         for_each_file(td, f, i) {
1093                 if (!td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1094                     strchr(f->file_name, FIO_OS_PATH_SEPARATOR) &&
1095                     !(td->flags & TD_F_DIRS_CREATED) &&
1096                     !create_work_dirs(td, f->file_name))
1097                         goto err_out;
1098         }
1099
1100         /*
1101          * Find out physical size of files or devices for this thread,
1102          * before we determine I/O size and range of our targets.
1103          * If ioengine defines a setup() method, it's responsible for
1104          * opening the files and setting f->real_file_size to indicate
1105          * the valid range for that file.
1106          */
1107         if (td->io_ops->setup)
1108                 err = td->io_ops->setup(td);
1109         else
1110                 err = get_file_sizes(td);
1111
1112         if (err)
1113                 goto err_out;
1114
1115         if (td->o.zone_mode == ZONE_MODE_ZBD) {
1116                 err = zbd_init_files(td);
1117                 if (err)
1118                         goto err_out;
1119         }
1120         zbd_recalc_options_with_zone_granularity(td);
1121
1122         if (o->read_iolog_file)
1123                 goto done;
1124
1125         /*
1126          * check sizes. if the files/devices do not exist and the size
1127          * isn't passed to fio, abort.
1128          */
1129         total_size = 0;
1130         for_each_file(td, f, i) {
1131                 f->fileno = i;
1132                 if (f->real_file_size == -1ULL)
1133                         total_size = -1ULL;
1134                 else
1135                         total_size += f->real_file_size;
1136         }
1137
1138         if (o->fill_device)
1139                 td->fill_device_size = get_fs_free_counts(td);
1140
1141         /*
1142          * device/file sizes are zero and no size given, punt
1143          */
1144         if ((!total_size || total_size == -1ULL) && !o->size &&
1145             !td_ioengine_flagged(td, FIO_NOIO) && !o->fill_device &&
1146             !(o->nr_files && (o->file_size_low || o->file_size_high))) {
1147                 log_err("%s: you need to specify size=\n", o->name);
1148                 td_verror(td, EINVAL, "total_file_size");
1149                 goto err_out;
1150         }
1151
1152         /*
1153          * Calculate per-file size and potential extra size for the
1154          * first files, if needed (i.e. if we don't have a fixed size).
1155          */
1156         if (!o->file_size_low && o->nr_files) {
1157                 uint64_t all_fs;
1158
1159                 fs = o->size / o->nr_files;
1160                 all_fs = fs * o->nr_files;
1161
1162                 if (all_fs < o->size)
1163                         nr_fs_extra = (o->size - all_fs) / bs;
1164         }
1165
1166         /*
1167          * now file sizes are known, so we can set ->io_size. if size= is
1168          * not given, ->io_size is just equal to ->real_file_size. if size
1169          * is given, ->io_size is size / nr_files.
1170          */
1171         extend_size = total_size = 0;
1172         need_extend = 0;
1173         for_each_file(td, f, i) {
1174                 f->file_offset = get_start_offset(td, f);
1175
1176                 /*
1177                  * Update ->io_size depending on options specified.
1178                  * ->file_size_low being 0 means filesize option isn't set.
1179                  * Non zero ->file_size_low equals ->file_size_high means
1180                  * filesize option is set in a fixed size format.
1181                  * Non zero ->file_size_low not equals ->file_size_high means
1182                  * filesize option is set in a range format.
1183                  */
1184                 if (!o->file_size_low) {
1185                         /*
1186                          * no file size or range given, file size is equal to
1187                          * total size divided by number of files. If the size
1188                          * doesn't divide nicely with the min blocksize,
1189                          * make the first files bigger.
1190                          */
1191                         f->io_size = fs;
1192                         if (nr_fs_extra) {
1193                                 nr_fs_extra--;
1194                                 f->io_size += bs;
1195                         }
1196
1197                         /*
1198                          * We normally don't come here for regular files, but
1199                          * if the result is 0 for a regular file, set it to the
1200                          * real file size. This could be size of the existing
1201                          * one if it already exists, but otherwise will be set
1202                          * to 0. A new file won't be created because
1203                          * ->io_size + ->file_offset equals ->real_file_size.
1204                          */
1205                         if (!f->io_size) {
1206                                 if (f->file_offset > f->real_file_size)
1207                                         goto err_offset;
1208                                 f->io_size = f->real_file_size - f->file_offset;
1209                                 if (!f->io_size)
1210                                         log_info("fio: file %s may be ignored\n",
1211                                                 f->file_name);
1212                         }
1213                 } else if (f->real_file_size < o->file_size_low ||
1214                            f->real_file_size > o->file_size_high) {
1215                         if (f->file_offset > o->file_size_low)
1216                                 goto err_offset;
1217                         /*
1218                          * file size given. if it's fixed, use that. if it's a
1219                          * range, generate a random size in-between.
1220                          */
1221                         if (o->file_size_low == o->file_size_high)
1222                                 f->io_size = o->file_size_low - f->file_offset;
1223                         else {
1224                                 f->io_size = get_rand_file_size(td)
1225                                                 - f->file_offset;
1226                         }
1227                 } else
1228                         f->io_size = f->real_file_size - f->file_offset;
1229
1230                 if (f->io_size == -1ULL)
1231                         total_size = -1ULL;
1232                 else {
1233                         uint64_t io_size;
1234
1235                         if (o->size_percent && o->size_percent != 100) {
1236                                 uint64_t file_size;
1237
1238                                 file_size = f->io_size + f->file_offset;
1239                                 f->io_size = (file_size *
1240                                               o->size_percent) / 100;
1241                                 if (f->io_size > (file_size - f->file_offset))
1242                                         f->io_size = file_size - f->file_offset;
1243
1244                                 f->io_size -= (f->io_size % td_min_bs(td));
1245                         }
1246
1247                         io_size = f->io_size;
1248                         if (o->io_size_percent && o->io_size_percent != 100) {
1249                                 io_size *= o->io_size_percent;
1250                                 io_size /= 100;
1251                         }
1252
1253                         total_size += io_size;
1254                 }
1255
1256                 if (f->filetype == FIO_TYPE_FILE &&
1257                     (f->io_size + f->file_offset) > f->real_file_size) {
1258                         if (!td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1259                             !o->create_on_open) {
1260                                 need_extend++;
1261                                 extend_size += (f->io_size + f->file_offset);
1262                                 fio_file_set_extend(f);
1263                         } else if (!td_ioengine_flagged(td, FIO_DISKLESSIO) ||
1264                                    (td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1265                                     td_ioengine_flagged(td, FIO_FAKEIO)))
1266                                 f->real_file_size = f->io_size + f->file_offset;
1267                 }
1268         }
1269
1270         if (td->o.block_error_hist) {
1271                 int len;
1272
1273                 assert(td->o.nr_files == 1);    /* checked in fixup_options */
1274                 f = td->files[0];
1275                 len = f->io_size / td->o.bs[DDIR_TRIM];
1276                 if (len > MAX_NR_BLOCK_INFOS || len <= 0) {
1277                         log_err("fio: cannot calculate block histogram with "
1278                                 "%d trim blocks, maximum %d\n",
1279                                 len, MAX_NR_BLOCK_INFOS);
1280                         td_verror(td, EINVAL, "block_error_hist");
1281                         goto err_out;
1282                 }
1283
1284                 td->ts.nr_block_infos = len;
1285                 for (i = 0; i < len; i++)
1286                         td->ts.block_infos[i] =
1287                                 BLOCK_INFO(0, BLOCK_STATE_UNINIT);
1288         } else
1289                 td->ts.nr_block_infos = 0;
1290
1291         if (!o->size || (total_size && o->size > total_size))
1292                 o->size = total_size;
1293
1294         if (o->size < td_min_bs(td)) {
1295                 log_err("fio: blocksize is larger than data set range\n");
1296                 goto err_out;
1297         }
1298
1299         /*
1300          * See if we need to extend some files, typically needed when our
1301          * target regular files don't exist yet, but our jobs require them
1302          * initially due to read I/Os.
1303          */
1304         if (need_extend) {
1305                 temp_stall_ts = 1;
1306                 if (output_format & FIO_OUTPUT_NORMAL) {
1307                         log_info("%s: Laying out IO file%s (%u file%s / %s%lluMiB)\n",
1308                                  o->name,
1309                                  need_extend > 1 ? "s" : "",
1310                                  need_extend,
1311                                  need_extend > 1 ? "s" : "",
1312                                  need_extend > 1 ? "total " : "",
1313                                  extend_size >> 20);
1314                 }
1315
1316                 for_each_file(td, f, i) {
1317                         unsigned long long old_len = -1ULL, extend_len = -1ULL;
1318
1319                         if (!fio_file_extend(f))
1320                                 continue;
1321
1322                         assert(f->filetype == FIO_TYPE_FILE);
1323                         fio_file_clear_extend(f);
1324                         if (!o->fill_device) {
1325                                 old_len = f->real_file_size;
1326                                 extend_len = f->io_size + f->file_offset -
1327                                                 old_len;
1328                         }
1329                         f->real_file_size = (f->io_size + f->file_offset);
1330                         err = extend_file(td, f);
1331                         if (err)
1332                                 break;
1333
1334                         err = __file_invalidate_cache(td, f, old_len,
1335                                                                 extend_len);
1336
1337                         /*
1338                          * Shut up static checker
1339                          */
1340                         if (f->fd != -1)
1341                                 close(f->fd);
1342
1343                         f->fd = -1;
1344                         if (err)
1345                                 break;
1346                 }
1347                 temp_stall_ts = 0;
1348         }
1349
1350         if (err)
1351                 goto err_out;
1352
1353         /*
1354          * Prepopulate files with data. It might be expected to read some
1355          * "real" data instead of zero'ed files (if no writes to file occurred
1356          * prior to a read job). Engine has to provide a way to do that.
1357          */
1358         if (td->io_ops->prepopulate_file) {
1359                 temp_stall_ts = 1;
1360
1361                 for_each_file(td, f, i) {
1362                         if (output_format & FIO_OUTPUT_NORMAL) {
1363                                 log_info("%s: Prepopulating IO file (%s)\n",
1364                                                         o->name, f->file_name);
1365                         }
1366
1367                         err = td->io_ops->prepopulate_file(td, f);
1368                         if (err)
1369                                 break;
1370
1371                         err = __file_invalidate_cache(td, f, f->file_offset,
1372                                                                 f->io_size);
1373
1374                         /*
1375                          * Shut up static checker
1376                          */
1377                         if (f->fd != -1)
1378                                 close(f->fd);
1379
1380                         f->fd = -1;
1381                         if (err)
1382                                 break;
1383                 }
1384                 temp_stall_ts = 0;
1385         }
1386
1387         if (err)
1388                 goto err_out;
1389
1390         /*
1391          * iolog already set the total io size, if we read back
1392          * stored entries.
1393          */
1394         if (!o->read_iolog_file) {
1395                 if (o->io_size)
1396                         td->total_io_size = o->io_size * o->loops;
1397                 else
1398                         td->total_io_size = o->size * o->loops;
1399         }
1400
1401 done:
1402         if (td->o.zone_mode == ZONE_MODE_ZBD) {
1403                 err = zbd_setup_files(td);
1404                 if (err)
1405                         goto err_out;
1406         }
1407
1408         if (o->create_only)
1409                 td->done = 1;
1410
1411         td_restore_runstate(td, old_state);
1412
1413         return 0;
1414
1415 err_offset:
1416         log_err("%s: you need to specify valid offset=\n", o->name);
1417 err_out:
1418         td_restore_runstate(td, old_state);
1419         return 1;
1420 }
1421
1422 bool pre_read_files(struct thread_data *td)
1423 {
1424         struct fio_file *f;
1425         unsigned int i;
1426
1427         dprint(FD_FILE, "pre_read files\n");
1428
1429         for_each_file(td, f, i) {
1430                 if (!pre_read_file(td, f))
1431                         return false;
1432         }
1433
1434         return true;
1435 }
1436
1437 static void __init_rand_distribution(struct thread_data *td, struct fio_file *f)
1438 {
1439         unsigned int range_size, seed;
1440         uint64_t nranges;
1441         uint64_t fsize;
1442
1443         range_size = min(td->o.min_bs[DDIR_READ], td->o.min_bs[DDIR_WRITE]);
1444         fsize = min(f->real_file_size, f->io_size);
1445
1446         nranges = (fsize + range_size - 1ULL) / range_size;
1447
1448         seed = jhash(f->file_name, strlen(f->file_name), 0) * td->thread_number;
1449         if (!td->o.rand_repeatable)
1450                 seed = td->rand_seeds[FIO_RAND_BLOCK_OFF];
1451
1452         if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
1453                 zipf_init(&f->zipf, nranges, td->o.zipf_theta.u.f, td->o.random_center.u.f, seed);
1454         else if (td->o.random_distribution == FIO_RAND_DIST_PARETO)
1455                 pareto_init(&f->zipf, nranges, td->o.pareto_h.u.f, td->o.random_center.u.f, seed);
1456         else if (td->o.random_distribution == FIO_RAND_DIST_GAUSS)
1457                 gauss_init(&f->gauss, nranges, td->o.gauss_dev.u.f, td->o.random_center.u.f, seed);
1458 }
1459
1460 static bool init_rand_distribution(struct thread_data *td)
1461 {
1462         struct fio_file *f;
1463         unsigned int i;
1464         int state;
1465
1466         if (td->o.random_distribution == FIO_RAND_DIST_RANDOM ||
1467             td->o.random_distribution == FIO_RAND_DIST_ZONED ||
1468             td->o.random_distribution == FIO_RAND_DIST_ZONED_ABS)
1469                 return false;
1470
1471         state = td_bump_runstate(td, TD_SETTING_UP);
1472
1473         for_each_file(td, f, i)
1474                 __init_rand_distribution(td, f);
1475
1476         td_restore_runstate(td, state);
1477         return true;
1478 }
1479
1480 /*
1481  * Check if the number of blocks exceeds the randomness capability of
1482  * the selected generator. Tausworthe is 32-bit, the others are fully
1483  * 64-bit capable.
1484  */
1485 static int check_rand_gen_limits(struct thread_data *td, struct fio_file *f,
1486                                  uint64_t blocks)
1487 {
1488         if (blocks <= FRAND32_MAX)
1489                 return 0;
1490         if (td->o.random_generator != FIO_RAND_GEN_TAUSWORTHE)
1491                 return 0;
1492
1493         /*
1494          * If the user hasn't specified a random generator, switch
1495          * to tausworthe64 with informational warning. If the user did
1496          * specify one, just warn.
1497          */
1498         log_info("fio: file %s exceeds 32-bit tausworthe random generator.\n",
1499                         f->file_name);
1500
1501         if (!fio_option_is_set(&td->o, random_generator)) {
1502                 log_info("fio: Switching to tausworthe64. Use the "
1503                          "random_generator= option to get rid of this "
1504                          "warning.\n");
1505                 td->o.random_generator = FIO_RAND_GEN_TAUSWORTHE64;
1506                 return 0;
1507         }
1508
1509         /*
1510          * Just make this information to avoid breaking scripts.
1511          */
1512         log_info("fio: Use the random_generator= option to switch to lfsr or "
1513                          "tausworthe64.\n");
1514         return 0;
1515 }
1516
1517 bool init_random_map(struct thread_data *td)
1518 {
1519         unsigned long long blocks;
1520         struct fio_file *f;
1521         unsigned int i;
1522
1523         if (init_rand_distribution(td))
1524                 return true;
1525         if (!td_random(td))
1526                 return true;
1527
1528         for_each_file(td, f, i) {
1529                 uint64_t fsize = min(f->real_file_size, f->io_size);
1530
1531                 if (td->o.zone_mode == ZONE_MODE_STRIDED)
1532                         fsize = td->o.zone_range;
1533
1534                 blocks = fsize / (unsigned long long) td->o.rw_min_bs;
1535
1536                 if (check_rand_gen_limits(td, f, blocks))
1537                         return false;
1538
1539                 if (td->o.random_generator == FIO_RAND_GEN_LFSR) {
1540                         uint64_t seed;
1541
1542                         seed = td->rand_seeds[FIO_RAND_BLOCK_OFF];
1543
1544                         if (!lfsr_init(&f->lfsr, blocks, seed, 0)) {
1545                                 fio_file_set_lfsr(f);
1546                                 continue;
1547                         } else {
1548                                 log_err("fio: failed initializing LFSR\n");
1549                                 return false;
1550                         }
1551                 } else if (!td->o.norandommap) {
1552                         f->io_axmap = axmap_new(blocks);
1553                         if (f->io_axmap) {
1554                                 fio_file_set_axmap(f);
1555                                 continue;
1556                         }
1557                 } else if (td->o.norandommap)
1558                         continue;
1559
1560                 if (!td->o.softrandommap) {
1561                         log_err("fio: failed allocating random map. If running"
1562                                 " a large number of jobs, try the 'norandommap'"
1563                                 " option or set 'softrandommap'. Or give"
1564                                 " a larger --alloc-size to fio.\n");
1565                         return false;
1566                 }
1567
1568                 log_info("fio: file %s failed allocating random map. Running "
1569                          "job without.\n", f->file_name);
1570         }
1571
1572         return true;
1573 }
1574
1575 void close_files(struct thread_data *td)
1576 {
1577         struct fio_file *f;
1578         unsigned int i;
1579
1580         for_each_file(td, f, i) {
1581                 if (fio_file_open(f))
1582                         td_io_close_file(td, f);
1583         }
1584 }
1585
1586 void fio_file_free(struct fio_file *f)
1587 {
1588         if (fio_file_axmap(f))
1589                 axmap_free(f->io_axmap);
1590         if (!fio_file_smalloc(f)) {
1591                 free(f->file_name);
1592                 free(f);
1593         } else {
1594                 sfree(f->file_name);
1595                 sfree(f);
1596         }
1597 }
1598
1599 void close_and_free_files(struct thread_data *td)
1600 {
1601         struct fio_file *f;
1602         unsigned int i;
1603
1604         dprint(FD_FILE, "close files\n");
1605
1606         for_each_file(td, f, i) {
1607                 if (td->o.unlink && f->filetype == FIO_TYPE_FILE) {
1608                         dprint(FD_FILE, "free unlink %s\n", f->file_name);
1609                         td_io_unlink_file(td, f);
1610                 }
1611
1612                 if (fio_file_open(f))
1613                         td_io_close_file(td, f);
1614
1615                 remove_file_hash(f);
1616
1617                 if (td->o.unlink && f->filetype == FIO_TYPE_FILE) {
1618                         dprint(FD_FILE, "free unlink %s\n", f->file_name);
1619                         td_io_unlink_file(td, f);
1620                 }
1621
1622                 zbd_close_file(f);
1623                 fio_file_free(f);
1624         }
1625
1626         td->o.filename = NULL;
1627         free(td->files);
1628         free(td->file_locks);
1629         td->files_index = 0;
1630         td->files = NULL;
1631         td->file_locks = NULL;
1632         td->o.file_lock_mode = FILE_LOCK_NONE;
1633         td->o.nr_files = 0;
1634 }
1635
1636 static void get_file_type(struct fio_file *f)
1637 {
1638         struct stat sb;
1639
1640         if (!strcmp(f->file_name, "-"))
1641                 f->filetype = FIO_TYPE_PIPE;
1642         else
1643                 f->filetype = FIO_TYPE_FILE;
1644
1645 #ifdef WIN32
1646         /* \\.\ is the device namespace in Windows, where every file is
1647          * a block device */
1648         if (strncmp(f->file_name, "\\\\.\\", 4) == 0)
1649                 f->filetype = FIO_TYPE_BLOCK;
1650 #endif
1651
1652         if (!stat(f->file_name, &sb)) {
1653                 if (S_ISBLK(sb.st_mode))
1654                         f->filetype = FIO_TYPE_BLOCK;
1655                 else if (S_ISCHR(sb.st_mode))
1656                         f->filetype = FIO_TYPE_CHAR;
1657                 else if (S_ISFIFO(sb.st_mode))
1658                         f->filetype = FIO_TYPE_PIPE;
1659         }
1660 }
1661
1662 static bool __is_already_allocated(const char *fname, bool set)
1663 {
1664         struct flist_head *entry;
1665         bool ret;
1666
1667         ret = file_bloom_exists(fname, set);
1668         if (!ret)
1669                 return ret;
1670
1671         flist_for_each(entry, &filename_list) {
1672                 struct file_name *fn;
1673
1674                 fn = flist_entry(entry, struct file_name, list);
1675
1676                 if (!strcmp(fn->filename, fname))
1677                         return true;
1678         }
1679
1680         return false;
1681 }
1682
1683 static bool is_already_allocated(const char *fname)
1684 {
1685         bool ret;
1686
1687         fio_file_hash_lock();
1688         ret = __is_already_allocated(fname, false);
1689         fio_file_hash_unlock();
1690
1691         return ret;
1692 }
1693
1694 static void set_already_allocated(const char *fname)
1695 {
1696         struct file_name *fn;
1697
1698         fn = malloc(sizeof(struct file_name));
1699         fn->filename = strdup(fname);
1700
1701         fio_file_hash_lock();
1702         if (!__is_already_allocated(fname, true)) {
1703                 flist_add_tail(&fn->list, &filename_list);
1704                 fn = NULL;
1705         }
1706         fio_file_hash_unlock();
1707
1708         if (fn) {
1709                 free(fn->filename);
1710                 free(fn);
1711         }
1712 }
1713
1714 static void free_already_allocated(void)
1715 {
1716         struct flist_head *entry, *tmp;
1717         struct file_name *fn;
1718
1719         if (flist_empty(&filename_list))
1720                 return;
1721
1722         fio_file_hash_lock();
1723         flist_for_each_safe(entry, tmp, &filename_list) {
1724                 fn = flist_entry(entry, struct file_name, list);
1725                 free(fn->filename);
1726                 flist_del(&fn->list);
1727                 free(fn);
1728         }
1729
1730         fio_file_hash_unlock();
1731 }
1732
1733 static struct fio_file *alloc_new_file(struct thread_data *td)
1734 {
1735         struct fio_file *f;
1736
1737         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
1738                 f = calloc(1, sizeof(*f));
1739         else
1740                 f = scalloc(1, sizeof(*f));
1741         if (!f) {
1742                 assert(0);
1743                 return NULL;
1744         }
1745
1746         f->fd = -1;
1747         f->shadow_fd = -1;
1748         fio_file_reset(td, f);
1749         if (!td_ioengine_flagged(td, FIO_NOFILEHASH))
1750                 fio_file_set_smalloc(f);
1751         return f;
1752 }
1753
1754 bool exists_and_not_regfile(const char *filename)
1755 {
1756         struct stat sb;
1757
1758         if (lstat(filename, &sb) == -1)
1759                 return false;
1760
1761 #ifndef WIN32 /* NOT Windows */
1762         if (S_ISREG(sb.st_mode))
1763                 return false;
1764 #else
1765         /* \\.\ is the device namespace in Windows, where every file
1766          * is a device node */
1767         if (S_ISREG(sb.st_mode) && strncmp(filename, "\\\\.\\", 4) != 0)
1768                 return false;
1769 #endif
1770
1771         return true;
1772 }
1773
1774 int add_file(struct thread_data *td, const char *fname, int numjob, int inc)
1775 {
1776         int cur_files = td->files_index;
1777         char file_name[PATH_MAX];
1778         struct fio_file *f;
1779         int len = 0;
1780
1781         dprint(FD_FILE, "add file %s\n", fname);
1782
1783         if (td->o.directory)
1784                 len = set_name_idx(file_name, PATH_MAX, td->o.directory, numjob,
1785                                         td->o.unique_filename);
1786
1787         sprintf(file_name + len, "%s", fname);
1788
1789         /* clean cloned siblings using existing files */
1790         if (numjob && is_already_allocated(file_name) &&
1791             !exists_and_not_regfile(fname))
1792                 return 0;
1793
1794         f = alloc_new_file(td);
1795
1796         if (td->files_size <= td->files_index) {
1797                 unsigned int new_size = td->o.nr_files + 1;
1798
1799                 dprint(FD_FILE, "resize file array to %d files\n", new_size);
1800
1801                 td->files = realloc(td->files, new_size * sizeof(f));
1802                 if (td->files == NULL) {
1803                         log_err("fio: realloc OOM\n");
1804                         assert(0);
1805                 }
1806                 if (td->o.file_lock_mode != FILE_LOCK_NONE) {
1807                         td->file_locks = realloc(td->file_locks, new_size);
1808                         if (!td->file_locks) {
1809                                 log_err("fio: realloc OOM\n");
1810                                 assert(0);
1811                         }
1812                         td->file_locks[cur_files] = FILE_LOCK_NONE;
1813                 }
1814                 td->files_size = new_size;
1815         }
1816         td->files[cur_files] = f;
1817         f->fileno = cur_files;
1818
1819         /*
1820          * init function, io engine may not be loaded yet
1821          */
1822         if (td->io_ops && td_ioengine_flagged(td, FIO_DISKLESSIO))
1823                 f->real_file_size = -1ULL;
1824
1825         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
1826                 f->file_name = strdup(file_name);
1827         else
1828                 f->file_name = smalloc_strdup(file_name);
1829
1830         /* can't handle smalloc failure from here */
1831         assert(f->file_name);
1832
1833         get_file_type(f);
1834
1835         switch (td->o.file_lock_mode) {
1836         case FILE_LOCK_NONE:
1837                 break;
1838         case FILE_LOCK_READWRITE:
1839                 f->rwlock = fio_rwlock_init();
1840                 break;
1841         case FILE_LOCK_EXCLUSIVE:
1842                 f->lock = fio_sem_init(FIO_SEM_UNLOCKED);
1843                 break;
1844         default:
1845                 log_err("fio: unknown lock mode: %d\n", td->o.file_lock_mode);
1846                 assert(0);
1847         }
1848
1849         td->files_index++;
1850
1851         if (td->o.numjobs > 1)
1852                 set_already_allocated(file_name);
1853
1854         if (inc)
1855                 td->o.nr_files++;
1856
1857         dprint(FD_FILE, "file %p \"%s\" added at %d\n", f, f->file_name,
1858                                                         cur_files);
1859
1860         return cur_files;
1861 }
1862
1863 int add_file_exclusive(struct thread_data *td, const char *fname)
1864 {
1865         struct fio_file *f;
1866         unsigned int i;
1867
1868         for_each_file(td, f, i) {
1869                 if (!strcmp(f->file_name, fname))
1870                         return i;
1871         }
1872
1873         return add_file(td, fname, 0, 1);
1874 }
1875
1876 void get_file(struct fio_file *f)
1877 {
1878         dprint(FD_FILE, "get file %s, ref=%d\n", f->file_name, f->references);
1879         assert(fio_file_open(f));
1880         f->references++;
1881 }
1882
1883 int put_file(struct thread_data *td, struct fio_file *f)
1884 {
1885         int f_ret = 0, ret = 0;
1886
1887         dprint(FD_FILE, "put file %s, ref=%d\n", f->file_name, f->references);
1888
1889         if (!fio_file_open(f)) {
1890                 assert(f->fd == -1);
1891                 return 0;
1892         }
1893
1894         assert(f->references);
1895         if (--f->references)
1896                 return 0;
1897
1898         disk_util_dec(f->du);
1899
1900         if (td->o.file_lock_mode != FILE_LOCK_NONE)
1901                 unlock_file_all(td, f);
1902
1903         if (should_fsync(td) && td->o.fsync_on_close) {
1904                 f_ret = fsync(f->fd);
1905                 if (f_ret < 0)
1906                         f_ret = errno;
1907         }
1908
1909         if (td->io_ops->close_file)
1910                 ret = td->io_ops->close_file(td, f);
1911
1912         if (!ret)
1913                 ret = f_ret;
1914
1915         td->nr_open_files--;
1916         fio_file_clear_closing(f);
1917         fio_file_clear_open(f);
1918         assert(f->fd == -1);
1919         return ret;
1920 }
1921
1922 void lock_file(struct thread_data *td, struct fio_file *f, enum fio_ddir ddir)
1923 {
1924         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1925                 return;
1926
1927         if (td->o.file_lock_mode == FILE_LOCK_READWRITE) {
1928                 if (ddir == DDIR_READ)
1929                         fio_rwlock_read(f->rwlock);
1930                 else
1931                         fio_rwlock_write(f->rwlock);
1932         } else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1933                 fio_sem_down(f->lock);
1934
1935         td->file_locks[f->fileno] = td->o.file_lock_mode;
1936 }
1937
1938 void unlock_file(struct thread_data *td, struct fio_file *f)
1939 {
1940         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1941                 return;
1942
1943         if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
1944                 fio_rwlock_unlock(f->rwlock);
1945         else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1946                 fio_sem_up(f->lock);
1947
1948         td->file_locks[f->fileno] = FILE_LOCK_NONE;
1949 }
1950
1951 void unlock_file_all(struct thread_data *td, struct fio_file *f)
1952 {
1953         if (td->o.file_lock_mode == FILE_LOCK_NONE || !td->file_locks)
1954                 return;
1955         if (td->file_locks[f->fileno] != FILE_LOCK_NONE)
1956                 unlock_file(td, f);
1957 }
1958
1959 static bool recurse_dir(struct thread_data *td, const char *dirname)
1960 {
1961         struct dirent *dir;
1962         bool ret = false;
1963         DIR *D;
1964
1965         D = opendir(dirname);
1966         if (!D) {
1967                 char buf[FIO_VERROR_SIZE];
1968
1969                 snprintf(buf, FIO_VERROR_SIZE, "opendir(%s)", dirname);
1970                 td_verror(td, errno, buf);
1971                 return true;
1972         }
1973
1974         while ((dir = readdir(D)) != NULL) {
1975                 char full_path[PATH_MAX];
1976                 struct stat sb;
1977
1978                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1979                         continue;
1980
1981                 sprintf(full_path, "%s%c%s", dirname, FIO_OS_PATH_SEPARATOR, dir->d_name);
1982
1983                 if (lstat(full_path, &sb) == -1) {
1984                         if (errno != ENOENT) {
1985                                 td_verror(td, errno, "stat");
1986                                 ret = true;
1987                                 break;
1988                         }
1989                 }
1990
1991                 if (S_ISREG(sb.st_mode)) {
1992                         add_file(td, full_path, 0, 1);
1993                         continue;
1994                 }
1995                 if (!S_ISDIR(sb.st_mode))
1996                         continue;
1997
1998                 ret = recurse_dir(td, full_path);
1999                 if (ret)
2000                         break;
2001         }
2002
2003         closedir(D);
2004         return ret;
2005 }
2006
2007 int add_dir_files(struct thread_data *td, const char *path)
2008 {
2009         int ret = recurse_dir(td, path);
2010
2011         if (!ret)
2012                 log_info("fio: opendir added %d files\n", td->o.nr_files);
2013
2014         return ret;
2015 }
2016
2017 void dup_files(struct thread_data *td, struct thread_data *org)
2018 {
2019         struct fio_file *f;
2020         unsigned int i;
2021
2022         dprint(FD_FILE, "dup files: %d\n", org->files_index);
2023
2024         if (!org->files)
2025                 return;
2026
2027         td->files = calloc(org->files_index, sizeof(f));
2028
2029         if (td->o.file_lock_mode != FILE_LOCK_NONE)
2030                 td->file_locks = malloc(org->files_index);
2031
2032         assert(org->files_index >= org->o.nr_files);
2033         for_each_file(org, f, i) {
2034                 struct fio_file *__f;
2035
2036                 __f = alloc_new_file(td);
2037
2038                 if (f->file_name) {
2039                         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
2040                                 __f->file_name = strdup(f->file_name);
2041                         else
2042                                 __f->file_name = smalloc_strdup(f->file_name);
2043
2044                         /* can't handle smalloc failure from here */
2045                         assert(__f->file_name);
2046                         __f->filetype = f->filetype;
2047                 }
2048
2049                 if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
2050                         __f->lock = f->lock;
2051                 else if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
2052                         __f->rwlock = f->rwlock;
2053
2054                 td->files[i] = __f;
2055         }
2056 }
2057
2058 /*
2059  * Returns the index that matches the filename, or -1 if not there
2060  */
2061 int get_fileno(struct thread_data *td, const char *fname)
2062 {
2063         struct fio_file *f;
2064         unsigned int i;
2065
2066         for_each_file(td, f, i)
2067                 if (!strcmp(f->file_name, fname))
2068                         return i;
2069
2070         return -1;
2071 }
2072
2073 /*
2074  * For log usage, where we add/open/close files automatically
2075  */
2076 void free_release_files(struct thread_data *td)
2077 {
2078         close_files(td);
2079         td->o.nr_files = 0;
2080         td->o.open_files = 0;
2081         td->files_index = 0;
2082 }
2083
2084 void fio_file_reset(struct thread_data *td, struct fio_file *f)
2085 {
2086         int i;
2087
2088         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
2089                 f->last_pos[i] = f->file_offset;
2090                 f->last_start[i] = -1ULL;
2091         }
2092
2093         if (fio_file_axmap(f))
2094                 axmap_reset(f->io_axmap);
2095         else if (fio_file_lfsr(f))
2096                 lfsr_reset(&f->lfsr, td->rand_seeds[FIO_RAND_BLOCK_OFF]);
2097
2098         zbd_file_reset(td, f);
2099 }
2100
2101 bool fio_files_done(struct thread_data *td)
2102 {
2103         struct fio_file *f;
2104         unsigned int i;
2105
2106         for_each_file(td, f, i)
2107                 if (!fio_file_done(f))
2108                         return false;
2109
2110         return true;
2111 }
2112
2113 /* free memory used in initialization phase only */
2114 void filesetup_mem_free(void)
2115 {
2116         free_already_allocated();
2117 }
2118
2119 /*
2120  * This function is for platforms which support direct I/O but not O_DIRECT.
2121  */
2122 int fio_set_directio(struct thread_data *td, struct fio_file *f)
2123 {
2124 #ifdef FIO_OS_DIRECTIO
2125         int ret = fio_set_odirect(f);
2126
2127         if (ret) {
2128                 td_verror(td, ret, "fio_set_directio");
2129 #if defined(__sun__)
2130                 if (ret == ENOTTY) { /* ENOTTY suggests RAW device or ZFS */
2131                         log_err("fio: doing directIO to RAW devices or ZFS not supported\n");
2132                 } else {
2133                         log_err("fio: the file system does not seem to support direct IO\n");
2134                 }
2135 #else
2136                 log_err("fio: the file system does not seem to support direct IO\n");
2137 #endif
2138                 return -1;
2139         }
2140
2141         return 0;
2142 #else
2143         log_err("fio: direct IO is not supported on this host operating system\n");
2144         return -1;
2145 #endif
2146 }