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