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