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/config-file.h"
32 #include "qemu/error-report.h"
33 #include "qemu/bitops.h"
34 #include "qemu/bitmap.h"
35 #include "block/block_int.h"
36 #include "scsi/constants.h"
38 #include "qemu/option.h"
39 #include "qemu/uuid.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-commands-misc.h"
42 #include "qapi/qmp/qdict.h"
43 #include "qapi/qmp/qstring.h"
44 #include "crypto/secret.h"
45 #include "scsi/utils.h"
47 /* Conflict between scsi/utils.h and libiscsi! :( */
48 #define SCSI_XFER_NONE ISCSI_XFER_NONE
49 #include <iscsi/iscsi.h>
50 #include <iscsi/scsi-lowlevel.h>
52 QEMU_BUILD_BUG_ON((int)SCSI_XFER_NONE != (int)ISCSI_XFER_NONE);
58 typedef struct IscsiLun {
59 struct iscsi_context *iscsi;
60 AioContext *aio_context;
62 enum scsi_inquiry_peripheral_device_type type;
67 QEMUTimer *event_timer;
69 struct scsi_inquiry_logical_block_provisioning lbp;
70 struct scsi_inquiry_block_limits bl;
71 unsigned char *zeroblock;
72 /* The allocmap tracks which clusters (pages) on the iSCSI target are
73 * allocated and which are not. In case a target returns zeros for
74 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
75 * of reading zeros over the wire if a read request falls within an
76 * unallocated block. As there are 3 possible states we need 2 bitmaps to
77 * track. allocmap_valid keeps track if QEMU's information about a page is
78 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
79 * valid information about a page the corresponding allocmap entry should be
80 * switched to unallocated as well to force a new lookup of the allocation
81 * status as lookups are generally skipped if a page is suspect to be
82 * allocated. If a iSCSI target is opened with cache.direct = on the
83 * allocmap_valid does not exist turning all cached information invalid so
84 * that a fresh lookup is made for any page even if allocmap entry returns
85 * it's unallocated. */
86 unsigned long *allocmap;
87 unsigned long *allocmap_valid;
96 bool request_timed_out;
99 typedef struct IscsiTask {
104 struct scsi_task *task;
107 QEMUTimer retry_timer;
112 typedef struct IscsiAIOCB {
116 struct scsi_task *task;
127 /* libiscsi uses time_t so its enough to process events every second */
128 #define EVENT_INTERVAL 1000
129 #define NOP_INTERVAL 5000
130 #define MAX_NOP_FAILURES 3
131 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
132 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
134 /* this threshold is a trade-off knob to choose between
135 * the potential additional overhead of an extra GET_LBA_STATUS request
136 * vs. unnecessarily reading a lot of zero sectors over the wire.
137 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
138 * sectors we check the allocation status of the area covered by the
139 * request first if the allocationmap indicates that the area might be
141 #define ISCSI_CHECKALLOC_THRES 64
148 qemu_bh_delete(acb->bh);
153 acb->common.cb(acb->common.opaque, acb->status);
155 if (acb->task != NULL) {
156 scsi_free_scsi_task(acb->task);
164 iscsi_schedule_bh(IscsiAIOCB *acb)
169 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
170 qemu_bh_schedule(acb->bh);
173 static void iscsi_co_generic_bh_cb(void *opaque)
175 struct IscsiTask *iTask = opaque;
178 aio_co_wake(iTask->co);
181 static void iscsi_retry_timer_expired(void *opaque)
183 struct IscsiTask *iTask = opaque;
186 aio_co_wake(iTask->co);
190 static inline unsigned exp_random(double mean)
192 return -mean * log((double)rand() / RAND_MAX);
195 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
196 * libiscsi 1.10.0, together with other constants we need. Use it as
197 * a hint that we have to define them ourselves if needed, to keep the
198 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
199 * the test because SCSI_STATUS_* is an enum.
201 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
202 * an enum, check against the LIBISCSI_API_VERSION macro, which was
203 * introduced in 1.11.0. If it is present, there is no need to define
206 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
207 !defined(LIBISCSI_API_VERSION)
208 #define SCSI_STATUS_TASK_SET_FULL 0x28
209 #define SCSI_STATUS_TIMEOUT 0x0f000002
210 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
211 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
214 #ifndef LIBISCSI_API_VERSION
215 #define LIBISCSI_API_VERSION 20130701
218 static int iscsi_translate_sense(struct scsi_sense *sense)
220 return - scsi_sense_to_errno(sense->key,
221 (sense->ascq & 0xFF00) >> 8,
225 /* Called (via iscsi_service) with QemuMutex held. */
227 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
228 void *command_data, void *opaque)
230 struct IscsiTask *iTask = opaque;
231 struct scsi_task *task = command_data;
233 iTask->status = status;
237 if (status != SCSI_STATUS_GOOD) {
238 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
239 if (status == SCSI_STATUS_CHECK_CONDITION
240 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
241 error_report("iSCSI CheckCondition: %s",
242 iscsi_get_error(iscsi));
246 if (status == SCSI_STATUS_BUSY ||
247 status == SCSI_STATUS_TIMEOUT ||
248 status == SCSI_STATUS_TASK_SET_FULL) {
249 unsigned retry_time =
250 exp_random(iscsi_retry_times[iTask->retries - 1]);
251 if (status == SCSI_STATUS_TIMEOUT) {
252 /* make sure the request is rescheduled AFTER the
253 * reconnect is initiated */
254 retry_time = EVENT_INTERVAL * 2;
255 iTask->iscsilun->request_timed_out = true;
257 error_report("iSCSI Busy/TaskSetFull/TimeOut"
258 " (retry #%u in %u ms): %s",
259 iTask->retries, retry_time,
260 iscsi_get_error(iscsi));
261 aio_timer_init(iTask->iscsilun->aio_context,
262 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
263 SCALE_MS, iscsi_retry_timer_expired, iTask);
264 timer_mod(&iTask->retry_timer,
265 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
270 iTask->err_code = iscsi_translate_sense(&task->sense);
271 iTask->err_str = g_strdup(iscsi_get_error(iscsi));
276 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
277 iscsi_co_generic_bh_cb, iTask);
283 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
285 *iTask = (struct IscsiTask) {
286 .co = qemu_coroutine_self(),
287 .iscsilun = iscsilun,
292 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
295 IscsiAIOCB *acb = private_data;
297 acb->status = -ECANCELED;
298 iscsi_schedule_bh(acb);
302 iscsi_aio_cancel(BlockAIOCB *blockacb)
304 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
305 IscsiLun *iscsilun = acb->iscsilun;
307 if (acb->status != -EINPROGRESS) {
311 /* send a task mgmt call to the target to cancel the task on the target */
312 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
313 iscsi_abort_task_cb, acb);
317 static const AIOCBInfo iscsi_aiocb_info = {
318 .aiocb_size = sizeof(IscsiAIOCB),
319 .cancel_async = iscsi_aio_cancel,
323 static void iscsi_process_read(void *arg);
324 static void iscsi_process_write(void *arg);
326 /* Called with QemuMutex held. */
328 iscsi_set_events(IscsiLun *iscsilun)
330 struct iscsi_context *iscsi = iscsilun->iscsi;
331 int ev = iscsi_which_events(iscsi);
333 if (ev != iscsilun->events) {
334 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
336 (ev & POLLIN) ? iscsi_process_read : NULL,
337 (ev & POLLOUT) ? iscsi_process_write : NULL,
340 iscsilun->events = ev;
344 static void iscsi_timed_check_events(void *opaque)
346 IscsiLun *iscsilun = opaque;
348 /* check for timed out requests */
349 iscsi_service(iscsilun->iscsi, 0);
351 if (iscsilun->request_timed_out) {
352 iscsilun->request_timed_out = false;
353 iscsi_reconnect(iscsilun->iscsi);
356 /* newer versions of libiscsi may return zero events. Ensure we are able
357 * to return to service once this situation changes. */
358 iscsi_set_events(iscsilun);
360 timer_mod(iscsilun->event_timer,
361 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
365 iscsi_process_read(void *arg)
367 IscsiLun *iscsilun = arg;
368 struct iscsi_context *iscsi = iscsilun->iscsi;
370 qemu_mutex_lock(&iscsilun->mutex);
371 iscsi_service(iscsi, POLLIN);
372 iscsi_set_events(iscsilun);
373 qemu_mutex_unlock(&iscsilun->mutex);
377 iscsi_process_write(void *arg)
379 IscsiLun *iscsilun = arg;
380 struct iscsi_context *iscsi = iscsilun->iscsi;
382 qemu_mutex_lock(&iscsilun->mutex);
383 iscsi_service(iscsi, POLLOUT);
384 iscsi_set_events(iscsilun);
385 qemu_mutex_unlock(&iscsilun->mutex);
388 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
390 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
393 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
395 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
398 static bool is_byte_request_lun_aligned(int64_t offset, int count,
401 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
402 error_report("iSCSI misaligned request: "
403 "iscsilun->block_size %u, offset %" PRIi64
405 iscsilun->block_size, offset, count);
411 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
414 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
415 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
416 nb_sectors << BDRV_SECTOR_BITS,
420 static void iscsi_allocmap_free(IscsiLun *iscsilun)
422 g_free(iscsilun->allocmap);
423 g_free(iscsilun->allocmap_valid);
424 iscsilun->allocmap = NULL;
425 iscsilun->allocmap_valid = NULL;
429 static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
431 iscsi_allocmap_free(iscsilun);
433 iscsilun->allocmap_size =
434 DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks, iscsilun),
435 iscsilun->cluster_sectors);
437 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
438 if (!iscsilun->allocmap) {
442 if (open_flags & BDRV_O_NOCACHE) {
443 /* in case that cache.direct = on all allocmap entries are
444 * treated as invalid to force a relookup of the block
445 * status on every read request */
449 iscsilun->allocmap_valid = bitmap_try_new(iscsilun->allocmap_size);
450 if (!iscsilun->allocmap_valid) {
451 /* if we are under memory pressure free the allocmap as well */
452 iscsi_allocmap_free(iscsilun);
460 iscsi_allocmap_update(IscsiLun *iscsilun, int64_t sector_num,
461 int nb_sectors, bool allocated, bool valid)
463 int64_t cl_num_expanded, nb_cls_expanded, cl_num_shrunk, nb_cls_shrunk;
465 if (iscsilun->allocmap == NULL) {
468 /* expand to entirely contain all affected clusters */
469 cl_num_expanded = sector_num / iscsilun->cluster_sectors;
470 nb_cls_expanded = DIV_ROUND_UP(sector_num + nb_sectors,
471 iscsilun->cluster_sectors) - cl_num_expanded;
472 /* shrink to touch only completely contained clusters */
473 cl_num_shrunk = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
474 nb_cls_shrunk = (sector_num + nb_sectors) / iscsilun->cluster_sectors
477 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
479 if (nb_cls_shrunk > 0) {
480 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
484 if (iscsilun->allocmap_valid == NULL) {
488 if (nb_cls_shrunk > 0) {
489 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
492 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
498 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
501 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
505 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
508 /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
509 * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
511 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
514 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
517 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
520 static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
522 if (iscsilun->allocmap) {
523 bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
525 if (iscsilun->allocmap_valid) {
526 bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
531 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
535 if (iscsilun->allocmap == NULL) {
538 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
539 return !(find_next_bit(iscsilun->allocmap, size,
540 sector_num / iscsilun->cluster_sectors) == size);
543 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
544 int64_t sector_num, int nb_sectors)
547 if (iscsilun->allocmap_valid == NULL) {
550 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
551 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
552 sector_num / iscsilun->cluster_sectors) == size);
555 static int coroutine_fn
556 iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
557 QEMUIOVector *iov, int flags)
559 IscsiLun *iscsilun = bs->opaque;
560 struct IscsiTask iTask;
562 uint32_t num_sectors;
563 bool fua = flags & BDRV_REQ_FUA;
567 assert(iscsilun->dpofua);
569 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
573 if (bs->bl.max_transfer) {
574 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
577 lba = sector_qemu2lun(sector_num, iscsilun);
578 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
579 iscsi_co_init_iscsitask(iscsilun, &iTask);
580 qemu_mutex_lock(&iscsilun->mutex);
582 if (iscsilun->use_16_for_rw) {
583 #if LIBISCSI_API_VERSION >= (20160603)
584 iTask.task = iscsi_write16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
585 NULL, num_sectors * iscsilun->block_size,
586 iscsilun->block_size, 0, 0, fua, 0, 0,
587 iscsi_co_generic_cb, &iTask,
588 (struct scsi_iovec *)iov->iov, iov->niov);
590 iTask.task = iscsi_write10_iov_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,
594 (struct scsi_iovec *)iov->iov, iov->niov);
597 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
598 NULL, num_sectors * iscsilun->block_size,
599 iscsilun->block_size, 0, 0, fua, 0, 0,
600 iscsi_co_generic_cb, &iTask);
602 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
603 NULL, num_sectors * iscsilun->block_size,
604 iscsilun->block_size, 0, 0, fua, 0, 0,
605 iscsi_co_generic_cb, &iTask);
608 if (iTask.task == NULL) {
609 qemu_mutex_unlock(&iscsilun->mutex);
612 #if LIBISCSI_API_VERSION < (20160603)
613 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
616 while (!iTask.complete) {
617 iscsi_set_events(iscsilun);
618 qemu_mutex_unlock(&iscsilun->mutex);
619 qemu_coroutine_yield();
620 qemu_mutex_lock(&iscsilun->mutex);
623 if (iTask.task != NULL) {
624 scsi_free_scsi_task(iTask.task);
628 if (iTask.do_retry) {
633 if (iTask.status != SCSI_STATUS_GOOD) {
634 iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
635 error_report("iSCSI WRITE10/16 failed at lba %" PRIu64 ": %s", lba,
641 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
644 qemu_mutex_unlock(&iscsilun->mutex);
645 g_free(iTask.err_str);
651 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
653 int nb_sectors, int *pnum,
654 BlockDriverState **file)
656 IscsiLun *iscsilun = bs->opaque;
657 struct scsi_get_lba_status *lbas = NULL;
658 struct scsi_lba_status_descriptor *lbasd = NULL;
659 struct IscsiTask iTask;
663 iscsi_co_init_iscsitask(iscsilun, &iTask);
665 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
670 /* default to all sectors allocated */
671 ret = BDRV_BLOCK_DATA;
672 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
675 /* LUN does not support logical block provisioning */
676 if (!iscsilun->lbpme) {
680 lba = sector_qemu2lun(sector_num, iscsilun);
682 qemu_mutex_lock(&iscsilun->mutex);
684 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
685 lba, 8 + 16, iscsi_co_generic_cb,
691 while (!iTask.complete) {
692 iscsi_set_events(iscsilun);
693 qemu_mutex_unlock(&iscsilun->mutex);
694 qemu_coroutine_yield();
695 qemu_mutex_lock(&iscsilun->mutex);
698 if (iTask.do_retry) {
699 if (iTask.task != NULL) {
700 scsi_free_scsi_task(iTask.task);
707 if (iTask.status != SCSI_STATUS_GOOD) {
708 /* in case the get_lba_status_callout fails (i.e.
709 * because the device is busy or the cmd is not
710 * supported) we pretend all blocks are allocated
711 * for backwards compatibility */
712 error_report("iSCSI GET_LBA_STATUS failed at lba %" PRIu64 ": %s",
717 lbas = scsi_datain_unmarshall(iTask.task);
723 lbasd = &lbas->descriptors[0];
725 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
730 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
732 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
733 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
734 ret &= ~BDRV_BLOCK_DATA;
735 if (iscsilun->lbprz) {
736 ret |= BDRV_BLOCK_ZERO;
740 if (ret & BDRV_BLOCK_ZERO) {
741 iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
743 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
746 if (*pnum > nb_sectors) {
750 qemu_mutex_unlock(&iscsilun->mutex);
751 g_free(iTask.err_str);
753 if (iTask.task != NULL) {
754 scsi_free_scsi_task(iTask.task);
756 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
762 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
763 int64_t sector_num, int nb_sectors,
766 IscsiLun *iscsilun = bs->opaque;
767 struct IscsiTask iTask;
769 uint32_t num_sectors;
772 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
776 if (bs->bl.max_transfer) {
777 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
780 /* if cache.direct is off and we have a valid entry in our allocation map
781 * we can skip checking the block status and directly return zeroes if
782 * the request falls within an unallocated area */
783 if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
784 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
785 qemu_iovec_memset(iov, 0, 0x00, iov->size);
789 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
790 !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
791 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
793 BlockDriverState *file;
794 /* check the block status from the beginning of the cluster
795 * containing the start sector */
796 int64_t ret = iscsi_co_get_block_status(bs,
797 sector_num - sector_num % iscsilun->cluster_sectors,
798 BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
802 /* if the whole request falls into an unallocated area we can avoid
803 * to read and directly return zeroes instead */
804 if (ret & BDRV_BLOCK_ZERO &&
805 pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
806 qemu_iovec_memset(iov, 0, 0x00, iov->size);
811 lba = sector_qemu2lun(sector_num, iscsilun);
812 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
814 iscsi_co_init_iscsitask(iscsilun, &iTask);
815 qemu_mutex_lock(&iscsilun->mutex);
817 if (iscsilun->use_16_for_rw) {
818 #if LIBISCSI_API_VERSION >= (20160603)
819 iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
820 num_sectors * iscsilun->block_size,
821 iscsilun->block_size, 0, 0, 0, 0, 0,
822 iscsi_co_generic_cb, &iTask,
823 (struct scsi_iovec *)iov->iov, iov->niov);
825 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
826 num_sectors * iscsilun->block_size,
827 iscsilun->block_size,
829 iscsi_co_generic_cb, &iTask,
830 (struct scsi_iovec *)iov->iov, iov->niov);
833 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
834 num_sectors * iscsilun->block_size,
835 iscsilun->block_size, 0, 0, 0, 0, 0,
836 iscsi_co_generic_cb, &iTask);
838 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
839 num_sectors * iscsilun->block_size,
840 iscsilun->block_size,
842 iscsi_co_generic_cb, &iTask);
845 if (iTask.task == NULL) {
846 qemu_mutex_unlock(&iscsilun->mutex);
849 #if LIBISCSI_API_VERSION < (20160603)
850 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
852 while (!iTask.complete) {
853 iscsi_set_events(iscsilun);
854 qemu_mutex_unlock(&iscsilun->mutex);
855 qemu_coroutine_yield();
856 qemu_mutex_lock(&iscsilun->mutex);
859 if (iTask.task != NULL) {
860 scsi_free_scsi_task(iTask.task);
864 if (iTask.do_retry) {
869 if (iTask.status != SCSI_STATUS_GOOD) {
870 error_report("iSCSI READ10/16 failed at lba %" PRIu64 ": %s",
875 qemu_mutex_unlock(&iscsilun->mutex);
876 g_free(iTask.err_str);
880 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
882 IscsiLun *iscsilun = bs->opaque;
883 struct IscsiTask iTask;
886 iscsi_co_init_iscsitask(iscsilun, &iTask);
887 qemu_mutex_lock(&iscsilun->mutex);
889 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
890 0, iscsi_co_generic_cb, &iTask) == NULL) {
891 qemu_mutex_unlock(&iscsilun->mutex);
895 while (!iTask.complete) {
896 iscsi_set_events(iscsilun);
897 qemu_mutex_unlock(&iscsilun->mutex);
898 qemu_coroutine_yield();
899 qemu_mutex_lock(&iscsilun->mutex);
902 if (iTask.task != NULL) {
903 scsi_free_scsi_task(iTask.task);
907 if (iTask.do_retry) {
912 if (iTask.status != SCSI_STATUS_GOOD) {
913 error_report("iSCSI SYNCHRONIZECACHE10 failed: %s", iTask.err_str);
917 qemu_mutex_unlock(&iscsilun->mutex);
918 g_free(iTask.err_str);
923 /* Called (via iscsi_service) with QemuMutex held. */
925 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
926 void *command_data, void *opaque)
928 IscsiAIOCB *acb = opaque;
935 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
936 iscsi_get_error(iscsi));
937 acb->status = iscsi_translate_sense(&acb->task->sense);
940 acb->ioh->driver_status = 0;
941 acb->ioh->host_status = 0;
943 acb->ioh->status = status;
945 #define SG_ERR_DRIVER_SENSE 0x08
947 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
950 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
952 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
953 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
954 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
955 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
958 iscsi_schedule_bh(acb);
961 static void iscsi_ioctl_bh_completion(void *opaque)
963 IscsiAIOCB *acb = opaque;
965 qemu_bh_delete(acb->bh);
966 acb->common.cb(acb->common.opaque, acb->ret);
970 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
972 BlockDriverState *bs = acb->common.bs;
973 IscsiLun *iscsilun = bs->opaque;
977 case SG_GET_VERSION_NUM:
981 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
987 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
988 iscsi_ioctl_bh_completion, acb);
990 qemu_bh_schedule(acb->bh);
993 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
994 unsigned long int req, void *buf,
995 BlockCompletionFunc *cb, void *opaque)
997 IscsiLun *iscsilun = bs->opaque;
998 struct iscsi_context *iscsi = iscsilun->iscsi;
999 struct iscsi_data data;
1002 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
1004 acb->iscsilun = iscsilun;
1006 acb->status = -EINPROGRESS;
1011 iscsi_ioctl_handle_emulated(acb, req, buf);
1012 return &acb->common;
1015 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
1016 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
1017 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1018 qemu_aio_unref(acb);
1022 acb->task = malloc(sizeof(struct scsi_task));
1023 if (acb->task == NULL) {
1024 error_report("iSCSI: Failed to allocate task for scsi command. %s",
1025 iscsi_get_error(iscsi));
1026 qemu_aio_unref(acb);
1029 memset(acb->task, 0, sizeof(struct scsi_task));
1031 switch (acb->ioh->dxfer_direction) {
1032 case SG_DXFER_TO_DEV:
1033 acb->task->xfer_dir = SCSI_XFER_WRITE;
1035 case SG_DXFER_FROM_DEV:
1036 acb->task->xfer_dir = SCSI_XFER_READ;
1039 acb->task->xfer_dir = SCSI_XFER_NONE;
1043 acb->task->cdb_size = acb->ioh->cmd_len;
1044 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1045 acb->task->expxferlen = acb->ioh->dxfer_len;
1048 qemu_mutex_lock(&iscsilun->mutex);
1049 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
1050 if (acb->ioh->iovec_count == 0) {
1051 data.data = acb->ioh->dxferp;
1052 data.size = acb->ioh->dxfer_len;
1054 scsi_task_set_iov_out(acb->task,
1055 (struct scsi_iovec *) acb->ioh->dxferp,
1056 acb->ioh->iovec_count);
1060 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1062 (data.size > 0) ? &data : NULL,
1064 qemu_mutex_unlock(&iscsilun->mutex);
1065 scsi_free_scsi_task(acb->task);
1066 qemu_aio_unref(acb);
1070 /* tell libiscsi to read straight into the buffer we got from ioctl */
1071 if (acb->task->xfer_dir == SCSI_XFER_READ) {
1072 if (acb->ioh->iovec_count == 0) {
1073 scsi_task_add_data_in_buffer(acb->task,
1074 acb->ioh->dxfer_len,
1077 scsi_task_set_iov_in(acb->task,
1078 (struct scsi_iovec *) acb->ioh->dxferp,
1079 acb->ioh->iovec_count);
1083 iscsi_set_events(iscsilun);
1084 qemu_mutex_unlock(&iscsilun->mutex);
1086 return &acb->common;
1092 iscsi_getlength(BlockDriverState *bs)
1094 IscsiLun *iscsilun = bs->opaque;
1097 len = iscsilun->num_blocks;
1098 len *= iscsilun->block_size;
1104 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
1106 IscsiLun *iscsilun = bs->opaque;
1107 struct IscsiTask iTask;
1108 struct unmap_list list;
1111 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1115 if (!iscsilun->lbp.lbpu) {
1116 /* UNMAP is not supported by the target */
1120 list.lba = offset / iscsilun->block_size;
1121 list.num = bytes / iscsilun->block_size;
1123 iscsi_co_init_iscsitask(iscsilun, &iTask);
1124 qemu_mutex_lock(&iscsilun->mutex);
1126 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1127 iscsi_co_generic_cb, &iTask) == NULL) {
1132 while (!iTask.complete) {
1133 iscsi_set_events(iscsilun);
1134 qemu_mutex_unlock(&iscsilun->mutex);
1135 qemu_coroutine_yield();
1136 qemu_mutex_lock(&iscsilun->mutex);
1139 if (iTask.task != NULL) {
1140 scsi_free_scsi_task(iTask.task);
1144 if (iTask.do_retry) {
1149 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1150 bytes >> BDRV_SECTOR_BITS);
1152 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1153 /* the target might fail with a check condition if it
1154 is not happy with the alignment of the UNMAP request
1155 we silently fail in this case */
1159 if (iTask.status != SCSI_STATUS_GOOD) {
1160 error_report("iSCSI UNMAP failed at lba %" PRIu64 ": %s",
1161 list.lba, iTask.err_str);
1167 qemu_mutex_unlock(&iscsilun->mutex);
1168 g_free(iTask.err_str);
1173 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1174 int bytes, BdrvRequestFlags flags)
1176 IscsiLun *iscsilun = bs->opaque;
1177 struct IscsiTask iTask;
1180 bool use_16_for_ws = iscsilun->use_16_for_rw;
1183 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1187 if (flags & BDRV_REQ_MAY_UNMAP) {
1188 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1189 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1190 use_16_for_ws = true;
1192 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1193 /* WRITESAME16 with UNMAP is not supported by the target,
1194 * fall back and try WRITESAME10/16 without UNMAP */
1195 flags &= ~BDRV_REQ_MAY_UNMAP;
1196 use_16_for_ws = iscsilun->use_16_for_rw;
1200 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1201 /* WRITESAME without UNMAP is not supported by the target */
1205 lba = offset / iscsilun->block_size;
1206 nb_blocks = bytes / iscsilun->block_size;
1208 if (iscsilun->zeroblock == NULL) {
1209 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1210 if (iscsilun->zeroblock == NULL) {
1215 qemu_mutex_lock(&iscsilun->mutex);
1216 iscsi_co_init_iscsitask(iscsilun, &iTask);
1218 if (use_16_for_ws) {
1219 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1220 iscsilun->zeroblock, iscsilun->block_size,
1221 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1222 0, 0, iscsi_co_generic_cb, &iTask);
1224 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1225 iscsilun->zeroblock, iscsilun->block_size,
1226 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1227 0, 0, iscsi_co_generic_cb, &iTask);
1229 if (iTask.task == NULL) {
1230 qemu_mutex_unlock(&iscsilun->mutex);
1234 while (!iTask.complete) {
1235 iscsi_set_events(iscsilun);
1236 qemu_mutex_unlock(&iscsilun->mutex);
1237 qemu_coroutine_yield();
1238 qemu_mutex_lock(&iscsilun->mutex);
1241 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1242 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1243 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1244 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1245 /* WRITE SAME is not supported by the target */
1246 iscsilun->has_write_same = false;
1247 scsi_free_scsi_task(iTask.task);
1252 if (iTask.task != NULL) {
1253 scsi_free_scsi_task(iTask.task);
1257 if (iTask.do_retry) {
1262 if (iTask.status != SCSI_STATUS_GOOD) {
1263 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1264 bytes >> BDRV_SECTOR_BITS);
1265 error_report("iSCSI WRITESAME10/16 failed at lba %" PRIu64 ": %s",
1266 lba, iTask.err_str);
1271 if (flags & BDRV_REQ_MAY_UNMAP) {
1272 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1273 bytes >> BDRV_SECTOR_BITS);
1275 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1276 bytes >> BDRV_SECTOR_BITS);
1280 qemu_mutex_unlock(&iscsilun->mutex);
1281 g_free(iTask.err_str);
1285 static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
1288 const char *user = NULL;
1289 const char *password = NULL;
1290 const char *secretid;
1291 char *secret = NULL;
1293 user = qemu_opt_get(opts, "user");
1298 secretid = qemu_opt_get(opts, "password-secret");
1299 password = qemu_opt_get(opts, "password");
1300 if (secretid && password) {
1301 error_setg(errp, "'password' and 'password-secret' properties are "
1302 "mutually exclusive");
1306 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1311 } else if (!password) {
1312 error_setg(errp, "CHAP username specified but no password was given");
1316 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1317 error_setg(errp, "Failed to set initiator username and password");
1323 static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
1326 const char *digest = NULL;
1328 digest = qemu_opt_get(opts, "header-digest");
1330 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1331 } else if (!strcmp(digest, "crc32c")) {
1332 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1333 } else if (!strcmp(digest, "none")) {
1334 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1335 } else if (!strcmp(digest, "crc32c-none")) {
1336 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1337 } else if (!strcmp(digest, "none-crc32c")) {
1338 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1340 error_setg(errp, "Invalid header-digest setting : %s", digest);
1344 static char *get_initiator_name(QemuOpts *opts)
1348 UuidInfo *uuid_info;
1350 name = qemu_opt_get(opts, "initiator-name");
1352 return g_strdup(name);
1355 uuid_info = qmp_query_uuid(NULL);
1356 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1357 name = qemu_get_vm_name();
1359 name = uuid_info->UUID;
1361 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1362 name ? ":" : "", name ? name : "");
1363 qapi_free_UuidInfo(uuid_info);
1367 static void iscsi_nop_timed_event(void *opaque)
1369 IscsiLun *iscsilun = opaque;
1371 qemu_mutex_lock(&iscsilun->mutex);
1372 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1373 error_report("iSCSI: NOP timeout. Reconnecting...");
1374 iscsilun->request_timed_out = true;
1375 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1376 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1380 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1381 iscsi_set_events(iscsilun);
1384 qemu_mutex_unlock(&iscsilun->mutex);
1387 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1389 struct scsi_task *task = NULL;
1390 struct scsi_readcapacity10 *rc10 = NULL;
1391 struct scsi_readcapacity16 *rc16 = NULL;
1392 int retries = ISCSI_CMD_RETRIES;
1396 scsi_free_scsi_task(task);
1400 switch (iscsilun->type) {
1402 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1403 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1404 rc16 = scsi_datain_unmarshall(task);
1406 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1408 iscsilun->block_size = rc16->block_length;
1409 iscsilun->num_blocks = rc16->returned_lba + 1;
1410 iscsilun->lbpme = !!rc16->lbpme;
1411 iscsilun->lbprz = !!rc16->lbprz;
1412 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1416 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1417 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1420 /* Fall through and try READ CAPACITY(10) instead. */
1422 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1423 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1424 rc10 = scsi_datain_unmarshall(task);
1426 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1428 iscsilun->block_size = rc10->block_size;
1429 if (rc10->lba == 0) {
1430 /* blank disk loaded */
1431 iscsilun->num_blocks = 0;
1433 iscsilun->num_blocks = rc10->lba + 1;
1441 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1442 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1445 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1446 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1447 } else if (!iscsilun->block_size ||
1448 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1449 error_setg(errp, "iSCSI: the target returned an invalid "
1450 "block size of %d.", iscsilun->block_size);
1453 scsi_free_scsi_task(task);
1457 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1458 int evpd, int pc, void **inq, Error **errp)
1461 struct scsi_task *task = NULL;
1462 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1463 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1466 full_size = scsi_datain_getfullsize(task);
1467 if (full_size > task->datain.size) {
1468 scsi_free_scsi_task(task);
1470 /* we need more data for the full list */
1471 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1472 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1477 *inq = scsi_datain_unmarshall(task);
1479 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1486 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1487 iscsi_get_error(iscsi));
1490 scsi_free_scsi_task(task);
1495 static void iscsi_detach_aio_context(BlockDriverState *bs)
1497 IscsiLun *iscsilun = bs->opaque;
1499 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1500 false, NULL, NULL, NULL, NULL);
1501 iscsilun->events = 0;
1503 if (iscsilun->nop_timer) {
1504 timer_del(iscsilun->nop_timer);
1505 timer_free(iscsilun->nop_timer);
1506 iscsilun->nop_timer = NULL;
1508 if (iscsilun->event_timer) {
1509 timer_del(iscsilun->event_timer);
1510 timer_free(iscsilun->event_timer);
1511 iscsilun->event_timer = NULL;
1515 static void iscsi_attach_aio_context(BlockDriverState *bs,
1516 AioContext *new_context)
1518 IscsiLun *iscsilun = bs->opaque;
1520 iscsilun->aio_context = new_context;
1521 iscsi_set_events(iscsilun);
1523 /* Set up a timer for sending out iSCSI NOPs */
1524 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1525 QEMU_CLOCK_REALTIME, SCALE_MS,
1526 iscsi_nop_timed_event, iscsilun);
1527 timer_mod(iscsilun->nop_timer,
1528 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1530 /* Set up a timer for periodic calls to iscsi_set_events and to
1531 * scan for command timeout */
1532 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1533 QEMU_CLOCK_REALTIME, SCALE_MS,
1534 iscsi_timed_check_events, iscsilun);
1535 timer_mod(iscsilun->event_timer,
1536 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1539 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1541 struct scsi_task *task;
1542 struct scsi_mode_sense *ms = NULL;
1543 iscsilun->write_protected = false;
1544 iscsilun->dpofua = false;
1546 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1547 1, SCSI_MODESENSE_PC_CURRENT,
1550 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1551 iscsi_get_error(iscsilun->iscsi));
1555 if (task->status != SCSI_STATUS_GOOD) {
1556 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1559 ms = scsi_datain_unmarshall(task);
1561 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1562 iscsi_get_error(iscsilun->iscsi));
1565 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1566 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1570 scsi_free_scsi_task(task);
1574 static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1578 const char *user, *password, *password_secret, *initiator_name,
1579 *header_digest, *timeout;
1581 list = qemu_find_opts("iscsi");
1586 opts = qemu_opts_find(list, target);
1588 opts = QTAILQ_FIRST(&list->head);
1594 user = qemu_opt_get(opts, "user");
1596 qdict_set_default_str(options, "user", user);
1599 password = qemu_opt_get(opts, "password");
1601 qdict_set_default_str(options, "password", password);
1604 password_secret = qemu_opt_get(opts, "password-secret");
1605 if (password_secret) {
1606 qdict_set_default_str(options, "password-secret", password_secret);
1609 initiator_name = qemu_opt_get(opts, "initiator-name");
1610 if (initiator_name) {
1611 qdict_set_default_str(options, "initiator-name", initiator_name);
1614 header_digest = qemu_opt_get(opts, "header-digest");
1615 if (header_digest) {
1616 /* -iscsi takes upper case values, but QAPI only supports lower case
1617 * enum constant names, so we have to convert here. */
1618 char *qapi_value = g_ascii_strdown(header_digest, -1);
1619 qdict_set_default_str(options, "header-digest", qapi_value);
1623 timeout = qemu_opt_get(opts, "timeout");
1625 qdict_set_default_str(options, "timeout", timeout);
1630 * We support iscsi url's on the form
1631 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1633 static void iscsi_parse_filename(const char *filename, QDict *options,
1636 struct iscsi_url *iscsi_url;
1637 const char *transport_name;
1640 iscsi_url = iscsi_parse_full_url(NULL, filename);
1641 if (iscsi_url == NULL) {
1642 error_setg(errp, "Failed to parse URL : %s", filename);
1646 #if LIBISCSI_API_VERSION >= (20160603)
1647 switch (iscsi_url->transport) {
1649 transport_name = "tcp";
1651 case ISER_TRANSPORT:
1652 transport_name = "iser";
1655 error_setg(errp, "Unknown transport type (%d)",
1656 iscsi_url->transport);
1660 transport_name = "tcp";
1663 qdict_set_default_str(options, "transport", transport_name);
1664 qdict_set_default_str(options, "portal", iscsi_url->portal);
1665 qdict_set_default_str(options, "target", iscsi_url->target);
1667 lun_str = g_strdup_printf("%d", iscsi_url->lun);
1668 qdict_set_default_str(options, "lun", lun_str);
1671 /* User/password from -iscsi take precedence over those from the URL */
1672 iscsi_parse_iscsi_option(iscsi_url->target, options);
1674 if (iscsi_url->user[0] != '\0') {
1675 qdict_set_default_str(options, "user", iscsi_url->user);
1676 qdict_set_default_str(options, "password", iscsi_url->passwd);
1679 iscsi_destroy_url(iscsi_url);
1682 static QemuOptsList runtime_opts = {
1684 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1687 .name = "transport",
1688 .type = QEMU_OPT_STRING,
1692 .type = QEMU_OPT_STRING,
1696 .type = QEMU_OPT_STRING,
1700 .type = QEMU_OPT_STRING,
1704 .type = QEMU_OPT_STRING,
1707 .name = "password-secret",
1708 .type = QEMU_OPT_STRING,
1712 .type = QEMU_OPT_NUMBER,
1715 .name = "initiator-name",
1716 .type = QEMU_OPT_STRING,
1719 .name = "header-digest",
1720 .type = QEMU_OPT_STRING,
1724 .type = QEMU_OPT_NUMBER,
1728 .type = QEMU_OPT_STRING,
1730 { /* end of list */ }
1734 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1737 IscsiLun *iscsilun = bs->opaque;
1738 struct iscsi_context *iscsi = NULL;
1739 struct scsi_task *task = NULL;
1740 struct scsi_inquiry_standard *inq = NULL;
1741 struct scsi_inquiry_supported_pages *inq_vpd;
1742 char *initiator_name = NULL;
1744 Error *local_err = NULL;
1745 const char *transport_name, *portal, *target, *filename;
1746 #if LIBISCSI_API_VERSION >= (20160603)
1747 enum iscsi_transport_type transport;
1749 int i, ret = 0, timeout = 0, lun;
1751 /* If we are given a filename, parse the filename, with precedence given to
1752 * filename encoded options */
1753 filename = qdict_get_try_str(options, "filename");
1755 warn_report("'filename' option specified. "
1756 "This is an unsupported option, and may be deprecated "
1758 iscsi_parse_filename(filename, options, &local_err);
1761 error_propagate(errp, local_err);
1766 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1767 qemu_opts_absorb_qdict(opts, options, &local_err);
1769 error_propagate(errp, local_err);
1774 transport_name = qemu_opt_get(opts, "transport");
1775 portal = qemu_opt_get(opts, "portal");
1776 target = qemu_opt_get(opts, "target");
1777 lun = qemu_opt_get_number(opts, "lun", 0);
1779 if (!transport_name || !portal || !target) {
1780 error_setg(errp, "Need all of transport, portal and target options");
1785 if (!strcmp(transport_name, "tcp")) {
1786 #if LIBISCSI_API_VERSION >= (20160603)
1787 transport = TCP_TRANSPORT;
1788 } else if (!strcmp(transport_name, "iser")) {
1789 transport = ISER_TRANSPORT;
1791 /* TCP is what older libiscsi versions always use */
1794 error_setg(errp, "Unknown transport: %s", transport_name);
1799 memset(iscsilun, 0, sizeof(IscsiLun));
1801 initiator_name = get_initiator_name(opts);
1803 iscsi = iscsi_create_context(initiator_name);
1804 if (iscsi == NULL) {
1805 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1809 #if LIBISCSI_API_VERSION >= (20160603)
1810 if (iscsi_init_transport(iscsi, transport)) {
1811 error_setg(errp, ("Error initializing transport."));
1816 if (iscsi_set_targetname(iscsi, target)) {
1817 error_setg(errp, "iSCSI: Failed to set target name.");
1822 /* check if we got CHAP username/password via the options */
1823 apply_chap(iscsi, opts, &local_err);
1824 if (local_err != NULL) {
1825 error_propagate(errp, local_err);
1830 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1831 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1836 /* check if we got HEADER_DIGEST via the options */
1837 apply_header_digest(iscsi, opts, &local_err);
1838 if (local_err != NULL) {
1839 error_propagate(errp, local_err);
1844 /* timeout handling is broken in libiscsi before 1.15.0 */
1845 timeout = qemu_opt_get_number(opts, "timeout", 0);
1846 #if LIBISCSI_API_VERSION >= 20150621
1847 iscsi_set_timeout(iscsi, timeout);
1850 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1854 if (iscsi_full_connect_sync(iscsi, portal, lun) != 0) {
1855 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1856 iscsi_get_error(iscsi));
1861 iscsilun->iscsi = iscsi;
1862 iscsilun->aio_context = bdrv_get_aio_context(bs);
1863 iscsilun->lun = lun;
1864 iscsilun->has_write_same = true;
1866 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1867 (void **) &inq, errp);
1872 iscsilun->type = inq->periperal_device_type;
1873 scsi_free_scsi_task(task);
1876 iscsi_modesense_sync(iscsilun);
1877 if (iscsilun->dpofua) {
1878 bs->supported_write_flags = BDRV_REQ_FUA;
1881 /* Check the write protect flag of the LUN if we want to write */
1882 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1883 iscsilun->write_protected) {
1884 error_setg(errp, "Cannot open a write protected LUN as read-write");
1889 iscsi_readcapacity_sync(iscsilun, &local_err);
1890 if (local_err != NULL) {
1891 error_propagate(errp, local_err);
1895 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1897 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1898 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1899 * will try to read from the device to guess the image format.
1901 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1905 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1906 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1907 (void **) &inq_vpd, errp);
1912 for (i = 0; i < inq_vpd->num_pages; i++) {
1913 struct scsi_task *inq_task;
1914 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1915 struct scsi_inquiry_block_limits *inq_bl;
1916 switch (inq_vpd->pages[i]) {
1917 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1918 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1919 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1920 (void **) &inq_lbp, errp);
1921 if (inq_task == NULL) {
1925 memcpy(&iscsilun->lbp, inq_lbp,
1926 sizeof(struct scsi_inquiry_logical_block_provisioning));
1927 scsi_free_scsi_task(inq_task);
1929 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1930 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1931 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1932 (void **) &inq_bl, errp);
1933 if (inq_task == NULL) {
1937 memcpy(&iscsilun->bl, inq_bl,
1938 sizeof(struct scsi_inquiry_block_limits));
1939 scsi_free_scsi_task(inq_task);
1945 scsi_free_scsi_task(task);
1948 qemu_mutex_init(&iscsilun->mutex);
1949 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1951 /* Guess the internal cluster (page) size of the iscsi target by the means
1952 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1953 * reasonable size */
1954 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1955 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1956 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1957 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1958 if (iscsilun->lbprz) {
1959 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1963 if (iscsilun->lbprz && iscsilun->lbp.lbpws) {
1964 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1968 qemu_opts_del(opts);
1969 g_free(initiator_name);
1971 scsi_free_scsi_task(task);
1975 if (iscsi != NULL) {
1976 if (iscsi_is_logged_in(iscsi)) {
1977 iscsi_logout_sync(iscsi);
1979 iscsi_destroy_context(iscsi);
1981 memset(iscsilun, 0, sizeof(IscsiLun));
1987 static void iscsi_close(BlockDriverState *bs)
1989 IscsiLun *iscsilun = bs->opaque;
1990 struct iscsi_context *iscsi = iscsilun->iscsi;
1992 iscsi_detach_aio_context(bs);
1993 if (iscsi_is_logged_in(iscsi)) {
1994 iscsi_logout_sync(iscsi);
1996 iscsi_destroy_context(iscsi);
1997 g_free(iscsilun->zeroblock);
1998 iscsi_allocmap_free(iscsilun);
1999 qemu_mutex_destroy(&iscsilun->mutex);
2000 memset(iscsilun, 0, sizeof(IscsiLun));
2003 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
2005 /* We don't actually refresh here, but just return data queried in
2006 * iscsi_open(): iscsi targets don't change their limits. */
2008 IscsiLun *iscsilun = bs->opaque;
2009 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
2010 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
2012 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
2014 bs->bl.request_alignment = block_size;
2016 if (iscsilun->bl.max_xfer_len) {
2017 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
2020 if (max_xfer_len * block_size < INT_MAX) {
2021 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
2024 if (iscsilun->lbp.lbpu) {
2025 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
2026 bs->bl.max_pdiscard =
2027 iscsilun->bl.max_unmap * iscsilun->block_size;
2029 bs->bl.pdiscard_alignment =
2030 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2032 bs->bl.pdiscard_alignment = iscsilun->block_size;
2035 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
2036 bs->bl.max_pwrite_zeroes =
2037 iscsilun->bl.max_ws_len * iscsilun->block_size;
2039 if (iscsilun->lbp.lbpws) {
2040 bs->bl.pwrite_zeroes_alignment =
2041 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2043 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
2045 if (iscsilun->bl.opt_xfer_len &&
2046 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
2047 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
2048 iscsilun->block_size);
2052 /* Note that this will not re-establish a connection with an iSCSI target - it
2053 * is effectively a NOP. */
2054 static int iscsi_reopen_prepare(BDRVReopenState *state,
2055 BlockReopenQueue *queue, Error **errp)
2057 IscsiLun *iscsilun = state->bs->opaque;
2059 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
2060 error_setg(errp, "Cannot open a write protected LUN as read-write");
2066 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
2068 IscsiLun *iscsilun = reopen_state->bs->opaque;
2070 /* the cache.direct status might have changed */
2071 if (iscsilun->allocmap != NULL) {
2072 iscsi_allocmap_init(iscsilun, reopen_state->flags);
2076 static int iscsi_truncate(BlockDriverState *bs, int64_t offset,
2077 PreallocMode prealloc, Error **errp)
2079 IscsiLun *iscsilun = bs->opaque;
2080 Error *local_err = NULL;
2082 if (prealloc != PREALLOC_MODE_OFF) {
2083 error_setg(errp, "Unsupported preallocation mode '%s'",
2084 PreallocMode_str(prealloc));
2088 if (iscsilun->type != TYPE_DISK) {
2089 error_setg(errp, "Cannot resize non-disk iSCSI devices");
2093 iscsi_readcapacity_sync(iscsilun, &local_err);
2094 if (local_err != NULL) {
2095 error_propagate(errp, local_err);
2099 if (offset > iscsi_getlength(bs)) {
2100 error_setg(errp, "Cannot grow iSCSI devices");
2104 if (iscsilun->allocmap != NULL) {
2105 iscsi_allocmap_init(iscsilun, bs->open_flags);
2111 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
2114 int64_t total_size = 0;
2115 BlockDriverState *bs;
2116 IscsiLun *iscsilun = NULL;
2118 Error *local_err = NULL;
2122 /* Read out options */
2123 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2125 bs->opaque = g_new0(struct IscsiLun, 1);
2126 iscsilun = bs->opaque;
2128 bs_options = qdict_new();
2129 iscsi_parse_filename(filename, bs_options, &local_err);
2131 error_propagate(errp, local_err);
2134 ret = iscsi_open(bs, bs_options, 0, NULL);
2136 QDECREF(bs_options);
2141 iscsi_detach_aio_context(bs);
2142 if (iscsilun->type != TYPE_DISK) {
2146 if (bs->total_sectors < total_size) {
2153 if (iscsilun->iscsi != NULL) {
2154 iscsi_destroy_context(iscsilun->iscsi);
2162 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2164 IscsiLun *iscsilun = bs->opaque;
2165 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
2166 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
2170 static void iscsi_invalidate_cache(BlockDriverState *bs,
2173 IscsiLun *iscsilun = bs->opaque;
2174 iscsi_allocmap_invalidate(iscsilun);
2177 static QemuOptsList iscsi_create_opts = {
2178 .name = "iscsi-create-opts",
2179 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2182 .name = BLOCK_OPT_SIZE,
2183 .type = QEMU_OPT_SIZE,
2184 .help = "Virtual disk size"
2186 { /* end of list */ }
2190 static BlockDriver bdrv_iscsi = {
2191 .format_name = "iscsi",
2192 .protocol_name = "iscsi",
2194 .instance_size = sizeof(IscsiLun),
2195 .bdrv_parse_filename = iscsi_parse_filename,
2196 .bdrv_file_open = iscsi_open,
2197 .bdrv_close = iscsi_close,
2198 .bdrv_create = iscsi_create,
2199 .create_opts = &iscsi_create_opts,
2200 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2201 .bdrv_reopen_commit = iscsi_reopen_commit,
2202 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2204 .bdrv_getlength = iscsi_getlength,
2205 .bdrv_get_info = iscsi_get_info,
2206 .bdrv_truncate = iscsi_truncate,
2207 .bdrv_refresh_limits = iscsi_refresh_limits,
2209 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2210 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2211 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2212 .bdrv_co_readv = iscsi_co_readv,
2213 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2214 .bdrv_co_flush_to_disk = iscsi_co_flush,
2217 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2220 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2221 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2224 #if LIBISCSI_API_VERSION >= (20160603)
2225 static BlockDriver bdrv_iser = {
2226 .format_name = "iser",
2227 .protocol_name = "iser",
2229 .instance_size = sizeof(IscsiLun),
2230 .bdrv_parse_filename = iscsi_parse_filename,
2231 .bdrv_file_open = iscsi_open,
2232 .bdrv_close = iscsi_close,
2233 .bdrv_create = iscsi_create,
2234 .create_opts = &iscsi_create_opts,
2235 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2236 .bdrv_reopen_commit = iscsi_reopen_commit,
2237 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2239 .bdrv_getlength = iscsi_getlength,
2240 .bdrv_get_info = iscsi_get_info,
2241 .bdrv_truncate = iscsi_truncate,
2242 .bdrv_refresh_limits = iscsi_refresh_limits,
2244 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2245 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2246 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2247 .bdrv_co_readv = iscsi_co_readv,
2248 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2249 .bdrv_co_flush_to_disk = iscsi_co_flush,
2252 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2255 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2256 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2260 static void iscsi_block_init(void)
2262 bdrv_register(&bdrv_iscsi);
2263 #if LIBISCSI_API_VERSION >= (20160603)
2264 bdrv_register(&bdrv_iser);
2268 block_init(iscsi_block_init);