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