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