xref: /openbmc/qemu/block/iscsi.c (revision 4a09d0bb)
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         if (nb_cls_shrunk > 0) {
503             bitmap_clear(iscsilun->allocmap, cl_num_shrunk, nb_cls_shrunk);
504         }
505     }
506 
507     if (iscsilun->allocmap_valid == NULL) {
508         return;
509     }
510     if (valid) {
511         if (nb_cls_shrunk > 0) {
512             bitmap_set(iscsilun->allocmap_valid, cl_num_shrunk, nb_cls_shrunk);
513         }
514     } else {
515         bitmap_clear(iscsilun->allocmap_valid, cl_num_expanded,
516                      nb_cls_expanded);
517     }
518 }
519 
520 static void
521 iscsi_allocmap_set_allocated(IscsiLun *iscsilun, int64_t sector_num,
522                              int nb_sectors)
523 {
524     iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, true, true);
525 }
526 
527 static void
528 iscsi_allocmap_set_unallocated(IscsiLun *iscsilun, int64_t sector_num,
529                                int nb_sectors)
530 {
531     /* Note: if cache.direct=on the fifth argument to iscsi_allocmap_update
532      * is ignored, so this will in effect be an iscsi_allocmap_set_invalid.
533      */
534     iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, true);
535 }
536 
537 static void iscsi_allocmap_set_invalid(IscsiLun *iscsilun, int64_t sector_num,
538                                        int nb_sectors)
539 {
540     iscsi_allocmap_update(iscsilun, sector_num, nb_sectors, false, false);
541 }
542 
543 static void iscsi_allocmap_invalidate(IscsiLun *iscsilun)
544 {
545     if (iscsilun->allocmap) {
546         bitmap_zero(iscsilun->allocmap, iscsilun->allocmap_size);
547     }
548     if (iscsilun->allocmap_valid) {
549         bitmap_zero(iscsilun->allocmap_valid, iscsilun->allocmap_size);
550     }
551 }
552 
553 static inline bool
554 iscsi_allocmap_is_allocated(IscsiLun *iscsilun, int64_t sector_num,
555                             int nb_sectors)
556 {
557     unsigned long size;
558     if (iscsilun->allocmap == NULL) {
559         return true;
560     }
561     size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
562     return !(find_next_bit(iscsilun->allocmap, size,
563                            sector_num / iscsilun->cluster_sectors) == size);
564 }
565 
566 static inline bool iscsi_allocmap_is_valid(IscsiLun *iscsilun,
567                                            int64_t sector_num, int nb_sectors)
568 {
569     unsigned long size;
570     if (iscsilun->allocmap_valid == NULL) {
571         return false;
572     }
573     size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
574     return (find_next_zero_bit(iscsilun->allocmap_valid, size,
575                                sector_num / iscsilun->cluster_sectors) == size);
576 }
577 
578 static int coroutine_fn
579 iscsi_co_writev_flags(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
580                       QEMUIOVector *iov, int flags)
581 {
582     IscsiLun *iscsilun = bs->opaque;
583     struct IscsiTask iTask;
584     uint64_t lba;
585     uint32_t num_sectors;
586     bool fua = flags & BDRV_REQ_FUA;
587 
588     if (fua) {
589         assert(iscsilun->dpofua);
590     }
591     if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
592         return -EINVAL;
593     }
594 
595     if (bs->bl.max_transfer) {
596         assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
597     }
598 
599     lba = sector_qemu2lun(sector_num, iscsilun);
600     num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
601     iscsi_co_init_iscsitask(iscsilun, &iTask);
602 retry:
603     if (iscsilun->use_16_for_rw) {
604 #if LIBISCSI_API_VERSION >= (20160603)
605         iTask.task = iscsi_write16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
606                                             NULL, num_sectors * iscsilun->block_size,
607                                             iscsilun->block_size, 0, 0, fua, 0, 0,
608                                             iscsi_co_generic_cb, &iTask,
609                                             (struct scsi_iovec *)iov->iov, iov->niov);
610     } else {
611         iTask.task = iscsi_write10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
612                                             NULL, num_sectors * iscsilun->block_size,
613                                             iscsilun->block_size, 0, 0, fua, 0, 0,
614                                             iscsi_co_generic_cb, &iTask,
615                                             (struct scsi_iovec *)iov->iov, iov->niov);
616     }
617 #else
618         iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
619                                         NULL, num_sectors * iscsilun->block_size,
620                                         iscsilun->block_size, 0, 0, fua, 0, 0,
621                                         iscsi_co_generic_cb, &iTask);
622     } else {
623         iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
624                                         NULL, num_sectors * iscsilun->block_size,
625                                         iscsilun->block_size, 0, 0, fua, 0, 0,
626                                         iscsi_co_generic_cb, &iTask);
627     }
628 #endif
629     if (iTask.task == NULL) {
630         return -ENOMEM;
631     }
632 #if LIBISCSI_API_VERSION < (20160603)
633     scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
634                           iov->niov);
635 #endif
636     while (!iTask.complete) {
637         iscsi_set_events(iscsilun);
638         qemu_coroutine_yield();
639     }
640 
641     if (iTask.task != NULL) {
642         scsi_free_scsi_task(iTask.task);
643         iTask.task = NULL;
644     }
645 
646     if (iTask.do_retry) {
647         iTask.complete = 0;
648         goto retry;
649     }
650 
651     if (iTask.status != SCSI_STATUS_GOOD) {
652         iscsi_allocmap_set_invalid(iscsilun, sector_num, nb_sectors);
653         return iTask.err_code;
654     }
655 
656     iscsi_allocmap_set_allocated(iscsilun, sector_num, nb_sectors);
657 
658     return 0;
659 }
660 
661 
662 
663 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
664                                                   int64_t sector_num,
665                                                   int nb_sectors, int *pnum,
666                                                   BlockDriverState **file)
667 {
668     IscsiLun *iscsilun = bs->opaque;
669     struct scsi_get_lba_status *lbas = NULL;
670     struct scsi_lba_status_descriptor *lbasd = NULL;
671     struct IscsiTask iTask;
672     int64_t ret;
673 
674     iscsi_co_init_iscsitask(iscsilun, &iTask);
675 
676     if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
677         ret = -EINVAL;
678         goto out;
679     }
680 
681     /* default to all sectors allocated */
682     ret = BDRV_BLOCK_DATA;
683     ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
684     *pnum = nb_sectors;
685 
686     /* LUN does not support logical block provisioning */
687     if (!iscsilun->lbpme) {
688         goto out;
689     }
690 
691 retry:
692     if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
693                                   sector_qemu2lun(sector_num, iscsilun),
694                                   8 + 16, iscsi_co_generic_cb,
695                                   &iTask) == NULL) {
696         ret = -ENOMEM;
697         goto out;
698     }
699 
700     while (!iTask.complete) {
701         iscsi_set_events(iscsilun);
702         qemu_coroutine_yield();
703     }
704 
705     if (iTask.do_retry) {
706         if (iTask.task != NULL) {
707             scsi_free_scsi_task(iTask.task);
708             iTask.task = NULL;
709         }
710         iTask.complete = 0;
711         goto retry;
712     }
713 
714     if (iTask.status != SCSI_STATUS_GOOD) {
715         /* in case the get_lba_status_callout fails (i.e.
716          * because the device is busy or the cmd is not
717          * supported) we pretend all blocks are allocated
718          * for backwards compatibility */
719         goto out;
720     }
721 
722     lbas = scsi_datain_unmarshall(iTask.task);
723     if (lbas == NULL) {
724         ret = -EIO;
725         goto out;
726     }
727 
728     lbasd = &lbas->descriptors[0];
729 
730     if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
731         ret = -EIO;
732         goto out;
733     }
734 
735     *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
736 
737     if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
738         lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
739         ret &= ~BDRV_BLOCK_DATA;
740         if (iscsilun->lbprz) {
741             ret |= BDRV_BLOCK_ZERO;
742         }
743     }
744 
745     if (ret & BDRV_BLOCK_ZERO) {
746         iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);
747     } else {
748         iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);
749     }
750 
751     if (*pnum > nb_sectors) {
752         *pnum = nb_sectors;
753     }
754 out:
755     if (iTask.task != NULL) {
756         scsi_free_scsi_task(iTask.task);
757     }
758     if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
759         *file = bs;
760     }
761     return ret;
762 }
763 
764 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
765                                        int64_t sector_num, int nb_sectors,
766                                        QEMUIOVector *iov)
767 {
768     IscsiLun *iscsilun = bs->opaque;
769     struct IscsiTask iTask;
770     uint64_t lba;
771     uint32_t num_sectors;
772 
773     if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
774         return -EINVAL;
775     }
776 
777     if (bs->bl.max_transfer) {
778         assert(nb_sectors << BDRV_SECTOR_BITS <= bs->bl.max_transfer);
779     }
780 
781     /* if cache.direct is off and we have a valid entry in our allocation map
782      * we can skip checking the block status and directly return zeroes if
783      * the request falls within an unallocated area */
784     if (iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
785         !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
786             qemu_iovec_memset(iov, 0, 0x00, iov->size);
787             return 0;
788     }
789 
790     if (nb_sectors >= ISCSI_CHECKALLOC_THRES &&
791         !iscsi_allocmap_is_valid(iscsilun, sector_num, nb_sectors) &&
792         !iscsi_allocmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
793         int pnum;
794         BlockDriverState *file;
795         /* check the block status from the beginning of the cluster
796          * containing the start sector */
797         int64_t ret = iscsi_co_get_block_status(bs,
798                           sector_num - sector_num % iscsilun->cluster_sectors,
799                           BDRV_REQUEST_MAX_SECTORS, &pnum, &file);
800         if (ret < 0) {
801             return ret;
802         }
803         /* if the whole request falls into an unallocated area we can avoid
804          * to read and directly return zeroes instead */
805         if (ret & BDRV_BLOCK_ZERO &&
806             pnum >= nb_sectors + sector_num % iscsilun->cluster_sectors) {
807             qemu_iovec_memset(iov, 0, 0x00, iov->size);
808             return 0;
809         }
810     }
811 
812     lba = sector_qemu2lun(sector_num, iscsilun);
813     num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
814 
815     iscsi_co_init_iscsitask(iscsilun, &iTask);
816 retry:
817     if (iscsilun->use_16_for_rw) {
818 #if LIBISCSI_API_VERSION >= (20160603)
819         iTask.task = iscsi_read16_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
820                                            num_sectors * iscsilun->block_size,
821                                            iscsilun->block_size, 0, 0, 0, 0, 0,
822                                            iscsi_co_generic_cb, &iTask,
823                                            (struct scsi_iovec *)iov->iov, iov->niov);
824     } else {
825         iTask.task = iscsi_read10_iov_task(iscsilun->iscsi, iscsilun->lun, lba,
826                                            num_sectors * iscsilun->block_size,
827                                            iscsilun->block_size,
828                                            0, 0, 0, 0, 0,
829                                            iscsi_co_generic_cb, &iTask,
830                                            (struct scsi_iovec *)iov->iov, iov->niov);
831     }
832 #else
833         iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
834                                        num_sectors * iscsilun->block_size,
835                                        iscsilun->block_size, 0, 0, 0, 0, 0,
836                                        iscsi_co_generic_cb, &iTask);
837     } else {
838         iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
839                                        num_sectors * iscsilun->block_size,
840                                        iscsilun->block_size,
841                                        0, 0, 0, 0, 0,
842                                        iscsi_co_generic_cb, &iTask);
843     }
844 #endif
845     if (iTask.task == NULL) {
846         return -ENOMEM;
847     }
848 #if LIBISCSI_API_VERSION < (20160603)
849     scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
850 #endif
851     while (!iTask.complete) {
852         iscsi_set_events(iscsilun);
853         qemu_coroutine_yield();
854     }
855 
856     if (iTask.task != NULL) {
857         scsi_free_scsi_task(iTask.task);
858         iTask.task = NULL;
859     }
860 
861     if (iTask.do_retry) {
862         iTask.complete = 0;
863         goto retry;
864     }
865 
866     if (iTask.status != SCSI_STATUS_GOOD) {
867         return iTask.err_code;
868     }
869 
870     return 0;
871 }
872 
873 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
874 {
875     IscsiLun *iscsilun = bs->opaque;
876     struct IscsiTask iTask;
877 
878     iscsi_co_init_iscsitask(iscsilun, &iTask);
879 retry:
880     if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
881                                       0, iscsi_co_generic_cb, &iTask) == NULL) {
882         return -ENOMEM;
883     }
884 
885     while (!iTask.complete) {
886         iscsi_set_events(iscsilun);
887         qemu_coroutine_yield();
888     }
889 
890     if (iTask.task != NULL) {
891         scsi_free_scsi_task(iTask.task);
892         iTask.task = NULL;
893     }
894 
895     if (iTask.do_retry) {
896         iTask.complete = 0;
897         goto retry;
898     }
899 
900     if (iTask.status != SCSI_STATUS_GOOD) {
901         return iTask.err_code;
902     }
903 
904     return 0;
905 }
906 
907 #ifdef __linux__
908 static void
909 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
910                      void *command_data, void *opaque)
911 {
912     IscsiAIOCB *acb = opaque;
913 
914     g_free(acb->buf);
915     acb->buf = NULL;
916 
917     acb->status = 0;
918     if (status < 0) {
919         error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
920                      iscsi_get_error(iscsi));
921         acb->status = iscsi_translate_sense(&acb->task->sense);
922     }
923 
924     acb->ioh->driver_status = 0;
925     acb->ioh->host_status   = 0;
926     acb->ioh->resid         = 0;
927     acb->ioh->status        = status;
928 
929 #define SG_ERR_DRIVER_SENSE    0x08
930 
931     if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
932         int ss;
933 
934         acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
935 
936         acb->ioh->sb_len_wr = acb->task->datain.size - 2;
937         ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
938              acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
939         memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
940     }
941 
942     iscsi_schedule_bh(acb);
943 }
944 
945 static void iscsi_ioctl_bh_completion(void *opaque)
946 {
947     IscsiAIOCB *acb = opaque;
948 
949     qemu_bh_delete(acb->bh);
950     acb->common.cb(acb->common.opaque, acb->ret);
951     qemu_aio_unref(acb);
952 }
953 
954 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
955 {
956     BlockDriverState *bs = acb->common.bs;
957     IscsiLun *iscsilun = bs->opaque;
958     int ret = 0;
959 
960     switch (req) {
961     case SG_GET_VERSION_NUM:
962         *(int *)buf = 30000;
963         break;
964     case SG_GET_SCSI_ID:
965         ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
966         break;
967     default:
968         ret = -EINVAL;
969     }
970     assert(!acb->bh);
971     acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
972                          iscsi_ioctl_bh_completion, acb);
973     acb->ret = ret;
974     qemu_bh_schedule(acb->bh);
975 }
976 
977 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
978         unsigned long int req, void *buf,
979         BlockCompletionFunc *cb, void *opaque)
980 {
981     IscsiLun *iscsilun = bs->opaque;
982     struct iscsi_context *iscsi = iscsilun->iscsi;
983     struct iscsi_data data;
984     IscsiAIOCB *acb;
985 
986     acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
987 
988     acb->iscsilun = iscsilun;
989     acb->bh          = NULL;
990     acb->status      = -EINPROGRESS;
991     acb->buf         = NULL;
992     acb->ioh         = buf;
993 
994     if (req != SG_IO) {
995         iscsi_ioctl_handle_emulated(acb, req, buf);
996         return &acb->common;
997     }
998 
999     if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
1000         error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
1001                      acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
1002         qemu_aio_unref(acb);
1003         return NULL;
1004     }
1005 
1006     acb->task = malloc(sizeof(struct scsi_task));
1007     if (acb->task == NULL) {
1008         error_report("iSCSI: Failed to allocate task for scsi command. %s",
1009                      iscsi_get_error(iscsi));
1010         qemu_aio_unref(acb);
1011         return NULL;
1012     }
1013     memset(acb->task, 0, sizeof(struct scsi_task));
1014 
1015     switch (acb->ioh->dxfer_direction) {
1016     case SG_DXFER_TO_DEV:
1017         acb->task->xfer_dir = SCSI_XFER_WRITE;
1018         break;
1019     case SG_DXFER_FROM_DEV:
1020         acb->task->xfer_dir = SCSI_XFER_READ;
1021         break;
1022     default:
1023         acb->task->xfer_dir = SCSI_XFER_NONE;
1024         break;
1025     }
1026 
1027     acb->task->cdb_size = acb->ioh->cmd_len;
1028     memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
1029     acb->task->expxferlen = acb->ioh->dxfer_len;
1030 
1031     data.size = 0;
1032     if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
1033         if (acb->ioh->iovec_count == 0) {
1034             data.data = acb->ioh->dxferp;
1035             data.size = acb->ioh->dxfer_len;
1036         } else {
1037             scsi_task_set_iov_out(acb->task,
1038                                  (struct scsi_iovec *) acb->ioh->dxferp,
1039                                  acb->ioh->iovec_count);
1040         }
1041     }
1042 
1043     if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
1044                                  iscsi_aio_ioctl_cb,
1045                                  (data.size > 0) ? &data : NULL,
1046                                  acb) != 0) {
1047         scsi_free_scsi_task(acb->task);
1048         qemu_aio_unref(acb);
1049         return NULL;
1050     }
1051 
1052     /* tell libiscsi to read straight into the buffer we got from ioctl */
1053     if (acb->task->xfer_dir == SCSI_XFER_READ) {
1054         if (acb->ioh->iovec_count == 0) {
1055             scsi_task_add_data_in_buffer(acb->task,
1056                                          acb->ioh->dxfer_len,
1057                                          acb->ioh->dxferp);
1058         } else {
1059             scsi_task_set_iov_in(acb->task,
1060                                  (struct scsi_iovec *) acb->ioh->dxferp,
1061                                  acb->ioh->iovec_count);
1062         }
1063     }
1064 
1065     iscsi_set_events(iscsilun);
1066 
1067     return &acb->common;
1068 }
1069 
1070 #endif
1071 
1072 static int64_t
1073 iscsi_getlength(BlockDriverState *bs)
1074 {
1075     IscsiLun *iscsilun = bs->opaque;
1076     int64_t len;
1077 
1078     len  = iscsilun->num_blocks;
1079     len *= iscsilun->block_size;
1080 
1081     return len;
1082 }
1083 
1084 static int
1085 coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int count)
1086 {
1087     IscsiLun *iscsilun = bs->opaque;
1088     struct IscsiTask iTask;
1089     struct unmap_list list;
1090 
1091     if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {
1092         return -ENOTSUP;
1093     }
1094 
1095     if (!iscsilun->lbp.lbpu) {
1096         /* UNMAP is not supported by the target */
1097         return 0;
1098     }
1099 
1100     list.lba = offset / iscsilun->block_size;
1101     list.num = count / iscsilun->block_size;
1102 
1103     iscsi_co_init_iscsitask(iscsilun, &iTask);
1104 retry:
1105     if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
1106                          iscsi_co_generic_cb, &iTask) == NULL) {
1107         return -ENOMEM;
1108     }
1109 
1110     while (!iTask.complete) {
1111         iscsi_set_events(iscsilun);
1112         qemu_coroutine_yield();
1113     }
1114 
1115     if (iTask.task != NULL) {
1116         scsi_free_scsi_task(iTask.task);
1117         iTask.task = NULL;
1118     }
1119 
1120     if (iTask.do_retry) {
1121         iTask.complete = 0;
1122         goto retry;
1123     }
1124 
1125     if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
1126         /* the target might fail with a check condition if it
1127            is not happy with the alignment of the UNMAP request
1128            we silently fail in this case */
1129         return 0;
1130     }
1131 
1132     if (iTask.status != SCSI_STATUS_GOOD) {
1133         return iTask.err_code;
1134     }
1135 
1136     iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1137                                count >> BDRV_SECTOR_BITS);
1138 
1139     return 0;
1140 }
1141 
1142 static int
1143 coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1144                                     int count, BdrvRequestFlags flags)
1145 {
1146     IscsiLun *iscsilun = bs->opaque;
1147     struct IscsiTask iTask;
1148     uint64_t lba;
1149     uint32_t nb_blocks;
1150     bool use_16_for_ws = iscsilun->use_16_for_rw;
1151 
1152     if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {
1153         return -ENOTSUP;
1154     }
1155 
1156     if (flags & BDRV_REQ_MAY_UNMAP) {
1157         if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
1158             /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
1159             use_16_for_ws = true;
1160         }
1161         if (use_16_for_ws && !iscsilun->lbp.lbpws) {
1162             /* WRITESAME16 with UNMAP is not supported by the target,
1163              * fall back and try WRITESAME10/16 without UNMAP */
1164             flags &= ~BDRV_REQ_MAY_UNMAP;
1165             use_16_for_ws = iscsilun->use_16_for_rw;
1166         }
1167     }
1168 
1169     if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1170         /* WRITESAME without UNMAP is not supported by the target */
1171         return -ENOTSUP;
1172     }
1173 
1174     lba = offset / iscsilun->block_size;
1175     nb_blocks = count / iscsilun->block_size;
1176 
1177     if (iscsilun->zeroblock == NULL) {
1178         iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1179         if (iscsilun->zeroblock == NULL) {
1180             return -ENOMEM;
1181         }
1182     }
1183 
1184     iscsi_co_init_iscsitask(iscsilun, &iTask);
1185 retry:
1186     if (use_16_for_ws) {
1187         iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1188                                             iscsilun->zeroblock, iscsilun->block_size,
1189                                             nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1190                                             0, 0, iscsi_co_generic_cb, &iTask);
1191     } else {
1192         iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1193                                             iscsilun->zeroblock, iscsilun->block_size,
1194                                             nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1195                                             0, 0, iscsi_co_generic_cb, &iTask);
1196     }
1197     if (iTask.task == NULL) {
1198         return -ENOMEM;
1199     }
1200 
1201     while (!iTask.complete) {
1202         iscsi_set_events(iscsilun);
1203         qemu_coroutine_yield();
1204     }
1205 
1206     if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1207         iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1208         (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1209          iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1210         /* WRITE SAME is not supported by the target */
1211         iscsilun->has_write_same = false;
1212         scsi_free_scsi_task(iTask.task);
1213         return -ENOTSUP;
1214     }
1215 
1216     if (iTask.task != NULL) {
1217         scsi_free_scsi_task(iTask.task);
1218         iTask.task = NULL;
1219     }
1220 
1221     if (iTask.do_retry) {
1222         iTask.complete = 0;
1223         goto retry;
1224     }
1225 
1226     if (iTask.status != SCSI_STATUS_GOOD) {
1227         iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1228                                    count >> BDRV_SECTOR_BITS);
1229         return iTask.err_code;
1230     }
1231 
1232     if (flags & BDRV_REQ_MAY_UNMAP) {
1233         iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,
1234                                    count >> BDRV_SECTOR_BITS);
1235     } else {
1236         iscsi_allocmap_set_allocated(iscsilun, offset >> BDRV_SECTOR_BITS,
1237                                      count >> BDRV_SECTOR_BITS);
1238     }
1239 
1240     return 0;
1241 }
1242 
1243 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1244                        Error **errp)
1245 {
1246     QemuOptsList *list;
1247     QemuOpts *opts;
1248     const char *user = NULL;
1249     const char *password = NULL;
1250     const char *secretid;
1251     char *secret = NULL;
1252 
1253     list = qemu_find_opts("iscsi");
1254     if (!list) {
1255         return;
1256     }
1257 
1258     opts = qemu_opts_find(list, target);
1259     if (opts == NULL) {
1260         opts = QTAILQ_FIRST(&list->head);
1261         if (!opts) {
1262             return;
1263         }
1264     }
1265 
1266     user = qemu_opt_get(opts, "user");
1267     if (!user) {
1268         return;
1269     }
1270 
1271     secretid = qemu_opt_get(opts, "password-secret");
1272     password = qemu_opt_get(opts, "password");
1273     if (secretid && password) {
1274         error_setg(errp, "'password' and 'password-secret' properties are "
1275                    "mutually exclusive");
1276         return;
1277     }
1278     if (secretid) {
1279         secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1280         if (!secret) {
1281             return;
1282         }
1283         password = secret;
1284     } else if (!password) {
1285         error_setg(errp, "CHAP username specified but no password was given");
1286         return;
1287     }
1288 
1289     if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1290         error_setg(errp, "Failed to set initiator username and password");
1291     }
1292 
1293     g_free(secret);
1294 }
1295 
1296 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1297                                 Error **errp)
1298 {
1299     QemuOptsList *list;
1300     QemuOpts *opts;
1301     const char *digest = NULL;
1302 
1303     list = qemu_find_opts("iscsi");
1304     if (!list) {
1305         return;
1306     }
1307 
1308     opts = qemu_opts_find(list, target);
1309     if (opts == NULL) {
1310         opts = QTAILQ_FIRST(&list->head);
1311         if (!opts) {
1312             return;
1313         }
1314     }
1315 
1316     digest = qemu_opt_get(opts, "header-digest");
1317     if (!digest) {
1318         return;
1319     }
1320 
1321     if (!strcmp(digest, "CRC32C")) {
1322         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1323     } else if (!strcmp(digest, "NONE")) {
1324         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1325     } else if (!strcmp(digest, "CRC32C-NONE")) {
1326         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1327     } else if (!strcmp(digest, "NONE-CRC32C")) {
1328         iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1329     } else {
1330         error_setg(errp, "Invalid header-digest setting : %s", digest);
1331     }
1332 }
1333 
1334 static char *parse_initiator_name(const char *target)
1335 {
1336     QemuOptsList *list;
1337     QemuOpts *opts;
1338     const char *name;
1339     char *iscsi_name;
1340     UuidInfo *uuid_info;
1341 
1342     list = qemu_find_opts("iscsi");
1343     if (list) {
1344         opts = qemu_opts_find(list, target);
1345         if (!opts) {
1346             opts = QTAILQ_FIRST(&list->head);
1347         }
1348         if (opts) {
1349             name = qemu_opt_get(opts, "initiator-name");
1350             if (name) {
1351                 return g_strdup(name);
1352             }
1353         }
1354     }
1355 
1356     uuid_info = qmp_query_uuid(NULL);
1357     if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1358         name = qemu_get_vm_name();
1359     } else {
1360         name = uuid_info->UUID;
1361     }
1362     iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1363                                  name ? ":" : "", name ? name : "");
1364     qapi_free_UuidInfo(uuid_info);
1365     return iscsi_name;
1366 }
1367 
1368 static int parse_timeout(const char *target)
1369 {
1370     QemuOptsList *list;
1371     QemuOpts *opts;
1372     const char *timeout;
1373 
1374     list = qemu_find_opts("iscsi");
1375     if (list) {
1376         opts = qemu_opts_find(list, target);
1377         if (!opts) {
1378             opts = QTAILQ_FIRST(&list->head);
1379         }
1380         if (opts) {
1381             timeout = qemu_opt_get(opts, "timeout");
1382             if (timeout) {
1383                 return atoi(timeout);
1384             }
1385         }
1386     }
1387 
1388     return 0;
1389 }
1390 
1391 static void iscsi_nop_timed_event(void *opaque)
1392 {
1393     IscsiLun *iscsilun = opaque;
1394 
1395     if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1396         error_report("iSCSI: NOP timeout. Reconnecting...");
1397         iscsilun->request_timed_out = true;
1398     } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1399         error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1400         return;
1401     }
1402 
1403     timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1404     iscsi_set_events(iscsilun);
1405 }
1406 
1407 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1408 {
1409     struct scsi_task *task = NULL;
1410     struct scsi_readcapacity10 *rc10 = NULL;
1411     struct scsi_readcapacity16 *rc16 = NULL;
1412     int retries = ISCSI_CMD_RETRIES;
1413 
1414     do {
1415         if (task != NULL) {
1416             scsi_free_scsi_task(task);
1417             task = NULL;
1418         }
1419 
1420         switch (iscsilun->type) {
1421         case TYPE_DISK:
1422             task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1423             if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1424                 rc16 = scsi_datain_unmarshall(task);
1425                 if (rc16 == NULL) {
1426                     error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1427                 } else {
1428                     iscsilun->block_size = rc16->block_length;
1429                     iscsilun->num_blocks = rc16->returned_lba + 1;
1430                     iscsilun->lbpme = !!rc16->lbpme;
1431                     iscsilun->lbprz = !!rc16->lbprz;
1432                     iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1433                 }
1434                 break;
1435             }
1436             if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1437                 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1438                 break;
1439             }
1440             /* Fall through and try READ CAPACITY(10) instead.  */
1441         case TYPE_ROM:
1442             task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1443             if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1444                 rc10 = scsi_datain_unmarshall(task);
1445                 if (rc10 == NULL) {
1446                     error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1447                 } else {
1448                     iscsilun->block_size = rc10->block_size;
1449                     if (rc10->lba == 0) {
1450                         /* blank disk loaded */
1451                         iscsilun->num_blocks = 0;
1452                     } else {
1453                         iscsilun->num_blocks = rc10->lba + 1;
1454                     }
1455                 }
1456             }
1457             break;
1458         default:
1459             return;
1460         }
1461     } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1462              && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1463              && retries-- > 0);
1464 
1465     if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1466         error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1467     } else if (!iscsilun->block_size ||
1468                iscsilun->block_size % BDRV_SECTOR_SIZE) {
1469         error_setg(errp, "iSCSI: the target returned an invalid "
1470                    "block size of %d.", iscsilun->block_size);
1471     }
1472     if (task) {
1473         scsi_free_scsi_task(task);
1474     }
1475 }
1476 
1477 /* TODO Convert to fine grained options */
1478 static QemuOptsList runtime_opts = {
1479     .name = "iscsi",
1480     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1481     .desc = {
1482         {
1483             .name = "filename",
1484             .type = QEMU_OPT_STRING,
1485             .help = "URL to the iscsi image",
1486         },
1487         { /* end of list */ }
1488     },
1489 };
1490 
1491 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1492                                           int evpd, int pc, void **inq, Error **errp)
1493 {
1494     int full_size;
1495     struct scsi_task *task = NULL;
1496     task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1497     if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1498         goto fail;
1499     }
1500     full_size = scsi_datain_getfullsize(task);
1501     if (full_size > task->datain.size) {
1502         scsi_free_scsi_task(task);
1503 
1504         /* we need more data for the full list */
1505         task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1506         if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1507             goto fail;
1508         }
1509     }
1510 
1511     *inq = scsi_datain_unmarshall(task);
1512     if (*inq == NULL) {
1513         error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1514         goto fail_with_err;
1515     }
1516 
1517     return task;
1518 
1519 fail:
1520     error_setg(errp, "iSCSI: Inquiry command failed : %s",
1521                iscsi_get_error(iscsi));
1522 fail_with_err:
1523     if (task != NULL) {
1524         scsi_free_scsi_task(task);
1525     }
1526     return NULL;
1527 }
1528 
1529 static void iscsi_detach_aio_context(BlockDriverState *bs)
1530 {
1531     IscsiLun *iscsilun = bs->opaque;
1532 
1533     aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1534                        false, NULL, NULL, NULL, NULL);
1535     iscsilun->events = 0;
1536 
1537     if (iscsilun->nop_timer) {
1538         timer_del(iscsilun->nop_timer);
1539         timer_free(iscsilun->nop_timer);
1540         iscsilun->nop_timer = NULL;
1541     }
1542     if (iscsilun->event_timer) {
1543         timer_del(iscsilun->event_timer);
1544         timer_free(iscsilun->event_timer);
1545         iscsilun->event_timer = NULL;
1546     }
1547 }
1548 
1549 static void iscsi_attach_aio_context(BlockDriverState *bs,
1550                                      AioContext *new_context)
1551 {
1552     IscsiLun *iscsilun = bs->opaque;
1553 
1554     iscsilun->aio_context = new_context;
1555     iscsi_set_events(iscsilun);
1556 
1557     /* Set up a timer for sending out iSCSI NOPs */
1558     iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1559                                         QEMU_CLOCK_REALTIME, SCALE_MS,
1560                                         iscsi_nop_timed_event, iscsilun);
1561     timer_mod(iscsilun->nop_timer,
1562               qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1563 
1564     /* Set up a timer for periodic calls to iscsi_set_events and to
1565      * scan for command timeout */
1566     iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1567                                           QEMU_CLOCK_REALTIME, SCALE_MS,
1568                                           iscsi_timed_check_events, iscsilun);
1569     timer_mod(iscsilun->event_timer,
1570               qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1571 }
1572 
1573 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1574 {
1575     struct scsi_task *task;
1576     struct scsi_mode_sense *ms = NULL;
1577     iscsilun->write_protected = false;
1578     iscsilun->dpofua = false;
1579 
1580     task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1581                                  1, SCSI_MODESENSE_PC_CURRENT,
1582                                  0x3F, 0, 255);
1583     if (task == NULL) {
1584         error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1585                      iscsi_get_error(iscsilun->iscsi));
1586         goto out;
1587     }
1588 
1589     if (task->status != SCSI_STATUS_GOOD) {
1590         error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1591         goto out;
1592     }
1593     ms = scsi_datain_unmarshall(task);
1594     if (!ms) {
1595         error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1596                      iscsi_get_error(iscsilun->iscsi));
1597         goto out;
1598     }
1599     iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1600     iscsilun->dpofua          = ms->device_specific_parameter & 0x10;
1601 
1602 out:
1603     if (task) {
1604         scsi_free_scsi_task(task);
1605     }
1606 }
1607 
1608 /*
1609  * We support iscsi url's on the form
1610  * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1611  */
1612 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1613                       Error **errp)
1614 {
1615     IscsiLun *iscsilun = bs->opaque;
1616     struct iscsi_context *iscsi = NULL;
1617     struct iscsi_url *iscsi_url = NULL;
1618     struct scsi_task *task = NULL;
1619     struct scsi_inquiry_standard *inq = NULL;
1620     struct scsi_inquiry_supported_pages *inq_vpd;
1621     char *initiator_name = NULL;
1622     QemuOpts *opts;
1623     Error *local_err = NULL;
1624     const char *filename;
1625     int i, ret = 0, timeout = 0;
1626 
1627     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1628     qemu_opts_absorb_qdict(opts, options, &local_err);
1629     if (local_err) {
1630         error_propagate(errp, local_err);
1631         ret = -EINVAL;
1632         goto out;
1633     }
1634 
1635     filename = qemu_opt_get(opts, "filename");
1636 
1637     iscsi_url = iscsi_parse_full_url(iscsi, filename);
1638     if (iscsi_url == NULL) {
1639         error_setg(errp, "Failed to parse URL : %s", filename);
1640         ret = -EINVAL;
1641         goto out;
1642     }
1643 
1644     memset(iscsilun, 0, sizeof(IscsiLun));
1645 
1646     initiator_name = parse_initiator_name(iscsi_url->target);
1647 
1648     iscsi = iscsi_create_context(initiator_name);
1649     if (iscsi == NULL) {
1650         error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1651         ret = -ENOMEM;
1652         goto out;
1653     }
1654 #if LIBISCSI_API_VERSION >= (20160603)
1655     if (iscsi_init_transport(iscsi, iscsi_url->transport)) {
1656         error_setg(errp, ("Error initializing transport."));
1657         ret = -EINVAL;
1658         goto out;
1659     }
1660 #endif
1661     if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1662         error_setg(errp, "iSCSI: Failed to set target name.");
1663         ret = -EINVAL;
1664         goto out;
1665     }
1666 
1667     if (iscsi_url->user[0] != '\0') {
1668         ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1669                                               iscsi_url->passwd);
1670         if (ret != 0) {
1671             error_setg(errp, "Failed to set initiator username and password");
1672             ret = -EINVAL;
1673             goto out;
1674         }
1675     }
1676 
1677     /* check if we got CHAP username/password via the options */
1678     parse_chap(iscsi, iscsi_url->target, &local_err);
1679     if (local_err != NULL) {
1680         error_propagate(errp, local_err);
1681         ret = -EINVAL;
1682         goto out;
1683     }
1684 
1685     if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1686         error_setg(errp, "iSCSI: Failed to set session type to normal.");
1687         ret = -EINVAL;
1688         goto out;
1689     }
1690 
1691     iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1692 
1693     /* check if we got HEADER_DIGEST via the options */
1694     parse_header_digest(iscsi, iscsi_url->target, &local_err);
1695     if (local_err != NULL) {
1696         error_propagate(errp, local_err);
1697         ret = -EINVAL;
1698         goto out;
1699     }
1700 
1701     /* timeout handling is broken in libiscsi before 1.15.0 */
1702     timeout = parse_timeout(iscsi_url->target);
1703 #if LIBISCSI_API_VERSION >= 20150621
1704     iscsi_set_timeout(iscsi, timeout);
1705 #else
1706     if (timeout) {
1707         error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1708     }
1709 #endif
1710 
1711     if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1712         error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1713             iscsi_get_error(iscsi));
1714         ret = -EINVAL;
1715         goto out;
1716     }
1717 
1718     iscsilun->iscsi = iscsi;
1719     iscsilun->aio_context = bdrv_get_aio_context(bs);
1720     iscsilun->lun   = iscsi_url->lun;
1721     iscsilun->has_write_same = true;
1722 
1723     task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1724                             (void **) &inq, errp);
1725     if (task == NULL) {
1726         ret = -EINVAL;
1727         goto out;
1728     }
1729     iscsilun->type = inq->periperal_device_type;
1730     scsi_free_scsi_task(task);
1731     task = NULL;
1732 
1733     iscsi_modesense_sync(iscsilun);
1734     if (iscsilun->dpofua) {
1735         bs->supported_write_flags = BDRV_REQ_FUA;
1736     }
1737     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1738 
1739     /* Check the write protect flag of the LUN if we want to write */
1740     if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1741         iscsilun->write_protected) {
1742         error_setg(errp, "Cannot open a write protected LUN as read-write");
1743         ret = -EACCES;
1744         goto out;
1745     }
1746 
1747     iscsi_readcapacity_sync(iscsilun, &local_err);
1748     if (local_err != NULL) {
1749         error_propagate(errp, local_err);
1750         ret = -EINVAL;
1751         goto out;
1752     }
1753     bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1754 
1755     /* We don't have any emulation for devices other than disks and CD-ROMs, so
1756      * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1757      * will try to read from the device to guess the image format.
1758      */
1759     if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1760         bs->sg = true;
1761     }
1762 
1763     task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1764                             SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1765                             (void **) &inq_vpd, errp);
1766     if (task == NULL) {
1767         ret = -EINVAL;
1768         goto out;
1769     }
1770     for (i = 0; i < inq_vpd->num_pages; i++) {
1771         struct scsi_task *inq_task;
1772         struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1773         struct scsi_inquiry_block_limits *inq_bl;
1774         switch (inq_vpd->pages[i]) {
1775         case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1776             inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1777                                         SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1778                                         (void **) &inq_lbp, errp);
1779             if (inq_task == NULL) {
1780                 ret = -EINVAL;
1781                 goto out;
1782             }
1783             memcpy(&iscsilun->lbp, inq_lbp,
1784                    sizeof(struct scsi_inquiry_logical_block_provisioning));
1785             scsi_free_scsi_task(inq_task);
1786             break;
1787         case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1788             inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1789                                     SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1790                                     (void **) &inq_bl, errp);
1791             if (inq_task == NULL) {
1792                 ret = -EINVAL;
1793                 goto out;
1794             }
1795             memcpy(&iscsilun->bl, inq_bl,
1796                    sizeof(struct scsi_inquiry_block_limits));
1797             scsi_free_scsi_task(inq_task);
1798             break;
1799         default:
1800             break;
1801         }
1802     }
1803     scsi_free_scsi_task(task);
1804     task = NULL;
1805 
1806     iscsi_attach_aio_context(bs, iscsilun->aio_context);
1807 
1808     /* Guess the internal cluster (page) size of the iscsi target by the means
1809      * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1810      * reasonable size */
1811     if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1812         iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1813         iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1814                                      iscsilun->block_size) >> BDRV_SECTOR_BITS;
1815         if (iscsilun->lbprz) {
1816             ret = iscsi_allocmap_init(iscsilun, bs->open_flags);
1817         }
1818     }
1819 
1820 out:
1821     qemu_opts_del(opts);
1822     g_free(initiator_name);
1823     if (iscsi_url != NULL) {
1824         iscsi_destroy_url(iscsi_url);
1825     }
1826     if (task != NULL) {
1827         scsi_free_scsi_task(task);
1828     }
1829 
1830     if (ret) {
1831         if (iscsi != NULL) {
1832             if (iscsi_is_logged_in(iscsi)) {
1833                 iscsi_logout_sync(iscsi);
1834             }
1835             iscsi_destroy_context(iscsi);
1836         }
1837         memset(iscsilun, 0, sizeof(IscsiLun));
1838     }
1839     return ret;
1840 }
1841 
1842 static void iscsi_close(BlockDriverState *bs)
1843 {
1844     IscsiLun *iscsilun = bs->opaque;
1845     struct iscsi_context *iscsi = iscsilun->iscsi;
1846 
1847     iscsi_detach_aio_context(bs);
1848     if (iscsi_is_logged_in(iscsi)) {
1849         iscsi_logout_sync(iscsi);
1850     }
1851     iscsi_destroy_context(iscsi);
1852     g_free(iscsilun->zeroblock);
1853     iscsi_allocmap_free(iscsilun);
1854     memset(iscsilun, 0, sizeof(IscsiLun));
1855 }
1856 
1857 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1858 {
1859     /* We don't actually refresh here, but just return data queried in
1860      * iscsi_open(): iscsi targets don't change their limits. */
1861 
1862     IscsiLun *iscsilun = bs->opaque;
1863     uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1864     unsigned int block_size = MAX(BDRV_SECTOR_SIZE, iscsilun->block_size);
1865 
1866     assert(iscsilun->block_size >= BDRV_SECTOR_SIZE || bs->sg);
1867 
1868     bs->bl.request_alignment = block_size;
1869 
1870     if (iscsilun->bl.max_xfer_len) {
1871         max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1872     }
1873 
1874     if (max_xfer_len * block_size < INT_MAX) {
1875         bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;
1876     }
1877 
1878     if (iscsilun->lbp.lbpu) {
1879         if (iscsilun->bl.max_unmap < 0xffffffff / block_size) {
1880             bs->bl.max_pdiscard =
1881                 iscsilun->bl.max_unmap * iscsilun->block_size;
1882         }
1883         bs->bl.pdiscard_alignment =
1884             iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
1885     } else {
1886         bs->bl.pdiscard_alignment = iscsilun->block_size;
1887     }
1888 
1889     if (iscsilun->bl.max_ws_len < 0xffffffff / block_size) {
1890         bs->bl.max_pwrite_zeroes =
1891             iscsilun->bl.max_ws_len * iscsilun->block_size;
1892     }
1893     if (iscsilun->lbp.lbpws) {
1894         bs->bl.pwrite_zeroes_alignment =
1895             iscsilun->bl.opt_unmap_gran * iscsilun->block_size;
1896     } else {
1897         bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;
1898     }
1899     if (iscsilun->bl.opt_xfer_len &&
1900         iscsilun->bl.opt_xfer_len < INT_MAX / block_size) {
1901         bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *
1902                                         iscsilun->block_size);
1903     }
1904 }
1905 
1906 /* Note that this will not re-establish a connection with an iSCSI target - it
1907  * is effectively a NOP.  */
1908 static int iscsi_reopen_prepare(BDRVReopenState *state,
1909                                 BlockReopenQueue *queue, Error **errp)
1910 {
1911     IscsiLun *iscsilun = state->bs->opaque;
1912 
1913     if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1914         error_setg(errp, "Cannot open a write protected LUN as read-write");
1915         return -EACCES;
1916     }
1917     return 0;
1918 }
1919 
1920 static void iscsi_reopen_commit(BDRVReopenState *reopen_state)
1921 {
1922     IscsiLun *iscsilun = reopen_state->bs->opaque;
1923 
1924     /* the cache.direct status might have changed */
1925     if (iscsilun->allocmap != NULL) {
1926         iscsi_allocmap_init(iscsilun, reopen_state->flags);
1927     }
1928 }
1929 
1930 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1931 {
1932     IscsiLun *iscsilun = bs->opaque;
1933     Error *local_err = NULL;
1934 
1935     if (iscsilun->type != TYPE_DISK) {
1936         return -ENOTSUP;
1937     }
1938 
1939     iscsi_readcapacity_sync(iscsilun, &local_err);
1940     if (local_err != NULL) {
1941         error_free(local_err);
1942         return -EIO;
1943     }
1944 
1945     if (offset > iscsi_getlength(bs)) {
1946         return -EINVAL;
1947     }
1948 
1949     if (iscsilun->allocmap != NULL) {
1950         iscsi_allocmap_init(iscsilun, bs->open_flags);
1951     }
1952 
1953     return 0;
1954 }
1955 
1956 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1957 {
1958     int ret = 0;
1959     int64_t total_size = 0;
1960     BlockDriverState *bs;
1961     IscsiLun *iscsilun = NULL;
1962     QDict *bs_options;
1963 
1964     bs = bdrv_new();
1965 
1966     /* Read out options */
1967     total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1968                               BDRV_SECTOR_SIZE);
1969     bs->opaque = g_new0(struct IscsiLun, 1);
1970     iscsilun = bs->opaque;
1971 
1972     bs_options = qdict_new();
1973     qdict_put(bs_options, "filename", qstring_from_str(filename));
1974     ret = iscsi_open(bs, bs_options, 0, NULL);
1975     QDECREF(bs_options);
1976 
1977     if (ret != 0) {
1978         goto out;
1979     }
1980     iscsi_detach_aio_context(bs);
1981     if (iscsilun->type != TYPE_DISK) {
1982         ret = -ENODEV;
1983         goto out;
1984     }
1985     if (bs->total_sectors < total_size) {
1986         ret = -ENOSPC;
1987         goto out;
1988     }
1989 
1990     ret = 0;
1991 out:
1992     if (iscsilun->iscsi != NULL) {
1993         iscsi_destroy_context(iscsilun->iscsi);
1994     }
1995     g_free(bs->opaque);
1996     bs->opaque = NULL;
1997     bdrv_unref(bs);
1998     return ret;
1999 }
2000 
2001 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2002 {
2003     IscsiLun *iscsilun = bs->opaque;
2004     bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
2005     bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
2006     bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
2007     return 0;
2008 }
2009 
2010 static void iscsi_invalidate_cache(BlockDriverState *bs,
2011                                    Error **errp)
2012 {
2013     IscsiLun *iscsilun = bs->opaque;
2014     iscsi_allocmap_invalidate(iscsilun);
2015 }
2016 
2017 static QemuOptsList iscsi_create_opts = {
2018     .name = "iscsi-create-opts",
2019     .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
2020     .desc = {
2021         {
2022             .name = BLOCK_OPT_SIZE,
2023             .type = QEMU_OPT_SIZE,
2024             .help = "Virtual disk size"
2025         },
2026         { /* end of list */ }
2027     }
2028 };
2029 
2030 static BlockDriver bdrv_iscsi = {
2031     .format_name     = "iscsi",
2032     .protocol_name   = "iscsi",
2033 
2034     .instance_size   = sizeof(IscsiLun),
2035     .bdrv_needs_filename = true,
2036     .bdrv_file_open  = iscsi_open,
2037     .bdrv_close      = iscsi_close,
2038     .bdrv_create     = iscsi_create,
2039     .create_opts     = &iscsi_create_opts,
2040     .bdrv_reopen_prepare   = iscsi_reopen_prepare,
2041     .bdrv_reopen_commit    = iscsi_reopen_commit,
2042     .bdrv_invalidate_cache = iscsi_invalidate_cache,
2043 
2044     .bdrv_getlength  = iscsi_getlength,
2045     .bdrv_get_info   = iscsi_get_info,
2046     .bdrv_truncate   = iscsi_truncate,
2047     .bdrv_refresh_limits = iscsi_refresh_limits,
2048 
2049     .bdrv_co_get_block_status = iscsi_co_get_block_status,
2050     .bdrv_co_pdiscard      = iscsi_co_pdiscard,
2051     .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2052     .bdrv_co_readv         = iscsi_co_readv,
2053     .bdrv_co_writev_flags  = iscsi_co_writev_flags,
2054     .bdrv_co_flush_to_disk = iscsi_co_flush,
2055 
2056 #ifdef __linux__
2057     .bdrv_aio_ioctl   = iscsi_aio_ioctl,
2058 #endif
2059 
2060     .bdrv_detach_aio_context = iscsi_detach_aio_context,
2061     .bdrv_attach_aio_context = iscsi_attach_aio_context,
2062 };
2063 
2064 #if LIBISCSI_API_VERSION >= (20160603)
2065 static BlockDriver bdrv_iser = {
2066     .format_name     = "iser",
2067     .protocol_name   = "iser",
2068 
2069     .instance_size   = sizeof(IscsiLun),
2070     .bdrv_needs_filename = true,
2071     .bdrv_file_open  = iscsi_open,
2072     .bdrv_close      = iscsi_close,
2073     .bdrv_create     = iscsi_create,
2074     .create_opts     = &iscsi_create_opts,
2075     .bdrv_reopen_prepare   = iscsi_reopen_prepare,
2076     .bdrv_reopen_commit    = iscsi_reopen_commit,
2077     .bdrv_invalidate_cache = iscsi_invalidate_cache,
2078 
2079     .bdrv_getlength  = iscsi_getlength,
2080     .bdrv_get_info   = iscsi_get_info,
2081     .bdrv_truncate   = iscsi_truncate,
2082     .bdrv_refresh_limits = iscsi_refresh_limits,
2083 
2084     .bdrv_co_get_block_status = iscsi_co_get_block_status,
2085     .bdrv_co_pdiscard      = iscsi_co_pdiscard,
2086     .bdrv_co_pwrite_zeroes = iscsi_co_pwrite_zeroes,
2087     .bdrv_co_readv         = iscsi_co_readv,
2088     .bdrv_co_writev_flags  = iscsi_co_writev_flags,
2089     .bdrv_co_flush_to_disk = iscsi_co_flush,
2090 
2091 #ifdef __linux__
2092     .bdrv_aio_ioctl   = iscsi_aio_ioctl,
2093 #endif
2094 
2095     .bdrv_detach_aio_context = iscsi_detach_aio_context,
2096     .bdrv_attach_aio_context = iscsi_attach_aio_context,
2097 };
2098 #endif
2099 
2100 static void iscsi_block_init(void)
2101 {
2102     bdrv_register(&bdrv_iscsi);
2103 #if LIBISCSI_API_VERSION >= (20160603)
2104     bdrv_register(&bdrv_iser);
2105 #endif
2106 }
2107 
2108 block_init(iscsi_block_init);
2109