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