migration: yet more possible state transitions
[qemu/ar7.git] / block / iscsi.c
blob93f1ee4c63120a0e05f005c18e875f524e19f27d
1 /*
2 * QEMU Block driver for iSCSI images
4 * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
5 * Copyright (c) 2012-2015 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 "config-host.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 "sysemu/sysemu.h"
40 #include "qmp-commands.h"
41 #include "qapi/qmp/qstring.h"
43 #include <iscsi/iscsi.h>
44 #include <iscsi/scsi-lowlevel.h>
46 #ifdef __linux__
47 #include <scsi/sg.h>
48 #include <block/scsi.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 struct scsi_inquiry_logical_block_provisioning lbp;
62 struct scsi_inquiry_block_limits bl;
63 unsigned char *zeroblock;
64 unsigned long *allocationmap;
65 int cluster_sectors;
66 bool use_16_for_rw;
67 bool write_protected;
68 bool lbpme;
69 bool lbprz;
70 bool dpofua;
71 bool has_write_same;
72 bool force_next_flush;
73 bool request_timed_out;
74 } IscsiLun;
76 typedef struct IscsiTask {
77 int status;
78 int complete;
79 int retries;
80 int do_retry;
81 struct scsi_task *task;
82 Coroutine *co;
83 QEMUBH *bh;
84 IscsiLun *iscsilun;
85 QEMUTimer retry_timer;
86 bool force_next_flush;
87 } IscsiTask;
89 typedef struct IscsiAIOCB {
90 BlockAIOCB common;
91 QEMUIOVector *qiov;
92 QEMUBH *bh;
93 IscsiLun *iscsilun;
94 struct scsi_task *task;
95 uint8_t *buf;
96 int status;
97 int64_t sector_num;
98 int nb_sectors;
99 #ifdef __linux__
100 sg_io_hdr_t *ioh;
101 #endif
102 } IscsiAIOCB;
104 /* libiscsi uses time_t so its enough to process events every second */
105 #define EVENT_INTERVAL 1000
106 #define NOP_INTERVAL 5000
107 #define MAX_NOP_FAILURES 3
108 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
109 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
111 /* this threshold is a trade-off knob to choose between
112 * the potential additional overhead of an extra GET_LBA_STATUS request
113 * vs. unnecessarily reading a lot of zero sectors over the wire.
114 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
115 * sectors we check the allocation status of the area covered by the
116 * request first if the allocationmap indicates that the area might be
117 * unallocated. */
118 #define ISCSI_CHECKALLOC_THRES 64
120 static void
121 iscsi_bh_cb(void *p)
123 IscsiAIOCB *acb = p;
125 qemu_bh_delete(acb->bh);
127 g_free(acb->buf);
128 acb->buf = NULL;
130 acb->common.cb(acb->common.opaque, acb->status);
132 if (acb->task != NULL) {
133 scsi_free_scsi_task(acb->task);
134 acb->task = NULL;
137 qemu_aio_unref(acb);
140 static void
141 iscsi_schedule_bh(IscsiAIOCB *acb)
143 if (acb->bh) {
144 return;
146 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
147 qemu_bh_schedule(acb->bh);
150 static void iscsi_co_generic_bh_cb(void *opaque)
152 struct IscsiTask *iTask = opaque;
153 iTask->complete = 1;
154 qemu_bh_delete(iTask->bh);
155 qemu_coroutine_enter(iTask->co, NULL);
158 static void iscsi_retry_timer_expired(void *opaque)
160 struct IscsiTask *iTask = opaque;
161 iTask->complete = 1;
162 if (iTask->co) {
163 qemu_coroutine_enter(iTask->co, NULL);
167 static inline unsigned exp_random(double mean)
169 return -mean * log((double)rand() / RAND_MAX);
172 /* SCSI_STATUS_TASK_SET_FULL and SCSI_STATUS_TIMEOUT were introduced
173 * in libiscsi 1.10.0 as part of an enum. The LIBISCSI_API_VERSION
174 * macro was introduced in 1.11.0. So use the API_VERSION macro as
175 * a hint that the macros are defined and define them ourselves
176 * otherwise to keep the required libiscsi version at 1.9.0 */
177 #if !defined(LIBISCSI_API_VERSION)
178 #define QEMU_SCSI_STATUS_TASK_SET_FULL 0x28
179 #define QEMU_SCSI_STATUS_TIMEOUT 0x0f000002
180 #else
181 #define QEMU_SCSI_STATUS_TASK_SET_FULL SCSI_STATUS_TASK_SET_FULL
182 #define QEMU_SCSI_STATUS_TIMEOUT SCSI_STATUS_TIMEOUT
183 #endif
185 static void
186 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
187 void *command_data, void *opaque)
189 struct IscsiTask *iTask = opaque;
190 struct scsi_task *task = command_data;
192 iTask->status = status;
193 iTask->do_retry = 0;
194 iTask->task = task;
196 if (status != SCSI_STATUS_GOOD) {
197 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
198 if (status == SCSI_STATUS_CHECK_CONDITION
199 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
200 error_report("iSCSI CheckCondition: %s",
201 iscsi_get_error(iscsi));
202 iTask->do_retry = 1;
203 goto out;
205 if (status == SCSI_STATUS_BUSY ||
206 status == QEMU_SCSI_STATUS_TIMEOUT ||
207 status == QEMU_SCSI_STATUS_TASK_SET_FULL) {
208 unsigned retry_time =
209 exp_random(iscsi_retry_times[iTask->retries - 1]);
210 if (status == QEMU_SCSI_STATUS_TIMEOUT) {
211 /* make sure the request is rescheduled AFTER the
212 * reconnect is initiated */
213 retry_time = EVENT_INTERVAL * 2;
214 iTask->iscsilun->request_timed_out = true;
216 error_report("iSCSI Busy/TaskSetFull/TimeOut"
217 " (retry #%u in %u ms): %s",
218 iTask->retries, retry_time,
219 iscsi_get_error(iscsi));
220 aio_timer_init(iTask->iscsilun->aio_context,
221 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
222 SCALE_MS, iscsi_retry_timer_expired, iTask);
223 timer_mod(&iTask->retry_timer,
224 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
225 iTask->do_retry = 1;
226 return;
229 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
230 } else {
231 iTask->iscsilun->force_next_flush |= iTask->force_next_flush;
234 out:
235 if (iTask->co) {
236 iTask->bh = aio_bh_new(iTask->iscsilun->aio_context,
237 iscsi_co_generic_bh_cb, iTask);
238 qemu_bh_schedule(iTask->bh);
239 } else {
240 iTask->complete = 1;
244 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
246 *iTask = (struct IscsiTask) {
247 .co = qemu_coroutine_self(),
248 .iscsilun = iscsilun,
252 static void
253 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
254 void *private_data)
256 IscsiAIOCB *acb = private_data;
258 acb->status = -ECANCELED;
259 iscsi_schedule_bh(acb);
262 static void
263 iscsi_aio_cancel(BlockAIOCB *blockacb)
265 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
266 IscsiLun *iscsilun = acb->iscsilun;
268 if (acb->status != -EINPROGRESS) {
269 return;
272 /* send a task mgmt call to the target to cancel the task on the target */
273 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
274 iscsi_abort_task_cb, acb);
278 static const AIOCBInfo iscsi_aiocb_info = {
279 .aiocb_size = sizeof(IscsiAIOCB),
280 .cancel_async = iscsi_aio_cancel,
284 static void iscsi_process_read(void *arg);
285 static void iscsi_process_write(void *arg);
287 static void
288 iscsi_set_events(IscsiLun *iscsilun)
290 struct iscsi_context *iscsi = iscsilun->iscsi;
291 int ev = iscsi_which_events(iscsi);
293 if (ev != iscsilun->events) {
294 aio_set_fd_handler(iscsilun->aio_context,
295 iscsi_get_fd(iscsi),
296 (ev & POLLIN) ? iscsi_process_read : NULL,
297 (ev & POLLOUT) ? iscsi_process_write : NULL,
298 iscsilun);
299 iscsilun->events = ev;
303 static void iscsi_timed_check_events(void *opaque)
305 IscsiLun *iscsilun = opaque;
307 /* check for timed out requests */
308 iscsi_service(iscsilun->iscsi, 0);
310 if (iscsilun->request_timed_out) {
311 iscsilun->request_timed_out = false;
312 iscsi_reconnect(iscsilun->iscsi);
315 /* newer versions of libiscsi may return zero events. Ensure we are able
316 * to return to service once this situation changes. */
317 iscsi_set_events(iscsilun);
319 timer_mod(iscsilun->event_timer,
320 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
323 static void
324 iscsi_process_read(void *arg)
326 IscsiLun *iscsilun = arg;
327 struct iscsi_context *iscsi = iscsilun->iscsi;
329 iscsi_service(iscsi, POLLIN);
330 iscsi_set_events(iscsilun);
333 static void
334 iscsi_process_write(void *arg)
336 IscsiLun *iscsilun = arg;
337 struct iscsi_context *iscsi = iscsilun->iscsi;
339 iscsi_service(iscsi, POLLOUT);
340 iscsi_set_events(iscsilun);
343 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
345 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
348 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
350 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
353 static bool is_request_lun_aligned(int64_t sector_num, int nb_sectors,
354 IscsiLun *iscsilun)
356 if ((sector_num * BDRV_SECTOR_SIZE) % iscsilun->block_size ||
357 (nb_sectors * BDRV_SECTOR_SIZE) % iscsilun->block_size) {
358 error_report("iSCSI misaligned request: "
359 "iscsilun->block_size %u, sector_num %" PRIi64
360 ", nb_sectors %d",
361 iscsilun->block_size, sector_num, nb_sectors);
362 return 0;
364 return 1;
367 static unsigned long *iscsi_allocationmap_init(IscsiLun *iscsilun)
369 return bitmap_try_new(DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks,
370 iscsilun),
371 iscsilun->cluster_sectors));
374 static void iscsi_allocationmap_set(IscsiLun *iscsilun, int64_t sector_num,
375 int nb_sectors)
377 if (iscsilun->allocationmap == NULL) {
378 return;
380 bitmap_set(iscsilun->allocationmap,
381 sector_num / iscsilun->cluster_sectors,
382 DIV_ROUND_UP(nb_sectors, iscsilun->cluster_sectors));
385 static void iscsi_allocationmap_clear(IscsiLun *iscsilun, int64_t sector_num,
386 int nb_sectors)
388 int64_t cluster_num, nb_clusters;
389 if (iscsilun->allocationmap == NULL) {
390 return;
392 cluster_num = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
393 nb_clusters = (sector_num + nb_sectors) / iscsilun->cluster_sectors
394 - cluster_num;
395 if (nb_clusters > 0) {
396 bitmap_clear(iscsilun->allocationmap, cluster_num, nb_clusters);
400 static int coroutine_fn iscsi_co_writev(BlockDriverState *bs,
401 int64_t sector_num, int nb_sectors,
402 QEMUIOVector *iov)
404 IscsiLun *iscsilun = bs->opaque;
405 struct IscsiTask iTask;
406 uint64_t lba;
407 uint32_t num_sectors;
408 int fua;
410 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
411 return -EINVAL;
414 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
415 error_report("iSCSI Error: Write of %d sectors exceeds max_xfer_len "
416 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
417 return -EINVAL;
420 lba = sector_qemu2lun(sector_num, iscsilun);
421 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
422 iscsi_co_init_iscsitask(iscsilun, &iTask);
423 retry:
424 fua = iscsilun->dpofua && !bs->enable_write_cache;
425 iTask.force_next_flush = !fua;
426 if (iscsilun->use_16_for_rw) {
427 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
428 NULL, num_sectors * iscsilun->block_size,
429 iscsilun->block_size, 0, 0, fua, 0, 0,
430 iscsi_co_generic_cb, &iTask);
431 } else {
432 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
433 NULL, num_sectors * iscsilun->block_size,
434 iscsilun->block_size, 0, 0, fua, 0, 0,
435 iscsi_co_generic_cb, &iTask);
437 if (iTask.task == NULL) {
438 return -ENOMEM;
440 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
441 iov->niov);
442 while (!iTask.complete) {
443 iscsi_set_events(iscsilun);
444 qemu_coroutine_yield();
447 if (iTask.task != NULL) {
448 scsi_free_scsi_task(iTask.task);
449 iTask.task = NULL;
452 if (iTask.do_retry) {
453 iTask.complete = 0;
454 goto retry;
457 if (iTask.status != SCSI_STATUS_GOOD) {
458 return -EIO;
461 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
463 return 0;
467 static bool iscsi_allocationmap_is_allocated(IscsiLun *iscsilun,
468 int64_t sector_num, int nb_sectors)
470 unsigned long size;
471 if (iscsilun->allocationmap == NULL) {
472 return true;
474 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
475 return !(find_next_bit(iscsilun->allocationmap, size,
476 sector_num / iscsilun->cluster_sectors) == size);
479 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
480 int64_t sector_num,
481 int nb_sectors, int *pnum)
483 IscsiLun *iscsilun = bs->opaque;
484 struct scsi_get_lba_status *lbas = NULL;
485 struct scsi_lba_status_descriptor *lbasd = NULL;
486 struct IscsiTask iTask;
487 int64_t ret;
489 iscsi_co_init_iscsitask(iscsilun, &iTask);
491 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
492 ret = -EINVAL;
493 goto out;
496 /* default to all sectors allocated */
497 ret = BDRV_BLOCK_DATA;
498 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
499 *pnum = nb_sectors;
501 /* LUN does not support logical block provisioning */
502 if (!iscsilun->lbpme) {
503 goto out;
506 retry:
507 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
508 sector_qemu2lun(sector_num, iscsilun),
509 8 + 16, iscsi_co_generic_cb,
510 &iTask) == NULL) {
511 ret = -ENOMEM;
512 goto out;
515 while (!iTask.complete) {
516 iscsi_set_events(iscsilun);
517 qemu_coroutine_yield();
520 if (iTask.do_retry) {
521 if (iTask.task != NULL) {
522 scsi_free_scsi_task(iTask.task);
523 iTask.task = NULL;
525 iTask.complete = 0;
526 goto retry;
529 if (iTask.status != SCSI_STATUS_GOOD) {
530 /* in case the get_lba_status_callout fails (i.e.
531 * because the device is busy or the cmd is not
532 * supported) we pretend all blocks are allocated
533 * for backwards compatibility */
534 goto out;
537 lbas = scsi_datain_unmarshall(iTask.task);
538 if (lbas == NULL) {
539 ret = -EIO;
540 goto out;
543 lbasd = &lbas->descriptors[0];
545 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
546 ret = -EIO;
547 goto out;
550 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
552 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
553 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
554 ret &= ~BDRV_BLOCK_DATA;
555 if (iscsilun->lbprz) {
556 ret |= BDRV_BLOCK_ZERO;
560 if (ret & BDRV_BLOCK_ZERO) {
561 iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);
562 } else {
563 iscsi_allocationmap_set(iscsilun, sector_num, *pnum);
566 if (*pnum > nb_sectors) {
567 *pnum = nb_sectors;
569 out:
570 if (iTask.task != NULL) {
571 scsi_free_scsi_task(iTask.task);
573 return ret;
576 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
577 int64_t sector_num, int nb_sectors,
578 QEMUIOVector *iov)
580 IscsiLun *iscsilun = bs->opaque;
581 struct IscsiTask iTask;
582 uint64_t lba;
583 uint32_t num_sectors;
585 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
586 return -EINVAL;
589 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
590 error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "
591 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
592 return -EINVAL;
595 if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
596 !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
597 int64_t ret;
598 int pnum;
599 ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum);
600 if (ret < 0) {
601 return ret;
603 if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
604 qemu_iovec_memset(iov, 0, 0x00, iov->size);
605 return 0;
609 lba = sector_qemu2lun(sector_num, iscsilun);
610 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
612 iscsi_co_init_iscsitask(iscsilun, &iTask);
613 retry:
614 if (iscsilun->use_16_for_rw) {
615 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
616 num_sectors * iscsilun->block_size,
617 iscsilun->block_size, 0, 0, 0, 0, 0,
618 iscsi_co_generic_cb, &iTask);
619 } else {
620 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
621 num_sectors * iscsilun->block_size,
622 iscsilun->block_size,
623 0, 0, 0, 0, 0,
624 iscsi_co_generic_cb, &iTask);
626 if (iTask.task == NULL) {
627 return -ENOMEM;
629 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
631 while (!iTask.complete) {
632 iscsi_set_events(iscsilun);
633 qemu_coroutine_yield();
636 if (iTask.task != NULL) {
637 scsi_free_scsi_task(iTask.task);
638 iTask.task = NULL;
641 if (iTask.do_retry) {
642 iTask.complete = 0;
643 goto retry;
646 if (iTask.status != SCSI_STATUS_GOOD) {
647 return -EIO;
650 return 0;
653 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
655 IscsiLun *iscsilun = bs->opaque;
656 struct IscsiTask iTask;
658 if (!iscsilun->force_next_flush) {
659 return 0;
661 iscsilun->force_next_flush = false;
663 iscsi_co_init_iscsitask(iscsilun, &iTask);
664 retry:
665 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
666 0, iscsi_co_generic_cb, &iTask) == NULL) {
667 return -ENOMEM;
670 while (!iTask.complete) {
671 iscsi_set_events(iscsilun);
672 qemu_coroutine_yield();
675 if (iTask.task != NULL) {
676 scsi_free_scsi_task(iTask.task);
677 iTask.task = NULL;
680 if (iTask.do_retry) {
681 iTask.complete = 0;
682 goto retry;
685 if (iTask.status != SCSI_STATUS_GOOD) {
686 return -EIO;
689 return 0;
692 #ifdef __linux__
693 static void
694 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
695 void *command_data, void *opaque)
697 IscsiAIOCB *acb = opaque;
699 g_free(acb->buf);
700 acb->buf = NULL;
702 acb->status = 0;
703 if (status < 0) {
704 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
705 iscsi_get_error(iscsi));
706 acb->status = -EIO;
709 acb->ioh->driver_status = 0;
710 acb->ioh->host_status = 0;
711 acb->ioh->resid = 0;
713 #define SG_ERR_DRIVER_SENSE 0x08
715 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
716 int ss;
718 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
720 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
721 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
722 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
723 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
726 iscsi_schedule_bh(acb);
729 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
730 unsigned long int req, void *buf,
731 BlockCompletionFunc *cb, void *opaque)
733 IscsiLun *iscsilun = bs->opaque;
734 struct iscsi_context *iscsi = iscsilun->iscsi;
735 struct iscsi_data data;
736 IscsiAIOCB *acb;
738 assert(req == SG_IO);
740 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
742 acb->iscsilun = iscsilun;
743 acb->bh = NULL;
744 acb->status = -EINPROGRESS;
745 acb->buf = NULL;
746 acb->ioh = buf;
748 acb->task = malloc(sizeof(struct scsi_task));
749 if (acb->task == NULL) {
750 error_report("iSCSI: Failed to allocate task for scsi command. %s",
751 iscsi_get_error(iscsi));
752 qemu_aio_unref(acb);
753 return NULL;
755 memset(acb->task, 0, sizeof(struct scsi_task));
757 switch (acb->ioh->dxfer_direction) {
758 case SG_DXFER_TO_DEV:
759 acb->task->xfer_dir = SCSI_XFER_WRITE;
760 break;
761 case SG_DXFER_FROM_DEV:
762 acb->task->xfer_dir = SCSI_XFER_READ;
763 break;
764 default:
765 acb->task->xfer_dir = SCSI_XFER_NONE;
766 break;
769 acb->task->cdb_size = acb->ioh->cmd_len;
770 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
771 acb->task->expxferlen = acb->ioh->dxfer_len;
773 data.size = 0;
774 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
775 if (acb->ioh->iovec_count == 0) {
776 data.data = acb->ioh->dxferp;
777 data.size = acb->ioh->dxfer_len;
778 } else {
779 scsi_task_set_iov_out(acb->task,
780 (struct scsi_iovec *) acb->ioh->dxferp,
781 acb->ioh->iovec_count);
785 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
786 iscsi_aio_ioctl_cb,
787 (data.size > 0) ? &data : NULL,
788 acb) != 0) {
789 scsi_free_scsi_task(acb->task);
790 qemu_aio_unref(acb);
791 return NULL;
794 /* tell libiscsi to read straight into the buffer we got from ioctl */
795 if (acb->task->xfer_dir == SCSI_XFER_READ) {
796 if (acb->ioh->iovec_count == 0) {
797 scsi_task_add_data_in_buffer(acb->task,
798 acb->ioh->dxfer_len,
799 acb->ioh->dxferp);
800 } else {
801 scsi_task_set_iov_in(acb->task,
802 (struct scsi_iovec *) acb->ioh->dxferp,
803 acb->ioh->iovec_count);
807 iscsi_set_events(iscsilun);
809 return &acb->common;
812 static void ioctl_cb(void *opaque, int status)
814 int *p_status = opaque;
815 *p_status = status;
818 static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
820 IscsiLun *iscsilun = bs->opaque;
821 int status;
823 switch (req) {
824 case SG_GET_VERSION_NUM:
825 *(int *)buf = 30000;
826 break;
827 case SG_GET_SCSI_ID:
828 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
829 break;
830 case SG_IO:
831 status = -EINPROGRESS;
832 iscsi_aio_ioctl(bs, req, buf, ioctl_cb, &status);
834 while (status == -EINPROGRESS) {
835 aio_poll(iscsilun->aio_context, true);
838 return 0;
839 default:
840 return -1;
842 return 0;
844 #endif
846 static int64_t
847 iscsi_getlength(BlockDriverState *bs)
849 IscsiLun *iscsilun = bs->opaque;
850 int64_t len;
852 len = iscsilun->num_blocks;
853 len *= iscsilun->block_size;
855 return len;
858 static int
859 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
860 int nb_sectors)
862 IscsiLun *iscsilun = bs->opaque;
863 struct IscsiTask iTask;
864 struct unmap_list list;
866 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
867 return -EINVAL;
870 if (!iscsilun->lbp.lbpu) {
871 /* UNMAP is not supported by the target */
872 return 0;
875 list.lba = sector_qemu2lun(sector_num, iscsilun);
876 list.num = sector_qemu2lun(nb_sectors, iscsilun);
878 iscsi_co_init_iscsitask(iscsilun, &iTask);
879 retry:
880 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
881 iscsi_co_generic_cb, &iTask) == NULL) {
882 return -ENOMEM;
885 while (!iTask.complete) {
886 iscsi_set_events(iscsilun);
887 qemu_coroutine_yield();
890 if (iTask.task != NULL) {
891 scsi_free_scsi_task(iTask.task);
892 iTask.task = NULL;
895 if (iTask.do_retry) {
896 iTask.complete = 0;
897 goto retry;
900 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
901 /* the target might fail with a check condition if it
902 is not happy with the alignment of the UNMAP request
903 we silently fail in this case */
904 return 0;
907 if (iTask.status != SCSI_STATUS_GOOD) {
908 return -EIO;
911 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
913 return 0;
916 static int
917 coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
918 int nb_sectors, BdrvRequestFlags flags)
920 IscsiLun *iscsilun = bs->opaque;
921 struct IscsiTask iTask;
922 uint64_t lba;
923 uint32_t nb_blocks;
924 bool use_16_for_ws = iscsilun->use_16_for_rw;
926 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
927 return -EINVAL;
930 if (flags & BDRV_REQ_MAY_UNMAP) {
931 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
932 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
933 use_16_for_ws = true;
935 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
936 /* WRITESAME16 with UNMAP is not supported by the target,
937 * fall back and try WRITESAME10/16 without UNMAP */
938 flags &= ~BDRV_REQ_MAY_UNMAP;
939 use_16_for_ws = iscsilun->use_16_for_rw;
943 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
944 /* WRITESAME without UNMAP is not supported by the target */
945 return -ENOTSUP;
948 lba = sector_qemu2lun(sector_num, iscsilun);
949 nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
951 if (iscsilun->zeroblock == NULL) {
952 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
953 if (iscsilun->zeroblock == NULL) {
954 return -ENOMEM;
958 iscsi_co_init_iscsitask(iscsilun, &iTask);
959 iTask.force_next_flush = true;
960 retry:
961 if (use_16_for_ws) {
962 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
963 iscsilun->zeroblock, iscsilun->block_size,
964 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
965 0, 0, iscsi_co_generic_cb, &iTask);
966 } else {
967 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
968 iscsilun->zeroblock, iscsilun->block_size,
969 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
970 0, 0, iscsi_co_generic_cb, &iTask);
972 if (iTask.task == NULL) {
973 return -ENOMEM;
976 while (!iTask.complete) {
977 iscsi_set_events(iscsilun);
978 qemu_coroutine_yield();
981 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
982 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
983 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
984 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
985 /* WRITE SAME is not supported by the target */
986 iscsilun->has_write_same = false;
987 scsi_free_scsi_task(iTask.task);
988 return -ENOTSUP;
991 if (iTask.task != NULL) {
992 scsi_free_scsi_task(iTask.task);
993 iTask.task = NULL;
996 if (iTask.do_retry) {
997 iTask.complete = 0;
998 goto retry;
1001 if (iTask.status != SCSI_STATUS_GOOD) {
1002 return -EIO;
1005 if (flags & BDRV_REQ_MAY_UNMAP) {
1006 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
1007 } else {
1008 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
1011 return 0;
1014 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1015 Error **errp)
1017 QemuOptsList *list;
1018 QemuOpts *opts;
1019 const char *user = NULL;
1020 const char *password = NULL;
1022 list = qemu_find_opts("iscsi");
1023 if (!list) {
1024 return;
1027 opts = qemu_opts_find(list, target);
1028 if (opts == NULL) {
1029 opts = QTAILQ_FIRST(&list->head);
1030 if (!opts) {
1031 return;
1035 user = qemu_opt_get(opts, "user");
1036 if (!user) {
1037 return;
1040 password = qemu_opt_get(opts, "password");
1041 if (!password) {
1042 error_setg(errp, "CHAP username specified but no password was given");
1043 return;
1046 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1047 error_setg(errp, "Failed to set initiator username and password");
1051 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1052 Error **errp)
1054 QemuOptsList *list;
1055 QemuOpts *opts;
1056 const char *digest = NULL;
1058 list = qemu_find_opts("iscsi");
1059 if (!list) {
1060 return;
1063 opts = qemu_opts_find(list, target);
1064 if (opts == NULL) {
1065 opts = QTAILQ_FIRST(&list->head);
1066 if (!opts) {
1067 return;
1071 digest = qemu_opt_get(opts, "header-digest");
1072 if (!digest) {
1073 return;
1076 if (!strcmp(digest, "CRC32C")) {
1077 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1078 } else if (!strcmp(digest, "NONE")) {
1079 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1080 } else if (!strcmp(digest, "CRC32C-NONE")) {
1081 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1082 } else if (!strcmp(digest, "NONE-CRC32C")) {
1083 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1084 } else {
1085 error_setg(errp, "Invalid header-digest setting : %s", digest);
1089 static char *parse_initiator_name(const char *target)
1091 QemuOptsList *list;
1092 QemuOpts *opts;
1093 const char *name;
1094 char *iscsi_name;
1095 UuidInfo *uuid_info;
1097 list = qemu_find_opts("iscsi");
1098 if (list) {
1099 opts = qemu_opts_find(list, target);
1100 if (!opts) {
1101 opts = QTAILQ_FIRST(&list->head);
1103 if (opts) {
1104 name = qemu_opt_get(opts, "initiator-name");
1105 if (name) {
1106 return g_strdup(name);
1111 uuid_info = qmp_query_uuid(NULL);
1112 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1113 name = qemu_get_vm_name();
1114 } else {
1115 name = uuid_info->UUID;
1117 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1118 name ? ":" : "", name ? name : "");
1119 qapi_free_UuidInfo(uuid_info);
1120 return iscsi_name;
1123 static int parse_timeout(const char *target)
1125 QemuOptsList *list;
1126 QemuOpts *opts;
1127 const char *timeout;
1129 list = qemu_find_opts("iscsi");
1130 if (list) {
1131 opts = qemu_opts_find(list, target);
1132 if (!opts) {
1133 opts = QTAILQ_FIRST(&list->head);
1135 if (opts) {
1136 timeout = qemu_opt_get(opts, "timeout");
1137 if (timeout) {
1138 return atoi(timeout);
1143 return 0;
1146 static void iscsi_nop_timed_event(void *opaque)
1148 IscsiLun *iscsilun = opaque;
1150 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1151 error_report("iSCSI: NOP timeout. Reconnecting...");
1152 iscsilun->request_timed_out = true;
1153 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1154 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1155 return;
1158 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1159 iscsi_set_events(iscsilun);
1162 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1164 struct scsi_task *task = NULL;
1165 struct scsi_readcapacity10 *rc10 = NULL;
1166 struct scsi_readcapacity16 *rc16 = NULL;
1167 int retries = ISCSI_CMD_RETRIES;
1169 do {
1170 if (task != NULL) {
1171 scsi_free_scsi_task(task);
1172 task = NULL;
1175 switch (iscsilun->type) {
1176 case TYPE_DISK:
1177 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1178 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1179 rc16 = scsi_datain_unmarshall(task);
1180 if (rc16 == NULL) {
1181 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1182 } else {
1183 iscsilun->block_size = rc16->block_length;
1184 iscsilun->num_blocks = rc16->returned_lba + 1;
1185 iscsilun->lbpme = !!rc16->lbpme;
1186 iscsilun->lbprz = !!rc16->lbprz;
1187 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1190 break;
1191 case TYPE_ROM:
1192 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1193 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1194 rc10 = scsi_datain_unmarshall(task);
1195 if (rc10 == NULL) {
1196 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1197 } else {
1198 iscsilun->block_size = rc10->block_size;
1199 if (rc10->lba == 0) {
1200 /* blank disk loaded */
1201 iscsilun->num_blocks = 0;
1202 } else {
1203 iscsilun->num_blocks = rc10->lba + 1;
1207 break;
1208 default:
1209 return;
1211 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1212 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1213 && retries-- > 0);
1215 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1216 error_setg(errp, "iSCSI: failed to send readcapacity10 command.");
1217 } else if (!iscsilun->block_size ||
1218 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1219 error_setg(errp, "iSCSI: the target returned an invalid "
1220 "block size of %d.", iscsilun->block_size);
1222 if (task) {
1223 scsi_free_scsi_task(task);
1227 /* TODO Convert to fine grained options */
1228 static QemuOptsList runtime_opts = {
1229 .name = "iscsi",
1230 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1231 .desc = {
1233 .name = "filename",
1234 .type = QEMU_OPT_STRING,
1235 .help = "URL to the iscsi image",
1237 { /* end of list */ }
1241 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1242 int evpd, int pc, void **inq, Error **errp)
1244 int full_size;
1245 struct scsi_task *task = NULL;
1246 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1247 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1248 goto fail;
1250 full_size = scsi_datain_getfullsize(task);
1251 if (full_size > task->datain.size) {
1252 scsi_free_scsi_task(task);
1254 /* we need more data for the full list */
1255 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1256 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1257 goto fail;
1261 *inq = scsi_datain_unmarshall(task);
1262 if (*inq == NULL) {
1263 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1264 goto fail_with_err;
1267 return task;
1269 fail:
1270 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1271 iscsi_get_error(iscsi));
1272 fail_with_err:
1273 if (task != NULL) {
1274 scsi_free_scsi_task(task);
1276 return NULL;
1279 static void iscsi_detach_aio_context(BlockDriverState *bs)
1281 IscsiLun *iscsilun = bs->opaque;
1283 aio_set_fd_handler(iscsilun->aio_context,
1284 iscsi_get_fd(iscsilun->iscsi),
1285 NULL, NULL, NULL);
1286 iscsilun->events = 0;
1288 if (iscsilun->nop_timer) {
1289 timer_del(iscsilun->nop_timer);
1290 timer_free(iscsilun->nop_timer);
1291 iscsilun->nop_timer = NULL;
1293 if (iscsilun->event_timer) {
1294 timer_del(iscsilun->event_timer);
1295 timer_free(iscsilun->event_timer);
1296 iscsilun->event_timer = NULL;
1300 static void iscsi_attach_aio_context(BlockDriverState *bs,
1301 AioContext *new_context)
1303 IscsiLun *iscsilun = bs->opaque;
1305 iscsilun->aio_context = new_context;
1306 iscsi_set_events(iscsilun);
1308 /* Set up a timer for sending out iSCSI NOPs */
1309 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1310 QEMU_CLOCK_REALTIME, SCALE_MS,
1311 iscsi_nop_timed_event, iscsilun);
1312 timer_mod(iscsilun->nop_timer,
1313 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1315 /* Set up a timer for periodic calls to iscsi_set_events and to
1316 * scan for command timeout */
1317 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1318 QEMU_CLOCK_REALTIME, SCALE_MS,
1319 iscsi_timed_check_events, iscsilun);
1320 timer_mod(iscsilun->event_timer,
1321 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1324 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1326 struct scsi_task *task;
1327 struct scsi_mode_sense *ms = NULL;
1328 iscsilun->write_protected = false;
1329 iscsilun->dpofua = false;
1331 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1332 1, SCSI_MODESENSE_PC_CURRENT,
1333 0x3F, 0, 255);
1334 if (task == NULL) {
1335 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1336 iscsi_get_error(iscsilun->iscsi));
1337 goto out;
1340 if (task->status != SCSI_STATUS_GOOD) {
1341 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1342 goto out;
1344 ms = scsi_datain_unmarshall(task);
1345 if (!ms) {
1346 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1347 iscsi_get_error(iscsilun->iscsi));
1348 goto out;
1350 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1351 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1353 out:
1354 if (task) {
1355 scsi_free_scsi_task(task);
1360 * We support iscsi url's on the form
1361 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1363 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1364 Error **errp)
1366 IscsiLun *iscsilun = bs->opaque;
1367 struct iscsi_context *iscsi = NULL;
1368 struct iscsi_url *iscsi_url = NULL;
1369 struct scsi_task *task = NULL;
1370 struct scsi_inquiry_standard *inq = NULL;
1371 struct scsi_inquiry_supported_pages *inq_vpd;
1372 char *initiator_name = NULL;
1373 QemuOpts *opts;
1374 Error *local_err = NULL;
1375 const char *filename;
1376 int i, ret = 0, timeout = 0;
1378 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1379 qemu_opts_absorb_qdict(opts, options, &local_err);
1380 if (local_err) {
1381 error_propagate(errp, local_err);
1382 ret = -EINVAL;
1383 goto out;
1386 filename = qemu_opt_get(opts, "filename");
1388 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1389 if (iscsi_url == NULL) {
1390 error_setg(errp, "Failed to parse URL : %s", filename);
1391 ret = -EINVAL;
1392 goto out;
1395 memset(iscsilun, 0, sizeof(IscsiLun));
1397 initiator_name = parse_initiator_name(iscsi_url->target);
1399 iscsi = iscsi_create_context(initiator_name);
1400 if (iscsi == NULL) {
1401 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1402 ret = -ENOMEM;
1403 goto out;
1406 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1407 error_setg(errp, "iSCSI: Failed to set target name.");
1408 ret = -EINVAL;
1409 goto out;
1412 if (iscsi_url->user[0] != '\0') {
1413 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1414 iscsi_url->passwd);
1415 if (ret != 0) {
1416 error_setg(errp, "Failed to set initiator username and password");
1417 ret = -EINVAL;
1418 goto out;
1422 /* check if we got CHAP username/password via the options */
1423 parse_chap(iscsi, iscsi_url->target, &local_err);
1424 if (local_err != NULL) {
1425 error_propagate(errp, local_err);
1426 ret = -EINVAL;
1427 goto out;
1430 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1431 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1432 ret = -EINVAL;
1433 goto out;
1436 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1438 /* check if we got HEADER_DIGEST via the options */
1439 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1440 if (local_err != NULL) {
1441 error_propagate(errp, local_err);
1442 ret = -EINVAL;
1443 goto out;
1446 /* timeout handling is broken in libiscsi before 1.15.0 */
1447 timeout = parse_timeout(iscsi_url->target);
1448 #if defined(LIBISCSI_API_VERSION) && LIBISCSI_API_VERSION >= 20150621
1449 iscsi_set_timeout(iscsi, timeout);
1450 #else
1451 if (timeout) {
1452 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1454 #endif
1456 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1457 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1458 iscsi_get_error(iscsi));
1459 ret = -EINVAL;
1460 goto out;
1463 iscsilun->iscsi = iscsi;
1464 iscsilun->aio_context = bdrv_get_aio_context(bs);
1465 iscsilun->lun = iscsi_url->lun;
1466 iscsilun->has_write_same = true;
1468 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1469 (void **) &inq, errp);
1470 if (task == NULL) {
1471 ret = -EINVAL;
1472 goto out;
1474 iscsilun->type = inq->periperal_device_type;
1475 scsi_free_scsi_task(task);
1476 task = NULL;
1478 iscsi_modesense_sync(iscsilun);
1480 /* Check the write protect flag of the LUN if we want to write */
1481 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1482 iscsilun->write_protected) {
1483 error_setg(errp, "Cannot open a write protected LUN as read-write");
1484 ret = -EACCES;
1485 goto out;
1488 iscsi_readcapacity_sync(iscsilun, &local_err);
1489 if (local_err != NULL) {
1490 error_propagate(errp, local_err);
1491 ret = -EINVAL;
1492 goto out;
1494 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1495 bs->request_alignment = iscsilun->block_size;
1497 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1498 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1499 * will try to read from the device to guess the image format.
1501 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1502 bs->sg = 1;
1505 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1506 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1507 (void **) &inq_vpd, errp);
1508 if (task == NULL) {
1509 ret = -EINVAL;
1510 goto out;
1512 for (i = 0; i < inq_vpd->num_pages; i++) {
1513 struct scsi_task *inq_task;
1514 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1515 struct scsi_inquiry_block_limits *inq_bl;
1516 switch (inq_vpd->pages[i]) {
1517 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1518 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1519 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1520 (void **) &inq_lbp, errp);
1521 if (inq_task == NULL) {
1522 ret = -EINVAL;
1523 goto out;
1525 memcpy(&iscsilun->lbp, inq_lbp,
1526 sizeof(struct scsi_inquiry_logical_block_provisioning));
1527 scsi_free_scsi_task(inq_task);
1528 break;
1529 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1530 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1531 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1532 (void **) &inq_bl, errp);
1533 if (inq_task == NULL) {
1534 ret = -EINVAL;
1535 goto out;
1537 memcpy(&iscsilun->bl, inq_bl,
1538 sizeof(struct scsi_inquiry_block_limits));
1539 scsi_free_scsi_task(inq_task);
1540 break;
1541 default:
1542 break;
1545 scsi_free_scsi_task(task);
1546 task = NULL;
1548 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1550 /* Guess the internal cluster (page) size of the iscsi target by the means
1551 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1552 * reasonable size */
1553 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1554 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1555 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1556 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1557 if (iscsilun->lbprz) {
1558 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1559 if (iscsilun->allocationmap == NULL) {
1560 ret = -ENOMEM;
1565 out:
1566 qemu_opts_del(opts);
1567 g_free(initiator_name);
1568 if (iscsi_url != NULL) {
1569 iscsi_destroy_url(iscsi_url);
1571 if (task != NULL) {
1572 scsi_free_scsi_task(task);
1575 if (ret) {
1576 if (iscsi != NULL) {
1577 if (iscsi_is_logged_in(iscsi)) {
1578 iscsi_logout_sync(iscsi);
1580 iscsi_destroy_context(iscsi);
1582 memset(iscsilun, 0, sizeof(IscsiLun));
1584 return ret;
1587 static void iscsi_close(BlockDriverState *bs)
1589 IscsiLun *iscsilun = bs->opaque;
1590 struct iscsi_context *iscsi = iscsilun->iscsi;
1592 iscsi_detach_aio_context(bs);
1593 if (iscsi_is_logged_in(iscsi)) {
1594 iscsi_logout_sync(iscsi);
1596 iscsi_destroy_context(iscsi);
1597 g_free(iscsilun->zeroblock);
1598 g_free(iscsilun->allocationmap);
1599 memset(iscsilun, 0, sizeof(IscsiLun));
1602 static int sector_limits_lun2qemu(int64_t sector, IscsiLun *iscsilun)
1604 return MIN(sector_lun2qemu(sector, iscsilun), INT_MAX / 2 + 1);
1607 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1609 /* We don't actually refresh here, but just return data queried in
1610 * iscsi_open(): iscsi targets don't change their limits. */
1612 IscsiLun *iscsilun = bs->opaque;
1613 uint32_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1615 if (iscsilun->bl.max_xfer_len) {
1616 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1619 bs->bl.max_transfer_length = sector_limits_lun2qemu(max_xfer_len, iscsilun);
1621 if (iscsilun->lbp.lbpu) {
1622 if (iscsilun->bl.max_unmap < 0xffffffff) {
1623 bs->bl.max_discard =
1624 sector_limits_lun2qemu(iscsilun->bl.max_unmap, iscsilun);
1626 bs->bl.discard_alignment =
1627 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1630 if (iscsilun->bl.max_ws_len < 0xffffffff) {
1631 bs->bl.max_write_zeroes =
1632 sector_limits_lun2qemu(iscsilun->bl.max_ws_len, iscsilun);
1634 if (iscsilun->lbp.lbpws) {
1635 bs->bl.write_zeroes_alignment =
1636 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1638 bs->bl.opt_transfer_length =
1639 sector_limits_lun2qemu(iscsilun->bl.opt_xfer_len, iscsilun);
1642 /* Note that this will not re-establish a connection with an iSCSI target - it
1643 * is effectively a NOP. */
1644 static int iscsi_reopen_prepare(BDRVReopenState *state,
1645 BlockReopenQueue *queue, Error **errp)
1647 IscsiLun *iscsilun = state->bs->opaque;
1649 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1650 error_setg(errp, "Cannot open a write protected LUN as read-write");
1651 return -EACCES;
1653 return 0;
1656 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1658 IscsiLun *iscsilun = bs->opaque;
1659 Error *local_err = NULL;
1661 if (iscsilun->type != TYPE_DISK) {
1662 return -ENOTSUP;
1665 iscsi_readcapacity_sync(iscsilun, &local_err);
1666 if (local_err != NULL) {
1667 error_free(local_err);
1668 return -EIO;
1671 if (offset > iscsi_getlength(bs)) {
1672 return -EINVAL;
1675 if (iscsilun->allocationmap != NULL) {
1676 g_free(iscsilun->allocationmap);
1677 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1680 return 0;
1683 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1685 int ret = 0;
1686 int64_t total_size = 0;
1687 BlockDriverState *bs;
1688 IscsiLun *iscsilun = NULL;
1689 QDict *bs_options;
1691 bs = bdrv_new();
1693 /* Read out options */
1694 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1695 BDRV_SECTOR_SIZE);
1696 bs->opaque = g_new0(struct IscsiLun, 1);
1697 iscsilun = bs->opaque;
1699 bs_options = qdict_new();
1700 qdict_put(bs_options, "filename", qstring_from_str(filename));
1701 ret = iscsi_open(bs, bs_options, 0, NULL);
1702 QDECREF(bs_options);
1704 if (ret != 0) {
1705 goto out;
1707 iscsi_detach_aio_context(bs);
1708 if (iscsilun->type != TYPE_DISK) {
1709 ret = -ENODEV;
1710 goto out;
1712 if (bs->total_sectors < total_size) {
1713 ret = -ENOSPC;
1714 goto out;
1717 ret = 0;
1718 out:
1719 if (iscsilun->iscsi != NULL) {
1720 iscsi_destroy_context(iscsilun->iscsi);
1722 g_free(bs->opaque);
1723 bs->opaque = NULL;
1724 bdrv_unref(bs);
1725 return ret;
1728 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1730 IscsiLun *iscsilun = bs->opaque;
1731 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
1732 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1733 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1734 return 0;
1737 static QemuOptsList iscsi_create_opts = {
1738 .name = "iscsi-create-opts",
1739 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1740 .desc = {
1742 .name = BLOCK_OPT_SIZE,
1743 .type = QEMU_OPT_SIZE,
1744 .help = "Virtual disk size"
1746 { /* end of list */ }
1750 static BlockDriver bdrv_iscsi = {
1751 .format_name = "iscsi",
1752 .protocol_name = "iscsi",
1754 .instance_size = sizeof(IscsiLun),
1755 .bdrv_needs_filename = true,
1756 .bdrv_file_open = iscsi_open,
1757 .bdrv_close = iscsi_close,
1758 .bdrv_create = iscsi_create,
1759 .create_opts = &iscsi_create_opts,
1760 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1762 .bdrv_getlength = iscsi_getlength,
1763 .bdrv_get_info = iscsi_get_info,
1764 .bdrv_truncate = iscsi_truncate,
1765 .bdrv_refresh_limits = iscsi_refresh_limits,
1767 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1768 .bdrv_co_discard = iscsi_co_discard,
1769 .bdrv_co_write_zeroes = iscsi_co_write_zeroes,
1770 .bdrv_co_readv = iscsi_co_readv,
1771 .bdrv_co_writev = iscsi_co_writev,
1772 .bdrv_co_flush_to_disk = iscsi_co_flush,
1774 #ifdef __linux__
1775 .bdrv_ioctl = iscsi_ioctl,
1776 .bdrv_aio_ioctl = iscsi_aio_ioctl,
1777 #endif
1779 .bdrv_detach_aio_context = iscsi_detach_aio_context,
1780 .bdrv_attach_aio_context = iscsi_attach_aio_context,
1783 static QemuOptsList qemu_iscsi_opts = {
1784 .name = "iscsi",
1785 .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1786 .desc = {
1788 .name = "user",
1789 .type = QEMU_OPT_STRING,
1790 .help = "username for CHAP authentication to target",
1792 .name = "password",
1793 .type = QEMU_OPT_STRING,
1794 .help = "password for CHAP authentication to target",
1796 .name = "header-digest",
1797 .type = QEMU_OPT_STRING,
1798 .help = "HeaderDigest setting. "
1799 "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1801 .name = "initiator-name",
1802 .type = QEMU_OPT_STRING,
1803 .help = "Initiator iqn name to use when connecting",
1805 .name = "timeout",
1806 .type = QEMU_OPT_NUMBER,
1807 .help = "Request timeout in seconds (default 0 = no timeout)",
1809 { /* end of list */ }
1813 static void iscsi_block_init(void)
1815 bdrv_register(&bdrv_iscsi);
1816 qemu_add_opts(&qemu_iscsi_opts);
1819 block_init(iscsi_block_init);