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