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