init: do not create lat logs when not needed
[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         if (td->o.oatomic) {
745                 if (!FIO_O_ATOMIC) {
746                         td_verror(td, EINVAL, "OS does not support atomic IO");
747                         return 1;
748                 }
749                 flags |= OS_O_DIRECT | FIO_O_ATOMIC;
750         }
751         flags |= td->o.sync_io;
752         if (td->o.create_on_open && td->o.allow_create)
753                 flags |= O_CREAT;
754 skip_flags:
755         if (f->filetype != FIO_TYPE_FILE)
756                 flags |= FIO_O_NOATIME;
757
758 open_again:
759         if (td_write(td)) {
760                 if (!read_only)
761                         flags |= O_RDWR;
762
763                 if (f->filetype == FIO_TYPE_FILE && td->o.allow_create)
764                         flags |= O_CREAT;
765
766                 if (is_std)
767                         f->fd = dup(STDOUT_FILENO);
768                 else
769                         from_hash = file_lookup_open(f, flags);
770         } else if (td_read(td)) {
771                 if (f->filetype == FIO_TYPE_CHAR && !read_only)
772                         flags |= O_RDWR;
773                 else
774                         flags |= O_RDONLY;
775
776                 if (is_std)
777                         f->fd = dup(STDIN_FILENO);
778                 else
779                         from_hash = file_lookup_open(f, flags);
780         } else if (td_trim(td)) {
781                 assert(!td_rw(td)); /* should have matched above */
782                 if (!read_only)
783                         flags |= O_RDWR;
784                 from_hash = file_lookup_open(f, flags);
785         }
786
787         if (f->fd == -1) {
788                 char buf[FIO_VERROR_SIZE];
789                 int __e = errno;
790
791                 if (__e == EPERM && (flags & FIO_O_NOATIME)) {
792                         flags &= ~FIO_O_NOATIME;
793                         goto open_again;
794                 }
795                 if (__e == EMFILE && file_close_shadow_fds(td))
796                         goto open_again;
797
798                 snprintf(buf, sizeof(buf), "open(%s)", f->file_name);
799
800                 if (__e == EINVAL && (flags & OS_O_DIRECT)) {
801                         log_err("fio: looks like your file system does not " \
802                                 "support direct=1/buffered=0\n");
803                 }
804
805                 td_verror(td, __e, buf);
806                 return 1;
807         }
808
809         if (!from_hash && f->fd != -1) {
810                 if (add_file_hash(f)) {
811                         int fio_unused ret;
812
813                         /*
814                          * Stash away descriptor for later close. This is to
815                          * work-around a "feature" on Linux, where a close of
816                          * an fd that has been opened for write will trigger
817                          * udev to call blkid to check partitions, fs id, etc.
818                          * That pollutes the device cache, which can slow down
819                          * unbuffered accesses.
820                          */
821                         if (f->shadow_fd == -1)
822                                 f->shadow_fd = f->fd;
823                         else {
824                                 /*
825                                  * OK to ignore, we haven't done anything
826                                  * with it
827                                  */
828                                 ret = generic_close_file(td, f);
829                         }
830                         goto open_again;
831                 }
832         }
833
834         return 0;
835 }
836
837 /*
838  * This function i.e. get_file_size() is the default .get_file_size
839  * implementation of majority of I/O engines.
840  */
841 int generic_get_file_size(struct thread_data *td, struct fio_file *f)
842 {
843         return get_file_size(td, f);
844 }
845
846 /*
847  * open/close all files, so that ->real_file_size gets set
848  */
849 static int get_file_sizes(struct thread_data *td)
850 {
851         struct fio_file *f;
852         unsigned int i;
853         int err = 0;
854
855         for_each_file(td, f, i) {
856                 dprint(FD_FILE, "get file size for %p/%d/%s\n", f, i,
857                                                                 f->file_name);
858
859                 if (td_io_get_file_size(td, f)) {
860                         if (td->error != ENOENT) {
861                                 log_err("%s\n", td->verror);
862                                 err = 1;
863                                 break;
864                         }
865                         clear_error(td);
866                 }
867
868                 /*
869                  * There are corner cases where we end up with -1 for
870                  * ->real_file_size due to unsupported file type, etc.
871                  * We then just set to size option value divided by number
872                  * of files, similar to the way file ->io_size is set.
873                  * stat(2) failure doesn't set ->real_file_size to -1.
874                  */
875                 if (f->real_file_size == -1ULL && td->o.size)
876                         f->real_file_size = td->o.size / td->o.nr_files;
877         }
878
879         return err;
880 }
881
882 struct fio_mount {
883         struct flist_head list;
884         const char *base;
885         char __base[256];
886         unsigned int key;
887 };
888
889 /*
890  * Get free number of bytes for each file on each unique mount.
891  */
892 static unsigned long long get_fs_free_counts(struct thread_data *td)
893 {
894         struct flist_head *n, *tmp;
895         unsigned long long ret = 0;
896         struct fio_mount *fm;
897         FLIST_HEAD(list);
898         struct fio_file *f;
899         unsigned int i;
900
901         for_each_file(td, f, i) {
902                 struct stat sb;
903                 char buf[256];
904
905                 if (f->filetype == FIO_TYPE_BLOCK || f->filetype == FIO_TYPE_CHAR) {
906                         if (f->real_file_size != -1ULL)
907                                 ret += f->real_file_size;
908                         continue;
909                 } else if (f->filetype != FIO_TYPE_FILE)
910                         continue;
911
912                 snprintf(buf, FIO_ARRAY_SIZE(buf), "%s", f->file_name);
913
914                 if (stat(buf, &sb) < 0) {
915                         if (errno != ENOENT)
916                                 break;
917                         strcpy(buf, ".");
918                         if (stat(buf, &sb) < 0)
919                                 break;
920                 }
921
922                 fm = NULL;
923                 flist_for_each(n, &list) {
924                         fm = flist_entry(n, struct fio_mount, list);
925                         if (fm->key == sb.st_dev)
926                                 break;
927
928                         fm = NULL;
929                 }
930
931                 if (fm)
932                         continue;
933
934                 fm = calloc(1, sizeof(*fm));
935                 snprintf(fm->__base, FIO_ARRAY_SIZE(fm->__base), "%s", buf);
936                 fm->base = basename(fm->__base);
937                 fm->key = sb.st_dev;
938                 flist_add(&fm->list, &list);
939         }
940
941         flist_for_each_safe(n, tmp, &list) {
942                 unsigned long long sz;
943
944                 fm = flist_entry(n, struct fio_mount, list);
945                 flist_del(&fm->list);
946
947                 sz = get_fs_free_size(fm->base);
948                 if (sz && sz != -1ULL)
949                         ret += sz;
950
951                 free(fm);
952         }
953
954         return ret;
955 }
956
957 uint64_t get_start_offset(struct thread_data *td, struct fio_file *f)
958 {
959         bool align = false;
960         struct thread_options *o = &td->o;
961         unsigned long long align_bs;
962         unsigned long long offset;
963         unsigned long long increment;
964
965         if (o->file_append && f->filetype == FIO_TYPE_FILE)
966                 return f->real_file_size;
967
968         if (o->offset_increment_percent) {
969                 assert(!o->offset_increment);
970                 increment = o->offset_increment_percent * f->real_file_size / 100;
971                 align = true;
972         } else
973                 increment = o->offset_increment;
974
975         if (o->start_offset_percent > 0) {
976                 /* calculate the raw offset */
977                 offset = (f->real_file_size * o->start_offset_percent / 100) +
978                         (td->subjob_number * increment);
979
980                 align = true;
981         } else {
982                 /* start_offset_percent not set */
983                 offset = o->start_offset +
984                                 td->subjob_number * increment;
985         }
986
987         if (align) {
988                 /*
989                  * if offset_align is provided, use it
990                  */
991                 if (fio_option_is_set(o, start_offset_align)) {
992                         align_bs = o->start_offset_align;
993                 } else {
994                         /* else take the minimum block size */
995                         align_bs = td_min_bs(td);
996                 }
997
998                 /*
999                  * block align the offset at the next available boundary at
1000                  * ceiling(offset / align_bs) * align_bs
1001                  */
1002                 offset = (offset / align_bs + (offset % align_bs != 0)) * align_bs;
1003         }
1004
1005         return offset;
1006 }
1007
1008 /*
1009  * Find longest path component that exists and return its length
1010  */
1011 int longest_existing_path(char *path) {
1012         char buf[PATH_MAX];
1013         bool done;
1014         char *buf_pos;
1015         int offset;
1016 #ifdef WIN32
1017         DWORD dwAttr;
1018 #else
1019         struct stat sb;
1020 #endif
1021
1022         sprintf(buf, "%s", path);
1023         done = false;
1024         while (!done) {
1025                 buf_pos = strrchr(buf, FIO_OS_PATH_SEPARATOR);
1026                 if (!buf_pos) {
1027                         offset = 0;
1028                         break;
1029                 }
1030
1031                 *(buf_pos + 1) = '\0';
1032
1033 #ifdef WIN32
1034                 dwAttr = GetFileAttributesA(buf);
1035                 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1036                         done = true;
1037                 }
1038 #else
1039                 if (stat(buf, &sb) == 0)
1040                         done = true;
1041 #endif
1042                 if (done)
1043                         offset = buf_pos - buf;
1044                 else
1045                         *buf_pos = '\0';
1046         }
1047
1048         return offset;
1049 }
1050
1051 static bool create_work_dirs(struct thread_data *td, const char *fname)
1052 {
1053         char path[PATH_MAX];
1054         char *start, *end;
1055         int offset;
1056
1057         snprintf(path, PATH_MAX, "%s", fname);
1058         start = path;
1059
1060         offset = longest_existing_path(path);
1061         end = start + offset;
1062         while ((end = strchr(end, FIO_OS_PATH_SEPARATOR)) != NULL) {
1063                 if (end == start) {
1064                         end++;
1065                         continue;
1066                 }
1067                 *end = '\0';
1068                 errno = 0;
1069                 if (fio_mkdir(path, 0700) && errno != EEXIST) {
1070                         log_err("fio: failed to create dir (%s): %s\n",
1071                                 start, strerror(errno));
1072                         return false;
1073                 }
1074                 *end = FIO_OS_PATH_SEPARATOR;
1075                 end++;
1076         }
1077         td->flags |= TD_F_DIRS_CREATED;
1078         return true;
1079 }
1080
1081 /*
1082  * Open the files and setup files sizes, creating files if necessary.
1083  */
1084 int setup_files(struct thread_data *td)
1085 {
1086         unsigned long long total_size, extend_size;
1087         struct thread_options *o = &td->o;
1088         struct fio_file *f;
1089         unsigned int i, nr_fs_extra = 0;
1090         int err = 0, need_extend;
1091         int old_state;
1092         const unsigned long long bs = td_min_bs(td);
1093         uint64_t fs = 0;
1094
1095         dprint(FD_FILE, "setup files\n");
1096
1097         old_state = td_bump_runstate(td, TD_SETTING_UP);
1098
1099         for_each_file(td, f, i) {
1100                 if (!td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1101                     strchr(f->file_name, FIO_OS_PATH_SEPARATOR) &&
1102                     !(td->flags & TD_F_DIRS_CREATED) &&
1103                     !create_work_dirs(td, f->file_name))
1104                         goto err_out;
1105         }
1106
1107         /*
1108          * Find out physical size of files or devices for this thread,
1109          * before we determine I/O size and range of our targets.
1110          * If ioengine defines a setup() method, it's responsible for
1111          * opening the files and setting f->real_file_size to indicate
1112          * the valid range for that file.
1113          */
1114         if (td->io_ops->setup)
1115                 err = td->io_ops->setup(td);
1116         else
1117                 err = get_file_sizes(td);
1118
1119         if (err)
1120                 goto err_out;
1121
1122         if (td->o.zone_mode == ZONE_MODE_ZBD) {
1123                 err = zbd_init_files(td);
1124                 if (err)
1125                         goto err_out;
1126         }
1127         zbd_recalc_options_with_zone_granularity(td);
1128
1129         if (o->read_iolog_file)
1130                 goto done;
1131
1132         /*
1133          * check sizes. if the files/devices do not exist and the size
1134          * isn't passed to fio, abort.
1135          */
1136         total_size = 0;
1137         for_each_file(td, f, i) {
1138                 f->fileno = i;
1139                 if (f->real_file_size == -1ULL)
1140                         total_size = -1ULL;
1141                 else
1142                         total_size += f->real_file_size;
1143         }
1144
1145         if (o->fill_device)
1146                 td->fill_device_size = get_fs_free_counts(td);
1147
1148         /*
1149          * device/file sizes are zero and no size given, punt
1150          */
1151         if ((!total_size || total_size == -1ULL) && !o->size &&
1152             !td_ioengine_flagged(td, FIO_NOIO) && !o->fill_device &&
1153             !(o->nr_files && (o->file_size_low || o->file_size_high))) {
1154                 log_err("%s: you need to specify size=\n", o->name);
1155                 td_verror(td, EINVAL, "total_file_size");
1156                 goto err_out;
1157         }
1158
1159         /*
1160          * Calculate per-file size and potential extra size for the
1161          * first files, if needed (i.e. if we don't have a fixed size).
1162          */
1163         if (!o->file_size_low && o->nr_files) {
1164                 uint64_t all_fs;
1165
1166                 fs = o->size / o->nr_files;
1167                 all_fs = fs * o->nr_files;
1168
1169                 if (all_fs < o->size)
1170                         nr_fs_extra = (o->size - all_fs) / bs;
1171         }
1172
1173         /*
1174          * now file sizes are known, so we can set ->io_size. if size= is
1175          * not given, ->io_size is just equal to ->real_file_size. if size
1176          * is given, ->io_size is size / nr_files.
1177          */
1178         extend_size = total_size = 0;
1179         need_extend = 0;
1180         for_each_file(td, f, i) {
1181                 f->file_offset = get_start_offset(td, f);
1182
1183                 /*
1184                  * Update ->io_size depending on options specified.
1185                  * ->file_size_low being 0 means filesize option isn't set.
1186                  * Non zero ->file_size_low equals ->file_size_high means
1187                  * filesize option is set in a fixed size format.
1188                  * Non zero ->file_size_low not equals ->file_size_high means
1189                  * filesize option is set in a range format.
1190                  */
1191                 if (!o->file_size_low) {
1192                         /*
1193                          * no file size or range given, file size is equal to
1194                          * total size divided by number of files. If the size
1195                          * doesn't divide nicely with the min blocksize,
1196                          * make the first files bigger.
1197                          */
1198                         f->io_size = fs;
1199                         if (nr_fs_extra) {
1200                                 nr_fs_extra--;
1201                                 f->io_size += bs;
1202                         }
1203
1204                         /*
1205                          * We normally don't come here for regular files, but
1206                          * if the result is 0 for a regular file, set it to the
1207                          * real file size. This could be size of the existing
1208                          * one if it already exists, but otherwise will be set
1209                          * to 0. A new file won't be created because
1210                          * ->io_size + ->file_offset equals ->real_file_size.
1211                          */
1212                         if (!f->io_size) {
1213                                 if (f->file_offset > f->real_file_size)
1214                                         goto err_offset;
1215                                 f->io_size = f->real_file_size - f->file_offset;
1216                                 if (!f->io_size)
1217                                         log_info("fio: file %s may be ignored\n",
1218                                                 f->file_name);
1219                         }
1220                 } else if (f->real_file_size < o->file_size_low ||
1221                            f->real_file_size > o->file_size_high) {
1222                         if (f->file_offset > o->file_size_low)
1223                                 goto err_offset;
1224                         /*
1225                          * file size given. if it's fixed, use that. if it's a
1226                          * range, generate a random size in-between.
1227                          */
1228                         if (o->file_size_low == o->file_size_high)
1229                                 f->io_size = o->file_size_low - f->file_offset;
1230                         else {
1231                                 f->io_size = get_rand_file_size(td)
1232                                                 - f->file_offset;
1233                         }
1234                 } else
1235                         f->io_size = f->real_file_size - f->file_offset;
1236
1237                 if (f->io_size == -1ULL)
1238                         total_size = -1ULL;
1239                 else {
1240                         uint64_t io_size;
1241
1242                         if (o->size_percent && o->size_percent != 100) {
1243                                 uint64_t file_size;
1244
1245                                 file_size = f->io_size + f->file_offset;
1246                                 f->io_size = (file_size *
1247                                               o->size_percent) / 100;
1248                                 if (f->io_size > (file_size - f->file_offset))
1249                                         f->io_size = file_size - f->file_offset;
1250
1251                                 f->io_size -= (f->io_size % td_min_bs(td));
1252                         }
1253
1254                         io_size = f->io_size;
1255                         if (o->io_size_percent && o->io_size_percent != 100) {
1256                                 io_size *= o->io_size_percent;
1257                                 io_size /= 100;
1258                         }
1259
1260                         total_size += io_size;
1261                 }
1262
1263                 if (f->filetype == FIO_TYPE_FILE &&
1264                     (f->io_size + f->file_offset) > f->real_file_size) {
1265                         if (!td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1266                             !o->create_on_open) {
1267                                 need_extend++;
1268                                 extend_size += (f->io_size + f->file_offset);
1269                                 fio_file_set_extend(f);
1270                         } else if (!td_ioengine_flagged(td, FIO_DISKLESSIO) ||
1271                                    (td_ioengine_flagged(td, FIO_DISKLESSIO) &&
1272                                     td_ioengine_flagged(td, FIO_FAKEIO)))
1273                                 f->real_file_size = f->io_size + f->file_offset;
1274                 }
1275         }
1276
1277         if (td->o.block_error_hist) {
1278                 int len;
1279
1280                 assert(td->o.nr_files == 1);    /* checked in fixup_options */
1281                 f = td->files[0];
1282                 len = f->io_size / td->o.bs[DDIR_TRIM];
1283                 if (len > MAX_NR_BLOCK_INFOS || len <= 0) {
1284                         log_err("fio: cannot calculate block histogram with "
1285                                 "%d trim blocks, maximum %d\n",
1286                                 len, MAX_NR_BLOCK_INFOS);
1287                         td_verror(td, EINVAL, "block_error_hist");
1288                         goto err_out;
1289                 }
1290
1291                 td->ts.nr_block_infos = len;
1292                 for (i = 0; i < len; i++)
1293                         td->ts.block_infos[i] =
1294                                 BLOCK_INFO(0, BLOCK_STATE_UNINIT);
1295         } else
1296                 td->ts.nr_block_infos = 0;
1297
1298         if (!o->size || (total_size && o->size > total_size))
1299                 o->size = total_size;
1300
1301         if (o->size < td_min_bs(td)) {
1302                 log_err("fio: blocksize is larger than data set range\n");
1303                 goto err_out;
1304         }
1305
1306         /*
1307          * See if we need to extend some files, typically needed when our
1308          * target regular files don't exist yet, but our jobs require them
1309          * initially due to read I/Os.
1310          */
1311         if (need_extend) {
1312                 temp_stall_ts = 1;
1313                 if (output_format & FIO_OUTPUT_NORMAL) {
1314                         log_info("%s: Laying out IO file%s (%u file%s / %s%lluMiB)\n",
1315                                  o->name,
1316                                  need_extend > 1 ? "s" : "",
1317                                  need_extend,
1318                                  need_extend > 1 ? "s" : "",
1319                                  need_extend > 1 ? "total " : "",
1320                                  extend_size >> 20);
1321                 }
1322
1323                 for_each_file(td, f, i) {
1324                         unsigned long long old_len = -1ULL, extend_len = -1ULL;
1325
1326                         if (!fio_file_extend(f))
1327                                 continue;
1328
1329                         assert(f->filetype == FIO_TYPE_FILE);
1330                         fio_file_clear_extend(f);
1331                         if (!o->fill_device) {
1332                                 old_len = f->real_file_size;
1333                                 extend_len = f->io_size + f->file_offset -
1334                                                 old_len;
1335                         }
1336                         f->real_file_size = (f->io_size + f->file_offset);
1337                         err = extend_file(td, f);
1338                         if (err)
1339                                 break;
1340
1341                         err = __file_invalidate_cache(td, f, old_len,
1342                                                                 extend_len);
1343
1344                         /*
1345                          * Shut up static checker
1346                          */
1347                         if (f->fd != -1)
1348                                 close(f->fd);
1349
1350                         f->fd = -1;
1351                         if (err)
1352                                 break;
1353                 }
1354                 temp_stall_ts = 0;
1355         }
1356
1357         if (err)
1358                 goto err_out;
1359
1360         /*
1361          * Prepopulate files with data. It might be expected to read some
1362          * "real" data instead of zero'ed files (if no writes to file occurred
1363          * prior to a read job). Engine has to provide a way to do that.
1364          */
1365         if (td->io_ops->prepopulate_file) {
1366                 temp_stall_ts = 1;
1367
1368                 for_each_file(td, f, i) {
1369                         if (output_format & FIO_OUTPUT_NORMAL) {
1370                                 log_info("%s: Prepopulating IO file (%s)\n",
1371                                                         o->name, f->file_name);
1372                         }
1373
1374                         err = td->io_ops->prepopulate_file(td, f);
1375                         if (err)
1376                                 break;
1377
1378                         err = __file_invalidate_cache(td, f, f->file_offset,
1379                                                                 f->io_size);
1380
1381                         /*
1382                          * Shut up static checker
1383                          */
1384                         if (f->fd != -1)
1385                                 close(f->fd);
1386
1387                         f->fd = -1;
1388                         if (err)
1389                                 break;
1390                 }
1391                 temp_stall_ts = 0;
1392         }
1393
1394         if (err)
1395                 goto err_out;
1396
1397         /*
1398          * iolog already set the total io size, if we read back
1399          * stored entries.
1400          */
1401         if (!o->read_iolog_file) {
1402                 if (o->io_size)
1403                         td->total_io_size = o->io_size * o->loops;
1404                 else
1405                         td->total_io_size = o->size * o->loops;
1406         }
1407
1408 done:
1409         if (td->o.zone_mode == ZONE_MODE_ZBD) {
1410                 err = zbd_setup_files(td);
1411                 if (err)
1412                         goto err_out;
1413         }
1414
1415         if (o->create_only)
1416                 td->done = 1;
1417
1418         td_restore_runstate(td, old_state);
1419
1420         return 0;
1421
1422 err_offset:
1423         log_err("%s: you need to specify valid offset=\n", o->name);
1424 err_out:
1425         td_restore_runstate(td, old_state);
1426         return 1;
1427 }
1428
1429 bool pre_read_files(struct thread_data *td)
1430 {
1431         struct fio_file *f;
1432         unsigned int i;
1433
1434         dprint(FD_FILE, "pre_read files\n");
1435
1436         for_each_file(td, f, i) {
1437                 if (!pre_read_file(td, f))
1438                         return false;
1439         }
1440
1441         return true;
1442 }
1443
1444 static void __init_rand_distribution(struct thread_data *td, struct fio_file *f)
1445 {
1446         unsigned int range_size, seed;
1447         uint64_t nranges;
1448         uint64_t fsize;
1449
1450         range_size = min(td->o.min_bs[DDIR_READ], td->o.min_bs[DDIR_WRITE]);
1451         fsize = min(f->real_file_size, f->io_size);
1452
1453         nranges = (fsize + range_size - 1ULL) / range_size;
1454
1455         seed = jhash(f->file_name, strlen(f->file_name), 0) * td->thread_number;
1456         if (!td->o.rand_repeatable)
1457                 seed = td->rand_seeds[4];
1458
1459         if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
1460                 zipf_init(&f->zipf, nranges, td->o.zipf_theta.u.f, td->o.random_center.u.f, seed);
1461         else if (td->o.random_distribution == FIO_RAND_DIST_PARETO)
1462                 pareto_init(&f->zipf, nranges, td->o.pareto_h.u.f, td->o.random_center.u.f, seed);
1463         else if (td->o.random_distribution == FIO_RAND_DIST_GAUSS)
1464                 gauss_init(&f->gauss, nranges, td->o.gauss_dev.u.f, td->o.random_center.u.f, seed);
1465 }
1466
1467 static bool init_rand_distribution(struct thread_data *td)
1468 {
1469         struct fio_file *f;
1470         unsigned int i;
1471         int state;
1472
1473         if (td->o.random_distribution == FIO_RAND_DIST_RANDOM ||
1474             td->o.random_distribution == FIO_RAND_DIST_ZONED ||
1475             td->o.random_distribution == FIO_RAND_DIST_ZONED_ABS)
1476                 return false;
1477
1478         state = td_bump_runstate(td, TD_SETTING_UP);
1479
1480         for_each_file(td, f, i)
1481                 __init_rand_distribution(td, f);
1482
1483         td_restore_runstate(td, state);
1484         return true;
1485 }
1486
1487 /*
1488  * Check if the number of blocks exceeds the randomness capability of
1489  * the selected generator. Tausworthe is 32-bit, the others are fullly
1490  * 64-bit capable.
1491  */
1492 static int check_rand_gen_limits(struct thread_data *td, struct fio_file *f,
1493                                  uint64_t blocks)
1494 {
1495         if (blocks <= FRAND32_MAX)
1496                 return 0;
1497         if (td->o.random_generator != FIO_RAND_GEN_TAUSWORTHE)
1498                 return 0;
1499
1500         /*
1501          * If the user hasn't specified a random generator, switch
1502          * to tausworthe64 with informational warning. If the user did
1503          * specify one, just warn.
1504          */
1505         log_info("fio: file %s exceeds 32-bit tausworthe random generator.\n",
1506                         f->file_name);
1507
1508         if (!fio_option_is_set(&td->o, random_generator)) {
1509                 log_info("fio: Switching to tausworthe64. Use the "
1510                          "random_generator= option to get rid of this "
1511                          "warning.\n");
1512                 td->o.random_generator = FIO_RAND_GEN_TAUSWORTHE64;
1513                 return 0;
1514         }
1515
1516         /*
1517          * Just make this information to avoid breaking scripts.
1518          */
1519         log_info("fio: Use the random_generator= option to switch to lfsr or "
1520                          "tausworthe64.\n");
1521         return 0;
1522 }
1523
1524 bool init_random_map(struct thread_data *td)
1525 {
1526         unsigned long long blocks;
1527         struct fio_file *f;
1528         unsigned int i;
1529
1530         if (init_rand_distribution(td))
1531                 return true;
1532         if (!td_random(td))
1533                 return true;
1534
1535         for_each_file(td, f, i) {
1536                 uint64_t fsize = min(f->real_file_size, f->io_size);
1537
1538                 if (td->o.zone_mode == ZONE_MODE_STRIDED)
1539                         fsize = td->o.zone_range;
1540
1541                 blocks = fsize / (unsigned long long) td->o.rw_min_bs;
1542
1543                 if (check_rand_gen_limits(td, f, blocks))
1544                         return false;
1545
1546                 if (td->o.random_generator == FIO_RAND_GEN_LFSR) {
1547                         uint64_t seed;
1548
1549                         seed = td->rand_seeds[FIO_RAND_BLOCK_OFF];
1550
1551                         if (!lfsr_init(&f->lfsr, blocks, seed, 0)) {
1552                                 fio_file_set_lfsr(f);
1553                                 continue;
1554                         } else {
1555                                 log_err("fio: failed initializing LFSR\n");
1556                                 return false;
1557                         }
1558                 } else if (!td->o.norandommap) {
1559                         f->io_axmap = axmap_new(blocks);
1560                         if (f->io_axmap) {
1561                                 fio_file_set_axmap(f);
1562                                 continue;
1563                         }
1564                 } else if (td->o.norandommap)
1565                         continue;
1566
1567                 if (!td->o.softrandommap) {
1568                         log_err("fio: failed allocating random map. If running"
1569                                 " a large number of jobs, try the 'norandommap'"
1570                                 " option or set 'softrandommap'. Or give"
1571                                 " a larger --alloc-size to fio.\n");
1572                         return false;
1573                 }
1574
1575                 log_info("fio: file %s failed allocating random map. Running "
1576                          "job without.\n", f->file_name);
1577         }
1578
1579         return true;
1580 }
1581
1582 void close_files(struct thread_data *td)
1583 {
1584         struct fio_file *f;
1585         unsigned int i;
1586
1587         for_each_file(td, f, i) {
1588                 if (fio_file_open(f))
1589                         td_io_close_file(td, f);
1590         }
1591 }
1592
1593 void fio_file_free(struct fio_file *f)
1594 {
1595         if (fio_file_axmap(f))
1596                 axmap_free(f->io_axmap);
1597         if (!fio_file_smalloc(f)) {
1598                 free(f->file_name);
1599                 free(f);
1600         } else {
1601                 sfree(f->file_name);
1602                 sfree(f);
1603         }
1604 }
1605
1606 void close_and_free_files(struct thread_data *td)
1607 {
1608         struct fio_file *f;
1609         unsigned int i;
1610
1611         dprint(FD_FILE, "close files\n");
1612
1613         for_each_file(td, f, i) {
1614                 if (td->o.unlink && f->filetype == FIO_TYPE_FILE) {
1615                         dprint(FD_FILE, "free unlink %s\n", f->file_name);
1616                         td_io_unlink_file(td, f);
1617                 }
1618
1619                 if (fio_file_open(f))
1620                         td_io_close_file(td, f);
1621
1622                 remove_file_hash(f);
1623
1624                 if (td->o.unlink && f->filetype == FIO_TYPE_FILE) {
1625                         dprint(FD_FILE, "free unlink %s\n", f->file_name);
1626                         td_io_unlink_file(td, f);
1627                 }
1628
1629                 zbd_close_file(f);
1630                 fio_file_free(f);
1631         }
1632
1633         td->o.filename = NULL;
1634         free(td->files);
1635         free(td->file_locks);
1636         td->files_index = 0;
1637         td->files = NULL;
1638         td->file_locks = NULL;
1639         td->o.file_lock_mode = FILE_LOCK_NONE;
1640         td->o.nr_files = 0;
1641 }
1642
1643 static void get_file_type(struct fio_file *f)
1644 {
1645         struct stat sb;
1646
1647         if (!strcmp(f->file_name, "-"))
1648                 f->filetype = FIO_TYPE_PIPE;
1649         else
1650                 f->filetype = FIO_TYPE_FILE;
1651
1652 #ifdef WIN32
1653         /* \\.\ is the device namespace in Windows, where every file is
1654          * a block device */
1655         if (strncmp(f->file_name, "\\\\.\\", 4) == 0)
1656                 f->filetype = FIO_TYPE_BLOCK;
1657 #endif
1658
1659         if (!stat(f->file_name, &sb)) {
1660                 if (S_ISBLK(sb.st_mode))
1661                         f->filetype = FIO_TYPE_BLOCK;
1662                 else if (S_ISCHR(sb.st_mode))
1663                         f->filetype = FIO_TYPE_CHAR;
1664                 else if (S_ISFIFO(sb.st_mode))
1665                         f->filetype = FIO_TYPE_PIPE;
1666         }
1667 }
1668
1669 static bool __is_already_allocated(const char *fname, bool set)
1670 {
1671         struct flist_head *entry;
1672         bool ret;
1673
1674         ret = file_bloom_exists(fname, set);
1675         if (!ret)
1676                 return ret;
1677
1678         flist_for_each(entry, &filename_list) {
1679                 struct file_name *fn;
1680
1681                 fn = flist_entry(entry, struct file_name, list);
1682
1683                 if (!strcmp(fn->filename, fname))
1684                         return true;
1685         }
1686
1687         return false;
1688 }
1689
1690 static bool is_already_allocated(const char *fname)
1691 {
1692         bool ret;
1693
1694         fio_file_hash_lock();
1695         ret = __is_already_allocated(fname, false);
1696         fio_file_hash_unlock();
1697
1698         return ret;
1699 }
1700
1701 static void set_already_allocated(const char *fname)
1702 {
1703         struct file_name *fn;
1704
1705         fn = malloc(sizeof(struct file_name));
1706         fn->filename = strdup(fname);
1707
1708         fio_file_hash_lock();
1709         if (!__is_already_allocated(fname, true)) {
1710                 flist_add_tail(&fn->list, &filename_list);
1711                 fn = NULL;
1712         }
1713         fio_file_hash_unlock();
1714
1715         if (fn) {
1716                 free(fn->filename);
1717                 free(fn);
1718         }
1719 }
1720
1721 static void free_already_allocated(void)
1722 {
1723         struct flist_head *entry, *tmp;
1724         struct file_name *fn;
1725
1726         if (flist_empty(&filename_list))
1727                 return;
1728
1729         fio_file_hash_lock();
1730         flist_for_each_safe(entry, tmp, &filename_list) {
1731                 fn = flist_entry(entry, struct file_name, list);
1732                 free(fn->filename);
1733                 flist_del(&fn->list);
1734                 free(fn);
1735         }
1736
1737         fio_file_hash_unlock();
1738 }
1739
1740 static struct fio_file *alloc_new_file(struct thread_data *td)
1741 {
1742         struct fio_file *f;
1743
1744         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
1745                 f = calloc(1, sizeof(*f));
1746         else
1747                 f = scalloc(1, sizeof(*f));
1748         if (!f) {
1749                 assert(0);
1750                 return NULL;
1751         }
1752
1753         f->fd = -1;
1754         f->shadow_fd = -1;
1755         fio_file_reset(td, f);
1756         if (!td_ioengine_flagged(td, FIO_NOFILEHASH))
1757                 fio_file_set_smalloc(f);
1758         return f;
1759 }
1760
1761 bool exists_and_not_regfile(const char *filename)
1762 {
1763         struct stat sb;
1764
1765         if (lstat(filename, &sb) == -1)
1766                 return false;
1767
1768 #ifndef WIN32 /* NOT Windows */
1769         if (S_ISREG(sb.st_mode))
1770                 return false;
1771 #else
1772         /* \\.\ is the device namespace in Windows, where every file
1773          * is a device node */
1774         if (S_ISREG(sb.st_mode) && strncmp(filename, "\\\\.\\", 4) != 0)
1775                 return false;
1776 #endif
1777
1778         return true;
1779 }
1780
1781 int add_file(struct thread_data *td, const char *fname, int numjob, int inc)
1782 {
1783         int cur_files = td->files_index;
1784         char file_name[PATH_MAX];
1785         struct fio_file *f;
1786         int len = 0;
1787
1788         dprint(FD_FILE, "add file %s\n", fname);
1789
1790         if (td->o.directory)
1791                 len = set_name_idx(file_name, PATH_MAX, td->o.directory, numjob,
1792                                         td->o.unique_filename);
1793
1794         sprintf(file_name + len, "%s", fname);
1795
1796         /* clean cloned siblings using existing files */
1797         if (numjob && is_already_allocated(file_name) &&
1798             !exists_and_not_regfile(fname))
1799                 return 0;
1800
1801         f = alloc_new_file(td);
1802
1803         if (td->files_size <= td->files_index) {
1804                 unsigned int new_size = td->o.nr_files + 1;
1805
1806                 dprint(FD_FILE, "resize file array to %d files\n", new_size);
1807
1808                 td->files = realloc(td->files, new_size * sizeof(f));
1809                 if (td->files == NULL) {
1810                         log_err("fio: realloc OOM\n");
1811                         assert(0);
1812                 }
1813                 if (td->o.file_lock_mode != FILE_LOCK_NONE) {
1814                         td->file_locks = realloc(td->file_locks, new_size);
1815                         if (!td->file_locks) {
1816                                 log_err("fio: realloc OOM\n");
1817                                 assert(0);
1818                         }
1819                         td->file_locks[cur_files] = FILE_LOCK_NONE;
1820                 }
1821                 td->files_size = new_size;
1822         }
1823         td->files[cur_files] = f;
1824         f->fileno = cur_files;
1825
1826         /*
1827          * init function, io engine may not be loaded yet
1828          */
1829         if (td->io_ops && td_ioengine_flagged(td, FIO_DISKLESSIO))
1830                 f->real_file_size = -1ULL;
1831
1832         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
1833                 f->file_name = strdup(file_name);
1834         else
1835                 f->file_name = smalloc_strdup(file_name);
1836
1837         /* can't handle smalloc failure from here */
1838         assert(f->file_name);
1839
1840         get_file_type(f);
1841
1842         switch (td->o.file_lock_mode) {
1843         case FILE_LOCK_NONE:
1844                 break;
1845         case FILE_LOCK_READWRITE:
1846                 f->rwlock = fio_rwlock_init();
1847                 break;
1848         case FILE_LOCK_EXCLUSIVE:
1849                 f->lock = fio_sem_init(FIO_SEM_UNLOCKED);
1850                 break;
1851         default:
1852                 log_err("fio: unknown lock mode: %d\n", td->o.file_lock_mode);
1853                 assert(0);
1854         }
1855
1856         td->files_index++;
1857
1858         if (td->o.numjobs > 1)
1859                 set_already_allocated(file_name);
1860
1861         if (inc)
1862                 td->o.nr_files++;
1863
1864         dprint(FD_FILE, "file %p \"%s\" added at %d\n", f, f->file_name,
1865                                                         cur_files);
1866
1867         return cur_files;
1868 }
1869
1870 int add_file_exclusive(struct thread_data *td, const char *fname)
1871 {
1872         struct fio_file *f;
1873         unsigned int i;
1874
1875         for_each_file(td, f, i) {
1876                 if (!strcmp(f->file_name, fname))
1877                         return i;
1878         }
1879
1880         return add_file(td, fname, 0, 1);
1881 }
1882
1883 void get_file(struct fio_file *f)
1884 {
1885         dprint(FD_FILE, "get file %s, ref=%d\n", f->file_name, f->references);
1886         assert(fio_file_open(f));
1887         f->references++;
1888 }
1889
1890 int put_file(struct thread_data *td, struct fio_file *f)
1891 {
1892         int f_ret = 0, ret = 0;
1893
1894         dprint(FD_FILE, "put file %s, ref=%d\n", f->file_name, f->references);
1895
1896         if (!fio_file_open(f)) {
1897                 assert(f->fd == -1);
1898                 return 0;
1899         }
1900
1901         assert(f->references);
1902         if (--f->references)
1903                 return 0;
1904
1905         disk_util_dec(f->du);
1906
1907         if (td->o.file_lock_mode != FILE_LOCK_NONE)
1908                 unlock_file_all(td, f);
1909
1910         if (should_fsync(td) && td->o.fsync_on_close) {
1911                 f_ret = fsync(f->fd);
1912                 if (f_ret < 0)
1913                         f_ret = errno;
1914         }
1915
1916         if (td->io_ops->close_file)
1917                 ret = td->io_ops->close_file(td, f);
1918
1919         if (!ret)
1920                 ret = f_ret;
1921
1922         td->nr_open_files--;
1923         fio_file_clear_closing(f);
1924         fio_file_clear_open(f);
1925         assert(f->fd == -1);
1926         return ret;
1927 }
1928
1929 void lock_file(struct thread_data *td, struct fio_file *f, enum fio_ddir ddir)
1930 {
1931         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1932                 return;
1933
1934         if (td->o.file_lock_mode == FILE_LOCK_READWRITE) {
1935                 if (ddir == DDIR_READ)
1936                         fio_rwlock_read(f->rwlock);
1937                 else
1938                         fio_rwlock_write(f->rwlock);
1939         } else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1940                 fio_sem_down(f->lock);
1941
1942         td->file_locks[f->fileno] = td->o.file_lock_mode;
1943 }
1944
1945 void unlock_file(struct thread_data *td, struct fio_file *f)
1946 {
1947         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1948                 return;
1949
1950         if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
1951                 fio_rwlock_unlock(f->rwlock);
1952         else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1953                 fio_sem_up(f->lock);
1954
1955         td->file_locks[f->fileno] = FILE_LOCK_NONE;
1956 }
1957
1958 void unlock_file_all(struct thread_data *td, struct fio_file *f)
1959 {
1960         if (td->o.file_lock_mode == FILE_LOCK_NONE || !td->file_locks)
1961                 return;
1962         if (td->file_locks[f->fileno] != FILE_LOCK_NONE)
1963                 unlock_file(td, f);
1964 }
1965
1966 static bool recurse_dir(struct thread_data *td, const char *dirname)
1967 {
1968         struct dirent *dir;
1969         bool ret = false;
1970         DIR *D;
1971
1972         D = opendir(dirname);
1973         if (!D) {
1974                 char buf[FIO_VERROR_SIZE];
1975
1976                 snprintf(buf, FIO_VERROR_SIZE, "opendir(%s)", dirname);
1977                 td_verror(td, errno, buf);
1978                 return true;
1979         }
1980
1981         while ((dir = readdir(D)) != NULL) {
1982                 char full_path[PATH_MAX];
1983                 struct stat sb;
1984
1985                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1986                         continue;
1987
1988                 sprintf(full_path, "%s%c%s", dirname, FIO_OS_PATH_SEPARATOR, dir->d_name);
1989
1990                 if (lstat(full_path, &sb) == -1) {
1991                         if (errno != ENOENT) {
1992                                 td_verror(td, errno, "stat");
1993                                 ret = true;
1994                                 break;
1995                         }
1996                 }
1997
1998                 if (S_ISREG(sb.st_mode)) {
1999                         add_file(td, full_path, 0, 1);
2000                         continue;
2001                 }
2002                 if (!S_ISDIR(sb.st_mode))
2003                         continue;
2004
2005                 ret = recurse_dir(td, full_path);
2006                 if (ret)
2007                         break;
2008         }
2009
2010         closedir(D);
2011         return ret;
2012 }
2013
2014 int add_dir_files(struct thread_data *td, const char *path)
2015 {
2016         int ret = recurse_dir(td, path);
2017
2018         if (!ret)
2019                 log_info("fio: opendir added %d files\n", td->o.nr_files);
2020
2021         return ret;
2022 }
2023
2024 void dup_files(struct thread_data *td, struct thread_data *org)
2025 {
2026         struct fio_file *f;
2027         unsigned int i;
2028
2029         dprint(FD_FILE, "dup files: %d\n", org->files_index);
2030
2031         if (!org->files)
2032                 return;
2033
2034         td->files = malloc(org->files_index * sizeof(f));
2035
2036         if (td->o.file_lock_mode != FILE_LOCK_NONE)
2037                 td->file_locks = malloc(org->files_index);
2038
2039         for_each_file(org, f, i) {
2040                 struct fio_file *__f;
2041
2042                 __f = alloc_new_file(td);
2043
2044                 if (f->file_name) {
2045                         if (td_ioengine_flagged(td, FIO_NOFILEHASH))
2046                                 __f->file_name = strdup(f->file_name);
2047                         else
2048                                 __f->file_name = smalloc_strdup(f->file_name);
2049
2050                         /* can't handle smalloc failure from here */
2051                         assert(__f->file_name);
2052                         __f->filetype = f->filetype;
2053                 }
2054
2055                 if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
2056                         __f->lock = f->lock;
2057                 else if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
2058                         __f->rwlock = f->rwlock;
2059
2060                 td->files[i] = __f;
2061         }
2062 }
2063
2064 /*
2065  * Returns the index that matches the filename, or -1 if not there
2066  */
2067 int get_fileno(struct thread_data *td, const char *fname)
2068 {
2069         struct fio_file *f;
2070         unsigned int i;
2071
2072         for_each_file(td, f, i)
2073                 if (!strcmp(f->file_name, fname))
2074                         return i;
2075
2076         return -1;
2077 }
2078
2079 /*
2080  * For log usage, where we add/open/close files automatically
2081  */
2082 void free_release_files(struct thread_data *td)
2083 {
2084         close_files(td);
2085         td->o.nr_files = 0;
2086         td->o.open_files = 0;
2087         td->files_index = 0;
2088 }
2089
2090 void fio_file_reset(struct thread_data *td, struct fio_file *f)
2091 {
2092         int i;
2093
2094         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
2095                 f->last_pos[i] = f->file_offset;
2096                 f->last_start[i] = -1ULL;
2097         }
2098
2099         if (fio_file_axmap(f))
2100                 axmap_reset(f->io_axmap);
2101         else if (fio_file_lfsr(f))
2102                 lfsr_reset(&f->lfsr, td->rand_seeds[FIO_RAND_BLOCK_OFF]);
2103
2104         zbd_file_reset(td, f);
2105 }
2106
2107 bool fio_files_done(struct thread_data *td)
2108 {
2109         struct fio_file *f;
2110         unsigned int i;
2111
2112         for_each_file(td, f, i)
2113                 if (!fio_file_done(f))
2114                         return false;
2115
2116         return true;
2117 }
2118
2119 /* free memory used in initialization phase only */
2120 void filesetup_mem_free(void)
2121 {
2122         free_already_allocated();
2123 }
2124
2125 /*
2126  * This function is for platforms which support direct I/O but not O_DIRECT.
2127  */
2128 int fio_set_directio(struct thread_data *td, struct fio_file *f)
2129 {
2130 #ifdef FIO_OS_DIRECTIO
2131         int ret = fio_set_odirect(f);
2132
2133         if (ret) {
2134                 td_verror(td, ret, "fio_set_directio");
2135 #if defined(__sun__)
2136                 if (ret == ENOTTY) { /* ENOTTY suggests RAW device or ZFS */
2137                         log_err("fio: doing directIO to RAW devices or ZFS not supported\n");
2138                 } else {
2139                         log_err("fio: the file system does not seem to support direct IO\n");
2140                 }
2141 #else
2142                 log_err("fio: the file system does not seem to support direct IO\n");
2143 #endif
2144                 return -1;
2145         }
2146
2147         return 0;
2148 #else
2149         log_err("fio: direct IO is not supported on this host operating system\n");
2150         return -1;
2151 #endif
2152 }