]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - block/iscsi.c
block/iscsi: use a bh to schedule co reentrance
[lisovros/qemu_apohw.git] / block / iscsi.c
1 /*
2  * QEMU Block driver for iSCSI images
3  *
4  * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 #include "config-host.h"
26
27 #include <poll.h>
28 #include <arpa/inet.h>
29 #include "qemu-common.h"
30 #include "qemu/config-file.h"
31 #include "qemu/error-report.h"
32 #include "block/block_int.h"
33 #include "trace.h"
34 #include "block/scsi.h"
35 #include "qemu/iov.h"
36 #include "sysemu/sysemu.h"
37 #include "qmp-commands.h"
38
39 #include <iscsi/iscsi.h>
40 #include <iscsi/scsi-lowlevel.h>
41
42 #ifdef __linux__
43 #include <scsi/sg.h>
44 #include <block/scsi.h>
45 #endif
46
47 typedef struct IscsiLun {
48     struct iscsi_context *iscsi;
49     int lun;
50     enum scsi_inquiry_peripheral_device_type type;
51     int block_size;
52     uint64_t num_blocks;
53     int events;
54     QEMUTimer *nop_timer;
55     uint8_t lbpme;
56     uint8_t lbprz;
57     struct scsi_inquiry_logical_block_provisioning lbp;
58     struct scsi_inquiry_block_limits bl;
59 } IscsiLun;
60
61 typedef struct IscsiTask {
62     int status;
63     int complete;
64     int retries;
65     int do_retry;
66     struct scsi_task *task;
67     Coroutine *co;
68     QEMUBH *bh;
69 } IscsiTask;
70
71 typedef struct IscsiAIOCB {
72     BlockDriverAIOCB common;
73     QEMUIOVector *qiov;
74     QEMUBH *bh;
75     IscsiLun *iscsilun;
76     struct scsi_task *task;
77     uint8_t *buf;
78     int status;
79     int canceled;
80     int retries;
81     int64_t sector_num;
82     int nb_sectors;
83 #ifdef __linux__
84     sg_io_hdr_t *ioh;
85 #endif
86 } IscsiAIOCB;
87
88 #define NOP_INTERVAL 5000
89 #define MAX_NOP_FAILURES 3
90 #define ISCSI_CMD_RETRIES 5
91 #define ISCSI_MAX_UNMAP 131072
92
93 static void
94 iscsi_bh_cb(void *p)
95 {
96     IscsiAIOCB *acb = p;
97
98     qemu_bh_delete(acb->bh);
99
100     g_free(acb->buf);
101     acb->buf = NULL;
102
103     if (acb->canceled == 0) {
104         acb->common.cb(acb->common.opaque, acb->status);
105     }
106
107     if (acb->task != NULL) {
108         scsi_free_scsi_task(acb->task);
109         acb->task = NULL;
110     }
111
112     qemu_aio_release(acb);
113 }
114
115 static void
116 iscsi_schedule_bh(IscsiAIOCB *acb)
117 {
118     if (acb->bh) {
119         return;
120     }
121     acb->bh = qemu_bh_new(iscsi_bh_cb, acb);
122     qemu_bh_schedule(acb->bh);
123 }
124
125 static void iscsi_co_generic_bh_cb(void *opaque)
126 {
127     struct IscsiTask *iTask = opaque;
128     qemu_bh_delete(iTask->bh);
129     qemu_coroutine_enter(iTask->co, NULL);
130 }
131
132 static void
133 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
134                         void *command_data, void *opaque)
135 {
136     struct IscsiTask *iTask = opaque;
137     struct scsi_task *task = command_data;
138
139     iTask->complete = 1;
140     iTask->status = status;
141     iTask->do_retry = 0;
142     iTask->task = task;
143
144     if (iTask->retries-- > 0 && status == SCSI_STATUS_CHECK_CONDITION
145         && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
146         iTask->do_retry = 1;
147         goto out;
148     }
149
150     if (status != SCSI_STATUS_GOOD) {
151         error_report("iSCSI: Failure. %s", iscsi_get_error(iscsi));
152     }
153
154 out:
155     if (iTask->co) {
156         iTask->bh = qemu_bh_new(iscsi_co_generic_bh_cb, iTask);
157         qemu_bh_schedule(iTask->bh);
158     }
159 }
160
161 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
162 {
163     *iTask = (struct IscsiTask) {
164         .co         = qemu_coroutine_self(),
165         .retries    = ISCSI_CMD_RETRIES,
166     };
167 }
168
169 static void
170 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
171                     void *private_data)
172 {
173     IscsiAIOCB *acb = private_data;
174
175     acb->status = -ECANCELED;
176     iscsi_schedule_bh(acb);
177 }
178
179 static void
180 iscsi_aio_cancel(BlockDriverAIOCB *blockacb)
181 {
182     IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
183     IscsiLun *iscsilun = acb->iscsilun;
184
185     if (acb->status != -EINPROGRESS) {
186         return;
187     }
188
189     acb->canceled = 1;
190
191     /* send a task mgmt call to the target to cancel the task on the target */
192     iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
193                                      iscsi_abort_task_cb, acb);
194
195     while (acb->status == -EINPROGRESS) {
196         qemu_aio_wait();
197     }
198 }
199
200 static const AIOCBInfo iscsi_aiocb_info = {
201     .aiocb_size         = sizeof(IscsiAIOCB),
202     .cancel             = iscsi_aio_cancel,
203 };
204
205
206 static void iscsi_process_read(void *arg);
207 static void iscsi_process_write(void *arg);
208
209 static void
210 iscsi_set_events(IscsiLun *iscsilun)
211 {
212     struct iscsi_context *iscsi = iscsilun->iscsi;
213     int ev;
214
215     /* We always register a read handler.  */
216     ev = POLLIN;
217     ev |= iscsi_which_events(iscsi);
218     if (ev != iscsilun->events) {
219         qemu_aio_set_fd_handler(iscsi_get_fd(iscsi),
220                       iscsi_process_read,
221                       (ev & POLLOUT) ? iscsi_process_write : NULL,
222                       iscsilun);
223
224     }
225
226     iscsilun->events = ev;
227 }
228
229 static void
230 iscsi_process_read(void *arg)
231 {
232     IscsiLun *iscsilun = arg;
233     struct iscsi_context *iscsi = iscsilun->iscsi;
234
235     iscsi_service(iscsi, POLLIN);
236     iscsi_set_events(iscsilun);
237 }
238
239 static void
240 iscsi_process_write(void *arg)
241 {
242     IscsiLun *iscsilun = arg;
243     struct iscsi_context *iscsi = iscsilun->iscsi;
244
245     iscsi_service(iscsi, POLLOUT);
246     iscsi_set_events(iscsilun);
247 }
248
249 static int
250 iscsi_aio_writev_acb(IscsiAIOCB *acb);
251
252 static void
253 iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
254                      void *command_data, void *opaque)
255 {
256     IscsiAIOCB *acb = opaque;
257
258     trace_iscsi_aio_write16_cb(iscsi, status, acb, acb->canceled);
259
260     g_free(acb->buf);
261     acb->buf = NULL;
262
263     if (acb->canceled != 0) {
264         return;
265     }
266
267     acb->status = 0;
268     if (status != 0) {
269         if (status == SCSI_STATUS_CHECK_CONDITION
270             && acb->task->sense.key == SCSI_SENSE_UNIT_ATTENTION
271             && acb->retries-- > 0) {
272             scsi_free_scsi_task(acb->task);
273             acb->task = NULL;
274             if (iscsi_aio_writev_acb(acb) == 0) {
275                 iscsi_set_events(acb->iscsilun);
276                 return;
277             }
278         }
279         error_report("Failed to write16 data to iSCSI lun. %s",
280                      iscsi_get_error(iscsi));
281         acb->status = -EIO;
282     }
283
284     iscsi_schedule_bh(acb);
285 }
286
287 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
288 {
289     return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
290 }
291
292 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
293 {
294     return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
295 }
296
297 static bool is_request_lun_aligned(int64_t sector_num, int nb_sectors,
298                                       IscsiLun *iscsilun)
299 {
300     if ((sector_num * BDRV_SECTOR_SIZE) % iscsilun->block_size ||
301         (nb_sectors * BDRV_SECTOR_SIZE) % iscsilun->block_size) {
302             error_report("iSCSI misaligned request: "
303                          "iscsilun->block_size %u, sector_num %" PRIi64
304                          ", nb_sectors %d",
305                          iscsilun->block_size, sector_num, nb_sectors);
306             return 0;
307     }
308     return 1;
309 }
310
311 static int
312 iscsi_aio_writev_acb(IscsiAIOCB *acb)
313 {
314     struct iscsi_context *iscsi = acb->iscsilun->iscsi;
315     size_t size;
316     uint32_t num_sectors;
317     uint64_t lba;
318 #if !defined(LIBISCSI_FEATURE_IOVECTOR)
319     struct iscsi_data data;
320 #endif
321     int ret;
322
323     acb->canceled   = 0;
324     acb->bh         = NULL;
325     acb->status     = -EINPROGRESS;
326     acb->buf        = NULL;
327
328     /* this will allow us to get rid of 'buf' completely */
329     size = acb->nb_sectors * BDRV_SECTOR_SIZE;
330
331 #if !defined(LIBISCSI_FEATURE_IOVECTOR)
332     data.size = MIN(size, acb->qiov->size);
333
334     /* if the iovec only contains one buffer we can pass it directly */
335     if (acb->qiov->niov == 1) {
336         data.data = acb->qiov->iov[0].iov_base;
337     } else {
338         acb->buf = g_malloc(data.size);
339         qemu_iovec_to_buf(acb->qiov, 0, acb->buf, data.size);
340         data.data = acb->buf;
341     }
342 #endif
343
344     acb->task = malloc(sizeof(struct scsi_task));
345     if (acb->task == NULL) {
346         error_report("iSCSI: Failed to allocate task for scsi WRITE16 "
347                      "command. %s", iscsi_get_error(iscsi));
348         return -1;
349     }
350     memset(acb->task, 0, sizeof(struct scsi_task));
351
352     acb->task->xfer_dir = SCSI_XFER_WRITE;
353     acb->task->cdb_size = 16;
354     acb->task->cdb[0] = 0x8a;
355     lba = sector_qemu2lun(acb->sector_num, acb->iscsilun);
356     *(uint32_t *)&acb->task->cdb[2]  = htonl(lba >> 32);
357     *(uint32_t *)&acb->task->cdb[6]  = htonl(lba & 0xffffffff);
358     num_sectors = sector_qemu2lun(acb->nb_sectors, acb->iscsilun);
359     *(uint32_t *)&acb->task->cdb[10] = htonl(num_sectors);
360     acb->task->expxferlen = size;
361
362 #if defined(LIBISCSI_FEATURE_IOVECTOR)
363     ret = iscsi_scsi_command_async(iscsi, acb->iscsilun->lun, acb->task,
364                                    iscsi_aio_write16_cb,
365                                    NULL,
366                                    acb);
367 #else
368     ret = iscsi_scsi_command_async(iscsi, acb->iscsilun->lun, acb->task,
369                                    iscsi_aio_write16_cb,
370                                    &data,
371                                    acb);
372 #endif
373     if (ret != 0) {
374         scsi_free_scsi_task(acb->task);
375         g_free(acb->buf);
376         return -1;
377     }
378
379 #if defined(LIBISCSI_FEATURE_IOVECTOR)
380     scsi_task_set_iov_out(acb->task, (struct scsi_iovec*) acb->qiov->iov, acb->qiov->niov);
381 #endif
382
383     return 0;
384 }
385
386 static BlockDriverAIOCB *
387 iscsi_aio_writev(BlockDriverState *bs, int64_t sector_num,
388                  QEMUIOVector *qiov, int nb_sectors,
389                  BlockDriverCompletionFunc *cb,
390                  void *opaque)
391 {
392     IscsiLun *iscsilun = bs->opaque;
393     IscsiAIOCB *acb;
394
395     if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
396         return NULL;
397     }
398
399     acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
400     trace_iscsi_aio_writev(iscsilun->iscsi, sector_num, nb_sectors, opaque, acb);
401
402     acb->iscsilun    = iscsilun;
403     acb->qiov        = qiov;
404     acb->nb_sectors  = nb_sectors;
405     acb->sector_num  = sector_num;
406     acb->retries     = ISCSI_CMD_RETRIES;
407
408     if (iscsi_aio_writev_acb(acb) != 0) {
409         qemu_aio_release(acb);
410         return NULL;
411     }
412
413     iscsi_set_events(iscsilun);
414     return &acb->common;
415 }
416
417 static int
418 iscsi_aio_readv_acb(IscsiAIOCB *acb);
419
420 static void
421 iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
422                     void *command_data, void *opaque)
423 {
424     IscsiAIOCB *acb = opaque;
425
426     trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);
427
428     if (acb->canceled != 0) {
429         return;
430     }
431
432     acb->status = 0;
433     if (status != 0) {
434         if (status == SCSI_STATUS_CHECK_CONDITION
435             && acb->task->sense.key == SCSI_SENSE_UNIT_ATTENTION
436             && acb->retries-- > 0) {
437             scsi_free_scsi_task(acb->task);
438             acb->task = NULL;
439             if (iscsi_aio_readv_acb(acb) == 0) {
440                 iscsi_set_events(acb->iscsilun);
441                 return;
442             }
443         }
444         error_report("Failed to read16 data from iSCSI lun. %s",
445                      iscsi_get_error(iscsi));
446         acb->status = -EIO;
447     }
448
449     iscsi_schedule_bh(acb);
450 }
451
452 static int
453 iscsi_aio_readv_acb(IscsiAIOCB *acb)
454 {
455     struct iscsi_context *iscsi = acb->iscsilun->iscsi;
456     size_t size;
457     uint64_t lba;
458     uint32_t num_sectors;
459     int ret;
460 #if !defined(LIBISCSI_FEATURE_IOVECTOR)
461     int i;
462 #endif
463
464     acb->canceled    = 0;
465     acb->bh          = NULL;
466     acb->status      = -EINPROGRESS;
467     acb->buf         = NULL;
468
469     size = acb->nb_sectors * BDRV_SECTOR_SIZE;
470
471     acb->task = malloc(sizeof(struct scsi_task));
472     if (acb->task == NULL) {
473         error_report("iSCSI: Failed to allocate task for scsi READ16 "
474                      "command. %s", iscsi_get_error(iscsi));
475         return -1;
476     }
477     memset(acb->task, 0, sizeof(struct scsi_task));
478
479     acb->task->xfer_dir = SCSI_XFER_READ;
480     acb->task->expxferlen = size;
481     lba = sector_qemu2lun(acb->sector_num, acb->iscsilun);
482     num_sectors = sector_qemu2lun(acb->nb_sectors, acb->iscsilun);
483
484     switch (acb->iscsilun->type) {
485     case TYPE_DISK:
486         acb->task->cdb_size = 16;
487         acb->task->cdb[0]  = 0x88;
488         *(uint32_t *)&acb->task->cdb[2]  = htonl(lba >> 32);
489         *(uint32_t *)&acb->task->cdb[6]  = htonl(lba & 0xffffffff);
490         *(uint32_t *)&acb->task->cdb[10] = htonl(num_sectors);
491         break;
492     default:
493         acb->task->cdb_size = 10;
494         acb->task->cdb[0]  = 0x28;
495         *(uint32_t *)&acb->task->cdb[2] = htonl(lba);
496         *(uint16_t *)&acb->task->cdb[7] = htons(num_sectors);
497         break;
498     }
499
500     ret = iscsi_scsi_command_async(iscsi, acb->iscsilun->lun, acb->task,
501                                    iscsi_aio_read16_cb,
502                                    NULL,
503                                    acb);
504     if (ret != 0) {
505         scsi_free_scsi_task(acb->task);
506         return -1;
507     }
508
509 #if defined(LIBISCSI_FEATURE_IOVECTOR)
510     scsi_task_set_iov_in(acb->task, (struct scsi_iovec*) acb->qiov->iov, acb->qiov->niov);
511 #else
512     for (i = 0; i < acb->qiov->niov; i++) {
513         scsi_task_add_data_in_buffer(acb->task,
514                 acb->qiov->iov[i].iov_len,
515                 acb->qiov->iov[i].iov_base);
516     }
517 #endif
518     return 0;
519 }
520
521 static BlockDriverAIOCB *
522 iscsi_aio_readv(BlockDriverState *bs, int64_t sector_num,
523                 QEMUIOVector *qiov, int nb_sectors,
524                 BlockDriverCompletionFunc *cb,
525                 void *opaque)
526 {
527     IscsiLun *iscsilun = bs->opaque;
528     IscsiAIOCB *acb;
529
530     if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
531         return NULL;
532     }
533
534     acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
535     trace_iscsi_aio_readv(iscsilun->iscsi, sector_num, nb_sectors, opaque, acb);
536
537     acb->nb_sectors  = nb_sectors;
538     acb->sector_num  = sector_num;
539     acb->iscsilun    = iscsilun;
540     acb->qiov        = qiov;
541     acb->retries     = ISCSI_CMD_RETRIES;
542
543     if (iscsi_aio_readv_acb(acb) != 0) {
544         qemu_aio_release(acb);
545         return NULL;
546     }
547
548     iscsi_set_events(iscsilun);
549     return &acb->common;
550 }
551
552 static int
553 iscsi_aio_flush_acb(IscsiAIOCB *acb);
554
555 static void
556 iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
557                      void *command_data, void *opaque)
558 {
559     IscsiAIOCB *acb = opaque;
560
561     if (acb->canceled != 0) {
562         return;
563     }
564
565     acb->status = 0;
566     if (status != 0) {
567         if (status == SCSI_STATUS_CHECK_CONDITION
568             && acb->task->sense.key == SCSI_SENSE_UNIT_ATTENTION
569             && acb->retries-- > 0) {
570             scsi_free_scsi_task(acb->task);
571             acb->task = NULL;
572             if (iscsi_aio_flush_acb(acb) == 0) {
573                 iscsi_set_events(acb->iscsilun);
574                 return;
575             }
576         }
577         error_report("Failed to sync10 data on iSCSI lun. %s",
578                      iscsi_get_error(iscsi));
579         acb->status = -EIO;
580     }
581
582     iscsi_schedule_bh(acb);
583 }
584
585 static int
586 iscsi_aio_flush_acb(IscsiAIOCB *acb)
587 {
588     struct iscsi_context *iscsi = acb->iscsilun->iscsi;
589
590     acb->canceled   = 0;
591     acb->bh         = NULL;
592     acb->status     = -EINPROGRESS;
593     acb->buf        = NULL;
594
595     acb->task = iscsi_synchronizecache10_task(iscsi, acb->iscsilun->lun,
596                                          0, 0, 0, 0,
597                                          iscsi_synccache10_cb,
598                                          acb);
599     if (acb->task == NULL) {
600         error_report("iSCSI: Failed to send synchronizecache10 command. %s",
601                      iscsi_get_error(iscsi));
602         return -1;
603     }
604
605     return 0;
606 }
607
608 static BlockDriverAIOCB *
609 iscsi_aio_flush(BlockDriverState *bs,
610                 BlockDriverCompletionFunc *cb, void *opaque)
611 {
612     IscsiLun *iscsilun = bs->opaque;
613
614     IscsiAIOCB *acb;
615
616     acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
617
618     acb->iscsilun    = iscsilun;
619     acb->retries     = ISCSI_CMD_RETRIES;
620
621     if (iscsi_aio_flush_acb(acb) != 0) {
622         qemu_aio_release(acb);
623         return NULL;
624     }
625
626     iscsi_set_events(iscsilun);
627
628     return &acb->common;
629 }
630
631 #ifdef __linux__
632 static void
633 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
634                      void *command_data, void *opaque)
635 {
636     IscsiAIOCB *acb = opaque;
637
638     g_free(acb->buf);
639     acb->buf = NULL;
640
641     if (acb->canceled != 0) {
642         return;
643     }
644
645     acb->status = 0;
646     if (status < 0) {
647         error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
648                      iscsi_get_error(iscsi));
649         acb->status = -EIO;
650     }
651
652     acb->ioh->driver_status = 0;
653     acb->ioh->host_status   = 0;
654     acb->ioh->resid         = 0;
655
656 #define SG_ERR_DRIVER_SENSE    0x08
657
658     if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
659         int ss;
660
661         acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
662
663         acb->ioh->sb_len_wr = acb->task->datain.size - 2;
664         ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
665              acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
666         memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
667     }
668
669     iscsi_schedule_bh(acb);
670 }
671
672 static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
673         unsigned long int req, void *buf,
674         BlockDriverCompletionFunc *cb, void *opaque)
675 {
676     IscsiLun *iscsilun = bs->opaque;
677     struct iscsi_context *iscsi = iscsilun->iscsi;
678     struct iscsi_data data;
679     IscsiAIOCB *acb;
680
681     assert(req == SG_IO);
682
683     acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
684
685     acb->iscsilun = iscsilun;
686     acb->canceled    = 0;
687     acb->bh          = NULL;
688     acb->status      = -EINPROGRESS;
689     acb->buf         = NULL;
690     acb->ioh         = buf;
691
692     acb->task = malloc(sizeof(struct scsi_task));
693     if (acb->task == NULL) {
694         error_report("iSCSI: Failed to allocate task for scsi command. %s",
695                      iscsi_get_error(iscsi));
696         qemu_aio_release(acb);
697         return NULL;
698     }
699     memset(acb->task, 0, sizeof(struct scsi_task));
700
701     switch (acb->ioh->dxfer_direction) {
702     case SG_DXFER_TO_DEV:
703         acb->task->xfer_dir = SCSI_XFER_WRITE;
704         break;
705     case SG_DXFER_FROM_DEV:
706         acb->task->xfer_dir = SCSI_XFER_READ;
707         break;
708     default:
709         acb->task->xfer_dir = SCSI_XFER_NONE;
710         break;
711     }
712
713     acb->task->cdb_size = acb->ioh->cmd_len;
714     memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
715     acb->task->expxferlen = acb->ioh->dxfer_len;
716
717     data.size = 0;
718     if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
719         if (acb->ioh->iovec_count == 0) {
720             data.data = acb->ioh->dxferp;
721             data.size = acb->ioh->dxfer_len;
722         } else {
723 #if defined(LIBISCSI_FEATURE_IOVECTOR)
724             scsi_task_set_iov_out(acb->task,
725                                  (struct scsi_iovec *) acb->ioh->dxferp,
726                                  acb->ioh->iovec_count);
727 #else
728             struct iovec *iov = (struct iovec *)acb->ioh->dxferp;
729
730             acb->buf = g_malloc(acb->ioh->dxfer_len);
731             data.data = acb->buf;
732             data.size = iov_to_buf(iov, acb->ioh->iovec_count, 0,
733                                    acb->buf, acb->ioh->dxfer_len);
734 #endif
735         }
736     }
737
738     if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
739                                  iscsi_aio_ioctl_cb,
740                                  (data.size > 0) ? &data : NULL,
741                                  acb) != 0) {
742         scsi_free_scsi_task(acb->task);
743         qemu_aio_release(acb);
744         return NULL;
745     }
746
747     /* tell libiscsi to read straight into the buffer we got from ioctl */
748     if (acb->task->xfer_dir == SCSI_XFER_READ) {
749         if (acb->ioh->iovec_count == 0) {
750             scsi_task_add_data_in_buffer(acb->task,
751                                          acb->ioh->dxfer_len,
752                                          acb->ioh->dxferp);
753         } else {
754 #if defined(LIBISCSI_FEATURE_IOVECTOR)
755             scsi_task_set_iov_in(acb->task,
756                                  (struct scsi_iovec *) acb->ioh->dxferp,
757                                  acb->ioh->iovec_count);
758 #else
759             int i;
760             for (i = 0; i < acb->ioh->iovec_count; i++) {
761                 struct iovec *iov = (struct iovec *)acb->ioh->dxferp;
762
763                 scsi_task_add_data_in_buffer(acb->task,
764                     iov[i].iov_len,
765                     iov[i].iov_base);
766             }
767 #endif
768         }
769     }
770
771     iscsi_set_events(iscsilun);
772
773     return &acb->common;
774 }
775
776
777 static void ioctl_cb(void *opaque, int status)
778 {
779     int *p_status = opaque;
780     *p_status = status;
781 }
782
783 static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
784 {
785     IscsiLun *iscsilun = bs->opaque;
786     int status;
787
788     switch (req) {
789     case SG_GET_VERSION_NUM:
790         *(int *)buf = 30000;
791         break;
792     case SG_GET_SCSI_ID:
793         ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
794         break;
795     case SG_IO:
796         status = -EINPROGRESS;
797         iscsi_aio_ioctl(bs, req, buf, ioctl_cb, &status);
798
799         while (status == -EINPROGRESS) {
800             qemu_aio_wait();
801         }
802
803         return 0;
804     default:
805         return -1;
806     }
807     return 0;
808 }
809 #endif
810
811 static int64_t
812 iscsi_getlength(BlockDriverState *bs)
813 {
814     IscsiLun *iscsilun = bs->opaque;
815     int64_t len;
816
817     len  = iscsilun->num_blocks;
818     len *= iscsilun->block_size;
819
820     return len;
821 }
822
823 #if defined(LIBISCSI_FEATURE_IOVECTOR)
824
825 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
826                                                   int64_t sector_num,
827                                                   int nb_sectors, int *pnum)
828 {
829     IscsiLun *iscsilun = bs->opaque;
830     struct scsi_get_lba_status *lbas = NULL;
831     struct scsi_lba_status_descriptor *lbasd = NULL;
832     struct IscsiTask iTask;
833     int64_t ret;
834
835     iscsi_co_init_iscsitask(iscsilun, &iTask);
836
837     if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
838         ret = -EINVAL;
839         goto out;
840     }
841
842     /* default to all sectors allocated */
843     ret = BDRV_BLOCK_DATA;
844     ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
845     *pnum = nb_sectors;
846
847     /* LUN does not support logical block provisioning */
848     if (iscsilun->lbpme == 0) {
849         goto out;
850     }
851
852 retry:
853     if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
854                                   sector_qemu2lun(sector_num, iscsilun),
855                                   8 + 16, iscsi_co_generic_cb,
856                                   &iTask) == NULL) {
857         ret = -EIO;
858         goto out;
859     }
860
861     while (!iTask.complete) {
862         iscsi_set_events(iscsilun);
863         qemu_coroutine_yield();
864     }
865
866     if (iTask.do_retry) {
867         if (iTask.task != NULL) {
868             scsi_free_scsi_task(iTask.task);
869             iTask.task = NULL;
870         }
871         goto retry;
872     }
873
874     if (iTask.status != SCSI_STATUS_GOOD) {
875         /* in case the get_lba_status_callout fails (i.e.
876          * because the device is busy or the cmd is not
877          * supported) we pretend all blocks are allocated
878          * for backwards compatibility */
879         goto out;
880     }
881
882     lbas = scsi_datain_unmarshall(iTask.task);
883     if (lbas == NULL) {
884         ret = -EIO;
885         goto out;
886     }
887
888     lbasd = &lbas->descriptors[0];
889
890     if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
891         ret = -EIO;
892         goto out;
893     }
894
895     *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
896     if (*pnum > nb_sectors) {
897         *pnum = nb_sectors;
898     }
899
900     if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
901         lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
902         ret &= ~BDRV_BLOCK_DATA;
903         if (iscsilun->lbprz) {
904             ret |= BDRV_BLOCK_ZERO;
905         }
906     }
907
908 out:
909     if (iTask.task != NULL) {
910         scsi_free_scsi_task(iTask.task);
911     }
912     return ret;
913 }
914
915 #endif /* LIBISCSI_FEATURE_IOVECTOR */
916
917 static int
918 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
919                                    int nb_sectors)
920 {
921     IscsiLun *iscsilun = bs->opaque;
922     struct IscsiTask iTask;
923     struct unmap_list list;
924     uint32_t nb_blocks;
925     uint32_t max_unmap;
926
927     if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
928         return -EINVAL;
929     }
930
931     if (!iscsilun->lbp.lbpu) {
932         /* UNMAP is not supported by the target */
933         return 0;
934     }
935
936     list.lba = sector_qemu2lun(sector_num, iscsilun);
937     nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
938
939     max_unmap = iscsilun->bl.max_unmap;
940     if (max_unmap == 0xffffffff) {
941         max_unmap = ISCSI_MAX_UNMAP;
942     }
943
944     while (nb_blocks > 0) {
945         iscsi_co_init_iscsitask(iscsilun, &iTask);
946         list.num = nb_blocks;
947         if (list.num > max_unmap) {
948             list.num = max_unmap;
949         }
950 retry:
951         if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
952                          iscsi_co_generic_cb, &iTask) == NULL) {
953             return -EIO;
954         }
955
956         while (!iTask.complete) {
957             iscsi_set_events(iscsilun);
958             qemu_coroutine_yield();
959         }
960
961         if (iTask.task != NULL) {
962             scsi_free_scsi_task(iTask.task);
963             iTask.task = NULL;
964         }
965
966         if (iTask.do_retry) {
967             goto retry;
968         }
969
970         if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
971             /* the target might fail with a check condition if it
972                is not happy with the alignment of the UNMAP request
973                we silently fail in this case */
974             return 0;
975         }
976
977         if (iTask.status != SCSI_STATUS_GOOD) {
978             return -EIO;
979         }
980
981         list.lba += list.num;
982         nb_blocks -= list.num;
983     }
984
985     return 0;
986 }
987
988 static int parse_chap(struct iscsi_context *iscsi, const char *target)
989 {
990     QemuOptsList *list;
991     QemuOpts *opts;
992     const char *user = NULL;
993     const char *password = NULL;
994
995     list = qemu_find_opts("iscsi");
996     if (!list) {
997         return 0;
998     }
999
1000     opts = qemu_opts_find(list, target);
1001     if (opts == NULL) {
1002         opts = QTAILQ_FIRST(&list->head);
1003         if (!opts) {
1004             return 0;
1005         }
1006     }
1007
1008     user = qemu_opt_get(opts, "user");
1009     if (!user) {
1010         return 0;
1011     }
1012
1013     password = qemu_opt_get(opts, "password");
1014     if (!password) {
1015         error_report("CHAP username specified but no password was given");
1016         return -1;
1017     }
1018
1019     if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1020         error_report("Failed to set initiator username and password");
1021         return -1;
1022     }
1023
1024     return 0;
1025 }
1026
1027 static void parse_header_digest(struct iscsi_context *iscsi, const char *target)
1028 {
1029     QemuOptsList *list;
1030     QemuOpts *opts;
1031     const char *digest = NULL;
1032
1033     list = qemu_find_opts("iscsi");
1034     if (!list) {
1035         return;
1036     }
1037
1038     opts = qemu_opts_find(list, target);
1039     if (opts == NULL) {
1040         opts = QTAILQ_FIRST(&list->head);
1041         if (!opts) {
1042             return;
1043         }
1044     }
1045
1046     digest = qemu_opt_get(opts, "header-digest");
1047     if (!digest) {
1048         return;
1049     }
1050
1051     if (!strcmp(digest, "CRC32C")) {
1052         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1053     } else if (!strcmp(digest, "NONE")) {
1054         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1055     } else if (!strcmp(digest, "CRC32C-NONE")) {
1056         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1057     } else if (!strcmp(digest, "NONE-CRC32C")) {
1058         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1059     } else {
1060         error_report("Invalid header-digest setting : %s", digest);
1061     }
1062 }
1063
1064 static char *parse_initiator_name(const char *target)
1065 {
1066     QemuOptsList *list;
1067     QemuOpts *opts;
1068     const char *name;
1069     char *iscsi_name;
1070     UuidInfo *uuid_info;
1071
1072     list = qemu_find_opts("iscsi");
1073     if (list) {
1074         opts = qemu_opts_find(list, target);
1075         if (!opts) {
1076             opts = QTAILQ_FIRST(&list->head);
1077         }
1078         if (opts) {
1079             name = qemu_opt_get(opts, "initiator-name");
1080             if (name) {
1081                 return g_strdup(name);
1082             }
1083         }
1084     }
1085
1086     uuid_info = qmp_query_uuid(NULL);
1087     if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1088         name = qemu_get_vm_name();
1089     } else {
1090         name = uuid_info->UUID;
1091     }
1092     iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1093                                  name ? ":" : "", name ? name : "");
1094     qapi_free_UuidInfo(uuid_info);
1095     return iscsi_name;
1096 }
1097
1098 #if defined(LIBISCSI_FEATURE_NOP_COUNTER)
1099 static void iscsi_nop_timed_event(void *opaque)
1100 {
1101     IscsiLun *iscsilun = opaque;
1102
1103     if (iscsi_get_nops_in_flight(iscsilun->iscsi) > MAX_NOP_FAILURES) {
1104         error_report("iSCSI: NOP timeout. Reconnecting...");
1105         iscsi_reconnect(iscsilun->iscsi);
1106     }
1107
1108     if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1109         error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1110         return;
1111     }
1112
1113     timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1114     iscsi_set_events(iscsilun);
1115 }
1116 #endif
1117
1118 static int iscsi_readcapacity_sync(IscsiLun *iscsilun)
1119 {
1120     struct scsi_task *task = NULL;
1121     struct scsi_readcapacity10 *rc10 = NULL;
1122     struct scsi_readcapacity16 *rc16 = NULL;
1123     int ret = 0;
1124     int retries = ISCSI_CMD_RETRIES; 
1125
1126     do {
1127         if (task != NULL) {
1128             scsi_free_scsi_task(task);
1129             task = NULL;
1130         }
1131
1132         switch (iscsilun->type) {
1133         case TYPE_DISK:
1134             task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1135             if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1136                 rc16 = scsi_datain_unmarshall(task);
1137                 if (rc16 == NULL) {
1138                     error_report("iSCSI: Failed to unmarshall readcapacity16 data.");
1139                     ret = -EINVAL;
1140                 } else {
1141                     iscsilun->block_size = rc16->block_length;
1142                     iscsilun->num_blocks = rc16->returned_lba + 1;
1143                     iscsilun->lbpme = rc16->lbpme;
1144                     iscsilun->lbprz = rc16->lbprz;
1145                 }
1146             }
1147             break;
1148         case TYPE_ROM:
1149             task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1150             if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1151                 rc10 = scsi_datain_unmarshall(task);
1152                 if (rc10 == NULL) {
1153                     error_report("iSCSI: Failed to unmarshall readcapacity10 data.");
1154                     ret = -EINVAL;
1155                 } else {
1156                     iscsilun->block_size = rc10->block_size;
1157                     if (rc10->lba == 0) {
1158                         /* blank disk loaded */
1159                         iscsilun->num_blocks = 0;
1160                     } else {
1161                         iscsilun->num_blocks = rc10->lba + 1;
1162                     }
1163                 }
1164             }
1165             break;
1166         default:
1167             return 0;
1168         }
1169     } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1170              && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1171              && retries-- > 0);
1172
1173     if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1174         error_report("iSCSI: failed to send readcapacity10 command.");
1175         ret = -EINVAL;
1176     }
1177     if (task) {
1178         scsi_free_scsi_task(task);
1179     }
1180     return ret;
1181 }
1182
1183 /* TODO Convert to fine grained options */
1184 static QemuOptsList runtime_opts = {
1185     .name = "iscsi",
1186     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1187     .desc = {
1188         {
1189             .name = "filename",
1190             .type = QEMU_OPT_STRING,
1191             .help = "URL to the iscsi image",
1192         },
1193         { /* end of list */ }
1194     },
1195 };
1196
1197 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi,
1198                                           int lun, int evpd, int pc) {
1199         int full_size;
1200         struct scsi_task *task = NULL;
1201         task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1202         if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1203             goto fail;
1204         }
1205         full_size = scsi_datain_getfullsize(task);
1206         if (full_size > task->datain.size) {
1207             scsi_free_scsi_task(task);
1208
1209             /* we need more data for the full list */
1210             task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1211             if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1212                 goto fail;
1213             }
1214         }
1215
1216         return task;
1217
1218 fail:
1219         error_report("iSCSI: Inquiry command failed : %s",
1220                      iscsi_get_error(iscsi));
1221         if (task) {
1222             scsi_free_scsi_task(task);
1223             return NULL;
1224         }
1225         return NULL;
1226 }
1227
1228 /*
1229  * We support iscsi url's on the form
1230  * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1231  */
1232 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1233                       Error **errp)
1234 {
1235     IscsiLun *iscsilun = bs->opaque;
1236     struct iscsi_context *iscsi = NULL;
1237     struct iscsi_url *iscsi_url = NULL;
1238     struct scsi_task *task = NULL;
1239     struct scsi_inquiry_standard *inq = NULL;
1240     char *initiator_name = NULL;
1241     QemuOpts *opts;
1242     Error *local_err = NULL;
1243     const char *filename;
1244     int ret;
1245
1246     if ((BDRV_SECTOR_SIZE % 512) != 0) {
1247         error_report("iSCSI: Invalid BDRV_SECTOR_SIZE. "
1248                      "BDRV_SECTOR_SIZE(%lld) is not a multiple "
1249                      "of 512", BDRV_SECTOR_SIZE);
1250         return -EINVAL;
1251     }
1252
1253     opts = qemu_opts_create_nofail(&runtime_opts);
1254     qemu_opts_absorb_qdict(opts, options, &local_err);
1255     if (error_is_set(&local_err)) {
1256         qerror_report_err(local_err);
1257         error_free(local_err);
1258         ret = -EINVAL;
1259         goto out;
1260     }
1261
1262     filename = qemu_opt_get(opts, "filename");
1263
1264
1265     iscsi_url = iscsi_parse_full_url(iscsi, filename);
1266     if (iscsi_url == NULL) {
1267         error_report("Failed to parse URL : %s", filename);
1268         ret = -EINVAL;
1269         goto out;
1270     }
1271
1272     memset(iscsilun, 0, sizeof(IscsiLun));
1273
1274     initiator_name = parse_initiator_name(iscsi_url->target);
1275
1276     iscsi = iscsi_create_context(initiator_name);
1277     if (iscsi == NULL) {
1278         error_report("iSCSI: Failed to create iSCSI context.");
1279         ret = -ENOMEM;
1280         goto out;
1281     }
1282
1283     if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1284         error_report("iSCSI: Failed to set target name.");
1285         ret = -EINVAL;
1286         goto out;
1287     }
1288
1289     if (iscsi_url->user != NULL) {
1290         ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1291                                               iscsi_url->passwd);
1292         if (ret != 0) {
1293             error_report("Failed to set initiator username and password");
1294             ret = -EINVAL;
1295             goto out;
1296         }
1297     }
1298
1299     /* check if we got CHAP username/password via the options */
1300     if (parse_chap(iscsi, iscsi_url->target) != 0) {
1301         error_report("iSCSI: Failed to set CHAP user/password");
1302         ret = -EINVAL;
1303         goto out;
1304     }
1305
1306     if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1307         error_report("iSCSI: Failed to set session type to normal.");
1308         ret = -EINVAL;
1309         goto out;
1310     }
1311
1312     iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1313
1314     /* check if we got HEADER_DIGEST via the options */
1315     parse_header_digest(iscsi, iscsi_url->target);
1316
1317     if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1318         error_report("iSCSI: Failed to connect to LUN : %s",
1319             iscsi_get_error(iscsi));
1320         ret = -EINVAL;
1321         goto out;
1322     }
1323
1324     iscsilun->iscsi = iscsi;
1325     iscsilun->lun   = iscsi_url->lun;
1326
1327     task = iscsi_inquiry_sync(iscsi, iscsilun->lun, 0, 0, 36);
1328
1329     if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1330         error_report("iSCSI: failed to send inquiry command.");
1331         ret = -EINVAL;
1332         goto out;
1333     }
1334
1335     inq = scsi_datain_unmarshall(task);
1336     if (inq == NULL) {
1337         error_report("iSCSI: Failed to unmarshall inquiry data.");
1338         ret = -EINVAL;
1339         goto out;
1340     }
1341
1342     iscsilun->type = inq->periperal_device_type;
1343
1344     if ((ret = iscsi_readcapacity_sync(iscsilun)) != 0) {
1345         goto out;
1346     }
1347     bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1348
1349     /* Medium changer or tape. We dont have any emulation for this so this must
1350      * be sg ioctl compatible. We force it to be sg, otherwise qemu will try
1351      * to read from the device to guess the image format.
1352      */
1353     if (iscsilun->type == TYPE_MEDIUM_CHANGER ||
1354         iscsilun->type == TYPE_TAPE) {
1355         bs->sg = 1;
1356     }
1357
1358     if (iscsilun->lbpme) {
1359         struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1360         task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1361                                 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING);
1362         if (task == NULL) {
1363             ret = -EINVAL;
1364             goto out;
1365         }
1366         inq_lbp = scsi_datain_unmarshall(task);
1367         if (inq_lbp == NULL) {
1368             error_report("iSCSI: failed to unmarshall inquiry datain blob");
1369             ret = -EINVAL;
1370             goto out;
1371         }
1372         memcpy(&iscsilun->lbp, inq_lbp,
1373                sizeof(struct scsi_inquiry_logical_block_provisioning));
1374         scsi_free_scsi_task(task);
1375         task = NULL;
1376     }
1377
1378     if (iscsilun->lbp.lbpu || iscsilun->lbp.lbpws) {
1379         struct scsi_inquiry_block_limits *inq_bl;
1380         task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1381                                 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS);
1382         if (task == NULL) {
1383             ret = -EINVAL;
1384             goto out;
1385         }
1386         inq_bl = scsi_datain_unmarshall(task);
1387         if (inq_bl == NULL) {
1388             error_report("iSCSI: failed to unmarshall inquiry datain blob");
1389             ret = -EINVAL;
1390             goto out;
1391         }
1392         memcpy(&iscsilun->bl, inq_bl,
1393                sizeof(struct scsi_inquiry_block_limits));
1394         scsi_free_scsi_task(task);
1395         task = NULL;
1396     }
1397
1398 #if defined(LIBISCSI_FEATURE_NOP_COUNTER)
1399     /* Set up a timer for sending out iSCSI NOPs */
1400     iscsilun->nop_timer = timer_new_ms(QEMU_CLOCK_REALTIME, iscsi_nop_timed_event, iscsilun);
1401     timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1402 #endif
1403
1404 out:
1405     qemu_opts_del(opts);
1406     if (initiator_name != NULL) {
1407         g_free(initiator_name);
1408     }
1409     if (iscsi_url != NULL) {
1410         iscsi_destroy_url(iscsi_url);
1411     }
1412     if (task != NULL) {
1413         scsi_free_scsi_task(task);
1414     }
1415
1416     if (ret) {
1417         if (iscsi != NULL) {
1418             iscsi_destroy_context(iscsi);
1419         }
1420         memset(iscsilun, 0, sizeof(IscsiLun));
1421     }
1422     return ret;
1423 }
1424
1425 static void iscsi_close(BlockDriverState *bs)
1426 {
1427     IscsiLun *iscsilun = bs->opaque;
1428     struct iscsi_context *iscsi = iscsilun->iscsi;
1429
1430     if (iscsilun->nop_timer) {
1431         timer_del(iscsilun->nop_timer);
1432         timer_free(iscsilun->nop_timer);
1433     }
1434     qemu_aio_set_fd_handler(iscsi_get_fd(iscsi), NULL, NULL, NULL);
1435     iscsi_destroy_context(iscsi);
1436     memset(iscsilun, 0, sizeof(IscsiLun));
1437 }
1438
1439 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1440 {
1441     IscsiLun *iscsilun = bs->opaque;
1442     int ret = 0;
1443
1444     if (iscsilun->type != TYPE_DISK) {
1445         return -ENOTSUP;
1446     }
1447
1448     if ((ret = iscsi_readcapacity_sync(iscsilun)) != 0) {
1449         return ret;
1450     }
1451
1452     if (offset > iscsi_getlength(bs)) {
1453         return -EINVAL;
1454     }
1455
1456     return 0;
1457 }
1458
1459 static int iscsi_has_zero_init(BlockDriverState *bs)
1460 {
1461     return 0;
1462 }
1463
1464 static int iscsi_create(const char *filename, QEMUOptionParameter *options,
1465                         Error **errp)
1466 {
1467     int ret = 0;
1468     int64_t total_size = 0;
1469     BlockDriverState *bs;
1470     IscsiLun *iscsilun = NULL;
1471     QDict *bs_options;
1472
1473     bs = bdrv_new("");
1474
1475     /* Read out options */
1476     while (options && options->name) {
1477         if (!strcmp(options->name, "size")) {
1478             total_size = options->value.n / BDRV_SECTOR_SIZE;
1479         }
1480         options++;
1481     }
1482
1483     bs->opaque = g_malloc0(sizeof(struct IscsiLun));
1484     iscsilun = bs->opaque;
1485
1486     bs_options = qdict_new();
1487     qdict_put(bs_options, "filename", qstring_from_str(filename));
1488     ret = iscsi_open(bs, bs_options, 0, NULL);
1489     QDECREF(bs_options);
1490
1491     if (ret != 0) {
1492         goto out;
1493     }
1494     if (iscsilun->nop_timer) {
1495         timer_del(iscsilun->nop_timer);
1496         timer_free(iscsilun->nop_timer);
1497     }
1498     if (iscsilun->type != TYPE_DISK) {
1499         ret = -ENODEV;
1500         goto out;
1501     }
1502     if (bs->total_sectors < total_size) {
1503         ret = -ENOSPC;
1504         goto out;
1505     }
1506
1507     ret = 0;
1508 out:
1509     if (iscsilun->iscsi != NULL) {
1510         iscsi_destroy_context(iscsilun->iscsi);
1511     }
1512     g_free(bs->opaque);
1513     bs->opaque = NULL;
1514     bdrv_unref(bs);
1515     return ret;
1516 }
1517
1518 static QEMUOptionParameter iscsi_create_options[] = {
1519     {
1520         .name = BLOCK_OPT_SIZE,
1521         .type = OPT_SIZE,
1522         .help = "Virtual disk size"
1523     },
1524     { NULL }
1525 };
1526
1527 static BlockDriver bdrv_iscsi = {
1528     .format_name     = "iscsi",
1529     .protocol_name   = "iscsi",
1530
1531     .instance_size   = sizeof(IscsiLun),
1532     .bdrv_needs_filename = true,
1533     .bdrv_file_open  = iscsi_open,
1534     .bdrv_close      = iscsi_close,
1535     .bdrv_create     = iscsi_create,
1536     .create_options  = iscsi_create_options,
1537
1538     .bdrv_getlength  = iscsi_getlength,
1539     .bdrv_truncate   = iscsi_truncate,
1540
1541 #if defined(LIBISCSI_FEATURE_IOVECTOR)
1542     .bdrv_co_get_block_status = iscsi_co_get_block_status,
1543 #endif
1544     .bdrv_co_discard      = iscsi_co_discard,
1545
1546     .bdrv_aio_readv  = iscsi_aio_readv,
1547     .bdrv_aio_writev = iscsi_aio_writev,
1548     .bdrv_aio_flush  = iscsi_aio_flush,
1549
1550     .bdrv_has_zero_init = iscsi_has_zero_init,
1551
1552 #ifdef __linux__
1553     .bdrv_ioctl       = iscsi_ioctl,
1554     .bdrv_aio_ioctl   = iscsi_aio_ioctl,
1555 #endif
1556 };
1557
1558 static QemuOptsList qemu_iscsi_opts = {
1559     .name = "iscsi",
1560     .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1561     .desc = {
1562         {
1563             .name = "user",
1564             .type = QEMU_OPT_STRING,
1565             .help = "username for CHAP authentication to target",
1566         },{
1567             .name = "password",
1568             .type = QEMU_OPT_STRING,
1569             .help = "password for CHAP authentication to target",
1570         },{
1571             .name = "header-digest",
1572             .type = QEMU_OPT_STRING,
1573             .help = "HeaderDigest setting. "
1574                     "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1575         },{
1576             .name = "initiator-name",
1577             .type = QEMU_OPT_STRING,
1578             .help = "Initiator iqn name to use when connecting",
1579         },
1580         { /* end of list */ }
1581     },
1582 };
1583
1584 static void iscsi_block_init(void)
1585 {
1586     bdrv_register(&bdrv_iscsi);
1587     qemu_add_opts(&qemu_iscsi_opts);
1588 }
1589
1590 block_init(iscsi_block_init);