2 * QEMU Block driver for iSCSI images
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
26 #include "qemu/osdep.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 "block/scsi.h"
39 #include "qemu/uuid.h"
40 #include "qmp-commands.h"
41 #include "qapi/qmp/qstring.h"
42 #include "crypto/secret.h"
43 #include "scsi/scsi.h"
45 #include <iscsi/iscsi.h>
46 #include <iscsi/scsi-lowlevel.h>
52 typedef struct IscsiLun {
53 struct iscsi_context *iscsi;
54 AioContext *aio_context;
56 enum scsi_inquiry_peripheral_device_type type;
61 QEMUTimer *event_timer;
63 struct scsi_inquiry_logical_block_provisioning lbp;
64 struct scsi_inquiry_block_limits bl;
65 unsigned char *zeroblock;
66 /* The allocmap tracks which clusters (pages) on the iSCSI target are
67 * allocated and which are not. In case a target returns zeros for
68 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
69 * of reading zeros over the wire if a read request falls within an
70 * unallocated block. As there are 3 possible states we need 2 bitmaps to
71 * track. allocmap_valid keeps track if QEMU's information about a page is
72 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
73 * valid information about a page the corresponding allocmap entry should be
74 * switched to unallocated as well to force a new lookup of the allocation
75 * status as lookups are generally skipped if a page is suspect to be
76 * allocated. If a iSCSI target is opened with cache.direct = on the
77 * allocmap_valid does not exist turning all cached information invalid so
78 * that a fresh lookup is made for any page even if allocmap entry returns
79 * it's unallocated. */
80 unsigned long *allocmap;
81 unsigned long *allocmap_valid;
90 bool request_timed_out;
93 typedef struct IscsiTask {
98 struct scsi_task *task;
101 QEMUTimer retry_timer;
105 typedef struct IscsiAIOCB {
109 struct scsi_task *task;
120 /* libiscsi uses time_t so its enough to process events every second */
121 #define EVENT_INTERVAL 1000
122 #define NOP_INTERVAL 5000
123 #define MAX_NOP_FAILURES 3
124 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
125 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
127 /* this threshold is a trade-off knob to choose between
128 * the potential additional overhead of an extra GET_LBA_STATUS request
129 * vs. unnecessarily reading a lot of zero sectors over the wire.
130 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
131 * sectors we check the allocation status of the area covered by the
132 * request first if the allocationmap indicates that the area might be
134 #define ISCSI_CHECKALLOC_THRES 64
141 qemu_bh_delete(acb->bh);
146 acb->common.cb(acb->common.opaque, acb->status);
148 if (acb->task != NULL) {
149 scsi_free_scsi_task(acb->task);
157 iscsi_schedule_bh(IscsiAIOCB *acb)
162 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
163 qemu_bh_schedule(acb->bh);
166 static void iscsi_co_generic_bh_cb(void *opaque)
168 struct IscsiTask *iTask = opaque;
171 aio_co_wake(iTask->co);
174 static void iscsi_retry_timer_expired(void *opaque)
176 struct IscsiTask *iTask = opaque;
179 aio_co_wake(iTask->co);
183 static inline unsigned exp_random(double mean)
185 return -mean * log((double)rand() / RAND_MAX);
188 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
189 * libiscsi 1.10.0, together with other constants we need. Use it as
190 * a hint that we have to define them ourselves if needed, to keep the
191 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
192 * the test because SCSI_STATUS_* is an enum.
194 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
195 * an enum, check against the LIBISCSI_API_VERSION macro, which was
196 * introduced in 1.11.0. If it is present, there is no need to define
199 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
200 !defined(LIBISCSI_API_VERSION)
201 #define SCSI_STATUS_TASK_SET_FULL 0x28
202 #define SCSI_STATUS_TIMEOUT 0x0f000002
203 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
204 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
207 #ifndef LIBISCSI_API_VERSION
208 #define LIBISCSI_API_VERSION 20130701
211 static int iscsi_translate_sense(struct scsi_sense *sense)
213 return - scsi_sense_to_errno(sense->key,
214 (sense->ascq & 0xFF00) >> 8,
218 /* Called (via iscsi_service) with QemuMutex held. */
220 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
221 void *command_data, void *opaque)
223 struct IscsiTask *iTask = opaque;
224 struct scsi_task *task = command_data;
226 iTask->status = status;
230 if (status != SCSI_STATUS_GOOD) {
231 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
232 if (status == SCSI_STATUS_CHECK_CONDITION
233 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
234 error_report("iSCSI CheckCondition: %s",
235 iscsi_get_error(iscsi));
239 if (status == SCSI_STATUS_BUSY ||
240 status == SCSI_STATUS_TIMEOUT ||
241 status == SCSI_STATUS_TASK_SET_FULL) {
242 unsigned retry_time =
243 exp_random(iscsi_retry_times[iTask->retries - 1]);
244 if (status == SCSI_STATUS_TIMEOUT) {
245 /* make sure the request is rescheduled AFTER the
246 * reconnect is initiated */
247 retry_time = EVENT_INTERVAL * 2;
248 iTask->iscsilun->request_timed_out = true;
250 error_report("iSCSI Busy/TaskSetFull/TimeOut"
251 " (retry #%u in %u ms): %s",
252 iTask->retries, retry_time,
253 iscsi_get_error(iscsi));
254 aio_timer_init(iTask->iscsilun->aio_context,
255 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
256 SCALE_MS, iscsi_retry_timer_expired, iTask);
257 timer_mod(&iTask->retry_timer,
258 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
263 iTask->err_code = iscsi_translate_sense(&task->sense);
264 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
269 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
270 iscsi_co_generic_bh_cb, iTask);
276 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
278 *iTask = (struct IscsiTask) {
279 .co = qemu_coroutine_self(),
280 .iscsilun = iscsilun,
285 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
288 IscsiAIOCB *acb = private_data;
290 acb->status = -ECANCELED;
291 iscsi_schedule_bh(acb);
295 iscsi_aio_cancel(BlockAIOCB *blockacb)
297 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
298 IscsiLun *iscsilun = acb->iscsilun;
300 if (acb->status != -EINPROGRESS) {
304 /* send a task mgmt call to the target to cancel the task on the target */
305 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
306 iscsi_abort_task_cb, acb);
310 static const AIOCBInfo iscsi_aiocb_info = {
311 .aiocb_size = sizeof(IscsiAIOCB),
312 .cancel_async = iscsi_aio_cancel,
316 static void iscsi_process_read(void *arg);
317 static void iscsi_process_write(void *arg);
319 /* Called with QemuMutex held. */
321 iscsi_set_events(IscsiLun *iscsilun)
323 struct iscsi_context *iscsi = iscsilun->iscsi;
324 int ev = iscsi_which_events(iscsi);
326 if (ev != iscsilun->events) {
327 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
329 (ev & POLLIN) ? iscsi_process_read : NULL,
330 (ev & POLLOUT) ? iscsi_process_write : NULL,
333 iscsilun->events = ev;
337 static void iscsi_timed_check_events(void *opaque)
339 IscsiLun *iscsilun = opaque;
341 /* check for timed out requests */
342 iscsi_service(iscsilun->iscsi, 0);
344 if (iscsilun->request_timed_out) {
345 iscsilun->request_timed_out = false;
346 iscsi_reconnect(iscsilun->iscsi);
349 /* newer versions of libiscsi may return zero events. Ensure we are able
350 * to return to service once this situation changes. */
351 iscsi_set_events(iscsilun);
353 timer_mod(iscsilun->event_timer,
354 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
358 iscsi_process_read(void *arg)
360 IscsiLun *iscsilun = arg;
361 struct iscsi_context *iscsi = iscsilun->iscsi;
363 qemu_mutex_lock(&iscsilun->mutex);
364 iscsi_service(iscsi, POLLIN);
365 iscsi_set_events(iscsilun);
366 qemu_mutex_unlock(&iscsilun->mutex);
370 iscsi_process_write(void *arg)
372 IscsiLun *iscsilun = arg;
373 struct iscsi_context *iscsi = iscsilun->iscsi;
375 qemu_mutex_lock(&iscsilun->mutex);
376 iscsi_service(iscsi, POLLOUT);
377 iscsi_set_events(iscsilun);
378 qemu_mutex_unlock(&iscsilun->mutex);
381 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
383 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
386 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
388 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
391 static bool is_byte_request_lun_aligned(int64_t offset, int count,
394 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
395 error_report("iSCSI misaligned request: "
396 "iscsilun->block_size %u, offset %" PRIi64
398 iscsilun->block_size, offset, count);
404 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
407 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
408 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
409 nb_sectors << BDRV_SECTOR_BITS,
413 static void iscsi_allocmap_free(IscsiLun *iscsilun)
415 g_free(iscsilun->allocmap);
416 g_free(iscsilun->allocmap_valid);
417 iscsilun->allocmap = NULL;
418 iscsilun->allocmap_valid = NULL;
422 static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
424 iscsi_allocmap_free(iscsilun);
426 iscsilun->allocmap_size =
427 DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks, iscsilun),
428 iscsilun->cluster_sectors);
430 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
431 if (!iscsilun->allocmap) {
435 if (open_flags & BDRV_O_NOCACHE) {
436 /* in case that cache.direct = on all allocmap entries are
437 * treated as invalid to force a relookup of the block
438 * status on every read request */
442 iscsilun->allocmap_valid = bitmap_try_new(iscsilun->allocmap_size);
443 if (!iscsilun->allocmap_valid) {
444 /* if we are under memory pressure free the allocmap as well */
445 iscsi_allocmap_free(iscsilun);
453 iscsi_allocmap_update(IscsiLun *iscsilun, int64_t sector_num,
454 int nb_sectors, bool allocated, bool valid)
456 int64_t cl_num_expanded, nb_cls_expanded, cl_num_shrunk, nb_cls_shrunk;
458 if (iscsilun->allocmap == NULL) {
461 /* expand to entirely contain all affected clusters */
462 cl_num_expanded = sector_num / iscsilun->cluster_sectors;
463 nb_cls_expanded = DIV_ROUND_UP(sector_num + nb_sectors,
464 iscsilun->cluster_sectors) - cl_num_expanded;
465 /* shrink to touch only completely contained clusters */
466 cl_num_shrunk = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
467 nb_cls_shrunk = (sector_num + nb_sectors) / iscsilun->cluster_sectors
470 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
472 if (nb_cls_shrunk > 0) {
473 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
477 if (iscsilun->allocmap_valid == NULL) {
481 if (nb_cls_shrunk > 0) {
482 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
485 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
491 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
494 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
498 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
501 /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
502 * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
504 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
507 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
510 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
513 static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
515 if (iscsilun->allocmap) {
516 bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
518 if (iscsilun->allocmap_valid) {
519 bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
524 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
528 if (iscsilun->allocmap == NULL) {
531 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
532 return !(find_next_bit(iscsilun->allocmap, size,
533 sector_num / iscsilun->cluster_sectors) == size);
536 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
537 int64_t sector_num, int nb_sectors)
540 if (iscsilun->allocmap_valid == NULL) {
543 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
544 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
545 sector_num / iscsilun->cluster_sectors) == size);
548 static int coroutine_fn
549 iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
550 QEMUIOVector *iov, int flags)
552 IscsiLun *iscsilun = bs->opaque;
553 struct IscsiTask iTask;
555 uint32_t num_sectors;
556 bool fua = flags & BDRV_REQ_FUA;
560 assert(iscsilun->dpofua);
562 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
566 if (bs->bl.max_transfer) {
567 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
570 lba = sector_qemu2lun(sector_num, iscsilun);
571 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
572 iscsi_co_init_iscsitask(iscsilun, &iTask);
573 qemu_mutex_lock(&iscsilun->mutex);
575 if (iscsilun->use_16_for_rw) {
576 #if LIBISCSI_API_VERSION >= (20160603)
577 iTask.task = iscsi_write16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
578 NULL, num_sectors * iscsilun->block_size,
579 iscsilun->block_size, 0, 0, fua, 0, 0,
580 iscsi_co_generic_cb, &iTask,
581 (struct scsi_iovec *)iov->iov, iov->niov);
583 iTask.task = iscsi_write10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
584 NULL, num_sectors * iscsilun->block_size,
585 iscsilun->block_size, 0, 0, fua, 0, 0,
586 iscsi_co_generic_cb, &iTask,
587 (struct scsi_iovec *)iov->iov, iov->niov);
590 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
591 NULL, num_sectors * iscsilun->block_size,
592 iscsilun->block_size, 0, 0, fua, 0, 0,
593 iscsi_co_generic_cb, &iTask);
595 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
596 NULL, num_sectors * iscsilun->block_size,
597 iscsilun->block_size, 0, 0, fua, 0, 0,
598 iscsi_co_generic_cb, &iTask);
601 if (iTask.task == NULL) {
602 qemu_mutex_unlock(&iscsilun->mutex);
605 #if LIBISCSI_API_VERSION < (20160603)
606 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
609 while (!iTask.complete) {
610 iscsi_set_events(iscsilun);
611 qemu_mutex_unlock(&iscsilun->mutex);
612 qemu_coroutine_yield();
613 qemu_mutex_lock(&iscsilun->mutex);
616 if (iTask.task != NULL) {
617 scsi_free_scsi_task(iTask.task);
621 if (iTask.do_retry) {
626 if (iTask.status != SCSI_STATUS_GOOD) {
627 iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
632 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
635 qemu_mutex_unlock(&iscsilun->mutex);
641 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
643 int nb_sectors, int *pnum,
644 BlockDriverState **file)
646 IscsiLun *iscsilun = bs->opaque;
647 struct scsi_get_lba_status *lbas = NULL;
648 struct scsi_lba_status_descriptor *lbasd = NULL;
649 struct IscsiTask iTask;
652 iscsi_co_init_iscsitask(iscsilun, &iTask);
654 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
659 /* default to all sectors allocated */
660 ret = BDRV_BLOCK_DATA;
661 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
664 /* LUN does not support logical block provisioning */
665 if (!iscsilun->lbpme) {
669 qemu_mutex_lock(&iscsilun->mutex);
671 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
672 sector_qemu2lun(sector_num, iscsilun),
673 8 + 16, iscsi_co_generic_cb,
679 while (!iTask.complete) {
680 iscsi_set_events(iscsilun);
681 qemu_mutex_unlock(&iscsilun->mutex);
682 qemu_coroutine_yield();
683 qemu_mutex_lock(&iscsilun->mutex);
686 if (iTask.do_retry) {
687 if (iTask.task != NULL) {
688 scsi_free_scsi_task(iTask.task);
695 if (iTask.status != SCSI_STATUS_GOOD) {
696 /* in case the get_lba_status_callout fails (i.e.
697 * because the device is busy or the cmd is not
698 * supported) we pretend all blocks are allocated
699 * for backwards compatibility */
703 lbas = scsi_datain_unmarshall(iTask.task);
709 lbasd = &lbas->descriptors[0];
711 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
716 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
718 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
719 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
720 ret &= ~BDRV_BLOCK_DATA;
721 if (iscsilun->lbprz) {
722 ret |= BDRV_BLOCK_ZERO;
726 if (ret & BDRV_BLOCK_ZERO) {
727 iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
729 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
732 if (*pnum > nb_sectors) {
736 qemu_mutex_unlock(&iscsilun->mutex);
738 if (iTask.task != NULL) {
739 scsi_free_scsi_task(iTask.task);
741 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
747 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
748 int64_t sector_num, int nb_sectors,
751 IscsiLun *iscsilun = bs->opaque;
752 struct IscsiTask iTask;
754 uint32_t num_sectors;
756 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
760 if (bs->bl.max_transfer) {
761 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
764 /* if cache.direct is off and we have a valid entry in our allocation map
765 * we can skip checking the block status and directly return zeroes if
766 * the request falls within an unallocated area */
767 if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
768 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
769 qemu_iovec_memset(iov, 0, 0x00, iov->size);
773 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
774 !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
775 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
777 BlockDriverState *file;
778 /* check the block status from the beginning of the cluster
779 * containing the start sector */
780 int64_t ret = iscsi_co_get_block_status(bs,
781 sector_num - sector_num % iscsilun->cluster_sectors,
782 BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
786 /* if the whole request falls into an unallocated area we can avoid
787 * to read and directly return zeroes instead */
788 if (ret & BDRV_BLOCK_ZERO &&
789 pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
790 qemu_iovec_memset(iov, 0, 0x00, iov->size);
795 lba = sector_qemu2lun(sector_num, iscsilun);
796 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
798 iscsi_co_init_iscsitask(iscsilun, &iTask);
799 qemu_mutex_lock(&iscsilun->mutex);
801 if (iscsilun->use_16_for_rw) {
802 #if LIBISCSI_API_VERSION >= (20160603)
803 iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
804 num_sectors * iscsilun->block_size,
805 iscsilun->block_size, 0, 0, 0, 0, 0,
806 iscsi_co_generic_cb, &iTask,
807 (struct scsi_iovec *)iov->iov, iov->niov);
809 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
810 num_sectors * iscsilun->block_size,
811 iscsilun->block_size,
813 iscsi_co_generic_cb, &iTask,
814 (struct scsi_iovec *)iov->iov, iov->niov);
817 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
818 num_sectors * iscsilun->block_size,
819 iscsilun->block_size, 0, 0, 0, 0, 0,
820 iscsi_co_generic_cb, &iTask);
822 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
823 num_sectors * iscsilun->block_size,
824 iscsilun->block_size,
826 iscsi_co_generic_cb, &iTask);
829 if (iTask.task == NULL) {
830 qemu_mutex_unlock(&iscsilun->mutex);
833 #if LIBISCSI_API_VERSION < (20160603)
834 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
836 while (!iTask.complete) {
837 iscsi_set_events(iscsilun);
838 qemu_mutex_unlock(&iscsilun->mutex);
839 qemu_coroutine_yield();
840 qemu_mutex_lock(&iscsilun->mutex);
843 if (iTask.task != NULL) {
844 scsi_free_scsi_task(iTask.task);
848 if (iTask.do_retry) {
852 qemu_mutex_unlock(&iscsilun->mutex);
854 if (iTask.status != SCSI_STATUS_GOOD) {
855 return iTask.err_code;
861 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
863 IscsiLun *iscsilun = bs->opaque;
864 struct IscsiTask iTask;
866 iscsi_co_init_iscsitask(iscsilun, &iTask);
867 qemu_mutex_lock(&iscsilun->mutex);
869 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
870 0, iscsi_co_generic_cb, &iTask) == NULL) {
871 qemu_mutex_unlock(&iscsilun->mutex);
875 while (!iTask.complete) {
876 iscsi_set_events(iscsilun);
877 qemu_mutex_unlock(&iscsilun->mutex);
878 qemu_coroutine_yield();
879 qemu_mutex_lock(&iscsilun->mutex);
882 if (iTask.task != NULL) {
883 scsi_free_scsi_task(iTask.task);
887 if (iTask.do_retry) {
891 qemu_mutex_unlock(&iscsilun->mutex);
893 if (iTask.status != SCSI_STATUS_GOOD) {
894 return iTask.err_code;
901 /* Called (via iscsi_service) with QemuMutex held. */
903 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
904 void *command_data, void *opaque)
906 IscsiAIOCB *acb = opaque;
913 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
914 iscsi_get_error(iscsi));
915 acb->status = iscsi_translate_sense(&acb->task->sense);
918 acb->ioh->driver_status = 0;
919 acb->ioh->host_status = 0;
921 acb->ioh->status = status;
923 #define SG_ERR_DRIVER_SENSE 0x08
925 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
928 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
930 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
931 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
932 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
933 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
936 iscsi_schedule_bh(acb);
939 static void iscsi_ioctl_bh_completion(void *opaque)
941 IscsiAIOCB *acb = opaque;
943 qemu_bh_delete(acb->bh);
944 acb->common.cb(acb->common.opaque, acb->ret);
948 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
950 BlockDriverState *bs = acb->common.bs;
951 IscsiLun *iscsilun = bs->opaque;
955 case SG_GET_VERSION_NUM:
959 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
965 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
966 iscsi_ioctl_bh_completion, acb);
968 qemu_bh_schedule(acb->bh);
971 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
972 unsigned long int req, void *buf,
973 BlockCompletionFunc *cb, void *opaque)
975 IscsiLun *iscsilun = bs->opaque;
976 struct iscsi_context *iscsi = iscsilun->iscsi;
977 struct iscsi_data data;
980 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
982 acb->iscsilun = iscsilun;
984 acb->status = -EINPROGRESS;
989 iscsi_ioctl_handle_emulated(acb, req, buf);
993 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
994 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
995 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1000 acb->task = malloc(sizeof(struct scsi_task));
1001 if (acb->task == NULL) {
1002 error_report("iSCSI: Failed to allocate task for scsi command. %s",
1003 iscsi_get_error(iscsi));
1004 qemu_aio_unref(acb);
1007 memset(acb->task, 0, sizeof(struct scsi_task));
1009 switch (acb->ioh->dxfer_direction) {
1010 case SG_DXFER_TO_DEV:
1011 acb->task->xfer_dir = SCSI_XFER_WRITE;
1013 case SG_DXFER_FROM_DEV:
1014 acb->task->xfer_dir = SCSI_XFER_READ;
1017 acb->task->xfer_dir = SCSI_XFER_NONE;
1021 acb->task->cdb_size = acb->ioh->cmd_len;
1022 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1023 acb->task->expxferlen = acb->ioh->dxfer_len;
1026 qemu_mutex_lock(&iscsilun->mutex);
1027 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
1028 if (acb->ioh->iovec_count == 0) {
1029 data.data = acb->ioh->dxferp;
1030 data.size = acb->ioh->dxfer_len;
1032 scsi_task_set_iov_out(acb->task,
1033 (struct scsi_iovec *) acb->ioh->dxferp,
1034 acb->ioh->iovec_count);
1038 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1040 (data.size > 0) ? &data : NULL,
1042 qemu_mutex_unlock(&iscsilun->mutex);
1043 scsi_free_scsi_task(acb->task);
1044 qemu_aio_unref(acb);
1048 /* tell libiscsi to read straight into the buffer we got from ioctl */
1049 if (acb->task->xfer_dir == SCSI_XFER_READ) {
1050 if (acb->ioh->iovec_count == 0) {
1051 scsi_task_add_data_in_buffer(acb->task,
1052 acb->ioh->dxfer_len,
1055 scsi_task_set_iov_in(acb->task,
1056 (struct scsi_iovec *) acb->ioh->dxferp,
1057 acb->ioh->iovec_count);
1061 iscsi_set_events(iscsilun);
1062 qemu_mutex_unlock(&iscsilun->mutex);
1064 return &acb->common;
1070 iscsi_getlength(BlockDriverState *bs)
1072 IscsiLun *iscsilun = bs->opaque;
1075 len = iscsilun->num_blocks;
1076 len *= iscsilun->block_size;
1082 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
1084 IscsiLun *iscsilun = bs->opaque;
1085 struct IscsiTask iTask;
1086 struct unmap_list list;
1089 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1093 if (!iscsilun->lbp.lbpu) {
1094 /* UNMAP is not supported by the target */
1098 list.lba = offset / iscsilun->block_size;
1099 list.num = bytes / iscsilun->block_size;
1101 iscsi_co_init_iscsitask(iscsilun, &iTask);
1102 qemu_mutex_lock(&iscsilun->mutex);
1104 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1105 iscsi_co_generic_cb, &iTask) == NULL) {
1110 while (!iTask.complete) {
1111 iscsi_set_events(iscsilun);
1112 qemu_mutex_unlock(&iscsilun->mutex);
1113 qemu_coroutine_yield();
1114 qemu_mutex_lock(&iscsilun->mutex);
1117 if (iTask.task != NULL) {
1118 scsi_free_scsi_task(iTask.task);
1122 if (iTask.do_retry) {
1127 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1128 /* the target might fail with a check condition if it
1129 is not happy with the alignment of the UNMAP request
1130 we silently fail in this case */
1134 if (iTask.status != SCSI_STATUS_GOOD) {
1139 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1140 bytes >> BDRV_SECTOR_BITS);
1143 qemu_mutex_unlock(&iscsilun->mutex);
1148 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1149 int bytes, BdrvRequestFlags flags)
1151 IscsiLun *iscsilun = bs->opaque;
1152 struct IscsiTask iTask;
1155 bool use_16_for_ws = iscsilun->use_16_for_rw;
1158 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1162 if (flags & BDRV_REQ_MAY_UNMAP) {
1163 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1164 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1165 use_16_for_ws = true;
1167 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1168 /* WRITESAME16 with UNMAP is not supported by the target,
1169 * fall back and try WRITESAME10/16 without UNMAP */
1170 flags &= ~BDRV_REQ_MAY_UNMAP;
1171 use_16_for_ws = iscsilun->use_16_for_rw;
1175 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1176 /* WRITESAME without UNMAP is not supported by the target */
1180 lba = offset / iscsilun->block_size;
1181 nb_blocks = bytes / iscsilun->block_size;
1183 if (iscsilun->zeroblock == NULL) {
1184 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1185 if (iscsilun->zeroblock == NULL) {
1190 qemu_mutex_lock(&iscsilun->mutex);
1191 iscsi_co_init_iscsitask(iscsilun, &iTask);
1193 if (use_16_for_ws) {
1194 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1195 iscsilun->zeroblock, iscsilun->block_size,
1196 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1197 0, 0, iscsi_co_generic_cb, &iTask);
1199 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1200 iscsilun->zeroblock, iscsilun->block_size,
1201 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1202 0, 0, iscsi_co_generic_cb, &iTask);
1204 if (iTask.task == NULL) {
1205 qemu_mutex_unlock(&iscsilun->mutex);
1209 while (!iTask.complete) {
1210 iscsi_set_events(iscsilun);
1211 qemu_mutex_unlock(&iscsilun->mutex);
1212 qemu_coroutine_yield();
1213 qemu_mutex_lock(&iscsilun->mutex);
1216 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1217 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1218 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1219 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1220 /* WRITE SAME is not supported by the target */
1221 iscsilun->has_write_same = false;
1222 scsi_free_scsi_task(iTask.task);
1227 if (iTask.task != NULL) {
1228 scsi_free_scsi_task(iTask.task);
1232 if (iTask.do_retry) {
1237 if (iTask.status != SCSI_STATUS_GOOD) {
1238 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1239 bytes >> BDRV_SECTOR_BITS);
1244 if (flags & BDRV_REQ_MAY_UNMAP) {
1245 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1246 bytes >> BDRV_SECTOR_BITS);
1248 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1249 bytes >> BDRV_SECTOR_BITS);
1253 qemu_mutex_unlock(&iscsilun->mutex);
1257 static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
1260 const char *user = NULL;
1261 const char *password = NULL;
1262 const char *secretid;
1263 char *secret = NULL;
1265 user = qemu_opt_get(opts, "user");
1270 secretid = qemu_opt_get(opts, "password-secret");
1271 password = qemu_opt_get(opts, "password");
1272 if (secretid && password) {
1273 error_setg(errp, "'password' and 'password-secret' properties are "
1274 "mutually exclusive");
1278 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1283 } else if (!password) {
1284 error_setg(errp, "CHAP username specified but no password was given");
1288 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1289 error_setg(errp, "Failed to set initiator username and password");
1295 static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
1298 const char *digest = NULL;
1300 digest = qemu_opt_get(opts, "header-digest");
1302 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1303 } else if (!strcmp(digest, "crc32c")) {
1304 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1305 } else if (!strcmp(digest, "none")) {
1306 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1307 } else if (!strcmp(digest, "crc32c-none")) {
1308 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1309 } else if (!strcmp(digest, "none-crc32c")) {
1310 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1312 error_setg(errp, "Invalid header-digest setting : %s", digest);
1316 static char *get_initiator_name(QemuOpts *opts)
1320 UuidInfo *uuid_info;
1322 name = qemu_opt_get(opts, "initiator-name");
1324 return g_strdup(name);
1327 uuid_info = qmp_query_uuid(NULL);
1328 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1329 name = qemu_get_vm_name();
1331 name = uuid_info->UUID;
1333 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1334 name ? ":" : "", name ? name : "");
1335 qapi_free_UuidInfo(uuid_info);
1339 static void iscsi_nop_timed_event(void *opaque)
1341 IscsiLun *iscsilun = opaque;
1343 qemu_mutex_lock(&iscsilun->mutex);
1344 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1345 error_report("iSCSI: NOP timeout. Reconnecting...");
1346 iscsilun->request_timed_out = true;
1347 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1348 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1352 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1353 iscsi_set_events(iscsilun);
1356 qemu_mutex_unlock(&iscsilun->mutex);
1359 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1361 struct scsi_task *task = NULL;
1362 struct scsi_readcapacity10 *rc10 = NULL;
1363 struct scsi_readcapacity16 *rc16 = NULL;
1364 int retries = ISCSI_CMD_RETRIES;
1368 scsi_free_scsi_task(task);
1372 switch (iscsilun->type) {
1374 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1375 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1376 rc16 = scsi_datain_unmarshall(task);
1378 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1380 iscsilun->block_size = rc16->block_length;
1381 iscsilun->num_blocks = rc16->returned_lba + 1;
1382 iscsilun->lbpme = !!rc16->lbpme;
1383 iscsilun->lbprz = !!rc16->lbprz;
1384 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1388 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1389 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1392 /* Fall through and try READ CAPACITY(10) instead. */
1394 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1395 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1396 rc10 = scsi_datain_unmarshall(task);
1398 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1400 iscsilun->block_size = rc10->block_size;
1401 if (rc10->lba == 0) {
1402 /* blank disk loaded */
1403 iscsilun->num_blocks = 0;
1405 iscsilun->num_blocks = rc10->lba + 1;
1413 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1414 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1417 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1418 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1419 } else if (!iscsilun->block_size ||
1420 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1421 error_setg(errp, "iSCSI: the target returned an invalid "
1422 "block size of %d.", iscsilun->block_size);
1425 scsi_free_scsi_task(task);
1429 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1430 int evpd, int pc, void **inq, Error **errp)
1433 struct scsi_task *task = NULL;
1434 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1435 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1438 full_size = scsi_datain_getfullsize(task);
1439 if (full_size > task->datain.size) {
1440 scsi_free_scsi_task(task);
1442 /* we need more data for the full list */
1443 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1444 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1449 *inq = scsi_datain_unmarshall(task);
1451 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1458 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1459 iscsi_get_error(iscsi));
1462 scsi_free_scsi_task(task);
1467 static void iscsi_detach_aio_context(BlockDriverState *bs)
1469 IscsiLun *iscsilun = bs->opaque;
1471 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1472 false, NULL, NULL, NULL, NULL);
1473 iscsilun->events = 0;
1475 if (iscsilun->nop_timer) {
1476 timer_del(iscsilun->nop_timer);
1477 timer_free(iscsilun->nop_timer);
1478 iscsilun->nop_timer = NULL;
1480 if (iscsilun->event_timer) {
1481 timer_del(iscsilun->event_timer);
1482 timer_free(iscsilun->event_timer);
1483 iscsilun->event_timer = NULL;
1487 static void iscsi_attach_aio_context(BlockDriverState *bs,
1488 AioContext *new_context)
1490 IscsiLun *iscsilun = bs->opaque;
1492 iscsilun->aio_context = new_context;
1493 iscsi_set_events(iscsilun);
1495 /* Set up a timer for sending out iSCSI NOPs */
1496 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1497 QEMU_CLOCK_REALTIME, SCALE_MS,
1498 iscsi_nop_timed_event, iscsilun);
1499 timer_mod(iscsilun->nop_timer,
1500 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1502 /* Set up a timer for periodic calls to iscsi_set_events and to
1503 * scan for command timeout */
1504 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1505 QEMU_CLOCK_REALTIME, SCALE_MS,
1506 iscsi_timed_check_events, iscsilun);
1507 timer_mod(iscsilun->event_timer,
1508 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1511 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1513 struct scsi_task *task;
1514 struct scsi_mode_sense *ms = NULL;
1515 iscsilun->write_protected = false;
1516 iscsilun->dpofua = false;
1518 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1519 1, SCSI_MODESENSE_PC_CURRENT,
1522 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1523 iscsi_get_error(iscsilun->iscsi));
1527 if (task->status != SCSI_STATUS_GOOD) {
1528 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1531 ms = scsi_datain_unmarshall(task);
1533 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1534 iscsi_get_error(iscsilun->iscsi));
1537 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1538 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1542 scsi_free_scsi_task(task);
1546 static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1550 const char *user, *password, *password_secret, *initiator_name,
1551 *header_digest, *timeout;
1553 list = qemu_find_opts("iscsi");
1558 opts = qemu_opts_find(list, target);
1560 opts = QTAILQ_FIRST(&list->head);
1566 user = qemu_opt_get(opts, "user");
1568 qdict_set_default_str(options, "user", user);
1571 password = qemu_opt_get(opts, "password");
1573 qdict_set_default_str(options, "password", password);
1576 password_secret = qemu_opt_get(opts, "password-secret");
1577 if (password_secret) {
1578 qdict_set_default_str(options, "password-secret", password_secret);
1581 initiator_name = qemu_opt_get(opts, "initiator-name");
1582 if (initiator_name) {
1583 qdict_set_default_str(options, "initiator-name", initiator_name);
1586 header_digest = qemu_opt_get(opts, "header-digest");
1587 if (header_digest) {
1588 /* -iscsi takes upper case values, but QAPI only supports lower case
1589 * enum constant names, so we have to convert here. */
1590 char *qapi_value = g_ascii_strdown(header_digest, -1);
1591 qdict_set_default_str(options, "header-digest", qapi_value);
1595 timeout = qemu_opt_get(opts, "timeout");
1597 qdict_set_default_str(options, "timeout", timeout);
1602 * We support iscsi url's on the form
1603 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1605 static void iscsi_parse_filename(const char *filename, QDict *options,
1608 struct iscsi_url *iscsi_url;
1609 const char *transport_name;
1612 iscsi_url = iscsi_parse_full_url(NULL, filename);
1613 if (iscsi_url == NULL) {
1614 error_setg(errp, "Failed to parse URL : %s", filename);
1618 #if LIBISCSI_API_VERSION >= (20160603)
1619 switch (iscsi_url->transport) {
1621 transport_name = "tcp";
1623 case ISER_TRANSPORT:
1624 transport_name = "iser";
1627 error_setg(errp, "Unknown transport type (%d)",
1628 iscsi_url->transport);
1632 transport_name = "tcp";
1635 qdict_set_default_str(options, "transport", transport_name);
1636 qdict_set_default_str(options, "portal", iscsi_url->portal);
1637 qdict_set_default_str(options, "target", iscsi_url->target);
1639 lun_str = g_strdup_printf("%d", iscsi_url->lun);
1640 qdict_set_default_str(options, "lun", lun_str);
1643 /* User/password from -iscsi take precedence over those from the URL */
1644 iscsi_parse_iscsi_option(iscsi_url->target, options);
1646 if (iscsi_url->user[0] != '\0') {
1647 qdict_set_default_str(options, "user", iscsi_url->user);
1648 qdict_set_default_str(options, "password", iscsi_url->passwd);
1651 iscsi_destroy_url(iscsi_url);
1654 static QemuOptsList runtime_opts = {
1656 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1659 .name = "transport",
1660 .type = QEMU_OPT_STRING,
1664 .type = QEMU_OPT_STRING,
1668 .type = QEMU_OPT_STRING,
1672 .type = QEMU_OPT_STRING,
1676 .type = QEMU_OPT_STRING,
1679 .name = "password-secret",
1680 .type = QEMU_OPT_STRING,
1684 .type = QEMU_OPT_NUMBER,
1687 .name = "initiator-name",
1688 .type = QEMU_OPT_STRING,
1691 .name = "header-digest",
1692 .type = QEMU_OPT_STRING,
1696 .type = QEMU_OPT_NUMBER,
1700 .type = QEMU_OPT_STRING,
1702 { /* end of list */ }
1706 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1709 IscsiLun *iscsilun = bs->opaque;
1710 struct iscsi_context *iscsi = NULL;
1711 struct scsi_task *task = NULL;
1712 struct scsi_inquiry_standard *inq = NULL;
1713 struct scsi_inquiry_supported_pages *inq_vpd;
1714 char *initiator_name = NULL;
1716 Error *local_err = NULL;
1717 const char *transport_name, *portal, *target, *filename;
1718 #if LIBISCSI_API_VERSION >= (20160603)
1719 enum iscsi_transport_type transport;
1721 int i, ret = 0, timeout = 0, lun;
1723 /* If we are given a filename, parse the filename, with precedence given to
1724 * filename encoded options */
1725 filename = qdict_get_try_str(options, "filename");
1727 warn_report("'filename' option specified. "
1728 "This is an unsupported option, and may be deprecated "
1730 iscsi_parse_filename(filename, options, &local_err);
1733 error_propagate(errp, local_err);
1738 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1739 qemu_opts_absorb_qdict(opts, options, &local_err);
1741 error_propagate(errp, local_err);
1746 transport_name = qemu_opt_get(opts, "transport");
1747 portal = qemu_opt_get(opts, "portal");
1748 target = qemu_opt_get(opts, "target");
1749 lun = qemu_opt_get_number(opts, "lun", 0);
1751 if (!transport_name || !portal || !target) {
1752 error_setg(errp, "Need all of transport, portal and target options");
1757 if (!strcmp(transport_name, "tcp")) {
1758 #if LIBISCSI_API_VERSION >= (20160603)
1759 transport = TCP_TRANSPORT;
1760 } else if (!strcmp(transport_name, "iser")) {
1761 transport = ISER_TRANSPORT;
1763 /* TCP is what older libiscsi versions always use */
1766 error_setg(errp, "Unknown transport: %s", transport_name);
1771 memset(iscsilun, 0, sizeof(IscsiLun));
1773 initiator_name = get_initiator_name(opts);
1775 iscsi = iscsi_create_context(initiator_name);
1776 if (iscsi == NULL) {
1777 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1781 #if LIBISCSI_API_VERSION >= (20160603)
1782 if (iscsi_init_transport(iscsi, transport)) {
1783 error_setg(errp, ("Error initializing transport."));
1788 if (iscsi_set_targetname(iscsi, target)) {
1789 error_setg(errp, "iSCSI: Failed to set target name.");
1794 /* check if we got CHAP username/password via the options */
1795 apply_chap(iscsi, opts, &local_err);
1796 if (local_err != NULL) {
1797 error_propagate(errp, local_err);
1802 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1803 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1808 /* check if we got HEADER_DIGEST via the options */
1809 apply_header_digest(iscsi, opts, &local_err);
1810 if (local_err != NULL) {
1811 error_propagate(errp, local_err);
1816 /* timeout handling is broken in libiscsi before 1.15.0 */
1817 timeout = qemu_opt_get_number(opts, "timeout", 0);
1818 #if LIBISCSI_API_VERSION >= 20150621
1819 iscsi_set_timeout(iscsi, timeout);
1822 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1826 if (iscsi_full_connect_sync(iscsi, portal, lun) != 0) {
1827 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1828 iscsi_get_error(iscsi));
1833 iscsilun->iscsi = iscsi;
1834 iscsilun->aio_context = bdrv_get_aio_context(bs);
1835 iscsilun->lun = lun;
1836 iscsilun->has_write_same = true;
1838 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1839 (void **) &inq, errp);
1844 iscsilun->type = inq->periperal_device_type;
1845 scsi_free_scsi_task(task);
1848 iscsi_modesense_sync(iscsilun);
1849 if (iscsilun->dpofua) {
1850 bs->supported_write_flags = BDRV_REQ_FUA;
1852 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1854 /* Check the write protect flag of the LUN if we want to write */
1855 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1856 iscsilun->write_protected) {
1857 error_setg(errp, "Cannot open a write protected LUN as read-write");
1862 iscsi_readcapacity_sync(iscsilun, &local_err);
1863 if (local_err != NULL) {
1864 error_propagate(errp, local_err);
1868 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1870 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1871 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1872 * will try to read from the device to guess the image format.
1874 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1878 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1879 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1880 (void **) &inq_vpd, errp);
1885 for (i = 0; i < inq_vpd->num_pages; i++) {
1886 struct scsi_task *inq_task;
1887 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1888 struct scsi_inquiry_block_limits *inq_bl;
1889 switch (inq_vpd->pages[i]) {
1890 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1891 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1892 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1893 (void **) &inq_lbp, errp);
1894 if (inq_task == NULL) {
1898 memcpy(&iscsilun->lbp, inq_lbp,
1899 sizeof(struct scsi_inquiry_logical_block_provisioning));
1900 scsi_free_scsi_task(inq_task);
1902 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1903 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1904 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1905 (void **) &inq_bl, errp);
1906 if (inq_task == NULL) {
1910 memcpy(&iscsilun->bl, inq_bl,
1911 sizeof(struct scsi_inquiry_block_limits));
1912 scsi_free_scsi_task(inq_task);
1918 scsi_free_scsi_task(task);
1921 qemu_mutex_init(&iscsilun->mutex);
1922 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1924 /* Guess the internal cluster (page) size of the iscsi target by the means
1925 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1926 * reasonable size */
1927 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1928 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1929 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1930 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1931 if (iscsilun->lbprz) {
1932 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1937 qemu_opts_del(opts);
1938 g_free(initiator_name);
1940 scsi_free_scsi_task(task);
1944 if (iscsi != NULL) {
1945 if (iscsi_is_logged_in(iscsi)) {
1946 iscsi_logout_sync(iscsi);
1948 iscsi_destroy_context(iscsi);
1950 memset(iscsilun, 0, sizeof(IscsiLun));
1956 static void iscsi_close(BlockDriverState *bs)
1958 IscsiLun *iscsilun = bs->opaque;
1959 struct iscsi_context *iscsi = iscsilun->iscsi;
1961 iscsi_detach_aio_context(bs);
1962 if (iscsi_is_logged_in(iscsi)) {
1963 iscsi_logout_sync(iscsi);
1965 iscsi_destroy_context(iscsi);
1966 g_free(iscsilun->zeroblock);
1967 iscsi_allocmap_free(iscsilun);
1968 qemu_mutex_destroy(&iscsilun->mutex);
1969 memset(iscsilun, 0, sizeof(IscsiLun));
1972 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1974 /* We don't actually refresh here, but just return data queried in
1975 * iscsi_open(): iscsi targets don't change their limits. */
1977 IscsiLun *iscsilun = bs->opaque;
1978 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1979 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
1981 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
1983 bs->bl.request_alignment = block_size;
1985 if (iscsilun->bl.max_xfer_len) {
1986 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1989 if (max_xfer_len * block_size < INT_MAX) {
1990 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
1993 if (iscsilun->lbp.lbpu) {
1994 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
1995 bs->bl.max_pdiscard =
1996 iscsilun->bl.max_unmap * iscsilun->block_size;
1998 bs->bl.pdiscard_alignment =
1999 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2001 bs->bl.pdiscard_alignment = iscsilun->block_size;
2004 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
2005 bs->bl.max_pwrite_zeroes =
2006 iscsilun->bl.max_ws_len * iscsilun->block_size;
2008 if (iscsilun->lbp.lbpws) {
2009 bs->bl.pwrite_zeroes_alignment =
2010 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2012 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
2014 if (iscsilun->bl.opt_xfer_len &&
2015 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
2016 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
2017 iscsilun->block_size);
2021 /* Note that this will not re-establish a connection with an iSCSI target - it
2022 * is effectively a NOP. */
2023 static int iscsi_reopen_prepare(BDRVReopenState *state,
2024 BlockReopenQueue *queue, Error **errp)
2026 IscsiLun *iscsilun = state->bs->opaque;
2028 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
2029 error_setg(errp, "Cannot open a write protected LUN as read-write");
2035 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
2037 IscsiLun *iscsilun = reopen_state->bs->opaque;
2039 /* the cache.direct status might have changed */
2040 if (iscsilun->allocmap != NULL) {
2041 iscsi_allocmap_init(iscsilun, reopen_state->flags);
2045 static int iscsi_truncate(BlockDriverState *bs, int64_t offset,
2046 PreallocMode prealloc, Error **errp)
2048 IscsiLun *iscsilun = bs->opaque;
2049 Error *local_err = NULL;
2051 if (prealloc != PREALLOC_MODE_OFF) {
2052 error_setg(errp, "Unsupported preallocation mode '%s'",
2053 PreallocMode_str(prealloc));
2057 if (iscsilun->type != TYPE_DISK) {
2058 error_setg(errp, "Cannot resize non-disk iSCSI devices");
2062 iscsi_readcapacity_sync(iscsilun, &local_err);
2063 if (local_err != NULL) {
2064 error_propagate(errp, local_err);
2068 if (offset > iscsi_getlength(bs)) {
2069 error_setg(errp, "Cannot grow iSCSI devices");
2073 if (iscsilun->allocmap != NULL) {
2074 iscsi_allocmap_init(iscsilun, bs->open_flags);
2080 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
2083 int64_t total_size = 0;
2084 BlockDriverState *bs;
2085 IscsiLun *iscsilun = NULL;
2087 Error *local_err = NULL;
2091 /* Read out options */
2092 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2094 bs->opaque = g_new0(struct IscsiLun, 1);
2095 iscsilun = bs->opaque;
2097 bs_options = qdict_new();
2098 iscsi_parse_filename(filename, bs_options, &local_err);
2100 error_propagate(errp, local_err);
2103 ret = iscsi_open(bs, bs_options, 0, NULL);
2105 QDECREF(bs_options);
2110 iscsi_detach_aio_context(bs);
2111 if (iscsilun->type != TYPE_DISK) {
2115 if (bs->total_sectors < total_size) {
2122 if (iscsilun->iscsi != NULL) {
2123 iscsi_destroy_context(iscsilun->iscsi);
2131 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2133 IscsiLun *iscsilun = bs->opaque;
2134 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
2135 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
2136 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
2140 static void iscsi_invalidate_cache(BlockDriverState *bs,
2143 IscsiLun *iscsilun = bs->opaque;
2144 iscsi_allocmap_invalidate(iscsilun);
2147 static QemuOptsList iscsi_create_opts = {
2148 .name = "iscsi-create-opts",
2149 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2152 .name = BLOCK_OPT_SIZE,
2153 .type = QEMU_OPT_SIZE,
2154 .help = "Virtual disk size"
2156 { /* end of list */ }
2160 static BlockDriver bdrv_iscsi = {
2161 .format_name = "iscsi",
2162 .protocol_name = "iscsi",
2164 .instance_size = sizeof(IscsiLun),
2165 .bdrv_parse_filename = iscsi_parse_filename,
2166 .bdrv_file_open = iscsi_open,
2167 .bdrv_close = iscsi_close,
2168 .bdrv_create = iscsi_create,
2169 .create_opts = &iscsi_create_opts,
2170 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2171 .bdrv_reopen_commit = iscsi_reopen_commit,
2172 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2174 .bdrv_getlength = iscsi_getlength,
2175 .bdrv_get_info = iscsi_get_info,
2176 .bdrv_truncate = iscsi_truncate,
2177 .bdrv_refresh_limits = iscsi_refresh_limits,
2179 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2180 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2181 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2182 .bdrv_co_readv = iscsi_co_readv,
2183 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2184 .bdrv_co_flush_to_disk = iscsi_co_flush,
2187 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2190 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2191 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2194 #if LIBISCSI_API_VERSION >= (20160603)
2195 static BlockDriver bdrv_iser = {
2196 .format_name = "iser",
2197 .protocol_name = "iser",
2199 .instance_size = sizeof(IscsiLun),
2200 .bdrv_parse_filename = iscsi_parse_filename,
2201 .bdrv_file_open = iscsi_open,
2202 .bdrv_close = iscsi_close,
2203 .bdrv_create = iscsi_create,
2204 .create_opts = &iscsi_create_opts,
2205 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2206 .bdrv_reopen_commit = iscsi_reopen_commit,
2207 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2209 .bdrv_getlength = iscsi_getlength,
2210 .bdrv_get_info = iscsi_get_info,
2211 .bdrv_truncate = iscsi_truncate,
2212 .bdrv_refresh_limits = iscsi_refresh_limits,
2214 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2215 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2216 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2217 .bdrv_co_readv = iscsi_co_readv,
2218 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2219 .bdrv_co_flush_to_disk = iscsi_co_flush,
2222 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2225 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2226 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2230 static void iscsi_block_init(void)
2232 bdrv_register(&bdrv_iscsi);
2233 #if LIBISCSI_API_VERSION >= (20160603)
2234 bdrv_register(&bdrv_iser);
2238 block_init(iscsi_block_init);