s390x/cpumodel: document S390FeatDef.bit not applicable
[qemu/ar7.git] / block / iscsi.c
blob421983dd6ff6bf5c5b48c29edf5ffef5318cd97e
1 /*
2 * QEMU Block driver for iSCSI images
4 * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
5 * Copyright (c) 2012-2017 Peter Lieven <pl@kamp.de>
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu/osdep.h"
28 #include <poll.h>
29 #include <math.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"
37 #include "qemu/iov.h"
38 #include "qemu/option.h"
39 #include "qemu/uuid.h"
40 #include "qmp-commands.h"
41 #include "qapi/error.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>
51 #undef SCSI_XFER_NONE
52 QEMU_BUILD_BUG_ON((int)SCSI_XFER_NONE != (int)ISCSI_XFER_NONE);
54 #ifdef __linux__
55 #include <scsi/sg.h>
56 #endif
58 typedef struct IscsiLun {
59 struct iscsi_context *iscsi;
60 AioContext *aio_context;
61 int lun;
62 enum scsi_inquiry_peripheral_device_type type;
63 int block_size;
64 uint64_t num_blocks;
65 int events;
66 QEMUTimer *nop_timer;
67 QEMUTimer *event_timer;
68 QemuMutex mutex;
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;
88 long allocmap_size;
89 int cluster_sectors;
90 bool use_16_for_rw;
91 bool write_protected;
92 bool lbpme;
93 bool lbprz;
94 bool dpofua;
95 bool has_write_same;
96 bool request_timed_out;
97 } IscsiLun;
99 typedef struct IscsiTask {
100 int status;
101 int complete;
102 int retries;
103 int do_retry;
104 struct scsi_task *task;
105 Coroutine *co;
106 IscsiLun *iscsilun;
107 QEMUTimer retry_timer;
108 int err_code;
109 char *err_str;
110 } IscsiTask;
112 typedef struct IscsiAIOCB {
113 BlockAIOCB common;
114 QEMUBH *bh;
115 IscsiLun *iscsilun;
116 struct scsi_task *task;
117 uint8_t *buf;
118 int status;
119 int64_t sector_num;
120 int nb_sectors;
121 int ret;
122 #ifdef __linux__
123 sg_io_hdr_t *ioh;
124 #endif
125 } IscsiAIOCB;
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
140 * unallocated. */
141 #define ISCSI_CHECKALLOC_THRES 64
143 static void
144 iscsi_bh_cb(void *p)
146 IscsiAIOCB *acb = p;
148 qemu_bh_delete(acb->bh);
150 g_free(acb->buf);
151 acb->buf = NULL;
153 acb->common.cb(acb->common.opaque, acb->status);
155 if (acb->task != NULL) {
156 scsi_free_scsi_task(acb->task);
157 acb->task = NULL;
160 qemu_aio_unref(acb);
163 static void
164 iscsi_schedule_bh(IscsiAIOCB *acb)
166 if (acb->bh) {
167 return;
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;
177 iTask->complete = 1;
178 aio_co_wake(iTask->co);
181 static void iscsi_retry_timer_expired(void *opaque)
183 struct IscsiTask *iTask = opaque;
184 iTask->complete = 1;
185 if (iTask->co) {
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
204 * anything.
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
212 #endif
214 #ifndef LIBISCSI_API_VERSION
215 #define LIBISCSI_API_VERSION 20130701
216 #endif
218 static int iscsi_translate_sense(struct scsi_sense *sense)
220 return - scsi_sense_to_errno(sense->key,
221 (sense->ascq & 0xFF00) >> 8,
222 sense->ascq & 0xFF);
225 /* Called (via iscsi_service) with QemuMutex held. */
226 static void
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;
234 iTask->do_retry = 0;
235 iTask->task = task;
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));
243 iTask->do_retry = 1;
244 goto out;
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);
266 iTask->do_retry = 1;
267 return;
270 iTask->err_code = iscsi_translate_sense(&task->sense);
271 iTask->err_str = g_strdup(iscsi_get_error(iscsi));
274 out:
275 if (iTask->co) {
276 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
277 iscsi_co_generic_bh_cb, iTask);
278 } else {
279 iTask->complete = 1;
283 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
285 *iTask = (struct IscsiTask) {
286 .co = qemu_coroutine_self(),
287 .iscsilun = iscsilun,
291 static void
292 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
293 void *private_data)
295 IscsiAIOCB *acb = private_data;
297 acb->status = -ECANCELED;
298 iscsi_schedule_bh(acb);
301 static void
302 iscsi_aio_cancel(BlockAIOCB *blockacb)
304 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
305 IscsiLun *iscsilun = acb->iscsilun;
307 if (acb->status != -EINPROGRESS) {
308 return;
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. */
327 static void
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),
335 false,
336 (ev & POLLIN) ? iscsi_process_read : NULL,
337 (ev & POLLOUT) ? iscsi_process_write : NULL,
338 NULL,
339 iscsilun);
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);
364 static void
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);
376 static void
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,
399 IscsiLun *iscsilun)
401 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
402 error_report("iSCSI misaligned request: "
403 "iscsilun->block_size %u, offset %" PRIi64
404 ", count %d",
405 iscsilun->block_size, offset, count);
406 return false;
408 return true;
411 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
412 IscsiLun *iscsilun)
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,
417 iscsilun);
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) {
439 return -ENOMEM;
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 */
446 return 0;
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);
453 return -ENOMEM;
456 return 0;
459 static void
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) {
466 return;
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
475 - cl_num_shrunk;
476 if (allocated) {
477 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
478 } else {
479 if (nb_cls_shrunk > 0) {
480 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
484 if (iscsilun->allocmap_valid == NULL) {
485 return;
487 if (valid) {
488 if (nb_cls_shrunk > 0) {
489 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
491 } else {
492 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
493 nb_cls_expanded);
497 static void
498 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
499 int nb_sectors)
501 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
504 static void
505 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
506 int nb_sectors)
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,
515 int nb_sectors)
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);
530 static inline bool
531 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
532 int nb_sectors)
534 unsigned long size;
535 if (iscsilun->allocmap == NULL) {
536 return true;
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)
546 unsigned long size;
547 if (iscsilun->allocmap_valid == NULL) {
548 return false;
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;
561 uint64_t lba;
562 uint32_t num_sectors;
563 bool fua = flags & BDRV_REQ_FUA;
564 int r = 0;
566 if (fua) {
567 assert(iscsilun->dpofua);
569 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
570 return -EINVAL;
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);
581 retry:
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);
589 } else {
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);
596 #else
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);
601 } else {
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);
607 #endif
608 if (iTask.task == NULL) {
609 qemu_mutex_unlock(&iscsilun->mutex);
610 return -ENOMEM;
612 #if LIBISCSI_API_VERSION < (20160603)
613 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
614 iov->niov);
615 #endif
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);
625 iTask.task = NULL;
628 if (iTask.do_retry) {
629 iTask.complete = 0;
630 goto 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,
636 iTask.err_str);
637 r = iTask.err_code;
638 goto out_unlock;
641 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
643 out_unlock:
644 qemu_mutex_unlock(&iscsilun->mutex);
645 g_free(iTask.err_str);
646 return r;
651 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
652 int64_t sector_num,
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;
660 uint64_t lba;
661 int64_t ret;
663 iscsi_co_init_iscsitask(iscsilun, &iTask);
665 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
666 ret = -EINVAL;
667 goto out;
670 /* default to all sectors allocated */
671 ret = BDRV_BLOCK_DATA;
672 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
673 *pnum = nb_sectors;
675 /* LUN does not support logical block provisioning */
676 if (!iscsilun->lbpme) {
677 goto out;
680 lba = sector_qemu2lun(sector_num, iscsilun);
682 qemu_mutex_lock(&iscsilun->mutex);
683 retry:
684 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
685 lba, 8 + 16, iscsi_co_generic_cb,
686 &iTask) == NULL) {
687 ret = -ENOMEM;
688 goto out_unlock;
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);
701 iTask.task = NULL;
703 iTask.complete = 0;
704 goto retry;
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",
713 lba, iTask.err_str);
714 goto out_unlock;
717 lbas = scsi_datain_unmarshall(iTask.task);
718 if (lbas == NULL) {
719 ret = -EIO;
720 goto out_unlock;
723 lbasd = &lbas->descriptors[0];
725 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
726 ret = -EIO;
727 goto out_unlock;
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);
742 } else {
743 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
746 if (*pnum > nb_sectors) {
747 *pnum = nb_sectors;
749 out_unlock:
750 qemu_mutex_unlock(&iscsilun->mutex);
751 g_free(iTask.err_str);
752 out:
753 if (iTask.task != NULL) {
754 scsi_free_scsi_task(iTask.task);
756 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
757 *file = bs;
759 return ret;
762 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
763 int64_t sector_num, int nb_sectors,
764 QEMUIOVector *iov)
766 IscsiLun *iscsilun = bs->opaque;
767 struct IscsiTask iTask;
768 uint64_t lba;
769 uint32_t num_sectors;
770 int r = 0;
772 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
773 return -EINVAL;
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);
786 return 0;
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)) {
792 int pnum;
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);
799 if (ret < 0) {
800 return ret;
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);
807 return 0;
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);
816 retry:
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);
824 } else {
825 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
826 num_sectors * iscsilun->block_size,
827 iscsilun->block_size,
828 0, 0, 0, 0, 0,
829 iscsi_co_generic_cb, &iTask,
830 (struct scsi_iovec *)iov->iov, iov->niov);
832 #else
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);
837 } else {
838 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
839 num_sectors * iscsilun->block_size,
840 iscsilun->block_size,
841 0, 0, 0, 0, 0,
842 iscsi_co_generic_cb, &iTask);
844 #endif
845 if (iTask.task == NULL) {
846 qemu_mutex_unlock(&iscsilun->mutex);
847 return -ENOMEM;
849 #if LIBISCSI_API_VERSION < (20160603)
850 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
851 #endif
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);
861 iTask.task = NULL;
864 if (iTask.do_retry) {
865 iTask.complete = 0;
866 goto retry;
869 if (iTask.status != SCSI_STATUS_GOOD) {
870 error_report("iSCSI READ10/16 failed at lba %" PRIu64 ": %s",
871 lba, iTask.err_str);
872 r = iTask.err_code;
875 qemu_mutex_unlock(&iscsilun->mutex);
876 g_free(iTask.err_str);
877 return r;
880 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
882 IscsiLun *iscsilun = bs->opaque;
883 struct IscsiTask iTask;
884 int r = 0;
886 iscsi_co_init_iscsitask(iscsilun, &iTask);
887 qemu_mutex_lock(&iscsilun->mutex);
888 retry:
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);
892 return -ENOMEM;
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);
904 iTask.task = NULL;
907 if (iTask.do_retry) {
908 iTask.complete = 0;
909 goto retry;
912 if (iTask.status != SCSI_STATUS_GOOD) {
913 error_report("iSCSI SYNCHRONIZECACHE10 failed: %s", iTask.err_str);
914 r = iTask.err_code;
917 qemu_mutex_unlock(&iscsilun->mutex);
918 g_free(iTask.err_str);
919 return r;
922 #ifdef __linux__
923 /* Called (via iscsi_service) with QemuMutex held. */
924 static void
925 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
926 void *command_data, void *opaque)
928 IscsiAIOCB *acb = opaque;
930 g_free(acb->buf);
931 acb->buf = NULL;
933 acb->status = 0;
934 if (status < 0) {
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;
942 acb->ioh->resid = 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) {
948 int ss;
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);
967 qemu_aio_unref(acb);
970 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
972 BlockDriverState *bs = acb->common.bs;
973 IscsiLun *iscsilun = bs->opaque;
974 int ret = 0;
976 switch (req) {
977 case SG_GET_VERSION_NUM:
978 *(int *)buf = 30000;
979 break;
980 case SG_GET_SCSI_ID:
981 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
982 break;
983 default:
984 ret = -EINVAL;
986 assert(!acb->bh);
987 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
988 iscsi_ioctl_bh_completion, acb);
989 acb->ret = ret;
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;
1000 IscsiAIOCB *acb;
1002 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
1004 acb->iscsilun = iscsilun;
1005 acb->bh = NULL;
1006 acb->status = -EINPROGRESS;
1007 acb->buf = NULL;
1008 acb->ioh = buf;
1010 if (req != SG_IO) {
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);
1019 return NULL;
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);
1027 return NULL;
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;
1034 break;
1035 case SG_DXFER_FROM_DEV:
1036 acb->task->xfer_dir = SCSI_XFER_READ;
1037 break;
1038 default:
1039 acb->task->xfer_dir = SCSI_XFER_NONE;
1040 break;
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;
1047 data.size = 0;
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;
1053 } else {
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,
1061 iscsi_aio_ioctl_cb,
1062 (data.size > 0) ? &data : NULL,
1063 acb) != 0) {
1064 qemu_mutex_unlock(&iscsilun->mutex);
1065 scsi_free_scsi_task(acb->task);
1066 qemu_aio_unref(acb);
1067 return NULL;
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,
1075 acb->ioh->dxferp);
1076 } else {
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;
1089 #endif
1091 static int64_t
1092 iscsi_getlength(BlockDriverState *bs)
1094 IscsiLun *iscsilun = bs->opaque;
1095 int64_t len;
1097 len = iscsilun->num_blocks;
1098 len *= iscsilun->block_size;
1100 return len;
1103 static int
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;
1109 int r = 0;
1111 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1112 return -ENOTSUP;
1115 if (!iscsilun->lbp.lbpu) {
1116 /* UNMAP is not supported by the target */
1117 return 0;
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);
1125 retry:
1126 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1127 iscsi_co_generic_cb, &iTask) == NULL) {
1128 r = -ENOMEM;
1129 goto out_unlock;
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);
1141 iTask.task = NULL;
1144 if (iTask.do_retry) {
1145 iTask.complete = 0;
1146 goto 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 */
1156 goto out_unlock;
1159 if (iTask.status != SCSI_STATUS_GOOD) {
1160 error_report("iSCSI UNMAP failed at lba %" PRIu64 ": %s",
1161 list.lba, iTask.err_str);
1162 r = iTask.err_code;
1163 goto out_unlock;
1166 out_unlock:
1167 qemu_mutex_unlock(&iscsilun->mutex);
1168 g_free(iTask.err_str);
1169 return r;
1172 static int
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;
1178 uint64_t lba;
1179 uint32_t nb_blocks;
1180 bool use_16_for_ws = iscsilun->use_16_for_rw;
1181 int r = 0;
1183 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1184 return -ENOTSUP;
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 */
1202 return -ENOTSUP;
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) {
1211 return -ENOMEM;
1215 qemu_mutex_lock(&iscsilun->mutex);
1216 iscsi_co_init_iscsitask(iscsilun, &iTask);
1217 retry:
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);
1223 } else {
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);
1231 return -ENOMEM;
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);
1248 r = -ENOTSUP;
1249 goto out_unlock;
1252 if (iTask.task != NULL) {
1253 scsi_free_scsi_task(iTask.task);
1254 iTask.task = NULL;
1257 if (iTask.do_retry) {
1258 iTask.complete = 0;
1259 goto 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);
1267 r = iTask.err_code;
1268 goto out_unlock;
1271 if (flags & BDRV_REQ_MAY_UNMAP) {
1272 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1273 bytes >> BDRV_SECTOR_BITS);
1274 } else {
1275 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1276 bytes >> BDRV_SECTOR_BITS);
1279 out_unlock:
1280 qemu_mutex_unlock(&iscsilun->mutex);
1281 g_free(iTask.err_str);
1282 return r;
1285 static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
1286 Error **errp)
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");
1294 if (!user) {
1295 return;
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");
1303 return;
1305 if (secretid) {
1306 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1307 if (!secret) {
1308 return;
1310 password = secret;
1311 } else if (!password) {
1312 error_setg(errp, "CHAP username specified but no password was given");
1313 return;
1316 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1317 error_setg(errp, "Failed to set initiator username and password");
1320 g_free(secret);
1323 static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
1324 Error **errp)
1326 const char *digest = NULL;
1328 digest = qemu_opt_get(opts, "header-digest");
1329 if (!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);
1339 } else {
1340 error_setg(errp, "Invalid header-digest setting : %s", digest);
1344 static char *get_initiator_name(QemuOpts *opts)
1346 const char *name;
1347 char *iscsi_name;
1348 UuidInfo *uuid_info;
1350 name = qemu_opt_get(opts, "initiator-name");
1351 if (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();
1358 } else {
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);
1364 return iscsi_name;
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.");
1377 goto out;
1380 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1381 iscsi_set_events(iscsilun);
1383 out:
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;
1394 do {
1395 if (task != NULL) {
1396 scsi_free_scsi_task(task);
1397 task = NULL;
1400 switch (iscsilun->type) {
1401 case TYPE_DISK:
1402 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1403 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1404 rc16 = scsi_datain_unmarshall(task);
1405 if (rc16 == NULL) {
1406 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1407 } else {
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);
1414 break;
1416 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1417 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1418 break;
1420 /* Fall through and try READ CAPACITY(10) instead. */
1421 case TYPE_ROM:
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);
1425 if (rc10 == NULL) {
1426 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1427 } else {
1428 iscsilun->block_size = rc10->block_size;
1429 if (rc10->lba == 0) {
1430 /* blank disk loaded */
1431 iscsilun->num_blocks = 0;
1432 } else {
1433 iscsilun->num_blocks = rc10->lba + 1;
1437 break;
1438 default:
1439 return;
1441 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1442 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1443 && retries-- > 0);
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);
1452 if (task) {
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)
1460 int full_size;
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) {
1464 goto fail;
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) {
1473 goto fail;
1477 *inq = scsi_datain_unmarshall(task);
1478 if (*inq == NULL) {
1479 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1480 goto fail_with_err;
1483 return task;
1485 fail:
1486 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1487 iscsi_get_error(iscsi));
1488 fail_with_err:
1489 if (task != NULL) {
1490 scsi_free_scsi_task(task);
1492 return NULL;
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,
1548 0x3F, 0, 255);
1549 if (task == NULL) {
1550 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1551 iscsi_get_error(iscsilun->iscsi));
1552 goto out;
1555 if (task->status != SCSI_STATUS_GOOD) {
1556 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1557 goto out;
1559 ms = scsi_datain_unmarshall(task);
1560 if (!ms) {
1561 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1562 iscsi_get_error(iscsilun->iscsi));
1563 goto out;
1565 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1566 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1568 out:
1569 if (task) {
1570 scsi_free_scsi_task(task);
1574 static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1576 QemuOptsList *list;
1577 QemuOpts *opts;
1578 const char *user, *password, *password_secret, *initiator_name,
1579 *header_digest, *timeout;
1581 list = qemu_find_opts("iscsi");
1582 if (!list) {
1583 return;
1586 opts = qemu_opts_find(list, target);
1587 if (opts == NULL) {
1588 opts = QTAILQ_FIRST(&list->head);
1589 if (!opts) {
1590 return;
1594 user = qemu_opt_get(opts, "user");
1595 if (user) {
1596 qdict_set_default_str(options, "user", user);
1599 password = qemu_opt_get(opts, "password");
1600 if (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);
1620 g_free(qapi_value);
1623 timeout = qemu_opt_get(opts, "timeout");
1624 if (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,
1634 Error **errp)
1636 struct iscsi_url *iscsi_url;
1637 const char *transport_name;
1638 char *lun_str;
1640 iscsi_url = iscsi_parse_full_url(NULL, filename);
1641 if (iscsi_url == NULL) {
1642 error_setg(errp, "Failed to parse URL : %s", filename);
1643 return;
1646 #if LIBISCSI_API_VERSION >= (20160603)
1647 switch (iscsi_url->transport) {
1648 case TCP_TRANSPORT:
1649 transport_name = "tcp";
1650 break;
1651 case ISER_TRANSPORT:
1652 transport_name = "iser";
1653 break;
1654 default:
1655 error_setg(errp, "Unknown transport type (%d)",
1656 iscsi_url->transport);
1657 return;
1659 #else
1660 transport_name = "tcp";
1661 #endif
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);
1669 g_free(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 = {
1683 .name = "iscsi",
1684 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1685 .desc = {
1687 .name = "transport",
1688 .type = QEMU_OPT_STRING,
1691 .name = "portal",
1692 .type = QEMU_OPT_STRING,
1695 .name = "target",
1696 .type = QEMU_OPT_STRING,
1699 .name = "user",
1700 .type = QEMU_OPT_STRING,
1703 .name = "password",
1704 .type = QEMU_OPT_STRING,
1707 .name = "password-secret",
1708 .type = QEMU_OPT_STRING,
1711 .name = "lun",
1712 .type = QEMU_OPT_NUMBER,
1715 .name = "initiator-name",
1716 .type = QEMU_OPT_STRING,
1719 .name = "header-digest",
1720 .type = QEMU_OPT_STRING,
1723 .name = "timeout",
1724 .type = QEMU_OPT_NUMBER,
1727 .name = "filename",
1728 .type = QEMU_OPT_STRING,
1730 { /* end of list */ }
1734 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1735 Error **errp)
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;
1743 QemuOpts *opts;
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;
1748 #endif
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");
1754 if (filename) {
1755 warn_report("'filename' option specified. "
1756 "This is an unsupported option, and may be deprecated "
1757 "in the future");
1758 iscsi_parse_filename(filename, options, &local_err);
1759 if (local_err) {
1760 ret = -EINVAL;
1761 error_propagate(errp, local_err);
1762 goto exit;
1766 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1767 qemu_opts_absorb_qdict(opts, options, &local_err);
1768 if (local_err) {
1769 error_propagate(errp, local_err);
1770 ret = -EINVAL;
1771 goto out;
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");
1781 ret = -EINVAL;
1782 goto out;
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;
1790 #else
1791 /* TCP is what older libiscsi versions always use */
1792 #endif
1793 } else {
1794 error_setg(errp, "Unknown transport: %s", transport_name);
1795 ret = -EINVAL;
1796 goto out;
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.");
1806 ret = -ENOMEM;
1807 goto out;
1809 #if LIBISCSI_API_VERSION >= (20160603)
1810 if (iscsi_init_transport(iscsi, transport)) {
1811 error_setg(errp, ("Error initializing transport."));
1812 ret = -EINVAL;
1813 goto out;
1815 #endif
1816 if (iscsi_set_targetname(iscsi, target)) {
1817 error_setg(errp, "iSCSI: Failed to set target name.");
1818 ret = -EINVAL;
1819 goto out;
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);
1826 ret = -EINVAL;
1827 goto out;
1830 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1831 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1832 ret = -EINVAL;
1833 goto out;
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);
1840 ret = -EINVAL;
1841 goto out;
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);
1848 #else
1849 if (timeout) {
1850 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1852 #endif
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));
1857 ret = -EINVAL;
1858 goto out;
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);
1868 if (task == NULL) {
1869 ret = -EINVAL;
1870 goto out;
1872 iscsilun->type = inq->periperal_device_type;
1873 scsi_free_scsi_task(task);
1874 task = NULL;
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");
1885 ret = -EACCES;
1886 goto out;
1889 iscsi_readcapacity_sync(iscsilun, &local_err);
1890 if (local_err != NULL) {
1891 error_propagate(errp, local_err);
1892 ret = -EINVAL;
1893 goto out;
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) {
1902 bs->sg = true;
1905 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1906 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1907 (void **) &inq_vpd, errp);
1908 if (task == NULL) {
1909 ret = -EINVAL;
1910 goto out;
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) {
1922 ret = -EINVAL;
1923 goto out;
1925 memcpy(&iscsilun->lbp, inq_lbp,
1926 sizeof(struct scsi_inquiry_logical_block_provisioning));
1927 scsi_free_scsi_task(inq_task);
1928 break;
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) {
1934 ret = -EINVAL;
1935 goto out;
1937 memcpy(&iscsilun->bl, inq_bl,
1938 sizeof(struct scsi_inquiry_block_limits));
1939 scsi_free_scsi_task(inq_task);
1940 break;
1941 default:
1942 break;
1945 scsi_free_scsi_task(task);
1946 task = NULL;
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;
1967 out:
1968 qemu_opts_del(opts);
1969 g_free(initiator_name);
1970 if (task != NULL) {
1971 scsi_free_scsi_task(task);
1974 if (ret) {
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));
1983 exit:
1984 return ret;
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;
2031 } else {
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;
2042 } else {
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");
2061 return -EACCES;
2063 return 0;
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));
2085 return -ENOTSUP;
2088 if (iscsilun->type != TYPE_DISK) {
2089 error_setg(errp, "Cannot resize non-disk iSCSI devices");
2090 return -ENOTSUP;
2093 iscsi_readcapacity_sync(iscsilun, &local_err);
2094 if (local_err != NULL) {
2095 error_propagate(errp, local_err);
2096 return -EIO;
2099 if (offset > iscsi_getlength(bs)) {
2100 error_setg(errp, "Cannot grow iSCSI devices");
2101 return -EINVAL;
2104 if (iscsilun->allocmap != NULL) {
2105 iscsi_allocmap_init(iscsilun, bs->open_flags);
2108 return 0;
2111 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
2113 int ret = 0;
2114 int64_t total_size = 0;
2115 BlockDriverState *bs;
2116 IscsiLun *iscsilun = NULL;
2117 QDict *bs_options;
2118 Error *local_err = NULL;
2120 bs = bdrv_new();
2122 /* Read out options */
2123 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2124 BDRV_SECTOR_SIZE);
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);
2130 if (local_err) {
2131 error_propagate(errp, local_err);
2132 ret = -EINVAL;
2133 } else {
2134 ret = iscsi_open(bs, bs_options, 0, NULL);
2136 QDECREF(bs_options);
2138 if (ret != 0) {
2139 goto out;
2141 iscsi_detach_aio_context(bs);
2142 if (iscsilun->type != TYPE_DISK) {
2143 ret = -ENODEV;
2144 goto out;
2146 if (bs->total_sectors < total_size) {
2147 ret = -ENOSPC;
2148 goto out;
2151 ret = 0;
2152 out:
2153 if (iscsilun->iscsi != NULL) {
2154 iscsi_destroy_context(iscsilun->iscsi);
2156 g_free(bs->opaque);
2157 bs->opaque = NULL;
2158 bdrv_unref(bs);
2159 return ret;
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;
2167 return 0;
2170 static void iscsi_invalidate_cache(BlockDriverState *bs,
2171 Error **errp)
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),
2180 .desc = {
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,
2216 #ifdef __linux__
2217 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2218 #endif
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,
2251 #ifdef __linux__
2252 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2253 #endif
2255 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2256 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2258 #endif
2260 static void iscsi_block_init(void)
2262 bdrv_register(&bdrv_iscsi);
2263 #if LIBISCSI_API_VERSION >= (20160603)
2264 bdrv_register(&bdrv_iser);
2265 #endif
2268 block_init(iscsi_block_init);