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