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