VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/ISCSIHDDCore.cpp@ 31714

Last change on this file since 31714 was 31714, checked in by vboxsync, 15 years ago

iSCSI: Bug fixes. ExpStartSN should start with 0 because the field is reserved for the first login request PDU. Check if the target supports command queuing. Fixes netbsd-iscsi target. Correct transfer direction for flush requests (fixes LIO targets)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 188.7 KB
Line 
1/* $Id: ISCSIHDDCore.cpp 31714 2010-08-16 19:37:05Z vboxsync $ */
2/** @file
3 * iSCSI initiator driver, VD backend.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_VD_ISCSI
23#include <VBox/VBoxHDD-Plugin.h>
24#define VBOX_VDICORE_VD /* Signal that the header is included from here. */
25#include "VDICore.h"
26#include <VBox/err.h>
27
28#include <VBox/log.h>
29#include <iprt/alloc.h>
30#include <iprt/assert.h>
31#include <iprt/uuid.h>
32#include <iprt/file.h>
33#include <iprt/string.h>
34#include <iprt/asm.h>
35#include <iprt/thread.h>
36#include <iprt/semaphore.h>
37#include <iprt/md5.h>
38#include <iprt/tcp.h>
39#include <iprt/time.h>
40#include <VBox/scsi.h>
41
42
43/*******************************************************************************
44* Defined Constants And Macros *
45*******************************************************************************/
46
47/** Default port number to use for iSCSI. */
48#define ISCSI_DEFAULT_PORT 3260
49
50
51/** Converts a number in the range of 0 - 15 into the corresponding hex char. */
52#define NUM_2_HEX(b) ('0' + (b) + (((b) > 9) ? 39 : 0))
53/** Converts a hex char into the corresponding number in the range 0-15. */
54#define HEX_2_NUM(c) (((c) <= '9') ? ((c) - '0') : (((c - 'A' + 10) & 0xf)))
55/* Converts a base64 char into the corresponding number in the range 0-63. */
56#define B64_2_NUM(c) ((c >= 'A' && c <= 'Z') ? (c - 'A') : (c >= 'a' && c <= 'z') ? (c - 'a' + 26) : (c >= '0' && c <= '9') ? (c - '0' + 52) : (c == '+') ? 62 : (c == '/') ? 63 : -1)
57
58
59/** Minumum CHAP_MD5 challenge length in bytes. */
60#define CHAP_MD5_CHALLENGE_MIN 16
61/** Maximum CHAP_MD5 challenge length in bytes. */
62#define CHAP_MD5_CHALLENGE_MAX 24
63
64
65/**
66 * SCSI peripheral device type. */
67typedef enum SCSIDEVTYPE
68{
69 /** direct-access device. */
70 SCSI_DEVTYPE_DISK = 0,
71 /** sequential-access device. */
72 SCSI_DEVTYPE_TAPE,
73 /** printer device. */
74 SCSI_DEVTYPE_PRINTER,
75 /** processor device. */
76 SCSI_DEVTYPE_PROCESSOR,
77 /** write-once device. */
78 SCSI_DEVTYPE_WORM,
79 /** CD/DVD device. */
80 SCSI_DEVTYPE_CDROM,
81 /** scanner device. */
82 SCSI_DEVTYPE_SCANNER,
83 /** optical memory device. */
84 SCSI_DEVTYPE_OPTICAL,
85 /** medium changer. */
86 SCSI_DEVTYPE_CHANGER,
87 /** communications device. */
88 SCSI_DEVTYPE_COMMUNICATION,
89 /** storage array controller device. */
90 SCSI_DEVTYPE_RAIDCTL = 0x0c,
91 /** enclosure services device. */
92 SCSI_DEVTYPE_ENCLOSURE,
93 /** simplified direct-access device. */
94 SCSI_DEVTYPE_SIMPLEDISK,
95 /** optical card reader/writer device. */
96 SCSI_DEVTYPE_OCRW,
97 /** bridge controller device. */
98 SCSI_DEVTYPE_BRIDGE,
99 /** object-based storage device. */
100 SCSI_DEVTYPE_OSD
101} SCSIDEVTYPE;
102
103/** Mask for extracting the SCSI device type out of the first byte of the INQUIRY response. */
104#define SCSI_DEVTYPE_MASK 0x1f
105
106/** Mask to extract the CmdQue bit out of the seventh byte of the INQUIRY resposne. */
107#define SCSI_INQUIRY_CMDQUE_MASK 0x02
108
109/** Maximum PDU payload size we can handle in one piece. Greater or equal than
110 * s_iscsiConfigDefaultWriteSplit. */
111#define ISCSI_DATA_LENGTH_MAX _256K
112
113/** Maximum PDU size we can handle in one piece. */
114#define ISCSI_RECV_PDU_BUFFER_SIZE (ISCSI_DATA_LENGTH_MAX + ISCSI_BHS_SIZE)
115
116
117/** Version of the iSCSI standard which this initiator driver can handle. */
118#define ISCSI_MY_VERSION 0
119
120
121/** Length of ISCSI basic header segment. */
122#define ISCSI_BHS_SIZE 48
123
124
125/** Reserved task tag value. */
126#define ISCSI_TASK_TAG_RSVD 0xffffffff
127
128
129/**
130 * iSCSI opcodes. */
131typedef enum ISCSIOPCODE
132{
133 /** NOP-Out. */
134 ISCSIOP_NOP_OUT = 0x00000000,
135 /** SCSI command. */
136 ISCSIOP_SCSI_CMD = 0x01000000,
137 /** SCSI task management request. */
138 ISCSIOP_SCSI_TASKMGMT_REQ = 0x02000000,
139 /** Login request. */
140 ISCSIOP_LOGIN_REQ = 0x03000000,
141 /** Text request. */
142 ISCSIOP_TEXT_REQ = 0x04000000,
143 /** SCSI Data-Out. */
144 ISCSIOP_SCSI_DATA_OUT = 0x05000000,
145 /** Logout request. */
146 ISCSIOP_LOGOUT_REQ = 0x06000000,
147 /** SNACK request. */
148 ISCSIOP_SNACK_REQ = 0x10000000,
149
150 /** NOP-In. */
151 ISCSIOP_NOP_IN = 0x20000000,
152 /** SCSI response. */
153 ISCSIOP_SCSI_RES = 0x21000000,
154 /** SCSI Task Management response. */
155 ISCSIOP_SCSI_TASKMGMT_RES = 0x22000000,
156 /** Login response. */
157 ISCSIOP_LOGIN_RES = 0x23000000,
158 /** Text response. */
159 ISCSIOP_TEXT_RES = 0x24000000,
160 /** SCSI Data-In. */
161 ISCSIOP_SCSI_DATA_IN = 0x25000000,
162 /** Logout response. */
163 ISCSIOP_LOGOUT_RES = 0x26000000,
164 /** Ready To Transfer (R2T). */
165 ISCSIOP_R2T = 0x31000000,
166 /** Asynchronous message. */
167 ISCSIOP_ASYN_MSG = 0x32000000,
168 /** Reject. */
169 ISCSIOP_REJECT = 0x3f000000
170} ISCSIOPCODE;
171
172/** Mask for extracting the iSCSI opcode out of the first header word. */
173#define ISCSIOP_MASK 0x3f000000
174
175
176/** ISCSI BHS word 0: Request should be processed immediately. */
177#define ISCSI_IMMEDIATE_DELIVERY_BIT 0x40000000
178
179/** ISCSI BHS word 0: This is the final PDU for this request/response. */
180#define ISCSI_FINAL_BIT 0x00800000
181/** ISCSI BHS word 0: Mask for extracting the CSG. */
182#define ISCSI_CSG_MASK 0x000c0000
183/** ISCSI BHS word 0: Shift offset for extracting the CSG. */
184#define ISCSI_CSG_SHIFT 18
185/** ISCSI BHS word 0: Mask for extracting the NSG. */
186#define ISCSI_NSG_MASK 0x00030000
187/** ISCSI BHS word 0: Shift offset for extracting the NSG. */
188#define ISCSI_NSG_SHIFT 16
189
190/** ISCSI BHS word 0: task attribute untagged */
191#define ISCSI_TASK_ATTR_UNTAGGED 0x00000000
192/** ISCSI BHS word 0: task attribute simple */
193#define ISCSI_TASK_ATTR_SIMPLE 0x00010000
194/** ISCSI BHS word 0: task attribute ordered */
195#define ISCSI_TASK_ATTR_ORDERED 0x00020000
196/** ISCSI BHS word 0: task attribute head of queue */
197#define ISCSI_TASK_ATTR_HOQ 0x00030000
198/** ISCSI BHS word 0: task attribute ACA */
199#define ISCSI_TASK_ATTR_ACA 0x00040000
200
201/** ISCSI BHS word 0: transit to next login phase. */
202#define ISCSI_TRANSIT_BIT 0x00800000
203/** ISCSI BHS word 0: continue with login negotiation. */
204#define ISCSI_CONTINUE_BIT 0x00400000
205
206/** ISCSI BHS word 0: residual underflow. */
207#define ISCSI_RESIDUAL_UNFL_BIT 0x00020000
208/** ISCSI BHS word 0: residual overflow. */
209#define ISCSI_RESIDUAL_OVFL_BIT 0x00040000
210/** ISCSI BHS word 0: Bidirectional read residual underflow. */
211#define ISCSI_BI_READ_RESIDUAL_UNFL_BIT 0x00080000
212/** ISCSI BHS word 0: Bidirectional read residual overflow. */
213#define ISCSI_BI_READ_RESIDUAL_OVFL_BIT 0x00100000
214
215/** ISCSI BHS word 0: SCSI response mask. */
216#define ISCSI_SCSI_RESPONSE_MASK 0x0000ff00
217/** ISCSI BHS word 0: SCSI status mask. */
218#define ISCSI_SCSI_STATUS_MASK 0x000000ff
219
220/** ISCSI BHS word 0: response includes status. */
221#define ISCSI_STATUS_BIT 0x00010000
222
223/** Maximum number of scatter/gather segments needed to send a PDU. */
224#define ISCSI_SG_SEGMENTS_MAX 4
225
226/** Number of entries in the command table. */
227#define ISCSI_CMD_WAITING_ENTRIES 32
228
229/**
230 * iSCSI login status class. */
231typedef enum ISCSILOGINSTATUSCLASS
232{
233 /** Success. */
234 ISCSI_LOGIN_STATUS_CLASS_SUCCESS = 0,
235 /** Redirection. */
236 ISCSI_LOGIN_STATUS_CLASS_REDIRECTION,
237 /** Initiator error. */
238 ISCSI_LOGIN_STATUS_CLASS_INITIATOR_ERROR,
239 /** Target error. */
240 ISCSI_LOGIN_STATUS_CLASS_TARGET_ERROR
241} ISCSILOGINSTATUSCLASS;
242
243
244/**
245 * iSCSI connection state. */
246typedef enum ISCSISTATE
247{
248 /** Not having a connection/session at all. */
249 ISCSISTATE_FREE,
250 /** Currently trying to login. */
251 ISCSISTATE_IN_LOGIN,
252 /** Normal operation, corresponds roughly to the Full Feature Phase. */
253 ISCSISTATE_NORMAL,
254 /** Currently trying to logout. */
255 ISCSISTATE_IN_LOGOUT
256} ISCSISTATE;
257
258/**
259 * iSCSI PDU send flags (and maybe more in the future). */
260typedef enum ISCSIPDUFLAGS
261{
262 /** No special flags */
263 ISCSIPDU_DEFAULT = 0,
264 /** Do not attempt to re-attach to the target if the connection is lost */
265 ISCSIPDU_NO_REATTACH = RT_BIT(1)
266} ISCSIPDUFLAGS;
267
268
269/*******************************************************************************
270* Structures and Typedefs *
271*******************************************************************************/
272
273/**
274 * iSCSI login negotiation parameter
275 */
276typedef struct ISCSIPARAMETER
277{
278 /** Name of the parameter. */
279 const char *pszParamName;
280 /** Value of the parameter. */
281 const char *pszParamValue;
282 /** Length of the binary parameter. 0=zero-terminated string. */
283 size_t cbParamValue;
284} ISCSIPARAMETER;
285
286
287/**
288 * iSCSI Response PDU buffer (scatter).
289 */
290typedef struct ISCSIRES
291{
292 /** Length of PDU segment. */
293 size_t cbSeg;
294 /** Pointer to PDU segment. */
295 void *pvSeg;
296} ISCSIRES;
297/** Pointer to an iSCSI Response PDU buffer. */
298typedef ISCSIRES *PISCSIRES;
299/** Pointer to a const iSCSI Response PDU buffer. */
300typedef ISCSIRES const *PCISCSIRES;
301
302
303/**
304 * iSCSI Request PDU buffer (gather).
305 */
306typedef struct ISCSIREQ
307{
308 /** Length of PDU segment in bytes. */
309 size_t cbSeg;
310 /** Pointer to PDU segment. */
311 const void *pcvSeg;
312} ISCSIREQ;
313/** Pointer to an iSCSI Request PDU buffer. */
314typedef ISCSIREQ *PISCSIREQ;
315/** Pointer to a const iSCSI Request PDU buffer. */
316typedef ISCSIREQ const *PCISCSIREQ;
317
318
319/**
320 * SCSI transfer directions.
321 */
322typedef enum SCSIXFER
323{
324 SCSIXFER_NONE = 0,
325 SCSIXFER_TO_TARGET,
326 SCSIXFER_FROM_TARGET,
327 SCSIXFER_TO_FROM_TARGET
328} SCSIXFER, *PSCSIXFER;
329
330/** Forward declaration. */
331typedef struct ISCSIIMAGE *PISCSIIMAGE;
332
333/**
334 * SCSI request structure.
335 */
336typedef struct SCSIREQ
337{
338 /** Transfer direction. */
339 SCSIXFER enmXfer;
340 /** Length of command block. */
341 size_t cbCmd;
342 /** Length of Initiator2Target data buffer. */
343 size_t cbI2TData;
344 /** Length of Target2Initiator data buffer. */
345 size_t cbT2IData;
346 /** Length of sense buffer
347 * This contains the number of sense bytes received upon completion. */
348 size_t cbSense;
349 /** Completion status of the command. */
350 uint8_t status;
351 /** Pointer to command block. */
352 void *pvCmd;
353 /** Pointer to sense buffer. */
354 void *pvSense;
355 /** Pointer to the Initiator2Target S/G list. */
356 PRTSGSEG paI2TSegs;
357 /** Number of entries in the I2T S/G list. */
358 unsigned cI2TSegs;
359 /** Pointer to the Target2Initiator S/G list. */
360 PRTSGSEG paT2ISegs;
361 /** Number of entries in the T2I S/G list. */
362 unsigned cT2ISegs;
363 /** S/G buffer for the target to initiator bits. */
364 RTSGBUF SgBufT2I;
365} SCSIREQ, *PSCSIREQ;
366
367/**
368 * Async request structure holding all necessary data for
369 * request processing.
370 */
371typedef struct SCSIREQASYNC
372{
373 /** I/O context associated with this request. */
374 PVDIOCTX pIoCtx;
375 /** Pointer to the SCSI request structure. */
376 PSCSIREQ pScsiReq;
377 /** The CDB. */
378 uint8_t abCDB[10];
379 /** The sense buffer. */
380 uint8_t abSense[96];
381 /** Status code to return if we got sense data. */
382 int rcSense;
383 /** Number of retries if the command completes with sense
384 * data before we return with an error.
385 */
386 unsigned cSenseRetries;
387 /** The number of entries in the I2T S/G list. */
388 unsigned cI2TSegs;
389 /** The number of entries in the T2I S/G list. */
390 unsigned cT2ISegs;
391 /** The S/G list - variable in size.
392 * This array holds both the I2T and T2I segments.
393 * The I2T segments are first and the T2I are second.
394 */
395 RTSGSEG aSegs[1];
396} SCSIREQASYNC, *PSCSIREQASYNC;
397
398typedef enum ISCSICMDTYPE
399{
400 /** Process a SCSI request. */
401 ISCSICMDTYPE_REQ = 0,
402 /** Call a function in the I/O thread. */
403 ISCSICMDTYPE_EXEC,
404 /** Usual 32bit hack. */
405 ISCSICMDTYPE_32BIT_HACK = 0x7fffffff
406} ISCSICMDTYPE;
407
408
409/** The command completion function. */
410typedef DECLCALLBACK(void) FNISCSICMDCOMPLETED(PISCSIIMAGE pImage, int rcReq, void *pvUser);
411/** Pointer to a command completion function. */
412typedef FNISCSICMDCOMPLETED *PFNISCSICMDCOMPLETED;
413
414/** The command execution function. */
415typedef DECLCALLBACK(int) FNISCSIEXEC(void *pvUser);
416/** Pointer to a command execution function. */
417typedef FNISCSIEXEC *PFNISCSIEXEC;
418
419/**
420 * Structure used to complete a synchronous request.
421 */
422typedef struct ISCSICMDSYNC
423{
424 /** Event sempahore to wakeup the waiting thread. */
425 RTSEMEVENT EventSem;
426 /** Status code of the command. */
427 int rcCmd;
428} ISCSICMDSYNC, *PISCSICMDSYNC;
429
430/**
431 * iSCSI command.
432 * Used to forward requests to the I/O thread
433 * if existing.
434 */
435typedef struct ISCSICMD
436{
437 /** Next one in the list. */
438 struct ISCSICMD *pNext;
439 /** Assigned ITT. */
440 uint32_t Itt;
441 /** Completion callback. */
442 PFNISCSICMDCOMPLETED pfnComplete;
443 /** Opaque user data. */
444 void *pvUser;
445 /** Command to execute. */
446 ISCSICMDTYPE enmCmdType;
447 /** Command type dependent data. */
448 union
449 {
450 /** Process a SCSI request. */
451 struct
452 {
453 /** The SCSI request to process. */
454 PSCSIREQ pScsiReq;
455 } ScsiReq;
456 /** Call a function in the I/O thread. */
457 struct
458 {
459 /** The method to execute. */
460 PFNISCSIEXEC pfnExec;
461 /** User data. */
462 void *pvUser;
463 } Exec;
464 } CmdType;
465} ISCSICMD, *PISCSICMD;
466
467/**
468 * Send iSCSI PDU.
469 * Contains all necessary data to send a PDU.
470 */
471typedef struct ISCSIPDUTX
472{
473 /** Pointer to the next PDu to send. */
474 struct ISCSIPDUTX *pNext;
475 /** The BHS. */
476 uint32_t aBHS[12];
477 /** The S/G buffer used for sending. */
478 RTSGBUF SgBuf;
479 /** Number of bytes to send until the PDU completed. */
480 size_t cbSgLeft;
481 /** The iSCSI command this PDU belongs to. */
482 PISCSICMD pIScsiCmd;
483 /** Number of segments in the request segments array. */
484 unsigned cISCSIReq;
485 /** The request segments - variable in size. */
486 RTSGSEG aISCSIReq[1];
487} ISCSIPDUTX, *PISCSIPDUTX;
488
489/**
490 * Block driver instance data.
491 */
492typedef struct ISCSIIMAGE
493{
494 /** Pointer to the filename (location). Not really used. */
495 const char *pszFilename;
496 /** Pointer to the initiator name. */
497 char *pszInitiatorName;
498 /** Pointer to the target name. */
499 char *pszTargetName;
500 /** Pointer to the target address. */
501 char *pszTargetAddress;
502 /** Pointer to the user name for authenticating the Initiator. */
503 char *pszInitiatorUsername;
504 /** Pointer to the secret for authenticating the Initiator. */
505 uint8_t *pbInitiatorSecret;
506 /** Length of the secret for authenticating the Initiator. */
507 size_t cbInitiatorSecret;
508 /** Pointer to the user name for authenticating the Target. */
509 char *pszTargetUsername;
510 /** Pointer to the secret for authenticating the Initiator. */
511 uint8_t *pbTargetSecret;
512 /** Length of the secret for authenticating the Initiator. */
513 size_t cbTargetSecret;
514 /** Limit for iSCSI writes, essentially limiting the amount of data
515 * written in a single write. This is negotiated with the target, so
516 * the actual size might be smaller. */
517 uint32_t cbWriteSplit;
518 /** Initiator session identifier. */
519 uint64_t ISID;
520 /** SCSI Logical Unit Number. */
521 uint64_t LUN;
522 /** Pointer to the per-disk VD interface list. */
523 PVDINTERFACE pVDIfsDisk;
524 /** Error interface. */
525 PVDINTERFACE pInterfaceError;
526 /** Error interface callback table. */
527 PVDINTERFACEERROR pInterfaceErrorCallbacks;
528 /** TCP network stack interface. */
529 PVDINTERFACE pInterfaceNet;
530 /** TCP network stack interface callback table. */
531 PVDINTERFACETCPNET pInterfaceNetCallbacks;
532 /** Pointer to the per-image VD interface list. */
533 PVDINTERFACE pVDIfsImage;
534 /** Config interface. */
535 PVDINTERFACE pInterfaceConfig;
536 /** Config interface callback table. */
537 PVDINTERFACECONFIG pInterfaceConfigCallbacks;
538 /** I/O interface. */
539 PVDINTERFACE pInterfaceIo;
540 /** I/O interface callback table. */
541 PVDINTERFACEIO pInterfaceIoCallbacks;
542 /** Image open flags. */
543 unsigned uOpenFlags;
544 /** Number of re-login retries when a connection fails. */
545 uint32_t cISCSIRetries;
546 /** Sector size on volume. */
547 uint32_t cbSector;
548 /** Size of volume in sectors. */
549 uint64_t cVolume;
550 /** Total volume size in bytes. Easier than multiplying the above values all the time. */
551 uint64_t cbSize;
552
553 /** Negotiated maximum data length when sending to target. */
554 uint32_t cbSendDataLength;
555 /** Negotiated maximum data length when receiving from target. */
556 uint32_t cbRecvDataLength;
557
558 /** Current state of the connection/session. */
559 ISCSISTATE state;
560 /** Flag whether the first Login Response PDU has been seen. */
561 bool FirstRecvPDU;
562 /** Initiator Task Tag of the last iSCSI request PDU. */
563 uint32_t ITT;
564 /** Sequence number of the last command. */
565 uint32_t CmdSN;
566 /** Sequence number of the next command expected by the target. */
567 uint32_t ExpCmdSN;
568 /** Maximum sequence number accepted by the target (determines size of window). */
569 uint32_t MaxCmdSN;
570 /** Expected sequence number of next status. */
571 uint32_t ExpStatSN;
572 /** Currently active request. */
573 PISCSIREQ paCurrReq;
574 /** Segment number of currently active request. */
575 uint32_t cnCurrReq;
576 /** Pointer to receive PDU buffer. (Freed by RT) */
577 void *pvRecvPDUBuf;
578 /** Length of receive PDU buffer. */
579 size_t cbRecvPDUBuf;
580 /** Mutex protecting against concurrent use from several threads. */
581 RTSEMMUTEX Mutex;
582
583 /** Pointer to the target hostname. */
584 char *pszHostname;
585 /** Pointer to the target hostname. */
586 uint32_t uPort;
587 /** Socket handle of the TCP connection. */
588 VDSOCKET Socket;
589 /** Timeout for read operations on the TCP connection (in milliseconds). */
590 uint32_t uReadTimeout;
591 /** Flag whether to automatically generate the initiator name. */
592 bool fAutomaticInitiatorName;
593 /** Flag whether to use the host IP stack or DevINIP. */
594 bool fHostIP;
595
596 /** Head of request queue */
597 PISCSICMD pScsiReqQueue;
598 /** Mutex protecting the request queue from concurrent access. */
599 RTSEMMUTEX MutexReqQueue;
600 /** I/O thread. */
601 RTTHREAD hThreadIo;
602 /** Flag whether the thread should be still running. */
603 volatile bool fRunning;
604 /* Flag whether the target supports command queuing. */
605 bool fCmdQueuingSupported;
606 /** Flag whether extended select is supported. */
607 bool fExtendedSelectSupported;
608 /** Padding used for aligning the PDUs. */
609 uint8_t aPadding[4];
610 /** Socket events to poll for. */
611 uint32_t fPollEvents;
612 /** Number of bytes to read to complete the current PDU. */
613 size_t cbRecvPDUResidual;
614 /** Current position in the PDU buffer. */
615 uint8_t *pbRecvPDUBufCur;
616 /** Flag whether we are currently reading the BHS. */
617 bool fRecvPDUBHS;
618 /** List of PDUs waiting to get transmitted. */
619 PISCSIPDUTX pIScsiPDUTxHead;
620 /** Tail of PDUs waiting to get transmitted. */
621 PISCSIPDUTX pIScsiPDUTxTail;
622 /** PDU we are currently transmitting. */
623 PISCSIPDUTX pIScsiPDUTxCur;
624 /** Number of commands waiting for an answer from the target.
625 * Used for timeout handling for poll.
626 */
627 unsigned cCmdsWaiting;
628 /** Table of commands waiting for a response from the target. */
629 PISCSICMD aCmdsWaiting[ISCSI_CMD_WAITING_ENTRIES];
630} ISCSIIMAGE;
631
632
633/*******************************************************************************
634* Static Variables *
635*******************************************************************************/
636
637/** Default initiator basename. */
638static const char *s_iscsiDefaultInitiatorBasename = "iqn.2009-08.com.sun.virtualbox.initiator";
639
640/** Default LUN. */
641static const char *s_iscsiConfigDefaultLUN = "0";
642
643/** Default timeout, 10 seconds. */
644static const char *s_iscsiConfigDefaultTimeout = "10000";
645
646/** Default write split value, less or equal to ISCSI_DATA_LENGTH_MAX. */
647static const char *s_iscsiConfigDefaultWriteSplit = "262144";
648
649/** Default host IP stack. */
650static const char *s_iscsiConfigDefaultHostIPStack = "1";
651
652/** Description of all accepted config parameters. */
653static const VDCONFIGINFO s_iscsiConfigInfo[] =
654{
655 { "TargetName", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
656 /* LUN is defined of string type to handle the "enc" prefix. */
657 { "LUN", s_iscsiConfigDefaultLUN, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
658 { "TargetAddress", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
659 { "InitiatorName", NULL, VDCFGVALUETYPE_STRING, 0 },
660 { "InitiatorUsername", NULL, VDCFGVALUETYPE_STRING, 0 },
661 { "InitiatorSecret", NULL, VDCFGVALUETYPE_BYTES, 0 },
662 { "TargetUsername", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_EXPERT },
663 { "TargetSecret", NULL, VDCFGVALUETYPE_BYTES, VD_CFGKEY_EXPERT },
664 { "WriteSplit", s_iscsiConfigDefaultWriteSplit, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
665 { "Timeout", s_iscsiConfigDefaultTimeout, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
666 { "HostIPStack", s_iscsiConfigDefaultHostIPStack, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
667 { NULL, NULL, VDCFGVALUETYPE_INTEGER, 0 }
668};
669
670/*******************************************************************************
671* Internal Functions *
672*******************************************************************************/
673
674/* iSCSI low-level functions (only to be used from the iSCSI high-level functions). */
675static uint32_t iscsiNewITT(PISCSIIMAGE pImage);
676static int iscsiSendPDU(PISCSIIMAGE pImage, PISCSIREQ paReq, uint32_t cnReq, uint32_t uFlags);
677static int iscsiRecvPDU(PISCSIIMAGE pImage, uint32_t itt, PISCSIRES paRes, uint32_t cnRes);
678static int iscsiRecvPDUAsync(PISCSIIMAGE pImage);
679static int iscsiSendPDUAsync(PISCSIIMAGE pImage);
680static int iscsiValidatePDU(PISCSIRES paRes, uint32_t cnRes);
681static int iscsiRecvPDUProcess(PISCSIIMAGE pImage, PISCSIRES paRes, uint32_t cnRes);
682static int iscsiPDUTxPrepare(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd);
683static int iscsiRecvPDUUpdateRequest(PISCSIIMAGE pImage, PISCSIRES paRes, uint32_t cnRes);
684static void iscsiCmdComplete(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd, int rcCmd);
685static int iscsiTextAddKeyValue(uint8_t *pbBuf, size_t cbBuf, size_t *pcbBufCurr, const char *pcszKey, const char *pcszValue, size_t cbValue);
686static int iscsiTextGetKeyValue(const uint8_t *pbBuf, size_t cbBuf, const char *pcszKey, const char **ppcszValue);
687static int iscsiStrToBinary(const char *pcszValue, uint8_t *pbValue, size_t *pcbValue);
688static int iscsiUpdateParameters(PISCSIIMAGE pImage, const uint8_t *pbBuf, size_t cbBuf);
689
690/* Serial number arithmetic comparison. */
691static bool serial_number_less(uint32_t sn1, uint32_t sn2);
692
693/* CHAP-MD5 functions. */
694#ifdef IMPLEMENT_TARGET_AUTH
695static void chap_md5_generate_challenge(uint8_t *pbChallenge, size_t *pcbChallenge);
696#endif
697static void chap_md5_compute_response(uint8_t *pbResponse, uint8_t id, const uint8_t *pbChallenge, size_t cbChallenge,
698 const uint8_t *pbSecret, size_t cbSecret);
699
700
701/**
702 * Internal: signal an error to the frontend.
703 */
704DECLINLINE(int) iscsiError(PISCSIIMAGE pImage, int rc, RT_SRC_POS_DECL,
705 const char *pszFormat, ...)
706{
707 va_list va;
708 va_start(va, pszFormat);
709 if (pImage->pInterfaceError)
710 pImage->pInterfaceErrorCallbacks->pfnError(pImage->pInterfaceError->pvUser, rc, RT_SRC_POS_ARGS,
711 pszFormat, va);
712 va_end(va);
713
714#ifdef LOG_ENABLED
715 va_start(va, pszFormat);
716 Log(("iscsiError(%d/%s): %N\n", iLine, pszFunction, pszFormat, &va));
717 va_end(va);
718#endif
719 return rc;
720}
721
722DECLINLINE(bool) iscsiIsClientConnected(PISCSIIMAGE pImage)
723{
724 return pImage->Socket != NIL_VDSOCKET
725 && pImage->pInterfaceNetCallbacks->pfnIsClientConnected(pImage->Socket);
726}
727
728/**
729 * Calculates the hash for the given ITT used
730 * to look up the command in the table.
731 */
732DECLINLINE(uint32_t) iscsiIttHash(uint32_t Itt)
733{
734 return Itt % ISCSI_CMD_WAITING_ENTRIES;
735}
736
737static PISCSICMD iscsiCmdGetFromItt(PISCSIIMAGE pImage, uint32_t Itt)
738{
739 PISCSICMD pIScsiCmd = NULL;
740
741 pIScsiCmd = pImage->aCmdsWaiting[iscsiIttHash(Itt)];
742
743 while ( pIScsiCmd
744 && pIScsiCmd->Itt != Itt)
745 pIScsiCmd = pIScsiCmd->pNext;
746
747 return pIScsiCmd;
748}
749
750static void iscsiCmdInsert(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd)
751{
752 PISCSICMD pIScsiCmdOld;
753 uint32_t idx = iscsiIttHash(pIScsiCmd->Itt);
754
755 Assert(!pIScsiCmd->pNext);
756
757 pIScsiCmdOld = pImage->aCmdsWaiting[idx];
758 pIScsiCmd->pNext = pIScsiCmdOld;
759 pImage->aCmdsWaiting[idx] = pIScsiCmd;
760 pImage->cCmdsWaiting++;
761}
762
763static PISCSICMD iscsiCmdRemove(PISCSIIMAGE pImage, uint32_t Itt)
764{
765 PISCSICMD pIScsiCmd = NULL;
766 PISCSICMD pIScsiCmdPrev = NULL;
767 uint32_t idx = iscsiIttHash(Itt);
768
769 pIScsiCmd = pImage->aCmdsWaiting[idx];
770
771 while ( pIScsiCmd
772 && pIScsiCmd->Itt != Itt)
773 {
774 pIScsiCmdPrev = pIScsiCmd;
775 pIScsiCmd = pIScsiCmd->pNext;
776 }
777
778 if (pIScsiCmd)
779 {
780 if (pIScsiCmdPrev)
781 {
782 Assert(!pIScsiCmd->pNext || VALID_PTR(pIScsiCmd->pNext));
783 pIScsiCmdPrev->pNext = pIScsiCmd->pNext;
784 }
785 else
786 {
787 pImage->aCmdsWaiting[idx] = pIScsiCmd->pNext;
788 Assert(!pImage->aCmdsWaiting[idx] || VALID_PTR(pImage->aCmdsWaiting[idx]));
789 }
790 pImage->cCmdsWaiting--;
791 }
792
793 return pIScsiCmd;
794}
795
796/**
797 * Removes all commands from the table and returns the
798 * list head
799 *
800 * @returns Pointer to the head of teh command list.
801 * @param pImage iSCSI connection to use.
802 */
803static PISCSICMD iscsiCmdRemoveAll(PISCSIIMAGE pImage)
804{
805 PISCSICMD pIScsiCmdHead = NULL;
806
807 for (unsigned idx = 0; idx < RT_ELEMENTS(pImage->aCmdsWaiting); idx++)
808 {
809 PISCSICMD pHead;
810 PISCSICMD pTail;
811
812 pHead = pImage->aCmdsWaiting[idx];
813 pImage->aCmdsWaiting[idx] = NULL;
814
815 if (pHead)
816 {
817 /* Get the tail. */
818 pTail = pHead;
819 while (pTail->pNext)
820 pTail = pTail->pNext;
821
822 /* Concatenate. */
823 pTail->pNext = pIScsiCmdHead;
824 pIScsiCmdHead = pHead;
825 }
826 }
827
828 return pIScsiCmdHead;
829}
830
831static int iscsiTransportConnect(PISCSIIMAGE pImage)
832{
833 int rc;
834 if (!pImage->pszHostname)
835 return VERR_NET_DEST_ADDRESS_REQUIRED;
836
837 rc = pImage->pInterfaceNetCallbacks->pfnClientConnect(pImage->Socket, pImage->pszHostname, pImage->uPort);
838 if (RT_FAILURE(rc))
839 {
840 if ( rc == VERR_NET_CONNECTION_REFUSED
841 || rc == VERR_NET_CONNECTION_RESET
842 || rc == VERR_NET_UNREACHABLE
843 || rc == VERR_NET_HOST_UNREACHABLE
844 || rc == VERR_NET_CONNECTION_TIMED_OUT)
845 {
846 /* Standardize return value for no connection. */
847 rc = VERR_NET_CONNECTION_REFUSED;
848 }
849 return rc;
850 }
851
852 /* Disable Nagle algorithm, we want things to be sent immediately. */
853 pImage->pInterfaceNetCallbacks->pfnSetSendCoalescing(pImage->Socket, false);
854
855 /* Make initiator name and ISID unique on this host. */
856 RTNETADDR LocalAddr;
857 rc = pImage->pInterfaceNetCallbacks->pfnGetLocalAddress(pImage->Socket,
858 &LocalAddr);
859 if (RT_FAILURE(rc))
860 return rc;
861 if ( LocalAddr.uPort == RTNETADDR_PORT_NA
862 || LocalAddr.uPort > 65535)
863 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
864 pImage->ISID &= ~65535ULL;
865 pImage->ISID |= LocalAddr.uPort;
866 /* Eliminate the port so that it isn't included below. */
867 LocalAddr.uPort = RTNETADDR_PORT_NA;
868 if (pImage->fAutomaticInitiatorName)
869 {
870 if (pImage->pszInitiatorName)
871 RTStrFree(pImage->pszInitiatorName);
872 RTStrAPrintf(&pImage->pszInitiatorName, "%s:01:%RTnaddr",
873 s_iscsiDefaultInitiatorBasename, &LocalAddr);
874 if (!pImage->pszInitiatorName)
875 return VERR_NO_MEMORY;
876 }
877 return VINF_SUCCESS;
878}
879
880
881static int iscsiTransportRead(PISCSIIMAGE pImage, PISCSIRES paResponse, unsigned int cnResponse)
882{
883 int rc = VINF_SUCCESS;
884 unsigned int i = 0;
885 size_t cbToRead, cbActuallyRead, residual, cbSegActual = 0, cbAHSLength, cbDataLength;
886 char *pDst;
887
888 LogFlowFunc(("cnResponse=%d (%s:%d)\n", cnResponse, pImage->pszHostname, pImage->uPort));
889 if (!iscsiIsClientConnected(pImage))
890 {
891 /* Reconnecting makes no sense in this case, as there will be nothing
892 * to receive. We would just run into a timeout. */
893 rc = VERR_BROKEN_PIPE;
894 }
895
896 if (RT_SUCCESS(rc) && paResponse[0].cbSeg >= ISCSI_BHS_SIZE)
897 {
898 cbToRead = 0;
899 residual = ISCSI_BHS_SIZE; /* Do not read more than the BHS length before the true PDU length is known. */
900 cbSegActual = residual;
901 pDst = (char *)paResponse[i].pvSeg;
902 uint64_t u64Timeout = RTTimeMilliTS() + pImage->uReadTimeout;
903 do
904 {
905 int64_t cMilliesRemaining = u64Timeout - RTTimeMilliTS();
906 if (cMilliesRemaining <= 0)
907 {
908 rc = VERR_TIMEOUT;
909 break;
910 }
911 Assert(cMilliesRemaining < 1000000);
912 rc = pImage->pInterfaceNetCallbacks->pfnSelectOne(pImage->Socket,
913 cMilliesRemaining);
914 if (RT_FAILURE(rc))
915 break;
916 rc = pImage->pInterfaceNetCallbacks->pfnRead(pImage->Socket,
917 pDst, residual,
918 &cbActuallyRead);
919 if (RT_FAILURE(rc))
920 break;
921 if (cbActuallyRead == 0)
922 {
923 /* The other end has closed the connection. */
924 pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
925 pImage->state = ISCSISTATE_FREE;
926 rc = VERR_NET_CONNECTION_RESET;
927 break;
928 }
929 if (cbToRead == 0)
930 {
931 /* Currently reading the BHS. */
932 residual -= cbActuallyRead;
933 pDst += cbActuallyRead;
934 if (residual <= 40)
935 {
936 /* Enough data read to figure out the actual PDU size. */
937 uint32_t word1 = RT_N2H_U32(((uint32_t *)(paResponse[0].pvSeg))[1]);
938 cbAHSLength = (word1 & 0xff000000) >> 24;
939 cbAHSLength = ((cbAHSLength - 1) | 3) + 1; /* Add padding. */
940 cbDataLength = word1 & 0x00ffffff;
941 cbDataLength = ((cbDataLength - 1) | 3) + 1; /* Add padding. */
942 cbToRead = residual + cbAHSLength + cbDataLength;
943 residual += paResponse[0].cbSeg - ISCSI_BHS_SIZE;
944 if (residual > cbToRead)
945 residual = cbToRead;
946 cbSegActual = ISCSI_BHS_SIZE + cbAHSLength + cbDataLength;
947 /* Check whether we are already done with this PDU (no payload). */
948 if (cbToRead == 0)
949 break;
950 }
951 }
952 else
953 {
954 cbToRead -= cbActuallyRead;
955 if (cbToRead == 0)
956 break;
957 pDst += cbActuallyRead;
958 residual -= cbActuallyRead;
959 }
960 if (residual == 0)
961 {
962 i++;
963 if (i >= cnResponse)
964 {
965 /* No space left in receive buffers. */
966 rc = VERR_BUFFER_OVERFLOW;
967 break;
968 }
969 pDst = (char *)paResponse[i].pvSeg;
970 residual = paResponse[i].cbSeg;
971 if (residual > cbToRead)
972 residual = cbToRead;
973 cbSegActual = residual;
974 }
975 LogFlowFunc(("cbToRead=%u residual=%u cbSegActual=%u cbActuallRead=%u\n",
976 cbToRead, residual, cbSegActual, cbActuallyRead));
977 } while (true);
978 }
979 else
980 {
981 if (RT_SUCCESS(rc))
982 rc = VERR_BUFFER_OVERFLOW;
983 }
984 if (RT_SUCCESS(rc))
985 {
986 paResponse[i].cbSeg = cbSegActual;
987 for (i++; i < cnResponse; i++)
988 paResponse[i].cbSeg = 0;
989 }
990
991 if (RT_UNLIKELY( RT_FAILURE(rc)
992 && ( rc == VERR_NET_CONNECTION_RESET
993 || rc == VERR_NET_CONNECTION_ABORTED
994 || rc == VERR_NET_CONNECTION_RESET_BY_PEER
995 || rc == VERR_NET_CONNECTION_REFUSED
996 || rc == VERR_BROKEN_PIPE)))
997 {
998 /* Standardize return value for broken connection. */
999 rc = VERR_BROKEN_PIPE;
1000 }
1001
1002 LogFlowFunc(("returns %Rrc\n", rc));
1003 return rc;
1004}
1005
1006
1007static int iscsiTransportWrite(PISCSIIMAGE pImage, PISCSIREQ paRequest, unsigned int cnRequest)
1008{
1009 int rc = VINF_SUCCESS;
1010 uint32_t pad = 0;
1011 unsigned int i;
1012
1013 LogFlowFunc(("cnRequest=%d (%s:%d)\n", cnRequest, pImage->pszHostname, pImage->uPort));
1014 if (!iscsiIsClientConnected(pImage))
1015 {
1016 /* Attempt to reconnect if the connection was previously broken. */
1017 rc = iscsiTransportConnect(pImage);
1018 }
1019
1020 if (RT_SUCCESS(rc))
1021 {
1022 /* Construct scatter/gather buffer for entire request, worst case
1023 * needs twice as many entries to allow for padding. */
1024 unsigned cBuf = 0;
1025 for (i = 0; i < cnRequest; i++)
1026 {
1027 cBuf++;
1028 if (paRequest[i].cbSeg & 3)
1029 cBuf++;
1030 }
1031 Assert(cBuf < ISCSI_SG_SEGMENTS_MAX);
1032 RTSGBUF buf;
1033 RTSGSEG aSeg[ISCSI_SG_SEGMENTS_MAX];
1034 static char aPad[4] = { 0, 0, 0, 0 };
1035 RTSgBufInit(&buf, &aSeg[0], cBuf);
1036 unsigned iBuf = 0;
1037 for (i = 0; i < cnRequest; i++)
1038 {
1039 /* Actual data chunk. */
1040 aSeg[iBuf].pvSeg = (void *)paRequest[i].pcvSeg;
1041 aSeg[iBuf].cbSeg = paRequest[i].cbSeg;
1042 iBuf++;
1043 /* Insert proper padding before the next chunk. */
1044 if (paRequest[i].cbSeg & 3)
1045 {
1046 aSeg[iBuf].pvSeg = &aPad[0];
1047 aSeg[iBuf].cbSeg = 4 - (paRequest[i].cbSeg & 3);
1048 iBuf++;
1049 }
1050 }
1051 /* Send out the request, the socket is set to send data immediately,
1052 * avoiding unnecessary delays. */
1053 rc = pImage->pInterfaceNetCallbacks->pfnSgWrite(pImage->Socket, &buf);
1054
1055 }
1056
1057 if (RT_UNLIKELY( RT_FAILURE(rc)
1058 && ( rc == VERR_NET_CONNECTION_RESET
1059 || rc == VERR_NET_CONNECTION_ABORTED
1060 || rc == VERR_NET_CONNECTION_RESET_BY_PEER
1061 || rc == VERR_NET_CONNECTION_REFUSED
1062 || rc == VERR_BROKEN_PIPE)))
1063 {
1064 /* Standardize return value for broken connection. */
1065 rc = VERR_BROKEN_PIPE;
1066 }
1067
1068 LogFlowFunc(("returns %Rrc\n", rc));
1069 return rc;
1070}
1071
1072
1073static int iscsiTransportOpen(PISCSIIMAGE pImage)
1074{
1075 int rc = VINF_SUCCESS;
1076 size_t cbHostname = 0; /* shut up gcc */
1077 const char *pcszPort = NULL; /* shut up gcc */
1078 char *pszPortEnd;
1079 uint16_t uPort;
1080
1081 /* Clean up previous connection data. */
1082 if (iscsiIsClientConnected(pImage))
1083 {
1084 pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
1085 }
1086 if (pImage->pszHostname)
1087 {
1088 RTMemFree(pImage->pszHostname);
1089 pImage->pszHostname = NULL;
1090 pImage->uPort = 0;
1091 }
1092
1093 /* Locate the port number via the colon separating the hostname from the port. */
1094 if (*pImage->pszTargetAddress)
1095 {
1096 if (*pImage->pszTargetAddress != '[')
1097 {
1098 /* Normal hostname or IPv4 dotted decimal. */
1099 pcszPort = strchr(pImage->pszTargetAddress, ':');
1100 if (pcszPort != NULL)
1101 {
1102 cbHostname = pcszPort - pImage->pszTargetAddress;
1103 pcszPort++;
1104 }
1105 else
1106 cbHostname = strlen(pImage->pszTargetAddress);
1107 }
1108 else
1109 {
1110 /* IPv6 literal address. Contains colons, so skip to closing square bracket. */
1111 pcszPort = strchr(pImage->pszTargetAddress, ']');
1112 if (pcszPort != NULL)
1113 {
1114 pcszPort++;
1115 cbHostname = pcszPort - pImage->pszTargetAddress;
1116 if (*pcszPort == '\0')
1117 pcszPort = NULL;
1118 else if (*pcszPort != ':')
1119 rc = VERR_PARSE_ERROR;
1120 else
1121 pcszPort++;
1122 }
1123 else
1124 rc = VERR_PARSE_ERROR;
1125 }
1126 }
1127 else
1128 rc = VERR_PARSE_ERROR;
1129
1130 /* Now split address into hostname and port. */
1131 if (RT_SUCCESS(rc))
1132 {
1133 pImage->pszHostname = (char *)RTMemAlloc(cbHostname + 1);
1134 if (!pImage->pszHostname)
1135 rc = VERR_NO_MEMORY;
1136 else
1137 {
1138 memcpy(pImage->pszHostname, pImage->pszTargetAddress, cbHostname);
1139 pImage->pszHostname[cbHostname] = '\0';
1140 if (pcszPort != NULL)
1141 {
1142 rc = RTStrToUInt16Ex(pcszPort, &pszPortEnd, 0, &uPort);
1143 /* Note that RT_SUCCESS() macro to check the rc value is not strict enough in this case. */
1144 if (rc == VINF_SUCCESS && *pszPortEnd == '\0' && uPort != 0)
1145 {
1146 pImage->uPort = uPort;
1147 }
1148 else
1149 {
1150 rc = VERR_PARSE_ERROR;
1151 }
1152 }
1153 else
1154 pImage->uPort = ISCSI_DEFAULT_PORT;
1155 }
1156 }
1157
1158 if (RT_SUCCESS(rc))
1159 {
1160 if (!iscsiIsClientConnected(pImage))
1161 rc = iscsiTransportConnect(pImage);
1162 }
1163 else
1164 {
1165 if (pImage->pszHostname)
1166 {
1167 RTMemFree(pImage->pszHostname);
1168 pImage->pszHostname = NULL;
1169 }
1170 pImage->uPort = 0;
1171 }
1172
1173 LogFlowFunc(("returns %Rrc\n", rc));
1174 return rc;
1175}
1176
1177
1178static int iscsiTransportClose(PISCSIIMAGE pImage)
1179{
1180 int rc;
1181
1182 LogFlowFunc(("(%s:%d)\n", pImage->pszHostname, pImage->uPort));
1183 if (iscsiIsClientConnected(pImage))
1184 {
1185 rc = pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
1186 }
1187 else
1188 rc = VINF_SUCCESS;
1189 LogFlowFunc(("returns %Rrc\n", rc));
1190 return rc;
1191}
1192
1193
1194/**
1195 * Attach to an iSCSI target. Performs all operations necessary to enter
1196 * Full Feature Phase.
1197 *
1198 * @returns VBox status.
1199 * @param pImage The iSCSI connection state to be used.
1200 */
1201static int iscsiAttach(void *pvUser)
1202{
1203 int rc;
1204 uint32_t itt;
1205 uint32_t csg, nsg, substate;
1206 uint64_t isid_tsih;
1207 uint8_t bBuf[4096]; /* Should be large enough even for large authentication values. */
1208 size_t cbBuf;
1209 bool transit;
1210 uint8_t pbChallenge[1024]; /* RFC3720 specifies this as maximum. */
1211 size_t cbChallenge = 0; /* shut up gcc */
1212 uint8_t bChapIdx;
1213 uint8_t aResponse[RTMD5HASHSIZE];
1214 uint32_t cnISCSIReq;
1215 ISCSIREQ aISCSIReq[4];
1216 uint32_t aReqBHS[12];
1217 uint32_t cnISCSIRes;
1218 ISCSIRES aISCSIRes[2];
1219 uint32_t aResBHS[12];
1220 char *pszNext;
1221 PISCSIIMAGE pImage = (PISCSIIMAGE)pvUser;
1222
1223 bool fParameterNeg = true;;
1224 pImage->cbRecvDataLength = ISCSI_DATA_LENGTH_MAX;
1225 pImage->cbSendDataLength = RT_MIN(ISCSI_DATA_LENGTH_MAX, pImage->cbWriteSplit);
1226 char szMaxDataLength[16];
1227 RTStrPrintf(szMaxDataLength, sizeof(szMaxDataLength), "%u", ISCSI_DATA_LENGTH_MAX);
1228 ISCSIPARAMETER aParameterNeg[] =
1229 {
1230 { "HeaderDigest", "None", 0 },
1231 { "DataDigest", "None", 0 },
1232 { "MaxConnections", "1", 0 },
1233 { "InitialR2T", "No", 0 },
1234 { "ImmediateData", "Yes", 0 },
1235 { "MaxRecvDataSegmentLength", szMaxDataLength, 0 },
1236 { "MaxBurstLength", szMaxDataLength, 0 },
1237 { "FirstBurstLength", szMaxDataLength, 0 },
1238 { "DefaultTime2Wait", "0", 0 },
1239 { "DefaultTime2Retain", "60", 0 },
1240 { "DataPDUInOrder", "Yes", 0 },
1241 { "DataSequenceInOrder", "Yes", 0 },
1242 { "ErrorRecoveryLevel", "0", 0 },
1243 { "MaxOutstandingR2T", "1", 0 }
1244 };
1245
1246 LogFlowFunc(("entering\n"));
1247
1248 Assert(pImage->state == ISCSISTATE_FREE);
1249
1250 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
1251
1252 /* Make 100% sure the connection isn't reused for a new login. */
1253 iscsiTransportClose(pImage);
1254
1255restart:
1256 if (!iscsiIsClientConnected(pImage))
1257 {
1258 rc = iscsiTransportOpen(pImage);
1259 if (RT_FAILURE(rc))
1260 goto out;
1261 }
1262
1263 pImage->state = ISCSISTATE_IN_LOGIN;
1264 pImage->ITT = 1;
1265 pImage->FirstRecvPDU = true;
1266 pImage->CmdSN = 1;
1267 pImage->ExpCmdSN = 0;
1268 pImage->MaxCmdSN = 1;
1269 pImage->ExpStatSN = 0;
1270
1271 /*
1272 * Send login request to target.
1273 */
1274 itt = iscsiNewITT(pImage);
1275 csg = 0;
1276 nsg = 0;
1277 substate = 0;
1278 isid_tsih = pImage->ISID << 16; /* TSIH field currently always 0 */
1279
1280 do {
1281 transit = false;
1282 cbBuf = 0;
1283 /* Handle all cases with a single switch statement. */
1284 switch (csg << 8 | substate)
1285 {
1286 case 0x0000: /* security negotiation, step 0: propose authentication. */
1287 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "SessionType", "Normal", 0);
1288 if (RT_FAILURE(rc))
1289 goto out;
1290 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "InitiatorName", pImage->pszInitiatorName, 0);
1291 if (RT_FAILURE(rc))
1292 goto out;
1293 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "TargetName", pImage->pszTargetName, 0);
1294 if (RT_FAILURE(rc))
1295 goto out;
1296 if (pImage->pszInitiatorUsername == NULL)
1297 {
1298 /* No authentication. Immediately switch to next phase. */
1299 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "AuthMethod", "None", 0);
1300 if (RT_FAILURE(rc))
1301 goto out;
1302 nsg = 1;
1303 transit = true;
1304 }
1305 else
1306 {
1307 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "AuthMethod", "CHAP,None", 0);
1308 if (RT_FAILURE(rc))
1309 goto out;
1310 }
1311 break;
1312 case 0x0001: /* security negotiation, step 1: propose CHAP_MD5 variant. */
1313 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_A", "5", 0);
1314 if (RT_FAILURE(rc))
1315 goto out;
1316 break;
1317 case 0x0002: /* security negotiation, step 2: send authentication info. */
1318 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_N", pImage->pszInitiatorUsername, 0);
1319 if (RT_FAILURE(rc))
1320 goto out;
1321 chap_md5_compute_response(aResponse, bChapIdx, pbChallenge, cbChallenge,
1322 pImage->pbInitiatorSecret, pImage->cbInitiatorSecret);
1323 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_R", (const char *)aResponse, RTMD5HASHSIZE);
1324 if (RT_FAILURE(rc))
1325 goto out;
1326 nsg = 1;
1327 transit = true;
1328 break;
1329 case 0x0100: /* login operational negotiation, step 0: set parameters. */
1330 if (fParameterNeg)
1331 {
1332 for (unsigned i = 0; i < RT_ELEMENTS(aParameterNeg); i++)
1333 {
1334 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf,
1335 aParameterNeg[i].pszParamName,
1336 aParameterNeg[i].pszParamValue,
1337 aParameterNeg[i].cbParamValue);
1338 if (RT_FAILURE(rc))
1339 goto out;
1340 }
1341 fParameterNeg = false;
1342 }
1343
1344 nsg = 3;
1345 transit = true;
1346 break;
1347 case 0x0300: /* full feature phase. */
1348 default:
1349 /* Should never come here. */
1350 AssertMsgFailed(("send: Undefined login state %d substate %d\n", csg, substate));
1351 break;
1352 }
1353
1354 aReqBHS[0] = RT_H2N_U32( ISCSI_IMMEDIATE_DELIVERY_BIT
1355 | (csg << ISCSI_CSG_SHIFT)
1356 | (transit ? (nsg << ISCSI_NSG_SHIFT | ISCSI_TRANSIT_BIT) : 0)
1357 | ISCSI_MY_VERSION /* Minimum version. */
1358 | (ISCSI_MY_VERSION << 8) /* Maximum version. */
1359 | ISCSIOP_LOGIN_REQ); /* C=0 */
1360 aReqBHS[1] = RT_H2N_U32((uint32_t)cbBuf); /* TotalAHSLength=0 */
1361 aReqBHS[2] = RT_H2N_U32(isid_tsih >> 32);
1362 aReqBHS[3] = RT_H2N_U32(isid_tsih & 0xffffffff);
1363 aReqBHS[4] = itt;
1364 aReqBHS[5] = RT_H2N_U32(1 << 16); /* CID=1,reserved */
1365 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1366 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1367 aReqBHS[8] = 0; /* reserved */
1368 aReqBHS[9] = 0; /* reserved */
1369 aReqBHS[10] = 0; /* reserved */
1370 aReqBHS[11] = 0; /* reserved */
1371
1372 cnISCSIReq = 0;
1373 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1374 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1375 cnISCSIReq++;
1376
1377 aISCSIReq[cnISCSIReq].pcvSeg = bBuf;
1378 aISCSIReq[cnISCSIReq].cbSeg = cbBuf;
1379 cnISCSIReq++;
1380
1381 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq, ISCSIPDU_NO_REATTACH);
1382 if (RT_SUCCESS(rc))
1383 {
1384 ISCSIOPCODE cmd;
1385 ISCSILOGINSTATUSCLASS loginStatusClass;
1386
1387 cnISCSIRes = 0;
1388 aISCSIRes[cnISCSIRes].pvSeg = aResBHS;
1389 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aResBHS);
1390 cnISCSIRes++;
1391 aISCSIRes[cnISCSIRes].pvSeg = bBuf;
1392 aISCSIRes[cnISCSIRes].cbSeg = sizeof(bBuf);
1393 cnISCSIRes++;
1394
1395 rc = iscsiRecvPDU(pImage, itt, aISCSIRes, cnISCSIRes);
1396 if (RT_FAILURE(rc))
1397 break;
1398 /** @todo collect partial login responses with Continue bit set. */
1399 Assert(aISCSIRes[0].pvSeg == aResBHS);
1400 Assert(aISCSIRes[0].cbSeg >= ISCSI_BHS_SIZE);
1401 Assert((RT_N2H_U32(aResBHS[0]) & ISCSI_CONTINUE_BIT) == 0);
1402
1403 cmd = (ISCSIOPCODE)(RT_N2H_U32(aResBHS[0]) & ISCSIOP_MASK);
1404 if (cmd == ISCSIOP_LOGIN_RES)
1405 {
1406 if ((RT_N2H_U32(aResBHS[0]) & 0xff) != ISCSI_MY_VERSION)
1407 {
1408 iscsiTransportClose(pImage);
1409 rc = VERR_PARSE_ERROR;
1410 break; /* Give up immediately, as a RFC violation in version fields is very serious. */
1411 }
1412
1413 loginStatusClass = (ISCSILOGINSTATUSCLASS)(RT_N2H_U32(aResBHS[9]) >> 24);
1414 switch (loginStatusClass)
1415 {
1416 case ISCSI_LOGIN_STATUS_CLASS_SUCCESS:
1417 uint32_t targetCSG;
1418 uint32_t targetNSG;
1419 bool targetTransit;
1420
1421 if (pImage->FirstRecvPDU)
1422 {
1423 pImage->FirstRecvPDU = false;
1424 pImage->ExpStatSN = RT_N2H_U32(aResBHS[6]) + 1;
1425 }
1426
1427 targetCSG = (RT_N2H_U32(aResBHS[0]) & ISCSI_CSG_MASK) >> ISCSI_CSG_SHIFT;
1428 targetNSG = (RT_N2H_U32(aResBHS[0]) & ISCSI_NSG_MASK) >> ISCSI_NSG_SHIFT;
1429 targetTransit = !!(RT_N2H_U32(aResBHS[0]) & ISCSI_TRANSIT_BIT);
1430
1431 /* Handle all cases with a single switch statement. */
1432 switch (csg << 8 | substate)
1433 {
1434 case 0x0000: /* security negotiation, step 0: receive final authentication. */
1435 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1436 if (RT_FAILURE(rc))
1437 break;
1438
1439 const char *pcszAuthMethod;
1440
1441 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "AuthMethod", &pcszAuthMethod);
1442 if (RT_FAILURE(rc))
1443 {
1444 rc = VERR_PARSE_ERROR;
1445 break;
1446 }
1447 if (strcmp(pcszAuthMethod, "None") == 0)
1448 {
1449 /* Authentication offered, but none required. Skip to operational parameters. */
1450 csg = 1;
1451 nsg = 1;
1452 transit = true;
1453 substate = 0;
1454 break;
1455 }
1456 else if (strcmp(pcszAuthMethod, "CHAP") == 0 && targetNSG == 0 && !targetTransit)
1457 {
1458 /* CHAP authentication required, continue with next substate. */
1459 substate++;
1460 break;
1461 }
1462
1463 /* Unknown auth method or login response PDU headers incorrect. */
1464 rc = VERR_PARSE_ERROR;
1465 break;
1466 case 0x0001: /* security negotiation, step 1: receive final CHAP variant and challenge. */
1467 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1468 if (RT_FAILURE(rc))
1469 break;
1470
1471 const char *pcszChapAuthMethod;
1472 const char *pcszChapIdxTarget;
1473 const char *pcszChapChallengeStr;
1474
1475 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_A", &pcszChapAuthMethod);
1476 if (RT_FAILURE(rc))
1477 {
1478 rc = VERR_PARSE_ERROR;
1479 break;
1480 }
1481 if (strcmp(pcszChapAuthMethod, "5") != 0)
1482 {
1483 rc = VERR_PARSE_ERROR;
1484 break;
1485 }
1486 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_I", &pcszChapIdxTarget);
1487 if (RT_FAILURE(rc))
1488 {
1489 rc = VERR_PARSE_ERROR;
1490 break;
1491 }
1492 rc = RTStrToUInt8Ex(pcszChapIdxTarget, &pszNext, 0, &bChapIdx);
1493 if ((rc > VINF_SUCCESS) || *pszNext != '\0')
1494 {
1495 rc = VERR_PARSE_ERROR;
1496 break;
1497 }
1498 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_C", &pcszChapChallengeStr);
1499 if (RT_FAILURE(rc))
1500 {
1501 rc = VERR_PARSE_ERROR;
1502 break;
1503 }
1504 cbChallenge = sizeof(pbChallenge);
1505 rc = iscsiStrToBinary(pcszChapChallengeStr, pbChallenge, &cbChallenge);
1506 if (RT_FAILURE(rc))
1507 break;
1508 substate++;
1509 transit = true;
1510 break;
1511 case 0x0002: /* security negotiation, step 2: check authentication success. */
1512 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1513 if (RT_FAILURE(rc))
1514 break;
1515
1516 if (targetCSG == 0 && targetNSG == 1 && targetTransit)
1517 {
1518 /* Target wants to continue in login operational state, authentication success. */
1519 csg = 1;
1520 nsg = 3;
1521 substate = 0;
1522 break;
1523 }
1524 rc = VERR_PARSE_ERROR;
1525 break;
1526 case 0x0100: /* login operational negotiation, step 0: check results. */
1527 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1528 if (RT_FAILURE(rc))
1529 break;
1530
1531 if (targetCSG == 1 && targetNSG == 3 && targetTransit)
1532 {
1533 /* Target wants to continue in full feature phase, login finished. */
1534 csg = 3;
1535 nsg = 3;
1536 substate = 0;
1537 break;
1538 }
1539 else if (targetCSG == 1 && targetNSG == 1 && !targetTransit)
1540 {
1541 /* Target wants to negotiate certain parameters and
1542 * stay in login operational negotiation. */
1543 csg = 1;
1544 nsg = 3;
1545 substate = 0;
1546 }
1547 rc = VERR_PARSE_ERROR;
1548 break;
1549 case 0x0300: /* full feature phase. */
1550 default:
1551 AssertMsgFailed(("recv: Undefined login state %d substate %d\n", csg, substate));
1552 rc = VERR_PARSE_ERROR;
1553 break;
1554 }
1555 break;
1556 case ISCSI_LOGIN_STATUS_CLASS_REDIRECTION:
1557 const char *pcszTargetRedir;
1558
1559 /* Target has moved to some other location, as indicated in the TargetAddress key. */
1560 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "TargetAddress", &pcszTargetRedir);
1561 if (RT_FAILURE(rc))
1562 {
1563 rc = VERR_PARSE_ERROR;
1564 break;
1565 }
1566 if (pImage->pszTargetAddress)
1567 RTMemFree(pImage->pszTargetAddress);
1568 {
1569 size_t cb = strlen(pcszTargetRedir) + 1;
1570 pImage->pszTargetAddress = (char *)RTMemAlloc(cb);
1571 if (!pImage->pszTargetAddress)
1572 {
1573 rc = VERR_NO_MEMORY;
1574 break;
1575 }
1576 memcpy(pImage->pszTargetAddress, pcszTargetRedir, cb);
1577 }
1578 rc = iscsiTransportOpen(pImage);
1579 goto restart;
1580 case ISCSI_LOGIN_STATUS_CLASS_INITIATOR_ERROR:
1581 iscsiTransportClose(pImage);
1582 rc = VERR_IO_GEN_FAILURE;
1583 goto out;
1584 case ISCSI_LOGIN_STATUS_CLASS_TARGET_ERROR:
1585 iscsiTransportClose(pImage);
1586 rc = VINF_EOF;
1587 break;
1588 default:
1589 rc = VERR_PARSE_ERROR;
1590 }
1591
1592 if (csg == 3)
1593 {
1594 /*
1595 * Finished login, continuing with Full Feature Phase.
1596 */
1597 rc = VINF_SUCCESS;
1598 break;
1599 }
1600 }
1601 else
1602 {
1603 AssertMsgFailed(("%s: ignoring unexpected PDU with first word = %#08x\n", __FUNCTION__, RT_N2H_U32(aResBHS[0])));
1604 }
1605 }
1606 else
1607 break;
1608 } while (true);
1609
1610out:
1611 if (RT_FAILURE(rc))
1612 {
1613 /*
1614 * Close connection to target.
1615 */
1616 iscsiTransportClose(pImage);
1617 pImage->state = ISCSISTATE_FREE;
1618 }
1619 else
1620 pImage->state = ISCSISTATE_NORMAL;
1621
1622 RTSemMutexRelease(pImage->Mutex);
1623
1624 LogFlowFunc(("returning %Rrc\n", rc));
1625 LogRel(("iSCSI: login to target %s %s\n", pImage->pszTargetName, RT_SUCCESS(rc) ? "successful" : "failed"));
1626 return rc;
1627}
1628
1629
1630/**
1631 * Detach from an iSCSI target.
1632 *
1633 * @returns VBox status.
1634 * @param pImage The iSCSI connection state to be used.
1635 */
1636static int iscsiDetach(void *pvUser)
1637{
1638 int rc;
1639 uint32_t itt;
1640 uint32_t cnISCSIReq = 0;
1641 ISCSIREQ aISCSIReq[4];
1642 uint32_t aReqBHS[12];
1643 PISCSIIMAGE pImage = (PISCSIIMAGE)pvUser;
1644
1645 LogFlowFunc(("entering\n"));
1646
1647 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
1648
1649 if (pImage->state != ISCSISTATE_FREE && pImage->state != ISCSISTATE_IN_LOGOUT)
1650 {
1651 pImage->state = ISCSISTATE_IN_LOGOUT;
1652
1653 /*
1654 * Send logout request to target.
1655 */
1656 itt = iscsiNewITT(pImage);
1657 aReqBHS[0] = RT_H2N_U32(ISCSI_FINAL_BIT | ISCSIOP_LOGOUT_REQ); /* I=0,F=1,Reason=close session */
1658 aReqBHS[1] = RT_H2N_U32(0); /* TotalAHSLength=0,DataSementLength=0 */
1659 aReqBHS[2] = 0; /* reserved */
1660 aReqBHS[3] = 0; /* reserved */
1661 aReqBHS[4] = itt;
1662 aReqBHS[5] = 0; /* reserved */
1663 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1664 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1665 aReqBHS[8] = 0; /* reserved */
1666 aReqBHS[9] = 0; /* reserved */
1667 aReqBHS[10] = 0; /* reserved */
1668 aReqBHS[11] = 0; /* reserved */
1669 pImage->CmdSN++;
1670
1671 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1672 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1673 cnISCSIReq++;
1674
1675 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq, ISCSIPDU_NO_REATTACH);
1676 if (RT_SUCCESS(rc))
1677 {
1678 /*
1679 * Read logout response from target.
1680 */
1681 ISCSIRES aISCSIRes;
1682 uint32_t aResBHS[12];
1683
1684 aISCSIRes.pvSeg = aResBHS;
1685 aISCSIRes.cbSeg = sizeof(aResBHS);
1686 rc = iscsiRecvPDU(pImage, itt, &aISCSIRes, 1);
1687 if (RT_SUCCESS(rc))
1688 {
1689 if (RT_N2H_U32(aResBHS[0]) != (ISCSI_FINAL_BIT | ISCSIOP_LOGOUT_RES))
1690 AssertMsgFailed(("iSCSI Logout response invalid\n"));
1691 }
1692 else
1693 AssertMsgFailed(("iSCSI Logout response error, rc=%Rrc\n", rc));
1694 }
1695 else
1696 AssertMsgFailed(("Could not send iSCSI Logout request, rc=%Rrc\n", rc));
1697 }
1698
1699 if (pImage->state != ISCSISTATE_FREE)
1700 {
1701 /*
1702 * Close connection to target.
1703 */
1704 rc = iscsiTransportClose(pImage);
1705 if (RT_FAILURE(rc))
1706 AssertMsgFailed(("Could not close connection to target, rc=%Rrc\n", rc));
1707 }
1708
1709 pImage->state = ISCSISTATE_FREE;
1710
1711 RTSemMutexRelease(pImage->Mutex);
1712
1713 LogFlowFunc(("leaving\n"));
1714 LogRel(("iSCSI: logout to target %s\n", pImage->pszTargetName));
1715 return VINF_SUCCESS;
1716}
1717
1718
1719/**
1720 * Perform a command on an iSCSI target. Target must be already in
1721 * Full Feature Phase.
1722 *
1723 * @returns VBOX status.
1724 * @param pImage The iSCSI connection state to be used.
1725 * @param pRequest Command descriptor. Contains all information about
1726 * the command, its transfer directions and pointers
1727 * to the buffer(s) used for transferring data and
1728 * status information.
1729 */
1730static int iscsiCommand(PISCSIIMAGE pImage, PSCSIREQ pRequest)
1731{
1732 int rc;
1733 uint32_t itt;
1734 uint32_t cbData;
1735 uint32_t cnISCSIReq = 0;
1736 ISCSIREQ aISCSIReq[4];
1737 uint32_t aReqBHS[12];
1738
1739 uint32_t *pDst = NULL;
1740 size_t cbBufLength;
1741 uint32_t aStatus[256]; /**< Plenty of buffer for status information. */
1742 uint32_t ExpDataSN = 0;
1743 bool final = false;
1744
1745 LogFlowFunc(("entering, CmdSN=%d\n", pImage->CmdSN));
1746
1747 Assert(pRequest->enmXfer != SCSIXFER_TO_FROM_TARGET); /**< @todo not yet supported, would require AHS. */
1748 Assert(pRequest->cbI2TData <= 0xffffff); /* larger transfers would require R2T support. */
1749 Assert(pRequest->cbCmd <= 16); /* would cause buffer overrun below. */
1750
1751 /* If not in normal state, then the transport connection was dropped. Try
1752 * to reestablish by logging in, the target might be responsive again. */
1753 if (pImage->state == ISCSISTATE_FREE)
1754 rc = iscsiAttach(pImage);
1755
1756 /* If still not in normal state, then the underlying transport connection
1757 * cannot be established. Get out before bad things happen (and make
1758 * sure the caller suspends the VM again). */
1759 if (pImage->state != ISCSISTATE_NORMAL)
1760 {
1761 rc = VERR_NET_CONNECTION_REFUSED;
1762 goto out;
1763 }
1764
1765 /*
1766 * Send SCSI command to target with all I2T data included.
1767 */
1768 cbData = 0;
1769 if (pRequest->enmXfer == SCSIXFER_FROM_TARGET)
1770 cbData = (uint32_t)pRequest->cbT2IData;
1771 else
1772 cbData = (uint32_t)pRequest->cbI2TData;
1773
1774 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
1775
1776 itt = iscsiNewITT(pImage);
1777 memset(aReqBHS, 0, sizeof(aReqBHS));
1778 aReqBHS[0] = RT_H2N_U32( ISCSI_FINAL_BIT | ISCSI_TASK_ATTR_ORDERED | ISCSIOP_SCSI_CMD
1779 | (pRequest->enmXfer << 21)); /* I=0,F=1,Attr=Ordered */
1780 aReqBHS[1] = RT_H2N_U32(0x00000000 | ((uint32_t)pRequest->cbI2TData & 0xffffff)); /* TotalAHSLength=0 */
1781 aReqBHS[2] = RT_H2N_U32(pImage->LUN >> 32);
1782 aReqBHS[3] = RT_H2N_U32(pImage->LUN & 0xffffffff);
1783 aReqBHS[4] = itt;
1784 aReqBHS[5] = RT_H2N_U32(cbData);
1785 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1786 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1787 memcpy(aReqBHS + 8, pRequest->pvCmd, pRequest->cbCmd);
1788 pImage->CmdSN++;
1789
1790 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1791 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1792 cnISCSIReq++;
1793
1794 if ( pRequest->enmXfer == SCSIXFER_TO_TARGET
1795 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET)
1796 {
1797 Assert(pRequest->cI2TSegs == 1);
1798 aISCSIReq[cnISCSIReq].pcvSeg = pRequest->paI2TSegs[0].pvSeg;
1799 aISCSIReq[cnISCSIReq].cbSeg = pRequest->paI2TSegs[0].cbSeg; /* Padding done by transport. */
1800 cnISCSIReq++;
1801 }
1802
1803 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq, ISCSIPDU_DEFAULT);
1804 if (RT_FAILURE(rc))
1805 goto out_release;
1806
1807 /* Place SCSI request in queue. */
1808 pImage->paCurrReq = aISCSIReq;
1809 pImage->cnCurrReq = cnISCSIReq;
1810
1811 /*
1812 * Read SCSI response/data in PDUs from target.
1813 */
1814 if ( pRequest->enmXfer == SCSIXFER_FROM_TARGET
1815 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET)
1816 {
1817 Assert(pRequest->cT2ISegs == 1);
1818 pDst = (uint32_t *)pRequest->paT2ISegs[0].pvSeg;
1819 cbBufLength = pRequest->paT2ISegs[0].cbSeg;
1820 }
1821 else
1822 cbBufLength = 0;
1823
1824 do {
1825 uint32_t cnISCSIRes = 0;
1826 ISCSIRES aISCSIRes[4];
1827 uint32_t aResBHS[12];
1828
1829 aISCSIRes[cnISCSIRes].pvSeg = aResBHS;
1830 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aResBHS);
1831 cnISCSIRes++;
1832 if (cbBufLength != 0 &&
1833 ( pRequest->enmXfer == SCSIXFER_FROM_TARGET
1834 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET))
1835 {
1836 aISCSIRes[cnISCSIRes].pvSeg = pDst;
1837 aISCSIRes[cnISCSIRes].cbSeg = cbBufLength;
1838 cnISCSIRes++;
1839 }
1840 /* Always reserve space for the status - it's impossible to tell
1841 * beforehand whether this will be the final PDU or not. */
1842 aISCSIRes[cnISCSIRes].pvSeg = aStatus;
1843 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aStatus);
1844 cnISCSIRes++;
1845
1846 rc = iscsiRecvPDU(pImage, itt, aISCSIRes, cnISCSIRes);
1847 if (RT_FAILURE(rc))
1848 break;
1849
1850 final = !!(RT_N2H_U32(aResBHS[0]) & ISCSI_FINAL_BIT);
1851 ISCSIOPCODE cmd = (ISCSIOPCODE)(RT_N2H_U32(aResBHS[0]) & ISCSIOP_MASK);
1852 if (cmd == ISCSIOP_SCSI_RES)
1853 {
1854 /* This is the final PDU which delivers the status (and may be omitted if
1855 * the last Data-In PDU included successful completion status). Note
1856 * that ExpStatSN has been bumped already in iscsiRecvPDU. */
1857 if (!final || ((RT_N2H_U32(aResBHS[0]) & 0x0000ff00) != 0) || (RT_N2H_U32(aResBHS[6]) != pImage->ExpStatSN - 1))
1858 {
1859 /* SCSI Response in the wrong place or with a (target) failure. */
1860 rc = VERR_PARSE_ERROR;
1861 break;
1862 }
1863 /* The following is a bit tricky, as in error situations we may
1864 * get the status only instead of the result data plus optional
1865 * status. Thus the status may have ended up partially in the
1866 * data area. */
1867 pRequest->status = RT_N2H_U32(aResBHS[0]) & 0x000000ff;
1868 cbData = RT_N2H_U32(aResBHS[1]) & 0x00ffffff;
1869 if (cbData >= 2)
1870 {
1871 uint32_t cbStat = RT_N2H_U32(((uint32_t *)aISCSIRes[1].pvSeg)[0]) >> 16;
1872 if (cbStat + 2 > cbData)
1873 {
1874 rc = VERR_BUFFER_OVERFLOW;
1875 break;
1876 }
1877 /* Truncate sense data if it doesn't fit into the buffer. */
1878 pRequest->cbSense = RT_MIN(cbStat, pRequest->cbSense);
1879 memcpy(pRequest->pvSense,
1880 ((const char *)aISCSIRes[1].pvSeg) + 2,
1881 RT_MIN(aISCSIRes[1].cbSeg - 2, pRequest->cbSense));
1882 if ( cnISCSIRes > 2 && aISCSIRes[2].cbSeg
1883 && (ssize_t)pRequest->cbSense - aISCSIRes[1].cbSeg + 2 > 0)
1884 {
1885 memcpy((char *)pRequest->pvSense + aISCSIRes[1].cbSeg - 2,
1886 aISCSIRes[2].pvSeg,
1887 pRequest->cbSense - aISCSIRes[1].cbSeg + 2);
1888 }
1889 }
1890 else if (cbData == 1)
1891 {
1892 rc = VERR_PARSE_ERROR;
1893 break;
1894 }
1895 else
1896 pRequest->cbSense = 0;
1897 break;
1898 }
1899 else if (cmd == ISCSIOP_SCSI_DATA_IN)
1900 {
1901 /* A Data-In PDU carries some data that needs to be added to the received
1902 * data in response to the command. There may be both partial and complete
1903 * Data-In PDUs, so collect data until the status is included or the status
1904 * is sent in a separate SCSI Result frame (see above). */
1905 if (final && aISCSIRes[2].cbSeg != 0)
1906 {
1907 /* The received PDU is partially stored in the buffer for status.
1908 * Must not happen under normal circumstances and is a target error. */
1909 rc = VERR_BUFFER_OVERFLOW;
1910 break;
1911 }
1912 uint32_t len = RT_N2H_U32(aResBHS[1]) & 0x00ffffff;
1913 pDst = (uint32_t *)((char *)pDst + len);
1914 cbBufLength -= len;
1915 ExpDataSN++;
1916 if (final && (RT_N2H_U32(aResBHS[0]) & ISCSI_STATUS_BIT) != 0)
1917 {
1918 pRequest->status = RT_N2H_U32(aResBHS[0]) & 0x000000ff;
1919 pRequest->cbSense = 0;
1920 break;
1921 }
1922 }
1923 else
1924 {
1925 rc = VERR_PARSE_ERROR;
1926 break;
1927 }
1928 } while (true);
1929
1930 /* Remove SCSI request from queue. */
1931 pImage->paCurrReq = NULL;
1932 pImage->cnCurrReq = 0;
1933
1934out_release:
1935 if (rc == VERR_TIMEOUT)
1936 {
1937 /* Drop connection in case the target plays dead. Much better than
1938 * delaying the next requests until the timed out command actually
1939 * finishes. Also keep in mind that command shouldn't take longer than
1940 * about 30-40 seconds, or the guest will lose its patience. */
1941 iscsiTransportClose(pImage);
1942 pImage->state = ISCSISTATE_FREE;
1943 }
1944 RTSemMutexRelease(pImage->Mutex);
1945
1946out:
1947 LogFlowFunc(("returns %Rrc\n", rc));
1948 return rc;
1949}
1950
1951
1952/**
1953 * Generate a new Initiator Task Tag.
1954 *
1955 * @returns Initiator Task Tag.
1956 * @param pImage The iSCSI connection state to be used.
1957 */
1958static uint32_t iscsiNewITT(PISCSIIMAGE pImage)
1959{
1960 uint32_t next_itt;
1961
1962 next_itt = pImage->ITT++;
1963 if (pImage->ITT == ISCSI_TASK_TAG_RSVD)
1964 pImage->ITT = 0;
1965 return RT_H2N_U32(next_itt);
1966}
1967
1968
1969/**
1970 * Send an iSCSI request. The request can consist of several segments, which
1971 * are padded to 4 byte boundaries and concatenated.
1972 *
1973 * @returns VBOX status
1974 * @param pImage The iSCSI connection state to be used.
1975 * @param paReq Pointer to array of iSCSI request sections.
1976 * @param cnReq Number of valid iSCSI request sections in the array.
1977 * @param uFlags Flags controlling the exact send semantics.
1978 */
1979static int iscsiSendPDU(PISCSIIMAGE pImage, PISCSIREQ paReq, uint32_t cnReq,
1980 uint32_t uFlags)
1981{
1982 int rc = VINF_SUCCESS;
1983 /** @todo return VERR_VD_ISCSI_INVALID_STATE in the appropriate situations,
1984 * needs cleaning up of timeout/disconnect handling a bit, as otherwise
1985 * too many incorrect errors are signalled. */
1986 Assert(cnReq >= 1);
1987 Assert(paReq[0].cbSeg >= ISCSI_BHS_SIZE);
1988
1989 for (uint32_t i = 0; i < pImage->cISCSIRetries; i++)
1990 {
1991 rc = iscsiTransportWrite(pImage, paReq, cnReq);
1992 if (RT_SUCCESS(rc))
1993 break;
1994 if ( (uFlags & ISCSIPDU_NO_REATTACH)
1995 || (rc != VERR_BROKEN_PIPE && rc != VERR_NET_CONNECTION_REFUSED))
1996 break;
1997 /* No point in reestablishing the connection for a logout */
1998 if (pImage->state == ISCSISTATE_IN_LOGOUT)
1999 break;
2000 RTThreadSleep(500);
2001 if (pImage->state != ISCSISTATE_IN_LOGIN)
2002 {
2003 /* Attempt to re-login when a connection fails, but only when not
2004 * currently logging in. */
2005 rc = iscsiAttach(pImage);
2006 if (RT_FAILURE(rc))
2007 break;
2008 }
2009 }
2010 return rc;
2011}
2012
2013
2014/**
2015 * Wait for an iSCSI response with a matching Initiator Target Tag. The response is
2016 * split into several segments, as requested by the caller-provided buffer specification.
2017 * Remember that the response can be split into several PDUs by the sender, so make
2018 * sure that all parts are collected and processed appropriately by the caller.
2019 *
2020 * @returns VBOX status
2021 * @param pImage The iSCSI connection state to be used.
2022 * @param paRes Pointer to array of iSCSI response sections.
2023 * @param cnRes Number of valid iSCSI response sections in the array.
2024 */
2025static int iscsiRecvPDU(PISCSIIMAGE pImage, uint32_t itt, PISCSIRES paRes, uint32_t cnRes)
2026{
2027 int rc = VINF_SUCCESS;
2028 ISCSIRES aResBuf;
2029
2030 for (uint32_t i = 0; i < pImage->cISCSIRetries; i++)
2031 {
2032 aResBuf.pvSeg = pImage->pvRecvPDUBuf;
2033 aResBuf.cbSeg = pImage->cbRecvPDUBuf;
2034 rc = iscsiTransportRead(pImage, &aResBuf, 1);
2035 if (RT_FAILURE(rc))
2036 {
2037 if (rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_REFUSED)
2038 {
2039 /* No point in reestablishing the connection for a logout */
2040 if (pImage->state == ISCSISTATE_IN_LOGOUT)
2041 break;
2042 /* Connection broken while waiting for a response - wait a while and
2043 * try to restart by re-sending the original request (if any).
2044 * This also handles the connection reestablishment (login etc.). */
2045 RTThreadSleep(500);
2046 if (pImage->state != ISCSISTATE_IN_LOGIN)
2047 {
2048 /* Attempt to re-login when a connection fails, but only when not
2049 * currently logging in. */
2050 rc = iscsiAttach(pImage);
2051 if (RT_FAILURE(rc))
2052 break;
2053 }
2054 if (pImage->paCurrReq != NULL)
2055 {
2056 rc = iscsiSendPDU(pImage, pImage->paCurrReq, pImage->cnCurrReq, ISCSIPDU_DEFAULT);
2057 if (RT_FAILURE(rc))
2058 break;
2059 }
2060 }
2061 else
2062 {
2063 /* Signal other errors (VERR_BUFFER_OVERFLOW etc.) to the caller. */
2064 break;
2065 }
2066 }
2067 else
2068 {
2069 ISCSIOPCODE cmd;
2070 const uint32_t *pcvResSeg = (const uint32_t *)aResBuf.pvSeg;
2071
2072 /* Check whether the received PDU is valid, and update the internal state of
2073 * the iSCSI connection/session. */
2074 rc = iscsiValidatePDU(&aResBuf, 1);
2075 if (RT_FAILURE(rc))
2076 continue;
2077 cmd = (ISCSIOPCODE)(RT_N2H_U32(pcvResSeg[0]) & ISCSIOP_MASK);
2078 switch (cmd)
2079 {
2080 case ISCSIOP_SCSI_RES:
2081 case ISCSIOP_SCSI_TASKMGMT_RES:
2082 case ISCSIOP_SCSI_DATA_IN:
2083 case ISCSIOP_R2T:
2084 case ISCSIOP_ASYN_MSG:
2085 case ISCSIOP_TEXT_RES:
2086 case ISCSIOP_LOGIN_RES:
2087 case ISCSIOP_LOGOUT_RES:
2088 case ISCSIOP_REJECT:
2089 case ISCSIOP_NOP_IN:
2090 if (serial_number_less(pImage->MaxCmdSN, RT_N2H_U32(pcvResSeg[8])))
2091 pImage->MaxCmdSN = RT_N2H_U32(pcvResSeg[8]);
2092 if (serial_number_less(pImage->ExpCmdSN, RT_N2H_U32(pcvResSeg[7])))
2093 pImage->ExpCmdSN = RT_N2H_U32(pcvResSeg[7]);
2094 break;
2095 default:
2096 rc = VERR_PARSE_ERROR;
2097 }
2098 if (RT_FAILURE(rc))
2099 continue;
2100 if ( !pImage->FirstRecvPDU
2101 && (cmd != ISCSIOP_SCSI_DATA_IN || (RT_N2H_U32(pcvResSeg[0]) & ISCSI_STATUS_BIT)))
2102 {
2103 if (pImage->ExpStatSN == RT_N2H_U32(pcvResSeg[6]))
2104 {
2105 /* StatSN counter is not advanced on R2T and on a target SN update NOP-In. */
2106 if ( (cmd != ISCSIOP_R2T)
2107 && ((cmd != ISCSIOP_NOP_IN) || (RT_N2H_U32(pcvResSeg[4]) != ISCSI_TASK_TAG_RSVD)))
2108 pImage->ExpStatSN++;
2109 }
2110 else
2111 {
2112 rc = VERR_PARSE_ERROR;
2113 continue;
2114 }
2115 }
2116 /* Finally check whether the received PDU matches what the caller wants. */
2117 if ( itt == pcvResSeg[4]
2118 && itt != ISCSI_TASK_TAG_RSVD)
2119 {
2120 /* Copy received PDU (one segment) to caller-provided buffers. */
2121 uint32_t j;
2122 size_t cbSeg;
2123 const uint8_t *pSrc;
2124
2125 pSrc = (const uint8_t *)aResBuf.pvSeg;
2126 cbSeg = aResBuf.cbSeg;
2127 for (j = 0; j < cnRes; j++)
2128 {
2129 if (cbSeg > paRes[j].cbSeg)
2130 {
2131 memcpy(paRes[j].pvSeg, pSrc, paRes[j].cbSeg);
2132 pSrc += paRes[j].cbSeg;
2133 cbSeg -= paRes[j].cbSeg;
2134 }
2135 else
2136 {
2137 memcpy(paRes[j].pvSeg, pSrc, cbSeg);
2138 paRes[j].cbSeg = cbSeg;
2139 cbSeg = 0;
2140 break;
2141 }
2142 }
2143 if (cbSeg != 0)
2144 {
2145 rc = VERR_BUFFER_OVERFLOW;
2146 break;
2147 }
2148 for (j++; j < cnRes; j++)
2149 paRes[j].cbSeg = 0;
2150 break;
2151 }
2152 else if ( cmd == ISCSIOP_NOP_IN
2153 && RT_N2H_U32(pcvResSeg[5]) != ISCSI_TASK_TAG_RSVD)
2154 {
2155 uint32_t cnISCSIReq;
2156 ISCSIREQ aISCSIReq[4];
2157 uint32_t aReqBHS[12];
2158
2159 aReqBHS[0] = RT_H2N_U32(ISCSI_IMMEDIATE_DELIVERY_BIT | ISCSI_FINAL_BIT | ISCSIOP_NOP_OUT);
2160 aReqBHS[1] = RT_H2N_U32(0); /* TotalAHSLength=0,DataSementLength=0 */
2161 aReqBHS[2] = pcvResSeg[2]; /* copy LUN from NOP-In */
2162 aReqBHS[3] = pcvResSeg[3]; /* copy LUN from NOP-In */
2163 aReqBHS[4] = RT_H2N_U32(ISCSI_TASK_TAG_RSVD); /* ITT, reply */
2164 aReqBHS[5] = pcvResSeg[5]; /* copy TTT from NOP-In */
2165 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
2166 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
2167 aReqBHS[8] = 0; /* reserved */
2168 aReqBHS[9] = 0; /* reserved */
2169 aReqBHS[10] = 0; /* reserved */
2170 aReqBHS[11] = 0; /* reserved */
2171
2172 cnISCSIReq = 0;
2173 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
2174 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
2175 cnISCSIReq++;
2176
2177 iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq, ISCSIPDU_NO_REATTACH);
2178 /* Break if the caller wanted to process the NOP-in only. */
2179 if (itt == ISCSI_TASK_TAG_RSVD)
2180 break;
2181 }
2182 }
2183 }
2184 return rc;
2185}
2186
2187
2188/**
2189 * Reset the PDU buffer
2190 *
2191 * @param pImage The iSCSI connection state to be used.
2192 */
2193static void iscsiRecvPDUReset(PISCSIIMAGE pImage)
2194{
2195 pImage->cbRecvPDUResidual = ISCSI_BHS_SIZE;
2196 pImage->fRecvPDUBHS = true;
2197 pImage->pbRecvPDUBufCur = (uint8_t *)pImage->pvRecvPDUBuf;
2198}
2199
2200static void iscsiPDUTxAdd(PISCSIIMAGE pImage, PISCSIPDUTX pIScsiPDUTx, bool fFront)
2201{
2202 if (!fFront)
2203 {
2204 /* Link the PDU at the tail of the list. */
2205 if (!pImage->pIScsiPDUTxHead)
2206 pImage->pIScsiPDUTxHead = pIScsiPDUTx;
2207 else
2208 pImage->pIScsiPDUTxTail->pNext = pIScsiPDUTx;
2209 pImage->pIScsiPDUTxTail = pIScsiPDUTx;
2210 }
2211 else
2212 {
2213 /* Link PDU to at the front of the list. */
2214 pIScsiPDUTx->pNext = pImage->pIScsiPDUTxHead;
2215 pImage->pIScsiPDUTxHead = pIScsiPDUTx;
2216 if (!pImage->pIScsiPDUTxTail)
2217 pImage->pIScsiPDUTxTail = pIScsiPDUTx;
2218 }
2219}
2220
2221/**
2222 * Receives a PDU in a non blocking way.
2223 *
2224 * @returns VBOX status code.
2225 * @param pImage The iSCSI connection state to be used.
2226 */
2227static int iscsiRecvPDUAsync(PISCSIIMAGE pImage)
2228{
2229 size_t cbActuallyRead = 0;
2230 int rc = VINF_SUCCESS;
2231
2232 LogFlowFunc(("pImage=%#p\n", pImage));
2233
2234 /* Check if we are in the middle of a PDU receive. */
2235 if (pImage->cbRecvPDUResidual == 0)
2236 {
2237 /*
2238 * We are receiving a new PDU, don't read more than the BHS initially
2239 * until we know the real size of the PDU.
2240 */
2241 iscsiRecvPDUReset(pImage);
2242 LogFlow(("Receiving new PDU\n"));
2243 }
2244
2245 rc = pImage->pInterfaceNetCallbacks->pfnReadNB(pImage->Socket, pImage->pbRecvPDUBufCur,
2246 pImage->cbRecvPDUResidual, &cbActuallyRead);
2247 if (RT_SUCCESS(rc) && cbActuallyRead == 0)
2248 rc = VERR_BROKEN_PIPE;
2249
2250 if (RT_SUCCESS(rc))
2251 {
2252 LogFlow(("Received %zu bytes\n", cbActuallyRead));
2253 pImage->cbRecvPDUResidual -= cbActuallyRead;
2254 pImage->pbRecvPDUBufCur += cbActuallyRead;
2255
2256 /* Check if we received everything we wanted. */
2257 if ( !pImage->cbRecvPDUResidual
2258 && pImage->fRecvPDUBHS)
2259 {
2260 size_t cbAHSLength, cbDataLength;
2261
2262 /* If we were reading the BHS first get the actual PDU size now. */
2263 uint32_t word1 = RT_N2H_U32(((uint32_t *)(pImage->pvRecvPDUBuf))[1]);
2264 cbAHSLength = (word1 & 0xff000000) >> 24;
2265 cbAHSLength = ((cbAHSLength - 1) | 3) + 1; /* Add padding. */
2266 cbDataLength = word1 & 0x00ffffff;
2267 cbDataLength = ((cbDataLength - 1) | 3) + 1; /* Add padding. */
2268 pImage->cbRecvPDUResidual = cbAHSLength + cbDataLength;
2269 pImage->fRecvPDUBHS = false; /* Start receiving the rest of the PDU. */
2270 }
2271
2272 if (!pImage->cbRecvPDUResidual)
2273 {
2274 /* We received the complete PDU with or without any payload now. */
2275 LogFlow(("Received complete PDU\n"));
2276 ISCSIRES aResBuf;
2277 aResBuf.pvSeg = pImage->pvRecvPDUBuf;
2278 aResBuf.cbSeg = pImage->cbRecvPDUBuf;
2279 rc = iscsiRecvPDUProcess(pImage, &aResBuf, 1);
2280 }
2281 }
2282 else
2283 LogFlowFunc(("Reading from the socket returned with rc=%Rrc\n", rc));
2284
2285 return rc;
2286}
2287
2288static int iscsiSendPDUAsync(PISCSIIMAGE pImage)
2289{
2290 size_t cbSent = 0;
2291 int rc = VINF_SUCCESS;
2292
2293 LogFlowFunc(("pImage=%#p\n", pImage));
2294
2295 do
2296 {
2297 /* If there is no PDU active, get the first one from the list. */
2298 if (!pImage->pIScsiPDUTxCur)
2299 {
2300 if (!pImage->pIScsiPDUTxHead)
2301 break;
2302
2303 pImage->pIScsiPDUTxCur = pImage->pIScsiPDUTxHead;
2304 pImage->pIScsiPDUTxHead = pImage->pIScsiPDUTxCur->pNext;
2305 if (!pImage->pIScsiPDUTxHead)
2306 pImage->pIScsiPDUTxTail = NULL;
2307 }
2308
2309 /* Send as much as we can. */
2310 rc = pImage->pInterfaceNetCallbacks->pfnSgWriteNB(pImage->Socket, &pImage->pIScsiPDUTxCur->SgBuf, &cbSent);
2311 if (RT_SUCCESS(rc))
2312 {
2313 LogFlow(("Sent %zu bytes for PDU %#p\n", cbSent, pImage->pIScsiPDUTxCur));
2314 pImage->pIScsiPDUTxCur->cbSgLeft -= cbSent;
2315 RTSgBufAdvance(&pImage->pIScsiPDUTxCur->SgBuf, cbSent);
2316 if (!pImage->pIScsiPDUTxCur->cbSgLeft)
2317 {
2318 /* PDU completed, free it and place the command on the waiting for response list. */
2319 if (pImage->pIScsiPDUTxCur->pIScsiCmd)
2320 {
2321 LogFlow(("Sent complete PDU, placing on waiting list\n"));
2322 iscsiCmdInsert(pImage, pImage->pIScsiPDUTxCur->pIScsiCmd);
2323 }
2324 RTMemFree(pImage->pIScsiPDUTxCur);
2325 pImage->pIScsiPDUTxCur = NULL;
2326 }
2327 }
2328 } while ( RT_SUCCESS(rc)
2329 && !pImage->pIScsiPDUTxCur);
2330
2331 /* Add the write poll flag if we still have something to send, clear it otherwise. */
2332 if (pImage->pIScsiPDUTxCur)
2333 pImage->fPollEvents |= VD_INTERFACETCPNET_EVT_WRITE;
2334 else
2335 pImage->fPollEvents &= ~VD_INTERFACETCPNET_EVT_WRITE;
2336
2337 return rc;
2338}
2339
2340/**
2341 * Process a received PDU.
2342 *
2343 * @return VBOX status code.
2344 * @param pImage The iSCSI connection state to be used.
2345 * @param paRes Pointer to the array of iSCSI repsonse sections.
2346 * @param cnRes Number of valid iSCSI response sections in the array.
2347 */
2348static int iscsiRecvPDUProcess(PISCSIIMAGE pImage, PISCSIRES paRes, uint32_t cnRes)
2349{
2350 int rc = VINF_SUCCESS;
2351
2352 LogFlowFunc(("pImage=%#p paRes=%#p cnRes=%u\n", pImage, paRes, cnRes));
2353
2354 /* Validate the PDU first. */
2355 rc = iscsiValidatePDU(paRes, cnRes);
2356 if (RT_SUCCESS(rc))
2357 {
2358 ISCSIOPCODE cmd;
2359 const uint32_t *pcvResSeg = (const uint32_t *)paRes[0].pvSeg;
2360
2361 Assert(paRes[0].cbSeg > 9 * sizeof(uint32_t));
2362
2363 do
2364 {
2365 cmd = (ISCSIOPCODE)(RT_N2H_U32(pcvResSeg[0]) & ISCSIOP_MASK);
2366 switch (cmd)
2367 {
2368 case ISCSIOP_SCSI_RES:
2369 case ISCSIOP_SCSI_TASKMGMT_RES:
2370 case ISCSIOP_SCSI_DATA_IN:
2371 case ISCSIOP_R2T:
2372 case ISCSIOP_ASYN_MSG:
2373 case ISCSIOP_TEXT_RES:
2374 case ISCSIOP_LOGIN_RES:
2375 case ISCSIOP_LOGOUT_RES:
2376 case ISCSIOP_REJECT:
2377 case ISCSIOP_NOP_IN:
2378 if (serial_number_less(pImage->MaxCmdSN, RT_N2H_U32(pcvResSeg[8])))
2379 pImage->MaxCmdSN = RT_N2H_U32(pcvResSeg[8]);
2380 if (serial_number_less(pImage->ExpCmdSN, RT_N2H_U32(pcvResSeg[7])))
2381 pImage->ExpCmdSN = RT_N2H_U32(pcvResSeg[7]);
2382 break;
2383 default:
2384 rc = VERR_PARSE_ERROR;
2385 }
2386
2387 if (RT_FAILURE(rc))
2388 break;
2389
2390 if ( !pImage->FirstRecvPDU
2391 && (cmd != ISCSIOP_SCSI_DATA_IN || (RT_N2H_U32(pcvResSeg[0]) & ISCSI_STATUS_BIT)))
2392 {
2393 if (pImage->ExpStatSN == RT_N2H_U32(pcvResSeg[6]))
2394 {
2395 /* StatSN counter is not advanced on R2T and on a target SN update NOP-In. */
2396 if ( (cmd != ISCSIOP_R2T)
2397 && ((cmd != ISCSIOP_NOP_IN) || (RT_N2H_U32(pcvResSeg[4]) != ISCSI_TASK_TAG_RSVD)))
2398 pImage->ExpStatSN++;
2399 }
2400 else
2401 {
2402 rc = VERR_PARSE_ERROR;
2403 break;
2404 }
2405 }
2406
2407 if (pcvResSeg[4] != ISCSI_TASK_TAG_RSVD)
2408 {
2409 /*
2410 * This is a response from the target for a request from the initiator.
2411 * Get the request and update its state.
2412 */
2413 rc = iscsiRecvPDUUpdateRequest(pImage, paRes, cnRes);
2414 }
2415 else
2416 {
2417 /* This is a target initiated request (we handle only NOP-In request at the moment). */
2418 if ( cmd == ISCSIOP_NOP_IN
2419 && RT_N2H_U32(pcvResSeg[5]) != ISCSI_TASK_TAG_RSVD)
2420 {
2421 PISCSIPDUTX pIScsiPDUTx;
2422 uint32_t cnISCSIReq;
2423 uint32_t *paReqBHS;
2424
2425 LogFlowFunc(("Sending NOP-Out\n"));
2426
2427 /* Allocate a new PDU initialize it and put onto the waiting list. */
2428 pIScsiPDUTx = (PISCSIPDUTX)RTMemAllocZ(sizeof(ISCSIPDUTX));
2429 if (!pIScsiPDUTx)
2430 {
2431 rc = VERR_NO_MEMORY;
2432 break;
2433 }
2434 paReqBHS = &pIScsiPDUTx->aBHS[0];
2435 paReqBHS[0] = RT_H2N_U32(ISCSI_IMMEDIATE_DELIVERY_BIT | ISCSI_FINAL_BIT | ISCSIOP_NOP_OUT);
2436 paReqBHS[1] = RT_H2N_U32(0); /* TotalAHSLength=0,DataSementLength=0 */
2437 paReqBHS[2] = pcvResSeg[2]; /* copy LUN from NOP-In */
2438 paReqBHS[3] = pcvResSeg[3]; /* copy LUN from NOP-In */
2439 paReqBHS[4] = RT_H2N_U32(ISCSI_TASK_TAG_RSVD); /* ITT, reply */
2440 paReqBHS[5] = pcvResSeg[5]; /* copy TTT from NOP-In */
2441 paReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
2442 paReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
2443 paReqBHS[8] = 0; /* reserved */
2444 paReqBHS[9] = 0; /* reserved */
2445 paReqBHS[10] = 0; /* reserved */
2446 paReqBHS[11] = 0; /* reserved */
2447
2448 cnISCSIReq = 0;
2449 pIScsiPDUTx->aISCSIReq[cnISCSIReq].pvSeg = paReqBHS;
2450 pIScsiPDUTx->aISCSIReq[cnISCSIReq].cbSeg = sizeof(pIScsiPDUTx->aBHS);
2451 cnISCSIReq++;
2452 pIScsiPDUTx->cbSgLeft = sizeof(pIScsiPDUTx->aBHS);
2453 RTSgBufInit(&pIScsiPDUTx->SgBuf, pIScsiPDUTx->aISCSIReq, cnISCSIReq);
2454
2455 /* Link the PDU to the list. */
2456 iscsiPDUTxAdd(pImage, pIScsiPDUTx, false /* fFront */);
2457
2458 /* Start transfer of a PDU if there is no one active at the moment. */
2459 if (!pImage->pIScsiPDUTxCur)
2460 rc = iscsiSendPDUAsync(pImage);
2461 }
2462 }
2463 } while (0);
2464 }
2465
2466 return rc;
2467}
2468
2469/**
2470 * Check the static (not dependent on the connection/session state) validity of an iSCSI response PDU.
2471 *
2472 * @returns VBOX status
2473 * @param paRes Pointer to array of iSCSI response sections.
2474 * @param cnRes Number of valid iSCSI response sections in the array.
2475 */
2476static int iscsiValidatePDU(PISCSIRES paRes, uint32_t cnRes)
2477{
2478 const uint32_t *pcrgResBHS;
2479 uint32_t hw0;
2480 Assert(cnRes >= 1);
2481 Assert(paRes[0].cbSeg >= ISCSI_BHS_SIZE);
2482
2483 LogFlowFunc(("paRes=%#p cnRes=%u\n", paRes, cnRes));
2484
2485 pcrgResBHS = (const uint32_t *)(paRes[0].pvSeg);
2486 hw0 = RT_N2H_U32(pcrgResBHS[0]);
2487 switch (hw0 & ISCSIOP_MASK)
2488 {
2489 case ISCSIOP_NOP_IN:
2490 /* NOP-In responses must not be split into several PDUs nor it may contain
2491 * ping data for target-initiated pings nor may both task tags be valid task tags. */
2492 if ( (hw0 & ISCSI_FINAL_BIT) == 0
2493 || ( RT_N2H_U32(pcrgResBHS[4]) == ISCSI_TASK_TAG_RSVD
2494 && RT_N2H_U32(pcrgResBHS[1]) != 0)
2495 || ( RT_N2H_U32(pcrgResBHS[4]) != ISCSI_TASK_TAG_RSVD
2496 && RT_N2H_U32(pcrgResBHS[5]) != ISCSI_TASK_TAG_RSVD))
2497 return VERR_PARSE_ERROR;
2498 break;
2499 case ISCSIOP_SCSI_RES:
2500 /* SCSI responses must not be split into several PDUs nor must the residual
2501 * bits be contradicting each other nor may the residual bits be set for PDUs
2502 * containing anything else but a completed command response. Underflow
2503 * is no reason for declaring a PDU as invalid, as the target may choose
2504 * to return less data than we assume to get. */
2505 if ( (hw0 & ISCSI_FINAL_BIT) == 0
2506 || ((hw0 & ISCSI_BI_READ_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_BI_READ_RESIDUAL_UNFL_BIT))
2507 || ((hw0 & ISCSI_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_RESIDUAL_UNFL_BIT))
2508 || ( ((hw0 & ISCSI_SCSI_RESPONSE_MASK) == 0)
2509 && ((hw0 & ISCSI_SCSI_STATUS_MASK) == SCSI_STATUS_OK)
2510 && (hw0 & ( ISCSI_BI_READ_RESIDUAL_OVFL_BIT | ISCSI_BI_READ_RESIDUAL_UNFL_BIT
2511 | ISCSI_RESIDUAL_OVFL_BIT))))
2512 return VERR_PARSE_ERROR;
2513 break;
2514 case ISCSIOP_LOGIN_RES:
2515 /* Login responses must not contain contradicting transit and continue bits. */
2516 if ((hw0 & ISCSI_CONTINUE_BIT) && ((hw0 & ISCSI_TRANSIT_BIT) != 0))
2517 return VERR_PARSE_ERROR;
2518 break;
2519 case ISCSIOP_TEXT_RES:
2520 /* Text responses must not contain contradicting final and continue bits nor
2521 * may the final bit be set for PDUs containing a target transfer tag other than
2522 * the reserved transfer tag (and vice versa). */
2523 if ( (((hw0 & ISCSI_CONTINUE_BIT) && (hw0 & ISCSI_FINAL_BIT) != 0))
2524 || (((hw0 & ISCSI_FINAL_BIT) && (RT_N2H_U32(pcrgResBHS[5]) != ISCSI_TASK_TAG_RSVD)))
2525 || (((hw0 & ISCSI_FINAL_BIT) == 0) && (RT_N2H_U32(pcrgResBHS[5]) == ISCSI_TASK_TAG_RSVD)))
2526 return VERR_PARSE_ERROR;
2527 break;
2528 case ISCSIOP_SCSI_DATA_IN:
2529 /* SCSI Data-in responses must not contain contradicting residual bits when
2530 * status bit is set. */
2531 if ((hw0 & ISCSI_STATUS_BIT) && (hw0 & ISCSI_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_RESIDUAL_UNFL_BIT))
2532 return VERR_PARSE_ERROR;
2533 break;
2534 case ISCSIOP_LOGOUT_RES:
2535 /* Logout responses must not have the final bit unset and may not contain any
2536 * data or additional header segments. */
2537 if ( ((hw0 & ISCSI_FINAL_BIT) == 0)
2538 || (RT_N2H_U32(pcrgResBHS[1]) != 0))
2539 return VERR_PARSE_ERROR;
2540 break;
2541 case ISCSIOP_ASYN_MSG:
2542 /* Asynchronous Messages must not have the final bit unset and may not contain
2543 * an initiator task tag. */
2544 if ( ((hw0 & ISCSI_FINAL_BIT) == 0)
2545 || (RT_N2H_U32(pcrgResBHS[4]) != ISCSI_TASK_TAG_RSVD))
2546 return VERR_PARSE_ERROR;
2547 break;
2548 case ISCSIOP_SCSI_TASKMGMT_RES:
2549 case ISCSIOP_R2T:
2550 case ISCSIOP_REJECT:
2551 default:
2552 /* Do some logging, ignore PDU. */
2553 LogFlowFunc(("ignore unhandled PDU, first word %#08x\n", RT_N2H_U32(pcrgResBHS[0])));
2554 return VERR_PARSE_ERROR;
2555 }
2556 /* A target must not send PDUs with MaxCmdSN less than ExpCmdSN-1. */
2557
2558 if (serial_number_less(RT_N2H_U32(pcrgResBHS[8]), RT_N2H_U32(pcrgResBHS[7])-1))
2559 return VERR_PARSE_ERROR;
2560
2561 return VINF_SUCCESS;
2562}
2563
2564
2565/**
2566 * Prepares a PDU to transfer for the given command and adds it to the list.
2567 */
2568static int iscsiPDUTxPrepare(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd)
2569{
2570 int rc = VINF_SUCCESS;
2571 uint32_t *paReqBHS;
2572 size_t cbData = 0;
2573 size_t cbSegs = 0;
2574 PSCSIREQ pScsiReq;
2575 PISCSIPDUTX pIScsiPDU = NULL;
2576
2577 LogFlowFunc(("pImage=%#p pIScsiCmd=%#p\n", pImage, pIScsiCmd));
2578
2579 Assert(pIScsiCmd->enmCmdType == ISCSICMDTYPE_REQ);
2580
2581 pIScsiCmd->Itt = iscsiNewITT(pImage);
2582 pScsiReq = pIScsiCmd->CmdType.ScsiReq.pScsiReq;
2583
2584 if (pScsiReq->cT2ISegs)
2585 RTSgBufInit(&pScsiReq->SgBufT2I, pScsiReq->paT2ISegs, pScsiReq->cT2ISegs);
2586
2587 /*
2588 * Allocate twice as much entries as required for padding (worst case).
2589 * The additional segment is for the BHS.
2590 */
2591 size_t cI2TSegs = 2*(pScsiReq->cI2TSegs + 1);
2592 pIScsiPDU = (PISCSIPDUTX)RTMemAllocZ(RT_OFFSETOF(ISCSIPDUTX, aISCSIReq[cI2TSegs]));
2593 if (!pIScsiPDU)
2594 return VERR_NO_MEMORY;
2595
2596 pIScsiPDU->pIScsiCmd = pIScsiCmd;
2597
2598 if (pScsiReq->enmXfer == SCSIXFER_FROM_TARGET)
2599 cbData = (uint32_t)pScsiReq->cbT2IData;
2600 else
2601 cbData = (uint32_t)pScsiReq->cbI2TData;
2602
2603 paReqBHS = pIScsiPDU->aBHS;
2604
2605 /* Setup the BHS. */
2606 paReqBHS[0] = RT_H2N_U32( ISCSI_FINAL_BIT | ISCSI_TASK_ATTR_ORDERED | ISCSIOP_SCSI_CMD
2607 | (pScsiReq->enmXfer << 21)); /* I=0,F=1,Attr=Ordered */
2608 paReqBHS[1] = RT_H2N_U32(0x00000000 | ((uint32_t)pScsiReq->cbI2TData & 0xffffff)); /* TotalAHSLength=0 */
2609 paReqBHS[2] = RT_H2N_U32(pImage->LUN >> 32);
2610 paReqBHS[3] = RT_H2N_U32(pImage->LUN & 0xffffffff);
2611 paReqBHS[4] = pIScsiCmd->Itt;
2612 paReqBHS[5] = RT_H2N_U32(cbData);
2613 paReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
2614 paReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
2615 memcpy(paReqBHS + 8, pScsiReq->pvCmd, pScsiReq->cbCmd);
2616 pImage->CmdSN++;
2617
2618 /* Setup the S/G buffers. */
2619 uint32_t cnISCSIReq = 0;
2620 pIScsiPDU->aISCSIReq[cnISCSIReq].cbSeg = sizeof(pIScsiPDU->aBHS);
2621 pIScsiPDU->aISCSIReq[cnISCSIReq].pvSeg = pIScsiPDU->aBHS;
2622 cnISCSIReq++;
2623 cbSegs = sizeof(pIScsiPDU->aBHS);
2624 /* Padding is not necessary for the BHS. */
2625
2626 if (pScsiReq->cbI2TData)
2627 {
2628 for (unsigned cSeg = 0; cSeg < pScsiReq->cI2TSegs; cSeg++)
2629 {
2630 Assert(cnISCSIReq < cI2TSegs);
2631 pIScsiPDU->aISCSIReq[cnISCSIReq].cbSeg = pScsiReq->paI2TSegs[cSeg].cbSeg;
2632 pIScsiPDU->aISCSIReq[cnISCSIReq].pvSeg = pScsiReq->paI2TSegs[cSeg].pvSeg;
2633 cbSegs += pScsiReq->paI2TSegs[cSeg].cbSeg;
2634 cnISCSIReq++;
2635
2636 /* Add padding if necessary. */
2637 if (pScsiReq->paI2TSegs[cSeg].cbSeg & 3)
2638 {
2639 Assert(cnISCSIReq < cI2TSegs);
2640 pIScsiPDU->aISCSIReq[cnISCSIReq].pvSeg = &pImage->aPadding[0];
2641 pIScsiPDU->aISCSIReq[cnISCSIReq].cbSeg = 4 - (pScsiReq->paI2TSegs[cSeg].cbSeg & 3);
2642 cbSegs += pIScsiPDU->aISCSIReq[cnISCSIReq].cbSeg;
2643 cnISCSIReq++;
2644 }
2645 }
2646 }
2647
2648 pIScsiPDU->cISCSIReq = cnISCSIReq;
2649 pIScsiPDU->cbSgLeft = cbSegs;
2650 RTSgBufInit(&pIScsiPDU->SgBuf, pIScsiPDU->aISCSIReq, cnISCSIReq);
2651
2652 /* Link the PDU to the list. */
2653 iscsiPDUTxAdd(pImage, pIScsiPDU, false /* fFront */);
2654
2655 /* Start transfer of a PDU if there is no one active at the moment. */
2656 if (!pImage->pIScsiPDUTxCur)
2657 rc = iscsiSendPDUAsync(pImage);
2658
2659 return rc;
2660}
2661
2662
2663/**
2664 * Updates the state of a request from the PDU we received.
2665 *
2666 * @return VBox status code.
2667 * @param pImage iSCSI connection state to use.
2668 * @param paRes Pointer to array of iSCSI response sections.
2669 * @param cnRes Number of valid iSCSI response sections in the array.
2670 */
2671static int iscsiRecvPDUUpdateRequest(PISCSIIMAGE pImage, PISCSIRES paRes, uint32_t cnRes)
2672{
2673 int rc = VINF_SUCCESS;
2674 PISCSICMD pIScsiCmd;
2675 uint32_t *paResBHS;
2676
2677 LogFlowFunc(("pImage=%#p paRes=%#p cnRes=%u\n", pImage, paRes, cnRes));
2678
2679 Assert(cnRes == 1);
2680 Assert(paRes[0].cbSeg >= ISCSI_BHS_SIZE);
2681
2682 paResBHS = (uint32_t *)paRes[0].pvSeg;
2683
2684 pIScsiCmd = iscsiCmdGetFromItt(pImage, paResBHS[4]);
2685
2686 if (pIScsiCmd)
2687 {
2688 bool final = false;
2689 PSCSIREQ pScsiReq;
2690
2691 LogFlow(("Found SCSI command %#p for Itt=%#u\n", pIScsiCmd, paResBHS[4]));
2692
2693 Assert(pIScsiCmd->enmCmdType == ISCSICMDTYPE_REQ);
2694 pScsiReq = pIScsiCmd->CmdType.ScsiReq.pScsiReq;
2695
2696 final = !!(RT_N2H_U32(paResBHS[0]) & ISCSI_FINAL_BIT);
2697 ISCSIOPCODE cmd = (ISCSIOPCODE)(RT_N2H_U32(paResBHS[0]) & ISCSIOP_MASK);
2698 if (cmd == ISCSIOP_SCSI_RES)
2699 {
2700 /* This is the final PDU which delivers the status (and may be omitted if
2701 * the last Data-In PDU included successful completion status). Note
2702 * that ExpStatSN has been bumped already in iscsiRecvPDU. */
2703 if (!final || ((RT_N2H_U32(paResBHS[0]) & 0x0000ff00) != 0) || (RT_N2H_U32(paResBHS[6]) != pImage->ExpStatSN - 1))
2704 {
2705 /* SCSI Response in the wrong place or with a (target) failure. */
2706 LogFlow(("Wrong ExpStatSN value in PDU\n"));
2707 rc = VERR_PARSE_ERROR;
2708 }
2709 else
2710 {
2711 pScsiReq->status = RT_N2H_U32(paResBHS[0]) & 0x000000ff;
2712 size_t cbData = RT_N2H_U32(paResBHS[1]) & 0x00ffffff;
2713 void *pvSense = (uint8_t *)paRes[0].pvSeg + ISCSI_BHS_SIZE;
2714
2715 if (cbData >= 2)
2716 {
2717 uint32_t cbStat = RT_N2H_U32(((uint32_t *)pvSense)[0]) >> 16;
2718 if (cbStat + 2 > cbData)
2719 {
2720 rc = VERR_BUFFER_OVERFLOW;
2721 }
2722 else
2723 {
2724 /* Truncate sense data if it doesn't fit into the buffer. */
2725 pScsiReq->cbSense = RT_MIN(cbStat, pScsiReq->cbSense);
2726 memcpy(pScsiReq->pvSense, (uint8_t *)pvSense + 2,
2727 RT_MIN(paRes[0].cbSeg - ISCSI_BHS_SIZE - 2, pScsiReq->cbSense));
2728 }
2729 }
2730 else if (cbData == 1)
2731 rc = VERR_PARSE_ERROR;
2732 else
2733 pScsiReq->cbSense = 0;
2734 }
2735 iscsiCmdComplete(pImage, pIScsiCmd, rc);
2736 }
2737 else if (cmd == ISCSIOP_SCSI_DATA_IN)
2738 {
2739 /* A Data-In PDU carries some data that needs to be added to the received
2740 * data in response to the command. There may be both partial and complete
2741 * Data-In PDUs, so collect data until the status is included or the status
2742 * is sent in a separate SCSI Result frame (see above). */
2743 size_t cbData = RT_N2H_U32(paResBHS[1]) & 0x00ffffff;
2744 void *pvData = (uint8_t *)paRes[0].pvSeg + ISCSI_BHS_SIZE;
2745
2746 if (final && cbData > pScsiReq->cbT2IData)
2747 {
2748 /* The received PDU is bigger than what we requested.
2749 * Must not happen under normal circumstances and is a target error. */
2750 rc = VERR_BUFFER_OVERFLOW;
2751 }
2752 else
2753 {
2754 /* Copy data from the received PDU into the T2I segments. */
2755 size_t cbCopied = RTSgBufCopyFromBuf(&pScsiReq->SgBufT2I, pvData, cbData);
2756 Assert(cbCopied == cbData);
2757
2758 if (final && (RT_N2H_U32(paResBHS[0]) & ISCSI_STATUS_BIT) != 0)
2759 {
2760 pScsiReq->status = RT_N2H_U32(paResBHS[0]) & 0x000000ff;
2761 pScsiReq->cbSense = 0;
2762 iscsiCmdComplete(pImage, pIScsiCmd, VINF_SUCCESS);
2763 }
2764 }
2765 }
2766 else
2767 rc = VERR_PARSE_ERROR;
2768 }
2769
2770 /* Log any errors here but ignore the PDU. */
2771 if (RT_FAILURE(rc))
2772 {
2773 LogRel(("iSCSI: Received malformed PDU from target %s (rc=%Rrc), ignoring\n", pImage->pszTargetName, rc));
2774 rc = VINF_SUCCESS;
2775 }
2776
2777 return rc;
2778}
2779
2780/**
2781 * Appends a key-value pair to the buffer. Normal ASCII strings (cbValue == 0) and large binary values
2782 * of a given length (cbValue > 0) are directly supported. Other value types must be converted to ASCII
2783 * by the caller. Strings must be in UTF-8 encoding.
2784 *
2785 * @returns VBOX status
2786 * @param pbBuf Pointer to the key-value buffer.
2787 * @param cbBuf Length of the key-value buffer.
2788 * @param pcbBufCurr Currently used portion of the key-value buffer.
2789 * @param pszKey Pointer to a string containing the key.
2790 * @param pszValue Pointer to either a string containing the value or to a large binary value.
2791 * @param cbValue Length of the binary value if applicable.
2792 */
2793static int iscsiTextAddKeyValue(uint8_t *pbBuf, size_t cbBuf, size_t *pcbBufCurr, const char *pcszKey,
2794 const char *pcszValue, size_t cbValue)
2795{
2796 size_t cbBufTmp = *pcbBufCurr;
2797 size_t cbKey = strlen(pcszKey);
2798 size_t cbValueEnc;
2799 uint8_t *pbCurr;
2800
2801 if (cbValue == 0)
2802 cbValueEnc = strlen(pcszValue);
2803 else
2804 cbValueEnc = cbValue * 2 + 2; /* 2 hex bytes per byte, 2 bytes prefix */
2805
2806 if (cbBuf < cbBufTmp + cbKey + 1 + cbValueEnc + 1)
2807 {
2808 /* Buffer would overflow, signal error. */
2809 return VERR_BUFFER_OVERFLOW;
2810 }
2811
2812 /*
2813 * Append a key=value pair (zero terminated string) to the end of the buffer.
2814 */
2815 pbCurr = pbBuf + cbBufTmp;
2816 memcpy(pbCurr, pcszKey, cbKey);
2817 pbCurr += cbKey;
2818 *pbCurr++ = '=';
2819 if (cbValue == 0)
2820 {
2821 memcpy(pbCurr, pcszValue, cbValueEnc);
2822 pbCurr += cbValueEnc;
2823 }
2824 else
2825 {
2826 *pbCurr++ = '0';
2827 *pbCurr++ = 'x';
2828 for (uint32_t i = 0; i < cbValue; i++)
2829 {
2830 uint8_t b;
2831 b = pcszValue[i];
2832 *pbCurr++ = NUM_2_HEX(b >> 4);
2833 *pbCurr++ = NUM_2_HEX(b & 0xf);
2834 }
2835 }
2836 *pbCurr = '\0';
2837 *pcbBufCurr = cbBufTmp + cbKey + 1 + cbValueEnc + 1;
2838
2839 return VINF_SUCCESS;
2840}
2841
2842
2843/**
2844 * Retrieve the value for a given key from the key=value buffer.
2845 *
2846 * @returns VBOX status.
2847 * @param pbBuf Buffer containing key=value pairs.
2848 * @param cbBuf Length of buffer with key=value pairs.
2849 * @param pszKey Pointer to key for which to retrieve the value.
2850 * @param ppszValue Pointer to value string pointer.
2851 */
2852static int iscsiTextGetKeyValue(const uint8_t *pbBuf, size_t cbBuf, const char *pcszKey, const char **ppcszValue)
2853{
2854 size_t cbKey = strlen(pcszKey);
2855
2856 while (cbBuf != 0)
2857 {
2858 size_t cbKeyValNull = strlen((const char *)pbBuf) + 1;
2859
2860 if (strncmp(pcszKey, (const char *)pbBuf, cbKey) == 0 && pbBuf[cbKey] == '=')
2861 {
2862 *ppcszValue = (const char *)(pbBuf + cbKey + 1);
2863 return VINF_SUCCESS;
2864 }
2865 pbBuf += cbKeyValNull;
2866 cbBuf -= cbKeyValNull;
2867 }
2868 return VERR_INVALID_NAME;
2869}
2870
2871
2872/**
2873 * Convert a long-binary value from a value string to the binary representation.
2874 *
2875 * @returns VBOX status
2876 * @param pszValue Pointer to a string containing the textual value representation.
2877 * @param pbValue Pointer to the value buffer for the binary value.
2878 * @param pcbValue In: length of value buffer, out: actual length of binary value.
2879 */
2880static int iscsiStrToBinary(const char *pcszValue, uint8_t *pbValue, size_t *pcbValue)
2881{
2882 size_t cbValue = *pcbValue;
2883 char c1, c2, c3, c4;
2884 Assert(cbValue >= 1);
2885
2886 if (strlen(pcszValue) < 3)
2887 return VERR_PARSE_ERROR;
2888 if (*pcszValue++ != '0')
2889 return VERR_PARSE_ERROR;
2890 switch (*pcszValue++)
2891 {
2892 case 'x':
2893 case 'X':
2894 if (strlen(pcszValue) & 1)
2895 {
2896 c1 = *pcszValue++;
2897 *pbValue++ = HEX_2_NUM(c1);
2898 cbValue--;
2899 }
2900 while (*pcszValue != '\0')
2901 {
2902 if (cbValue == 0)
2903 return VERR_BUFFER_OVERFLOW;
2904 c1 = *pcszValue++;
2905 if ((c1 < '0' || c1 > '9') && (c1 < 'a' || c1 > 'f') && (c1 < 'A' || c1 > 'F'))
2906 return VERR_PARSE_ERROR;
2907 c2 = *pcszValue++;
2908 if ((c2 < '0' || c2 > '9') && (c2 < 'a' || c2 > 'f') && (c2 < 'A' || c2 > 'F'))
2909 return VERR_PARSE_ERROR;
2910 *pbValue++ = (HEX_2_NUM(c1) << 4) | HEX_2_NUM(c2);
2911 cbValue--;
2912 }
2913 *pcbValue -= cbValue;
2914 break;
2915 case 'b':
2916 case 'B':
2917 if ((strlen(pcszValue) & 3) != 0)
2918 return VERR_PARSE_ERROR;
2919 while (*pcszValue != '\0')
2920 {
2921 uint32_t temp;
2922 if (cbValue == 0)
2923 return VERR_BUFFER_OVERFLOW;
2924 c1 = *pcszValue++;
2925 if ((c1 < 'A' || c1 > 'Z') && (c1 < 'a' || c1 >'z') && (c1 < '0' || c1 > '9') && (c1 != '+') && (c1 != '/'))
2926 return VERR_PARSE_ERROR;
2927 c2 = *pcszValue++;
2928 if ((c2 < 'A' || c2 > 'Z') && (c2 < 'a' || c2 >'z') && (c2 < '0' || c2 > '9') && (c2 != '+') && (c2 != '/'))
2929 return VERR_PARSE_ERROR;
2930 c3 = *pcszValue++;
2931 if ((c3 < 'A' || c3 > 'Z') && (c3 < 'a' || c3 >'z') && (c3 < '0' || c3 > '9') && (c3 != '+') && (c3 != '/') && (c3 != '='))
2932 return VERR_PARSE_ERROR;
2933 c4 = *pcszValue++;
2934 if ( (c3 == '=' && c4 != '=')
2935 || ((c4 < 'A' || c4 > 'Z') && (c4 < 'a' || c4 >'z') && (c4 < '0' || c4 > '9') && (c4 != '+') && (c4 != '/') && (c4 != '=')))
2936 return VERR_PARSE_ERROR;
2937 temp = (B64_2_NUM(c1) << 18) | (B64_2_NUM(c2) << 12);
2938 if (c3 == '=') {
2939 if (*pcszValue != '\0')
2940 return VERR_PARSE_ERROR;
2941 *pbValue++ = temp >> 16;
2942 cbValue--;
2943 } else {
2944 temp |= B64_2_NUM(c3) << 6;
2945 if (c4 == '=') {
2946 if (*pcszValue != '\0')
2947 return VERR_PARSE_ERROR;
2948 if (cbValue < 2)
2949 return VERR_BUFFER_OVERFLOW;
2950 *pbValue++ = temp >> 16;
2951 *pbValue++ = (temp >> 8) & 0xff;
2952 cbValue -= 2;
2953 }
2954 else
2955 {
2956 temp |= B64_2_NUM(c4);
2957 if (cbValue < 3)
2958 return VERR_BUFFER_OVERFLOW;
2959 *pbValue++ = temp >> 16;
2960 *pbValue++ = (temp >> 8) & 0xff;
2961 *pbValue++ = temp & 0xff;
2962 cbValue -= 3;
2963 }
2964 }
2965 }
2966 *pcbValue -= cbValue;
2967 break;
2968 default:
2969 return VERR_PARSE_ERROR;
2970 }
2971 return VINF_SUCCESS;
2972}
2973
2974
2975/**
2976 * Retrieve the relevant parameter values and update the initiator state.
2977 *
2978 * @returns VBOX status.
2979 * @param pImage Current iSCSI initiator state.
2980 * @param pbBuf Buffer containing key=value pairs.
2981 * @param cbBuf Length of buffer with key=value pairs.
2982 */
2983static int iscsiUpdateParameters(PISCSIIMAGE pImage, const uint8_t *pbBuf, size_t cbBuf)
2984{
2985 int rc;
2986 const char *pcszMaxRecvDataSegmentLength = NULL;
2987 const char *pcszMaxBurstLength = NULL;
2988 const char *pcszFirstBurstLength = NULL;
2989 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "MaxRecvDataSegmentLength", &pcszMaxRecvDataSegmentLength);
2990 if (rc == VERR_INVALID_NAME)
2991 rc = VINF_SUCCESS;
2992 if (RT_FAILURE(rc))
2993 return VERR_PARSE_ERROR;
2994 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "MaxBurstLength", &pcszMaxBurstLength);
2995 if (rc == VERR_INVALID_NAME)
2996 rc = VINF_SUCCESS;
2997 if (RT_FAILURE(rc))
2998 return VERR_PARSE_ERROR;
2999 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "FirstBurstLength", &pcszFirstBurstLength);
3000 if (rc == VERR_INVALID_NAME)
3001 rc = VINF_SUCCESS;
3002 if (RT_FAILURE(rc))
3003 return VERR_PARSE_ERROR;
3004 if (pcszMaxRecvDataSegmentLength)
3005 {
3006 uint32_t cb = pImage->cbSendDataLength;
3007 rc = RTStrToUInt32Full(pcszMaxRecvDataSegmentLength, 0, &cb);
3008 AssertRC(rc);
3009 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
3010 }
3011 if (pcszMaxBurstLength)
3012 {
3013 uint32_t cb = pImage->cbSendDataLength;
3014 rc = RTStrToUInt32Full(pcszMaxBurstLength, 0, &cb);
3015 AssertRC(rc);
3016 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
3017 }
3018 if (pcszFirstBurstLength)
3019 {
3020 uint32_t cb = pImage->cbSendDataLength;
3021 rc = RTStrToUInt32Full(pcszFirstBurstLength, 0, &cb);
3022 AssertRC(rc);
3023 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
3024 }
3025 return VINF_SUCCESS;
3026}
3027
3028
3029static bool serial_number_less(uint32_t s1, uint32_t s2)
3030{
3031 return (s1 < s2 && s2 - s1 < 0x80000000) || (s1 > s2 && s1 - s2 > 0x80000000);
3032}
3033
3034
3035#ifdef IMPLEMENT_TARGET_AUTH
3036static void chap_md5_generate_challenge(uint8_t *pbChallenge, size_t *pcbChallenge)
3037{
3038 uint8_t cbChallenge;
3039
3040 cbChallenge = RTrand_U8(CHAP_MD5_CHALLENGE_MIN, CHAP_MD5_CHALLENGE_MAX);
3041 RTrand_bytes(pbChallenge, cbChallenge);
3042 *pcbChallenge = cbChallenge;
3043}
3044#endif
3045
3046
3047static void chap_md5_compute_response(uint8_t *pbResponse, uint8_t id, const uint8_t *pbChallenge, size_t cbChallenge,
3048 const uint8_t *pbSecret, size_t cbSecret)
3049{
3050 RTMD5CONTEXT ctx;
3051 uint8_t bId;
3052
3053 bId = id;
3054 RTMd5Init(&ctx);
3055 RTMd5Update(&ctx, &bId, 1);
3056 RTMd5Update(&ctx, pbSecret, cbSecret);
3057 RTMd5Update(&ctx, pbChallenge, cbChallenge);
3058 RTMd5Final(pbResponse, &ctx);
3059}
3060
3061/**
3062 * Internal. - Wrapper around the extended select callback of the net interface.
3063 */
3064DECLINLINE(int) iscsiIoThreadWait(PISCSIIMAGE pImage, RTMSINTERVAL cMillies, uint32_t fEvents, uint32_t *pfEvents)
3065{
3066 return pImage->pInterfaceNetCallbacks->pfnSelectOneEx(pImage->Socket, fEvents, pfEvents, cMillies);
3067}
3068
3069/**
3070 * Internal. - Pokes a thread waiting for I/O.
3071 */
3072DECLINLINE(int) iscsiIoThreadPoke(PISCSIIMAGE pImage)
3073{
3074 return pImage->pInterfaceNetCallbacks->pfnPoke(pImage->Socket);
3075}
3076
3077/**
3078 * Internal. - Get the next request from the queue.
3079 */
3080DECLINLINE(PISCSICMD) iscsiCmdGet(PISCSIIMAGE pImage)
3081{
3082 int rc;
3083 PISCSICMD pIScsiCmd = NULL;
3084
3085 rc = RTSemMutexRequest(pImage->MutexReqQueue, RT_INDEFINITE_WAIT);
3086 AssertRC(rc);
3087
3088 pIScsiCmd = pImage->pScsiReqQueue;
3089 if (pIScsiCmd)
3090 {
3091 pImage->pScsiReqQueue = pIScsiCmd->pNext;
3092 pIScsiCmd->pNext = NULL;
3093 }
3094
3095 rc = RTSemMutexRelease(pImage->MutexReqQueue);
3096 AssertRC(rc);
3097
3098 return pIScsiCmd;
3099}
3100
3101
3102/**
3103 * Internal. - Adds the given command to the queue.
3104 */
3105DECLINLINE(int) iscsiCmdPut(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd)
3106{
3107 int rc = RTSemMutexRequest(pImage->MutexReqQueue, RT_INDEFINITE_WAIT);
3108 AssertRC(rc);
3109
3110 pIScsiCmd->pNext = pImage->pScsiReqQueue;
3111 pImage->pScsiReqQueue = pIScsiCmd;
3112
3113 rc = RTSemMutexRelease(pImage->MutexReqQueue);
3114 AssertRC(rc);
3115
3116 iscsiIoThreadPoke(pImage);
3117
3118 return rc;
3119}
3120
3121/**
3122 * Internal. - Completes the request with the appropriate action.
3123 * Synchronous requests are completed with waking up the thread
3124 * and asynchronous ones by continuing the associated I/O context.
3125 */
3126static void iscsiCmdComplete(PISCSIIMAGE pImage, PISCSICMD pIScsiCmd, int rcCmd)
3127{
3128 LogFlowFunc(("pImage=%#p pIScsiCmd=%#p rcCmd=%Rrc\n", pImage, pIScsiCmd, rcCmd));
3129
3130 /* Remove from the table first. */
3131 iscsiCmdRemove(pImage, pIScsiCmd->Itt);
3132
3133 /* Call completion callback. */
3134 pIScsiCmd->pfnComplete(pImage, rcCmd, pIScsiCmd->pvUser);
3135
3136 /* Free command structure. */
3137#ifdef DEBUG
3138 memset(pIScsiCmd, 0xff, sizeof(ISCSICMD));
3139#endif
3140 RTMemFree(pIScsiCmd);
3141}
3142
3143/**
3144 * Reattaches the to the target after an error aborting
3145 * pending commands and resending them.
3146 *
3147 * @param pImage iSCSI connection state.
3148 */
3149static void iscsiReattach(PISCSIIMAGE pImage)
3150{
3151 int rc = VINF_SUCCESS;
3152 PISCSICMD pIScsiCmdHead = NULL;
3153 PISCSICMD pIScsiCmd = NULL;
3154 PISCSICMD pIScsiCmdCur = NULL;
3155 PISCSIPDUTX pIScsiPDUTx = NULL;
3156
3157 /* Close connection. */
3158 iscsiTransportClose(pImage);
3159 pImage->state = ISCSISTATE_FREE;
3160
3161 /* Reset PDU we are receiving. */
3162 iscsiRecvPDUReset(pImage);
3163
3164 /*
3165 * Abort all PDUs we are about to transmit,
3166 * the command need a new Itt if the relogin is successful.
3167 */
3168 while (pImage->pIScsiPDUTxHead)
3169 {
3170 pIScsiPDUTx = pImage->pIScsiPDUTxHead;
3171 pImage->pIScsiPDUTxHead = pIScsiPDUTx->pNext;
3172
3173 pIScsiCmd = pIScsiPDUTx->pIScsiCmd;
3174
3175 if (pIScsiCmd)
3176 {
3177 /* Place on command list. */
3178 pIScsiCmd->pNext = pIScsiCmdHead;
3179 pIScsiCmdHead = pIScsiCmd;
3180 }
3181 RTMemFree(pIScsiPDUTx);
3182 }
3183
3184 /* Clear the current PDU too. */
3185 if (pImage->pIScsiPDUTxCur)
3186 {
3187 pIScsiPDUTx = pImage->pIScsiPDUTxCur;
3188
3189 pImage->pIScsiPDUTxCur = NULL;
3190 pIScsiCmd = pIScsiPDUTx->pIScsiCmd;
3191
3192 if (pIScsiCmd)
3193 {
3194 pIScsiCmd->pNext = pIScsiCmdHead;
3195 pIScsiCmdHead = pIScsiCmd;
3196 }
3197 RTMemFree(pIScsiPDUTx);
3198 }
3199
3200 /*
3201 * Get all commands which are waiting for a response
3202 * They need to be resend too after a successful reconnect.
3203 */
3204 pIScsiCmd = iscsiCmdRemoveAll(pImage);
3205
3206 if (pIScsiCmd)
3207 {
3208 pIScsiCmdCur = pIScsiCmd;
3209 while (pIScsiCmdCur->pNext)
3210 pIScsiCmdCur = pIScsiCmdCur->pNext;
3211
3212 /*
3213 * Place them in front of the list because they are the oldest requests
3214 * and need to be processed first to minimize the risk to time out.
3215 */
3216 pIScsiCmdCur->pNext = pIScsiCmdHead;
3217 pIScsiCmdHead = pIScsiCmd;
3218 }
3219
3220 /* Try to attach. */
3221 rc = iscsiAttach(pImage);
3222 if (RT_SUCCESS(rc))
3223 {
3224 /* Phew, we have a connection again.
3225 * Prepare new PDUs for the aborted commands.
3226 */
3227 while (pIScsiCmdHead)
3228 {
3229 pIScsiCmd = pIScsiCmdHead;
3230 pIScsiCmdHead = pIScsiCmdHead->pNext;
3231
3232 rc = iscsiPDUTxPrepare(pImage, pIScsiCmd);
3233 AssertRC(rc);
3234 }
3235 }
3236 else
3237 {
3238 /*
3239 * Still no luck, complete commands with error so the caller
3240 * has a chance to inform the user and maybe resend the command.
3241 */
3242 while (pIScsiCmdHead)
3243 {
3244 pIScsiCmd = pIScsiCmdHead;
3245 pIScsiCmdHead = pIScsiCmdHead->pNext;
3246
3247 iscsiCmdComplete(pImage, pIScsiCmd, VERR_BROKEN_PIPE);
3248 }
3249 }
3250}
3251
3252/**
3253 * Internal. Main iSCSI I/O worker.
3254 */
3255static DECLCALLBACK(int) iscsiIoThreadWorker(RTTHREAD ThreadSelf, void *pvUser)
3256{
3257 PISCSIIMAGE pImage = (PISCSIIMAGE)pvUser;
3258
3259 /* Initialize the initial event mask. */
3260 pImage->fPollEvents = VD_INTERFACETCPNET_EVT_READ | VD_INTERFACETCPNET_EVT_ERROR;
3261
3262 while (pImage->fRunning)
3263 {
3264 uint32_t fEvents;
3265 int rc;
3266
3267 fEvents = 0;
3268
3269 /* Wait for work or for data from the target. */
3270 RTMSINTERVAL msWait;
3271
3272 if (pImage->cCmdsWaiting)
3273 msWait = pImage->uReadTimeout;
3274 else
3275 msWait = RT_INDEFINITE_WAIT;
3276
3277 rc = iscsiIoThreadWait(pImage, msWait, pImage->fPollEvents, &fEvents);
3278 if (rc == VERR_INTERRUPTED)
3279 {
3280 /* Check the queue. */
3281 PISCSICMD pIScsiCmd = iscsiCmdGet(pImage);
3282
3283 while (pIScsiCmd)
3284 {
3285 switch (pIScsiCmd->enmCmdType)
3286 {
3287 case ISCSICMDTYPE_REQ:
3288 {
3289 rc = iscsiPDUTxPrepare(pImage, pIScsiCmd);
3290 AssertRC(rc);
3291 break;
3292 }
3293 case ISCSICMDTYPE_EXEC:
3294 {
3295 rc = pIScsiCmd->CmdType.Exec.pfnExec(pIScsiCmd->CmdType.Exec.pvUser);
3296 iscsiCmdComplete(pImage, pIScsiCmd, rc);
3297 break;
3298 }
3299 default:
3300 AssertMsgFailed(("Invalid command type %d\n", pIScsiCmd->enmCmdType));
3301 }
3302
3303 pIScsiCmd = iscsiCmdGet(pImage);
3304 }
3305 }
3306 else if (rc == VERR_TIMEOUT)
3307 {
3308 /*
3309 * We are waiting for a response from the target but
3310 * it didn't answered yet.
3311 * We assume the connection is broken and try to reconnect.
3312 */
3313 LogFlow(("Timed out while waiting for an asnwer from the target, reconnecting\n"));
3314 iscsiReattach(pImage);
3315 }
3316 else if (RT_SUCCESS(rc))
3317 {
3318 Assert(pImage->state == ISCSISTATE_NORMAL);
3319 LogFlow(("Got socket events %#x\n", fEvents));
3320
3321 if (fEvents & VD_INTERFACETCPNET_EVT_READ)
3322 {
3323 /* Continue or start a new PDU receive task */
3324 LogFlow(("There is data on the socket\n"));
3325 rc = iscsiRecvPDUAsync(pImage);
3326 if (rc == VERR_BROKEN_PIPE)
3327 iscsiReattach(pImage);
3328 else if (RT_FAILURE(rc))
3329 LogRel(("iSCSI: Handling incoming request failed %Rrc\n", rc));
3330 }
3331 else if (fEvents & VD_INTERFACETCPNET_EVT_WRITE)
3332 {
3333 LogFlow(("The socket is writable\n"));
3334 rc = iscsiSendPDUAsync(pImage);
3335 if (RT_FAILURE(rc))
3336 LogRel(("iSCSI: Sending PDU failed %Rrc\n", rc));
3337 }
3338 else if (fEvents & VD_INTERFACETCPNET_EVT_ERROR)
3339 {
3340 LogFlow(("An error ocurred\n"));
3341 iscsiReattach(pImage);
3342 }
3343 else
3344 LogRel(("iSCSI: Received unexpected event %#x\n", fEvents));
3345 }
3346 else
3347 {
3348 LogRel(("iSCSI: Waiting for I/O failed rc=%Rrc\n", rc));
3349 }
3350 }
3351
3352 return VINF_SUCCESS;
3353}
3354
3355/**
3356 * Internal. - Enqueues a request asynchronously.
3357 */
3358static int iscsiCommandAsync(PISCSIIMAGE pImage, PSCSIREQ pScsiReq,
3359 PFNISCSICMDCOMPLETED pfnComplete, void *pvUser)
3360{
3361 int rc;
3362
3363 if (pImage->fExtendedSelectSupported)
3364 {
3365 PISCSICMD pIScsiCmd = (PISCSICMD)RTMemAllocZ(sizeof(ISCSICMD));
3366 if (!pIScsiCmd)
3367 return VERR_NO_MEMORY;
3368
3369 /* Init the command structure. */
3370 pIScsiCmd->pNext = NULL;
3371 pIScsiCmd->enmCmdType = ISCSICMDTYPE_REQ;
3372 pIScsiCmd->pfnComplete = pfnComplete;
3373 pIScsiCmd->pvUser = pvUser;
3374 pIScsiCmd->CmdType.ScsiReq.pScsiReq = pScsiReq;
3375
3376 rc = iscsiCmdPut(pImage, pIScsiCmd);
3377 if (RT_FAILURE(rc))
3378 RTMemFree(pIScsiCmd);
3379 }
3380 else
3381 rc = VERR_NOT_SUPPORTED;
3382
3383 return rc;
3384}
3385
3386static void iscsiCommandCompleteSync(PISCSIIMAGE pImage, int rcReq, void *pvUser)
3387{
3388 PISCSICMDSYNC pIScsiCmdSync = (PISCSICMDSYNC)pvUser;
3389
3390 pIScsiCmdSync->rcCmd = rcReq;
3391 int rc = RTSemEventSignal(pIScsiCmdSync->EventSem);
3392 AssertRC(rc);
3393}
3394
3395/**
3396 * Internal. - Enqueues a request in a synchronous fashion
3397 * i.e. returns when the request completed.
3398 */
3399static int iscsiCommandSync(PISCSIIMAGE pImage, PSCSIREQ pScsiReq, bool fRetry, int rcSense)
3400{
3401 int rc;
3402
3403 if (pImage->fExtendedSelectSupported)
3404 {
3405 ISCSICMDSYNC IScsiCmdSync;
3406
3407 /* Create event semaphore. */
3408 rc = RTSemEventCreate(&IScsiCmdSync.EventSem);
3409 if (RT_FAILURE(rc))
3410 return rc;
3411
3412 if (fRetry)
3413 {
3414 for (unsigned i = 0; i < 10; i++)
3415 {
3416 rc = iscsiCommandAsync(pImage, pScsiReq, iscsiCommandCompleteSync, &IScsiCmdSync);
3417 if (RT_FAILURE(rc))
3418 break;
3419
3420 rc = RTSemEventWait(IScsiCmdSync.EventSem, RT_INDEFINITE_WAIT);
3421 AssertRC(rc);
3422 rc = IScsiCmdSync.rcCmd;
3423
3424 if ( (RT_SUCCESS(rc) && !pScsiReq->cbSense)
3425 || RT_FAILURE(rc))
3426 break;
3427 rc = rcSense;
3428 }
3429 }
3430 else
3431 {
3432 rc = iscsiCommandAsync(pImage, pScsiReq, iscsiCommandCompleteSync, &IScsiCmdSync);
3433 if (RT_SUCCESS(rc))
3434 {
3435 rc = RTSemEventWait(IScsiCmdSync.EventSem, RT_INDEFINITE_WAIT);
3436 AssertRC(rc);
3437 rc = IScsiCmdSync.rcCmd;
3438
3439 if (RT_FAILURE(rc) || pScsiReq->cbSense > 0)
3440 rc = rcSense;
3441 }
3442 }
3443
3444 RTSemEventDestroy(IScsiCmdSync.EventSem);
3445 }
3446 else
3447 {
3448 if (fRetry)
3449 {
3450 for (unsigned i = 0; i < 10; i++)
3451 {
3452 rc = iscsiCommand(pImage, pScsiReq);
3453 if ( (RT_SUCCESS(rc) && !pScsiReq->cbSense)
3454 || RT_FAILURE(rc))
3455 break;
3456 rc = rcSense;
3457 }
3458 }
3459 else
3460 {
3461 rc = iscsiCommand(pImage, pScsiReq);
3462 if (RT_SUCCESS(rc) && pScsiReq->cbSense > 0)
3463 rc = rcSense;
3464 }
3465 }
3466
3467 return rc;
3468}
3469
3470
3471/**
3472 * Internal. - Executes a given function in a synchronous fashion
3473 * on the I/O thread if available.
3474 */
3475static int iscsiExecSync(PISCSIIMAGE pImage, PFNISCSIEXEC pfnExec, void *pvUser)
3476{
3477 int rc;
3478
3479 if (pImage->fExtendedSelectSupported)
3480 {
3481 ISCSICMDSYNC IScsiCmdSync;
3482 PISCSICMD pIScsiCmd = (PISCSICMD)RTMemAllocZ(sizeof(ISCSICMD));
3483 if (!pIScsiCmd)
3484 return VERR_NO_MEMORY;
3485
3486 /* Create event semaphore. */
3487 rc = RTSemEventCreate(&IScsiCmdSync.EventSem);
3488 if (RT_FAILURE(rc))
3489 {
3490 RTMemFree(pIScsiCmd);
3491 return rc;
3492 }
3493
3494 /* Init the command structure. */
3495 pIScsiCmd->pNext = NULL;
3496 pIScsiCmd->enmCmdType = ISCSICMDTYPE_EXEC;
3497 pIScsiCmd->pfnComplete = iscsiCommandCompleteSync;
3498 pIScsiCmd->pvUser = &IScsiCmdSync;
3499 pIScsiCmd->CmdType.Exec.pfnExec = pfnExec;
3500 pIScsiCmd->CmdType.Exec.pvUser = pvUser;
3501
3502 rc = iscsiCmdPut(pImage, pIScsiCmd);
3503 if (RT_FAILURE(rc))
3504 RTMemFree(pIScsiCmd);
3505 else
3506 {
3507 rc = RTSemEventWait(IScsiCmdSync.EventSem, RT_INDEFINITE_WAIT);
3508 AssertRC(rc);
3509 rc = IScsiCmdSync.rcCmd;
3510 }
3511
3512 RTSemEventDestroy(IScsiCmdSync.EventSem);
3513 }
3514 else
3515 {
3516 /* No I/O thread, execute in the current thread. */
3517 rc = pfnExec(pvUser);
3518 }
3519
3520 return rc;
3521}
3522
3523
3524static void iscsiCommandAsyncComplete(PISCSIIMAGE pImage, int rcReq, void *pvUser)
3525{
3526 bool fComplete = true;
3527 size_t cbTransfered = 0;
3528 PSCSIREQASYNC pReqAsync = (PSCSIREQASYNC)pvUser;
3529 PSCSIREQ pScsiReq = pReqAsync->pScsiReq;
3530
3531 if ( RT_SUCCESS(rcReq)
3532 && pScsiReq->cbSense > 0)
3533 {
3534 /* Try again if possible. */
3535 if (pReqAsync->cSenseRetries > 0)
3536 {
3537 pReqAsync->cSenseRetries--;
3538 pScsiReq->cbSense = sizeof(pReqAsync->abSense);
3539 int rc = iscsiCommandAsync(pImage, pScsiReq, iscsiCommandAsyncComplete, pReqAsync);
3540 if (RT_SUCCESS(rc))
3541 fComplete = false;
3542 else
3543 rcReq = pReqAsync->rcSense;
3544 }
3545 else
3546 rcReq = pReqAsync->rcSense;
3547 }
3548
3549 if (fComplete)
3550 {
3551 if (pScsiReq->enmXfer == SCSIXFER_FROM_TARGET)
3552 cbTransfered = pScsiReq->cbT2IData;
3553 else if (pScsiReq->enmXfer == SCSIXFER_TO_TARGET)
3554 cbTransfered = pScsiReq->cbI2TData;
3555 else
3556 AssertMsg(pScsiReq->enmXfer == SCSIXFER_NONE, ("To/From transfers are not supported yet\n"));
3557
3558 /* Continue I/O context. */
3559 pImage->pInterfaceIoCallbacks->pfnIoCtxCompleted(pImage->pInterfaceIo->pvUser,
3560 pReqAsync->pIoCtx, rcReq,
3561 cbTransfered);
3562
3563 RTMemFree(pScsiReq);
3564 RTMemFree(pReqAsync);
3565 }
3566}
3567
3568
3569/**
3570 * Internal. Free all allocated space for representing an image, and optionally
3571 * delete the image from disk.
3572 */
3573static void iscsiFreeImage(PISCSIIMAGE pImage, bool fDelete)
3574{
3575 Assert(pImage);
3576 Assert(!fDelete); /* This MUST be false, the flag isn't supported. */
3577
3578 if (pImage->Mutex != NIL_RTSEMMUTEX)
3579 {
3580 /* Detaching only makes sense when the mutex is there. Otherwise the
3581 * failure happened long before we could attach to the target. */
3582 iscsiExecSync(pImage, iscsiDetach, pImage);
3583 RTSemMutexDestroy(pImage->Mutex);
3584 pImage->Mutex = NIL_RTSEMMUTEX;
3585 }
3586 if (pImage->hThreadIo != NIL_RTTHREAD)
3587 {
3588 int rc;
3589
3590 ASMAtomicXchgBool(&pImage->fRunning, false);
3591 rc = iscsiIoThreadPoke(pImage);
3592 AssertRC(rc);
3593
3594 /* Wait for the thread to terminate. */
3595 rc = RTThreadWait(pImage->hThreadIo, RT_INDEFINITE_WAIT, NULL);
3596 AssertRC(rc);
3597 }
3598 /* Destroy the socket. */
3599 if (pImage->Socket != NIL_VDSOCKET)
3600 {
3601 pImage->pInterfaceNetCallbacks->pfnSocketDestroy(pImage->Socket);
3602 }
3603 if (pImage->MutexReqQueue != NIL_RTSEMMUTEX)
3604 {
3605 RTSemMutexDestroy(pImage->MutexReqQueue);
3606 pImage->MutexReqQueue = NIL_RTSEMMUTEX;
3607 }
3608 if (pImage->pszTargetName)
3609 {
3610 RTMemFree(pImage->pszTargetName);
3611 pImage->pszTargetName = NULL;
3612 }
3613 if (pImage->pszInitiatorName)
3614 {
3615 if (pImage->fAutomaticInitiatorName)
3616 RTStrFree(pImage->pszInitiatorName);
3617 else
3618 RTMemFree(pImage->pszInitiatorName);
3619 pImage->pszInitiatorName = NULL;
3620 }
3621 if (pImage->pszInitiatorUsername)
3622 {
3623 RTMemFree(pImage->pszInitiatorUsername);
3624 pImage->pszInitiatorUsername = NULL;
3625 }
3626 if (pImage->pbInitiatorSecret)
3627 {
3628 RTMemFree(pImage->pbInitiatorSecret);
3629 pImage->pbInitiatorSecret = NULL;
3630 }
3631 if (pImage->pszTargetUsername)
3632 {
3633 RTMemFree(pImage->pszTargetUsername);
3634 pImage->pszTargetUsername = NULL;
3635 }
3636 if (pImage->pbTargetSecret)
3637 {
3638 RTMemFree(pImage->pbTargetSecret);
3639 pImage->pbTargetSecret = NULL;
3640 }
3641 if (pImage->pvRecvPDUBuf)
3642 {
3643 RTMemFree(pImage->pvRecvPDUBuf);
3644 pImage->pvRecvPDUBuf = NULL;
3645 }
3646}
3647
3648/**
3649 * Internal: Open an image, constructing all necessary data structures.
3650 */
3651static int iscsiOpenImage(PISCSIIMAGE pImage, unsigned uOpenFlags)
3652{
3653 int rc;
3654 char *pszLUN = NULL, *pszLUNInitial = NULL;
3655 bool fLunEncoded = false;
3656 uint32_t uWriteSplitDef = 0;
3657 uint32_t uTimeoutDef = 0;
3658 uint64_t uHostIPTmp = 0;
3659 bool fHostIPDef = 0;
3660 rc = RTStrToUInt32Full(s_iscsiConfigDefaultWriteSplit, 0, &uWriteSplitDef);
3661 AssertRC(rc);
3662 rc = RTStrToUInt32Full(s_iscsiConfigDefaultTimeout, 0, &uTimeoutDef);
3663 AssertRC(rc);
3664 rc = RTStrToUInt64Full(s_iscsiConfigDefaultHostIPStack, 0, &uHostIPTmp);
3665 AssertRC(rc);
3666 fHostIPDef = !!uHostIPTmp;
3667
3668#if 0
3669 if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3670 return VERR_NOT_SUPPORTED;
3671#endif
3672
3673 pImage->uOpenFlags = uOpenFlags;
3674
3675 /* Get error signalling interface. */
3676 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
3677 if (pImage->pInterfaceError)
3678 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
3679
3680 /* Get TCP network stack interface. */
3681 pImage->pInterfaceNet = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_TCPNET);
3682 if (pImage->pInterfaceNet)
3683 pImage->pInterfaceNetCallbacks = VDGetInterfaceTcpNet(pImage->pInterfaceNet);
3684 else
3685 {
3686 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_INTERFACE,
3687 RT_SRC_POS, N_("iSCSI: TCP network stack interface missing"));
3688 goto out;
3689 }
3690
3691 /* Get configuration interface. */
3692 pImage->pInterfaceConfig = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_CONFIG);
3693 if (pImage->pInterfaceConfig)
3694 pImage->pInterfaceConfigCallbacks = VDGetInterfaceConfig(pImage->pInterfaceConfig);
3695 else
3696 {
3697 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_INTERFACE,
3698 RT_SRC_POS, N_("iSCSI: configuration interface missing"));
3699 goto out;
3700 }
3701
3702 /* Get I/O interface. */
3703 pImage->pInterfaceIo = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_IO);
3704 if (pImage->pInterfaceIo)
3705 pImage->pInterfaceIoCallbacks = VDGetInterfaceIO(pImage->pInterfaceIo);
3706 else
3707 {
3708 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_INTERFACE,
3709 RT_SRC_POS, N_("iSCSI: I/O interface missing"));
3710 goto out;
3711 }
3712
3713 /* This ISID will be adjusted later to make it unique on this host. */
3714 pImage->ISID = 0x800000000000ULL | 0x001234560000ULL;
3715 pImage->cISCSIRetries = 10;
3716 pImage->state = ISCSISTATE_FREE;
3717 pImage->pvRecvPDUBuf = RTMemAlloc(ISCSI_RECV_PDU_BUFFER_SIZE);
3718 pImage->cbRecvPDUBuf = ISCSI_RECV_PDU_BUFFER_SIZE;
3719 if (pImage->pvRecvPDUBuf == NULL)
3720 {
3721 rc = VERR_NO_MEMORY;
3722 goto out;
3723 }
3724 pImage->Mutex = NIL_RTSEMMUTEX;
3725 pImage->MutexReqQueue = NIL_RTSEMMUTEX;
3726 rc = RTSemMutexCreate(&pImage->Mutex);
3727 if (RT_FAILURE(rc))
3728 goto out;
3729
3730 rc = RTSemMutexCreate(&pImage->MutexReqQueue);
3731 if (RT_FAILURE(rc))
3732 goto out;
3733
3734 /* Validate configuration, detect unknown keys. */
3735 if (!VDCFGAreKeysValid(pImage->pInterfaceConfigCallbacks,
3736 pImage->pInterfaceConfig->pvUser,
3737 "TargetName\0InitiatorName\0LUN\0TargetAddress\0InitiatorUsername\0InitiatorSecret\0TargetUsername\0TargetSecret\0WriteSplit\0Timeout\0HostIPStack\0"))
3738 {
3739 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_CFG_VALUES, RT_SRC_POS, N_("iSCSI: configuration error: unknown configuration keys present"));
3740 goto out;
3741 }
3742
3743 /* Query the iSCSI upper level configuration. */
3744 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
3745 pImage->pInterfaceConfig->pvUser,
3746 "TargetName", &pImage->pszTargetName);
3747 if (RT_FAILURE(rc))
3748 {
3749 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetName as string"));
3750 goto out;
3751 }
3752 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
3753 pImage->pInterfaceConfig->pvUser,
3754 "InitiatorName", &pImage->pszInitiatorName);
3755 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
3756 {
3757 pImage->fAutomaticInitiatorName = true;
3758 rc = VINF_SUCCESS;
3759 }
3760 if (RT_FAILURE(rc))
3761 {
3762 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorName as string"));
3763 goto out;
3764 }
3765 rc = VDCFGQueryStringAllocDef(pImage->pInterfaceConfigCallbacks,
3766 pImage->pInterfaceConfig->pvUser,
3767 "LUN", &pszLUN, s_iscsiConfigDefaultLUN);
3768 if (RT_FAILURE(rc))
3769 {
3770 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read LUN as string"));
3771 goto out;
3772 }
3773 pszLUNInitial = pszLUN;
3774 if (!strncmp(pszLUN, "enc", 3))
3775 {
3776 fLunEncoded = true;
3777 pszLUN += 3;
3778 }
3779 rc = RTStrToUInt64Full(pszLUN, 0, &pImage->LUN);
3780 if (RT_FAILURE(rc))
3781 {
3782 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to convert LUN to integer"));
3783 goto out;
3784 }
3785 if (!fLunEncoded)
3786 {
3787 if (pImage->LUN <= 255)
3788 {
3789 pImage->LUN = pImage->LUN << 48; /* uses peripheral device addressing method */
3790 }
3791 else if (pImage->LUN <= 16383)
3792 {
3793 pImage->LUN = (pImage->LUN << 48) | RT_BIT_64(62); /* uses flat space addressing method */
3794 }
3795 else
3796 {
3797 rc = VERR_OUT_OF_RANGE;
3798 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: LUN number out of range (0-16383)"));
3799 goto out;
3800 }
3801 }
3802 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
3803 pImage->pInterfaceConfig->pvUser,
3804 "TargetAddress", &pImage->pszTargetAddress);
3805 if (RT_FAILURE(rc))
3806 {
3807 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetAddress as string"));
3808 goto out;
3809 }
3810 pImage->pszInitiatorUsername = NULL;
3811 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
3812 pImage->pInterfaceConfig->pvUser,
3813 "InitiatorUsername",
3814 &pImage->pszInitiatorUsername);
3815 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
3816 rc = VINF_SUCCESS;
3817 if (RT_FAILURE(rc))
3818 {
3819 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorUsername as string"));
3820 goto out;
3821 }
3822 pImage->pbInitiatorSecret = NULL;
3823 pImage->cbInitiatorSecret = 0;
3824 rc = VDCFGQueryBytesAlloc(pImage->pInterfaceConfigCallbacks,
3825 pImage->pInterfaceConfig->pvUser,
3826 "InitiatorSecret",
3827 (void **)&pImage->pbInitiatorSecret,
3828 &pImage->cbInitiatorSecret);
3829 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
3830 rc = VINF_SUCCESS;
3831 if (RT_FAILURE(rc))
3832 {
3833 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorSecret as byte string"));
3834 goto out;
3835 }
3836 pImage->pszTargetUsername = NULL;
3837 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
3838 pImage->pInterfaceConfig->pvUser,
3839 "TargetUsername",
3840 &pImage->pszTargetUsername);
3841 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
3842 rc = VINF_SUCCESS;
3843 if (RT_FAILURE(rc))
3844 {
3845 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetUsername as string"));
3846 goto out;
3847 }
3848 pImage->pbTargetSecret = NULL;
3849 pImage->cbTargetSecret = 0;
3850 rc = VDCFGQueryBytesAlloc(pImage->pInterfaceConfigCallbacks,
3851 pImage->pInterfaceConfig->pvUser,
3852 "TargetSecret", (void **)&pImage->pbTargetSecret,
3853 &pImage->cbTargetSecret);
3854 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
3855 rc = VINF_SUCCESS;
3856 if (RT_FAILURE(rc))
3857 {
3858 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetSecret as byte string"));
3859 goto out;
3860 }
3861 rc = VDCFGQueryU32Def(pImage->pInterfaceConfigCallbacks,
3862 pImage->pInterfaceConfig->pvUser,
3863 "WriteSplit", &pImage->cbWriteSplit,
3864 uWriteSplitDef);
3865 if (RT_FAILURE(rc))
3866 {
3867 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read WriteSplit as U32"));
3868 goto out;
3869 }
3870
3871 pImage->pszHostname = NULL;
3872 pImage->uPort = 0;
3873 pImage->Socket = NIL_VDSOCKET;
3874 /* Query the iSCSI lower level configuration. */
3875 rc = VDCFGQueryU32Def(pImage->pInterfaceConfigCallbacks,
3876 pImage->pInterfaceConfig->pvUser,
3877 "Timeout", &pImage->uReadTimeout,
3878 uTimeoutDef);
3879 if (RT_FAILURE(rc))
3880 {
3881 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read Timeout as U32"));
3882 goto out;
3883 }
3884 rc = VDCFGQueryBoolDef(pImage->pInterfaceConfigCallbacks,
3885 pImage->pInterfaceConfig->pvUser,
3886 "HostIPStack", &pImage->fHostIP,
3887 fHostIPDef);
3888 if (RT_FAILURE(rc))
3889 {
3890 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read HostIPStack as boolean"));
3891 goto out;
3892 }
3893
3894 /* Don't actually establish iSCSI transport connection if this is just an
3895 * open to query the image information and the host IP stack isn't used.
3896 * Even trying is rather useless, as in this context the InTnet IP stack
3897 * isn't present. Returning dummies is the best possible result anyway. */
3898 if ((uOpenFlags & VD_OPEN_FLAGS_INFO) && !pImage->fHostIP)
3899 {
3900 LogFunc(("Not opening the transport connection as IntNet IP stack is not available. Will return dummies\n"));
3901 goto out;
3902 }
3903
3904 memset(pImage->aCmdsWaiting, 0, sizeof(pImage->aCmdsWaiting));
3905
3906 /* Create the socket structure. */
3907 rc = pImage->pInterfaceNetCallbacks->pfnSocketCreate(VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT,
3908 &pImage->Socket);
3909 if (RT_SUCCESS(rc))
3910 {
3911 pImage->fExtendedSelectSupported = true;
3912 pImage->fRunning = true;
3913 rc = RTThreadCreate(&pImage->hThreadIo, iscsiIoThreadWorker, pImage, 0,
3914 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "iSCSI-Io");
3915 if (RT_FAILURE(rc))
3916 {
3917 LogFunc(("Creating iSCSI I/O thread failed rc=%Rrc\n", rc));
3918 goto out;
3919 }
3920 }
3921 else if (rc == VERR_NOT_SUPPORTED)
3922 {
3923 /* Async I/O is not supported without extended select. */
3924 if ((uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO))
3925 {
3926 LogFunc(("Extended select is not supported by the interface but async I/O is requested -> %Rrc\n", rc));
3927 goto out;
3928 }
3929 else
3930 {
3931 pImage->fExtendedSelectSupported = false;
3932 rc = pImage->pInterfaceNetCallbacks->pfnSocketCreate(0, &pImage->Socket);
3933 if (RT_FAILURE(rc))
3934 {
3935 LogFunc(("Creating socket failed -> %Rrc\n", rc));
3936 goto out;
3937 }
3938 }
3939 }
3940 else
3941 {
3942 LogFunc(("Creating socket failed -> %Rrc\n", rc));
3943 goto out;
3944 }
3945
3946 /*
3947 * Attach to the iSCSI target. This implicitly establishes the iSCSI
3948 * transport connection.
3949 */
3950 rc = iscsiExecSync(pImage, iscsiAttach, pImage);
3951 if (RT_FAILURE(rc))
3952 {
3953 LogRel(("iSCSI: could not open target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
3954 goto out;
3955 }
3956 LogFlowFunc(("target '%s' opened successfully\n", pImage->pszTargetName));
3957
3958 SCSIREQ sr;
3959 RTSGSEG DataSeg;
3960 uint8_t sense[96];
3961 uint8_t data8[8];
3962 uint8_t data12[12];
3963
3964 /*
3965 * Inquire available LUNs - purely dummy request.
3966 */
3967 uint8_t cdb_rlun[12];
3968 uint8_t rlundata[16];
3969 cdb_rlun[0] = SCSI_REPORT_LUNS;
3970 cdb_rlun[1] = 0; /* reserved */
3971 cdb_rlun[2] = 0; /* reserved */
3972 cdb_rlun[3] = 0; /* reserved */
3973 cdb_rlun[4] = 0; /* reserved */
3974 cdb_rlun[5] = 0; /* reserved */
3975 cdb_rlun[6] = sizeof(rlundata) >> 24;
3976 cdb_rlun[7] = (sizeof(rlundata) >> 16) & 0xff;
3977 cdb_rlun[8] = (sizeof(rlundata) >> 8) & 0xff;
3978 cdb_rlun[9] = sizeof(rlundata) & 0xff;
3979 cdb_rlun[10] = 0; /* reserved */
3980 cdb_rlun[11] = 0; /* control */
3981
3982 DataSeg.pvSeg = rlundata;
3983 DataSeg.cbSeg = sizeof(rlundata);
3984
3985 sr.enmXfer = SCSIXFER_FROM_TARGET;
3986 sr.cbCmd = sizeof(cdb_rlun);
3987 sr.pvCmd = cdb_rlun;
3988 sr.cbI2TData = 0;
3989 sr.paI2TSegs = NULL;
3990 sr.cI2TSegs = 0;
3991 sr.cbT2IData = DataSeg.cbSeg;
3992 sr.paT2ISegs = &DataSeg;
3993 sr.cT2ISegs = 1;
3994 sr.cbSense = sizeof(sense);
3995 sr.pvSense = sense;
3996
3997 rc = iscsiCommandSync(pImage, &sr, false, VERR_INVALID_STATE);
3998 if (RT_FAILURE(rc))
3999 {
4000 LogRel(("iSCSI: Could not get LUN info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
4001 return rc;
4002 }
4003
4004 /*
4005 * Inquire device characteristics - no tapes, scanners etc., please.
4006 */
4007 uint8_t cdb_inq[6];
4008 cdb_inq[0] = SCSI_INQUIRY;
4009 cdb_inq[1] = 0; /* reserved */
4010 cdb_inq[2] = 0; /* reserved */
4011 cdb_inq[3] = 0; /* reserved */
4012 cdb_inq[4] = sizeof(data8);
4013 cdb_inq[5] = 0; /* control */
4014
4015 DataSeg.pvSeg = data8;
4016 DataSeg.cbSeg = sizeof(data8);
4017
4018 sr.enmXfer = SCSIXFER_FROM_TARGET;
4019 sr.cbCmd = sizeof(cdb_inq);
4020 sr.pvCmd = cdb_inq;
4021 sr.cbI2TData = 0;
4022 sr.paI2TSegs = NULL;
4023 sr.cI2TSegs = 0;
4024 sr.cbT2IData = DataSeg.cbSeg;
4025 sr.paT2ISegs = &DataSeg;
4026 sr.cT2ISegs = 1;
4027 sr.cbSense = sizeof(sense);
4028 sr.pvSense = sense;
4029
4030 rc = iscsiCommandSync(pImage, &sr, true /* fRetry */, VERR_INVALID_STATE);
4031 if (RT_SUCCESS(rc))
4032 {
4033 uint8_t devType = (sr.cbT2IData > 0) ? data8[0] & SCSI_DEVTYPE_MASK : 255;
4034 if (devType != SCSI_DEVTYPE_DISK)
4035 {
4036 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
4037 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports device type=%u"),
4038 pImage->pszTargetAddress, pImage->pszTargetName,
4039 pImage->LUN, devType);
4040 LogRel(("iSCSI: Unsupported SCSI peripheral device type %d for target %s\n", devType & SCSI_DEVTYPE_MASK, pImage->pszTargetName));
4041 goto out;
4042 }
4043 uint8_t uCmdQueue = (sr.cbT2IData >= 8) ? data8[7] & SCSI_INQUIRY_CMDQUE_MASK : 0;
4044 if (uCmdQueue > 0)
4045 pImage->fCmdQueuingSupported = true;
4046 else if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
4047 {
4048 rc = VERR_NOT_SUPPORTED;
4049 goto out;
4050 }
4051
4052 LogRel(("iSCSI: target address %s, target name %s, %s command queuing\n",
4053 pImage->pszTargetAddress, pImage->pszTargetName,
4054 pImage->fCmdQueuingSupported ? "supports" : "doesn't support"));
4055 }
4056 else
4057 {
4058 LogRel(("iSCSI: Could not get INQUIRY info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
4059 goto out;
4060 }
4061
4062 /*
4063 * Query write disable bit in the device specific parameter entry in the
4064 * mode parameter header. Refuse read/write opening of read only disks.
4065 */
4066
4067 uint8_t cdb_ms[6];
4068 uint8_t data4[4];
4069 cdb_ms[0] = SCSI_MODE_SENSE_6;
4070 cdb_ms[1] = 0; /* dbd=0/reserved */
4071 cdb_ms[2] = 0x3f; /* pc=0/page code=0x3f, ask for all pages */
4072 cdb_ms[3] = 0; /* subpage code=0, return everything in page_0 format */
4073 cdb_ms[4] = sizeof(data4); /* allocation length=4 */
4074 cdb_ms[5] = 0; /* control */
4075
4076 DataSeg.pvSeg = data4;
4077 DataSeg.cbSeg = sizeof(data4);
4078
4079 sr.enmXfer = SCSIXFER_FROM_TARGET;
4080 sr.cbCmd = sizeof(cdb_ms);
4081 sr.pvCmd = cdb_ms;
4082 sr.cbI2TData = 0;
4083 sr.paI2TSegs = NULL;
4084 sr.cI2TSegs = 0;
4085 sr.cbT2IData = DataSeg.cbSeg;
4086 sr.paT2ISegs = &DataSeg;
4087 sr.cT2ISegs = 1;
4088 sr.cbSense = sizeof(sense);
4089 sr.pvSense = sense;
4090
4091 rc = iscsiCommandSync(pImage, &sr, true /* fRetry */, VERR_INVALID_STATE);
4092 if (RT_SUCCESS(rc))
4093 {
4094 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY) && data4[2] & 0x80)
4095 {
4096 rc = VERR_VD_IMAGE_READ_ONLY;
4097 goto out;
4098 }
4099 }
4100 else
4101 {
4102 LogRel(("iSCSI: Could not get MODE SENSE info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
4103 goto out;
4104 }
4105
4106 /*
4107 * Determine sector size and capacity of the volume immediately.
4108 */
4109 uint8_t cdb_cap[16];
4110
4111 RT_ZERO(data12);
4112 RT_ZERO(cdb_cap);
4113 cdb_cap[0] = SCSI_SERVICE_ACTION_IN_16;
4114 cdb_cap[1] = SCSI_SVC_ACTION_IN_READ_CAPACITY_16; /* subcommand */
4115 cdb_cap[10+3] = sizeof(data12); /* allocation length (dword) */
4116
4117 DataSeg.pvSeg = data12;
4118 DataSeg.cbSeg = sizeof(data12);
4119
4120 sr.enmXfer = SCSIXFER_FROM_TARGET;
4121 sr.cbCmd = sizeof(cdb_cap);
4122 sr.pvCmd = cdb_cap;
4123 sr.cbI2TData = 0;
4124 sr.paI2TSegs = NULL;
4125 sr.cI2TSegs = 0;
4126 sr.cbT2IData = DataSeg.cbSeg;
4127 sr.paT2ISegs = &DataSeg;
4128 sr.cT2ISegs = 1;
4129 sr.cbSense = sizeof(sense);
4130 sr.pvSense = sense;
4131
4132 rc = iscsiCommandSync(pImage, &sr, false /* fRetry */, VINF_SUCCESS);
4133 if ( RT_SUCCESS(rc)
4134 && sr.status == SCSI_STATUS_OK)
4135 {
4136 pImage->cVolume = RT_BE2H_U64(*(uint64_t *)&data12[0]);
4137 pImage->cVolume++;
4138 pImage->cbSector = RT_BE2H_U32(*(uint32_t *)&data12[8]);
4139 pImage->cbSize = pImage->cVolume * pImage->cbSector;
4140 if (pImage->cVolume == 0 || pImage->cbSector != 512 || pImage->cbSize < pImage->cVolume)
4141 {
4142 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
4143 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports media sector count=%llu sector size=%u"),
4144 pImage->pszTargetAddress, pImage->pszTargetName,
4145 pImage->LUN, pImage->cVolume, pImage->cbSector);
4146 }
4147 }
4148 else
4149 {
4150 uint8_t cdb_capfb[10];
4151
4152 RT_ZERO(data8);
4153 cdb_capfb[0] = SCSI_READ_CAPACITY;
4154 cdb_capfb[1] = 0; /* reserved */
4155 cdb_capfb[2] = 0; /* reserved */
4156 cdb_capfb[3] = 0; /* reserved */
4157 cdb_capfb[4] = 0; /* reserved */
4158 cdb_capfb[5] = 0; /* reserved */
4159 cdb_capfb[6] = 0; /* reserved */
4160 cdb_capfb[7] = 0; /* reserved */
4161 cdb_capfb[8] = 0; /* reserved */
4162 cdb_capfb[9] = 0; /* control */
4163
4164 DataSeg.pvSeg = data8;
4165 DataSeg.cbSeg = sizeof(data8);
4166
4167 sr.enmXfer = SCSIXFER_FROM_TARGET;
4168 sr.cbCmd = sizeof(cdb_capfb);
4169 sr.pvCmd = cdb_capfb;
4170 sr.cbI2TData = 0;
4171 sr.paI2TSegs = NULL;
4172 sr.cI2TSegs = 0;
4173 sr.cbT2IData = DataSeg.cbSeg;
4174 sr.paT2ISegs = &DataSeg;
4175 sr.cT2ISegs = 1;
4176 sr.cbSense = sizeof(sense);
4177 sr.pvSense = sense;
4178
4179 rc = iscsiCommandSync(pImage, &sr, false /* fRetry */, VINF_SUCCESS);
4180 if (RT_SUCCESS(rc))
4181 {
4182 pImage->cVolume = (data8[0] << 24) | (data8[1] << 16) | (data8[2] << 8) | data8[3];
4183 pImage->cVolume++;
4184 pImage->cbSector = (data8[4] << 24) | (data8[5] << 16) | (data8[6] << 8) | data8[7];
4185 pImage->cbSize = pImage->cVolume * pImage->cbSector;
4186 if (pImage->cVolume == 0 || pImage->cbSector != 512)
4187 {
4188 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
4189 RT_SRC_POS, N_("iSCSI: fallback capacity detectio for target address %s, target name %s, SCSI LUN %lld reports media sector count=%llu sector size=%u"),
4190 pImage->pszTargetAddress, pImage->pszTargetName,
4191 pImage->LUN, pImage->cVolume, pImage->cbSector);
4192 }
4193 }
4194 else
4195 {
4196 LogRel(("iSCSI: Could not determine capacity of target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
4197 goto out;
4198 }
4199 }
4200
4201 /*
4202 * Check the read and write cache bits.
4203 * Try to enable the cache if it is disabled.
4204 *
4205 * We already checked that this is a block access device. No need
4206 * to do it again.
4207 */
4208 uint8_t aCachingModePage[32];
4209 uint8_t aCDBModeSense6[6];
4210
4211 memset(aCachingModePage, '\0', sizeof(aCachingModePage));
4212 aCDBModeSense6[0] = SCSI_MODE_SENSE_6;
4213 aCDBModeSense6[1] = 0;
4214 aCDBModeSense6[2] = (0x00 << 6) | (0x08 & 0x3f); /* Current values and caching mode page */
4215 aCDBModeSense6[3] = 0; /* Sub page code. */
4216 aCDBModeSense6[4] = sizeof(aCachingModePage) & 0xff;
4217 aCDBModeSense6[5] = 0;
4218
4219 DataSeg.pvSeg = aCachingModePage;
4220 DataSeg.cbSeg = sizeof(aCachingModePage);
4221
4222 sr.enmXfer = SCSIXFER_FROM_TARGET;
4223 sr.cbCmd = sizeof(aCDBModeSense6);
4224 sr.pvCmd = aCDBModeSense6;
4225 sr.cbI2TData = 0;
4226 sr.paI2TSegs = NULL;
4227 sr.cI2TSegs = 0;
4228 sr.cbT2IData = DataSeg.cbSeg;
4229 sr.paT2ISegs = &DataSeg;
4230 sr.cT2ISegs = 1;
4231 sr.cbSense = sizeof(sense);
4232 sr.pvSense = sense;
4233 rc = iscsiCommandSync(pImage, &sr, false /* fRetry */, VINF_SUCCESS);
4234 if ( RT_SUCCESS(rc)
4235 && (sr.status == SCSI_STATUS_OK)
4236 && (aCachingModePage[0] >= 15)
4237 && (aCachingModePage[4 + aCachingModePage[3]] & 0x3f) == 0x08
4238 && (aCachingModePage[4 + aCachingModePage[3] + 1] > 3))
4239 {
4240 uint32_t Offset = 4 + aCachingModePage[3];
4241 /*
4242 * Check if the read and/or the write cache is disabled.
4243 * The write cache is disabled if bit 2 (WCE) is zero and
4244 * the read cache is disabled if bit 0 (RCD) is set.
4245 */
4246 if (!ASMBitTest(&aCachingModePage[Offset + 2], 2) || ASMBitTest(&aCachingModePage[Offset + 2], 0))
4247 {
4248 /*
4249 * Write Cache Enable (WCE) bit is zero or the Read Cache Disable (RCD) is one
4250 * So one of the caches is disabled. Enable both caches.
4251 * The rest is unchanged.
4252 */
4253 ASMBitSet(&aCachingModePage[Offset + 2], 2);
4254 ASMBitClear(&aCachingModePage[Offset + 2], 0);
4255
4256 uint8_t aCDBCaching[6];
4257 aCDBCaching[0] = SCSI_MODE_SELECT_6;
4258 aCDBCaching[1] = 0; /* Don't write the page into NV RAM. */
4259 aCDBCaching[2] = 0;
4260 aCDBCaching[3] = 0;
4261 aCDBCaching[4] = sizeof(aCachingModePage) & 0xff;
4262 aCDBCaching[5] = 0;
4263
4264 DataSeg.pvSeg = aCachingModePage;
4265 DataSeg.cbSeg = sizeof(aCachingModePage);
4266
4267 sr.enmXfer = SCSIXFER_TO_TARGET;
4268 sr.cbCmd = sizeof(aCDBCaching);
4269 sr.pvCmd = aCDBCaching;
4270 sr.cbI2TData = DataSeg.cbSeg;
4271 sr.paI2TSegs = &DataSeg;
4272 sr.cI2TSegs = 1;
4273 sr.cbT2IData = 0;
4274 sr.paT2ISegs = NULL;
4275 sr.cT2ISegs = 0;
4276 sr.cbSense = sizeof(sense);
4277 sr.pvSense = sense;
4278 sr.status = 0;
4279 rc = iscsiCommandSync(pImage, &sr, false /* fRetry */, VINF_SUCCESS);
4280 if ( RT_SUCCESS(rc)
4281 && (sr.status == SCSI_STATUS_OK))
4282 {
4283 LogRel(("iSCSI: Enabled read and write cache of target %s\n", pImage->pszTargetName));
4284 }
4285 else
4286 {
4287 /* Log failures but continue. */
4288 LogRel(("iSCSI: Could not enable read and write cache of target %s, rc=%Rrc status=%#x\n",
4289 pImage->pszTargetName, rc, sr.status));
4290 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
4291 rc = VINF_SUCCESS;
4292 }
4293 }
4294 }
4295 else
4296 {
4297 /* Log errors but continue. */
4298 LogRel(("iSCSI: Could not check write cache of target %s, rc=%Rrc, got mode page %#x\n", pImage->pszTargetName, rc,aCachingModePage[0] & 0x3f));
4299 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
4300 rc = VINF_SUCCESS;
4301 }
4302
4303out:
4304 if (RT_FAILURE(rc))
4305 iscsiFreeImage(pImage, false);
4306 return rc;
4307}
4308
4309
4310/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
4311static int iscsiCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk)
4312{
4313 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
4314
4315 /* iSCSI images can't be checked for validity this way, as the filename
4316 * just can't supply enough configuration information. */
4317 int rc = VERR_VD_ISCSI_INVALID_HEADER;
4318
4319 LogFlowFunc(("returns %Rrc\n", rc));
4320 return rc;
4321}
4322
4323
4324/** @copydoc VBOXHDDBACKEND::pfnOpen */
4325static int iscsiOpen(const char *pszFilename, unsigned uOpenFlags,
4326 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
4327 void **ppBackendData)
4328{
4329 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
4330 int rc;
4331 PISCSIIMAGE pImage;
4332
4333 /* Check open flags. All valid flags are supported. */
4334 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
4335 {
4336 rc = VERR_INVALID_PARAMETER;
4337 goto out;
4338 }
4339
4340 /* Check remaining arguments. */
4341 if ( !VALID_PTR(pszFilename)
4342 || !*pszFilename
4343 || strchr(pszFilename, '"'))
4344 {
4345 rc = VERR_INVALID_PARAMETER;
4346 goto out;
4347 }
4348
4349 pImage = (PISCSIIMAGE)RTMemAllocZ(sizeof(ISCSIIMAGE));
4350 if (!pImage)
4351 {
4352 rc = VERR_NO_MEMORY;
4353 goto out;
4354 }
4355
4356 pImage->pszFilename = pszFilename;
4357 pImage->pszInitiatorName = NULL;
4358 pImage->pszTargetName = NULL;
4359 pImage->pszTargetAddress = NULL;
4360 pImage->pszInitiatorUsername = NULL;
4361 pImage->pbInitiatorSecret = NULL;
4362 pImage->pszTargetUsername = NULL;
4363 pImage->pbTargetSecret = NULL;
4364 pImage->paCurrReq = NULL;
4365 pImage->pvRecvPDUBuf = NULL;
4366 pImage->pszHostname = NULL;
4367 pImage->pVDIfsDisk = pVDIfsDisk;
4368 pImage->pVDIfsImage = pVDIfsImage;
4369
4370 rc = iscsiOpenImage(pImage, uOpenFlags);
4371 if (RT_SUCCESS(rc))
4372 {
4373 LogFlowFunc(("target %s cVolume %d, cbSector %d\n", pImage->pszTargetName, pImage->cVolume, pImage->cbSector));
4374 LogRel(("iSCSI: target address %s, target name %s, SCSI LUN %lld\n", pImage->pszTargetAddress, pImage->pszTargetName, pImage->LUN));
4375 *ppBackendData = pImage;
4376 }
4377
4378out:
4379 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4380 return rc;
4381}
4382
4383
4384/** @copydoc VBOXHDDBACKEND::pfnCreate */
4385static int iscsiCreate(const char *pszFilename, uint64_t cbSize,
4386 unsigned uImageFlags, const char *pszComment,
4387 PCPDMMEDIAGEOMETRY pPCHSGeometry,
4388 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
4389 unsigned uOpenFlags, unsigned uPercentStart,
4390 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
4391 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
4392 void **ppBackendData)
4393{
4394 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p ppBackendData=%#p", pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, ppBackendData));
4395 int rc = VERR_NOT_SUPPORTED;
4396
4397 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4398 return rc;
4399}
4400
4401
4402/** @copydoc VBOXHDDBACKEND::pfnRename */
4403static int iscsiRename(void *pBackendData, const char *pszFilename)
4404{
4405 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
4406 int rc = VERR_NOT_SUPPORTED;
4407
4408 LogFlowFunc(("returns %Rrc\n", rc));
4409 return rc;
4410}
4411
4412
4413/** @copydoc VBOXHDDBACKEND::pfnClose */
4414static int iscsiClose(void *pBackendData, bool fDelete)
4415{
4416 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
4417 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4418 int rc = VINF_SUCCESS;
4419
4420 Assert(!fDelete); /* This flag is unsupported. */
4421
4422 /* Freeing a never allocated image (e.g. because the open failed) is
4423 * not signalled as an error. After all nothing bad happens. */
4424 if (pImage)
4425 iscsiFreeImage(pImage, fDelete);
4426
4427 LogFlowFunc(("returns %Rrc\n", rc));
4428 return rc;
4429}
4430
4431
4432/** @copydoc VBOXHDDBACKEND::pfnRead */
4433static int iscsiRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
4434 size_t cbToRead, size_t *pcbActuallyRead)
4435{
4436 /** @todo reinstate logging of the target everywhere - dropped temporarily */
4437 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
4438 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4439 uint64_t lba;
4440 uint16_t tls;
4441 int rc;
4442
4443 Assert(pImage);
4444 Assert(uOffset % 512 == 0);
4445 Assert(cbToRead % 512 == 0);
4446
4447 Assert(pImage->cbSector);
4448 AssertPtr(pvBuf);
4449
4450 if ( uOffset + cbToRead > pImage->cbSize
4451 || cbToRead == 0)
4452 {
4453 rc = VERR_INVALID_PARAMETER;
4454 goto out;
4455 }
4456
4457 /*
4458 * Clip read size to a value which is supported by the target.
4459 */
4460 cbToRead = RT_MIN(cbToRead, pImage->cbRecvDataLength);
4461
4462 lba = uOffset / pImage->cbSector;
4463 tls = (uint16_t)(cbToRead / pImage->cbSector);
4464 SCSIREQ sr;
4465 RTSGSEG T2ISeg;
4466 uint8_t cdb[10];
4467 uint8_t sense[96];
4468
4469 cdb[0] = SCSI_READ_10;
4470 cdb[1] = 0; /* reserved */
4471 cdb[2] = (lba >> 24) & 0xff;
4472 cdb[3] = (lba >> 16) & 0xff;
4473 cdb[4] = (lba >> 8) & 0xff;
4474 cdb[5] = lba & 0xff;
4475 cdb[6] = 0; /* reserved */
4476 cdb[7] = (tls >> 8) & 0xff;
4477 cdb[8] = tls & 0xff;
4478 cdb[9] = 0; /* control */
4479
4480 T2ISeg.pvSeg = pvBuf;
4481 T2ISeg.cbSeg = cbToRead;
4482
4483 sr.enmXfer = SCSIXFER_FROM_TARGET;
4484 sr.cbCmd = sizeof(cdb);
4485 sr.pvCmd = cdb;
4486 sr.cbI2TData = 0;
4487 sr.paI2TSegs = NULL;
4488 sr.cI2TSegs = 0;
4489 sr.cbT2IData = cbToRead;
4490 sr.paT2ISegs = &T2ISeg;
4491 sr.cT2ISegs = 1;
4492 sr.cbSense = sizeof(sense);
4493 sr.pvSense = sense;
4494
4495 rc = iscsiCommandSync(pImage, &sr, true, VERR_READ_ERROR);
4496 if (RT_FAILURE(rc))
4497 {
4498 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
4499 *pcbActuallyRead = 0;
4500 }
4501 else
4502 *pcbActuallyRead = sr.cbT2IData;
4503
4504out:
4505 LogFlowFunc(("returns %Rrc\n", rc));
4506 return rc;
4507}
4508
4509
4510/** @copydoc VBOXHDDBACKEND::pfnWrite */
4511static int iscsiWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
4512 size_t cbToWrite, size_t *pcbWriteProcess,
4513 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
4514{
4515 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
4516 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4517 uint64_t lba;
4518 uint16_t tls;
4519 int rc;
4520
4521 Assert(pImage);
4522 Assert(uOffset % 512 == 0);
4523 Assert(cbToWrite % 512 == 0);
4524
4525 Assert(pImage->cbSector);
4526 Assert(pvBuf);
4527
4528 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4529 {
4530 rc = VERR_VD_IMAGE_READ_ONLY;
4531 goto out;
4532 }
4533
4534 *pcbPreRead = 0;
4535 *pcbPostRead = 0;
4536
4537 /*
4538 * Clip write size to a value which is supported by the target.
4539 */
4540 cbToWrite = RT_MIN(cbToWrite, pImage->cbSendDataLength);
4541
4542 lba = uOffset / pImage->cbSector;
4543 tls = (uint16_t)(cbToWrite / pImage->cbSector);
4544 SCSIREQ sr;
4545 RTSGSEG I2TSeg;
4546 uint8_t cdb[10];
4547 uint8_t sense[96];
4548
4549 cdb[0] = SCSI_WRITE_10;
4550 cdb[1] = 0; /* reserved */
4551 cdb[2] = (lba >> 24) & 0xff;
4552 cdb[3] = (lba >> 16) & 0xff;
4553 cdb[4] = (lba >> 8) & 0xff;
4554 cdb[5] = lba & 0xff;
4555 cdb[6] = 0; /* reserved */
4556 cdb[7] = (tls >> 8) & 0xff;
4557 cdb[8] = tls & 0xff;
4558 cdb[9] = 0; /* control */
4559
4560 I2TSeg.pvSeg = (void *)pvBuf;
4561 I2TSeg.cbSeg = cbToWrite;
4562
4563 sr.enmXfer = SCSIXFER_TO_TARGET;
4564 sr.cbCmd = sizeof(cdb);
4565 sr.pvCmd = cdb;
4566 sr.cbI2TData = cbToWrite;
4567 sr.paI2TSegs = &I2TSeg;
4568 sr.cI2TSegs = 1;
4569 sr.cbT2IData = 0;
4570 sr.paT2ISegs = NULL;
4571 sr.cT2ISegs = 0;
4572 sr.cbSense = sizeof(sense);
4573 sr.pvSense = sense;
4574
4575 rc = iscsiCommandSync(pImage, &sr, true, VERR_WRITE_ERROR);
4576 if (RT_FAILURE(rc))
4577 {
4578 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
4579 *pcbWriteProcess = 0;
4580 }
4581 else
4582 *pcbWriteProcess = cbToWrite;
4583
4584out:
4585 LogFlowFunc(("returns %Rrc\n", rc));
4586 return rc;
4587}
4588
4589
4590/** @copydoc VBOXHDDBACKEND::pfnFlush */
4591static int iscsiFlush(void *pBackendData)
4592{
4593 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4594 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4595 int rc;
4596
4597 Assert(pImage);
4598
4599 SCSIREQ sr;
4600 uint8_t cdb[10];
4601 uint8_t sense[96];
4602
4603 cdb[0] = SCSI_SYNCHRONIZE_CACHE;
4604 cdb[1] = 0; /* reserved */
4605 cdb[2] = 0; /* LBA 0 */
4606 cdb[3] = 0; /* LBA 0 */
4607 cdb[4] = 0; /* LBA 0 */
4608 cdb[5] = 0; /* LBA 0 */
4609 cdb[6] = 0; /* reserved */
4610 cdb[7] = 0; /* transfer everything to disk */
4611 cdb[8] = 0; /* transfer everything to disk */
4612 cdb[9] = 0; /* control */
4613
4614 sr.enmXfer = SCSIXFER_TO_TARGET;
4615 sr.cbCmd = sizeof(cdb);
4616 sr.pvCmd = cdb;
4617 sr.cbI2TData = 0;
4618 sr.paI2TSegs = NULL;
4619 sr.cI2TSegs = 0;
4620 sr.cbT2IData = 0;
4621 sr.paT2ISegs = NULL;
4622 sr.cT2ISegs = 0;
4623 sr.cbSense = sizeof(sense);
4624 sr.pvSense = sense;
4625
4626 rc = iscsiCommandSync(pImage, &sr, false, VINF_SUCCESS);
4627 if (RT_FAILURE(rc))
4628 AssertMsgFailed(("iscsiCommand(%s) -> %Rrc\n", pImage->pszTargetName, rc));
4629 LogFlowFunc(("returns %Rrc\n", rc));
4630 return rc;
4631}
4632
4633
4634/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
4635static unsigned iscsiGetVersion(void *pBackendData)
4636{
4637 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4638 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4639
4640 Assert(pImage);
4641 NOREF(pImage);
4642
4643 return 0;
4644}
4645
4646
4647/** @copydoc VBOXHDDBACKEND::pfnGetSize */
4648static uint64_t iscsiGetSize(void *pBackendData)
4649{
4650 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4651 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4652
4653 Assert(pImage);
4654
4655 if (pImage)
4656 return pImage->cbSize;
4657 else
4658 return 0;
4659}
4660
4661
4662/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
4663static uint64_t iscsiGetFileSize(void *pBackendData)
4664{
4665 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4666 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4667
4668 Assert(pImage);
4669 NOREF(pImage);
4670
4671 if (pImage)
4672 return pImage->cbSize;
4673 else
4674 return 0;
4675}
4676
4677
4678/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
4679static int iscsiGetPCHSGeometry(void *pBackendData,
4680 PPDMMEDIAGEOMETRY pPCHSGeometry)
4681{
4682 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
4683 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4684 int rc;
4685
4686 Assert(pImage);
4687
4688 if (pImage)
4689 rc = VERR_VD_GEOMETRY_NOT_SET;
4690 else
4691 rc = VERR_VD_NOT_OPENED;
4692
4693 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
4694 return rc;
4695}
4696
4697
4698/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
4699static int iscsiSetPCHSGeometry(void *pBackendData,
4700 PCPDMMEDIAGEOMETRY pPCHSGeometry)
4701{
4702 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
4703 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4704 int rc;
4705
4706 Assert(pImage);
4707
4708 if (pImage)
4709 {
4710 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4711 {
4712 rc = VERR_VD_IMAGE_READ_ONLY;
4713 goto out;
4714 }
4715 rc = VERR_VD_GEOMETRY_NOT_SET;
4716 }
4717 else
4718 rc = VERR_VD_NOT_OPENED;
4719
4720out:
4721 LogFlowFunc(("returns %Rrc\n", rc));
4722 return rc;
4723}
4724
4725
4726/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
4727static int iscsiGetLCHSGeometry(void *pBackendData,
4728 PPDMMEDIAGEOMETRY pLCHSGeometry)
4729{
4730 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
4731 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4732 int rc;
4733
4734 Assert(pImage);
4735
4736 if (pImage)
4737 rc = VERR_VD_GEOMETRY_NOT_SET;
4738 else
4739 rc = VERR_VD_NOT_OPENED;
4740
4741 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
4742 return rc;
4743}
4744
4745
4746/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
4747static unsigned iscsiGetImageFlags(void *pBackendData)
4748{
4749 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4750 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4751 unsigned uImageFlags;
4752
4753 Assert(pImage);
4754 NOREF(pImage);
4755
4756 uImageFlags = VD_IMAGE_FLAGS_FIXED;
4757
4758 LogFlowFunc(("returns %#x\n", uImageFlags));
4759 return uImageFlags;
4760}
4761
4762
4763/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
4764static unsigned iscsiGetOpenFlags(void *pBackendData)
4765{
4766 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
4767 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4768 unsigned uOpenFlags;
4769
4770 Assert(pImage);
4771
4772 if (pImage)
4773 uOpenFlags = pImage->uOpenFlags;
4774 else
4775 uOpenFlags = 0;
4776
4777 LogFlowFunc(("returns %#x\n", uOpenFlags));
4778 return uOpenFlags;
4779}
4780
4781
4782/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
4783static int iscsiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
4784{
4785 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
4786 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4787 int rc;
4788
4789 /* Image must be opened and the new flags must be valid. Just readonly and
4790 * info flags are supported. */
4791 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO)))
4792 {
4793 rc = VERR_INVALID_PARAMETER;
4794 goto out;
4795 }
4796
4797 /* Implement this operation via reopening the image if we actually need
4798 * to do something. A read/write -> readonly transition doesn't need a
4799 * reopen. In the other direction we don't have the necessary information
4800 * as the "disk is readonly" flag is thrown away. Can be optimized too,
4801 * but it's not worth the effort at the moment. */
4802 if ( !(uOpenFlags & VD_OPEN_FLAGS_READONLY)
4803 && (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4804 {
4805 iscsiFreeImage(pImage, false);
4806 rc = iscsiOpenImage(pImage, uOpenFlags);
4807 }
4808 else
4809 {
4810 pImage->uOpenFlags = uOpenFlags;
4811 rc = VINF_SUCCESS;
4812 }
4813out:
4814 LogFlowFunc(("returns %Rrc\n", rc));
4815 return rc;
4816}
4817
4818
4819/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
4820static int iscsiSetLCHSGeometry(void *pBackendData,
4821 PCPDMMEDIAGEOMETRY pLCHSGeometry)
4822{
4823 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
4824 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4825 int rc;
4826
4827 Assert(pImage);
4828
4829 if (pImage)
4830 {
4831 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4832 {
4833 rc = VERR_VD_IMAGE_READ_ONLY;
4834 goto out;
4835 }
4836 rc = VERR_VD_GEOMETRY_NOT_SET;
4837 }
4838 else
4839 rc = VERR_VD_NOT_OPENED;
4840
4841out:
4842 LogFlowFunc(("returns %Rrc\n", rc));
4843 return rc;
4844}
4845
4846
4847/** @copydoc VBOXHDDBACKEND::pfnGetComment */
4848static int iscsiGetComment(void *pBackendData, char *pszComment,
4849 size_t cbComment)
4850{
4851 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
4852 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4853 int rc;
4854
4855 Assert(pImage);
4856
4857 if (pImage)
4858 rc = VERR_NOT_SUPPORTED;
4859 else
4860 rc = VERR_VD_NOT_OPENED;
4861
4862 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
4863 return rc;
4864}
4865
4866
4867/** @copydoc VBOXHDDBACKEND::pfnSetComment */
4868static int iscsiSetComment(void *pBackendData, const char *pszComment)
4869{
4870 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
4871 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4872 int rc;
4873
4874 Assert(pImage);
4875
4876 if (pImage)
4877 {
4878 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4879 rc = VERR_NOT_SUPPORTED;
4880 else
4881 rc = VERR_VD_IMAGE_READ_ONLY;
4882 }
4883 else
4884 rc = VERR_VD_NOT_OPENED;
4885
4886 LogFlowFunc(("returns %Rrc\n", rc));
4887 return rc;
4888}
4889
4890
4891/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
4892static int iscsiGetUuid(void *pBackendData, PRTUUID pUuid)
4893{
4894 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
4895 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4896 int rc;
4897
4898 Assert(pImage);
4899
4900 if (pImage)
4901 rc = VERR_NOT_SUPPORTED;
4902 else
4903 rc = VERR_VD_NOT_OPENED;
4904
4905 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
4906 return rc;
4907}
4908
4909
4910/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
4911static int iscsiSetUuid(void *pBackendData, PCRTUUID pUuid)
4912{
4913 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
4914 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4915 int rc;
4916
4917 LogFlowFunc(("%RTuuid\n", pUuid));
4918 Assert(pImage);
4919
4920 if (pImage)
4921 {
4922 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4923 rc = VERR_NOT_SUPPORTED;
4924 else
4925 rc = VERR_VD_IMAGE_READ_ONLY;
4926 }
4927 else
4928 rc = VERR_VD_NOT_OPENED;
4929
4930 LogFlowFunc(("returns %Rrc\n", rc));
4931 return rc;
4932}
4933
4934
4935/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
4936static int iscsiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
4937{
4938 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
4939 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4940 int rc;
4941
4942 Assert(pImage);
4943
4944 if (pImage)
4945 rc = VERR_NOT_SUPPORTED;
4946 else
4947 rc = VERR_VD_NOT_OPENED;
4948
4949 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
4950 return rc;
4951}
4952
4953
4954/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
4955static int iscsiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
4956{
4957 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
4958 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4959 int rc;
4960
4961 LogFlowFunc(("%RTuuid\n", pUuid));
4962 Assert(pImage);
4963
4964 if (pImage)
4965 {
4966 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4967 rc = VERR_NOT_SUPPORTED;
4968 else
4969 rc = VERR_VD_IMAGE_READ_ONLY;
4970 }
4971 else
4972 rc = VERR_VD_NOT_OPENED;
4973
4974 LogFlowFunc(("returns %Rrc\n", rc));
4975 return rc;
4976}
4977
4978
4979/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
4980static int iscsiGetParentUuid(void *pBackendData, PRTUUID pUuid)
4981{
4982 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
4983 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
4984 int rc;
4985
4986 Assert(pImage);
4987
4988 if (pImage)
4989 rc = VERR_NOT_SUPPORTED;
4990 else
4991 rc = VERR_VD_NOT_OPENED;
4992
4993 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
4994 return rc;
4995}
4996
4997
4998/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
4999static int iscsiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
5000{
5001 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5002 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5003 int rc;
5004
5005 LogFlowFunc(("%RTuuid\n", pUuid));
5006 Assert(pImage);
5007
5008 if (pImage)
5009 {
5010 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5011 rc = VERR_NOT_SUPPORTED;
5012 else
5013 rc = VERR_VD_IMAGE_READ_ONLY;
5014 }
5015 else
5016 rc = VERR_VD_NOT_OPENED;
5017
5018 LogFlowFunc(("returns %Rrc\n", rc));
5019 return rc;
5020}
5021
5022
5023/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
5024static int iscsiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
5025{
5026 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5027 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5028 int rc;
5029
5030 Assert(pImage);
5031
5032 if (pImage)
5033 rc = VERR_NOT_SUPPORTED;
5034 else
5035 rc = VERR_VD_NOT_OPENED;
5036
5037 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5038 return rc;
5039}
5040
5041
5042/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
5043static int iscsiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
5044{
5045 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5046 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5047 int rc;
5048
5049 LogFlowFunc(("%RTuuid\n", pUuid));
5050 Assert(pImage);
5051
5052 if (pImage)
5053 {
5054 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5055 rc = VERR_NOT_SUPPORTED;
5056 else
5057 rc = VERR_VD_IMAGE_READ_ONLY;
5058 }
5059 else
5060 rc = VERR_VD_NOT_OPENED;
5061
5062 LogFlowFunc(("returns %Rrc\n", rc));
5063 return rc;
5064}
5065
5066
5067/** @copydoc VBOXHDDBACKEND::pfnDump */
5068static void iscsiDump(void *pBackendData)
5069{
5070 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5071
5072 Assert(pImage);
5073 if (pImage)
5074 {
5075 /** @todo put something useful here */
5076 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: cVolume=%u\n", pImage->cVolume);
5077 }
5078}
5079
5080
5081/** @copydoc VBOXHDDBACKEND::pfnGetTimeStamp */
5082static int iscsiGetTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
5083{
5084 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
5085 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5086 int rc = VERR_NOT_SUPPORTED;
5087
5088 Assert(pImage);
5089 NOREF(pImage);
5090
5091 LogFlowFunc(("returns %Rrc\n", rc));
5092 return rc;
5093}
5094
5095
5096/** @copydoc VBOXHDDBACKEND::pfnGetParentTimeStamp */
5097static int iscsiGetParentTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
5098{
5099 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
5100 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5101 int rc = VERR_NOT_SUPPORTED;
5102
5103 Assert(pImage);
5104 NOREF(pImage);
5105
5106 LogFlowFunc(("returns %Rrc\n", rc));
5107 return rc;
5108}
5109
5110
5111/** @copydoc VBOXHDDBACKEND::pfnSetParentTimeStamp */
5112static int iscsiSetParentTimeStamp(void *pBackendData, PCRTTIMESPEC pTimeStamp)
5113{
5114 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
5115 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5116 int rc = VERR_NOT_SUPPORTED;
5117
5118 Assert(pImage);
5119 NOREF(pImage);
5120
5121 LogFlowFunc(("returns %Rrc\n", rc));
5122 return rc;
5123}
5124
5125
5126/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
5127static int iscsiGetParentFilename(void *pBackendData, char **ppszParentFilename)
5128{
5129 LogFlowFunc(("pBackendData=%#p ppszParentFilename=%#p\n", pBackendData, ppszParentFilename));
5130 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5131 int rc = VERR_NOT_SUPPORTED;
5132
5133 Assert(pImage);
5134 NOREF(pImage);
5135
5136 LogFlowFunc(("returns %Rrc\n", rc));
5137 return rc;
5138}
5139
5140
5141/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
5142static int iscsiSetParentFilename(void *pBackendData, const char *pszParentFilename)
5143{
5144 LogFlowFunc(("pBackendData=%#p pszParentFilename=%s\n", pBackendData, pszParentFilename));
5145 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
5146 int rc = VERR_NOT_SUPPORTED;
5147
5148 Assert(pImage);
5149 NOREF(pImage);
5150
5151 LogFlowFunc(("returns %Rrc\n", rc));
5152 return rc;
5153}
5154
5155/** @copydoc VBOXHDDBACKEND::pfnComposeLocation */
5156static int iscsiComposeLocation(PVDINTERFACE pConfig, char **pszLocation)
5157{
5158 char *pszTarget = NULL;
5159 char *pszLUN = NULL;
5160 char *pszAddress = NULL;
5161 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
5162 if (RT_SUCCESS(rc))
5163 {
5164 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
5165 if (RT_SUCCESS(rc))
5166 {
5167 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
5168 if (RT_SUCCESS(rc))
5169 {
5170 if (RTStrAPrintf(pszLocation, "iscsi://%s/%s/%s",
5171 pszAddress, pszTarget, pszLUN) < 0)
5172 rc = VERR_NO_MEMORY;
5173 }
5174 }
5175 }
5176 RTMemFree(pszTarget);
5177 RTMemFree(pszLUN);
5178 RTMemFree(pszAddress);
5179 return rc;
5180}
5181
5182/** @copydoc VBOXHDDBACKEND::pfnComposeName */
5183static int iscsiComposeName(PVDINTERFACE pConfig, char **pszName)
5184{
5185 char *pszTarget = NULL;
5186 char *pszLUN = NULL;
5187 char *pszAddress = NULL;
5188 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
5189 if (RT_SUCCESS(rc))
5190 {
5191 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
5192 if (RT_SUCCESS(rc))
5193 {
5194 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
5195 if (RT_SUCCESS(rc))
5196 {
5197 /** @todo think about a nicer looking location scheme for iSCSI */
5198 if (RTStrAPrintf(pszName, "%s/%s/%s",
5199 pszAddress, pszTarget, pszLUN) < 0)
5200 rc = VERR_NO_MEMORY;
5201 }
5202 }
5203 }
5204 RTMemFree(pszTarget);
5205 RTMemFree(pszLUN);
5206 RTMemFree(pszAddress);
5207
5208 return rc;
5209}
5210
5211static bool iscsiIsAsyncIOSupported(void *pvBackendData)
5212{
5213 PISCSIIMAGE pImage = (PISCSIIMAGE)pvBackendData;
5214 return pImage->fCmdQueuingSupported;
5215}
5216
5217static int iscsiAsyncRead(void *pvBackendData, uint64_t uOffset, size_t cbToRead,
5218 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
5219{
5220 PISCSIIMAGE pImage = (PISCSIIMAGE)pvBackendData;
5221 int rc = VINF_SUCCESS;
5222
5223 LogFlowFunc(("pBackendData=%p uOffset=%#llx pIoCtx=%#p cbToRead=%u pcbActuallyRead=%p\n",
5224 pvBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
5225
5226 if (uOffset + cbToRead > pImage->cbSize)
5227 return VERR_INVALID_PARAMETER;
5228
5229 /*
5230 * Clip read size to a value which is supported by the target.
5231 */
5232 cbToRead = RT_MIN(cbToRead, pImage->cbRecvDataLength);
5233
5234 unsigned cT2ISegs = 0;
5235 size_t cbSegs = 0;
5236
5237 /* Get the number of segments. */
5238 cbSegs = pImage->pInterfaceIoCallbacks->pfnIoCtxSegArrayCreate(pImage->pInterfaceIo->pvUser, pIoCtx,
5239 NULL, &cT2ISegs, cbToRead);
5240 Assert(cbSegs == cbToRead);
5241
5242 PSCSIREQASYNC pReqAsync = (PSCSIREQASYNC)RTMemAllocZ(RT_OFFSETOF(SCSIREQASYNC, aSegs[cT2ISegs]));
5243 if (RT_LIKELY(pReqAsync))
5244 {
5245 PSCSIREQ pReq = (PSCSIREQ)RTMemAllocZ(sizeof(SCSIREQ));
5246 if (pReq)
5247 {
5248 uint64_t lba;
5249 uint16_t tls;
5250 uint8_t *pbCDB = &pReqAsync->abCDB[0];
5251
5252 lba = uOffset / pImage->cbSector;
5253 tls = (uint16_t)(cbToRead / pImage->cbSector);
5254
5255 cbSegs = pImage->pInterfaceIoCallbacks->pfnIoCtxSegArrayCreate(pImage->pInterfaceIo->pvUser, pIoCtx,
5256 &pReqAsync->aSegs[0],
5257 &cT2ISegs, cbToRead);
5258 Assert(cbSegs == cbToRead);
5259 pReqAsync->cT2ISegs = cT2ISegs;
5260 pReqAsync->pIoCtx = pIoCtx;
5261 pReqAsync->pScsiReq = pReq;
5262 pReqAsync->cSenseRetries = 10;
5263 pReqAsync->rcSense = VERR_READ_ERROR;
5264
5265 pbCDB[0] = SCSI_READ_10;
5266 pbCDB[1] = 0; /* reserved */
5267 pbCDB[2] = (lba >> 24) & 0xff;
5268 pbCDB[3] = (lba >> 16) & 0xff;
5269 pbCDB[4] = (lba >> 8) & 0xff;
5270 pbCDB[5] = lba & 0xff;
5271 pbCDB[6] = 0; /* reserved */
5272 pbCDB[7] = (tls >> 8) & 0xff;
5273 pbCDB[8] = tls & 0xff;
5274 pbCDB[9] = 0; /* control */
5275
5276 pReq->enmXfer = SCSIXFER_FROM_TARGET;
5277 pReq->cbCmd = sizeof(pReqAsync->abCDB);
5278 pReq->pvCmd = pReqAsync->abCDB;
5279 pReq->cbI2TData = 0;
5280 pReq->paI2TSegs = NULL;
5281 pReq->cI2TSegs = 0;
5282 pReq->cbT2IData = cbToRead;
5283 pReq->paT2ISegs = &pReqAsync->aSegs[pReqAsync->cI2TSegs];
5284 pReq->cT2ISegs = pReqAsync->cT2ISegs;
5285 pReq->cbSense = sizeof(pReqAsync->abSense);
5286 pReq->pvSense = pReqAsync->abSense;
5287
5288 rc = iscsiCommandAsync(pImage, pReq, iscsiCommandAsyncComplete, pReqAsync);
5289 if (RT_FAILURE(rc))
5290 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
5291 else
5292 {
5293 *pcbActuallyRead = cbToRead;
5294 return VERR_VD_IOCTX_HALT; /* Halt the I/O context until further notification from the I/O thread. */
5295 }
5296
5297 RTMemFree(pReq);
5298 }
5299 else
5300 rc = VERR_NO_MEMORY;
5301
5302 RTMemFree(pReqAsync);
5303 }
5304 else
5305 rc = VERR_NO_MEMORY;
5306
5307 LogFlowFunc(("returns rc=%Rrc\n", rc));
5308 return rc;
5309}
5310
5311static int iscsiAsyncWrite(void *pvBackendData, uint64_t uOffset, size_t cbToWrite,
5312 PVDIOCTX pIoCtx,
5313 size_t *pcbWriteProcess, size_t *pcbPreRead,
5314 size_t *pcbPostRead, unsigned fWrite)
5315{
5316 PISCSIIMAGE pImage = (PISCSIIMAGE)pvBackendData;
5317 int rc = VINF_SUCCESS;
5318
5319 LogFlowFunc(("pBackendData=%p uOffset=%llu pIoCtx=%#p cbToWrite=%u pcbWriteProcess=%p pcbPreRead=%p pcbPostRead=%p fWrite=%u\n",
5320 pvBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead, fWrite));
5321
5322 AssertPtr(pImage);
5323 Assert(uOffset % 512 == 0);
5324 Assert(cbToWrite % 512 == 0);
5325
5326 if (uOffset + cbToWrite > pImage->cbSize)
5327 return VERR_INVALID_PARAMETER;
5328
5329 /*
5330 * Clip read size to a value which is supported by the target.
5331 */
5332 cbToWrite = RT_MIN(cbToWrite, pImage->cbSendDataLength);
5333
5334 unsigned cI2TSegs = 0;
5335 size_t cbSegs = 0;
5336
5337 /* Get the number of segments. */
5338 cbSegs = pImage->pInterfaceIoCallbacks->pfnIoCtxSegArrayCreate(pImage->pInterfaceIo->pvUser, pIoCtx,
5339 NULL, &cI2TSegs, cbToWrite);
5340 Assert(cbSegs == cbToWrite);
5341
5342 PSCSIREQASYNC pReqAsync = (PSCSIREQASYNC)RTMemAllocZ(RT_OFFSETOF(SCSIREQASYNC, aSegs[cI2TSegs]));
5343 if (RT_LIKELY(pReqAsync))
5344 {
5345 PSCSIREQ pReq = (PSCSIREQ)RTMemAllocZ(sizeof(SCSIREQ));
5346 if (pReq)
5347 {
5348 uint64_t lba;
5349 uint16_t tls;
5350 uint8_t *pbCDB = &pReqAsync->abCDB[0];
5351
5352 lba = uOffset / pImage->cbSector;
5353 tls = (uint16_t)(cbToWrite / pImage->cbSector);
5354
5355 cbSegs = pImage->pInterfaceIoCallbacks->pfnIoCtxSegArrayCreate(pImage->pInterfaceIo->pvUser, pIoCtx,
5356 &pReqAsync->aSegs[0],
5357 &cI2TSegs, cbToWrite);
5358 Assert(cbSegs == cbToWrite);
5359 pReqAsync->cI2TSegs = cI2TSegs;
5360 pReqAsync->pIoCtx = pIoCtx;
5361 pReqAsync->pScsiReq = pReq;
5362 pReqAsync->cSenseRetries = 10;
5363 pReqAsync->rcSense = VERR_WRITE_ERROR;
5364
5365 pbCDB[0] = SCSI_WRITE_10;
5366 pbCDB[1] = 0; /* reserved */
5367 pbCDB[2] = (lba >> 24) & 0xff;
5368 pbCDB[3] = (lba >> 16) & 0xff;
5369 pbCDB[4] = (lba >> 8) & 0xff;
5370 pbCDB[5] = lba & 0xff;
5371 pbCDB[6] = 0; /* reserved */
5372 pbCDB[7] = (tls >> 8) & 0xff;
5373 pbCDB[8] = tls & 0xff;
5374 pbCDB[9] = 0; /* control */
5375
5376 pReq->enmXfer = SCSIXFER_TO_TARGET;
5377 pReq->cbCmd = sizeof(pReqAsync->abCDB);
5378 pReq->pvCmd = pReqAsync->abCDB;
5379 pReq->cbI2TData = cbToWrite;
5380 pReq->paI2TSegs = &pReqAsync->aSegs[0];
5381 pReq->cI2TSegs = pReqAsync->cI2TSegs;
5382 pReq->cbT2IData = 0;
5383 pReq->paT2ISegs = NULL;
5384 pReq->cT2ISegs = 0;
5385 pReq->cbSense = sizeof(pReqAsync->abSense);
5386 pReq->pvSense = pReqAsync->abSense;
5387
5388 rc = iscsiCommandAsync(pImage, pReq, iscsiCommandAsyncComplete, pReqAsync);
5389 if (RT_FAILURE(rc))
5390 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
5391 else
5392 {
5393 *pcbWriteProcess = cbToWrite;
5394 return VERR_VD_IOCTX_HALT; /* Halt the I/O context until further notification from the I/O thread. */
5395 }
5396
5397 RTMemFree(pReq);
5398 }
5399 else
5400 rc = VERR_NO_MEMORY;
5401
5402 RTMemFree(pReqAsync);
5403 }
5404 else
5405 rc = VERR_NO_MEMORY;
5406
5407 LogFlowFunc(("returns rc=%Rrc\n", rc));
5408 return rc;
5409}
5410
5411static int iscsiAsyncFlush(void *pvBackendData, PVDIOCTX pIoCtx)
5412{
5413 PISCSIIMAGE pImage = (PISCSIIMAGE)pvBackendData;
5414 int rc = VINF_SUCCESS;
5415
5416 LogFlowFunc(("pvBackendData=%p pIoCtx=%#p\n", pvBackendData, pIoCtx));
5417
5418 PSCSIREQASYNC pReqAsync = (PSCSIREQASYNC)RTMemAllocZ(sizeof(SCSIREQASYNC));
5419 if (RT_LIKELY(pReqAsync))
5420 {
5421 PSCSIREQ pReq = (PSCSIREQ)RTMemAllocZ(sizeof(SCSIREQ));
5422 if (pReq)
5423 {
5424 uint8_t *pbCDB = &pReqAsync->abCDB[0];
5425
5426 pReqAsync->pIoCtx = pIoCtx;
5427 pReqAsync->pScsiReq = pReq;
5428 pReqAsync->cSenseRetries = 0;
5429 pReqAsync->rcSense = VINF_SUCCESS;
5430
5431 pbCDB[0] = SCSI_SYNCHRONIZE_CACHE;
5432 pbCDB[1] = 0; /* reserved */
5433 pbCDB[2] = 0; /* reserved */
5434 pbCDB[3] = 0; /* reserved */
5435 pbCDB[4] = 0; /* reserved */
5436 pbCDB[5] = 0; /* reserved */
5437 pbCDB[6] = 0; /* reserved */
5438 pbCDB[7] = 0; /* reserved */
5439 pbCDB[8] = 0; /* reserved */
5440 pbCDB[9] = 0; /* control */
5441
5442 pReq->enmXfer = SCSIXFER_NONE;
5443 pReq->cbCmd = sizeof(pReqAsync->abCDB);
5444 pReq->pvCmd = pReqAsync->abCDB;
5445 pReq->cbI2TData = 0;
5446 pReq->paI2TSegs = NULL;
5447 pReq->cI2TSegs = 0;
5448 pReq->cbT2IData = 0;
5449 pReq->paT2ISegs = NULL;
5450 pReq->cT2ISegs = 0;
5451 pReq->cbSense = sizeof(pReqAsync->abSense);
5452 pReq->pvSense = pReqAsync->abSense;
5453
5454 rc = iscsiCommandAsync(pImage, pReq, iscsiCommandAsyncComplete, pReqAsync);
5455 if (RT_FAILURE(rc))
5456 AssertMsgFailed(("iscsiCommand(%s) -> %Rrc\n", pImage->pszTargetName, rc));
5457 else
5458 return VERR_VD_IOCTX_HALT; /* Halt the I/O context until further notification from the I/O thread. */
5459
5460 RTMemFree(pReq);
5461 }
5462 else
5463 rc = VERR_NO_MEMORY;
5464
5465 RTMemFree(pReqAsync);
5466 }
5467 else
5468 rc = VERR_NO_MEMORY;
5469
5470 LogFlowFunc(("returns rc=%Rrc\n", rc));
5471 return rc;
5472}
5473
5474
5475VBOXHDDBACKEND g_ISCSIBackend =
5476{
5477 /* pszBackendName */
5478 "iSCSI",
5479 /* cbSize */
5480 sizeof(VBOXHDDBACKEND),
5481 /* uBackendCaps */
5482 VD_CAP_CONFIG | VD_CAP_TCPNET | VD_CAP_ASYNC,
5483 /* papszFileExtensions */
5484 NULL,
5485 /* paConfigInfo */
5486 s_iscsiConfigInfo,
5487 /* hPlugin */
5488 NIL_RTLDRMOD,
5489 /* pfnCheckIfValid */
5490 iscsiCheckIfValid,
5491 /* pfnOpen */
5492 iscsiOpen,
5493 /* pfnCreate */
5494 iscsiCreate,
5495 /* pfnRename */
5496 iscsiRename,
5497 /* pfnClose */
5498 iscsiClose,
5499 /* pfnRead */
5500 iscsiRead,
5501 /* pfnWrite */
5502 iscsiWrite,
5503 /* pfnFlush */
5504 iscsiFlush,
5505 /* pfnGetVersion */
5506 iscsiGetVersion,
5507 /* pfnGetSize */
5508 iscsiGetSize,
5509 /* pfnGetFileSize */
5510 iscsiGetFileSize,
5511 /* pfnGetPCHSGeometry */
5512 iscsiGetPCHSGeometry,
5513 /* pfnSetPCHSGeometry */
5514 iscsiSetPCHSGeometry,
5515 /* pfnGetLCHSGeometry */
5516 iscsiGetLCHSGeometry,
5517 /* pfnSetLCHSGeometry */
5518 iscsiSetLCHSGeometry,
5519 /* pfnGetImageFlags */
5520 iscsiGetImageFlags,
5521 /* pfnGetOpenFlags */
5522 iscsiGetOpenFlags,
5523 /* pfnSetOpenFlags */
5524 iscsiSetOpenFlags,
5525 /* pfnGetComment */
5526 iscsiGetComment,
5527 /* pfnSetComment */
5528 iscsiSetComment,
5529 /* pfnGetUuid */
5530 iscsiGetUuid,
5531 /* pfnSetUuid */
5532 iscsiSetUuid,
5533 /* pfnGetModificationUuid */
5534 iscsiGetModificationUuid,
5535 /* pfnSetModificationUuid */
5536 iscsiSetModificationUuid,
5537 /* pfnGetParentUuid */
5538 iscsiGetParentUuid,
5539 /* pfnSetParentUuid */
5540 iscsiSetParentUuid,
5541 /* pfnGetParentModificationUuid */
5542 iscsiGetParentModificationUuid,
5543 /* pfnSetParentModificationUuid */
5544 iscsiSetParentModificationUuid,
5545 /* pfnDump */
5546 iscsiDump,
5547 /* pfnGetTimeStamp */
5548 iscsiGetTimeStamp,
5549 /* pfnGetParentTimeStamp */
5550 iscsiGetParentTimeStamp,
5551 /* pfnSetParentTimeStamp */
5552 iscsiSetParentTimeStamp,
5553 /* pfnGetParentFilename */
5554 iscsiGetParentFilename,
5555 /* pfnSetParentFilename */
5556 iscsiSetParentFilename,
5557 /* pfnIsAsyncIOSupported */
5558 iscsiIsAsyncIOSupported,
5559 /* pfnAsyncRead */
5560 iscsiAsyncRead,
5561 /* pfnAsyncWrite */
5562 iscsiAsyncWrite,
5563 /* pfnAsyncFlush */
5564 iscsiAsyncFlush,
5565 /* pfnComposeLocation */
5566 iscsiComposeLocation,
5567 /* pfnComposeName */
5568 iscsiComposeName,
5569 /* pfnCompact */
5570 NULL
5571};
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette