block/iscsi: avoid potential overflow of acb->task->cdb
[qemu.git] / block / iscsi.c
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 = flags & BDRV_REQ_FUA;
460
461 if (fua) {
462 assert(iscsilun->dpofua);
463 }
464 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
465 return -EINVAL;
466 }
467
468 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
469 error_report("iSCSI Error: Write of %d sectors exceeds max_xfer_len "
470 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
471 return -EINVAL;
472 }
473
474 lba = sector_qemu2lun(sector_num, iscsilun);
475 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
476 iscsi_co_init_iscsitask(iscsilun, &iTask);
477 retry:
478 if (iscsilun->use_16_for_rw) {
479 iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,
480 NULL, num_sectors * iscsilun->block_size,
481 iscsilun->block_size, 0, 0, fua, 0, 0,
482 iscsi_co_generic_cb, &iTask);
483 } else {
484 iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,
485 NULL, num_sectors * iscsilun->block_size,
486 iscsilun->block_size, 0, 0, fua, 0, 0,
487 iscsi_co_generic_cb, &iTask);
488 }
489 if (iTask.task == NULL) {
490 return -ENOMEM;
491 }
492 scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,
493 iov->niov);
494 while (!iTask.complete) {
495 iscsi_set_events(iscsilun);
496 qemu_coroutine_yield();
497 }
498
499 if (iTask.task != NULL) {
500 scsi_free_scsi_task(iTask.task);
501 iTask.task = NULL;
502 }
503
504 if (iTask.do_retry) {
505 iTask.complete = 0;
506 goto retry;
507 }
508
509 if (iTask.status != SCSI_STATUS_GOOD) {
510 return iTask.err_code;
511 }
512
513 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
514
515 return 0;
516 }
517
518
519 static bool iscsi_allocationmap_is_allocated(IscsiLun *iscsilun,
520 int64_t sector_num, int nb_sectors)
521 {
522 unsigned long size;
523 if (iscsilun->allocationmap == NULL) {
524 return true;
525 }
526 size = DIV_ROUND_UP(sector_num + nb_sectors, iscsilun->cluster_sectors);
527 return !(find_next_bit(iscsilun->allocationmap, size,
528 sector_num / iscsilun->cluster_sectors) == size);
529 }
530
531 static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,
532 int64_t sector_num,
533 int nb_sectors, int *pnum,
534 BlockDriverState **file)
535 {
536 IscsiLun *iscsilun = bs->opaque;
537 struct scsi_get_lba_status *lbas = NULL;
538 struct scsi_lba_status_descriptor *lbasd = NULL;
539 struct IscsiTask iTask;
540 int64_t ret;
541
542 iscsi_co_init_iscsitask(iscsilun, &iTask);
543
544 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
545 ret = -EINVAL;
546 goto out;
547 }
548
549 /* default to all sectors allocated */
550 ret = BDRV_BLOCK_DATA;
551 ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;
552 *pnum = nb_sectors;
553
554 /* LUN does not support logical block provisioning */
555 if (!iscsilun->lbpme) {
556 goto out;
557 }
558
559 retry:
560 if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,
561 sector_qemu2lun(sector_num, iscsilun),
562 8 + 16, iscsi_co_generic_cb,
563 &iTask) == NULL) {
564 ret = -ENOMEM;
565 goto out;
566 }
567
568 while (!iTask.complete) {
569 iscsi_set_events(iscsilun);
570 qemu_coroutine_yield();
571 }
572
573 if (iTask.do_retry) {
574 if (iTask.task != NULL) {
575 scsi_free_scsi_task(iTask.task);
576 iTask.task = NULL;
577 }
578 iTask.complete = 0;
579 goto retry;
580 }
581
582 if (iTask.status != SCSI_STATUS_GOOD) {
583 /* in case the get_lba_status_callout fails (i.e.
584 * because the device is busy or the cmd is not
585 * supported) we pretend all blocks are allocated
586 * for backwards compatibility */
587 goto out;
588 }
589
590 lbas = scsi_datain_unmarshall(iTask.task);
591 if (lbas == NULL) {
592 ret = -EIO;
593 goto out;
594 }
595
596 lbasd = &lbas->descriptors[0];
597
598 if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {
599 ret = -EIO;
600 goto out;
601 }
602
603 *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);
604
605 if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||
606 lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {
607 ret &= ~BDRV_BLOCK_DATA;
608 if (iscsilun->lbprz) {
609 ret |= BDRV_BLOCK_ZERO;
610 }
611 }
612
613 if (ret & BDRV_BLOCK_ZERO) {
614 iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);
615 } else {
616 iscsi_allocationmap_set(iscsilun, sector_num, *pnum);
617 }
618
619 if (*pnum > nb_sectors) {
620 *pnum = nb_sectors;
621 }
622 out:
623 if (iTask.task != NULL) {
624 scsi_free_scsi_task(iTask.task);
625 }
626 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
627 *file = bs;
628 }
629 return ret;
630 }
631
632 static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
633 int64_t sector_num, int nb_sectors,
634 QEMUIOVector *iov)
635 {
636 IscsiLun *iscsilun = bs->opaque;
637 struct IscsiTask iTask;
638 uint64_t lba;
639 uint32_t num_sectors;
640
641 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
642 return -EINVAL;
643 }
644
645 if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
646 error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "
647 "of %d sectors", nb_sectors, bs->bl.max_transfer_length);
648 return -EINVAL;
649 }
650
651 if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
652 !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
653 int64_t ret;
654 int pnum;
655 BlockDriverState *file;
656 ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum, &file);
657 if (ret < 0) {
658 return ret;
659 }
660 if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
661 qemu_iovec_memset(iov, 0, 0x00, iov->size);
662 return 0;
663 }
664 }
665
666 lba = sector_qemu2lun(sector_num, iscsilun);
667 num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
668
669 iscsi_co_init_iscsitask(iscsilun, &iTask);
670 retry:
671 if (iscsilun->use_16_for_rw) {
672 iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
673 num_sectors * iscsilun->block_size,
674 iscsilun->block_size, 0, 0, 0, 0, 0,
675 iscsi_co_generic_cb, &iTask);
676 } else {
677 iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
678 num_sectors * iscsilun->block_size,
679 iscsilun->block_size,
680 0, 0, 0, 0, 0,
681 iscsi_co_generic_cb, &iTask);
682 }
683 if (iTask.task == NULL) {
684 return -ENOMEM;
685 }
686 scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
687
688 while (!iTask.complete) {
689 iscsi_set_events(iscsilun);
690 qemu_coroutine_yield();
691 }
692
693 if (iTask.task != NULL) {
694 scsi_free_scsi_task(iTask.task);
695 iTask.task = NULL;
696 }
697
698 if (iTask.do_retry) {
699 iTask.complete = 0;
700 goto retry;
701 }
702
703 if (iTask.status != SCSI_STATUS_GOOD) {
704 return iTask.err_code;
705 }
706
707 return 0;
708 }
709
710 static int coroutine_fn iscsi_co_flush(BlockDriverState *bs)
711 {
712 IscsiLun *iscsilun = bs->opaque;
713 struct IscsiTask iTask;
714
715 iscsi_co_init_iscsitask(iscsilun, &iTask);
716 retry:
717 if (iscsi_synchronizecache10_task(iscsilun->iscsi, iscsilun->lun, 0, 0, 0,
718 0, iscsi_co_generic_cb, &iTask) == NULL) {
719 return -ENOMEM;
720 }
721
722 while (!iTask.complete) {
723 iscsi_set_events(iscsilun);
724 qemu_coroutine_yield();
725 }
726
727 if (iTask.task != NULL) {
728 scsi_free_scsi_task(iTask.task);
729 iTask.task = NULL;
730 }
731
732 if (iTask.do_retry) {
733 iTask.complete = 0;
734 goto retry;
735 }
736
737 if (iTask.status != SCSI_STATUS_GOOD) {
738 return iTask.err_code;
739 }
740
741 return 0;
742 }
743
744 #ifdef __linux__
745 static void
746 iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
747 void *command_data, void *opaque)
748 {
749 IscsiAIOCB *acb = opaque;
750
751 g_free(acb->buf);
752 acb->buf = NULL;
753
754 acb->status = 0;
755 if (status < 0) {
756 error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
757 iscsi_get_error(iscsi));
758 acb->status = iscsi_translate_sense(&acb->task->sense);
759 }
760
761 acb->ioh->driver_status = 0;
762 acb->ioh->host_status = 0;
763 acb->ioh->resid = 0;
764 acb->ioh->status = status;
765
766 #define SG_ERR_DRIVER_SENSE 0x08
767
768 if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
769 int ss;
770
771 acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
772
773 acb->ioh->sb_len_wr = acb->task->datain.size - 2;
774 ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
775 acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
776 memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
777 }
778
779 iscsi_schedule_bh(acb);
780 }
781
782 static void iscsi_ioctl_bh_completion(void *opaque)
783 {
784 IscsiAIOCB *acb = opaque;
785
786 qemu_bh_delete(acb->bh);
787 acb->common.cb(acb->common.opaque, acb->ret);
788 qemu_aio_unref(acb);
789 }
790
791 static void iscsi_ioctl_handle_emulated(IscsiAIOCB *acb, int req, void *buf)
792 {
793 BlockDriverState *bs = acb->common.bs;
794 IscsiLun *iscsilun = bs->opaque;
795 int ret = 0;
796
797 switch (req) {
798 case SG_GET_VERSION_NUM:
799 *(int *)buf = 30000;
800 break;
801 case SG_GET_SCSI_ID:
802 ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
803 break;
804 default:
805 ret = -EINVAL;
806 }
807 assert(!acb->bh);
808 acb->bh = aio_bh_new(bdrv_get_aio_context(bs),
809 iscsi_ioctl_bh_completion, acb);
810 acb->ret = ret;
811 qemu_bh_schedule(acb->bh);
812 }
813
814 static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
815 unsigned long int req, void *buf,
816 BlockCompletionFunc *cb, void *opaque)
817 {
818 IscsiLun *iscsilun = bs->opaque;
819 struct iscsi_context *iscsi = iscsilun->iscsi;
820 struct iscsi_data data;
821 IscsiAIOCB *acb;
822
823 acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
824
825 acb->iscsilun = iscsilun;
826 acb->bh = NULL;
827 acb->status = -EINPROGRESS;
828 acb->buf = NULL;
829 acb->ioh = buf;
830
831 if (req != SG_IO) {
832 iscsi_ioctl_handle_emulated(acb, req, buf);
833 return &acb->common;
834 }
835
836 if (acb->ioh->cmd_len > SCSI_CDB_MAX_SIZE) {
837 error_report("iSCSI: ioctl error CDB exceeds max size (%d > %d)",
838 acb->ioh->cmd_len, SCSI_CDB_MAX_SIZE);
839 qemu_aio_unref(acb);
840 return NULL;
841 }
842
843 acb->task = malloc(sizeof(struct scsi_task));
844 if (acb->task == NULL) {
845 error_report("iSCSI: Failed to allocate task for scsi command. %s",
846 iscsi_get_error(iscsi));
847 qemu_aio_unref(acb);
848 return NULL;
849 }
850 memset(acb->task, 0, sizeof(struct scsi_task));
851
852 switch (acb->ioh->dxfer_direction) {
853 case SG_DXFER_TO_DEV:
854 acb->task->xfer_dir = SCSI_XFER_WRITE;
855 break;
856 case SG_DXFER_FROM_DEV:
857 acb->task->xfer_dir = SCSI_XFER_READ;
858 break;
859 default:
860 acb->task->xfer_dir = SCSI_XFER_NONE;
861 break;
862 }
863
864 acb->task->cdb_size = acb->ioh->cmd_len;
865 memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
866 acb->task->expxferlen = acb->ioh->dxfer_len;
867
868 data.size = 0;
869 if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
870 if (acb->ioh->iovec_count == 0) {
871 data.data = acb->ioh->dxferp;
872 data.size = acb->ioh->dxfer_len;
873 } else {
874 scsi_task_set_iov_out(acb->task,
875 (struct scsi_iovec *) acb->ioh->dxferp,
876 acb->ioh->iovec_count);
877 }
878 }
879
880 if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
881 iscsi_aio_ioctl_cb,
882 (data.size > 0) ? &data : NULL,
883 acb) != 0) {
884 scsi_free_scsi_task(acb->task);
885 qemu_aio_unref(acb);
886 return NULL;
887 }
888
889 /* tell libiscsi to read straight into the buffer we got from ioctl */
890 if (acb->task->xfer_dir == SCSI_XFER_READ) {
891 if (acb->ioh->iovec_count == 0) {
892 scsi_task_add_data_in_buffer(acb->task,
893 acb->ioh->dxfer_len,
894 acb->ioh->dxferp);
895 } else {
896 scsi_task_set_iov_in(acb->task,
897 (struct scsi_iovec *) acb->ioh->dxferp,
898 acb->ioh->iovec_count);
899 }
900 }
901
902 iscsi_set_events(iscsilun);
903
904 return &acb->common;
905 }
906
907 #endif
908
909 static int64_t
910 iscsi_getlength(BlockDriverState *bs)
911 {
912 IscsiLun *iscsilun = bs->opaque;
913 int64_t len;
914
915 len = iscsilun->num_blocks;
916 len *= iscsilun->block_size;
917
918 return len;
919 }
920
921 static int
922 coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,
923 int nb_sectors)
924 {
925 IscsiLun *iscsilun = bs->opaque;
926 struct IscsiTask iTask;
927 struct unmap_list list;
928
929 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
930 return -EINVAL;
931 }
932
933 if (!iscsilun->lbp.lbpu) {
934 /* UNMAP is not supported by the target */
935 return 0;
936 }
937
938 list.lba = sector_qemu2lun(sector_num, iscsilun);
939 list.num = sector_qemu2lun(nb_sectors, iscsilun);
940
941 iscsi_co_init_iscsitask(iscsilun, &iTask);
942 retry:
943 if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,
944 iscsi_co_generic_cb, &iTask) == NULL) {
945 return -ENOMEM;
946 }
947
948 while (!iTask.complete) {
949 iscsi_set_events(iscsilun);
950 qemu_coroutine_yield();
951 }
952
953 if (iTask.task != NULL) {
954 scsi_free_scsi_task(iTask.task);
955 iTask.task = NULL;
956 }
957
958 if (iTask.do_retry) {
959 iTask.complete = 0;
960 goto retry;
961 }
962
963 if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {
964 /* the target might fail with a check condition if it
965 is not happy with the alignment of the UNMAP request
966 we silently fail in this case */
967 return 0;
968 }
969
970 if (iTask.status != SCSI_STATUS_GOOD) {
971 return iTask.err_code;
972 }
973
974 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
975
976 return 0;
977 }
978
979 static int
980 coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
981 int nb_sectors, BdrvRequestFlags flags)
982 {
983 IscsiLun *iscsilun = bs->opaque;
984 struct IscsiTask iTask;
985 uint64_t lba;
986 uint32_t nb_blocks;
987 bool use_16_for_ws = iscsilun->use_16_for_rw;
988
989 if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
990 return -EINVAL;
991 }
992
993 if (flags & BDRV_REQ_MAY_UNMAP) {
994 if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {
995 /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */
996 use_16_for_ws = true;
997 }
998 if (use_16_for_ws && !iscsilun->lbp.lbpws) {
999 /* WRITESAME16 with UNMAP is not supported by the target,
1000 * fall back and try WRITESAME10/16 without UNMAP */
1001 flags &= ~BDRV_REQ_MAY_UNMAP;
1002 use_16_for_ws = iscsilun->use_16_for_rw;
1003 }
1004 }
1005
1006 if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {
1007 /* WRITESAME without UNMAP is not supported by the target */
1008 return -ENOTSUP;
1009 }
1010
1011 lba = sector_qemu2lun(sector_num, iscsilun);
1012 nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);
1013
1014 if (iscsilun->zeroblock == NULL) {
1015 iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);
1016 if (iscsilun->zeroblock == NULL) {
1017 return -ENOMEM;
1018 }
1019 }
1020
1021 iscsi_co_init_iscsitask(iscsilun, &iTask);
1022 retry:
1023 if (use_16_for_ws) {
1024 iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,
1025 iscsilun->zeroblock, iscsilun->block_size,
1026 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1027 0, 0, iscsi_co_generic_cb, &iTask);
1028 } else {
1029 iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,
1030 iscsilun->zeroblock, iscsilun->block_size,
1031 nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),
1032 0, 0, iscsi_co_generic_cb, &iTask);
1033 }
1034 if (iTask.task == NULL) {
1035 return -ENOMEM;
1036 }
1037
1038 while (!iTask.complete) {
1039 iscsi_set_events(iscsilun);
1040 qemu_coroutine_yield();
1041 }
1042
1043 if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&
1044 iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&
1045 (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||
1046 iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {
1047 /* WRITE SAME is not supported by the target */
1048 iscsilun->has_write_same = false;
1049 scsi_free_scsi_task(iTask.task);
1050 return -ENOTSUP;
1051 }
1052
1053 if (iTask.task != NULL) {
1054 scsi_free_scsi_task(iTask.task);
1055 iTask.task = NULL;
1056 }
1057
1058 if (iTask.do_retry) {
1059 iTask.complete = 0;
1060 goto retry;
1061 }
1062
1063 if (iTask.status != SCSI_STATUS_GOOD) {
1064 return iTask.err_code;
1065 }
1066
1067 if (flags & BDRV_REQ_MAY_UNMAP) {
1068 iscsi_allocationmap_clear(iscsilun, sector_num, nb_sectors);
1069 } else {
1070 iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);
1071 }
1072
1073 return 0;
1074 }
1075
1076 static void parse_chap(struct iscsi_context *iscsi, const char *target,
1077 Error **errp)
1078 {
1079 QemuOptsList *list;
1080 QemuOpts *opts;
1081 const char *user = NULL;
1082 const char *password = NULL;
1083 const char *secretid;
1084 char *secret = NULL;
1085
1086 list = qemu_find_opts("iscsi");
1087 if (!list) {
1088 return;
1089 }
1090
1091 opts = qemu_opts_find(list, target);
1092 if (opts == NULL) {
1093 opts = QTAILQ_FIRST(&list->head);
1094 if (!opts) {
1095 return;
1096 }
1097 }
1098
1099 user = qemu_opt_get(opts, "user");
1100 if (!user) {
1101 return;
1102 }
1103
1104 secretid = qemu_opt_get(opts, "password-secret");
1105 password = qemu_opt_get(opts, "password");
1106 if (secretid && password) {
1107 error_setg(errp, "'password' and 'password-secret' properties are "
1108 "mutually exclusive");
1109 return;
1110 }
1111 if (secretid) {
1112 secret = qcrypto_secret_lookup_as_utf8(secretid, errp);
1113 if (!secret) {
1114 return;
1115 }
1116 password = secret;
1117 } else if (!password) {
1118 error_setg(errp, "CHAP username specified but no password was given");
1119 return;
1120 }
1121
1122 if (iscsi_set_initiator_username_pwd(iscsi, user, password)) {
1123 error_setg(errp, "Failed to set initiator username and password");
1124 }
1125
1126 g_free(secret);
1127 }
1128
1129 static void parse_header_digest(struct iscsi_context *iscsi, const char *target,
1130 Error **errp)
1131 {
1132 QemuOptsList *list;
1133 QemuOpts *opts;
1134 const char *digest = NULL;
1135
1136 list = qemu_find_opts("iscsi");
1137 if (!list) {
1138 return;
1139 }
1140
1141 opts = qemu_opts_find(list, target);
1142 if (opts == NULL) {
1143 opts = QTAILQ_FIRST(&list->head);
1144 if (!opts) {
1145 return;
1146 }
1147 }
1148
1149 digest = qemu_opt_get(opts, "header-digest");
1150 if (!digest) {
1151 return;
1152 }
1153
1154 if (!strcmp(digest, "CRC32C")) {
1155 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);
1156 } else if (!strcmp(digest, "NONE")) {
1157 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);
1158 } else if (!strcmp(digest, "CRC32C-NONE")) {
1159 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);
1160 } else if (!strcmp(digest, "NONE-CRC32C")) {
1161 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1162 } else {
1163 error_setg(errp, "Invalid header-digest setting : %s", digest);
1164 }
1165 }
1166
1167 static char *parse_initiator_name(const char *target)
1168 {
1169 QemuOptsList *list;
1170 QemuOpts *opts;
1171 const char *name;
1172 char *iscsi_name;
1173 UuidInfo *uuid_info;
1174
1175 list = qemu_find_opts("iscsi");
1176 if (list) {
1177 opts = qemu_opts_find(list, target);
1178 if (!opts) {
1179 opts = QTAILQ_FIRST(&list->head);
1180 }
1181 if (opts) {
1182 name = qemu_opt_get(opts, "initiator-name");
1183 if (name) {
1184 return g_strdup(name);
1185 }
1186 }
1187 }
1188
1189 uuid_info = qmp_query_uuid(NULL);
1190 if (strcmp(uuid_info->UUID, UUID_NONE) == 0) {
1191 name = qemu_get_vm_name();
1192 } else {
1193 name = uuid_info->UUID;
1194 }
1195 iscsi_name = g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
1196 name ? ":" : "", name ? name : "");
1197 qapi_free_UuidInfo(uuid_info);
1198 return iscsi_name;
1199 }
1200
1201 static int parse_timeout(const char *target)
1202 {
1203 QemuOptsList *list;
1204 QemuOpts *opts;
1205 const char *timeout;
1206
1207 list = qemu_find_opts("iscsi");
1208 if (list) {
1209 opts = qemu_opts_find(list, target);
1210 if (!opts) {
1211 opts = QTAILQ_FIRST(&list->head);
1212 }
1213 if (opts) {
1214 timeout = qemu_opt_get(opts, "timeout");
1215 if (timeout) {
1216 return atoi(timeout);
1217 }
1218 }
1219 }
1220
1221 return 0;
1222 }
1223
1224 static void iscsi_nop_timed_event(void *opaque)
1225 {
1226 IscsiLun *iscsilun = opaque;
1227
1228 if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {
1229 error_report("iSCSI: NOP timeout. Reconnecting...");
1230 iscsilun->request_timed_out = true;
1231 } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {
1232 error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");
1233 return;
1234 }
1235
1236 timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1237 iscsi_set_events(iscsilun);
1238 }
1239
1240 static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)
1241 {
1242 struct scsi_task *task = NULL;
1243 struct scsi_readcapacity10 *rc10 = NULL;
1244 struct scsi_readcapacity16 *rc16 = NULL;
1245 int retries = ISCSI_CMD_RETRIES;
1246
1247 do {
1248 if (task != NULL) {
1249 scsi_free_scsi_task(task);
1250 task = NULL;
1251 }
1252
1253 switch (iscsilun->type) {
1254 case TYPE_DISK:
1255 task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);
1256 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1257 rc16 = scsi_datain_unmarshall(task);
1258 if (rc16 == NULL) {
1259 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");
1260 } else {
1261 iscsilun->block_size = rc16->block_length;
1262 iscsilun->num_blocks = rc16->returned_lba + 1;
1263 iscsilun->lbpme = !!rc16->lbpme;
1264 iscsilun->lbprz = !!rc16->lbprz;
1265 iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);
1266 }
1267 break;
1268 }
1269 if (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1270 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION) {
1271 break;
1272 }
1273 /* Fall through and try READ CAPACITY(10) instead. */
1274 case TYPE_ROM:
1275 task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);
1276 if (task != NULL && task->status == SCSI_STATUS_GOOD) {
1277 rc10 = scsi_datain_unmarshall(task);
1278 if (rc10 == NULL) {
1279 error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");
1280 } else {
1281 iscsilun->block_size = rc10->block_size;
1282 if (rc10->lba == 0) {
1283 /* blank disk loaded */
1284 iscsilun->num_blocks = 0;
1285 } else {
1286 iscsilun->num_blocks = rc10->lba + 1;
1287 }
1288 }
1289 }
1290 break;
1291 default:
1292 return;
1293 }
1294 } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION
1295 && task->sense.key == SCSI_SENSE_UNIT_ATTENTION
1296 && retries-- > 0);
1297
1298 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1299 error_setg(errp, "iSCSI: failed to send readcapacity10/16 command");
1300 } else if (!iscsilun->block_size ||
1301 iscsilun->block_size % BDRV_SECTOR_SIZE) {
1302 error_setg(errp, "iSCSI: the target returned an invalid "
1303 "block size of %d.", iscsilun->block_size);
1304 }
1305 if (task) {
1306 scsi_free_scsi_task(task);
1307 }
1308 }
1309
1310 /* TODO Convert to fine grained options */
1311 static QemuOptsList runtime_opts = {
1312 .name = "iscsi",
1313 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1314 .desc = {
1315 {
1316 .name = "filename",
1317 .type = QEMU_OPT_STRING,
1318 .help = "URL to the iscsi image",
1319 },
1320 { /* end of list */ }
1321 },
1322 };
1323
1324 static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,
1325 int evpd, int pc, void **inq, Error **errp)
1326 {
1327 int full_size;
1328 struct scsi_task *task = NULL;
1329 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);
1330 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1331 goto fail;
1332 }
1333 full_size = scsi_datain_getfullsize(task);
1334 if (full_size > task->datain.size) {
1335 scsi_free_scsi_task(task);
1336
1337 /* we need more data for the full list */
1338 task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);
1339 if (task == NULL || task->status != SCSI_STATUS_GOOD) {
1340 goto fail;
1341 }
1342 }
1343
1344 *inq = scsi_datain_unmarshall(task);
1345 if (*inq == NULL) {
1346 error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");
1347 goto fail_with_err;
1348 }
1349
1350 return task;
1351
1352 fail:
1353 error_setg(errp, "iSCSI: Inquiry command failed : %s",
1354 iscsi_get_error(iscsi));
1355 fail_with_err:
1356 if (task != NULL) {
1357 scsi_free_scsi_task(task);
1358 }
1359 return NULL;
1360 }
1361
1362 static void iscsi_detach_aio_context(BlockDriverState *bs)
1363 {
1364 IscsiLun *iscsilun = bs->opaque;
1365
1366 aio_set_fd_handler(iscsilun->aio_context, iscsi_get_fd(iscsilun->iscsi),
1367 false, NULL, NULL, NULL);
1368 iscsilun->events = 0;
1369
1370 if (iscsilun->nop_timer) {
1371 timer_del(iscsilun->nop_timer);
1372 timer_free(iscsilun->nop_timer);
1373 iscsilun->nop_timer = NULL;
1374 }
1375 if (iscsilun->event_timer) {
1376 timer_del(iscsilun->event_timer);
1377 timer_free(iscsilun->event_timer);
1378 iscsilun->event_timer = NULL;
1379 }
1380 }
1381
1382 static void iscsi_attach_aio_context(BlockDriverState *bs,
1383 AioContext *new_context)
1384 {
1385 IscsiLun *iscsilun = bs->opaque;
1386
1387 iscsilun->aio_context = new_context;
1388 iscsi_set_events(iscsilun);
1389
1390 /* Set up a timer for sending out iSCSI NOPs */
1391 iscsilun->nop_timer = aio_timer_new(iscsilun->aio_context,
1392 QEMU_CLOCK_REALTIME, SCALE_MS,
1393 iscsi_nop_timed_event, iscsilun);
1394 timer_mod(iscsilun->nop_timer,
1395 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);
1396
1397 /* Set up a timer for periodic calls to iscsi_set_events and to
1398 * scan for command timeout */
1399 iscsilun->event_timer = aio_timer_new(iscsilun->aio_context,
1400 QEMU_CLOCK_REALTIME, SCALE_MS,
1401 iscsi_timed_check_events, iscsilun);
1402 timer_mod(iscsilun->event_timer,
1403 qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
1404 }
1405
1406 static void iscsi_modesense_sync(IscsiLun *iscsilun)
1407 {
1408 struct scsi_task *task;
1409 struct scsi_mode_sense *ms = NULL;
1410 iscsilun->write_protected = false;
1411 iscsilun->dpofua = false;
1412
1413 task = iscsi_modesense6_sync(iscsilun->iscsi, iscsilun->lun,
1414 1, SCSI_MODESENSE_PC_CURRENT,
1415 0x3F, 0, 255);
1416 if (task == NULL) {
1417 error_report("iSCSI: Failed to send MODE_SENSE(6) command: %s",
1418 iscsi_get_error(iscsilun->iscsi));
1419 goto out;
1420 }
1421
1422 if (task->status != SCSI_STATUS_GOOD) {
1423 error_report("iSCSI: Failed MODE_SENSE(6), LUN assumed writable");
1424 goto out;
1425 }
1426 ms = scsi_datain_unmarshall(task);
1427 if (!ms) {
1428 error_report("iSCSI: Failed to unmarshall MODE_SENSE(6) data: %s",
1429 iscsi_get_error(iscsilun->iscsi));
1430 goto out;
1431 }
1432 iscsilun->write_protected = ms->device_specific_parameter & 0x80;
1433 iscsilun->dpofua = ms->device_specific_parameter & 0x10;
1434
1435 out:
1436 if (task) {
1437 scsi_free_scsi_task(task);
1438 }
1439 }
1440
1441 /*
1442 * We support iscsi url's on the form
1443 * iscsi://[<username>%<password>@]<host>[:<port>]/<targetname>/<lun>
1444 */
1445 static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
1446 Error **errp)
1447 {
1448 IscsiLun *iscsilun = bs->opaque;
1449 struct iscsi_context *iscsi = NULL;
1450 struct iscsi_url *iscsi_url = NULL;
1451 struct scsi_task *task = NULL;
1452 struct scsi_inquiry_standard *inq = NULL;
1453 struct scsi_inquiry_supported_pages *inq_vpd;
1454 char *initiator_name = NULL;
1455 QemuOpts *opts;
1456 Error *local_err = NULL;
1457 const char *filename;
1458 int i, ret = 0, timeout = 0;
1459
1460 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1461 qemu_opts_absorb_qdict(opts, options, &local_err);
1462 if (local_err) {
1463 error_propagate(errp, local_err);
1464 ret = -EINVAL;
1465 goto out;
1466 }
1467
1468 filename = qemu_opt_get(opts, "filename");
1469
1470 iscsi_url = iscsi_parse_full_url(iscsi, filename);
1471 if (iscsi_url == NULL) {
1472 error_setg(errp, "Failed to parse URL : %s", filename);
1473 ret = -EINVAL;
1474 goto out;
1475 }
1476
1477 memset(iscsilun, 0, sizeof(IscsiLun));
1478
1479 initiator_name = parse_initiator_name(iscsi_url->target);
1480
1481 iscsi = iscsi_create_context(initiator_name);
1482 if (iscsi == NULL) {
1483 error_setg(errp, "iSCSI: Failed to create iSCSI context.");
1484 ret = -ENOMEM;
1485 goto out;
1486 }
1487
1488 if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
1489 error_setg(errp, "iSCSI: Failed to set target name.");
1490 ret = -EINVAL;
1491 goto out;
1492 }
1493
1494 if (iscsi_url->user[0] != '\0') {
1495 ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
1496 iscsi_url->passwd);
1497 if (ret != 0) {
1498 error_setg(errp, "Failed to set initiator username and password");
1499 ret = -EINVAL;
1500 goto out;
1501 }
1502 }
1503
1504 /* check if we got CHAP username/password via the options */
1505 parse_chap(iscsi, iscsi_url->target, &local_err);
1506 if (local_err != NULL) {
1507 error_propagate(errp, local_err);
1508 ret = -EINVAL;
1509 goto out;
1510 }
1511
1512 if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
1513 error_setg(errp, "iSCSI: Failed to set session type to normal.");
1514 ret = -EINVAL;
1515 goto out;
1516 }
1517
1518 iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
1519
1520 /* check if we got HEADER_DIGEST via the options */
1521 parse_header_digest(iscsi, iscsi_url->target, &local_err);
1522 if (local_err != NULL) {
1523 error_propagate(errp, local_err);
1524 ret = -EINVAL;
1525 goto out;
1526 }
1527
1528 /* timeout handling is broken in libiscsi before 1.15.0 */
1529 timeout = parse_timeout(iscsi_url->target);
1530 #if defined(LIBISCSI_API_VERSION) && LIBISCSI_API_VERSION >= 20150621
1531 iscsi_set_timeout(iscsi, timeout);
1532 #else
1533 if (timeout) {
1534 error_report("iSCSI: ignoring timeout value for libiscsi <1.15.0");
1535 }
1536 #endif
1537
1538 if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
1539 error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
1540 iscsi_get_error(iscsi));
1541 ret = -EINVAL;
1542 goto out;
1543 }
1544
1545 iscsilun->iscsi = iscsi;
1546 iscsilun->aio_context = bdrv_get_aio_context(bs);
1547 iscsilun->lun = iscsi_url->lun;
1548 iscsilun->has_write_same = true;
1549
1550 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
1551 (void **) &inq, errp);
1552 if (task == NULL) {
1553 ret = -EINVAL;
1554 goto out;
1555 }
1556 iscsilun->type = inq->periperal_device_type;
1557 scsi_free_scsi_task(task);
1558 task = NULL;
1559
1560 iscsi_modesense_sync(iscsilun);
1561 if (iscsilun->dpofua) {
1562 bs->supported_write_flags = BDRV_REQ_FUA;
1563 }
1564 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1565
1566 /* Check the write protect flag of the LUN if we want to write */
1567 if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
1568 iscsilun->write_protected) {
1569 error_setg(errp, "Cannot open a write protected LUN as read-write");
1570 ret = -EACCES;
1571 goto out;
1572 }
1573
1574 iscsi_readcapacity_sync(iscsilun, &local_err);
1575 if (local_err != NULL) {
1576 error_propagate(errp, local_err);
1577 ret = -EINVAL;
1578 goto out;
1579 }
1580 bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
1581 bs->request_alignment = iscsilun->block_size;
1582
1583 /* We don't have any emulation for devices other than disks and CD-ROMs, so
1584 * this must be sg ioctl compatible. We force it to be sg, otherwise qemu
1585 * will try to read from the device to guess the image format.
1586 */
1587 if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
1588 bs->sg = 1;
1589 }
1590
1591 task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1592 SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
1593 (void **) &inq_vpd, errp);
1594 if (task == NULL) {
1595 ret = -EINVAL;
1596 goto out;
1597 }
1598 for (i = 0; i < inq_vpd->num_pages; i++) {
1599 struct scsi_task *inq_task;
1600 struct scsi_inquiry_logical_block_provisioning *inq_lbp;
1601 struct scsi_inquiry_block_limits *inq_bl;
1602 switch (inq_vpd->pages[i]) {
1603 case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
1604 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1605 SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
1606 (void **) &inq_lbp, errp);
1607 if (inq_task == NULL) {
1608 ret = -EINVAL;
1609 goto out;
1610 }
1611 memcpy(&iscsilun->lbp, inq_lbp,
1612 sizeof(struct scsi_inquiry_logical_block_provisioning));
1613 scsi_free_scsi_task(inq_task);
1614 break;
1615 case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
1616 inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
1617 SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
1618 (void **) &inq_bl, errp);
1619 if (inq_task == NULL) {
1620 ret = -EINVAL;
1621 goto out;
1622 }
1623 memcpy(&iscsilun->bl, inq_bl,
1624 sizeof(struct scsi_inquiry_block_limits));
1625 scsi_free_scsi_task(inq_task);
1626 break;
1627 default:
1628 break;
1629 }
1630 }
1631 scsi_free_scsi_task(task);
1632 task = NULL;
1633
1634 iscsi_attach_aio_context(bs, iscsilun->aio_context);
1635
1636 /* Guess the internal cluster (page) size of the iscsi target by the means
1637 * of opt_unmap_gran. Transfer the unmap granularity only if it has a
1638 * reasonable size */
1639 if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
1640 iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
1641 iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
1642 iscsilun->block_size) >> BDRV_SECTOR_BITS;
1643 if (iscsilun->lbprz) {
1644 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1645 if (iscsilun->allocationmap == NULL) {
1646 ret = -ENOMEM;
1647 }
1648 }
1649 }
1650
1651 out:
1652 qemu_opts_del(opts);
1653 g_free(initiator_name);
1654 if (iscsi_url != NULL) {
1655 iscsi_destroy_url(iscsi_url);
1656 }
1657 if (task != NULL) {
1658 scsi_free_scsi_task(task);
1659 }
1660
1661 if (ret) {
1662 if (iscsi != NULL) {
1663 if (iscsi_is_logged_in(iscsi)) {
1664 iscsi_logout_sync(iscsi);
1665 }
1666 iscsi_destroy_context(iscsi);
1667 }
1668 memset(iscsilun, 0, sizeof(IscsiLun));
1669 }
1670 return ret;
1671 }
1672
1673 static void iscsi_close(BlockDriverState *bs)
1674 {
1675 IscsiLun *iscsilun = bs->opaque;
1676 struct iscsi_context *iscsi = iscsilun->iscsi;
1677
1678 iscsi_detach_aio_context(bs);
1679 if (iscsi_is_logged_in(iscsi)) {
1680 iscsi_logout_sync(iscsi);
1681 }
1682 iscsi_destroy_context(iscsi);
1683 g_free(iscsilun->zeroblock);
1684 g_free(iscsilun->allocationmap);
1685 memset(iscsilun, 0, sizeof(IscsiLun));
1686 }
1687
1688 static int sector_limits_lun2qemu(int64_t sector, IscsiLun *iscsilun)
1689 {
1690 return MIN(sector_lun2qemu(sector, iscsilun), INT_MAX / 2 + 1);
1691 }
1692
1693 static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)
1694 {
1695 /* We don't actually refresh here, but just return data queried in
1696 * iscsi_open(): iscsi targets don't change their limits. */
1697
1698 IscsiLun *iscsilun = bs->opaque;
1699 uint32_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;
1700
1701 if (iscsilun->bl.max_xfer_len) {
1702 max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);
1703 }
1704
1705 bs->bl.max_transfer_length = sector_limits_lun2qemu(max_xfer_len, iscsilun);
1706
1707 if (iscsilun->lbp.lbpu) {
1708 if (iscsilun->bl.max_unmap < 0xffffffff) {
1709 bs->bl.max_discard =
1710 sector_limits_lun2qemu(iscsilun->bl.max_unmap, iscsilun);
1711 }
1712 bs->bl.discard_alignment =
1713 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1714 }
1715
1716 if (iscsilun->bl.max_ws_len < 0xffffffff) {
1717 bs->bl.max_write_zeroes =
1718 sector_limits_lun2qemu(iscsilun->bl.max_ws_len, iscsilun);
1719 }
1720 if (iscsilun->lbp.lbpws) {
1721 bs->bl.write_zeroes_alignment =
1722 sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);
1723 }
1724 bs->bl.opt_transfer_length =
1725 sector_limits_lun2qemu(iscsilun->bl.opt_xfer_len, iscsilun);
1726 }
1727
1728 /* Note that this will not re-establish a connection with an iSCSI target - it
1729 * is effectively a NOP. */
1730 static int iscsi_reopen_prepare(BDRVReopenState *state,
1731 BlockReopenQueue *queue, Error **errp)
1732 {
1733 IscsiLun *iscsilun = state->bs->opaque;
1734
1735 if (state->flags & BDRV_O_RDWR && iscsilun->write_protected) {
1736 error_setg(errp, "Cannot open a write protected LUN as read-write");
1737 return -EACCES;
1738 }
1739 return 0;
1740 }
1741
1742 static int iscsi_truncate(BlockDriverState *bs, int64_t offset)
1743 {
1744 IscsiLun *iscsilun = bs->opaque;
1745 Error *local_err = NULL;
1746
1747 if (iscsilun->type != TYPE_DISK) {
1748 return -ENOTSUP;
1749 }
1750
1751 iscsi_readcapacity_sync(iscsilun, &local_err);
1752 if (local_err != NULL) {
1753 error_free(local_err);
1754 return -EIO;
1755 }
1756
1757 if (offset > iscsi_getlength(bs)) {
1758 return -EINVAL;
1759 }
1760
1761 if (iscsilun->allocationmap != NULL) {
1762 g_free(iscsilun->allocationmap);
1763 iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
1764 }
1765
1766 return 0;
1767 }
1768
1769 static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
1770 {
1771 int ret = 0;
1772 int64_t total_size = 0;
1773 BlockDriverState *bs;
1774 IscsiLun *iscsilun = NULL;
1775 QDict *bs_options;
1776
1777 bs = bdrv_new();
1778
1779 /* Read out options */
1780 total_size = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1781 BDRV_SECTOR_SIZE);
1782 bs->opaque = g_new0(struct IscsiLun, 1);
1783 iscsilun = bs->opaque;
1784
1785 bs_options = qdict_new();
1786 qdict_put(bs_options, "filename", qstring_from_str(filename));
1787 ret = iscsi_open(bs, bs_options, 0, NULL);
1788 QDECREF(bs_options);
1789
1790 if (ret != 0) {
1791 goto out;
1792 }
1793 iscsi_detach_aio_context(bs);
1794 if (iscsilun->type != TYPE_DISK) {
1795 ret = -ENODEV;
1796 goto out;
1797 }
1798 if (bs->total_sectors < total_size) {
1799 ret = -ENOSPC;
1800 goto out;
1801 }
1802
1803 ret = 0;
1804 out:
1805 if (iscsilun->iscsi != NULL) {
1806 iscsi_destroy_context(iscsilun->iscsi);
1807 }
1808 g_free(bs->opaque);
1809 bs->opaque = NULL;
1810 bdrv_unref(bs);
1811 return ret;
1812 }
1813
1814 static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1815 {
1816 IscsiLun *iscsilun = bs->opaque;
1817 bdi->unallocated_blocks_are_zero = iscsilun->lbprz;
1818 bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;
1819 bdi->cluster_size = iscsilun->cluster_sectors * BDRV_SECTOR_SIZE;
1820 return 0;
1821 }
1822
1823 static QemuOptsList iscsi_create_opts = {
1824 .name = "iscsi-create-opts",
1825 .head = QTAILQ_HEAD_INITIALIZER(iscsi_create_opts.head),
1826 .desc = {
1827 {
1828 .name = BLOCK_OPT_SIZE,
1829 .type = QEMU_OPT_SIZE,
1830 .help = "Virtual disk size"
1831 },
1832 { /* end of list */ }
1833 }
1834 };
1835
1836 static BlockDriver bdrv_iscsi = {
1837 .format_name = "iscsi",
1838 .protocol_name = "iscsi",
1839
1840 .instance_size = sizeof(IscsiLun),
1841 .bdrv_needs_filename = true,
1842 .bdrv_file_open = iscsi_open,
1843 .bdrv_close = iscsi_close,
1844 .bdrv_create = iscsi_create,
1845 .create_opts = &iscsi_create_opts,
1846 .bdrv_reopen_prepare = iscsi_reopen_prepare,
1847
1848 .bdrv_getlength = iscsi_getlength,
1849 .bdrv_get_info = iscsi_get_info,
1850 .bdrv_truncate = iscsi_truncate,
1851 .bdrv_refresh_limits = iscsi_refresh_limits,
1852
1853 .bdrv_co_get_block_status = iscsi_co_get_block_status,
1854 .bdrv_co_discard = iscsi_co_discard,
1855 .bdrv_co_write_zeroes = iscsi_co_write_zeroes,
1856 .bdrv_co_readv = iscsi_co_readv,
1857 .bdrv_co_writev_flags = iscsi_co_writev_flags,
1858 .bdrv_co_flush_to_disk = iscsi_co_flush,
1859
1860 #ifdef __linux__
1861 .bdrv_aio_ioctl = iscsi_aio_ioctl,
1862 #endif
1863
1864 .bdrv_detach_aio_context = iscsi_detach_aio_context,
1865 .bdrv_attach_aio_context = iscsi_attach_aio_context,
1866 };
1867
1868 static QemuOptsList qemu_iscsi_opts = {
1869 .name = "iscsi",
1870 .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
1871 .desc = {
1872 {
1873 .name = "user",
1874 .type = QEMU_OPT_STRING,
1875 .help = "username for CHAP authentication to target",
1876 },{
1877 .name = "password",
1878 .type = QEMU_OPT_STRING,
1879 .help = "password for CHAP authentication to target",
1880 },{
1881 .name = "password-secret",
1882 .type = QEMU_OPT_STRING,
1883 .help = "ID of the secret providing password for CHAP "
1884 "authentication to target",
1885 },{
1886 .name = "header-digest",
1887 .type = QEMU_OPT_STRING,
1888 .help = "HeaderDigest setting. "
1889 "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
1890 },{
1891 .name = "initiator-name",
1892 .type = QEMU_OPT_STRING,
1893 .help = "Initiator iqn name to use when connecting",
1894 },{
1895 .name = "timeout",
1896 .type = QEMU_OPT_NUMBER,
1897 .help = "Request timeout in seconds (default 0 = no timeout)",
1898 },
1899 { /* end of list */ }
1900 },
1901 };
1902
1903 static void iscsi_block_init(void)
1904 {
1905 bdrv_register(&bdrv_iscsi);
1906 qemu_add_opts(&qemu_iscsi_opts);
1907 }
1908
1909 block_init(iscsi_block_init);