1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/cpuvar.h>
27 #include <sys/types.h>
28 #include <sys/conf.h>
29 #include <sys/file.h>
30 #include <sys/ddi.h>
31 #include <sys/sunddi.h>
32 #include <sys/modctl.h>
33 
34 #include <sys/socket.h>
35 #include <sys/strsubr.h>
36 #include <sys/sysmacros.h>
37 #include <sys/note.h>
38 #include <sys/sdt.h>
39 
40 #include <sys/stmf.h>
41 #include <sys/stmf_ioctl.h>
42 #include <sys/portif.h>
43 #include <sys/idm/idm.h>
44 #include <sys/idm/idm_text.h>
45 
46 #define	ISCSIT_LOGIN_SM_STRINGS
47 #include <iscsit.h>
48 #include <iscsit_auth.h>
49 
50 typedef struct {
51 	list_node_t		le_ctx_node;
52 	iscsit_login_event_t	le_ctx_event;
53 	idm_pdu_t		*le_pdu;
54 } login_event_ctx_t;
55 
56 #ifndef TRUE
57 #define	TRUE B_TRUE
58 #endif
59 
60 #ifndef FALSE
61 #define	FALSE B_FALSE
62 #endif
63 
64 #define	DEFAULT_RADIUS_PORT	1812
65 
66 static void
67 login_sm_complete(void *ict_void);
68 
69 static void
70 login_sm_event_dispatch(iscsit_conn_login_t *lsm, iscsit_conn_t *ict,
71     login_event_ctx_t *ctx);
72 
73 static void
74 login_sm_init(iscsit_conn_t *ict, login_event_ctx_t *ctx);
75 
76 static void
77 login_sm_waiting(iscsit_conn_t *ict, login_event_ctx_t *ctx);
78 
79 static void
80 login_sm_processing(iscsit_conn_t *ict, login_event_ctx_t *ctx);
81 
82 static void
83 login_sm_responding(iscsit_conn_t *ict, login_event_ctx_t *ctx);
84 
85 static void
86 login_sm_responded(iscsit_conn_t *ict, login_event_ctx_t *ctx);
87 
88 static void
89 login_sm_ffp(iscsit_conn_t *ict, login_event_ctx_t *ctx);
90 
91 static void
92 login_sm_done(iscsit_conn_t *ict, login_event_ctx_t *ctx);
93 
94 static void
95 login_sm_error(iscsit_conn_t *ict, login_event_ctx_t *ctx);
96 
97 static void
98 login_sm_new_state(iscsit_conn_t *ict, login_event_ctx_t *ctx,
99     iscsit_login_state_t new_state);
100 
101 static void
102 login_sm_send_ack(iscsit_conn_t *ict, idm_pdu_t *pdu);
103 
104 static idm_status_t
105 login_sm_validate_ack(iscsit_conn_t *ict, idm_pdu_t *pdu);
106 
107 static boolean_t
108 login_sm_is_last_response(idm_pdu_t *pdu);
109 
110 static void
111 login_sm_handle_initial_login(iscsit_conn_t *ict, idm_pdu_t *pdu);
112 
113 static void
114 login_sm_send_next_response(iscsit_conn_t *ict, idm_pdu_t *pdu);
115 
116 static void
117 login_sm_process_request(iscsit_conn_t *ict);
118 
119 static idm_status_t
120 login_sm_req_pdu_check(iscsit_conn_t *ict, idm_pdu_t *pdu);
121 
122 static idm_status_t
123 login_sm_process_nvlist(iscsit_conn_t *ict);
124 
125 static idm_status_t
126 login_sm_check_security(iscsit_conn_t *ict);
127 
128 static idm_pdu_t *
129 login_sm_build_login_response(iscsit_conn_t *ict);
130 
131 static void
132 login_sm_ffp_actions(iscsit_conn_t *ict);
133 
134 static idm_status_t
135 login_sm_validate_initial_parameters(iscsit_conn_t *ict);
136 
137 static idm_status_t
138 login_sm_session_bind(iscsit_conn_t *ict);
139 
140 static idm_status_t
141 login_sm_set_auth(iscsit_conn_t *ict);
142 
143 static idm_status_t
144 login_sm_session_register(iscsit_conn_t *ict);
145 
146 static kv_status_t
147 iscsit_handle_key(iscsit_conn_t *ict, nvpair_t *nvp, char *nvp_name);
148 
149 static kv_status_t
150 iscsit_handle_common_key(iscsit_conn_t *ict, nvpair_t *nvp,
151     const idm_kv_xlate_t *ikvx);
152 
153 static kv_status_t
154 iscsit_handle_security_key(iscsit_conn_t *ict, nvpair_t *nvp,
155     const idm_kv_xlate_t *ikvx);
156 
157 static kv_status_t
158 iscsit_reply_security_key(iscsit_conn_t *ict);
159 
160 static kv_status_t
161 iscsit_handle_operational_key(iscsit_conn_t *ict, nvpair_t *nvp,
162     const idm_kv_xlate_t *ikvx);
163 
164 static kv_status_t
165 iscsit_reply_numerical(iscsit_conn_t *ict,
166     const char *nvp_name, const uint64_t value);
167 
168 static kv_status_t
169 iscsit_reply_string(iscsit_conn_t *ict,
170     const char *nvp_name, const char *text);
171 
172 static kv_status_t
173 iscsit_handle_digest(iscsit_conn_t *ict, nvpair_t *choices,
174     const idm_kv_xlate_t *ikvx);
175 
176 static kv_status_t
177 iscsit_handle_boolean(iscsit_conn_t *ict, nvpair_t *nvp, boolean_t value,
178     const idm_kv_xlate_t *ikvx, boolean_t iscsit_value);
179 
180 static kv_status_t
181 iscsit_handle_numerical(iscsit_conn_t *ict, nvpair_t *nvp, uint64_t value,
182     const idm_kv_xlate_t *ikvx,
183     uint64_t iscsi_min_value, uint64_t iscsi_max_value,
184     uint64_t iscsit_max_value);
185 
186 static void
187 iscsit_process_negotiated_values(iscsit_conn_t *ict);
188 
189 static void
190 login_resp_complete_cb(idm_pdu_t *pdu, idm_status_t status);
191 
192 static idm_status_t
193 iscsit_add_declarative_keys(iscsit_conn_t *ict);
194 
195 uint64_t max_dataseglen_target = ISCSIT_MAX_RECV_DATA_SEGMENT_LENGTH;
196 
197 idm_status_t
198 iscsit_login_sm_init(iscsit_conn_t *ict)
199 {
200 	iscsit_conn_login_t *lsm = &ict->ict_login_sm;
201 
202 	bzero(lsm, sizeof (iscsit_conn_login_t));
203 
204 	(void) nvlist_alloc(&lsm->icl_negotiated_values, NV_UNIQUE_NAME,
205 	    KM_SLEEP);
206 
207 	/*
208 	 * Hold connection until the login state machine completes
209 	 */
210 	iscsit_conn_hold(ict);
211 
212 	/*
213 	 * Pre-allocating a login response PDU means we will always be
214 	 * able to respond to a login request -- even if we can't allocate
215 	 * a data buffer to hold the text responses we can at least send
216 	 * a login failure.
217 	 */
218 	lsm->icl_login_resp_tmpl = kmem_zalloc(sizeof (iscsi_login_rsp_hdr_t),
219 	    KM_SLEEP);
220 
221 	idm_sm_audit_init(&lsm->icl_state_audit);
222 	mutex_init(&lsm->icl_mutex, NULL, MUTEX_DEFAULT, NULL);
223 	list_create(&lsm->icl_login_events, sizeof (login_event_ctx_t),
224 	    offsetof(login_event_ctx_t, le_ctx_node));
225 	list_create(&lsm->icl_pdu_list, sizeof (idm_pdu_t),
226 	    offsetof(idm_pdu_t, isp_client_lnd));
227 
228 	lsm->icl_login_state = ILS_LOGIN_INIT;
229 	lsm->icl_login_last_state = ILS_LOGIN_INIT;
230 
231 	/*
232 	 * Initialize operational parameters to default values.  Anything
233 	 * we don't specifically negotiate stays at the default.
234 	 */
235 	ict->ict_op.op_discovery_session = B_FALSE;
236 	ict->ict_op.op_initial_r2t = ISCSI_DEFAULT_INITIALR2T;
237 	ict->ict_op.op_immed_data = ISCSI_DEFAULT_IMMEDIATE_DATA;
238 	ict->ict_op.op_data_pdu_in_order = ISCSI_DEFAULT_DATA_PDU_IN_ORDER;
239 	ict->ict_op.op_data_sequence_in_order =
240 	    ISCSI_DEFAULT_DATA_SEQUENCE_IN_ORDER;
241 	ict->ict_op.op_max_connections = ISCSI_DEFAULT_MAX_CONNECTIONS;
242 	ict->ict_op.op_max_recv_data_segment_length =
243 	    ISCSI_DEFAULT_MAX_RECV_SEG_LEN;
244 	ict->ict_op.op_max_burst_length = ISCSI_DEFAULT_MAX_BURST_LENGTH;
245 	ict->ict_op.op_first_burst_length = ISCSI_DEFAULT_FIRST_BURST_LENGTH;
246 	ict->ict_op.op_default_time_2_wait = ISCSI_DEFAULT_TIME_TO_WAIT;
247 	ict->ict_op.op_default_time_2_retain = ISCSI_DEFAULT_TIME_TO_RETAIN;
248 	ict->ict_op.op_max_outstanding_r2t = ISCSI_DEFAULT_MAX_OUT_R2T;
249 	ict->ict_op.op_error_recovery_level =
250 	    ISCSI_DEFAULT_ERROR_RECOVERY_LEVEL;
251 
252 	return (IDM_STATUS_SUCCESS);
253 }
254 
255 static void
256 login_resp_complete_cb(idm_pdu_t *pdu, idm_status_t status)
257 {
258 	iscsit_conn_t *ict = pdu->isp_private;
259 
260 	/*
261 	 * Check that this is a login pdu
262 	 */
263 	ASSERT((pdu->isp_flags & IDM_PDU_LOGIN_TX) != 0);
264 	idm_pdu_free(pdu);
265 
266 	if ((status != IDM_STATUS_SUCCESS) ||
267 	    (ict->ict_login_sm.icl_login_resp_err_class != 0)) {
268 		/*
269 		 * Transport or login error occurred.
270 		 */
271 		iscsit_login_sm_event(ict, ILE_LOGIN_ERROR, NULL);
272 	}
273 	iscsit_conn_rele(ict);
274 }
275 
276 void
277 iscsit_login_sm_fini(iscsit_conn_t *ict)
278 {
279 	iscsit_conn_login_t *lsm = &ict->ict_login_sm;
280 
281 	mutex_enter(&lsm->icl_mutex);
282 	list_destroy(&lsm->icl_pdu_list);
283 	list_destroy(&lsm->icl_login_events);
284 
285 	kmem_free(lsm->icl_login_resp_tmpl, sizeof (iscsi_login_rsp_hdr_t));
286 
287 	/* clean up the login response idm text buffer */
288 	if (lsm->icl_login_resp_itb != NULL) {
289 		idm_itextbuf_free(lsm->icl_login_resp_itb);
290 		lsm->icl_login_resp_itb = NULL;
291 	}
292 
293 	nvlist_free(lsm->icl_negotiated_values);
294 	mutex_destroy(&lsm->icl_mutex);
295 }
296 
297 void
298 iscsit_login_sm_event(iscsit_conn_t *ict, iscsit_login_event_t event,
299     idm_pdu_t *pdu)
300 {
301 	/*
302 	 * This is a bit ugly but if we're already in ILS_LOGIN_ERROR
303 	 * or ILS_LOGIN_DONE then just drop any additional events.  They
304 	 * won't change the state and it's possible we've already called
305 	 * iscsit_login_sm_fini in which case the mutex is destroyed.
306 	 */
307 	if ((ict->ict_login_sm.icl_login_state == ILS_LOGIN_ERROR) ||
308 	    (ict->ict_login_sm.icl_login_state == ILS_LOGIN_DONE))
309 		return;
310 
311 	mutex_enter(&ict->ict_login_sm.icl_mutex);
312 	iscsit_login_sm_event_locked(ict, event, pdu);
313 	mutex_exit(&ict->ict_login_sm.icl_mutex);
314 }
315 void
316 iscsit_login_sm_event_locked(iscsit_conn_t *ict, iscsit_login_event_t event,
317     idm_pdu_t *pdu)
318 {
319 	iscsit_conn_login_t *lsm = &ict->ict_login_sm;
320 	login_event_ctx_t *ctx;
321 
322 	ASSERT(mutex_owned(&lsm->icl_mutex));
323 	ctx = kmem_zalloc(sizeof (*ctx), KM_SLEEP);
324 
325 	ctx->le_ctx_event = event;
326 	ctx->le_pdu = pdu;
327 
328 	list_insert_tail(&lsm->icl_login_events, ctx);
329 
330 	/*
331 	 * Use the icl_busy flag to keep the state machine single threaded.
332 	 * This also serves as recursion avoidance since this flag will
333 	 * always be set if we call login_sm_event from within the
334 	 * state machine code.
335 	 */
336 	if (!lsm->icl_busy) {
337 		lsm->icl_busy = B_TRUE;
338 		while (!list_is_empty(&lsm->icl_login_events)) {
339 			ctx = list_head(&lsm->icl_login_events);
340 			list_remove(&lsm->icl_login_events, ctx);
341 			idm_sm_audit_event(&lsm->icl_state_audit,
342 			    SAS_ISCSIT_LOGIN, (int)lsm->icl_login_state,
343 			    (int)ctx->le_ctx_event, (uintptr_t)pdu);
344 
345 			/*
346 			 * If the lsm is in a terminal state, just drain
347 			 * any remaining events.
348 			 */
349 			if ((lsm->icl_login_state == ILS_LOGIN_ERROR) ||
350 			    (lsm->icl_login_state == ILS_LOGIN_DONE)) {
351 				kmem_free(ctx, sizeof (*ctx));
352 				continue;
353 			}
354 			mutex_exit(&lsm->icl_mutex);
355 			login_sm_event_dispatch(lsm, ict, ctx);
356 			mutex_enter(&lsm->icl_mutex);
357 		}
358 		lsm->icl_busy = B_FALSE;
359 
360 		/*
361 		 * When the state machine reaches ILS_LOGIN_DONE or
362 		 * ILS_LOGIN_ERROR state the login process has completed
363 		 * and it's time to cleanup.  The state machine code will
364 		 * mark itself "complete" when this happens.
365 		 *
366 		 * To protect against spurious events (which shouldn't
367 		 * happen) set icl_busy again.
368 		 */
369 		if (lsm->icl_login_complete) {
370 			lsm->icl_busy = B_TRUE;
371 			if (taskq_dispatch(iscsit_global.global_dispatch_taskq,
372 			    login_sm_complete, ict, DDI_SLEEP) == NULL) {
373 				cmn_err(CE_WARN, "iscsit_login_sm_event_locked:"
374 				    " Failed to dispatch task");
375 			}
376 		}
377 	}
378 }
379 
380 static void
381 login_sm_complete(void *ict_void)
382 {
383 	iscsit_conn_t *ict = ict_void;
384 
385 	/*
386 	 * State machine has run to completion, resources
387 	 * will be cleaned up when connection is destroyed.
388 	 */
389 	iscsit_conn_rele(ict);
390 }
391 
392 static void
393 login_sm_event_dispatch(iscsit_conn_login_t *lsm, iscsit_conn_t *ict,
394     login_event_ctx_t *ctx)
395 {
396 	idm_pdu_t *pdu = ctx->le_pdu; /* Only valid for some events */
397 
398 	DTRACE_PROBE2(login__event, iscsit_conn_t *, ict,
399 	    login_event_ctx_t *, ctx);
400 
401 	IDM_SM_LOG(CE_NOTE, "login_sm_event_dispatch: ict %p event %s(%d)",
402 	    (void *)ict,
403 	    iscsit_ile_name[ctx->le_ctx_event], ctx->le_ctx_event);
404 
405 	/* State independent actions */
406 	switch (ctx->le_ctx_event) {
407 	case ILE_LOGIN_RCV:
408 		/* Perform basic sanity checks on the header */
409 		if (login_sm_req_pdu_check(ict, pdu) != IDM_STATUS_SUCCESS) {
410 			idm_pdu_t *rpdu;
411 
412 			SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
413 			    ISCSI_LOGIN_STATUS_INVALID_REQUEST);
414 			/*
415 			 * If we haven't processed any PDU's yet then use
416 			 * this one as a template for the response
417 			 */
418 			if (ict->ict_login_sm.icl_login_resp_tmpl->opcode == 0)
419 				login_sm_handle_initial_login(ict, pdu);
420 			rpdu = login_sm_build_login_response(ict);
421 			login_sm_send_next_response(ict, rpdu);
422 			idm_pdu_complete(pdu, IDM_STATUS_SUCCESS);
423 			kmem_free(ctx, sizeof (*ctx));
424 			return;
425 		}
426 		break;
427 	default:
428 		break;
429 	}
430 
431 	/* State dependent actions */
432 	switch (lsm->icl_login_state) {
433 	case ILS_LOGIN_INIT:
434 		login_sm_init(ict, ctx);
435 		break;
436 	case ILS_LOGIN_WAITING:
437 		login_sm_waiting(ict, ctx);
438 		break;
439 	case ILS_LOGIN_PROCESSING:
440 		login_sm_processing(ict, ctx);
441 		break;
442 	case ILS_LOGIN_RESPONDING:
443 		login_sm_responding(ict, ctx);
444 		break;
445 	case ILS_LOGIN_RESPONDED:
446 		login_sm_responded(ict, ctx);
447 		break;
448 	case ILS_LOGIN_FFP:
449 		login_sm_ffp(ict, ctx);
450 		break;
451 	case ILS_LOGIN_DONE:
452 		login_sm_done(ict, ctx);
453 		break;
454 	case ILS_LOGIN_ERROR:
455 		login_sm_error(ict, ctx);
456 		break;
457 	}
458 
459 	kmem_free(ctx, sizeof (*ctx));
460 }
461 
462 static void
463 login_sm_init(iscsit_conn_t *ict, login_event_ctx_t *ctx)
464 {
465 	idm_pdu_t *pdu;
466 
467 	switch (ctx->le_ctx_event) {
468 	case ILE_LOGIN_RCV:
469 		pdu = ctx->le_pdu;
470 
471 		/*
472 		 * This is the first login PDU we've received so use
473 		 * it to build the login response template and set our CSG.
474 		 */
475 		login_sm_handle_initial_login(ict, pdu);
476 
477 		/*
478 		 * Accumulate all the login PDU's that make up this
479 		 * request on a queue.
480 		 */
481 		mutex_enter(&ict->ict_login_sm.icl_mutex);
482 		list_insert_tail(&ict->ict_login_sm.icl_pdu_list, pdu);
483 		mutex_exit(&ict->ict_login_sm.icl_mutex);
484 
485 		if (pdu->isp_hdr->flags & ISCSI_FLAG_LOGIN_CONTINUE) {
486 			login_sm_send_ack(ict, pdu);
487 			login_sm_new_state(ict, ctx, ILS_LOGIN_WAITING);
488 		} else {
489 			login_sm_new_state(ict, ctx, ILS_LOGIN_PROCESSING);
490 		}
491 		break;
492 	case ILE_LOGIN_CONN_ERROR:
493 	case ILE_LOGIN_ERROR:
494 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
495 		break;
496 	default:
497 		ASSERT(0);
498 	}
499 }
500 
501 static void
502 login_sm_waiting(iscsit_conn_t *ict, login_event_ctx_t *ctx)
503 {
504 	idm_pdu_t *pdu;
505 
506 	switch (ctx->le_ctx_event) {
507 	case ILE_LOGIN_RCV:
508 		pdu = ctx->le_pdu;
509 		mutex_enter(&ict->ict_login_sm.icl_mutex);
510 		list_insert_tail(&ict->ict_login_sm.icl_pdu_list, pdu);
511 		mutex_exit(&ict->ict_login_sm.icl_mutex);
512 		if (!(pdu->isp_hdr->flags & ISCSI_FLAG_LOGIN_CONTINUE)) {
513 			login_sm_new_state(ict, ctx, ILS_LOGIN_PROCESSING);
514 		} else {
515 			login_sm_send_ack(ict, pdu);
516 		}
517 		break;
518 	case ILE_LOGIN_ERROR:
519 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
520 		break;
521 	case ILE_LOGIN_RESP_COMPLETE:
522 		break;
523 	default:
524 		ASSERT(0);
525 	}
526 }
527 
528 static void
529 login_sm_processing(iscsit_conn_t *ict, login_event_ctx_t *ctx)
530 {
531 	switch (ctx->le_ctx_event) {
532 	case ILE_LOGIN_RESP_READY:
533 		login_sm_new_state(ict, ctx, ILS_LOGIN_RESPONDING);
534 		break;
535 	case ILE_LOGIN_RCV:
536 		idm_pdu_complete(ctx->le_pdu, IDM_STATUS_SUCCESS);
537 		/*FALLTHROUGH*/
538 	case ILE_LOGIN_CONN_ERROR:
539 	case ILE_LOGIN_ERROR:
540 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
541 		break;
542 	default:
543 		ASSERT(0);
544 	}
545 }
546 
547 static void
548 login_sm_responding(iscsit_conn_t *ict, login_event_ctx_t *ctx)
549 {
550 	idm_pdu_t *pdu, *rpdu;
551 
552 	switch (ctx->le_ctx_event) {
553 	case ILE_LOGIN_RCV:
554 		pdu = ctx->le_pdu;
555 		/*
556 		 * We should only be in "responding" state if we have not
557 		 * sent the last PDU of a multi-PDU login response sequence.
558 		 * In that case we expect this received PDU to be an
559 		 * acknowledgement from the initiator (login PDU with C
560 		 * bit cleared and no data).  If it's the acknowledgement
561 		 * we are expecting then we send the next PDU in the login
562 		 * response sequence.  Otherwise it's a protocol error and
563 		 * the login fails.
564 		 */
565 		if (login_sm_validate_ack(ict, pdu) == IDM_STATUS_SUCCESS) {
566 			rpdu = login_sm_build_login_response(ict);
567 			login_sm_send_next_response(ict, rpdu);
568 		} else {
569 			login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
570 		}
571 		idm_pdu_complete(pdu, IDM_STATUS_SUCCESS);
572 		break;
573 	case ILE_LOGIN_FFP:
574 		login_sm_new_state(ict, ctx, ILS_LOGIN_FFP);
575 		break;
576 	case ILE_LOGIN_RESP_COMPLETE:
577 		login_sm_new_state(ict, ctx, ILS_LOGIN_RESPONDED);
578 		break;
579 	case ILE_LOGIN_CONN_ERROR:
580 	case ILE_LOGIN_ERROR:
581 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
582 		break;
583 	default:
584 		ASSERT(0);
585 	}
586 }
587 
588 static void
589 login_sm_responded(iscsit_conn_t *ict, login_event_ctx_t *ctx)
590 {
591 	idm_pdu_t		*pdu;
592 	iscsi_login_hdr_t	*lh;
593 
594 	switch (ctx->le_ctx_event) {
595 	case ILE_LOGIN_RCV:
596 		pdu = ctx->le_pdu;
597 		lh = (iscsi_login_hdr_t *)pdu->isp_hdr;
598 		/*
599 		 * Set the CSG, NSG and Transit bits based on the this PDU.
600 		 * The CSG already validated in login_sm_req_pdu_check().
601 		 * We'll clear the transit bit if we encounter any login
602 		 * parameters in the request that required an additional
603 		 * login transfer (i.e. no acceptable
604 		 * choices in range or we needed to change a boolean
605 		 * value from "Yes" to "No").
606 		 */
607 		ict->ict_login_sm.icl_login_csg =
608 		    ISCSI_LOGIN_CURRENT_STAGE(lh->flags);
609 		ict->ict_login_sm.icl_login_nsg =
610 		    ISCSI_LOGIN_NEXT_STAGE(lh->flags);
611 		ict->ict_login_sm.icl_login_transit =
612 		    lh->flags & ISCSI_FLAG_LOGIN_TRANSIT;
613 		mutex_enter(&ict->ict_login_sm.icl_mutex);
614 		list_insert_tail(&ict->ict_login_sm.icl_pdu_list, pdu);
615 		mutex_exit(&ict->ict_login_sm.icl_mutex);
616 		if (pdu->isp_hdr->flags & ISCSI_FLAG_LOGIN_CONTINUE) {
617 			login_sm_send_ack(ict, pdu);
618 			login_sm_new_state(ict, ctx, ILS_LOGIN_WAITING);
619 		} else {
620 			login_sm_new_state(ict, ctx, ILS_LOGIN_PROCESSING);
621 		}
622 		break;
623 	case ILE_LOGIN_CONN_ERROR:
624 	case ILE_LOGIN_ERROR:
625 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
626 		break;
627 	default:
628 		ASSERT(0);
629 	}
630 }
631 
632 static void
633 login_sm_ffp(iscsit_conn_t *ict, login_event_ctx_t *ctx)
634 {
635 	switch (ctx->le_ctx_event) {
636 	case ILE_LOGIN_RESP_COMPLETE:
637 		login_sm_new_state(ict, ctx, ILS_LOGIN_DONE);
638 		break;
639 	case ILE_LOGIN_CONN_ERROR:
640 	case ILE_LOGIN_ERROR:
641 		login_sm_new_state(ict, ctx, ILS_LOGIN_ERROR);
642 		break;
643 	default:
644 		ASSERT(0);
645 	}
646 
647 }
648 
649 /*ARGSUSED*/
650 static void
651 login_sm_done(iscsit_conn_t *ict, login_event_ctx_t *ctx)
652 {
653 	/* Terminal state, we should get no events */
654 	switch (ctx->le_ctx_event) {
655 	case ILE_LOGIN_RCV:
656 		/*
657 		 * We've already processed everything we're going to
658 		 * process.  Drop any additional login PDU's.
659 		 */
660 		idm_pdu_complete(ctx->le_pdu, IDM_STATUS_SUCCESS);
661 		break;
662 	case ILE_LOGIN_CONN_ERROR:
663 		/* Don't care */
664 		break;
665 	default:
666 		ASSERT(0);
667 	}
668 }
669 
670 /*ARGSUSED*/
671 static void
672 login_sm_error(iscsit_conn_t *ict, login_event_ctx_t *ctx)
673 {
674 	switch (ctx->le_ctx_event) {
675 	case ILE_LOGIN_RCV:
676 		/*
677 		 * We've already processed everything we're going to
678 		 * process.  Drop any additional login PDU's.
679 		 */
680 		idm_pdu_complete(ctx->le_pdu, IDM_STATUS_SUCCESS);
681 		break;
682 	case ILE_LOGIN_CONN_ERROR:
683 		/* Don't care */
684 		break;
685 	default:
686 		ASSERT(0);
687 	}
688 }
689 
690 static void
691 login_sm_new_state(iscsit_conn_t *ict, login_event_ctx_t *ctx,
692     iscsit_login_state_t new_state)
693 {
694 	iscsit_conn_login_t *lsm = &ict->ict_login_sm;
695 	idm_pdu_t *rpdu;
696 
697 	/*
698 	 * Validate new state
699 	 */
700 	ASSERT(new_state != ILS_UNDEFINED);
701 	ASSERT3U(new_state, <, ILS_MAX_STATE);
702 
703 	new_state = (new_state < ILS_MAX_STATE) ?
704 	    new_state : ILS_UNDEFINED;
705 
706 	IDM_SM_LOG(CE_NOTE, "login_sm_new_state: conn %p "
707 	    "%s (%d) --> %s (%d)\n", (void *)ict->ict_ic,
708 	    iscsit_ils_name[lsm->icl_login_state], lsm->icl_login_state,
709 	    iscsit_ils_name[new_state], new_state);
710 
711 	DTRACE_PROBE3(login__state__change,
712 	    iscsit_conn_t *, ict, login_event_ctx_t *, ctx,
713 	    iscsit_login_state_t, new_state);
714 
715 	mutex_enter(&lsm->icl_mutex);
716 	idm_sm_audit_state_change(&lsm->icl_state_audit, SAS_ISCSIT_LOGIN,
717 	    (int)lsm->icl_login_state, (int)new_state);
718 	lsm->icl_login_last_state = lsm->icl_login_state;
719 	lsm->icl_login_state = new_state;
720 	mutex_exit(&lsm->icl_mutex);
721 
722 	switch (lsm->icl_login_state) {
723 	case ILS_LOGIN_WAITING:
724 		/* Do nothing, waiting for more login PDU's */
725 		break;
726 	case ILS_LOGIN_PROCESSING:
727 		/* All login PDU's received, process login request */
728 		login_sm_process_request(ict);
729 		break;
730 	case ILS_LOGIN_RESPONDING:
731 		rpdu = login_sm_build_login_response(ict);
732 		login_sm_send_next_response(ict, rpdu);
733 		break;
734 	case ILS_LOGIN_RESPONDED:
735 		/* clean up the login response idm text buffer */
736 		if (lsm->icl_login_resp_itb != NULL) {
737 			idm_itextbuf_free(lsm->icl_login_resp_itb);
738 			lsm->icl_login_resp_itb = NULL;
739 		}
740 		break;
741 	case ILS_LOGIN_FFP:
742 		login_sm_ffp_actions(ict);
743 		break;
744 	case ILS_LOGIN_DONE:
745 	case ILS_LOGIN_ERROR:
746 		/*
747 		 * Flag the terminal state for the dispatcher
748 		 */
749 		lsm->icl_login_complete = B_TRUE;
750 		break;
751 	case ILS_LOGIN_INIT: /* Initial state, can't return */
752 	default:
753 		ASSERT(0);
754 		/*NOTREACHED*/
755 	}
756 }
757 
758 /*ARGSUSED*/
759 static void
760 login_sm_send_ack(iscsit_conn_t *ict, idm_pdu_t *pdu)
761 {
762 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
763 	idm_pdu_t		*lack;
764 
765 	/*
766 	 * allocate the response pdu
767 	 */
768 	lack = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
769 	idm_pdu_init(lack, ict->ict_ic, ict, login_resp_complete_cb);
770 	lack->isp_flags |= IDM_PDU_LOGIN_TX;
771 
772 	/*
773 	 * copy the response template into the response pdu
774 	 */
775 	bcopy(lsm->icl_login_resp_tmpl, lack->isp_hdr, sizeof (iscsi_hdr_t));
776 
777 	iscsit_conn_hold(ict);
778 	idm_pdu_tx(lack);
779 }
780 
781 /*ARGSUSED*/
782 static idm_status_t
783 login_sm_validate_ack(iscsit_conn_t *ict, idm_pdu_t *pdu)
784 {
785 	iscsi_hdr_t *ihp = pdu->isp_hdr;
786 	if (ihp->flags & ISCSI_FLAG_TEXT_CONTINUE) {
787 		return (IDM_STATUS_FAIL);
788 	}
789 	if (ntoh24(ihp->dlength) != 0) {
790 		return (IDM_STATUS_FAIL);
791 	}
792 	return (IDM_STATUS_SUCCESS);
793 }
794 
795 static boolean_t
796 login_sm_is_last_response(idm_pdu_t *pdu)
797 {
798 
799 	if (pdu->isp_hdr->flags & ISCSI_FLAG_LOGIN_CONTINUE) {
800 		return (B_FALSE);
801 	}
802 	return (B_TRUE);
803 }
804 
805 
806 static void
807 login_sm_handle_initial_login(iscsit_conn_t *ict, idm_pdu_t *pdu)
808 {
809 	iscsi_login_hdr_t *lh_req = (iscsi_login_hdr_t *)pdu->isp_hdr;
810 	iscsi_login_rsp_hdr_t *lh_resp =
811 	    ict->ict_login_sm.icl_login_resp_tmpl;
812 
813 	/*
814 	 * First login PDU, this connection should not have a sesssion
815 	 * associated.
816 	 */
817 	ASSERT(ict->ict_sess == NULL);
818 
819 	/*
820 	 * Save off TSIH and ISID for later use in finding a session
821 	 */
822 	ict->ict_login_sm.icl_cmdsn = ntohl(lh_req->cmdsn);
823 	ict->ict_login_sm.icl_tsih = ntohs(lh_req->tsid);
824 	bcopy(lh_req->isid, ict->ict_login_sm.icl_isid, ISCSI_ISID_LEN);
825 
826 	/*
827 	 * We'll need the CID as well
828 	 */
829 	ict->ict_cid = ntohs(lh_req->cid);
830 
831 	/*
832 	 * Set the CSG, NSG and Transit bits based on the first PDU
833 	 * in the login sequence.  The CSG already validated in
834 	 * login_sm_req_pdu_check(). We'll clear the transit bit if
835 	 * we encounter any login parameters in the request that
836 	 * required an additional login transfer (i.e. no acceptable
837 	 * choices in range or we needed to change a boolean
838 	 * value from "Yes" to "No").
839 	 */
840 	ict->ict_login_sm.icl_login_csg =
841 	    ISCSI_LOGIN_CURRENT_STAGE(lh_req->flags);
842 	ict->ict_login_sm.icl_login_nsg =
843 	    ISCSI_LOGIN_NEXT_STAGE(lh_req->flags);
844 	ict->ict_login_sm.icl_login_transit =
845 	    lh_req->flags & ISCSI_FLAG_LOGIN_TRANSIT;
846 
847 	/*
848 	 * Initialize header for login reject response.  This will also
849 	 * be copied for use as a template for other login responses
850 	 */
851 	lh_resp->opcode = ISCSI_OP_LOGIN_RSP;
852 	lh_resp->max_version = ISCSIT_MAX_VERSION;
853 
854 	/*
855 	 * We already validated that we can support one of the initiator's
856 	 * versions in login_sm_req_pdu_check().
857 	 */
858 #if (ISCSIT_MAX_VERSION > 0)
859 	if (ISCSIT_MAX_VERSION >= lh_req->min_version) {
860 		lh_resp->active_version =
861 		    MIN(lh_req->max_version, ISCSIT_MAX_VERSION);
862 	} else {
863 		ASSERT(ISCSIT_MAX_VERSION <= lh_req->max_version);
864 		lh_resp->active_version = ISCSIT_MAX_VERSION;
865 	}
866 #endif
867 
868 	lh_resp->hlength = 0; /* No AHS */
869 	bcopy(lh_req->isid, lh_resp->isid, ISCSI_ISID_LEN);
870 	lh_resp->tsid = lh_req->tsid;
871 	lh_resp->itt = lh_req->itt;
872 
873 	/*
874 	 * StatSn, ExpCmdSn and MaxCmdSn will be set immediately before
875 	 * transmission
876 	 */
877 }
878 
879 static void
880 login_sm_send_next_response(iscsit_conn_t *ict, idm_pdu_t *pdu)
881 {
882 	iscsi_login_rsp_hdr_t *lh_resp = (iscsi_login_rsp_hdr_t *)pdu->isp_hdr;
883 
884 	/* Make sure this PDU is part of the login phase */
885 	ASSERT((pdu->isp_flags & IDM_PDU_LOGIN_TX) != 0);
886 
887 	/*
888 	 * Fill in header values
889 	 */
890 	hton24(lh_resp->dlength, pdu->isp_datalen);
891 
892 	/*
893 	 * If the login is successful, this login response will contain
894 	 * the next StatSN and advance the StatSN for the connection.
895 	 */
896 	if (lh_resp->status_class == ISCSI_STATUS_CLASS_SUCCESS) {
897 		ASSERT(ict->ict_sess != NULL);
898 
899 		if ((lh_resp->flags & ISCSI_FLAG_LOGIN_TRANSIT) &&
900 		    (ISCSI_LOGIN_NEXT_STAGE(lh_resp->flags) ==
901 		    ISCSI_FULL_FEATURE_PHASE) &&
902 		    !(lh_resp->flags & ISCSI_FLAG_LOGIN_CONTINUE)) {
903 			iscsit_login_sm_event(ict, ILE_LOGIN_FFP, NULL);
904 		}
905 		if (login_sm_is_last_response(pdu) == B_TRUE) {
906 			/*
907 			 * The last of a potentially mult-PDU response finished.
908 			 */
909 			iscsit_login_sm_event(ict, ILE_LOGIN_RESP_COMPLETE,
910 			    NULL);
911 		}
912 
913 		iscsit_conn_hold(ict);
914 		pdu->isp_flags |= IDM_PDU_SET_STATSN | IDM_PDU_ADVANCE_STATSN;
915 		iscsit_pdu_tx(pdu);
916 	} else {
917 		/*
918 		 * If status_class != ISCSI_STATUS_CLASS_SUCCESS then
919 		 * StatSN is not valid and we can call idm_pdu_tx instead
920 		 * of iscsit_pdu_tx.  This is very good thing since in
921 		 * some cases of login failure we may not have a session.
922 		 * Since iscsit_calc_rspsn grabs the session mutex while
923 		 * it is retrieving values for expcmdsn and maxcmdsn this
924 		 * would cause a panic.
925 		 *
926 		 * Since we still want a value for expcmdsn, fill in an
927 		 * appropriate value based on the login request before
928 		 * sending the response. Cmdsn/expcmdsn do not advance during
929 		 * login phase.
930 		 */
931 		lh_resp->expcmdsn = htonl(ict->ict_login_sm.icl_cmdsn);
932 		lh_resp->maxcmdsn = htonl(ict->ict_login_sm.icl_cmdsn + 1);
933 
934 		iscsit_conn_hold(ict);
935 		idm_pdu_tx(pdu);
936 	}
937 
938 }
939 
940 static void
941 login_sm_process_request(iscsit_conn_t *ict)
942 {
943 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
944 	uint8_t			error_class = 0;
945 	uint8_t			error_detail = 0;
946 
947 	/*
948 	 * First walk all the PDU's that make up this login request
949 	 * and compile all the iSCSI key-value pairs into nvlist format.
950 	 */
951 
952 	ASSERT(lsm->icl_request_nvlist == NULL);
953 	/* create an nvlist for request key/value pairs */
954 	if (idm_pdu_list_to_nvlist(&lsm->icl_pdu_list,
955 	    &lsm->icl_request_nvlist, &error_detail) != IDM_STATUS_SUCCESS) {
956 		error_class = ISCSI_STATUS_CLASS_TARGET_ERR;
957 		SET_LOGIN_ERROR(ict, error_class, error_detail);
958 		goto request_fail;
959 	}
960 
961 	/* Allocate a new nvlist for response key/value pairs */
962 	ASSERT(lsm->icl_response_nvlist == NULL);
963 	if (nvlist_alloc(&lsm->icl_response_nvlist, NV_UNIQUE_NAME,
964 	    KM_NOSLEEP) != 0) {
965 		error_class = ISCSI_STATUS_CLASS_TARGET_ERR;
966 		error_detail = ISCSI_LOGIN_STATUS_NO_RESOURCES;
967 		SET_LOGIN_ERROR(ict, error_class, error_detail);
968 		goto request_fail;
969 	}
970 
971 	/*
972 	 * This would be a very good time to make sure we have
973 	 * negotiated the required values for the login phase.  For
974 	 * example we definitely should have defined InitiatorName,
975 	 * and Target name regardless of our current login phase.
976 	 */
977 	if (!ict->ict_op.op_initial_params_set) {
978 		if (login_sm_validate_initial_parameters(ict) !=
979 		    IDM_STATUS_SUCCESS) {
980 			goto request_fail;
981 		}
982 
983 		/*
984 		 * Now setup our session association.  This includes
985 		 * create a new session or looking up an existing session,
986 		 * and if this is not a discovery session then we will
987 		 * also register this session with STMF.
988 		 */
989 		if (login_sm_session_bind(ict) != IDM_STATUS_SUCCESS) {
990 			goto request_fail;
991 		}
992 
993 		if (login_sm_set_auth(ict) != IDM_STATUS_SUCCESS) {
994 			goto request_fail;
995 		}
996 
997 		/*
998 		 * Prepend TargetAlias and PortalGroupTag
999 		 */
1000 		if (ict->ict_op.op_discovery_session == B_FALSE) {
1001 			if ((lsm->icl_auth.ca_tgt_alias[0]) != '\0') {
1002 				(void) iscsit_reply_string(ict,
1003 				    "TargetAlias",
1004 				    &lsm->icl_auth.ca_tgt_alias[0]);
1005 			}
1006 			(void) iscsit_reply_numerical(ict,
1007 			    "TargetPortalGroupTag",
1008 			    (uint64_t)lsm->icl_tpgt_tag);
1009 		}
1010 
1011 		ict->ict_op.op_initial_params_set = B_TRUE;
1012 	}
1013 
1014 	if (login_sm_process_nvlist(ict) != IDM_STATUS_SUCCESS) {
1015 		goto request_fail;
1016 	}
1017 
1018 	if (login_sm_check_security(ict) != IDM_STATUS_SUCCESS) {
1019 		goto request_fail;
1020 	}
1021 
1022 	/* clean up request_nvlist */
1023 	if (lsm->icl_request_nvlist != NULL) {
1024 		nvlist_free(lsm->icl_request_nvlist);
1025 		lsm->icl_request_nvlist = NULL;
1026 	}
1027 
1028 	/* convert any responses to textbuf form */
1029 	ASSERT(lsm->icl_login_resp_itb == NULL);
1030 	if (lsm->icl_response_nvlist) {
1031 		lsm->icl_login_resp_itb = idm_nvlist_to_itextbuf(
1032 		    lsm->icl_response_nvlist);
1033 		if (lsm->icl_login_resp_itb == NULL) {
1034 			/* Still need to send the resp so continue */
1035 			SET_LOGIN_ERROR(ict,
1036 			    ISCSI_STATUS_CLASS_TARGET_ERR,
1037 			    ISCSI_LOGIN_STATUS_NO_RESOURCES);
1038 		}
1039 		/* clean up response_nvlist */
1040 		nvlist_free(lsm->icl_response_nvlist);
1041 		lsm->icl_response_nvlist = NULL;
1042 	}
1043 
1044 	/* tell the state machine to send the textbuf */
1045 	iscsit_login_sm_event(ict, ILE_LOGIN_RESP_READY, NULL);
1046 	return;
1047 
1048 request_fail:
1049 
1050 	/* clean up request_nvlist and response_nvlist */
1051 	if (lsm->icl_request_nvlist != NULL) {
1052 		nvlist_free(lsm->icl_request_nvlist);
1053 		lsm->icl_request_nvlist = NULL;
1054 	}
1055 	if (lsm->icl_response_nvlist != NULL) {
1056 		nvlist_free(lsm->icl_response_nvlist);
1057 		lsm->icl_response_nvlist = NULL;
1058 	}
1059 	/* Make sure we already set the login error */
1060 	if (ict->ict_login_sm.icl_login_resp_err_class ==
1061 	    ISCSI_STATUS_CLASS_SUCCESS) {
1062 		SET_LOGIN_ERROR(ict,
1063 		    ISCSI_STATUS_CLASS_TARGET_ERR,
1064 		    ISCSI_LOGIN_STATUS_TARGET_ERROR);
1065 	}
1066 	iscsit_login_sm_event(ict, ILE_LOGIN_RESP_READY, NULL);
1067 }
1068 
1069 
1070 static void
1071 login_sm_ffp_actions(iscsit_conn_t *ict)
1072 {
1073 	iscsit_process_negotiated_values(ict);
1074 }
1075 
1076 static idm_status_t
1077 login_sm_validate_initial_parameters(iscsit_conn_t *ict)
1078 {
1079 	int		nvrc;
1080 	char		*string_val;
1081 	uint8_t		error_class = ISCSI_STATUS_CLASS_INITIATOR_ERR;
1082 	uint8_t		error_detail = ISCSI_LOGIN_STATUS_MISSING_FIELDS;
1083 	idm_status_t	status = IDM_STATUS_FAIL;
1084 	iscsit_conn_login_t *lsm = &ict->ict_login_sm;
1085 
1086 	/*
1087 	 * Make sure we received the required information from the initial
1088 	 * login. Add these declaratives to the negotiated list and
1089 	 * remove them from the request list as we go. If anything fails,
1090 	 * the caller will clean-up the nvlists.
1091 	 */
1092 
1093 	/*
1094 	 * Initiator name
1095 	 */
1096 	if ((nvrc = nvlist_lookup_string(lsm->icl_request_nvlist,
1097 	    "InitiatorName", &string_val)) != 0) {
1098 		goto initial_params_done;
1099 	}
1100 	if ((nvrc = nvlist_add_string(lsm->icl_negotiated_values,
1101 	    "InitiatorName", string_val)) != 0) {
1102 		goto initial_params_done;
1103 	}
1104 	if ((nvrc = nvlist_lookup_string(lsm->icl_negotiated_values,
1105 	    "InitiatorName", &string_val)) != 0) {
1106 		goto initial_params_done;
1107 	}
1108 	lsm->icl_initiator_name = string_val;
1109 	idm_conn_set_initiator_name(ict->ict_ic, lsm->icl_initiator_name);
1110 	if ((nvrc = nvlist_remove(lsm->icl_request_nvlist,
1111 	    "InitiatorName", DATA_TYPE_STRING)) != 0) {
1112 		goto initial_params_done;
1113 	}
1114 
1115 	/*
1116 	 * Session type
1117 	 */
1118 	ict->ict_op.op_discovery_session = B_FALSE;
1119 	nvrc = nvlist_lookup_string(lsm->icl_request_nvlist,
1120 	    "SessionType", &string_val);
1121 	if (nvrc != ENOENT && nvrc != 0) {
1122 		goto initial_params_done;
1123 	}
1124 	if (nvrc == 0) {
1125 		if (strcmp(string_val, "Discovery") == 0) {
1126 			ict->ict_op.op_discovery_session = B_TRUE;
1127 		} else if (strcmp(string_val, "Normal") != 0) {
1128 			goto initial_params_done;
1129 		}
1130 		if ((nvrc = nvlist_add_string(lsm->icl_negotiated_values,
1131 		    "SessionType", string_val)) != 0) {
1132 			goto initial_params_done;
1133 		}
1134 		if ((nvrc = nvlist_remove(lsm->icl_request_nvlist,
1135 		    "SessionType", DATA_TYPE_STRING)) != 0) {
1136 			goto initial_params_done;
1137 		}
1138 	}
1139 
1140 	/*
1141 	 * Must have either TargetName or SessionType==Discovery
1142 	 */
1143 	lsm->icl_target_name = NULL;
1144 	nvrc = nvlist_lookup_string(lsm->icl_request_nvlist,
1145 	    "TargetName", &string_val);
1146 	if (nvrc != ENOENT && nvrc != 0) {
1147 		goto initial_params_done;
1148 	}
1149 	if (nvrc == 0) {
1150 		if ((nvrc = nvlist_add_string(lsm->icl_negotiated_values,
1151 		    "TargetName", string_val)) != 0) {
1152 			goto initial_params_done;
1153 		}
1154 		if ((nvrc = nvlist_lookup_string(lsm->icl_negotiated_values,
1155 		    "TargetName", &string_val)) != 0) {
1156 			goto initial_params_done;
1157 		}
1158 		lsm->icl_target_name = string_val;
1159 		idm_conn_set_target_name(ict->ict_ic, lsm->icl_target_name);
1160 		if ((nvrc = nvlist_remove(lsm->icl_request_nvlist,
1161 		    "TargetName", DATA_TYPE_STRING)) != 0) {
1162 			goto initial_params_done;
1163 		}
1164 	} else if (ict->ict_op.op_discovery_session == B_FALSE) {
1165 		/*
1166 		 * Missing target name
1167 		 */
1168 		goto initial_params_done;
1169 	}
1170 
1171 	idm_conn_set_isid(ict->ict_ic, lsm->icl_isid);
1172 	(void) snprintf(ict->ict_ic->ic_tsih, ISCSI_MAX_TSIH_LEN + 1, "0x%04x",
1173 	    lsm->icl_tsih);
1174 
1175 	IDM_SM_LOG(CE_NOTE, "conn %p: initiator=%s", (void *)ict->ict_ic,
1176 	    (lsm->icl_initiator_name == NULL) ? "N/A" :
1177 	    lsm->icl_initiator_name);
1178 	IDM_SM_LOG(CE_NOTE, "conn %p: target=%s", (void *)ict->ict_ic,
1179 	    (lsm->icl_target_name == NULL) ? "N/A" :
1180 	    lsm->icl_target_name);
1181 	IDM_SM_LOG(CE_NOTE, "conn %p: sessiontype=%s", (void *)ict->ict_ic,
1182 	    ict->ict_op.op_discovery_session ? "Discovery" : "Normal");
1183 
1184 	/* Sucess */
1185 	status = IDM_STATUS_SUCCESS;
1186 	error_class = ISCSI_STATUS_CLASS_SUCCESS;
1187 	error_detail = ISCSI_LOGIN_STATUS_ACCEPT;
1188 
1189 initial_params_done:
1190 	SET_LOGIN_ERROR(ict, error_class, error_detail);
1191 	return (status);
1192 }
1193 
1194 
1195 /*
1196  * login_sm_session_bind
1197  *
1198  * This function looks at the data from the initial login request
1199  * of a new connection and either looks up and existing session,
1200  * creates a new session, or returns an error.  RFC3720 section 5.3.1
1201  * defines these rules:
1202  *
1203  * +------------------------------------------------------------------+
1204  * |ISID      | TSIH        | CID    |     Target action              |
1205  * +------------------------------------------------------------------+
1206  * |new       | non-zero    | any    |     fail the login             |
1207  * |          |             |        |     ("session does not exist") |
1208  * +------------------------------------------------------------------+
1209  * |new       | zero        | any    |     instantiate a new session  |
1210  * +------------------------------------------------------------------+
1211  * |existing  | zero        | any    |     do session reinstatement   |
1212  * |          |             |        |     (see section 5.3.5)        |
1213  * +------------------------------------------------------------------+
1214  * |existing  | non-zero    | new    |     add a new connection to    |
1215  * |          | existing    |        |     the session                |
1216  * +------------------------------------------------------------------+
1217  * |existing  | non-zero    |existing|     do connection reinstatement|
1218  * |          | existing    |        |    (see section 5.3.4)         |
1219  * +------------------------------------------------------------------+
1220  * |existing  | non-zero    | any    |         fail the login         |
1221  * |          | new         |        |     ("session does not exist") |
1222  * +------------------------------------------------------------------+
1223  *
1224  */
1225 
1226 /*
1227  * Map an <ipv6,port> address to an <ipv4,port> address if possible.
1228  * Returns:
1229  *    1 - success
1230  *    0 - address not mapable
1231  */
1232 
1233 static int
1234 iscsit_is_v4_mapped(struct sockaddr_storage *sa, struct sockaddr_storage *v4sa)
1235 {
1236 	struct sockaddr_in *sin;
1237 	struct in_addr *in;
1238 	struct sockaddr_in6 *sin6;
1239 	struct in6_addr *in6;
1240 	int ret = 0;
1241 
1242 	sin6 = (struct sockaddr_in6 *)sa;
1243 	in6 = &sin6->sin6_addr;
1244 	if ((sa->ss_family == AF_INET6) &&
1245 	    (IN6_IS_ADDR_V4MAPPED(in6) || IN6_IS_ADDR_V4COMPAT(in6))) {
1246 		sin = (struct sockaddr_in *)v4sa;
1247 		in = &sin->sin_addr;
1248 		v4sa->ss_family = AF_INET;
1249 		sin->sin_port = sin6->sin6_port;
1250 		IN6_V4MAPPED_TO_INADDR(in6, in);
1251 		ret = 1;
1252 	}
1253 	return (ret);
1254 }
1255 
1256 static idm_status_t
1257 login_sm_session_bind(iscsit_conn_t *ict)
1258 {
1259 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1260 	iscsit_tgt_t		*tgt = NULL;
1261 	iscsit_tpgt_t		*tpgt = NULL;
1262 	iscsit_portal_t		*portal = NULL;
1263 	iscsit_sess_t		*existing_sess = NULL;
1264 	iscsit_sess_t		*new_sess = NULL;
1265 	iscsit_conn_t		*existing_ict = NULL;
1266 	uint8_t			error_class;
1267 	uint8_t			error_detail;
1268 
1269 	/*
1270 	 * Look up target and then check if there are sessions or connections
1271 	 * that match this request (see below).  Any holds taken on objects
1272 	 * must be released at the end of the function (let's keep things
1273 	 * simple).
1274 	 *
1275 	 * If target name is set then we should have a corresponding target
1276 	 * context configured.
1277 	 */
1278 	if (lsm->icl_target_name != NULL) {
1279 		/*
1280 		 * iscsit_tgt_lookup implicitly takes a ref on the target
1281 		 */
1282 		ISCSIT_GLOBAL_LOCK(RW_READER);
1283 		tgt = iscsit_tgt_lookup_locked(lsm->icl_target_name);
1284 		if (tgt == NULL) {
1285 			ISCSIT_GLOBAL_UNLOCK();
1286 			SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1287 			    ISCSI_LOGIN_STATUS_TGT_NOT_FOUND);
1288 			goto session_bind_error;
1289 		} else {
1290 			mutex_enter(&tgt->target_mutex);
1291 			tpgt = avl_first(&tgt->target_tpgt_list);
1292 
1293 			if (IS_DEFAULT_TPGT(tpgt)) {
1294 				lsm->icl_tpgt_tag = ISCSIT_DEFAULT_TPGT;
1295 			} else {
1296 				/*
1297 				 * Find the portal group tag for the
1298 				 * login response.
1299 				 */
1300 				struct sockaddr_storage v4sa, *sa;
1301 
1302 				sa = &ict->ict_ic->ic_laddr;
1303 				portal = iscsit_tgt_lookup_portal(tgt,
1304 				    sa, &tpgt);
1305 				if (portal == NULL &&
1306 				    iscsit_is_v4_mapped(sa, &v4sa)) {
1307 					/*
1308 					 * Try again if the local address
1309 					 * was v6 mappable to v4.
1310 					 */
1311 					portal = iscsit_tgt_lookup_portal(tgt,
1312 					    &v4sa, &tpgt);
1313 
1314 				}
1315 				if (portal == NULL) {
1316 					/*
1317 					 * Initiator came in on wrong address
1318 					 */
1319 					SET_LOGIN_ERROR(ict,
1320 					    ISCSI_STATUS_CLASS_INITIATOR_ERR,
1321 					    ISCSI_LOGIN_STATUS_TGT_NOT_FOUND);
1322 					mutex_exit(&tgt->target_mutex);
1323 					ISCSIT_GLOBAL_UNLOCK();
1324 					goto session_bind_error;
1325 				}
1326 
1327 				/*
1328 				 * Need to release holds on the portal and
1329 				 * tpgt after processing is complete.
1330 				 */
1331 				lsm->icl_tpgt_tag = tpgt->tpgt_tag;
1332 				iscsit_portal_rele(portal);
1333 				iscsit_tpgt_rele(tpgt);
1334 			}
1335 
1336 			if ((tgt->target_state != TS_STMF_ONLINE) ||
1337 			    ((iscsit_global.global_svc_state != ISE_ENABLED) &&
1338 			    ((iscsit_global.global_svc_state != ISE_BUSY)))) {
1339 				SET_LOGIN_ERROR(ict,
1340 				    ISCSI_STATUS_CLASS_TARGET_ERR,
1341 				    ISCSI_LOGIN_STATUS_SVC_UNAVAILABLE);
1342 				mutex_exit(&tgt->target_mutex);
1343 				ISCSIT_GLOBAL_UNLOCK();
1344 				goto session_bind_error;
1345 			}
1346 			mutex_exit(&tgt->target_mutex);
1347 			ISCSIT_GLOBAL_UNLOCK();
1348 		}
1349 	}
1350 
1351 	ASSERT((tgt != NULL) || (ict->ict_op.op_discovery_session == B_TRUE));
1352 
1353 	/*
1354 	 * Check if there is an existing session matching this ISID.  If
1355 	 * tgt == NULL then we'll look for the session on the global list
1356 	 * of discovery session.  If we find a session then the ISID
1357 	 * exists.
1358 	 */
1359 	existing_sess = iscsit_tgt_lookup_sess(tgt, lsm->icl_initiator_name,
1360 	    lsm->icl_isid, lsm->icl_tsih, lsm->icl_tpgt_tag);
1361 	if (existing_sess != NULL) {
1362 		existing_ict = iscsit_sess_lookup_conn(existing_sess,
1363 		    ict->ict_cid);
1364 	}
1365 
1366 	/*
1367 	 * If this is a discovery session, make sure it has appropriate
1368 	 * parameters.
1369 	 */
1370 	if ((ict->ict_op.op_discovery_session == B_TRUE) &&
1371 	    ((lsm->icl_tsih != ISCSI_UNSPEC_TSIH) || (existing_sess != NULL))) {
1372 		/* XXX Do we need to check for existing ISID (sess != NULL)? */
1373 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1374 		    ISCSI_LOGIN_STATUS_INVALID_REQUEST);
1375 		goto session_bind_error;
1376 	}
1377 
1378 	/*
1379 	 * Check the two error conditions from the table.
1380 	 *
1381 	 * ISID=new, TSIH=non-zero
1382 	 */
1383 	if ((existing_sess == NULL) && (lsm->icl_tsih != ISCSI_UNSPEC_TSIH)) {
1384 		/* fail the login */
1385 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1386 		    ISCSI_LOGIN_STATUS_NO_SESSION);
1387 		goto session_bind_error;
1388 	}
1389 
1390 	/* ISID=existing, TSIH=non-zero new */
1391 	if ((existing_sess != NULL) && (lsm->icl_tsih != 0) &&
1392 	    (existing_sess->ist_tsih != lsm->icl_tsih)) {
1393 		/* fail the login */
1394 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1395 		    ISCSI_LOGIN_STATUS_NO_SESSION);
1396 		goto session_bind_error;
1397 	}
1398 
1399 	/*
1400 	 * Handle the remaining table cases in order
1401 	 */
1402 	if (existing_sess == NULL) {
1403 		/* Should have caught this above */
1404 		ASSERT(lsm->icl_tsih == ISCSI_UNSPEC_TSIH);
1405 		/*
1406 		 * ISID=new, TSIH=zero --> instantiate a new session
1407 		 */
1408 		new_sess = iscsit_sess_create(tgt, ict, lsm->icl_cmdsn,
1409 		    lsm->icl_isid, lsm->icl_tpgt_tag, lsm->icl_initiator_name,
1410 		    lsm->icl_target_name, &error_class, &error_detail);
1411 		ASSERT(new_sess != NULL);
1412 
1413 		/* Session create may have failed even if it returned a value */
1414 		if (error_class != ISCSI_STATUS_CLASS_SUCCESS) {
1415 			SET_LOGIN_ERROR(ict, error_class, error_detail);
1416 			goto session_bind_error;
1417 		}
1418 
1419 		/*
1420 		 * If we don't already have an STMF session and this is not
1421 		 * a discovery session then we need to allocate and register
1422 		 * one.
1423 		 */
1424 		if (!ict->ict_op.op_discovery_session) {
1425 			if (login_sm_session_register(ict) !=
1426 			    IDM_STATUS_SUCCESS) {
1427 				/* login_sm_session_register sets error codes */
1428 				goto session_bind_error;
1429 			}
1430 		}
1431 
1432 	} else {
1433 		if (lsm->icl_tsih == ISCSI_UNSPEC_TSIH) {
1434 			/*
1435 			 * ISID=existing, TSIH=zero --> Session reinstatement
1436 			 */
1437 			new_sess = iscsit_sess_reinstate(tgt, existing_sess,
1438 			    ict, &error_class, &error_detail);
1439 			ASSERT(new_sess != NULL);
1440 
1441 			if (error_class != ISCSI_STATUS_CLASS_SUCCESS) {
1442 				SET_LOGIN_ERROR(ict, error_class, error_detail);
1443 				goto session_bind_error;
1444 			}
1445 
1446 			/*
1447 			 * If we don't already have an STMF session and this is
1448 			 * not a discovery session then we need to allocate and
1449 			 * register one.
1450 			 */
1451 			if (!ict->ict_op.op_discovery_session) {
1452 				if (login_sm_session_register(ict) !=
1453 				    IDM_STATUS_SUCCESS) {
1454 					/*
1455 					 * login_sm_session_register sets
1456 					 * error codes
1457 					 */
1458 					goto session_bind_error;
1459 				}
1460 			}
1461 		} else {
1462 			/*
1463 			 * The following code covers these two cases:
1464 			 * ISID=existing, TSIH=non-zero existing, CID=new
1465 			 * --> add new connection to MC/S session
1466 			 * ISID=existing, TSIH=non-zero existing, CID=existing
1467 			 * --> do connection reinstatement
1468 			 *
1469 			 * Session continuation uses this path as well
1470 			 */
1471 			cmn_err(CE_NOTE, "login_sm_session_bind: add new "
1472 			    "conn/sess continue");
1473 			if (existing_ict != NULL) {
1474 				/*
1475 				 * ISID=existing, TSIH=non-zero existing,
1476 				 * CID=existing --> do connection reinstatement
1477 				 */
1478 				if (iscsit_conn_reinstate(existing_ict, ict) !=
1479 				    IDM_STATUS_SUCCESS) {
1480 					/*
1481 					 * Most likely this means the connection
1482 					 * the initiator is trying to reinstate
1483 					 * is not in an acceptable state.
1484 					 */
1485 					SET_LOGIN_ERROR(ict,
1486 					    ISCSI_STATUS_CLASS_INITIATOR_ERR,
1487 					    ISCSI_LOGIN_STATUS_INIT_ERR);
1488 					goto session_bind_error;
1489 				}
1490 			}
1491 
1492 			iscsit_sess_sm_event(existing_sess, SE_CONN_IN_LOGIN,
1493 			    ict);
1494 		}
1495 	}
1496 
1497 	if (tgt != NULL)
1498 		iscsit_tgt_rele(tgt);
1499 	if (existing_sess != NULL)
1500 		iscsit_sess_rele(existing_sess);
1501 	if (existing_ict != NULL)
1502 		iscsit_conn_rele(existing_ict);
1503 
1504 	return (IDM_STATUS_SUCCESS);
1505 
1506 session_bind_error:
1507 	if (tgt != NULL)
1508 		iscsit_tgt_rele(tgt);
1509 	if (existing_sess != NULL)
1510 		iscsit_sess_rele(existing_sess);
1511 	if (existing_ict != NULL)
1512 		iscsit_conn_rele(existing_ict);
1513 
1514 	/*
1515 	 * If session bind fails we will fail the login but don't destroy
1516 	 * the session until later.
1517 	 */
1518 	return (IDM_STATUS_FAIL);
1519 }
1520 
1521 
1522 static idm_status_t
1523 login_sm_set_auth(iscsit_conn_t *ict)
1524 {
1525 	idm_status_t		idmrc = IDM_STATUS_SUCCESS;
1526 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1527 	iscsit_ini_t		*ini;
1528 	iscsit_tgt_t		*tgt;
1529 	char			*auth = "";
1530 	char			*radiusserver = "";
1531 	char			*radiussecret = "";
1532 	char			*chapuser = "";
1533 	char			*chapsecret = "";
1534 	char			*targetchapuser = "";
1535 	char			*targetchapsecret = "";
1536 	char			*targetalias = "";
1537 	int			i;
1538 
1539 	ISCSIT_GLOBAL_LOCK(RW_READER);
1540 
1541 	/*
1542 	 * Set authentication method to none for discovery session.
1543 	 */
1544 	if (ict->ict_op.op_discovery_session == B_TRUE) {
1545 		lsm->icl_auth.ca_method_valid_list[0] = AM_NONE;
1546 		ISCSIT_GLOBAL_UNLOCK();
1547 		return (idmrc);
1548 	}
1549 
1550 	/*
1551 	 * Get all the authentication parameters we need -- since we hold
1552 	 * the global config lock we guarantee that the parameters will
1553 	 * be consistent with each other.
1554 	 */
1555 	(void) nvlist_lookup_string(iscsit_global.global_props,
1556 	    PROP_AUTH, &auth);
1557 	(void) nvlist_lookup_string(iscsit_global.global_props,
1558 	    PROP_RADIUS_SERVER, &radiusserver);
1559 	(void) nvlist_lookup_string(iscsit_global.global_props,
1560 	    PROP_RADIUS_SECRET, &radiussecret);
1561 
1562 	ini = iscsit_ini_lookup_locked(lsm->icl_initiator_name);
1563 	if (ini != NULL) {
1564 		/* Get Initiator CHAP parameters */
1565 		(void) nvlist_lookup_string(ini->ini_props, PROP_CHAP_USER,
1566 		    &chapuser);
1567 		(void) nvlist_lookup_string(ini->ini_props, PROP_CHAP_SECRET,
1568 		    &chapsecret);
1569 	}
1570 
1571 	tgt = ict->ict_sess->ist_tgt;
1572 	if (tgt != NULL) {
1573 		/* See if we have a target-specific authentication setting */
1574 		(void) nvlist_lookup_string(tgt->target_props, PROP_AUTH,
1575 		    &auth);
1576 		/* Get target CHAP parameters */
1577 		(void) nvlist_lookup_string(tgt->target_props,
1578 		    PROP_TARGET_CHAP_USER, &targetchapuser);
1579 		(void) nvlist_lookup_string(tgt->target_props,
1580 		    PROP_TARGET_CHAP_SECRET, &targetchapsecret);
1581 		/* Get alias */
1582 		(void) nvlist_lookup_string(tgt->target_props,
1583 		    PROP_ALIAS, &targetalias);
1584 	}
1585 
1586 	/* Set authentication method */
1587 	i = 0;
1588 	if (strcmp(auth, PA_AUTH_RADIUS) == 0) {
1589 		/* CHAP authentication using RADIUS server */
1590 		lsm->icl_auth.ca_method_valid_list[i++] = AM_CHAP;
1591 		lsm->icl_auth.ca_use_radius = B_TRUE;
1592 	} else if (strcmp(auth, PA_AUTH_CHAP) == 0) {
1593 		/* Local CHAP authentication */
1594 		lsm->icl_auth.ca_method_valid_list[i++] = AM_CHAP;
1595 		lsm->icl_auth.ca_use_radius = B_FALSE;
1596 	} else if ((strcmp(auth, PA_AUTH_NONE) == 0) ||
1597 	    (strcmp(auth, "") == 0)) {
1598 		/* No authentication */
1599 		lsm->icl_auth.ca_method_valid_list[i++] = AM_NONE;
1600 	}
1601 
1602 	/*
1603 	 * If initiator/target CHAP username is not set then use the
1604 	 * node name.  If lsm->icl_target_name == NULL then this is
1605 	 * a discovery session so we don't need to work about the target.
1606 	 */
1607 	if (strcmp(chapuser, "") == 0) {
1608 		(void) strlcpy(lsm->icl_auth.ca_ini_chapuser,
1609 		    lsm->icl_initiator_name,
1610 		    min(iscsitAuthStringMaxLength, MAX_ISCSI_NODENAMELEN));
1611 	} else {
1612 		(void) strlcpy(lsm->icl_auth.ca_ini_chapuser, chapuser,
1613 		    iscsitAuthStringMaxLength);
1614 	}
1615 	if ((lsm->icl_target_name != NULL) &&
1616 	    (strcmp(targetchapuser, "") == 0)) {
1617 		(void) strlcpy(lsm->icl_auth.ca_tgt_chapuser,
1618 		    lsm->icl_target_name,
1619 		    min(iscsitAuthStringMaxLength, MAX_ISCSI_NODENAMELEN));
1620 	} else {
1621 		(void) strlcpy(lsm->icl_auth.ca_tgt_chapuser,
1622 		    targetchapuser, iscsitAuthStringMaxLength);
1623 	}
1624 
1625 	/*
1626 	 * Secrets are stored in base64-encoded format so we need to
1627 	 * decode them into binary form
1628 	 */
1629 	if (strcmp(chapsecret, "") == 0) {
1630 		lsm->icl_auth.ca_ini_chapsecretlen = 0;
1631 	} else {
1632 		if (iscsi_base64_str_to_binary(chapsecret,
1633 		    strnlen(chapsecret, iscsitAuthStringMaxLength),
1634 		    lsm->icl_auth.ca_ini_chapsecret, iscsitAuthStringMaxLength,
1635 		    &lsm->icl_auth.ca_ini_chapsecretlen) != 0) {
1636 			cmn_err(CE_WARN, "Corrupted CHAP secret"
1637 			    " for initiator %s", lsm->icl_initiator_name);
1638 			lsm->icl_auth.ca_ini_chapsecretlen = 0;
1639 		}
1640 	}
1641 	if (strcmp(targetchapsecret, "") == 0) {
1642 		lsm->icl_auth.ca_tgt_chapsecretlen = 0;
1643 	} else {
1644 		if (iscsi_base64_str_to_binary(targetchapsecret,
1645 		    strnlen(targetchapsecret, iscsitAuthStringMaxLength),
1646 		    lsm->icl_auth.ca_tgt_chapsecret, iscsitAuthStringMaxLength,
1647 		    &lsm->icl_auth.ca_tgt_chapsecretlen) != 0) {
1648 			cmn_err(CE_WARN, "Corrupted CHAP secret"
1649 			    " for target %s", lsm->icl_target_name);
1650 			lsm->icl_auth.ca_tgt_chapsecretlen = 0;
1651 		}
1652 	}
1653 	if (strcmp(radiussecret, "") == 0) {
1654 		lsm->icl_auth.ca_radius_secretlen = 0;
1655 	} else {
1656 		if (iscsi_base64_str_to_binary(radiussecret,
1657 		    strnlen(radiussecret, iscsitAuthStringMaxLength),
1658 		    lsm->icl_auth.ca_radius_secret, iscsitAuthStringMaxLength,
1659 		    &lsm->icl_auth.ca_radius_secretlen) != 0) {
1660 			cmn_err(CE_WARN, "Corrupted RADIUS secret");
1661 			lsm->icl_auth.ca_radius_secretlen = 0;
1662 		}
1663 	}
1664 
1665 	/*
1666 	 * Set alias
1667 	 */
1668 	(void) strlcpy(lsm->icl_auth.ca_tgt_alias, targetalias,
1669 	    MAX_ISCSI_NODENAMELEN);
1670 
1671 	/*
1672 	 * Now that authentication parameters are setup, validate the parameters
1673 	 * against the authentication mode
1674 	 * Decode RADIUS server value int lsm->icl_auth.ca_radius_server
1675 	 */
1676 	if ((strcmp(auth, PA_AUTH_RADIUS) == 0) &&
1677 	    ((lsm->icl_auth.ca_radius_secretlen == 0) ||
1678 	    (strcmp(radiusserver, "") == 0) ||
1679 	    it_common_convert_sa(radiusserver,
1680 	    &lsm->icl_auth.ca_radius_server,
1681 	    DEFAULT_RADIUS_PORT) == NULL)) {
1682 		cmn_err(CE_WARN, "RADIUS authentication selected "
1683 		    "for target %s but RADIUS parameters are not "
1684 		    "configured.", lsm->icl_target_name);
1685 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_TARGET_ERR,
1686 		    ISCSI_LOGIN_STATUS_TARGET_ERROR);
1687 		idmrc = IDM_STATUS_FAIL;
1688 	} else if ((strcmp(auth, PA_AUTH_CHAP) == 0) &&
1689 	    (lsm->icl_auth.ca_ini_chapsecretlen == 0)) {
1690 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1691 		    ISCSI_LOGIN_STATUS_AUTH_FAILED);
1692 		idmrc = IDM_STATUS_FAIL;
1693 	}
1694 
1695 	ISCSIT_GLOBAL_UNLOCK();
1696 
1697 	return (idmrc);
1698 }
1699 
1700 
1701 static idm_status_t
1702 login_sm_session_register(iscsit_conn_t *ict)
1703 {
1704 	iscsit_sess_t		*ist = ict->ict_sess;
1705 	stmf_scsi_session_t	*ss;
1706 
1707 	/*
1708 	 * Hold target mutex until we have finished registering with STMF
1709 	 */
1710 	mutex_enter(&ist->ist_tgt->target_mutex);
1711 	if (ist->ist_tgt->target_state != TS_STMF_ONLINE) {
1712 		mutex_exit(&ist->ist_tgt->target_mutex);
1713 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_INITIATOR_ERR,
1714 		    ISCSI_LOGIN_STATUS_TGT_REMOVED);
1715 		return (IDM_STATUS_FAIL);
1716 	}
1717 
1718 	ss = stmf_alloc(STMF_STRUCT_SCSI_SESSION, 0,
1719 	    0);
1720 	if (ss == NULL) {
1721 		mutex_exit(&ist->ist_tgt->target_mutex);
1722 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_TARGET_ERR,
1723 		    ISCSI_LOGIN_STATUS_NO_RESOURCES);
1724 		return (IDM_STATUS_FAIL);
1725 	}
1726 
1727 	ss->ss_rport_id = kmem_zalloc(sizeof (scsi_devid_desc_t) +
1728 	    strlen(ist->ist_initiator_name) + 1, KM_SLEEP);
1729 	(void) strcpy((char *)ss->ss_rport_id->ident, ist->ist_initiator_name);
1730 	ss->ss_rport_id->ident_length = strlen(ist->ist_initiator_name);
1731 	ss->ss_rport_id->protocol_id = PROTOCOL_iSCSI;
1732 	ss->ss_rport_id->piv = 1;
1733 	ss->ss_rport_id->code_set = CODE_SET_ASCII;
1734 	ss->ss_rport_id->association = ID_IS_TARGET_PORT;
1735 
1736 	ss->ss_lport = ist->ist_lport;
1737 
1738 	if (stmf_register_scsi_session(ict->ict_sess->ist_lport, ss) !=
1739 	    STMF_SUCCESS) {
1740 		mutex_exit(&ist->ist_tgt->target_mutex);
1741 		kmem_free(ss->ss_rport_id,
1742 		    sizeof (scsi_devid_desc_t) +
1743 		    strlen(ist->ist_initiator_name) + 1);
1744 		stmf_free(ss);
1745 		SET_LOGIN_ERROR(ict, ISCSI_STATUS_CLASS_TARGET_ERR,
1746 		    ISCSI_LOGIN_STATUS_TARGET_ERROR);
1747 		return (IDM_STATUS_FAIL);
1748 	}
1749 
1750 	ss->ss_port_private = ict->ict_sess;
1751 	ict->ict_sess->ist_stmf_sess = ss;
1752 	mutex_exit(&ist->ist_tgt->target_mutex);
1753 
1754 	return (IDM_STATUS_SUCCESS);
1755 }
1756 
1757 
1758 static idm_status_t
1759 login_sm_req_pdu_check(iscsit_conn_t *ict, idm_pdu_t *pdu)
1760 {
1761 	uint8_t			csg_req;
1762 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1763 	iscsi_login_hdr_t	*lh = (iscsi_login_hdr_t *)pdu->isp_hdr;
1764 	iscsi_login_rsp_hdr_t *lh_resp = lsm->icl_login_resp_tmpl;
1765 
1766 	/*
1767 	 * Check CSG
1768 	 */
1769 	csg_req = ISCSI_LOGIN_CURRENT_STAGE(lh->flags);
1770 	switch (csg_req) {
1771 	case ISCSI_SECURITY_NEGOTIATION_STAGE:
1772 	case ISCSI_OP_PARMS_NEGOTIATION_STAGE:
1773 		if ((csg_req != lsm->icl_login_csg) &&
1774 		    (lsm->icl_login_state != ILS_LOGIN_INIT)) {
1775 			/*
1776 			 * Inappropriate CSG change.  Initiator can only
1777 			 * change CSG after we've responded with the
1778 			 * transit bit set.  If we had responded with
1779 			 * a CSG change previous we would have updated
1780 			 * our copy of CSG.
1781 			 *
1782 			 * The exception is when we are in ILS_LOGIN_INIT
1783 			 * state since we haven't determined our initial
1784 			 * CSG value yet.
1785 			 */
1786 			goto pdu_check_fail;
1787 		}
1788 		break;
1789 	case ISCSI_FULL_FEATURE_PHASE:
1790 	default:
1791 		goto pdu_check_fail;
1792 	}
1793 
1794 	/*
1795 	 * If this is the first login PDU for a new connection then
1796 	 * the session will be NULL.
1797 	 */
1798 	if (ict->ict_sess != NULL) {
1799 		/*
1800 		 * We've already created a session on a previous PDU.  Make
1801 		 * sure this PDU is consistent with what we've already seen
1802 		 */
1803 		if ((ict->ict_cid != ntohs(lh->cid)) ||
1804 		    (bcmp(ict->ict_sess->ist_isid, lh->isid,
1805 		    ISCSI_ISID_LEN) != 0)) {
1806 			goto pdu_check_fail;
1807 		}
1808 	}
1809 
1810 	/*
1811 	 * Make sure we are compatible with the version range
1812 	 */
1813 #if (ISCSIT_MAX_VERSION > 0)
1814 	if ((lh->min_version > ISCSIT_MAX_VERSION) ||
1815 	    (lh->max_version < ISCSIT_MIN_VERSION)) {
1816 		goto pdu_check_fail;
1817 	}
1818 #endif
1819 
1820 	/*
1821 	 * Just in case the initiator changes things up on us along the way
1822 	 * check against our active_version -- we can't change the active
1823 	 * version and the initiator is not *supposed* to change its
1824 	 * min_version and max_version values so this should never happen.
1825 	 * Of course we only do this if the response header template has
1826 	 * been built.
1827 	 */
1828 	if ((lh_resp->opcode == ISCSI_OP_LOGIN_RSP) && /* header valid */
1829 	    ((lh->min_version > lh_resp->active_version) ||
1830 	    (lh->max_version < lh_resp->active_version))) {
1831 		goto pdu_check_fail;
1832 	}
1833 
1834 	return (IDM_STATUS_SUCCESS);
1835 
1836 pdu_check_fail:
1837 	return (IDM_STATUS_FAIL);
1838 }
1839 
1840 static idm_status_t
1841 login_sm_process_nvlist(iscsit_conn_t *ict)
1842 {
1843 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1844 	char			*nvp_name;
1845 	nvpair_t		*nvp;
1846 	nvpair_t		*next_nvp;
1847 	nvpair_t		*negotiated_nvp;
1848 	kv_status_t		kvrc;
1849 	uint8_t			error_class;
1850 	uint8_t			error_detail;
1851 	idm_status_t		idm_status;
1852 
1853 	error_class = ISCSI_STATUS_CLASS_SUCCESS;
1854 	error_detail = ISCSI_LOGIN_STATUS_ACCEPT;
1855 
1856 	/* First, request that the transport process the list */
1857 	kvrc = idm_negotiate_key_values(ict->ict_ic, lsm->icl_request_nvlist,
1858 	    lsm->icl_response_nvlist, lsm->icl_negotiated_values);
1859 	idm_kvstat_to_error(kvrc, &error_class, &error_detail);
1860 	if (error_class != ISCSI_STATUS_CLASS_SUCCESS) {
1861 		SET_LOGIN_ERROR(ict, error_class, error_detail);
1862 		idm_status = IDM_STATUS_FAIL;
1863 		return (idm_status);
1864 	}
1865 
1866 	/* Ensure we clear transit bit if the transport layer has countered */
1867 	if (kvrc == KV_HANDLED_NO_TRANSIT) {
1868 		lsm->icl_login_transit = B_FALSE;
1869 	}
1870 
1871 	/* Prepend the declarative params */
1872 	if (!ict->ict_op.op_declarative_params_set &&
1873 	    lsm->icl_login_csg == ISCSI_OP_PARMS_NEGOTIATION_STAGE) {
1874 		if (iscsit_add_declarative_keys(ict) != IDM_STATUS_SUCCESS) {
1875 			idm_status = IDM_STATUS_FAIL;
1876 			return (idm_status);
1877 		}
1878 		ict->ict_op.op_declarative_params_set = B_TRUE;
1879 	}
1880 
1881 	/* Now, move on and process the rest of the pairs */
1882 	nvp = nvlist_next_nvpair(lsm->icl_request_nvlist, NULL);
1883 	while (nvp != NULL) {
1884 		next_nvp = nvlist_next_nvpair(lsm->icl_request_nvlist, nvp);
1885 		nvp_name = nvpair_name(nvp);
1886 		/*
1887 		 * If we've already agreed upon a value then make sure this
1888 		 * is not attempting to change that value.  From RFC3270
1889 		 * section 5.3:
1890 		 *
1891 		 * "Neither the initiator nor the target should attempt to
1892 		 * declare or negotiate a parameter more than once during
1893 		 * login except for responses to specific keys that
1894 		 * explicitly allow repeated key declarations (e.g.,
1895 		 * TargetAddress).  An attempt to renegotiate/redeclare
1896 		 * parameters not specifically allowed MUST be detected
1897 		 * by the initiator and target.  If such an attempt is
1898 		 * detected by the target, the target MUST respond
1899 		 * with Login reject (initiator error); ..."
1900 		 */
1901 		if (nvlist_lookup_nvpair(lsm->icl_negotiated_values,
1902 		    nvp_name, &negotiated_nvp) == 0) {
1903 			kvrc = KV_HANDLED;
1904 		} else {
1905 			kvrc = iscsit_handle_key(ict, nvp, nvp_name);
1906 		}
1907 
1908 		idm_kvstat_to_error(kvrc, &error_class, &error_detail);
1909 		if (error_class != ISCSI_STATUS_CLASS_SUCCESS) {
1910 			break;
1911 		}
1912 
1913 		nvp = next_nvp;
1914 	}
1915 
1916 	if (error_class == ISCSI_STATUS_CLASS_SUCCESS) {
1917 		idm_status = IDM_STATUS_SUCCESS;
1918 	} else {
1919 		/* supply login class/detail for login errors */
1920 		SET_LOGIN_ERROR(ict, error_class, error_detail);
1921 		idm_status = IDM_STATUS_FAIL;
1922 	}
1923 
1924 	return (idm_status);
1925 }
1926 
1927 static idm_status_t
1928 login_sm_check_security(iscsit_conn_t *ict)
1929 {
1930 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1931 	conn_auth_t		*auth = &lsm->icl_auth;
1932 	iscsit_auth_method_t	*am_list = &auth->ca_method_valid_list[0];
1933 	kv_status_t		kvrc;
1934 	uint8_t			error_class;
1935 	uint8_t			error_detail;
1936 	idm_status_t		idm_status;
1937 
1938 	error_class = ISCSI_STATUS_CLASS_SUCCESS;
1939 	error_detail = ISCSI_LOGIN_STATUS_ACCEPT;
1940 
1941 	/* Check authentication status. */
1942 	if (lsm->icl_login_csg == ISCSI_SECURITY_NEGOTIATION_STAGE) {
1943 		/*
1944 		 * We should have some authentication key/value pair(s)
1945 		 * received from initiator and the authentication phase
1946 		 * has been shifted when the key/value pair(s) are being
1947 		 * handled in the previous call iscsit_handle_security_key.
1948 		 * Now it turns to target to check the authentication phase
1949 		 * and shift it after taking some authentication action.
1950 		 */
1951 		kvrc = iscsit_reply_security_key(ict);
1952 		idm_kvstat_to_error(kvrc, &error_class, &error_detail);
1953 	} else if (!ict->ict_login_sm.icl_auth_pass) {
1954 		/*
1955 		 * Check to see if the target allows initiators to bypass the
1956 		 * security check.  If the target is configured to require
1957 		 * authentication, we reject the connection.
1958 		 */
1959 		if (am_list[0] == AM_NONE || am_list[0] == 0) {
1960 			ict->ict_login_sm.icl_auth_pass = 1;
1961 		} else {
1962 			error_class = ISCSI_STATUS_CLASS_INITIATOR_ERR;
1963 			error_detail = ISCSI_LOGIN_STATUS_AUTH_FAILED;
1964 		}
1965 	}
1966 
1967 	if (error_class == ISCSI_STATUS_CLASS_SUCCESS) {
1968 		idm_status = IDM_STATUS_SUCCESS;
1969 	} else {
1970 		/* supply login class/detail for login errors */
1971 		SET_LOGIN_ERROR(ict, error_class, error_detail);
1972 		idm_status = IDM_STATUS_FAIL;
1973 	}
1974 
1975 	return (idm_status);
1976 }
1977 
1978 static idm_pdu_t *
1979 login_sm_build_login_response(iscsit_conn_t *ict)
1980 {
1981 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
1982 	iscsi_login_rsp_hdr_t	*lh;
1983 	int			transit, text_transit = 1;
1984 	idm_pdu_t		*login_resp;
1985 
1986 	/*
1987 	 * Create a response PDU and fill it with as much of
1988 	 * the response text that will fit.
1989 	 */
1990 
1991 	if (lsm->icl_login_resp_itb) {
1992 		/* allocate a pdu with space for text */
1993 		login_resp = idm_pdu_alloc(sizeof (iscsi_hdr_t),
1994 		    ISCSI_DEFAULT_MAX_RECV_SEG_LEN);
1995 		/* copy a chunk of text into the pdu */
1996 		lsm->icl_login_resp_buf = idm_pdu_init_text_data(
1997 		    login_resp, lsm->icl_login_resp_itb,
1998 		    ISCSI_DEFAULT_MAX_RECV_SEG_LEN,
1999 		    lsm->icl_login_resp_buf, &text_transit);
2000 		if (text_transit) {
2001 			/* text buf has been consumed */
2002 			idm_itextbuf_free(lsm->icl_login_resp_itb);
2003 			lsm->icl_login_resp_itb = NULL;
2004 			lsm->icl_login_resp_buf = NULL;
2005 		}
2006 	} else {
2007 		/* allocate a pdu for just a header */
2008 		login_resp = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
2009 	}
2010 	/* finish initializing the pdu */
2011 	idm_pdu_init(login_resp,
2012 	    ict->ict_ic, ict, login_resp_complete_cb);
2013 	login_resp->isp_flags |= IDM_PDU_LOGIN_TX;
2014 
2015 	/*
2016 	 * Use the BHS header values from the response template
2017 	 */
2018 	bcopy(lsm->icl_login_resp_tmpl,
2019 	    login_resp->isp_hdr, sizeof (iscsi_login_rsp_hdr_t));
2020 
2021 	lh = (iscsi_login_rsp_hdr_t *)login_resp->isp_hdr;
2022 
2023 	/* Set error class/detail */
2024 	lh->status_class = lsm->icl_login_resp_err_class;
2025 	lh->status_detail = lsm->icl_login_resp_err_detail;
2026 	/* Set CSG, NSG and Transit */
2027 	lh->flags = 0;
2028 	lh->flags |= lsm->icl_login_csg << 2;
2029 
2030 
2031 	if (lh->status_class == ISCSI_STATUS_CLASS_SUCCESS) {
2032 		if (lsm->icl_login_transit &&
2033 		    lsm->icl_auth_pass != 0) {
2034 			transit = 1;
2035 		} else {
2036 			transit = 0;
2037 		}
2038 		/*
2039 		 * inititalize the text data
2040 		 */
2041 		if (transit == 1 && text_transit == 1) {
2042 			lh->flags |= lsm->icl_login_nsg;
2043 			lsm->icl_login_csg = lsm->icl_login_nsg;
2044 			lh->flags |= ISCSI_FLAG_LOGIN_TRANSIT;
2045 		} else {
2046 			lh->flags &= ~ISCSI_FLAG_LOGIN_TRANSIT;
2047 		}
2048 
2049 		/* If we are transitioning to FFP then set TSIH */
2050 		if (transit && (lh->flags & ISCSI_FLAG_LOGIN_TRANSIT) &&
2051 		    lsm->icl_login_csg == ISCSI_FULL_FEATURE_PHASE) {
2052 			lh->tsid = htons(ict->ict_sess->ist_tsih);
2053 		}
2054 	} else {
2055 		login_resp->isp_data = 0;
2056 		login_resp->isp_datalen = 0;
2057 	}
2058 	return (login_resp);
2059 }
2060 
2061 static kv_status_t
2062 iscsit_handle_key(iscsit_conn_t *ict, nvpair_t *nvp, char *nvp_name)
2063 {
2064 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2065 	kv_status_t		kvrc;
2066 	const idm_kv_xlate_t	*ikvx;
2067 
2068 	ikvx = idm_lookup_kv_xlate(nvp_name, strlen(nvp_name));
2069 	if (ikvx->ik_key_id == KI_MAX_KEY) {
2070 		/*
2071 		 * Any key not understood by the acceptor may be igonred
2072 		 * by the acceptor without affecting the basic function.
2073 		 * However, the answer for a key not understood MUST be
2074 		 * key=NotUnderstood.
2075 		 */
2076 		kvrc = iscsit_reply_string(ict, nvp_name,
2077 		    ISCSI_TEXT_NOTUNDERSTOOD);
2078 	} else {
2079 		kvrc = iscsit_handle_common_key(ict, nvp, ikvx);
2080 		if (kvrc == KV_UNHANDLED) {
2081 			switch (lsm->icl_login_csg) {
2082 			case ISCSI_SECURITY_NEGOTIATION_STAGE:
2083 				kvrc = iscsit_handle_security_key(
2084 				    ict, nvp, ikvx);
2085 				break;
2086 			case ISCSI_OP_PARMS_NEGOTIATION_STAGE:
2087 				kvrc = iscsit_handle_operational_key(
2088 				    ict, nvp, ikvx);
2089 				break;
2090 			case ISCSI_FULL_FEATURE_PHASE:
2091 			default:
2092 				/* What are we doing here? */
2093 				ASSERT(0);
2094 				kvrc = KV_UNHANDLED;
2095 			}
2096 		}
2097 	}
2098 
2099 	return (kvrc);
2100 }
2101 
2102 static kv_status_t
2103 iscsit_handle_common_key(iscsit_conn_t *ict, nvpair_t *nvp,
2104     const idm_kv_xlate_t *ikvx)
2105 {
2106 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2107 	kv_status_t		kvrc;
2108 	char			*string_val;
2109 	int			nvrc;
2110 
2111 	switch (ikvx->ik_key_id) {
2112 	case KI_INITIATOR_NAME:
2113 	case KI_INITIATOR_ALIAS:
2114 		nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values, nvp);
2115 		kvrc = idm_nvstat_to_kvstat(nvrc);
2116 		break;
2117 	case KI_TARGET_NAME:
2118 		/* We'll validate the target during login_sm_session_bind() */
2119 		nvrc = nvpair_value_string(nvp, &string_val);
2120 		ASSERT(nvrc == 0); /* We built this nvlist */
2121 
2122 		nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values, nvp);
2123 		kvrc = idm_nvstat_to_kvstat(nvrc);
2124 		break;
2125 	case KI_TARGET_ALIAS:
2126 	case KI_TARGET_ADDRESS:
2127 	case KI_TARGET_PORTAL_GROUP_TAG:
2128 		kvrc = KV_TARGET_ONLY; /* Only the target can declare this */
2129 		break;
2130 	case KI_SESSION_TYPE:
2131 		/*
2132 		 * If we don't receive this key on the initial login
2133 		 * we assume this is a normal session.
2134 		 */
2135 		nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values, nvp);
2136 		kvrc = idm_nvstat_to_kvstat(nvrc);
2137 		nvrc = nvpair_value_string(nvp, &string_val);
2138 		ASSERT(nvrc == 0); /* We built this nvlist */
2139 		ict->ict_op.op_discovery_session =
2140 		    strcmp(string_val, "Discovery") == 0 ? B_TRUE : B_FALSE;
2141 		break;
2142 	default:
2143 		/*
2144 		 * This is not really an error but we should
2145 		 * leave this nvpair on the list since we
2146 		 * didn't do anything with it.  Either
2147 		 * the security or operational phase
2148 		 * handling functions should process it.
2149 		 */
2150 		kvrc = KV_UNHANDLED;
2151 		break;
2152 	}
2153 
2154 	return (kvrc);
2155 }
2156 
2157 static kv_status_t
2158 iscsit_handle_security_key(iscsit_conn_t *ict, nvpair_t *nvp,
2159     const idm_kv_xlate_t *ikvx)
2160 {
2161 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2162 	iscsit_auth_client_t	*client = &lsm->icl_auth_client;
2163 	iscsikey_id_t		kv_id;
2164 	kv_status_t		kvrc;
2165 	iscsit_auth_handler_t	handler;
2166 
2167 	/*
2168 	 * After all of security keys are handled, this function will
2169 	 * be called again to verify current authentication status
2170 	 * and perform some actual authentication work. At this time,
2171 	 * the nvp and ikvx will be passed in as NULLs.
2172 	 */
2173 	if (ikvx != NULL) {
2174 		kv_id = ikvx->ik_key_id;
2175 	} else {
2176 		kv_id = 0;
2177 	}
2178 
2179 	handler = iscsit_auth_get_handler(client, kv_id);
2180 	if (handler) {
2181 		kvrc = handler(ict, nvp, ikvx);
2182 	} else {
2183 		kvrc = KV_UNHANDLED; /* invalid request */
2184 	}
2185 
2186 	return (kvrc);
2187 }
2188 
2189 static kv_status_t
2190 iscsit_reply_security_key(iscsit_conn_t *ict)
2191 {
2192 	return (iscsit_handle_security_key(ict, NULL, NULL));
2193 }
2194 
2195 static kv_status_t
2196 iscsit_handle_operational_key(iscsit_conn_t *ict, nvpair_t *nvp,
2197     const idm_kv_xlate_t *ikvx)
2198 {
2199 	kv_status_t		kvrc = KV_UNHANDLED;
2200 	boolean_t		bool_val;
2201 	uint64_t		num_val;
2202 	int			nvrc;
2203 
2204 	/*
2205 	 * Retrieve values.  All value lookups are expected to succeed
2206 	 * since we build the nvlist while decoding the text buffer.  This
2207 	 * step is intended to eliminate some duplication of code (for example
2208 	 * we only need to code the numerical value lookup once).  We will
2209 	 * handle the values (if necessary) below.
2210 	 */
2211 	switch (ikvx->ik_key_id) {
2212 		/* Lists */
2213 	case KI_HEADER_DIGEST:
2214 	case KI_DATA_DIGEST:
2215 		break;
2216 		/* Booleans */
2217 	case KI_INITIAL_R2T:
2218 	case KI_IMMEDIATE_DATA:
2219 	case KI_DATA_PDU_IN_ORDER:
2220 	case KI_DATA_SEQUENCE_IN_ORDER:
2221 	case KI_IFMARKER:
2222 	case KI_OFMARKER:
2223 		nvrc = nvpair_value_boolean_value(nvp, &bool_val);
2224 		ASSERT(nvrc == 0); /* We built this nvlist */
2225 		break;
2226 		/* Numericals */
2227 	case KI_MAX_CONNECTIONS:
2228 	case KI_MAX_RECV_DATA_SEGMENT_LENGTH:
2229 	case KI_MAX_BURST_LENGTH:
2230 	case KI_FIRST_BURST_LENGTH:
2231 	case KI_DEFAULT_TIME_2_WAIT:
2232 	case KI_DEFAULT_TIME_2_RETAIN:
2233 	case KI_MAX_OUTSTANDING_R2T:
2234 	case KI_ERROR_RECOVERY_LEVEL:
2235 		nvrc = nvpair_value_uint64(nvp, &num_val);
2236 		ASSERT(nvrc == 0);
2237 		break;
2238 		/* Ranges */
2239 	case KI_OFMARKERINT:
2240 	case KI_IFMARKERINT:
2241 		break;
2242 	default:
2243 		break;
2244 	}
2245 
2246 	/*
2247 	 * Now handle the values according to the key name.  Sometimes we
2248 	 * don't care what the value is -- in that case we just add the nvpair
2249 	 * to the negotiated values list.
2250 	 */
2251 	switch (ikvx->ik_key_id) {
2252 	case KI_HEADER_DIGEST:
2253 		kvrc = iscsit_handle_digest(ict, nvp, ikvx);
2254 		break;
2255 	case KI_DATA_DIGEST:
2256 		kvrc = iscsit_handle_digest(ict, nvp, ikvx);
2257 		break;
2258 	case KI_INITIAL_R2T:
2259 		/* We *require* INITIAL_R2T=yes */
2260 		kvrc = iscsit_handle_boolean(ict, nvp, bool_val, ikvx,
2261 		    B_TRUE);
2262 		break;
2263 	case KI_IMMEDIATE_DATA:
2264 		kvrc = iscsit_handle_boolean(ict, nvp, bool_val, ikvx,
2265 		    bool_val);
2266 		break;
2267 	case KI_DATA_PDU_IN_ORDER:
2268 		kvrc = iscsit_handle_boolean(ict, nvp, bool_val, ikvx,
2269 		    B_TRUE);
2270 		break;
2271 	case KI_DATA_SEQUENCE_IN_ORDER:
2272 		/* We allow any value for DATA_SEQUENCE_IN_ORDER */
2273 		kvrc = iscsit_handle_boolean(ict, nvp, bool_val, ikvx,
2274 		    bool_val);
2275 		break;
2276 	case KI_OFMARKER:
2277 	case KI_IFMARKER:
2278 		/* We don't support markers */
2279 		kvrc = iscsit_handle_boolean(ict, nvp, bool_val, ikvx,
2280 		    B_FALSE);
2281 		break;
2282 	case KI_MAX_CONNECTIONS:
2283 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2284 		    ISCSI_MIN_CONNECTIONS,
2285 		    ISCSI_MAX_CONNECTIONS,
2286 		    ISCSIT_MAX_CONNECTIONS);
2287 		break;
2288 		/* this is a declartive param */
2289 	case KI_MAX_RECV_DATA_SEGMENT_LENGTH:
2290 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2291 		    ISCSI_MIN_RECV_DATA_SEGMENT_LENGTH,
2292 		    ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH,
2293 		    ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
2294 		break;
2295 	case KI_MAX_BURST_LENGTH:
2296 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2297 		    ISCSI_MIN_MAX_BURST_LENGTH,
2298 		    ISCSI_MAX_BURST_LENGTH,
2299 		    ISCSIT_MAX_BURST_LENGTH);
2300 		break;
2301 	case KI_FIRST_BURST_LENGTH:
2302 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2303 		    ISCSI_MIN_FIRST_BURST_LENGTH,
2304 		    ISCSI_MAX_FIRST_BURST_LENGTH,
2305 		    ISCSIT_MAX_FIRST_BURST_LENGTH);
2306 		break;
2307 	case KI_DEFAULT_TIME_2_WAIT:
2308 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2309 		    ISCSI_MIN_TIME2WAIT,
2310 		    ISCSI_MAX_TIME2WAIT,
2311 		    ISCSIT_MAX_TIME2WAIT);
2312 		break;
2313 	case KI_DEFAULT_TIME_2_RETAIN:
2314 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2315 		    ISCSI_MIN_TIME2RETAIN,
2316 		    ISCSI_MAX_TIME2RETAIN,
2317 		    ISCSIT_MAX_TIME2RETAIN);
2318 		break;
2319 	case KI_MAX_OUTSTANDING_R2T:
2320 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2321 		    ISCSI_MIN_MAX_OUTSTANDING_R2T,
2322 		    ISCSI_MAX_OUTSTANDING_R2T,
2323 		    ISCSIT_MAX_OUTSTANDING_R2T);
2324 		break;
2325 	case KI_ERROR_RECOVERY_LEVEL:
2326 		kvrc = iscsit_handle_numerical(ict, nvp, num_val, ikvx,
2327 		    ISCSI_MIN_ERROR_RECOVERY_LEVEL,
2328 		    ISCSI_MAX_ERROR_RECOVERY_LEVEL,
2329 		    ISCSIT_MAX_ERROR_RECOVERY_LEVEL);
2330 		break;
2331 	case KI_OFMARKERINT:
2332 	case KI_IFMARKERINT:
2333 		kvrc = iscsit_reply_string(ict, ikvx->ik_key_name,
2334 		    ISCSI_TEXT_IRRELEVANT);
2335 		break;
2336 	default:
2337 		kvrc = KV_UNHANDLED; /* invalid request */
2338 		break;
2339 	}
2340 
2341 	return (kvrc);
2342 }
2343 
2344 static kv_status_t
2345 iscsit_reply_numerical(iscsit_conn_t *ict,
2346     const char *nvp_name, const uint64_t value)
2347 {
2348 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2349 	kv_status_t		kvrc;
2350 	int			nvrc;
2351 
2352 	nvrc = nvlist_add_uint64(lsm->icl_response_nvlist,
2353 	    nvp_name, value);
2354 	kvrc = idm_nvstat_to_kvstat(nvrc);
2355 
2356 	return (kvrc);
2357 }
2358 
2359 static kv_status_t
2360 iscsit_reply_string(iscsit_conn_t *ict,
2361     const char *nvp_name, const char *text)
2362 {
2363 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2364 	kv_status_t		kvrc;
2365 	int			nvrc;
2366 
2367 	nvrc = nvlist_add_string(lsm->icl_response_nvlist,
2368 	    nvp_name, text);
2369 	kvrc = idm_nvstat_to_kvstat(nvrc);
2370 
2371 	return (kvrc);
2372 }
2373 
2374 static kv_status_t
2375 iscsit_handle_digest(iscsit_conn_t *ict, nvpair_t *choices,
2376     const idm_kv_xlate_t *ikvx)
2377 {
2378 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2379 	kv_status_t		kvrc = KV_VALUE_ERROR;
2380 	int			nvrc;
2381 	nvpair_t		*digest_choice;
2382 	char			*digest_choice_string;
2383 
2384 	/*
2385 	 * Need to add persistent config here if we want users to allow
2386 	 * disabling of digests on the target side.  You could argue that
2387 	 * this makes things too complicated... just let the initiator state
2388 	 * what it wants and we'll take it.  For now that's exactly what
2389 	 * we'll do.
2390 	 *
2391 	 * Basic digest negotiation happens here at iSCSI level.   IDM
2392 	 * can override this during negotiate_key_values phase to
2393 	 * decline to set up any digest processing.
2394 	 */
2395 	digest_choice = idm_get_next_listvalue(choices, NULL);
2396 
2397 	/*
2398 	 * Loop through all choices.  As soon as we find a choice
2399 	 * that we support add the value to our negotiated values list
2400 	 * and respond with that value in the login response.
2401 	 */
2402 	while (digest_choice != NULL) {
2403 		nvrc = nvpair_value_string(digest_choice,
2404 		    &digest_choice_string);
2405 		ASSERT(nvrc == 0);
2406 
2407 		if ((strcasecmp(digest_choice_string, "crc32c") == 0) ||
2408 		    (strcasecmp(digest_choice_string, "none") == 0)) {
2409 			/* Add to negotiated values list */
2410 			nvrc = nvlist_add_string(lsm->icl_negotiated_values,
2411 			    ikvx->ik_key_name, digest_choice_string);
2412 			kvrc = idm_nvstat_to_kvstat(nvrc);
2413 			if (nvrc == 0) {
2414 				/* Add to login response list */
2415 				nvrc = nvlist_add_string(
2416 				    lsm->icl_response_nvlist,
2417 				    ikvx->ik_key_name, digest_choice_string);
2418 				kvrc = idm_nvstat_to_kvstat(nvrc);
2419 			}
2420 			break;
2421 		}
2422 		digest_choice = idm_get_next_listvalue(choices,
2423 		    digest_choice);
2424 	}
2425 
2426 	if (digest_choice == NULL)
2427 		kvrc = KV_VALUE_ERROR;
2428 
2429 	return (kvrc);
2430 }
2431 
2432 static kv_status_t
2433 iscsit_handle_boolean(iscsit_conn_t *ict, nvpair_t *nvp, boolean_t value,
2434     const idm_kv_xlate_t *ikvx, boolean_t iscsit_value)
2435 {
2436 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2437 	kv_status_t		kvrc;
2438 	int			nvrc;
2439 
2440 	if (ikvx->ik_declarative) {
2441 		nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values, nvp);
2442 	} else {
2443 		if (value != iscsit_value) {
2444 			/* Respond back to initiator with our value */
2445 			value = iscsit_value;
2446 			lsm->icl_login_transit = B_FALSE;
2447 			nvrc = 0;
2448 		} else {
2449 			/* Add this to our negotiated values */
2450 			nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values,
2451 			    nvp);
2452 		}
2453 
2454 		/* Response of Simple-value Negotiation */
2455 		if (nvrc == 0) {
2456 			nvrc = nvlist_add_boolean_value(
2457 			    lsm->icl_response_nvlist, ikvx->ik_key_name, value);
2458 		}
2459 	}
2460 
2461 	kvrc = idm_nvstat_to_kvstat(nvrc);
2462 
2463 	return (kvrc);
2464 }
2465 
2466 static kv_status_t
2467 iscsit_handle_numerical(iscsit_conn_t *ict, nvpair_t *nvp, uint64_t value,
2468     const idm_kv_xlate_t *ikvx,
2469     uint64_t iscsi_min_value, uint64_t iscsi_max_value,
2470     uint64_t iscsit_max_value)
2471 {
2472 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2473 	kv_status_t		kvrc;
2474 	int			nvrc;
2475 
2476 	/* Validate against standard */
2477 	if ((value < iscsi_min_value) || (value > iscsi_max_value)) {
2478 		kvrc = KV_VALUE_ERROR;
2479 	} else if (ikvx->ik_declarative) {
2480 		nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values, nvp);
2481 		kvrc = idm_nvstat_to_kvstat(nvrc);
2482 	} else {
2483 		if (value > iscsit_max_value) {
2484 			/* Respond back to initiator with our value */
2485 			value = iscsit_max_value;
2486 			lsm->icl_login_transit = B_FALSE;
2487 			nvrc = 0;
2488 		} else {
2489 			/* Add this to our negotiated values */
2490 			nvrc = nvlist_add_nvpair(lsm->icl_negotiated_values,
2491 			    nvp);
2492 		}
2493 
2494 		/* Response of Simple-value Negotiation */
2495 		if (nvrc == 0) {
2496 			nvrc = nvlist_add_uint64(lsm->icl_response_nvlist,
2497 			    ikvx->ik_key_name, value);
2498 		}
2499 		kvrc = idm_nvstat_to_kvstat(nvrc);
2500 	}
2501 
2502 	return (kvrc);
2503 }
2504 
2505 
2506 static void
2507 iscsit_process_negotiated_values(iscsit_conn_t *ict)
2508 {
2509 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2510 	char			*string_val;
2511 	boolean_t		boolean_val;
2512 	uint64_t		uint64_val;
2513 	int			nvrc;
2514 
2515 	/* Let the IDM level activate its parameters first */
2516 	idm_notice_key_values(ict->ict_ic, lsm->icl_negotiated_values);
2517 
2518 	/*
2519 	 * Initiator alias and target alias
2520 	 */
2521 	if ((nvrc = nvlist_lookup_string(lsm->icl_negotiated_values,
2522 	    "InitiatorAlias", &string_val)) != ENOENT) {
2523 		ASSERT(nvrc == 0);
2524 		ict->ict_sess->ist_initiator_alias =
2525 		    kmem_alloc(strlen(string_val) + 1, KM_SLEEP);
2526 		(void) strcpy(ict->ict_sess->ist_initiator_alias, string_val);
2527 	}
2528 
2529 	if ((nvrc = nvlist_lookup_string(lsm->icl_negotiated_values,
2530 	    "TargetAlias", &string_val)) != ENOENT) {
2531 		ASSERT(nvrc == 0);
2532 		ict->ict_sess->ist_target_alias =
2533 		    kmem_alloc(strlen(string_val) + 1, KM_SLEEP);
2534 		(void) strcpy(ict->ict_sess->ist_target_alias, string_val);
2535 	}
2536 
2537 	/*
2538 	 * Operational parameters.  We process SessionType when it is
2539 	 * initially received since it is required on the initial login.
2540 	 */
2541 	if ((nvrc = nvlist_lookup_boolean_value(lsm->icl_negotiated_values,
2542 	    "InitialR2T", &boolean_val)) != ENOENT) {
2543 		ASSERT(nvrc == 0);
2544 		ict->ict_op.op_initial_r2t = boolean_val;
2545 	}
2546 
2547 	if ((nvrc = nvlist_lookup_boolean_value(lsm->icl_negotiated_values,
2548 	    "ImmediateData", &boolean_val)) != ENOENT) {
2549 		ASSERT(nvrc == 0);
2550 		ict->ict_op.op_immed_data = boolean_val;
2551 	}
2552 
2553 	if ((nvrc = nvlist_lookup_boolean_value(lsm->icl_negotiated_values,
2554 	    "DataPDUInOrder", &boolean_val)) != ENOENT) {
2555 		ASSERT(nvrc == 0);
2556 		ict->ict_op.op_data_pdu_in_order = boolean_val;
2557 	}
2558 
2559 	if ((nvrc = nvlist_lookup_boolean_value(lsm->icl_negotiated_values,
2560 	    "DataSequenceInOrder", &boolean_val)) != ENOENT) {
2561 		ASSERT(nvrc == 0);
2562 		ict->ict_op.op_data_sequence_in_order = boolean_val;
2563 	}
2564 
2565 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2566 	    "MaxConnections", &uint64_val)) != ENOENT) {
2567 		ASSERT(nvrc == 0);
2568 		ict->ict_op.op_max_connections = uint64_val;
2569 	}
2570 
2571 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2572 	    "MaxRecvDataSegmentLength", &uint64_val)) != ENOENT) {
2573 		ASSERT(nvrc == 0);
2574 		ict->ict_op.op_max_recv_data_segment_length = uint64_val;
2575 	}
2576 
2577 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2578 	    "MaxBurstLength", &uint64_val)) != ENOENT) {
2579 		ASSERT(nvrc == 0);
2580 		ict->ict_op.op_max_burst_length = uint64_val;
2581 	}
2582 
2583 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2584 	    "FirstBurstLength", &uint64_val)) != ENOENT) {
2585 		ASSERT(nvrc == 0);
2586 		ict->ict_op.op_first_burst_length = uint64_val;
2587 	}
2588 
2589 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2590 	    "DefaultTime2Wait", &uint64_val)) != ENOENT) {
2591 		ASSERT(nvrc == 0);
2592 		ict->ict_op.op_default_time_2_wait = uint64_val;
2593 	}
2594 
2595 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2596 	    "DefaultTime2Retain", &uint64_val)) != ENOENT) {
2597 		ASSERT(nvrc == 0);
2598 		ict->ict_op.op_default_time_2_retain = uint64_val;
2599 	}
2600 
2601 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2602 	    "MaxOutstandingR2T", &uint64_val)) != ENOENT) {
2603 		ASSERT(nvrc == 0);
2604 		ict->ict_op.op_max_outstanding_r2t = uint64_val;
2605 	}
2606 
2607 	if ((nvrc = nvlist_lookup_uint64(lsm->icl_negotiated_values,
2608 	    "ErrorRecoveryLevel", &uint64_val)) != ENOENT) {
2609 		ASSERT(nvrc == 0);
2610 		ict->ict_op.op_error_recovery_level = uint64_val;
2611 	}
2612 }
2613 
2614 static idm_status_t
2615 iscsit_add_declarative_keys(iscsit_conn_t *ict)
2616 {
2617 	nvlist_t		*cfg_nv = NULL;
2618 	kv_status_t		kvrc;
2619 	int			nvrc;
2620 	iscsit_conn_login_t	*lsm = &ict->ict_login_sm;
2621 	uint8_t			error_class;
2622 	uint8_t			error_detail;
2623 	idm_status_t		idm_status;
2624 
2625 	if ((nvrc = nvlist_alloc(&cfg_nv, NV_UNIQUE_NAME, KM_NOSLEEP)) != 0) {
2626 		kvrc = idm_nvstat_to_kvstat(nvrc);
2627 		goto alloc_fail;
2628 	}
2629 	if ((nvrc = nvlist_add_uint64(cfg_nv, "MaxRecvDataSegmentLength",
2630 	    max_dataseglen_target)) != 0) {
2631 		kvrc = idm_nvstat_to_kvstat(nvrc);
2632 		goto done;
2633 	}
2634 
2635 	kvrc = idm_declare_key_values(ict->ict_ic, cfg_nv,
2636 	    lsm->icl_response_nvlist);
2637 done:
2638 	nvlist_free(cfg_nv);
2639 alloc_fail:
2640 	idm_kvstat_to_error(kvrc, &error_class, &error_detail);
2641 	if (error_class == ISCSI_STATUS_CLASS_SUCCESS) {
2642 		idm_status = IDM_STATUS_SUCCESS;
2643 	} else {
2644 		SET_LOGIN_ERROR(ict, error_class, error_detail);
2645 		idm_status = IDM_STATUS_FAIL;
2646 	}
2647 	return (idm_status);
2648 }
2649