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