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