OSDN Git Service

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