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