Fix another typo in gtod_reduce()
[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 "os/os.h"
15 #include "hash.h"
16 #include "lib/axmap.h"
17
18 #ifdef CONFIG_LINUX_FALLOCATE
19 #include <linux/falloc.h>
20 #endif
21
22 static int root_warn;
23
24 static inline void clear_error(struct thread_data *td)
25 {
26         td->error = 0;
27         td->verror[0] = '\0';
28 }
29
30 /*
31  * Leaves f->fd open on success, caller must close
32  */
33 static int extend_file(struct thread_data *td, struct fio_file *f)
34 {
35         int r, new_layout = 0, unlink_file = 0, flags;
36         unsigned long long left;
37         unsigned int bs;
38         char *b;
39
40         if (read_only) {
41                 log_err("fio: refusing extend of file due to read-only\n");
42                 return 0;
43         }
44
45         /*
46          * check if we need to lay the file out complete again. fio
47          * does that for operations involving reads, or for writes
48          * where overwrite is set
49          */
50         if (td_read(td) || (td_write(td) && td->o.overwrite) ||
51             (td_write(td) && td->io_ops->flags & FIO_NOEXTEND))
52                 new_layout = 1;
53         if (td_write(td) && !td->o.overwrite)
54                 unlink_file = 1;
55
56         if (unlink_file || new_layout) {
57                 dprint(FD_FILE, "layout unlink %s\n", f->file_name);
58                 if ((unlink(f->file_name) < 0) && (errno != ENOENT)) {
59                         td_verror(td, errno, "unlink");
60                         return 1;
61                 }
62         }
63
64         flags = O_WRONLY | O_CREAT;
65         if (new_layout)
66                 flags |= O_TRUNC;
67
68         dprint(FD_FILE, "open file %s, flags %x\n", f->file_name, flags);
69         f->fd = open(f->file_name, flags, 0644);
70         if (f->fd < 0) {
71                 td_verror(td, errno, "open");
72                 return 1;
73         }
74
75 #ifdef CONFIG_POSIX_FALLOCATE
76         if (!td->o.fill_device) {
77                 switch (td->o.fallocate_mode) {
78                 case FIO_FALLOCATE_NONE:
79                         break;
80                 case FIO_FALLOCATE_POSIX:
81                         dprint(FD_FILE, "posix_fallocate file %s size %llu\n",
82                                  f->file_name,
83                                  (unsigned long long) f->real_file_size);
84
85                         r = posix_fallocate(f->fd, 0, f->real_file_size);
86                         if (r > 0) {
87                                 log_err("fio: posix_fallocate fails: %s\n",
88                                                 strerror(r));
89                         }
90                         break;
91 #ifdef CONFIG_LINUX_FALLOCATE
92                 case FIO_FALLOCATE_KEEP_SIZE:
93                         dprint(FD_FILE,
94                                 "fallocate(FALLOC_FL_KEEP_SIZE) "
95                                 "file %s size %llu\n", f->file_name,
96                                 (unsigned long long) f->real_file_size);
97
98                         r = fallocate(f->fd, FALLOC_FL_KEEP_SIZE, 0,
99                                         f->real_file_size);
100                         if (r != 0)
101                                 td_verror(td, errno, "fallocate");
102
103                         break;
104 #endif /* CONFIG_LINUX_FALLOCATE */
105                 default:
106                         log_err("fio: unknown fallocate mode: %d\n",
107                                 td->o.fallocate_mode);
108                         assert(0);
109                 }
110         }
111 #endif /* CONFIG_POSIX_FALLOCATE */
112
113         if (!new_layout)
114                 goto done;
115
116         /*
117          * The size will be -1ULL when fill_device is used, so don't truncate
118          * or fallocate this file, just write it
119          */
120         if (!td->o.fill_device) {
121                 dprint(FD_FILE, "truncate file %s, size %llu\n", f->file_name,
122                                         (unsigned long long) f->real_file_size);
123                 if (ftruncate(f->fd, f->real_file_size) == -1) {
124                         if (errno != EFBIG) {
125                                 td_verror(td, errno, "ftruncate");
126                                 goto err;
127                         }
128                 }
129         }
130
131         b = malloc(td->o.max_bs[DDIR_WRITE]);
132
133         left = f->real_file_size;
134         while (left && !td->terminate) {
135                 bs = td->o.max_bs[DDIR_WRITE];
136                 if (bs > left)
137                         bs = left;
138
139                 fill_io_buffer(td, b, bs, bs);
140
141                 r = write(f->fd, b, bs);
142
143                 if (r > 0) {
144                         left -= r;
145                         continue;
146                 } else {
147                         if (r < 0) {
148                                 int __e = errno;
149
150                                 if (__e == ENOSPC) {
151                                         if (td->o.fill_device)
152                                                 break;
153                                         log_info("fio: ENOSPC on laying out "
154                                                  "file, stopping\n");
155                                         break;
156                                 }
157                                 td_verror(td, errno, "write");
158                         } else
159                                 td_verror(td, EIO, "write");
160
161                         break;
162                 }
163         }
164
165         if (td->terminate) {
166                 dprint(FD_FILE, "terminate unlink %s\n", f->file_name);
167                 unlink(f->file_name);
168         } else if (td->o.create_fsync) {
169                 if (fsync(f->fd) < 0) {
170                         td_verror(td, errno, "fsync");
171                         goto err;
172                 }
173         }
174         if (td->o.fill_device && !td_write(td)) {
175                 fio_file_clear_size_known(f);
176                 if (td_io_get_file_size(td, f))
177                         goto err;
178                 if (f->io_size > f->real_file_size)
179                         f->io_size = f->real_file_size;
180         }
181
182         free(b);
183 done:
184         return 0;
185 err:
186         close(f->fd);
187         f->fd = -1;
188         return 1;
189 }
190
191 static int pre_read_file(struct thread_data *td, struct fio_file *f)
192 {
193         int r, did_open = 0, old_runstate;
194         unsigned long long left;
195         unsigned int bs;
196         char *b;
197
198         if (td->io_ops->flags & FIO_PIPEIO)
199                 return 0;
200
201         if (!fio_file_open(f)) {
202                 if (td->io_ops->open_file(td, f)) {
203                         log_err("fio: cannot pre-read, failed to open file\n");
204                         return 1;
205                 }
206                 did_open = 1;
207         }
208
209         old_runstate = td->runstate;
210         td_set_runstate(td, TD_PRE_READING);
211
212         bs = td->o.max_bs[DDIR_READ];
213         b = malloc(bs);
214         memset(b, 0, bs);
215
216         lseek(f->fd, f->file_offset, SEEK_SET);
217         left = f->io_size;
218
219         while (left && !td->terminate) {
220                 if (bs > left)
221                         bs = left;
222
223                 r = read(f->fd, b, bs);
224
225                 if (r == (int) bs) {
226                         left -= bs;
227                         continue;
228                 } else {
229                         td_verror(td, EIO, "pre_read");
230                         break;
231                 }
232         }
233
234         td_set_runstate(td, old_runstate);
235
236         if (did_open)
237                 td->io_ops->close_file(td, f);
238         free(b);
239         return 0;
240 }
241
242 static unsigned long long get_rand_file_size(struct thread_data *td)
243 {
244         unsigned long long ret, sized;
245         unsigned long r;
246
247         if (td->o.use_os_rand) {
248                 r = os_random_long(&td->file_size_state);
249                 sized = td->o.file_size_high - td->o.file_size_low;
250                 ret = (unsigned long long) ((double) sized * (r / (OS_RAND_MAX + 1.0)));
251         } else {
252                 r = __rand(&td->__file_size_state);
253                 sized = td->o.file_size_high - td->o.file_size_low;
254                 ret = (unsigned long long) ((double) sized * (r / (FRAND_MAX + 1.0)));
255         }
256
257         ret += td->o.file_size_low;
258         ret -= (ret % td->o.rw_min_bs);
259         return ret;
260 }
261
262 static int file_size(struct thread_data *td, struct fio_file *f)
263 {
264         struct stat st;
265
266         if (stat(f->file_name, &st) == -1) {
267                 td_verror(td, errno, "fstat");
268                 return 1;
269         }
270
271         f->real_file_size = st.st_size;
272         return 0;
273 }
274
275 static int bdev_size(struct thread_data *td, struct fio_file *f)
276 {
277         unsigned long long bytes = 0;
278         int r;
279
280         if (td->io_ops->open_file(td, f)) {
281                 log_err("fio: failed opening blockdev %s for size check\n",
282                         f->file_name);
283                 return 1;
284         }
285
286         r = blockdev_size(f, &bytes);
287         if (r) {
288                 td_verror(td, r, "blockdev_size");
289                 goto err;
290         }
291
292         if (!bytes) {
293                 log_err("%s: zero sized block device?\n", f->file_name);
294                 goto err;
295         }
296
297         f->real_file_size = bytes;
298         td->io_ops->close_file(td, f);
299         return 0;
300 err:
301         td->io_ops->close_file(td, f);
302         return 1;
303 }
304
305 static int char_size(struct thread_data *td, struct fio_file *f)
306 {
307 #ifdef FIO_HAVE_CHARDEV_SIZE
308         unsigned long long bytes = 0;
309         int r;
310
311         if (td->io_ops->open_file(td, f)) {
312                 log_err("fio: failed opening blockdev %s for size check\n",
313                         f->file_name);
314                 return 1;
315         }
316
317         r = chardev_size(f, &bytes);
318         if (r) {
319                 td_verror(td, r, "chardev_size");
320                 goto err;
321         }
322
323         if (!bytes) {
324                 log_err("%s: zero sized char device?\n", f->file_name);
325                 goto err;
326         }
327
328         f->real_file_size = bytes;
329         td->io_ops->close_file(td, f);
330         return 0;
331 err:
332         td->io_ops->close_file(td, f);
333         return 1;
334 #else
335         f->real_file_size = -1ULL;
336         return 0;
337 #endif
338 }
339
340 static int get_file_size(struct thread_data *td, struct fio_file *f)
341 {
342         int ret = 0;
343
344         if (fio_file_size_known(f))
345                 return 0;
346
347         if (f->filetype == FIO_TYPE_FILE)
348                 ret = file_size(td, f);
349         else if (f->filetype == FIO_TYPE_BD)
350                 ret = bdev_size(td, f);
351         else if (f->filetype == FIO_TYPE_CHAR)
352                 ret = char_size(td, f);
353         else
354                 f->real_file_size = -1;
355
356         if (ret)
357                 return ret;
358
359         if (f->file_offset > f->real_file_size) {
360                 log_err("%s: offset extends end (%llu > %llu)\n", td->o.name,
361                                         (unsigned long long) f->file_offset,
362                                         (unsigned long long) f->real_file_size);
363                 return 1;
364         }
365
366         fio_file_set_size_known(f);
367         return 0;
368 }
369
370 static int __file_invalidate_cache(struct thread_data *td, struct fio_file *f,
371                                    unsigned long long off,
372                                    unsigned long long len)
373 {
374         int ret = 0;
375
376         if (len == -1ULL)
377                 len = f->io_size;
378         if (off == -1ULL)
379                 off = f->file_offset;
380
381         if (len == -1ULL || off == -1ULL)
382                 return 0;
383
384         dprint(FD_IO, "invalidate cache %s: %llu/%llu\n", f->file_name, off,
385                                                                 len);
386
387         /*
388          * FIXME: add blockdev flushing too
389          */
390         if (f->mmap_ptr) {
391                 ret = posix_madvise(f->mmap_ptr, f->mmap_sz, POSIX_MADV_DONTNEED);
392 #ifdef FIO_MADV_FREE
393                 if (f->filetype == FIO_TYPE_BD)
394                         (void) posix_madvise(f->mmap_ptr, f->mmap_sz, FIO_MADV_FREE);
395 #endif
396         } else if (f->filetype == FIO_TYPE_FILE) {
397                 ret = posix_fadvise(f->fd, off, len, POSIX_FADV_DONTNEED);
398         } else if (f->filetype == FIO_TYPE_BD) {
399                 ret = blockdev_invalidate_cache(f);
400                 if (ret < 0 && errno == EACCES && geteuid()) {
401                         if (!root_warn) {
402                                 log_err("fio: only root may flush block "
403                                         "devices. Cache flush bypassed!\n");
404                                 root_warn = 1;
405                         }
406                         ret = 0;
407                 }
408         } else if (f->filetype == FIO_TYPE_CHAR || f->filetype == FIO_TYPE_PIPE)
409                 ret = 0;
410
411         if (ret < 0) {
412                 td_verror(td, errno, "invalidate_cache");
413                 return 1;
414         } else if (ret > 0) {
415                 td_verror(td, ret, "invalidate_cache");
416                 return 1;
417         }
418
419         return ret;
420
421 }
422
423 int file_invalidate_cache(struct thread_data *td, struct fio_file *f)
424 {
425         if (!fio_file_open(f))
426                 return 0;
427
428         return __file_invalidate_cache(td, f, -1ULL, -1ULL);
429 }
430
431 int generic_close_file(struct thread_data fio_unused *td, struct fio_file *f)
432 {
433         int ret = 0;
434
435         dprint(FD_FILE, "fd close %s\n", f->file_name);
436
437         remove_file_hash(f);
438
439         if (close(f->fd) < 0)
440                 ret = errno;
441
442         f->fd = -1;
443
444         if (f->shadow_fd != -1) {
445                 close(f->shadow_fd);
446                 f->shadow_fd = -1;
447         }
448
449         f->engine_data = 0;
450         return ret;
451 }
452
453 int file_lookup_open(struct fio_file *f, int flags)
454 {
455         struct fio_file *__f;
456         int from_hash;
457
458         __f = lookup_file_hash(f->file_name);
459         if (__f) {
460                 dprint(FD_FILE, "found file in hash %s\n", f->file_name);
461                 /*
462                  * racy, need the __f->lock locked
463                  */
464                 f->lock = __f->lock;
465                 from_hash = 1;
466         } else {
467                 dprint(FD_FILE, "file not found in hash %s\n", f->file_name);
468                 from_hash = 0;
469         }
470
471         f->fd = open(f->file_name, flags, 0600);
472         return from_hash;
473 }
474
475 static int file_close_shadow_fds(struct thread_data *td)
476 {
477         struct fio_file *f;
478         int num_closed = 0;
479         unsigned int i;
480
481         for_each_file(td, f, i) {
482                 if (f->shadow_fd == -1)
483                         continue;
484
485                 close(f->shadow_fd);
486                 f->shadow_fd = -1;
487                 num_closed++;
488         }
489
490         return num_closed;
491 }
492
493 int generic_open_file(struct thread_data *td, struct fio_file *f)
494 {
495         int is_std = 0;
496         int flags = 0;
497         int from_hash = 0;
498
499         dprint(FD_FILE, "fd open %s\n", f->file_name);
500
501         if (td_trim(td) && f->filetype != FIO_TYPE_BD) {
502                 log_err("fio: trim only applies to block device\n");
503                 return 1;
504         }
505
506         if (!strcmp(f->file_name, "-")) {
507                 if (td_rw(td)) {
508                         log_err("fio: can't read/write to stdin/out\n");
509                         return 1;
510                 }
511                 is_std = 1;
512
513                 /*
514                  * move output logging to stderr, if we are writing to stdout
515                  */
516                 if (td_write(td))
517                         f_out = stderr;
518         }
519
520         if (td_trim(td))
521                 goto skip_flags;
522         if (td->o.odirect)
523                 flags |= OS_O_DIRECT;
524         if (td->o.oatomic) {
525                 if (!FIO_O_ATOMIC) {
526                         td_verror(td, EINVAL, "OS does not support atomic IO");
527                         return 1;
528                 }
529                 flags |= OS_O_DIRECT | FIO_O_ATOMIC;
530         }
531         if (td->o.sync_io)
532                 flags |= O_SYNC;
533         if (td->o.create_on_open)
534                 flags |= O_CREAT;
535 skip_flags:
536         if (f->filetype != FIO_TYPE_FILE)
537                 flags |= FIO_O_NOATIME;
538
539 open_again:
540         if (td_write(td)) {
541                 if (!read_only)
542                         flags |= O_RDWR;
543
544                 if (f->filetype == FIO_TYPE_FILE)
545                         flags |= O_CREAT;
546
547                 if (is_std)
548                         f->fd = dup(STDOUT_FILENO);
549                 else
550                         from_hash = file_lookup_open(f, flags);
551         } else if (td_read(td)) {
552                 if (f->filetype == FIO_TYPE_CHAR && !read_only)
553                         flags |= O_RDWR;
554                 else
555                         flags |= O_RDONLY;
556
557                 if (is_std)
558                         f->fd = dup(STDIN_FILENO);
559                 else
560                         from_hash = file_lookup_open(f, flags);
561         } else { //td trim
562                 flags |= O_RDWR;
563                 from_hash = file_lookup_open(f, flags);
564         }
565
566         if (f->fd == -1) {
567                 char buf[FIO_VERROR_SIZE];
568                 int __e = errno;
569
570                 if (__e == EPERM && (flags & FIO_O_NOATIME)) {
571                         flags &= ~FIO_O_NOATIME;
572                         goto open_again;
573                 }
574                 if (__e == EMFILE && file_close_shadow_fds(td))
575                         goto open_again;
576
577                 snprintf(buf, sizeof(buf), "open(%s)", f->file_name);
578
579                 if (__e == EINVAL && (flags & OS_O_DIRECT)) {
580                         log_err("fio: looks like your file system does not " \
581                                 "support direct=1/buffered=0\n");
582                 }
583
584                 td_verror(td, __e, buf);
585         }
586
587         if (!from_hash && f->fd != -1) {
588                 if (add_file_hash(f)) {
589                         int fio_unused ret;
590
591                         /*
592                          * Stash away descriptor for later close. This is to
593                          * work-around a "feature" on Linux, where a close of
594                          * an fd that has been opened for write will trigger
595                          * udev to call blkid to check partitions, fs id, etc.
596                          * That pollutes the device cache, which can slow down
597                          * unbuffered accesses.
598                          */
599                         if (f->shadow_fd == -1)
600                                 f->shadow_fd = f->fd;
601                         else {
602                                 /*
603                                  * OK to ignore, we haven't done anything
604                                  * with it
605                                  */
606                                 ret = generic_close_file(td, f);
607                         }
608                         goto open_again;
609                 }
610         }
611
612         return 0;
613 }
614
615 int generic_get_file_size(struct thread_data *td, struct fio_file *f)
616 {
617         return get_file_size(td, f);
618 }
619
620 /*
621  * open/close all files, so that ->real_file_size gets set
622  */
623 static int get_file_sizes(struct thread_data *td)
624 {
625         struct fio_file *f;
626         unsigned int i;
627         int err = 0;
628
629         for_each_file(td, f, i) {
630                 dprint(FD_FILE, "get file size for %p/%d/%p\n", f, i,
631                                                                 f->file_name);
632
633                 if (td_io_get_file_size(td, f)) {
634                         if (td->error != ENOENT) {
635                                 log_err("%s\n", td->verror);
636                                 err = 1;
637                         }
638                         clear_error(td);
639                 }
640
641                 if (f->real_file_size == -1ULL && td->o.size)
642                         f->real_file_size = td->o.size / td->o.nr_files;
643         }
644
645         return err;
646 }
647
648 struct fio_mount {
649         struct flist_head list;
650         const char *base;
651         char __base[256];
652         unsigned int key;
653 };
654
655 /*
656  * Get free number of bytes for each file on each unique mount.
657  */
658 static unsigned long long get_fs_free_counts(struct thread_data *td)
659 {
660         struct flist_head *n, *tmp;
661         unsigned long long ret = 0;
662         struct fio_mount *fm;
663         FLIST_HEAD(list);
664         struct fio_file *f;
665         unsigned int i;
666
667         for_each_file(td, f, i) {
668                 struct stat sb;
669                 char buf[256];
670
671                 if (f->filetype == FIO_TYPE_BD || f->filetype == FIO_TYPE_CHAR) {
672                         if (f->real_file_size != -1ULL)
673                                 ret += f->real_file_size;
674                         continue;
675                 } else if (f->filetype != FIO_TYPE_FILE)
676                         continue;
677
678                 strcpy(buf, f->file_name);
679
680                 if (stat(buf, &sb) < 0) {
681                         if (errno != ENOENT)
682                                 break;
683                         strcpy(buf, ".");
684                         if (stat(buf, &sb) < 0)
685                                 break;
686                 }
687
688                 fm = NULL;
689                 flist_for_each(n, &list) {
690                         fm = flist_entry(n, struct fio_mount, list);
691                         if (fm->key == sb.st_dev)
692                                 break;
693
694                         fm = NULL;
695                 }
696
697                 if (fm)
698                         continue;
699
700                 fm = malloc(sizeof(*fm));
701                 strcpy(fm->__base, buf);
702                 fm->base = basename(fm->__base);
703                 fm->key = sb.st_dev;
704                 flist_add(&fm->list, &list);
705         }
706
707         flist_for_each_safe(n, tmp, &list) {
708                 unsigned long long sz;
709
710                 fm = flist_entry(n, struct fio_mount, list);
711                 flist_del(&fm->list);
712
713                 sz = get_fs_size(fm->base);
714                 if (sz && sz != -1ULL)
715                         ret += sz;
716
717                 free(fm);
718         }
719
720         return ret;
721 }
722
723 uint64_t get_start_offset(struct thread_data *td)
724 {
725         return td->o.start_offset +
726                 (td->thread_number - 1) * td->o.offset_increment;
727 }
728
729 /*
730  * Open the files and setup files sizes, creating files if necessary.
731  */
732 int setup_files(struct thread_data *td)
733 {
734         unsigned long long total_size, extend_size;
735         struct thread_options *o = &td->o;
736         struct fio_file *f;
737         unsigned int i, nr_fs_extra = 0;
738         int err = 0, need_extend;
739         int old_state;
740         const unsigned int bs = td_min_bs(td);
741         uint64_t fs = 0;
742
743         dprint(FD_FILE, "setup files\n");
744
745         old_state = td->runstate;
746         td_set_runstate(td, TD_SETTING_UP);
747
748         if (o->read_iolog_file)
749                 goto done;
750
751         /*
752          * if ioengine defines a setup() method, it's responsible for
753          * opening the files and setting f->real_file_size to indicate
754          * the valid range for that file.
755          */
756         if (td->io_ops->setup)
757                 err = td->io_ops->setup(td);
758         else
759                 err = get_file_sizes(td);
760
761         if (err)
762                 goto err_out;
763
764         /*
765          * check sizes. if the files/devices do not exist and the size
766          * isn't passed to fio, abort.
767          */
768         total_size = 0;
769         for_each_file(td, f, i) {
770                 if (f->real_file_size == -1ULL)
771                         total_size = -1ULL;
772                 else
773                         total_size += f->real_file_size;
774         }
775
776         if (o->fill_device)
777                 td->fill_device_size = get_fs_free_counts(td);
778
779         /*
780          * device/file sizes are zero and no size given, punt
781          */
782         if ((!total_size || total_size == -1ULL) && !o->size &&
783             !(td->io_ops->flags & FIO_NOIO) && !o->fill_device &&
784             !(o->nr_files && (o->file_size_low || o->file_size_high))) {
785                 log_err("%s: you need to specify size=\n", o->name);
786                 td_verror(td, EINVAL, "total_file_size");
787                 goto err_out;
788         }
789
790         /*
791          * Calculate per-file size and potential extra size for the
792          * first files, if needed.
793          */
794         if (!o->file_size_low) {
795                 uint64_t all_fs;
796
797                 fs = o->size / o->nr_files;
798                 all_fs = fs * o->nr_files;
799
800                 if (all_fs < o->size)
801                         nr_fs_extra = (o->size - all_fs) / bs;
802         }
803
804         /*
805          * now file sizes are known, so we can set ->io_size. if size= is
806          * not given, ->io_size is just equal to ->real_file_size. if size
807          * is given, ->io_size is size / nr_files.
808          */
809         extend_size = total_size = 0;
810         need_extend = 0;
811         for_each_file(td, f, i) {
812                 f->file_offset = get_start_offset(td);
813
814                 if (!o->file_size_low) {
815                         /*
816                          * no file size range given, file size is equal to
817                          * total size divided by number of files. If that is
818                          * zero, set it to the real file size. If the size
819                          * doesn't divide nicely with the min blocksize,
820                          * make the first files bigger.
821                          */
822                         f->io_size = fs;
823                         if (nr_fs_extra) {
824                                 nr_fs_extra--;
825                                 f->io_size += bs;
826                         }
827
828                         if (!f->io_size)
829                                 f->io_size = f->real_file_size - f->file_offset;
830                 } else if (f->real_file_size < o->file_size_low ||
831                            f->real_file_size > o->file_size_high) {
832                         if (f->file_offset > o->file_size_low)
833                                 goto err_offset;
834                         /*
835                          * file size given. if it's fixed, use that. if it's a
836                          * range, generate a random size in-between.
837                          */
838                         if (o->file_size_low == o->file_size_high)
839                                 f->io_size = o->file_size_low - f->file_offset;
840                         else {
841                                 f->io_size = get_rand_file_size(td)
842                                                 - f->file_offset;
843                         }
844                 } else
845                         f->io_size = f->real_file_size - f->file_offset;
846
847                 if (f->io_size == -1ULL)
848                         total_size = -1ULL;
849                 else {
850                         if (o->size_percent)
851                                 f->io_size = (f->io_size * o->size_percent) / 100;
852                         total_size += f->io_size;
853                 }
854
855                 if (f->filetype == FIO_TYPE_FILE &&
856                     (f->io_size + f->file_offset) > f->real_file_size &&
857                     !(td->io_ops->flags & FIO_DISKLESSIO)) {
858                         if (!o->create_on_open) {
859                                 need_extend++;
860                                 extend_size += (f->io_size + f->file_offset);
861                         } else
862                                 f->real_file_size = f->io_size + f->file_offset;
863                         fio_file_set_extend(f);
864                 }
865         }
866
867         if (!o->size || o->size > total_size)
868                 o->size = total_size;
869
870         /*
871          * See if we need to extend some files
872          */
873         if (need_extend) {
874                 temp_stall_ts = 1;
875                 if (output_format == FIO_OUTPUT_NORMAL)
876                         log_info("%s: Laying out IO file(s) (%u file(s) /"
877                                  " %lluMB)\n", o->name, need_extend,
878                                         extend_size >> 20);
879
880                 for_each_file(td, f, i) {
881                         unsigned long long old_len = -1ULL, extend_len = -1ULL;
882
883                         if (!fio_file_extend(f))
884                                 continue;
885
886                         assert(f->filetype == FIO_TYPE_FILE);
887                         fio_file_clear_extend(f);
888                         if (!o->fill_device) {
889                                 old_len = f->real_file_size;
890                                 extend_len = f->io_size + f->file_offset -
891                                                 old_len;
892                         }
893                         f->real_file_size = (f->io_size + f->file_offset);
894                         err = extend_file(td, f);
895                         if (err)
896                                 break;
897
898                         err = __file_invalidate_cache(td, f, old_len,
899                                                                 extend_len);
900                         close(f->fd);
901                         f->fd = -1;
902                         if (err)
903                                 break;
904                 }
905                 temp_stall_ts = 0;
906         }
907
908         if (err)
909                 goto err_out;
910
911         if (!o->zone_size)
912                 o->zone_size = o->size;
913
914         /*
915          * iolog already set the total io size, if we read back
916          * stored entries.
917          */
918         if (!o->read_iolog_file)
919                 td->total_io_size = o->size * o->loops;
920
921 done:
922         if (o->create_only)
923                 td->done = 1;
924
925         td_set_runstate(td, old_state);
926         return 0;
927 err_offset:
928         log_err("%s: you need to specify valid offset=\n", o->name);
929 err_out:
930         td_set_runstate(td, old_state);
931         return 1;
932 }
933
934 int pre_read_files(struct thread_data *td)
935 {
936         struct fio_file *f;
937         unsigned int i;
938
939         dprint(FD_FILE, "pre_read files\n");
940
941         for_each_file(td, f, i) {
942                 pre_read_file(td, f);
943         }
944
945         return 1;
946 }
947
948 static int __init_rand_distribution(struct thread_data *td, struct fio_file *f)
949 {
950         unsigned int range_size, seed;
951         unsigned long nranges;
952         uint64_t file_size;
953
954         range_size = min(td->o.min_bs[DDIR_READ], td->o.min_bs[DDIR_WRITE]);
955         file_size = min(f->real_file_size, f->io_size);
956
957         nranges = (file_size + range_size - 1) / range_size;
958
959         seed = jhash(f->file_name, strlen(f->file_name), 0) * td->thread_number;
960         if (!td->o.rand_repeatable)
961                 seed = td->rand_seeds[4];
962
963         if (td->o.random_distribution == FIO_RAND_DIST_ZIPF)
964                 zipf_init(&f->zipf, nranges, td->o.zipf_theta.u.f, seed);
965         else
966                 pareto_init(&f->zipf, nranges, td->o.pareto_h.u.f, seed);
967
968         return 1;
969 }
970
971 static int init_rand_distribution(struct thread_data *td)
972 {
973         struct fio_file *f;
974         unsigned int i;
975         int state;
976
977         if (td->o.random_distribution == FIO_RAND_DIST_RANDOM)
978                 return 0;
979
980         state = td->runstate;
981         td_set_runstate(td, TD_SETTING_UP);
982         for_each_file(td, f, i)
983                 __init_rand_distribution(td, f);
984         td_set_runstate(td, state);
985
986         return 1;
987 }
988
989 int init_random_map(struct thread_data *td)
990 {
991         unsigned long long blocks;
992         struct fio_file *f;
993         unsigned int i;
994
995         if (init_rand_distribution(td))
996                 return 0;
997         if (!td_random(td))
998                 return 0;
999
1000         for_each_file(td, f, i) {
1001                 uint64_t file_size = min(f->real_file_size, f->io_size);
1002
1003                 blocks = file_size / (unsigned long long) td->o.rw_min_bs;
1004
1005                 if (td->o.random_generator == FIO_RAND_GEN_LFSR) {
1006                         unsigned long seed;
1007
1008                         seed = td->rand_seeds[FIO_RAND_BLOCK_OFF];
1009                         
1010                         if (!lfsr_init(&f->lfsr, blocks, seed, seed & 0xF))
1011                                 continue;
1012                 } else if (!td->o.norandommap) {
1013                         f->io_axmap = axmap_new(blocks);
1014                         if (f->io_axmap)
1015                                 continue;
1016                 } else if (td->o.norandommap)
1017                         continue;
1018
1019                 if (!td->o.softrandommap) {
1020                         log_err("fio: failed allocating random map. If running"
1021                                 " a large number of jobs, try the 'norandommap'"
1022                                 " option or set 'softrandommap'. Or give"
1023                                 " a larger --alloc-size to fio.\n");
1024                         return 1;
1025                 }
1026
1027                 log_info("fio: file %s failed allocating random map. Running "
1028                          "job without.\n", f->file_name);
1029         }
1030
1031         return 0;
1032 }
1033
1034 void close_files(struct thread_data *td)
1035 {
1036         struct fio_file *f;
1037         unsigned int i;
1038
1039         for_each_file(td, f, i) {
1040                 if (fio_file_open(f))
1041                         td_io_close_file(td, f);
1042         }
1043 }
1044
1045 void close_and_free_files(struct thread_data *td)
1046 {
1047         struct fio_file *f;
1048         unsigned int i;
1049
1050         dprint(FD_FILE, "close files\n");
1051
1052         for_each_file(td, f, i) {
1053                 if (td->o.unlink && f->filetype == FIO_TYPE_FILE) {
1054                         dprint(FD_FILE, "free unlink %s\n", f->file_name);
1055                         unlink(f->file_name);
1056                 }
1057
1058                 if (fio_file_open(f))
1059                         td_io_close_file(td, f);
1060
1061                 remove_file_hash(f);
1062
1063                 sfree(f->file_name);
1064                 f->file_name = NULL;
1065                 axmap_free(f->io_axmap);
1066                 f->io_axmap = NULL;
1067                 sfree(f);
1068         }
1069
1070         td->o.filename = NULL;
1071         free(td->files);
1072         free(td->file_locks);
1073         td->files_index = 0;
1074         td->files = NULL;
1075         td->file_locks = NULL;
1076         td->o.file_lock_mode = FILE_LOCK_NONE;
1077         td->o.nr_files = 0;
1078 }
1079
1080 static void get_file_type(struct fio_file *f)
1081 {
1082         struct stat sb;
1083
1084         if (!strcmp(f->file_name, "-"))
1085                 f->filetype = FIO_TYPE_PIPE;
1086         else
1087                 f->filetype = FIO_TYPE_FILE;
1088
1089         /* \\.\ is the device namespace in Windows, where every file is
1090          * a block device */
1091         if (strncmp(f->file_name, "\\\\.\\", 4) == 0)
1092                 f->filetype = FIO_TYPE_BD;
1093
1094         if (!stat(f->file_name, &sb)) {
1095                 if (S_ISBLK(sb.st_mode))
1096                         f->filetype = FIO_TYPE_BD;
1097                 else if (S_ISCHR(sb.st_mode))
1098                         f->filetype = FIO_TYPE_CHAR;
1099                 else if (S_ISFIFO(sb.st_mode))
1100                         f->filetype = FIO_TYPE_PIPE;
1101         }
1102 }
1103
1104 int add_file(struct thread_data *td, const char *fname)
1105 {
1106         int cur_files = td->files_index;
1107         char file_name[PATH_MAX];
1108         struct fio_file *f;
1109         int len = 0;
1110
1111         dprint(FD_FILE, "add file %s\n", fname);
1112
1113         f = smalloc(sizeof(*f));
1114         if (!f) {
1115                 log_err("fio: smalloc OOM\n");
1116                 assert(0);
1117         }
1118
1119         f->fd = -1;
1120         f->shadow_fd = -1;
1121         fio_file_reset(td, f);
1122
1123         if (td->files_size <= td->files_index) {
1124                 unsigned int new_size = td->o.nr_files + 1;
1125
1126                 dprint(FD_FILE, "resize file array to %d files\n", new_size);
1127
1128                 td->files = realloc(td->files, new_size * sizeof(f));
1129                 if (td->files == NULL) {
1130                         log_err("fio: realloc OOM\n");
1131                         assert(0);
1132                 }
1133                 if (td->o.file_lock_mode != FILE_LOCK_NONE) {
1134                         td->file_locks = realloc(td->file_locks, new_size);
1135                         if (!td->file_locks) {
1136                                 log_err("fio: realloc OOM\n");
1137                                 assert(0);
1138                         }
1139                         td->file_locks[cur_files] = FILE_LOCK_NONE;
1140                 }
1141                 td->files_size = new_size;
1142         }
1143         td->files[cur_files] = f;
1144         f->fileno = cur_files;
1145
1146         /*
1147          * init function, io engine may not be loaded yet
1148          */
1149         if (td->io_ops && (td->io_ops->flags & FIO_DISKLESSIO))
1150                 f->real_file_size = -1ULL;
1151
1152         if (td->o.directory)
1153                 len = sprintf(file_name, "%s/", td->o.directory);
1154
1155         sprintf(file_name + len, "%s", fname);
1156         f->file_name = smalloc_strdup(file_name);
1157         if (!f->file_name) {
1158                 log_err("fio: smalloc OOM\n");
1159                 assert(0);
1160         }
1161
1162         get_file_type(f);
1163
1164         switch (td->o.file_lock_mode) {
1165         case FILE_LOCK_NONE:
1166                 break;
1167         case FILE_LOCK_READWRITE:
1168                 f->rwlock = fio_rwlock_init();
1169                 break;
1170         case FILE_LOCK_EXCLUSIVE:
1171                 f->lock = fio_mutex_init(FIO_MUTEX_UNLOCKED);
1172                 break;
1173         default:
1174                 log_err("fio: unknown lock mode: %d\n", td->o.file_lock_mode);
1175                 assert(0);
1176         }
1177
1178         td->files_index++;
1179         if (f->filetype == FIO_TYPE_FILE)
1180                 td->nr_normal_files++;
1181
1182         dprint(FD_FILE, "file %p \"%s\" added at %d\n", f, f->file_name,
1183                                                         cur_files);
1184
1185         return cur_files;
1186 }
1187
1188 int add_file_exclusive(struct thread_data *td, const char *fname)
1189 {
1190         struct fio_file *f;
1191         unsigned int i;
1192
1193         for_each_file(td, f, i) {
1194                 if (!strcmp(f->file_name, fname))
1195                         return i;
1196         }
1197
1198         return add_file(td, fname);
1199 }
1200
1201 void get_file(struct fio_file *f)
1202 {
1203         dprint(FD_FILE, "get file %s, ref=%d\n", f->file_name, f->references);
1204         assert(fio_file_open(f));
1205         f->references++;
1206 }
1207
1208 int put_file(struct thread_data *td, struct fio_file *f)
1209 {
1210         int f_ret = 0, ret = 0;
1211
1212         dprint(FD_FILE, "put file %s, ref=%d\n", f->file_name, f->references);
1213
1214         if (!fio_file_open(f)) {
1215                 assert(f->fd == -1);
1216                 return 0;
1217         }
1218
1219         assert(f->references);
1220         if (--f->references)
1221                 return 0;
1222
1223         if (should_fsync(td) && td->o.fsync_on_close)
1224                 f_ret = fsync(f->fd);
1225
1226         if (td->io_ops->close_file)
1227                 ret = td->io_ops->close_file(td, f);
1228
1229         if (!ret)
1230                 ret = f_ret;
1231
1232         td->nr_open_files--;
1233         fio_file_clear_open(f);
1234         assert(f->fd == -1);
1235         return ret;
1236 }
1237
1238 void lock_file(struct thread_data *td, struct fio_file *f, enum fio_ddir ddir)
1239 {
1240         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1241                 return;
1242
1243         if (td->o.file_lock_mode == FILE_LOCK_READWRITE) {
1244                 if (ddir == DDIR_READ)
1245                         fio_rwlock_read(f->rwlock);
1246                 else
1247                         fio_rwlock_write(f->rwlock);
1248         } else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1249                 fio_mutex_down(f->lock);
1250
1251         td->file_locks[f->fileno] = td->o.file_lock_mode;
1252 }
1253
1254 void unlock_file(struct thread_data *td, struct fio_file *f)
1255 {
1256         if (!f->lock || td->o.file_lock_mode == FILE_LOCK_NONE)
1257                 return;
1258
1259         if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
1260                 fio_rwlock_unlock(f->rwlock);
1261         else if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1262                 fio_mutex_up(f->lock);
1263
1264         td->file_locks[f->fileno] = FILE_LOCK_NONE;
1265 }
1266
1267 void unlock_file_all(struct thread_data *td, struct fio_file *f)
1268 {
1269         if (td->o.file_lock_mode == FILE_LOCK_NONE || !td->file_locks)
1270                 return;
1271         if (td->file_locks[f->fileno] != FILE_LOCK_NONE)
1272                 unlock_file(td, f);
1273 }
1274
1275 static int recurse_dir(struct thread_data *td, const char *dirname)
1276 {
1277         struct dirent *dir;
1278         int ret = 0;
1279         DIR *D;
1280
1281         D = opendir(dirname);
1282         if (!D) {
1283                 char buf[FIO_VERROR_SIZE];
1284
1285                 snprintf(buf, FIO_VERROR_SIZE, "opendir(%s)", dirname);
1286                 td_verror(td, errno, buf);
1287                 return 1;
1288         }
1289
1290         while ((dir = readdir(D)) != NULL) {
1291                 char full_path[PATH_MAX];
1292                 struct stat sb;
1293
1294                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1295                         continue;
1296
1297                 sprintf(full_path, "%s%s%s", dirname, FIO_OS_PATH_SEPARATOR, dir->d_name);
1298
1299                 if (lstat(full_path, &sb) == -1) {
1300                         if (errno != ENOENT) {
1301                                 td_verror(td, errno, "stat");
1302                                 return 1;
1303                         }
1304                 }
1305
1306                 if (S_ISREG(sb.st_mode)) {
1307                         add_file(td, full_path);
1308                         td->o.nr_files++;
1309                         continue;
1310                 }
1311                 if (!S_ISDIR(sb.st_mode))
1312                         continue;
1313
1314                 ret = recurse_dir(td, full_path);
1315                 if (ret)
1316                         break;
1317         }
1318
1319         closedir(D);
1320         return ret;
1321 }
1322
1323 int add_dir_files(struct thread_data *td, const char *path)
1324 {
1325         int ret = recurse_dir(td, path);
1326
1327         if (!ret)
1328                 log_info("fio: opendir added %d files\n", td->o.nr_files);
1329
1330         return ret;
1331 }
1332
1333 void dup_files(struct thread_data *td, struct thread_data *org)
1334 {
1335         struct fio_file *f;
1336         unsigned int i;
1337
1338         dprint(FD_FILE, "dup files: %d\n", org->files_index);
1339
1340         if (!org->files)
1341                 return;
1342
1343         td->files = malloc(org->files_index * sizeof(f));
1344
1345         if (td->o.file_lock_mode != FILE_LOCK_NONE)
1346                 td->file_locks = malloc(org->files_index);
1347
1348         for_each_file(org, f, i) {
1349                 struct fio_file *__f;
1350
1351                 __f = smalloc(sizeof(*__f));
1352                 if (!__f) {
1353                         log_err("fio: smalloc OOM\n");
1354                         assert(0);
1355                 }
1356                 __f->fd = -1;
1357                 fio_file_reset(td, __f);
1358
1359                 if (f->file_name) {
1360                         __f->file_name = smalloc_strdup(f->file_name);
1361                         if (!__f->file_name) {
1362                                 log_err("fio: smalloc OOM\n");
1363                                 assert(0);
1364                         }
1365
1366                         __f->filetype = f->filetype;
1367                 }
1368
1369                 if (td->o.file_lock_mode == FILE_LOCK_EXCLUSIVE)
1370                         __f->lock = f->lock;
1371                 else if (td->o.file_lock_mode == FILE_LOCK_READWRITE)
1372                         __f->rwlock = f->rwlock;
1373
1374                 td->files[i] = __f;
1375         }
1376 }
1377
1378 /*
1379  * Returns the index that matches the filename, or -1 if not there
1380  */
1381 int get_fileno(struct thread_data *td, const char *fname)
1382 {
1383         struct fio_file *f;
1384         unsigned int i;
1385
1386         for_each_file(td, f, i)
1387                 if (!strcmp(f->file_name, fname))
1388                         return i;
1389
1390         return -1;
1391 }
1392
1393 /*
1394  * For log usage, where we add/open/close files automatically
1395  */
1396 void free_release_files(struct thread_data *td)
1397 {
1398         close_files(td);
1399         td->files_index = 0;
1400         td->nr_normal_files = 0;
1401 }
1402
1403 void fio_file_reset(struct thread_data *td, struct fio_file *f)
1404 {
1405         f->last_pos = f->file_offset;
1406         f->last_start = -1ULL;
1407         if (f->io_axmap)
1408                 axmap_reset(f->io_axmap);
1409         if (td->o.random_generator == FIO_RAND_GEN_LFSR)
1410                 lfsr_reset(&f->lfsr, td->rand_seeds[FIO_RAND_BLOCK_OFF]);
1411 }
1412
1413 int fio_files_done(struct thread_data *td)
1414 {
1415         struct fio_file *f;
1416         unsigned int i;
1417
1418         for_each_file(td, f, i)
1419                 if (!fio_file_done(f))
1420                         return 0;
1421
1422         return 1;
1423 }