block/iscsi: use 16 byte CDBs only when necessary
[qemu/cris-port.git] / block / iscsi.c
blob38754872faa28eeccd3920ec47b9b35a1b59fda8
1 /*
2 * QEMU Block driver for iSCSI images
4 * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
5 * Copyright (c) 2012-2014 Peter Lieven <pl@kamp.de>
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "config-host.h"
28 #include <poll.h>
29 #include <math.h>
30 #include <arpa/inet.h>
31 #include "qemu-common.h"
32 #include "qemu/config-file.h"
33 #include "qemu/error-report.h"
34 #include "qemu/bitops.h"
35 #include "qemu/bitmap.h"
36 #include "block/block_int.h"
37 #include "trace.h"
38 #include "block/scsi.h"
39 #include "qemu/iov.h"
40 #include "sysemu/sysemu.h"
41 #include "qmp-commands.h"
43 #include <iscsi/iscsi.h>
44 #include <iscsi/scsi-lowlevel.h>
46 #ifdef __linux__
47 #include <scsi/sg.h>
48 #include <block/scsi.h>
49 #endif
51 typedef struct IscsiLun {
52 struct iscsi_context *iscsi;
53 AioContext *aio_context;
54 int lun;
55 enum scsi_inquiry_peripheral_device_type type;
56 int block_size;
57 uint64_t num_blocks;
58 int events;
59 QEMUTimer *nop_timer;
60 uint8_t lbpme;
61 uint8_t lbprz;
62 uint8_t has_write_same;
63 struct scsi_inquiry_logical_block_provisioning lbp;
64 struct scsi_inquiry_block_limits bl;
65 unsigned char *zeroblock;
66 unsigned long *allocationmap;
67 int cluster_sectors;
68 bool use_16_for_rw;
69 } IscsiLun;
71 typedef struct IscsiTask {
72 int status;
73 int complete;
74 int retries;
75 int do_retry;
76 struct scsi_task *task;
77 Coroutine *co;
78 QEMUBH *bh;
79 IscsiLun *iscsilun;
80 QEMUTimer retry_timer;
81 } IscsiTask;
83 typedef struct IscsiAIOCB {
84 BlockDriverAIOCB common;
85 QEMUIOVector *qiov;
86 QEMUBH *bh;
87 IscsiLun *iscsilun;
88 struct scsi_task *task;
89 uint8_t *buf;
90 int status;
91 int canceled;
92 int64_t sector_num;
93 int nb_sectors;
94 #ifdef __linux__
95 sg_io_hdr_t *ioh;
96 #endif
97 } IscsiAIOCB;
99 #define NOP_INTERVAL 5000
100 #define MAX_NOP_FAILURES 3
101 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
102 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048};
104 /* this threshhold is a trade-off knob to choose between
105 * the potential additional overhead of an extra GET_LBA_STATUS request
106 * vs. unnecessarily reading a lot of zero sectors over the wire.
107 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
108 * sectors we check the allocation status of the area covered by the
109 * request first if the allocationmap indicates that the area might be
110 * unallocated. */
111 #define ISCSI_CHECKALLOC_THRES 64
113 static void
114 iscsi_bh_cb(void *p)
116 IscsiAIOCB *acb = p;
118 qemu_bh_delete(acb->bh);
120 g_free(acb->buf);
121 acb->buf = NULL;
123 if (acb->canceled == 0) {
124 acb->common.cb(acb->common.opaque, acb->status);
127 if (acb->task != NULL) {
128 scsi_free_scsi_task(acb->task);
129 acb->task = NULL;
132 qemu_aio_release(acb);
135 static void
136 iscsi_schedule_bh(IscsiAIOCB *acb)
138 if (acb->bh) {
139 return;
141 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
142 qemu_bh_schedule(acb->bh);
145 static void iscsi_co_generic_bh_cb(void *opaque)
147 struct IscsiTask *iTask = opaque;
148 iTask->complete = 1;
149 qemu_bh_delete(iTask->bh);
150 qemu_coroutine_enter(iTask->co, NULL);
153 static void iscsi_retry_timer_expired(void *opaque)
155 struct IscsiTask *iTask = opaque;
156 iTask->complete = 1;
157 if (iTask->co) {
158 qemu_coroutine_enter(iTask->co, NULL);
162 static inline unsigned exp_random(double mean)
164 return -mean * log((double)rand() / RAND_MAX);
167 static void
168 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
169 void *command_data, void *opaque)
171 struct IscsiTask *iTask = opaque;
172 struct scsi_task *task = command_data;
174 iTask->status = status;
175 iTask->do_retry = 0;
176 iTask->task = task;
178 if (status != SCSI_STATUS_GOOD) {
179 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
180 if (status == SCSI_STATUS_CHECK_CONDITION
181 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
182 error_report("iSCSI CheckCondition: %s",
183 iscsi_get_error(iscsi));
184 iTask->do_retry = 1;
185 goto out;
187 if (status == SCSI_STATUS_BUSY) {
188 unsigned retry_time =
189 exp_random(iscsi_retry_times[iTask->retries - 1]);
190 error_report("iSCSI Busy (retry #%u in %u ms): %s",
191 iTask->retries, retry_time,
192 iscsi_get_error(iscsi));
193 aio_timer_init(iTask->iscsilun->aio_context,
194 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
195 SCALE_MS, iscsi_retry_timer_expired, iTask);
196 timer_mod(&iTask->retry_timer,
197 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
198 iTask->do_retry = 1;
199 return;
202 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
205 out:
206 if (iTask->co) {
207 iTask->bh = aio_bh_new(iTask->iscsilun->aio_context,
208 iscsi_co_generic_bh_cb, iTask);
209 qemu_bh_schedule(iTask->bh);
210 } else {
211 iTask->complete = 1;
215 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
217 *iTask = (struct IscsiTask) {
218 .co = qemu_coroutine_self(),
219 .retries = ISCSI_CMD_RETRIES,
220 .iscsilun = iscsilun,
224 static void
225 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
226 void *private_data)
228 IscsiAIOCB *acb = private_data;
230 acb->status = -ECANCELED;
231 iscsi_schedule_bh(acb);
234 static void
235 iscsi_aio_cancel(BlockDriverAIOCB *blockacb)
237 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
238 IscsiLun *iscsilun = acb->iscsilun;
240 if (acb->status != -EINPROGRESS) {
241 return;
244 acb->canceled = 1;
246 /* send a task mgmt call to the target to cancel the task on the target */
247 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
248 iscsi_abort_task_cb, acb);
250 while (acb->status == -EINPROGRESS) {
251 aio_poll(iscsilun->aio_context, true);
255 static const AIOCBInfo iscsi_aiocb_info = {
256 .aiocb_size = sizeof(IscsiAIOCB),
257 .cancel = iscsi_aio_cancel,
261 static void iscsi_process_read(void *arg);
262 static void iscsi_process_write(void *arg);
264 static void
265 iscsi_set_events(IscsiLun *iscsilun)
267 struct iscsi_context *iscsi = iscsilun->iscsi;
268 int ev;
270 /* We always register a read handler. */
271 ev = POLLIN;
272 ev |= iscsi_which_events(iscsi);
273 if (ev != iscsilun->events) {
274 aio_set_fd_handler(iscsilun->aio_context,
275 iscsi_get_fd(iscsi),
276 iscsi_process_read,
277 (ev & POLLOUT) ? iscsi_process_write : NULL,
278 iscsilun);
282 iscsilun->events = ev;
285 static void
286 iscsi_process_read(void *arg)
288 IscsiLun *iscsilun = arg;
289 struct iscsi_context *iscsi = iscsilun->iscsi;
291 iscsi_service(iscsi, POLLIN);
292 iscsi_set_events(iscsilun);
295 static void
296 iscsi_process_write(void *arg)
298 IscsiLun *iscsilun = arg;
299 struct iscsi_context *iscsi = iscsilun->iscsi;
301 iscsi_service(iscsi, POLLOUT);
302 iscsi_set_events(iscsilun);
305 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
307 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
310 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
312 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
315 static bool is_request_lun_aligned(int64_t sector_num, int nb_sectors,
316 IscsiLun *iscsilun)
318 if ((sector_num * BDRV_SECTOR_SIZE) % iscsilun->block_size ||
319 (nb_sectors * BDRV_SECTOR_SIZE) % iscsilun->block_size) {
320 error_report("iSCSI misaligned request: "
321 "iscsilun->block_size %u, sector_num %" PRIi64
322 ", nb_sectors %d",
323 iscsilun->block_size, sector_num, nb_sectors);
324 return 0;
326 return 1;
329 static void iscsi_allocationmap_set(IscsiLun *iscsilun, int64_t sector_num,
330 int nb_sectors)
332 if (iscsilun->allocationmap == NULL) {
333 return;
335 bitmap_set(iscsilun->allocationmap,
336 sector_num / iscsilun->cluster_sectors,
337 DIV_ROUND_UP(nb_sectors, iscsilun->cluster_sectors));
340 static void iscsi_allocationmap_clear(IscsiLun *iscsilun, int64_t sector_num,
341 int nb_sectors)
343 int64_t cluster_num, nb_clusters;
344 if (iscsilun->allocationmap == NULL) {
345 return;
347 cluster_num = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
348 nb_clusters = (sector_num + nb_sectors) / iscsilun->cluster_sectors
349 - cluster_num;
350 if (nb_clusters > 0) {
351 bitmap_clear(iscsilun->allocationmap, cluster_num, nb_clusters);
355 static int coroutine_fn iscsi_co_writev(BlockDriverState *bs,
356 int64_t sector_num, int nb_sectors,
357 QEMUIOVector *iov)
359 IscsiLun *iscsilun = bs->opaque;
360 struct IscsiTask iTask;
361 uint64_t lba;
362 uint32_t num_sectors;
363 uint8_t *data = NULL;
364 uint8_t *buf = NULL;
366 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
367 return -EINVAL;
370 lba = sector_qemu2lun(sector_num, iscsilun);
371 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
372 #if !defined(LIBISCSI_FEATURE_IOVECTOR)
373 /* if the iovec only contains one buffer we can pass it directly */
374 if (iov->niov == 1) {
375 data = iov->iov[0].iov_base;
376 } else {
377 size_t size = MIN(nb_sectors * BDRV_SECTOR_SIZE, iov->size);
378 buf = g_malloc(size);
379 qemu_iovec_to_buf(iov, 0, buf, size);
380 data = buf;
382 #endif
383 iscsi_co_init_iscsitask(iscsilun, &iTask);
384 retry:
385 if (iscsilun->use_16_for_rw) {
386 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
387 data, num_sectors * iscsilun->block_size,
388 iscsilun->block_size, 0, 0, 0, 0, 0,
389 iscsi_co_generic_cb, &iTask);
390 } else {
391 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
392 data, num_sectors * iscsilun->block_size,
393 iscsilun->block_size, 0, 0, 0, 0, 0,
394 iscsi_co_generic_cb, &iTask);
396 if (iTask.task == NULL) {
397 g_free(buf);
398 return -ENOMEM;
400 #if defined(LIBISCSI_FEATURE_IOVECTOR)
401 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
402 iov->niov);
403 #endif
404 while (!iTask.complete) {
405 iscsi_set_events(iscsilun);
406 qemu_coroutine_yield();
409 if (iTask.task != NULL) {
410 scsi_free_scsi_task(iTask.task);
411 iTask.task = NULL;
414 if (iTask.do_retry) {
415 iTask.complete = 0;
416 goto retry;
419 g_free(buf);
421 if (iTask.status != SCSI_STATUS_GOOD) {
422 return -EIO;
425 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
427 return 0;
431 #if defined(LIBISCSI_FEATURE_IOVECTOR)
432 static bool iscsi_allocationmap_is_allocated(IscsiLun *iscsilun,
433 int64_t sector_num, int nb_sectors)
435 unsigned long size;
436 if (iscsilun->allocationmap == NULL) {
437 return true;
439 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
440 return !(find_next_bit(iscsilun->allocationmap, size,
441 sector_num / iscsilun->cluster_sectors) == size);
444 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
445 int64_t sector_num,
446 int nb_sectors, int *pnum)
448 IscsiLun *iscsilun = bs->opaque;
449 struct scsi_get_lba_status *lbas = NULL;
450 struct scsi_lba_status_descriptor *lbasd = NULL;
451 struct IscsiTask iTask;
452 int64_t ret;
454 iscsi_co_init_iscsitask(iscsilun, &iTask);
456 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
457 ret = -EINVAL;
458 goto out;
461 /* default to all sectors allocated */
462 ret = BDRV_BLOCK_DATA;
463 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
464 *pnum = nb_sectors;
466 /* LUN does not support logical block provisioning */
467 if (iscsilun->lbpme == 0) {
468 goto out;
471 retry:
472 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
473 sector_qemu2lun(sector_num, iscsilun),
474 8 + 16, iscsi_co_generic_cb,
475 &iTask) == NULL) {
476 ret = -ENOMEM;
477 goto out;
480 while (!iTask.complete) {
481 iscsi_set_events(iscsilun);
482 qemu_coroutine_yield();
485 if (iTask.do_retry) {
486 if (iTask.task != NULL) {
487 scsi_free_scsi_task(iTask.task);
488 iTask.task = NULL;
490 iTask.complete = 0;
491 goto retry;
494 if (iTask.status != SCSI_STATUS_GOOD) {
495 /* in case the get_lba_status_callout fails (i.e.
496 * because the device is busy or the cmd is not
497 * supported) we pretend all blocks are allocated
498 * for backwards compatibility */
499 goto out;
502 lbas = scsi_datain_unmarshall(iTask.task);
503 if (lbas == NULL) {
504 ret = -EIO;
505 goto out;
508 lbasd = &lbas->descriptors[0];
510 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
511 ret = -EIO;
512 goto out;
515 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
517 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
518 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
519 ret &= ~BDRV_BLOCK_DATA;
520 if (iscsilun->lbprz) {
521 ret |= BDRV_BLOCK_ZERO;
525 if (ret & BDRV_BLOCK_ZERO) {
526 iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);
527 } else {
528 iscsi_allocationmap_set(iscsilun, sector_num, *pnum);
531 if (*pnum > nb_sectors) {
532 *pnum = nb_sectors;
534 out:
535 if (iTask.task != NULL) {
536 scsi_free_scsi_task(iTask.task);
538 return ret;
541 #endif /* LIBISCSI_FEATURE_IOVECTOR */
544 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
545 int64_t sector_num, int nb_sectors,
546 QEMUIOVector *iov)
548 IscsiLun *iscsilun = bs->opaque;
549 struct IscsiTask iTask;
550 uint64_t lba;
551 uint32_t num_sectors;
552 #if !defined(LIBISCSI_FEATURE_IOVECTOR)
553 int i;
554 #endif
556 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
557 return -EINVAL;
560 #if defined(LIBISCSI_FEATURE_IOVECTOR)
561 if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
562 !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
563 int64_t ret;
564 int pnum;
565 ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum);
566 if (ret < 0) {
567 return ret;
569 if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
570 qemu_iovec_memset(iov, 0, 0x00, iov->size);
571 return 0;
574 #endif
576 lba = sector_qemu2lun(sector_num, iscsilun);
577 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
579 iscsi_co_init_iscsitask(iscsilun, &iTask);
580 retry:
581 if (iscsilun->use_16_for_rw) {
582 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
583 num_sectors * iscsilun->block_size,
584 iscsilun->block_size, 0, 0, 0, 0, 0,
585 iscsi_co_generic_cb, &iTask);
586 } else {
587 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
588 num_sectors * iscsilun->block_size,
589 iscsilun->block_size,
590 #if !defined(CONFIG_LIBISCSI_1_4) /* API change from 1.4.0 to 1.5.0 */
591 0, 0, 0, 0, 0,
592 #endif
593 iscsi_co_generic_cb, &iTask);
595 if (iTask.task == NULL) {
596 return -ENOMEM;
598 #if defined(LIBISCSI_FEATURE_IOVECTOR)
599 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
600 #else
601 for (i = 0; i < iov->niov; i++) {
602 scsi_task_add_data_in_buffer(iTask.task,
603 iov->iov[i].iov_len,
604 iov->iov[i].iov_base);
606 #endif
608 while (!iTask.complete) {
609 iscsi_set_events(iscsilun);
610 qemu_coroutine_yield();
613 if (iTask.task != NULL) {
614 scsi_free_scsi_task(iTask.task);
615 iTask.task = NULL;
618 if (iTask.do_retry) {
619 iTask.complete = 0;
620 goto retry;
623 if (iTask.status != SCSI_STATUS_GOOD) {
624 return -EIO;
627 return 0;
630 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
632 IscsiLun *iscsilun = bs->opaque;
633 struct IscsiTask iTask;
635 if (bs->sg) {
636 return 0;
639 iscsi_co_init_iscsitask(iscsilun, &iTask);
641 retry:
642 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
643 0, iscsi_co_generic_cb, &iTask) == NULL) {
644 return -ENOMEM;
647 while (!iTask.complete) {
648 iscsi_set_events(iscsilun);
649 qemu_coroutine_yield();
652 if (iTask.task != NULL) {
653 scsi_free_scsi_task(iTask.task);
654 iTask.task = NULL;
657 if (iTask.do_retry) {
658 iTask.complete = 0;
659 goto retry;
662 if (iTask.status != SCSI_STATUS_GOOD) {
663 return -EIO;
666 return 0;
669 #ifdef __linux__
670 static void
671 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
672 void *command_data, void *opaque)
674 IscsiAIOCB *acb = opaque;
676 g_free(acb->buf);
677 acb->buf = NULL;
679 if (acb->canceled != 0) {
680 return;
683 acb->status = 0;
684 if (status < 0) {
685 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
686 iscsi_get_error(iscsi));
687 acb->status = -EIO;
690 acb->ioh->driver_status = 0;
691 acb->ioh->host_status = 0;
692 acb->ioh->resid = 0;
694 #define SG_ERR_DRIVER_SENSE 0x08
696 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
697 int ss;
699 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
701 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
702 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
703 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
704 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
707 iscsi_schedule_bh(acb);
710 static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
711 unsigned long int req, void *buf,
712 BlockDriverCompletionFunc *cb, void *opaque)
714 IscsiLun *iscsilun = bs->opaque;
715 struct iscsi_context *iscsi = iscsilun->iscsi;
716 struct iscsi_data data;
717 IscsiAIOCB *acb;
719 assert(req == SG_IO);
721 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
723 acb->iscsilun = iscsilun;
724 acb->canceled = 0;
725 acb->bh = NULL;
726 acb->status = -EINPROGRESS;
727 acb->buf = NULL;
728 acb->ioh = buf;
730 acb->task = malloc(sizeof(struct scsi_task));
731 if (acb->task == NULL) {
732 error_report("iSCSI: Failed to allocate task for scsi command. %s",
733 iscsi_get_error(iscsi));
734 qemu_aio_release(acb);
735 return NULL;
737 memset(acb->task, 0, sizeof(struct scsi_task));
739 switch (acb->ioh->dxfer_direction) {
740 case SG_DXFER_TO_DEV:
741 acb->task->xfer_dir = SCSI_XFER_WRITE;
742 break;
743 case SG_DXFER_FROM_DEV:
744 acb->task->xfer_dir = SCSI_XFER_READ;
745 break;
746 default:
747 acb->task->xfer_dir = SCSI_XFER_NONE;
748 break;
751 acb->task->cdb_size = acb->ioh->cmd_len;
752 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
753 acb->task->expxferlen = acb->ioh->dxfer_len;
755 data.size = 0;
756 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
757 if (acb->ioh->iovec_count == 0) {
758 data.data = acb->ioh->dxferp;
759 data.size = acb->ioh->dxfer_len;
760 } else {
761 #if defined(LIBISCSI_FEATURE_IOVECTOR)
762 scsi_task_set_iov_out(acb->task,
763 (struct scsi_iovec *) acb->ioh->dxferp,
764 acb->ioh->iovec_count);
765 #else
766 struct iovec *iov = (struct iovec *)acb->ioh->dxferp;
768 acb->buf = g_malloc(acb->ioh->dxfer_len);
769 data.data = acb->buf;
770 data.size = iov_to_buf(iov, acb->ioh->iovec_count, 0,
771 acb->buf, acb->ioh->dxfer_len);
772 #endif
776 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
777 iscsi_aio_ioctl_cb,
778 (data.size > 0) ? &data : NULL,
779 acb) != 0) {
780 scsi_free_scsi_task(acb->task);
781 qemu_aio_release(acb);
782 return NULL;
785 /* tell libiscsi to read straight into the buffer we got from ioctl */
786 if (acb->task->xfer_dir == SCSI_XFER_READ) {
787 if (acb->ioh->iovec_count == 0) {
788 scsi_task_add_data_in_buffer(acb->task,
789 acb->ioh->dxfer_len,
790 acb->ioh->dxferp);
791 } else {
792 #if defined(LIBISCSI_FEATURE_IOVECTOR)
793 scsi_task_set_iov_in(acb->task,
794 (struct scsi_iovec *) acb->ioh->dxferp,
795 acb->ioh->iovec_count);
796 #else
797 int i;
798 for (i = 0; i < acb->ioh->iovec_count; i++) {
799 struct iovec *iov = (struct iovec *)acb->ioh->dxferp;
801 scsi_task_add_data_in_buffer(acb->task,
802 iov[i].iov_len,
803 iov[i].iov_base);
805 #endif
809 iscsi_set_events(iscsilun);
811 return &acb->common;
815 static void ioctl_cb(void *opaque, int status)
817 int *p_status = opaque;
818 *p_status = status;
821 static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
823 IscsiLun *iscsilun = bs->opaque;
824 int status;
826 switch (req) {
827 case SG_GET_VERSION_NUM:
828 *(int *)buf = 30000;
829 break;
830 case SG_GET_SCSI_ID:
831 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
832 break;
833 case SG_IO:
834 status = -EINPROGRESS;
835 iscsi_aio_ioctl(bs, req, buf, ioctl_cb, &status);
837 while (status == -EINPROGRESS) {
838 aio_poll(iscsilun->aio_context, true);
841 return 0;
842 default:
843 return -1;
845 return 0;
847 #endif
849 static int64_t
850 iscsi_getlength(BlockDriverState *bs)
852 IscsiLun *iscsilun = bs->opaque;
853 int64_t len;
855 len = iscsilun->num_blocks;
856 len *= iscsilun->block_size;
858 return len;
861 static int
862 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
863 int nb_sectors)
865 IscsiLun *iscsilun = bs->opaque;
866 struct IscsiTask iTask;
867 struct unmap_list list;
869 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
870 return -EINVAL;
873 if (!iscsilun->lbp.lbpu) {
874 /* UNMAP is not supported by the target */
875 return 0;
878 list.lba = sector_qemu2lun(sector_num, iscsilun);
879 list.num = sector_qemu2lun(nb_sectors, iscsilun);
881 iscsi_co_init_iscsitask(iscsilun, &iTask);
882 retry:
883 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
884 iscsi_co_generic_cb, &iTask) == NULL) {
885 return -ENOMEM;
888 while (!iTask.complete) {
889 iscsi_set_events(iscsilun);
890 qemu_coroutine_yield();
893 if (iTask.task != NULL) {
894 scsi_free_scsi_task(iTask.task);
895 iTask.task = NULL;
898 if (iTask.do_retry) {
899 iTask.complete = 0;
900 goto retry;
903 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
904 /* the target might fail with a check condition if it
905 is not happy with the alignment of the UNMAP request
906 we silently fail in this case */
907 return 0;
910 if (iTask.status != SCSI_STATUS_GOOD) {
911 return -EIO;
914 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
916 return 0;
919 #if defined(SCSI_SENSE_ASCQ_CAPACITY_DATA_HAS_CHANGED)
921 static int
922 coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
923 int nb_sectors, BdrvRequestFlags flags)
925 IscsiLun *iscsilun = bs->opaque;
926 struct IscsiTask iTask;
927 uint64_t lba;
928 uint32_t nb_blocks;
929 bool use_16_for_ws = iscsilun->use_16_for_rw;
931 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
932 return -EINVAL;
935 if (flags & BDRV_REQ_MAY_UNMAP) {
936 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
937 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
938 use_16_for_ws = true;
940 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
941 /* WRITESAME16 with UNMAP is not supported by the target,
942 * fall back and try WRITESAME10/16 without UNMAP */
943 flags &= ~BDRV_REQ_MAY_UNMAP;
944 use_16_for_ws = iscsilun->use_16_for_rw;
948 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
949 /* WRITESAME without UNMAP is not supported by the target */
950 return -ENOTSUP;
953 lba = sector_qemu2lun(sector_num, iscsilun);
954 nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
956 if (iscsilun->zeroblock == NULL) {
957 iscsilun->zeroblock = g_malloc0(iscsilun->block_size);
960 iscsi_co_init_iscsitask(iscsilun, &iTask);
961 retry:
962 if (use_16_for_ws) {
963 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
964 iscsilun->zeroblock, iscsilun->block_size,
965 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
966 0, 0, iscsi_co_generic_cb, &iTask);
967 } else {
968 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
969 iscsilun->zeroblock, iscsilun->block_size,
970 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
971 0, 0, iscsi_co_generic_cb, &iTask);
973 if (iTask.task == NULL) {
974 return -ENOMEM;
977 while (!iTask.complete) {
978 iscsi_set_events(iscsilun);
979 qemu_coroutine_yield();
982 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
983 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
984 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
985 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
986 /* WRITE SAME is not supported by the target */
987 iscsilun->has_write_same = false;
988 scsi_free_scsi_task(iTask.task);
989 return -ENOTSUP;
992 if (iTask.task != NULL) {
993 scsi_free_scsi_task(iTask.task);
994 iTask.task = NULL;
997 if (iTask.do_retry) {
998 iTask.complete = 0;
999 goto retry;
1002 if (iTask.status != SCSI_STATUS_GOOD) {
1003 return -EIO;
1006 if (flags & BDRV_REQ_MAY_UNMAP) {
1007 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
1008 } else {
1009 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
1012 return 0;
1015 #endif /* SCSI_SENSE_ASCQ_CAPACITY_DATA_HAS_CHANGED */
1017 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1018 Error **errp)
1020 QemuOptsList *list;
1021 QemuOpts *opts;
1022 const char *user = NULL;
1023 const char *password = NULL;
1025 list = qemu_find_opts("iscsi");
1026 if (!list) {
1027 return;
1030 opts = qemu_opts_find(list, target);
1031 if (opts == NULL) {
1032 opts = QTAILQ_FIRST(&list->head);
1033 if (!opts) {
1034 return;
1038 user = qemu_opt_get(opts, "user");
1039 if (!user) {
1040 return;
1043 password = qemu_opt_get(opts, "password");
1044 if (!password) {
1045 error_setg(errp, "CHAP username specified but no password was given");
1046 return;
1049 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1050 error_setg(errp, "Failed to set initiator username and password");
1054 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1055 Error **errp)
1057 QemuOptsList *list;
1058 QemuOpts *opts;
1059 const char *digest = NULL;
1061 list = qemu_find_opts("iscsi");
1062 if (!list) {
1063 return;
1066 opts = qemu_opts_find(list, target);
1067 if (opts == NULL) {
1068 opts = QTAILQ_FIRST(&list->head);
1069 if (!opts) {
1070 return;
1074 digest = qemu_opt_get(opts, "header-digest");
1075 if (!digest) {
1076 return;
1079 if (!strcmp(digest, "CRC32C")) {
1080 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1081 } else if (!strcmp(digest, "NONE")) {
1082 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1083 } else if (!strcmp(digest, "CRC32C-NONE")) {
1084 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1085 } else if (!strcmp(digest, "NONE-CRC32C")) {
1086 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1087 } else {
1088 error_setg(errp, "Invalid header-digest setting : %s", digest);
1092 static char *parse_initiator_name(const char *target)
1094 QemuOptsList *list;
1095 QemuOpts *opts;
1096 const char *name;
1097 char *iscsi_name;
1098 UuidInfo *uuid_info;
1100 list = qemu_find_opts("iscsi");
1101 if (list) {
1102 opts = qemu_opts_find(list, target);
1103 if (!opts) {
1104 opts = QTAILQ_FIRST(&list->head);
1106 if (opts) {
1107 name = qemu_opt_get(opts, "initiator-name");
1108 if (name) {
1109 return g_strdup(name);
1114 uuid_info = qmp_query_uuid(NULL);
1115 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1116 name = qemu_get_vm_name();
1117 } else {
1118 name = uuid_info->UUID;
1120 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1121 name ? ":" : "", name ? name : "");
1122 qapi_free_UuidInfo(uuid_info);
1123 return iscsi_name;
1126 #if defined(LIBISCSI_FEATURE_NOP_COUNTER)
1127 static void iscsi_nop_timed_event(void *opaque)
1129 IscsiLun *iscsilun = opaque;
1131 if (iscsi_get_nops_in_flight(iscsilun->iscsi) > MAX_NOP_FAILURES) {
1132 error_report("iSCSI: NOP timeout. Reconnecting...");
1133 iscsi_reconnect(iscsilun->iscsi);
1136 if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1137 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1138 return;
1141 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1142 iscsi_set_events(iscsilun);
1144 #endif
1146 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1148 struct scsi_task *task = NULL;
1149 struct scsi_readcapacity10 *rc10 = NULL;
1150 struct scsi_readcapacity16 *rc16 = NULL;
1151 int retries = ISCSI_CMD_RETRIES;
1153 do {
1154 if (task != NULL) {
1155 scsi_free_scsi_task(task);
1156 task = NULL;
1159 switch (iscsilun->type) {
1160 case TYPE_DISK:
1161 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1162 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1163 rc16 = scsi_datain_unmarshall(task);
1164 if (rc16 == NULL) {
1165 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1166 } else {
1167 iscsilun->block_size = rc16->block_length;
1168 iscsilun->num_blocks = rc16->returned_lba + 1;
1169 iscsilun->lbpme = rc16->lbpme;
1170 iscsilun->lbprz = rc16->lbprz;
1171 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1174 break;
1175 case TYPE_ROM:
1176 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1177 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1178 rc10 = scsi_datain_unmarshall(task);
1179 if (rc10 == NULL) {
1180 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1181 } else {
1182 iscsilun->block_size = rc10->block_size;
1183 if (rc10->lba == 0) {
1184 /* blank disk loaded */
1185 iscsilun->num_blocks = 0;
1186 } else {
1187 iscsilun->num_blocks = rc10->lba + 1;
1191 break;
1192 default:
1193 return;
1195 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1196 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1197 && retries-- > 0);
1199 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1200 error_setg(errp, "iSCSI: failed to send readcapacity10 command.");
1202 if (task) {
1203 scsi_free_scsi_task(task);
1207 /* TODO Convert to fine grained options */
1208 static QemuOptsList runtime_opts = {
1209 .name = "iscsi",
1210 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1211 .desc = {
1213 .name = "filename",
1214 .type = QEMU_OPT_STRING,
1215 .help = "URL to the iscsi image",
1217 { /* end of list */ }
1221 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1222 int evpd, int pc, void **inq, Error **errp)
1224 int full_size;
1225 struct scsi_task *task = NULL;
1226 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1227 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1228 goto fail;
1230 full_size = scsi_datain_getfullsize(task);
1231 if (full_size > task->datain.size) {
1232 scsi_free_scsi_task(task);
1234 /* we need more data for the full list */
1235 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1236 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1237 goto fail;
1241 *inq = scsi_datain_unmarshall(task);
1242 if (*inq == NULL) {
1243 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1244 goto fail_with_err;
1247 return task;
1249 fail:
1250 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1251 iscsi_get_error(iscsi));
1252 fail_with_err:
1253 if (task != NULL) {
1254 scsi_free_scsi_task(task);
1256 return NULL;
1259 static void iscsi_detach_aio_context(BlockDriverState *bs)
1261 IscsiLun *iscsilun = bs->opaque;
1263 aio_set_fd_handler(iscsilun->aio_context,
1264 iscsi_get_fd(iscsilun->iscsi),
1265 NULL, NULL, NULL);
1266 iscsilun->events = 0;
1268 if (iscsilun->nop_timer) {
1269 timer_del(iscsilun->nop_timer);
1270 timer_free(iscsilun->nop_timer);
1271 iscsilun->nop_timer = NULL;
1275 static void iscsi_attach_aio_context(BlockDriverState *bs,
1276 AioContext *new_context)
1278 IscsiLun *iscsilun = bs->opaque;
1280 iscsilun->aio_context = new_context;
1281 iscsi_set_events(iscsilun);
1283 #if defined(LIBISCSI_FEATURE_NOP_COUNTER)
1284 /* Set up a timer for sending out iSCSI NOPs */
1285 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1286 QEMU_CLOCK_REALTIME, SCALE_MS,
1287 iscsi_nop_timed_event, iscsilun);
1288 timer_mod(iscsilun->nop_timer,
1289 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1290 #endif
1294 * We support iscsi url's on the form
1295 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1297 * Note: flags are currently not used by iscsi_open. If this function
1298 * is changed such that flags are used, please examine iscsi_reopen_prepare()
1299 * to see if needs to be changed as well.
1301 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1302 Error **errp)
1304 IscsiLun *iscsilun = bs->opaque;
1305 struct iscsi_context *iscsi = NULL;
1306 struct iscsi_url *iscsi_url = NULL;
1307 struct scsi_task *task = NULL;
1308 struct scsi_inquiry_standard *inq = NULL;
1309 struct scsi_inquiry_supported_pages *inq_vpd;
1310 char *initiator_name = NULL;
1311 QemuOpts *opts;
1312 Error *local_err = NULL;
1313 const char *filename;
1314 int i, ret;
1316 if ((BDRV_SECTOR_SIZE % 512) != 0) {
1317 error_setg(errp, "iSCSI: Invalid BDRV_SECTOR_SIZE. "
1318 "BDRV_SECTOR_SIZE(%lld) is not a multiple "
1319 "of 512", BDRV_SECTOR_SIZE);
1320 return -EINVAL;
1323 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1324 qemu_opts_absorb_qdict(opts, options, &local_err);
1325 if (local_err) {
1326 error_propagate(errp, local_err);
1327 ret = -EINVAL;
1328 goto out;
1331 filename = qemu_opt_get(opts, "filename");
1333 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1334 if (iscsi_url == NULL) {
1335 error_setg(errp, "Failed to parse URL : %s", filename);
1336 ret = -EINVAL;
1337 goto out;
1340 memset(iscsilun, 0, sizeof(IscsiLun));
1342 initiator_name = parse_initiator_name(iscsi_url->target);
1344 iscsi = iscsi_create_context(initiator_name);
1345 if (iscsi == NULL) {
1346 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1347 ret = -ENOMEM;
1348 goto out;
1351 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1352 error_setg(errp, "iSCSI: Failed to set target name.");
1353 ret = -EINVAL;
1354 goto out;
1357 if (iscsi_url->user != NULL) {
1358 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1359 iscsi_url->passwd);
1360 if (ret != 0) {
1361 error_setg(errp, "Failed to set initiator username and password");
1362 ret = -EINVAL;
1363 goto out;
1367 /* check if we got CHAP username/password via the options */
1368 parse_chap(iscsi, iscsi_url->target, &local_err);
1369 if (local_err != NULL) {
1370 error_propagate(errp, local_err);
1371 ret = -EINVAL;
1372 goto out;
1375 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1376 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1377 ret = -EINVAL;
1378 goto out;
1381 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1383 /* check if we got HEADER_DIGEST via the options */
1384 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1385 if (local_err != NULL) {
1386 error_propagate(errp, local_err);
1387 ret = -EINVAL;
1388 goto out;
1391 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1392 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1393 iscsi_get_error(iscsi));
1394 ret = -EINVAL;
1395 goto out;
1398 iscsilun->iscsi = iscsi;
1399 iscsilun->aio_context = bdrv_get_aio_context(bs);
1400 iscsilun->lun = iscsi_url->lun;
1401 iscsilun->has_write_same = true;
1403 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1404 (void **) &inq, errp);
1405 if (task == NULL) {
1406 ret = -EINVAL;
1407 goto out;
1409 iscsilun->type = inq->periperal_device_type;
1410 scsi_free_scsi_task(task);
1411 task = NULL;
1413 iscsi_readcapacity_sync(iscsilun, &local_err);
1414 if (local_err != NULL) {
1415 error_propagate(errp, local_err);
1416 ret = -EINVAL;
1417 goto out;
1419 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1420 bs->request_alignment = iscsilun->block_size;
1422 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1423 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1424 * will try to read from the device to guess the image format.
1426 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1427 bs->sg = 1;
1430 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1431 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1432 (void **) &inq_vpd, errp);
1433 if (task == NULL) {
1434 ret = -EINVAL;
1435 goto out;
1437 for (i = 0; i < inq_vpd->num_pages; i++) {
1438 struct scsi_task *inq_task;
1439 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1440 struct scsi_inquiry_block_limits *inq_bl;
1441 switch (inq_vpd->pages[i]) {
1442 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1443 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1444 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1445 (void **) &inq_lbp, errp);
1446 if (inq_task == NULL) {
1447 ret = -EINVAL;
1448 goto out;
1450 memcpy(&iscsilun->lbp, inq_lbp,
1451 sizeof(struct scsi_inquiry_logical_block_provisioning));
1452 scsi_free_scsi_task(inq_task);
1453 break;
1454 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1455 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1456 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1457 (void **) &inq_bl, errp);
1458 if (inq_task == NULL) {
1459 ret = -EINVAL;
1460 goto out;
1462 memcpy(&iscsilun->bl, inq_bl,
1463 sizeof(struct scsi_inquiry_block_limits));
1464 scsi_free_scsi_task(inq_task);
1465 break;
1466 default:
1467 break;
1470 scsi_free_scsi_task(task);
1471 task = NULL;
1473 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1475 /* Guess the internal cluster (page) size of the iscsi target by the means
1476 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1477 * reasonable size */
1478 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1479 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1480 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1481 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1482 #if defined(LIBISCSI_FEATURE_IOVECTOR)
1483 if (iscsilun->lbprz && !(bs->open_flags & BDRV_O_NOCACHE)) {
1484 iscsilun->allocationmap =
1485 bitmap_new(DIV_ROUND_UP(bs->total_sectors,
1486 iscsilun->cluster_sectors));
1488 #endif
1491 out:
1492 qemu_opts_del(opts);
1493 g_free(initiator_name);
1494 if (iscsi_url != NULL) {
1495 iscsi_destroy_url(iscsi_url);
1497 if (task != NULL) {
1498 scsi_free_scsi_task(task);
1501 if (ret) {
1502 if (iscsi != NULL) {
1503 iscsi_destroy_context(iscsi);
1505 memset(iscsilun, 0, sizeof(IscsiLun));
1507 return ret;
1510 static void iscsi_close(BlockDriverState *bs)
1512 IscsiLun *iscsilun = bs->opaque;
1513 struct iscsi_context *iscsi = iscsilun->iscsi;
1515 iscsi_detach_aio_context(bs);
1516 iscsi_destroy_context(iscsi);
1517 g_free(iscsilun->zeroblock);
1518 g_free(iscsilun->allocationmap);
1519 memset(iscsilun, 0, sizeof(IscsiLun));
1522 static int iscsi_refresh_limits(BlockDriverState *bs)
1524 IscsiLun *iscsilun = bs->opaque;
1526 /* We don't actually refresh here, but just return data queried in
1527 * iscsi_open(): iscsi targets don't change their limits. */
1528 if (iscsilun->lbp.lbpu) {
1529 if (iscsilun->bl.max_unmap < 0xffffffff) {
1530 bs->bl.max_discard = sector_lun2qemu(iscsilun->bl.max_unmap,
1531 iscsilun);
1533 bs->bl.discard_alignment = sector_lun2qemu(iscsilun->bl.opt_unmap_gran,
1534 iscsilun);
1537 if (iscsilun->bl.max_ws_len < 0xffffffff) {
1538 bs->bl.max_write_zeroes = sector_lun2qemu(iscsilun->bl.max_ws_len,
1539 iscsilun);
1541 if (iscsilun->lbp.lbpws) {
1542 bs->bl.write_zeroes_alignment = sector_lun2qemu(iscsilun->bl.opt_unmap_gran,
1543 iscsilun);
1545 bs->bl.opt_transfer_length = sector_lun2qemu(iscsilun->bl.opt_xfer_len,
1546 iscsilun);
1547 return 0;
1550 /* Since iscsi_open() ignores bdrv_flags, there is nothing to do here in
1551 * prepare. Note that this will not re-establish a connection with an iSCSI
1552 * target - it is effectively a NOP. */
1553 static int iscsi_reopen_prepare(BDRVReopenState *state,
1554 BlockReopenQueue *queue, Error **errp)
1556 /* NOP */
1557 return 0;
1560 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1562 IscsiLun *iscsilun = bs->opaque;
1563 Error *local_err = NULL;
1565 if (iscsilun->type != TYPE_DISK) {
1566 return -ENOTSUP;
1569 iscsi_readcapacity_sync(iscsilun, &local_err);
1570 if (local_err != NULL) {
1571 error_free(local_err);
1572 return -EIO;
1575 if (offset > iscsi_getlength(bs)) {
1576 return -EINVAL;
1579 if (iscsilun->allocationmap != NULL) {
1580 g_free(iscsilun->allocationmap);
1581 iscsilun->allocationmap =
1582 bitmap_new(DIV_ROUND_UP(bs->total_sectors,
1583 iscsilun->cluster_sectors));
1586 return 0;
1589 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1591 int ret = 0;
1592 int64_t total_size = 0;
1593 BlockDriverState *bs;
1594 IscsiLun *iscsilun = NULL;
1595 QDict *bs_options;
1597 bs = bdrv_new("", &error_abort);
1599 /* Read out options */
1600 total_size =
1601 qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;
1602 bs->opaque = g_malloc0(sizeof(struct IscsiLun));
1603 iscsilun = bs->opaque;
1605 bs_options = qdict_new();
1606 qdict_put(bs_options, "filename", qstring_from_str(filename));
1607 ret = iscsi_open(bs, bs_options, 0, NULL);
1608 QDECREF(bs_options);
1610 if (ret != 0) {
1611 goto out;
1613 iscsi_detach_aio_context(bs);
1614 if (iscsilun->type != TYPE_DISK) {
1615 ret = -ENODEV;
1616 goto out;
1618 if (bs->total_sectors < total_size) {
1619 ret = -ENOSPC;
1620 goto out;
1623 ret = 0;
1624 out:
1625 if (iscsilun->iscsi != NULL) {
1626 iscsi_destroy_context(iscsilun->iscsi);
1628 g_free(bs->opaque);
1629 bs->opaque = NULL;
1630 bdrv_unref(bs);
1631 return ret;
1634 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1636 IscsiLun *iscsilun = bs->opaque;
1637 bdi->unallocated_blocks_are_zero = !!iscsilun->lbprz;
1638 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1639 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1640 return 0;
1643 static QemuOptsList iscsi_create_opts = {
1644 .name = "iscsi-create-opts",
1645 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1646 .desc = {
1648 .name = BLOCK_OPT_SIZE,
1649 .type = QEMU_OPT_SIZE,
1650 .help = "Virtual disk size"
1652 { /* end of list */ }
1656 static BlockDriver bdrv_iscsi = {
1657 .format_name = "iscsi",
1658 .protocol_name = "iscsi",
1660 .instance_size = sizeof(IscsiLun),
1661 .bdrv_needs_filename = true,
1662 .bdrv_file_open = iscsi_open,
1663 .bdrv_close = iscsi_close,
1664 .bdrv_create = iscsi_create,
1665 .create_opts = &iscsi_create_opts,
1666 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1668 .bdrv_getlength = iscsi_getlength,
1669 .bdrv_get_info = iscsi_get_info,
1670 .bdrv_truncate = iscsi_truncate,
1671 .bdrv_refresh_limits = iscsi_refresh_limits,
1673 #if defined(LIBISCSI_FEATURE_IOVECTOR)
1674 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1675 #endif
1676 .bdrv_co_discard = iscsi_co_discard,
1677 #if defined(SCSI_SENSE_ASCQ_CAPACITY_DATA_HAS_CHANGED)
1678 .bdrv_co_write_zeroes = iscsi_co_write_zeroes,
1679 #endif
1680 .bdrv_co_readv = iscsi_co_readv,
1681 .bdrv_co_writev = iscsi_co_writev,
1682 .bdrv_co_flush_to_disk = iscsi_co_flush,
1684 #ifdef __linux__
1685 .bdrv_ioctl = iscsi_ioctl,
1686 .bdrv_aio_ioctl = iscsi_aio_ioctl,
1687 #endif
1689 .bdrv_detach_aio_context = iscsi_detach_aio_context,
1690 .bdrv_attach_aio_context = iscsi_attach_aio_context,
1693 static QemuOptsList qemu_iscsi_opts = {
1694 .name = "iscsi",
1695 .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1696 .desc = {
1698 .name = "user",
1699 .type = QEMU_OPT_STRING,
1700 .help = "username for CHAP authentication to target",
1702 .name = "password",
1703 .type = QEMU_OPT_STRING,
1704 .help = "password for CHAP authentication to target",
1706 .name = "header-digest",
1707 .type = QEMU_OPT_STRING,
1708 .help = "HeaderDigest setting. "
1709 "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1711 .name = "initiator-name",
1712 .type = QEMU_OPT_STRING,
1713 .help = "Initiator iqn name to use when connecting",
1715 { /* end of list */ }
1719 static void iscsi_block_init(void)
1721 bdrv_register(&bdrv_iscsi);
1722 qemu_add_opts(&qemu_iscsi_opts);
1725 block_init(iscsi_block_init);