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