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