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