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