4 * IO engine that reads/writes from files by doing memcpy to/from
5 * a memory mapped region of the file.
15 #include "../verify.h"
18 * Limits us to 1GB of mapped files in total
20 #define MMAP_TOTAL_SZ (1 * 1024 * 1024 * 1024UL)
22 static unsigned long mmap_map_size;
23 static unsigned long mmap_map_mask;
25 static int fio_mmap_file(struct thread_data *td, struct fio_file *f,
26 size_t length, off_t off)
32 flags = PROT_READ | PROT_WRITE;
33 else if (td_write(td)) {
36 if (td->o.verify != VERIFY_NONE)
41 f->mmap_ptr = mmap(NULL, length, flags, MAP_SHARED, f->fd, off);
42 if (f->mmap_ptr == MAP_FAILED) {
46 td_verror(td, err, "mmap");
51 if (madvise(f->mmap_ptr, length, MADV_SEQUENTIAL) < 0) {
52 td_verror(td, errno, "madvise");
56 if (madvise(f->mmap_ptr, length, MADV_RANDOM) < 0) {
57 td_verror(td, errno, "madvise");
66 static int fio_mmapio_prep(struct thread_data *td, struct io_u *io_u)
68 struct fio_file *f = io_u->file;
71 if (io_u->buflen > mmap_map_size) {
72 log_err("fio: bs too big for mmap engine\n");
77 if (io_u->offset >= f->mmap_off &&
78 io_u->offset + io_u->buflen < f->mmap_off + f->mmap_sz)
82 if (munmap(f->mmap_ptr, f->mmap_sz) < 0) {
89 f->mmap_sz = mmap_map_size;
90 if (f->mmap_sz > f->io_size)
91 f->mmap_sz = f->io_size;
93 f->mmap_off = io_u->offset;
95 ret = fio_mmap_file(td, f, f->mmap_sz, f->mmap_off);
98 io_u->mmap_data = f->mmap_ptr + io_u->offset - f->mmap_off -
104 static int fio_mmapio_queue(struct thread_data *td, struct io_u *io_u)
106 struct fio_file *f = io_u->file;
108 fio_ro_check(td, io_u);
110 if (io_u->ddir == DDIR_READ)
111 memcpy(io_u->xfer_buf, io_u->mmap_data, io_u->xfer_buflen);
112 else if (io_u->ddir == DDIR_WRITE)
113 memcpy(io_u->mmap_data, io_u->xfer_buf, io_u->xfer_buflen);
114 else if (ddir_sync(io_u->ddir)) {
115 if (msync(f->mmap_ptr, f->mmap_sz, MS_SYNC)) {
117 td_verror(td, io_u->error, "msync");
122 * not really direct, but should drop the pages from the cache
124 if (td->o.odirect && !ddir_sync(io_u->ddir)) {
125 if (msync(io_u->mmap_data, io_u->xfer_buflen, MS_SYNC) < 0) {
127 td_verror(td, io_u->error, "msync");
129 if (madvise(io_u->mmap_data, io_u->xfer_buflen, MADV_DONTNEED) < 0) {
131 td_verror(td, io_u->error, "madvise");
135 return FIO_Q_COMPLETED;
138 static int fio_mmapio_init(struct thread_data *td)
140 unsigned long shift, mask;
142 mmap_map_size = MMAP_TOTAL_SZ / td->o.nr_files;
143 mask = mmap_map_size;
152 mmap_map_mask = 1UL << shift;
156 static struct ioengine_ops ioengine = {
158 .version = FIO_IOOPS_VERSION,
159 .init = fio_mmapio_init,
160 .prep = fio_mmapio_prep,
161 .queue = fio_mmapio_queue,
162 .open_file = generic_open_file,
163 .close_file = generic_close_file,
164 .get_file_size = generic_get_file_size,
165 .flags = FIO_SYNCIO | FIO_NOEXTEND,
168 static void fio_init fio_mmapio_register(void)
170 register_ioengine(&ioengine);
173 static void fio_exit fio_mmapio_unregister(void)
175 unregister_ioengine(&ioengine);