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