engines/sg: kill dead function
[fio.git] / engines / sg.c
1 /*
2  * sg engine
3  *
4  * IO engine that uses the Linux SG v3 interface to talk to SCSI devices
5  *
6  * This ioengine can operate in two modes:
7  *      sync    with block devices (/dev/sdX) or
8  *              with character devices (/dev/sgY) with direct=1 or sync=1
9  *      async   with character devices with direct=0 and sync=0
10  *
11  * What value does queue() return for the different cases?
12  *                              queue() return value
13  * In sync mode:
14  *  /dev/sdX            RWT     FIO_Q_COMPLETED
15  *  /dev/sgY            RWT     FIO_Q_COMPLETED
16  *   with direct=1 or sync=1
17  *
18  * In async mode:
19  *  /dev/sgY            RWT     FIO_Q_QUEUED
20  *   direct=0 and sync=0
21  *
22  * Because FIO_SYNCIO is set for this ioengine td_io_queue() will fill in
23  * issue_time *before* each IO is sent to queue()
24  *
25  * Where are the IO counting functions called for the different cases?
26  *
27  * In sync mode:
28  *  /dev/sdX (commit==NULL)
29  *   RWT
30  *    io_u_mark_depth()                 called in td_io_queue()
31  *    io_u_mark_submit/complete()       called in td_io_queue()
32  *    issue_time                        set in td_io_queue()
33  *
34  *  /dev/sgY with direct=1 or sync=1 (commit does nothing)
35  *   RWT
36  *    io_u_mark_depth()                 called in td_io_queue()
37  *    io_u_mark_submit/complete()       called in queue()
38  *    issue_time                        set in td_io_queue()
39  *  
40  * In async mode:
41  *  /dev/sgY with direct=0 and sync=0
42  *   RW: read and write operations are submitted in queue()
43  *    io_u_mark_depth()                 called in td_io_commit()
44  *    io_u_mark_submit()                called in queue()
45  *    issue_time                        set in td_io_queue()
46  *   T: trim operations are queued in queue() and submitted in commit()
47  *    io_u_mark_depth()                 called in td_io_commit()
48  *    io_u_mark_submit()                called in commit()
49  *    issue_time                        set in commit()
50  *
51  */
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <unistd.h>
55 #include <errno.h>
56 #include <poll.h>
57
58 #include "../fio.h"
59 #include "../optgroup.h"
60
61 #ifdef FIO_HAVE_SGIO
62
63 enum {
64         FIO_SG_WRITE            = 1,
65         FIO_SG_WRITE_VERIFY     = 2,
66         FIO_SG_WRITE_SAME       = 3
67 };
68
69 struct sg_options {
70         void *pad;
71         unsigned int readfua;
72         unsigned int writefua;
73         unsigned int write_mode;
74 };
75
76 static struct fio_option options[] = {
77         {
78                 .name   = "readfua",
79                 .lname  = "sg engine read fua flag support",
80                 .type   = FIO_OPT_BOOL,
81                 .off1   = offsetof(struct sg_options, readfua),
82                 .help   = "Set FUA flag (force unit access) for all Read operations",
83                 .def    = "0",
84                 .category = FIO_OPT_C_ENGINE,
85                 .group  = FIO_OPT_G_SG,
86         },
87         {
88                 .name   = "writefua",
89                 .lname  = "sg engine write fua flag support",
90                 .type   = FIO_OPT_BOOL,
91                 .off1   = offsetof(struct sg_options, writefua),
92                 .help   = "Set FUA flag (force unit access) for all Write operations",
93                 .def    = "0",
94                 .category = FIO_OPT_C_ENGINE,
95                 .group  = FIO_OPT_G_SG,
96         },
97         {
98                 .name   = "sg_write_mode",
99                 .lname  = "specify sg write mode",
100                 .type   = FIO_OPT_STR,
101                 .off1   = offsetof(struct sg_options, write_mode),
102                 .help   = "Specify SCSI WRITE mode",
103                 .def    = "write",
104                 .posval = {
105                           { .ival = "write",
106                             .oval = FIO_SG_WRITE,
107                             .help = "Issue standard SCSI WRITE commands",
108                           },
109                           { .ival = "verify",
110                             .oval = FIO_SG_WRITE_VERIFY,
111                             .help = "Issue SCSI WRITE AND VERIFY commands",
112                           },
113                           { .ival = "same",
114                             .oval = FIO_SG_WRITE_SAME,
115                             .help = "Issue SCSI WRITE SAME commands",
116                           },
117                 },
118                 .category = FIO_OPT_C_ENGINE,
119                 .group  = FIO_OPT_G_SG,
120         },
121         {
122                 .name   = NULL,
123         },
124 };
125
126 #define MAX_10B_LBA  0xFFFFFFFFULL
127 #define SCSI_TIMEOUT_MS 30000   // 30 second timeout; currently no method to override
128 #define MAX_SB 64               // sense block maximum return size
129 /*
130 #define FIO_SGIO_DEBUG
131 */
132
133 struct sgio_cmd {
134         unsigned char cdb[16];      // enhanced from 10 to support 16 byte commands
135         unsigned char sb[MAX_SB];   // add sense block to commands
136         int nr;
137 };
138
139 struct sgio_trim {
140         uint8_t *unmap_param;
141         unsigned int unmap_range_count;
142         struct io_u **trim_io_us;
143 };
144
145 struct sgio_data {
146         struct sgio_cmd *cmds;
147         struct io_u **events;
148         struct pollfd *pfds;
149         int *fd_flags;
150         void *sgbuf;
151         unsigned int bs;
152         int type_checked;
153         struct sgio_trim **trim_queues;
154         int current_queue;
155 #ifdef FIO_SGIO_DEBUG
156         unsigned int *trim_queue_map;
157 #endif
158 };
159
160 static inline uint32_t sgio_get_be32(uint8_t *buf)
161 {
162         return be32_to_cpu(*((uint32_t *) buf));
163 }
164
165 static inline uint64_t sgio_get_be64(uint8_t *buf)
166 {
167         return be64_to_cpu(*((uint64_t *) buf));
168 }
169
170 static inline void sgio_set_be16(uint16_t val, uint8_t *buf)
171 {
172         uint16_t t = cpu_to_be16(val);
173
174         memcpy(buf, &t, sizeof(uint16_t));
175 }
176
177 static inline void sgio_set_be32(uint32_t val, uint8_t *buf)
178 {
179         uint32_t t = cpu_to_be32(val);
180
181         memcpy(buf, &t, sizeof(uint32_t));
182 }
183
184 static inline void sgio_set_be64(uint64_t val, uint8_t *buf)
185 {
186         uint64_t t = cpu_to_be64(val);
187
188         memcpy(buf, &t, sizeof(uint64_t));
189 }
190
191 static inline bool sgio_unbuffered(struct thread_data *td)
192 {
193         return (td->o.odirect || td->o.sync_io);
194 }
195
196 static void sgio_hdr_init(struct sgio_data *sd, struct sg_io_hdr *hdr,
197                           struct io_u *io_u, int fs)
198 {
199         struct sgio_cmd *sc = &sd->cmds[io_u->index];
200
201         memset(hdr, 0, sizeof(*hdr));
202         memset(sc->cdb, 0, sizeof(sc->cdb));
203
204         hdr->interface_id = 'S';
205         hdr->cmdp = sc->cdb;
206         hdr->cmd_len = sizeof(sc->cdb);
207         hdr->sbp = sc->sb;
208         hdr->mx_sb_len = sizeof(sc->sb);
209         hdr->pack_id = io_u->index;
210         hdr->usr_ptr = io_u;
211         hdr->timeout = SCSI_TIMEOUT_MS;
212
213         if (fs) {
214                 hdr->dxferp = io_u->xfer_buf;
215                 hdr->dxfer_len = io_u->xfer_buflen;
216         }
217 }
218
219 static int pollin_events(struct pollfd *pfds, int fds)
220 {
221         int i;
222
223         for (i = 0; i < fds; i++)
224                 if (pfds[i].revents & POLLIN)
225                         return 1;
226
227         return 0;
228 }
229
230 static int sg_fd_read(int fd, void *data, size_t size)
231 {
232         int err = 0;
233
234         while (size) {
235                 ssize_t ret;
236
237                 ret = read(fd, data, size);
238                 if (ret < 0) {
239                         if (errno == EAGAIN || errno == EINTR)
240                                 continue;
241                         err = errno;
242                         break;
243                 } else if (!ret)
244                         break;
245                 else {
246                         data += ret;
247                         size -= ret;
248                 }
249         }
250
251         if (err)
252                 return err;
253         if (size)
254                 return EAGAIN;
255
256         return 0;
257 }
258
259 static int fio_sgio_getevents(struct thread_data *td, unsigned int min,
260                               unsigned int max,
261                               const struct timespec fio_unused *t)
262 {
263         struct sgio_data *sd = td->io_ops_data;
264         int left = max, eventNum, ret, r = 0, trims = 0;
265         void *buf = sd->sgbuf;
266         unsigned int i, j, events;
267         struct fio_file *f;
268         struct io_u *io_u;
269
270         /*
271          * Fill in the file descriptors
272          */
273         for_each_file(td, f, i) {
274                 /*
275                  * don't block for min events == 0
276                  */
277                 if (!min)
278                         sd->fd_flags[i] = fio_set_fd_nonblocking(f->fd, "sg");
279                 else
280                         sd->fd_flags[i] = -1;
281
282                 sd->pfds[i].fd = f->fd;
283                 sd->pfds[i].events = POLLIN;
284         }
285
286         /*
287         ** There are two counters here:
288         **  - number of SCSI commands completed
289         **  - number of io_us completed
290         **
291         ** These are the same with reads and writes, but
292         ** could differ with trim/unmap commands because
293         ** a single unmap can include multiple io_us
294         */
295
296         while (left > 0) {
297                 char *p;
298
299                 dprint(FD_IO, "sgio_getevents: sd %p: min=%d, max=%d, left=%d\n", sd, min, max, left);
300
301                 do {
302                         if (!min)
303                                 break;
304
305                         ret = poll(sd->pfds, td->o.nr_files, -1);
306                         if (ret < 0) {
307                                 if (!r)
308                                         r = -errno;
309                                 td_verror(td, errno, "poll");
310                                 break;
311                         } else if (!ret)
312                                 continue;
313
314                         if (pollin_events(sd->pfds, td->o.nr_files))
315                                 break;
316                 } while (1);
317
318                 if (r < 0)
319                         break;
320
321 re_read:
322                 p = buf;
323                 events = 0;
324                 for_each_file(td, f, i) {
325                         for (eventNum = 0; eventNum < left; eventNum++) {
326                                 ret = sg_fd_read(f->fd, p, sizeof(struct sg_io_hdr));
327                                 dprint(FD_IO, "sgio_getevents: sg_fd_read ret: %d\n", ret);
328                                 if (ret) {
329                                         r = -ret;
330                                         td_verror(td, r, "sg_read");
331                                         break;
332                                 }
333                                 io_u = ((struct sg_io_hdr *)p)->usr_ptr;
334                                 if (io_u->ddir == DDIR_TRIM) {
335                                         events += sd->trim_queues[io_u->index]->unmap_range_count;
336                                         eventNum += sd->trim_queues[io_u->index]->unmap_range_count - 1;
337                                 } else
338                                         events++;
339
340                                 p += sizeof(struct sg_io_hdr);
341                                 dprint(FD_IO, "sgio_getevents: events: %d, eventNum: %d, left: %d\n", events, eventNum, left);
342                         }
343                 }
344
345                 if (r < 0 && !events)
346                         break;
347                 if (!events) {
348                         usleep(1000);
349                         goto re_read;
350                 }
351
352                 left -= events;
353                 r += events;
354
355                 for (i = 0; i < events; i++) {
356                         struct sg_io_hdr *hdr = (struct sg_io_hdr *) buf + i;
357                         sd->events[i + trims] = hdr->usr_ptr;
358                         io_u = (struct io_u *)(hdr->usr_ptr);
359
360                         if (hdr->info & SG_INFO_CHECK) {
361                                 /* record if an io error occurred, ignore resid */
362                                 memcpy(&io_u->hdr, hdr, sizeof(struct sg_io_hdr));
363                                 sd->events[i + trims]->error = EIO;
364                         }
365
366                         if (io_u->ddir == DDIR_TRIM) {
367                                 struct sgio_trim *st = sd->trim_queues[io_u->index];
368 #ifdef FIO_SGIO_DEBUG
369                                 assert(st->trim_io_us[0] == io_u);
370                                 assert(sd->trim_queue_map[io_u->index] == io_u->index);
371                                 dprint(FD_IO, "sgio_getevents: reaping %d io_us from trim queue %d\n", st->unmap_range_count, io_u->index);
372                                 dprint(FD_IO, "sgio_getevents: reaped io_u %d and stored in events[%d]\n", io_u->index, i+trims);
373 #endif
374                                 for (j = 1; j < st->unmap_range_count; j++) {
375                                         ++trims;
376                                         sd->events[i + trims] = st->trim_io_us[j];
377 #ifdef FIO_SGIO_DEBUG
378                                         dprint(FD_IO, "sgio_getevents: reaped io_u %d and stored in events[%d]\n", st->trim_io_us[j]->index, i+trims);
379                                         assert(sd->trim_queue_map[st->trim_io_us[j]->index] == io_u->index);
380 #endif
381                                         if (hdr->info & SG_INFO_CHECK) {
382                                                 /* record if an io error occurred, ignore resid */
383                                                 memcpy(&st->trim_io_us[j]->hdr, hdr, sizeof(struct sg_io_hdr));
384                                                 sd->events[i + trims]->error = EIO;
385                                         }
386                                 }
387                                 events -= st->unmap_range_count - 1;
388                                 st->unmap_range_count = 0;
389                         }
390                 }
391         }
392
393         if (!min) {
394                 for_each_file(td, f, i) {
395                         if (sd->fd_flags[i] == -1)
396                                 continue;
397
398                         if (fcntl(f->fd, F_SETFL, sd->fd_flags[i]) < 0)
399                                 log_err("fio: sg failed to restore fcntl flags: %s\n", strerror(errno));
400                 }
401         }
402
403         return r;
404 }
405
406 static enum fio_q_status fio_sgio_ioctl_doio(struct thread_data *td,
407                                              struct fio_file *f,
408                                              struct io_u *io_u)
409 {
410         struct sgio_data *sd = td->io_ops_data;
411         struct sg_io_hdr *hdr = &io_u->hdr;
412         int ret;
413
414         sd->events[0] = io_u;
415
416         ret = ioctl(f->fd, SG_IO, hdr);
417         if (ret < 0)
418                 return ret;
419
420         /* record if an io error occurred */
421         if (hdr->info & SG_INFO_CHECK)
422                 io_u->error = EIO;
423
424         return FIO_Q_COMPLETED;
425 }
426
427 static enum fio_q_status fio_sgio_rw_doio(struct fio_file *f,
428                                           struct io_u *io_u, int do_sync)
429 {
430         struct sg_io_hdr *hdr = &io_u->hdr;
431         int ret;
432
433         ret = write(f->fd, hdr, sizeof(*hdr));
434         if (ret < 0)
435                 return ret;
436
437         if (do_sync) {
438                 ret = read(f->fd, hdr, sizeof(*hdr));
439                 if (ret < 0)
440                         return ret;
441
442                 /* record if an io error occurred */
443                 if (hdr->info & SG_INFO_CHECK)
444                         io_u->error = EIO;
445
446                 return FIO_Q_COMPLETED;
447         }
448
449         return FIO_Q_QUEUED;
450 }
451
452 static enum fio_q_status fio_sgio_doio(struct thread_data *td,
453                                        struct io_u *io_u, int do_sync)
454 {
455         struct fio_file *f = io_u->file;
456         enum fio_q_status ret;
457
458         if (f->filetype == FIO_TYPE_BLOCK) {
459                 ret = fio_sgio_ioctl_doio(td, f, io_u);
460                 td_verror(td, io_u->error, __func__);
461         } else {
462                 ret = fio_sgio_rw_doio(f, io_u, do_sync);
463                 if (do_sync)
464                         td_verror(td, io_u->error, __func__);
465         }
466
467         return ret;
468 }
469
470 static void fio_sgio_rw_lba(struct sg_io_hdr *hdr, unsigned long long lba,
471                             unsigned long long nr_blocks)
472 {
473         if (lba < MAX_10B_LBA) {
474                 sgio_set_be32((uint32_t) lba, &hdr->cmdp[2]);
475                 sgio_set_be16((uint16_t) nr_blocks, &hdr->cmdp[7]);
476         } else {
477                 sgio_set_be64(lba, &hdr->cmdp[2]);
478                 sgio_set_be32((uint32_t) nr_blocks, &hdr->cmdp[10]);
479         }
480
481         return;
482 }
483
484 static int fio_sgio_prep(struct thread_data *td, struct io_u *io_u)
485 {
486         struct sg_io_hdr *hdr = &io_u->hdr;
487         struct sg_options *o = td->eo;
488         struct sgio_data *sd = td->io_ops_data;
489         unsigned long long nr_blocks, lba;
490         int offset;
491
492         if (io_u->xfer_buflen & (sd->bs - 1)) {
493                 log_err("read/write not sector aligned\n");
494                 return EINVAL;
495         }
496
497         nr_blocks = io_u->xfer_buflen / sd->bs;
498         lba = io_u->offset / sd->bs;
499
500         if (io_u->ddir == DDIR_READ) {
501                 sgio_hdr_init(sd, hdr, io_u, 1);
502
503                 hdr->dxfer_direction = SG_DXFER_FROM_DEV;
504                 if (lba < MAX_10B_LBA)
505                         hdr->cmdp[0] = 0x28; // read(10)
506                 else
507                         hdr->cmdp[0] = 0x88; // read(16)
508
509                 if (o->readfua)
510                         hdr->cmdp[1] |= 0x08;
511
512                 fio_sgio_rw_lba(hdr, lba, nr_blocks);
513
514         } else if (io_u->ddir == DDIR_WRITE) {
515                 sgio_hdr_init(sd, hdr, io_u, 1);
516
517                 hdr->dxfer_direction = SG_DXFER_TO_DEV;
518                 switch(o->write_mode) {
519                 case FIO_SG_WRITE:
520                         if (lba < MAX_10B_LBA)
521                                 hdr->cmdp[0] = 0x2a; // write(10)
522                         else
523                                 hdr->cmdp[0] = 0x8a; // write(16)
524                         if (o->writefua)
525                                 hdr->cmdp[1] |= 0x08;
526                         break;
527                 case FIO_SG_WRITE_VERIFY:
528                         if (lba < MAX_10B_LBA)
529                                 hdr->cmdp[0] = 0x2e; // write and verify(10)
530                         else
531                                 hdr->cmdp[0] = 0x8e; // write and verify(16)
532                         break;
533                         // BYTCHK is disabled by virtue of the memset in sgio_hdr_init
534                 case FIO_SG_WRITE_SAME:
535                         hdr->dxfer_len = sd->bs;
536                         if (lba < MAX_10B_LBA)
537                                 hdr->cmdp[0] = 0x41; // write same(10)
538                         else
539                                 hdr->cmdp[0] = 0x93; // write same(16)
540                         break;
541                 };
542
543                 fio_sgio_rw_lba(hdr, lba, nr_blocks);
544
545         } else if (io_u->ddir == DDIR_TRIM) {
546                 struct sgio_trim *st;
547
548                 if (sd->current_queue == -1) {
549                         sgio_hdr_init(sd, hdr, io_u, 0);
550
551                         hdr->cmd_len = 10;
552                         hdr->dxfer_direction = SG_DXFER_TO_DEV;
553                         hdr->cmdp[0] = 0x42; // unmap
554                         sd->current_queue = io_u->index;
555                         st = sd->trim_queues[sd->current_queue];
556                         hdr->dxferp = st->unmap_param;
557 #ifdef FIO_SGIO_DEBUG
558                         assert(sd->trim_queues[io_u->index]->unmap_range_count == 0);
559                         dprint(FD_IO, "sg: creating new queue based on io_u %d\n", io_u->index);
560 #endif
561                 }
562                 else
563                         st = sd->trim_queues[sd->current_queue];
564
565                 dprint(FD_IO, "sg: adding io_u %d to trim queue %d\n", io_u->index, sd->current_queue);
566                 st->trim_io_us[st->unmap_range_count] = io_u;
567 #ifdef FIO_SGIO_DEBUG
568                 sd->trim_queue_map[io_u->index] = sd->current_queue;
569 #endif
570
571                 offset = 8 + 16 * st->unmap_range_count;
572                 sgio_set_be64(lba, &st->unmap_param[offset]);
573                 sgio_set_be32((uint32_t) nr_blocks, &st->unmap_param[offset + 8]);
574
575                 st->unmap_range_count++;
576
577         } else if (ddir_sync(io_u->ddir)) {
578                 sgio_hdr_init(sd, hdr, io_u, 0);
579                 hdr->dxfer_direction = SG_DXFER_NONE;
580                 if (lba < MAX_10B_LBA)
581                         hdr->cmdp[0] = 0x35; // synccache(10)
582                 else
583                         hdr->cmdp[0] = 0x91; // synccache(16)
584         } else
585                 assert(0);
586
587         return 0;
588 }
589
590 static void fio_sgio_unmap_setup(struct sg_io_hdr *hdr, struct sgio_trim *st)
591 {
592         uint16_t cnt = st->unmap_range_count * 16;
593
594         hdr->dxfer_len = cnt + 8;
595         sgio_set_be16(cnt + 8, &hdr->cmdp[7]);
596         sgio_set_be16(cnt + 6, st->unmap_param);
597         sgio_set_be16(cnt, &st->unmap_param[2]);
598
599         return;
600 }
601
602 static enum fio_q_status fio_sgio_queue(struct thread_data *td,
603                                         struct io_u *io_u)
604 {
605         struct sg_io_hdr *hdr = &io_u->hdr;
606         struct sgio_data *sd = td->io_ops_data;
607         int ret, do_sync = 0;
608
609         fio_ro_check(td, io_u);
610
611         if (sgio_unbuffered(td) || ddir_sync(io_u->ddir))
612                 do_sync = 1;
613
614         if (io_u->ddir == DDIR_TRIM) {
615                 if (do_sync || io_u->file->filetype == FIO_TYPE_BLOCK) {
616                         struct sgio_trim *st = sd->trim_queues[sd->current_queue];
617
618                         /* finish cdb setup for unmap because we are
619                         ** doing unmap commands synchronously */
620 #ifdef FIO_SGIO_DEBUG
621                         assert(st->unmap_range_count == 1);
622                         assert(io_u == st->trim_io_us[0]);
623 #endif
624                         hdr = &io_u->hdr;
625
626                         fio_sgio_unmap_setup(hdr, st);
627
628                         st->unmap_range_count = 0;
629                         sd->current_queue = -1;
630                 } else
631                         /* queue up trim ranges and submit in commit() */
632                         return FIO_Q_QUEUED;
633         }
634
635         ret = fio_sgio_doio(td, io_u, do_sync);
636
637         if (ret < 0)
638                 io_u->error = errno;
639         else if (hdr->status) {
640                 io_u->resid = hdr->resid;
641                 io_u->error = EIO;
642         } else if (td->io_ops->commit != NULL) {
643                 if (do_sync && !ddir_sync(io_u->ddir)) {
644                         io_u_mark_submit(td, 1);
645                         io_u_mark_complete(td, 1);
646                 } else if (io_u->ddir == DDIR_READ || io_u->ddir == DDIR_WRITE) {
647                         io_u_mark_submit(td, 1);
648                         io_u_queued(td, io_u);
649                 }
650         }
651
652         if (io_u->error) {
653                 td_verror(td, io_u->error, "xfer");
654                 return FIO_Q_COMPLETED;
655         }
656
657         return ret;
658 }
659
660 static int fio_sgio_commit(struct thread_data *td)
661 {
662         struct sgio_data *sd = td->io_ops_data;
663         struct sgio_trim *st;
664         struct io_u *io_u;
665         struct sg_io_hdr *hdr;
666         struct timespec now;
667         unsigned int i;
668         int ret;
669
670         if (sd->current_queue == -1)
671                 return 0;
672
673         st = sd->trim_queues[sd->current_queue];
674         io_u = st->trim_io_us[0];
675         hdr = &io_u->hdr;
676
677         fio_sgio_unmap_setup(hdr, st);
678
679         sd->current_queue = -1;
680
681         ret = fio_sgio_rw_doio(io_u->file, io_u, 0);
682
683         if (ret < 0 || hdr->status) {
684                 int error;
685
686                 if (ret < 0)
687                         error = errno;
688                 else {
689                         error = EIO;
690                         ret = -EIO;
691                 }
692
693                 for (i = 0; i < st->unmap_range_count; i++) {
694                         st->trim_io_us[i]->error = error;
695                         clear_io_u(td, st->trim_io_us[i]);
696                         if (hdr->status)
697                                 st->trim_io_us[i]->resid = hdr->resid;
698                 }
699
700                 td_verror(td, error, "xfer");
701                 return ret;
702         }
703
704         if (fio_fill_issue_time(td)) {
705                 fio_gettime(&now, NULL);
706                 for (i = 0; i < st->unmap_range_count; i++) {
707                         memcpy(&st->trim_io_us[i]->issue_time, &now, sizeof(now));
708                         io_u_queued(td, io_u);
709                 }
710         }
711         io_u_mark_submit(td, st->unmap_range_count);
712
713         return 0;
714 }
715
716 static struct io_u *fio_sgio_event(struct thread_data *td, int event)
717 {
718         struct sgio_data *sd = td->io_ops_data;
719
720         return sd->events[event];
721 }
722
723 static int fio_sgio_read_capacity(struct thread_data *td, unsigned int *bs,
724                                   unsigned long long *max_lba)
725 {
726         /*
727          * need to do read capacity operation w/o benefit of sd or
728          * io_u structures, which are not initialized until later.
729          */
730         struct sg_io_hdr hdr;
731         unsigned long long hlba;
732         unsigned int blksz = 0;
733         unsigned char cmd[16];
734         unsigned char sb[64];
735         unsigned char buf[32];  // read capacity return
736         int ret;
737         int fd = -1;
738
739         struct fio_file *f = td->files[0];
740
741         /* open file independent of rest of application */
742         fd = open(f->file_name, O_RDONLY);
743         if (fd < 0)
744                 return -errno;
745
746         memset(&hdr, 0, sizeof(hdr));
747         memset(cmd, 0, sizeof(cmd));
748         memset(sb, 0, sizeof(sb));
749         memset(buf, 0, sizeof(buf));
750
751         /* First let's try a 10 byte read capacity. */
752         hdr.interface_id = 'S';
753         hdr.cmdp = cmd;
754         hdr.cmd_len = 10;
755         hdr.sbp = sb;
756         hdr.mx_sb_len = sizeof(sb);
757         hdr.timeout = SCSI_TIMEOUT_MS;
758         hdr.cmdp[0] = 0x25;  // Read Capacity(10)
759         hdr.dxfer_direction = SG_DXFER_FROM_DEV;
760         hdr.dxferp = buf;
761         hdr.dxfer_len = sizeof(buf);
762
763         ret = ioctl(fd, SG_IO, &hdr);
764         if (ret < 0) {
765                 close(fd);
766                 return ret;
767         }
768
769         if (hdr.info & SG_INFO_CHECK) {
770                 /* RCAP(10) might be unsupported by device. Force RCAP(16) */
771                 hlba = MAX_10B_LBA;
772         } else {
773                 blksz = sgio_get_be32(&buf[4]);
774                 hlba = sgio_get_be32(buf);
775         }
776
777         /*
778          * If max lba masked by MAX_10B_LBA equals MAX_10B_LBA,
779          * then need to retry with 16 byte Read Capacity command.
780          */
781         if (hlba == MAX_10B_LBA) {
782                 hdr.cmd_len = 16;
783                 hdr.cmdp[0] = 0x9e; // service action
784                 hdr.cmdp[1] = 0x10; // Read Capacity(16)
785                 sgio_set_be32(sizeof(buf), &hdr.cmdp[10]);
786
787                 hdr.dxfer_direction = SG_DXFER_FROM_DEV;
788                 hdr.dxferp = buf;
789                 hdr.dxfer_len = sizeof(buf);
790
791                 ret = ioctl(fd, SG_IO, &hdr);
792                 if (ret < 0) {
793                         close(fd);
794                         return ret;
795                 }
796
797                 /* record if an io error occurred */
798                 if (hdr.info & SG_INFO_CHECK)
799                         td_verror(td, EIO, "fio_sgio_read_capacity");
800
801                 blksz = sgio_get_be32(&buf[8]);
802                 hlba = sgio_get_be64(buf);
803         }
804
805         if (blksz) {
806                 *bs = blksz;
807                 *max_lba = hlba;
808                 ret = 0;
809         } else {
810                 ret = EIO;
811         }
812
813         close(fd);
814         return ret;
815 }
816
817 static void fio_sgio_cleanup(struct thread_data *td)
818 {
819         struct sgio_data *sd = td->io_ops_data;
820         int i;
821
822         if (sd) {
823                 free(sd->events);
824                 free(sd->cmds);
825                 free(sd->fd_flags);
826                 free(sd->pfds);
827                 free(sd->sgbuf);
828 #ifdef FIO_SGIO_DEBUG
829                 free(sd->trim_queue_map);
830 #endif
831
832                 for (i = 0; i < td->o.iodepth; i++) {
833                         free(sd->trim_queues[i]->unmap_param);
834                         free(sd->trim_queues[i]->trim_io_us);
835                         free(sd->trim_queues[i]);
836                 }
837
838                 free(sd->trim_queues);
839                 free(sd);
840         }
841 }
842
843 static int fio_sgio_init(struct thread_data *td)
844 {
845         struct sgio_data *sd;
846         struct sgio_trim *st;
847         int i;
848
849         sd = calloc(1, sizeof(*sd));
850         sd->cmds = calloc(td->o.iodepth, sizeof(struct sgio_cmd));
851         sd->sgbuf = calloc(td->o.iodepth, sizeof(struct sg_io_hdr));
852         sd->events = calloc(td->o.iodepth, sizeof(struct io_u *));
853         sd->pfds = calloc(td->o.nr_files, sizeof(struct pollfd));
854         sd->fd_flags = calloc(td->o.nr_files, sizeof(int));
855         sd->type_checked = 0;
856
857         sd->trim_queues = calloc(td->o.iodepth, sizeof(struct sgio_trim *));
858         sd->current_queue = -1;
859 #ifdef FIO_SGIO_DEBUG
860         sd->trim_queue_map = calloc(td->o.iodepth, sizeof(int));
861 #endif
862         for (i = 0; i < td->o.iodepth; i++) {
863                 sd->trim_queues[i] = calloc(1, sizeof(struct sgio_trim));
864                 st = sd->trim_queues[i];
865                 st->unmap_param = calloc(td->o.iodepth + 1, sizeof(char[16]));
866                 st->unmap_range_count = 0;
867                 st->trim_io_us = calloc(td->o.iodepth, sizeof(struct io_u *));
868         }
869
870         td->io_ops_data = sd;
871
872         /*
873          * we want to do it, regardless of whether odirect is set or not
874          */
875         td->o.override_sync = 1;
876         return 0;
877 }
878
879 static int fio_sgio_type_check(struct thread_data *td, struct fio_file *f)
880 {
881         struct sgio_data *sd = td->io_ops_data;
882         unsigned int bs = 0;
883         unsigned long long max_lba = 0;
884
885         if (f->filetype == FIO_TYPE_BLOCK) {
886                 if (ioctl(f->fd, BLKSSZGET, &bs) < 0) {
887                         td_verror(td, errno, "ioctl");
888                         return 1;
889                 }
890         } else if (f->filetype == FIO_TYPE_CHAR) {
891                 int version, ret;
892
893                 if (ioctl(f->fd, SG_GET_VERSION_NUM, &version) < 0) {
894                         td_verror(td, errno, "ioctl");
895                         return 1;
896                 }
897
898                 ret = fio_sgio_read_capacity(td, &bs, &max_lba);
899                 if (ret) {
900                         td_verror(td, td->error, "fio_sgio_read_capacity");
901                         log_err("ioengine sg unable to read capacity successfully\n");
902                         return 1;
903                 }
904         } else {
905                 td_verror(td, EINVAL, "wrong file type");
906                 log_err("ioengine sg only works on block or character devices\n");
907                 return 1;
908         }
909
910         sd->bs = bs;
911         // Determine size of commands needed based on max_lba
912         if (max_lba >= MAX_10B_LBA) {
913                 dprint(FD_IO, "sgio_type_check: using 16 byte read/write "
914                         "commands for lba above 0x%016llx/0x%016llx\n",
915                         MAX_10B_LBA, max_lba);
916         }
917
918         if (f->filetype == FIO_TYPE_BLOCK) {
919                 td->io_ops->getevents = NULL;
920                 td->io_ops->event = NULL;
921                 td->io_ops->commit = NULL;
922                 /*
923                 ** Setting these functions to null may cause problems
924                 ** with filename=/dev/sda:/dev/sg0 since we are only
925                 ** considering a single file
926                 */
927         }
928         sd->type_checked = 1;
929
930         return 0;
931 }
932
933 static int fio_sgio_open(struct thread_data *td, struct fio_file *f)
934 {
935         struct sgio_data *sd = td->io_ops_data;
936         int ret;
937
938         ret = generic_open_file(td, f);
939         if (ret)
940                 return ret;
941
942         if (sd && !sd->type_checked && fio_sgio_type_check(td, f)) {
943                 ret = generic_close_file(td, f);
944                 return 1;
945         }
946
947         return 0;
948 }
949
950 /*
951  * Build an error string with details about the driver, host or scsi
952  * error contained in the sg header Caller will use as necessary.
953  */
954 static char *fio_sgio_errdetails(struct io_u *io_u)
955 {
956         struct sg_io_hdr *hdr = &io_u->hdr;
957 #define MAXERRDETAIL 1024
958 #define MAXMSGCHUNK  128
959         char *msg, msgchunk[MAXMSGCHUNK];
960         int i;
961
962         msg = calloc(1, MAXERRDETAIL);
963         strcpy(msg, "");
964
965         /*
966          * can't seem to find sg_err.h, so I'll just echo the define values
967          * so others can search on internet to find clearer clues of meaning.
968          */
969         if (hdr->info & SG_INFO_CHECK) {
970                 if (hdr->host_status) {
971                         snprintf(msgchunk, MAXMSGCHUNK, "SG Host Status: 0x%02x; ", hdr->host_status);
972                         strlcat(msg, msgchunk, MAXERRDETAIL);
973                         switch (hdr->host_status) {
974                         case 0x01:
975                                 strlcat(msg, "SG_ERR_DID_NO_CONNECT", MAXERRDETAIL);
976                                 break;
977                         case 0x02:
978                                 strlcat(msg, "SG_ERR_DID_BUS_BUSY", MAXERRDETAIL);
979                                 break;
980                         case 0x03:
981                                 strlcat(msg, "SG_ERR_DID_TIME_OUT", MAXERRDETAIL);
982                                 break;
983                         case 0x04:
984                                 strlcat(msg, "SG_ERR_DID_BAD_TARGET", MAXERRDETAIL);
985                                 break;
986                         case 0x05:
987                                 strlcat(msg, "SG_ERR_DID_ABORT", MAXERRDETAIL);
988                                 break;
989                         case 0x06:
990                                 strlcat(msg, "SG_ERR_DID_PARITY", MAXERRDETAIL);
991                                 break;
992                         case 0x07:
993                                 strlcat(msg, "SG_ERR_DID_ERROR (internal error)", MAXERRDETAIL);
994                                 break;
995                         case 0x08:
996                                 strlcat(msg, "SG_ERR_DID_RESET", MAXERRDETAIL);
997                                 break;
998                         case 0x09:
999                                 strlcat(msg, "SG_ERR_DID_BAD_INTR (unexpected)", MAXERRDETAIL);
1000                                 break;
1001                         case 0x0a:
1002                                 strlcat(msg, "SG_ERR_DID_PASSTHROUGH", MAXERRDETAIL);
1003                                 break;
1004                         case 0x0b:
1005                                 strlcat(msg, "SG_ERR_DID_SOFT_ERROR (driver retry?)", MAXERRDETAIL);
1006                                 break;
1007                         case 0x0c:
1008                                 strlcat(msg, "SG_ERR_DID_IMM_RETRY", MAXERRDETAIL);
1009                                 break;
1010                         case 0x0d:
1011                                 strlcat(msg, "SG_ERR_DID_REQUEUE", MAXERRDETAIL);
1012                                 break;
1013                         case 0x0e:
1014                                 strlcat(msg, "SG_ERR_DID_TRANSPORT_DISRUPTED", MAXERRDETAIL);
1015                                 break;
1016                         case 0x0f:
1017                                 strlcat(msg, "SG_ERR_DID_TRANSPORT_FAILFAST", MAXERRDETAIL);
1018                                 break;
1019                         case 0x10:
1020                                 strlcat(msg, "SG_ERR_DID_TARGET_FAILURE", MAXERRDETAIL);
1021                                 break;
1022                         case 0x11:
1023                                 strlcat(msg, "SG_ERR_DID_NEXUS_FAILURE", MAXERRDETAIL);
1024                                 break;
1025                         case 0x12:
1026                                 strlcat(msg, "SG_ERR_DID_ALLOC_FAILURE", MAXERRDETAIL);
1027                                 break;
1028                         case 0x13:
1029                                 strlcat(msg, "SG_ERR_DID_MEDIUM_ERROR", MAXERRDETAIL);
1030                                 break;
1031                         default:
1032                                 strlcat(msg, "Unknown", MAXERRDETAIL);
1033                                 break;
1034                         }
1035                         strlcat(msg, ". ", MAXERRDETAIL);
1036                 }
1037                 if (hdr->driver_status) {
1038                         snprintf(msgchunk, MAXMSGCHUNK, "SG Driver Status: 0x%02x; ", hdr->driver_status);
1039                         strlcat(msg, msgchunk, MAXERRDETAIL);
1040                         switch (hdr->driver_status & 0x0F) {
1041                         case 0x01:
1042                                 strlcat(msg, "SG_ERR_DRIVER_BUSY", MAXERRDETAIL);
1043                                 break;
1044                         case 0x02:
1045                                 strlcat(msg, "SG_ERR_DRIVER_SOFT", MAXERRDETAIL);
1046                                 break;
1047                         case 0x03:
1048                                 strlcat(msg, "SG_ERR_DRIVER_MEDIA", MAXERRDETAIL);
1049                                 break;
1050                         case 0x04:
1051                                 strlcat(msg, "SG_ERR_DRIVER_ERROR", MAXERRDETAIL);
1052                                 break;
1053                         case 0x05:
1054                                 strlcat(msg, "SG_ERR_DRIVER_INVALID", MAXERRDETAIL);
1055                                 break;
1056                         case 0x06:
1057                                 strlcat(msg, "SG_ERR_DRIVER_TIMEOUT", MAXERRDETAIL);
1058                                 break;
1059                         case 0x07:
1060                                 strlcat(msg, "SG_ERR_DRIVER_HARD", MAXERRDETAIL);
1061                                 break;
1062                         case 0x08:
1063                                 strlcat(msg, "SG_ERR_DRIVER_SENSE", MAXERRDETAIL);
1064                                 break;
1065                         default:
1066                                 strlcat(msg, "Unknown", MAXERRDETAIL);
1067                                 break;
1068                         }
1069                         strlcat(msg, "; ", MAXERRDETAIL);
1070                         switch (hdr->driver_status & 0xF0) {
1071                         case 0x10:
1072                                 strlcat(msg, "SG_ERR_SUGGEST_RETRY", MAXERRDETAIL);
1073                                 break;
1074                         case 0x20:
1075                                 strlcat(msg, "SG_ERR_SUGGEST_ABORT", MAXERRDETAIL);
1076                                 break;
1077                         case 0x30:
1078                                 strlcat(msg, "SG_ERR_SUGGEST_REMAP", MAXERRDETAIL);
1079                                 break;
1080                         case 0x40:
1081                                 strlcat(msg, "SG_ERR_SUGGEST_DIE", MAXERRDETAIL);
1082                                 break;
1083                         case 0x80:
1084                                 strlcat(msg, "SG_ERR_SUGGEST_SENSE", MAXERRDETAIL);
1085                                 break;
1086                         }
1087                         strlcat(msg, ". ", MAXERRDETAIL);
1088                 }
1089                 if (hdr->status) {
1090                         snprintf(msgchunk, MAXMSGCHUNK, "SG SCSI Status: 0x%02x; ", hdr->status);
1091                         strlcat(msg, msgchunk, MAXERRDETAIL);
1092                         // SCSI 3 status codes
1093                         switch (hdr->status) {
1094                         case 0x02:
1095                                 strlcat(msg, "CHECK_CONDITION", MAXERRDETAIL);
1096                                 break;
1097                         case 0x04:
1098                                 strlcat(msg, "CONDITION_MET", MAXERRDETAIL);
1099                                 break;
1100                         case 0x08:
1101                                 strlcat(msg, "BUSY", MAXERRDETAIL);
1102                                 break;
1103                         case 0x10:
1104                                 strlcat(msg, "INTERMEDIATE", MAXERRDETAIL);
1105                                 break;
1106                         case 0x14:
1107                                 strlcat(msg, "INTERMEDIATE_CONDITION_MET", MAXERRDETAIL);
1108                                 break;
1109                         case 0x18:
1110                                 strlcat(msg, "RESERVATION_CONFLICT", MAXERRDETAIL);
1111                                 break;
1112                         case 0x22:
1113                                 strlcat(msg, "COMMAND_TERMINATED", MAXERRDETAIL);
1114                                 break;
1115                         case 0x28:
1116                                 strlcat(msg, "TASK_SET_FULL", MAXERRDETAIL);
1117                                 break;
1118                         case 0x30:
1119                                 strlcat(msg, "ACA_ACTIVE", MAXERRDETAIL);
1120                                 break;
1121                         case 0x40:
1122                                 strlcat(msg, "TASK_ABORTED", MAXERRDETAIL);
1123                                 break;
1124                         default:
1125                                 strlcat(msg, "Unknown", MAXERRDETAIL);
1126                                 break;
1127                         }
1128                         strlcat(msg, ". ", MAXERRDETAIL);
1129                 }
1130                 if (hdr->sb_len_wr) {
1131                         snprintf(msgchunk, MAXMSGCHUNK, "Sense Data (%d bytes):", hdr->sb_len_wr);
1132                         strlcat(msg, msgchunk, MAXERRDETAIL);
1133                         for (i = 0; i < hdr->sb_len_wr; i++) {
1134                                 snprintf(msgchunk, MAXMSGCHUNK, " %02x", hdr->sbp[i]);
1135                                 strlcat(msg, msgchunk, MAXERRDETAIL);
1136                         }
1137                         strlcat(msg, ". ", MAXERRDETAIL);
1138                 }
1139                 if (hdr->resid != 0) {
1140                         snprintf(msgchunk, MAXMSGCHUNK, "SG Driver: %d bytes out of %d not transferred. ", hdr->resid, hdr->dxfer_len);
1141                         strlcat(msg, msgchunk, MAXERRDETAIL);
1142                 }
1143                 if (hdr->cmdp) {
1144                         strlcat(msg, "cdb:", MAXERRDETAIL);
1145                         for (i = 0; i < hdr->cmd_len; i++) {
1146                                 snprintf(msgchunk, MAXMSGCHUNK, " %02x", hdr->cmdp[i]);
1147                                 strlcat(msg, msgchunk, MAXERRDETAIL);
1148                         }
1149                         strlcat(msg, ". ", MAXERRDETAIL);
1150                         if (io_u->ddir == DDIR_TRIM) {
1151                                 unsigned char *param_list = hdr->dxferp;
1152                                 strlcat(msg, "dxferp:", MAXERRDETAIL);
1153                                 for (i = 0; i < hdr->dxfer_len; i++) {
1154                                         snprintf(msgchunk, MAXMSGCHUNK, " %02x", param_list[i]);
1155                                         strlcat(msg, msgchunk, MAXERRDETAIL);
1156                                 }
1157                                 strlcat(msg, ". ", MAXERRDETAIL);
1158                         }
1159                 }
1160         }
1161
1162         if (!(hdr->info & SG_INFO_CHECK) && !strlen(msg))
1163                 strncpy(msg, "SG Driver did not report a Host, Driver or Device check",
1164                         MAXERRDETAIL - 1);
1165
1166         return msg;
1167 }
1168
1169 /*
1170  * get max file size from read capacity.
1171  */
1172 static int fio_sgio_get_file_size(struct thread_data *td, struct fio_file *f)
1173 {
1174         /*
1175          * get_file_size is being called even before sgio_init is
1176          * called, so none of the sg_io structures are
1177          * initialized in the thread_data yet.  So we need to do the
1178          * ReadCapacity without any of those helpers.  One of the effects
1179          * is that ReadCapacity may get called 4 times on each open:
1180          * readcap(10) followed by readcap(16) if needed - just to get
1181          * the file size after the init occurs - it will be called
1182          * again when "type_check" is called during structure
1183          * initialization I'm not sure how to prevent this little
1184          * inefficiency.
1185          */
1186         unsigned int bs = 0;
1187         unsigned long long max_lba = 0;
1188         int ret;
1189
1190         if (fio_file_size_known(f))
1191                 return 0;
1192
1193         if (f->filetype != FIO_TYPE_BLOCK && f->filetype != FIO_TYPE_CHAR) {
1194                 td_verror(td, EINVAL, "wrong file type");
1195                 log_err("ioengine sg only works on block or character devices\n");
1196                 return 1;
1197         }
1198
1199         ret = fio_sgio_read_capacity(td, &bs, &max_lba);
1200         if (ret ) {
1201                 td_verror(td, td->error, "fio_sgio_read_capacity");
1202                 log_err("ioengine sg unable to successfully execute read capacity to get block size and maximum lba\n");
1203                 return 1;
1204         }
1205
1206         f->real_file_size = (max_lba + 1) * bs;
1207         fio_file_set_size_known(f);
1208         return 0;
1209 }
1210
1211
1212 static struct ioengine_ops ioengine = {
1213         .name           = "sg",
1214         .version        = FIO_IOOPS_VERSION,
1215         .init           = fio_sgio_init,
1216         .prep           = fio_sgio_prep,
1217         .queue          = fio_sgio_queue,
1218         .commit         = fio_sgio_commit,
1219         .getevents      = fio_sgio_getevents,
1220         .errdetails     = fio_sgio_errdetails,
1221         .event          = fio_sgio_event,
1222         .cleanup        = fio_sgio_cleanup,
1223         .open_file      = fio_sgio_open,
1224         .close_file     = generic_close_file,
1225         .get_file_size  = fio_sgio_get_file_size,
1226         .flags          = FIO_SYNCIO | FIO_RAWIO,
1227         .options        = options,
1228         .option_struct_size     = sizeof(struct sg_options)
1229 };
1230
1231 #else /* FIO_HAVE_SGIO */
1232
1233 /*
1234  * When we have a proper configure system in place, we simply wont build
1235  * and install this io engine. For now install a crippled version that
1236  * just complains and fails to load.
1237  */
1238 static int fio_sgio_init(struct thread_data fio_unused *td)
1239 {
1240         log_err("fio: ioengine sg not available\n");
1241         return 1;
1242 }
1243
1244 static struct ioengine_ops ioengine = {
1245         .name           = "sg",
1246         .version        = FIO_IOOPS_VERSION,
1247         .init           = fio_sgio_init,
1248 };
1249
1250 #endif
1251
1252 static void fio_init fio_sgio_register(void)
1253 {
1254         register_ioengine(&ioengine);
1255 }
1256
1257 static void fio_exit fio_sgio_unregister(void)
1258 {
1259         unregister_ioengine(&ioengine);
1260 }