block: Fix dirty bitmap in bdrv_co_discard
[qemu/ar7.git] / block / iscsi.c
bloba6b8fe295b749152ce8dd3222a75cd6468a44b3c
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 static void
173 iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
174 void *command_data, void *opaque)
176 struct IscsiTask *iTask = opaque;
177 struct scsi_task *task = command_data;
179 iTask->status = status;
180 iTask->do_retry = 0;
181 iTask->task = task;
183 if (status != SCSI_STATUS_GOOD) {
184 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
185 if (status == SCSI_STATUS_CHECK_CONDITION
186 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
187 error_report("iSCSI CheckCondition: %s",
188 iscsi_get_error(iscsi));
189 iTask->do_retry = 1;
190 goto out;
192 if (status == SCSI_STATUS_BUSY || status == SCSI_STATUS_TIMEOUT ||
193 status == SCSI_STATUS_TASK_SET_FULL) {
194 unsigned retry_time =
195 exp_random(iscsi_retry_times[iTask->retries - 1]);
196 if (status == SCSI_STATUS_TIMEOUT) {
197 /* make sure the request is rescheduled AFTER the
198 * reconnect is initiated */
199 retry_time = EVENT_INTERVAL * 2;
200 iTask->iscsilun->request_timed_out = true;
202 error_report("iSCSI Busy/TaskSetFull/TimeOut"
203 " (retry #%u in %u ms): %s",
204 iTask->retries, retry_time,
205 iscsi_get_error(iscsi));
206 aio_timer_init(iTask->iscsilun->aio_context,
207 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
208 SCALE_MS, iscsi_retry_timer_expired, iTask);
209 timer_mod(&iTask->retry_timer,
210 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
211 iTask->do_retry = 1;
212 return;
215 error_report("iSCSI Failure: %s", iscsi_get_error(iscsi));
216 } else {
217 iTask->iscsilun->force_next_flush |= iTask->force_next_flush;
220 out:
221 if (iTask->co) {
222 iTask->bh = aio_bh_new(iTask->iscsilun->aio_context,
223 iscsi_co_generic_bh_cb, iTask);
224 qemu_bh_schedule(iTask->bh);
225 } else {
226 iTask->complete = 1;
230 static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
232 *iTask = (struct IscsiTask) {
233 .co = qemu_coroutine_self(),
234 .iscsilun = iscsilun,
238 static void
239 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
240 void *private_data)
242 IscsiAIOCB *acb = private_data;
244 acb->status = -ECANCELED;
245 iscsi_schedule_bh(acb);
248 static void
249 iscsi_aio_cancel(BlockAIOCB *blockacb)
251 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
252 IscsiLun *iscsilun = acb->iscsilun;
254 if (acb->status != -EINPROGRESS) {
255 return;
258 /* send a task mgmt call to the target to cancel the task on the target */
259 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
260 iscsi_abort_task_cb, acb);
264 static const AIOCBInfo iscsi_aiocb_info = {
265 .aiocb_size = sizeof(IscsiAIOCB),
266 .cancel_async = iscsi_aio_cancel,
270 static void iscsi_process_read(void *arg);
271 static void iscsi_process_write(void *arg);
273 static void
274 iscsi_set_events(IscsiLun *iscsilun)
276 struct iscsi_context *iscsi = iscsilun->iscsi;
277 int ev = iscsi_which_events(iscsi);
279 if (ev != iscsilun->events) {
280 aio_set_fd_handler(iscsilun->aio_context,
281 iscsi_get_fd(iscsi),
282 (ev & POLLIN) ? iscsi_process_read : NULL,
283 (ev & POLLOUT) ? iscsi_process_write : NULL,
284 iscsilun);
285 iscsilun->events = ev;
289 static void iscsi_timed_check_events(void *opaque)
291 IscsiLun *iscsilun = opaque;
293 /* check for timed out requests */
294 iscsi_service(iscsilun->iscsi, 0);
296 if (iscsilun->request_timed_out) {
297 iscsilun->request_timed_out = false;
298 iscsi_reconnect(iscsilun->iscsi);
301 /* newer versions of libiscsi may return zero events. Ensure we are able
302 * to return to service once this situation changes. */
303 iscsi_set_events(iscsilun);
305 timer_mod(iscsilun->event_timer,
306 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
309 static void
310 iscsi_process_read(void *arg)
312 IscsiLun *iscsilun = arg;
313 struct iscsi_context *iscsi = iscsilun->iscsi;
315 iscsi_service(iscsi, POLLIN);
316 iscsi_set_events(iscsilun);
319 static void
320 iscsi_process_write(void *arg)
322 IscsiLun *iscsilun = arg;
323 struct iscsi_context *iscsi = iscsilun->iscsi;
325 iscsi_service(iscsi, POLLOUT);
326 iscsi_set_events(iscsilun);
329 static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
331 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
334 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
336 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
339 static bool is_request_lun_aligned(int64_t sector_num, int nb_sectors,
340 IscsiLun *iscsilun)
342 if ((sector_num * BDRV_SECTOR_SIZE) % iscsilun->block_size ||
343 (nb_sectors * BDRV_SECTOR_SIZE) % iscsilun->block_size) {
344 error_report("iSCSI misaligned request: "
345 "iscsilun->block_size %u, sector_num %" PRIi64
346 ", nb_sectors %d",
347 iscsilun->block_size, sector_num, nb_sectors);
348 return 0;
350 return 1;
353 static unsigned long *iscsi_allocationmap_init(IscsiLun *iscsilun)
355 return bitmap_try_new(DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks,
356 iscsilun),
357 iscsilun->cluster_sectors));
360 static void iscsi_allocationmap_set(IscsiLun *iscsilun, int64_t sector_num,
361 int nb_sectors)
363 if (iscsilun->allocationmap == NULL) {
364 return;
366 bitmap_set(iscsilun->allocationmap,
367 sector_num / iscsilun->cluster_sectors,
368 DIV_ROUND_UP(nb_sectors, iscsilun->cluster_sectors));
371 static void iscsi_allocationmap_clear(IscsiLun *iscsilun, int64_t sector_num,
372 int nb_sectors)
374 int64_t cluster_num, nb_clusters;
375 if (iscsilun->allocationmap == NULL) {
376 return;
378 cluster_num = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
379 nb_clusters = (sector_num + nb_sectors) / iscsilun->cluster_sectors
380 - cluster_num;
381 if (nb_clusters > 0) {
382 bitmap_clear(iscsilun->allocationmap, cluster_num, nb_clusters);
386 static int coroutine_fn iscsi_co_writev(BlockDriverState *bs,
387 int64_t sector_num, int nb_sectors,
388 QEMUIOVector *iov)
390 IscsiLun *iscsilun = bs->opaque;
391 struct IscsiTask iTask;
392 uint64_t lba;
393 uint32_t num_sectors;
394 int fua;
396 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
397 return -EINVAL;
400 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
401 error_report("iSCSI Error: Write of %d sectors exceeds max_xfer_len "
402 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
403 return -EINVAL;
406 lba = sector_qemu2lun(sector_num, iscsilun);
407 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
408 iscsi_co_init_iscsitask(iscsilun, &iTask);
409 retry:
410 fua = iscsilun->dpofua && !bs->enable_write_cache;
411 iTask.force_next_flush = !fua;
412 if (iscsilun->use_16_for_rw) {
413 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
414 NULL, num_sectors * iscsilun->block_size,
415 iscsilun->block_size, 0, 0, fua, 0, 0,
416 iscsi_co_generic_cb, &iTask);
417 } else {
418 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
419 NULL, num_sectors * iscsilun->block_size,
420 iscsilun->block_size, 0, 0, fua, 0, 0,
421 iscsi_co_generic_cb, &iTask);
423 if (iTask.task == NULL) {
424 return -ENOMEM;
426 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
427 iov->niov);
428 while (!iTask.complete) {
429 iscsi_set_events(iscsilun);
430 qemu_coroutine_yield();
433 if (iTask.task != NULL) {
434 scsi_free_scsi_task(iTask.task);
435 iTask.task = NULL;
438 if (iTask.do_retry) {
439 iTask.complete = 0;
440 goto retry;
443 if (iTask.status != SCSI_STATUS_GOOD) {
444 return -EIO;
447 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
449 return 0;
453 static bool iscsi_allocationmap_is_allocated(IscsiLun *iscsilun,
454 int64_t sector_num, int nb_sectors)
456 unsigned long size;
457 if (iscsilun->allocationmap == NULL) {
458 return true;
460 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
461 return !(find_next_bit(iscsilun->allocationmap, size,
462 sector_num / iscsilun->cluster_sectors) == size);
465 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
466 int64_t sector_num,
467 int nb_sectors, int *pnum)
469 IscsiLun *iscsilun = bs->opaque;
470 struct scsi_get_lba_status *lbas = NULL;
471 struct scsi_lba_status_descriptor *lbasd = NULL;
472 struct IscsiTask iTask;
473 int64_t ret;
475 iscsi_co_init_iscsitask(iscsilun, &iTask);
477 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
478 ret = -EINVAL;
479 goto out;
482 /* default to all sectors allocated */
483 ret = BDRV_BLOCK_DATA;
484 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
485 *pnum = nb_sectors;
487 /* LUN does not support logical block provisioning */
488 if (!iscsilun->lbpme) {
489 goto out;
492 retry:
493 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
494 sector_qemu2lun(sector_num, iscsilun),
495 8 + 16, iscsi_co_generic_cb,
496 &iTask) == NULL) {
497 ret = -ENOMEM;
498 goto out;
501 while (!iTask.complete) {
502 iscsi_set_events(iscsilun);
503 qemu_coroutine_yield();
506 if (iTask.do_retry) {
507 if (iTask.task != NULL) {
508 scsi_free_scsi_task(iTask.task);
509 iTask.task = NULL;
511 iTask.complete = 0;
512 goto retry;
515 if (iTask.status != SCSI_STATUS_GOOD) {
516 /* in case the get_lba_status_callout fails (i.e.
517 * because the device is busy or the cmd is not
518 * supported) we pretend all blocks are allocated
519 * for backwards compatibility */
520 goto out;
523 lbas = scsi_datain_unmarshall(iTask.task);
524 if (lbas == NULL) {
525 ret = -EIO;
526 goto out;
529 lbasd = &lbas->descriptors[0];
531 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
532 ret = -EIO;
533 goto out;
536 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
538 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
539 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
540 ret &= ~BDRV_BLOCK_DATA;
541 if (iscsilun->lbprz) {
542 ret |= BDRV_BLOCK_ZERO;
546 if (ret & BDRV_BLOCK_ZERO) {
547 iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);
548 } else {
549 iscsi_allocationmap_set(iscsilun, sector_num, *pnum);
552 if (*pnum > nb_sectors) {
553 *pnum = nb_sectors;
555 out:
556 if (iTask.task != NULL) {
557 scsi_free_scsi_task(iTask.task);
559 return ret;
562 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
563 int64_t sector_num, int nb_sectors,
564 QEMUIOVector *iov)
566 IscsiLun *iscsilun = bs->opaque;
567 struct IscsiTask iTask;
568 uint64_t lba;
569 uint32_t num_sectors;
571 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
572 return -EINVAL;
575 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
576 error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "
577 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
578 return -EINVAL;
581 if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
582 !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
583 int64_t ret;
584 int pnum;
585 ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum);
586 if (ret < 0) {
587 return ret;
589 if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
590 qemu_iovec_memset(iov, 0, 0x00, iov->size);
591 return 0;
595 lba = sector_qemu2lun(sector_num, iscsilun);
596 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
598 iscsi_co_init_iscsitask(iscsilun, &iTask);
599 retry:
600 if (iscsilun->use_16_for_rw) {
601 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
602 num_sectors * iscsilun->block_size,
603 iscsilun->block_size, 0, 0, 0, 0, 0,
604 iscsi_co_generic_cb, &iTask);
605 } else {
606 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
607 num_sectors * iscsilun->block_size,
608 iscsilun->block_size,
609 0, 0, 0, 0, 0,
610 iscsi_co_generic_cb, &iTask);
612 if (iTask.task == NULL) {
613 return -ENOMEM;
615 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
617 while (!iTask.complete) {
618 iscsi_set_events(iscsilun);
619 qemu_coroutine_yield();
622 if (iTask.task != NULL) {
623 scsi_free_scsi_task(iTask.task);
624 iTask.task = NULL;
627 if (iTask.do_retry) {
628 iTask.complete = 0;
629 goto retry;
632 if (iTask.status != SCSI_STATUS_GOOD) {
633 return -EIO;
636 return 0;
639 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
641 IscsiLun *iscsilun = bs->opaque;
642 struct IscsiTask iTask;
644 if (!iscsilun->force_next_flush) {
645 return 0;
647 iscsilun->force_next_flush = false;
649 iscsi_co_init_iscsitask(iscsilun, &iTask);
650 retry:
651 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
652 0, iscsi_co_generic_cb, &iTask) == NULL) {
653 return -ENOMEM;
656 while (!iTask.complete) {
657 iscsi_set_events(iscsilun);
658 qemu_coroutine_yield();
661 if (iTask.task != NULL) {
662 scsi_free_scsi_task(iTask.task);
663 iTask.task = NULL;
666 if (iTask.do_retry) {
667 iTask.complete = 0;
668 goto retry;
671 if (iTask.status != SCSI_STATUS_GOOD) {
672 return -EIO;
675 return 0;
678 #ifdef __linux__
679 static void
680 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
681 void *command_data, void *opaque)
683 IscsiAIOCB *acb = opaque;
685 g_free(acb->buf);
686 acb->buf = NULL;
688 acb->status = 0;
689 if (status < 0) {
690 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
691 iscsi_get_error(iscsi));
692 acb->status = -EIO;
695 acb->ioh->driver_status = 0;
696 acb->ioh->host_status = 0;
697 acb->ioh->resid = 0;
699 #define SG_ERR_DRIVER_SENSE 0x08
701 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
702 int ss;
704 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
706 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
707 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
708 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
709 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
712 iscsi_schedule_bh(acb);
715 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
716 unsigned long int req, void *buf,
717 BlockCompletionFunc *cb, void *opaque)
719 IscsiLun *iscsilun = bs->opaque;
720 struct iscsi_context *iscsi = iscsilun->iscsi;
721 struct iscsi_data data;
722 IscsiAIOCB *acb;
724 assert(req == SG_IO);
726 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
728 acb->iscsilun = iscsilun;
729 acb->bh = NULL;
730 acb->status = -EINPROGRESS;
731 acb->buf = NULL;
732 acb->ioh = buf;
734 acb->task = malloc(sizeof(struct scsi_task));
735 if (acb->task == NULL) {
736 error_report("iSCSI: Failed to allocate task for scsi command. %s",
737 iscsi_get_error(iscsi));
738 qemu_aio_unref(acb);
739 return NULL;
741 memset(acb->task, 0, sizeof(struct scsi_task));
743 switch (acb->ioh->dxfer_direction) {
744 case SG_DXFER_TO_DEV:
745 acb->task->xfer_dir = SCSI_XFER_WRITE;
746 break;
747 case SG_DXFER_FROM_DEV:
748 acb->task->xfer_dir = SCSI_XFER_READ;
749 break;
750 default:
751 acb->task->xfer_dir = SCSI_XFER_NONE;
752 break;
755 acb->task->cdb_size = acb->ioh->cmd_len;
756 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
757 acb->task->expxferlen = acb->ioh->dxfer_len;
759 data.size = 0;
760 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
761 if (acb->ioh->iovec_count == 0) {
762 data.data = acb->ioh->dxferp;
763 data.size = acb->ioh->dxfer_len;
764 } else {
765 scsi_task_set_iov_out(acb->task,
766 (struct scsi_iovec *) acb->ioh->dxferp,
767 acb->ioh->iovec_count);
771 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
772 iscsi_aio_ioctl_cb,
773 (data.size > 0) ? &data : NULL,
774 acb) != 0) {
775 scsi_free_scsi_task(acb->task);
776 qemu_aio_unref(acb);
777 return NULL;
780 /* tell libiscsi to read straight into the buffer we got from ioctl */
781 if (acb->task->xfer_dir == SCSI_XFER_READ) {
782 if (acb->ioh->iovec_count == 0) {
783 scsi_task_add_data_in_buffer(acb->task,
784 acb->ioh->dxfer_len,
785 acb->ioh->dxferp);
786 } else {
787 scsi_task_set_iov_in(acb->task,
788 (struct scsi_iovec *) acb->ioh->dxferp,
789 acb->ioh->iovec_count);
793 iscsi_set_events(iscsilun);
795 return &acb->common;
798 static void ioctl_cb(void *opaque, int status)
800 int *p_status = opaque;
801 *p_status = status;
804 static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
806 IscsiLun *iscsilun = bs->opaque;
807 int status;
809 switch (req) {
810 case SG_GET_VERSION_NUM:
811 *(int *)buf = 30000;
812 break;
813 case SG_GET_SCSI_ID:
814 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
815 break;
816 case SG_IO:
817 status = -EINPROGRESS;
818 iscsi_aio_ioctl(bs, req, buf, ioctl_cb, &status);
820 while (status == -EINPROGRESS) {
821 aio_poll(iscsilun->aio_context, true);
824 return 0;
825 default:
826 return -1;
828 return 0;
830 #endif
832 static int64_t
833 iscsi_getlength(BlockDriverState *bs)
835 IscsiLun *iscsilun = bs->opaque;
836 int64_t len;
838 len = iscsilun->num_blocks;
839 len *= iscsilun->block_size;
841 return len;
844 static int
845 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
846 int nb_sectors)
848 IscsiLun *iscsilun = bs->opaque;
849 struct IscsiTask iTask;
850 struct unmap_list list;
852 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
853 return -EINVAL;
856 if (!iscsilun->lbp.lbpu) {
857 /* UNMAP is not supported by the target */
858 return 0;
861 list.lba = sector_qemu2lun(sector_num, iscsilun);
862 list.num = sector_qemu2lun(nb_sectors, iscsilun);
864 iscsi_co_init_iscsitask(iscsilun, &iTask);
865 retry:
866 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
867 iscsi_co_generic_cb, &iTask) == NULL) {
868 return -ENOMEM;
871 while (!iTask.complete) {
872 iscsi_set_events(iscsilun);
873 qemu_coroutine_yield();
876 if (iTask.task != NULL) {
877 scsi_free_scsi_task(iTask.task);
878 iTask.task = NULL;
881 if (iTask.do_retry) {
882 iTask.complete = 0;
883 goto retry;
886 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
887 /* the target might fail with a check condition if it
888 is not happy with the alignment of the UNMAP request
889 we silently fail in this case */
890 return 0;
893 if (iTask.status != SCSI_STATUS_GOOD) {
894 return -EIO;
897 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
899 return 0;
902 static int
903 coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
904 int nb_sectors, BdrvRequestFlags flags)
906 IscsiLun *iscsilun = bs->opaque;
907 struct IscsiTask iTask;
908 uint64_t lba;
909 uint32_t nb_blocks;
910 bool use_16_for_ws = iscsilun->use_16_for_rw;
912 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
913 return -EINVAL;
916 if (flags & BDRV_REQ_MAY_UNMAP) {
917 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
918 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
919 use_16_for_ws = true;
921 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
922 /* WRITESAME16 with UNMAP is not supported by the target,
923 * fall back and try WRITESAME10/16 without UNMAP */
924 flags &= ~BDRV_REQ_MAY_UNMAP;
925 use_16_for_ws = iscsilun->use_16_for_rw;
929 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
930 /* WRITESAME without UNMAP is not supported by the target */
931 return -ENOTSUP;
934 lba = sector_qemu2lun(sector_num, iscsilun);
935 nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
937 if (iscsilun->zeroblock == NULL) {
938 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
939 if (iscsilun->zeroblock == NULL) {
940 return -ENOMEM;
944 iscsi_co_init_iscsitask(iscsilun, &iTask);
945 iTask.force_next_flush = true;
946 retry:
947 if (use_16_for_ws) {
948 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
949 iscsilun->zeroblock, iscsilun->block_size,
950 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
951 0, 0, iscsi_co_generic_cb, &iTask);
952 } else {
953 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
954 iscsilun->zeroblock, iscsilun->block_size,
955 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
956 0, 0, iscsi_co_generic_cb, &iTask);
958 if (iTask.task == NULL) {
959 return -ENOMEM;
962 while (!iTask.complete) {
963 iscsi_set_events(iscsilun);
964 qemu_coroutine_yield();
967 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
968 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
969 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
970 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
971 /* WRITE SAME is not supported by the target */
972 iscsilun->has_write_same = false;
973 scsi_free_scsi_task(iTask.task);
974 return -ENOTSUP;
977 if (iTask.task != NULL) {
978 scsi_free_scsi_task(iTask.task);
979 iTask.task = NULL;
982 if (iTask.do_retry) {
983 iTask.complete = 0;
984 goto retry;
987 if (iTask.status != SCSI_STATUS_GOOD) {
988 return -EIO;
991 if (flags & BDRV_REQ_MAY_UNMAP) {
992 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
993 } else {
994 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
997 return 0;
1000 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1001 Error **errp)
1003 QemuOptsList *list;
1004 QemuOpts *opts;
1005 const char *user = NULL;
1006 const char *password = NULL;
1008 list = qemu_find_opts("iscsi");
1009 if (!list) {
1010 return;
1013 opts = qemu_opts_find(list, target);
1014 if (opts == NULL) {
1015 opts = QTAILQ_FIRST(&list->head);
1016 if (!opts) {
1017 return;
1021 user = qemu_opt_get(opts, "user");
1022 if (!user) {
1023 return;
1026 password = qemu_opt_get(opts, "password");
1027 if (!password) {
1028 error_setg(errp, "CHAP username specified but no password was given");
1029 return;
1032 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1033 error_setg(errp, "Failed to set initiator username and password");
1037 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1038 Error **errp)
1040 QemuOptsList *list;
1041 QemuOpts *opts;
1042 const char *digest = NULL;
1044 list = qemu_find_opts("iscsi");
1045 if (!list) {
1046 return;
1049 opts = qemu_opts_find(list, target);
1050 if (opts == NULL) {
1051 opts = QTAILQ_FIRST(&list->head);
1052 if (!opts) {
1053 return;
1057 digest = qemu_opt_get(opts, "header-digest");
1058 if (!digest) {
1059 return;
1062 if (!strcmp(digest, "CRC32C")) {
1063 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1064 } else if (!strcmp(digest, "NONE")) {
1065 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1066 } else if (!strcmp(digest, "CRC32C-NONE")) {
1067 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1068 } else if (!strcmp(digest, "NONE-CRC32C")) {
1069 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1070 } else {
1071 error_setg(errp, "Invalid header-digest setting : %s", digest);
1075 static char *parse_initiator_name(const char *target)
1077 QemuOptsList *list;
1078 QemuOpts *opts;
1079 const char *name;
1080 char *iscsi_name;
1081 UuidInfo *uuid_info;
1083 list = qemu_find_opts("iscsi");
1084 if (list) {
1085 opts = qemu_opts_find(list, target);
1086 if (!opts) {
1087 opts = QTAILQ_FIRST(&list->head);
1089 if (opts) {
1090 name = qemu_opt_get(opts, "initiator-name");
1091 if (name) {
1092 return g_strdup(name);
1097 uuid_info = qmp_query_uuid(NULL);
1098 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1099 name = qemu_get_vm_name();
1100 } else {
1101 name = uuid_info->UUID;
1103 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1104 name ? ":" : "", name ? name : "");
1105 qapi_free_UuidInfo(uuid_info);
1106 return iscsi_name;
1109 static int parse_timeout(const char *target)
1111 QemuOptsList *list;
1112 QemuOpts *opts;
1113 const char *timeout;
1115 list = qemu_find_opts("iscsi");
1116 if (list) {
1117 opts = qemu_opts_find(list, target);
1118 if (!opts) {
1119 opts = QTAILQ_FIRST(&list->head);
1121 if (opts) {
1122 timeout = qemu_opt_get(opts, "timeout");
1123 if (timeout) {
1124 return atoi(timeout);
1129 return 0;
1132 static void iscsi_nop_timed_event(void *opaque)
1134 IscsiLun *iscsilun = opaque;
1136 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1137 error_report("iSCSI: NOP timeout. Reconnecting...");
1138 iscsilun->request_timed_out = true;
1139 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1140 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1141 return;
1144 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1145 iscsi_set_events(iscsilun);
1148 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1150 struct scsi_task *task = NULL;
1151 struct scsi_readcapacity10 *rc10 = NULL;
1152 struct scsi_readcapacity16 *rc16 = NULL;
1153 int retries = ISCSI_CMD_RETRIES;
1155 do {
1156 if (task != NULL) {
1157 scsi_free_scsi_task(task);
1158 task = NULL;
1161 switch (iscsilun->type) {
1162 case TYPE_DISK:
1163 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1164 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1165 rc16 = scsi_datain_unmarshall(task);
1166 if (rc16 == NULL) {
1167 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1168 } else {
1169 iscsilun->block_size = rc16->block_length;
1170 iscsilun->num_blocks = rc16->returned_lba + 1;
1171 iscsilun->lbpme = !!rc16->lbpme;
1172 iscsilun->lbprz = !!rc16->lbprz;
1173 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1176 break;
1177 case TYPE_ROM:
1178 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1179 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1180 rc10 = scsi_datain_unmarshall(task);
1181 if (rc10 == NULL) {
1182 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1183 } else {
1184 iscsilun->block_size = rc10->block_size;
1185 if (rc10->lba == 0) {
1186 /* blank disk loaded */
1187 iscsilun->num_blocks = 0;
1188 } else {
1189 iscsilun->num_blocks = rc10->lba + 1;
1193 break;
1194 default:
1195 return;
1197 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1198 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1199 && retries-- > 0);
1201 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1202 error_setg(errp, "iSCSI: failed to send readcapacity10 command.");
1204 if (task) {
1205 scsi_free_scsi_task(task);
1209 /* TODO Convert to fine grained options */
1210 static QemuOptsList runtime_opts = {
1211 .name = "iscsi",
1212 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1213 .desc = {
1215 .name = "filename",
1216 .type = QEMU_OPT_STRING,
1217 .help = "URL to the iscsi image",
1219 { /* end of list */ }
1223 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1224 int evpd, int pc, void **inq, Error **errp)
1226 int full_size;
1227 struct scsi_task *task = NULL;
1228 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1229 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1230 goto fail;
1232 full_size = scsi_datain_getfullsize(task);
1233 if (full_size > task->datain.size) {
1234 scsi_free_scsi_task(task);
1236 /* we need more data for the full list */
1237 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1238 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1239 goto fail;
1243 *inq = scsi_datain_unmarshall(task);
1244 if (*inq == NULL) {
1245 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1246 goto fail_with_err;
1249 return task;
1251 fail:
1252 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1253 iscsi_get_error(iscsi));
1254 fail_with_err:
1255 if (task != NULL) {
1256 scsi_free_scsi_task(task);
1258 return NULL;
1261 static void iscsi_detach_aio_context(BlockDriverState *bs)
1263 IscsiLun *iscsilun = bs->opaque;
1265 aio_set_fd_handler(iscsilun->aio_context,
1266 iscsi_get_fd(iscsilun->iscsi),
1267 NULL, NULL, NULL);
1268 iscsilun->events = 0;
1270 if (iscsilun->nop_timer) {
1271 timer_del(iscsilun->nop_timer);
1272 timer_free(iscsilun->nop_timer);
1273 iscsilun->nop_timer = NULL;
1275 if (iscsilun->event_timer) {
1276 timer_del(iscsilun->event_timer);
1277 timer_free(iscsilun->event_timer);
1278 iscsilun->event_timer = NULL;
1282 static void iscsi_attach_aio_context(BlockDriverState *bs,
1283 AioContext *new_context)
1285 IscsiLun *iscsilun = bs->opaque;
1287 iscsilun->aio_context = new_context;
1288 iscsi_set_events(iscsilun);
1290 /* Set up a timer for sending out iSCSI NOPs */
1291 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1292 QEMU_CLOCK_REALTIME, SCALE_MS,
1293 iscsi_nop_timed_event, iscsilun);
1294 timer_mod(iscsilun->nop_timer,
1295 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1297 /* Set up a timer for periodic calls to iscsi_set_events and to
1298 * scan for command timeout */
1299 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1300 QEMU_CLOCK_REALTIME, SCALE_MS,
1301 iscsi_timed_check_events, iscsilun);
1302 timer_mod(iscsilun->event_timer,
1303 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1306 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1308 struct scsi_task *task;
1309 struct scsi_mode_sense *ms = NULL;
1310 iscsilun->write_protected = false;
1311 iscsilun->dpofua = false;
1313 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1314 1, SCSI_MODESENSE_PC_CURRENT,
1315 0x3F, 0, 255);
1316 if (task == NULL) {
1317 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1318 iscsi_get_error(iscsilun->iscsi));
1319 goto out;
1322 if (task->status != SCSI_STATUS_GOOD) {
1323 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1324 goto out;
1326 ms = scsi_datain_unmarshall(task);
1327 if (!ms) {
1328 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1329 iscsi_get_error(iscsilun->iscsi));
1330 goto out;
1332 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1333 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1335 out:
1336 if (task) {
1337 scsi_free_scsi_task(task);
1342 * We support iscsi url's on the form
1343 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1345 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1346 Error **errp)
1348 IscsiLun *iscsilun = bs->opaque;
1349 struct iscsi_context *iscsi = NULL;
1350 struct iscsi_url *iscsi_url = NULL;
1351 struct scsi_task *task = NULL;
1352 struct scsi_inquiry_standard *inq = NULL;
1353 struct scsi_inquiry_supported_pages *inq_vpd;
1354 char *initiator_name = NULL;
1355 QemuOpts *opts;
1356 Error *local_err = NULL;
1357 const char *filename;
1358 int i, ret = 0;
1360 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1361 qemu_opts_absorb_qdict(opts, options, &local_err);
1362 if (local_err) {
1363 error_propagate(errp, local_err);
1364 ret = -EINVAL;
1365 goto out;
1368 filename = qemu_opt_get(opts, "filename");
1370 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1371 if (iscsi_url == NULL) {
1372 error_setg(errp, "Failed to parse URL : %s", filename);
1373 ret = -EINVAL;
1374 goto out;
1377 memset(iscsilun, 0, sizeof(IscsiLun));
1379 initiator_name = parse_initiator_name(iscsi_url->target);
1381 iscsi = iscsi_create_context(initiator_name);
1382 if (iscsi == NULL) {
1383 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1384 ret = -ENOMEM;
1385 goto out;
1388 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1389 error_setg(errp, "iSCSI: Failed to set target name.");
1390 ret = -EINVAL;
1391 goto out;
1394 if (iscsi_url->user[0] != '\0') {
1395 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1396 iscsi_url->passwd);
1397 if (ret != 0) {
1398 error_setg(errp, "Failed to set initiator username and password");
1399 ret = -EINVAL;
1400 goto out;
1404 /* check if we got CHAP username/password via the options */
1405 parse_chap(iscsi, iscsi_url->target, &local_err);
1406 if (local_err != NULL) {
1407 error_propagate(errp, local_err);
1408 ret = -EINVAL;
1409 goto out;
1412 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1413 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1414 ret = -EINVAL;
1415 goto out;
1418 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1420 /* check if we got HEADER_DIGEST via the options */
1421 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1422 if (local_err != NULL) {
1423 error_propagate(errp, local_err);
1424 ret = -EINVAL;
1425 goto out;
1428 iscsi_set_timeout(iscsi, parse_timeout(iscsi_url->target));
1430 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1431 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1432 iscsi_get_error(iscsi));
1433 ret = -EINVAL;
1434 goto out;
1437 iscsilun->iscsi = iscsi;
1438 iscsilun->aio_context = bdrv_get_aio_context(bs);
1439 iscsilun->lun = iscsi_url->lun;
1440 iscsilun->has_write_same = true;
1442 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1443 (void **) &inq, errp);
1444 if (task == NULL) {
1445 ret = -EINVAL;
1446 goto out;
1448 iscsilun->type = inq->periperal_device_type;
1449 scsi_free_scsi_task(task);
1450 task = NULL;
1452 iscsi_modesense_sync(iscsilun);
1454 /* Check the write protect flag of the LUN if we want to write */
1455 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1456 iscsilun->write_protected) {
1457 error_setg(errp, "Cannot open a write protected LUN as read-write");
1458 ret = -EACCES;
1459 goto out;
1462 iscsi_readcapacity_sync(iscsilun, &local_err);
1463 if (local_err != NULL) {
1464 error_propagate(errp, local_err);
1465 ret = -EINVAL;
1466 goto out;
1468 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1469 bs->request_alignment = iscsilun->block_size;
1471 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1472 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1473 * will try to read from the device to guess the image format.
1475 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1476 bs->sg = 1;
1479 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1480 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1481 (void **) &inq_vpd, errp);
1482 if (task == NULL) {
1483 ret = -EINVAL;
1484 goto out;
1486 for (i = 0; i < inq_vpd->num_pages; i++) {
1487 struct scsi_task *inq_task;
1488 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1489 struct scsi_inquiry_block_limits *inq_bl;
1490 switch (inq_vpd->pages[i]) {
1491 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1492 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1493 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1494 (void **) &inq_lbp, errp);
1495 if (inq_task == NULL) {
1496 ret = -EINVAL;
1497 goto out;
1499 memcpy(&iscsilun->lbp, inq_lbp,
1500 sizeof(struct scsi_inquiry_logical_block_provisioning));
1501 scsi_free_scsi_task(inq_task);
1502 break;
1503 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1504 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1505 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1506 (void **) &inq_bl, errp);
1507 if (inq_task == NULL) {
1508 ret = -EINVAL;
1509 goto out;
1511 memcpy(&iscsilun->bl, inq_bl,
1512 sizeof(struct scsi_inquiry_block_limits));
1513 scsi_free_scsi_task(inq_task);
1514 break;
1515 default:
1516 break;
1519 scsi_free_scsi_task(task);
1520 task = NULL;
1522 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1524 /* Guess the internal cluster (page) size of the iscsi target by the means
1525 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1526 * reasonable size */
1527 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1528 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1529 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1530 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1531 if (iscsilun->lbprz) {
1532 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1533 if (iscsilun->allocationmap == NULL) {
1534 ret = -ENOMEM;
1539 out:
1540 qemu_opts_del(opts);
1541 g_free(initiator_name);
1542 if (iscsi_url != NULL) {
1543 iscsi_destroy_url(iscsi_url);
1545 if (task != NULL) {
1546 scsi_free_scsi_task(task);
1549 if (ret) {
1550 if (iscsi != NULL) {
1551 if (iscsi_is_logged_in(iscsi)) {
1552 iscsi_logout_sync(iscsi);
1554 iscsi_destroy_context(iscsi);
1556 memset(iscsilun, 0, sizeof(IscsiLun));
1558 return ret;
1561 static void iscsi_close(BlockDriverState *bs)
1563 IscsiLun *iscsilun = bs->opaque;
1564 struct iscsi_context *iscsi = iscsilun->iscsi;
1566 iscsi_detach_aio_context(bs);
1567 if (iscsi_is_logged_in(iscsi)) {
1568 iscsi_logout_sync(iscsi);
1570 iscsi_destroy_context(iscsi);
1571 g_free(iscsilun->zeroblock);
1572 g_free(iscsilun->allocationmap);
1573 memset(iscsilun, 0, sizeof(IscsiLun));
1576 static int sector_limits_lun2qemu(int64_t sector, IscsiLun *iscsilun)
1578 return MIN(sector_lun2qemu(sector, iscsilun), INT_MAX / 2 + 1);
1581 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1583 /* We don't actually refresh here, but just return data queried in
1584 * iscsi_open(): iscsi targets don't change their limits. */
1586 IscsiLun *iscsilun = bs->opaque;
1587 uint32_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1589 if (iscsilun->bl.max_xfer_len) {
1590 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1593 bs->bl.max_transfer_length = sector_limits_lun2qemu(max_xfer_len, iscsilun);
1595 if (iscsilun->lbp.lbpu) {
1596 if (iscsilun->bl.max_unmap < 0xffffffff) {
1597 bs->bl.max_discard =
1598 sector_limits_lun2qemu(iscsilun->bl.max_unmap, iscsilun);
1600 bs->bl.discard_alignment =
1601 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1604 if (iscsilun->bl.max_ws_len < 0xffffffff) {
1605 bs->bl.max_write_zeroes =
1606 sector_limits_lun2qemu(iscsilun->bl.max_ws_len, iscsilun);
1608 if (iscsilun->lbp.lbpws) {
1609 bs->bl.write_zeroes_alignment =
1610 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1612 bs->bl.opt_transfer_length =
1613 sector_limits_lun2qemu(iscsilun->bl.opt_xfer_len, iscsilun);
1616 /* Note that this will not re-establish a connection with an iSCSI target - it
1617 * is effectively a NOP. */
1618 static int iscsi_reopen_prepare(BDRVReopenState *state,
1619 BlockReopenQueue *queue, Error **errp)
1621 IscsiLun *iscsilun = state->bs->opaque;
1623 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1624 error_setg(errp, "Cannot open a write protected LUN as read-write");
1625 return -EACCES;
1627 return 0;
1630 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1632 IscsiLun *iscsilun = bs->opaque;
1633 Error *local_err = NULL;
1635 if (iscsilun->type != TYPE_DISK) {
1636 return -ENOTSUP;
1639 iscsi_readcapacity_sync(iscsilun, &local_err);
1640 if (local_err != NULL) {
1641 error_free(local_err);
1642 return -EIO;
1645 if (offset > iscsi_getlength(bs)) {
1646 return -EINVAL;
1649 if (iscsilun->allocationmap != NULL) {
1650 g_free(iscsilun->allocationmap);
1651 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1654 return 0;
1657 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1659 int ret = 0;
1660 int64_t total_size = 0;
1661 BlockDriverState *bs;
1662 IscsiLun *iscsilun = NULL;
1663 QDict *bs_options;
1665 bs = bdrv_new();
1667 /* Read out options */
1668 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1669 BDRV_SECTOR_SIZE);
1670 bs->opaque = g_new0(struct IscsiLun, 1);
1671 iscsilun = bs->opaque;
1673 bs_options = qdict_new();
1674 qdict_put(bs_options, "filename", qstring_from_str(filename));
1675 ret = iscsi_open(bs, bs_options, 0, NULL);
1676 QDECREF(bs_options);
1678 if (ret != 0) {
1679 goto out;
1681 iscsi_detach_aio_context(bs);
1682 if (iscsilun->type != TYPE_DISK) {
1683 ret = -ENODEV;
1684 goto out;
1686 if (bs->total_sectors < total_size) {
1687 ret = -ENOSPC;
1688 goto out;
1691 ret = 0;
1692 out:
1693 if (iscsilun->iscsi != NULL) {
1694 iscsi_destroy_context(iscsilun->iscsi);
1696 g_free(bs->opaque);
1697 bs->opaque = NULL;
1698 bdrv_unref(bs);
1699 return ret;
1702 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1704 IscsiLun *iscsilun = bs->opaque;
1705 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
1706 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1707 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1708 return 0;
1711 static QemuOptsList iscsi_create_opts = {
1712 .name = "iscsi-create-opts",
1713 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1714 .desc = {
1716 .name = BLOCK_OPT_SIZE,
1717 .type = QEMU_OPT_SIZE,
1718 .help = "Virtual disk size"
1720 { /* end of list */ }
1724 static BlockDriver bdrv_iscsi = {
1725 .format_name = "iscsi",
1726 .protocol_name = "iscsi",
1728 .instance_size = sizeof(IscsiLun),
1729 .bdrv_needs_filename = true,
1730 .bdrv_file_open = iscsi_open,
1731 .bdrv_close = iscsi_close,
1732 .bdrv_create = iscsi_create,
1733 .create_opts = &iscsi_create_opts,
1734 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1736 .bdrv_getlength = iscsi_getlength,
1737 .bdrv_get_info = iscsi_get_info,
1738 .bdrv_truncate = iscsi_truncate,
1739 .bdrv_refresh_limits = iscsi_refresh_limits,
1741 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1742 .bdrv_co_discard = iscsi_co_discard,
1743 .bdrv_co_write_zeroes = iscsi_co_write_zeroes,
1744 .bdrv_co_readv = iscsi_co_readv,
1745 .bdrv_co_writev = iscsi_co_writev,
1746 .bdrv_co_flush_to_disk = iscsi_co_flush,
1748 #ifdef __linux__
1749 .bdrv_ioctl = iscsi_ioctl,
1750 .bdrv_aio_ioctl = iscsi_aio_ioctl,
1751 #endif
1753 .bdrv_detach_aio_context = iscsi_detach_aio_context,
1754 .bdrv_attach_aio_context = iscsi_attach_aio_context,
1757 static QemuOptsList qemu_iscsi_opts = {
1758 .name = "iscsi",
1759 .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1760 .desc = {
1762 .name = "user",
1763 .type = QEMU_OPT_STRING,
1764 .help = "username for CHAP authentication to target",
1766 .name = "password",
1767 .type = QEMU_OPT_STRING,
1768 .help = "password for CHAP authentication to target",
1770 .name = "header-digest",
1771 .type = QEMU_OPT_STRING,
1772 .help = "HeaderDigest setting. "
1773 "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1775 .name = "initiator-name",
1776 .type = QEMU_OPT_STRING,
1777 .help = "Initiator iqn name to use when connecting",
1779 .name = "timeout",
1780 .type = QEMU_OPT_NUMBER,
1781 .help = "Request timeout in seconds (default 0 = no timeout)",
1783 { /* end of list */ }
1787 static void iscsi_block_init(void)
1789 bdrv_register(&bdrv_iscsi);
1790 qemu_add_opts(&qemu_iscsi_opts);
1793 block_init(iscsi_block_init);