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