iPXE
iscsi.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017  * 02110-1301, USA.
00018  *
00019  * You can also choose to distribute this program under the terms of
00020  * the Unmodified Binary Distribution Licence (as given in the file
00021  * COPYING.UBDL), provided that you have satisfied its requirements.
00022  */
00023 
00024 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
00025 
00026 #include <stddef.h>
00027 #include <string.h>
00028 #include <stdlib.h>
00029 #include <stdio.h>
00030 #include <ctype.h>
00031 #include <errno.h>
00032 #include <assert.h>
00033 #include <byteswap.h>
00034 #include <ipxe/vsprintf.h>
00035 #include <ipxe/socket.h>
00036 #include <ipxe/iobuf.h>
00037 #include <ipxe/uri.h>
00038 #include <ipxe/xfer.h>
00039 #include <ipxe/open.h>
00040 #include <ipxe/scsi.h>
00041 #include <ipxe/process.h>
00042 #include <ipxe/uaccess.h>
00043 #include <ipxe/tcpip.h>
00044 #include <ipxe/settings.h>
00045 #include <ipxe/features.h>
00046 #include <ipxe/base16.h>
00047 #include <ipxe/base64.h>
00048 #include <ipxe/ibft.h>
00049 #include <ipxe/iscsi.h>
00050 
00051 /** @file
00052  *
00053  * iSCSI protocol
00054  *
00055  */
00056 
00057 FEATURE ( FEATURE_PROTOCOL, "iSCSI", DHCP_EB_FEATURE_ISCSI, 1 );
00058 
00059 /* Disambiguate the various error causes */
00060 #define EACCES_INCORRECT_TARGET_USERNAME \
00061         __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_USERNAME )
00062 #define EINFO_EACCES_INCORRECT_TARGET_USERNAME \
00063         __einfo_uniqify ( EINFO_EACCES, 0x01, "Incorrect target username" )
00064 #define EACCES_INCORRECT_TARGET_PASSWORD \
00065         __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_PASSWORD )
00066 #define EINFO_EACCES_INCORRECT_TARGET_PASSWORD \
00067         __einfo_uniqify ( EINFO_EACCES, 0x02, "Incorrect target password" )
00068 #define EINVAL_ROOT_PATH_TOO_SHORT \
00069         __einfo_error ( EINFO_EINVAL_ROOT_PATH_TOO_SHORT )
00070 #define EINFO_EINVAL_ROOT_PATH_TOO_SHORT \
00071         __einfo_uniqify ( EINFO_EINVAL, 0x01, "Root path too short" )
00072 #define EINVAL_BAD_CREDENTIAL_MIX \
00073         __einfo_error ( EINFO_EINVAL_BAD_CREDENTIAL_MIX )
00074 #define EINFO_EINVAL_BAD_CREDENTIAL_MIX \
00075         __einfo_uniqify ( EINFO_EINVAL, 0x02, "Bad credential mix" )
00076 #define EINVAL_NO_ROOT_PATH \
00077         __einfo_error ( EINFO_EINVAL_NO_ROOT_PATH )
00078 #define EINFO_EINVAL_NO_ROOT_PATH \
00079         __einfo_uniqify ( EINFO_EINVAL, 0x03, "No root path" )
00080 #define EINVAL_NO_TARGET_IQN \
00081         __einfo_error ( EINFO_EINVAL_NO_TARGET_IQN )
00082 #define EINFO_EINVAL_NO_TARGET_IQN \
00083         __einfo_uniqify ( EINFO_EINVAL, 0x04, "No target IQN" )
00084 #define EINVAL_NO_INITIATOR_IQN \
00085         __einfo_error ( EINFO_EINVAL_NO_INITIATOR_IQN )
00086 #define EINFO_EINVAL_NO_INITIATOR_IQN \
00087         __einfo_uniqify ( EINFO_EINVAL, 0x05, "No initiator IQN" )
00088 #define EIO_TARGET_UNAVAILABLE \
00089         __einfo_error ( EINFO_EIO_TARGET_UNAVAILABLE )
00090 #define EINFO_EIO_TARGET_UNAVAILABLE \
00091         __einfo_uniqify ( EINFO_EIO, 0x01, "Target not currently operational" )
00092 #define EIO_TARGET_NO_RESOURCES \
00093         __einfo_error ( EINFO_EIO_TARGET_NO_RESOURCES )
00094 #define EINFO_EIO_TARGET_NO_RESOURCES \
00095         __einfo_uniqify ( EINFO_EIO, 0x02, "Target out of resources" )
00096 #define ENOTSUP_INITIATOR_STATUS \
00097         __einfo_error ( EINFO_ENOTSUP_INITIATOR_STATUS )
00098 #define EINFO_ENOTSUP_INITIATOR_STATUS \
00099         __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported initiator status" )
00100 #define ENOTSUP_OPCODE \
00101         __einfo_error ( EINFO_ENOTSUP_OPCODE )
00102 #define EINFO_ENOTSUP_OPCODE \
00103         __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported opcode" )
00104 #define ENOTSUP_DISCOVERY \
00105         __einfo_error ( EINFO_ENOTSUP_DISCOVERY )
00106 #define EINFO_ENOTSUP_DISCOVERY \
00107         __einfo_uniqify ( EINFO_ENOTSUP, 0x03, "Discovery not supported" )
00108 #define ENOTSUP_TARGET_STATUS \
00109         __einfo_error ( EINFO_ENOTSUP_TARGET_STATUS )
00110 #define EINFO_ENOTSUP_TARGET_STATUS \
00111         __einfo_uniqify ( EINFO_ENOTSUP, 0x04, "Unsupported target status" )
00112 #define EPERM_INITIATOR_AUTHENTICATION \
00113         __einfo_error ( EINFO_EPERM_INITIATOR_AUTHENTICATION )
00114 #define EINFO_EPERM_INITIATOR_AUTHENTICATION \
00115         __einfo_uniqify ( EINFO_EPERM, 0x01, "Initiator authentication failed" )
00116 #define EPERM_INITIATOR_AUTHORISATION \
00117         __einfo_error ( EINFO_EPERM_INITIATOR_AUTHORISATION )
00118 #define EINFO_EPERM_INITIATOR_AUTHORISATION \
00119         __einfo_uniqify ( EINFO_EPERM, 0x02, "Initiator not authorised" )
00120 #define EPROTO_INVALID_CHAP_ALGORITHM \
00121         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_ALGORITHM )
00122 #define EINFO_EPROTO_INVALID_CHAP_ALGORITHM \
00123         __einfo_uniqify ( EINFO_EPROTO, 0x01, "Invalid CHAP algorithm" )
00124 #define EPROTO_INVALID_CHAP_IDENTIFIER \
00125         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_IDENTIFIER )
00126 #define EINFO_EPROTO_INVALID_CHAP_IDENTIFIER \
00127         __einfo_uniqify ( EINFO_EPROTO, 0x02, "Invalid CHAP identifier" )
00128 #define EPROTO_INVALID_LARGE_BINARY \
00129         __einfo_error ( EINFO_EPROTO_INVALID_LARGE_BINARY )
00130 #define EINFO_EPROTO_INVALID_LARGE_BINARY \
00131         __einfo_uniqify ( EINFO_EPROTO, 0x03, "Invalid large binary value" )
00132 #define EPROTO_INVALID_CHAP_RESPONSE \
00133         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_RESPONSE )
00134 #define EINFO_EPROTO_INVALID_CHAP_RESPONSE \
00135         __einfo_uniqify ( EINFO_EPROTO, 0x04, "Invalid CHAP response" )
00136 #define EPROTO_INVALID_KEY_VALUE_PAIR \
00137         __einfo_error ( EINFO_EPROTO_INVALID_KEY_VALUE_PAIR )
00138 #define EINFO_EPROTO_INVALID_KEY_VALUE_PAIR \
00139         __einfo_uniqify ( EINFO_EPROTO, 0x05, "Invalid key/value pair" )
00140 #define EPROTO_VALUE_REJECTED \
00141         __einfo_error ( EINFO_EPROTO_VALUE_REJECTED )
00142 #define EINFO_EPROTO_VALUE_REJECTED                                     \
00143         __einfo_uniqify ( EINFO_EPROTO, 0x06, "Parameter rejected" )
00144 
00145 static void iscsi_start_tx ( struct iscsi_session *iscsi );
00146 static void iscsi_start_login ( struct iscsi_session *iscsi );
00147 static void iscsi_start_data_out ( struct iscsi_session *iscsi,
00148                                    unsigned int datasn );
00149 
00150 /**
00151  * Finish receiving PDU data into buffer
00152  *
00153  * @v iscsi             iSCSI session
00154  */
00155 static void iscsi_rx_buffered_data_done ( struct iscsi_session *iscsi ) {
00156         free ( iscsi->rx_buffer );
00157         iscsi->rx_buffer = NULL;
00158 }
00159 
00160 /**
00161  * Receive PDU data into buffer
00162  *
00163  * @v iscsi             iSCSI session
00164  * @v data              Data to receive
00165  * @v len               Length of data
00166  * @ret rc              Return status code
00167  *
00168  * This can be used when the RX PDU type handler wishes to buffer up
00169  * all received data and process the PDU as a single unit.  The caller
00170  * is repsonsible for calling iscsi_rx_buffered_data_done() after
00171  * processing the data.
00172  */
00173 static int iscsi_rx_buffered_data ( struct iscsi_session *iscsi,
00174                                     const void *data, size_t len ) {
00175 
00176         /* Allocate buffer on first call */
00177         if ( ! iscsi->rx_buffer ) {
00178                 iscsi->rx_buffer = malloc ( iscsi->rx_len );
00179                 if ( ! iscsi->rx_buffer )
00180                         return -ENOMEM;
00181         }
00182 
00183         /* Copy data to buffer */
00184         assert ( ( iscsi->rx_offset + len ) <= iscsi->rx_len );
00185         memcpy ( ( iscsi->rx_buffer + iscsi->rx_offset ), data, len );
00186 
00187         return 0;
00188 }
00189 
00190 /**
00191  * Free iSCSI session
00192  *
00193  * @v refcnt            Reference counter
00194  */
00195 static void iscsi_free ( struct refcnt *refcnt ) {
00196         struct iscsi_session *iscsi =
00197                 container_of ( refcnt, struct iscsi_session, refcnt );
00198 
00199         free ( iscsi->initiator_iqn );
00200         free ( iscsi->target_address );
00201         free ( iscsi->target_iqn );
00202         free ( iscsi->initiator_username );
00203         free ( iscsi->initiator_password );
00204         free ( iscsi->target_username );
00205         free ( iscsi->target_password );
00206         chap_finish ( &iscsi->chap );
00207         iscsi_rx_buffered_data_done ( iscsi );
00208         free ( iscsi->command );
00209         free ( iscsi );
00210 }
00211 
00212 /**
00213  * Shut down iSCSI interface
00214  *
00215  * @v iscsi             iSCSI session
00216  * @v rc                Reason for close
00217  */
00218 static void iscsi_close ( struct iscsi_session *iscsi, int rc ) {
00219 
00220         /* A TCP graceful close is still an error from our point of view */
00221         if ( rc == 0 )
00222                 rc = -ECONNRESET;
00223 
00224         DBGC ( iscsi, "iSCSI %p closed: %s\n", iscsi, strerror ( rc ) );
00225 
00226         /* Stop transmission process */
00227         process_del ( &iscsi->process );
00228 
00229         /* Shut down interfaces */
00230         intfs_shutdown ( rc, &iscsi->socket, &iscsi->control, &iscsi->data,
00231                          NULL );
00232 }
00233 
00234 /**
00235  * Assign new iSCSI initiator task tag
00236  *
00237  * @v iscsi             iSCSI session
00238  */
00239 static void iscsi_new_itt ( struct iscsi_session *iscsi ) {
00240         static uint16_t itt_idx;
00241 
00242         iscsi->itt = ( ISCSI_TAG_MAGIC | (++itt_idx) );
00243 }
00244 
00245 /**
00246  * Open iSCSI transport-layer connection
00247  *
00248  * @v iscsi             iSCSI session
00249  * @ret rc              Return status code
00250  */
00251 static int iscsi_open_connection ( struct iscsi_session *iscsi ) {
00252         struct sockaddr_tcpip target;
00253         int rc;
00254 
00255         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
00256         assert ( iscsi->rx_state == ISCSI_RX_BHS );
00257         assert ( iscsi->rx_offset == 0 );
00258 
00259         /* Open socket */
00260         memset ( &target, 0, sizeof ( target ) );
00261         target.st_port = htons ( iscsi->target_port );
00262         if ( ( rc = xfer_open_named_socket ( &iscsi->socket, SOCK_STREAM,
00263                                              ( struct sockaddr * ) &target,
00264                                              iscsi->target_address,
00265                                              NULL ) ) != 0 ) {
00266                 DBGC ( iscsi, "iSCSI %p could not open socket: %s\n",
00267                        iscsi, strerror ( rc ) );
00268                 return rc;
00269         }
00270 
00271         /* Enter security negotiation phase */
00272         iscsi->status = ( ISCSI_STATUS_SECURITY_NEGOTIATION_PHASE |
00273                           ISCSI_STATUS_STRINGS_SECURITY );
00274         if ( iscsi->target_username )
00275                 iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_REQUIRED;
00276 
00277         /* Assign new ISID */
00278         iscsi->isid_iana_qual = ( random() & 0xffff );
00279 
00280         /* Assign fresh initiator task tag */
00281         iscsi_new_itt ( iscsi );
00282 
00283         /* Initiate login */
00284         iscsi_start_login ( iscsi );
00285 
00286         return 0;
00287 }
00288 
00289 /**
00290  * Close iSCSI transport-layer connection
00291  *
00292  * @v iscsi             iSCSI session
00293  * @v rc                Reason for close
00294  *
00295  * Closes the transport-layer connection and resets the session state
00296  * ready to attempt a fresh login.
00297  */
00298 static void iscsi_close_connection ( struct iscsi_session *iscsi, int rc ) {
00299 
00300         /* Close all data transfer interfaces */
00301         intf_restart ( &iscsi->socket, rc );
00302 
00303         /* Clear connection status */
00304         iscsi->status = 0;
00305 
00306         /* Reset TX and RX state machines */
00307         iscsi->tx_state = ISCSI_TX_IDLE;
00308         iscsi->rx_state = ISCSI_RX_BHS;
00309         iscsi->rx_offset = 0;
00310 
00311         /* Free any temporary dynamically allocated memory */
00312         chap_finish ( &iscsi->chap );
00313         iscsi_rx_buffered_data_done ( iscsi );
00314 }
00315 
00316 /**
00317  * Mark iSCSI SCSI operation as complete
00318  *
00319  * @v iscsi             iSCSI session
00320  * @v rc                Return status code
00321  * @v rsp               SCSI response, if any
00322  *
00323  * Note that iscsi_scsi_done() will not close the connection, and must
00324  * therefore be called only when the internal state machines are in an
00325  * appropriate state, otherwise bad things may happen on the next call
00326  * to iscsi_scsi_command().  The general rule is to call
00327  * iscsi_scsi_done() only at the end of receiving a PDU; at this point
00328  * the TX and RX engines should both be idle.
00329  */
00330 static void iscsi_scsi_done ( struct iscsi_session *iscsi, int rc,
00331                               struct scsi_rsp *rsp ) {
00332         uint32_t itt = iscsi->itt;
00333 
00334         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
00335 
00336         /* Clear command */
00337         free ( iscsi->command );
00338         iscsi->command = NULL;
00339 
00340         /* Send SCSI response, if any */
00341         if ( rsp )
00342                 scsi_response ( &iscsi->data, rsp );
00343 
00344         /* Close SCSI command, if this is still the same command.  (It
00345          * is possible that the command interface has already been
00346          * closed as a result of the SCSI response we sent.)
00347          */
00348         if ( iscsi->itt == itt )
00349                 intf_restart ( &iscsi->data, rc );
00350 }
00351 
00352 /****************************************************************************
00353  *
00354  * iSCSI SCSI command issuing
00355  *
00356  */
00357 
00358 /**
00359  * Build iSCSI SCSI command BHS
00360  *
00361  * @v iscsi             iSCSI session
00362  *
00363  * We don't currently support bidirectional commands (i.e. with both
00364  * Data-In and Data-Out segments); these would require providing code
00365  * to generate an AHS, and there doesn't seem to be any need for it at
00366  * the moment.
00367  */
00368 static void iscsi_start_command ( struct iscsi_session *iscsi ) {
00369         struct iscsi_bhs_scsi_command *command = &iscsi->tx_bhs.scsi_command;
00370 
00371         assert ( ! ( iscsi->command->data_in && iscsi->command->data_out ) );
00372 
00373         /* Construct BHS and initiate transmission */
00374         iscsi_start_tx ( iscsi );
00375         command->opcode = ISCSI_OPCODE_SCSI_COMMAND;
00376         command->flags = ( ISCSI_FLAG_FINAL |
00377                            ISCSI_COMMAND_ATTR_SIMPLE );
00378         if ( iscsi->command->data_in )
00379                 command->flags |= ISCSI_COMMAND_FLAG_READ;
00380         if ( iscsi->command->data_out )
00381                 command->flags |= ISCSI_COMMAND_FLAG_WRITE;
00382         /* lengths left as zero */
00383         memcpy ( &command->lun, &iscsi->command->lun,
00384                  sizeof ( command->lun ) );
00385         command->itt = htonl ( iscsi->itt );
00386         command->exp_len = htonl ( iscsi->command->data_in_len |
00387                                    iscsi->command->data_out_len );
00388         command->cmdsn = htonl ( iscsi->cmdsn );
00389         command->expstatsn = htonl ( iscsi->statsn + 1 );
00390         memcpy ( &command->cdb, &iscsi->command->cdb, sizeof ( command->cdb ));
00391         DBGC2 ( iscsi, "iSCSI %p start " SCSI_CDB_FORMAT " %s %#zx\n",
00392                 iscsi, SCSI_CDB_DATA ( command->cdb ),
00393                 ( iscsi->command->data_in ? "in" : "out" ),
00394                 ( iscsi->command->data_in ?
00395                   iscsi->command->data_in_len :
00396                   iscsi->command->data_out_len ) );
00397 }
00398 
00399 /**
00400  * Receive data segment of an iSCSI SCSI response PDU
00401  *
00402  * @v iscsi             iSCSI session
00403  * @v data              Received data
00404  * @v len               Length of received data
00405  * @v remaining         Data remaining after this data
00406  * @ret rc              Return status code
00407  */
00408 static int iscsi_rx_scsi_response ( struct iscsi_session *iscsi,
00409                                     const void *data, size_t len,
00410                                     size_t remaining ) {
00411         struct iscsi_bhs_scsi_response *response
00412                 = &iscsi->rx_bhs.scsi_response;
00413         struct scsi_rsp rsp;
00414         uint32_t residual_count;
00415         size_t data_len;
00416         int rc;
00417 
00418         /* Buffer up the PDU data */
00419         if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
00420                 DBGC ( iscsi, "iSCSI %p could not buffer SCSI response: %s\n",
00421                        iscsi, strerror ( rc ) );
00422                 return rc;
00423         }
00424         if ( remaining )
00425                 return 0;
00426 
00427         /* Parse SCSI response and discard buffer */
00428         memset ( &rsp, 0, sizeof ( rsp ) );
00429         rsp.status = response->status;
00430         residual_count = ntohl ( response->residual_count );
00431         if ( response->flags & ISCSI_DATA_FLAG_OVERFLOW ) {
00432                 rsp.overrun = residual_count;
00433         } else if ( response->flags & ISCSI_DATA_FLAG_UNDERFLOW ) {
00434                 rsp.overrun = -(residual_count);
00435         }
00436         data_len = ISCSI_DATA_LEN ( response->lengths );
00437         if ( data_len ) {
00438                 scsi_parse_sense ( ( iscsi->rx_buffer + 2 ), ( data_len - 2 ),
00439                                    &rsp.sense );
00440         }
00441         iscsi_rx_buffered_data_done ( iscsi );
00442 
00443         /* Check for errors */
00444         if ( response->response != ISCSI_RESPONSE_COMMAND_COMPLETE )
00445                 return -EIO;
00446 
00447         /* Mark as completed */
00448         iscsi_scsi_done ( iscsi, 0, &rsp );
00449         return 0;
00450 }
00451 
00452 /**
00453  * Receive data segment of an iSCSI data-in PDU
00454  *
00455  * @v iscsi             iSCSI session
00456  * @v data              Received data
00457  * @v len               Length of received data
00458  * @v remaining         Data remaining after this data
00459  * @ret rc              Return status code
00460  */
00461 static int iscsi_rx_data_in ( struct iscsi_session *iscsi,
00462                               const void *data, size_t len,
00463                               size_t remaining ) {
00464         struct iscsi_bhs_data_in *data_in = &iscsi->rx_bhs.data_in;
00465         unsigned long offset;
00466 
00467         /* Copy data to data-in buffer */
00468         offset = ntohl ( data_in->offset ) + iscsi->rx_offset;
00469         assert ( iscsi->command != NULL );
00470         assert ( iscsi->command->data_in );
00471         assert ( ( offset + len ) <= iscsi->command->data_in_len );
00472         copy_to_user ( iscsi->command->data_in, offset, data, len );
00473 
00474         /* Wait for whole SCSI response to arrive */
00475         if ( remaining )
00476                 return 0;
00477 
00478         /* Mark as completed if status is present */
00479         if ( data_in->flags & ISCSI_DATA_FLAG_STATUS ) {
00480                 assert ( ( offset + len ) == iscsi->command->data_in_len );
00481                 assert ( data_in->flags & ISCSI_FLAG_FINAL );
00482                 /* iSCSI cannot return an error status via a data-in */
00483                 iscsi_scsi_done ( iscsi, 0, NULL );
00484         }
00485 
00486         return 0;
00487 }
00488 
00489 /**
00490  * Receive data segment of an iSCSI R2T PDU
00491  *
00492  * @v iscsi             iSCSI session
00493  * @v data              Received data
00494  * @v len               Length of received data
00495  * @v remaining         Data remaining after this data
00496  * @ret rc              Return status code
00497  */
00498 static int iscsi_rx_r2t ( struct iscsi_session *iscsi,
00499                           const void *data __unused, size_t len __unused,
00500                           size_t remaining __unused ) {
00501         struct iscsi_bhs_r2t *r2t = &iscsi->rx_bhs.r2t;
00502 
00503         /* Record transfer parameters and trigger first data-out */
00504         iscsi->ttt = ntohl ( r2t->ttt );
00505         iscsi->transfer_offset = ntohl ( r2t->offset );
00506         iscsi->transfer_len = ntohl ( r2t->len );
00507         iscsi_start_data_out ( iscsi, 0 );
00508 
00509         return 0;
00510 }
00511 
00512 /**
00513  * Build iSCSI data-out BHS
00514  *
00515  * @v iscsi             iSCSI session
00516  * @v datasn            Data sequence number within the transfer
00517  *
00518  */
00519 static void iscsi_start_data_out ( struct iscsi_session *iscsi,
00520                                    unsigned int datasn ) {
00521         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
00522         unsigned long offset;
00523         unsigned long remaining;
00524         unsigned long len;
00525 
00526         /* We always send 512-byte Data-Out PDUs; this removes the
00527          * need to worry about the target's MaxRecvDataSegmentLength.
00528          */
00529         offset = datasn * 512;
00530         remaining = iscsi->transfer_len - offset;
00531         len = remaining;
00532         if ( len > 512 )
00533                 len = 512;
00534 
00535         /* Construct BHS and initiate transmission */
00536         iscsi_start_tx ( iscsi );
00537         data_out->opcode = ISCSI_OPCODE_DATA_OUT;
00538         if ( len == remaining )
00539                 data_out->flags = ( ISCSI_FLAG_FINAL );
00540         ISCSI_SET_LENGTHS ( data_out->lengths, 0, len );
00541         data_out->lun = iscsi->command->lun;
00542         data_out->itt = htonl ( iscsi->itt );
00543         data_out->ttt = htonl ( iscsi->ttt );
00544         data_out->expstatsn = htonl ( iscsi->statsn + 1 );
00545         data_out->datasn = htonl ( datasn );
00546         data_out->offset = htonl ( iscsi->transfer_offset + offset );
00547         DBGC ( iscsi, "iSCSI %p start data out DataSN %#x len %#lx\n",
00548                iscsi, datasn, len );
00549 }
00550 
00551 /**
00552  * Complete iSCSI data-out PDU transmission
00553  *
00554  * @v iscsi             iSCSI session
00555  *
00556  */
00557 static void iscsi_data_out_done ( struct iscsi_session *iscsi ) {
00558         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
00559 
00560         /* If we haven't reached the end of the sequence, start
00561          * sending the next data-out PDU.
00562          */
00563         if ( ! ( data_out->flags & ISCSI_FLAG_FINAL ) )
00564                 iscsi_start_data_out ( iscsi, ntohl ( data_out->datasn ) + 1 );
00565 }
00566 
00567 /**
00568  * Send iSCSI data-out data segment
00569  *
00570  * @v iscsi             iSCSI session
00571  * @ret rc              Return status code
00572  */
00573 static int iscsi_tx_data_out ( struct iscsi_session *iscsi ) {
00574         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
00575         struct io_buffer *iobuf;
00576         unsigned long offset;
00577         size_t len;
00578         size_t pad_len;
00579 
00580         offset = ntohl ( data_out->offset );
00581         len = ISCSI_DATA_LEN ( data_out->lengths );
00582         pad_len = ISCSI_DATA_PAD_LEN ( data_out->lengths );
00583 
00584         assert ( iscsi->command != NULL );
00585         assert ( iscsi->command->data_out );
00586         assert ( ( offset + len ) <= iscsi->command->data_out_len );
00587 
00588         iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
00589         if ( ! iobuf )
00590                 return -ENOMEM;
00591         
00592         copy_from_user ( iob_put ( iobuf, len ),
00593                          iscsi->command->data_out, offset, len );
00594         memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
00595 
00596         return xfer_deliver_iob ( &iscsi->socket, iobuf );
00597 }
00598 
00599 /**
00600  * Receive data segment of an iSCSI NOP-In
00601  *
00602  * @v iscsi             iSCSI session
00603  * @v data              Received data
00604  * @v len               Length of received data
00605  * @v remaining         Data remaining after this data
00606  * @ret rc              Return status code
00607  */
00608 static int iscsi_rx_nop_in ( struct iscsi_session *iscsi,
00609                              const void *data __unused, size_t len __unused,
00610                              size_t remaining __unused ) {
00611         struct iscsi_nop_in *nop_in = &iscsi->rx_bhs.nop_in;
00612 
00613         DBGC2 ( iscsi, "iSCSI %p received NOP-In\n", iscsi );
00614 
00615         /* We don't currently have the ability to respond to NOP-Ins
00616          * sent as ping requests, but we can happily accept NOP-Ins
00617          * sent merely to update CmdSN.
00618          */
00619         if ( nop_in->ttt == htonl ( ISCSI_TAG_RESERVED ) )
00620                 return 0;
00621 
00622         /* Ignore any other NOP-Ins.  The target may eventually
00623          * disconnect us for failing to respond, but this minimises
00624          * unnecessary connection closures.
00625          */
00626         DBGC ( iscsi, "iSCSI %p received unsupported NOP-In with TTT %08x\n",
00627                iscsi, ntohl ( nop_in->ttt ) );
00628         return 0;
00629 }
00630 
00631 /****************************************************************************
00632  *
00633  * iSCSI login
00634  *
00635  */
00636 
00637 /**
00638  * Build iSCSI login request strings
00639  *
00640  * @v iscsi             iSCSI session
00641  *
00642  * These are the initial set of strings sent in the first login
00643  * request PDU.  We want the following settings:
00644  *
00645  *     HeaderDigest=None
00646  *     DataDigest=None
00647  *     MaxConnections=1 (irrelevant; we make only one connection anyway) [4]
00648  *     InitialR2T=Yes [1]
00649  *     ImmediateData=No (irrelevant; we never send immediate data) [4]
00650  *     MaxRecvDataSegmentLength=8192 (default; we don't care) [3]
00651  *     MaxBurstLength=262144 (default; we don't care) [3]
00652  *     FirstBurstLength=65536 (irrelevant due to other settings) [5]
00653  *     DefaultTime2Wait=0 [2]
00654  *     DefaultTime2Retain=0 [2]
00655  *     MaxOutstandingR2T=1
00656  *     DataPDUInOrder=Yes
00657  *     DataSequenceInOrder=Yes
00658  *     ErrorRecoveryLevel=0
00659  *
00660  * [1] InitialR2T has an OR resolution function, so the target may
00661  * force us to use it.  We therefore simplify our logic by always
00662  * using it.
00663  *
00664  * [2] These ensure that we can safely start a new task once we have
00665  * reconnected after a failure, without having to manually tidy up
00666  * after the old one.
00667  *
00668  * [3] We are quite happy to use the RFC-defined default values for
00669  * these parameters, but some targets (notably OpenSolaris)
00670  * incorrectly assume a default value of zero, so we explicitly
00671  * specify the default values.
00672  *
00673  * [4] We are quite happy to use the RFC-defined default values for
00674  * these parameters, but some targets (notably a QNAP TS-639Pro) fail
00675  * unless they are supplied, so we explicitly specify the default
00676  * values.
00677  *
00678  * [5] FirstBurstLength is defined to be irrelevant since we already
00679  * force InitialR2T=Yes and ImmediateData=No, but some targets
00680  * (notably LIO as of kernel 4.11) fail unless it is specified, so we
00681  * explicitly specify the default value.
00682  */
00683 static int iscsi_build_login_request_strings ( struct iscsi_session *iscsi,
00684                                                void *data, size_t len ) {
00685         unsigned int used = 0;
00686         const char *auth_method;
00687 
00688         if ( iscsi->status & ISCSI_STATUS_STRINGS_SECURITY ) {
00689                 /* Default to allowing no authentication */
00690                 auth_method = "None";
00691                 /* If we have a credential to supply, permit CHAP */
00692                 if ( iscsi->initiator_username )
00693                         auth_method = "CHAP,None";
00694                 /* If we have a credential to check, force CHAP */
00695                 if ( iscsi->target_username )
00696                         auth_method = "CHAP";
00697                 used += ssnprintf ( data + used, len - used,
00698                                     "InitiatorName=%s%c"
00699                                     "TargetName=%s%c"
00700                                     "SessionType=Normal%c"
00701                                     "AuthMethod=%s%c",
00702                                     iscsi->initiator_iqn, 0,
00703                                     iscsi->target_iqn, 0, 0,
00704                                     auth_method, 0 );
00705         }
00706 
00707         if ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_ALGORITHM ) {
00708                 used += ssnprintf ( data + used, len - used, "CHAP_A=5%c", 0 );
00709         }
00710         
00711         if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_RESPONSE ) ) {
00712                 char buf[ base16_encoded_len ( iscsi->chap.response_len ) + 1 ];
00713                 assert ( iscsi->initiator_username != NULL );
00714                 base16_encode ( iscsi->chap.response, iscsi->chap.response_len,
00715                                 buf, sizeof ( buf ) );
00716                 used += ssnprintf ( data + used, len - used,
00717                                     "CHAP_N=%s%cCHAP_R=0x%s%c",
00718                                     iscsi->initiator_username, 0, buf, 0 );
00719         }
00720 
00721         if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_CHALLENGE ) ) {
00722                 size_t challenge_len = ( sizeof ( iscsi->chap_challenge ) - 1 );
00723                 char buf[ base16_encoded_len ( challenge_len ) + 1 ];
00724                 base16_encode ( ( iscsi->chap_challenge + 1 ), challenge_len,
00725                                 buf, sizeof ( buf ) );
00726                 used += ssnprintf ( data + used, len - used,
00727                                     "CHAP_I=%d%cCHAP_C=0x%s%c",
00728                                     iscsi->chap_challenge[0], 0, buf, 0 );
00729         }
00730 
00731         if ( iscsi->status & ISCSI_STATUS_STRINGS_OPERATIONAL ) {
00732                 used += ssnprintf ( data + used, len - used,
00733                                     "HeaderDigest=None%c"
00734                                     "DataDigest=None%c"
00735                                     "MaxConnections=1%c"
00736                                     "InitialR2T=Yes%c"
00737                                     "ImmediateData=No%c"
00738                                     "MaxRecvDataSegmentLength=8192%c"
00739                                     "MaxBurstLength=262144%c"
00740                                     "FirstBurstLength=65536%c"
00741                                     "DefaultTime2Wait=0%c"
00742                                     "DefaultTime2Retain=0%c"
00743                                     "MaxOutstandingR2T=1%c"
00744                                     "DataPDUInOrder=Yes%c"
00745                                     "DataSequenceInOrder=Yes%c"
00746                                     "ErrorRecoveryLevel=0%c",
00747                                     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
00748         }
00749 
00750         return used;
00751 }
00752 
00753 /**
00754  * Build iSCSI login request BHS
00755  *
00756  * @v iscsi             iSCSI session
00757  */
00758 static void iscsi_start_login ( struct iscsi_session *iscsi ) {
00759         struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
00760         int len;
00761 
00762         switch ( iscsi->status & ISCSI_LOGIN_CSG_MASK ) {
00763         case ISCSI_LOGIN_CSG_SECURITY_NEGOTIATION:
00764                 DBGC ( iscsi, "iSCSI %p entering security negotiation\n",
00765                        iscsi );
00766                 break;
00767         case ISCSI_LOGIN_CSG_OPERATIONAL_NEGOTIATION:
00768                 DBGC ( iscsi, "iSCSI %p entering operational negotiation\n",
00769                        iscsi );
00770                 break;
00771         default:
00772                 assert ( 0 );
00773         }
00774 
00775         /* Construct BHS and initiate transmission */
00776         iscsi_start_tx ( iscsi );
00777         request->opcode = ( ISCSI_OPCODE_LOGIN_REQUEST |
00778                             ISCSI_FLAG_IMMEDIATE );
00779         request->flags = ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) |
00780                            ISCSI_LOGIN_FLAG_TRANSITION );
00781         /* version_max and version_min left as zero */
00782         len = iscsi_build_login_request_strings ( iscsi, NULL, 0 );
00783         ISCSI_SET_LENGTHS ( request->lengths, 0, len );
00784         request->isid_iana_en = htonl ( ISCSI_ISID_IANA |
00785                                         IANA_EN_FEN_SYSTEMS );
00786         request->isid_iana_qual = htons ( iscsi->isid_iana_qual );
00787         /* tsih left as zero */
00788         request->itt = htonl ( iscsi->itt );
00789         /* cid left as zero */
00790         request->cmdsn = htonl ( iscsi->cmdsn );
00791         request->expstatsn = htonl ( iscsi->statsn + 1 );
00792 }
00793 
00794 /**
00795  * Complete iSCSI login request PDU transmission
00796  *
00797  * @v iscsi             iSCSI session
00798  *
00799  */
00800 static void iscsi_login_request_done ( struct iscsi_session *iscsi ) {
00801 
00802         /* Clear any "strings to send" flags */
00803         iscsi->status &= ~ISCSI_STATUS_STRINGS_MASK;
00804 
00805         /* Free any dynamically allocated storage used for login */
00806         chap_finish ( &iscsi->chap );
00807 }
00808 
00809 /**
00810  * Transmit data segment of an iSCSI login request PDU
00811  *
00812  * @v iscsi             iSCSI session
00813  * @ret rc              Return status code
00814  *
00815  * For login requests, the data segment consists of the login strings.
00816  */
00817 static int iscsi_tx_login_request ( struct iscsi_session *iscsi ) {
00818         struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
00819         struct io_buffer *iobuf;
00820         size_t len;
00821         size_t pad_len;
00822 
00823         len = ISCSI_DATA_LEN ( request->lengths );
00824         pad_len = ISCSI_DATA_PAD_LEN ( request->lengths );
00825         iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
00826         if ( ! iobuf )
00827                 return -ENOMEM;
00828         iob_put ( iobuf, len );
00829         iscsi_build_login_request_strings ( iscsi, iobuf->data, len );
00830         memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
00831 
00832         return xfer_deliver_iob ( &iscsi->socket, iobuf );
00833 }
00834 
00835 /**
00836  * Decode large binary value
00837  *
00838  * @v encoded           Encoded large binary value
00839  * @v raw               Raw data
00840  * @v len               Length of data buffer
00841  * @ret len             Length of raw data, or negative error
00842  */
00843 static int iscsi_large_binary_decode ( const char *encoded, uint8_t *raw,
00844                                        size_t len ) {
00845 
00846         /* Check for initial '0x' or '0b' and decode as appropriate */
00847         if ( *(encoded++) == '0' ) {
00848                 switch ( tolower ( *(encoded++) ) ) {
00849                 case 'x' :
00850                         return base16_decode ( encoded, raw, len );
00851                 case 'b' :
00852                         return base64_decode ( encoded, raw, len );
00853                 }
00854         }
00855 
00856         return -EPROTO_INVALID_LARGE_BINARY;
00857 }
00858 
00859 /**
00860  * Handle iSCSI TargetAddress text value
00861  *
00862  * @v iscsi             iSCSI session
00863  * @v value             TargetAddress value
00864  * @ret rc              Return status code
00865  */
00866 static int iscsi_handle_targetaddress_value ( struct iscsi_session *iscsi,
00867                                               const char *value ) {
00868         char *separator;
00869 
00870         DBGC ( iscsi, "iSCSI %p will redirect to %s\n", iscsi, value );
00871 
00872         /* Replace target address */
00873         free ( iscsi->target_address );
00874         iscsi->target_address = strdup ( value );
00875         if ( ! iscsi->target_address )
00876                 return -ENOMEM;
00877 
00878         /* Replace target port */
00879         iscsi->target_port = htons ( ISCSI_PORT );
00880         separator = strchr ( iscsi->target_address, ':' );
00881         if ( separator ) {
00882                 *separator = '\0';
00883                 iscsi->target_port = strtoul ( ( separator + 1 ), NULL, 0 );
00884         }
00885 
00886         return 0;
00887 }
00888 
00889 /**
00890  * Handle iSCSI AuthMethod text value
00891  *
00892  * @v iscsi             iSCSI session
00893  * @v value             AuthMethod value
00894  * @ret rc              Return status code
00895  */
00896 static int iscsi_handle_authmethod_value ( struct iscsi_session *iscsi,
00897                                            const char *value ) {
00898 
00899         /* If server requests CHAP, send the CHAP_A string */
00900         if ( strcmp ( value, "CHAP" ) == 0 ) {
00901                 DBGC ( iscsi, "iSCSI %p initiating CHAP authentication\n",
00902                        iscsi );
00903                 iscsi->status |= ( ISCSI_STATUS_STRINGS_CHAP_ALGORITHM |
00904                                    ISCSI_STATUS_AUTH_FORWARD_REQUIRED );
00905         }
00906 
00907         return 0;
00908 }
00909 
00910 /**
00911  * Handle iSCSI CHAP_A text value
00912  *
00913  * @v iscsi             iSCSI session
00914  * @v value             CHAP_A value
00915  * @ret rc              Return status code
00916  */
00917 static int iscsi_handle_chap_a_value ( struct iscsi_session *iscsi,
00918                                        const char *value ) {
00919 
00920         /* We only ever offer "5" (i.e. MD5) as an algorithm, so if
00921          * the server responds with anything else it is a protocol
00922          * violation.
00923          */
00924         if ( strcmp ( value, "5" ) != 0 ) {
00925                 DBGC ( iscsi, "iSCSI %p got invalid CHAP algorithm \"%s\"\n",
00926                        iscsi, value );
00927                 return -EPROTO_INVALID_CHAP_ALGORITHM;
00928         }
00929 
00930         return 0;
00931 }
00932 
00933 /**
00934  * Handle iSCSI CHAP_I text value
00935  *
00936  * @v iscsi             iSCSI session
00937  * @v value             CHAP_I value
00938  * @ret rc              Return status code
00939  */
00940 static int iscsi_handle_chap_i_value ( struct iscsi_session *iscsi,
00941                                        const char *value ) {
00942         unsigned int identifier;
00943         char *endp;
00944         int rc;
00945 
00946         /* The CHAP identifier is an integer value */
00947         identifier = strtoul ( value, &endp, 0 );
00948         if ( *endp != '\0' ) {
00949                 DBGC ( iscsi, "iSCSI %p saw invalid CHAP identifier \"%s\"\n",
00950                        iscsi, value );
00951                 return -EPROTO_INVALID_CHAP_IDENTIFIER;
00952         }
00953 
00954         /* Prepare for CHAP with MD5 */
00955         chap_finish ( &iscsi->chap );
00956         if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
00957                 DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
00958                        iscsi, strerror ( rc ) );
00959                 return rc;
00960         }
00961 
00962         /* Identifier and secret are the first two components of the
00963          * challenge.
00964          */
00965         chap_set_identifier ( &iscsi->chap, identifier );
00966         if ( iscsi->initiator_password ) {
00967                 chap_update ( &iscsi->chap, iscsi->initiator_password,
00968                               strlen ( iscsi->initiator_password ) );
00969         }
00970 
00971         return 0;
00972 }
00973 
00974 /**
00975  * Handle iSCSI CHAP_C text value
00976  *
00977  * @v iscsi             iSCSI session
00978  * @v value             CHAP_C value
00979  * @ret rc              Return status code
00980  */
00981 static int iscsi_handle_chap_c_value ( struct iscsi_session *iscsi,
00982                                        const char *value ) {
00983         uint8_t buf[ strlen ( value ) ]; /* Decoding never expands data */
00984         unsigned int i;
00985         int len;
00986         int rc;
00987 
00988         /* Process challenge */
00989         len = iscsi_large_binary_decode ( value, buf, sizeof ( buf ) );
00990         if ( len < 0 ) {
00991                 rc = len;
00992                 DBGC ( iscsi, "iSCSI %p invalid CHAP challenge \"%s\": %s\n",
00993                        iscsi, value, strerror ( rc ) );
00994                 return rc;
00995         }
00996         chap_update ( &iscsi->chap, buf, len );
00997 
00998         /* Build CHAP response */
00999         DBGC ( iscsi, "iSCSI %p sending CHAP response\n", iscsi );
01000         chap_respond ( &iscsi->chap );
01001         iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_RESPONSE;
01002 
01003         /* Send CHAP challenge, if applicable */
01004         if ( iscsi->target_username ) {
01005                 iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_CHALLENGE;
01006                 /* Generate CHAP challenge data */
01007                 for ( i = 0 ; i < sizeof ( iscsi->chap_challenge ) ; i++ ) {
01008                         iscsi->chap_challenge[i] = random();
01009                 }
01010         }
01011 
01012         return 0;
01013 }
01014 
01015 /**
01016  * Handle iSCSI CHAP_N text value
01017  *
01018  * @v iscsi             iSCSI session
01019  * @v value             CHAP_N value
01020  * @ret rc              Return status code
01021  */
01022 static int iscsi_handle_chap_n_value ( struct iscsi_session *iscsi,
01023                                        const char *value ) {
01024 
01025         /* The target username isn't actually involved at any point in
01026          * the authentication process; it merely serves to identify
01027          * which password the target is using to generate the CHAP
01028          * response.  We unnecessarily verify that the username is as
01029          * expected, in order to provide mildly helpful diagnostics if
01030          * the target is supplying the wrong username/password
01031          * combination.
01032          */
01033         if ( iscsi->target_username &&
01034              ( strcmp ( iscsi->target_username, value ) != 0 ) ) {
01035                 DBGC ( iscsi, "iSCSI %p target username \"%s\" incorrect "
01036                        "(wanted \"%s\")\n",
01037                        iscsi, value, iscsi->target_username );
01038                 return -EACCES_INCORRECT_TARGET_USERNAME;
01039         }
01040 
01041         return 0;
01042 }
01043 
01044 /**
01045  * Handle iSCSI CHAP_R text value
01046  *
01047  * @v iscsi             iSCSI session
01048  * @v value             CHAP_R value
01049  * @ret rc              Return status code
01050  */
01051 static int iscsi_handle_chap_r_value ( struct iscsi_session *iscsi,
01052                                        const char *value ) {
01053         uint8_t buf[ strlen ( value ) ]; /* Decoding never expands data */
01054         int len;
01055         int rc;
01056 
01057         /* Generate CHAP response for verification */
01058         chap_finish ( &iscsi->chap );
01059         if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
01060                 DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
01061                        iscsi, strerror ( rc ) );
01062                 return rc;
01063         }
01064         chap_set_identifier ( &iscsi->chap, iscsi->chap_challenge[0] );
01065         if ( iscsi->target_password ) {
01066                 chap_update ( &iscsi->chap, iscsi->target_password,
01067                               strlen ( iscsi->target_password ) );
01068         }
01069         chap_update ( &iscsi->chap, &iscsi->chap_challenge[1],
01070                       ( sizeof ( iscsi->chap_challenge ) - 1 ) );
01071         chap_respond ( &iscsi->chap );
01072 
01073         /* Process response */
01074         len = iscsi_large_binary_decode ( value, buf, sizeof ( buf ) );
01075         if ( len < 0 ) {
01076                 rc = len;
01077                 DBGC ( iscsi, "iSCSI %p invalid CHAP response \"%s\": %s\n",
01078                        iscsi, value, strerror ( rc ) );
01079                 return rc;
01080         }
01081 
01082         /* Check CHAP response */
01083         if ( len != ( int ) iscsi->chap.response_len ) {
01084                 DBGC ( iscsi, "iSCSI %p invalid CHAP response length\n",
01085                        iscsi );
01086                 return -EPROTO_INVALID_CHAP_RESPONSE;
01087         }
01088         if ( memcmp ( buf, iscsi->chap.response, len ) != 0 ) {
01089                 DBGC ( iscsi, "iSCSI %p incorrect CHAP response \"%s\"\n",
01090                        iscsi, value );
01091                 return -EACCES_INCORRECT_TARGET_PASSWORD;
01092         }
01093 
01094         /* Mark session as authenticated */
01095         iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_OK;
01096 
01097         return 0;
01098 }
01099 
01100 /** An iSCSI text string that we want to handle */
01101 struct iscsi_string_type {
01102         /** String key
01103          *
01104          * This is the portion preceding the "=" sign,
01105          * e.g. "InitiatorName", "CHAP_A", etc.
01106          */
01107         const char *key;
01108         /** Handle iSCSI string value
01109          *
01110          * @v iscsi             iSCSI session
01111          * @v value             iSCSI string value
01112          * @ret rc              Return status code
01113          */
01114         int ( * handle ) ( struct iscsi_session *iscsi, const char *value );
01115 };
01116 
01117 /** iSCSI text strings that we want to handle */
01118 static struct iscsi_string_type iscsi_string_types[] = {
01119         { "TargetAddress", iscsi_handle_targetaddress_value },
01120         { "AuthMethod", iscsi_handle_authmethod_value },
01121         { "CHAP_A", iscsi_handle_chap_a_value },
01122         { "CHAP_I", iscsi_handle_chap_i_value },
01123         { "CHAP_C", iscsi_handle_chap_c_value },
01124         { "CHAP_N", iscsi_handle_chap_n_value },
01125         { "CHAP_R", iscsi_handle_chap_r_value },
01126         { NULL, NULL }
01127 };
01128 
01129 /**
01130  * Handle iSCSI string
01131  *
01132  * @v iscsi             iSCSI session
01133  * @v string            iSCSI string (in "key=value" format)
01134  * @ret rc              Return status code
01135  */
01136 static int iscsi_handle_string ( struct iscsi_session *iscsi,
01137                                  const char *string ) {
01138         struct iscsi_string_type *type;
01139         const char *separator;
01140         const char *value;
01141         size_t key_len;
01142         int rc;
01143 
01144         /* Find separator */
01145         separator = strchr ( string, '=' );
01146         if ( ! separator ) {
01147                 DBGC ( iscsi, "iSCSI %p malformed string %s\n",
01148                        iscsi, string );
01149                 return -EPROTO_INVALID_KEY_VALUE_PAIR;
01150         }
01151         key_len = ( separator - string );
01152         value = ( separator + 1 );
01153 
01154         /* Check for rejections.  Since we send only non-rejectable
01155          * values, any rejection is a fatal protocol error.
01156          */
01157         if ( strcmp ( value, "Reject" ) == 0 ) {
01158                 DBGC ( iscsi, "iSCSI %p rejection: %s\n", iscsi, string );
01159                 return -EPROTO_VALUE_REJECTED;
01160         }
01161 
01162         /* Handle key/value pair */
01163         for ( type = iscsi_string_types ; type->key ; type++ ) {
01164                 if ( strncmp ( string, type->key, key_len ) != 0 )
01165                         continue;
01166                 DBGC ( iscsi, "iSCSI %p handling %s\n", iscsi, string );
01167                 if ( ( rc = type->handle ( iscsi, value ) ) != 0 ) {
01168                         DBGC ( iscsi, "iSCSI %p could not handle %s: %s\n",
01169                                iscsi, string, strerror ( rc ) );
01170                         return rc;
01171                 }
01172                 return 0;
01173         }
01174         DBGC ( iscsi, "iSCSI %p ignoring %s\n", iscsi, string );
01175         return 0;
01176 }
01177 
01178 /**
01179  * Handle iSCSI strings
01180  *
01181  * @v iscsi             iSCSI session
01182  * @v string            iSCSI string buffer
01183  * @v len               Length of string buffer
01184  * @ret rc              Return status code
01185  */
01186 static int iscsi_handle_strings ( struct iscsi_session *iscsi,
01187                                   const char *strings, size_t len ) {
01188         size_t string_len;
01189         int rc;
01190 
01191         /* Handle each string in turn, taking care not to overrun the
01192          * data buffer in case of badly-terminated data.
01193          */
01194         while ( 1 ) {
01195                 string_len = ( strnlen ( strings, len ) + 1 );
01196                 if ( string_len > len )
01197                         break;
01198                 if ( ( rc = iscsi_handle_string ( iscsi, strings ) ) != 0 )
01199                         return rc;
01200                 strings += string_len;
01201                 len -= string_len;
01202         }
01203         return 0;
01204 }
01205 
01206 /**
01207  * Convert iSCSI response status to return status code
01208  *
01209  * @v status_class      iSCSI status class
01210  * @v status_detail     iSCSI status detail
01211  * @ret rc              Return status code
01212  */
01213 static int iscsi_status_to_rc ( unsigned int status_class,
01214                                 unsigned int status_detail ) {
01215         switch ( status_class ) {
01216         case ISCSI_STATUS_INITIATOR_ERROR :
01217                 switch ( status_detail ) {
01218                 case ISCSI_STATUS_INITIATOR_ERROR_AUTHENTICATION :
01219                         return -EPERM_INITIATOR_AUTHENTICATION;
01220                 case ISCSI_STATUS_INITIATOR_ERROR_AUTHORISATION :
01221                         return -EPERM_INITIATOR_AUTHORISATION;
01222                 case ISCSI_STATUS_INITIATOR_ERROR_NOT_FOUND :
01223                 case ISCSI_STATUS_INITIATOR_ERROR_REMOVED :
01224                         return -ENODEV;
01225                 default :
01226                         return -ENOTSUP_INITIATOR_STATUS;
01227                 }
01228         case ISCSI_STATUS_TARGET_ERROR :
01229                 switch ( status_detail ) {
01230                 case ISCSI_STATUS_TARGET_ERROR_UNAVAILABLE:
01231                         return -EIO_TARGET_UNAVAILABLE;
01232                 case ISCSI_STATUS_TARGET_ERROR_NO_RESOURCES:
01233                         return -EIO_TARGET_NO_RESOURCES;
01234                 default:
01235                         return -ENOTSUP_TARGET_STATUS;
01236                 }
01237         default :
01238                 return -EINVAL;
01239         }
01240 }
01241 
01242 /**
01243  * Receive data segment of an iSCSI login response PDU
01244  *
01245  * @v iscsi             iSCSI session
01246  * @v data              Received data
01247  * @v len               Length of received data
01248  * @v remaining         Data remaining after this data
01249  * @ret rc              Return status code
01250  */
01251 static int iscsi_rx_login_response ( struct iscsi_session *iscsi,
01252                                      const void *data, size_t len,
01253                                      size_t remaining ) {
01254         struct iscsi_bhs_login_response *response
01255                 = &iscsi->rx_bhs.login_response;
01256         int rc;
01257 
01258         /* Buffer up the PDU data */
01259         if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
01260                 DBGC ( iscsi, "iSCSI %p could not buffer login response: %s\n",
01261                        iscsi, strerror ( rc ) );
01262                 return rc;
01263         }
01264         if ( remaining )
01265                 return 0;
01266 
01267         /* Process string data and discard string buffer */
01268         if ( ( rc = iscsi_handle_strings ( iscsi, iscsi->rx_buffer,
01269                                            iscsi->rx_len ) ) != 0 )
01270                 return rc;
01271         iscsi_rx_buffered_data_done ( iscsi );
01272 
01273         /* Check for login redirection */
01274         if ( response->status_class == ISCSI_STATUS_REDIRECT ) {
01275                 DBGC ( iscsi, "iSCSI %p redirecting to new server\n", iscsi );
01276                 iscsi_close_connection ( iscsi, 0 );
01277                 if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 ) {
01278                         DBGC ( iscsi, "iSCSI %p could not redirect: %s\n ",
01279                                iscsi, strerror ( rc ) );
01280                         return rc;
01281                 }
01282                 return 0;
01283         }
01284 
01285         /* Check for fatal errors */
01286         if ( response->status_class != 0 ) {
01287                 DBGC ( iscsi, "iSCSI login failure: class %02x detail %02x\n",
01288                        response->status_class, response->status_detail );
01289                 rc = iscsi_status_to_rc ( response->status_class,
01290                                           response->status_detail );
01291                 return rc;
01292         }
01293 
01294         /* Handle login transitions */
01295         if ( response->flags & ISCSI_LOGIN_FLAG_TRANSITION ) {
01296                 iscsi->status &= ~( ISCSI_STATUS_PHASE_MASK |
01297                                     ISCSI_STATUS_STRINGS_MASK );
01298                 switch ( response->flags & ISCSI_LOGIN_NSG_MASK ) {
01299                 case ISCSI_LOGIN_NSG_OPERATIONAL_NEGOTIATION:
01300                         iscsi->status |=
01301                                 ( ISCSI_STATUS_OPERATIONAL_NEGOTIATION_PHASE |
01302                                   ISCSI_STATUS_STRINGS_OPERATIONAL );
01303                         break;
01304                 case ISCSI_LOGIN_NSG_FULL_FEATURE_PHASE:
01305                         iscsi->status |= ISCSI_STATUS_FULL_FEATURE_PHASE;
01306                         break;
01307                 default:
01308                         DBGC ( iscsi, "iSCSI %p got invalid response flags "
01309                                "%02x\n", iscsi, response->flags );
01310                         return -EIO;
01311                 }
01312         }
01313 
01314         /* Send next login request PDU if we haven't reached the full
01315          * feature phase yet.
01316          */
01317         if ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) !=
01318              ISCSI_STATUS_FULL_FEATURE_PHASE ) {
01319                 iscsi_start_login ( iscsi );
01320                 return 0;
01321         }
01322 
01323         /* Check that target authentication was successful (if required) */
01324         if ( ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_REQUIRED ) &&
01325              ! ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_OK ) ) {
01326                 DBGC ( iscsi, "iSCSI %p nefarious target tried to bypass "
01327                        "authentication\n", iscsi );
01328                 return -EPROTO;
01329         }
01330 
01331         /* Notify SCSI layer of window change */
01332         DBGC ( iscsi, "iSCSI %p entering full feature phase\n", iscsi );
01333         xfer_window_changed ( &iscsi->control );
01334 
01335         return 0;
01336 }
01337 
01338 /****************************************************************************
01339  *
01340  * iSCSI to socket interface
01341  *
01342  */
01343 
01344 /**
01345  * Pause TX engine
01346  *
01347  * @v iscsi             iSCSI session
01348  */
01349 static void iscsi_tx_pause ( struct iscsi_session *iscsi ) {
01350         process_del ( &iscsi->process );
01351 }
01352 
01353 /**
01354  * Resume TX engine
01355  *
01356  * @v iscsi             iSCSI session
01357  */
01358 static void iscsi_tx_resume ( struct iscsi_session *iscsi ) {
01359         process_add ( &iscsi->process );
01360 }
01361 
01362 /**
01363  * Start up a new TX PDU
01364  *
01365  * @v iscsi             iSCSI session
01366  *
01367  * This initiates the process of sending a new PDU.  Only one PDU may
01368  * be in transit at any one time.
01369  */
01370 static void iscsi_start_tx ( struct iscsi_session *iscsi ) {
01371 
01372         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
01373 
01374         /* Initialise TX BHS */
01375         memset ( &iscsi->tx_bhs, 0, sizeof ( iscsi->tx_bhs ) );
01376 
01377         /* Flag TX engine to start transmitting */
01378         iscsi->tx_state = ISCSI_TX_BHS;
01379 
01380         /* Start transmission process */
01381         iscsi_tx_resume ( iscsi );
01382 }
01383 
01384 /**
01385  * Transmit nothing
01386  *
01387  * @v iscsi             iSCSI session
01388  * @ret rc              Return status code
01389  */
01390 static int iscsi_tx_nothing ( struct iscsi_session *iscsi __unused ) {
01391         return 0;
01392 }
01393 
01394 /**
01395  * Transmit basic header segment of an iSCSI PDU
01396  *
01397  * @v iscsi             iSCSI session
01398  * @ret rc              Return status code
01399  */
01400 static int iscsi_tx_bhs ( struct iscsi_session *iscsi ) {
01401         return xfer_deliver_raw ( &iscsi->socket,  &iscsi->tx_bhs,
01402                                   sizeof ( iscsi->tx_bhs ) );
01403 }
01404 
01405 /**
01406  * Transmit data segment of an iSCSI PDU
01407  *
01408  * @v iscsi             iSCSI session
01409  * @ret rc              Return status code
01410  * 
01411  * Handle transmission of part of a PDU data segment.  iscsi::tx_bhs
01412  * will be valid when this is called.
01413  */
01414 static int iscsi_tx_data ( struct iscsi_session *iscsi ) {
01415         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
01416 
01417         switch ( common->opcode & ISCSI_OPCODE_MASK ) {
01418         case ISCSI_OPCODE_DATA_OUT:
01419                 return iscsi_tx_data_out ( iscsi );
01420         case ISCSI_OPCODE_LOGIN_REQUEST:
01421                 return iscsi_tx_login_request ( iscsi );
01422         default:
01423                 /* Nothing to send in other states */
01424                 return 0;
01425         }
01426 }
01427 
01428 /**
01429  * Complete iSCSI PDU transmission
01430  *
01431  * @v iscsi             iSCSI session
01432  *
01433  * Called when a PDU has been completely transmitted and the TX state
01434  * machine is about to enter the idle state.  iscsi::tx_bhs will be
01435  * valid for the just-completed PDU when this is called.
01436  */
01437 static void iscsi_tx_done ( struct iscsi_session *iscsi ) {
01438         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
01439 
01440         /* Stop transmission process */
01441         iscsi_tx_pause ( iscsi );
01442 
01443         switch ( common->opcode & ISCSI_OPCODE_MASK ) {
01444         case ISCSI_OPCODE_DATA_OUT:
01445                 iscsi_data_out_done ( iscsi );
01446                 break;
01447         case ISCSI_OPCODE_LOGIN_REQUEST:
01448                 iscsi_login_request_done ( iscsi );
01449                 break;
01450         default:
01451                 /* No action */
01452                 break;
01453         }
01454 }
01455 
01456 /**
01457  * Transmit iSCSI PDU
01458  *
01459  * @v iscsi             iSCSI session
01460  * @v buf               Temporary data buffer
01461  * @v len               Length of temporary data buffer
01462  * 
01463  * Constructs data to be sent for the current TX state
01464  */
01465 static void iscsi_tx_step ( struct iscsi_session *iscsi ) {
01466         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
01467         int ( * tx ) ( struct iscsi_session *iscsi );
01468         enum iscsi_tx_state next_state;
01469         size_t tx_len;
01470         int rc;
01471 
01472         /* Select fragment to transmit */
01473         while ( 1 ) {
01474                 switch ( iscsi->tx_state ) {
01475                 case ISCSI_TX_BHS:
01476                         tx = iscsi_tx_bhs;
01477                         tx_len = sizeof ( iscsi->tx_bhs );
01478                         next_state = ISCSI_TX_AHS;
01479                         break;
01480                 case ISCSI_TX_AHS:
01481                         tx = iscsi_tx_nothing;
01482                         tx_len = 0;
01483                         next_state = ISCSI_TX_DATA;
01484                         break;
01485                 case ISCSI_TX_DATA:
01486                         tx = iscsi_tx_data;
01487                         tx_len = ISCSI_DATA_LEN ( common->lengths );
01488                         next_state = ISCSI_TX_IDLE;
01489                         break;
01490                 case ISCSI_TX_IDLE:
01491                         /* Nothing to do; pause processing */
01492                         iscsi_tx_pause ( iscsi );
01493                         return;
01494                 default:
01495                         assert ( 0 );
01496                         return;
01497                 }
01498 
01499                 /* Check for window availability, if needed */
01500                 if ( tx_len && ( xfer_window ( &iscsi->socket ) == 0 ) ) {
01501                         /* Cannot transmit at this point; pause
01502                          * processing and wait for window to reopen
01503                          */
01504                         iscsi_tx_pause ( iscsi );
01505                         return;
01506                 }
01507 
01508                 /* Transmit data */
01509                 if ( ( rc = tx ( iscsi ) ) != 0 ) {
01510                         DBGC ( iscsi, "iSCSI %p could not transmit: %s\n",
01511                                iscsi, strerror ( rc ) );
01512                         /* Transmission errors are fatal */
01513                         iscsi_close ( iscsi, rc );
01514                         return;
01515                 }
01516 
01517                 /* Move to next state */
01518                 iscsi->tx_state = next_state;
01519 
01520                 /* If we have moved to the idle state, mark
01521                  * transmission as complete
01522                  */
01523                 if ( iscsi->tx_state == ISCSI_TX_IDLE )
01524                         iscsi_tx_done ( iscsi );
01525         }
01526 }
01527 
01528 /** iSCSI TX process descriptor */
01529 static struct process_descriptor iscsi_process_desc =
01530         PROC_DESC ( struct iscsi_session, process, iscsi_tx_step );
01531 
01532 /**
01533  * Receive basic header segment of an iSCSI PDU
01534  *
01535  * @v iscsi             iSCSI session
01536  * @v data              Received data
01537  * @v len               Length of received data
01538  * @v remaining         Data remaining after this data
01539  * @ret rc              Return status code
01540  *
01541  * This fills in iscsi::rx_bhs with the data from the BHS portion of
01542  * the received PDU.
01543  */
01544 static int iscsi_rx_bhs ( struct iscsi_session *iscsi, const void *data,
01545                           size_t len, size_t remaining __unused ) {
01546         memcpy ( &iscsi->rx_bhs.bytes[iscsi->rx_offset], data, len );
01547         if ( ( iscsi->rx_offset + len ) >= sizeof ( iscsi->rx_bhs ) ) {
01548                 DBGC2 ( iscsi, "iSCSI %p received PDU opcode %#x len %#x\n",
01549                         iscsi, iscsi->rx_bhs.common.opcode,
01550                         ISCSI_DATA_LEN ( iscsi->rx_bhs.common.lengths ) );
01551         }
01552         return 0;
01553 }
01554 
01555 /**
01556  * Discard portion of an iSCSI PDU.
01557  *
01558  * @v iscsi             iSCSI session
01559  * @v data              Received data
01560  * @v len               Length of received data
01561  * @v remaining         Data remaining after this data
01562  * @ret rc              Return status code
01563  *
01564  * This discards data from a portion of a received PDU.
01565  */
01566 static int iscsi_rx_discard ( struct iscsi_session *iscsi __unused,
01567                               const void *data __unused, size_t len __unused,
01568                               size_t remaining __unused ) {
01569         /* Do nothing */
01570         return 0;
01571 }
01572 
01573 /**
01574  * Receive data segment of an iSCSI PDU
01575  *
01576  * @v iscsi             iSCSI session
01577  * @v data              Received data
01578  * @v len               Length of received data
01579  * @v remaining         Data remaining after this data
01580  * @ret rc              Return status code
01581  *
01582  * Handle processing of part of a PDU data segment.  iscsi::rx_bhs
01583  * will be valid when this is called.
01584  */
01585 static int iscsi_rx_data ( struct iscsi_session *iscsi, const void *data,
01586                            size_t len, size_t remaining ) {
01587         struct iscsi_bhs_common_response *response
01588                 = &iscsi->rx_bhs.common_response;
01589 
01590         /* Update cmdsn and statsn */
01591         iscsi->cmdsn = ntohl ( response->expcmdsn );
01592         iscsi->statsn = ntohl ( response->statsn );
01593 
01594         switch ( response->opcode & ISCSI_OPCODE_MASK ) {
01595         case ISCSI_OPCODE_LOGIN_RESPONSE:
01596                 return iscsi_rx_login_response ( iscsi, data, len, remaining );
01597         case ISCSI_OPCODE_SCSI_RESPONSE:
01598                 return iscsi_rx_scsi_response ( iscsi, data, len, remaining );
01599         case ISCSI_OPCODE_DATA_IN:
01600                 return iscsi_rx_data_in ( iscsi, data, len, remaining );
01601         case ISCSI_OPCODE_R2T:
01602                 return iscsi_rx_r2t ( iscsi, data, len, remaining );
01603         case ISCSI_OPCODE_NOP_IN:
01604                 return iscsi_rx_nop_in ( iscsi, data, len, remaining );
01605         default:
01606                 if ( remaining )
01607                         return 0;
01608                 DBGC ( iscsi, "iSCSI %p unknown opcode %02x\n", iscsi,
01609                        response->opcode );
01610                 return -ENOTSUP_OPCODE;
01611         }
01612 }
01613 
01614 /**
01615  * Receive new data
01616  *
01617  * @v iscsi             iSCSI session
01618  * @v iobuf             I/O buffer
01619  * @v meta              Data transfer metadata
01620  * @ret rc              Return status code
01621  *
01622  * This handles received PDUs.  The receive strategy is to fill in
01623  * iscsi::rx_bhs with the contents of the BHS portion of the PDU,
01624  * throw away any AHS portion, and then process each part of the data
01625  * portion as it arrives.  The data processing routine therefore
01626  * always has a full copy of the BHS available, even for portions of
01627  * the data in different packets to the BHS.
01628  */
01629 static int iscsi_socket_deliver ( struct iscsi_session *iscsi,
01630                                   struct io_buffer *iobuf,
01631                                   struct xfer_metadata *meta __unused ) {
01632         struct iscsi_bhs_common *common = &iscsi->rx_bhs.common;
01633         int ( * rx ) ( struct iscsi_session *iscsi, const void *data,
01634                        size_t len, size_t remaining );
01635         enum iscsi_rx_state next_state;
01636         size_t frag_len;
01637         size_t remaining;
01638         int rc;
01639 
01640         while ( 1 ) {
01641                 switch ( iscsi->rx_state ) {
01642                 case ISCSI_RX_BHS:
01643                         rx = iscsi_rx_bhs;
01644                         iscsi->rx_len = sizeof ( iscsi->rx_bhs );
01645                         next_state = ISCSI_RX_AHS;                      
01646                         break;
01647                 case ISCSI_RX_AHS:
01648                         rx = iscsi_rx_discard;
01649                         iscsi->rx_len = 4 * ISCSI_AHS_LEN ( common->lengths );
01650                         next_state = ISCSI_RX_DATA;
01651                         break;
01652                 case ISCSI_RX_DATA:
01653                         rx = iscsi_rx_data;
01654                         iscsi->rx_len = ISCSI_DATA_LEN ( common->lengths );
01655                         next_state = ISCSI_RX_DATA_PADDING;
01656                         break;
01657                 case ISCSI_RX_DATA_PADDING:
01658                         rx = iscsi_rx_discard;
01659                         iscsi->rx_len = ISCSI_DATA_PAD_LEN ( common->lengths );
01660                         next_state = ISCSI_RX_BHS;
01661                         break;
01662                 default:
01663                         assert ( 0 );
01664                         rc = -EINVAL;
01665                         goto done;
01666                 }
01667 
01668                 frag_len = iscsi->rx_len - iscsi->rx_offset;
01669                 if ( frag_len > iob_len ( iobuf ) )
01670                         frag_len = iob_len ( iobuf );
01671                 remaining = iscsi->rx_len - iscsi->rx_offset - frag_len;
01672                 if ( ( rc = rx ( iscsi, iobuf->data, frag_len,
01673                                  remaining ) ) != 0 ) {
01674                         DBGC ( iscsi, "iSCSI %p could not process received "
01675                                "data: %s\n", iscsi, strerror ( rc ) );
01676                         goto done;
01677                 }
01678 
01679                 iscsi->rx_offset += frag_len;
01680                 iob_pull ( iobuf, frag_len );
01681 
01682                 /* If all the data for this state has not yet been
01683                  * received, stay in this state for now.
01684                  */
01685                 if ( iscsi->rx_offset != iscsi->rx_len ) {
01686                         rc = 0;
01687                         goto done;
01688                 }
01689 
01690                 iscsi->rx_state = next_state;
01691                 iscsi->rx_offset = 0;
01692         }
01693 
01694  done:
01695         /* Free I/O buffer */
01696         free_iob ( iobuf );
01697 
01698         /* Destroy session on error */
01699         if ( rc != 0 )
01700                 iscsi_close ( iscsi, rc );
01701 
01702         return rc;
01703 }
01704 
01705 /**
01706  * Handle redirection event
01707  *
01708  * @v iscsi             iSCSI session
01709  * @v type              Location type
01710  * @v args              Remaining arguments depend upon location type
01711  * @ret rc              Return status code
01712  */
01713 static int iscsi_vredirect ( struct iscsi_session *iscsi, int type,
01714                              va_list args ) {
01715         va_list tmp;
01716         struct sockaddr *peer;
01717         int rc;
01718 
01719         /* Intercept redirects to a LOCATION_SOCKET and record the IP
01720          * address for the iBFT.  This is a bit of a hack, but avoids
01721          * inventing an ioctl()-style call to retrieve the socket
01722          * address from a data-xfer interface.
01723          */
01724         if ( type == LOCATION_SOCKET ) {
01725                 va_copy ( tmp, args );
01726                 ( void ) va_arg ( tmp, int ); /* Discard "semantics" */
01727                 peer = va_arg ( tmp, struct sockaddr * );
01728                 memcpy ( &iscsi->target_sockaddr, peer,
01729                          sizeof ( iscsi->target_sockaddr ) );
01730                 va_end ( tmp );
01731         }
01732 
01733         /* Redirect to new location */
01734         if ( ( rc = xfer_vreopen ( &iscsi->socket, type, args ) ) != 0 )
01735                 goto err;
01736 
01737         return 0;
01738 
01739  err:
01740         iscsi_close ( iscsi, rc );
01741         return rc;
01742 }
01743 
01744 /** iSCSI socket interface operations */
01745 static struct interface_operation iscsi_socket_operations[] = {
01746         INTF_OP ( xfer_deliver, struct iscsi_session *, iscsi_socket_deliver ),
01747         INTF_OP ( xfer_window_changed, struct iscsi_session *,
01748                   iscsi_tx_resume ),
01749         INTF_OP ( xfer_vredirect, struct iscsi_session *, iscsi_vredirect ),
01750         INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
01751 };
01752 
01753 /** iSCSI socket interface descriptor */
01754 static struct interface_descriptor iscsi_socket_desc =
01755         INTF_DESC ( struct iscsi_session, socket, iscsi_socket_operations );
01756 
01757 /****************************************************************************
01758  *
01759  * iSCSI command issuing
01760  *
01761  */
01762 
01763 /**
01764  * Check iSCSI flow-control window
01765  *
01766  * @v iscsi             iSCSI session
01767  * @ret len             Length of window
01768  */
01769 static size_t iscsi_scsi_window ( struct iscsi_session *iscsi ) {
01770 
01771         if ( ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) ==
01772                ISCSI_STATUS_FULL_FEATURE_PHASE ) &&
01773              ( iscsi->command == NULL ) ) {
01774                 /* We cannot handle concurrent commands */
01775                 return 1;
01776         } else {
01777                 return 0;
01778         }
01779 }
01780 
01781 /**
01782  * Issue iSCSI SCSI command
01783  *
01784  * @v iscsi             iSCSI session
01785  * @v parent            Parent interface
01786  * @v command           SCSI command
01787  * @ret tag             Command tag, or negative error
01788  */
01789 static int iscsi_scsi_command ( struct iscsi_session *iscsi,
01790                                 struct interface *parent,
01791                                 struct scsi_cmd *command ) {
01792 
01793         /* This iSCSI implementation cannot handle multiple concurrent
01794          * commands or commands arriving before login is complete.
01795          */
01796         if ( iscsi_scsi_window ( iscsi ) == 0 ) {
01797                 DBGC ( iscsi, "iSCSI %p cannot handle concurrent commands\n",
01798                        iscsi );
01799                 return -EOPNOTSUPP;
01800         }
01801 
01802         /* Store command */
01803         iscsi->command = malloc ( sizeof ( *command ) );
01804         if ( ! iscsi->command )
01805                 return -ENOMEM;
01806         memcpy ( iscsi->command, command, sizeof ( *command ) );
01807 
01808         /* Assign new ITT */
01809         iscsi_new_itt ( iscsi );
01810 
01811         /* Start sending command */
01812         iscsi_start_command ( iscsi );
01813 
01814         /* Attach to parent interface and return */
01815         intf_plug_plug ( &iscsi->data, parent );
01816         return iscsi->itt;
01817 }
01818 
01819 /**
01820  * Get iSCSI ACPI descriptor
01821  *
01822  * @v iscsi             iSCSI session
01823  * @ret desc            ACPI descriptor
01824  */
01825 static struct acpi_descriptor * iscsi_describe ( struct iscsi_session *iscsi ) {
01826 
01827         return &iscsi->desc;
01828 }
01829 
01830 /** iSCSI SCSI command-issuing interface operations */
01831 static struct interface_operation iscsi_control_op[] = {
01832         INTF_OP ( scsi_command, struct iscsi_session *, iscsi_scsi_command ),
01833         INTF_OP ( xfer_window, struct iscsi_session *, iscsi_scsi_window ),
01834         INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
01835         INTF_OP ( acpi_describe, struct iscsi_session *, iscsi_describe ),
01836 };
01837 
01838 /** iSCSI SCSI command-issuing interface descriptor */
01839 static struct interface_descriptor iscsi_control_desc =
01840         INTF_DESC ( struct iscsi_session, control, iscsi_control_op );
01841 
01842 /**
01843  * Close iSCSI command
01844  *
01845  * @v iscsi             iSCSI session
01846  * @v rc                Reason for close
01847  */
01848 static void iscsi_command_close ( struct iscsi_session *iscsi, int rc ) {
01849 
01850         /* Restart interface */
01851         intf_restart ( &iscsi->data, rc );
01852 
01853         /* Treat unsolicited command closures mid-command as fatal,
01854          * because we have no code to handle partially-completed PDUs.
01855          */
01856         if ( iscsi->command != NULL )
01857                 iscsi_close ( iscsi, ( ( rc == 0 ) ? -ECANCELED : rc ) );
01858 }
01859 
01860 /** iSCSI SCSI command interface operations */
01861 static struct interface_operation iscsi_data_op[] = {
01862         INTF_OP ( intf_close, struct iscsi_session *, iscsi_command_close ),
01863 };
01864 
01865 /** iSCSI SCSI command interface descriptor */
01866 static struct interface_descriptor iscsi_data_desc =
01867         INTF_DESC ( struct iscsi_session, data, iscsi_data_op );
01868 
01869 /****************************************************************************
01870  *
01871  * Instantiator
01872  *
01873  */
01874 
01875 /** iSCSI root path components (as per RFC4173) */
01876 enum iscsi_root_path_component {
01877         RP_SERVERNAME = 0,
01878         RP_PROTOCOL,
01879         RP_PORT,
01880         RP_LUN,
01881         RP_TARGETNAME,
01882         NUM_RP_COMPONENTS
01883 };
01884 
01885 /** iSCSI initiator IQN setting */
01886 const struct setting initiator_iqn_setting __setting ( SETTING_SANBOOT_EXTRA,
01887                                                        initiator-iqn ) = {
01888         .name = "initiator-iqn",
01889         .description = "iSCSI initiator name",
01890         .tag = DHCP_ISCSI_INITIATOR_IQN,
01891         .type = &setting_type_string,
01892 };
01893 
01894 /** iSCSI reverse username setting */
01895 const struct setting reverse_username_setting __setting ( SETTING_AUTH_EXTRA,
01896                                                           reverse-username ) = {
01897         .name = "reverse-username",
01898         .description = "Reverse user name",
01899         .tag = DHCP_EB_REVERSE_USERNAME,
01900         .type = &setting_type_string,
01901 };
01902 
01903 /** iSCSI reverse password setting */
01904 const struct setting reverse_password_setting __setting ( SETTING_AUTH_EXTRA,
01905                                                           reverse-password ) = {
01906         .name = "reverse-password",
01907         .description = "Reverse password",
01908         .tag = DHCP_EB_REVERSE_PASSWORD,
01909         .type = &setting_type_string,
01910 };
01911 
01912 /**
01913  * Parse iSCSI root path
01914  *
01915  * @v iscsi             iSCSI session
01916  * @v root_path         iSCSI root path (as per RFC4173)
01917  * @ret rc              Return status code
01918  */
01919 static int iscsi_parse_root_path ( struct iscsi_session *iscsi,
01920                                    const char *root_path ) {
01921         char rp_copy[ strlen ( root_path ) + 1 ];
01922         char *rp_comp[NUM_RP_COMPONENTS];
01923         char *rp = rp_copy;
01924         int skip = 0;
01925         int i = 0;
01926         int rc;
01927 
01928         /* Split root path into component parts */
01929         strcpy ( rp_copy, root_path );
01930         while ( 1 ) {
01931                 rp_comp[i++] = rp;
01932                 if ( i == NUM_RP_COMPONENTS )
01933                         break;
01934                 for ( ; ( ( *rp != ':' ) || skip ) ; rp++ ) {
01935                         if ( ! *rp ) {
01936                                 DBGC ( iscsi, "iSCSI %p root path \"%s\" "
01937                                        "too short\n", iscsi, root_path );
01938                                 return -EINVAL_ROOT_PATH_TOO_SHORT;
01939                         } else if ( *rp == '[' ) {
01940                                 skip = 1;
01941                         } else if ( *rp == ']' ) {
01942                                 skip = 0;
01943                         }
01944                 }
01945                 *(rp++) = '\0';
01946         }
01947 
01948         /* Use root path components to configure iSCSI session */
01949         iscsi->target_address = strdup ( rp_comp[RP_SERVERNAME] );
01950         if ( ! iscsi->target_address )
01951                 return -ENOMEM;
01952         iscsi->target_port = strtoul ( rp_comp[RP_PORT], NULL, 10 );
01953         if ( ! iscsi->target_port )
01954                 iscsi->target_port = ISCSI_PORT;
01955         if ( ( rc = scsi_parse_lun ( rp_comp[RP_LUN], &iscsi->lun ) ) != 0 ) {
01956                 DBGC ( iscsi, "iSCSI %p invalid LUN \"%s\"\n",
01957                        iscsi, rp_comp[RP_LUN] );
01958                 return rc;
01959         }
01960         iscsi->target_iqn = strdup ( rp_comp[RP_TARGETNAME] );
01961         if ( ! iscsi->target_iqn )
01962                 return -ENOMEM;
01963 
01964         return 0;
01965 }
01966 
01967 /**
01968  * Fetch iSCSI settings
01969  *
01970  * @v iscsi             iSCSI session
01971  * @ret rc              Return status code
01972  */
01973 static int iscsi_fetch_settings ( struct iscsi_session *iscsi ) {
01974         char *hostname;
01975         union uuid uuid;
01976         int len;
01977 
01978         /* Fetch relevant settings.  Don't worry about freeing on
01979          * error, since iscsi_free() will take care of that anyway.
01980          */
01981         fetch_string_setting_copy ( NULL, &username_setting,
01982                                     &iscsi->initiator_username );
01983         fetch_string_setting_copy ( NULL, &password_setting,
01984                                     &iscsi->initiator_password );
01985         fetch_string_setting_copy ( NULL, &reverse_username_setting,
01986                                     &iscsi->target_username );
01987         fetch_string_setting_copy ( NULL, &reverse_password_setting,
01988                                     &iscsi->target_password );
01989 
01990         /* Use explicit initiator IQN if provided */
01991         fetch_string_setting_copy ( NULL, &initiator_iqn_setting,
01992                                     &iscsi->initiator_iqn );
01993         if ( iscsi->initiator_iqn )
01994                 return 0;
01995 
01996         /* Otherwise, try to construct an initiator IQN from the hostname */
01997         fetch_string_setting_copy ( NULL, &hostname_setting, &hostname );
01998         if ( hostname ) {
01999                 len = asprintf ( &iscsi->initiator_iqn,
02000                                  ISCSI_DEFAULT_IQN_PREFIX ":%s", hostname );
02001                 free ( hostname );
02002                 if ( len < 0 ) {
02003                         DBGC ( iscsi, "iSCSI %p could not allocate initiator "
02004                                "IQN\n", iscsi );
02005                         return -ENOMEM;
02006                 }
02007                 assert ( iscsi->initiator_iqn );
02008                 return 0;
02009         }
02010 
02011         /* Otherwise, try to construct an initiator IQN from the UUID */
02012         if ( ( len = fetch_uuid_setting ( NULL, &uuid_setting, &uuid ) ) < 0 ) {
02013                 DBGC ( iscsi, "iSCSI %p has no suitable initiator IQN\n",
02014                        iscsi );
02015                 return -EINVAL_NO_INITIATOR_IQN;
02016         }
02017         if ( ( len = asprintf ( &iscsi->initiator_iqn,
02018                                 ISCSI_DEFAULT_IQN_PREFIX ":%s",
02019                                 uuid_ntoa ( &uuid ) ) ) < 0 ) {
02020                 DBGC ( iscsi, "iSCSI %p could not allocate initiator IQN\n",
02021                        iscsi );
02022                 return -ENOMEM;
02023         }
02024         assert ( iscsi->initiator_iqn );
02025 
02026         return 0;
02027 }
02028 
02029 
02030 /**
02031  * Check iSCSI authentication details
02032  *
02033  * @v iscsi             iSCSI session
02034  * @ret rc              Return status code
02035  */
02036 static int iscsi_check_auth ( struct iscsi_session *iscsi ) {
02037 
02038         /* Check for invalid authentication combinations */
02039         if ( ( /* Initiator username without password (or vice-versa) */
02040                 ( !! iscsi->initiator_username ) ^
02041                 ( !! iscsi->initiator_password ) ) ||
02042              ( /* Target username without password (or vice-versa) */
02043                 ( !! iscsi->target_username ) ^
02044                 ( !! iscsi->target_password ) ) ||
02045              ( /* Target (reverse) without initiator (forward) */
02046                 ( iscsi->target_username &&
02047                   ( ! iscsi->initiator_username ) ) ) ) {
02048                 DBGC ( iscsi, "iSCSI %p invalid credentials: initiator "
02049                        "%sname,%spw, target %sname,%spw\n", iscsi,
02050                        ( iscsi->initiator_username ? "" : "no " ),
02051                        ( iscsi->initiator_password ? "" : "no " ),
02052                        ( iscsi->target_username ? "" : "no " ),
02053                        ( iscsi->target_password ? "" : "no " ) );
02054                 return -EINVAL_BAD_CREDENTIAL_MIX;
02055         }
02056 
02057         return 0;
02058 }
02059 
02060 /**
02061  * Open iSCSI URI
02062  *
02063  * @v parent            Parent interface
02064  * @v uri               URI
02065  * @ret rc              Return status code
02066  */
02067 static int iscsi_open ( struct interface *parent, struct uri *uri ) {
02068         struct iscsi_session *iscsi;
02069         int rc;
02070 
02071         /* Sanity check */
02072         if ( ! uri->opaque ) {
02073                 rc = -EINVAL_NO_ROOT_PATH;
02074                 goto err_sanity_uri;
02075         }
02076 
02077         /* Allocate and initialise structure */
02078         iscsi = zalloc ( sizeof ( *iscsi ) );
02079         if ( ! iscsi ) {
02080                 rc = -ENOMEM;
02081                 goto err_zalloc;
02082         }
02083         ref_init ( &iscsi->refcnt, iscsi_free );
02084         intf_init ( &iscsi->control, &iscsi_control_desc, &iscsi->refcnt );
02085         intf_init ( &iscsi->data, &iscsi_data_desc, &iscsi->refcnt );
02086         intf_init ( &iscsi->socket, &iscsi_socket_desc, &iscsi->refcnt );
02087         process_init_stopped ( &iscsi->process, &iscsi_process_desc,
02088                                &iscsi->refcnt );
02089         acpi_init ( &iscsi->desc, &ibft_model, &iscsi->refcnt );
02090 
02091         /* Parse root path */
02092         if ( ( rc = iscsi_parse_root_path ( iscsi, uri->opaque ) ) != 0 )
02093                 goto err_parse_root_path;
02094         /* Set fields not specified by root path */
02095         if ( ( rc = iscsi_fetch_settings ( iscsi ) ) != 0 )
02096                 goto err_fetch_settings;
02097         /* Validate authentication */
02098         if ( ( rc = iscsi_check_auth ( iscsi ) ) != 0 )
02099                 goto err_check_auth;
02100 
02101         /* Sanity checks */
02102         if ( ! iscsi->target_address ) {
02103                 DBGC ( iscsi, "iSCSI %p does not yet support discovery\n",
02104                        iscsi );
02105                 rc = -ENOTSUP_DISCOVERY;
02106                 goto err_sanity_address;
02107         }
02108         if ( ! iscsi->target_iqn ) {
02109                 DBGC ( iscsi, "iSCSI %p no target address supplied in %s\n",
02110                        iscsi, uri->opaque );
02111                 rc = -EINVAL_NO_TARGET_IQN;
02112                 goto err_sanity_iqn;
02113         }
02114         DBGC ( iscsi, "iSCSI %p initiator %s\n",iscsi, iscsi->initiator_iqn );
02115         DBGC ( iscsi, "iSCSI %p target %s %s\n",
02116                iscsi, iscsi->target_address, iscsi->target_iqn );
02117 
02118         /* Open socket */
02119         if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 )
02120                 goto err_open_connection;
02121 
02122         /* Attach SCSI device to parent interface */
02123         if ( ( rc = scsi_open ( parent, &iscsi->control,
02124                                 &iscsi->lun ) ) != 0 ) {
02125                 DBGC ( iscsi, "iSCSI %p could not create SCSI device: %s\n",
02126                        iscsi, strerror ( rc ) );
02127                 goto err_scsi_open;
02128         }
02129 
02130         /* Mortalise self, and return */
02131         ref_put ( &iscsi->refcnt );
02132         return 0;
02133         
02134  err_scsi_open:
02135  err_open_connection:
02136  err_sanity_iqn:
02137  err_sanity_address:
02138  err_check_auth:
02139  err_fetch_settings:
02140  err_parse_root_path:
02141         iscsi_close ( iscsi, rc );
02142         ref_put ( &iscsi->refcnt );
02143  err_zalloc:
02144  err_sanity_uri:
02145         return rc;
02146 }
02147 
02148 /** iSCSI URI opener */
02149 struct uri_opener iscsi_uri_opener __uri_opener = {
02150         .scheme = "iscsi",
02151         .open = iscsi_open,
02152 };