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