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