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