Merge branch 'filelock_assert_fix' of https://github.com/bardavid/fio into master
[fio.git] / engines / windowsaio.c
1 /*
2  * windowsaio engine
3  *
4  * IO engine using Windows IO Completion Ports.
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <signal.h>
11 #include <errno.h>
12
13 #include "../fio.h"
14
15 typedef BOOL (WINAPI *CANCELIOEX)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
16
17 int geterrno_from_win_error (DWORD code, int deferrno);
18
19 struct fio_overlapped {
20         OVERLAPPED o;
21         struct io_u *io_u;
22         BOOL io_complete;
23 };
24
25 struct windowsaio_data {
26         struct io_u **aio_events;
27         HANDLE iocp;
28         HANDLE iothread;
29         HANDLE iocomplete_event;
30         BOOL iothread_running;
31 };
32
33 struct thread_ctx {
34         HANDLE iocp;
35         struct windowsaio_data *wd;
36 };
37
38 static DWORD WINAPI IoCompletionRoutine(LPVOID lpParameter);
39
40 static int fio_windowsaio_init(struct thread_data *td)
41 {
42         struct windowsaio_data *wd;
43         int rc = 0;
44
45         wd = calloc(1, sizeof(struct windowsaio_data));
46         if (wd == NULL) {
47                  log_err("windowsaio: failed to allocate memory for engine data\n");
48                 rc = 1;
49         }
50
51         if (!rc) {
52                 wd->aio_events = malloc(td->o.iodepth * sizeof(struct io_u*));
53                 if (wd->aio_events == NULL) {
54                         log_err("windowsaio: failed to allocate memory for aio events list\n");
55                         rc = 1;
56                 }
57         }
58
59         if (!rc) {
60                 /* Create an auto-reset event */
61                 wd->iocomplete_event = CreateEvent(NULL, FALSE, FALSE, NULL);
62                 if (wd->iocomplete_event == NULL) {
63                         log_err("windowsaio: failed to create io complete event handle\n");
64                         rc = 1;
65                 }
66         }
67
68         if (rc) {
69                 if (wd != NULL) {
70                         if (wd->aio_events != NULL)
71                                 free(wd->aio_events);
72
73                         free(wd);
74                 }
75         }
76
77         td->io_ops_data = wd;
78
79         if (!rc) {
80                 struct thread_ctx *ctx;
81                 struct windowsaio_data *wd;
82                 HANDLE hFile;
83
84                 hFile = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
85                 if (hFile == INVALID_HANDLE_VALUE) {
86                         log_err("windowsaio: failed to create io completion port\n");
87                         rc = 1;
88                 }
89
90                 wd = td->io_ops_data;
91                 wd->iothread_running = TRUE;
92                 wd->iocp = hFile;
93
94                 if (!rc)
95                         ctx = malloc(sizeof(struct thread_ctx));
96
97                 if (!rc && ctx == NULL) {
98                         log_err("windowsaio: failed to allocate memory for thread context structure\n");
99                         CloseHandle(hFile);
100                         rc = 1;
101                 }
102
103                 if (!rc) {
104                         DWORD threadid;
105
106                         ctx->iocp = hFile;
107                         ctx->wd = wd;
108                         wd->iothread = CreateThread(NULL, 0, IoCompletionRoutine, ctx, 0, &threadid);
109
110                         if (wd->iothread != NULL &&
111                             fio_option_is_set(&td->o, cpumask))
112                                 fio_setaffinity(threadid, td->o.cpumask);
113                         else
114                                 log_err("windowsaio: failed to create io completion thread\n");
115                 }
116
117                 if (rc || wd->iothread == NULL)
118                         rc = 1;
119         }
120
121         return rc;
122 }
123
124 static void fio_windowsaio_cleanup(struct thread_data *td)
125 {
126         struct windowsaio_data *wd;
127
128         wd = td->io_ops_data;
129
130         if (wd != NULL) {
131                 wd->iothread_running = FALSE;
132                 WaitForSingleObject(wd->iothread, INFINITE);
133
134                 CloseHandle(wd->iothread);
135                 CloseHandle(wd->iocomplete_event);
136
137                 free(wd->aio_events);
138                 free(wd);
139
140                 td->io_ops_data = NULL;
141         }
142 }
143
144 static int windowsaio_invalidate_cache(struct fio_file *f)
145 {
146         DWORD error;
147         DWORD isharemode = (FILE_SHARE_DELETE | FILE_SHARE_READ |
148                                 FILE_SHARE_WRITE);
149         HANDLE ihFile;
150         int rc = 0;
151
152         /*
153          * Encourage Windows to drop cached parts of a file by temporarily
154          * opening it for non-buffered access. Note: this will only work when
155          * the following is the only thing with the file open on the whole
156          * system.
157          */
158         dprint(FD_IO, "windowaio: attempt invalidate cache for %s\n",
159                         f->file_name);
160         ihFile = CreateFile(f->file_name, 0, isharemode, NULL, OPEN_EXISTING,
161                         FILE_FLAG_NO_BUFFERING, NULL);
162
163         if (ihFile != INVALID_HANDLE_VALUE) {
164                 if (!CloseHandle(ihFile)) {
165                         error = GetLastError();
166                         log_info("windowsaio: invalidation fd close %s "
167                                  "failed: error %d\n", f->file_name, error);
168                         rc = 1;
169                 }
170         } else {
171                 error = GetLastError();
172                 if (error != ERROR_FILE_NOT_FOUND) {
173                         log_info("windowsaio: cache invalidation of %s failed: "
174                                         "error %d\n", f->file_name, error);
175                         rc = 1;
176                 }
177         }
178
179         return rc;
180 }
181
182 static int fio_windowsaio_open_file(struct thread_data *td, struct fio_file *f)
183 {
184         int rc = 0;
185         DWORD flags = FILE_FLAG_POSIX_SEMANTICS | FILE_FLAG_OVERLAPPED;
186         DWORD sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE;
187         DWORD openmode = OPEN_ALWAYS;
188         DWORD access;
189
190         dprint(FD_FILE, "fd open %s\n", f->file_name);
191
192         if (f->filetype == FIO_TYPE_PIPE) {
193                 log_err("windowsaio: pipes are not supported\n");
194                 return 1;
195         }
196
197         if (!strcmp(f->file_name, "-")) {
198                 log_err("windowsaio: can't read/write to stdin/out\n");
199                 return 1;
200         }
201
202         if (td->o.odirect)
203                 flags |= FILE_FLAG_NO_BUFFERING;
204         if (td->o.sync_io)
205                 flags |= FILE_FLAG_WRITE_THROUGH;
206
207         /*
208          * Inform Windows whether we're going to be doing sequential or
209          * random IO so it can tune the Cache Manager
210          */
211         switch (td->o.fadvise_hint) {
212         case F_ADV_TYPE:
213                 if (td_random(td))
214                         flags |= FILE_FLAG_RANDOM_ACCESS;
215                 else
216                         flags |= FILE_FLAG_SEQUENTIAL_SCAN;
217                 break;
218         case F_ADV_RANDOM:
219                 flags |= FILE_FLAG_RANDOM_ACCESS;
220                 break;
221         case F_ADV_SEQUENTIAL:
222                 flags |= FILE_FLAG_SEQUENTIAL_SCAN;
223                 break;
224         case F_ADV_NONE:
225                 break;
226         default:
227                 log_err("fio: unknown fadvise type %d\n", td->o.fadvise_hint);
228         }
229
230         if (!td_write(td) || read_only)
231                 access = GENERIC_READ;
232         else
233                 access = (GENERIC_READ | GENERIC_WRITE);
234
235         if (td->o.create_on_open)
236                 openmode = OPEN_ALWAYS;
237         else
238                 openmode = OPEN_EXISTING;
239
240         /* If we're going to use direct I/O, Windows will try and invalidate
241          * its cache at that point so there's no need to do it here */
242         if (td->o.invalidate_cache && !td->o.odirect)
243                 windowsaio_invalidate_cache(f);
244
245         f->hFile = CreateFile(f->file_name, access, sharemode,
246                 NULL, openmode, flags, NULL);
247
248         if (f->hFile == INVALID_HANDLE_VALUE) {
249                 log_err("windowsaio: failed to open file \"%s\"\n", f->file_name);
250                 rc = 1;
251         }
252
253         /* Only set up the completion port and thread if we're not just
254          * querying the device size */
255         if (!rc && td->io_ops_data != NULL) {
256                 struct windowsaio_data *wd;
257
258                 wd = td->io_ops_data;
259
260                 if (CreateIoCompletionPort(f->hFile, wd->iocp, 0, 0) == NULL) {
261                         log_err("windowsaio: failed to create io completion port\n");
262                         rc = 1;
263                 }
264         }
265
266         return rc;
267 }
268
269 static int fio_windowsaio_close_file(struct thread_data fio_unused *td, struct fio_file *f)
270 {
271         int rc = 0;
272
273         dprint(FD_FILE, "fd close %s\n", f->file_name);
274
275         if (f->hFile != INVALID_HANDLE_VALUE) {
276                 if (!CloseHandle(f->hFile)) {
277                         log_info("windowsaio: failed to close file handle for \"%s\"\n", f->file_name);
278                         rc = 1;
279                 }
280         }
281
282         f->hFile = INVALID_HANDLE_VALUE;
283         return rc;
284 }
285
286 static BOOL timeout_expired(DWORD start_count, DWORD end_count)
287 {
288         BOOL expired = FALSE;
289         DWORD current_time;
290
291         current_time = GetTickCount();
292
293         if ((end_count > start_count) && current_time >= end_count)
294                 expired = TRUE;
295         else if (current_time < start_count && current_time > end_count)
296                 expired = TRUE;
297
298         return expired;
299 }
300
301 static struct io_u* fio_windowsaio_event(struct thread_data *td, int event)
302 {
303         struct windowsaio_data *wd = td->io_ops_data;
304         return wd->aio_events[event];
305 }
306
307 static int fio_windowsaio_getevents(struct thread_data *td, unsigned int min,
308                                     unsigned int max,
309                                     const struct timespec *t)
310 {
311         struct windowsaio_data *wd = td->io_ops_data;
312         unsigned int dequeued = 0;
313         struct io_u *io_u;
314         int i;
315         struct fio_overlapped *fov;
316         DWORD start_count = 0;
317         DWORD end_count = 0;
318         DWORD status;
319         DWORD mswait = 250;
320
321         if (t != NULL) {
322                 mswait = (t->tv_sec * 1000) + (t->tv_nsec / 1000000);
323                 start_count = GetTickCount();
324                 end_count = start_count + (t->tv_sec * 1000) + (t->tv_nsec / 1000000);
325         }
326
327         do {
328                 io_u_qiter(&td->io_u_all, io_u, i) {
329                         if (!(io_u->flags & IO_U_F_FLIGHT))
330                                 continue;
331
332                         fov = (struct fio_overlapped*)io_u->engine_data;
333
334                         if (fov->io_complete) {
335                                 fov->io_complete = FALSE;
336                                 wd->aio_events[dequeued] = io_u;
337                                 dequeued++;
338                         }
339
340                 }
341                 if (dequeued >= min)
342                         break;
343
344                 if (dequeued < min) {
345                         status = WaitForSingleObject(wd->iocomplete_event, mswait);
346                         if (status != WAIT_OBJECT_0 && dequeued >= min)
347                                 break;
348                 }
349
350                 if (dequeued >= min ||
351                     (t != NULL && timeout_expired(start_count, end_count)))
352                         break;
353         } while (1);
354
355         return dequeued;
356 }
357
358 static enum fio_q_status fio_windowsaio_queue(struct thread_data *td,
359                                               struct io_u *io_u)
360 {
361         struct fio_overlapped *o = io_u->engine_data;
362         LPOVERLAPPED lpOvl = &o->o;
363         BOOL success = FALSE;
364         int rc = FIO_Q_COMPLETED;
365
366         fio_ro_check(td, io_u);
367
368         lpOvl->Internal = 0;
369         lpOvl->InternalHigh = 0;
370         lpOvl->Offset = io_u->offset & 0xFFFFFFFF;
371         lpOvl->OffsetHigh = io_u->offset >> 32;
372
373         switch (io_u->ddir) {
374         case DDIR_WRITE:
375                 success = WriteFile(io_u->file->hFile, io_u->xfer_buf,
376                                         io_u->xfer_buflen, NULL, lpOvl);
377                 break;
378         case DDIR_READ:
379                 success = ReadFile(io_u->file->hFile, io_u->xfer_buf,
380                                         io_u->xfer_buflen, NULL, lpOvl);
381                 break;
382         case DDIR_SYNC:
383         case DDIR_DATASYNC:
384         case DDIR_SYNC_FILE_RANGE:
385                 success = FlushFileBuffers(io_u->file->hFile);
386                 if (!success) {
387                         log_err("windowsaio: failed to flush file buffers\n");
388                         io_u->error = win_to_posix_error(GetLastError());
389                 }
390
391                 return FIO_Q_COMPLETED;
392         case DDIR_TRIM:
393                 log_err("windowsaio: manual TRIM isn't supported on Windows\n");
394                 io_u->error = 1;
395                 io_u->resid = io_u->xfer_buflen;
396                 return FIO_Q_COMPLETED;
397         default:
398                 assert(0);
399                 break;
400         }
401
402         if (success || GetLastError() == ERROR_IO_PENDING)
403                 rc = FIO_Q_QUEUED;
404         else {
405                 io_u->error = win_to_posix_error(GetLastError());
406                 io_u->resid = io_u->xfer_buflen;
407         }
408
409         return rc;
410 }
411
412 /* Runs as a thread and waits for queued IO to complete */
413 static DWORD WINAPI IoCompletionRoutine(LPVOID lpParameter)
414 {
415         OVERLAPPED *ovl;
416         struct fio_overlapped *fov;
417         struct io_u *io_u;
418         struct windowsaio_data *wd;
419         struct thread_ctx *ctx;
420         ULONG_PTR ulKey = 0;
421         DWORD bytes;
422
423         ctx = (struct thread_ctx*)lpParameter;
424         wd = ctx->wd;
425
426         do {
427                 BOOL ret;
428
429                 ret = GetQueuedCompletionStatus(ctx->iocp, &bytes, &ulKey,
430                                                 &ovl, 250);
431                 if (!ret && ovl == NULL)
432                         continue;
433
434                 fov = CONTAINING_RECORD(ovl, struct fio_overlapped, o);
435                 io_u = fov->io_u;
436
437                 if (ovl->Internal == ERROR_SUCCESS) {
438                         io_u->resid = io_u->xfer_buflen - ovl->InternalHigh;
439                         io_u->error = 0;
440                 } else {
441                         io_u->resid = io_u->xfer_buflen;
442                         io_u->error = win_to_posix_error(GetLastError());
443                 }
444
445                 fov->io_complete = TRUE;
446                 SetEvent(wd->iocomplete_event);
447         } while (ctx->wd->iothread_running);
448
449         CloseHandle(ctx->iocp);
450         free(ctx);
451         return 0;
452 }
453
454 static void fio_windowsaio_io_u_free(struct thread_data *td, struct io_u *io_u)
455 {
456         struct fio_overlapped *o = io_u->engine_data;
457
458         if (o) {
459                 io_u->engine_data = NULL;
460                 free(o);
461         }
462 }
463
464 static int fio_windowsaio_io_u_init(struct thread_data *td, struct io_u *io_u)
465 {
466         struct fio_overlapped *o;
467
468         o = malloc(sizeof(*o));
469         o->io_complete = FALSE;
470         o->io_u = io_u;
471         o->o.hEvent = NULL;
472         io_u->engine_data = o;
473         return 0;
474 }
475
476 static struct ioengine_ops ioengine = {
477         .name           = "windowsaio",
478         .version        = FIO_IOOPS_VERSION,
479         .init           = fio_windowsaio_init,
480         .queue          = fio_windowsaio_queue,
481         .getevents      = fio_windowsaio_getevents,
482         .event          = fio_windowsaio_event,
483         .cleanup        = fio_windowsaio_cleanup,
484         .open_file      = fio_windowsaio_open_file,
485         .close_file     = fio_windowsaio_close_file,
486         .get_file_size  = generic_get_file_size,
487         .io_u_init      = fio_windowsaio_io_u_init,
488         .io_u_free      = fio_windowsaio_io_u_free,
489 };
490
491 static void fio_init fio_windowsaio_register(void)
492 {
493         register_ioengine(&ioengine);
494 }
495
496 static void fio_exit fio_windowsaio_unregister(void)
497 {
498         unregister_ioengine(&ioengine);
499 }