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