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