Rename mis->file to from_src_file
[qemu/ar7.git] / block / iscsi.c
blob080ef523452400b451633b1bf1ba9b76349bdc64
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 int err_code;
88 } IscsiTask;
90 typedef struct IscsiAIOCB {
91 BlockAIOCB common;
92 QEMUIOVector *qiov;
93 QEMUBH *bh;
94 IscsiLun *iscsilun;
95 struct scsi_task *task;
96 uint8_t *buf;
97 int status;
98 int64_t sector_num;
99 int nb_sectors;
100 #ifdef __linux__
101 sg_io_hdr_t *ioh;
102 #endif
103 } IscsiAIOCB;
105 /* libiscsi uses time_t so its enough to process events every second */
106 #define EVENT_INTERVAL 1000
107 #define NOP_INTERVAL 5000
108 #define MAX_NOP_FAILURES 3
109 #define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
110 static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
112 /* this threshold is a trade-off knob to choose between
113 * the potential additional overhead of an extra GET_LBA_STATUS request
114 * vs. unnecessarily reading a lot of zero sectors over the wire.
115 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
116 * sectors we check the allocation status of the area covered by the
117 * request first if the allocationmap indicates that the area might be
118 * unallocated. */
119 #define ISCSI_CHECKALLOC_THRES 64
121 static void
122 iscsi_bh_cb(void *p)
124 IscsiAIOCB *acb = p;
126 qemu_bh_delete(acb->bh);
128 g_free(acb->buf);
129 acb->buf = NULL;
131 acb->common.cb(acb->common.opaque, acb->status);
133 if (acb->task != NULL) {
134 scsi_free_scsi_task(acb->task);
135 acb->task = NULL;
138 qemu_aio_unref(acb);
141 static void
142 iscsi_schedule_bh(IscsiAIOCB *acb)
144 if (acb->bh) {
145 return;
147 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
148 qemu_bh_schedule(acb->bh);
151 static void iscsi_co_generic_bh_cb(void *opaque)
153 struct IscsiTask *iTask = opaque;
154 iTask->complete = 1;
155 qemu_bh_delete(iTask->bh);
156 qemu_coroutine_enter(iTask->co, NULL);
159 static void iscsi_retry_timer_expired(void *opaque)
161 struct IscsiTask *iTask = opaque;
162 iTask->complete = 1;
163 if (iTask->co) {
164 qemu_coroutine_enter(iTask->co, NULL);
168 static inline unsigned exp_random(double mean)
170 return -mean * log((double)rand() / RAND_MAX);
173 /* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
174 * libiscsi 1.10.0, together with other constants we need. Use it as
175 * a hint that we have to define them ourselves if needed, to keep the
176 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
177 * the test because SCSI_STATUS_* is an enum.
179 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
180 * an enum, check against the LIBISCSI_API_VERSION macro, which was
181 * introduced in 1.11.0. If it is present, there is no need to define
182 * anything.
184 #if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
185 !defined(LIBISCSI_API_VERSION)
186 #define SCSI_STATUS_TASK_SET_FULL 0x28
187 #define SCSI_STATUS_TIMEOUT 0x0f000002
188 #define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
189 #define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
190 #endif
192 static int iscsi_translate_sense(struct scsi_sense *sense)
194 int ret;
196 switch (sense->key) {
197 case SCSI_SENSE_NOT_READY:
198 return -EBUSY;
199 case SCSI_SENSE_DATA_PROTECTION:
200 return -EACCES;
201 case SCSI_SENSE_COMMAND_ABORTED:
202 return -ECANCELED;
203 case SCSI_SENSE_ILLEGAL_REQUEST:
204 /* Parse ASCQ */
205 break;
206 default:
207 return -EIO;
209 switch (sense->ascq) {
210 case SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR:
211 case SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE:
212 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB:
213 case SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST:
214 ret = -EINVAL;
215 break;
216 case SCSI_SENSE_ASCQ_LBA_OUT_OF_RANGE:
217 ret = -ENOSPC;
218 break;
219 case SCSI_SENSE_ASCQ_LOGICAL_UNIT_NOT_SUPPORTED:
220 ret = -ENOTSUP;
221 break;
222 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT:
223 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_CLOSED:
224 case SCSI_SENSE_ASCQ_MEDIUM_NOT_PRESENT_TRAY_OPEN:
225 ret = -ENOMEDIUM;
226 break;
227 case SCSI_SENSE_ASCQ_WRITE_PROTECTED:
228 ret = -EACCES;
229 break;
230 default:
231 ret = -EIO;
232 break;
234 return ret;
237 static void
238 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
239 void *command_data, void *opaque)
241 struct IscsiTask *iTask = opaque;
242 struct scsi_task *task = command_data;
244 iTask->status = status;
245 iTask->do_retry = 0;
246 iTask->task = task;
248 if (status != SCSI_STATUS_GOOD) {
249 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
250 if (status == SCSI_STATUS_CHECK_CONDITION
251 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
252 error_report("iSCSI CheckCondition: %s",
253 iscsi_get_error(iscsi));
254 iTask->do_retry = 1;
255 goto out;
257 if (status == SCSI_STATUS_BUSY ||
258 status == SCSI_STATUS_TIMEOUT ||
259 status == SCSI_STATUS_TASK_SET_FULL) {
260 unsigned retry_time =
261 exp_random(iscsi_retry_times[iTask->retries - 1]);
262 if (status == SCSI_STATUS_TIMEOUT) {
263 /* make sure the request is rescheduled AFTER the
264 * reconnect is initiated */
265 retry_time = EVENT_INTERVAL * 2;
266 iTask->iscsilun->request_timed_out = true;
268 error_report("iSCSI Busy/TaskSetFull/TimeOut"
269 " (retry #%u in %u ms): %s",
270 iTask->retries, retry_time,
271 iscsi_get_error(iscsi));
272 aio_timer_init(iTask->iscsilun->aio_context,
273 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
274 SCALE_MS, iscsi_retry_timer_expired, iTask);
275 timer_mod(&iTask->retry_timer,
276 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
277 iTask->do_retry = 1;
278 return;
281 iTask->err_code = iscsi_translate_sense(&task->sense);
282 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
283 } else {
284 iTask->iscsilun->force_next_flush |= iTask->force_next_flush;
287 out:
288 if (iTask->co) {
289 iTask->bh = aio_bh_new(iTask->iscsilun->aio_context,
290 iscsi_co_generic_bh_cb, iTask);
291 qemu_bh_schedule(iTask->bh);
292 } else {
293 iTask->complete = 1;
297 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
299 *iTask = (struct IscsiTask) {
300 .co = qemu_coroutine_self(),
301 .iscsilun = iscsilun,
305 static void
306 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
307 void *private_data)
309 IscsiAIOCB *acb = private_data;
311 acb->status = -ECANCELED;
312 iscsi_schedule_bh(acb);
315 static void
316 iscsi_aio_cancel(BlockAIOCB *blockacb)
318 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
319 IscsiLun *iscsilun = acb->iscsilun;
321 if (acb->status != -EINPROGRESS) {
322 return;
325 /* send a task mgmt call to the target to cancel the task on the target */
326 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
327 iscsi_abort_task_cb, acb);
331 static const AIOCBInfo iscsi_aiocb_info = {
332 .aiocb_size = sizeof(IscsiAIOCB),
333 .cancel_async = iscsi_aio_cancel,
337 static void iscsi_process_read(void *arg);
338 static void iscsi_process_write(void *arg);
340 static void
341 iscsi_set_events(IscsiLun *iscsilun)
343 struct iscsi_context *iscsi = iscsilun->iscsi;
344 int ev = iscsi_which_events(iscsi);
346 if (ev != iscsilun->events) {
347 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
348 false,
349 (ev & POLLIN) ? iscsi_process_read : NULL,
350 (ev & POLLOUT) ? iscsi_process_write : NULL,
351 iscsilun);
352 iscsilun->events = ev;
356 static void iscsi_timed_check_events(void *opaque)
358 IscsiLun *iscsilun = opaque;
360 /* check for timed out requests */
361 iscsi_service(iscsilun->iscsi, 0);
363 if (iscsilun->request_timed_out) {
364 iscsilun->request_timed_out = false;
365 iscsi_reconnect(iscsilun->iscsi);
368 /* newer versions of libiscsi may return zero events. Ensure we are able
369 * to return to service once this situation changes. */
370 iscsi_set_events(iscsilun);
372 timer_mod(iscsilun->event_timer,
373 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
376 static void
377 iscsi_process_read(void *arg)
379 IscsiLun *iscsilun = arg;
380 struct iscsi_context *iscsi = iscsilun->iscsi;
382 iscsi_service(iscsi, POLLIN);
383 iscsi_set_events(iscsilun);
386 static void
387 iscsi_process_write(void *arg)
389 IscsiLun *iscsilun = arg;
390 struct iscsi_context *iscsi = iscsilun->iscsi;
392 iscsi_service(iscsi, POLLOUT);
393 iscsi_set_events(iscsilun);
396 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
398 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
401 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
403 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
406 static bool is_request_lun_aligned(int64_t sector_num, int nb_sectors,
407 IscsiLun *iscsilun)
409 if ((sector_num * BDRV_SECTOR_SIZE) % iscsilun->block_size ||
410 (nb_sectors * BDRV_SECTOR_SIZE) % iscsilun->block_size) {
411 error_report("iSCSI misaligned request: "
412 "iscsilun->block_size %u, sector_num %" PRIi64
413 ", nb_sectors %d",
414 iscsilun->block_size, sector_num, nb_sectors);
415 return 0;
417 return 1;
420 static unsigned long *iscsi_allocationmap_init(IscsiLun *iscsilun)
422 return bitmap_try_new(DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks,
423 iscsilun),
424 iscsilun->cluster_sectors));
427 static void iscsi_allocationmap_set(IscsiLun *iscsilun, int64_t sector_num,
428 int nb_sectors)
430 if (iscsilun->allocationmap == NULL) {
431 return;
433 bitmap_set(iscsilun->allocationmap,
434 sector_num / iscsilun->cluster_sectors,
435 DIV_ROUND_UP(nb_sectors, iscsilun->cluster_sectors));
438 static void iscsi_allocationmap_clear(IscsiLun *iscsilun, int64_t sector_num,
439 int nb_sectors)
441 int64_t cluster_num, nb_clusters;
442 if (iscsilun->allocationmap == NULL) {
443 return;
445 cluster_num = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
446 nb_clusters = (sector_num + nb_sectors) / iscsilun->cluster_sectors
447 - cluster_num;
448 if (nb_clusters > 0) {
449 bitmap_clear(iscsilun->allocationmap, cluster_num, nb_clusters);
453 static int coroutine_fn iscsi_co_writev(BlockDriverState *bs,
454 int64_t sector_num, int nb_sectors,
455 QEMUIOVector *iov)
457 IscsiLun *iscsilun = bs->opaque;
458 struct IscsiTask iTask;
459 uint64_t lba;
460 uint32_t num_sectors;
461 int fua;
463 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
464 return -EINVAL;
467 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
468 error_report("iSCSI Error: Write of %d sectors exceeds max_xfer_len "
469 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
470 return -EINVAL;
473 lba = sector_qemu2lun(sector_num, iscsilun);
474 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
475 iscsi_co_init_iscsitask(iscsilun, &iTask);
476 retry:
477 fua = iscsilun->dpofua && !bs->enable_write_cache;
478 iTask.force_next_flush = !fua;
479 if (iscsilun->use_16_for_rw) {
480 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
481 NULL, num_sectors * iscsilun->block_size,
482 iscsilun->block_size, 0, 0, fua, 0, 0,
483 iscsi_co_generic_cb, &iTask);
484 } else {
485 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
486 NULL, num_sectors * iscsilun->block_size,
487 iscsilun->block_size, 0, 0, fua, 0, 0,
488 iscsi_co_generic_cb, &iTask);
490 if (iTask.task == NULL) {
491 return -ENOMEM;
493 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
494 iov->niov);
495 while (!iTask.complete) {
496 iscsi_set_events(iscsilun);
497 qemu_coroutine_yield();
500 if (iTask.task != NULL) {
501 scsi_free_scsi_task(iTask.task);
502 iTask.task = NULL;
505 if (iTask.do_retry) {
506 iTask.complete = 0;
507 goto retry;
510 if (iTask.status != SCSI_STATUS_GOOD) {
511 return iTask.err_code;
514 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
516 return 0;
520 static bool iscsi_allocationmap_is_allocated(IscsiLun *iscsilun,
521 int64_t sector_num, int nb_sectors)
523 unsigned long size;
524 if (iscsilun->allocationmap == NULL) {
525 return true;
527 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
528 return !(find_next_bit(iscsilun->allocationmap, size,
529 sector_num / iscsilun->cluster_sectors) == size);
532 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
533 int64_t sector_num,
534 int nb_sectors, int *pnum)
536 IscsiLun *iscsilun = bs->opaque;
537 struct scsi_get_lba_status *lbas = NULL;
538 struct scsi_lba_status_descriptor *lbasd = NULL;
539 struct IscsiTask iTask;
540 int64_t ret;
542 iscsi_co_init_iscsitask(iscsilun, &iTask);
544 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
545 ret = -EINVAL;
546 goto out;
549 /* default to all sectors allocated */
550 ret = BDRV_BLOCK_DATA;
551 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
552 *pnum = nb_sectors;
554 /* LUN does not support logical block provisioning */
555 if (!iscsilun->lbpme) {
556 goto out;
559 retry:
560 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
561 sector_qemu2lun(sector_num, iscsilun),
562 8 + 16, iscsi_co_generic_cb,
563 &iTask) == NULL) {
564 ret = -ENOMEM;
565 goto out;
568 while (!iTask.complete) {
569 iscsi_set_events(iscsilun);
570 qemu_coroutine_yield();
573 if (iTask.do_retry) {
574 if (iTask.task != NULL) {
575 scsi_free_scsi_task(iTask.task);
576 iTask.task = NULL;
578 iTask.complete = 0;
579 goto retry;
582 if (iTask.status != SCSI_STATUS_GOOD) {
583 /* in case the get_lba_status_callout fails (i.e.
584 * because the device is busy or the cmd is not
585 * supported) we pretend all blocks are allocated
586 * for backwards compatibility */
587 goto out;
590 lbas = scsi_datain_unmarshall(iTask.task);
591 if (lbas == NULL) {
592 ret = -EIO;
593 goto out;
596 lbasd = &lbas->descriptors[0];
598 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
599 ret = -EIO;
600 goto out;
603 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
605 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
606 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
607 ret &= ~BDRV_BLOCK_DATA;
608 if (iscsilun->lbprz) {
609 ret |= BDRV_BLOCK_ZERO;
613 if (ret & BDRV_BLOCK_ZERO) {
614 iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);
615 } else {
616 iscsi_allocationmap_set(iscsilun, sector_num, *pnum);
619 if (*pnum > nb_sectors) {
620 *pnum = nb_sectors;
622 out:
623 if (iTask.task != NULL) {
624 scsi_free_scsi_task(iTask.task);
626 return ret;
629 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
630 int64_t sector_num, int nb_sectors,
631 QEMUIOVector *iov)
633 IscsiLun *iscsilun = bs->opaque;
634 struct IscsiTask iTask;
635 uint64_t lba;
636 uint32_t num_sectors;
638 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
639 return -EINVAL;
642 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
643 error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "
644 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
645 return -EINVAL;
648 if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
649 !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
650 int64_t ret;
651 int pnum;
652 ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum);
653 if (ret < 0) {
654 return ret;
656 if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
657 qemu_iovec_memset(iov, 0, 0x00, iov->size);
658 return 0;
662 lba = sector_qemu2lun(sector_num, iscsilun);
663 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
665 iscsi_co_init_iscsitask(iscsilun, &iTask);
666 retry:
667 if (iscsilun->use_16_for_rw) {
668 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
669 num_sectors * iscsilun->block_size,
670 iscsilun->block_size, 0, 0, 0, 0, 0,
671 iscsi_co_generic_cb, &iTask);
672 } else {
673 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
674 num_sectors * iscsilun->block_size,
675 iscsilun->block_size,
676 0, 0, 0, 0, 0,
677 iscsi_co_generic_cb, &iTask);
679 if (iTask.task == NULL) {
680 return -ENOMEM;
682 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
684 while (!iTask.complete) {
685 iscsi_set_events(iscsilun);
686 qemu_coroutine_yield();
689 if (iTask.task != NULL) {
690 scsi_free_scsi_task(iTask.task);
691 iTask.task = NULL;
694 if (iTask.do_retry) {
695 iTask.complete = 0;
696 goto retry;
699 if (iTask.status != SCSI_STATUS_GOOD) {
700 return iTask.err_code;
703 return 0;
706 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
708 IscsiLun *iscsilun = bs->opaque;
709 struct IscsiTask iTask;
711 if (!iscsilun->force_next_flush) {
712 return 0;
714 iscsilun->force_next_flush = false;
716 iscsi_co_init_iscsitask(iscsilun, &iTask);
717 retry:
718 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
719 0, iscsi_co_generic_cb, &iTask) == NULL) {
720 return -ENOMEM;
723 while (!iTask.complete) {
724 iscsi_set_events(iscsilun);
725 qemu_coroutine_yield();
728 if (iTask.task != NULL) {
729 scsi_free_scsi_task(iTask.task);
730 iTask.task = NULL;
733 if (iTask.do_retry) {
734 iTask.complete = 0;
735 goto retry;
738 if (iTask.status != SCSI_STATUS_GOOD) {
739 return iTask.err_code;
742 return 0;
745 #ifdef __linux__
746 static void
747 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
748 void *command_data, void *opaque)
750 IscsiAIOCB *acb = opaque;
752 g_free(acb->buf);
753 acb->buf = NULL;
755 acb->status = 0;
756 if (status < 0) {
757 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
758 iscsi_get_error(iscsi));
759 acb->status = iscsi_translate_sense(&acb->task->sense);
762 acb->ioh->driver_status = 0;
763 acb->ioh->host_status = 0;
764 acb->ioh->resid = 0;
766 #define SG_ERR_DRIVER_SENSE 0x08
768 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
769 int ss;
771 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
773 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
774 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
775 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
776 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
779 iscsi_schedule_bh(acb);
782 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
783 unsigned long int req, void *buf,
784 BlockCompletionFunc *cb, void *opaque)
786 IscsiLun *iscsilun = bs->opaque;
787 struct iscsi_context *iscsi = iscsilun->iscsi;
788 struct iscsi_data data;
789 IscsiAIOCB *acb;
791 assert(req == SG_IO);
793 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
795 acb->iscsilun = iscsilun;
796 acb->bh = NULL;
797 acb->status = -EINPROGRESS;
798 acb->buf = NULL;
799 acb->ioh = buf;
801 acb->task = malloc(sizeof(struct scsi_task));
802 if (acb->task == NULL) {
803 error_report("iSCSI: Failed to allocate task for scsi command. %s",
804 iscsi_get_error(iscsi));
805 qemu_aio_unref(acb);
806 return NULL;
808 memset(acb->task, 0, sizeof(struct scsi_task));
810 switch (acb->ioh->dxfer_direction) {
811 case SG_DXFER_TO_DEV:
812 acb->task->xfer_dir = SCSI_XFER_WRITE;
813 break;
814 case SG_DXFER_FROM_DEV:
815 acb->task->xfer_dir = SCSI_XFER_READ;
816 break;
817 default:
818 acb->task->xfer_dir = SCSI_XFER_NONE;
819 break;
822 acb->task->cdb_size = acb->ioh->cmd_len;
823 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
824 acb->task->expxferlen = acb->ioh->dxfer_len;
826 data.size = 0;
827 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
828 if (acb->ioh->iovec_count == 0) {
829 data.data = acb->ioh->dxferp;
830 data.size = acb->ioh->dxfer_len;
831 } else {
832 scsi_task_set_iov_out(acb->task,
833 (struct scsi_iovec *) acb->ioh->dxferp,
834 acb->ioh->iovec_count);
838 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
839 iscsi_aio_ioctl_cb,
840 (data.size > 0) ? &data : NULL,
841 acb) != 0) {
842 scsi_free_scsi_task(acb->task);
843 qemu_aio_unref(acb);
844 return NULL;
847 /* tell libiscsi to read straight into the buffer we got from ioctl */
848 if (acb->task->xfer_dir == SCSI_XFER_READ) {
849 if (acb->ioh->iovec_count == 0) {
850 scsi_task_add_data_in_buffer(acb->task,
851 acb->ioh->dxfer_len,
852 acb->ioh->dxferp);
853 } else {
854 scsi_task_set_iov_in(acb->task,
855 (struct scsi_iovec *) acb->ioh->dxferp,
856 acb->ioh->iovec_count);
860 iscsi_set_events(iscsilun);
862 return &acb->common;
865 static void ioctl_cb(void *opaque, int status)
867 int *p_status = opaque;
868 *p_status = status;
871 static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
873 IscsiLun *iscsilun = bs->opaque;
874 int status;
876 switch (req) {
877 case SG_GET_VERSION_NUM:
878 *(int *)buf = 30000;
879 break;
880 case SG_GET_SCSI_ID:
881 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
882 break;
883 case SG_IO:
884 status = -EINPROGRESS;
885 iscsi_aio_ioctl(bs, req, buf, ioctl_cb, &status);
887 while (status == -EINPROGRESS) {
888 aio_poll(iscsilun->aio_context, true);
891 return 0;
892 default:
893 return -1;
895 return 0;
897 #endif
899 static int64_t
900 iscsi_getlength(BlockDriverState *bs)
902 IscsiLun *iscsilun = bs->opaque;
903 int64_t len;
905 len = iscsilun->num_blocks;
906 len *= iscsilun->block_size;
908 return len;
911 static int
912 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
913 int nb_sectors)
915 IscsiLun *iscsilun = bs->opaque;
916 struct IscsiTask iTask;
917 struct unmap_list list;
919 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
920 return -EINVAL;
923 if (!iscsilun->lbp.lbpu) {
924 /* UNMAP is not supported by the target */
925 return 0;
928 list.lba = sector_qemu2lun(sector_num, iscsilun);
929 list.num = sector_qemu2lun(nb_sectors, iscsilun);
931 iscsi_co_init_iscsitask(iscsilun, &iTask);
932 retry:
933 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
934 iscsi_co_generic_cb, &iTask) == NULL) {
935 return -ENOMEM;
938 while (!iTask.complete) {
939 iscsi_set_events(iscsilun);
940 qemu_coroutine_yield();
943 if (iTask.task != NULL) {
944 scsi_free_scsi_task(iTask.task);
945 iTask.task = NULL;
948 if (iTask.do_retry) {
949 iTask.complete = 0;
950 goto retry;
953 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
954 /* the target might fail with a check condition if it
955 is not happy with the alignment of the UNMAP request
956 we silently fail in this case */
957 return 0;
960 if (iTask.status != SCSI_STATUS_GOOD) {
961 return iTask.err_code;
964 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
966 return 0;
969 static int
970 coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
971 int nb_sectors, BdrvRequestFlags flags)
973 IscsiLun *iscsilun = bs->opaque;
974 struct IscsiTask iTask;
975 uint64_t lba;
976 uint32_t nb_blocks;
977 bool use_16_for_ws = iscsilun->use_16_for_rw;
979 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
980 return -EINVAL;
983 if (flags & BDRV_REQ_MAY_UNMAP) {
984 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
985 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
986 use_16_for_ws = true;
988 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
989 /* WRITESAME16 with UNMAP is not supported by the target,
990 * fall back and try WRITESAME10/16 without UNMAP */
991 flags &= ~BDRV_REQ_MAY_UNMAP;
992 use_16_for_ws = iscsilun->use_16_for_rw;
996 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
997 /* WRITESAME without UNMAP is not supported by the target */
998 return -ENOTSUP;
1001 lba = sector_qemu2lun(sector_num, iscsilun);
1002 nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
1004 if (iscsilun->zeroblock == NULL) {
1005 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1006 if (iscsilun->zeroblock == NULL) {
1007 return -ENOMEM;
1011 iscsi_co_init_iscsitask(iscsilun, &iTask);
1012 iTask.force_next_flush = true;
1013 retry:
1014 if (use_16_for_ws) {
1015 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1016 iscsilun->zeroblock, iscsilun->block_size,
1017 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1018 0, 0, iscsi_co_generic_cb, &iTask);
1019 } else {
1020 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1021 iscsilun->zeroblock, iscsilun->block_size,
1022 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1023 0, 0, iscsi_co_generic_cb, &iTask);
1025 if (iTask.task == NULL) {
1026 return -ENOMEM;
1029 while (!iTask.complete) {
1030 iscsi_set_events(iscsilun);
1031 qemu_coroutine_yield();
1034 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1035 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1036 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1037 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1038 /* WRITE SAME is not supported by the target */
1039 iscsilun->has_write_same = false;
1040 scsi_free_scsi_task(iTask.task);
1041 return -ENOTSUP;
1044 if (iTask.task != NULL) {
1045 scsi_free_scsi_task(iTask.task);
1046 iTask.task = NULL;
1049 if (iTask.do_retry) {
1050 iTask.complete = 0;
1051 goto retry;
1054 if (iTask.status != SCSI_STATUS_GOOD) {
1055 return iTask.err_code;
1058 if (flags & BDRV_REQ_MAY_UNMAP) {
1059 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
1060 } else {
1061 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
1064 return 0;
1067 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1068 Error **errp)
1070 QemuOptsList *list;
1071 QemuOpts *opts;
1072 const char *user = NULL;
1073 const char *password = NULL;
1075 list = qemu_find_opts("iscsi");
1076 if (!list) {
1077 return;
1080 opts = qemu_opts_find(list, target);
1081 if (opts == NULL) {
1082 opts = QTAILQ_FIRST(&list->head);
1083 if (!opts) {
1084 return;
1088 user = qemu_opt_get(opts, "user");
1089 if (!user) {
1090 return;
1093 password = qemu_opt_get(opts, "password");
1094 if (!password) {
1095 error_setg(errp, "CHAP username specified but no password was given");
1096 return;
1099 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1100 error_setg(errp, "Failed to set initiator username and password");
1104 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1105 Error **errp)
1107 QemuOptsList *list;
1108 QemuOpts *opts;
1109 const char *digest = NULL;
1111 list = qemu_find_opts("iscsi");
1112 if (!list) {
1113 return;
1116 opts = qemu_opts_find(list, target);
1117 if (opts == NULL) {
1118 opts = QTAILQ_FIRST(&list->head);
1119 if (!opts) {
1120 return;
1124 digest = qemu_opt_get(opts, "header-digest");
1125 if (!digest) {
1126 return;
1129 if (!strcmp(digest, "CRC32C")) {
1130 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1131 } else if (!strcmp(digest, "NONE")) {
1132 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1133 } else if (!strcmp(digest, "CRC32C-NONE")) {
1134 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1135 } else if (!strcmp(digest, "NONE-CRC32C")) {
1136 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1137 } else {
1138 error_setg(errp, "Invalid header-digest setting : %s", digest);
1142 static char *parse_initiator_name(const char *target)
1144 QemuOptsList *list;
1145 QemuOpts *opts;
1146 const char *name;
1147 char *iscsi_name;
1148 UuidInfo *uuid_info;
1150 list = qemu_find_opts("iscsi");
1151 if (list) {
1152 opts = qemu_opts_find(list, target);
1153 if (!opts) {
1154 opts = QTAILQ_FIRST(&list->head);
1156 if (opts) {
1157 name = qemu_opt_get(opts, "initiator-name");
1158 if (name) {
1159 return g_strdup(name);
1164 uuid_info = qmp_query_uuid(NULL);
1165 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1166 name = qemu_get_vm_name();
1167 } else {
1168 name = uuid_info->UUID;
1170 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1171 name ? ":" : "", name ? name : "");
1172 qapi_free_UuidInfo(uuid_info);
1173 return iscsi_name;
1176 static int parse_timeout(const char *target)
1178 QemuOptsList *list;
1179 QemuOpts *opts;
1180 const char *timeout;
1182 list = qemu_find_opts("iscsi");
1183 if (list) {
1184 opts = qemu_opts_find(list, target);
1185 if (!opts) {
1186 opts = QTAILQ_FIRST(&list->head);
1188 if (opts) {
1189 timeout = qemu_opt_get(opts, "timeout");
1190 if (timeout) {
1191 return atoi(timeout);
1196 return 0;
1199 static void iscsi_nop_timed_event(void *opaque)
1201 IscsiLun *iscsilun = opaque;
1203 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1204 error_report("iSCSI: NOP timeout. Reconnecting...");
1205 iscsilun->request_timed_out = true;
1206 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1207 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1208 return;
1211 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1212 iscsi_set_events(iscsilun);
1215 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1217 struct scsi_task *task = NULL;
1218 struct scsi_readcapacity10 *rc10 = NULL;
1219 struct scsi_readcapacity16 *rc16 = NULL;
1220 int retries = ISCSI_CMD_RETRIES;
1222 do {
1223 if (task != NULL) {
1224 scsi_free_scsi_task(task);
1225 task = NULL;
1228 switch (iscsilun->type) {
1229 case TYPE_DISK:
1230 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1231 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1232 rc16 = scsi_datain_unmarshall(task);
1233 if (rc16 == NULL) {
1234 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1235 } else {
1236 iscsilun->block_size = rc16->block_length;
1237 iscsilun->num_blocks = rc16->returned_lba + 1;
1238 iscsilun->lbpme = !!rc16->lbpme;
1239 iscsilun->lbprz = !!rc16->lbprz;
1240 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1243 break;
1244 case TYPE_ROM:
1245 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1246 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1247 rc10 = scsi_datain_unmarshall(task);
1248 if (rc10 == NULL) {
1249 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1250 } else {
1251 iscsilun->block_size = rc10->block_size;
1252 if (rc10->lba == 0) {
1253 /* blank disk loaded */
1254 iscsilun->num_blocks = 0;
1255 } else {
1256 iscsilun->num_blocks = rc10->lba + 1;
1260 break;
1261 default:
1262 return;
1264 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1265 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1266 && retries-- > 0);
1268 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1269 error_setg(errp, "iSCSI: failed to send readcapacity10 command.");
1270 } else if (!iscsilun->block_size ||
1271 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1272 error_setg(errp, "iSCSI: the target returned an invalid "
1273 "block size of %d.", iscsilun->block_size);
1275 if (task) {
1276 scsi_free_scsi_task(task);
1280 /* TODO Convert to fine grained options */
1281 static QemuOptsList runtime_opts = {
1282 .name = "iscsi",
1283 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1284 .desc = {
1286 .name = "filename",
1287 .type = QEMU_OPT_STRING,
1288 .help = "URL to the iscsi image",
1290 { /* end of list */ }
1294 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1295 int evpd, int pc, void **inq, Error **errp)
1297 int full_size;
1298 struct scsi_task *task = NULL;
1299 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1300 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1301 goto fail;
1303 full_size = scsi_datain_getfullsize(task);
1304 if (full_size > task->datain.size) {
1305 scsi_free_scsi_task(task);
1307 /* we need more data for the full list */
1308 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1309 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1310 goto fail;
1314 *inq = scsi_datain_unmarshall(task);
1315 if (*inq == NULL) {
1316 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1317 goto fail_with_err;
1320 return task;
1322 fail:
1323 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1324 iscsi_get_error(iscsi));
1325 fail_with_err:
1326 if (task != NULL) {
1327 scsi_free_scsi_task(task);
1329 return NULL;
1332 static void iscsi_detach_aio_context(BlockDriverState *bs)
1334 IscsiLun *iscsilun = bs->opaque;
1336 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1337 false, NULL, NULL, NULL);
1338 iscsilun->events = 0;
1340 if (iscsilun->nop_timer) {
1341 timer_del(iscsilun->nop_timer);
1342 timer_free(iscsilun->nop_timer);
1343 iscsilun->nop_timer = NULL;
1345 if (iscsilun->event_timer) {
1346 timer_del(iscsilun->event_timer);
1347 timer_free(iscsilun->event_timer);
1348 iscsilun->event_timer = NULL;
1352 static void iscsi_attach_aio_context(BlockDriverState *bs,
1353 AioContext *new_context)
1355 IscsiLun *iscsilun = bs->opaque;
1357 iscsilun->aio_context = new_context;
1358 iscsi_set_events(iscsilun);
1360 /* Set up a timer for sending out iSCSI NOPs */
1361 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1362 QEMU_CLOCK_REALTIME, SCALE_MS,
1363 iscsi_nop_timed_event, iscsilun);
1364 timer_mod(iscsilun->nop_timer,
1365 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1367 /* Set up a timer for periodic calls to iscsi_set_events and to
1368 * scan for command timeout */
1369 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1370 QEMU_CLOCK_REALTIME, SCALE_MS,
1371 iscsi_timed_check_events, iscsilun);
1372 timer_mod(iscsilun->event_timer,
1373 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1376 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1378 struct scsi_task *task;
1379 struct scsi_mode_sense *ms = NULL;
1380 iscsilun->write_protected = false;
1381 iscsilun->dpofua = false;
1383 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1384 1, SCSI_MODESENSE_PC_CURRENT,
1385 0x3F, 0, 255);
1386 if (task == NULL) {
1387 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1388 iscsi_get_error(iscsilun->iscsi));
1389 goto out;
1392 if (task->status != SCSI_STATUS_GOOD) {
1393 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1394 goto out;
1396 ms = scsi_datain_unmarshall(task);
1397 if (!ms) {
1398 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1399 iscsi_get_error(iscsilun->iscsi));
1400 goto out;
1402 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1403 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1405 out:
1406 if (task) {
1407 scsi_free_scsi_task(task);
1412 * We support iscsi url's on the form
1413 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1415 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1416 Error **errp)
1418 IscsiLun *iscsilun = bs->opaque;
1419 struct iscsi_context *iscsi = NULL;
1420 struct iscsi_url *iscsi_url = NULL;
1421 struct scsi_task *task = NULL;
1422 struct scsi_inquiry_standard *inq = NULL;
1423 struct scsi_inquiry_supported_pages *inq_vpd;
1424 char *initiator_name = NULL;
1425 QemuOpts *opts;
1426 Error *local_err = NULL;
1427 const char *filename;
1428 int i, ret = 0, timeout = 0;
1430 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1431 qemu_opts_absorb_qdict(opts, options, &local_err);
1432 if (local_err) {
1433 error_propagate(errp, local_err);
1434 ret = -EINVAL;
1435 goto out;
1438 filename = qemu_opt_get(opts, "filename");
1440 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1441 if (iscsi_url == NULL) {
1442 error_setg(errp, "Failed to parse URL : %s", filename);
1443 ret = -EINVAL;
1444 goto out;
1447 memset(iscsilun, 0, sizeof(IscsiLun));
1449 initiator_name = parse_initiator_name(iscsi_url->target);
1451 iscsi = iscsi_create_context(initiator_name);
1452 if (iscsi == NULL) {
1453 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1454 ret = -ENOMEM;
1455 goto out;
1458 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1459 error_setg(errp, "iSCSI: Failed to set target name.");
1460 ret = -EINVAL;
1461 goto out;
1464 if (iscsi_url->user[0] != '\0') {
1465 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1466 iscsi_url->passwd);
1467 if (ret != 0) {
1468 error_setg(errp, "Failed to set initiator username and password");
1469 ret = -EINVAL;
1470 goto out;
1474 /* check if we got CHAP username/password via the options */
1475 parse_chap(iscsi, iscsi_url->target, &local_err);
1476 if (local_err != NULL) {
1477 error_propagate(errp, local_err);
1478 ret = -EINVAL;
1479 goto out;
1482 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1483 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1484 ret = -EINVAL;
1485 goto out;
1488 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1490 /* check if we got HEADER_DIGEST via the options */
1491 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1492 if (local_err != NULL) {
1493 error_propagate(errp, local_err);
1494 ret = -EINVAL;
1495 goto out;
1498 /* timeout handling is broken in libiscsi before 1.15.0 */
1499 timeout = parse_timeout(iscsi_url->target);
1500 #if defined(LIBISCSI_API_VERSION) && LIBISCSI_API_VERSION >= 20150621
1501 iscsi_set_timeout(iscsi, timeout);
1502 #else
1503 if (timeout) {
1504 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1506 #endif
1508 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1509 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1510 iscsi_get_error(iscsi));
1511 ret = -EINVAL;
1512 goto out;
1515 iscsilun->iscsi = iscsi;
1516 iscsilun->aio_context = bdrv_get_aio_context(bs);
1517 iscsilun->lun = iscsi_url->lun;
1518 iscsilun->has_write_same = true;
1520 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1521 (void **) &inq, errp);
1522 if (task == NULL) {
1523 ret = -EINVAL;
1524 goto out;
1526 iscsilun->type = inq->periperal_device_type;
1527 scsi_free_scsi_task(task);
1528 task = NULL;
1530 iscsi_modesense_sync(iscsilun);
1532 /* Check the write protect flag of the LUN if we want to write */
1533 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1534 iscsilun->write_protected) {
1535 error_setg(errp, "Cannot open a write protected LUN as read-write");
1536 ret = -EACCES;
1537 goto out;
1540 iscsi_readcapacity_sync(iscsilun, &local_err);
1541 if (local_err != NULL) {
1542 error_propagate(errp, local_err);
1543 ret = -EINVAL;
1544 goto out;
1546 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1547 bs->request_alignment = iscsilun->block_size;
1549 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1550 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1551 * will try to read from the device to guess the image format.
1553 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1554 bs->sg = 1;
1557 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1558 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1559 (void **) &inq_vpd, errp);
1560 if (task == NULL) {
1561 ret = -EINVAL;
1562 goto out;
1564 for (i = 0; i < inq_vpd->num_pages; i++) {
1565 struct scsi_task *inq_task;
1566 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1567 struct scsi_inquiry_block_limits *inq_bl;
1568 switch (inq_vpd->pages[i]) {
1569 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1570 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1571 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1572 (void **) &inq_lbp, errp);
1573 if (inq_task == NULL) {
1574 ret = -EINVAL;
1575 goto out;
1577 memcpy(&iscsilun->lbp, inq_lbp,
1578 sizeof(struct scsi_inquiry_logical_block_provisioning));
1579 scsi_free_scsi_task(inq_task);
1580 break;
1581 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1582 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1583 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1584 (void **) &inq_bl, errp);
1585 if (inq_task == NULL) {
1586 ret = -EINVAL;
1587 goto out;
1589 memcpy(&iscsilun->bl, inq_bl,
1590 sizeof(struct scsi_inquiry_block_limits));
1591 scsi_free_scsi_task(inq_task);
1592 break;
1593 default:
1594 break;
1597 scsi_free_scsi_task(task);
1598 task = NULL;
1600 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1602 /* Guess the internal cluster (page) size of the iscsi target by the means
1603 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1604 * reasonable size */
1605 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1606 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1607 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1608 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1609 if (iscsilun->lbprz) {
1610 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1611 if (iscsilun->allocationmap == NULL) {
1612 ret = -ENOMEM;
1617 out:
1618 qemu_opts_del(opts);
1619 g_free(initiator_name);
1620 if (iscsi_url != NULL) {
1621 iscsi_destroy_url(iscsi_url);
1623 if (task != NULL) {
1624 scsi_free_scsi_task(task);
1627 if (ret) {
1628 if (iscsi != NULL) {
1629 if (iscsi_is_logged_in(iscsi)) {
1630 iscsi_logout_sync(iscsi);
1632 iscsi_destroy_context(iscsi);
1634 memset(iscsilun, 0, sizeof(IscsiLun));
1636 return ret;
1639 static void iscsi_close(BlockDriverState *bs)
1641 IscsiLun *iscsilun = bs->opaque;
1642 struct iscsi_context *iscsi = iscsilun->iscsi;
1644 iscsi_detach_aio_context(bs);
1645 if (iscsi_is_logged_in(iscsi)) {
1646 iscsi_logout_sync(iscsi);
1648 iscsi_destroy_context(iscsi);
1649 g_free(iscsilun->zeroblock);
1650 g_free(iscsilun->allocationmap);
1651 memset(iscsilun, 0, sizeof(IscsiLun));
1654 static int sector_limits_lun2qemu(int64_t sector, IscsiLun *iscsilun)
1656 return MIN(sector_lun2qemu(sector, iscsilun), INT_MAX / 2 + 1);
1659 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1661 /* We don't actually refresh here, but just return data queried in
1662 * iscsi_open(): iscsi targets don't change their limits. */
1664 IscsiLun *iscsilun = bs->opaque;
1665 uint32_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1667 if (iscsilun->bl.max_xfer_len) {
1668 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1671 bs->bl.max_transfer_length = sector_limits_lun2qemu(max_xfer_len, iscsilun);
1673 if (iscsilun->lbp.lbpu) {
1674 if (iscsilun->bl.max_unmap < 0xffffffff) {
1675 bs->bl.max_discard =
1676 sector_limits_lun2qemu(iscsilun->bl.max_unmap, iscsilun);
1678 bs->bl.discard_alignment =
1679 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1682 if (iscsilun->bl.max_ws_len < 0xffffffff) {
1683 bs->bl.max_write_zeroes =
1684 sector_limits_lun2qemu(iscsilun->bl.max_ws_len, iscsilun);
1686 if (iscsilun->lbp.lbpws) {
1687 bs->bl.write_zeroes_alignment =
1688 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1690 bs->bl.opt_transfer_length =
1691 sector_limits_lun2qemu(iscsilun->bl.opt_xfer_len, iscsilun);
1694 /* Note that this will not re-establish a connection with an iSCSI target - it
1695 * is effectively a NOP. */
1696 static int iscsi_reopen_prepare(BDRVReopenState *state,
1697 BlockReopenQueue *queue, Error **errp)
1699 IscsiLun *iscsilun = state->bs->opaque;
1701 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1702 error_setg(errp, "Cannot open a write protected LUN as read-write");
1703 return -EACCES;
1705 return 0;
1708 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1710 IscsiLun *iscsilun = bs->opaque;
1711 Error *local_err = NULL;
1713 if (iscsilun->type != TYPE_DISK) {
1714 return -ENOTSUP;
1717 iscsi_readcapacity_sync(iscsilun, &local_err);
1718 if (local_err != NULL) {
1719 error_free(local_err);
1720 return -EIO;
1723 if (offset > iscsi_getlength(bs)) {
1724 return -EINVAL;
1727 if (iscsilun->allocationmap != NULL) {
1728 g_free(iscsilun->allocationmap);
1729 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1732 return 0;
1735 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1737 int ret = 0;
1738 int64_t total_size = 0;
1739 BlockDriverState *bs;
1740 IscsiLun *iscsilun = NULL;
1741 QDict *bs_options;
1743 bs = bdrv_new();
1745 /* Read out options */
1746 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1747 BDRV_SECTOR_SIZE);
1748 bs->opaque = g_new0(struct IscsiLun, 1);
1749 iscsilun = bs->opaque;
1751 bs_options = qdict_new();
1752 qdict_put(bs_options, "filename", qstring_from_str(filename));
1753 ret = iscsi_open(bs, bs_options, 0, NULL);
1754 QDECREF(bs_options);
1756 if (ret != 0) {
1757 goto out;
1759 iscsi_detach_aio_context(bs);
1760 if (iscsilun->type != TYPE_DISK) {
1761 ret = -ENODEV;
1762 goto out;
1764 if (bs->total_sectors < total_size) {
1765 ret = -ENOSPC;
1766 goto out;
1769 ret = 0;
1770 out:
1771 if (iscsilun->iscsi != NULL) {
1772 iscsi_destroy_context(iscsilun->iscsi);
1774 g_free(bs->opaque);
1775 bs->opaque = NULL;
1776 bdrv_unref(bs);
1777 return ret;
1780 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1782 IscsiLun *iscsilun = bs->opaque;
1783 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
1784 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1785 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1786 return 0;
1789 static QemuOptsList iscsi_create_opts = {
1790 .name = "iscsi-create-opts",
1791 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1792 .desc = {
1794 .name = BLOCK_OPT_SIZE,
1795 .type = QEMU_OPT_SIZE,
1796 .help = "Virtual disk size"
1798 { /* end of list */ }
1802 static BlockDriver bdrv_iscsi = {
1803 .format_name = "iscsi",
1804 .protocol_name = "iscsi",
1806 .instance_size = sizeof(IscsiLun),
1807 .bdrv_needs_filename = true,
1808 .bdrv_file_open = iscsi_open,
1809 .bdrv_close = iscsi_close,
1810 .bdrv_create = iscsi_create,
1811 .create_opts = &iscsi_create_opts,
1812 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1814 .bdrv_getlength = iscsi_getlength,
1815 .bdrv_get_info = iscsi_get_info,
1816 .bdrv_truncate = iscsi_truncate,
1817 .bdrv_refresh_limits = iscsi_refresh_limits,
1819 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1820 .bdrv_co_discard = iscsi_co_discard,
1821 .bdrv_co_write_zeroes = iscsi_co_write_zeroes,
1822 .bdrv_co_readv = iscsi_co_readv,
1823 .bdrv_co_writev = iscsi_co_writev,
1824 .bdrv_co_flush_to_disk = iscsi_co_flush,
1826 #ifdef __linux__
1827 .bdrv_ioctl = iscsi_ioctl,
1828 .bdrv_aio_ioctl = iscsi_aio_ioctl,
1829 #endif
1831 .bdrv_detach_aio_context = iscsi_detach_aio_context,
1832 .bdrv_attach_aio_context = iscsi_attach_aio_context,
1835 static QemuOptsList qemu_iscsi_opts = {
1836 .name = "iscsi",
1837 .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1838 .desc = {
1840 .name = "user",
1841 .type = QEMU_OPT_STRING,
1842 .help = "username for CHAP authentication to target",
1844 .name = "password",
1845 .type = QEMU_OPT_STRING,
1846 .help = "password for CHAP authentication to target",
1848 .name = "header-digest",
1849 .type = QEMU_OPT_STRING,
1850 .help = "HeaderDigest setting. "
1851 "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1853 .name = "initiator-name",
1854 .type = QEMU_OPT_STRING,
1855 .help = "Initiator iqn name to use when connecting",
1857 .name = "timeout",
1858 .type = QEMU_OPT_NUMBER,
1859 .help = "Request timeout in seconds (default 0 = no timeout)",
1861 { /* end of list */ }
1865 static void iscsi_block_init(void)
1867 bdrv_register(&bdrv_iscsi);
1868 qemu_add_opts(&qemu_iscsi_opts);
1871 block_init(iscsi_block_init);