block/iscsi: drop unused IscsiAIOCB->buf field
[qemu/kevin.git] / block / iscsi.c
bloba4e3730a82c5e1fdd239edfde2423b5e13488c99
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 "block/qdict.h"
37 #include "scsi/constants.h"
38 #include "qemu/iov.h"
39 #include "qemu/option.h"
40 #include "qemu/uuid.h"
41 #include "qapi/error.h"
42 #include "qapi/qapi-commands-misc.h"
43 #include "qapi/qmp/qdict.h"
44 #include "qapi/qmp/qstring.h"
45 #include "crypto/secret.h"
46 #include "scsi/utils.h"
47 #include "trace.h"
49 /* Conflict between scsi/utils.h and libiscsi! :( */
50 #define SCSI_XFER_NONE ISCSI_XFER_NONE
51 #include <iscsi/iscsi.h>
52 #include <iscsi/scsi-lowlevel.h>
53 #undef SCSI_XFER_NONE
54 QEMU_BUILD_BUG_ON((int)SCSI_XFER_NONE != (int)ISCSI_XFER_NONE);
56 #ifdef __linux__
57 #include <scsi/sg.h>
58 #endif
60 typedef struct IscsiLun {
61 struct iscsi_context *iscsi;
62 AioContext *aio_context;
63 int lun;
64 enum scsi_inquiry_peripheral_device_type type;
65 int block_size;
66 uint64_t num_blocks;
67 int events;
68 QEMUTimer *nop_timer;
69 QEMUTimer *event_timer;
70 QemuMutex mutex;
71 struct scsi_inquiry_logical_block_provisioning lbp;
72 struct scsi_inquiry_block_limits bl;
73 struct scsi_inquiry_device_designator *dd;
74 unsigned char *zeroblock;
75 /* The allocmap tracks which clusters (pages) on the iSCSI target are
76 * allocated and which are not. In case a target returns zeros for
77 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
78 * of reading zeros over the wire if a read request falls within an
79 * unallocated block. As there are 3 possible states we need 2 bitmaps to
80 * track. allocmap_valid keeps track if QEMU's information about a page is
81 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
82 * valid information about a page the corresponding allocmap entry should be
83 * switched to unallocated as well to force a new lookup of the allocation
84 * status as lookups are generally skipped if a page is suspect to be
85 * allocated. If a iSCSI target is opened with cache.direct = on the
86 * allocmap_valid does not exist turning all cached information invalid so
87 * that a fresh lookup is made for any page even if allocmap entry returns
88 * it's unallocated. */
89 unsigned long *allocmap;
90 unsigned long *allocmap_valid;
91 long allocmap_size;
92 int cluster_size;
93 bool use_16_for_rw;
94 bool write_protected;
95 bool lbpme;
96 bool lbprz;
97 bool dpofua;
98 bool has_write_same;
99 bool request_timed_out;
100 } IscsiLun;
102 typedef struct IscsiTask {
103 int status;
104 int complete;
105 int retries;
106 int do_retry;
107 struct scsi_task *task;
108 Coroutine *co;
109 IscsiLun *iscsilun;
110 QEMUTimer retry_timer;
111 int err_code;
112 char *err_str;
113 } IscsiTask;
115 typedef struct IscsiAIOCB {
116 BlockAIOCB common;
117 QEMUBH *bh;
118 IscsiLun *iscsilun;
119 struct scsi_task *task;
120 int status;
121 int64_t sector_num;
122 int nb_sectors;
123 int ret;
124 #ifdef __linux__
125 sg_io_hdr_t *ioh;
126 #endif
127 } IscsiAIOCB;
129 /* libiscsi uses time_t so its enough to process events every second */
130 #define EVENT_INTERVAL 1000
131 #define NOP_INTERVAL 5000
132 #define MAX_NOP_FAILURES 3
133 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
134 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
136 /* this threshold is a trade-off knob to choose between
137 * the potential additional overhead of an extra GET_LBA_STATUS request
138 * vs. unnecessarily reading a lot of zero sectors over the wire.
139 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
140 * sectors we check the allocation status of the area covered by the
141 * request first if the allocationmap indicates that the area might be
142 * unallocated. */
143 #define ISCSI_CHECKALLOC_THRES 64
145 static void
146 iscsi_bh_cb(void *p)
148 IscsiAIOCB *acb = p;
150 qemu_bh_delete(acb->bh);
152 acb->common.cb(acb->common.opaque, acb->status);
154 if (acb->task != NULL) {
155 scsi_free_scsi_task(acb->task);
156 acb->task = NULL;
159 qemu_aio_unref(acb);
162 static void
163 iscsi_schedule_bh(IscsiAIOCB *acb)
165 if (acb->bh) {
166 return;
168 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
169 qemu_bh_schedule(acb->bh);
172 static void iscsi_co_generic_bh_cb(void *opaque)
174 struct IscsiTask *iTask = opaque;
176 iTask->complete = 1;
177 aio_co_wake(iTask->co);
180 static void iscsi_retry_timer_expired(void *opaque)
182 struct IscsiTask *iTask = opaque;
183 iTask->complete = 1;
184 if (iTask->co) {
185 aio_co_wake(iTask->co);
189 static inline unsigned exp_random(double mean)
191 return -mean * log((double)rand() / RAND_MAX);
194 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
195 * libiscsi 1.10.0, together with other constants we need. Use it as
196 * a hint that we have to define them ourselves if needed, to keep the
197 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
198 * the test because SCSI_STATUS_* is an enum.
200 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
201 * an enum, check against the LIBISCSI_API_VERSION macro, which was
202 * introduced in 1.11.0. If it is present, there is no need to define
203 * anything.
205 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
206 !defined(LIBISCSI_API_VERSION)
207 #define SCSI_STATUS_TASK_SET_FULL 0x28
208 #define SCSI_STATUS_TIMEOUT 0x0f000002
209 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
210 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
211 #endif
213 #ifndef LIBISCSI_API_VERSION
214 #define LIBISCSI_API_VERSION 20130701
215 #endif
217 static int iscsi_translate_sense(struct scsi_sense *sense)
219 return - scsi_sense_to_errno(sense->key,
220 (sense->ascq & 0xFF00) >> 8,
221 sense->ascq & 0xFF);
224 /* Called (via iscsi_service) with QemuMutex held. */
225 static void
226 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
227 void *command_data, void *opaque)
229 struct IscsiTask *iTask = opaque;
230 struct scsi_task *task = command_data;
232 iTask->status = status;
233 iTask->do_retry = 0;
234 iTask->task = task;
236 if (status != SCSI_STATUS_GOOD) {
237 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
238 if (status == SCSI_STATUS_CHECK_CONDITION
239 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
240 error_report("iSCSI CheckCondition: %s",
241 iscsi_get_error(iscsi));
242 iTask->do_retry = 1;
243 goto out;
245 if (status == SCSI_STATUS_BUSY ||
246 status == SCSI_STATUS_TIMEOUT ||
247 status == SCSI_STATUS_TASK_SET_FULL) {
248 unsigned retry_time =
249 exp_random(iscsi_retry_times[iTask->retries - 1]);
250 if (status == SCSI_STATUS_TIMEOUT) {
251 /* make sure the request is rescheduled AFTER the
252 * reconnect is initiated */
253 retry_time = EVENT_INTERVAL * 2;
254 iTask->iscsilun->request_timed_out = true;
256 error_report("iSCSI Busy/TaskSetFull/TimeOut"
257 " (retry #%u in %u ms): %s",
258 iTask->retries, retry_time,
259 iscsi_get_error(iscsi));
260 aio_timer_init(iTask->iscsilun->aio_context,
261 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
262 SCALE_MS, iscsi_retry_timer_expired, iTask);
263 timer_mod(&iTask->retry_timer,
264 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
265 iTask->do_retry = 1;
266 return;
269 iTask->err_code = iscsi_translate_sense(&task->sense);
270 iTask->err_str = g_strdup(iscsi_get_error(iscsi));
273 out:
274 if (iTask->co) {
275 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
276 iscsi_co_generic_bh_cb, iTask);
277 } else {
278 iTask->complete = 1;
282 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
284 *iTask = (struct IscsiTask) {
285 .co = qemu_coroutine_self(),
286 .iscsilun = iscsilun,
290 static void
291 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
292 void *private_data)
294 IscsiAIOCB *acb = private_data;
296 acb->status = -ECANCELED;
297 iscsi_schedule_bh(acb);
300 static void
301 iscsi_aio_cancel(BlockAIOCB *blockacb)
303 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
304 IscsiLun *iscsilun = acb->iscsilun;
306 if (acb->status != -EINPROGRESS) {
307 return;
310 /* send a task mgmt call to the target to cancel the task on the target */
311 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
312 iscsi_abort_task_cb, acb);
316 static const AIOCBInfo iscsi_aiocb_info = {
317 .aiocb_size = sizeof(IscsiAIOCB),
318 .cancel_async = iscsi_aio_cancel,
322 static void iscsi_process_read(void *arg);
323 static void iscsi_process_write(void *arg);
325 /* Called with QemuMutex held. */
326 static void
327 iscsi_set_events(IscsiLun *iscsilun)
329 struct iscsi_context *iscsi = iscsilun->iscsi;
330 int ev = iscsi_which_events(iscsi);
332 if (ev != iscsilun->events) {
333 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
334 false,
335 (ev & POLLIN) ? iscsi_process_read : NULL,
336 (ev & POLLOUT) ? iscsi_process_write : NULL,
337 NULL,
338 iscsilun);
339 iscsilun->events = ev;
343 static void iscsi_timed_check_events(void *opaque)
345 IscsiLun *iscsilun = opaque;
347 /* check for timed out requests */
348 iscsi_service(iscsilun->iscsi, 0);
350 if (iscsilun->request_timed_out) {
351 iscsilun->request_timed_out = false;
352 iscsi_reconnect(iscsilun->iscsi);
355 /* newer versions of libiscsi may return zero events. Ensure we are able
356 * to return to service once this situation changes. */
357 iscsi_set_events(iscsilun);
359 timer_mod(iscsilun->event_timer,
360 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
363 static void
364 iscsi_process_read(void *arg)
366 IscsiLun *iscsilun = arg;
367 struct iscsi_context *iscsi = iscsilun->iscsi;
369 qemu_mutex_lock(&iscsilun->mutex);
370 iscsi_service(iscsi, POLLIN);
371 iscsi_set_events(iscsilun);
372 qemu_mutex_unlock(&iscsilun->mutex);
375 static void
376 iscsi_process_write(void *arg)
378 IscsiLun *iscsilun = arg;
379 struct iscsi_context *iscsi = iscsilun->iscsi;
381 qemu_mutex_lock(&iscsilun->mutex);
382 iscsi_service(iscsi, POLLOUT);
383 iscsi_set_events(iscsilun);
384 qemu_mutex_unlock(&iscsilun->mutex);
387 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
389 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
392 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
394 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
397 static bool is_byte_request_lun_aligned(int64_t offset, int count,
398 IscsiLun *iscsilun)
400 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
401 error_report("iSCSI misaligned request: "
402 "iscsilun->block_size %u, offset %" PRIi64
403 ", count %d",
404 iscsilun->block_size, offset, count);
405 return false;
407 return true;
410 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
411 IscsiLun *iscsilun)
413 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
414 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
415 nb_sectors << BDRV_SECTOR_BITS,
416 iscsilun);
419 static void iscsi_allocmap_free(IscsiLun *iscsilun)
421 g_free(iscsilun->allocmap);
422 g_free(iscsilun->allocmap_valid);
423 iscsilun->allocmap = NULL;
424 iscsilun->allocmap_valid = NULL;
428 static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
430 iscsi_allocmap_free(iscsilun);
432 assert(iscsilun->cluster_size);
433 iscsilun->allocmap_size =
434 DIV_ROUND_UP(iscsilun->num_blocks * iscsilun->block_size,
435 iscsilun->cluster_size);
437 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
438 if (!iscsilun->allocmap) {
439 return -ENOMEM;
442 if (open_flags & BDRV_O_NOCACHE) {
443 /* when 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 offset,
461 int64_t bytes, 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 assert(iscsilun->cluster_size);
470 cl_num_expanded = offset / iscsilun->cluster_size;
471 nb_cls_expanded = DIV_ROUND_UP(offset + bytes,
472 iscsilun->cluster_size) - cl_num_expanded;
473 /* shrink to touch only completely contained clusters */
474 cl_num_shrunk = DIV_ROUND_UP(offset, iscsilun->cluster_size);
475 nb_cls_shrunk = (offset + bytes) / iscsilun->cluster_size - 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 offset,
499 int64_t bytes)
501 iscsi_allocmap_update(iscsilun, offset, bytes, true, true);
504 static void
505 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t offset,
506 int64_t bytes)
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, offset, bytes, false, true);
514 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t offset,
515 int64_t bytes)
517 iscsi_allocmap_update(iscsilun, offset, bytes, 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 offset,
532 int64_t bytes)
534 unsigned long size;
535 if (iscsilun->allocmap == NULL) {
536 return true;
538 assert(iscsilun->cluster_size);
539 size = DIV_ROUND_UP(offset + bytes, iscsilun->cluster_size);
540 return !(find_next_bit(iscsilun->allocmap, size,
541 offset / iscsilun->cluster_size) == size);
544 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
545 int64_t offset, int64_t bytes)
547 unsigned long size;
548 if (iscsilun->allocmap_valid == NULL) {
549 return false;
551 assert(iscsilun->cluster_size);
552 size = DIV_ROUND_UP(offset + bytes, iscsilun->cluster_size);
553 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
554 offset / iscsilun->cluster_size) == size);
557 static void coroutine_fn iscsi_co_wait_for_task(IscsiTask *iTask,
558 IscsiLun *iscsilun)
560 while (!iTask->complete) {
561 iscsi_set_events(iscsilun);
562 qemu_mutex_unlock(&iscsilun->mutex);
563 qemu_coroutine_yield();
564 qemu_mutex_lock(&iscsilun->mutex);
568 static int coroutine_fn
569 iscsi_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
570 QEMUIOVector *iov, int flags)
572 IscsiLun *iscsilun = bs->opaque;
573 struct IscsiTask iTask;
574 uint64_t lba;
575 uint32_t num_sectors;
576 bool fua = flags & BDRV_REQ_FUA;
577 int r = 0;
579 if (fua) {
580 assert(iscsilun->dpofua);
582 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
583 return -EINVAL;
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);
593 qemu_mutex_lock(&iscsilun->mutex);
594 retry:
595 if (iscsilun->use_16_for_rw) {
596 #if LIBISCSI_API_VERSION >= (20160603)
597 iTask.task = iscsi_write16_iov_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 (struct scsi_iovec *)iov->iov, iov->niov);
602 } else {
603 iTask.task = iscsi_write10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
604 NULL, num_sectors * iscsilun->block_size,
605 iscsilun->block_size, 0, 0, fua, 0, 0,
606 iscsi_co_generic_cb, &iTask,
607 (struct scsi_iovec *)iov->iov, iov->niov);
609 #else
610 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
611 NULL, num_sectors * iscsilun->block_size,
612 iscsilun->block_size, 0, 0, fua, 0, 0,
613 iscsi_co_generic_cb, &iTask);
614 } else {
615 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
616 NULL, num_sectors * iscsilun->block_size,
617 iscsilun->block_size, 0, 0, fua, 0, 0,
618 iscsi_co_generic_cb, &iTask);
620 #endif
621 if (iTask.task == NULL) {
622 qemu_mutex_unlock(&iscsilun->mutex);
623 return -ENOMEM;
625 #if LIBISCSI_API_VERSION < (20160603)
626 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
627 iov->niov);
628 #endif
629 iscsi_co_wait_for_task(&iTask, iscsilun);
631 if (iTask.task != NULL) {
632 scsi_free_scsi_task(iTask.task);
633 iTask.task = NULL;
636 if (iTask.do_retry) {
637 iTask.complete = 0;
638 goto retry;
641 if (iTask.status != SCSI_STATUS_GOOD) {
642 iscsi_allocmap_set_invalid(iscsilun, sector_num * BDRV_SECTOR_SIZE,
643 nb_sectors * BDRV_SECTOR_SIZE);
644 error_report("iSCSI WRITE10/16 failed at lba %" PRIu64 ": %s", lba,
645 iTask.err_str);
646 r = iTask.err_code;
647 goto out_unlock;
650 iscsi_allocmap_set_allocated(iscsilun, sector_num * BDRV_SECTOR_SIZE,
651 nb_sectors * BDRV_SECTOR_SIZE);
653 out_unlock:
654 qemu_mutex_unlock(&iscsilun->mutex);
655 g_free(iTask.err_str);
656 return r;
661 static int coroutine_fn iscsi_co_block_status(BlockDriverState *bs,
662 bool want_zero, int64_t offset,
663 int64_t bytes, int64_t *pnum,
664 int64_t *map,
665 BlockDriverState **file)
667 IscsiLun *iscsilun = bs->opaque;
668 struct scsi_get_lba_status *lbas = NULL;
669 struct scsi_lba_status_descriptor *lbasd = NULL;
670 struct IscsiTask iTask;
671 uint64_t lba;
672 int ret;
674 iscsi_co_init_iscsitask(iscsilun, &iTask);
676 assert(QEMU_IS_ALIGNED(offset | bytes, iscsilun->block_size));
678 /* default to all sectors allocated */
679 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
680 if (map) {
681 *map = offset;
683 *pnum = bytes;
685 /* LUN does not support logical block provisioning */
686 if (!iscsilun->lbpme) {
687 goto out;
690 lba = offset / iscsilun->block_size;
692 qemu_mutex_lock(&iscsilun->mutex);
693 retry:
694 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
695 lba, 8 + 16, iscsi_co_generic_cb,
696 &iTask) == NULL) {
697 ret = -ENOMEM;
698 goto out_unlock;
700 iscsi_co_wait_for_task(&iTask, iscsilun);
702 if (iTask.do_retry) {
703 if (iTask.task != NULL) {
704 scsi_free_scsi_task(iTask.task);
705 iTask.task = NULL;
707 iTask.complete = 0;
708 goto retry;
711 if (iTask.status != SCSI_STATUS_GOOD) {
712 /* in case the get_lba_status_callout fails (i.e.
713 * because the device is busy or the cmd is not
714 * supported) we pretend all blocks are allocated
715 * for backwards compatibility */
716 error_report("iSCSI GET_LBA_STATUS failed at lba %" PRIu64 ": %s",
717 lba, iTask.err_str);
718 goto out_unlock;
721 lbas = scsi_datain_unmarshall(iTask.task);
722 if (lbas == NULL) {
723 ret = -EIO;
724 goto out_unlock;
727 lbasd = &lbas->descriptors[0];
729 if (lba != lbasd->lba) {
730 ret = -EIO;
731 goto out_unlock;
734 *pnum = (int64_t) lbasd->num_blocks * iscsilun->block_size;
736 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
737 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
738 ret &= ~BDRV_BLOCK_DATA;
739 if (iscsilun->lbprz) {
740 ret |= BDRV_BLOCK_ZERO;
744 if (ret & BDRV_BLOCK_ZERO) {
745 iscsi_allocmap_set_unallocated(iscsilun, offset, *pnum);
746 } else {
747 iscsi_allocmap_set_allocated(iscsilun, offset, *pnum);
750 if (*pnum > bytes) {
751 *pnum = bytes;
753 out_unlock:
754 qemu_mutex_unlock(&iscsilun->mutex);
755 g_free(iTask.err_str);
756 out:
757 if (iTask.task != NULL) {
758 scsi_free_scsi_task(iTask.task);
760 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID && file) {
761 *file = bs;
763 return ret;
766 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
767 int64_t sector_num, int nb_sectors,
768 QEMUIOVector *iov)
770 IscsiLun *iscsilun = bs->opaque;
771 struct IscsiTask iTask;
772 uint64_t lba;
773 uint32_t num_sectors;
774 int r = 0;
776 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
777 return -EINVAL;
780 if (bs->bl.max_transfer) {
781 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
784 /* if cache.direct is off and we have a valid entry in our allocation map
785 * we can skip checking the block status and directly return zeroes if
786 * the request falls within an unallocated area */
787 if (iscsi_allocmap_is_valid(iscsilun, sector_num * BDRV_SECTOR_SIZE,
788 nb_sectors * BDRV_SECTOR_SIZE) &&
789 !iscsi_allocmap_is_allocated(iscsilun, sector_num * BDRV_SECTOR_SIZE,
790 nb_sectors * BDRV_SECTOR_SIZE)) {
791 qemu_iovec_memset(iov, 0, 0x00, iov->size);
792 return 0;
795 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
796 !iscsi_allocmap_is_valid(iscsilun, sector_num * BDRV_SECTOR_SIZE,
797 nb_sectors * BDRV_SECTOR_SIZE) &&
798 !iscsi_allocmap_is_allocated(iscsilun, sector_num * BDRV_SECTOR_SIZE,
799 nb_sectors * BDRV_SECTOR_SIZE)) {
800 int64_t pnum;
801 /* check the block status from the beginning of the cluster
802 * containing the start sector */
803 int64_t head;
804 int ret;
806 assert(iscsilun->cluster_size);
807 head = (sector_num * BDRV_SECTOR_SIZE) % iscsilun->cluster_size;
808 ret = iscsi_co_block_status(bs, true,
809 sector_num * BDRV_SECTOR_SIZE - head,
810 BDRV_REQUEST_MAX_BYTES, &pnum, NULL, NULL);
811 if (ret < 0) {
812 return ret;
814 /* if the whole request falls into an unallocated area we can avoid
815 * reading and directly return zeroes instead */
816 if (ret & BDRV_BLOCK_ZERO &&
817 pnum >= nb_sectors * BDRV_SECTOR_SIZE + head) {
818 qemu_iovec_memset(iov, 0, 0x00, iov->size);
819 return 0;
823 lba = sector_qemu2lun(sector_num, iscsilun);
824 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
826 iscsi_co_init_iscsitask(iscsilun, &iTask);
827 qemu_mutex_lock(&iscsilun->mutex);
828 retry:
829 if (iscsilun->use_16_for_rw) {
830 #if LIBISCSI_API_VERSION >= (20160603)
831 iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
832 num_sectors * iscsilun->block_size,
833 iscsilun->block_size, 0, 0, 0, 0, 0,
834 iscsi_co_generic_cb, &iTask,
835 (struct scsi_iovec *)iov->iov, iov->niov);
836 } else {
837 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
838 num_sectors * iscsilun->block_size,
839 iscsilun->block_size,
840 0, 0, 0, 0, 0,
841 iscsi_co_generic_cb, &iTask,
842 (struct scsi_iovec *)iov->iov, iov->niov);
844 #else
845 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
846 num_sectors * iscsilun->block_size,
847 iscsilun->block_size, 0, 0, 0, 0, 0,
848 iscsi_co_generic_cb, &iTask);
849 } else {
850 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
851 num_sectors * iscsilun->block_size,
852 iscsilun->block_size,
853 0, 0, 0, 0, 0,
854 iscsi_co_generic_cb, &iTask);
856 #endif
857 if (iTask.task == NULL) {
858 qemu_mutex_unlock(&iscsilun->mutex);
859 return -ENOMEM;
861 #if LIBISCSI_API_VERSION < (20160603)
862 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
863 #endif
865 iscsi_co_wait_for_task(&iTask, iscsilun);
866 if (iTask.task != NULL) {
867 scsi_free_scsi_task(iTask.task);
868 iTask.task = NULL;
871 if (iTask.do_retry) {
872 iTask.complete = 0;
873 goto retry;
876 if (iTask.status != SCSI_STATUS_GOOD) {
877 error_report("iSCSI READ10/16 failed at lba %" PRIu64 ": %s",
878 lba, iTask.err_str);
879 r = iTask.err_code;
882 qemu_mutex_unlock(&iscsilun->mutex);
883 g_free(iTask.err_str);
884 return r;
887 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
889 IscsiLun *iscsilun = bs->opaque;
890 struct IscsiTask iTask;
891 int r = 0;
893 iscsi_co_init_iscsitask(iscsilun, &iTask);
894 qemu_mutex_lock(&iscsilun->mutex);
895 retry:
896 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
897 0, iscsi_co_generic_cb, &iTask) == NULL) {
898 qemu_mutex_unlock(&iscsilun->mutex);
899 return -ENOMEM;
902 iscsi_co_wait_for_task(&iTask, iscsilun);
904 if (iTask.task != NULL) {
905 scsi_free_scsi_task(iTask.task);
906 iTask.task = NULL;
909 if (iTask.do_retry) {
910 iTask.complete = 0;
911 goto retry;
914 if (iTask.status != SCSI_STATUS_GOOD) {
915 error_report("iSCSI SYNCHRONIZECACHE10 failed: %s", iTask.err_str);
916 r = iTask.err_code;
919 qemu_mutex_unlock(&iscsilun->mutex);
920 g_free(iTask.err_str);
921 return r;
924 #ifdef __linux__
925 /* Called (via iscsi_service) with QemuMutex held. */
926 static void
927 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
928 void *command_data, void *opaque)
930 IscsiAIOCB *acb = opaque;
932 acb->status = 0;
933 if (status < 0) {
934 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
935 iscsi_get_error(iscsi));
936 acb->status = iscsi_translate_sense(&acb->task->sense);
939 acb->ioh->driver_status = 0;
940 acb->ioh->host_status = 0;
941 acb->ioh->resid = 0;
942 acb->ioh->status = status;
944 #define SG_ERR_DRIVER_SENSE 0x08
946 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
947 int ss;
949 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
951 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
952 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
953 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
954 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
957 iscsi_schedule_bh(acb);
960 static void iscsi_ioctl_bh_completion(void *opaque)
962 IscsiAIOCB *acb = opaque;
964 qemu_bh_delete(acb->bh);
965 acb->common.cb(acb->common.opaque, acb->ret);
966 qemu_aio_unref(acb);
969 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
971 BlockDriverState *bs = acb->common.bs;
972 IscsiLun *iscsilun = bs->opaque;
973 int ret = 0;
975 switch (req) {
976 case SG_GET_VERSION_NUM:
977 *(int *)buf = 30000;
978 break;
979 case SG_GET_SCSI_ID:
980 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
981 break;
982 default:
983 ret = -EINVAL;
985 assert(!acb->bh);
986 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
987 iscsi_ioctl_bh_completion, acb);
988 acb->ret = ret;
989 qemu_bh_schedule(acb->bh);
992 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
993 unsigned long int req, void *buf,
994 BlockCompletionFunc *cb, void *opaque)
996 IscsiLun *iscsilun = bs->opaque;
997 struct iscsi_context *iscsi = iscsilun->iscsi;
998 struct iscsi_data data;
999 IscsiAIOCB *acb;
1001 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
1003 acb->iscsilun = iscsilun;
1004 acb->bh = NULL;
1005 acb->status = -EINPROGRESS;
1006 acb->ioh = buf;
1008 if (req != SG_IO) {
1009 iscsi_ioctl_handle_emulated(acb, req, buf);
1010 return &acb->common;
1013 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
1014 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
1015 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1016 qemu_aio_unref(acb);
1017 return NULL;
1020 acb->task = malloc(sizeof(struct scsi_task));
1021 if (acb->task == NULL) {
1022 error_report("iSCSI: Failed to allocate task for scsi command. %s",
1023 iscsi_get_error(iscsi));
1024 qemu_aio_unref(acb);
1025 return NULL;
1027 memset(acb->task, 0, sizeof(struct scsi_task));
1029 switch (acb->ioh->dxfer_direction) {
1030 case SG_DXFER_TO_DEV:
1031 acb->task->xfer_dir = SCSI_XFER_WRITE;
1032 break;
1033 case SG_DXFER_FROM_DEV:
1034 acb->task->xfer_dir = SCSI_XFER_READ;
1035 break;
1036 default:
1037 acb->task->xfer_dir = SCSI_XFER_NONE;
1038 break;
1041 acb->task->cdb_size = acb->ioh->cmd_len;
1042 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1043 acb->task->expxferlen = acb->ioh->dxfer_len;
1045 data.size = 0;
1046 qemu_mutex_lock(&iscsilun->mutex);
1047 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
1048 if (acb->ioh->iovec_count == 0) {
1049 data.data = acb->ioh->dxferp;
1050 data.size = acb->ioh->dxfer_len;
1051 } else {
1052 scsi_task_set_iov_out(acb->task,
1053 (struct scsi_iovec *) acb->ioh->dxferp,
1054 acb->ioh->iovec_count);
1058 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1059 iscsi_aio_ioctl_cb,
1060 (data.size > 0) ? &data : NULL,
1061 acb) != 0) {
1062 qemu_mutex_unlock(&iscsilun->mutex);
1063 scsi_free_scsi_task(acb->task);
1064 qemu_aio_unref(acb);
1065 return NULL;
1068 /* tell libiscsi to read straight into the buffer we got from ioctl */
1069 if (acb->task->xfer_dir == SCSI_XFER_READ) {
1070 if (acb->ioh->iovec_count == 0) {
1071 scsi_task_add_data_in_buffer(acb->task,
1072 acb->ioh->dxfer_len,
1073 acb->ioh->dxferp);
1074 } else {
1075 scsi_task_set_iov_in(acb->task,
1076 (struct scsi_iovec *) acb->ioh->dxferp,
1077 acb->ioh->iovec_count);
1081 iscsi_set_events(iscsilun);
1082 qemu_mutex_unlock(&iscsilun->mutex);
1084 return &acb->common;
1087 #endif
1089 static int64_t
1090 iscsi_getlength(BlockDriverState *bs)
1092 IscsiLun *iscsilun = bs->opaque;
1093 int64_t len;
1095 len = iscsilun->num_blocks;
1096 len *= iscsilun->block_size;
1098 return len;
1101 static int
1102 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
1104 IscsiLun *iscsilun = bs->opaque;
1105 struct IscsiTask iTask;
1106 struct unmap_list list;
1107 int r = 0;
1109 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1110 return -ENOTSUP;
1113 if (!iscsilun->lbp.lbpu) {
1114 /* UNMAP is not supported by the target */
1115 return 0;
1118 list.lba = offset / iscsilun->block_size;
1119 list.num = bytes / iscsilun->block_size;
1121 iscsi_co_init_iscsitask(iscsilun, &iTask);
1122 qemu_mutex_lock(&iscsilun->mutex);
1123 retry:
1124 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1125 iscsi_co_generic_cb, &iTask) == NULL) {
1126 r = -ENOMEM;
1127 goto out_unlock;
1130 iscsi_co_wait_for_task(&iTask, iscsilun);
1132 if (iTask.task != NULL) {
1133 scsi_free_scsi_task(iTask.task);
1134 iTask.task = NULL;
1137 if (iTask.do_retry) {
1138 iTask.complete = 0;
1139 goto retry;
1142 iscsi_allocmap_set_invalid(iscsilun, offset, bytes);
1144 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1145 /* the target might fail with a check condition if it
1146 is not happy with the alignment of the UNMAP request
1147 we silently fail in this case */
1148 goto out_unlock;
1151 if (iTask.status != SCSI_STATUS_GOOD) {
1152 error_report("iSCSI UNMAP failed at lba %" PRIu64 ": %s",
1153 list.lba, iTask.err_str);
1154 r = iTask.err_code;
1155 goto out_unlock;
1158 out_unlock:
1159 qemu_mutex_unlock(&iscsilun->mutex);
1160 g_free(iTask.err_str);
1161 return r;
1164 static int
1165 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1166 int bytes, BdrvRequestFlags flags)
1168 IscsiLun *iscsilun = bs->opaque;
1169 struct IscsiTask iTask;
1170 uint64_t lba;
1171 uint32_t nb_blocks;
1172 bool use_16_for_ws = iscsilun->use_16_for_rw;
1173 int r = 0;
1175 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
1176 return -ENOTSUP;
1179 if (flags & BDRV_REQ_MAY_UNMAP) {
1180 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1181 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1182 use_16_for_ws = true;
1184 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1185 /* WRITESAME16 with UNMAP is not supported by the target,
1186 * fall back and try WRITESAME10/16 without UNMAP */
1187 flags &= ~BDRV_REQ_MAY_UNMAP;
1188 use_16_for_ws = iscsilun->use_16_for_rw;
1192 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1193 /* WRITESAME without UNMAP is not supported by the target */
1194 return -ENOTSUP;
1197 lba = offset / iscsilun->block_size;
1198 nb_blocks = bytes / iscsilun->block_size;
1200 if (iscsilun->zeroblock == NULL) {
1201 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1202 if (iscsilun->zeroblock == NULL) {
1203 return -ENOMEM;
1207 qemu_mutex_lock(&iscsilun->mutex);
1208 iscsi_co_init_iscsitask(iscsilun, &iTask);
1209 retry:
1210 if (use_16_for_ws) {
1211 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1212 iscsilun->zeroblock, iscsilun->block_size,
1213 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1214 0, 0, iscsi_co_generic_cb, &iTask);
1215 } else {
1216 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1217 iscsilun->zeroblock, iscsilun->block_size,
1218 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1219 0, 0, iscsi_co_generic_cb, &iTask);
1221 if (iTask.task == NULL) {
1222 qemu_mutex_unlock(&iscsilun->mutex);
1223 return -ENOMEM;
1226 iscsi_co_wait_for_task(&iTask, iscsilun);
1228 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1229 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1230 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1231 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1232 /* WRITE SAME is not supported by the target */
1233 iscsilun->has_write_same = false;
1234 scsi_free_scsi_task(iTask.task);
1235 r = -ENOTSUP;
1236 goto out_unlock;
1239 if (iTask.task != NULL) {
1240 scsi_free_scsi_task(iTask.task);
1241 iTask.task = NULL;
1244 if (iTask.do_retry) {
1245 iTask.complete = 0;
1246 goto retry;
1249 if (iTask.status != SCSI_STATUS_GOOD) {
1250 iscsi_allocmap_set_invalid(iscsilun, offset, bytes);
1251 error_report("iSCSI WRITESAME10/16 failed at lba %" PRIu64 ": %s",
1252 lba, iTask.err_str);
1253 r = iTask.err_code;
1254 goto out_unlock;
1257 if (flags & BDRV_REQ_MAY_UNMAP) {
1258 iscsi_allocmap_set_invalid(iscsilun, offset, bytes);
1259 } else {
1260 iscsi_allocmap_set_allocated(iscsilun, offset, bytes);
1263 out_unlock:
1264 qemu_mutex_unlock(&iscsilun->mutex);
1265 g_free(iTask.err_str);
1266 return r;
1269 static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
1270 Error **errp)
1272 const char *user = NULL;
1273 const char *password = NULL;
1274 const char *secretid;
1275 char *secret = NULL;
1277 user = qemu_opt_get(opts, "user");
1278 if (!user) {
1279 return;
1282 secretid = qemu_opt_get(opts, "password-secret");
1283 password = qemu_opt_get(opts, "password");
1284 if (secretid && password) {
1285 error_setg(errp, "'password' and 'password-secret' properties are "
1286 "mutually exclusive");
1287 return;
1289 if (secretid) {
1290 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1291 if (!secret) {
1292 return;
1294 password = secret;
1295 } else if (!password) {
1296 error_setg(errp, "CHAP username specified but no password was given");
1297 return;
1300 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1301 error_setg(errp, "Failed to set initiator username and password");
1304 g_free(secret);
1307 static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
1308 Error **errp)
1310 const char *digest = NULL;
1312 digest = qemu_opt_get(opts, "header-digest");
1313 if (!digest) {
1314 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1315 } else if (!strcmp(digest, "crc32c")) {
1316 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1317 } else if (!strcmp(digest, "none")) {
1318 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1319 } else if (!strcmp(digest, "crc32c-none")) {
1320 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1321 } else if (!strcmp(digest, "none-crc32c")) {
1322 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1323 } else {
1324 error_setg(errp, "Invalid header-digest setting : %s", digest);
1328 static char *get_initiator_name(QemuOpts *opts)
1330 const char *name;
1331 char *iscsi_name;
1332 UuidInfo *uuid_info;
1334 name = qemu_opt_get(opts, "initiator-name");
1335 if (name) {
1336 return g_strdup(name);
1339 uuid_info = qmp_query_uuid(NULL);
1340 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1341 name = qemu_get_vm_name();
1342 } else {
1343 name = uuid_info->UUID;
1345 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1346 name ? ":" : "", name ? name : "");
1347 qapi_free_UuidInfo(uuid_info);
1348 return iscsi_name;
1351 static void iscsi_nop_timed_event(void *opaque)
1353 IscsiLun *iscsilun = opaque;
1355 qemu_mutex_lock(&iscsilun->mutex);
1356 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1357 error_report("iSCSI: NOP timeout. Reconnecting...");
1358 iscsilun->request_timed_out = true;
1359 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1360 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1361 goto out;
1364 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1365 iscsi_set_events(iscsilun);
1367 out:
1368 qemu_mutex_unlock(&iscsilun->mutex);
1371 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1373 struct scsi_task *task = NULL;
1374 struct scsi_readcapacity10 *rc10 = NULL;
1375 struct scsi_readcapacity16 *rc16 = NULL;
1376 int retries = ISCSI_CMD_RETRIES;
1378 do {
1379 if (task != NULL) {
1380 scsi_free_scsi_task(task);
1381 task = NULL;
1384 switch (iscsilun->type) {
1385 case TYPE_DISK:
1386 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1387 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1388 rc16 = scsi_datain_unmarshall(task);
1389 if (rc16 == NULL) {
1390 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1391 } else {
1392 iscsilun->block_size = rc16->block_length;
1393 iscsilun->num_blocks = rc16->returned_lba + 1;
1394 iscsilun->lbpme = !!rc16->lbpme;
1395 iscsilun->lbprz = !!rc16->lbprz;
1396 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1398 break;
1400 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1401 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1402 break;
1404 /* Fall through and try READ CAPACITY(10) instead. */
1405 case TYPE_ROM:
1406 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1407 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1408 rc10 = scsi_datain_unmarshall(task);
1409 if (rc10 == NULL) {
1410 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1411 } else {
1412 iscsilun->block_size = rc10->block_size;
1413 if (rc10->lba == 0) {
1414 /* blank disk loaded */
1415 iscsilun->num_blocks = 0;
1416 } else {
1417 iscsilun->num_blocks = rc10->lba + 1;
1421 break;
1422 default:
1423 return;
1425 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1426 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1427 && retries-- > 0);
1429 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1430 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1431 } else if (!iscsilun->block_size ||
1432 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1433 error_setg(errp, "iSCSI: the target returned an invalid "
1434 "block size of %d.", iscsilun->block_size);
1436 if (task) {
1437 scsi_free_scsi_task(task);
1441 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1442 int evpd, int pc, void **inq, Error **errp)
1444 int full_size;
1445 struct scsi_task *task = NULL;
1446 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1447 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1448 goto fail;
1450 full_size = scsi_datain_getfullsize(task);
1451 if (full_size > task->datain.size) {
1452 scsi_free_scsi_task(task);
1454 /* we need more data for the full list */
1455 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1456 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1457 goto fail;
1461 *inq = scsi_datain_unmarshall(task);
1462 if (*inq == NULL) {
1463 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1464 goto fail_with_err;
1467 return task;
1469 fail:
1470 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1471 iscsi_get_error(iscsi));
1472 fail_with_err:
1473 if (task != NULL) {
1474 scsi_free_scsi_task(task);
1476 return NULL;
1479 static void iscsi_detach_aio_context(BlockDriverState *bs)
1481 IscsiLun *iscsilun = bs->opaque;
1483 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1484 false, NULL, NULL, NULL, NULL);
1485 iscsilun->events = 0;
1487 if (iscsilun->nop_timer) {
1488 timer_del(iscsilun->nop_timer);
1489 timer_free(iscsilun->nop_timer);
1490 iscsilun->nop_timer = NULL;
1492 if (iscsilun->event_timer) {
1493 timer_del(iscsilun->event_timer);
1494 timer_free(iscsilun->event_timer);
1495 iscsilun->event_timer = NULL;
1499 static void iscsi_attach_aio_context(BlockDriverState *bs,
1500 AioContext *new_context)
1502 IscsiLun *iscsilun = bs->opaque;
1504 iscsilun->aio_context = new_context;
1505 iscsi_set_events(iscsilun);
1507 /* Set up a timer for sending out iSCSI NOPs */
1508 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1509 QEMU_CLOCK_REALTIME, SCALE_MS,
1510 iscsi_nop_timed_event, iscsilun);
1511 timer_mod(iscsilun->nop_timer,
1512 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1514 /* Set up a timer for periodic calls to iscsi_set_events and to
1515 * scan for command timeout */
1516 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1517 QEMU_CLOCK_REALTIME, SCALE_MS,
1518 iscsi_timed_check_events, iscsilun);
1519 timer_mod(iscsilun->event_timer,
1520 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1523 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1525 struct scsi_task *task;
1526 struct scsi_mode_sense *ms = NULL;
1527 iscsilun->write_protected = false;
1528 iscsilun->dpofua = false;
1530 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1531 1, SCSI_MODESENSE_PC_CURRENT,
1532 0x3F, 0, 255);
1533 if (task == NULL) {
1534 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1535 iscsi_get_error(iscsilun->iscsi));
1536 goto out;
1539 if (task->status != SCSI_STATUS_GOOD) {
1540 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1541 goto out;
1543 ms = scsi_datain_unmarshall(task);
1544 if (!ms) {
1545 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1546 iscsi_get_error(iscsilun->iscsi));
1547 goto out;
1549 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1550 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1552 out:
1553 if (task) {
1554 scsi_free_scsi_task(task);
1558 static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1560 QemuOptsList *list;
1561 QemuOpts *opts;
1562 const char *user, *password, *password_secret, *initiator_name,
1563 *header_digest, *timeout;
1565 list = qemu_find_opts("iscsi");
1566 if (!list) {
1567 return;
1570 opts = qemu_opts_find(list, target);
1571 if (opts == NULL) {
1572 opts = QTAILQ_FIRST(&list->head);
1573 if (!opts) {
1574 return;
1578 user = qemu_opt_get(opts, "user");
1579 if (user) {
1580 qdict_set_default_str(options, "user", user);
1583 password = qemu_opt_get(opts, "password");
1584 if (password) {
1585 qdict_set_default_str(options, "password", password);
1588 password_secret = qemu_opt_get(opts, "password-secret");
1589 if (password_secret) {
1590 qdict_set_default_str(options, "password-secret", password_secret);
1593 initiator_name = qemu_opt_get(opts, "initiator-name");
1594 if (initiator_name) {
1595 qdict_set_default_str(options, "initiator-name", initiator_name);
1598 header_digest = qemu_opt_get(opts, "header-digest");
1599 if (header_digest) {
1600 /* -iscsi takes upper case values, but QAPI only supports lower case
1601 * enum constant names, so we have to convert here. */
1602 char *qapi_value = g_ascii_strdown(header_digest, -1);
1603 qdict_set_default_str(options, "header-digest", qapi_value);
1604 g_free(qapi_value);
1607 timeout = qemu_opt_get(opts, "timeout");
1608 if (timeout) {
1609 qdict_set_default_str(options, "timeout", timeout);
1614 * We support iscsi url's on the form
1615 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1617 static void iscsi_parse_filename(const char *filename, QDict *options,
1618 Error **errp)
1620 struct iscsi_url *iscsi_url;
1621 const char *transport_name;
1622 char *lun_str;
1624 iscsi_url = iscsi_parse_full_url(NULL, filename);
1625 if (iscsi_url == NULL) {
1626 error_setg(errp, "Failed to parse URL : %s", filename);
1627 return;
1630 #if LIBISCSI_API_VERSION >= (20160603)
1631 switch (iscsi_url->transport) {
1632 case TCP_TRANSPORT:
1633 transport_name = "tcp";
1634 break;
1635 case ISER_TRANSPORT:
1636 transport_name = "iser";
1637 break;
1638 default:
1639 error_setg(errp, "Unknown transport type (%d)",
1640 iscsi_url->transport);
1641 return;
1643 #else
1644 transport_name = "tcp";
1645 #endif
1647 qdict_set_default_str(options, "transport", transport_name);
1648 qdict_set_default_str(options, "portal", iscsi_url->portal);
1649 qdict_set_default_str(options, "target", iscsi_url->target);
1651 lun_str = g_strdup_printf("%d", iscsi_url->lun);
1652 qdict_set_default_str(options, "lun", lun_str);
1653 g_free(lun_str);
1655 /* User/password from -iscsi take precedence over those from the URL */
1656 iscsi_parse_iscsi_option(iscsi_url->target, options);
1658 if (iscsi_url->user[0] != '\0') {
1659 qdict_set_default_str(options, "user", iscsi_url->user);
1660 qdict_set_default_str(options, "password", iscsi_url->passwd);
1663 iscsi_destroy_url(iscsi_url);
1666 static QemuOptsList runtime_opts = {
1667 .name = "iscsi",
1668 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1669 .desc = {
1671 .name = "transport",
1672 .type = QEMU_OPT_STRING,
1675 .name = "portal",
1676 .type = QEMU_OPT_STRING,
1679 .name = "target",
1680 .type = QEMU_OPT_STRING,
1683 .name = "user",
1684 .type = QEMU_OPT_STRING,
1687 .name = "password",
1688 .type = QEMU_OPT_STRING,
1691 .name = "password-secret",
1692 .type = QEMU_OPT_STRING,
1695 .name = "lun",
1696 .type = QEMU_OPT_NUMBER,
1699 .name = "initiator-name",
1700 .type = QEMU_OPT_STRING,
1703 .name = "header-digest",
1704 .type = QEMU_OPT_STRING,
1707 .name = "timeout",
1708 .type = QEMU_OPT_NUMBER,
1710 { /* end of list */ }
1714 static void iscsi_save_designator(IscsiLun *lun,
1715 struct scsi_inquiry_device_identification *inq_di)
1717 struct scsi_inquiry_device_designator *desig, *copy = NULL;
1719 for (desig = inq_di->designators; desig; desig = desig->next) {
1720 if (desig->association ||
1721 desig->designator_type > SCSI_DESIGNATOR_TYPE_NAA) {
1722 continue;
1724 /* NAA works better than T10 vendor ID based designator. */
1725 if (!copy || copy->designator_type < desig->designator_type) {
1726 copy = desig;
1729 if (copy) {
1730 lun->dd = g_new(struct scsi_inquiry_device_designator, 1);
1731 *lun->dd = *copy;
1732 lun->dd->next = NULL;
1733 lun->dd->designator = g_malloc(copy->designator_length);
1734 memcpy(lun->dd->designator, copy->designator, copy->designator_length);
1738 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1739 Error **errp)
1741 IscsiLun *iscsilun = bs->opaque;
1742 struct iscsi_context *iscsi = NULL;
1743 struct scsi_task *task = NULL;
1744 struct scsi_inquiry_standard *inq = NULL;
1745 struct scsi_inquiry_supported_pages *inq_vpd;
1746 char *initiator_name = NULL;
1747 QemuOpts *opts;
1748 Error *local_err = NULL;
1749 const char *transport_name, *portal, *target;
1750 #if LIBISCSI_API_VERSION >= (20160603)
1751 enum iscsi_transport_type transport;
1752 #endif
1753 int i, ret = 0, timeout = 0, lun;
1755 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1756 qemu_opts_absorb_qdict(opts, options, &local_err);
1757 if (local_err) {
1758 error_propagate(errp, local_err);
1759 ret = -EINVAL;
1760 goto out;
1763 transport_name = qemu_opt_get(opts, "transport");
1764 portal = qemu_opt_get(opts, "portal");
1765 target = qemu_opt_get(opts, "target");
1766 lun = qemu_opt_get_number(opts, "lun", 0);
1768 if (!transport_name || !portal || !target) {
1769 error_setg(errp, "Need all of transport, portal and target options");
1770 ret = -EINVAL;
1771 goto out;
1774 if (!strcmp(transport_name, "tcp")) {
1775 #if LIBISCSI_API_VERSION >= (20160603)
1776 transport = TCP_TRANSPORT;
1777 } else if (!strcmp(transport_name, "iser")) {
1778 transport = ISER_TRANSPORT;
1779 #else
1780 /* TCP is what older libiscsi versions always use */
1781 #endif
1782 } else {
1783 error_setg(errp, "Unknown transport: %s", transport_name);
1784 ret = -EINVAL;
1785 goto out;
1788 memset(iscsilun, 0, sizeof(IscsiLun));
1790 initiator_name = get_initiator_name(opts);
1792 iscsi = iscsi_create_context(initiator_name);
1793 if (iscsi == NULL) {
1794 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1795 ret = -ENOMEM;
1796 goto out;
1798 #if LIBISCSI_API_VERSION >= (20160603)
1799 if (iscsi_init_transport(iscsi, transport)) {
1800 error_setg(errp, ("Error initializing transport."));
1801 ret = -EINVAL;
1802 goto out;
1804 #endif
1805 if (iscsi_set_targetname(iscsi, target)) {
1806 error_setg(errp, "iSCSI: Failed to set target name.");
1807 ret = -EINVAL;
1808 goto out;
1811 /* check if we got CHAP username/password via the options */
1812 apply_chap(iscsi, opts, &local_err);
1813 if (local_err != NULL) {
1814 error_propagate(errp, local_err);
1815 ret = -EINVAL;
1816 goto out;
1819 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1820 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1821 ret = -EINVAL;
1822 goto out;
1825 /* check if we got HEADER_DIGEST via the options */
1826 apply_header_digest(iscsi, opts, &local_err);
1827 if (local_err != NULL) {
1828 error_propagate(errp, local_err);
1829 ret = -EINVAL;
1830 goto out;
1833 /* timeout handling is broken in libiscsi before 1.15.0 */
1834 timeout = qemu_opt_get_number(opts, "timeout", 0);
1835 #if LIBISCSI_API_VERSION >= 20150621
1836 iscsi_set_timeout(iscsi, timeout);
1837 #else
1838 if (timeout) {
1839 warn_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1841 #endif
1843 if (iscsi_full_connect_sync(iscsi, portal, lun) != 0) {
1844 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1845 iscsi_get_error(iscsi));
1846 ret = -EINVAL;
1847 goto out;
1850 iscsilun->iscsi = iscsi;
1851 iscsilun->aio_context = bdrv_get_aio_context(bs);
1852 iscsilun->lun = lun;
1853 iscsilun->has_write_same = true;
1855 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1856 (void **) &inq, errp);
1857 if (task == NULL) {
1858 ret = -EINVAL;
1859 goto out;
1861 iscsilun->type = inq->periperal_device_type;
1862 scsi_free_scsi_task(task);
1863 task = NULL;
1865 iscsi_modesense_sync(iscsilun);
1866 if (iscsilun->dpofua) {
1867 bs->supported_write_flags = BDRV_REQ_FUA;
1870 /* Check the write protect flag of the LUN if we want to write */
1871 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1872 iscsilun->write_protected) {
1873 ret = bdrv_apply_auto_read_only(bs, "LUN is write protected", errp);
1874 if (ret < 0) {
1875 goto out;
1877 flags &= ~BDRV_O_RDWR;
1880 iscsi_readcapacity_sync(iscsilun, &local_err);
1881 if (local_err != NULL) {
1882 error_propagate(errp, local_err);
1883 ret = -EINVAL;
1884 goto out;
1886 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1888 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1889 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1890 * will try to read from the device to guess the image format.
1892 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1893 bs->sg = true;
1896 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1897 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1898 (void **) &inq_vpd, errp);
1899 if (task == NULL) {
1900 ret = -EINVAL;
1901 goto out;
1903 for (i = 0; i < inq_vpd->num_pages; i++) {
1904 struct scsi_task *inq_task;
1905 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1906 struct scsi_inquiry_block_limits *inq_bl;
1907 struct scsi_inquiry_device_identification *inq_di;
1908 switch (inq_vpd->pages[i]) {
1909 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1910 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1911 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1912 (void **) &inq_lbp, errp);
1913 if (inq_task == NULL) {
1914 ret = -EINVAL;
1915 goto out;
1917 memcpy(&iscsilun->lbp, inq_lbp,
1918 sizeof(struct scsi_inquiry_logical_block_provisioning));
1919 scsi_free_scsi_task(inq_task);
1920 break;
1921 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1922 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1923 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1924 (void **) &inq_bl, errp);
1925 if (inq_task == NULL) {
1926 ret = -EINVAL;
1927 goto out;
1929 memcpy(&iscsilun->bl, inq_bl,
1930 sizeof(struct scsi_inquiry_block_limits));
1931 scsi_free_scsi_task(inq_task);
1932 break;
1933 case SCSI_INQUIRY_PAGECODE_DEVICE_IDENTIFICATION:
1934 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1935 SCSI_INQUIRY_PAGECODE_DEVICE_IDENTIFICATION,
1936 (void **) &inq_di, errp);
1937 if (inq_task == NULL) {
1938 ret = -EINVAL;
1939 goto out;
1941 iscsi_save_designator(iscsilun, inq_di);
1942 scsi_free_scsi_task(inq_task);
1943 break;
1944 default:
1945 break;
1948 scsi_free_scsi_task(task);
1949 task = NULL;
1951 qemu_mutex_init(&iscsilun->mutex);
1952 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1954 /* Guess the internal cluster (page) size of the iscsi target by the means
1955 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1956 * reasonable size */
1957 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1958 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1959 iscsilun->cluster_size = iscsilun->bl.opt_unmap_gran *
1960 iscsilun->block_size;
1961 if (iscsilun->lbprz) {
1962 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1966 if (iscsilun->lbprz && iscsilun->lbp.lbpws) {
1967 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1970 out:
1971 qemu_opts_del(opts);
1972 g_free(initiator_name);
1973 if (task != NULL) {
1974 scsi_free_scsi_task(task);
1977 if (ret) {
1978 if (iscsi != NULL) {
1979 if (iscsi_is_logged_in(iscsi)) {
1980 iscsi_logout_sync(iscsi);
1982 iscsi_destroy_context(iscsi);
1984 memset(iscsilun, 0, sizeof(IscsiLun));
1987 return ret;
1990 static void iscsi_close(BlockDriverState *bs)
1992 IscsiLun *iscsilun = bs->opaque;
1993 struct iscsi_context *iscsi = iscsilun->iscsi;
1995 iscsi_detach_aio_context(bs);
1996 if (iscsi_is_logged_in(iscsi)) {
1997 iscsi_logout_sync(iscsi);
1999 iscsi_destroy_context(iscsi);
2000 if (iscsilun->dd) {
2001 g_free(iscsilun->dd->designator);
2002 g_free(iscsilun->dd);
2004 g_free(iscsilun->zeroblock);
2005 iscsi_allocmap_free(iscsilun);
2006 qemu_mutex_destroy(&iscsilun->mutex);
2007 memset(iscsilun, 0, sizeof(IscsiLun));
2010 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
2012 /* We don't actually refresh here, but just return data queried in
2013 * iscsi_open(): iscsi targets don't change their limits. */
2015 IscsiLun *iscsilun = bs->opaque;
2016 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
2017 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
2019 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
2021 bs->bl.request_alignment = block_size;
2023 if (iscsilun->bl.max_xfer_len) {
2024 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
2027 if (max_xfer_len * block_size < INT_MAX) {
2028 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
2031 if (iscsilun->lbp.lbpu) {
2032 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
2033 bs->bl.max_pdiscard =
2034 iscsilun->bl.max_unmap * iscsilun->block_size;
2036 bs->bl.pdiscard_alignment =
2037 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2038 } else {
2039 bs->bl.pdiscard_alignment = iscsilun->block_size;
2042 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
2043 bs->bl.max_pwrite_zeroes =
2044 iscsilun->bl.max_ws_len * iscsilun->block_size;
2046 if (iscsilun->lbp.lbpws) {
2047 bs->bl.pwrite_zeroes_alignment =
2048 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2049 } else {
2050 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
2052 if (iscsilun->bl.opt_xfer_len &&
2053 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
2054 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
2055 iscsilun->block_size);
2059 /* Note that this will not re-establish a connection with an iSCSI target - it
2060 * is effectively a NOP. */
2061 static int iscsi_reopen_prepare(BDRVReopenState *state,
2062 BlockReopenQueue *queue, Error **errp)
2064 IscsiLun *iscsilun = state->bs->opaque;
2066 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
2067 error_setg(errp, "Cannot open a write protected LUN as read-write");
2068 return -EACCES;
2070 return 0;
2073 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
2075 IscsiLun *iscsilun = reopen_state->bs->opaque;
2077 /* the cache.direct status might have changed */
2078 if (iscsilun->allocmap != NULL) {
2079 iscsi_allocmap_init(iscsilun, reopen_state->flags);
2083 static int coroutine_fn iscsi_co_truncate(BlockDriverState *bs, int64_t offset,
2084 PreallocMode prealloc, Error **errp)
2086 IscsiLun *iscsilun = bs->opaque;
2087 Error *local_err = NULL;
2089 if (prealloc != PREALLOC_MODE_OFF) {
2090 error_setg(errp, "Unsupported preallocation mode '%s'",
2091 PreallocMode_str(prealloc));
2092 return -ENOTSUP;
2095 if (iscsilun->type != TYPE_DISK) {
2096 error_setg(errp, "Cannot resize non-disk iSCSI devices");
2097 return -ENOTSUP;
2100 iscsi_readcapacity_sync(iscsilun, &local_err);
2101 if (local_err != NULL) {
2102 error_propagate(errp, local_err);
2103 return -EIO;
2106 if (offset > iscsi_getlength(bs)) {
2107 error_setg(errp, "Cannot grow iSCSI devices");
2108 return -EINVAL;
2111 if (iscsilun->allocmap != NULL) {
2112 iscsi_allocmap_init(iscsilun, bs->open_flags);
2115 return 0;
2118 static int coroutine_fn iscsi_co_create_opts(const char *filename, QemuOpts *opts,
2119 Error **errp)
2121 int ret = 0;
2122 int64_t total_size = 0;
2123 BlockDriverState *bs;
2124 IscsiLun *iscsilun = NULL;
2125 QDict *bs_options;
2126 Error *local_err = NULL;
2128 bs = bdrv_new();
2130 /* Read out options */
2131 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2132 BDRV_SECTOR_SIZE);
2133 bs->opaque = g_new0(struct IscsiLun, 1);
2134 iscsilun = bs->opaque;
2136 bs_options = qdict_new();
2137 iscsi_parse_filename(filename, bs_options, &local_err);
2138 if (local_err) {
2139 error_propagate(errp, local_err);
2140 ret = -EINVAL;
2141 } else {
2142 ret = iscsi_open(bs, bs_options, 0, NULL);
2144 qobject_unref(bs_options);
2146 if (ret != 0) {
2147 goto out;
2149 iscsi_detach_aio_context(bs);
2150 if (iscsilun->type != TYPE_DISK) {
2151 ret = -ENODEV;
2152 goto out;
2154 if (bs->total_sectors < total_size) {
2155 ret = -ENOSPC;
2156 goto out;
2159 ret = 0;
2160 out:
2161 if (iscsilun->iscsi != NULL) {
2162 iscsi_destroy_context(iscsilun->iscsi);
2164 g_free(bs->opaque);
2165 bs->opaque = NULL;
2166 bdrv_unref(bs);
2167 return ret;
2170 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2172 IscsiLun *iscsilun = bs->opaque;
2173 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
2174 bdi->cluster_size = iscsilun->cluster_size;
2175 return 0;
2178 static void coroutine_fn iscsi_co_invalidate_cache(BlockDriverState *bs,
2179 Error **errp)
2181 IscsiLun *iscsilun = bs->opaque;
2182 iscsi_allocmap_invalidate(iscsilun);
2185 static int coroutine_fn iscsi_co_copy_range_from(BlockDriverState *bs,
2186 BdrvChild *src,
2187 uint64_t src_offset,
2188 BdrvChild *dst,
2189 uint64_t dst_offset,
2190 uint64_t bytes,
2191 BdrvRequestFlags read_flags,
2192 BdrvRequestFlags write_flags)
2194 return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
2195 read_flags, write_flags);
2198 static struct scsi_task *iscsi_xcopy_task(int param_len)
2200 struct scsi_task *task;
2202 task = g_new0(struct scsi_task, 1);
2204 task->cdb[0] = EXTENDED_COPY;
2205 task->cdb[10] = (param_len >> 24) & 0xFF;
2206 task->cdb[11] = (param_len >> 16) & 0xFF;
2207 task->cdb[12] = (param_len >> 8) & 0xFF;
2208 task->cdb[13] = param_len & 0xFF;
2209 task->cdb_size = 16;
2210 task->xfer_dir = SCSI_XFER_WRITE;
2211 task->expxferlen = param_len;
2213 return task;
2216 static void iscsi_populate_target_desc(unsigned char *desc, IscsiLun *lun)
2218 struct scsi_inquiry_device_designator *dd = lun->dd;
2220 memset(desc, 0, 32);
2221 desc[0] = 0xE4; /* IDENT_DESCR_TGT_DESCR */
2222 desc[4] = dd->code_set;
2223 desc[5] = (dd->designator_type & 0xF)
2224 | ((dd->association & 3) << 4);
2225 desc[7] = dd->designator_length;
2226 memcpy(desc + 8, dd->designator, MIN(dd->designator_length, 20));
2228 desc[28] = 0;
2229 desc[29] = (lun->block_size >> 16) & 0xFF;
2230 desc[30] = (lun->block_size >> 8) & 0xFF;
2231 desc[31] = lun->block_size & 0xFF;
2234 static void iscsi_xcopy_desc_hdr(uint8_t *hdr, int dc, int cat, int src_index,
2235 int dst_index)
2237 hdr[0] = 0x02; /* BLK_TO_BLK_SEG_DESCR */
2238 hdr[1] = ((dc << 1) | cat) & 0xFF;
2239 hdr[2] = (XCOPY_BLK2BLK_SEG_DESC_SIZE >> 8) & 0xFF;
2240 /* don't account for the first 4 bytes in descriptor header*/
2241 hdr[3] = (XCOPY_BLK2BLK_SEG_DESC_SIZE - 4 /* SEG_DESC_SRC_INDEX_OFFSET */) & 0xFF;
2242 hdr[4] = (src_index >> 8) & 0xFF;
2243 hdr[5] = src_index & 0xFF;
2244 hdr[6] = (dst_index >> 8) & 0xFF;
2245 hdr[7] = dst_index & 0xFF;
2248 static void iscsi_xcopy_populate_desc(uint8_t *desc, int dc, int cat,
2249 int src_index, int dst_index, int num_blks,
2250 uint64_t src_lba, uint64_t dst_lba)
2252 iscsi_xcopy_desc_hdr(desc, dc, cat, src_index, dst_index);
2254 /* The caller should verify the request size */
2255 assert(num_blks < 65536);
2256 desc[10] = (num_blks >> 8) & 0xFF;
2257 desc[11] = num_blks & 0xFF;
2258 desc[12] = (src_lba >> 56) & 0xFF;
2259 desc[13] = (src_lba >> 48) & 0xFF;
2260 desc[14] = (src_lba >> 40) & 0xFF;
2261 desc[15] = (src_lba >> 32) & 0xFF;
2262 desc[16] = (src_lba >> 24) & 0xFF;
2263 desc[17] = (src_lba >> 16) & 0xFF;
2264 desc[18] = (src_lba >> 8) & 0xFF;
2265 desc[19] = src_lba & 0xFF;
2266 desc[20] = (dst_lba >> 56) & 0xFF;
2267 desc[21] = (dst_lba >> 48) & 0xFF;
2268 desc[22] = (dst_lba >> 40) & 0xFF;
2269 desc[23] = (dst_lba >> 32) & 0xFF;
2270 desc[24] = (dst_lba >> 24) & 0xFF;
2271 desc[25] = (dst_lba >> 16) & 0xFF;
2272 desc[26] = (dst_lba >> 8) & 0xFF;
2273 desc[27] = dst_lba & 0xFF;
2276 static void iscsi_xcopy_populate_header(unsigned char *buf, int list_id, int str,
2277 int list_id_usage, int prio,
2278 int tgt_desc_len,
2279 int seg_desc_len, int inline_data_len)
2281 buf[0] = list_id;
2282 buf[1] = ((str & 1) << 5) | ((list_id_usage & 3) << 3) | (prio & 7);
2283 buf[2] = (tgt_desc_len >> 8) & 0xFF;
2284 buf[3] = tgt_desc_len & 0xFF;
2285 buf[8] = (seg_desc_len >> 24) & 0xFF;
2286 buf[9] = (seg_desc_len >> 16) & 0xFF;
2287 buf[10] = (seg_desc_len >> 8) & 0xFF;
2288 buf[11] = seg_desc_len & 0xFF;
2289 buf[12] = (inline_data_len >> 24) & 0xFF;
2290 buf[13] = (inline_data_len >> 16) & 0xFF;
2291 buf[14] = (inline_data_len >> 8) & 0xFF;
2292 buf[15] = inline_data_len & 0xFF;
2295 static void iscsi_xcopy_data(struct iscsi_data *data,
2296 IscsiLun *src, int64_t src_lba,
2297 IscsiLun *dst, int64_t dst_lba,
2298 uint16_t num_blocks)
2300 uint8_t *buf;
2301 const int src_offset = XCOPY_DESC_OFFSET;
2302 const int dst_offset = XCOPY_DESC_OFFSET + IDENT_DESCR_TGT_DESCR_SIZE;
2303 const int seg_offset = dst_offset + IDENT_DESCR_TGT_DESCR_SIZE;
2305 data->size = XCOPY_DESC_OFFSET +
2306 IDENT_DESCR_TGT_DESCR_SIZE * 2 +
2307 XCOPY_BLK2BLK_SEG_DESC_SIZE;
2308 data->data = g_malloc0(data->size);
2309 buf = data->data;
2311 /* Initialise the parameter list header */
2312 iscsi_xcopy_populate_header(buf, 1, 0, 2 /* LIST_ID_USAGE_DISCARD */,
2313 0, 2 * IDENT_DESCR_TGT_DESCR_SIZE,
2314 XCOPY_BLK2BLK_SEG_DESC_SIZE,
2317 /* Initialise CSCD list with one src + one dst descriptor */
2318 iscsi_populate_target_desc(&buf[src_offset], src);
2319 iscsi_populate_target_desc(&buf[dst_offset], dst);
2321 /* Initialise one segment descriptor */
2322 iscsi_xcopy_populate_desc(&buf[seg_offset], 0, 0, 0, 1, num_blocks,
2323 src_lba, dst_lba);
2326 static int coroutine_fn iscsi_co_copy_range_to(BlockDriverState *bs,
2327 BdrvChild *src,
2328 uint64_t src_offset,
2329 BdrvChild *dst,
2330 uint64_t dst_offset,
2331 uint64_t bytes,
2332 BdrvRequestFlags read_flags,
2333 BdrvRequestFlags write_flags)
2335 IscsiLun *dst_lun = dst->bs->opaque;
2336 IscsiLun *src_lun;
2337 struct IscsiTask iscsi_task;
2338 struct iscsi_data data;
2339 int r = 0;
2340 int block_size;
2342 if (src->bs->drv->bdrv_co_copy_range_to != iscsi_co_copy_range_to) {
2343 return -ENOTSUP;
2345 src_lun = src->bs->opaque;
2347 if (!src_lun->dd || !dst_lun->dd) {
2348 return -ENOTSUP;
2350 if (!is_byte_request_lun_aligned(dst_offset, bytes, dst_lun)) {
2351 return -ENOTSUP;
2353 if (!is_byte_request_lun_aligned(src_offset, bytes, src_lun)) {
2354 return -ENOTSUP;
2356 if (dst_lun->block_size != src_lun->block_size ||
2357 !dst_lun->block_size) {
2358 return -ENOTSUP;
2361 block_size = dst_lun->block_size;
2362 if (bytes / block_size > 65535) {
2363 return -ENOTSUP;
2366 iscsi_xcopy_data(&data,
2367 src_lun, src_offset / block_size,
2368 dst_lun, dst_offset / block_size,
2369 bytes / block_size);
2371 iscsi_co_init_iscsitask(dst_lun, &iscsi_task);
2373 qemu_mutex_lock(&dst_lun->mutex);
2374 iscsi_task.task = iscsi_xcopy_task(data.size);
2375 retry:
2376 if (iscsi_scsi_command_async(dst_lun->iscsi, dst_lun->lun,
2377 iscsi_task.task, iscsi_co_generic_cb,
2378 &data,
2379 &iscsi_task) != 0) {
2380 r = -EIO;
2381 goto out_unlock;
2384 iscsi_co_wait_for_task(&iscsi_task, dst_lun);
2386 if (iscsi_task.do_retry) {
2387 iscsi_task.complete = 0;
2388 goto retry;
2391 if (iscsi_task.status != SCSI_STATUS_GOOD) {
2392 r = iscsi_task.err_code;
2393 goto out_unlock;
2396 out_unlock:
2398 trace_iscsi_xcopy(src_lun, src_offset, dst_lun, dst_offset, bytes, r);
2399 g_free(iscsi_task.task);
2400 qemu_mutex_unlock(&dst_lun->mutex);
2401 g_free(iscsi_task.err_str);
2402 return r;
2405 static QemuOptsList iscsi_create_opts = {
2406 .name = "iscsi-create-opts",
2407 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2408 .desc = {
2410 .name = BLOCK_OPT_SIZE,
2411 .type = QEMU_OPT_SIZE,
2412 .help = "Virtual disk size"
2414 { /* end of list */ }
2418 static BlockDriver bdrv_iscsi = {
2419 .format_name = "iscsi",
2420 .protocol_name = "iscsi",
2422 .instance_size = sizeof(IscsiLun),
2423 .bdrv_parse_filename = iscsi_parse_filename,
2424 .bdrv_file_open = iscsi_open,
2425 .bdrv_close = iscsi_close,
2426 .bdrv_co_create_opts = iscsi_co_create_opts,
2427 .create_opts = &iscsi_create_opts,
2428 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2429 .bdrv_reopen_commit = iscsi_reopen_commit,
2430 .bdrv_co_invalidate_cache = iscsi_co_invalidate_cache,
2432 .bdrv_getlength = iscsi_getlength,
2433 .bdrv_get_info = iscsi_get_info,
2434 .bdrv_co_truncate = iscsi_co_truncate,
2435 .bdrv_refresh_limits = iscsi_refresh_limits,
2437 .bdrv_co_block_status = iscsi_co_block_status,
2438 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2439 .bdrv_co_copy_range_from = iscsi_co_copy_range_from,
2440 .bdrv_co_copy_range_to = iscsi_co_copy_range_to,
2441 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2442 .bdrv_co_readv = iscsi_co_readv,
2443 .bdrv_co_writev = iscsi_co_writev,
2444 .bdrv_co_flush_to_disk = iscsi_co_flush,
2446 #ifdef __linux__
2447 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2448 #endif
2450 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2451 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2454 #if LIBISCSI_API_VERSION >= (20160603)
2455 static BlockDriver bdrv_iser = {
2456 .format_name = "iser",
2457 .protocol_name = "iser",
2459 .instance_size = sizeof(IscsiLun),
2460 .bdrv_parse_filename = iscsi_parse_filename,
2461 .bdrv_file_open = iscsi_open,
2462 .bdrv_close = iscsi_close,
2463 .bdrv_co_create_opts = iscsi_co_create_opts,
2464 .create_opts = &iscsi_create_opts,
2465 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2466 .bdrv_reopen_commit = iscsi_reopen_commit,
2467 .bdrv_co_invalidate_cache = iscsi_co_invalidate_cache,
2469 .bdrv_getlength = iscsi_getlength,
2470 .bdrv_get_info = iscsi_get_info,
2471 .bdrv_co_truncate = iscsi_co_truncate,
2472 .bdrv_refresh_limits = iscsi_refresh_limits,
2474 .bdrv_co_block_status = iscsi_co_block_status,
2475 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2476 .bdrv_co_copy_range_from = iscsi_co_copy_range_from,
2477 .bdrv_co_copy_range_to = iscsi_co_copy_range_to,
2478 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2479 .bdrv_co_readv = iscsi_co_readv,
2480 .bdrv_co_writev = iscsi_co_writev,
2481 .bdrv_co_flush_to_disk = iscsi_co_flush,
2483 #ifdef __linux__
2484 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2485 #endif
2487 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2488 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2490 #endif
2492 static void iscsi_block_init(void)
2494 bdrv_register(&bdrv_iscsi);
2495 #if LIBISCSI_API_VERSION >= (20160603)
2496 bdrv_register(&bdrv_iser);
2497 #endif
2500 block_init(iscsi_block_init);