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