Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / net / tcp / iscsi.c
1 /*
2  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 #include <stddef.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <byteswap.h>
29 #include <ipxe/vsprintf.h>
30 #include <ipxe/socket.h>
31 #include <ipxe/iobuf.h>
32 #include <ipxe/uri.h>
33 #include <ipxe/xfer.h>
34 #include <ipxe/open.h>
35 #include <ipxe/scsi.h>
36 #include <ipxe/process.h>
37 #include <ipxe/uaccess.h>
38 #include <ipxe/tcpip.h>
39 #include <ipxe/settings.h>
40 #include <ipxe/features.h>
41 #include <ipxe/base16.h>
42 #include <ipxe/base64.h>
43 #include <ipxe/ibft.h>
44 #include <ipxe/iscsi.h>
45
46 /** @file
47  *
48  * iSCSI protocol
49  *
50  */
51
52 FEATURE ( FEATURE_PROTOCOL, "iSCSI", DHCP_EB_FEATURE_ISCSI, 1 );
53
54 /* Disambiguate the various error causes */
55 #define EACCES_INCORRECT_TARGET_USERNAME \
56         __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_USERNAME )
57 #define EINFO_EACCES_INCORRECT_TARGET_USERNAME \
58         __einfo_uniqify ( EINFO_EACCES, 0x01, "Incorrect target username" )
59 #define EACCES_INCORRECT_TARGET_PASSWORD \
60         __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_PASSWORD )
61 #define EINFO_EACCES_INCORRECT_TARGET_PASSWORD \
62         __einfo_uniqify ( EINFO_EACCES, 0x02, "Incorrect target password" )
63 #define EINVAL_ROOT_PATH_TOO_SHORT \
64         __einfo_error ( EINFO_EINVAL_ROOT_PATH_TOO_SHORT )
65 #define EINFO_EINVAL_ROOT_PATH_TOO_SHORT \
66         __einfo_uniqify ( EINFO_EINVAL, 0x01, "Root path too short" )
67 #define EINVAL_BAD_CREDENTIAL_MIX \
68         __einfo_error ( EINFO_EINVAL_BAD_CREDENTIAL_MIX )
69 #define EINFO_EINVAL_BAD_CREDENTIAL_MIX \
70         __einfo_uniqify ( EINFO_EINVAL, 0x02, "Bad credential mix" )
71 #define EINVAL_NO_ROOT_PATH \
72         __einfo_error ( EINFO_EINVAL_NO_ROOT_PATH )
73 #define EINFO_EINVAL_NO_ROOT_PATH \
74         __einfo_uniqify ( EINFO_EINVAL, 0x03, "No root path" )
75 #define EINVAL_NO_TARGET_IQN \
76         __einfo_error ( EINFO_EINVAL_NO_TARGET_IQN )
77 #define EINFO_EINVAL_NO_TARGET_IQN \
78         __einfo_uniqify ( EINFO_EINVAL, 0x04, "No target IQN" )
79 #define EINVAL_NO_INITIATOR_IQN \
80         __einfo_error ( EINFO_EINVAL_NO_INITIATOR_IQN )
81 #define EINFO_EINVAL_NO_INITIATOR_IQN \
82         __einfo_uniqify ( EINFO_EINVAL, 0x05, "No initiator IQN" )
83 #define EIO_TARGET_UNAVAILABLE \
84         __einfo_error ( EINFO_EIO_TARGET_UNAVAILABLE )
85 #define EINFO_EIO_TARGET_UNAVAILABLE \
86         __einfo_uniqify ( EINFO_EIO, 0x01, "Target not currently operational" )
87 #define EIO_TARGET_NO_RESOURCES \
88         __einfo_error ( EINFO_EIO_TARGET_NO_RESOURCES )
89 #define EINFO_EIO_TARGET_NO_RESOURCES \
90         __einfo_uniqify ( EINFO_EIO, 0x02, "Target out of resources" )
91 #define ENOTSUP_INITIATOR_STATUS \
92         __einfo_error ( EINFO_ENOTSUP_INITIATOR_STATUS )
93 #define EINFO_ENOTSUP_INITIATOR_STATUS \
94         __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported initiator status" )
95 #define ENOTSUP_OPCODE \
96         __einfo_error ( EINFO_ENOTSUP_OPCODE )
97 #define EINFO_ENOTSUP_OPCODE \
98         __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported opcode" )
99 #define ENOTSUP_DISCOVERY \
100         __einfo_error ( EINFO_ENOTSUP_DISCOVERY )
101 #define EINFO_ENOTSUP_DISCOVERY \
102         __einfo_uniqify ( EINFO_ENOTSUP, 0x03, "Discovery not supported" )
103 #define ENOTSUP_TARGET_STATUS \
104         __einfo_error ( EINFO_ENOTSUP_TARGET_STATUS )
105 #define EINFO_ENOTSUP_TARGET_STATUS \
106         __einfo_uniqify ( EINFO_ENOTSUP, 0x04, "Unsupported target status" )
107 #define ENOTSUP_NOP_IN \
108         __einfo_error ( EINFO_ENOTSUP_NOP_IN )
109 #define EINFO_ENOTSUP_NOP_IN \
110         __einfo_uniqify ( EINFO_ENOTSUP, 0x05, "Unsupported NOP-In received" )
111 #define EPERM_INITIATOR_AUTHENTICATION \
112         __einfo_error ( EINFO_EPERM_INITIATOR_AUTHENTICATION )
113 #define EINFO_EPERM_INITIATOR_AUTHENTICATION \
114         __einfo_uniqify ( EINFO_EPERM, 0x01, "Initiator authentication failed" )
115 #define EPERM_INITIATOR_AUTHORISATION \
116         __einfo_error ( EINFO_EPERM_INITIATOR_AUTHORISATION )
117 #define EINFO_EPERM_INITIATOR_AUTHORISATION \
118         __einfo_uniqify ( EINFO_EPERM, 0x02, "Initiator not authorised" )
119 #define EPROTO_INVALID_CHAP_ALGORITHM \
120         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_ALGORITHM )
121 #define EINFO_EPROTO_INVALID_CHAP_ALGORITHM \
122         __einfo_uniqify ( EINFO_EPROTO, 0x01, "Invalid CHAP algorithm" )
123 #define EPROTO_INVALID_CHAP_IDENTIFIER \
124         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_IDENTIFIER )
125 #define EINFO_EPROTO_INVALID_CHAP_IDENTIFIER \
126         __einfo_uniqify ( EINFO_EPROTO, 0x02, "Invalid CHAP identifier" )
127 #define EPROTO_INVALID_LARGE_BINARY \
128         __einfo_error ( EINFO_EPROTO_INVALID_LARGE_BINARY )
129 #define EINFO_EPROTO_INVALID_LARGE_BINARY \
130         __einfo_uniqify ( EINFO_EPROTO, 0x03, "Invalid large binary" )
131 #define EPROTO_INVALID_CHAP_RESPONSE \
132         __einfo_error ( EINFO_EPROTO_INVALID_CHAP_RESPONSE )
133 #define EINFO_EPROTO_INVALID_CHAP_RESPONSE \
134         __einfo_uniqify ( EINFO_EPROTO, 0x04, "Invalid CHAP response" )
135 #define EPROTO_INVALID_KEY_VALUE_PAIR \
136         __einfo_error ( EINFO_EPROTO_INVALID_KEY_VALUE_PAIR )
137 #define EINFO_EPROTO_INVALID_KEY_VALUE_PAIR \
138         __einfo_uniqify ( EINFO_EPROTO, 0x05, "Invalid key/value pair" )
139 #define EPROTO_VALUE_REJECTED \
140         __einfo_error ( EINFO_EPROTO_VALUE_REJECTED )
141 #define EINFO_EPROTO_VALUE_REJECTED                                     \
142         __einfo_uniqify ( EINFO_EPROTO, 0x06, "Parameter rejected" )
143
144 static void iscsi_start_tx ( struct iscsi_session *iscsi );
145 static void iscsi_start_login ( struct iscsi_session *iscsi );
146 static void iscsi_start_data_out ( struct iscsi_session *iscsi,
147                                    unsigned int datasn );
148
149 /**
150  * Finish receiving PDU data into buffer
151  *
152  * @v iscsi             iSCSI session
153  */
154 static void iscsi_rx_buffered_data_done ( struct iscsi_session *iscsi ) {
155         free ( iscsi->rx_buffer );
156         iscsi->rx_buffer = NULL;
157 }
158
159 /**
160  * Receive PDU data into buffer
161  *
162  * @v iscsi             iSCSI session
163  * @v data              Data to receive
164  * @v len               Length of data
165  * @ret rc              Return status code
166  *
167  * This can be used when the RX PDU type handler wishes to buffer up
168  * all received data and process the PDU as a single unit.  The caller
169  * is repsonsible for calling iscsi_rx_buffered_data_done() after
170  * processing the data.
171  */
172 static int iscsi_rx_buffered_data ( struct iscsi_session *iscsi,
173                                     const void *data, size_t len ) {
174
175         /* Allocate buffer on first call */
176         if ( ! iscsi->rx_buffer ) {
177                 iscsi->rx_buffer = malloc ( iscsi->rx_len );
178                 if ( ! iscsi->rx_buffer )
179                         return -ENOMEM;
180         }
181
182         /* Copy data to buffer */
183         assert ( ( iscsi->rx_offset + len ) <= iscsi->rx_len );
184         memcpy ( ( iscsi->rx_buffer + iscsi->rx_offset ), data, len );
185
186         return 0;
187 }
188
189 /**
190  * Free iSCSI session
191  *
192  * @v refcnt            Reference counter
193  */
194 static void iscsi_free ( struct refcnt *refcnt ) {
195         struct iscsi_session *iscsi =
196                 container_of ( refcnt, struct iscsi_session, refcnt );
197
198         free ( iscsi->initiator_iqn );
199         free ( iscsi->target_address );
200         free ( iscsi->target_iqn );
201         free ( iscsi->initiator_username );
202         free ( iscsi->initiator_password );
203         free ( iscsi->target_username );
204         free ( iscsi->target_password );
205         chap_finish ( &iscsi->chap );
206         iscsi_rx_buffered_data_done ( iscsi );
207         free ( iscsi->command );
208         free ( iscsi );
209 }
210
211 /**
212  * Shut down iSCSI interface
213  *
214  * @v iscsi             iSCSI session
215  * @v rc                Reason for close
216  */
217 static void iscsi_close ( struct iscsi_session *iscsi, int rc ) {
218
219         /* A TCP graceful close is still an error from our point of view */
220         if ( rc == 0 )
221                 rc = -ECONNRESET;
222
223         DBGC ( iscsi, "iSCSI %p closed: %s\n", iscsi, strerror ( rc ) );
224
225         /* Stop transmission process */
226         process_del ( &iscsi->process );
227
228         /* Shut down interfaces */
229         intf_shutdown ( &iscsi->socket, rc );
230         intf_shutdown ( &iscsi->control, rc );
231         intf_shutdown ( &iscsi->data, rc );
232 }
233
234 /**
235  * Assign new iSCSI initiator task tag
236  *
237  * @v iscsi             iSCSI session
238  */
239 static void iscsi_new_itt ( struct iscsi_session *iscsi ) {
240         static uint16_t itt_idx;
241
242         iscsi->itt = ( ISCSI_TAG_MAGIC | (++itt_idx) );
243 }
244
245 /**
246  * Open iSCSI transport-layer connection
247  *
248  * @v iscsi             iSCSI session
249  * @ret rc              Return status code
250  */
251 static int iscsi_open_connection ( struct iscsi_session *iscsi ) {
252         struct sockaddr_tcpip target;
253         int rc;
254
255         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
256         assert ( iscsi->rx_state == ISCSI_RX_BHS );
257         assert ( iscsi->rx_offset == 0 );
258
259         /* Open socket */
260         memset ( &target, 0, sizeof ( target ) );
261         target.st_port = htons ( iscsi->target_port );
262         if ( ( rc = xfer_open_named_socket ( &iscsi->socket, SOCK_STREAM,
263                                              ( struct sockaddr * ) &target,
264                                              iscsi->target_address,
265                                              NULL ) ) != 0 ) {
266                 DBGC ( iscsi, "iSCSI %p could not open socket: %s\n",
267                        iscsi, strerror ( rc ) );
268                 return rc;
269         }
270
271         /* Enter security negotiation phase */
272         iscsi->status = ( ISCSI_STATUS_SECURITY_NEGOTIATION_PHASE |
273                           ISCSI_STATUS_STRINGS_SECURITY );
274         if ( iscsi->target_username )
275                 iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_REQUIRED;
276
277         /* Assign new ISID */
278         iscsi->isid_iana_qual = ( random() & 0xffff );
279
280         /* Assign fresh initiator task tag */
281         iscsi_new_itt ( iscsi );
282
283         /* Initiate login */
284         iscsi_start_login ( iscsi );
285
286         return 0;
287 }
288
289 /**
290  * Close iSCSI transport-layer connection
291  *
292  * @v iscsi             iSCSI session
293  * @v rc                Reason for close
294  *
295  * Closes the transport-layer connection and resets the session state
296  * ready to attempt a fresh login.
297  */
298 static void iscsi_close_connection ( struct iscsi_session *iscsi, int rc ) {
299
300         /* Close all data transfer interfaces */
301         intf_restart ( &iscsi->socket, rc );
302
303         /* Clear connection status */
304         iscsi->status = 0;
305
306         /* Reset TX and RX state machines */
307         iscsi->tx_state = ISCSI_TX_IDLE;
308         iscsi->rx_state = ISCSI_RX_BHS;
309         iscsi->rx_offset = 0;
310
311         /* Free any temporary dynamically allocated memory */
312         chap_finish ( &iscsi->chap );
313         iscsi_rx_buffered_data_done ( iscsi );
314 }
315
316 /**
317  * Mark iSCSI SCSI operation as complete
318  *
319  * @v iscsi             iSCSI session
320  * @v rc                Return status code
321  * @v rsp               SCSI response, if any
322  *
323  * Note that iscsi_scsi_done() will not close the connection, and must
324  * therefore be called only when the internal state machines are in an
325  * appropriate state, otherwise bad things may happen on the next call
326  * to iscsi_scsi_command().  The general rule is to call
327  * iscsi_scsi_done() only at the end of receiving a PDU; at this point
328  * the TX and RX engines should both be idle.
329  */
330 static void iscsi_scsi_done ( struct iscsi_session *iscsi, int rc,
331                               struct scsi_rsp *rsp ) {
332         uint32_t itt = iscsi->itt;
333
334         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
335
336         /* Clear command */
337         free ( iscsi->command );
338         iscsi->command = NULL;
339
340         /* Send SCSI response, if any */
341         if ( rsp )
342                 scsi_response ( &iscsi->data, rsp );
343
344         /* Close SCSI command, if this is still the same command.  (It
345          * is possible that the command interface has already been
346          * closed as a result of the SCSI response we sent.)
347          */
348         if ( iscsi->itt == itt )
349                 intf_restart ( &iscsi->data, rc );
350 }
351
352 /****************************************************************************
353  *
354  * iSCSI SCSI command issuing
355  *
356  */
357
358 /**
359  * Build iSCSI SCSI command BHS
360  *
361  * @v iscsi             iSCSI session
362  *
363  * We don't currently support bidirectional commands (i.e. with both
364  * Data-In and Data-Out segments); these would require providing code
365  * to generate an AHS, and there doesn't seem to be any need for it at
366  * the moment.
367  */
368 static void iscsi_start_command ( struct iscsi_session *iscsi ) {
369         struct iscsi_bhs_scsi_command *command = &iscsi->tx_bhs.scsi_command;
370
371         assert ( ! ( iscsi->command->data_in && iscsi->command->data_out ) );
372
373         /* Construct BHS and initiate transmission */
374         iscsi_start_tx ( iscsi );
375         command->opcode = ISCSI_OPCODE_SCSI_COMMAND;
376         command->flags = ( ISCSI_FLAG_FINAL |
377                            ISCSI_COMMAND_ATTR_SIMPLE );
378         if ( iscsi->command->data_in )
379                 command->flags |= ISCSI_COMMAND_FLAG_READ;
380         if ( iscsi->command->data_out )
381                 command->flags |= ISCSI_COMMAND_FLAG_WRITE;
382         /* lengths left as zero */
383         memcpy ( &command->lun, &iscsi->command->lun,
384                  sizeof ( command->lun ) );
385         command->itt = htonl ( iscsi->itt );
386         command->exp_len = htonl ( iscsi->command->data_in_len |
387                                    iscsi->command->data_out_len );
388         command->cmdsn = htonl ( iscsi->cmdsn );
389         command->expstatsn = htonl ( iscsi->statsn + 1 );
390         memcpy ( &command->cdb, &iscsi->command->cdb, sizeof ( command->cdb ));
391         DBGC2 ( iscsi, "iSCSI %p start " SCSI_CDB_FORMAT " %s %#zx\n",
392                 iscsi, SCSI_CDB_DATA ( command->cdb ),
393                 ( iscsi->command->data_in ? "in" : "out" ),
394                 ( iscsi->command->data_in ?
395                   iscsi->command->data_in_len :
396                   iscsi->command->data_out_len ) );
397 }
398
399 /**
400  * Receive data segment of an iSCSI SCSI response PDU
401  *
402  * @v iscsi             iSCSI session
403  * @v data              Received data
404  * @v len               Length of received data
405  * @v remaining         Data remaining after this data
406  * @ret rc              Return status code
407  */
408 static int iscsi_rx_scsi_response ( struct iscsi_session *iscsi,
409                                     const void *data, size_t len,
410                                     size_t remaining ) {
411         struct iscsi_bhs_scsi_response *response
412                 = &iscsi->rx_bhs.scsi_response;
413         struct scsi_rsp rsp;
414         uint32_t residual_count;
415         size_t data_len;
416         int rc;
417
418         /* Buffer up the PDU data */
419         if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
420                 DBGC ( iscsi, "iSCSI %p could not buffer SCSI response: %s\n",
421                        iscsi, strerror ( rc ) );
422                 return rc;
423         }
424         if ( remaining )
425                 return 0;
426
427         /* Parse SCSI response and discard buffer */
428         memset ( &rsp, 0, sizeof ( rsp ) );
429         rsp.status = response->status;
430         residual_count = ntohl ( response->residual_count );
431         if ( response->flags & ISCSI_DATA_FLAG_OVERFLOW ) {
432                 rsp.overrun = residual_count;
433         } else if ( response->flags & ISCSI_DATA_FLAG_UNDERFLOW ) {
434                 rsp.overrun = -(residual_count);
435         }
436         data_len = ISCSI_DATA_LEN ( response->lengths );
437         if ( data_len ) {
438                 scsi_parse_sense ( ( iscsi->rx_buffer + 2 ), ( data_len - 2 ),
439                                    &rsp.sense );
440         }
441         iscsi_rx_buffered_data_done ( iscsi );
442
443         /* Check for errors */
444         if ( response->response != ISCSI_RESPONSE_COMMAND_COMPLETE )
445                 return -EIO;
446
447         /* Mark as completed */
448         iscsi_scsi_done ( iscsi, 0, &rsp );
449         return 0;
450 }
451
452 /**
453  * Receive data segment of an iSCSI data-in PDU
454  *
455  * @v iscsi             iSCSI session
456  * @v data              Received data
457  * @v len               Length of received data
458  * @v remaining         Data remaining after this data
459  * @ret rc              Return status code
460  */
461 static int iscsi_rx_data_in ( struct iscsi_session *iscsi,
462                               const void *data, size_t len,
463                               size_t remaining ) {
464         struct iscsi_bhs_data_in *data_in = &iscsi->rx_bhs.data_in;
465         unsigned long offset;
466
467         /* Copy data to data-in buffer */
468         offset = ntohl ( data_in->offset ) + iscsi->rx_offset;
469         assert ( iscsi->command != NULL );
470         assert ( iscsi->command->data_in );
471         assert ( ( offset + len ) <= iscsi->command->data_in_len );
472         copy_to_user ( iscsi->command->data_in, offset, data, len );
473
474         /* Wait for whole SCSI response to arrive */
475         if ( remaining )
476                 return 0;
477
478         /* Mark as completed if status is present */
479         if ( data_in->flags & ISCSI_DATA_FLAG_STATUS ) {
480                 assert ( ( offset + len ) == iscsi->command->data_in_len );
481                 assert ( data_in->flags & ISCSI_FLAG_FINAL );
482                 /* iSCSI cannot return an error status via a data-in */
483                 iscsi_scsi_done ( iscsi, 0, NULL );
484         }
485
486         return 0;
487 }
488
489 /**
490  * Receive data segment of an iSCSI R2T PDU
491  *
492  * @v iscsi             iSCSI session
493  * @v data              Received data
494  * @v len               Length of received data
495  * @v remaining         Data remaining after this data
496  * @ret rc              Return status code
497  */
498 static int iscsi_rx_r2t ( struct iscsi_session *iscsi,
499                           const void *data __unused, size_t len __unused,
500                           size_t remaining __unused ) {
501         struct iscsi_bhs_r2t *r2t = &iscsi->rx_bhs.r2t;
502
503         /* Record transfer parameters and trigger first data-out */
504         iscsi->ttt = ntohl ( r2t->ttt );
505         iscsi->transfer_offset = ntohl ( r2t->offset );
506         iscsi->transfer_len = ntohl ( r2t->len );
507         iscsi_start_data_out ( iscsi, 0 );
508
509         return 0;
510 }
511
512 /**
513  * Build iSCSI data-out BHS
514  *
515  * @v iscsi             iSCSI session
516  * @v datasn            Data sequence number within the transfer
517  *
518  */
519 static void iscsi_start_data_out ( struct iscsi_session *iscsi,
520                                    unsigned int datasn ) {
521         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
522         unsigned long offset;
523         unsigned long remaining;
524         unsigned long len;
525
526         /* We always send 512-byte Data-Out PDUs; this removes the
527          * need to worry about the target's MaxRecvDataSegmentLength.
528          */
529         offset = datasn * 512;
530         remaining = iscsi->transfer_len - offset;
531         len = remaining;
532         if ( len > 512 )
533                 len = 512;
534
535         /* Construct BHS and initiate transmission */
536         iscsi_start_tx ( iscsi );
537         data_out->opcode = ISCSI_OPCODE_DATA_OUT;
538         if ( len == remaining )
539                 data_out->flags = ( ISCSI_FLAG_FINAL );
540         ISCSI_SET_LENGTHS ( data_out->lengths, 0, len );
541         data_out->lun = iscsi->command->lun;
542         data_out->itt = htonl ( iscsi->itt );
543         data_out->ttt = htonl ( iscsi->ttt );
544         data_out->expstatsn = htonl ( iscsi->statsn + 1 );
545         data_out->datasn = htonl ( datasn );
546         data_out->offset = htonl ( iscsi->transfer_offset + offset );
547         DBGC ( iscsi, "iSCSI %p start data out DataSN %#x len %#lx\n",
548                iscsi, datasn, len );
549 }
550
551 /**
552  * Complete iSCSI data-out PDU transmission
553  *
554  * @v iscsi             iSCSI session
555  *
556  */
557 static void iscsi_data_out_done ( struct iscsi_session *iscsi ) {
558         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
559
560         /* If we haven't reached the end of the sequence, start
561          * sending the next data-out PDU.
562          */
563         if ( ! ( data_out->flags & ISCSI_FLAG_FINAL ) )
564                 iscsi_start_data_out ( iscsi, ntohl ( data_out->datasn ) + 1 );
565 }
566
567 /**
568  * Send iSCSI data-out data segment
569  *
570  * @v iscsi             iSCSI session
571  * @ret rc              Return status code
572  */
573 static int iscsi_tx_data_out ( struct iscsi_session *iscsi ) {
574         struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
575         struct io_buffer *iobuf;
576         unsigned long offset;
577         size_t len;
578         size_t pad_len;
579
580         offset = ntohl ( data_out->offset );
581         len = ISCSI_DATA_LEN ( data_out->lengths );
582         pad_len = ISCSI_DATA_PAD_LEN ( data_out->lengths );
583
584         assert ( iscsi->command != NULL );
585         assert ( iscsi->command->data_out );
586         assert ( ( offset + len ) <= iscsi->command->data_out_len );
587
588         iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
589         if ( ! iobuf )
590                 return -ENOMEM;
591         
592         copy_from_user ( iob_put ( iobuf, len ),
593                          iscsi->command->data_out, offset, len );
594         memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
595
596         return xfer_deliver_iob ( &iscsi->socket, iobuf );
597 }
598
599 /**
600  * Receive data segment of an iSCSI NOP-In
601  *
602  * @v iscsi             iSCSI session
603  * @v data              Received data
604  * @v len               Length of received data
605  * @v remaining         Data remaining after this data
606  * @ret rc              Return status code
607  */
608 static int iscsi_rx_nop_in ( struct iscsi_session *iscsi,
609                              const void *data __unused, size_t len __unused,
610                              size_t remaining __unused ) {
611         struct iscsi_nop_in *nop_in = &iscsi->rx_bhs.nop_in;
612
613         DBGC2 ( iscsi, "iSCSI %p received NOP-In\n", iscsi );
614
615         /* We don't currently have the ability to respond to NOP-Ins
616          * sent as ping requests, but we can happily accept NOP-Ins
617          * sent merely to update CmdSN.
618          */
619         if ( nop_in->ttt != htonl ( ISCSI_TAG_RESERVED ) ) {
620                 DBGC ( iscsi, "iSCSI %p received unsupported NOP-In with TTT "
621                        "%08x\n", iscsi, ntohl ( nop_in->ttt ) );
622                 return -ENOTSUP_NOP_IN;
623         }
624
625         return 0;
626 }
627
628 /****************************************************************************
629  *
630  * iSCSI login
631  *
632  */
633
634 /**
635  * Build iSCSI login request strings
636  *
637  * @v iscsi             iSCSI session
638  *
639  * These are the initial set of strings sent in the first login
640  * request PDU.  We want the following settings:
641  *
642  *     HeaderDigest=None
643  *     DataDigest=None
644  *     MaxConnections is irrelevant; we make only one connection anyway [4]
645  *     InitialR2T=Yes [1]
646  *     ImmediateData is irrelevant; we never send immediate data [4]
647  *     MaxRecvDataSegmentLength=8192 (default; we don't care) [3]
648  *     MaxBurstLength=262144 (default; we don't care) [3]
649  *     FirstBurstLength=262144 (default; we don't care)
650  *     DefaultTime2Wait=0 [2]
651  *     DefaultTime2Retain=0 [2]
652  *     MaxOutstandingR2T=1
653  *     DataPDUInOrder=Yes
654  *     DataSequenceInOrder=Yes
655  *     ErrorRecoveryLevel=0
656  *
657  * [1] InitialR2T has an OR resolution function, so the target may
658  * force us to use it.  We therefore simplify our logic by always
659  * using it.
660  *
661  * [2] These ensure that we can safely start a new task once we have
662  * reconnected after a failure, without having to manually tidy up
663  * after the old one.
664  *
665  * [3] We are quite happy to use the RFC-defined default values for
666  * these parameters, but some targets (notably OpenSolaris)
667  * incorrectly assume a default value of zero, so we explicitly
668  * specify the default values.
669  *
670  * [4] We are quite happy to use the RFC-defined default values for
671  * these parameters, but some targets (notably a QNAP TS-639Pro) fail
672  * unless they are supplied, so we explicitly specify the default
673  * values.
674  */
675 static int iscsi_build_login_request_strings ( struct iscsi_session *iscsi,
676                                                void *data, size_t len ) {
677         unsigned int used = 0;
678         const char *auth_method;
679
680         if ( iscsi->status & ISCSI_STATUS_STRINGS_SECURITY ) {
681                 /* Default to allowing no authentication */
682                 auth_method = "None";
683                 /* If we have a credential to supply, permit CHAP */
684                 if ( iscsi->initiator_username )
685                         auth_method = "CHAP,None";
686                 /* If we have a credential to check, force CHAP */
687                 if ( iscsi->target_username )
688                         auth_method = "CHAP";
689                 used += ssnprintf ( data + used, len - used,
690                                     "InitiatorName=%s%c"
691                                     "TargetName=%s%c"
692                                     "SessionType=Normal%c"
693                                     "AuthMethod=%s%c",
694                                     iscsi->initiator_iqn, 0,
695                                     iscsi->target_iqn, 0, 0,
696                                     auth_method, 0 );
697         }
698
699         if ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_ALGORITHM ) {
700                 used += ssnprintf ( data + used, len - used, "CHAP_A=5%c", 0 );
701         }
702         
703         if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_RESPONSE ) ) {
704                 char buf[ base16_encoded_len ( iscsi->chap.response_len ) + 1 ];
705                 assert ( iscsi->initiator_username != NULL );
706                 base16_encode ( iscsi->chap.response, iscsi->chap.response_len,
707                                 buf );
708                 used += ssnprintf ( data + used, len - used,
709                                     "CHAP_N=%s%cCHAP_R=0x%s%c",
710                                     iscsi->initiator_username, 0, buf, 0 );
711         }
712
713         if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_CHALLENGE ) ) {
714                 size_t challenge_len = ( sizeof ( iscsi->chap_challenge ) - 1 );
715                 char buf[ base16_encoded_len ( challenge_len ) + 1 ];
716                 base16_encode ( ( iscsi->chap_challenge + 1 ), challenge_len,
717                                 buf );
718                 used += ssnprintf ( data + used, len - used,
719                                     "CHAP_I=%d%cCHAP_C=0x%s%c",
720                                     iscsi->chap_challenge[0], 0, buf, 0 );
721         }
722
723         if ( iscsi->status & ISCSI_STATUS_STRINGS_OPERATIONAL ) {
724                 used += ssnprintf ( data + used, len - used,
725                                     "HeaderDigest=None%c"
726                                     "DataDigest=None%c"
727                                     "MaxConnections=1%c"
728                                     "InitialR2T=Yes%c"
729                                     "ImmediateData=No%c"
730                                     "MaxRecvDataSegmentLength=8192%c"
731                                     "MaxBurstLength=262144%c"
732                                     "DefaultTime2Wait=0%c"
733                                     "DefaultTime2Retain=0%c"
734                                     "MaxOutstandingR2T=1%c"
735                                     "DataPDUInOrder=Yes%c"
736                                     "DataSequenceInOrder=Yes%c"
737                                     "ErrorRecoveryLevel=0%c",
738                                     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
739         }
740
741         return used;
742 }
743
744 /**
745  * Build iSCSI login request BHS
746  *
747  * @v iscsi             iSCSI session
748  */
749 static void iscsi_start_login ( struct iscsi_session *iscsi ) {
750         struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
751         int len;
752
753         switch ( iscsi->status & ISCSI_LOGIN_CSG_MASK ) {
754         case ISCSI_LOGIN_CSG_SECURITY_NEGOTIATION:
755                 DBGC ( iscsi, "iSCSI %p entering security negotiation\n",
756                        iscsi );
757                 break;
758         case ISCSI_LOGIN_CSG_OPERATIONAL_NEGOTIATION:
759                 DBGC ( iscsi, "iSCSI %p entering operational negotiation\n",
760                        iscsi );
761                 break;
762         default:
763                 assert ( 0 );
764         }
765
766         /* Construct BHS and initiate transmission */
767         iscsi_start_tx ( iscsi );
768         request->opcode = ( ISCSI_OPCODE_LOGIN_REQUEST |
769                             ISCSI_FLAG_IMMEDIATE );
770         request->flags = ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) |
771                            ISCSI_LOGIN_FLAG_TRANSITION );
772         /* version_max and version_min left as zero */
773         len = iscsi_build_login_request_strings ( iscsi, NULL, 0 );
774         ISCSI_SET_LENGTHS ( request->lengths, 0, len );
775         request->isid_iana_en = htonl ( ISCSI_ISID_IANA |
776                                         IANA_EN_FEN_SYSTEMS );
777         request->isid_iana_qual = htons ( iscsi->isid_iana_qual );
778         /* tsih left as zero */
779         request->itt = htonl ( iscsi->itt );
780         /* cid left as zero */
781         request->cmdsn = htonl ( iscsi->cmdsn );
782         request->expstatsn = htonl ( iscsi->statsn + 1 );
783 }
784
785 /**
786  * Complete iSCSI login request PDU transmission
787  *
788  * @v iscsi             iSCSI session
789  *
790  */
791 static void iscsi_login_request_done ( struct iscsi_session *iscsi ) {
792
793         /* Clear any "strings to send" flags */
794         iscsi->status &= ~ISCSI_STATUS_STRINGS_MASK;
795
796         /* Free any dynamically allocated storage used for login */
797         chap_finish ( &iscsi->chap );
798 }
799
800 /**
801  * Transmit data segment of an iSCSI login request PDU
802  *
803  * @v iscsi             iSCSI session
804  * @ret rc              Return status code
805  *
806  * For login requests, the data segment consists of the login strings.
807  */
808 static int iscsi_tx_login_request ( struct iscsi_session *iscsi ) {
809         struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
810         struct io_buffer *iobuf;
811         size_t len;
812         size_t pad_len;
813
814         len = ISCSI_DATA_LEN ( request->lengths );
815         pad_len = ISCSI_DATA_PAD_LEN ( request->lengths );
816         iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
817         if ( ! iobuf )
818                 return -ENOMEM;
819         iob_put ( iobuf, len );
820         iscsi_build_login_request_strings ( iscsi, iobuf->data, len );
821         memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
822
823         return xfer_deliver_iob ( &iscsi->socket, iobuf );
824 }
825
826 /**
827  * Calculate maximum length of decoded large binary value
828  *
829  * @v encoded           Encoded large binary value
830  * @v max_raw_len       Maximum length of raw data
831  */
832 static inline size_t
833 iscsi_large_binary_decoded_max_len ( const char *encoded ) {
834         return ( strlen ( encoded ) ); /* Decoding never expands data */
835 }
836
837 /**
838  * Decode large binary value
839  *
840  * @v encoded           Encoded large binary value
841  * @v raw               Raw data
842  * @ret len             Length of raw data, or negative error
843  */
844 static int iscsi_large_binary_decode ( const char *encoded, uint8_t *raw ) {
845
846         if ( encoded[0] != '0' )
847                 return -EPROTO_INVALID_LARGE_BINARY;
848
849         switch ( encoded[1] ) {
850         case 'x' :
851         case 'X' :
852                 return base16_decode ( ( encoded + 2 ), raw );
853         case 'b' :
854         case 'B' :
855                 return base64_decode ( ( encoded + 2 ), raw );
856         default:
857                 return -EPROTO_INVALID_LARGE_BINARY;
858         }
859 }
860
861 /**
862  * Handle iSCSI TargetAddress text value
863  *
864  * @v iscsi             iSCSI session
865  * @v value             TargetAddress value
866  * @ret rc              Return status code
867  */
868 static int iscsi_handle_targetaddress_value ( struct iscsi_session *iscsi,
869                                               const char *value ) {
870         char *separator;
871
872         DBGC ( iscsi, "iSCSI %p will redirect to %s\n", iscsi, value );
873
874         /* Replace target address */
875         free ( iscsi->target_address );
876         iscsi->target_address = strdup ( value );
877         if ( ! iscsi->target_address )
878                 return -ENOMEM;
879
880         /* Replace target port */
881         iscsi->target_port = htons ( ISCSI_PORT );
882         separator = strchr ( iscsi->target_address, ':' );
883         if ( separator ) {
884                 *separator = '\0';
885                 iscsi->target_port = strtoul ( ( separator + 1 ), NULL, 0 );
886         }
887
888         return 0;
889 }
890
891 /**
892  * Handle iSCSI AuthMethod text value
893  *
894  * @v iscsi             iSCSI session
895  * @v value             AuthMethod value
896  * @ret rc              Return status code
897  */
898 static int iscsi_handle_authmethod_value ( struct iscsi_session *iscsi,
899                                            const char *value ) {
900
901         /* If server requests CHAP, send the CHAP_A string */
902         if ( strcmp ( value, "CHAP" ) == 0 ) {
903                 DBGC ( iscsi, "iSCSI %p initiating CHAP authentication\n",
904                        iscsi );
905                 iscsi->status |= ( ISCSI_STATUS_STRINGS_CHAP_ALGORITHM |
906                                    ISCSI_STATUS_AUTH_FORWARD_REQUIRED );
907         }
908
909         return 0;
910 }
911
912 /**
913  * Handle iSCSI CHAP_A text value
914  *
915  * @v iscsi             iSCSI session
916  * @v value             CHAP_A value
917  * @ret rc              Return status code
918  */
919 static int iscsi_handle_chap_a_value ( struct iscsi_session *iscsi,
920                                        const char *value ) {
921
922         /* We only ever offer "5" (i.e. MD5) as an algorithm, so if
923          * the server responds with anything else it is a protocol
924          * violation.
925          */
926         if ( strcmp ( value, "5" ) != 0 ) {
927                 DBGC ( iscsi, "iSCSI %p got invalid CHAP algorithm \"%s\"\n",
928                        iscsi, value );
929                 return -EPROTO_INVALID_CHAP_ALGORITHM;
930         }
931
932         return 0;
933 }
934
935 /**
936  * Handle iSCSI CHAP_I text value
937  *
938  * @v iscsi             iSCSI session
939  * @v value             CHAP_I value
940  * @ret rc              Return status code
941  */
942 static int iscsi_handle_chap_i_value ( struct iscsi_session *iscsi,
943                                        const char *value ) {
944         unsigned int identifier;
945         char *endp;
946         int rc;
947
948         /* The CHAP identifier is an integer value */
949         identifier = strtoul ( value, &endp, 0 );
950         if ( *endp != '\0' ) {
951                 DBGC ( iscsi, "iSCSI %p saw invalid CHAP identifier \"%s\"\n",
952                        iscsi, value );
953                 return -EPROTO_INVALID_CHAP_IDENTIFIER;
954         }
955
956         /* Prepare for CHAP with MD5 */
957         chap_finish ( &iscsi->chap );
958         if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
959                 DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
960                        iscsi, strerror ( rc ) );
961                 return rc;
962         }
963
964         /* Identifier and secret are the first two components of the
965          * challenge.
966          */
967         chap_set_identifier ( &iscsi->chap, identifier );
968         if ( iscsi->initiator_password ) {
969                 chap_update ( &iscsi->chap, iscsi->initiator_password,
970                               strlen ( iscsi->initiator_password ) );
971         }
972
973         return 0;
974 }
975
976 /**
977  * Handle iSCSI CHAP_C text value
978  *
979  * @v iscsi             iSCSI session
980  * @v value             CHAP_C value
981  * @ret rc              Return status code
982  */
983 static int iscsi_handle_chap_c_value ( struct iscsi_session *iscsi,
984                                        const char *value ) {
985         uint8_t buf[ iscsi_large_binary_decoded_max_len ( value ) ];
986         unsigned int i;
987         size_t len;
988         int rc;
989
990         /* Process challenge */
991         rc = iscsi_large_binary_decode ( value, buf );
992         if ( rc < 0 ) {
993                 DBGC ( iscsi, "iSCSI %p invalid CHAP challenge \"%s\": %s\n",
994                        iscsi, value, strerror ( rc ) );
995                 return rc;
996         }
997         len = rc;
998         chap_update ( &iscsi->chap, buf, len );
999
1000         /* Build CHAP response */
1001         DBGC ( iscsi, "iSCSI %p sending CHAP response\n", iscsi );
1002         chap_respond ( &iscsi->chap );
1003         iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_RESPONSE;
1004
1005         /* Send CHAP challenge, if applicable */
1006         if ( iscsi->target_username ) {
1007                 iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_CHALLENGE;
1008                 /* Generate CHAP challenge data */
1009                 for ( i = 0 ; i < sizeof ( iscsi->chap_challenge ) ; i++ ) {
1010                         iscsi->chap_challenge[i] = random();
1011                 }
1012         }
1013
1014         return 0;
1015 }
1016
1017 /**
1018  * Handle iSCSI CHAP_N text value
1019  *
1020  * @v iscsi             iSCSI session
1021  * @v value             CHAP_N value
1022  * @ret rc              Return status code
1023  */
1024 static int iscsi_handle_chap_n_value ( struct iscsi_session *iscsi,
1025                                        const char *value ) {
1026
1027         /* The target username isn't actually involved at any point in
1028          * the authentication process; it merely serves to identify
1029          * which password the target is using to generate the CHAP
1030          * response.  We unnecessarily verify that the username is as
1031          * expected, in order to provide mildly helpful diagnostics if
1032          * the target is supplying the wrong username/password
1033          * combination.
1034          */
1035         if ( iscsi->target_username &&
1036              ( strcmp ( iscsi->target_username, value ) != 0 ) ) {
1037                 DBGC ( iscsi, "iSCSI %p target username \"%s\" incorrect "
1038                        "(wanted \"%s\")\n",
1039                        iscsi, value, iscsi->target_username );
1040                 return -EACCES_INCORRECT_TARGET_USERNAME;
1041         }
1042
1043         return 0;
1044 }
1045
1046 /**
1047  * Handle iSCSI CHAP_R text value
1048  *
1049  * @v iscsi             iSCSI session
1050  * @v value             CHAP_R value
1051  * @ret rc              Return status code
1052  */
1053 static int iscsi_handle_chap_r_value ( struct iscsi_session *iscsi,
1054                                        const char *value ) {
1055         uint8_t buf[ iscsi_large_binary_decoded_max_len ( value ) ];
1056         size_t len;
1057         int rc;
1058
1059         /* Generate CHAP response for verification */
1060         chap_finish ( &iscsi->chap );
1061         if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
1062                 DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
1063                        iscsi, strerror ( rc ) );
1064                 return rc;
1065         }
1066         chap_set_identifier ( &iscsi->chap, iscsi->chap_challenge[0] );
1067         if ( iscsi->target_password ) {
1068                 chap_update ( &iscsi->chap, iscsi->target_password,
1069                               strlen ( iscsi->target_password ) );
1070         }
1071         chap_update ( &iscsi->chap, &iscsi->chap_challenge[1],
1072                       ( sizeof ( iscsi->chap_challenge ) - 1 ) );
1073         chap_respond ( &iscsi->chap );
1074
1075         /* Process response */
1076         rc = iscsi_large_binary_decode ( value, buf );
1077         if ( rc < 0 ) {
1078                 DBGC ( iscsi, "iSCSI %p invalid CHAP response \"%s\": %s\n",
1079                        iscsi, value, strerror ( rc ) );
1080                 return rc;
1081         }
1082         len = rc;
1083
1084         /* Check CHAP response */
1085         if ( len != iscsi->chap.response_len ) {
1086                 DBGC ( iscsi, "iSCSI %p invalid CHAP response length\n",
1087                        iscsi );
1088                 return -EPROTO_INVALID_CHAP_RESPONSE;
1089         }
1090         if ( memcmp ( buf, iscsi->chap.response, len ) != 0 ) {
1091                 DBGC ( iscsi, "iSCSI %p incorrect CHAP response \"%s\"\n",
1092                        iscsi, value );
1093                 return -EACCES_INCORRECT_TARGET_PASSWORD;
1094         }
1095
1096         /* Mark session as authenticated */
1097         iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_OK;
1098
1099         return 0;
1100 }
1101
1102 /** An iSCSI text string that we want to handle */
1103 struct iscsi_string_type {
1104         /** String key
1105          *
1106          * This is the portion preceding the "=" sign,
1107          * e.g. "InitiatorName", "CHAP_A", etc.
1108          */
1109         const char *key;
1110         /** Handle iSCSI string value
1111          *
1112          * @v iscsi             iSCSI session
1113          * @v value             iSCSI string value
1114          * @ret rc              Return status code
1115          */
1116         int ( * handle ) ( struct iscsi_session *iscsi, const char *value );
1117 };
1118
1119 /** iSCSI text strings that we want to handle */
1120 static struct iscsi_string_type iscsi_string_types[] = {
1121         { "TargetAddress", iscsi_handle_targetaddress_value },
1122         { "AuthMethod", iscsi_handle_authmethod_value },
1123         { "CHAP_A", iscsi_handle_chap_a_value },
1124         { "CHAP_I", iscsi_handle_chap_i_value },
1125         { "CHAP_C", iscsi_handle_chap_c_value },
1126         { "CHAP_N", iscsi_handle_chap_n_value },
1127         { "CHAP_R", iscsi_handle_chap_r_value },
1128         { NULL, NULL }
1129 };
1130
1131 /**
1132  * Handle iSCSI string
1133  *
1134  * @v iscsi             iSCSI session
1135  * @v string            iSCSI string (in "key=value" format)
1136  * @ret rc              Return status code
1137  */
1138 static int iscsi_handle_string ( struct iscsi_session *iscsi,
1139                                  const char *string ) {
1140         struct iscsi_string_type *type;
1141         const char *separator;
1142         const char *value;
1143         size_t key_len;
1144         int rc;
1145
1146         /* Find separator */
1147         separator = strchr ( string, '=' );
1148         if ( ! separator ) {
1149                 DBGC ( iscsi, "iSCSI %p malformed string %s\n",
1150                        iscsi, string );
1151                 return -EPROTO_INVALID_KEY_VALUE_PAIR;
1152         }
1153         key_len = ( separator - string );
1154         value = ( separator + 1 );
1155
1156         /* Check for rejections.  Since we send only non-rejectable
1157          * values, any rejection is a fatal protocol error.
1158          */
1159         if ( strcmp ( value, "Reject" ) == 0 ) {
1160                 DBGC ( iscsi, "iSCSI %p rejection: %s\n", iscsi, string );
1161                 return -EPROTO_VALUE_REJECTED;
1162         }
1163
1164         /* Handle key/value pair */
1165         for ( type = iscsi_string_types ; type->key ; type++ ) {
1166                 if ( strncmp ( string, type->key, key_len ) != 0 )
1167                         continue;
1168                 DBGC ( iscsi, "iSCSI %p handling %s\n", iscsi, string );
1169                 if ( ( rc = type->handle ( iscsi, value ) ) != 0 ) {
1170                         DBGC ( iscsi, "iSCSI %p could not handle %s: %s\n",
1171                                iscsi, string, strerror ( rc ) );
1172                         return rc;
1173                 }
1174                 return 0;
1175         }
1176         DBGC ( iscsi, "iSCSI %p ignoring %s\n", iscsi, string );
1177         return 0;
1178 }
1179
1180 /**
1181  * Handle iSCSI strings
1182  *
1183  * @v iscsi             iSCSI session
1184  * @v string            iSCSI string buffer
1185  * @v len               Length of string buffer
1186  * @ret rc              Return status code
1187  */
1188 static int iscsi_handle_strings ( struct iscsi_session *iscsi,
1189                                   const char *strings, size_t len ) {
1190         size_t string_len;
1191         int rc;
1192
1193         /* Handle each string in turn, taking care not to overrun the
1194          * data buffer in case of badly-terminated data.
1195          */
1196         while ( 1 ) {
1197                 string_len = ( strnlen ( strings, len ) + 1 );
1198                 if ( string_len > len )
1199                         break;
1200                 if ( ( rc = iscsi_handle_string ( iscsi, strings ) ) != 0 )
1201                         return rc;
1202                 strings += string_len;
1203                 len -= string_len;
1204         }
1205         return 0;
1206 }
1207
1208 /**
1209  * Convert iSCSI response status to return status code
1210  *
1211  * @v status_class      iSCSI status class
1212  * @v status_detail     iSCSI status detail
1213  * @ret rc              Return status code
1214  */
1215 static int iscsi_status_to_rc ( unsigned int status_class,
1216                                 unsigned int status_detail ) {
1217         switch ( status_class ) {
1218         case ISCSI_STATUS_INITIATOR_ERROR :
1219                 switch ( status_detail ) {
1220                 case ISCSI_STATUS_INITIATOR_ERROR_AUTHENTICATION :
1221                         return -EPERM_INITIATOR_AUTHENTICATION;
1222                 case ISCSI_STATUS_INITIATOR_ERROR_AUTHORISATION :
1223                         return -EPERM_INITIATOR_AUTHORISATION;
1224                 case ISCSI_STATUS_INITIATOR_ERROR_NOT_FOUND :
1225                 case ISCSI_STATUS_INITIATOR_ERROR_REMOVED :
1226                         return -ENODEV;
1227                 default :
1228                         return -ENOTSUP_INITIATOR_STATUS;
1229                 }
1230         case ISCSI_STATUS_TARGET_ERROR :
1231                 switch ( status_detail ) {
1232                 case ISCSI_STATUS_TARGET_ERROR_UNAVAILABLE:
1233                         return -EIO_TARGET_UNAVAILABLE;
1234                 case ISCSI_STATUS_TARGET_ERROR_NO_RESOURCES:
1235                         return -EIO_TARGET_NO_RESOURCES;
1236                 default:
1237                         return -ENOTSUP_TARGET_STATUS;
1238                 }
1239         default :
1240                 return -EINVAL;
1241         }
1242 }
1243
1244 /**
1245  * Receive data segment of an iSCSI login response PDU
1246  *
1247  * @v iscsi             iSCSI session
1248  * @v data              Received data
1249  * @v len               Length of received data
1250  * @v remaining         Data remaining after this data
1251  * @ret rc              Return status code
1252  */
1253 static int iscsi_rx_login_response ( struct iscsi_session *iscsi,
1254                                      const void *data, size_t len,
1255                                      size_t remaining ) {
1256         struct iscsi_bhs_login_response *response
1257                 = &iscsi->rx_bhs.login_response;
1258         int rc;
1259
1260         /* Buffer up the PDU data */
1261         if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
1262                 DBGC ( iscsi, "iSCSI %p could not buffer login response: %s\n",
1263                        iscsi, strerror ( rc ) );
1264                 return rc;
1265         }
1266         if ( remaining )
1267                 return 0;
1268
1269         /* Process string data and discard string buffer */
1270         if ( ( rc = iscsi_handle_strings ( iscsi, iscsi->rx_buffer,
1271                                            iscsi->rx_len ) ) != 0 )
1272                 return rc;
1273         iscsi_rx_buffered_data_done ( iscsi );
1274
1275         /* Check for login redirection */
1276         if ( response->status_class == ISCSI_STATUS_REDIRECT ) {
1277                 DBGC ( iscsi, "iSCSI %p redirecting to new server\n", iscsi );
1278                 iscsi_close_connection ( iscsi, 0 );
1279                 if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 ) {
1280                         DBGC ( iscsi, "iSCSI %p could not redirect: %s\n ",
1281                                iscsi, strerror ( rc ) );
1282                         return rc;
1283                 }
1284                 return 0;
1285         }
1286
1287         /* Check for fatal errors */
1288         if ( response->status_class != 0 ) {
1289                 DBGC ( iscsi, "iSCSI login failure: class %02x detail %02x\n",
1290                        response->status_class, response->status_detail );
1291                 rc = iscsi_status_to_rc ( response->status_class,
1292                                           response->status_detail );
1293                 return rc;
1294         }
1295
1296         /* Handle login transitions */
1297         if ( response->flags & ISCSI_LOGIN_FLAG_TRANSITION ) {
1298                 iscsi->status &= ~( ISCSI_STATUS_PHASE_MASK |
1299                                     ISCSI_STATUS_STRINGS_MASK );
1300                 switch ( response->flags & ISCSI_LOGIN_NSG_MASK ) {
1301                 case ISCSI_LOGIN_NSG_OPERATIONAL_NEGOTIATION:
1302                         iscsi->status |=
1303                                 ( ISCSI_STATUS_OPERATIONAL_NEGOTIATION_PHASE |
1304                                   ISCSI_STATUS_STRINGS_OPERATIONAL );
1305                         break;
1306                 case ISCSI_LOGIN_NSG_FULL_FEATURE_PHASE:
1307                         iscsi->status |= ISCSI_STATUS_FULL_FEATURE_PHASE;
1308                         break;
1309                 default:
1310                         DBGC ( iscsi, "iSCSI %p got invalid response flags "
1311                                "%02x\n", iscsi, response->flags );
1312                         return -EIO;
1313                 }
1314         }
1315
1316         /* Send next login request PDU if we haven't reached the full
1317          * feature phase yet.
1318          */
1319         if ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) !=
1320              ISCSI_STATUS_FULL_FEATURE_PHASE ) {
1321                 iscsi_start_login ( iscsi );
1322                 return 0;
1323         }
1324
1325         /* Check that target authentication was successful (if required) */
1326         if ( ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_REQUIRED ) &&
1327              ! ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_OK ) ) {
1328                 DBGC ( iscsi, "iSCSI %p nefarious target tried to bypass "
1329                        "authentication\n", iscsi );
1330                 return -EPROTO;
1331         }
1332
1333         /* Notify SCSI layer of window change */
1334         DBGC ( iscsi, "iSCSI %p entering full feature phase\n", iscsi );
1335         xfer_window_changed ( &iscsi->control );
1336
1337         return 0;
1338 }
1339
1340 /****************************************************************************
1341  *
1342  * iSCSI to socket interface
1343  *
1344  */
1345
1346 /**
1347  * Pause TX engine
1348  *
1349  * @v iscsi             iSCSI session
1350  */
1351 static void iscsi_tx_pause ( struct iscsi_session *iscsi ) {
1352         process_del ( &iscsi->process );
1353 }
1354
1355 /**
1356  * Resume TX engine
1357  *
1358  * @v iscsi             iSCSI session
1359  */
1360 static void iscsi_tx_resume ( struct iscsi_session *iscsi ) {
1361         process_add ( &iscsi->process );
1362 }
1363
1364 /**
1365  * Start up a new TX PDU
1366  *
1367  * @v iscsi             iSCSI session
1368  *
1369  * This initiates the process of sending a new PDU.  Only one PDU may
1370  * be in transit at any one time.
1371  */
1372 static void iscsi_start_tx ( struct iscsi_session *iscsi ) {
1373
1374         assert ( iscsi->tx_state == ISCSI_TX_IDLE );
1375
1376         /* Initialise TX BHS */
1377         memset ( &iscsi->tx_bhs, 0, sizeof ( iscsi->tx_bhs ) );
1378
1379         /* Flag TX engine to start transmitting */
1380         iscsi->tx_state = ISCSI_TX_BHS;
1381
1382         /* Start transmission process */
1383         iscsi_tx_resume ( iscsi );
1384 }
1385
1386 /**
1387  * Transmit nothing
1388  *
1389  * @v iscsi             iSCSI session
1390  * @ret rc              Return status code
1391  */
1392 static int iscsi_tx_nothing ( struct iscsi_session *iscsi __unused ) {
1393         return 0;
1394 }
1395
1396 /**
1397  * Transmit basic header segment of an iSCSI PDU
1398  *
1399  * @v iscsi             iSCSI session
1400  * @ret rc              Return status code
1401  */
1402 static int iscsi_tx_bhs ( struct iscsi_session *iscsi ) {
1403         return xfer_deliver_raw ( &iscsi->socket,  &iscsi->tx_bhs,
1404                                   sizeof ( iscsi->tx_bhs ) );
1405 }
1406
1407 /**
1408  * Transmit data segment of an iSCSI PDU
1409  *
1410  * @v iscsi             iSCSI session
1411  * @ret rc              Return status code
1412  * 
1413  * Handle transmission of part of a PDU data segment.  iscsi::tx_bhs
1414  * will be valid when this is called.
1415  */
1416 static int iscsi_tx_data ( struct iscsi_session *iscsi ) {
1417         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
1418
1419         switch ( common->opcode & ISCSI_OPCODE_MASK ) {
1420         case ISCSI_OPCODE_DATA_OUT:
1421                 return iscsi_tx_data_out ( iscsi );
1422         case ISCSI_OPCODE_LOGIN_REQUEST:
1423                 return iscsi_tx_login_request ( iscsi );
1424         default:
1425                 /* Nothing to send in other states */
1426                 return 0;
1427         }
1428 }
1429
1430 /**
1431  * Complete iSCSI PDU transmission
1432  *
1433  * @v iscsi             iSCSI session
1434  *
1435  * Called when a PDU has been completely transmitted and the TX state
1436  * machine is about to enter the idle state.  iscsi::tx_bhs will be
1437  * valid for the just-completed PDU when this is called.
1438  */
1439 static void iscsi_tx_done ( struct iscsi_session *iscsi ) {
1440         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
1441
1442         /* Stop transmission process */
1443         iscsi_tx_pause ( iscsi );
1444
1445         switch ( common->opcode & ISCSI_OPCODE_MASK ) {
1446         case ISCSI_OPCODE_DATA_OUT:
1447                 iscsi_data_out_done ( iscsi );
1448         case ISCSI_OPCODE_LOGIN_REQUEST:
1449                 iscsi_login_request_done ( iscsi );
1450         default:
1451                 /* No action */
1452                 break;
1453         }
1454 }
1455
1456 /**
1457  * Transmit iSCSI PDU
1458  *
1459  * @v iscsi             iSCSI session
1460  * @v buf               Temporary data buffer
1461  * @v len               Length of temporary data buffer
1462  * 
1463  * Constructs data to be sent for the current TX state
1464  */
1465 static void iscsi_tx_step ( struct iscsi_session *iscsi ) {
1466         struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
1467         int ( * tx ) ( struct iscsi_session *iscsi );
1468         enum iscsi_tx_state next_state;
1469         size_t tx_len;
1470         int rc;
1471
1472         /* Select fragment to transmit */
1473         while ( 1 ) {
1474                 switch ( iscsi->tx_state ) {
1475                 case ISCSI_TX_BHS:
1476                         tx = iscsi_tx_bhs;
1477                         tx_len = sizeof ( iscsi->tx_bhs );
1478                         next_state = ISCSI_TX_AHS;
1479                         break;
1480                 case ISCSI_TX_AHS:
1481                         tx = iscsi_tx_nothing;
1482                         tx_len = 0;
1483                         next_state = ISCSI_TX_DATA;
1484                         break;
1485                 case ISCSI_TX_DATA:
1486                         tx = iscsi_tx_data;
1487                         tx_len = ISCSI_DATA_LEN ( common->lengths );
1488                         next_state = ISCSI_TX_IDLE;
1489                         break;
1490                 case ISCSI_TX_IDLE:
1491                         /* Nothing to do; pause processing */
1492                         iscsi_tx_pause ( iscsi );
1493                         return;
1494                 default:
1495                         assert ( 0 );
1496                         return;
1497                 }
1498
1499                 /* Check for window availability, if needed */
1500                 if ( tx_len && ( xfer_window ( &iscsi->socket ) == 0 ) ) {
1501                         /* Cannot transmit at this point; pause
1502                          * processing and wait for window to reopen
1503                          */
1504                         iscsi_tx_pause ( iscsi );
1505                         return;
1506                 }
1507
1508                 /* Transmit data */
1509                 if ( ( rc = tx ( iscsi ) ) != 0 ) {
1510                         DBGC ( iscsi, "iSCSI %p could not transmit: %s\n",
1511                                iscsi, strerror ( rc ) );
1512                         /* Transmission errors are fatal */
1513                         iscsi_close ( iscsi, rc );
1514                         return;
1515                 }
1516
1517                 /* Move to next state */
1518                 iscsi->tx_state = next_state;
1519
1520                 /* If we have moved to the idle state, mark
1521                  * transmission as complete
1522                  */
1523                 if ( iscsi->tx_state == ISCSI_TX_IDLE )
1524                         iscsi_tx_done ( iscsi );
1525         }
1526 }
1527
1528 /** iSCSI TX process descriptor */
1529 static struct process_descriptor iscsi_process_desc =
1530         PROC_DESC ( struct iscsi_session, process, iscsi_tx_step );
1531
1532 /**
1533  * Receive basic header segment of an iSCSI PDU
1534  *
1535  * @v iscsi             iSCSI session
1536  * @v data              Received data
1537  * @v len               Length of received data
1538  * @v remaining         Data remaining after this data
1539  * @ret rc              Return status code
1540  *
1541  * This fills in iscsi::rx_bhs with the data from the BHS portion of
1542  * the received PDU.
1543  */
1544 static int iscsi_rx_bhs ( struct iscsi_session *iscsi, const void *data,
1545                           size_t len, size_t remaining __unused ) {
1546         memcpy ( &iscsi->rx_bhs.bytes[iscsi->rx_offset], data, len );
1547         if ( ( iscsi->rx_offset + len ) >= sizeof ( iscsi->rx_bhs ) ) {
1548                 DBGC2 ( iscsi, "iSCSI %p received PDU opcode %#x len %#x\n",
1549                         iscsi, iscsi->rx_bhs.common.opcode,
1550                         ISCSI_DATA_LEN ( iscsi->rx_bhs.common.lengths ) );
1551         }
1552         return 0;
1553 }
1554
1555 /**
1556  * Discard portion of an iSCSI PDU.
1557  *
1558  * @v iscsi             iSCSI session
1559  * @v data              Received data
1560  * @v len               Length of received data
1561  * @v remaining         Data remaining after this data
1562  * @ret rc              Return status code
1563  *
1564  * This discards data from a portion of a received PDU.
1565  */
1566 static int iscsi_rx_discard ( struct iscsi_session *iscsi __unused,
1567                               const void *data __unused, size_t len __unused,
1568                               size_t remaining __unused ) {
1569         /* Do nothing */
1570         return 0;
1571 }
1572
1573 /**
1574  * Receive data segment of an iSCSI PDU
1575  *
1576  * @v iscsi             iSCSI session
1577  * @v data              Received data
1578  * @v len               Length of received data
1579  * @v remaining         Data remaining after this data
1580  * @ret rc              Return status code
1581  *
1582  * Handle processing of part of a PDU data segment.  iscsi::rx_bhs
1583  * will be valid when this is called.
1584  */
1585 static int iscsi_rx_data ( struct iscsi_session *iscsi, const void *data,
1586                            size_t len, size_t remaining ) {
1587         struct iscsi_bhs_common_response *response
1588                 = &iscsi->rx_bhs.common_response;
1589
1590         /* Update cmdsn and statsn */
1591         iscsi->cmdsn = ntohl ( response->expcmdsn );
1592         iscsi->statsn = ntohl ( response->statsn );
1593
1594         switch ( response->opcode & ISCSI_OPCODE_MASK ) {
1595         case ISCSI_OPCODE_LOGIN_RESPONSE:
1596                 return iscsi_rx_login_response ( iscsi, data, len, remaining );
1597         case ISCSI_OPCODE_SCSI_RESPONSE:
1598                 return iscsi_rx_scsi_response ( iscsi, data, len, remaining );
1599         case ISCSI_OPCODE_DATA_IN:
1600                 return iscsi_rx_data_in ( iscsi, data, len, remaining );
1601         case ISCSI_OPCODE_R2T:
1602                 return iscsi_rx_r2t ( iscsi, data, len, remaining );
1603         case ISCSI_OPCODE_NOP_IN:
1604                 return iscsi_rx_nop_in ( iscsi, data, len, remaining );
1605         default:
1606                 if ( remaining )
1607                         return 0;
1608                 DBGC ( iscsi, "iSCSI %p unknown opcode %02x\n", iscsi,
1609                        response->opcode );
1610                 return -ENOTSUP_OPCODE;
1611         }
1612 }
1613
1614 /**
1615  * Receive new data
1616  *
1617  * @v iscsi             iSCSI session
1618  * @v iobuf             I/O buffer
1619  * @v meta              Data transfer metadata
1620  * @ret rc              Return status code
1621  *
1622  * This handles received PDUs.  The receive strategy is to fill in
1623  * iscsi::rx_bhs with the contents of the BHS portion of the PDU,
1624  * throw away any AHS portion, and then process each part of the data
1625  * portion as it arrives.  The data processing routine therefore
1626  * always has a full copy of the BHS available, even for portions of
1627  * the data in different packets to the BHS.
1628  */
1629 static int iscsi_socket_deliver ( struct iscsi_session *iscsi,
1630                                   struct io_buffer *iobuf,
1631                                   struct xfer_metadata *meta __unused ) {
1632         struct iscsi_bhs_common *common = &iscsi->rx_bhs.common;
1633         int ( * rx ) ( struct iscsi_session *iscsi, const void *data,
1634                        size_t len, size_t remaining );
1635         enum iscsi_rx_state next_state;
1636         size_t frag_len;
1637         size_t remaining;
1638         int rc;
1639
1640         while ( 1 ) {
1641                 switch ( iscsi->rx_state ) {
1642                 case ISCSI_RX_BHS:
1643                         rx = iscsi_rx_bhs;
1644                         iscsi->rx_len = sizeof ( iscsi->rx_bhs );
1645                         next_state = ISCSI_RX_AHS;                      
1646                         break;
1647                 case ISCSI_RX_AHS:
1648                         rx = iscsi_rx_discard;
1649                         iscsi->rx_len = 4 * ISCSI_AHS_LEN ( common->lengths );
1650                         next_state = ISCSI_RX_DATA;
1651                         break;
1652                 case ISCSI_RX_DATA:
1653                         rx = iscsi_rx_data;
1654                         iscsi->rx_len = ISCSI_DATA_LEN ( common->lengths );
1655                         next_state = ISCSI_RX_DATA_PADDING;
1656                         break;
1657                 case ISCSI_RX_DATA_PADDING:
1658                         rx = iscsi_rx_discard;
1659                         iscsi->rx_len = ISCSI_DATA_PAD_LEN ( common->lengths );
1660                         next_state = ISCSI_RX_BHS;
1661                         break;
1662                 default:
1663                         assert ( 0 );
1664                         rc = -EINVAL;
1665                         goto done;
1666                 }
1667
1668                 frag_len = iscsi->rx_len - iscsi->rx_offset;
1669                 if ( frag_len > iob_len ( iobuf ) )
1670                         frag_len = iob_len ( iobuf );
1671                 remaining = iscsi->rx_len - iscsi->rx_offset - frag_len;
1672                 if ( ( rc = rx ( iscsi, iobuf->data, frag_len,
1673                                  remaining ) ) != 0 ) {
1674                         DBGC ( iscsi, "iSCSI %p could not process received "
1675                                "data: %s\n", iscsi, strerror ( rc ) );
1676                         goto done;
1677                 }
1678
1679                 iscsi->rx_offset += frag_len;
1680                 iob_pull ( iobuf, frag_len );
1681
1682                 /* If all the data for this state has not yet been
1683                  * received, stay in this state for now.
1684                  */
1685                 if ( iscsi->rx_offset != iscsi->rx_len ) {
1686                         rc = 0;
1687                         goto done;
1688                 }
1689
1690                 iscsi->rx_state = next_state;
1691                 iscsi->rx_offset = 0;
1692         }
1693
1694  done:
1695         /* Free I/O buffer */
1696         free_iob ( iobuf );
1697
1698         /* Destroy session on error */
1699         if ( rc != 0 )
1700                 iscsi_close ( iscsi, rc );
1701
1702         return rc;
1703 }
1704
1705 /**
1706  * Handle redirection event
1707  *
1708  * @v iscsi             iSCSI session
1709  * @v type              Location type
1710  * @v args              Remaining arguments depend upon location type
1711  * @ret rc              Return status code
1712  */
1713 static int iscsi_vredirect ( struct iscsi_session *iscsi, int type,
1714                              va_list args ) {
1715         va_list tmp;
1716         struct sockaddr *peer;
1717
1718         /* Intercept redirects to a LOCATION_SOCKET and record the IP
1719          * address for the iBFT.  This is a bit of a hack, but avoids
1720          * inventing an ioctl()-style call to retrieve the socket
1721          * address from a data-xfer interface.
1722          */
1723         if ( type == LOCATION_SOCKET ) {
1724                 va_copy ( tmp, args );
1725                 ( void ) va_arg ( tmp, int ); /* Discard "semantics" */
1726                 peer = va_arg ( tmp, struct sockaddr * );
1727                 memcpy ( &iscsi->target_sockaddr, peer,
1728                          sizeof ( iscsi->target_sockaddr ) );
1729                 va_end ( tmp );
1730         }
1731
1732         return xfer_vreopen ( &iscsi->socket, type, args );
1733 }
1734
1735 /** iSCSI socket interface operations */
1736 static struct interface_operation iscsi_socket_operations[] = {
1737         INTF_OP ( xfer_deliver, struct iscsi_session *, iscsi_socket_deliver ),
1738         INTF_OP ( xfer_window_changed, struct iscsi_session *,
1739                   iscsi_tx_resume ),
1740         INTF_OP ( xfer_vredirect, struct iscsi_session *, iscsi_vredirect ),
1741         INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
1742 };
1743
1744 /** iSCSI socket interface descriptor */
1745 static struct interface_descriptor iscsi_socket_desc =
1746         INTF_DESC ( struct iscsi_session, socket, iscsi_socket_operations );
1747
1748 /****************************************************************************
1749  *
1750  * iSCSI command issuing
1751  *
1752  */
1753
1754 /**
1755  * Check iSCSI flow-control window
1756  *
1757  * @v iscsi             iSCSI session
1758  * @ret len             Length of window
1759  */
1760 static size_t iscsi_scsi_window ( struct iscsi_session *iscsi ) {
1761
1762         if ( ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) ==
1763                ISCSI_STATUS_FULL_FEATURE_PHASE ) &&
1764              ( iscsi->command == NULL ) ) {
1765                 /* We cannot handle concurrent commands */
1766                 return 1;
1767         } else {
1768                 return 0;
1769         }
1770 }
1771
1772 /**
1773  * Issue iSCSI SCSI command
1774  *
1775  * @v iscsi             iSCSI session
1776  * @v parent            Parent interface
1777  * @v command           SCSI command
1778  * @ret tag             Command tag, or negative error
1779  */
1780 static int iscsi_scsi_command ( struct iscsi_session *iscsi,
1781                                 struct interface *parent,
1782                                 struct scsi_cmd *command ) {
1783
1784         /* This iSCSI implementation cannot handle multiple concurrent
1785          * commands or commands arriving before login is complete.
1786          */
1787         if ( iscsi_scsi_window ( iscsi ) == 0 ) {
1788                 DBGC ( iscsi, "iSCSI %p cannot handle concurrent commands\n",
1789                        iscsi );
1790                 return -EOPNOTSUPP;
1791         }
1792
1793         /* Store command */
1794         iscsi->command = malloc ( sizeof ( *command ) );
1795         if ( ! iscsi->command )
1796                 return -ENOMEM;
1797         memcpy ( iscsi->command, command, sizeof ( *command ) );
1798
1799         /* Assign new ITT */
1800         iscsi_new_itt ( iscsi );
1801
1802         /* Start sending command */
1803         iscsi_start_command ( iscsi );
1804
1805         /* Attach to parent interface and return */
1806         intf_plug_plug ( &iscsi->data, parent );
1807         return iscsi->itt;
1808 }
1809
1810 /** iSCSI SCSI command-issuing interface operations */
1811 static struct interface_operation iscsi_control_op[] = {
1812         INTF_OP ( scsi_command, struct iscsi_session *, iscsi_scsi_command ),
1813         INTF_OP ( xfer_window, struct iscsi_session *, iscsi_scsi_window ),
1814         INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
1815         INTF_OP ( acpi_describe, struct iscsi_session *, ibft_describe ),
1816 };
1817
1818 /** iSCSI SCSI command-issuing interface descriptor */
1819 static struct interface_descriptor iscsi_control_desc =
1820         INTF_DESC ( struct iscsi_session, control, iscsi_control_op );
1821
1822 /**
1823  * Close iSCSI command
1824  *
1825  * @v iscsi             iSCSI session
1826  * @v rc                Reason for close
1827  */
1828 static void iscsi_command_close ( struct iscsi_session *iscsi, int rc ) {
1829
1830         /* Restart interface */
1831         intf_restart ( &iscsi->data, rc );
1832
1833         /* Treat unsolicited command closures mid-command as fatal,
1834          * because we have no code to handle partially-completed PDUs.
1835          */
1836         if ( iscsi->command != NULL )
1837                 iscsi_close ( iscsi, ( ( rc == 0 ) ? -ECANCELED : rc ) );
1838 }
1839
1840 /** iSCSI SCSI command interface operations */
1841 static struct interface_operation iscsi_data_op[] = {
1842         INTF_OP ( intf_close, struct iscsi_session *, iscsi_command_close ),
1843 };
1844
1845 /** iSCSI SCSI command interface descriptor */
1846 static struct interface_descriptor iscsi_data_desc =
1847         INTF_DESC ( struct iscsi_session, data, iscsi_data_op );
1848
1849 /****************************************************************************
1850  *
1851  * Instantiator
1852  *
1853  */
1854
1855 /** iSCSI root path components (as per RFC4173) */
1856 enum iscsi_root_path_component {
1857         RP_SERVERNAME = 0,
1858         RP_PROTOCOL,
1859         RP_PORT,
1860         RP_LUN,
1861         RP_TARGETNAME,
1862         NUM_RP_COMPONENTS
1863 };
1864
1865 /** iSCSI initiator IQN setting */
1866 const struct setting initiator_iqn_setting __setting ( SETTING_SANBOOT_EXTRA,
1867                                                        initiator-iqn ) = {
1868         .name = "initiator-iqn",
1869         .description = "iSCSI initiator name",
1870         .tag = DHCP_ISCSI_INITIATOR_IQN,
1871         .type = &setting_type_string,
1872 };
1873
1874 /** iSCSI reverse username setting */
1875 const struct setting reverse_username_setting __setting ( SETTING_AUTH_EXTRA,
1876                                                           reverse-username ) = {
1877         .name = "reverse-username",
1878         .description = "Reverse user name",
1879         .tag = DHCP_EB_REVERSE_USERNAME,
1880         .type = &setting_type_string,
1881 };
1882
1883 /** iSCSI reverse password setting */
1884 const struct setting reverse_password_setting __setting ( SETTING_AUTH_EXTRA,
1885                                                           reverse-password ) = {
1886         .name = "reverse-password",
1887         .description = "Reverse password",
1888         .tag = DHCP_EB_REVERSE_PASSWORD,
1889         .type = &setting_type_string,
1890 };
1891
1892 /**
1893  * Parse iSCSI root path
1894  *
1895  * @v iscsi             iSCSI session
1896  * @v root_path         iSCSI root path (as per RFC4173)
1897  * @ret rc              Return status code
1898  */
1899 static int iscsi_parse_root_path ( struct iscsi_session *iscsi,
1900                                    const char *root_path ) {
1901         char rp_copy[ strlen ( root_path ) + 1 ];
1902         char *rp_comp[NUM_RP_COMPONENTS];
1903         char *rp = rp_copy;
1904         int i = 0;
1905         int rc;
1906
1907         /* Split root path into component parts */
1908         strcpy ( rp_copy, root_path );
1909         while ( 1 ) {
1910                 rp_comp[i++] = rp;
1911                 if ( i == NUM_RP_COMPONENTS )
1912                         break;
1913                 for ( ; *rp != ':' ; rp++ ) {
1914                         if ( ! *rp ) {
1915                                 DBGC ( iscsi, "iSCSI %p root path \"%s\" "
1916                                        "too short\n", iscsi, root_path );
1917                                 return -EINVAL_ROOT_PATH_TOO_SHORT;
1918                         }
1919                 }
1920                 *(rp++) = '\0';
1921         }
1922
1923         /* Use root path components to configure iSCSI session */
1924         iscsi->target_address = strdup ( rp_comp[RP_SERVERNAME] );
1925         if ( ! iscsi->target_address )
1926                 return -ENOMEM;
1927         iscsi->target_port = strtoul ( rp_comp[RP_PORT], NULL, 10 );
1928         if ( ! iscsi->target_port )
1929                 iscsi->target_port = ISCSI_PORT;
1930         if ( ( rc = scsi_parse_lun ( rp_comp[RP_LUN], &iscsi->lun ) ) != 0 ) {
1931                 DBGC ( iscsi, "iSCSI %p invalid LUN \"%s\"\n",
1932                        iscsi, rp_comp[RP_LUN] );
1933                 return rc;
1934         }
1935         iscsi->target_iqn = strdup ( rp_comp[RP_TARGETNAME] );
1936         if ( ! iscsi->target_iqn )
1937                 return -ENOMEM;
1938
1939         return 0;
1940 }
1941
1942 /**
1943  * Fetch iSCSI settings
1944  *
1945  * @v iscsi             iSCSI session
1946  * @ret rc              Return status code
1947  */
1948 static int iscsi_fetch_settings ( struct iscsi_session *iscsi ) {
1949         char *hostname;
1950         union uuid uuid;
1951         int len;
1952
1953         /* Fetch relevant settings.  Don't worry about freeing on
1954          * error, since iscsi_free() will take care of that anyway.
1955          */
1956         fetch_string_setting_copy ( NULL, &username_setting,
1957                                     &iscsi->initiator_username );
1958         fetch_string_setting_copy ( NULL, &password_setting,
1959                                     &iscsi->initiator_password );
1960         fetch_string_setting_copy ( NULL, &reverse_username_setting,
1961                                     &iscsi->target_username );
1962         fetch_string_setting_copy ( NULL, &reverse_password_setting,
1963                                     &iscsi->target_password );
1964
1965         /* Use explicit initiator IQN if provided */
1966         fetch_string_setting_copy ( NULL, &initiator_iqn_setting,
1967                                     &iscsi->initiator_iqn );
1968         if ( iscsi->initiator_iqn )
1969                 return 0;
1970
1971         /* Otherwise, try to construct an initiator IQN from the hostname */
1972         fetch_string_setting_copy ( NULL, &hostname_setting, &hostname );
1973         if ( hostname ) {
1974                 len = asprintf ( &iscsi->initiator_iqn,
1975                                  ISCSI_DEFAULT_IQN_PREFIX ":%s", hostname );
1976                 free ( hostname );
1977                 if ( len < 0 ) {
1978                         DBGC ( iscsi, "iSCSI %p could not allocate initiator "
1979                                "IQN\n", iscsi );
1980                         return -ENOMEM;
1981                 }
1982                 assert ( iscsi->initiator_iqn );
1983                 return 0;
1984         }
1985
1986         /* Otherwise, try to construct an initiator IQN from the UUID */
1987         if ( ( len = fetch_uuid_setting ( NULL, &uuid_setting, &uuid ) ) < 0 ) {
1988                 DBGC ( iscsi, "iSCSI %p has no suitable initiator IQN\n",
1989                        iscsi );
1990                 return -EINVAL_NO_INITIATOR_IQN;
1991         }
1992         if ( ( len = asprintf ( &iscsi->initiator_iqn,
1993                                 ISCSI_DEFAULT_IQN_PREFIX ":%s",
1994                                 uuid_ntoa ( &uuid ) ) ) < 0 ) {
1995                 DBGC ( iscsi, "iSCSI %p could not allocate initiator IQN\n",
1996                        iscsi );
1997                 return -ENOMEM;
1998         }
1999         assert ( iscsi->initiator_iqn );
2000
2001         return 0;
2002 }
2003
2004
2005 /**
2006  * Check iSCSI authentication details
2007  *
2008  * @v iscsi             iSCSI session
2009  * @ret rc              Return status code
2010  */
2011 static int iscsi_check_auth ( struct iscsi_session *iscsi ) {
2012
2013         /* Check for invalid authentication combinations */
2014         if ( ( /* Initiator username without password (or vice-versa) */
2015                 ( !! iscsi->initiator_username ) ^
2016                 ( !! iscsi->initiator_password ) ) ||
2017              ( /* Target username without password (or vice-versa) */
2018                 ( !! iscsi->target_username ) ^
2019                 ( !! iscsi->target_password ) ) ||
2020              ( /* Target (reverse) without initiator (forward) */
2021                 ( iscsi->target_username &&
2022                   ( ! iscsi->initiator_username ) ) ) ) {
2023                 DBGC ( iscsi, "iSCSI %p invalid credentials: initiator "
2024                        "%sname,%spw, target %sname,%spw\n", iscsi,
2025                        ( iscsi->initiator_username ? "" : "no " ),
2026                        ( iscsi->initiator_password ? "" : "no " ),
2027                        ( iscsi->target_username ? "" : "no " ),
2028                        ( iscsi->target_password ? "" : "no " ) );
2029                 return -EINVAL_BAD_CREDENTIAL_MIX;
2030         }
2031
2032         return 0;
2033 }
2034
2035 /**
2036  * Open iSCSI URI
2037  *
2038  * @v parent            Parent interface
2039  * @v uri               URI
2040  * @ret rc              Return status code
2041  */
2042 static int iscsi_open ( struct interface *parent, struct uri *uri ) {
2043         struct iscsi_session *iscsi;
2044         int rc;
2045
2046         /* Sanity check */
2047         if ( ! uri->opaque ) {
2048                 rc = -EINVAL_NO_ROOT_PATH;
2049                 goto err_sanity_uri;
2050         }
2051
2052         /* Allocate and initialise structure */
2053         iscsi = zalloc ( sizeof ( *iscsi ) );
2054         if ( ! iscsi ) {
2055                 rc = -ENOMEM;
2056                 goto err_zalloc;
2057         }
2058         ref_init ( &iscsi->refcnt, iscsi_free );
2059         intf_init ( &iscsi->control, &iscsi_control_desc, &iscsi->refcnt );
2060         intf_init ( &iscsi->data, &iscsi_data_desc, &iscsi->refcnt );
2061         intf_init ( &iscsi->socket, &iscsi_socket_desc, &iscsi->refcnt );
2062         process_init_stopped ( &iscsi->process, &iscsi_process_desc,
2063                                &iscsi->refcnt );
2064
2065         /* Parse root path */
2066         if ( ( rc = iscsi_parse_root_path ( iscsi, uri->opaque ) ) != 0 )
2067                 goto err_parse_root_path;
2068         /* Set fields not specified by root path */
2069         if ( ( rc = iscsi_fetch_settings ( iscsi ) ) != 0 )
2070                 goto err_fetch_settings;
2071         /* Validate authentication */
2072         if ( ( rc = iscsi_check_auth ( iscsi ) ) != 0 )
2073                 goto err_check_auth;
2074
2075         /* Sanity checks */
2076         if ( ! iscsi->target_address ) {
2077                 DBGC ( iscsi, "iSCSI %p does not yet support discovery\n",
2078                        iscsi );
2079                 rc = -ENOTSUP_DISCOVERY;
2080                 goto err_sanity_address;
2081         }
2082         if ( ! iscsi->target_iqn ) {
2083                 DBGC ( iscsi, "iSCSI %p no target address supplied in %s\n",
2084                        iscsi, uri->opaque );
2085                 rc = -EINVAL_NO_TARGET_IQN;
2086                 goto err_sanity_iqn;
2087         }
2088         DBGC ( iscsi, "iSCSI %p initiator %s\n",iscsi, iscsi->initiator_iqn );
2089         DBGC ( iscsi, "iSCSI %p target %s %s\n",
2090                iscsi, iscsi->target_address, iscsi->target_iqn );
2091
2092         /* Open socket */
2093         if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 )
2094                 goto err_open_connection;
2095
2096         /* Attach SCSI device to parent interface */
2097         if ( ( rc = scsi_open ( parent, &iscsi->control,
2098                                 &iscsi->lun ) ) != 0 ) {
2099                 DBGC ( iscsi, "iSCSI %p could not create SCSI device: %s\n",
2100                        iscsi, strerror ( rc ) );
2101                 goto err_scsi_open;
2102         }
2103
2104         /* Mortalise self, and return */
2105         ref_put ( &iscsi->refcnt );
2106         return 0;
2107         
2108  err_scsi_open:
2109  err_open_connection:
2110  err_sanity_iqn:
2111  err_sanity_address:
2112  err_check_auth:
2113  err_fetch_settings:
2114  err_parse_root_path:
2115         iscsi_close ( iscsi, rc );
2116         ref_put ( &iscsi->refcnt );
2117  err_zalloc:
2118  err_sanity_uri:
2119         return rc;
2120 }
2121
2122 /** iSCSI URI opener */
2123 struct uri_opener iscsi_uri_opener __uri_opener = {
2124         .scheme = "iscsi",
2125         .open = iscsi_open,
2126 };