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