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