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