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