windowsaio: fix file header format and improve error reporting.
[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 #include <windows.h>
13
14 #include "../fio.h"
15
16 typedef BOOL (WINAPI *CANCELIOEX)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
17
18 int geterrno_from_win_error (DWORD code, int deferrno);
19
20 struct fio_overlapped {
21         OVERLAPPED o;
22         struct io_u *io_u;
23         BOOL io_complete;
24 };
25
26 struct windowsaio_data {
27         struct io_u **aio_events;
28         HANDLE iocp;
29         HANDLE iothread;
30         HANDLE iocomplete_event;
31         CANCELIOEX pCancelIoEx;
32         BOOL iothread_running;
33 };
34
35 struct thread_ctx {
36         HANDLE iocp;
37         struct windowsaio_data *wd;
38 };
39
40 static int fio_windowsaio_cancel(struct thread_data *td,
41                                    struct io_u *io_u);
42 static BOOL timeout_expired(DWORD start_count, DWORD end_count);
43 static int fio_windowsaio_getevents(struct thread_data *td, unsigned int min,
44                                         unsigned int max, struct timespec *t);
45 static struct io_u *fio_windowsaio_event(struct thread_data *td, int event);
46 static int fio_windowsaio_queue(struct thread_data *td,
47                                   struct io_u *io_u);
48 static void fio_windowsaio_cleanup(struct thread_data *td);
49 static DWORD WINAPI IoCompletionRoutine(LPVOID lpParameter);
50 static int fio_windowsaio_init(struct thread_data *td);
51 static int fio_windowsaio_open_file(struct thread_data *td, struct fio_file *f);
52 static int fio_windowsaio_close_file(struct thread_data fio_unused *td, struct fio_file *f);
53 static int win_to_posix_error(DWORD winerr);
54
55 static int win_to_posix_error(DWORD winerr)
56 {
57         switch (winerr)
58         {
59         case ERROR_FILE_NOT_FOUND:              return ENOENT;
60         case ERROR_PATH_NOT_FOUND:              return ENOENT;
61         case ERROR_ACCESS_DENIED:               return EACCES;
62         case ERROR_INVALID_HANDLE:              return EBADF;
63         case ERROR_NOT_ENOUGH_MEMORY:   return ENOMEM;
64         case ERROR_INVALID_DATA:                return EINVAL;
65         case ERROR_OUTOFMEMORY:                 return ENOMEM;
66         case ERROR_INVALID_DRIVE:               return ENODEV;
67         case ERROR_NOT_SAME_DEVICE:             return EXDEV;
68         case ERROR_WRITE_PROTECT:               return EROFS;
69         case ERROR_BAD_UNIT:                    return ENODEV;
70         case ERROR_SHARING_VIOLATION:   return EACCES;
71         case ERROR_LOCK_VIOLATION:              return EACCES;
72         case ERROR_SHARING_BUFFER_EXCEEDED:     return ENOLCK;
73         case ERROR_HANDLE_DISK_FULL:    return ENOSPC;
74         case ERROR_NOT_SUPPORTED:               return ENOSYS;
75         case ERROR_FILE_EXISTS:                 return EEXIST;
76         case ERROR_CANNOT_MAKE:                 return EPERM;
77         case ERROR_INVALID_PARAMETER:   return EINVAL;
78         case ERROR_NO_PROC_SLOTS:               return EAGAIN;
79         case ERROR_BROKEN_PIPE:                 return EPIPE;
80         case ERROR_OPEN_FAILED:                 return EIO;
81         case ERROR_NO_MORE_SEARCH_HANDLES:      return ENFILE;
82         case ERROR_CALL_NOT_IMPLEMENTED:        return ENOSYS;
83         case ERROR_INVALID_NAME:                return ENOENT;
84         case ERROR_WAIT_NO_CHILDREN:    return ECHILD;
85         case ERROR_CHILD_NOT_COMPLETE:  return EBUSY;
86         case ERROR_DIR_NOT_EMPTY:               return ENOTEMPTY;
87         case ERROR_SIGNAL_REFUSED:              return EIO;
88         case ERROR_BAD_PATHNAME:                return ENOENT;
89         case ERROR_SIGNAL_PENDING:              return EBUSY;
90         case ERROR_MAX_THRDS_REACHED:   return EAGAIN;
91         case ERROR_BUSY:                                return EBUSY;
92         case ERROR_ALREADY_EXISTS:              return EEXIST;
93         case ERROR_NO_SIGNAL_SENT:              return EIO;
94         case ERROR_FILENAME_EXCED_RANGE:        return EINVAL;
95         case ERROR_META_EXPANSION_TOO_LONG:     return EINVAL;
96         case ERROR_INVALID_SIGNAL_NUMBER:       return EINVAL;
97         case ERROR_THREAD_1_INACTIVE:   return EINVAL;
98         case ERROR_BAD_PIPE:                    return EINVAL;
99         case ERROR_PIPE_BUSY:                   return EBUSY;
100         case ERROR_NO_DATA:                             return EPIPE;
101         case ERROR_MORE_DATA:                   return EAGAIN;
102         case ERROR_DIRECTORY:                   return ENOTDIR;
103         case ERROR_PIPE_CONNECTED:              return EBUSY;
104         case ERROR_NO_TOKEN:                    return EINVAL;
105         case ERROR_PROCESS_ABORTED:             return EFAULT;
106         case ERROR_BAD_DEVICE:                  return ENODEV;
107         case ERROR_BAD_USERNAME:                return EINVAL;
108         case ERROR_OPEN_FILES:                  return EAGAIN;
109         case ERROR_ACTIVE_CONNECTIONS:  return EAGAIN;
110         case ERROR_DEVICE_IN_USE:               return EAGAIN;
111         case ERROR_INVALID_AT_INTERRUPT_TIME:   return EINTR;
112         case ERROR_IO_DEVICE:                   return EIO;
113         case ERROR_NOT_OWNER:                   return EPERM;
114         case ERROR_END_OF_MEDIA:                return ENOSPC;
115         case ERROR_EOM_OVERFLOW:                return ENOSPC;
116         case ERROR_BEGINNING_OF_MEDIA:  return ESPIPE;
117         case ERROR_SETMARK_DETECTED:    return ESPIPE;
118         case ERROR_NO_DATA_DETECTED:    return ENOSPC;
119         case ERROR_POSSIBLE_DEADLOCK:   return EDEADLOCK;
120         case ERROR_CRC:                                 return EIO;
121         case ERROR_NEGATIVE_SEEK:               return EINVAL;
122         case ERROR_DISK_FULL:                   return ENOSPC;
123         case ERROR_NOACCESS:                    return EFAULT;
124         case ERROR_FILE_INVALID:                return ENXIO;
125         }
126
127         return winerr;
128 }
129
130 static int fio_windowsaio_init(struct thread_data *td)
131 {
132         struct windowsaio_data *wd;
133         HANDLE hKernel32Dll;
134         int rc = 0;
135
136         wd = calloc(1, sizeof(struct windowsaio_data));
137         if (wd == NULL) {
138                  log_err("windowsaio: failed to allocate memory for engine data\n");
139                 rc = 1;
140         }
141
142         if (!rc) {
143                 wd->aio_events = malloc(td->o.iodepth * sizeof(struct io_u*));
144                 if (wd->aio_events == NULL) {
145                         log_err("windowsaio: failed to allocate memory for aio events list\n");
146                         rc = 1;
147                 }
148         }
149
150         if (!rc) {
151                 /* Create an auto-reset event */
152                 wd->iocomplete_event = CreateEvent(NULL, FALSE, FALSE, NULL);
153                 if (wd->iocomplete_event == NULL) {
154                         log_err("windowsaio: failed to create io complete event handle\n");
155                         rc = 1;
156                 }
157         }
158
159         if (rc) {
160                 if (wd != NULL) {
161                         if (wd->aio_events != NULL)
162                                 free(wd->aio_events);
163
164                         free(wd);
165                 }
166         }
167
168         hKernel32Dll = GetModuleHandle("kernel32.dll");
169         wd->pCancelIoEx = (CANCELIOEX)GetProcAddress(hKernel32Dll, "CancelIoEx");
170         td->io_ops->data = wd;
171
172         if (!rc) {
173                 struct thread_ctx *ctx;
174                 struct windowsaio_data *wd;
175                 HANDLE hFile;
176
177                 hFile = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
178                 if (hFile == INVALID_HANDLE_VALUE) {
179                         log_err("windowsaio: failed to create io completion port\n");
180                         rc = 1;
181                 }
182
183                 wd = td->io_ops->data;
184                 wd->iothread_running = TRUE;
185                 wd->iocp = hFile;
186
187                 if (!rc)
188                         ctx = malloc(sizeof(struct thread_ctx));
189
190                 if (!rc && ctx == NULL)
191                 {
192                         log_err("windowsaio: failed to allocate memory for thread context structure\n");
193                         CloseHandle(hFile);
194                         rc = 1;
195                 }
196
197                 if (!rc)
198                 {
199                         ctx->iocp = hFile;
200                         ctx->wd = wd;
201                         wd->iothread = CreateThread(NULL, 0, IoCompletionRoutine, ctx, 0, NULL);
202                         if (wd->iothread == NULL)
203                                 log_err("windowsaio: failed to create io completion thread\n");
204                 }
205
206                 if (rc || wd->iothread == NULL)
207                         rc = 1;
208         }
209
210         return rc;
211 }
212
213 static void fio_windowsaio_cleanup(struct thread_data *td)
214 {
215         struct windowsaio_data *wd;
216
217         wd = td->io_ops->data;
218
219         if (wd != NULL) {
220                 wd->iothread_running = FALSE;
221                 WaitForSingleObject(wd->iothread, INFINITE);
222
223                 CloseHandle(wd->iothread);
224                 CloseHandle(wd->iocomplete_event);
225
226                 free(wd->aio_events);
227                 free(wd);
228
229                 td->io_ops->data = NULL;
230         }
231 }
232
233
234 static int fio_windowsaio_open_file(struct thread_data *td, struct fio_file *f)
235 {
236         int rc = 0;
237         DWORD flags = FILE_FLAG_POSIX_SEMANTICS | FILE_FLAG_OVERLAPPED;
238         DWORD sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE;
239         DWORD openmode = OPEN_ALWAYS;
240         DWORD access;
241
242         dprint(FD_FILE, "fd open %s\n", f->file_name);
243
244         if (f->filetype == FIO_TYPE_PIPE) {
245                 log_err("windowsaio: pipes are not supported\n");
246                 return 1;
247         }
248
249         if (!strcmp(f->file_name, "-")) {
250                 log_err("windowsaio: can't read/write to stdin/out\n");
251                 return 1;
252         }
253
254         if (td->o.odirect)
255                 flags |= FILE_FLAG_NO_BUFFERING;
256         if (td->o.sync_io)
257                 flags |= FILE_FLAG_WRITE_THROUGH;
258
259         /*
260          * Inform Windows whether we're going to be doing sequential or
261          * random io so it can tune the Cache Manager
262          */
263         if (td->o.td_ddir == TD_DDIR_READ  ||
264                 td->o.td_ddir == TD_DDIR_WRITE)
265                 flags |= FILE_FLAG_SEQUENTIAL_SCAN;
266         else
267                 flags |= FILE_FLAG_RANDOM_ACCESS;
268
269         if (!td_write(td) || read_only)
270                 access = GENERIC_READ;
271         else
272                 access = (GENERIC_READ | GENERIC_WRITE);
273
274         if (td->o.create_on_open)
275                 openmode = OPEN_ALWAYS;
276         else
277                 openmode = OPEN_EXISTING;
278
279         f->hFile = CreateFile(f->file_name, access, sharemode,
280                 NULL, openmode, flags, NULL);
281
282         if (f->hFile == INVALID_HANDLE_VALUE) {
283                 log_err("windowsaio: failed to open file \"%s\"\n", f->file_name);
284                 rc = 1;
285         }
286
287         /* Only set up the completion port and thread if we're not just
288          * querying the device size */
289         if (!rc && td->io_ops->data != NULL) {
290                 struct windowsaio_data *wd;
291
292                 wd = td->io_ops->data;
293
294                 if (CreateIoCompletionPort(f->hFile, wd->iocp, 0, 0) == NULL) {
295                         log_err("windowsaio: failed to create io completion port\n");
296                         rc = 1;
297                 }
298         }
299
300         return rc;
301 }
302
303 static int fio_windowsaio_close_file(struct thread_data fio_unused *td, struct fio_file *f)
304 {
305         int rc = 0;
306
307         dprint(FD_FILE, "fd close %s\n", f->file_name);
308
309         if (f->hFile != INVALID_HANDLE_VALUE) {
310                 if (!CloseHandle(f->hFile)) {
311                         log_info("windowsaio: failed to close file handle for \"%s\"\n", f->file_name);
312                         rc = 1;
313                 }
314         }
315
316         f->hFile = INVALID_HANDLE_VALUE;
317         return rc;
318 }
319
320 static BOOL timeout_expired(DWORD start_count, DWORD end_count)
321 {
322         BOOL expired = FALSE;
323         DWORD current_time;
324
325         current_time = GetTickCount();
326
327         if ((end_count > start_count) && current_time >= end_count)
328                 expired = TRUE;
329         else if (current_time < start_count && current_time > end_count)
330                 expired = TRUE;
331
332         return expired;
333 }
334
335 static struct io_u* fio_windowsaio_event(struct thread_data *td, int event)
336 {
337         struct windowsaio_data *wd = td->io_ops->data;
338         return wd->aio_events[event];
339 }
340
341 static int fio_windowsaio_getevents(struct thread_data *td, unsigned int min,
342                                         unsigned int max, struct timespec *t)
343 {
344         struct windowsaio_data *wd = td->io_ops->data;
345         struct flist_head *entry;
346         unsigned int dequeued = 0;
347         struct io_u *io_u;
348         struct fio_overlapped *fov;
349         DWORD start_count = 0;
350         DWORD end_count = 0;
351         DWORD status;
352         DWORD mswait = 250;
353
354         if (t != NULL) {
355                 mswait = (t->tv_sec * 1000) + (t->tv_nsec / 1000000);
356                 start_count = GetTickCount();
357                 end_count = start_count + (t->tv_sec * 1000) + (t->tv_nsec / 1000000);
358         }
359
360         do {
361                 flist_for_each(entry, &td->io_u_busylist) {
362                         io_u = flist_entry(entry, struct io_u, list);
363                         fov = (struct fio_overlapped*)io_u->engine_data;
364
365                         if (fov->io_complete) {
366                                 fov->io_complete = FALSE;
367                                 ResetEvent(fov->o.hEvent);
368                                 wd->aio_events[dequeued] = io_u;
369                                 dequeued++;
370                         }
371
372                         if (dequeued >= min)
373                                 break;
374                 }
375
376                 if (dequeued < min) {
377                         status = WaitForSingleObject(wd->iocomplete_event, mswait);
378                         if (status != WAIT_OBJECT_0 && dequeued >= min)
379                                 break;
380                 }
381
382                 if (dequeued >= min || (t != NULL && timeout_expired(start_count, end_count)))
383                         break;
384         } while (1);
385
386         return dequeued;
387 }
388
389 static int fio_windowsaio_queue(struct thread_data *td, struct io_u *io_u)
390 {
391         struct fio_overlapped *o = io_u->engine_data;
392         LPOVERLAPPED lpOvl = &o->o;
393         DWORD iobytes;
394         BOOL success = FALSE;
395         int rc = FIO_Q_COMPLETED;
396
397         fio_ro_check(td, io_u);
398
399         lpOvl->Internal = STATUS_PENDING;
400         lpOvl->InternalHigh = 0;
401         lpOvl->Offset = io_u->offset & 0xFFFFFFFF;
402         lpOvl->OffsetHigh = io_u->offset >> 32;
403
404         switch (io_u->ddir) {
405         case DDIR_WRITE:
406                 success = WriteFile(io_u->file->hFile, io_u->xfer_buf, io_u->xfer_buflen, &iobytes, lpOvl);
407                 break;
408         case DDIR_READ:
409                 success = ReadFile(io_u->file->hFile, io_u->xfer_buf, io_u->xfer_buflen, &iobytes, lpOvl);
410                 break;
411         case DDIR_SYNC:
412         case DDIR_DATASYNC:
413         case DDIR_SYNC_FILE_RANGE:
414                 success = FlushFileBuffers(io_u->file->hFile);
415                 if (!success) {
416                         log_err("windowsaio: failed to flush file buffers\n");
417                         io_u->error = win_to_posix_error(GetLastError());
418                 }
419
420                 return FIO_Q_COMPLETED;
421                 break;
422         case DDIR_TRIM:
423                 log_err("windowsaio: manual TRIM isn't supported on Windows\n");
424                 io_u->error = 1;
425                 io_u->resid = io_u->xfer_buflen;
426                 return FIO_Q_COMPLETED;
427                 break;
428         default:
429                 assert(0);
430                 break;
431         }
432
433         if (success || GetLastError() == ERROR_IO_PENDING)
434                 rc = FIO_Q_QUEUED;
435         else {
436                 io_u->error = win_to_posix_error(GetLastError());
437                 io_u->resid = io_u->xfer_buflen;
438         }
439
440         return rc;
441 }
442
443 /* Runs as a thread and waits for queued IO to complete */
444 static DWORD WINAPI IoCompletionRoutine(LPVOID lpParameter)
445 {
446         OVERLAPPED *ovl;
447         struct fio_overlapped *fov;
448         struct io_u *io_u;
449         struct windowsaio_data *wd;
450         struct thread_ctx *ctx;
451         ULONG_PTR ulKey = 0;
452         DWORD bytes;
453
454         ctx = (struct thread_ctx*)lpParameter;
455         wd = ctx->wd;
456
457         do {
458                 if (!GetQueuedCompletionStatus(ctx->iocp, &bytes, &ulKey, &ovl, 250) && ovl == NULL)
459                         continue;
460
461                 fov = CONTAINING_RECORD(ovl, struct fio_overlapped, o);
462                 io_u = fov->io_u;
463
464                 if (ovl->Internal == ERROR_SUCCESS) {
465                         io_u->resid = io_u->xfer_buflen - ovl->InternalHigh;
466                         io_u->error = 0;
467                 } else {
468                         io_u->resid = io_u->xfer_buflen;
469                         io_u->error = win_to_posix_error(GetLastError());
470                 }
471
472                 fov->io_complete = TRUE;
473                 SetEvent(wd->iocomplete_event);
474         } while (ctx->wd->iothread_running);
475
476         CloseHandle(ctx->iocp);
477         free(ctx);
478         return 0;
479 }
480
481 static int fio_windowsaio_cancel(struct thread_data *td,
482                                    struct io_u *io_u)
483 {
484         int rc = 0;
485
486         struct windowsaio_data *wd = td->io_ops->data;
487
488         /* If we're running on Vista or newer, we can cancel individual IO requests */
489         if (wd->pCancelIoEx != NULL) {
490                 struct fio_overlapped *ovl = io_u->engine_data;
491
492                 if (!wd->pCancelIoEx(io_u->file->hFile, &ovl->o)) {
493                         log_err("windowsaio: failed to cancel io\n");
494                         rc = 1;
495                 }
496         } else
497                 rc = 1;
498
499         return rc;
500 }
501
502 static void fio_windowsaio_io_u_free(struct thread_data *td, struct io_u *io_u)
503 {
504         struct fio_overlapped *o = io_u->engine_data;
505
506         if (o) {
507                 CloseHandle(o->o.hEvent);
508                 io_u->engine_data = NULL;
509                 free(o);
510         }
511 }
512
513 static int fio_windowsaio_io_u_init(struct thread_data *td, struct io_u *io_u)
514 {
515         struct fio_overlapped *o;
516
517         o = malloc(sizeof(*o));
518         o->io_complete = FALSE;
519         o->io_u = io_u;
520         o->o.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
521         if (o->o.hEvent == NULL) {
522                 log_err("windowsaio: failed to create event handle\n");
523                 free(o);
524                 return 1;
525         }
526
527         io_u->engine_data = o;
528         return 0;
529 }
530
531 static struct ioengine_ops ioengine = {
532         .name           = "windowsaio",
533         .version        = FIO_IOOPS_VERSION,
534         .init           = fio_windowsaio_init,
535         .queue          = fio_windowsaio_queue,
536         .cancel         = fio_windowsaio_cancel,
537         .getevents      = fio_windowsaio_getevents,
538         .event          = fio_windowsaio_event,
539         .cleanup        = fio_windowsaio_cleanup,
540         .open_file      = fio_windowsaio_open_file,
541         .close_file     = fio_windowsaio_close_file,
542         .get_file_size  = generic_get_file_size,
543         .io_u_init      = fio_windowsaio_io_u_init,
544         .io_u_free      = fio_windowsaio_io_u_free,
545 };
546
547 static void fio_init fio_windowsaio_register(void)
548 {
549         register_ioengine(&ioengine);
550 }
551
552 static void fio_exit fio_windowsaio_unregister(void)
553 {
554         unregister_ioengine(&ioengine);
555 }