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