block: Allow error return in BlockDevOps.change_media_cb()
[qemu/ar7.git] / block / iscsi.c
blob76319a1a6eadc34132aef4bd3d583e5f35f17d17
1 /*
2 * QEMU Block driver for iSCSI images
4 * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
5 * Copyright (c) 2012-2016 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-common.h"
32 #include "qemu/config-file.h"
33 #include "qemu/error-report.h"
34 #include "qemu/bitops.h"
35 #include "qemu/bitmap.h"
36 #include "block/block_int.h"
37 #include "block/scsi.h"
38 #include "qemu/iov.h"
39 #include "qemu/uuid.h"
40 #include "qmp-commands.h"
41 #include "qapi/qmp/qstring.h"
42 #include "crypto/secret.h"
44 #include <iscsi/iscsi.h>
45 #include <iscsi/scsi-lowlevel.h>
47 #ifdef __linux__
48 #include <scsi/sg.h>
49 #endif
51 typedef struct IscsiLun {
52 struct iscsi_context *iscsi;
53 AioContext *aio_context;
54 int lun;
55 enum scsi_inquiry_peripheral_device_type type;
56 int block_size;
57 uint64_t num_blocks;
58 int events;
59 QEMUTimer *nop_timer;
60 QEMUTimer *event_timer;
61 QemuMutex mutex;
62 struct scsi_inquiry_logical_block_provisioning lbp;
63 struct scsi_inquiry_block_limits bl;
64 unsigned char *zeroblock;
65 /* The allocmap tracks which clusters (pages) on the iSCSI target are
66 * allocated and which are not. In case a target returns zeros for
67 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
68 * of reading zeros over the wire if a read request falls within an
69 * unallocated block. As there are 3 possible states we need 2 bitmaps to
70 * track. allocmap_valid keeps track if QEMU's information about a page is
71 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
72 * valid information about a page the corresponding allocmap entry should be
73 * switched to unallocated as well to force a new lookup of the allocation
74 * status as lookups are generally skipped if a page is suspect to be
75 * allocated. If a iSCSI target is opened with cache.direct = on the
76 * allocmap_valid does not exist turning all cached information invalid so
77 * that a fresh lookup is made for any page even if allocmap entry returns
78 * it's unallocated. */
79 unsigned long *allocmap;
80 unsigned long *allocmap_valid;
81 long allocmap_size;
82 int cluster_sectors;
83 bool use_16_for_rw;
84 bool write_protected;
85 bool lbpme;
86 bool lbprz;
87 bool dpofua;
88 bool has_write_same;
89 bool request_timed_out;
90 } IscsiLun;
92 typedef struct IscsiTask {
93 int status;
94 int complete;
95 int retries;
96 int do_retry;
97 struct scsi_task *task;
98 Coroutine *co;
99 IscsiLun *iscsilun;
100 QEMUTimer retry_timer;
101 int err_code;
102 } IscsiTask;
104 typedef struct IscsiAIOCB {
105 BlockAIOCB common;
106 QEMUIOVector *qiov;
107 QEMUBH *bh;
108 IscsiLun *iscsilun;
109 struct scsi_task *task;
110 uint8_t *buf;
111 int status;
112 int64_t sector_num;
113 int nb_sectors;
114 int ret;
115 #ifdef __linux__
116 sg_io_hdr_t *ioh;
117 #endif
118 } IscsiAIOCB;
120 /* libiscsi uses time_t so its enough to process events every second */
121 #define EVENT_INTERVAL 1000
122 #define NOP_INTERVAL 5000
123 #define MAX_NOP_FAILURES 3
124 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
125 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
127 /* this threshold is a trade-off knob to choose between
128 * the potential additional overhead of an extra GET_LBA_STATUS request
129 * vs. unnecessarily reading a lot of zero sectors over the wire.
130 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
131 * sectors we check the allocation status of the area covered by the
132 * request first if the allocationmap indicates that the area might be
133 * unallocated. */
134 #define ISCSI_CHECKALLOC_THRES 64
136 static void
137 iscsi_bh_cb(void *p)
139 IscsiAIOCB *acb = p;
141 qemu_bh_delete(acb->bh);
143 g_free(acb->buf);
144 acb->buf = NULL;
146 acb->common.cb(acb->common.opaque, acb->status);
148 if (acb->task != NULL) {
149 scsi_free_scsi_task(acb->task);
150 acb->task = NULL;
153 qemu_aio_unref(acb);
156 static void
157 iscsi_schedule_bh(IscsiAIOCB *acb)
159 if (acb->bh) {
160 return;
162 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
163 qemu_bh_schedule(acb->bh);
166 static void iscsi_co_generic_bh_cb(void *opaque)
168 struct IscsiTask *iTask = opaque;
170 iTask->complete = 1;
171 aio_co_wake(iTask->co);
174 static void iscsi_retry_timer_expired(void *opaque)
176 struct IscsiTask *iTask = opaque;
177 iTask->complete = 1;
178 if (iTask->co) {
179 aio_co_wake(iTask->co);
183 static inline unsigned exp_random(double mean)
185 return -mean * log((double)rand() / RAND_MAX);
188 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
189 * libiscsi 1.10.0, together with other constants we need. Use it as
190 * a hint that we have to define them ourselves if needed, to keep the
191 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
192 * the test because SCSI_STATUS_* is an enum.
194 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
195 * an enum, check against the LIBISCSI_API_VERSION macro, which was
196 * introduced in 1.11.0. If it is present, there is no need to define
197 * anything.
199 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
200 !defined(LIBISCSI_API_VERSION)
201 #define SCSI_STATUS_TASK_SET_FULL 0x28
202 #define SCSI_STATUS_TIMEOUT 0x0f000002
203 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
204 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
205 #endif
207 #ifndef LIBISCSI_API_VERSION
208 #define LIBISCSI_API_VERSION 20130701
209 #endif
211 static int iscsi_translate_sense(struct scsi_sense *sense)
213 int ret;
215 switch (sense->key) {
216 case SCSI_SENSE_NOT_READY:
217 return -EBUSY;
218 case SCSI_SENSE_DATA_PROTECTION:
219 return -EACCES;
220 case SCSI_SENSE_COMMAND_ABORTED:
221 return -ECANCELED;
222 case SCSI_SENSE_ILLEGAL_REQUEST:
223 /* Parse ASCQ */
224 break;
225 default:
226 return -EIO;
228 switch (sense->ascq) {
229 case SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR:
230 case SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE:
231 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB:
232 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST:
233 ret = -EINVAL;
234 break;
235 case SCSI_SENSE_ASCQ_LBA_OUT_OF_RANGE:
236 ret = -ENOSPC;
237 break;
238 case SCSI_SENSE_ASCQ_LOGICAL_UNIT_NOT_SUPPORTED:
239 ret = -ENOTSUP;
240 break;
241 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT:
242 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_CLOSED:
243 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_OPEN:
244 ret = -ENOMEDIUM;
245 break;
246 case SCSI_SENSE_ASCQ_WRITE_PROTECTED:
247 ret = -EACCES;
248 break;
249 default:
250 ret = -EIO;
251 break;
253 return ret;
256 /* Called (via iscsi_service) with QemuMutex held. */
257 static void
258 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
259 void *command_data, void *opaque)
261 struct IscsiTask *iTask = opaque;
262 struct scsi_task *task = command_data;
264 iTask->status = status;
265 iTask->do_retry = 0;
266 iTask->task = task;
268 if (status != SCSI_STATUS_GOOD) {
269 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
270 if (status == SCSI_STATUS_CHECK_CONDITION
271 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
272 error_report("iSCSI CheckCondition: %s",
273 iscsi_get_error(iscsi));
274 iTask->do_retry = 1;
275 goto out;
277 if (status == SCSI_STATUS_BUSY ||
278 status == SCSI_STATUS_TIMEOUT ||
279 status == SCSI_STATUS_TASK_SET_FULL) {
280 unsigned retry_time =
281 exp_random(iscsi_retry_times[iTask->retries - 1]);
282 if (status == SCSI_STATUS_TIMEOUT) {
283 /* make sure the request is rescheduled AFTER the
284 * reconnect is initiated */
285 retry_time = EVENT_INTERVAL * 2;
286 iTask->iscsilun->request_timed_out = true;
288 error_report("iSCSI Busy/TaskSetFull/TimeOut"
289 " (retry #%u in %u ms): %s",
290 iTask->retries, retry_time,
291 iscsi_get_error(iscsi));
292 aio_timer_init(iTask->iscsilun->aio_context,
293 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
294 SCALE_MS, iscsi_retry_timer_expired, iTask);
295 timer_mod(&iTask->retry_timer,
296 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
297 iTask->do_retry = 1;
298 return;
301 iTask->err_code = iscsi_translate_sense(&task->sense);
302 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
305 out:
306 if (iTask->co) {
307 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
308 iscsi_co_generic_bh_cb, iTask);
309 } else {
310 iTask->complete = 1;
314 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
316 *iTask = (struct IscsiTask) {
317 .co = qemu_coroutine_self(),
318 .iscsilun = iscsilun,
322 static void
323 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
324 void *private_data)
326 IscsiAIOCB *acb = private_data;
328 acb->status = -ECANCELED;
329 iscsi_schedule_bh(acb);
332 static void
333 iscsi_aio_cancel(BlockAIOCB *blockacb)
335 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
336 IscsiLun *iscsilun = acb->iscsilun;
338 if (acb->status != -EINPROGRESS) {
339 return;
342 /* send a task mgmt call to the target to cancel the task on the target */
343 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
344 iscsi_abort_task_cb, acb);
348 static const AIOCBInfo iscsi_aiocb_info = {
349 .aiocb_size = sizeof(IscsiAIOCB),
350 .cancel_async = iscsi_aio_cancel,
354 static void iscsi_process_read(void *arg);
355 static void iscsi_process_write(void *arg);
357 /* Called with QemuMutex held. */
358 static void
359 iscsi_set_events(IscsiLun *iscsilun)
361 struct iscsi_context *iscsi = iscsilun->iscsi;
362 int ev = iscsi_which_events(iscsi);
364 if (ev != iscsilun->events) {
365 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
366 false,
367 (ev & POLLIN) ? iscsi_process_read : NULL,
368 (ev & POLLOUT) ? iscsi_process_write : NULL,
369 NULL,
370 iscsilun);
371 iscsilun->events = ev;
375 static void iscsi_timed_check_events(void *opaque)
377 IscsiLun *iscsilun = opaque;
379 /* check for timed out requests */
380 iscsi_service(iscsilun->iscsi, 0);
382 if (iscsilun->request_timed_out) {
383 iscsilun->request_timed_out = false;
384 iscsi_reconnect(iscsilun->iscsi);
387 /* newer versions of libiscsi may return zero events. Ensure we are able
388 * to return to service once this situation changes. */
389 iscsi_set_events(iscsilun);
391 timer_mod(iscsilun->event_timer,
392 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
395 static void
396 iscsi_process_read(void *arg)
398 IscsiLun *iscsilun = arg;
399 struct iscsi_context *iscsi = iscsilun->iscsi;
401 qemu_mutex_lock(&iscsilun->mutex);
402 iscsi_service(iscsi, POLLIN);
403 iscsi_set_events(iscsilun);
404 qemu_mutex_unlock(&iscsilun->mutex);
407 static void
408 iscsi_process_write(void *arg)
410 IscsiLun *iscsilun = arg;
411 struct iscsi_context *iscsi = iscsilun->iscsi;
413 qemu_mutex_lock(&iscsilun->mutex);
414 iscsi_service(iscsi, POLLOUT);
415 iscsi_set_events(iscsilun);
416 qemu_mutex_unlock(&iscsilun->mutex);
419 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
421 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
424 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
426 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
429 static bool is_byte_request_lun_aligned(int64_t offset, int count,
430 IscsiLun *iscsilun)
432 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
433 error_report("iSCSI misaligned request: "
434 "iscsilun->block_size %u, offset %" PRIi64
435 ", count %d",
436 iscsilun->block_size, offset, count);
437 return false;
439 return true;
442 static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
443 IscsiLun *iscsilun)
445 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
446 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
447 nb_sectors << BDRV_SECTOR_BITS,
448 iscsilun);
451 static void iscsi_allocmap_free(IscsiLun *iscsilun)
453 g_free(iscsilun->allocmap);
454 g_free(iscsilun->allocmap_valid);
455 iscsilun->allocmap = NULL;
456 iscsilun->allocmap_valid = NULL;
460 static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
462 iscsi_allocmap_free(iscsilun);
464 iscsilun->allocmap_size =
465 DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks, iscsilun),
466 iscsilun->cluster_sectors);
468 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
469 if (!iscsilun->allocmap) {
470 return -ENOMEM;
473 if (open_flags & BDRV_O_NOCACHE) {
474 /* in case that cache.direct = on all allocmap entries are
475 * treated as invalid to force a relookup of the block
476 * status on every read request */
477 return 0;
480 iscsilun->allocmap_valid = bitmap_try_new(iscsilun->allocmap_size);
481 if (!iscsilun->allocmap_valid) {
482 /* if we are under memory pressure free the allocmap as well */
483 iscsi_allocmap_free(iscsilun);
484 return -ENOMEM;
487 return 0;
490 static void
491 iscsi_allocmap_update(IscsiLun *iscsilun, int64_t sector_num,
492 int nb_sectors, bool allocated, bool valid)
494 int64_t cl_num_expanded, nb_cls_expanded, cl_num_shrunk, nb_cls_shrunk;
496 if (iscsilun->allocmap == NULL) {
497 return;
499 /* expand to entirely contain all affected clusters */
500 cl_num_expanded = sector_num / iscsilun->cluster_sectors;
501 nb_cls_expanded = DIV_ROUND_UP(sector_num + nb_sectors,
502 iscsilun->cluster_sectors) - cl_num_expanded;
503 /* shrink to touch only completely contained clusters */
504 cl_num_shrunk = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
505 nb_cls_shrunk = (sector_num + nb_sectors) / iscsilun->cluster_sectors
506 - cl_num_shrunk;
507 if (allocated) {
508 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
509 } else {
510 if (nb_cls_shrunk > 0) {
511 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
515 if (iscsilun->allocmap_valid == NULL) {
516 return;
518 if (valid) {
519 if (nb_cls_shrunk > 0) {
520 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
522 } else {
523 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
524 nb_cls_expanded);
528 static void
529 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
530 int nb_sectors)
532 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
535 static void
536 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
537 int nb_sectors)
539 /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
540 * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
542 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
545 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
546 int nb_sectors)
548 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
551 static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
553 if (iscsilun->allocmap) {
554 bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
556 if (iscsilun->allocmap_valid) {
557 bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
561 static inline bool
562 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
563 int nb_sectors)
565 unsigned long size;
566 if (iscsilun->allocmap == NULL) {
567 return true;
569 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
570 return !(find_next_bit(iscsilun->allocmap, size,
571 sector_num / iscsilun->cluster_sectors) == size);
574 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
575 int64_t sector_num, int nb_sectors)
577 unsigned long size;
578 if (iscsilun->allocmap_valid == NULL) {
579 return false;
581 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
582 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
583 sector_num / iscsilun->cluster_sectors) == size);
586 static int coroutine_fn
587 iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
588 QEMUIOVector *iov, int flags)
590 IscsiLun *iscsilun = bs->opaque;
591 struct IscsiTask iTask;
592 uint64_t lba;
593 uint32_t num_sectors;
594 bool fua = flags & BDRV_REQ_FUA;
595 int r = 0;
597 if (fua) {
598 assert(iscsilun->dpofua);
600 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
601 return -EINVAL;
604 if (bs->bl.max_transfer) {
605 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
608 lba = sector_qemu2lun(sector_num, iscsilun);
609 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
610 iscsi_co_init_iscsitask(iscsilun, &iTask);
611 qemu_mutex_lock(&iscsilun->mutex);
612 retry:
613 if (iscsilun->use_16_for_rw) {
614 #if LIBISCSI_API_VERSION >= (20160603)
615 iTask.task = iscsi_write16_iov_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,
619 (struct scsi_iovec *)iov->iov, iov->niov);
620 } else {
621 iTask.task = iscsi_write10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
622 NULL, num_sectors * iscsilun->block_size,
623 iscsilun->block_size, 0, 0, fua, 0, 0,
624 iscsi_co_generic_cb, &iTask,
625 (struct scsi_iovec *)iov->iov, iov->niov);
627 #else
628 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
629 NULL, num_sectors * iscsilun->block_size,
630 iscsilun->block_size, 0, 0, fua, 0, 0,
631 iscsi_co_generic_cb, &iTask);
632 } else {
633 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
634 NULL, num_sectors * iscsilun->block_size,
635 iscsilun->block_size, 0, 0, fua, 0, 0,
636 iscsi_co_generic_cb, &iTask);
638 #endif
639 if (iTask.task == NULL) {
640 return -ENOMEM;
642 #if LIBISCSI_API_VERSION < (20160603)
643 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
644 iov->niov);
645 #endif
646 while (!iTask.complete) {
647 iscsi_set_events(iscsilun);
648 qemu_mutex_unlock(&iscsilun->mutex);
649 qemu_coroutine_yield();
650 qemu_mutex_lock(&iscsilun->mutex);
653 if (iTask.task != NULL) {
654 scsi_free_scsi_task(iTask.task);
655 iTask.task = NULL;
658 if (iTask.do_retry) {
659 iTask.complete = 0;
660 goto retry;
663 if (iTask.status != SCSI_STATUS_GOOD) {
664 iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
665 r = iTask.err_code;
666 goto out_unlock;
669 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
671 out_unlock:
672 qemu_mutex_unlock(&iscsilun->mutex);
673 return r;
678 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
679 int64_t sector_num,
680 int nb_sectors, int *pnum,
681 BlockDriverState **file)
683 IscsiLun *iscsilun = bs->opaque;
684 struct scsi_get_lba_status *lbas = NULL;
685 struct scsi_lba_status_descriptor *lbasd = NULL;
686 struct IscsiTask iTask;
687 int64_t ret;
689 iscsi_co_init_iscsitask(iscsilun, &iTask);
691 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
692 ret = -EINVAL;
693 goto out;
696 /* default to all sectors allocated */
697 ret = BDRV_BLOCK_DATA;
698 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
699 *pnum = nb_sectors;
701 /* LUN does not support logical block provisioning */
702 if (!iscsilun->lbpme) {
703 goto out;
706 qemu_mutex_lock(&iscsilun->mutex);
707 retry:
708 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
709 sector_qemu2lun(sector_num, iscsilun),
710 8 + 16, iscsi_co_generic_cb,
711 &iTask) == NULL) {
712 ret = -ENOMEM;
713 goto out_unlock;
716 while (!iTask.complete) {
717 iscsi_set_events(iscsilun);
718 qemu_mutex_unlock(&iscsilun->mutex);
719 qemu_coroutine_yield();
720 qemu_mutex_lock(&iscsilun->mutex);
723 if (iTask.do_retry) {
724 if (iTask.task != NULL) {
725 scsi_free_scsi_task(iTask.task);
726 iTask.task = NULL;
728 iTask.complete = 0;
729 goto retry;
732 if (iTask.status != SCSI_STATUS_GOOD) {
733 /* in case the get_lba_status_callout fails (i.e.
734 * because the device is busy or the cmd is not
735 * supported) we pretend all blocks are allocated
736 * for backwards compatibility */
737 goto out_unlock;
740 lbas = scsi_datain_unmarshall(iTask.task);
741 if (lbas == NULL) {
742 ret = -EIO;
743 goto out_unlock;
746 lbasd = &lbas->descriptors[0];
748 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
749 ret = -EIO;
750 goto out_unlock;
753 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
755 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
756 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
757 ret &= ~BDRV_BLOCK_DATA;
758 if (iscsilun->lbprz) {
759 ret |= BDRV_BLOCK_ZERO;
763 if (ret & BDRV_BLOCK_ZERO) {
764 iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
765 } else {
766 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
769 if (*pnum > nb_sectors) {
770 *pnum = nb_sectors;
772 out_unlock:
773 qemu_mutex_unlock(&iscsilun->mutex);
774 out:
775 if (iTask.task != NULL) {
776 scsi_free_scsi_task(iTask.task);
778 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
779 *file = bs;
781 return ret;
784 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
785 int64_t sector_num, int nb_sectors,
786 QEMUIOVector *iov)
788 IscsiLun *iscsilun = bs->opaque;
789 struct IscsiTask iTask;
790 uint64_t lba;
791 uint32_t num_sectors;
793 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
794 return -EINVAL;
797 if (bs->bl.max_transfer) {
798 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
801 /* if cache.direct is off and we have a valid entry in our allocation map
802 * we can skip checking the block status and directly return zeroes if
803 * the request falls within an unallocated area */
804 if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
805 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
806 qemu_iovec_memset(iov, 0, 0x00, iov->size);
807 return 0;
810 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
811 !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
812 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
813 int pnum;
814 BlockDriverState *file;
815 /* check the block status from the beginning of the cluster
816 * containing the start sector */
817 int64_t ret = iscsi_co_get_block_status(bs,
818 sector_num - sector_num % iscsilun->cluster_sectors,
819 BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
820 if (ret < 0) {
821 return ret;
823 /* if the whole request falls into an unallocated area we can avoid
824 * to read and directly return zeroes instead */
825 if (ret & BDRV_BLOCK_ZERO &&
826 pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
827 qemu_iovec_memset(iov, 0, 0x00, iov->size);
828 return 0;
832 lba = sector_qemu2lun(sector_num, iscsilun);
833 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
835 iscsi_co_init_iscsitask(iscsilun, &iTask);
836 qemu_mutex_lock(&iscsilun->mutex);
837 retry:
838 if (iscsilun->use_16_for_rw) {
839 #if LIBISCSI_API_VERSION >= (20160603)
840 iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
841 num_sectors * iscsilun->block_size,
842 iscsilun->block_size, 0, 0, 0, 0, 0,
843 iscsi_co_generic_cb, &iTask,
844 (struct scsi_iovec *)iov->iov, iov->niov);
845 } else {
846 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
847 num_sectors * iscsilun->block_size,
848 iscsilun->block_size,
849 0, 0, 0, 0, 0,
850 iscsi_co_generic_cb, &iTask,
851 (struct scsi_iovec *)iov->iov, iov->niov);
853 #else
854 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
855 num_sectors * iscsilun->block_size,
856 iscsilun->block_size, 0, 0, 0, 0, 0,
857 iscsi_co_generic_cb, &iTask);
858 } else {
859 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
860 num_sectors * iscsilun->block_size,
861 iscsilun->block_size,
862 0, 0, 0, 0, 0,
863 iscsi_co_generic_cb, &iTask);
865 #endif
866 if (iTask.task == NULL) {
867 return -ENOMEM;
869 #if LIBISCSI_API_VERSION < (20160603)
870 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
871 #endif
872 while (!iTask.complete) {
873 iscsi_set_events(iscsilun);
874 qemu_mutex_unlock(&iscsilun->mutex);
875 qemu_coroutine_yield();
876 qemu_mutex_lock(&iscsilun->mutex);
879 if (iTask.task != NULL) {
880 scsi_free_scsi_task(iTask.task);
881 iTask.task = NULL;
884 if (iTask.do_retry) {
885 iTask.complete = 0;
886 goto retry;
888 qemu_mutex_unlock(&iscsilun->mutex);
890 if (iTask.status != SCSI_STATUS_GOOD) {
891 return iTask.err_code;
894 return 0;
897 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
899 IscsiLun *iscsilun = bs->opaque;
900 struct IscsiTask iTask;
902 iscsi_co_init_iscsitask(iscsilun, &iTask);
903 qemu_mutex_lock(&iscsilun->mutex);
904 retry:
905 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
906 0, iscsi_co_generic_cb, &iTask) == NULL) {
907 return -ENOMEM;
910 while (!iTask.complete) {
911 iscsi_set_events(iscsilun);
912 qemu_mutex_unlock(&iscsilun->mutex);
913 qemu_coroutine_yield();
914 qemu_mutex_lock(&iscsilun->mutex);
917 if (iTask.task != NULL) {
918 scsi_free_scsi_task(iTask.task);
919 iTask.task = NULL;
922 if (iTask.do_retry) {
923 iTask.complete = 0;
924 goto retry;
926 qemu_mutex_unlock(&iscsilun->mutex);
928 if (iTask.status != SCSI_STATUS_GOOD) {
929 return iTask.err_code;
932 return 0;
935 #ifdef __linux__
936 /* Called (via iscsi_service) with QemuMutex held. */
937 static void
938 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
939 void *command_data, void *opaque)
941 IscsiAIOCB *acb = opaque;
943 g_free(acb->buf);
944 acb->buf = NULL;
946 acb->status = 0;
947 if (status < 0) {
948 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
949 iscsi_get_error(iscsi));
950 acb->status = iscsi_translate_sense(&acb->task->sense);
953 acb->ioh->driver_status = 0;
954 acb->ioh->host_status = 0;
955 acb->ioh->resid = 0;
956 acb->ioh->status = status;
958 #define SG_ERR_DRIVER_SENSE 0x08
960 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
961 int ss;
963 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
965 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
966 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
967 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
968 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
971 iscsi_schedule_bh(acb);
974 static void iscsi_ioctl_bh_completion(void *opaque)
976 IscsiAIOCB *acb = opaque;
978 qemu_bh_delete(acb->bh);
979 acb->common.cb(acb->common.opaque, acb->ret);
980 qemu_aio_unref(acb);
983 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
985 BlockDriverState *bs = acb->common.bs;
986 IscsiLun *iscsilun = bs->opaque;
987 int ret = 0;
989 switch (req) {
990 case SG_GET_VERSION_NUM:
991 *(int *)buf = 30000;
992 break;
993 case SG_GET_SCSI_ID:
994 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
995 break;
996 default:
997 ret = -EINVAL;
999 assert(!acb->bh);
1000 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
1001 iscsi_ioctl_bh_completion, acb);
1002 acb->ret = ret;
1003 qemu_bh_schedule(acb->bh);
1006 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
1007 unsigned long int req, void *buf,
1008 BlockCompletionFunc *cb, void *opaque)
1010 IscsiLun *iscsilun = bs->opaque;
1011 struct iscsi_context *iscsi = iscsilun->iscsi;
1012 struct iscsi_data data;
1013 IscsiAIOCB *acb;
1015 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
1017 acb->iscsilun = iscsilun;
1018 acb->bh = NULL;
1019 acb->status = -EINPROGRESS;
1020 acb->buf = NULL;
1021 acb->ioh = buf;
1023 if (req != SG_IO) {
1024 iscsi_ioctl_handle_emulated(acb, req, buf);
1025 return &acb->common;
1028 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
1029 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
1030 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1031 qemu_aio_unref(acb);
1032 return NULL;
1035 acb->task = malloc(sizeof(struct scsi_task));
1036 if (acb->task == NULL) {
1037 error_report("iSCSI: Failed to allocate task for scsi command. %s",
1038 iscsi_get_error(iscsi));
1039 qemu_aio_unref(acb);
1040 return NULL;
1042 memset(acb->task, 0, sizeof(struct scsi_task));
1044 switch (acb->ioh->dxfer_direction) {
1045 case SG_DXFER_TO_DEV:
1046 acb->task->xfer_dir = SCSI_XFER_WRITE;
1047 break;
1048 case SG_DXFER_FROM_DEV:
1049 acb->task->xfer_dir = SCSI_XFER_READ;
1050 break;
1051 default:
1052 acb->task->xfer_dir = SCSI_XFER_NONE;
1053 break;
1056 acb->task->cdb_size = acb->ioh->cmd_len;
1057 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1058 acb->task->expxferlen = acb->ioh->dxfer_len;
1060 data.size = 0;
1061 qemu_mutex_lock(&iscsilun->mutex);
1062 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
1063 if (acb->ioh->iovec_count == 0) {
1064 data.data = acb->ioh->dxferp;
1065 data.size = acb->ioh->dxfer_len;
1066 } else {
1067 scsi_task_set_iov_out(acb->task,
1068 (struct scsi_iovec *) acb->ioh->dxferp,
1069 acb->ioh->iovec_count);
1073 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1074 iscsi_aio_ioctl_cb,
1075 (data.size > 0) ? &data : NULL,
1076 acb) != 0) {
1077 qemu_mutex_unlock(&iscsilun->mutex);
1078 scsi_free_scsi_task(acb->task);
1079 qemu_aio_unref(acb);
1080 return NULL;
1083 /* tell libiscsi to read straight into the buffer we got from ioctl */
1084 if (acb->task->xfer_dir == SCSI_XFER_READ) {
1085 if (acb->ioh->iovec_count == 0) {
1086 scsi_task_add_data_in_buffer(acb->task,
1087 acb->ioh->dxfer_len,
1088 acb->ioh->dxferp);
1089 } else {
1090 scsi_task_set_iov_in(acb->task,
1091 (struct scsi_iovec *) acb->ioh->dxferp,
1092 acb->ioh->iovec_count);
1096 iscsi_set_events(iscsilun);
1097 qemu_mutex_unlock(&iscsilun->mutex);
1099 return &acb->common;
1102 #endif
1104 static int64_t
1105 iscsi_getlength(BlockDriverState *bs)
1107 IscsiLun *iscsilun = bs->opaque;
1108 int64_t len;
1110 len = iscsilun->num_blocks;
1111 len *= iscsilun->block_size;
1113 return len;
1116 static int
1117 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int count)
1119 IscsiLun *iscsilun = bs->opaque;
1120 struct IscsiTask iTask;
1121 struct unmap_list list;
1122 int r = 0;
1124 if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {
1125 return -ENOTSUP;
1128 if (!iscsilun->lbp.lbpu) {
1129 /* UNMAP is not supported by the target */
1130 return 0;
1133 list.lba = offset / iscsilun->block_size;
1134 list.num = count / iscsilun->block_size;
1136 iscsi_co_init_iscsitask(iscsilun, &iTask);
1137 qemu_mutex_lock(&iscsilun->mutex);
1138 retry:
1139 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1140 iscsi_co_generic_cb, &iTask) == NULL) {
1141 r = -ENOMEM;
1142 goto out_unlock;
1145 while (!iTask.complete) {
1146 iscsi_set_events(iscsilun);
1147 qemu_mutex_unlock(&iscsilun->mutex);
1148 qemu_coroutine_yield();
1149 qemu_mutex_lock(&iscsilun->mutex);
1152 if (iTask.task != NULL) {
1153 scsi_free_scsi_task(iTask.task);
1154 iTask.task = NULL;
1157 if (iTask.do_retry) {
1158 iTask.complete = 0;
1159 goto retry;
1162 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1163 /* the target might fail with a check condition if it
1164 is not happy with the alignment of the UNMAP request
1165 we silently fail in this case */
1166 goto out_unlock;
1169 if (iTask.status != SCSI_STATUS_GOOD) {
1170 r = iTask.err_code;
1171 goto out_unlock;
1174 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1175 count >> BDRV_SECTOR_BITS);
1177 out_unlock:
1178 qemu_mutex_unlock(&iscsilun->mutex);
1179 return r;
1182 static int
1183 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1184 int count, BdrvRequestFlags flags)
1186 IscsiLun *iscsilun = bs->opaque;
1187 struct IscsiTask iTask;
1188 uint64_t lba;
1189 uint32_t nb_blocks;
1190 bool use_16_for_ws = iscsilun->use_16_for_rw;
1191 int r = 0;
1193 if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {
1194 return -ENOTSUP;
1197 if (flags & BDRV_REQ_MAY_UNMAP) {
1198 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1199 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1200 use_16_for_ws = true;
1202 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1203 /* WRITESAME16 with UNMAP is not supported by the target,
1204 * fall back and try WRITESAME10/16 without UNMAP */
1205 flags &= ~BDRV_REQ_MAY_UNMAP;
1206 use_16_for_ws = iscsilun->use_16_for_rw;
1210 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1211 /* WRITESAME without UNMAP is not supported by the target */
1212 return -ENOTSUP;
1215 lba = offset / iscsilun->block_size;
1216 nb_blocks = count / iscsilun->block_size;
1218 if (iscsilun->zeroblock == NULL) {
1219 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1220 if (iscsilun->zeroblock == NULL) {
1221 return -ENOMEM;
1225 qemu_mutex_lock(&iscsilun->mutex);
1226 iscsi_co_init_iscsitask(iscsilun, &iTask);
1227 retry:
1228 if (use_16_for_ws) {
1229 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1230 iscsilun->zeroblock, iscsilun->block_size,
1231 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1232 0, 0, iscsi_co_generic_cb, &iTask);
1233 } else {
1234 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1235 iscsilun->zeroblock, iscsilun->block_size,
1236 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1237 0, 0, iscsi_co_generic_cb, &iTask);
1239 if (iTask.task == NULL) {
1240 return -ENOMEM;
1243 while (!iTask.complete) {
1244 iscsi_set_events(iscsilun);
1245 qemu_mutex_unlock(&iscsilun->mutex);
1246 qemu_coroutine_yield();
1247 qemu_mutex_lock(&iscsilun->mutex);
1250 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1251 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1252 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1253 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1254 /* WRITE SAME is not supported by the target */
1255 iscsilun->has_write_same = false;
1256 scsi_free_scsi_task(iTask.task);
1257 r = -ENOTSUP;
1258 goto out_unlock;
1261 if (iTask.task != NULL) {
1262 scsi_free_scsi_task(iTask.task);
1263 iTask.task = NULL;
1266 if (iTask.do_retry) {
1267 iTask.complete = 0;
1268 goto retry;
1271 if (iTask.status != SCSI_STATUS_GOOD) {
1272 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1273 count >> BDRV_SECTOR_BITS);
1274 r = iTask.err_code;
1275 goto out_unlock;
1278 if (flags & BDRV_REQ_MAY_UNMAP) {
1279 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1280 count >> BDRV_SECTOR_BITS);
1281 } else {
1282 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1283 count >> BDRV_SECTOR_BITS);
1286 out_unlock:
1287 qemu_mutex_unlock(&iscsilun->mutex);
1288 return r;
1291 static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
1292 Error **errp)
1294 const char *user = NULL;
1295 const char *password = NULL;
1296 const char *secretid;
1297 char *secret = NULL;
1299 user = qemu_opt_get(opts, "user");
1300 if (!user) {
1301 return;
1304 secretid = qemu_opt_get(opts, "password-secret");
1305 password = qemu_opt_get(opts, "password");
1306 if (secretid && password) {
1307 error_setg(errp, "'password' and 'password-secret' properties are "
1308 "mutually exclusive");
1309 return;
1311 if (secretid) {
1312 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1313 if (!secret) {
1314 return;
1316 password = secret;
1317 } else if (!password) {
1318 error_setg(errp, "CHAP username specified but no password was given");
1319 return;
1322 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1323 error_setg(errp, "Failed to set initiator username and password");
1326 g_free(secret);
1329 static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
1330 Error **errp)
1332 const char *digest = NULL;
1334 digest = qemu_opt_get(opts, "header-digest");
1335 if (!digest) {
1336 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1337 } else if (!strcmp(digest, "crc32c")) {
1338 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1339 } else if (!strcmp(digest, "none")) {
1340 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1341 } else if (!strcmp(digest, "crc32c-none")) {
1342 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1343 } else if (!strcmp(digest, "none-crc32c")) {
1344 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1345 } else {
1346 error_setg(errp, "Invalid header-digest setting : %s", digest);
1350 static char *get_initiator_name(QemuOpts *opts)
1352 const char *name;
1353 char *iscsi_name;
1354 UuidInfo *uuid_info;
1356 name = qemu_opt_get(opts, "initiator-name");
1357 if (name) {
1358 return g_strdup(name);
1361 uuid_info = qmp_query_uuid(NULL);
1362 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1363 name = qemu_get_vm_name();
1364 } else {
1365 name = uuid_info->UUID;
1367 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1368 name ? ":" : "", name ? name : "");
1369 qapi_free_UuidInfo(uuid_info);
1370 return iscsi_name;
1373 static void iscsi_nop_timed_event(void *opaque)
1375 IscsiLun *iscsilun = opaque;
1377 qemu_mutex_lock(&iscsilun->mutex);
1378 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1379 error_report("iSCSI: NOP timeout. Reconnecting...");
1380 iscsilun->request_timed_out = true;
1381 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1382 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1383 goto out;
1386 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1387 iscsi_set_events(iscsilun);
1389 out:
1390 qemu_mutex_unlock(&iscsilun->mutex);
1393 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1395 struct scsi_task *task = NULL;
1396 struct scsi_readcapacity10 *rc10 = NULL;
1397 struct scsi_readcapacity16 *rc16 = NULL;
1398 int retries = ISCSI_CMD_RETRIES;
1400 do {
1401 if (task != NULL) {
1402 scsi_free_scsi_task(task);
1403 task = NULL;
1406 switch (iscsilun->type) {
1407 case TYPE_DISK:
1408 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1409 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1410 rc16 = scsi_datain_unmarshall(task);
1411 if (rc16 == NULL) {
1412 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1413 } else {
1414 iscsilun->block_size = rc16->block_length;
1415 iscsilun->num_blocks = rc16->returned_lba + 1;
1416 iscsilun->lbpme = !!rc16->lbpme;
1417 iscsilun->lbprz = !!rc16->lbprz;
1418 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1420 break;
1422 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1423 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1424 break;
1426 /* Fall through and try READ CAPACITY(10) instead. */
1427 case TYPE_ROM:
1428 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1429 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1430 rc10 = scsi_datain_unmarshall(task);
1431 if (rc10 == NULL) {
1432 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1433 } else {
1434 iscsilun->block_size = rc10->block_size;
1435 if (rc10->lba == 0) {
1436 /* blank disk loaded */
1437 iscsilun->num_blocks = 0;
1438 } else {
1439 iscsilun->num_blocks = rc10->lba + 1;
1443 break;
1444 default:
1445 return;
1447 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1448 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1449 && retries-- > 0);
1451 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1452 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1453 } else if (!iscsilun->block_size ||
1454 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1455 error_setg(errp, "iSCSI: the target returned an invalid "
1456 "block size of %d.", iscsilun->block_size);
1458 if (task) {
1459 scsi_free_scsi_task(task);
1463 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1464 int evpd, int pc, void **inq, Error **errp)
1466 int full_size;
1467 struct scsi_task *task = NULL;
1468 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1469 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1470 goto fail;
1472 full_size = scsi_datain_getfullsize(task);
1473 if (full_size > task->datain.size) {
1474 scsi_free_scsi_task(task);
1476 /* we need more data for the full list */
1477 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1478 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1479 goto fail;
1483 *inq = scsi_datain_unmarshall(task);
1484 if (*inq == NULL) {
1485 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1486 goto fail_with_err;
1489 return task;
1491 fail:
1492 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1493 iscsi_get_error(iscsi));
1494 fail_with_err:
1495 if (task != NULL) {
1496 scsi_free_scsi_task(task);
1498 return NULL;
1501 static void iscsi_detach_aio_context(BlockDriverState *bs)
1503 IscsiLun *iscsilun = bs->opaque;
1505 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1506 false, NULL, NULL, NULL, NULL);
1507 iscsilun->events = 0;
1509 if (iscsilun->nop_timer) {
1510 timer_del(iscsilun->nop_timer);
1511 timer_free(iscsilun->nop_timer);
1512 iscsilun->nop_timer = NULL;
1514 if (iscsilun->event_timer) {
1515 timer_del(iscsilun->event_timer);
1516 timer_free(iscsilun->event_timer);
1517 iscsilun->event_timer = NULL;
1521 static void iscsi_attach_aio_context(BlockDriverState *bs,
1522 AioContext *new_context)
1524 IscsiLun *iscsilun = bs->opaque;
1526 iscsilun->aio_context = new_context;
1527 iscsi_set_events(iscsilun);
1529 /* Set up a timer for sending out iSCSI NOPs */
1530 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1531 QEMU_CLOCK_REALTIME, SCALE_MS,
1532 iscsi_nop_timed_event, iscsilun);
1533 timer_mod(iscsilun->nop_timer,
1534 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1536 /* Set up a timer for periodic calls to iscsi_set_events and to
1537 * scan for command timeout */
1538 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1539 QEMU_CLOCK_REALTIME, SCALE_MS,
1540 iscsi_timed_check_events, iscsilun);
1541 timer_mod(iscsilun->event_timer,
1542 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1545 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1547 struct scsi_task *task;
1548 struct scsi_mode_sense *ms = NULL;
1549 iscsilun->write_protected = false;
1550 iscsilun->dpofua = false;
1552 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1553 1, SCSI_MODESENSE_PC_CURRENT,
1554 0x3F, 0, 255);
1555 if (task == NULL) {
1556 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1557 iscsi_get_error(iscsilun->iscsi));
1558 goto out;
1561 if (task->status != SCSI_STATUS_GOOD) {
1562 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1563 goto out;
1565 ms = scsi_datain_unmarshall(task);
1566 if (!ms) {
1567 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1568 iscsi_get_error(iscsilun->iscsi));
1569 goto out;
1571 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1572 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1574 out:
1575 if (task) {
1576 scsi_free_scsi_task(task);
1580 static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1582 QemuOptsList *list;
1583 QemuOpts *opts;
1584 const char *user, *password, *password_secret, *initiator_name,
1585 *header_digest, *timeout;
1587 list = qemu_find_opts("iscsi");
1588 if (!list) {
1589 return;
1592 opts = qemu_opts_find(list, target);
1593 if (opts == NULL) {
1594 opts = QTAILQ_FIRST(&list->head);
1595 if (!opts) {
1596 return;
1600 user = qemu_opt_get(opts, "user");
1601 if (user) {
1602 qdict_set_default_str(options, "user", user);
1605 password = qemu_opt_get(opts, "password");
1606 if (password) {
1607 qdict_set_default_str(options, "password", password);
1610 password_secret = qemu_opt_get(opts, "password-secret");
1611 if (password_secret) {
1612 qdict_set_default_str(options, "password-secret", password_secret);
1615 initiator_name = qemu_opt_get(opts, "initiator-name");
1616 if (initiator_name) {
1617 qdict_set_default_str(options, "initiator-name", initiator_name);
1620 header_digest = qemu_opt_get(opts, "header-digest");
1621 if (header_digest) {
1622 /* -iscsi takes upper case values, but QAPI only supports lower case
1623 * enum constant names, so we have to convert here. */
1624 char *qapi_value = g_ascii_strdown(header_digest, -1);
1625 qdict_set_default_str(options, "header-digest", qapi_value);
1626 g_free(qapi_value);
1629 timeout = qemu_opt_get(opts, "timeout");
1630 if (timeout) {
1631 qdict_set_default_str(options, "timeout", timeout);
1636 * We support iscsi url's on the form
1637 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1639 static void iscsi_parse_filename(const char *filename, QDict *options,
1640 Error **errp)
1642 struct iscsi_url *iscsi_url;
1643 const char *transport_name;
1644 char *lun_str;
1646 iscsi_url = iscsi_parse_full_url(NULL, filename);
1647 if (iscsi_url == NULL) {
1648 error_setg(errp, "Failed to parse URL : %s", filename);
1649 return;
1652 #if LIBISCSI_API_VERSION >= (20160603)
1653 switch (iscsi_url->transport) {
1654 case TCP_TRANSPORT:
1655 transport_name = "tcp";
1656 break;
1657 case ISER_TRANSPORT:
1658 transport_name = "iser";
1659 break;
1660 default:
1661 error_setg(errp, "Unknown transport type (%d)",
1662 iscsi_url->transport);
1663 return;
1665 #else
1666 transport_name = "tcp";
1667 #endif
1669 qdict_set_default_str(options, "transport", transport_name);
1670 qdict_set_default_str(options, "portal", iscsi_url->portal);
1671 qdict_set_default_str(options, "target", iscsi_url->target);
1673 lun_str = g_strdup_printf("%d", iscsi_url->lun);
1674 qdict_set_default_str(options, "lun", lun_str);
1675 g_free(lun_str);
1677 /* User/password from -iscsi take precedence over those from the URL */
1678 iscsi_parse_iscsi_option(iscsi_url->target, options);
1680 if (iscsi_url->user[0] != '\0') {
1681 qdict_set_default_str(options, "user", iscsi_url->user);
1682 qdict_set_default_str(options, "password", iscsi_url->passwd);
1685 iscsi_destroy_url(iscsi_url);
1688 static QemuOptsList runtime_opts = {
1689 .name = "iscsi",
1690 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1691 .desc = {
1693 .name = "transport",
1694 .type = QEMU_OPT_STRING,
1697 .name = "portal",
1698 .type = QEMU_OPT_STRING,
1701 .name = "target",
1702 .type = QEMU_OPT_STRING,
1705 .name = "user",
1706 .type = QEMU_OPT_STRING,
1709 .name = "password",
1710 .type = QEMU_OPT_STRING,
1713 .name = "password-secret",
1714 .type = QEMU_OPT_STRING,
1717 .name = "lun",
1718 .type = QEMU_OPT_NUMBER,
1721 .name = "initiator-name",
1722 .type = QEMU_OPT_STRING,
1725 .name = "header-digest",
1726 .type = QEMU_OPT_STRING,
1729 .name = "timeout",
1730 .type = QEMU_OPT_NUMBER,
1732 { /* end of list */ }
1736 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1737 Error **errp)
1739 IscsiLun *iscsilun = bs->opaque;
1740 struct iscsi_context *iscsi = NULL;
1741 struct scsi_task *task = NULL;
1742 struct scsi_inquiry_standard *inq = NULL;
1743 struct scsi_inquiry_supported_pages *inq_vpd;
1744 char *initiator_name = NULL;
1745 QemuOpts *opts;
1746 Error *local_err = NULL;
1747 const char *transport_name, *portal, *target;
1748 #if LIBISCSI_API_VERSION >= (20160603)
1749 enum iscsi_transport_type transport;
1750 #endif
1751 int i, ret = 0, timeout = 0, lun;
1753 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1754 qemu_opts_absorb_qdict(opts, options, &local_err);
1755 if (local_err) {
1756 error_propagate(errp, local_err);
1757 ret = -EINVAL;
1758 goto out;
1761 transport_name = qemu_opt_get(opts, "transport");
1762 portal = qemu_opt_get(opts, "portal");
1763 target = qemu_opt_get(opts, "target");
1764 lun = qemu_opt_get_number(opts, "lun", 0);
1766 if (!transport_name || !portal || !target) {
1767 error_setg(errp, "Need all of transport, portal and target options");
1768 ret = -EINVAL;
1769 goto out;
1772 if (!strcmp(transport_name, "tcp")) {
1773 #if LIBISCSI_API_VERSION >= (20160603)
1774 transport = TCP_TRANSPORT;
1775 } else if (!strcmp(transport_name, "iser")) {
1776 transport = ISER_TRANSPORT;
1777 #else
1778 /* TCP is what older libiscsi versions always use */
1779 #endif
1780 } else {
1781 error_setg(errp, "Unknown transport: %s", transport_name);
1782 ret = -EINVAL;
1783 goto out;
1786 memset(iscsilun, 0, sizeof(IscsiLun));
1788 initiator_name = get_initiator_name(opts);
1790 iscsi = iscsi_create_context(initiator_name);
1791 if (iscsi == NULL) {
1792 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1793 ret = -ENOMEM;
1794 goto out;
1796 #if LIBISCSI_API_VERSION >= (20160603)
1797 if (iscsi_init_transport(iscsi, transport)) {
1798 error_setg(errp, ("Error initializing transport."));
1799 ret = -EINVAL;
1800 goto out;
1802 #endif
1803 if (iscsi_set_targetname(iscsi, target)) {
1804 error_setg(errp, "iSCSI: Failed to set target name.");
1805 ret = -EINVAL;
1806 goto out;
1809 /* check if we got CHAP username/password via the options */
1810 apply_chap(iscsi, opts, &local_err);
1811 if (local_err != NULL) {
1812 error_propagate(errp, local_err);
1813 ret = -EINVAL;
1814 goto out;
1817 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1818 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1819 ret = -EINVAL;
1820 goto out;
1823 /* check if we got HEADER_DIGEST via the options */
1824 apply_header_digest(iscsi, opts, &local_err);
1825 if (local_err != NULL) {
1826 error_propagate(errp, local_err);
1827 ret = -EINVAL;
1828 goto out;
1831 /* timeout handling is broken in libiscsi before 1.15.0 */
1832 timeout = qemu_opt_get_number(opts, "timeout", 0);
1833 #if LIBISCSI_API_VERSION >= 20150621
1834 iscsi_set_timeout(iscsi, timeout);
1835 #else
1836 if (timeout) {
1837 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1839 #endif
1841 if (iscsi_full_connect_sync(iscsi, portal, lun) != 0) {
1842 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1843 iscsi_get_error(iscsi));
1844 ret = -EINVAL;
1845 goto out;
1848 iscsilun->iscsi = iscsi;
1849 iscsilun->aio_context = bdrv_get_aio_context(bs);
1850 iscsilun->lun = lun;
1851 iscsilun->has_write_same = true;
1853 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1854 (void **) &inq, errp);
1855 if (task == NULL) {
1856 ret = -EINVAL;
1857 goto out;
1859 iscsilun->type = inq->periperal_device_type;
1860 scsi_free_scsi_task(task);
1861 task = NULL;
1863 iscsi_modesense_sync(iscsilun);
1864 if (iscsilun->dpofua) {
1865 bs->supported_write_flags = BDRV_REQ_FUA;
1867 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1869 /* Check the write protect flag of the LUN if we want to write */
1870 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1871 iscsilun->write_protected) {
1872 error_setg(errp, "Cannot open a write protected LUN as read-write");
1873 ret = -EACCES;
1874 goto out;
1877 iscsi_readcapacity_sync(iscsilun, &local_err);
1878 if (local_err != NULL) {
1879 error_propagate(errp, local_err);
1880 ret = -EINVAL;
1881 goto out;
1883 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1885 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1886 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1887 * will try to read from the device to guess the image format.
1889 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1890 bs->sg = true;
1893 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1894 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1895 (void **) &inq_vpd, errp);
1896 if (task == NULL) {
1897 ret = -EINVAL;
1898 goto out;
1900 for (i = 0; i < inq_vpd->num_pages; i++) {
1901 struct scsi_task *inq_task;
1902 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1903 struct scsi_inquiry_block_limits *inq_bl;
1904 switch (inq_vpd->pages[i]) {
1905 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1906 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1907 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1908 (void **) &inq_lbp, errp);
1909 if (inq_task == NULL) {
1910 ret = -EINVAL;
1911 goto out;
1913 memcpy(&iscsilun->lbp, inq_lbp,
1914 sizeof(struct scsi_inquiry_logical_block_provisioning));
1915 scsi_free_scsi_task(inq_task);
1916 break;
1917 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1918 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1919 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1920 (void **) &inq_bl, errp);
1921 if (inq_task == NULL) {
1922 ret = -EINVAL;
1923 goto out;
1925 memcpy(&iscsilun->bl, inq_bl,
1926 sizeof(struct scsi_inquiry_block_limits));
1927 scsi_free_scsi_task(inq_task);
1928 break;
1929 default:
1930 break;
1933 scsi_free_scsi_task(task);
1934 task = NULL;
1936 qemu_mutex_init(&iscsilun->mutex);
1937 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1939 /* Guess the internal cluster (page) size of the iscsi target by the means
1940 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1941 * reasonable size */
1942 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1943 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1944 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1945 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1946 if (iscsilun->lbprz) {
1947 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1951 out:
1952 qemu_opts_del(opts);
1953 g_free(initiator_name);
1954 if (task != NULL) {
1955 scsi_free_scsi_task(task);
1958 if (ret) {
1959 if (iscsi != NULL) {
1960 if (iscsi_is_logged_in(iscsi)) {
1961 iscsi_logout_sync(iscsi);
1963 iscsi_destroy_context(iscsi);
1965 memset(iscsilun, 0, sizeof(IscsiLun));
1967 return ret;
1970 static void iscsi_close(BlockDriverState *bs)
1972 IscsiLun *iscsilun = bs->opaque;
1973 struct iscsi_context *iscsi = iscsilun->iscsi;
1975 iscsi_detach_aio_context(bs);
1976 if (iscsi_is_logged_in(iscsi)) {
1977 iscsi_logout_sync(iscsi);
1979 iscsi_destroy_context(iscsi);
1980 g_free(iscsilun->zeroblock);
1981 iscsi_allocmap_free(iscsilun);
1982 qemu_mutex_destroy(&iscsilun->mutex);
1983 memset(iscsilun, 0, sizeof(IscsiLun));
1986 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1988 /* We don't actually refresh here, but just return data queried in
1989 * iscsi_open(): iscsi targets don't change their limits. */
1991 IscsiLun *iscsilun = bs->opaque;
1992 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1993 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
1995 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
1997 bs->bl.request_alignment = block_size;
1999 if (iscsilun->bl.max_xfer_len) {
2000 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
2003 if (max_xfer_len * block_size < INT_MAX) {
2004 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
2007 if (iscsilun->lbp.lbpu) {
2008 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
2009 bs->bl.max_pdiscard =
2010 iscsilun->bl.max_unmap * iscsilun->block_size;
2012 bs->bl.pdiscard_alignment =
2013 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2014 } else {
2015 bs->bl.pdiscard_alignment = iscsilun->block_size;
2018 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
2019 bs->bl.max_pwrite_zeroes =
2020 iscsilun->bl.max_ws_len * iscsilun->block_size;
2022 if (iscsilun->lbp.lbpws) {
2023 bs->bl.pwrite_zeroes_alignment =
2024 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
2025 } else {
2026 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
2028 if (iscsilun->bl.opt_xfer_len &&
2029 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
2030 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
2031 iscsilun->block_size);
2035 /* Note that this will not re-establish a connection with an iSCSI target - it
2036 * is effectively a NOP. */
2037 static int iscsi_reopen_prepare(BDRVReopenState *state,
2038 BlockReopenQueue *queue, Error **errp)
2040 IscsiLun *iscsilun = state->bs->opaque;
2042 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
2043 error_setg(errp, "Cannot open a write protected LUN as read-write");
2044 return -EACCES;
2046 return 0;
2049 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
2051 IscsiLun *iscsilun = reopen_state->bs->opaque;
2053 /* the cache.direct status might have changed */
2054 if (iscsilun->allocmap != NULL) {
2055 iscsi_allocmap_init(iscsilun, reopen_state->flags);
2059 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
2061 IscsiLun *iscsilun = bs->opaque;
2062 Error *local_err = NULL;
2064 if (iscsilun->type != TYPE_DISK) {
2065 return -ENOTSUP;
2068 iscsi_readcapacity_sync(iscsilun, &local_err);
2069 if (local_err != NULL) {
2070 error_free(local_err);
2071 return -EIO;
2074 if (offset > iscsi_getlength(bs)) {
2075 return -EINVAL;
2078 if (iscsilun->allocmap != NULL) {
2079 iscsi_allocmap_init(iscsilun, bs->open_flags);
2082 return 0;
2085 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
2087 int ret = 0;
2088 int64_t total_size = 0;
2089 BlockDriverState *bs;
2090 IscsiLun *iscsilun = NULL;
2091 QDict *bs_options;
2093 bs = bdrv_new();
2095 /* Read out options */
2096 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2097 BDRV_SECTOR_SIZE);
2098 bs->opaque = g_new0(struct IscsiLun, 1);
2099 iscsilun = bs->opaque;
2101 bs_options = qdict_new();
2102 qdict_put(bs_options, "filename", qstring_from_str(filename));
2103 ret = iscsi_open(bs, bs_options, 0, NULL);
2104 QDECREF(bs_options);
2106 if (ret != 0) {
2107 goto out;
2109 iscsi_detach_aio_context(bs);
2110 if (iscsilun->type != TYPE_DISK) {
2111 ret = -ENODEV;
2112 goto out;
2114 if (bs->total_sectors < total_size) {
2115 ret = -ENOSPC;
2116 goto out;
2119 ret = 0;
2120 out:
2121 if (iscsilun->iscsi != NULL) {
2122 iscsi_destroy_context(iscsilun->iscsi);
2124 g_free(bs->opaque);
2125 bs->opaque = NULL;
2126 bdrv_unref(bs);
2127 return ret;
2130 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2132 IscsiLun *iscsilun = bs->opaque;
2133 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
2134 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
2135 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
2136 return 0;
2139 static void iscsi_invalidate_cache(BlockDriverState *bs,
2140 Error **errp)
2142 IscsiLun *iscsilun = bs->opaque;
2143 iscsi_allocmap_invalidate(iscsilun);
2146 static QemuOptsList iscsi_create_opts = {
2147 .name = "iscsi-create-opts",
2148 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2149 .desc = {
2151 .name = BLOCK_OPT_SIZE,
2152 .type = QEMU_OPT_SIZE,
2153 .help = "Virtual disk size"
2155 { /* end of list */ }
2159 static BlockDriver bdrv_iscsi = {
2160 .format_name = "iscsi",
2161 .protocol_name = "iscsi",
2163 .instance_size = sizeof(IscsiLun),
2164 .bdrv_parse_filename = iscsi_parse_filename,
2165 .bdrv_file_open = iscsi_open,
2166 .bdrv_close = iscsi_close,
2167 .bdrv_create = iscsi_create,
2168 .create_opts = &iscsi_create_opts,
2169 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2170 .bdrv_reopen_commit = iscsi_reopen_commit,
2171 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2173 .bdrv_getlength = iscsi_getlength,
2174 .bdrv_get_info = iscsi_get_info,
2175 .bdrv_truncate = iscsi_truncate,
2176 .bdrv_refresh_limits = iscsi_refresh_limits,
2178 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2179 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2180 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2181 .bdrv_co_readv = iscsi_co_readv,
2182 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2183 .bdrv_co_flush_to_disk = iscsi_co_flush,
2185 #ifdef __linux__
2186 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2187 #endif
2189 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2190 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2193 #if LIBISCSI_API_VERSION >= (20160603)
2194 static BlockDriver bdrv_iser = {
2195 .format_name = "iser",
2196 .protocol_name = "iser",
2198 .instance_size = sizeof(IscsiLun),
2199 .bdrv_parse_filename = iscsi_parse_filename,
2200 .bdrv_file_open = iscsi_open,
2201 .bdrv_close = iscsi_close,
2202 .bdrv_create = iscsi_create,
2203 .create_opts = &iscsi_create_opts,
2204 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2205 .bdrv_reopen_commit = iscsi_reopen_commit,
2206 .bdrv_invalidate_cache = iscsi_invalidate_cache,
2208 .bdrv_getlength = iscsi_getlength,
2209 .bdrv_get_info = iscsi_get_info,
2210 .bdrv_truncate = iscsi_truncate,
2211 .bdrv_refresh_limits = iscsi_refresh_limits,
2213 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2214 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2215 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2216 .bdrv_co_readv = iscsi_co_readv,
2217 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2218 .bdrv_co_flush_to_disk = iscsi_co_flush,
2220 #ifdef __linux__
2221 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2222 #endif
2224 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2225 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2227 #endif
2229 static void iscsi_block_init(void)
2231 bdrv_register(&bdrv_iscsi);
2232 #if LIBISCSI_API_VERSION >= (20160603)
2233 bdrv_register(&bdrv_iser);
2234 #endif
2237 block_init(iscsi_block_init);