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