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"
44 #include <iscsi/iscsi.h>
45 #include <iscsi/scsi-lowlevel.h>
51 typedef struct IscsiLun {
52 struct iscsi_context *iscsi;
53 AioContext *aio_context;
55 enum scsi_inquiry_peripheral_device_type type;
60 QEMUTimer *event_timer;
61 struct scsi_inquiry_logical_block_provisioning lbp;
62 struct scsi_inquiry_block_limits bl;
63 unsigned char *zeroblock;
64 /* The allocmap tracks which clusters (pages) on the iSCSI target are
65 * allocated and which are not. In case a target returns zeros for
66 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
67 * of reading zeros over the wire if a read request falls within an
68 * unallocated block. As there are 3 possible states we need 2 bitmaps to
69 * track. allocmap_valid keeps track if QEMU's information about a page is
70 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
71 * valid information about a page the corresponding allocmap entry should be
72 * switched to unallocated as well to force a new lookup of the allocation
73 * status as lookups are generally skipped if a page is suspect to be
74 * allocated. If a iSCSI target is opened with cache.direct = on the
75 * allocmap_valid does not exist turning all cached information invalid so
76 * that a fresh lookup is made for any page even if allocmap entry returns
77 * it's unallocated. */
78 unsigned long *allocmap;
79 unsigned long *allocmap_valid;
88 bool request_timed_out;
91 typedef struct IscsiTask {
96 struct scsi_task *task;
99 QEMUTimer retry_timer;
103 typedef struct IscsiAIOCB {
108 struct scsi_task *task;
119 /* libiscsi uses time_t so its enough to process events every second */
120 #define EVENT_INTERVAL 1000
121 #define NOP_INTERVAL 5000
122 #define MAX_NOP_FAILURES 3
123 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
124 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
126 /* this threshold is a trade-off knob to choose between
127 * the potential additional overhead of an extra GET_LBA_STATUS request
128 * vs. unnecessarily reading a lot of zero sectors over the wire.
129 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
130 * sectors we check the allocation status of the area covered by the
131 * request first if the allocationmap indicates that the area might be
133 #define ISCSI_CHECKALLOC_THRES 64
140 qemu_bh_delete(acb->bh);
145 acb->common.cb(acb->common.opaque, acb->status);
147 if (acb->task != NULL) {
148 scsi_free_scsi_task(acb->task);
156 iscsi_schedule_bh(IscsiAIOCB *acb)
161 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
162 qemu_bh_schedule(acb->bh);
165 static void iscsi_co_generic_bh_cb(void *opaque)
167 struct IscsiTask *iTask = opaque;
169 qemu_coroutine_enter(iTask->co);
172 static void iscsi_retry_timer_expired(void *opaque)
174 struct IscsiTask *iTask = opaque;
177 qemu_coroutine_enter(iTask->co);
181 static inline unsigned exp_random(double mean)
183 return -mean * log((double)rand() / RAND_MAX);
186 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
187 * libiscsi 1.10.0, together with other constants we need. Use it as
188 * a hint that we have to define them ourselves if needed, to keep the
189 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
190 * the test because SCSI_STATUS_* is an enum.
192 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
193 * an enum, check against the LIBISCSI_API_VERSION macro, which was
194 * introduced in 1.11.0. If it is present, there is no need to define
197 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
198 !defined(LIBISCSI_API_VERSION)
199 #define SCSI_STATUS_TASK_SET_FULL 0x28
200 #define SCSI_STATUS_TIMEOUT 0x0f000002
201 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
202 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
205 static int iscsi_translate_sense(struct scsi_sense *sense)
209 switch (sense->key) {
210 case SCSI_SENSE_NOT_READY:
212 case SCSI_SENSE_DATA_PROTECTION:
214 case SCSI_SENSE_COMMAND_ABORTED:
216 case SCSI_SENSE_ILLEGAL_REQUEST:
222 switch (sense->ascq) {
223 case SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR:
224 case SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE:
225 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB:
226 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST:
229 case SCSI_SENSE_ASCQ_LBA_OUT_OF_RANGE:
232 case SCSI_SENSE_ASCQ_LOGICAL_UNIT_NOT_SUPPORTED:
235 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT:
236 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_CLOSED:
237 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_OPEN:
240 case SCSI_SENSE_ASCQ_WRITE_PROTECTED:
251 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
252 void *command_data, void *opaque)
254 struct IscsiTask *iTask = opaque;
255 struct scsi_task *task = command_data;
257 iTask->status = status;
261 if (status != SCSI_STATUS_GOOD) {
262 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
263 if (status == SCSI_STATUS_CHECK_CONDITION
264 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
265 error_report("iSCSI CheckCondition: %s",
266 iscsi_get_error(iscsi));
270 if (status == SCSI_STATUS_BUSY ||
271 status == SCSI_STATUS_TIMEOUT ||
272 status == SCSI_STATUS_TASK_SET_FULL) {
273 unsigned retry_time =
274 exp_random(iscsi_retry_times[iTask->retries - 1]);
275 if (status == SCSI_STATUS_TIMEOUT) {
276 /* make sure the request is rescheduled AFTER the
277 * reconnect is initiated */
278 retry_time = EVENT_INTERVAL * 2;
279 iTask->iscsilun->request_timed_out = true;
281 error_report("iSCSI Busy/TaskSetFull/TimeOut"
282 " (retry #%u in %u ms): %s",
283 iTask->retries, retry_time,
284 iscsi_get_error(iscsi));
285 aio_timer_init(iTask->iscsilun->aio_context,
286 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
287 SCALE_MS, iscsi_retry_timer_expired, iTask);
288 timer_mod(&iTask->retry_timer,
289 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
294 iTask->err_code = iscsi_translate_sense(&task->sense);
295 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
300 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
301 iscsi_co_generic_bh_cb, iTask);
307 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
309 *iTask = (struct IscsiTask) {
310 .co = qemu_coroutine_self(),
311 .iscsilun = iscsilun,
316 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
319 IscsiAIOCB *acb = private_data;
321 acb->status = -ECANCELED;
322 iscsi_schedule_bh(acb);
326 iscsi_aio_cancel(BlockAIOCB *blockacb)
328 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
329 IscsiLun *iscsilun = acb->iscsilun;
331 if (acb->status != -EINPROGRESS) {
335 /* send a task mgmt call to the target to cancel the task on the target */
336 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
337 iscsi_abort_task_cb, acb);
341 static const AIOCBInfo iscsi_aiocb_info = {
342 .aiocb_size = sizeof(IscsiAIOCB),
343 .cancel_async = iscsi_aio_cancel,
347 static void iscsi_process_read(void *arg);
348 static void iscsi_process_write(void *arg);
351 iscsi_set_events(IscsiLun *iscsilun)
353 struct iscsi_context *iscsi = iscsilun->iscsi;
354 int ev = iscsi_which_events(iscsi);
356 if (ev != iscsilun->events) {
357 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
359 (ev & POLLIN) ? iscsi_process_read : NULL,
360 (ev & POLLOUT) ? iscsi_process_write : NULL,
362 iscsilun->events = ev;
366 static void iscsi_timed_check_events(void *opaque)
368 IscsiLun *iscsilun = opaque;
370 /* check for timed out requests */
371 iscsi_service(iscsilun->iscsi, 0);
373 if (iscsilun->request_timed_out) {
374 iscsilun->request_timed_out = false;
375 iscsi_reconnect(iscsilun->iscsi);
378 /* newer versions of libiscsi may return zero events. Ensure we are able
379 * to return to service once this situation changes. */
380 iscsi_set_events(iscsilun);
382 timer_mod(iscsilun->event_timer,
383 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
387 iscsi_process_read(void *arg)
389 IscsiLun *iscsilun = arg;
390 struct iscsi_context *iscsi = iscsilun->iscsi;
392 iscsi_service(iscsi, POLLIN);
393 iscsi_set_events(iscsilun);
397 iscsi_process_write(void *arg)
399 IscsiLun *iscsilun = arg;
400 struct iscsi_context *iscsi = iscsilun->iscsi;
402 iscsi_service(iscsi, POLLOUT);
403 iscsi_set_events(iscsilun);
406 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
408 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
411 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
413 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
416 static bool is_byte_request_lun_aligned(int64_t offset, int count,
419 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
420 error_report("iSCSI misaligned request: "
421 "iscsilun->block_size %u, offset %" PRIi64
423 iscsilun->block_size, offset, count);
429 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
432 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
433 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
434 nb_sectors << BDRV_SECTOR_BITS,
438 static void iscsi_allocmap_free(IscsiLun *iscsilun)
440 g_free(iscsilun->allocmap);
441 g_free(iscsilun->allocmap_valid);
442 iscsilun->allocmap = NULL;
443 iscsilun->allocmap_valid = NULL;
447 static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
449 iscsi_allocmap_free(iscsilun);
451 iscsilun->allocmap_size =
452 DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks, iscsilun),
453 iscsilun->cluster_sectors);
455 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
456 if (!iscsilun->allocmap) {
460 if (open_flags & BDRV_O_NOCACHE) {
461 /* in case that cache.direct = on all allocmap entries are
462 * treated as invalid to force a relookup of the block
463 * status on every read request */
467 iscsilun->allocmap_valid = bitmap_try_new(iscsilun->allocmap_size);
468 if (!iscsilun->allocmap_valid) {
469 /* if we are under memory pressure free the allocmap as well */
470 iscsi_allocmap_free(iscsilun);
478 iscsi_allocmap_update(IscsiLun *iscsilun, int64_t sector_num,
479 int nb_sectors, bool allocated, bool valid)
481 int64_t cl_num_expanded, nb_cls_expanded, cl_num_shrunk, nb_cls_shrunk;
483 if (iscsilun->allocmap == NULL) {
486 /* expand to entirely contain all affected clusters */
487 cl_num_expanded = sector_num / iscsilun->cluster_sectors;
488 nb_cls_expanded = DIV_ROUND_UP(sector_num + nb_sectors,
489 iscsilun->cluster_sectors) - cl_num_expanded;
490 /* shrink to touch only completely contained clusters */
491 cl_num_shrunk = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
492 nb_cls_shrunk = (sector_num + nb_sectors) / iscsilun->cluster_sectors
495 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
497 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
500 if (iscsilun->allocmap_valid == NULL) {
504 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
506 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
512 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
515 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
519 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
522 /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
523 * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
525 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
528 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
531 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
534 static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
536 if (iscsilun->allocmap) {
537 bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
539 if (iscsilun->allocmap_valid) {
540 bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
545 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
549 if (iscsilun->allocmap == NULL) {
552 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
553 return !(find_next_bit(iscsilun->allocmap, size,
554 sector_num / iscsilun->cluster_sectors) == size);
557 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
558 int64_t sector_num, int nb_sectors)
561 if (iscsilun->allocmap_valid == NULL) {
564 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
565 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
566 sector_num / iscsilun->cluster_sectors) == size);
569 static int coroutine_fn
570 iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
571 QEMUIOVector *iov, int flags)
573 IscsiLun *iscsilun = bs->opaque;
574 struct IscsiTask iTask;
576 uint32_t num_sectors;
577 bool fua = flags & BDRV_REQ_FUA;
580 assert(iscsilun->dpofua);
582 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
586 if (bs->bl.max_transfer) {
587 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
590 lba = sector_qemu2lun(sector_num, iscsilun);
591 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
592 iscsi_co_init_iscsitask(iscsilun, &iTask);
594 if (iscsilun->use_16_for_rw) {
595 iTask.task = iscsi_write16_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);
600 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
601 NULL, num_sectors * iscsilun->block_size,
602 iscsilun->block_size, 0, 0, fua, 0, 0,
603 iscsi_co_generic_cb, &iTask);
605 if (iTask.task == NULL) {
608 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
610 while (!iTask.complete) {
611 iscsi_set_events(iscsilun);
612 qemu_coroutine_yield();
615 if (iTask.task != NULL) {
616 scsi_free_scsi_task(iTask.task);
620 if (iTask.do_retry) {
625 if (iTask.status != SCSI_STATUS_GOOD) {
626 iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
627 return iTask.err_code;
630 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
637 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
639 int nb_sectors, int *pnum,
640 BlockDriverState **file)
642 IscsiLun *iscsilun = bs->opaque;
643 struct scsi_get_lba_status *lbas = NULL;
644 struct scsi_lba_status_descriptor *lbasd = NULL;
645 struct IscsiTask iTask;
648 iscsi_co_init_iscsitask(iscsilun, &iTask);
650 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
655 /* default to all sectors allocated */
656 ret = BDRV_BLOCK_DATA;
657 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
660 /* LUN does not support logical block provisioning */
661 if (!iscsilun->lbpme) {
666 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
667 sector_qemu2lun(sector_num, iscsilun),
668 8 + 16, iscsi_co_generic_cb,
674 while (!iTask.complete) {
675 iscsi_set_events(iscsilun);
676 qemu_coroutine_yield();
679 if (iTask.do_retry) {
680 if (iTask.task != NULL) {
681 scsi_free_scsi_task(iTask.task);
688 if (iTask.status != SCSI_STATUS_GOOD) {
689 /* in case the get_lba_status_callout fails (i.e.
690 * because the device is busy or the cmd is not
691 * supported) we pretend all blocks are allocated
692 * for backwards compatibility */
696 lbas = scsi_datain_unmarshall(iTask.task);
702 lbasd = &lbas->descriptors[0];
704 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
709 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
711 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
712 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
713 ret &= ~BDRV_BLOCK_DATA;
714 if (iscsilun->lbprz) {
715 ret |= BDRV_BLOCK_ZERO;
719 if (ret & BDRV_BLOCK_ZERO) {
720 iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
722 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
725 if (*pnum > nb_sectors) {
729 if (iTask.task != NULL) {
730 scsi_free_scsi_task(iTask.task);
732 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
738 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
739 int64_t sector_num, int nb_sectors,
742 IscsiLun *iscsilun = bs->opaque;
743 struct IscsiTask iTask;
745 uint32_t num_sectors;
747 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
751 if (bs->bl.max_transfer) {
752 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
755 /* if cache.direct is off and we have a valid entry in our allocation map
756 * we can skip checking the block status and directly return zeroes if
757 * the request falls within an unallocated area */
758 if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
759 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
760 qemu_iovec_memset(iov, 0, 0x00, iov->size);
764 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
765 !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
766 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
768 BlockDriverState *file;
769 /* check the block status from the beginning of the cluster
770 * containing the start sector */
771 int64_t ret = iscsi_co_get_block_status(bs,
772 sector_num - sector_num % iscsilun->cluster_sectors,
773 BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
777 /* if the whole request falls into an unallocated area we can avoid
778 * to read and directly return zeroes instead */
779 if (ret & BDRV_BLOCK_ZERO &&
780 pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
781 qemu_iovec_memset(iov, 0, 0x00, iov->size);
786 lba = sector_qemu2lun(sector_num, iscsilun);
787 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
789 iscsi_co_init_iscsitask(iscsilun, &iTask);
791 if (iscsilun->use_16_for_rw) {
792 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
793 num_sectors * iscsilun->block_size,
794 iscsilun->block_size, 0, 0, 0, 0, 0,
795 iscsi_co_generic_cb, &iTask);
797 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
798 num_sectors * iscsilun->block_size,
799 iscsilun->block_size,
801 iscsi_co_generic_cb, &iTask);
803 if (iTask.task == NULL) {
806 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
808 while (!iTask.complete) {
809 iscsi_set_events(iscsilun);
810 qemu_coroutine_yield();
813 if (iTask.task != NULL) {
814 scsi_free_scsi_task(iTask.task);
818 if (iTask.do_retry) {
823 if (iTask.status != SCSI_STATUS_GOOD) {
824 return iTask.err_code;
830 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
832 IscsiLun *iscsilun = bs->opaque;
833 struct IscsiTask iTask;
835 iscsi_co_init_iscsitask(iscsilun, &iTask);
837 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
838 0, iscsi_co_generic_cb, &iTask) == NULL) {
842 while (!iTask.complete) {
843 iscsi_set_events(iscsilun);
844 qemu_coroutine_yield();
847 if (iTask.task != NULL) {
848 scsi_free_scsi_task(iTask.task);
852 if (iTask.do_retry) {
857 if (iTask.status != SCSI_STATUS_GOOD) {
858 return iTask.err_code;
866 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
867 void *command_data, void *opaque)
869 IscsiAIOCB *acb = opaque;
876 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
877 iscsi_get_error(iscsi));
878 acb->status = iscsi_translate_sense(&acb->task->sense);
881 acb->ioh->driver_status = 0;
882 acb->ioh->host_status = 0;
884 acb->ioh->status = status;
886 #define SG_ERR_DRIVER_SENSE 0x08
888 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
891 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
893 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
894 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
895 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
896 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
899 iscsi_schedule_bh(acb);
902 static void iscsi_ioctl_bh_completion(void *opaque)
904 IscsiAIOCB *acb = opaque;
906 qemu_bh_delete(acb->bh);
907 acb->common.cb(acb->common.opaque, acb->ret);
911 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
913 BlockDriverState *bs = acb->common.bs;
914 IscsiLun *iscsilun = bs->opaque;
918 case SG_GET_VERSION_NUM:
922 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
928 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
929 iscsi_ioctl_bh_completion, acb);
931 qemu_bh_schedule(acb->bh);
934 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
935 unsigned long int req, void *buf,
936 BlockCompletionFunc *cb, void *opaque)
938 IscsiLun *iscsilun = bs->opaque;
939 struct iscsi_context *iscsi = iscsilun->iscsi;
940 struct iscsi_data data;
943 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
945 acb->iscsilun = iscsilun;
947 acb->status = -EINPROGRESS;
952 iscsi_ioctl_handle_emulated(acb, req, buf);
956 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
957 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
958 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
963 acb->task = malloc(sizeof(struct scsi_task));
964 if (acb->task == NULL) {
965 error_report("iSCSI: Failed to allocate task for scsi command. %s",
966 iscsi_get_error(iscsi));
970 memset(acb->task, 0, sizeof(struct scsi_task));
972 switch (acb->ioh->dxfer_direction) {
973 case SG_DXFER_TO_DEV:
974 acb->task->xfer_dir = SCSI_XFER_WRITE;
976 case SG_DXFER_FROM_DEV:
977 acb->task->xfer_dir = SCSI_XFER_READ;
980 acb->task->xfer_dir = SCSI_XFER_NONE;
984 acb->task->cdb_size = acb->ioh->cmd_len;
985 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
986 acb->task->expxferlen = acb->ioh->dxfer_len;
989 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
990 if (acb->ioh->iovec_count == 0) {
991 data.data = acb->ioh->dxferp;
992 data.size = acb->ioh->dxfer_len;
994 scsi_task_set_iov_out(acb->task,
995 (struct scsi_iovec *) acb->ioh->dxferp,
996 acb->ioh->iovec_count);
1000 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1002 (data.size > 0) ? &data : NULL,
1004 scsi_free_scsi_task(acb->task);
1005 qemu_aio_unref(acb);
1009 /* tell libiscsi to read straight into the buffer we got from ioctl */
1010 if (acb->task->xfer_dir == SCSI_XFER_READ) {
1011 if (acb->ioh->iovec_count == 0) {
1012 scsi_task_add_data_in_buffer(acb->task,
1013 acb->ioh->dxfer_len,
1016 scsi_task_set_iov_in(acb->task,
1017 (struct scsi_iovec *) acb->ioh->dxferp,
1018 acb->ioh->iovec_count);
1022 iscsi_set_events(iscsilun);
1024 return &acb->common;
1030 iscsi_getlength(BlockDriverState *bs)
1032 IscsiLun *iscsilun = bs->opaque;
1035 len = iscsilun->num_blocks;
1036 len *= iscsilun->block_size;
1042 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int count)
1044 IscsiLun *iscsilun = bs->opaque;
1045 struct IscsiTask iTask;
1046 struct unmap_list list;
1048 assert(is_byte_request_lun_aligned(offset, count, iscsilun));
1050 if (!iscsilun->lbp.lbpu) {
1051 /* UNMAP is not supported by the target */
1055 list.lba = offset / iscsilun->block_size;
1056 list.num = count / iscsilun->block_size;
1058 iscsi_co_init_iscsitask(iscsilun, &iTask);
1060 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1061 iscsi_co_generic_cb, &iTask) == NULL) {
1065 while (!iTask.complete) {
1066 iscsi_set_events(iscsilun);
1067 qemu_coroutine_yield();
1070 if (iTask.task != NULL) {
1071 scsi_free_scsi_task(iTask.task);
1075 if (iTask.do_retry) {
1080 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1081 /* the target might fail with a check condition if it
1082 is not happy with the alignment of the UNMAP request
1083 we silently fail in this case */
1087 if (iTask.status != SCSI_STATUS_GOOD) {
1088 return iTask.err_code;
1091 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1092 count >> BDRV_SECTOR_BITS);
1098 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1099 int count, BdrvRequestFlags flags)
1101 IscsiLun *iscsilun = bs->opaque;
1102 struct IscsiTask iTask;
1105 bool use_16_for_ws = iscsilun->use_16_for_rw;
1107 if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {
1111 if (flags & BDRV_REQ_MAY_UNMAP) {
1112 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1113 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1114 use_16_for_ws = true;
1116 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1117 /* WRITESAME16 with UNMAP is not supported by the target,
1118 * fall back and try WRITESAME10/16 without UNMAP */
1119 flags &= ~BDRV_REQ_MAY_UNMAP;
1120 use_16_for_ws = iscsilun->use_16_for_rw;
1124 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1125 /* WRITESAME without UNMAP is not supported by the target */
1129 lba = offset / iscsilun->block_size;
1130 nb_blocks = count / iscsilun->block_size;
1132 if (iscsilun->zeroblock == NULL) {
1133 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1134 if (iscsilun->zeroblock == NULL) {
1139 iscsi_co_init_iscsitask(iscsilun, &iTask);
1141 if (use_16_for_ws) {
1142 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1143 iscsilun->zeroblock, iscsilun->block_size,
1144 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1145 0, 0, iscsi_co_generic_cb, &iTask);
1147 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1148 iscsilun->zeroblock, iscsilun->block_size,
1149 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1150 0, 0, iscsi_co_generic_cb, &iTask);
1152 if (iTask.task == NULL) {
1156 while (!iTask.complete) {
1157 iscsi_set_events(iscsilun);
1158 qemu_coroutine_yield();
1161 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1162 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1163 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1164 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1165 /* WRITE SAME is not supported by the target */
1166 iscsilun->has_write_same = false;
1167 scsi_free_scsi_task(iTask.task);
1171 if (iTask.task != NULL) {
1172 scsi_free_scsi_task(iTask.task);
1176 if (iTask.do_retry) {
1181 if (iTask.status != SCSI_STATUS_GOOD) {
1182 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1183 count >> BDRV_SECTOR_BITS);
1184 return iTask.err_code;
1187 if (flags & BDRV_REQ_MAY_UNMAP) {
1188 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1189 count >> BDRV_SECTOR_BITS);
1191 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1192 count >> BDRV_SECTOR_BITS);
1198 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1203 const char *user = NULL;
1204 const char *password = NULL;
1205 const char *secretid;
1206 char *secret = NULL;
1208 list = qemu_find_opts("iscsi");
1213 opts = qemu_opts_find(list, target);
1215 opts = QTAILQ_FIRST(&list->head);
1221 user = qemu_opt_get(opts, "user");
1226 secretid = qemu_opt_get(opts, "password-secret");
1227 password = qemu_opt_get(opts, "password");
1228 if (secretid && password) {
1229 error_setg(errp, "'password' and 'password-secret' properties are "
1230 "mutually exclusive");
1234 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1239 } else if (!password) {
1240 error_setg(errp, "CHAP username specified but no password was given");
1244 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1245 error_setg(errp, "Failed to set initiator username and password");
1251 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1256 const char *digest = NULL;
1258 list = qemu_find_opts("iscsi");
1263 opts = qemu_opts_find(list, target);
1265 opts = QTAILQ_FIRST(&list->head);
1271 digest = qemu_opt_get(opts, "header-digest");
1276 if (!strcmp(digest, "CRC32C")) {
1277 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1278 } else if (!strcmp(digest, "NONE")) {
1279 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1280 } else if (!strcmp(digest, "CRC32C-NONE")) {
1281 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1282 } else if (!strcmp(digest, "NONE-CRC32C")) {
1283 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1285 error_setg(errp, "Invalid header-digest setting : %s", digest);
1289 static char *parse_initiator_name(const char *target)
1295 UuidInfo *uuid_info;
1297 list = qemu_find_opts("iscsi");
1299 opts = qemu_opts_find(list, target);
1301 opts = QTAILQ_FIRST(&list->head);
1304 name = qemu_opt_get(opts, "initiator-name");
1306 return g_strdup(name);
1311 uuid_info = qmp_query_uuid(NULL);
1312 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1313 name = qemu_get_vm_name();
1315 name = uuid_info->UUID;
1317 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1318 name ? ":" : "", name ? name : "");
1319 qapi_free_UuidInfo(uuid_info);
1323 static int parse_timeout(const char *target)
1327 const char *timeout;
1329 list = qemu_find_opts("iscsi");
1331 opts = qemu_opts_find(list, target);
1333 opts = QTAILQ_FIRST(&list->head);
1336 timeout = qemu_opt_get(opts, "timeout");
1338 return atoi(timeout);
1346 static void iscsi_nop_timed_event(void *opaque)
1348 IscsiLun *iscsilun = opaque;
1350 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1351 error_report("iSCSI: NOP timeout. Reconnecting...");
1352 iscsilun->request_timed_out = true;
1353 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1354 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1358 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1359 iscsi_set_events(iscsilun);
1362 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1364 struct scsi_task *task = NULL;
1365 struct scsi_readcapacity10 *rc10 = NULL;
1366 struct scsi_readcapacity16 *rc16 = NULL;
1367 int retries = ISCSI_CMD_RETRIES;
1371 scsi_free_scsi_task(task);
1375 switch (iscsilun->type) {
1377 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1378 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1379 rc16 = scsi_datain_unmarshall(task);
1381 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1383 iscsilun->block_size = rc16->block_length;
1384 iscsilun->num_blocks = rc16->returned_lba + 1;
1385 iscsilun->lbpme = !!rc16->lbpme;
1386 iscsilun->lbprz = !!rc16->lbprz;
1387 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1391 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1392 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1395 /* Fall through and try READ CAPACITY(10) instead. */
1397 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1398 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1399 rc10 = scsi_datain_unmarshall(task);
1401 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1403 iscsilun->block_size = rc10->block_size;
1404 if (rc10->lba == 0) {
1405 /* blank disk loaded */
1406 iscsilun->num_blocks = 0;
1408 iscsilun->num_blocks = rc10->lba + 1;
1416 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1417 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1420 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1421 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1422 } else if (!iscsilun->block_size ||
1423 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1424 error_setg(errp, "iSCSI: the target returned an invalid "
1425 "block size of %d.", iscsilun->block_size);
1428 scsi_free_scsi_task(task);
1432 /* TODO Convert to fine grained options */
1433 static QemuOptsList runtime_opts = {
1435 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1439 .type = QEMU_OPT_STRING,
1440 .help = "URL to the iscsi image",
1442 { /* end of list */ }
1446 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1447 int evpd, int pc, void **inq, Error **errp)
1450 struct scsi_task *task = NULL;
1451 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1452 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1455 full_size = scsi_datain_getfullsize(task);
1456 if (full_size > task->datain.size) {
1457 scsi_free_scsi_task(task);
1459 /* we need more data for the full list */
1460 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1461 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1466 *inq = scsi_datain_unmarshall(task);
1468 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1475 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1476 iscsi_get_error(iscsi));
1479 scsi_free_scsi_task(task);
1484 static void iscsi_detach_aio_context(BlockDriverState *bs)
1486 IscsiLun *iscsilun = bs->opaque;
1488 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1489 false, NULL, NULL, NULL);
1490 iscsilun->events = 0;
1492 if (iscsilun->nop_timer) {
1493 timer_del(iscsilun->nop_timer);
1494 timer_free(iscsilun->nop_timer);
1495 iscsilun->nop_timer = NULL;
1497 if (iscsilun->event_timer) {
1498 timer_del(iscsilun->event_timer);
1499 timer_free(iscsilun->event_timer);
1500 iscsilun->event_timer = NULL;
1504 static void iscsi_attach_aio_context(BlockDriverState *bs,
1505 AioContext *new_context)
1507 IscsiLun *iscsilun = bs->opaque;
1509 iscsilun->aio_context = new_context;
1510 iscsi_set_events(iscsilun);
1512 /* Set up a timer for sending out iSCSI NOPs */
1513 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1514 QEMU_CLOCK_REALTIME, SCALE_MS,
1515 iscsi_nop_timed_event, iscsilun);
1516 timer_mod(iscsilun->nop_timer,
1517 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1519 /* Set up a timer for periodic calls to iscsi_set_events and to
1520 * scan for command timeout */
1521 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1522 QEMU_CLOCK_REALTIME, SCALE_MS,
1523 iscsi_timed_check_events, iscsilun);
1524 timer_mod(iscsilun->event_timer,
1525 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1528 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1530 struct scsi_task *task;
1531 struct scsi_mode_sense *ms = NULL;
1532 iscsilun->write_protected = false;
1533 iscsilun->dpofua = false;
1535 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1536 1, SCSI_MODESENSE_PC_CURRENT,
1539 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1540 iscsi_get_error(iscsilun->iscsi));
1544 if (task->status != SCSI_STATUS_GOOD) {
1545 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1548 ms = scsi_datain_unmarshall(task);
1550 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1551 iscsi_get_error(iscsilun->iscsi));
1554 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1555 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1559 scsi_free_scsi_task(task);
1564 * We support iscsi url's on the form
1565 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1567 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1570 IscsiLun *iscsilun = bs->opaque;
1571 struct iscsi_context *iscsi = NULL;
1572 struct iscsi_url *iscsi_url = NULL;
1573 struct scsi_task *task = NULL;
1574 struct scsi_inquiry_standard *inq = NULL;
1575 struct scsi_inquiry_supported_pages *inq_vpd;
1576 char *initiator_name = NULL;
1578 Error *local_err = NULL;
1579 const char *filename;
1580 int i, ret = 0, timeout = 0;
1582 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1583 qemu_opts_absorb_qdict(opts, options, &local_err);
1585 error_propagate(errp, local_err);
1590 filename = qemu_opt_get(opts, "filename");
1592 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1593 if (iscsi_url == NULL) {
1594 error_setg(errp, "Failed to parse URL : %s", filename);
1599 memset(iscsilun, 0, sizeof(IscsiLun));
1601 initiator_name = parse_initiator_name(iscsi_url->target);
1603 iscsi = iscsi_create_context(initiator_name);
1604 if (iscsi == NULL) {
1605 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1610 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1611 error_setg(errp, "iSCSI: Failed to set target name.");
1616 if (iscsi_url->user[0] != '\0') {
1617 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1620 error_setg(errp, "Failed to set initiator username and password");
1626 /* check if we got CHAP username/password via the options */
1627 parse_chap(iscsi, iscsi_url->target, &local_err);
1628 if (local_err != NULL) {
1629 error_propagate(errp, local_err);
1634 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1635 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1640 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1642 /* check if we got HEADER_DIGEST via the options */
1643 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1644 if (local_err != NULL) {
1645 error_propagate(errp, local_err);
1650 /* timeout handling is broken in libiscsi before 1.15.0 */
1651 timeout = parse_timeout(iscsi_url->target);
1652 #if defined(LIBISCSI_API_VERSION) && LIBISCSI_API_VERSION >= 20150621
1653 iscsi_set_timeout(iscsi, timeout);
1656 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1660 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1661 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1662 iscsi_get_error(iscsi));
1667 iscsilun->iscsi = iscsi;
1668 iscsilun->aio_context = bdrv_get_aio_context(bs);
1669 iscsilun->lun = iscsi_url->lun;
1670 iscsilun->has_write_same = true;
1672 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1673 (void **) &inq, errp);
1678 iscsilun->type = inq->periperal_device_type;
1679 scsi_free_scsi_task(task);
1682 iscsi_modesense_sync(iscsilun);
1683 if (iscsilun->dpofua) {
1684 bs->supported_write_flags = BDRV_REQ_FUA;
1686 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1688 /* Check the write protect flag of the LUN if we want to write */
1689 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1690 iscsilun->write_protected) {
1691 error_setg(errp, "Cannot open a write protected LUN as read-write");
1696 iscsi_readcapacity_sync(iscsilun, &local_err);
1697 if (local_err != NULL) {
1698 error_propagate(errp, local_err);
1702 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1704 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1705 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1706 * will try to read from the device to guess the image format.
1708 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1712 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1713 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1714 (void **) &inq_vpd, errp);
1719 for (i = 0; i < inq_vpd->num_pages; i++) {
1720 struct scsi_task *inq_task;
1721 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1722 struct scsi_inquiry_block_limits *inq_bl;
1723 switch (inq_vpd->pages[i]) {
1724 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1725 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1726 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1727 (void **) &inq_lbp, errp);
1728 if (inq_task == NULL) {
1732 memcpy(&iscsilun->lbp, inq_lbp,
1733 sizeof(struct scsi_inquiry_logical_block_provisioning));
1734 scsi_free_scsi_task(inq_task);
1736 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1737 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1738 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1739 (void **) &inq_bl, errp);
1740 if (inq_task == NULL) {
1744 memcpy(&iscsilun->bl, inq_bl,
1745 sizeof(struct scsi_inquiry_block_limits));
1746 scsi_free_scsi_task(inq_task);
1752 scsi_free_scsi_task(task);
1755 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1757 /* Guess the internal cluster (page) size of the iscsi target by the means
1758 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1759 * reasonable size */
1760 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1761 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1762 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1763 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1764 if (iscsilun->lbprz) {
1765 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1770 qemu_opts_del(opts);
1771 g_free(initiator_name);
1772 if (iscsi_url != NULL) {
1773 iscsi_destroy_url(iscsi_url);
1776 scsi_free_scsi_task(task);
1780 if (iscsi != NULL) {
1781 if (iscsi_is_logged_in(iscsi)) {
1782 iscsi_logout_sync(iscsi);
1784 iscsi_destroy_context(iscsi);
1786 memset(iscsilun, 0, sizeof(IscsiLun));
1791 static void iscsi_close(BlockDriverState *bs)
1793 IscsiLun *iscsilun = bs->opaque;
1794 struct iscsi_context *iscsi = iscsilun->iscsi;
1796 iscsi_detach_aio_context(bs);
1797 if (iscsi_is_logged_in(iscsi)) {
1798 iscsi_logout_sync(iscsi);
1800 iscsi_destroy_context(iscsi);
1801 g_free(iscsilun->zeroblock);
1802 iscsi_allocmap_free(iscsilun);
1803 memset(iscsilun, 0, sizeof(IscsiLun));
1806 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1808 /* We don't actually refresh here, but just return data queried in
1809 * iscsi_open(): iscsi targets don't change their limits. */
1811 IscsiLun *iscsilun = bs->opaque;
1812 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1813 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
1815 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
1817 bs->bl.request_alignment = block_size;
1819 if (iscsilun->bl.max_xfer_len) {
1820 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1823 if (max_xfer_len * block_size < INT_MAX) {
1824 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
1827 if (iscsilun->lbp.lbpu) {
1828 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
1829 bs->bl.max_pdiscard =
1830 iscsilun->bl.max_unmap * iscsilun->block_size;
1832 bs->bl.pdiscard_alignment =
1833 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
1835 bs->bl.pdiscard_alignment = iscsilun->block_size;
1838 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
1839 bs->bl.max_pwrite_zeroes =
1840 iscsilun->bl.max_ws_len * iscsilun->block_size;
1842 if (iscsilun->lbp.lbpws) {
1843 bs->bl.pwrite_zeroes_alignment =
1844 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
1846 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
1848 if (iscsilun->bl.opt_xfer_len &&
1849 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
1850 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
1851 iscsilun->block_size);
1855 /* Note that this will not re-establish a connection with an iSCSI target - it
1856 * is effectively a NOP. */
1857 static int iscsi_reopen_prepare(BDRVReopenState *state,
1858 BlockReopenQueue *queue, Error **errp)
1860 IscsiLun *iscsilun = state->bs->opaque;
1862 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1863 error_setg(errp, "Cannot open a write protected LUN as read-write");
1869 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
1871 IscsiLun *iscsilun = reopen_state->bs->opaque;
1873 /* the cache.direct status might have changed */
1874 if (iscsilun->allocmap != NULL) {
1875 iscsi_allocmap_init(iscsilun, reopen_state->flags);
1879 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1881 IscsiLun *iscsilun = bs->opaque;
1882 Error *local_err = NULL;
1884 if (iscsilun->type != TYPE_DISK) {
1888 iscsi_readcapacity_sync(iscsilun, &local_err);
1889 if (local_err != NULL) {
1890 error_free(local_err);
1894 if (offset > iscsi_getlength(bs)) {
1898 if (iscsilun->allocmap != NULL) {
1899 iscsi_allocmap_init(iscsilun, bs->open_flags);
1905 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1908 int64_t total_size = 0;
1909 BlockDriverState *bs;
1910 IscsiLun *iscsilun = NULL;
1915 /* Read out options */
1916 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1918 bs->opaque = g_new0(struct IscsiLun, 1);
1919 iscsilun = bs->opaque;
1921 bs_options = qdict_new();
1922 qdict_put(bs_options, "filename", qstring_from_str(filename));
1923 ret = iscsi_open(bs, bs_options, 0, NULL);
1924 QDECREF(bs_options);
1929 iscsi_detach_aio_context(bs);
1930 if (iscsilun->type != TYPE_DISK) {
1934 if (bs->total_sectors < total_size) {
1941 if (iscsilun->iscsi != NULL) {
1942 iscsi_destroy_context(iscsilun->iscsi);
1950 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1952 IscsiLun *iscsilun = bs->opaque;
1953 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
1954 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1955 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1959 static void iscsi_invalidate_cache(BlockDriverState *bs,
1962 IscsiLun *iscsilun = bs->opaque;
1963 iscsi_allocmap_invalidate(iscsilun);
1966 static QemuOptsList iscsi_create_opts = {
1967 .name = "iscsi-create-opts",
1968 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1971 .name = BLOCK_OPT_SIZE,
1972 .type = QEMU_OPT_SIZE,
1973 .help = "Virtual disk size"
1975 { /* end of list */ }
1979 static BlockDriver bdrv_iscsi = {
1980 .format_name = "iscsi",
1981 .protocol_name = "iscsi",
1983 .instance_size = sizeof(IscsiLun),
1984 .bdrv_needs_filename = true,
1985 .bdrv_file_open = iscsi_open,
1986 .bdrv_close = iscsi_close,
1987 .bdrv_create = iscsi_create,
1988 .create_opts = &iscsi_create_opts,
1989 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1990 .bdrv_reopen_commit = iscsi_reopen_commit,
1991 .bdrv_invalidate_cache = iscsi_invalidate_cache,
1993 .bdrv_getlength = iscsi_getlength,
1994 .bdrv_get_info = iscsi_get_info,
1995 .bdrv_truncate = iscsi_truncate,
1996 .bdrv_refresh_limits = iscsi_refresh_limits,
1998 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1999 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2000 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2001 .bdrv_co_readv = iscsi_co_readv,
2002 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2003 .bdrv_co_flush_to_disk = iscsi_co_flush,
2006 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2009 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2010 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2013 static void iscsi_block_init(void)
2015 bdrv_register(&bdrv_iscsi);
2018 block_init(iscsi_block_init);