]> git.proxmox.com Git - mirror_qemu.git/blame - block/iscsi.c
qapi: Empty out qapi-schema.json
[mirror_qemu.git] / block / iscsi.c
CommitLineData
c589b249
RS
1/*
2 * QEMU Block driver for iSCSI images
3 *
4 * Copyright (c) 2010-2011 Ronnie Sahlberg <ronniesahlberg@gmail.com>
aef172ff 5 * Copyright (c) 2012-2017 Peter Lieven <pl@kamp.de>
c589b249
RS
6 *
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:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
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.
24 */
25
80c71a24 26#include "qemu/osdep.h"
c589b249
RS
27
28#include <poll.h>
efc6de0d 29#include <math.h>
f4dfa67f 30#include <arpa/inet.h>
1de7afc9
PB
31#include "qemu/config-file.h"
32#include "qemu/error-report.h"
b03c3805
PL
33#include "qemu/bitops.h"
34#include "qemu/bitmap.h"
737e150e 35#include "block/block_int.h"
08e2c9f1 36#include "scsi/constants.h"
0a53f010 37#include "qemu/iov.h"
922a01a0 38#include "qemu/option.h"
cea25275 39#include "qemu/uuid.h"
e688df6b 40#include "qapi/error.h"
112ed241 41#include "qapi/qapi-commands-misc.h"
452fcdbc 42#include "qapi/qmp/qdict.h"
d49b6836 43#include "qapi/qmp/qstring.h"
b189346e 44#include "crypto/secret.h"
e5b5728c 45#include "scsi/utils.h"
c589b249 46
e5b5728c
PB
47/* Conflict between scsi/utils.h and libiscsi! :( */
48#define SCSI_XFER_NONE ISCSI_XFER_NONE
c589b249
RS
49#include <iscsi/iscsi.h>
50#include <iscsi/scsi-lowlevel.h>
e5b5728c
PB
51#undef SCSI_XFER_NONE
52QEMU_BUILD_BUG_ON((int)SCSI_XFER_NONE != (int)ISCSI_XFER_NONE);
c589b249 53
98392453
RS
54#ifdef __linux__
55#include <scsi/sg.h>
98392453 56#endif
c589b249
RS
57
58typedef struct IscsiLun {
59 struct iscsi_context *iscsi;
80cf6257 60 AioContext *aio_context;
c589b249 61 int lun;
dbfff6d7 62 enum scsi_inquiry_peripheral_device_type type;
c589b249 63 int block_size;
c7b4a952 64 uint64_t num_blocks;
c9b9f682 65 int events;
5b5d34ec 66 QEMUTimer *nop_timer;
05b685fb 67 QEMUTimer *event_timer;
d045c466 68 QemuMutex mutex;
f18a7cbb
PL
69 struct scsi_inquiry_logical_block_provisioning lbp;
70 struct scsi_inquiry_block_limits bl;
d4cd9615 71 unsigned char *zeroblock;
e1123a3b
PL
72 /* The allocmap tracks which clusters (pages) on the iSCSI target are
73 * allocated and which are not. In case a target returns zeros for
74 * unallocated pages (iscsilun->lprz) we can directly return zeros instead
75 * of reading zeros over the wire if a read request falls within an
76 * unallocated block. As there are 3 possible states we need 2 bitmaps to
77 * track. allocmap_valid keeps track if QEMU's information about a page is
78 * valid. allocmap tracks if a page is allocated or not. In case QEMU has no
79 * valid information about a page the corresponding allocmap entry should be
80 * switched to unallocated as well to force a new lookup of the allocation
81 * status as lookups are generally skipped if a page is suspect to be
82 * allocated. If a iSCSI target is opened with cache.direct = on the
83 * allocmap_valid does not exist turning all cached information invalid so
84 * that a fresh lookup is made for any page even if allocmap entry returns
85 * it's unallocated. */
86 unsigned long *allocmap;
87 unsigned long *allocmap_valid;
88 long allocmap_size;
b03c3805 89 int cluster_sectors;
9281fe9e 90 bool use_16_for_rw;
43ae8fb1 91 bool write_protected;
0a386e48
PL
92 bool lbpme;
93 bool lbprz;
752ce451 94 bool dpofua;
0a386e48 95 bool has_write_same;
5dd7a535 96 bool request_timed_out;
c589b249
RS
97} IscsiLun;
98
54a5c1d5
PL
99typedef struct IscsiTask {
100 int status;
101 int complete;
102 int retries;
103 int do_retry;
104 struct scsi_task *task;
105 Coroutine *co;
80cf6257 106 IscsiLun *iscsilun;
efc6de0d 107 QEMUTimer retry_timer;
e01dd3da 108 int err_code;
e38bc234 109 char *err_str;
54a5c1d5
PL
110} IscsiTask;
111
c589b249 112typedef struct IscsiAIOCB {
7c84b1b8 113 BlockAIOCB common;
c589b249
RS
114 QEMUBH *bh;
115 IscsiLun *iscsilun;
116 struct scsi_task *task;
117 uint8_t *buf;
118 int status;
1dde716e
PL
119 int64_t sector_num;
120 int nb_sectors;
4bb17ab5 121 int ret;
98392453
RS
122#ifdef __linux__
123 sg_io_hdr_t *ioh;
124#endif
c589b249
RS
125} IscsiAIOCB;
126
5dd7a535
PL
127/* libiscsi uses time_t so its enough to process events every second */
128#define EVENT_INTERVAL 1000
5b5d34ec
PL
129#define NOP_INTERVAL 5000
130#define MAX_NOP_FAILURES 3
efc6de0d 131#define ISCSI_CMD_RETRIES ARRAY_SIZE(iscsi_retry_times)
59dd0a22 132static const unsigned iscsi_retry_times[] = {8, 32, 128, 512, 2048, 8192, 32768};
5b5d34ec 133
5d831be2 134/* this threshold is a trade-off knob to choose between
5917af81
PL
135 * the potential additional overhead of an extra GET_LBA_STATUS request
136 * vs. unnecessarily reading a lot of zero sectors over the wire.
137 * If a read request is greater or equal than ISCSI_CHECKALLOC_THRES
138 * sectors we check the allocation status of the area covered by the
139 * request first if the allocationmap indicates that the area might be
140 * unallocated. */
141#define ISCSI_CHECKALLOC_THRES 64
5b5d34ec 142
27cbd828 143static void
cfb3f506 144iscsi_bh_cb(void *p)
27cbd828
PB
145{
146 IscsiAIOCB *acb = p;
147
148 qemu_bh_delete(acb->bh);
149
4790b03d
PB
150 g_free(acb->buf);
151 acb->buf = NULL;
152
722d9333 153 acb->common.cb(acb->common.opaque, acb->status);
27cbd828 154
1bd075f2
PB
155 if (acb->task != NULL) {
156 scsi_free_scsi_task(acb->task);
157 acb->task = NULL;
158 }
159
8007429a 160 qemu_aio_unref(acb);
27cbd828
PB
161}
162
cfb3f506
PB
163static void
164iscsi_schedule_bh(IscsiAIOCB *acb)
27cbd828 165{
1bd075f2
PB
166 if (acb->bh) {
167 return;
168 }
80cf6257 169 acb->bh = aio_bh_new(acb->iscsilun->aio_context, iscsi_bh_cb, acb);
27cbd828 170 qemu_bh_schedule(acb->bh);
27cbd828
PB
171}
172
8b9dfe90
PL
173static void iscsi_co_generic_bh_cb(void *opaque)
174{
175 struct IscsiTask *iTask = opaque;
1919631e 176
fcd470d8 177 iTask->complete = 1;
1919631e 178 aio_co_wake(iTask->co);
8b9dfe90
PL
179}
180
efc6de0d
PL
181static void iscsi_retry_timer_expired(void *opaque)
182{
183 struct IscsiTask *iTask = opaque;
fcd470d8 184 iTask->complete = 1;
efc6de0d 185 if (iTask->co) {
2f47da5f 186 aio_co_wake(iTask->co);
efc6de0d
PL
187 }
188}
189
190static inline unsigned exp_random(double mean)
191{
192 return -mean * log((double)rand() / RAND_MAX);
193}
194
e01dd3da
FZ
195/* SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST was introduced in
196 * libiscsi 1.10.0, together with other constants we need. Use it as
197 * a hint that we have to define them ourselves if needed, to keep the
198 * minimum required libiscsi version at 1.9.0. We use an ASCQ macro for
199 * the test because SCSI_STATUS_* is an enum.
200 *
201 * To guard against future changes where SCSI_SENSE_ASCQ_* also becomes
202 * an enum, check against the LIBISCSI_API_VERSION macro, which was
203 * introduced in 1.11.0. If it is present, there is no need to define
204 * anything.
205 */
206#if !defined(SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST) && \
207 !defined(LIBISCSI_API_VERSION)
208#define SCSI_STATUS_TASK_SET_FULL 0x28
209#define SCSI_STATUS_TIMEOUT 0x0f000002
210#define SCSI_SENSE_ASCQ_INVALID_FIELD_IN_PARAMETER_LIST 0x2600
211#define SCSI_SENSE_ASCQ_PARAMETER_LIST_LENGTH_ERROR 0x1a00
9049736e
PL
212#endif
213
583ec22e
RS
214#ifndef LIBISCSI_API_VERSION
215#define LIBISCSI_API_VERSION 20130701
216#endif
217
e01dd3da
FZ
218static int iscsi_translate_sense(struct scsi_sense *sense)
219{
28751358
FZ
220 return - scsi_sense_to_errno(sense->key,
221 (sense->ascq & 0xFF00) >> 8,
222 sense->ascq & 0xFF);
e01dd3da
FZ
223}
224
d045c466 225/* Called (via iscsi_service) with QemuMutex held. */
54a5c1d5
PL
226static void
227iscsi_co_generic_cb(struct iscsi_context *iscsi, int status,
228 void *command_data, void *opaque)
229{
230 struct IscsiTask *iTask = opaque;
231 struct scsi_task *task = command_data;
232
54a5c1d5
PL
233 iTask->status = status;
234 iTask->do_retry = 0;
235 iTask->task = task;
236
54a5c1d5 237 if (status != SCSI_STATUS_GOOD) {
efc6de0d
PL
238 if (iTask->retries++ < ISCSI_CMD_RETRIES) {
239 if (status == SCSI_STATUS_CHECK_CONDITION
240 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
241 error_report("iSCSI CheckCondition: %s",
242 iscsi_get_error(iscsi));
243 iTask->do_retry = 1;
244 goto out;
245 }
9049736e 246 if (status == SCSI_STATUS_BUSY ||
e01dd3da
FZ
247 status == SCSI_STATUS_TIMEOUT ||
248 status == SCSI_STATUS_TASK_SET_FULL) {
efc6de0d
PL
249 unsigned retry_time =
250 exp_random(iscsi_retry_times[iTask->retries - 1]);
e01dd3da 251 if (status == SCSI_STATUS_TIMEOUT) {
5dd7a535
PL
252 /* make sure the request is rescheduled AFTER the
253 * reconnect is initiated */
254 retry_time = EVENT_INTERVAL * 2;
255 iTask->iscsilun->request_timed_out = true;
256 }
257 error_report("iSCSI Busy/TaskSetFull/TimeOut"
258 " (retry #%u in %u ms): %s",
efc6de0d
PL
259 iTask->retries, retry_time,
260 iscsi_get_error(iscsi));
261 aio_timer_init(iTask->iscsilun->aio_context,
262 &iTask->retry_timer, QEMU_CLOCK_REALTIME,
263 SCALE_MS, iscsi_retry_timer_expired, iTask);
264 timer_mod(&iTask->retry_timer,
265 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + retry_time);
266 iTask->do_retry = 1;
267 return;
268 }
269 }
e01dd3da 270 iTask->err_code = iscsi_translate_sense(&task->sense);
e38bc234 271 iTask->err_str = g_strdup(iscsi_get_error(iscsi));
54a5c1d5
PL
272 }
273
274out:
275 if (iTask->co) {
fffb6e12
PB
276 aio_bh_schedule_oneshot(iTask->iscsilun->aio_context,
277 iscsi_co_generic_bh_cb, iTask);
fcd470d8
PL
278 } else {
279 iTask->complete = 1;
54a5c1d5
PL
280 }
281}
282
283static void iscsi_co_init_iscsitask(IscsiLun *iscsilun, struct IscsiTask *iTask)
284{
285 *iTask = (struct IscsiTask) {
efc6de0d 286 .co = qemu_coroutine_self(),
efc6de0d 287 .iscsilun = iscsilun,
54a5c1d5
PL
288 };
289}
27cbd828 290
c589b249
RS
291static void
292iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
293 void *private_data)
294{
1bd075f2
PB
295 IscsiAIOCB *acb = private_data;
296
297 acb->status = -ECANCELED;
298 iscsi_schedule_bh(acb);
c589b249
RS
299}
300
301static void
7c84b1b8 302iscsi_aio_cancel(BlockAIOCB *blockacb)
c589b249
RS
303{
304 IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
305 IscsiLun *iscsilun = acb->iscsilun;
306
1bd075f2
PB
307 if (acb->status != -EINPROGRESS) {
308 return;
309 }
310
b2090919 311 /* send a task mgmt call to the target to cancel the task on the target */
64e69e80 312 iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
1bd075f2 313 iscsi_abort_task_cb, acb);
b2090919 314
c589b249
RS
315}
316
d7331bed 317static const AIOCBInfo iscsi_aiocb_info = {
c589b249 318 .aiocb_size = sizeof(IscsiAIOCB),
722d9333 319 .cancel_async = iscsi_aio_cancel,
c589b249
RS
320};
321
322
323static void iscsi_process_read(void *arg);
324static void iscsi_process_write(void *arg);
325
d045c466 326/* Called with QemuMutex held. */
c589b249
RS
327static void
328iscsi_set_events(IscsiLun *iscsilun)
329{
330 struct iscsi_context *iscsi = iscsilun->iscsi;
05b685fb 331 int ev = iscsi_which_events(iscsi);
c9b9f682 332
c9b9f682 333 if (ev != iscsilun->events) {
dca21ef2
FZ
334 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsi),
335 false,
05b685fb 336 (ev & POLLIN) ? iscsi_process_read : NULL,
80cf6257 337 (ev & POLLOUT) ? iscsi_process_write : NULL,
f6a51c84 338 NULL,
80cf6257 339 iscsilun);
05b685fb
PL
340 iscsilun->events = ev;
341 }
05b685fb 342}
c9b9f682 343
5dd7a535 344static void iscsi_timed_check_events(void *opaque)
05b685fb
PL
345{
346 IscsiLun *iscsilun = opaque;
5dd7a535
PL
347
348 /* check for timed out requests */
349 iscsi_service(iscsilun->iscsi, 0);
350
351 if (iscsilun->request_timed_out) {
352 iscsilun->request_timed_out = false;
353 iscsi_reconnect(iscsilun->iscsi);
354 }
355
356 /* newer versions of libiscsi may return zero events. Ensure we are able
357 * to return to service once this situation changes. */
05b685fb 358 iscsi_set_events(iscsilun);
5dd7a535
PL
359
360 timer_mod(iscsilun->event_timer,
361 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
c589b249
RS
362}
363
364static void
365iscsi_process_read(void *arg)
366{
367 IscsiLun *iscsilun = arg;
368 struct iscsi_context *iscsi = iscsilun->iscsi;
369
d045c466 370 qemu_mutex_lock(&iscsilun->mutex);
c589b249
RS
371 iscsi_service(iscsi, POLLIN);
372 iscsi_set_events(iscsilun);
d045c466 373 qemu_mutex_unlock(&iscsilun->mutex);
c589b249
RS
374}
375
376static void
377iscsi_process_write(void *arg)
378{
379 IscsiLun *iscsilun = arg;
380 struct iscsi_context *iscsi = iscsilun->iscsi;
381
d045c466 382 qemu_mutex_lock(&iscsilun->mutex);
c589b249
RS
383 iscsi_service(iscsi, POLLOUT);
384 iscsi_set_events(iscsilun);
d045c466 385 qemu_mutex_unlock(&iscsilun->mutex);
c589b249
RS
386}
387
0777b5dd
PL
388static int64_t sector_lun2qemu(int64_t sector, IscsiLun *iscsilun)
389{
390 return sector * iscsilun->block_size / BDRV_SECTOR_SIZE;
391}
392
c589b249
RS
393static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
394{
395 return sector * BDRV_SECTOR_SIZE / iscsilun->block_size;
396}
397
94d047a3
EB
398static bool is_byte_request_lun_aligned(int64_t offset, int count,
399 IscsiLun *iscsilun)
91bea4e2 400{
94d047a3
EB
401 if (offset % iscsilun->block_size || count % iscsilun->block_size) {
402 error_report("iSCSI misaligned request: "
403 "iscsilun->block_size %u, offset %" PRIi64
404 ", count %d",
405 iscsilun->block_size, offset, count);
406 return false;
407 }
408 return true;
409}
410
411static bool is_sector_request_lun_aligned(int64_t sector_num, int nb_sectors,
412 IscsiLun *iscsilun)
413{
0ead9312 414 assert(nb_sectors <= BDRV_REQUEST_MAX_SECTORS);
94d047a3
EB
415 return is_byte_request_lun_aligned(sector_num << BDRV_SECTOR_BITS,
416 nb_sectors << BDRV_SECTOR_BITS,
417 iscsilun);
91bea4e2
PL
418}
419
e1123a3b 420static void iscsi_allocmap_free(IscsiLun *iscsilun)
a9fe4c95 421{
e1123a3b
PL
422 g_free(iscsilun->allocmap);
423 g_free(iscsilun->allocmap_valid);
424 iscsilun->allocmap = NULL;
425 iscsilun->allocmap_valid = NULL;
a9fe4c95
PL
426}
427
e1123a3b
PL
428
429static int iscsi_allocmap_init(IscsiLun *iscsilun, int open_flags)
b03c3805 430{
e1123a3b
PL
431 iscsi_allocmap_free(iscsilun);
432
433 iscsilun->allocmap_size =
434 DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks, iscsilun),
435 iscsilun->cluster_sectors);
436
437 iscsilun->allocmap = bitmap_try_new(iscsilun->allocmap_size);
438 if (!iscsilun->allocmap) {
439 return -ENOMEM;
b03c3805 440 }
e1123a3b
PL
441
442 if (open_flags & BDRV_O_NOCACHE) {
443 /* in case that cache.direct = on all allocmap entries are
444 * treated as invalid to force a relookup of the block
445 * status on every read request */
446 return 0;
447 }
448
449 iscsilun->allocmap_valid = bitmap_try_new(iscsilun->allocmap_size);
450 if (!iscsilun->allocmap_valid) {
451 /* if we are under memory pressure free the allocmap as well */
452 iscsi_allocmap_free(iscsilun);
453 return -ENOMEM;
454 }
455
456 return 0;
b03c3805
PL
457}
458
e1123a3b
PL
459static void
460iscsi_allocmap_update(IscsiLun *iscsilun, int64_t sector_num,
461 int nb_sectors, bool allocated, bool valid)
b03c3805 462{
e1123a3b
PL
463 int64_t cl_num_expanded, nb_cls_expanded, cl_num_shrunk, nb_cls_shrunk;
464
465 if (iscsilun->allocmap == NULL) {
b03c3805
PL
466 return;
467 }
e1123a3b
PL
468 /* expand to entirely contain all affected clusters */
469 cl_num_expanded = sector_num / iscsilun->cluster_sectors;
470 nb_cls_expanded = DIV_ROUND_UP(sector_num + nb_sectors,
471 iscsilun->cluster_sectors) - cl_num_expanded;
472 /* shrink to touch only completely contained clusters */
473 cl_num_shrunk = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);
474 nb_cls_shrunk = (sector_num + nb_sectors) / iscsilun->cluster_sectors
475 - cl_num_shrunk;
476 if (allocated) {
477 bitmap_set(iscsilun->allocmap, cl_num_expanded, nb_cls_expanded);
478 } else {
1da45e0c
PL
479 if (nb_cls_shrunk > 0) {
480 bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
481 }
e1123a3b
PL
482 }
483
484 if (iscsilun->allocmap_valid == NULL) {
485 return;
486 }
487 if (valid) {
1da45e0c
PL
488 if (nb_cls_shrunk > 0) {
489 bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
490 }
e1123a3b
PL
491 } else {
492 bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
493 nb_cls_expanded);
494 }
495}
496
497static void
498iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
499 int nb_sectors)
500{
501 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
502}
503
504static void
505iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
506 int nb_sectors)
507{
508 /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
509 * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
510 */
511 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
512}
513
514static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
515 int nb_sectors)
516{
517 iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
518}
519
520static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
521{
522 if (iscsilun->allocmap) {
523 bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
524 }
525 if (iscsilun->allocmap_valid) {
526 bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
527 }
528}
529
530static inline bool
531iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
532 int nb_sectors)
533{
534 unsigned long size;
535 if (iscsilun->allocmap == NULL) {
536 return true;
b03c3805 537 }
e1123a3b
PL
538 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
539 return !(find_next_bit(iscsilun->allocmap, size,
540 sector_num / iscsilun->cluster_sectors) == size);
541}
542
543static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
544 int64_t sector_num, int nb_sectors)
545{
546 unsigned long size;
547 if (iscsilun->allocmap_valid == NULL) {
548 return false;
549 }
550 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
551 return (find_next_zero_bit(iscsilun->allocmap_valid, size,
552 sector_num / iscsilun->cluster_sectors) == size);
b03c3805
PL
553}
554
9f0eb9e1
KW
555static int coroutine_fn
556iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
557 QEMUIOVector *iov, int flags)
c589b249 558{
063c3378
PL
559 IscsiLun *iscsilun = bs->opaque;
560 struct IscsiTask iTask;
f4dfa67f 561 uint64_t lba;
063c3378 562 uint32_t num_sectors;
4df863f3 563 bool fua = flags & BDRV_REQ_FUA;
d045c466 564 int r = 0;
c589b249 565
4df863f3
EB
566 if (fua) {
567 assert(iscsilun->dpofua);
568 }
94d047a3 569 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
063c3378
PL
570 return -EINVAL;
571 }
7371d56f 572
6bd01f14
EB
573 if (bs->bl.max_transfer) {
574 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
dc9e7163
PL
575 }
576
063c3378
PL
577 lba = sector_qemu2lun(sector_num, iscsilun);
578 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
063c3378 579 iscsi_co_init_iscsitask(iscsilun, &iTask);
d045c466 580 qemu_mutex_lock(&iscsilun->mutex);
063c3378 581retry:
9281fe9e 582 if (iscsilun->use_16_for_rw) {
583ec22e
RS
583#if LIBISCSI_API_VERSION >= (20160603)
584 iTask.task = iscsi_write16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
585 NULL, num_sectors * iscsilun->block_size,
586 iscsilun->block_size, 0, 0, fua, 0, 0,
587 iscsi_co_generic_cb, &iTask,
588 (struct scsi_iovec *)iov->iov, iov->niov);
589 } else {
590 iTask.task = iscsi_write10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
591 NULL, num_sectors * iscsilun->block_size,
592 iscsilun->block_size, 0, 0, fua, 0, 0,
593 iscsi_co_generic_cb, &iTask,
594 (struct scsi_iovec *)iov->iov, iov->niov);
595 }
596#else
9281fe9e 597 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
8c215a9f 598 NULL, num_sectors * iscsilun->block_size,
73b5394e 599 iscsilun->block_size, 0, 0, fua, 0, 0,
9281fe9e
PL
600 iscsi_co_generic_cb, &iTask);
601 } else {
602 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
8c215a9f 603 NULL, num_sectors * iscsilun->block_size,
73b5394e 604 iscsilun->block_size, 0, 0, fua, 0, 0,
9281fe9e
PL
605 iscsi_co_generic_cb, &iTask);
606 }
583ec22e 607#endif
063c3378 608 if (iTask.task == NULL) {
f6eb0b31 609 qemu_mutex_unlock(&iscsilun->mutex);
92397116 610 return -ENOMEM;
f4dfa67f 611 }
583ec22e 612#if LIBISCSI_API_VERSION < (20160603)
063c3378
PL
613 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
614 iov->niov);
583ec22e 615#endif
063c3378
PL
616 while (!iTask.complete) {
617 iscsi_set_events(iscsilun);
d045c466 618 qemu_mutex_unlock(&iscsilun->mutex);
063c3378 619 qemu_coroutine_yield();
d045c466 620 qemu_mutex_lock(&iscsilun->mutex);
c589b249
RS
621 }
622
063c3378
PL
623 if (iTask.task != NULL) {
624 scsi_free_scsi_task(iTask.task);
625 iTask.task = NULL;
91bea4e2
PL
626 }
627
063c3378 628 if (iTask.do_retry) {
837c3901 629 iTask.complete = 0;
063c3378 630 goto retry;
1dde716e
PL
631 }
632
063c3378 633 if (iTask.status != SCSI_STATUS_GOOD) {
e1123a3b 634 iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
e38bc234
PL
635 error_report("iSCSI WRITE10/16 failed at lba %" PRIu64 ": %s", lba,
636 iTask.err_str);
d045c466
PB
637 r = iTask.err_code;
638 goto out_unlock;
c589b249
RS
639 }
640
e1123a3b 641 iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
b03c3805 642
d045c466
PB
643out_unlock:
644 qemu_mutex_unlock(&iscsilun->mutex);
e38bc234 645 g_free(iTask.err_str);
d045c466 646 return r;
c589b249
RS
647}
648
b03c3805 649
b03c3805 650
b03c3805
PL
651static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
652 int64_t sector_num,
67a0fd2a
FZ
653 int nb_sectors, int *pnum,
654 BlockDriverState **file)
b03c3805
PL
655{
656 IscsiLun *iscsilun = bs->opaque;
657 struct scsi_get_lba_status *lbas = NULL;
658 struct scsi_lba_status_descriptor *lbasd = NULL;
659 struct IscsiTask iTask;
e38bc234 660 uint64_t lba;
b03c3805
PL
661 int64_t ret;
662
79f9c75e
PL
663 iscsi_co_init_iscsitask(iscsilun, &iTask);
664
94d047a3 665 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
b03c3805
PL
666 ret = -EINVAL;
667 goto out;
668 }
669
670 /* default to all sectors allocated */
671 ret = BDRV_BLOCK_DATA;
672 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
673 *pnum = nb_sectors;
674
675 /* LUN does not support logical block provisioning */
0a386e48 676 if (!iscsilun->lbpme) {
b03c3805
PL
677 goto out;
678 }
679
e38bc234
PL
680 lba = sector_qemu2lun(sector_num, iscsilun);
681
d045c466 682 qemu_mutex_lock(&iscsilun->mutex);
b03c3805
PL
683retry:
684 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
e38bc234 685 lba, 8 + 16, iscsi_co_generic_cb,
b03c3805
PL
686 &iTask) == NULL) {
687 ret = -ENOMEM;
d045c466 688 goto out_unlock;
b03c3805
PL
689 }
690
691 while (!iTask.complete) {
692 iscsi_set_events(iscsilun);
d045c466 693 qemu_mutex_unlock(&iscsilun->mutex);
b03c3805 694 qemu_coroutine_yield();
d045c466 695 qemu_mutex_lock(&iscsilun->mutex);
b03c3805
PL
696 }
697
698 if (iTask.do_retry) {
699 if (iTask.task != NULL) {
700 scsi_free_scsi_task(iTask.task);
701 iTask.task = NULL;
702 }
703 iTask.complete = 0;
704 goto retry;
705 }
706
707 if (iTask.status != SCSI_STATUS_GOOD) {
708 /* in case the get_lba_status_callout fails (i.e.
709 * because the device is busy or the cmd is not
710 * supported) we pretend all blocks are allocated
711 * for backwards compatibility */
e38bc234
PL
712 error_report("iSCSI GET_LBA_STATUS failed at lba %" PRIu64 ": %s",
713 lba, iTask.err_str);
d045c466 714 goto out_unlock;
b03c3805
PL
715 }
716
717 lbas = scsi_datain_unmarshall(iTask.task);
718 if (lbas == NULL) {
719 ret = -EIO;
d045c466 720 goto out_unlock;
b03c3805
PL
721 }
722
723 lbasd = &lbas->descriptors[0];
724
725 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
726 ret = -EIO;
d045c466 727 goto out_unlock;
b03c3805
PL
728 }
729
730 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
731
732 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
733 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
734 ret &= ~BDRV_BLOCK_DATA;
735 if (iscsilun->lbprz) {
736 ret |= BDRV_BLOCK_ZERO;
737 }
738 }
739
740 if (ret & BDRV_BLOCK_ZERO) {
e1123a3b 741 iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
b03c3805 742 } else {
e1123a3b 743 iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
b03c3805
PL
744 }
745
746 if (*pnum > nb_sectors) {
747 *pnum = nb_sectors;
748 }
d045c466
PB
749out_unlock:
750 qemu_mutex_unlock(&iscsilun->mutex);
e38bc234 751 g_free(iTask.err_str);
b03c3805
PL
752out:
753 if (iTask.task != NULL) {
754 scsi_free_scsi_task(iTask.task);
755 }
3399833f
FZ
756 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
757 *file = bs;
758 }
b03c3805
PL
759 return ret;
760}
761
063c3378
PL
762static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
763 int64_t sector_num, int nb_sectors,
764 QEMUIOVector *iov)
c589b249 765{
063c3378
PL
766 IscsiLun *iscsilun = bs->opaque;
767 struct IscsiTask iTask;
1dde716e
PL
768 uint64_t lba;
769 uint32_t num_sectors;
e38bc234 770 int r = 0;
c589b249 771
94d047a3 772 if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
063c3378 773 return -EINVAL;
f4dfa67f 774 }
f4dfa67f 775
6bd01f14
EB
776 if (bs->bl.max_transfer) {
777 assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
dc9e7163
PL
778 }
779
e1123a3b
PL
780 /* if cache.direct is off and we have a valid entry in our allocation map
781 * we can skip checking the block status and directly return zeroes if
782 * the request falls within an unallocated area */
783 if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
784 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
785 qemu_iovec_memset(iov, 0, 0x00, iov->size);
786 return 0;
787 }
788
789 if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
790 !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
791 !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
b03c3805 792 int pnum;
67a0fd2a 793 BlockDriverState *file;
e1123a3b
PL
794 /* check the block status from the beginning of the cluster
795 * containing the start sector */
796 int64_t ret = iscsi_co_get_block_status(bs,
797 sector_num - sector_num % iscsilun->cluster_sectors,
798 BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
b03c3805
PL
799 if (ret < 0) {
800 return ret;
801 }
e1123a3b
PL
802 /* if the whole request falls into an unallocated area we can avoid
803 * to read and directly return zeroes instead */
804 if (ret & BDRV_BLOCK_ZERO &&
805 pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
b03c3805
PL
806 qemu_iovec_memset(iov, 0, 0x00, iov->size);
807 return 0;
808 }
809 }
b03c3805 810
063c3378
PL
811 lba = sector_qemu2lun(sector_num, iscsilun);
812 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
f4dfa67f 813
063c3378 814 iscsi_co_init_iscsitask(iscsilun, &iTask);
d045c466 815 qemu_mutex_lock(&iscsilun->mutex);
063c3378 816retry:
9281fe9e 817 if (iscsilun->use_16_for_rw) {
583ec22e
RS
818#if LIBISCSI_API_VERSION >= (20160603)
819 iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
820 num_sectors * iscsilun->block_size,
821 iscsilun->block_size, 0, 0, 0, 0, 0,
822 iscsi_co_generic_cb, &iTask,
823 (struct scsi_iovec *)iov->iov, iov->niov);
824 } else {
825 iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
826 num_sectors * iscsilun->block_size,
827 iscsilun->block_size,
828 0, 0, 0, 0, 0,
829 iscsi_co_generic_cb, &iTask,
830 (struct scsi_iovec *)iov->iov, iov->niov);
831 }
832#else
063c3378
PL
833 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
834 num_sectors * iscsilun->block_size,
835 iscsilun->block_size, 0, 0, 0, 0, 0,
836 iscsi_co_generic_cb, &iTask);
9281fe9e 837 } else {
063c3378
PL
838 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
839 num_sectors * iscsilun->block_size,
219c2521 840 iscsilun->block_size,
219c2521 841 0, 0, 0, 0, 0,
063c3378 842 iscsi_co_generic_cb, &iTask);
f4dfa67f 843 }
583ec22e 844#endif
063c3378 845 if (iTask.task == NULL) {
f6eb0b31 846 qemu_mutex_unlock(&iscsilun->mutex);
92397116 847 return -ENOMEM;
c589b249 848 }
583ec22e 849#if LIBISCSI_API_VERSION < (20160603)
063c3378 850 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
583ec22e 851#endif
063c3378
PL
852 while (!iTask.complete) {
853 iscsi_set_events(iscsilun);
d045c466 854 qemu_mutex_unlock(&iscsilun->mutex);
063c3378 855 qemu_coroutine_yield();
d045c466 856 qemu_mutex_lock(&iscsilun->mutex);
1dde716e 857 }
c589b249 858
063c3378
PL
859 if (iTask.task != NULL) {
860 scsi_free_scsi_task(iTask.task);
861 iTask.task = NULL;
c589b249
RS
862 }
863
063c3378 864 if (iTask.do_retry) {
837c3901 865 iTask.complete = 0;
063c3378 866 goto retry;
c589b249
RS
867 }
868
063c3378 869 if (iTask.status != SCSI_STATUS_GOOD) {
e38bc234
PL
870 error_report("iSCSI READ10/16 failed at lba %" PRIu64 ": %s",
871 lba, iTask.err_str);
872 r = iTask.err_code;
1dde716e
PL
873 }
874
e38bc234
PL
875 qemu_mutex_unlock(&iscsilun->mutex);
876 g_free(iTask.err_str);
877 return r;
1dde716e
PL
878}
879
063c3378 880static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
1dde716e
PL
881{
882 IscsiLun *iscsilun = bs->opaque;
063c3378 883 struct IscsiTask iTask;
e38bc234 884 int r = 0;
1dde716e 885
73b5394e 886 iscsi_co_init_iscsitask(iscsilun, &iTask);
d045c466 887 qemu_mutex_lock(&iscsilun->mutex);
063c3378
PL
888retry:
889 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
890 0, iscsi_co_generic_cb, &iTask) == NULL) {
f6eb0b31 891 qemu_mutex_unlock(&iscsilun->mutex);
92397116 892 return -ENOMEM;
063c3378 893 }
1dde716e 894
063c3378
PL
895 while (!iTask.complete) {
896 iscsi_set_events(iscsilun);
d045c466 897 qemu_mutex_unlock(&iscsilun->mutex);
063c3378 898 qemu_coroutine_yield();
d045c466 899 qemu_mutex_lock(&iscsilun->mutex);
063c3378 900 }
1dde716e 901
063c3378
PL
902 if (iTask.task != NULL) {
903 scsi_free_scsi_task(iTask.task);
904 iTask.task = NULL;
c589b249
RS
905 }
906
063c3378 907 if (iTask.do_retry) {
837c3901 908 iTask.complete = 0;
063c3378
PL
909 goto retry;
910 }
c589b249 911
063c3378 912 if (iTask.status != SCSI_STATUS_GOOD) {
e38bc234
PL
913 error_report("iSCSI SYNCHRONIZECACHE10 failed: %s", iTask.err_str);
914 r = iTask.err_code;
063c3378
PL
915 }
916
e38bc234
PL
917 qemu_mutex_unlock(&iscsilun->mutex);
918 g_free(iTask.err_str);
919 return r;
c589b249
RS
920}
921
98392453 922#ifdef __linux__
d045c466 923/* Called (via iscsi_service) with QemuMutex held. */
98392453
RS
924static void
925iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
926 void *command_data, void *opaque)
927{
928 IscsiAIOCB *acb = opaque;
929
0a53f010
RS
930 g_free(acb->buf);
931 acb->buf = NULL;
932
98392453
RS
933 acb->status = 0;
934 if (status < 0) {
935 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
936 iscsi_get_error(iscsi));
e01dd3da 937 acb->status = iscsi_translate_sense(&acb->task->sense);
98392453
RS
938 }
939
940 acb->ioh->driver_status = 0;
941 acb->ioh->host_status = 0;
942 acb->ioh->resid = 0;
644c6869 943 acb->ioh->status = status;
98392453
RS
944
945#define SG_ERR_DRIVER_SENSE 0x08
946
947 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
948 int ss;
949
950 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
951
952 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
953 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
954 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
955 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
956 }
957
cfb3f506 958 iscsi_schedule_bh(acb);
98392453
RS
959}
960
4bb17ab5
FZ
961static void iscsi_ioctl_bh_completion(void *opaque)
962{
963 IscsiAIOCB *acb = opaque;
964
965 qemu_bh_delete(acb->bh);
966 acb->common.cb(acb->common.opaque, acb->ret);
967 qemu_aio_unref(acb);
968}
969
970static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
971{
972 BlockDriverState *bs = acb->common.bs;
973 IscsiLun *iscsilun = bs->opaque;
974 int ret = 0;
975
976 switch (req) {
977 case SG_GET_VERSION_NUM:
978 *(int *)buf = 30000;
979 break;
980 case SG_GET_SCSI_ID:
981 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
982 break;
983 default:
984 ret = -EINVAL;
985 }
986 assert(!acb->bh);
987 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
988 iscsi_ioctl_bh_completion, acb);
989 acb->ret = ret;
990 qemu_bh_schedule(acb->bh);
991}
992
7c84b1b8 993static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
98392453 994 unsigned long int req, void *buf,
097310b5 995 BlockCompletionFunc *cb, void *opaque)
98392453
RS
996{
997 IscsiLun *iscsilun = bs->opaque;
998 struct iscsi_context *iscsi = iscsilun->iscsi;
999 struct iscsi_data data;
1000 IscsiAIOCB *acb;
1001
d7331bed 1002 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
98392453
RS
1003
1004 acb->iscsilun = iscsilun;
1bd075f2
PB
1005 acb->bh = NULL;
1006 acb->status = -EINPROGRESS;
98392453
RS
1007 acb->buf = NULL;
1008 acb->ioh = buf;
1009
4bb17ab5
FZ
1010 if (req != SG_IO) {
1011 iscsi_ioctl_handle_emulated(acb, req, buf);
1012 return &acb->common;
1013 }
1014
a6b3167f
PL
1015 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
1016 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
1017 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1018 qemu_aio_unref(acb);
1019 return NULL;
1020 }
1021
98392453
RS
1022 acb->task = malloc(sizeof(struct scsi_task));
1023 if (acb->task == NULL) {
1024 error_report("iSCSI: Failed to allocate task for scsi command. %s",
1025 iscsi_get_error(iscsi));
8007429a 1026 qemu_aio_unref(acb);
98392453
RS
1027 return NULL;
1028 }
1029 memset(acb->task, 0, sizeof(struct scsi_task));
1030
1031 switch (acb->ioh->dxfer_direction) {
1032 case SG_DXFER_TO_DEV:
1033 acb->task->xfer_dir = SCSI_XFER_WRITE;
1034 break;
1035 case SG_DXFER_FROM_DEV:
1036 acb->task->xfer_dir = SCSI_XFER_READ;
1037 break;
1038 default:
1039 acb->task->xfer_dir = SCSI_XFER_NONE;
1040 break;
1041 }
1042
1043 acb->task->cdb_size = acb->ioh->cmd_len;
1044 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1045 acb->task->expxferlen = acb->ioh->dxfer_len;
1046
0a53f010 1047 data.size = 0;
d045c466 1048 qemu_mutex_lock(&iscsilun->mutex);
98392453 1049 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
0a53f010
RS
1050 if (acb->ioh->iovec_count == 0) {
1051 data.data = acb->ioh->dxferp;
1052 data.size = acb->ioh->dxfer_len;
1053 } else {
0a53f010
RS
1054 scsi_task_set_iov_out(acb->task,
1055 (struct scsi_iovec *) acb->ioh->dxferp,
1056 acb->ioh->iovec_count);
0a53f010 1057 }
98392453 1058 }
0a53f010 1059
98392453
RS
1060 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1061 iscsi_aio_ioctl_cb,
0a53f010 1062 (data.size > 0) ? &data : NULL,
98392453 1063 acb) != 0) {
d045c466 1064 qemu_mutex_unlock(&iscsilun->mutex);
98392453 1065 scsi_free_scsi_task(acb->task);
8007429a 1066 qemu_aio_unref(acb);
98392453
RS
1067 return NULL;
1068 }
1069
1070 /* tell libiscsi to read straight into the buffer we got from ioctl */
1071 if (acb->task->xfer_dir == SCSI_XFER_READ) {
0a53f010
RS
1072 if (acb->ioh->iovec_count == 0) {
1073 scsi_task_add_data_in_buffer(acb->task,
1074 acb->ioh->dxfer_len,
1075 acb->ioh->dxferp);
1076 } else {
0a53f010
RS
1077 scsi_task_set_iov_in(acb->task,
1078 (struct scsi_iovec *) acb->ioh->dxferp,
1079 acb->ioh->iovec_count);
0a53f010 1080 }
98392453
RS
1081 }
1082
1083 iscsi_set_events(iscsilun);
d045c466 1084 qemu_mutex_unlock(&iscsilun->mutex);
98392453
RS
1085
1086 return &acb->common;
1087}
1088
98392453
RS
1089#endif
1090
c589b249
RS
1091static int64_t
1092iscsi_getlength(BlockDriverState *bs)
1093{
1094 IscsiLun *iscsilun = bs->opaque;
1095 int64_t len;
1096
1097 len = iscsilun->num_blocks;
1098 len *= iscsilun->block_size;
1099
1100 return len;
1101}
1102
65f3e339 1103static int
f5a5ca79 1104coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
65f3e339
PL
1105{
1106 IscsiLun *iscsilun = bs->opaque;
1107 struct IscsiTask iTask;
1108 struct unmap_list list;
d045c466 1109 int r = 0;
65f3e339 1110
f5a5ca79 1111 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
49228d1e
EB
1112 return -ENOTSUP;
1113 }
65f3e339
PL
1114
1115 if (!iscsilun->lbp.lbpu) {
1116 /* UNMAP is not supported by the target */
1117 return 0;
1118 }
1119
97c7e85c 1120 list.lba = offset / iscsilun->block_size;
f5a5ca79 1121 list.num = bytes / iscsilun->block_size;
65f3e339 1122
01a6a238 1123 iscsi_co_init_iscsitask(iscsilun, &iTask);
d045c466 1124 qemu_mutex_lock(&iscsilun->mutex);
65f3e339 1125retry:
01a6a238 1126 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
97c7e85c 1127 iscsi_co_generic_cb, &iTask) == NULL) {
d045c466
PB
1128 r = -ENOMEM;
1129 goto out_unlock;
01a6a238 1130 }
65f3e339 1131
01a6a238
PL
1132 while (!iTask.complete) {
1133 iscsi_set_events(iscsilun);
d045c466 1134 qemu_mutex_unlock(&iscsilun->mutex);
01a6a238 1135 qemu_coroutine_yield();
d045c466 1136 qemu_mutex_lock(&iscsilun->mutex);
01a6a238 1137 }
65f3e339 1138
01a6a238
PL
1139 if (iTask.task != NULL) {
1140 scsi_free_scsi_task(iTask.task);
1141 iTask.task = NULL;
1142 }
65f3e339 1143
01a6a238 1144 if (iTask.do_retry) {
837c3901 1145 iTask.complete = 0;
01a6a238
PL
1146 goto retry;
1147 }
65f3e339 1148
aef172ff
PL
1149 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1150 bytes >> BDRV_SECTOR_BITS);
1151
01a6a238
PL
1152 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1153 /* the target might fail with a check condition if it
1154 is not happy with the alignment of the UNMAP request
1155 we silently fail in this case */
d045c466 1156 goto out_unlock;
01a6a238 1157 }
65f3e339 1158
01a6a238 1159 if (iTask.status != SCSI_STATUS_GOOD) {
e38bc234
PL
1160 error_report("iSCSI UNMAP failed at lba %" PRIu64 ": %s",
1161 list.lba, iTask.err_str);
d045c466
PB
1162 r = iTask.err_code;
1163 goto out_unlock;
65f3e339
PL
1164 }
1165
d045c466
PB
1166out_unlock:
1167 qemu_mutex_unlock(&iscsilun->mutex);
e38bc234 1168 g_free(iTask.err_str);
d045c466 1169 return r;
65f3e339
PL
1170}
1171
d4cd9615 1172static int
94d047a3 1173coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
f5a5ca79 1174 int bytes, BdrvRequestFlags flags)
d4cd9615
PL
1175{
1176 IscsiLun *iscsilun = bs->opaque;
1177 struct IscsiTask iTask;
1178 uint64_t lba;
1179 uint32_t nb_blocks;
9281fe9e 1180 bool use_16_for_ws = iscsilun->use_16_for_rw;
d045c466 1181 int r = 0;
d4cd9615 1182
f5a5ca79 1183 if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {
94d047a3 1184 return -ENOTSUP;
d4cd9615
PL
1185 }
1186
9281fe9e
PL
1187 if (flags & BDRV_REQ_MAY_UNMAP) {
1188 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1189 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1190 use_16_for_ws = true;
1191 }
1192 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1193 /* WRITESAME16 with UNMAP is not supported by the target,
1194 * fall back and try WRITESAME10/16 without UNMAP */
1195 flags &= ~BDRV_REQ_MAY_UNMAP;
1196 use_16_for_ws = iscsilun->use_16_for_rw;
1197 }
fa6252b0
PB
1198 }
1199
dbe5c58f 1200 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
9281fe9e 1201 /* WRITESAME without UNMAP is not supported by the target */
d4cd9615
PL
1202 return -ENOTSUP;
1203 }
1204
94d047a3 1205 lba = offset / iscsilun->block_size;
f5a5ca79 1206 nb_blocks = bytes / iscsilun->block_size;
d4cd9615
PL
1207
1208 if (iscsilun->zeroblock == NULL) {
4d5a3f88
KW
1209 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1210 if (iscsilun->zeroblock == NULL) {
1211 return -ENOMEM;
1212 }
d4cd9615
PL
1213 }
1214
d045c466 1215 qemu_mutex_lock(&iscsilun->mutex);
d4cd9615
PL
1216 iscsi_co_init_iscsitask(iscsilun, &iTask);
1217retry:
9281fe9e
PL
1218 if (use_16_for_ws) {
1219 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1220 iscsilun->zeroblock, iscsilun->block_size,
1221 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1222 0, 0, iscsi_co_generic_cb, &iTask);
1223 } else {
1224 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1225 iscsilun->zeroblock, iscsilun->block_size,
1226 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1227 0, 0, iscsi_co_generic_cb, &iTask);
1228 }
1229 if (iTask.task == NULL) {
f6eb0b31 1230 qemu_mutex_unlock(&iscsilun->mutex);
92397116 1231 return -ENOMEM;
d4cd9615
PL
1232 }
1233
1234 while (!iTask.complete) {
1235 iscsi_set_events(iscsilun);
d045c466 1236 qemu_mutex_unlock(&iscsilun->mutex);
d4cd9615 1237 qemu_coroutine_yield();
d045c466 1238 qemu_mutex_lock(&iscsilun->mutex);
d4cd9615
PL
1239 }
1240
d9738fd2
PL
1241 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1242 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
27898a5d
PB
1243 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1244 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
d9738fd2
PL
1245 /* WRITE SAME is not supported by the target */
1246 iscsilun->has_write_same = false;
1247 scsi_free_scsi_task(iTask.task);
d045c466
PB
1248 r = -ENOTSUP;
1249 goto out_unlock;
d9738fd2
PL
1250 }
1251
d4cd9615
PL
1252 if (iTask.task != NULL) {
1253 scsi_free_scsi_task(iTask.task);
1254 iTask.task = NULL;
1255 }
1256
1257 if (iTask.do_retry) {
837c3901 1258 iTask.complete = 0;
d4cd9615
PL
1259 goto retry;
1260 }
1261
1262 if (iTask.status != SCSI_STATUS_GOOD) {
e1123a3b 1263 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
f5a5ca79 1264 bytes >> BDRV_SECTOR_BITS);
e38bc234
PL
1265 error_report("iSCSI WRITESAME10/16 failed at lba %" PRIu64 ": %s",
1266 lba, iTask.err_str);
d045c466
PB
1267 r = iTask.err_code;
1268 goto out_unlock;
d4cd9615
PL
1269 }
1270
b03c3805 1271 if (flags & BDRV_REQ_MAY_UNMAP) {
e1123a3b 1272 iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
f5a5ca79 1273 bytes >> BDRV_SECTOR_BITS);
b03c3805 1274 } else {
e1123a3b 1275 iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
f5a5ca79 1276 bytes >> BDRV_SECTOR_BITS);
b03c3805
PL
1277 }
1278
d045c466
PB
1279out_unlock:
1280 qemu_mutex_unlock(&iscsilun->mutex);
e38bc234 1281 g_free(iTask.err_str);
d045c466 1282 return r;
d4cd9615
PL
1283}
1284
43171420 1285static void apply_chap(struct iscsi_context *iscsi, QemuOpts *opts,
f2917853 1286 Error **errp)
f9dadc98 1287{
f9dadc98
RS
1288 const char *user = NULL;
1289 const char *password = NULL;
b189346e
DB
1290 const char *secretid;
1291 char *secret = NULL;
f9dadc98 1292
f9dadc98
RS
1293 user = qemu_opt_get(opts, "user");
1294 if (!user) {
f2917853 1295 return;
f9dadc98
RS
1296 }
1297
b189346e 1298 secretid = qemu_opt_get(opts, "password-secret");
f9dadc98 1299 password = qemu_opt_get(opts, "password");
b189346e
DB
1300 if (secretid && password) {
1301 error_setg(errp, "'password' and 'password-secret' properties are "
1302 "mutually exclusive");
1303 return;
1304 }
1305 if (secretid) {
1306 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1307 if (!secret) {
1308 return;
1309 }
1310 password = secret;
1311 } else if (!password) {
f2917853
PB
1312 error_setg(errp, "CHAP username specified but no password was given");
1313 return;
f9dadc98
RS
1314 }
1315
1316 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
f2917853 1317 error_setg(errp, "Failed to set initiator username and password");
f9dadc98 1318 }
b189346e
DB
1319
1320 g_free(secret);
f9dadc98
RS
1321}
1322
81aa2a0f 1323static void apply_header_digest(struct iscsi_context *iscsi, QemuOpts *opts,
f2917853 1324 Error **errp)
f9dadc98 1325{
f9dadc98
RS
1326 const char *digest = NULL;
1327
f9dadc98
RS
1328 digest = qemu_opt_get(opts, "header-digest");
1329 if (!digest) {
81aa2a0f 1330 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
31eb1202 1331 } else if (!strcmp(digest, "crc32c")) {
f9dadc98 1332 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
31eb1202 1333 } else if (!strcmp(digest, "none")) {
f9dadc98 1334 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
31eb1202 1335 } else if (!strcmp(digest, "crc32c-none")) {
f9dadc98 1336 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
31eb1202 1337 } else if (!strcmp(digest, "none-crc32c")) {
f9dadc98
RS
1338 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1339 } else {
f2917853 1340 error_setg(errp, "Invalid header-digest setting : %s", digest);
f9dadc98
RS
1341 }
1342}
1343
d4e79929 1344static char *get_initiator_name(QemuOpts *opts)
f9dadc98 1345{
5accc840
PB
1346 const char *name;
1347 char *iscsi_name;
1348 UuidInfo *uuid_info;
f9dadc98 1349
d4e79929
KW
1350 name = qemu_opt_get(opts, "initiator-name");
1351 if (name) {
1352 return g_strdup(name);
f9dadc98
RS
1353 }
1354
5accc840
PB
1355 uuid_info = qmp_query_uuid(NULL);
1356 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1357 name = qemu_get_vm_name();
f2ef4a6d 1358 } else {
5accc840 1359 name = uuid_info->UUID;
f9dadc98 1360 }
5accc840
PB
1361 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1362 name ? ":" : "", name ? name : "");
1363 qapi_free_UuidInfo(uuid_info);
1364 return iscsi_name;
f9dadc98
RS
1365}
1366
5b5d34ec
PL
1367static void iscsi_nop_timed_event(void *opaque)
1368{
1369 IscsiLun *iscsilun = opaque;
1370
d045c466 1371 qemu_mutex_lock(&iscsilun->mutex);
5dd7a535 1372 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
5b5d34ec 1373 error_report("iSCSI: NOP timeout. Reconnecting...");
5dd7a535
PL
1374 iscsilun->request_timed_out = true;
1375 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
5b5d34ec 1376 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
2f47da5f 1377 goto out;
5b5d34ec
PL
1378 }
1379
bc72ad67 1380 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
5b5d34ec 1381 iscsi_set_events(iscsilun);
2f47da5f
PB
1382
1383out:
d045c466 1384 qemu_mutex_unlock(&iscsilun->mutex);
5b5d34ec 1385}
5b5d34ec 1386
f2917853 1387static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
cb1b83e7
PL
1388{
1389 struct scsi_task *task = NULL;
1390 struct scsi_readcapacity10 *rc10 = NULL;
1391 struct scsi_readcapacity16 *rc16 = NULL;
cb1b83e7
PL
1392 int retries = ISCSI_CMD_RETRIES;
1393
1288844e
PB
1394 do {
1395 if (task != NULL) {
1396 scsi_free_scsi_task(task);
1397 task = NULL;
cb1b83e7 1398 }
1288844e
PB
1399
1400 switch (iscsilun->type) {
1401 case TYPE_DISK:
1402 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1403 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1404 rc16 = scsi_datain_unmarshall(task);
1405 if (rc16 == NULL) {
f2917853 1406 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1288844e
PB
1407 } else {
1408 iscsilun->block_size = rc16->block_length;
1409 iscsilun->num_blocks = rc16->returned_lba + 1;
0a386e48
PL
1410 iscsilun->lbpme = !!rc16->lbpme;
1411 iscsilun->lbprz = !!rc16->lbprz;
9281fe9e 1412 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1288844e 1413 }
1cb6d137 1414 break;
1288844e 1415 }
1cb6d137
ZL
1416 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1417 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1418 break;
1419 }
1420 /* Fall through and try READ CAPACITY(10) instead. */
1288844e
PB
1421 case TYPE_ROM:
1422 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1423 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1424 rc10 = scsi_datain_unmarshall(task);
1425 if (rc10 == NULL) {
f2917853 1426 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1288844e
PB
1427 } else {
1428 iscsilun->block_size = rc10->block_size;
1429 if (rc10->lba == 0) {
1430 /* blank disk loaded */
1431 iscsilun->num_blocks = 0;
1432 } else {
1433 iscsilun->num_blocks = rc10->lba + 1;
1434 }
1435 }
1436 }
1437 break;
1438 default:
f2917853 1439 return;
cb1b83e7 1440 }
1288844e
PB
1441 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1442 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1443 && retries-- > 0);
cb1b83e7 1444
1288844e 1445 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
240125bc 1446 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
6d1f252d
PL
1447 } else if (!iscsilun->block_size ||
1448 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1449 error_setg(errp, "iSCSI: the target returned an invalid "
1450 "block size of %d.", iscsilun->block_size);
1288844e 1451 }
cb1b83e7
PL
1452 if (task) {
1453 scsi_free_scsi_task(task);
1454 }
cb1b83e7
PL
1455}
1456
35cb1748 1457static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
24d3bd67 1458 int evpd, int pc, void **inq, Error **errp)
35cb1748
PB
1459{
1460 int full_size;
1461 struct scsi_task *task = NULL;
1462 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1463 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1464 goto fail;
1465 }
1466 full_size = scsi_datain_getfullsize(task);
1467 if (full_size > task->datain.size) {
1468 scsi_free_scsi_task(task);
1469
1470 /* we need more data for the full list */
1471 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
f18a7cbb
PL
1472 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1473 goto fail;
1474 }
35cb1748 1475 }
f18a7cbb 1476
24d3bd67
PL
1477 *inq = scsi_datain_unmarshall(task);
1478 if (*inq == NULL) {
1479 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
172fc4dd 1480 goto fail_with_err;
24d3bd67
PL
1481 }
1482
35cb1748 1483 return task;
f18a7cbb
PL
1484
1485fail:
172fc4dd
MA
1486 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1487 iscsi_get_error(iscsi));
1488fail_with_err:
24d3bd67 1489 if (task != NULL) {
35cb1748 1490 scsi_free_scsi_task(task);
35cb1748
PB
1491 }
1492 return NULL;
f18a7cbb
PL
1493}
1494
80cf6257
SH
1495static void iscsi_detach_aio_context(BlockDriverState *bs)
1496{
1497 IscsiLun *iscsilun = bs->opaque;
1498
dca21ef2 1499 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
f6a51c84 1500 false, NULL, NULL, NULL, NULL);
80cf6257
SH
1501 iscsilun->events = 0;
1502
1503 if (iscsilun->nop_timer) {
1504 timer_del(iscsilun->nop_timer);
1505 timer_free(iscsilun->nop_timer);
1506 iscsilun->nop_timer = NULL;
1507 }
05b685fb
PL
1508 if (iscsilun->event_timer) {
1509 timer_del(iscsilun->event_timer);
1510 timer_free(iscsilun->event_timer);
1511 iscsilun->event_timer = NULL;
1512 }
80cf6257
SH
1513}
1514
1515static void iscsi_attach_aio_context(BlockDriverState *bs,
1516 AioContext *new_context)
1517{
1518 IscsiLun *iscsilun = bs->opaque;
1519
1520 iscsilun->aio_context = new_context;
1521 iscsi_set_events(iscsilun);
1522
80cf6257
SH
1523 /* Set up a timer for sending out iSCSI NOPs */
1524 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1525 QEMU_CLOCK_REALTIME, SCALE_MS,
1526 iscsi_nop_timed_event, iscsilun);
1527 timer_mod(iscsilun->nop_timer,
1528 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
05b685fb 1529
5dd7a535
PL
1530 /* Set up a timer for periodic calls to iscsi_set_events and to
1531 * scan for command timeout */
05b685fb
PL
1532 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1533 QEMU_CLOCK_REALTIME, SCALE_MS,
5dd7a535
PL
1534 iscsi_timed_check_events, iscsilun);
1535 timer_mod(iscsilun->event_timer,
1536 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
80cf6257
SH
1537}
1538
7191f208 1539static void iscsi_modesense_sync(IscsiLun *iscsilun)
c1d4096b
FZ
1540{
1541 struct scsi_task *task;
1542 struct scsi_mode_sense *ms = NULL;
7191f208 1543 iscsilun->write_protected = false;
752ce451 1544 iscsilun->dpofua = false;
c1d4096b
FZ
1545
1546 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1547 1, SCSI_MODESENSE_PC_CURRENT,
1548 0x3F, 0, 255);
1549 if (task == NULL) {
1550 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1551 iscsi_get_error(iscsilun->iscsi));
1552 goto out;
1553 }
1554
1555 if (task->status != SCSI_STATUS_GOOD) {
1556 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1557 goto out;
1558 }
1559 ms = scsi_datain_unmarshall(task);
1560 if (!ms) {
1561 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1562 iscsi_get_error(iscsilun->iscsi));
1563 goto out;
1564 }
7191f208 1565 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
752ce451 1566 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
c1d4096b
FZ
1567
1568out:
1569 if (task) {
1570 scsi_free_scsi_task(task);
1571 }
c1d4096b
FZ
1572}
1573
43171420
KW
1574static void iscsi_parse_iscsi_option(const char *target, QDict *options)
1575{
1576 QemuOptsList *list;
1577 QemuOpts *opts;
81aa2a0f 1578 const char *user, *password, *password_secret, *initiator_name,
1d560104 1579 *header_digest, *timeout;
43171420
KW
1580
1581 list = qemu_find_opts("iscsi");
1582 if (!list) {
1583 return;
1584 }
1585
1586 opts = qemu_opts_find(list, target);
1587 if (opts == NULL) {
1588 opts = QTAILQ_FIRST(&list->head);
1589 if (!opts) {
1590 return;
1591 }
1592 }
1593
1594 user = qemu_opt_get(opts, "user");
1595 if (user) {
1596 qdict_set_default_str(options, "user", user);
1597 }
1598
1599 password = qemu_opt_get(opts, "password");
1600 if (password) {
1601 qdict_set_default_str(options, "password", password);
1602 }
1603
1604 password_secret = qemu_opt_get(opts, "password-secret");
1605 if (password_secret) {
1606 qdict_set_default_str(options, "password-secret", password_secret);
1607 }
d4e79929
KW
1608
1609 initiator_name = qemu_opt_get(opts, "initiator-name");
1610 if (initiator_name) {
1611 qdict_set_default_str(options, "initiator-name", initiator_name);
1612 }
81aa2a0f
KW
1613
1614 header_digest = qemu_opt_get(opts, "header-digest");
1615 if (header_digest) {
31eb1202
KW
1616 /* -iscsi takes upper case values, but QAPI only supports lower case
1617 * enum constant names, so we have to convert here. */
1618 char *qapi_value = g_ascii_strdown(header_digest, -1);
1619 qdict_set_default_str(options, "header-digest", qapi_value);
1620 g_free(qapi_value);
81aa2a0f 1621 }
1d560104
KW
1622
1623 timeout = qemu_opt_get(opts, "timeout");
1624 if (timeout) {
1625 qdict_set_default_str(options, "timeout", timeout);
1626 }
43171420
KW
1627}
1628
c589b249
RS
1629/*
1630 * We support iscsi url's on the form
1631 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1632 */
d5895fcb
KW
1633static void iscsi_parse_filename(const char *filename, QDict *options,
1634 Error **errp)
1635{
1636 struct iscsi_url *iscsi_url;
1637 const char *transport_name;
1638 char *lun_str;
1639
1640 iscsi_url = iscsi_parse_full_url(NULL, filename);
1641 if (iscsi_url == NULL) {
1642 error_setg(errp, "Failed to parse URL : %s", filename);
1643 return;
1644 }
1645
1646#if LIBISCSI_API_VERSION >= (20160603)
1647 switch (iscsi_url->transport) {
1648 case TCP_TRANSPORT:
1649 transport_name = "tcp";
1650 break;
1651 case ISER_TRANSPORT:
1652 transport_name = "iser";
1653 break;
1654 default:
1655 error_setg(errp, "Unknown transport type (%d)",
1656 iscsi_url->transport);
1657 return;
1658 }
1659#else
1660 transport_name = "tcp";
1661#endif
1662
1663 qdict_set_default_str(options, "transport", transport_name);
1664 qdict_set_default_str(options, "portal", iscsi_url->portal);
1665 qdict_set_default_str(options, "target", iscsi_url->target);
1666
1667 lun_str = g_strdup_printf("%d", iscsi_url->lun);
1668 qdict_set_default_str(options, "lun", lun_str);
1669 g_free(lun_str);
1670
43171420
KW
1671 /* User/password from -iscsi take precedence over those from the URL */
1672 iscsi_parse_iscsi_option(iscsi_url->target, options);
1673
d5895fcb
KW
1674 if (iscsi_url->user[0] != '\0') {
1675 qdict_set_default_str(options, "user", iscsi_url->user);
1676 qdict_set_default_str(options, "password", iscsi_url->passwd);
1677 }
1678
1679 iscsi_destroy_url(iscsi_url);
1680}
1681
d5895fcb
KW
1682static QemuOptsList runtime_opts = {
1683 .name = "iscsi",
1684 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1685 .desc = {
1686 {
1687 .name = "transport",
1688 .type = QEMU_OPT_STRING,
1689 },
1690 {
1691 .name = "portal",
1692 .type = QEMU_OPT_STRING,
1693 },
1694 {
1695 .name = "target",
1696 .type = QEMU_OPT_STRING,
1697 },
1698 {
1699 .name = "user",
1700 .type = QEMU_OPT_STRING,
1701 },
1702 {
1703 .name = "password",
1704 .type = QEMU_OPT_STRING,
1705 },
43171420
KW
1706 {
1707 .name = "password-secret",
1708 .type = QEMU_OPT_STRING,
1709 },
d5895fcb
KW
1710 {
1711 .name = "lun",
1712 .type = QEMU_OPT_NUMBER,
1713 },
d4e79929
KW
1714 {
1715 .name = "initiator-name",
1716 .type = QEMU_OPT_STRING,
1717 },
81aa2a0f
KW
1718 {
1719 .name = "header-digest",
1720 .type = QEMU_OPT_STRING,
1721 },
1d560104
KW
1722 {
1723 .name = "timeout",
1724 .type = QEMU_OPT_NUMBER,
1725 },
5c3ad1a6
JC
1726 {
1727 .name = "filename",
1728 .type = QEMU_OPT_STRING,
1729 },
d5895fcb
KW
1730 { /* end of list */ }
1731 },
1732};
1733
015a1036
HR
1734static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1735 Error **errp)
c589b249
RS
1736{
1737 IscsiLun *iscsilun = bs->opaque;
1738 struct iscsi_context *iscsi = NULL;
e829b0bb
PL
1739 struct scsi_task *task = NULL;
1740 struct scsi_inquiry_standard *inq = NULL;
24d3bd67 1741 struct scsi_inquiry_supported_pages *inq_vpd;
f9dadc98 1742 char *initiator_name = NULL;
60beb341
KW
1743 QemuOpts *opts;
1744 Error *local_err = NULL;
5c3ad1a6 1745 const char *transport_name, *portal, *target, *filename;
d5895fcb
KW
1746#if LIBISCSI_API_VERSION >= (20160603)
1747 enum iscsi_transport_type transport;
1748#endif
1749 int i, ret = 0, timeout = 0, lun;
c589b249 1750
5c3ad1a6
JC
1751 /* If we are given a filename, parse the filename, with precedence given to
1752 * filename encoded options */
1753 filename = qdict_get_try_str(options, "filename");
1754 if (filename) {
3dc6f869
AF
1755 warn_report("'filename' option specified. "
1756 "This is an unsupported option, and may be deprecated "
1757 "in the future");
5c3ad1a6
JC
1758 iscsi_parse_filename(filename, options, &local_err);
1759 if (local_err) {
1760 ret = -EINVAL;
1761 error_propagate(errp, local_err);
1762 goto exit;
1763 }
1764 }
1765
87ea75d5 1766 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
60beb341 1767 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 1768 if (local_err) {
f2917853 1769 error_propagate(errp, local_err);
60beb341
KW
1770 ret = -EINVAL;
1771 goto out;
1772 }
1773
d5895fcb
KW
1774 transport_name = qemu_opt_get(opts, "transport");
1775 portal = qemu_opt_get(opts, "portal");
1776 target = qemu_opt_get(opts, "target");
d5895fcb 1777 lun = qemu_opt_get_number(opts, "lun", 0);
60beb341 1778
d5895fcb
KW
1779 if (!transport_name || !portal || !target) {
1780 error_setg(errp, "Need all of transport, portal and target options");
1781 ret = -EINVAL;
1782 goto out;
1783 }
d5895fcb
KW
1784
1785 if (!strcmp(transport_name, "tcp")) {
1786#if LIBISCSI_API_VERSION >= (20160603)
1787 transport = TCP_TRANSPORT;
1788 } else if (!strcmp(transport_name, "iser")) {
1789 transport = ISER_TRANSPORT;
1790#else
1791 /* TCP is what older libiscsi versions always use */
1792#endif
1793 } else {
1794 error_setg(errp, "Unknown transport: %s", transport_name);
c589b249 1795 ret = -EINVAL;
b93c94f7 1796 goto out;
c589b249
RS
1797 }
1798
f9dadc98
RS
1799 memset(iscsilun, 0, sizeof(IscsiLun));
1800
d4e79929 1801 initiator_name = get_initiator_name(opts);
f9dadc98
RS
1802
1803 iscsi = iscsi_create_context(initiator_name);
1804 if (iscsi == NULL) {
f2917853 1805 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
f9dadc98 1806 ret = -ENOMEM;
b93c94f7 1807 goto out;
f9dadc98 1808 }
e0ae4987 1809#if LIBISCSI_API_VERSION >= (20160603)
d5895fcb 1810 if (iscsi_init_transport(iscsi, transport)) {
e0ae4987
RS
1811 error_setg(errp, ("Error initializing transport."));
1812 ret = -EINVAL;
1813 goto out;
1814 }
1815#endif
d5895fcb 1816 if (iscsi_set_targetname(iscsi, target)) {
f2917853 1817 error_setg(errp, "iSCSI: Failed to set target name.");
c589b249 1818 ret = -EINVAL;
b93c94f7 1819 goto out;
c589b249
RS
1820 }
1821
f9dadc98 1822 /* check if we got CHAP username/password via the options */
43171420 1823 apply_chap(iscsi, opts, &local_err);
f2917853
PB
1824 if (local_err != NULL) {
1825 error_propagate(errp, local_err);
f9dadc98 1826 ret = -EINVAL;
b93c94f7 1827 goto out;
f9dadc98
RS
1828 }
1829
c589b249 1830 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
f2917853 1831 error_setg(errp, "iSCSI: Failed to set session type to normal.");
c589b249 1832 ret = -EINVAL;
b93c94f7 1833 goto out;
c589b249
RS
1834 }
1835
f9dadc98 1836 /* check if we got HEADER_DIGEST via the options */
81aa2a0f 1837 apply_header_digest(iscsi, opts, &local_err);
f2917853
PB
1838 if (local_err != NULL) {
1839 error_propagate(errp, local_err);
1840 ret = -EINVAL;
1841 goto out;
1842 }
f9dadc98 1843
9049736e 1844 /* timeout handling is broken in libiscsi before 1.15.0 */
1d560104 1845 timeout = qemu_opt_get_number(opts, "timeout", 0);
583ec22e 1846#if LIBISCSI_API_VERSION >= 20150621
9049736e
PL
1847 iscsi_set_timeout(iscsi, timeout);
1848#else
1849 if (timeout) {
1850 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1851 }
1852#endif
5dd7a535 1853
d5895fcb 1854 if (iscsi_full_connect_sync(iscsi, portal, lun) != 0) {
f2917853 1855 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
e829b0bb
PL
1856 iscsi_get_error(iscsi));
1857 ret = -EINVAL;
1858 goto out;
1859 }
c589b249
RS
1860
1861 iscsilun->iscsi = iscsi;
80cf6257 1862 iscsilun->aio_context = bdrv_get_aio_context(bs);
d5895fcb 1863 iscsilun->lun = lun;
24d3bd67 1864 iscsilun->has_write_same = true;
c589b249 1865
24d3bd67
PL
1866 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1867 (void **) &inq, errp);
1868 if (task == NULL) {
c589b249 1869 ret = -EINVAL;
b93c94f7 1870 goto out;
c589b249 1871 }
e829b0bb 1872 iscsilun->type = inq->periperal_device_type;
24d3bd67
PL
1873 scsi_free_scsi_task(task);
1874 task = NULL;
e829b0bb 1875
7191f208 1876 iscsi_modesense_sync(iscsilun);
4df863f3
EB
1877 if (iscsilun->dpofua) {
1878 bs->supported_write_flags = BDRV_REQ_FUA;
1879 }
7191f208 1880
c1d4096b
FZ
1881 /* Check the write protect flag of the LUN if we want to write */
1882 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
43ae8fb1 1883 iscsilun->write_protected) {
c1d4096b
FZ
1884 error_setg(errp, "Cannot open a write protected LUN as read-write");
1885 ret = -EACCES;
1886 goto out;
1887 }
1888
f2917853
PB
1889 iscsi_readcapacity_sync(iscsilun, &local_err);
1890 if (local_err != NULL) {
1891 error_propagate(errp, local_err);
cd82b6fb 1892 ret = -EINVAL;
cb1b83e7 1893 goto out;
e829b0bb 1894 }
0777b5dd 1895 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
e829b0bb 1896
f47c3f5a
KW
1897 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1898 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1899 * will try to read from the device to guess the image format.
622695a4 1900 */
f47c3f5a 1901 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
54115412 1902 bs->sg = true;
622695a4
RS
1903 }
1904
24d3bd67
PL
1905 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1906 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1907 (void **) &inq_vpd, errp);
1908 if (task == NULL) {
1909 ret = -EINVAL;
1910 goto out;
f18a7cbb 1911 }
24d3bd67
PL
1912 for (i = 0; i < inq_vpd->num_pages; i++) {
1913 struct scsi_task *inq_task;
1914 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
f18a7cbb 1915 struct scsi_inquiry_block_limits *inq_bl;
24d3bd67
PL
1916 switch (inq_vpd->pages[i]) {
1917 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1918 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1919 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1920 (void **) &inq_lbp, errp);
1921 if (inq_task == NULL) {
1922 ret = -EINVAL;
1923 goto out;
1924 }
1925 memcpy(&iscsilun->lbp, inq_lbp,
1926 sizeof(struct scsi_inquiry_logical_block_provisioning));
1927 scsi_free_scsi_task(inq_task);
1928 break;
1929 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1930 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1931 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1932 (void **) &inq_bl, errp);
1933 if (inq_task == NULL) {
1934 ret = -EINVAL;
1935 goto out;
1936 }
1937 memcpy(&iscsilun->bl, inq_bl,
1938 sizeof(struct scsi_inquiry_block_limits));
1939 scsi_free_scsi_task(inq_task);
1940 break;
1941 default:
1942 break;
f18a7cbb 1943 }
f18a7cbb 1944 }
24d3bd67
PL
1945 scsi_free_scsi_task(task);
1946 task = NULL;
f18a7cbb 1947
d045c466 1948 qemu_mutex_init(&iscsilun->mutex);
80cf6257 1949 iscsi_attach_aio_context(bs, iscsilun->aio_context);
5b5d34ec 1950
b03c3805
PL
1951 /* Guess the internal cluster (page) size of the iscsi target by the means
1952 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1953 * reasonable size */
3d2acaa3 1954 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
b03c3805
PL
1955 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1956 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1957 iscsilun->block_size) >> BDRV_SECTOR_BITS;
9eac3622 1958 if (iscsilun->lbprz) {
e1123a3b 1959 ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
b03c3805 1960 }
b03c3805
PL
1961 }
1962
e24d813b
EB
1963 if (iscsilun->lbprz && iscsilun->lbp.lbpws) {
1964 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1965 }
1966
b93c94f7 1967out:
60beb341 1968 qemu_opts_del(opts);
f7047c2d 1969 g_free(initiator_name);
e829b0bb
PL
1970 if (task != NULL) {
1971 scsi_free_scsi_task(task);
1972 }
b93c94f7
PB
1973
1974 if (ret) {
1975 if (iscsi != NULL) {
20474e9a
PL
1976 if (iscsi_is_logged_in(iscsi)) {
1977 iscsi_logout_sync(iscsi);
1978 }
b93c94f7
PB
1979 iscsi_destroy_context(iscsi);
1980 }
1981 memset(iscsilun, 0, sizeof(IscsiLun));
c589b249 1982 }
5c3ad1a6 1983exit:
c589b249
RS
1984 return ret;
1985}
1986
1987static void iscsi_close(BlockDriverState *bs)
1988{
1989 IscsiLun *iscsilun = bs->opaque;
1990 struct iscsi_context *iscsi = iscsilun->iscsi;
1991
80cf6257 1992 iscsi_detach_aio_context(bs);
20474e9a
PL
1993 if (iscsi_is_logged_in(iscsi)) {
1994 iscsi_logout_sync(iscsi);
1995 }
c589b249 1996 iscsi_destroy_context(iscsi);
d4cd9615 1997 g_free(iscsilun->zeroblock);
e1123a3b 1998 iscsi_allocmap_free(iscsilun);
d045c466 1999 qemu_mutex_destroy(&iscsilun->mutex);
c589b249
RS
2000 memset(iscsilun, 0, sizeof(IscsiLun));
2001}
2002
52f6fa14
PL
2003static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
2004{
d34682cd
KW
2005 /* We don't actually refresh here, but just return data queried in
2006 * iscsi_open(): iscsi targets don't change their limits. */
52f6fa14
PL
2007
2008 IscsiLun *iscsilun = bs->opaque;
5def6b80 2009 uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
95eaa785 2010 unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
52f6fa14 2011
95eaa785
EB
2012 assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
2013
2014 bs->bl.request_alignment = block_size;
c8b3b998 2015
52f6fa14
PL
2016 if (iscsilun->bl.max_xfer_len) {
2017 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
2018 }
2019
95eaa785 2020 if (max_xfer_len * block_size < INT_MAX) {
5def6b80
EB
2021 bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
2022 }
52f6fa14 2023
c97ca29d 2024 if (iscsilun->lbp.lbpu) {
95eaa785 2025 if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
b9f7855a
EB
2026 bs->bl.max_pdiscard =
2027 iscsilun->bl.max_unmap * iscsilun->block_size;
d34682cd 2028 }
b9f7855a
EB
2029 bs->bl.pdiscard_alignment =
2030 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
8b184744 2031 } else {
b9f7855a 2032 bs->bl.pdiscard_alignment = iscsilun->block_size;
c97ca29d 2033 }
d34682cd 2034
95eaa785 2035 if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
cf081fca
EB
2036 bs->bl.max_pwrite_zeroes =
2037 iscsilun->bl.max_ws_len * iscsilun->block_size;
c97ca29d
PB
2038 }
2039 if (iscsilun->lbp.lbpws) {
cf081fca
EB
2040 bs->bl.pwrite_zeroes_alignment =
2041 iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
8b184744 2042 } else {
cf081fca 2043 bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
d34682cd 2044 }
5def6b80 2045 if (iscsilun->bl.opt_xfer_len &&
95eaa785 2046 iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
5def6b80
EB
2047 bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
2048 iscsilun->block_size);
2049 }
e9f526ab 2050}
d34682cd 2051
43ae8fb1
FZ
2052/* Note that this will not re-establish a connection with an iSCSI target - it
2053 * is effectively a NOP. */
dc6afb99
JC
2054static int iscsi_reopen_prepare(BDRVReopenState *state,
2055 BlockReopenQueue *queue, Error **errp)
2056{
43ae8fb1
FZ
2057 IscsiLun *iscsilun = state->bs->opaque;
2058
2059 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
2060 error_setg(errp, "Cannot open a write protected LUN as read-write");
2061 return -EACCES;
2062 }
d34682cd
KW
2063 return 0;
2064}
2065
e1123a3b
PL
2066static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
2067{
2068 IscsiLun *iscsilun = reopen_state->bs->opaque;
2069
2070 /* the cache.direct status might have changed */
2071 if (iscsilun->allocmap != NULL) {
2072 iscsi_allocmap_init(iscsilun, reopen_state->flags);
2073 }
2074}
2075
8243ccb7
HR
2076static int iscsi_truncate(BlockDriverState *bs, int64_t offset,
2077 PreallocMode prealloc, Error **errp)
cb1b83e7
PL
2078{
2079 IscsiLun *iscsilun = bs->opaque;
f2917853 2080 Error *local_err = NULL;
cb1b83e7 2081
8243ccb7
HR
2082 if (prealloc != PREALLOC_MODE_OFF) {
2083 error_setg(errp, "Unsupported preallocation mode '%s'",
977c736f 2084 PreallocMode_str(prealloc));
8243ccb7
HR
2085 return -ENOTSUP;
2086 }
2087
cb1b83e7 2088 if (iscsilun->type != TYPE_DISK) {
f59adb32 2089 error_setg(errp, "Cannot resize non-disk iSCSI devices");
cb1b83e7
PL
2090 return -ENOTSUP;
2091 }
2092
f2917853
PB
2093 iscsi_readcapacity_sync(iscsilun, &local_err);
2094 if (local_err != NULL) {
4bff28b8 2095 error_propagate(errp, local_err);
f2917853 2096 return -EIO;
cb1b83e7
PL
2097 }
2098
2099 if (offset > iscsi_getlength(bs)) {
f59adb32 2100 error_setg(errp, "Cannot grow iSCSI devices");
cb1b83e7
PL
2101 return -EINVAL;
2102 }
2103
e1123a3b
PL
2104 if (iscsilun->allocmap != NULL) {
2105 iscsi_allocmap_init(iscsilun, bs->open_flags);
b03c3805
PL
2106 }
2107
cb1b83e7
PL
2108 return 0;
2109}
2110
a59479e3 2111static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
de8864e5
PL
2112{
2113 int ret = 0;
2114 int64_t total_size = 0;
13c91cb7 2115 BlockDriverState *bs;
de8864e5 2116 IscsiLun *iscsilun = NULL;
60beb341 2117 QDict *bs_options;
2ec9a782 2118 Error *local_err = NULL;
de8864e5 2119
e4e9986b 2120 bs = bdrv_new();
de8864e5
PL
2121
2122 /* Read out options */
c2eb918e
HT
2123 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2124 BDRV_SECTOR_SIZE);
5839e53b 2125 bs->opaque = g_new0(struct IscsiLun, 1);
13c91cb7 2126 iscsilun = bs->opaque;
de8864e5 2127
60beb341 2128 bs_options = qdict_new();
2ec9a782
FZ
2129 iscsi_parse_filename(filename, bs_options, &local_err);
2130 if (local_err) {
2131 error_propagate(errp, local_err);
2132 ret = -EINVAL;
2133 } else {
2134 ret = iscsi_open(bs, bs_options, 0, NULL);
2135 }
60beb341
KW
2136 QDECREF(bs_options);
2137
de8864e5
PL
2138 if (ret != 0) {
2139 goto out;
2140 }
80cf6257 2141 iscsi_detach_aio_context(bs);
de8864e5
PL
2142 if (iscsilun->type != TYPE_DISK) {
2143 ret = -ENODEV;
2144 goto out;
2145 }
13c91cb7 2146 if (bs->total_sectors < total_size) {
de8864e5 2147 ret = -ENOSPC;
d3bda7bc 2148 goto out;
de8864e5
PL
2149 }
2150
2151 ret = 0;
2152out:
2153 if (iscsilun->iscsi != NULL) {
2154 iscsi_destroy_context(iscsilun->iscsi);
2155 }
13c91cb7
FZ
2156 g_free(bs->opaque);
2157 bs->opaque = NULL;
4f6fd349 2158 bdrv_unref(bs);
de8864e5
PL
2159 return ret;
2160}
2161
186d4f2b
PL
2162static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2163{
2164 IscsiLun *iscsilun = bs->opaque;
0a386e48 2165 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
b03c3805 2166 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
186d4f2b
PL
2167 return 0;
2168}
2169
e1123a3b
PL
2170static void iscsi_invalidate_cache(BlockDriverState *bs,
2171 Error **errp)
2172{
2173 IscsiLun *iscsilun = bs->opaque;
2174 iscsi_allocmap_invalidate(iscsilun);
2175}
2176
a59479e3
CL
2177static QemuOptsList iscsi_create_opts = {
2178 .name = "iscsi-create-opts",
2179 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2180 .desc = {
2181 {
2182 .name = BLOCK_OPT_SIZE,
2183 .type = QEMU_OPT_SIZE,
2184 .help = "Virtual disk size"
2185 },
2186 { /* end of list */ }
2187 }
de8864e5
PL
2188};
2189
c589b249
RS
2190static BlockDriver bdrv_iscsi = {
2191 .format_name = "iscsi",
2192 .protocol_name = "iscsi",
2193
d5895fcb
KW
2194 .instance_size = sizeof(IscsiLun),
2195 .bdrv_parse_filename = iscsi_parse_filename,
2196 .bdrv_file_open = iscsi_open,
2197 .bdrv_close = iscsi_close,
2198 .bdrv_create = iscsi_create,
2199 .create_opts = &iscsi_create_opts,
2200 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2201 .bdrv_reopen_commit = iscsi_reopen_commit,
2202 .bdrv_invalidate_cache = iscsi_invalidate_cache,
c589b249
RS
2203
2204 .bdrv_getlength = iscsi_getlength,
186d4f2b 2205 .bdrv_get_info = iscsi_get_info,
cb1b83e7 2206 .bdrv_truncate = iscsi_truncate,
d34682cd 2207 .bdrv_refresh_limits = iscsi_refresh_limits,
c589b249 2208
54a5c1d5 2209 .bdrv_co_get_block_status = iscsi_co_get_block_status,
97c7e85c 2210 .bdrv_co_pdiscard = iscsi_co_pdiscard,
94d047a3 2211 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
063c3378 2212 .bdrv_co_readv = iscsi_co_readv,
9f0eb9e1 2213 .bdrv_co_writev_flags = iscsi_co_writev_flags,
063c3378 2214 .bdrv_co_flush_to_disk = iscsi_co_flush,
fa6acb0c 2215
98392453 2216#ifdef __linux__
98392453
RS
2217 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2218#endif
80cf6257
SH
2219
2220 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2221 .bdrv_attach_aio_context = iscsi_attach_aio_context,
c589b249
RS
2222};
2223
e0ae4987
RS
2224#if LIBISCSI_API_VERSION >= (20160603)
2225static BlockDriver bdrv_iser = {
2226 .format_name = "iser",
2227 .protocol_name = "iser",
2228
d5895fcb
KW
2229 .instance_size = sizeof(IscsiLun),
2230 .bdrv_parse_filename = iscsi_parse_filename,
2231 .bdrv_file_open = iscsi_open,
2232 .bdrv_close = iscsi_close,
2233 .bdrv_create = iscsi_create,
2234 .create_opts = &iscsi_create_opts,
2235 .bdrv_reopen_prepare = iscsi_reopen_prepare,
2236 .bdrv_reopen_commit = iscsi_reopen_commit,
2237 .bdrv_invalidate_cache = iscsi_invalidate_cache,
e0ae4987
RS
2238
2239 .bdrv_getlength = iscsi_getlength,
2240 .bdrv_get_info = iscsi_get_info,
2241 .bdrv_truncate = iscsi_truncate,
2242 .bdrv_refresh_limits = iscsi_refresh_limits,
2243
2244 .bdrv_co_get_block_status = iscsi_co_get_block_status,
2245 .bdrv_co_pdiscard = iscsi_co_pdiscard,
2246 .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2247 .bdrv_co_readv = iscsi_co_readv,
2248 .bdrv_co_writev_flags = iscsi_co_writev_flags,
2249 .bdrv_co_flush_to_disk = iscsi_co_flush,
2250
2251#ifdef __linux__
2252 .bdrv_aio_ioctl = iscsi_aio_ioctl,
2253#endif
2254
2255 .bdrv_detach_aio_context = iscsi_detach_aio_context,
2256 .bdrv_attach_aio_context = iscsi_attach_aio_context,
2257};
2258#endif
2259
c589b249
RS
2260static void iscsi_block_init(void)
2261{
2262 bdrv_register(&bdrv_iscsi);
e0ae4987
RS
2263#if LIBISCSI_API_VERSION >= (20160603)
2264 bdrv_register(&bdrv_iser);
2265#endif
c589b249
RS
2266}
2267
2268block_init(iscsi_block_init);