xref: /openbmc/linux/drivers/scsi/libiscsi.c (revision df687341)
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */
24 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <linux/log2.h>
28 #include <linux/slab.h>
29 #include <linux/sched/signal.h>
30 #include <linux/module.h>
31 #include <asm/unaligned.h>
32 #include <net/tcp.h>
33 #include <scsi/scsi_cmnd.h>
34 #include <scsi/scsi_device.h>
35 #include <scsi/scsi_eh.h>
36 #include <scsi/scsi_tcq.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi.h>
39 #include <scsi/iscsi_proto.h>
40 #include <scsi/scsi_transport.h>
41 #include <scsi/scsi_transport_iscsi.h>
42 #include <scsi/libiscsi.h>
43 #include <trace/events/iscsi.h>
44 
45 static int iscsi_dbg_lib_conn;
46 module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int,
47 		   S_IRUGO | S_IWUSR);
48 MODULE_PARM_DESC(debug_libiscsi_conn,
49 		 "Turn on debugging for connections in libiscsi module. "
50 		 "Set to 1 to turn on, and zero to turn off. Default is off.");
51 
52 static int iscsi_dbg_lib_session;
53 module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int,
54 		   S_IRUGO | S_IWUSR);
55 MODULE_PARM_DESC(debug_libiscsi_session,
56 		 "Turn on debugging for sessions in libiscsi module. "
57 		 "Set to 1 to turn on, and zero to turn off. Default is off.");
58 
59 static int iscsi_dbg_lib_eh;
60 module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int,
61 		   S_IRUGO | S_IWUSR);
62 MODULE_PARM_DESC(debug_libiscsi_eh,
63 		 "Turn on debugging for error handling in libiscsi module. "
64 		 "Set to 1 to turn on, and zero to turn off. Default is off.");
65 
66 #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...)			\
67 	do {							\
68 		if (iscsi_dbg_lib_conn)				\
69 			iscsi_conn_printk(KERN_INFO, _conn,	\
70 					     "%s " dbg_fmt,	\
71 					     __func__, ##arg);	\
72 		iscsi_dbg_trace(trace_iscsi_dbg_conn,		\
73 				&(_conn)->cls_conn->dev,	\
74 				"%s " dbg_fmt, __func__, ##arg);\
75 	} while (0);
76 
77 #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...)			\
78 	do {								\
79 		if (iscsi_dbg_lib_session)				\
80 			iscsi_session_printk(KERN_INFO, _session,	\
81 					     "%s " dbg_fmt,		\
82 					     __func__, ##arg);		\
83 		iscsi_dbg_trace(trace_iscsi_dbg_session, 		\
84 				&(_session)->cls_session->dev,		\
85 				"%s " dbg_fmt, __func__, ##arg);	\
86 	} while (0);
87 
88 #define ISCSI_DBG_EH(_session, dbg_fmt, arg...)				\
89 	do {								\
90 		if (iscsi_dbg_lib_eh)					\
91 			iscsi_session_printk(KERN_INFO, _session,	\
92 					     "%s " dbg_fmt,		\
93 					     __func__, ##arg);		\
94 		iscsi_dbg_trace(trace_iscsi_dbg_eh,			\
95 				&(_session)->cls_session->dev,		\
96 				"%s " dbg_fmt, __func__, ##arg);	\
97 	} while (0);
98 
99 inline void iscsi_conn_queue_work(struct iscsi_conn *conn)
100 {
101 	struct Scsi_Host *shost = conn->session->host;
102 	struct iscsi_host *ihost = shost_priv(shost);
103 
104 	if (ihost->workq)
105 		queue_work(ihost->workq, &conn->xmitwork);
106 }
107 EXPORT_SYMBOL_GPL(iscsi_conn_queue_work);
108 
109 static void __iscsi_update_cmdsn(struct iscsi_session *session,
110 				 uint32_t exp_cmdsn, uint32_t max_cmdsn)
111 {
112 	/*
113 	 * standard specifies this check for when to update expected and
114 	 * max sequence numbers
115 	 */
116 	if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
117 		return;
118 
119 	if (exp_cmdsn != session->exp_cmdsn &&
120 	    !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
121 		session->exp_cmdsn = exp_cmdsn;
122 
123 	if (max_cmdsn != session->max_cmdsn &&
124 	    !iscsi_sna_lt(max_cmdsn, session->max_cmdsn))
125 		session->max_cmdsn = max_cmdsn;
126 }
127 
128 void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
129 {
130 	__iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn),
131 			     be32_to_cpu(hdr->max_cmdsn));
132 }
133 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
134 
135 /**
136  * iscsi_prep_data_out_pdu - initialize Data-Out
137  * @task: scsi command task
138  * @r2t: R2T info
139  * @hdr: iscsi data in pdu
140  *
141  * Notes:
142  *	Initialize Data-Out within this R2T sequence and finds
143  *	proper data_offset within this SCSI command.
144  *
145  *	This function is called with connection lock taken.
146  **/
147 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
148 			   struct iscsi_data *hdr)
149 {
150 	struct iscsi_conn *conn = task->conn;
151 	unsigned int left = r2t->data_length - r2t->sent;
152 
153 	task->hdr_len = sizeof(struct iscsi_data);
154 
155 	memset(hdr, 0, sizeof(struct iscsi_data));
156 	hdr->ttt = r2t->ttt;
157 	hdr->datasn = cpu_to_be32(r2t->datasn);
158 	r2t->datasn++;
159 	hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
160 	hdr->lun = task->lun;
161 	hdr->itt = task->hdr_itt;
162 	hdr->exp_statsn = r2t->exp_statsn;
163 	hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
164 	if (left > conn->max_xmit_dlength) {
165 		hton24(hdr->dlength, conn->max_xmit_dlength);
166 		r2t->data_count = conn->max_xmit_dlength;
167 		hdr->flags = 0;
168 	} else {
169 		hton24(hdr->dlength, left);
170 		r2t->data_count = left;
171 		hdr->flags = ISCSI_FLAG_CMD_FINAL;
172 	}
173 	conn->dataout_pdus_cnt++;
174 }
175 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
176 
177 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
178 {
179 	unsigned exp_len = task->hdr_len + len;
180 
181 	if (exp_len > task->hdr_max) {
182 		WARN_ON(1);
183 		return -EINVAL;
184 	}
185 
186 	WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
187 	task->hdr_len = exp_len;
188 	return 0;
189 }
190 
191 /*
192  * make an extended cdb AHS
193  */
194 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
195 {
196 	struct scsi_cmnd *cmd = task->sc;
197 	unsigned rlen, pad_len;
198 	unsigned short ahslength;
199 	struct iscsi_ecdb_ahdr *ecdb_ahdr;
200 	int rc;
201 
202 	ecdb_ahdr = iscsi_next_hdr(task);
203 	rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
204 
205 	BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
206 	ahslength = rlen + sizeof(ecdb_ahdr->reserved);
207 
208 	pad_len = iscsi_padding(rlen);
209 
210 	rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
211 	                   sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
212 	if (rc)
213 		return rc;
214 
215 	if (pad_len)
216 		memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
217 
218 	ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
219 	ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
220 	ecdb_ahdr->reserved = 0;
221 	memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
222 
223 	ISCSI_DBG_SESSION(task->conn->session,
224 			  "iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
225 		          "rlen %d pad_len %d ahs_length %d iscsi_headers_size "
226 		          "%u\n", cmd->cmd_len, rlen, pad_len, ahslength,
227 		          task->hdr_len);
228 	return 0;
229 }
230 
231 static int iscsi_prep_bidi_ahs(struct iscsi_task *task)
232 {
233 	struct scsi_cmnd *sc = task->sc;
234 	struct iscsi_rlength_ahdr *rlen_ahdr;
235 	int rc;
236 
237 	rlen_ahdr = iscsi_next_hdr(task);
238 	rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr));
239 	if (rc)
240 		return rc;
241 
242 	rlen_ahdr->ahslength =
243 		cpu_to_be16(sizeof(rlen_ahdr->read_length) +
244 						  sizeof(rlen_ahdr->reserved));
245 	rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
246 	rlen_ahdr->reserved = 0;
247 	rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
248 
249 	ISCSI_DBG_SESSION(task->conn->session,
250 			  "bidi-in rlen_ahdr->read_length(%d) "
251 		          "rlen_ahdr->ahslength(%d)\n",
252 		          be32_to_cpu(rlen_ahdr->read_length),
253 		          be16_to_cpu(rlen_ahdr->ahslength));
254 	return 0;
255 }
256 
257 /**
258  * iscsi_check_tmf_restrictions - check if a task is affected by TMF
259  * @task: iscsi task
260  * @opcode: opcode to check for
261  *
262  * During TMF a task has to be checked if it's affected.
263  * All unrelated I/O can be passed through, but I/O to the
264  * affected LUN should be restricted.
265  * If 'fast_abort' is set we won't be sending any I/O to the
266  * affected LUN.
267  * Otherwise the target is waiting for all TTTs to be completed,
268  * so we have to send all outstanding Data-Out PDUs to the target.
269  */
270 static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode)
271 {
272 	struct iscsi_conn *conn = task->conn;
273 	struct iscsi_tm *tmf = &conn->tmhdr;
274 	u64 hdr_lun;
275 
276 	if (conn->tmf_state == TMF_INITIAL)
277 		return 0;
278 
279 	if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC)
280 		return 0;
281 
282 	switch (ISCSI_TM_FUNC_VALUE(tmf)) {
283 	case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
284 		/*
285 		 * Allow PDUs for unrelated LUNs
286 		 */
287 		hdr_lun = scsilun_to_int(&tmf->lun);
288 		if (hdr_lun != task->sc->device->lun)
289 			return 0;
290 		/* fall through */
291 	case ISCSI_TM_FUNC_TARGET_WARM_RESET:
292 		/*
293 		 * Fail all SCSI cmd PDUs
294 		 */
295 		if (opcode != ISCSI_OP_SCSI_DATA_OUT) {
296 			iscsi_conn_printk(KERN_INFO, conn,
297 					  "task [op %x itt "
298 					  "0x%x/0x%x] "
299 					  "rejected.\n",
300 					  opcode, task->itt,
301 					  task->hdr_itt);
302 			return -EACCES;
303 		}
304 		/*
305 		 * And also all data-out PDUs in response to R2T
306 		 * if fast_abort is set.
307 		 */
308 		if (conn->session->fast_abort) {
309 			iscsi_conn_printk(KERN_INFO, conn,
310 					  "task [op %x itt "
311 					  "0x%x/0x%x] fast abort.\n",
312 					  opcode, task->itt,
313 					  task->hdr_itt);
314 			return -EACCES;
315 		}
316 		break;
317 	case ISCSI_TM_FUNC_ABORT_TASK:
318 		/*
319 		 * the caller has already checked if the task
320 		 * they want to abort was in the pending queue so if
321 		 * we are here the cmd pdu has gone out already, and
322 		 * we will only hit this for data-outs
323 		 */
324 		if (opcode == ISCSI_OP_SCSI_DATA_OUT &&
325 		    task->hdr_itt == tmf->rtt) {
326 			ISCSI_DBG_SESSION(conn->session,
327 					  "Preventing task %x/%x from sending "
328 					  "data-out due to abort task in "
329 					  "progress\n", task->itt,
330 					  task->hdr_itt);
331 			return -EACCES;
332 		}
333 		break;
334 	}
335 
336 	return 0;
337 }
338 
339 /**
340  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
341  * @task: iscsi task
342  *
343  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
344  * fields like dlength or final based on how much data it sends
345  */
346 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
347 {
348 	struct iscsi_conn *conn = task->conn;
349 	struct iscsi_session *session = conn->session;
350 	struct scsi_cmnd *sc = task->sc;
351 	struct iscsi_scsi_req *hdr;
352 	unsigned hdrlength, cmd_len, transfer_length;
353 	itt_t itt;
354 	int rc;
355 
356 	rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD);
357 	if (rc)
358 		return rc;
359 
360 	if (conn->session->tt->alloc_pdu) {
361 		rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD);
362 		if (rc)
363 			return rc;
364 	}
365 	hdr = (struct iscsi_scsi_req *)task->hdr;
366 	itt = hdr->itt;
367 	memset(hdr, 0, sizeof(*hdr));
368 
369 	if (session->tt->parse_pdu_itt)
370 		hdr->itt = task->hdr_itt = itt;
371 	else
372 		hdr->itt = task->hdr_itt = build_itt(task->itt,
373 						     task->conn->session->age);
374 	task->hdr_len = 0;
375 	rc = iscsi_add_hdr(task, sizeof(*hdr));
376 	if (rc)
377 		return rc;
378 	hdr->opcode = ISCSI_OP_SCSI_CMD;
379 	hdr->flags = ISCSI_ATTR_SIMPLE;
380 	int_to_scsilun(sc->device->lun, &hdr->lun);
381 	task->lun = hdr->lun;
382 	hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
383 	cmd_len = sc->cmd_len;
384 	if (cmd_len < ISCSI_CDB_SIZE)
385 		memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
386 	else if (cmd_len > ISCSI_CDB_SIZE) {
387 		rc = iscsi_prep_ecdb_ahs(task);
388 		if (rc)
389 			return rc;
390 		cmd_len = ISCSI_CDB_SIZE;
391 	}
392 	memcpy(hdr->cdb, sc->cmnd, cmd_len);
393 
394 	task->imm_count = 0;
395 	if (scsi_bidi_cmnd(sc)) {
396 		hdr->flags |= ISCSI_FLAG_CMD_READ;
397 		rc = iscsi_prep_bidi_ahs(task);
398 		if (rc)
399 			return rc;
400 	}
401 
402 	if (scsi_get_prot_op(sc) != SCSI_PROT_NORMAL)
403 		task->protected = true;
404 
405 	transfer_length = scsi_transfer_length(sc);
406 	hdr->data_length = cpu_to_be32(transfer_length);
407 	if (sc->sc_data_direction == DMA_TO_DEVICE) {
408 		struct iscsi_r2t_info *r2t = &task->unsol_r2t;
409 
410 		hdr->flags |= ISCSI_FLAG_CMD_WRITE;
411 		/*
412 		 * Write counters:
413 		 *
414 		 *	imm_count	bytes to be sent right after
415 		 *			SCSI PDU Header
416 		 *
417 		 *	unsol_count	bytes(as Data-Out) to be sent
418 		 *			without	R2T ack right after
419 		 *			immediate data
420 		 *
421 		 *	r2t data_length bytes to be sent via R2T ack's
422 		 *
423 		 *      pad_count       bytes to be sent as zero-padding
424 		 */
425 		memset(r2t, 0, sizeof(*r2t));
426 
427 		if (session->imm_data_en) {
428 			if (transfer_length >= session->first_burst)
429 				task->imm_count = min(session->first_burst,
430 							conn->max_xmit_dlength);
431 			else
432 				task->imm_count = min(transfer_length,
433 						      conn->max_xmit_dlength);
434 			hton24(hdr->dlength, task->imm_count);
435 		} else
436 			zero_data(hdr->dlength);
437 
438 		if (!session->initial_r2t_en) {
439 			r2t->data_length = min(session->first_burst,
440 					       transfer_length) -
441 					       task->imm_count;
442 			r2t->data_offset = task->imm_count;
443 			r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
444 			r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
445 		}
446 
447 		if (!task->unsol_r2t.data_length)
448 			/* No unsolicit Data-Out's */
449 			hdr->flags |= ISCSI_FLAG_CMD_FINAL;
450 	} else {
451 		hdr->flags |= ISCSI_FLAG_CMD_FINAL;
452 		zero_data(hdr->dlength);
453 
454 		if (sc->sc_data_direction == DMA_FROM_DEVICE)
455 			hdr->flags |= ISCSI_FLAG_CMD_READ;
456 	}
457 
458 	/* calculate size of additional header segments (AHSs) */
459 	hdrlength = task->hdr_len - sizeof(*hdr);
460 
461 	WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
462 	hdrlength /= ISCSI_PAD_LEN;
463 
464 	WARN_ON(hdrlength >= 256);
465 	hdr->hlength = hdrlength & 0xFF;
466 	hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
467 
468 	if (session->tt->init_task && session->tt->init_task(task))
469 		return -EIO;
470 
471 	task->state = ISCSI_TASK_RUNNING;
472 	session->cmdsn++;
473 
474 	conn->scsicmd_pdus_cnt++;
475 	ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x "
476 			  "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n",
477 			  scsi_bidi_cmnd(sc) ? "bidirectional" :
478 			  sc->sc_data_direction == DMA_TO_DEVICE ?
479 			  "write" : "read", conn->id, sc, sc->cmnd[0],
480 			  task->itt, transfer_length,
481 			  scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
482 			  session->cmdsn,
483 			  session->max_cmdsn - session->exp_cmdsn + 1);
484 	return 0;
485 }
486 
487 /**
488  * iscsi_free_task - free a task
489  * @task: iscsi cmd task
490  *
491  * Must be called with session back_lock.
492  * This function returns the scsi command to scsi-ml or cleans
493  * up mgmt tasks then returns the task to the pool.
494  */
495 static void iscsi_free_task(struct iscsi_task *task)
496 {
497 	struct iscsi_conn *conn = task->conn;
498 	struct iscsi_session *session = conn->session;
499 	struct scsi_cmnd *sc = task->sc;
500 	int oldstate = task->state;
501 
502 	ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n",
503 			  task->itt, task->state, task->sc);
504 
505 	session->tt->cleanup_task(task);
506 	task->state = ISCSI_TASK_FREE;
507 	task->sc = NULL;
508 	/*
509 	 * login task is preallocated so do not free
510 	 */
511 	if (conn->login_task == task)
512 		return;
513 
514 	kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*));
515 
516 	if (sc) {
517 		/* SCSI eh reuses commands to verify us */
518 		sc->SCp.ptr = NULL;
519 		/*
520 		 * queue command may call this to free the task, so
521 		 * it will decide how to return sc to scsi-ml.
522 		 */
523 		if (oldstate != ISCSI_TASK_REQUEUE_SCSIQ)
524 			sc->scsi_done(sc);
525 	}
526 }
527 
528 void __iscsi_get_task(struct iscsi_task *task)
529 {
530 	refcount_inc(&task->refcount);
531 }
532 EXPORT_SYMBOL_GPL(__iscsi_get_task);
533 
534 void __iscsi_put_task(struct iscsi_task *task)
535 {
536 	if (refcount_dec_and_test(&task->refcount))
537 		iscsi_free_task(task);
538 }
539 EXPORT_SYMBOL_GPL(__iscsi_put_task);
540 
541 void iscsi_put_task(struct iscsi_task *task)
542 {
543 	struct iscsi_session *session = task->conn->session;
544 
545 	/* regular RX path uses back_lock */
546 	spin_lock_bh(&session->back_lock);
547 	__iscsi_put_task(task);
548 	spin_unlock_bh(&session->back_lock);
549 }
550 EXPORT_SYMBOL_GPL(iscsi_put_task);
551 
552 /**
553  * iscsi_complete_task - finish a task
554  * @task: iscsi cmd task
555  * @state: state to complete task with
556  *
557  * Must be called with session back_lock.
558  */
559 static void iscsi_complete_task(struct iscsi_task *task, int state)
560 {
561 	struct iscsi_conn *conn = task->conn;
562 
563 	ISCSI_DBG_SESSION(conn->session,
564 			  "complete task itt 0x%x state %d sc %p\n",
565 			  task->itt, task->state, task->sc);
566 	if (task->state == ISCSI_TASK_COMPLETED ||
567 	    task->state == ISCSI_TASK_ABRT_TMF ||
568 	    task->state == ISCSI_TASK_ABRT_SESS_RECOV ||
569 	    task->state == ISCSI_TASK_REQUEUE_SCSIQ)
570 		return;
571 	WARN_ON_ONCE(task->state == ISCSI_TASK_FREE);
572 	task->state = state;
573 
574 	spin_lock_bh(&conn->taskqueuelock);
575 	if (!list_empty(&task->running)) {
576 		pr_debug_once("%s while task on list", __func__);
577 		list_del_init(&task->running);
578 	}
579 	spin_unlock_bh(&conn->taskqueuelock);
580 
581 	if (conn->task == task)
582 		conn->task = NULL;
583 
584 	if (conn->ping_task == task)
585 		conn->ping_task = NULL;
586 
587 	/* release get from queueing */
588 	__iscsi_put_task(task);
589 }
590 
591 /**
592  * iscsi_complete_scsi_task - finish scsi task normally
593  * @task: iscsi task for scsi cmd
594  * @exp_cmdsn: expected cmd sn in cpu format
595  * @max_cmdsn: max cmd sn in cpu format
596  *
597  * This is used when drivers do not need or cannot perform
598  * lower level pdu processing.
599  *
600  * Called with session back_lock
601  */
602 void iscsi_complete_scsi_task(struct iscsi_task *task,
603 			      uint32_t exp_cmdsn, uint32_t max_cmdsn)
604 {
605 	struct iscsi_conn *conn = task->conn;
606 
607 	ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt);
608 
609 	conn->last_recv = jiffies;
610 	__iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn);
611 	iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
612 }
613 EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task);
614 
615 
616 /*
617  * session back_lock must be held and if not called for a task that is
618  * still pending or from the xmit thread, then xmit thread must
619  * be suspended.
620  */
621 static void fail_scsi_task(struct iscsi_task *task, int err)
622 {
623 	struct iscsi_conn *conn = task->conn;
624 	struct scsi_cmnd *sc;
625 	int state;
626 
627 	/*
628 	 * if a command completes and we get a successful tmf response
629 	 * we will hit this because the scsi eh abort code does not take
630 	 * a ref to the task.
631 	 */
632 	sc = task->sc;
633 	if (!sc)
634 		return;
635 
636 	if (task->state == ISCSI_TASK_PENDING) {
637 		/*
638 		 * cmd never made it to the xmit thread, so we should not count
639 		 * the cmd in the sequencing
640 		 */
641 		conn->session->queued_cmdsn--;
642 		/* it was never sent so just complete like normal */
643 		state = ISCSI_TASK_COMPLETED;
644 	} else if (err == DID_TRANSPORT_DISRUPTED)
645 		state = ISCSI_TASK_ABRT_SESS_RECOV;
646 	else
647 		state = ISCSI_TASK_ABRT_TMF;
648 
649 	sc->result = err << 16;
650 	if (!scsi_bidi_cmnd(sc))
651 		scsi_set_resid(sc, scsi_bufflen(sc));
652 	else {
653 		scsi_out(sc)->resid = scsi_out(sc)->length;
654 		scsi_in(sc)->resid = scsi_in(sc)->length;
655 	}
656 
657 	/* regular RX path uses back_lock */
658 	spin_lock_bh(&conn->session->back_lock);
659 	iscsi_complete_task(task, state);
660 	spin_unlock_bh(&conn->session->back_lock);
661 }
662 
663 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
664 				struct iscsi_task *task)
665 {
666 	struct iscsi_session *session = conn->session;
667 	struct iscsi_hdr *hdr = task->hdr;
668 	struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
669 	uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
670 
671 	if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
672 		return -ENOTCONN;
673 
674 	if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT)
675 		nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
676 	/*
677 	 * pre-format CmdSN for outgoing PDU.
678 	 */
679 	nop->cmdsn = cpu_to_be32(session->cmdsn);
680 	if (hdr->itt != RESERVED_ITT) {
681 		/*
682 		 * TODO: We always use immediate for normal session pdus.
683 		 * If we start to send tmfs or nops as non-immediate then
684 		 * we should start checking the cmdsn numbers for mgmt tasks.
685 		 *
686 		 * During discovery sessions iscsid sends TEXT as non immediate,
687 		 * but we always only send one PDU at a time.
688 		 */
689 		if (conn->c_stage == ISCSI_CONN_STARTED &&
690 		    !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
691 			session->queued_cmdsn++;
692 			session->cmdsn++;
693 		}
694 	}
695 
696 	if (session->tt->init_task && session->tt->init_task(task))
697 		return -EIO;
698 
699 	if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
700 		session->state = ISCSI_STATE_LOGGING_OUT;
701 
702 	task->state = ISCSI_TASK_RUNNING;
703 	ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x "
704 			  "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK,
705 			  hdr->itt, task->data_count);
706 	return 0;
707 }
708 
709 static struct iscsi_task *
710 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
711 		      char *data, uint32_t data_size)
712 {
713 	struct iscsi_session *session = conn->session;
714 	struct iscsi_host *ihost = shost_priv(session->host);
715 	uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
716 	struct iscsi_task *task;
717 	itt_t itt;
718 
719 	if (session->state == ISCSI_STATE_TERMINATE)
720 		return NULL;
721 
722 	if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) {
723 		/*
724 		 * Login and Text are sent serially, in
725 		 * request-followed-by-response sequence.
726 		 * Same task can be used. Same ITT must be used.
727 		 * Note that login_task is preallocated at conn_create().
728 		 */
729 		if (conn->login_task->state != ISCSI_TASK_FREE) {
730 			iscsi_conn_printk(KERN_ERR, conn, "Login/Text in "
731 					  "progress. Cannot start new task.\n");
732 			return NULL;
733 		}
734 
735 		if (data_size > ISCSI_DEF_MAX_RECV_SEG_LEN) {
736 			iscsi_conn_printk(KERN_ERR, conn, "Invalid buffer len of %u for login task. Max len is %u\n", data_size, ISCSI_DEF_MAX_RECV_SEG_LEN);
737 			return NULL;
738 		}
739 
740 		task = conn->login_task;
741 	} else {
742 		if (session->state != ISCSI_STATE_LOGGED_IN)
743 			return NULL;
744 
745 		if (data_size != 0) {
746 			iscsi_conn_printk(KERN_ERR, conn, "Can not send data buffer of len %u for op 0x%x\n", data_size, opcode);
747 			return NULL;
748 		}
749 
750 		BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
751 		BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
752 
753 		if (!kfifo_out(&session->cmdpool.queue,
754 				 (void*)&task, sizeof(void*)))
755 			return NULL;
756 	}
757 	/*
758 	 * released in complete pdu for task we expect a response for, and
759 	 * released by the lld when it has transmitted the task for
760 	 * pdus we do not expect a response for.
761 	 */
762 	refcount_set(&task->refcount, 1);
763 	task->conn = conn;
764 	task->sc = NULL;
765 	INIT_LIST_HEAD(&task->running);
766 	task->state = ISCSI_TASK_PENDING;
767 
768 	if (data_size) {
769 		memcpy(task->data, data, data_size);
770 		task->data_count = data_size;
771 	} else
772 		task->data_count = 0;
773 
774 	if (conn->session->tt->alloc_pdu) {
775 		if (conn->session->tt->alloc_pdu(task, hdr->opcode)) {
776 			iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
777 					 "pdu for mgmt task.\n");
778 			goto free_task;
779 		}
780 	}
781 
782 	itt = task->hdr->itt;
783 	task->hdr_len = sizeof(struct iscsi_hdr);
784 	memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
785 
786 	if (hdr->itt != RESERVED_ITT) {
787 		if (session->tt->parse_pdu_itt)
788 			task->hdr->itt = itt;
789 		else
790 			task->hdr->itt = build_itt(task->itt,
791 						   task->conn->session->age);
792 	}
793 
794 	if (!ihost->workq) {
795 		if (iscsi_prep_mgmt_task(conn, task))
796 			goto free_task;
797 
798 		if (session->tt->xmit_task(task))
799 			goto free_task;
800 	} else {
801 		spin_lock_bh(&conn->taskqueuelock);
802 		list_add_tail(&task->running, &conn->mgmtqueue);
803 		spin_unlock_bh(&conn->taskqueuelock);
804 		iscsi_conn_queue_work(conn);
805 	}
806 
807 	return task;
808 
809 free_task:
810 	/* regular RX path uses back_lock */
811 	spin_lock(&session->back_lock);
812 	__iscsi_put_task(task);
813 	spin_unlock(&session->back_lock);
814 	return NULL;
815 }
816 
817 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
818 			char *data, uint32_t data_size)
819 {
820 	struct iscsi_conn *conn = cls_conn->dd_data;
821 	struct iscsi_session *session = conn->session;
822 	int err = 0;
823 
824 	spin_lock_bh(&session->frwd_lock);
825 	if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
826 		err = -EPERM;
827 	spin_unlock_bh(&session->frwd_lock);
828 	return err;
829 }
830 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
831 
832 /**
833  * iscsi_cmd_rsp - SCSI Command Response processing
834  * @conn: iscsi connection
835  * @hdr: iscsi header
836  * @task: scsi command task
837  * @data: cmd data buffer
838  * @datalen: len of buffer
839  *
840  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
841  * then completes the command and task.
842  **/
843 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
844 			       struct iscsi_task *task, char *data,
845 			       int datalen)
846 {
847 	struct iscsi_scsi_rsp *rhdr = (struct iscsi_scsi_rsp *)hdr;
848 	struct iscsi_session *session = conn->session;
849 	struct scsi_cmnd *sc = task->sc;
850 
851 	iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
852 	conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
853 
854 	sc->result = (DID_OK << 16) | rhdr->cmd_status;
855 
856 	if (task->protected) {
857 		sector_t sector;
858 		u8 ascq;
859 
860 		/**
861 		 * Transports that didn't implement check_protection
862 		 * callback but still published T10-PI support to scsi-mid
863 		 * deserve this BUG_ON.
864 		 **/
865 		BUG_ON(!session->tt->check_protection);
866 
867 		ascq = session->tt->check_protection(task, &sector);
868 		if (ascq) {
869 			sc->result = DRIVER_SENSE << 24 |
870 				     SAM_STAT_CHECK_CONDITION;
871 			scsi_build_sense_buffer(1, sc->sense_buffer,
872 						ILLEGAL_REQUEST, 0x10, ascq);
873 			scsi_set_sense_information(sc->sense_buffer,
874 						   SCSI_SENSE_BUFFERSIZE,
875 						   sector);
876 			goto out;
877 		}
878 	}
879 
880 	if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
881 		sc->result = DID_ERROR << 16;
882 		goto out;
883 	}
884 
885 	if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
886 		uint16_t senselen;
887 
888 		if (datalen < 2) {
889 invalid_datalen:
890 			iscsi_conn_printk(KERN_ERR,  conn,
891 					 "Got CHECK_CONDITION but invalid data "
892 					 "buffer size of %d\n", datalen);
893 			sc->result = DID_BAD_TARGET << 16;
894 			goto out;
895 		}
896 
897 		senselen = get_unaligned_be16(data);
898 		if (datalen < senselen)
899 			goto invalid_datalen;
900 
901 		memcpy(sc->sense_buffer, data + 2,
902 		       min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
903 		ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n",
904 				  min_t(uint16_t, senselen,
905 				  SCSI_SENSE_BUFFERSIZE));
906 	}
907 
908 	if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
909 			   ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
910 		int res_count = be32_to_cpu(rhdr->bi_residual_count);
911 
912 		if (scsi_bidi_cmnd(sc) && res_count > 0 &&
913 				(rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
914 				 res_count <= scsi_in(sc)->length))
915 			scsi_in(sc)->resid = res_count;
916 		else
917 			sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
918 	}
919 
920 	if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
921 	                   ISCSI_FLAG_CMD_OVERFLOW)) {
922 		int res_count = be32_to_cpu(rhdr->residual_count);
923 
924 		if (res_count > 0 &&
925 		    (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
926 		     res_count <= scsi_bufflen(sc)))
927 			/* write side for bidi or uni-io set_resid */
928 			scsi_set_resid(sc, res_count);
929 		else
930 			sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
931 	}
932 out:
933 	ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n",
934 			  sc, sc->result, task->itt);
935 	conn->scsirsp_pdus_cnt++;
936 	iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
937 }
938 
939 /**
940  * iscsi_data_in_rsp - SCSI Data-In Response processing
941  * @conn: iscsi connection
942  * @hdr:  iscsi pdu
943  * @task: scsi command task
944  **/
945 static void
946 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
947 		  struct iscsi_task *task)
948 {
949 	struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
950 	struct scsi_cmnd *sc = task->sc;
951 
952 	if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
953 		return;
954 
955 	iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr);
956 	sc->result = (DID_OK << 16) | rhdr->cmd_status;
957 	conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
958 	if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
959 	                   ISCSI_FLAG_DATA_OVERFLOW)) {
960 		int res_count = be32_to_cpu(rhdr->residual_count);
961 
962 		if (res_count > 0 &&
963 		    (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
964 		     res_count <= scsi_in(sc)->length))
965 			scsi_in(sc)->resid = res_count;
966 		else
967 			sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
968 	}
969 
970 	ISCSI_DBG_SESSION(conn->session, "data in with status done "
971 			  "[sc %p res %d itt 0x%x]\n",
972 			  sc, sc->result, task->itt);
973 	conn->scsirsp_pdus_cnt++;
974 	iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
975 }
976 
977 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
978 {
979 	struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
980 
981 	conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
982 	conn->tmfrsp_pdus_cnt++;
983 
984 	if (conn->tmf_state != TMF_QUEUED)
985 		return;
986 
987 	if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
988 		conn->tmf_state = TMF_SUCCESS;
989 	else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
990 		conn->tmf_state = TMF_NOT_FOUND;
991 	else
992 		conn->tmf_state = TMF_FAILED;
993 	wake_up(&conn->ehwait);
994 }
995 
996 static int iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
997 {
998         struct iscsi_nopout hdr;
999 	struct iscsi_task *task;
1000 
1001 	if (!rhdr && conn->ping_task)
1002 		return -EINVAL;
1003 
1004 	memset(&hdr, 0, sizeof(struct iscsi_nopout));
1005 	hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
1006 	hdr.flags = ISCSI_FLAG_CMD_FINAL;
1007 
1008 	if (rhdr) {
1009 		hdr.lun = rhdr->lun;
1010 		hdr.ttt = rhdr->ttt;
1011 		hdr.itt = RESERVED_ITT;
1012 	} else
1013 		hdr.ttt = RESERVED_ITT;
1014 
1015 	task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
1016 	if (!task) {
1017 		iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
1018 		return -EIO;
1019 	} else if (!rhdr) {
1020 		/* only track our nops */
1021 		conn->ping_task = task;
1022 		conn->last_ping = jiffies;
1023 	}
1024 
1025 	return 0;
1026 }
1027 
1028 static int iscsi_nop_out_rsp(struct iscsi_task *task,
1029 			     struct iscsi_nopin *nop, char *data, int datalen)
1030 {
1031 	struct iscsi_conn *conn = task->conn;
1032 	int rc = 0;
1033 
1034 	if (conn->ping_task != task) {
1035 		/*
1036 		 * If this is not in response to one of our
1037 		 * nops then it must be from userspace.
1038 		 */
1039 		if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop,
1040 				   data, datalen))
1041 			rc = ISCSI_ERR_CONN_FAILED;
1042 	} else
1043 		mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
1044 	iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1045 	return rc;
1046 }
1047 
1048 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1049 			       char *data, int datalen)
1050 {
1051 	struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
1052 	struct iscsi_hdr rejected_pdu;
1053 	int opcode, rc = 0;
1054 
1055 	conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
1056 
1057 	if (ntoh24(reject->dlength) > datalen ||
1058 	    ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) {
1059 		iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected "
1060 				  "pdu. Invalid data length (pdu dlength "
1061 				  "%u, datalen %d\n", ntoh24(reject->dlength),
1062 				  datalen);
1063 		return ISCSI_ERR_PROTO;
1064 	}
1065 	memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
1066 	opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK;
1067 
1068 	switch (reject->reason) {
1069 	case ISCSI_REASON_DATA_DIGEST_ERROR:
1070 		iscsi_conn_printk(KERN_ERR, conn,
1071 				  "pdu (op 0x%x itt 0x%x) rejected "
1072 				  "due to DataDigest error.\n",
1073 				  opcode, rejected_pdu.itt);
1074 		break;
1075 	case ISCSI_REASON_IMM_CMD_REJECT:
1076 		iscsi_conn_printk(KERN_ERR, conn,
1077 				  "pdu (op 0x%x itt 0x%x) rejected. Too many "
1078 				  "immediate commands.\n",
1079 				  opcode, rejected_pdu.itt);
1080 		/*
1081 		 * We only send one TMF at a time so if the target could not
1082 		 * handle it, then it should get fixed (RFC mandates that
1083 		 * a target can handle one immediate TMF per conn).
1084 		 *
1085 		 * For nops-outs, we could have sent more than one if
1086 		 * the target is sending us lots of nop-ins
1087 		 */
1088 		if (opcode != ISCSI_OP_NOOP_OUT)
1089 			return 0;
1090 
1091 		if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG)) {
1092 			/*
1093 			 * nop-out in response to target's nop-out rejected.
1094 			 * Just resend.
1095 			 */
1096 			/* In RX path we are under back lock */
1097 			spin_unlock(&conn->session->back_lock);
1098 			spin_lock(&conn->session->frwd_lock);
1099 			iscsi_send_nopout(conn,
1100 					  (struct iscsi_nopin*)&rejected_pdu);
1101 			spin_unlock(&conn->session->frwd_lock);
1102 			spin_lock(&conn->session->back_lock);
1103 		} else {
1104 			struct iscsi_task *task;
1105 			/*
1106 			 * Our nop as ping got dropped. We know the target
1107 			 * and transport are ok so just clean up
1108 			 */
1109 			task = iscsi_itt_to_task(conn, rejected_pdu.itt);
1110 			if (!task) {
1111 				iscsi_conn_printk(KERN_ERR, conn,
1112 						 "Invalid pdu reject. Could "
1113 						 "not lookup rejected task.\n");
1114 				rc = ISCSI_ERR_BAD_ITT;
1115 			} else
1116 				rc = iscsi_nop_out_rsp(task,
1117 					(struct iscsi_nopin*)&rejected_pdu,
1118 					NULL, 0);
1119 		}
1120 		break;
1121 	default:
1122 		iscsi_conn_printk(KERN_ERR, conn,
1123 				  "pdu (op 0x%x itt 0x%x) rejected. Reason "
1124 				  "code 0x%x\n", rejected_pdu.opcode,
1125 				  rejected_pdu.itt, reject->reason);
1126 		break;
1127 	}
1128 	return rc;
1129 }
1130 
1131 /**
1132  * iscsi_itt_to_task - look up task by itt
1133  * @conn: iscsi connection
1134  * @itt: itt
1135  *
1136  * This should be used for mgmt tasks like login and nops, or if
1137  * the LDD's itt space does not include the session age.
1138  *
1139  * The session back_lock must be held.
1140  */
1141 struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
1142 {
1143 	struct iscsi_session *session = conn->session;
1144 	int i;
1145 
1146 	if (itt == RESERVED_ITT)
1147 		return NULL;
1148 
1149 	if (session->tt->parse_pdu_itt)
1150 		session->tt->parse_pdu_itt(conn, itt, &i, NULL);
1151 	else
1152 		i = get_itt(itt);
1153 	if (i >= session->cmds_max)
1154 		return NULL;
1155 
1156 	return session->cmds[i];
1157 }
1158 EXPORT_SYMBOL_GPL(iscsi_itt_to_task);
1159 
1160 /**
1161  * __iscsi_complete_pdu - complete pdu
1162  * @conn: iscsi conn
1163  * @hdr: iscsi header
1164  * @data: data buffer
1165  * @datalen: len of data buffer
1166  *
1167  * Completes pdu processing by freeing any resources allocated at
1168  * queuecommand or send generic. session back_lock must be held and verify
1169  * itt must have been called.
1170  */
1171 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1172 			 char *data, int datalen)
1173 {
1174 	struct iscsi_session *session = conn->session;
1175 	int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
1176 	struct iscsi_task *task;
1177 	uint32_t itt;
1178 
1179 	conn->last_recv = jiffies;
1180 	rc = iscsi_verify_itt(conn, hdr->itt);
1181 	if (rc)
1182 		return rc;
1183 
1184 	if (hdr->itt != RESERVED_ITT)
1185 		itt = get_itt(hdr->itt);
1186 	else
1187 		itt = ~0U;
1188 
1189 	ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n",
1190 			  opcode, conn->id, itt, datalen);
1191 
1192 	if (itt == ~0U) {
1193 		iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1194 
1195 		switch(opcode) {
1196 		case ISCSI_OP_NOOP_IN:
1197 			if (datalen) {
1198 				rc = ISCSI_ERR_PROTO;
1199 				break;
1200 			}
1201 
1202 			if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
1203 				break;
1204 
1205 			/* In RX path we are under back lock */
1206 			spin_unlock(&session->back_lock);
1207 			spin_lock(&session->frwd_lock);
1208 			iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
1209 			spin_unlock(&session->frwd_lock);
1210 			spin_lock(&session->back_lock);
1211 			break;
1212 		case ISCSI_OP_REJECT:
1213 			rc = iscsi_handle_reject(conn, hdr, data, datalen);
1214 			break;
1215 		case ISCSI_OP_ASYNC_EVENT:
1216 			conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1217 			if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1218 				rc = ISCSI_ERR_CONN_FAILED;
1219 			break;
1220 		default:
1221 			rc = ISCSI_ERR_BAD_OPCODE;
1222 			break;
1223 		}
1224 		goto out;
1225 	}
1226 
1227 	switch(opcode) {
1228 	case ISCSI_OP_SCSI_CMD_RSP:
1229 	case ISCSI_OP_SCSI_DATA_IN:
1230 		task = iscsi_itt_to_ctask(conn, hdr->itt);
1231 		if (!task)
1232 			return ISCSI_ERR_BAD_ITT;
1233 		task->last_xfer = jiffies;
1234 		break;
1235 	case ISCSI_OP_R2T:
1236 		/*
1237 		 * LLD handles R2Ts if they need to.
1238 		 */
1239 		return 0;
1240 	case ISCSI_OP_LOGOUT_RSP:
1241 	case ISCSI_OP_LOGIN_RSP:
1242 	case ISCSI_OP_TEXT_RSP:
1243 	case ISCSI_OP_SCSI_TMFUNC_RSP:
1244 	case ISCSI_OP_NOOP_IN:
1245 		task = iscsi_itt_to_task(conn, hdr->itt);
1246 		if (!task)
1247 			return ISCSI_ERR_BAD_ITT;
1248 		break;
1249 	default:
1250 		return ISCSI_ERR_BAD_OPCODE;
1251 	}
1252 
1253 	switch(opcode) {
1254 	case ISCSI_OP_SCSI_CMD_RSP:
1255 		iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
1256 		break;
1257 	case ISCSI_OP_SCSI_DATA_IN:
1258 		iscsi_data_in_rsp(conn, hdr, task);
1259 		break;
1260 	case ISCSI_OP_LOGOUT_RSP:
1261 		iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1262 		if (datalen) {
1263 			rc = ISCSI_ERR_PROTO;
1264 			break;
1265 		}
1266 		conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1267 		goto recv_pdu;
1268 	case ISCSI_OP_LOGIN_RSP:
1269 	case ISCSI_OP_TEXT_RSP:
1270 		iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1271 		/*
1272 		 * login related PDU's exp_statsn is handled in
1273 		 * userspace
1274 		 */
1275 		goto recv_pdu;
1276 	case ISCSI_OP_SCSI_TMFUNC_RSP:
1277 		iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1278 		if (datalen) {
1279 			rc = ISCSI_ERR_PROTO;
1280 			break;
1281 		}
1282 
1283 		iscsi_tmf_rsp(conn, hdr);
1284 		iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1285 		break;
1286 	case ISCSI_OP_NOOP_IN:
1287 		iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1288 		if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
1289 			rc = ISCSI_ERR_PROTO;
1290 			break;
1291 		}
1292 		conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1293 
1294 		rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr,
1295 				       data, datalen);
1296 		break;
1297 	default:
1298 		rc = ISCSI_ERR_BAD_OPCODE;
1299 		break;
1300 	}
1301 
1302 out:
1303 	return rc;
1304 recv_pdu:
1305 	if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1306 		rc = ISCSI_ERR_CONN_FAILED;
1307 	iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1308 	return rc;
1309 }
1310 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
1311 
1312 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1313 		       char *data, int datalen)
1314 {
1315 	int rc;
1316 
1317 	spin_lock(&conn->session->back_lock);
1318 	rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
1319 	spin_unlock(&conn->session->back_lock);
1320 	return rc;
1321 }
1322 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
1323 
1324 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
1325 {
1326 	struct iscsi_session *session = conn->session;
1327 	int age = 0, i = 0;
1328 
1329 	if (itt == RESERVED_ITT)
1330 		return 0;
1331 
1332 	if (session->tt->parse_pdu_itt)
1333 		session->tt->parse_pdu_itt(conn, itt, &i, &age);
1334 	else {
1335 		i = get_itt(itt);
1336 		age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK;
1337 	}
1338 
1339 	if (age != session->age) {
1340 		iscsi_conn_printk(KERN_ERR, conn,
1341 				  "received itt %x expected session age (%x)\n",
1342 				  (__force u32)itt, session->age);
1343 		return ISCSI_ERR_BAD_ITT;
1344 	}
1345 
1346 	if (i >= session->cmds_max) {
1347 		iscsi_conn_printk(KERN_ERR, conn,
1348 				  "received invalid itt index %u (max cmds "
1349 				   "%u.\n", i, session->cmds_max);
1350 		return ISCSI_ERR_BAD_ITT;
1351 	}
1352 	return 0;
1353 }
1354 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
1355 
1356 /**
1357  * iscsi_itt_to_ctask - look up ctask by itt
1358  * @conn: iscsi connection
1359  * @itt: itt
1360  *
1361  * This should be used for cmd tasks.
1362  *
1363  * The session back_lock must be held.
1364  */
1365 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
1366 {
1367 	struct iscsi_task *task;
1368 
1369 	if (iscsi_verify_itt(conn, itt))
1370 		return NULL;
1371 
1372 	task = iscsi_itt_to_task(conn, itt);
1373 	if (!task || !task->sc)
1374 		return NULL;
1375 
1376 	if (task->sc->SCp.phase != conn->session->age) {
1377 		iscsi_session_printk(KERN_ERR, conn->session,
1378 				  "task's session age %d, expected %d\n",
1379 				  task->sc->SCp.phase, conn->session->age);
1380 		return NULL;
1381 	}
1382 
1383 	return task;
1384 }
1385 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1386 
1387 void iscsi_session_failure(struct iscsi_session *session,
1388 			   enum iscsi_err err)
1389 {
1390 	struct iscsi_conn *conn;
1391 	struct device *dev;
1392 
1393 	spin_lock_bh(&session->frwd_lock);
1394 	conn = session->leadconn;
1395 	if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1396 		spin_unlock_bh(&session->frwd_lock);
1397 		return;
1398 	}
1399 
1400 	dev = get_device(&conn->cls_conn->dev);
1401 	spin_unlock_bh(&session->frwd_lock);
1402 	if (!dev)
1403 	        return;
1404 	/*
1405 	 * if the host is being removed bypass the connection
1406 	 * recovery initialization because we are going to kill
1407 	 * the session.
1408 	 */
1409 	if (err == ISCSI_ERR_INVALID_HOST)
1410 		iscsi_conn_error_event(conn->cls_conn, err);
1411 	else
1412 		iscsi_conn_failure(conn, err);
1413 	put_device(dev);
1414 }
1415 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1416 
1417 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1418 {
1419 	struct iscsi_session *session = conn->session;
1420 
1421 	spin_lock_bh(&session->frwd_lock);
1422 	if (session->state == ISCSI_STATE_FAILED) {
1423 		spin_unlock_bh(&session->frwd_lock);
1424 		return;
1425 	}
1426 
1427 	if (conn->stop_stage == 0)
1428 		session->state = ISCSI_STATE_FAILED;
1429 	spin_unlock_bh(&session->frwd_lock);
1430 
1431 	set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1432 	set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1433 	iscsi_conn_error_event(conn->cls_conn, err);
1434 }
1435 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1436 
1437 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1438 {
1439 	struct iscsi_session *session = conn->session;
1440 
1441 	/*
1442 	 * Check for iSCSI window and take care of CmdSN wrap-around
1443 	 */
1444 	if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1445 		ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn "
1446 				  "%u MaxCmdSN %u CmdSN %u/%u\n",
1447 				  session->exp_cmdsn, session->max_cmdsn,
1448 				  session->cmdsn, session->queued_cmdsn);
1449 		return -ENOSPC;
1450 	}
1451 	return 0;
1452 }
1453 
1454 static int iscsi_xmit_task(struct iscsi_conn *conn)
1455 {
1456 	struct iscsi_task *task = conn->task;
1457 	int rc;
1458 
1459 	if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx))
1460 		return -ENODATA;
1461 
1462 	__iscsi_get_task(task);
1463 	spin_unlock_bh(&conn->session->frwd_lock);
1464 	rc = conn->session->tt->xmit_task(task);
1465 	spin_lock_bh(&conn->session->frwd_lock);
1466 	if (!rc) {
1467 		/* done with this task */
1468 		task->last_xfer = jiffies;
1469 		conn->task = NULL;
1470 	}
1471 	/* regular RX path uses back_lock */
1472 	spin_lock(&conn->session->back_lock);
1473 	__iscsi_put_task(task);
1474 	spin_unlock(&conn->session->back_lock);
1475 	return rc;
1476 }
1477 
1478 /**
1479  * iscsi_requeue_task - requeue task to run from session workqueue
1480  * @task: task to requeue
1481  *
1482  * LLDs that need to run a task from the session workqueue should call
1483  * this. The session frwd_lock must be held. This should only be called
1484  * by software drivers.
1485  */
1486 void iscsi_requeue_task(struct iscsi_task *task)
1487 {
1488 	struct iscsi_conn *conn = task->conn;
1489 
1490 	/*
1491 	 * this may be on the requeue list already if the xmit_task callout
1492 	 * is handling the r2ts while we are adding new ones
1493 	 */
1494 	spin_lock_bh(&conn->taskqueuelock);
1495 	if (list_empty(&task->running))
1496 		list_add_tail(&task->running, &conn->requeue);
1497 	spin_unlock_bh(&conn->taskqueuelock);
1498 	iscsi_conn_queue_work(conn);
1499 }
1500 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1501 
1502 /**
1503  * iscsi_data_xmit - xmit any command into the scheduled connection
1504  * @conn: iscsi connection
1505  *
1506  * Notes:
1507  *	The function can return -EAGAIN in which case the caller must
1508  *	re-schedule it again later or recover. '0' return code means
1509  *	successful xmit.
1510  **/
1511 static int iscsi_data_xmit(struct iscsi_conn *conn)
1512 {
1513 	struct iscsi_task *task;
1514 	int rc = 0;
1515 
1516 	spin_lock_bh(&conn->session->frwd_lock);
1517 	if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1518 		ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n");
1519 		spin_unlock_bh(&conn->session->frwd_lock);
1520 		return -ENODATA;
1521 	}
1522 
1523 	if (conn->task) {
1524 		rc = iscsi_xmit_task(conn);
1525 	        if (rc)
1526 		        goto done;
1527 	}
1528 
1529 	/*
1530 	 * process mgmt pdus like nops before commands since we should
1531 	 * only have one nop-out as a ping from us and targets should not
1532 	 * overflow us with nop-ins
1533 	 */
1534 	spin_lock_bh(&conn->taskqueuelock);
1535 check_mgmt:
1536 	while (!list_empty(&conn->mgmtqueue)) {
1537 		conn->task = list_entry(conn->mgmtqueue.next,
1538 					 struct iscsi_task, running);
1539 		list_del_init(&conn->task->running);
1540 		spin_unlock_bh(&conn->taskqueuelock);
1541 		if (iscsi_prep_mgmt_task(conn, conn->task)) {
1542 			/* regular RX path uses back_lock */
1543 			spin_lock_bh(&conn->session->back_lock);
1544 			__iscsi_put_task(conn->task);
1545 			spin_unlock_bh(&conn->session->back_lock);
1546 			conn->task = NULL;
1547 			spin_lock_bh(&conn->taskqueuelock);
1548 			continue;
1549 		}
1550 		rc = iscsi_xmit_task(conn);
1551 		if (rc)
1552 			goto done;
1553 		spin_lock_bh(&conn->taskqueuelock);
1554 	}
1555 
1556 	/* process pending command queue */
1557 	while (!list_empty(&conn->cmdqueue)) {
1558 		conn->task = list_entry(conn->cmdqueue.next, struct iscsi_task,
1559 					running);
1560 		list_del_init(&conn->task->running);
1561 		spin_unlock_bh(&conn->taskqueuelock);
1562 		if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1563 			fail_scsi_task(conn->task, DID_IMM_RETRY);
1564 			spin_lock_bh(&conn->taskqueuelock);
1565 			continue;
1566 		}
1567 		rc = iscsi_prep_scsi_cmd_pdu(conn->task);
1568 		if (rc) {
1569 			if (rc == -ENOMEM || rc == -EACCES) {
1570 				spin_lock_bh(&conn->taskqueuelock);
1571 				list_add_tail(&conn->task->running,
1572 					      &conn->cmdqueue);
1573 				conn->task = NULL;
1574 				spin_unlock_bh(&conn->taskqueuelock);
1575 				goto done;
1576 			} else
1577 				fail_scsi_task(conn->task, DID_ABORT);
1578 			spin_lock_bh(&conn->taskqueuelock);
1579 			continue;
1580 		}
1581 		rc = iscsi_xmit_task(conn);
1582 		if (rc)
1583 			goto done;
1584 		/*
1585 		 * we could continuously get new task requests so
1586 		 * we need to check the mgmt queue for nops that need to
1587 		 * be sent to aviod starvation
1588 		 */
1589 		spin_lock_bh(&conn->taskqueuelock);
1590 		if (!list_empty(&conn->mgmtqueue))
1591 			goto check_mgmt;
1592 	}
1593 
1594 	while (!list_empty(&conn->requeue)) {
1595 		/*
1596 		 * we always do fastlogout - conn stop code will clean up.
1597 		 */
1598 		if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1599 			break;
1600 
1601 		task = list_entry(conn->requeue.next, struct iscsi_task,
1602 				  running);
1603 		if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT))
1604 			break;
1605 
1606 		conn->task = task;
1607 		list_del_init(&conn->task->running);
1608 		conn->task->state = ISCSI_TASK_RUNNING;
1609 		spin_unlock_bh(&conn->taskqueuelock);
1610 		rc = iscsi_xmit_task(conn);
1611 		if (rc)
1612 			goto done;
1613 		spin_lock_bh(&conn->taskqueuelock);
1614 		if (!list_empty(&conn->mgmtqueue))
1615 			goto check_mgmt;
1616 	}
1617 	spin_unlock_bh(&conn->taskqueuelock);
1618 	spin_unlock_bh(&conn->session->frwd_lock);
1619 	return -ENODATA;
1620 
1621 done:
1622 	spin_unlock_bh(&conn->session->frwd_lock);
1623 	return rc;
1624 }
1625 
1626 static void iscsi_xmitworker(struct work_struct *work)
1627 {
1628 	struct iscsi_conn *conn =
1629 		container_of(work, struct iscsi_conn, xmitwork);
1630 	int rc;
1631 	/*
1632 	 * serialize Xmit worker on a per-connection basis.
1633 	 */
1634 	do {
1635 		rc = iscsi_data_xmit(conn);
1636 	} while (rc >= 0 || rc == -EAGAIN);
1637 }
1638 
1639 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1640 						  struct scsi_cmnd *sc)
1641 {
1642 	struct iscsi_task *task;
1643 
1644 	if (!kfifo_out(&conn->session->cmdpool.queue,
1645 			 (void *) &task, sizeof(void *)))
1646 		return NULL;
1647 
1648 	sc->SCp.phase = conn->session->age;
1649 	sc->SCp.ptr = (char *) task;
1650 
1651 	refcount_set(&task->refcount, 1);
1652 	task->state = ISCSI_TASK_PENDING;
1653 	task->conn = conn;
1654 	task->sc = sc;
1655 	task->have_checked_conn = false;
1656 	task->last_timeout = jiffies;
1657 	task->last_xfer = jiffies;
1658 	task->protected = false;
1659 	INIT_LIST_HEAD(&task->running);
1660 	return task;
1661 }
1662 
1663 enum {
1664 	FAILURE_BAD_HOST = 1,
1665 	FAILURE_SESSION_FAILED,
1666 	FAILURE_SESSION_FREED,
1667 	FAILURE_WINDOW_CLOSED,
1668 	FAILURE_OOM,
1669 	FAILURE_SESSION_TERMINATE,
1670 	FAILURE_SESSION_IN_RECOVERY,
1671 	FAILURE_SESSION_RECOVERY_TIMEOUT,
1672 	FAILURE_SESSION_LOGGING_OUT,
1673 	FAILURE_SESSION_NOT_READY,
1674 };
1675 
1676 int iscsi_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *sc)
1677 {
1678 	struct iscsi_cls_session *cls_session;
1679 	struct iscsi_host *ihost;
1680 	int reason = 0;
1681 	struct iscsi_session *session;
1682 	struct iscsi_conn *conn;
1683 	struct iscsi_task *task = NULL;
1684 
1685 	sc->result = 0;
1686 	sc->SCp.ptr = NULL;
1687 
1688 	ihost = shost_priv(host);
1689 
1690 	cls_session = starget_to_session(scsi_target(sc->device));
1691 	session = cls_session->dd_data;
1692 	spin_lock_bh(&session->frwd_lock);
1693 
1694 	reason = iscsi_session_chkready(cls_session);
1695 	if (reason) {
1696 		sc->result = reason;
1697 		goto fault;
1698 	}
1699 
1700 	if (session->state != ISCSI_STATE_LOGGED_IN) {
1701 		/*
1702 		 * to handle the race between when we set the recovery state
1703 		 * and block the session we requeue here (commands could
1704 		 * be entering our queuecommand while a block is starting
1705 		 * up because the block code is not locked)
1706 		 */
1707 		switch (session->state) {
1708 		case ISCSI_STATE_FAILED:
1709 			/*
1710 			 * cmds should fail during shutdown, if the session
1711 			 * state is bad, allowing completion to happen
1712 			 */
1713 			if (unlikely(system_state != SYSTEM_RUNNING)) {
1714 				reason = FAILURE_SESSION_FAILED;
1715 				sc->result = DID_NO_CONNECT << 16;
1716 				break;
1717 			}
1718 			/* fall through */
1719 		case ISCSI_STATE_IN_RECOVERY:
1720 			reason = FAILURE_SESSION_IN_RECOVERY;
1721 			sc->result = DID_IMM_RETRY << 16;
1722 			break;
1723 		case ISCSI_STATE_LOGGING_OUT:
1724 			reason = FAILURE_SESSION_LOGGING_OUT;
1725 			sc->result = DID_IMM_RETRY << 16;
1726 			break;
1727 		case ISCSI_STATE_RECOVERY_FAILED:
1728 			reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1729 			sc->result = DID_TRANSPORT_FAILFAST << 16;
1730 			break;
1731 		case ISCSI_STATE_TERMINATE:
1732 			reason = FAILURE_SESSION_TERMINATE;
1733 			sc->result = DID_NO_CONNECT << 16;
1734 			break;
1735 		default:
1736 			reason = FAILURE_SESSION_FREED;
1737 			sc->result = DID_NO_CONNECT << 16;
1738 		}
1739 		goto fault;
1740 	}
1741 
1742 	conn = session->leadconn;
1743 	if (!conn) {
1744 		reason = FAILURE_SESSION_FREED;
1745 		sc->result = DID_NO_CONNECT << 16;
1746 		goto fault;
1747 	}
1748 
1749 	if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1750 		reason = FAILURE_SESSION_IN_RECOVERY;
1751 		sc->result = DID_REQUEUE << 16;
1752 		goto fault;
1753 	}
1754 
1755 	if (iscsi_check_cmdsn_window_closed(conn)) {
1756 		reason = FAILURE_WINDOW_CLOSED;
1757 		goto reject;
1758 	}
1759 
1760 	task = iscsi_alloc_task(conn, sc);
1761 	if (!task) {
1762 		reason = FAILURE_OOM;
1763 		goto reject;
1764 	}
1765 
1766 	if (!ihost->workq) {
1767 		reason = iscsi_prep_scsi_cmd_pdu(task);
1768 		if (reason) {
1769 			if (reason == -ENOMEM ||  reason == -EACCES) {
1770 				reason = FAILURE_OOM;
1771 				goto prepd_reject;
1772 			} else {
1773 				sc->result = DID_ABORT << 16;
1774 				goto prepd_fault;
1775 			}
1776 		}
1777 		if (session->tt->xmit_task(task)) {
1778 			session->cmdsn--;
1779 			reason = FAILURE_SESSION_NOT_READY;
1780 			goto prepd_reject;
1781 		}
1782 	} else {
1783 		spin_lock_bh(&conn->taskqueuelock);
1784 		list_add_tail(&task->running, &conn->cmdqueue);
1785 		spin_unlock_bh(&conn->taskqueuelock);
1786 		iscsi_conn_queue_work(conn);
1787 	}
1788 
1789 	session->queued_cmdsn++;
1790 	spin_unlock_bh(&session->frwd_lock);
1791 	return 0;
1792 
1793 prepd_reject:
1794 	iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1795 reject:
1796 	spin_unlock_bh(&session->frwd_lock);
1797 	ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n",
1798 			  sc->cmnd[0], reason);
1799 	return SCSI_MLQUEUE_TARGET_BUSY;
1800 
1801 prepd_fault:
1802 	iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1803 fault:
1804 	spin_unlock_bh(&session->frwd_lock);
1805 	ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n",
1806 			  sc->cmnd[0], reason);
1807 	if (!scsi_bidi_cmnd(sc))
1808 		scsi_set_resid(sc, scsi_bufflen(sc));
1809 	else {
1810 		scsi_out(sc)->resid = scsi_out(sc)->length;
1811 		scsi_in(sc)->resid = scsi_in(sc)->length;
1812 	}
1813 	sc->scsi_done(sc);
1814 	return 0;
1815 }
1816 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1817 
1818 int iscsi_target_alloc(struct scsi_target *starget)
1819 {
1820 	struct iscsi_cls_session *cls_session = starget_to_session(starget);
1821 	struct iscsi_session *session = cls_session->dd_data;
1822 
1823 	starget->can_queue = session->scsi_cmds_max;
1824 	return 0;
1825 }
1826 EXPORT_SYMBOL_GPL(iscsi_target_alloc);
1827 
1828 static void iscsi_tmf_timedout(struct timer_list *t)
1829 {
1830 	struct iscsi_conn *conn = from_timer(conn, t, tmf_timer);
1831 	struct iscsi_session *session = conn->session;
1832 
1833 	spin_lock(&session->frwd_lock);
1834 	if (conn->tmf_state == TMF_QUEUED) {
1835 		conn->tmf_state = TMF_TIMEDOUT;
1836 		ISCSI_DBG_EH(session, "tmf timedout\n");
1837 		/* unblock eh_abort() */
1838 		wake_up(&conn->ehwait);
1839 	}
1840 	spin_unlock(&session->frwd_lock);
1841 }
1842 
1843 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1844 				   struct iscsi_tm *hdr, int age,
1845 				   int timeout)
1846 	__must_hold(&session->frwd_lock)
1847 {
1848 	struct iscsi_session *session = conn->session;
1849 	struct iscsi_task *task;
1850 
1851 	task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1852 				      NULL, 0);
1853 	if (!task) {
1854 		spin_unlock_bh(&session->frwd_lock);
1855 		iscsi_conn_printk(KERN_ERR, conn, "Could not send TMF.\n");
1856 		iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1857 		spin_lock_bh(&session->frwd_lock);
1858 		return -EPERM;
1859 	}
1860 	conn->tmfcmd_pdus_cnt++;
1861 	conn->tmf_timer.expires = timeout * HZ + jiffies;
1862 	add_timer(&conn->tmf_timer);
1863 	ISCSI_DBG_EH(session, "tmf set timeout\n");
1864 
1865 	spin_unlock_bh(&session->frwd_lock);
1866 	mutex_unlock(&session->eh_mutex);
1867 
1868 	/*
1869 	 * block eh thread until:
1870 	 *
1871 	 * 1) tmf response
1872 	 * 2) tmf timeout
1873 	 * 3) session is terminated or restarted or userspace has
1874 	 * given up on recovery
1875 	 */
1876 	wait_event_interruptible(conn->ehwait, age != session->age ||
1877 				 session->state != ISCSI_STATE_LOGGED_IN ||
1878 				 conn->tmf_state != TMF_QUEUED);
1879 	if (signal_pending(current))
1880 		flush_signals(current);
1881 	del_timer_sync(&conn->tmf_timer);
1882 
1883 	mutex_lock(&session->eh_mutex);
1884 	spin_lock_bh(&session->frwd_lock);
1885 	/* if the session drops it will clean up the task */
1886 	if (age != session->age ||
1887 	    session->state != ISCSI_STATE_LOGGED_IN)
1888 		return -ENOTCONN;
1889 	return 0;
1890 }
1891 
1892 /*
1893  * Fail commands. session lock held and recv side suspended and xmit
1894  * thread flushed
1895  */
1896 static void fail_scsi_tasks(struct iscsi_conn *conn, u64 lun, int error)
1897 {
1898 	struct iscsi_task *task;
1899 	int i;
1900 
1901 	for (i = 0; i < conn->session->cmds_max; i++) {
1902 		task = conn->session->cmds[i];
1903 		if (!task->sc || task->state == ISCSI_TASK_FREE)
1904 			continue;
1905 
1906 		if (lun != -1 && lun != task->sc->device->lun)
1907 			continue;
1908 
1909 		ISCSI_DBG_SESSION(conn->session,
1910 				  "failing sc %p itt 0x%x state %d\n",
1911 				  task->sc, task->itt, task->state);
1912 		fail_scsi_task(task, error);
1913 	}
1914 }
1915 
1916 /**
1917  * iscsi_suspend_queue - suspend iscsi_queuecommand
1918  * @conn: iscsi conn to stop queueing IO on
1919  *
1920  * This grabs the session frwd_lock to make sure no one is in
1921  * xmit_task/queuecommand, and then sets suspend to prevent
1922  * new commands from being queued. This only needs to be called
1923  * by offload drivers that need to sync a path like ep disconnect
1924  * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
1925  * will call iscsi_start_tx and iscsi_unblock_session when in FFP.
1926  */
1927 void iscsi_suspend_queue(struct iscsi_conn *conn)
1928 {
1929 	spin_lock_bh(&conn->session->frwd_lock);
1930 	set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1931 	spin_unlock_bh(&conn->session->frwd_lock);
1932 }
1933 EXPORT_SYMBOL_GPL(iscsi_suspend_queue);
1934 
1935 /**
1936  * iscsi_suspend_tx - suspend iscsi_data_xmit
1937  * @conn: iscsi conn tp stop processing IO on.
1938  *
1939  * This function sets the suspend bit to prevent iscsi_data_xmit
1940  * from sending new IO, and if work is queued on the xmit thread
1941  * it will wait for it to be completed.
1942  */
1943 void iscsi_suspend_tx(struct iscsi_conn *conn)
1944 {
1945 	struct Scsi_Host *shost = conn->session->host;
1946 	struct iscsi_host *ihost = shost_priv(shost);
1947 
1948 	set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1949 	if (ihost->workq)
1950 		flush_workqueue(ihost->workq);
1951 }
1952 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1953 
1954 static void iscsi_start_tx(struct iscsi_conn *conn)
1955 {
1956 	clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1957 	iscsi_conn_queue_work(conn);
1958 }
1959 
1960 /*
1961  * We want to make sure a ping is in flight. It has timed out.
1962  * And we are not busy processing a pdu that is making
1963  * progress but got started before the ping and is taking a while
1964  * to complete so the ping is just stuck behind it in a queue.
1965  */
1966 static int iscsi_has_ping_timed_out(struct iscsi_conn *conn)
1967 {
1968 	if (conn->ping_task &&
1969 	    time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1970 			   (conn->ping_timeout * HZ), jiffies))
1971 		return 1;
1972 	else
1973 		return 0;
1974 }
1975 
1976 enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc)
1977 {
1978 	enum blk_eh_timer_return rc = BLK_EH_DONE;
1979 	struct iscsi_task *task = NULL, *running_task;
1980 	struct iscsi_cls_session *cls_session;
1981 	struct iscsi_session *session;
1982 	struct iscsi_conn *conn;
1983 	int i;
1984 
1985 	cls_session = starget_to_session(scsi_target(sc->device));
1986 	session = cls_session->dd_data;
1987 
1988 	ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc);
1989 
1990 	spin_lock(&session->frwd_lock);
1991 	task = (struct iscsi_task *)sc->SCp.ptr;
1992 	if (!task) {
1993 		/*
1994 		 * Raced with completion. Blk layer has taken ownership
1995 		 * so let timeout code complete it now.
1996 		 */
1997 		rc = BLK_EH_DONE;
1998 		goto done;
1999 	}
2000 
2001 	if (session->state != ISCSI_STATE_LOGGED_IN) {
2002 		/*
2003 		 * During shutdown, if session is prematurely disconnected,
2004 		 * recovery won't happen and there will be hung cmds. Not
2005 		 * handling cmds would trigger EH, also bad in this case.
2006 		 * Instead, handle cmd, allow completion to happen and let
2007 		 * upper layer to deal with the result.
2008 		 */
2009 		if (unlikely(system_state != SYSTEM_RUNNING)) {
2010 			sc->result = DID_NO_CONNECT << 16;
2011 			ISCSI_DBG_EH(session, "sc on shutdown, handled\n");
2012 			rc = BLK_EH_DONE;
2013 			goto done;
2014 		}
2015 		/*
2016 		 * We are probably in the middle of iscsi recovery so let
2017 		 * that complete and handle the error.
2018 		 */
2019 		rc = BLK_EH_RESET_TIMER;
2020 		goto done;
2021 	}
2022 
2023 	conn = session->leadconn;
2024 	if (!conn) {
2025 		/* In the middle of shuting down */
2026 		rc = BLK_EH_RESET_TIMER;
2027 		goto done;
2028 	}
2029 
2030 	/*
2031 	 * If we have sent (at least queued to the network layer) a pdu or
2032 	 * recvd one for the task since the last timeout ask for
2033 	 * more time. If on the next timeout we have not made progress
2034 	 * we can check if it is the task or connection when we send the
2035 	 * nop as a ping.
2036 	 */
2037 	if (time_after(task->last_xfer, task->last_timeout)) {
2038 		ISCSI_DBG_EH(session, "Command making progress. Asking "
2039 			     "scsi-ml for more time to complete. "
2040 			     "Last data xfer at %lu. Last timeout was at "
2041 			     "%lu\n.", task->last_xfer, task->last_timeout);
2042 		task->have_checked_conn = false;
2043 		rc = BLK_EH_RESET_TIMER;
2044 		goto done;
2045 	}
2046 
2047 	if (!conn->recv_timeout && !conn->ping_timeout)
2048 		goto done;
2049 	/*
2050 	 * if the ping timedout then we are in the middle of cleaning up
2051 	 * and can let the iscsi eh handle it
2052 	 */
2053 	if (iscsi_has_ping_timed_out(conn)) {
2054 		rc = BLK_EH_RESET_TIMER;
2055 		goto done;
2056 	}
2057 
2058 	for (i = 0; i < conn->session->cmds_max; i++) {
2059 		running_task = conn->session->cmds[i];
2060 		if (!running_task->sc || running_task == task ||
2061 		     running_task->state != ISCSI_TASK_RUNNING)
2062 			continue;
2063 
2064 		/*
2065 		 * Only check if cmds started before this one have made
2066 		 * progress, or this could never fail
2067 		 */
2068 		if (time_after(running_task->sc->jiffies_at_alloc,
2069 			       task->sc->jiffies_at_alloc))
2070 			continue;
2071 
2072 		if (time_after(running_task->last_xfer, task->last_timeout)) {
2073 			/*
2074 			 * This task has not made progress, but a task
2075 			 * started before us has transferred data since
2076 			 * we started/last-checked. We could be queueing
2077 			 * too many tasks or the LU is bad.
2078 			 *
2079 			 * If the device is bad the cmds ahead of us on
2080 			 * other devs will complete, and this loop will
2081 			 * eventually fail starting the scsi eh.
2082 			 */
2083 			ISCSI_DBG_EH(session, "Command has not made progress "
2084 				     "but commands ahead of it have. "
2085 				     "Asking scsi-ml for more time to "
2086 				     "complete. Our last xfer vs running task "
2087 				     "last xfer %lu/%lu. Last check %lu.\n",
2088 				     task->last_xfer, running_task->last_xfer,
2089 				     task->last_timeout);
2090 			rc = BLK_EH_RESET_TIMER;
2091 			goto done;
2092 		}
2093 	}
2094 
2095 	/* Assumes nop timeout is shorter than scsi cmd timeout */
2096 	if (task->have_checked_conn)
2097 		goto done;
2098 
2099 	/*
2100 	 * Checking the transport already or nop from a cmd timeout still
2101 	 * running
2102 	 */
2103 	if (conn->ping_task) {
2104 		task->have_checked_conn = true;
2105 		rc = BLK_EH_RESET_TIMER;
2106 		goto done;
2107 	}
2108 
2109 	/* Make sure there is a transport check done */
2110 	iscsi_send_nopout(conn, NULL);
2111 	task->have_checked_conn = true;
2112 	rc = BLK_EH_RESET_TIMER;
2113 
2114 done:
2115 	if (task)
2116 		task->last_timeout = jiffies;
2117 	spin_unlock(&session->frwd_lock);
2118 	ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ?
2119 		     "timer reset" : "shutdown or nh");
2120 	return rc;
2121 }
2122 EXPORT_SYMBOL_GPL(iscsi_eh_cmd_timed_out);
2123 
2124 static void iscsi_check_transport_timeouts(struct timer_list *t)
2125 {
2126 	struct iscsi_conn *conn = from_timer(conn, t, transport_timer);
2127 	struct iscsi_session *session = conn->session;
2128 	unsigned long recv_timeout, next_timeout = 0, last_recv;
2129 
2130 	spin_lock(&session->frwd_lock);
2131 	if (session->state != ISCSI_STATE_LOGGED_IN)
2132 		goto done;
2133 
2134 	recv_timeout = conn->recv_timeout;
2135 	if (!recv_timeout)
2136 		goto done;
2137 
2138 	recv_timeout *= HZ;
2139 	last_recv = conn->last_recv;
2140 
2141 	if (iscsi_has_ping_timed_out(conn)) {
2142 		iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
2143 				  "expired, recv timeout %d, last rx %lu, "
2144 				  "last ping %lu, now %lu\n",
2145 				  conn->ping_timeout, conn->recv_timeout,
2146 				  last_recv, conn->last_ping, jiffies);
2147 		spin_unlock(&session->frwd_lock);
2148 		iscsi_conn_failure(conn, ISCSI_ERR_NOP_TIMEDOUT);
2149 		return;
2150 	}
2151 
2152 	if (time_before_eq(last_recv + recv_timeout, jiffies)) {
2153 		/* send a ping to try to provoke some traffic */
2154 		ISCSI_DBG_CONN(conn, "Sending nopout as ping\n");
2155 		if (iscsi_send_nopout(conn, NULL))
2156 			next_timeout = jiffies + (1 * HZ);
2157 		else
2158 			next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
2159 	} else
2160 		next_timeout = last_recv + recv_timeout;
2161 
2162 	ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout);
2163 	mod_timer(&conn->transport_timer, next_timeout);
2164 done:
2165 	spin_unlock(&session->frwd_lock);
2166 }
2167 
2168 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
2169 				      struct iscsi_tm *hdr)
2170 {
2171 	memset(hdr, 0, sizeof(*hdr));
2172 	hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2173 	hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
2174 	hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2175 	hdr->lun = task->lun;
2176 	hdr->rtt = task->hdr_itt;
2177 	hdr->refcmdsn = task->cmdsn;
2178 }
2179 
2180 int iscsi_eh_abort(struct scsi_cmnd *sc)
2181 {
2182 	struct iscsi_cls_session *cls_session;
2183 	struct iscsi_session *session;
2184 	struct iscsi_conn *conn;
2185 	struct iscsi_task *task;
2186 	struct iscsi_tm *hdr;
2187 	int age;
2188 
2189 	cls_session = starget_to_session(scsi_target(sc->device));
2190 	session = cls_session->dd_data;
2191 
2192 	ISCSI_DBG_EH(session, "aborting sc %p\n", sc);
2193 
2194 	mutex_lock(&session->eh_mutex);
2195 	spin_lock_bh(&session->frwd_lock);
2196 	/*
2197 	 * if session was ISCSI_STATE_IN_RECOVERY then we may not have
2198 	 * got the command.
2199 	 */
2200 	if (!sc->SCp.ptr) {
2201 		ISCSI_DBG_EH(session, "sc never reached iscsi layer or "
2202 				      "it completed.\n");
2203 		spin_unlock_bh(&session->frwd_lock);
2204 		mutex_unlock(&session->eh_mutex);
2205 		return SUCCESS;
2206 	}
2207 
2208 	/*
2209 	 * If we are not logged in or we have started a new session
2210 	 * then let the host reset code handle this
2211 	 */
2212 	if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
2213 	    sc->SCp.phase != session->age) {
2214 		spin_unlock_bh(&session->frwd_lock);
2215 		mutex_unlock(&session->eh_mutex);
2216 		ISCSI_DBG_EH(session, "failing abort due to dropped "
2217 				  "session.\n");
2218 		return FAILED;
2219 	}
2220 
2221 	conn = session->leadconn;
2222 	conn->eh_abort_cnt++;
2223 	age = session->age;
2224 
2225 	task = (struct iscsi_task *)sc->SCp.ptr;
2226 	ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n",
2227 		     sc, task->itt);
2228 
2229 	/* task completed before time out */
2230 	if (!task->sc) {
2231 		ISCSI_DBG_EH(session, "sc completed while abort in progress\n");
2232 		goto success;
2233 	}
2234 
2235 	if (task->state == ISCSI_TASK_PENDING) {
2236 		fail_scsi_task(task, DID_ABORT);
2237 		goto success;
2238 	}
2239 
2240 	/* only have one tmf outstanding at a time */
2241 	if (conn->tmf_state != TMF_INITIAL)
2242 		goto failed;
2243 	conn->tmf_state = TMF_QUEUED;
2244 
2245 	hdr = &conn->tmhdr;
2246 	iscsi_prep_abort_task_pdu(task, hdr);
2247 
2248 	if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout))
2249 		goto failed;
2250 
2251 	switch (conn->tmf_state) {
2252 	case TMF_SUCCESS:
2253 		spin_unlock_bh(&session->frwd_lock);
2254 		/*
2255 		 * stop tx side incase the target had sent a abort rsp but
2256 		 * the initiator was still writing out data.
2257 		 */
2258 		iscsi_suspend_tx(conn);
2259 		/*
2260 		 * we do not stop the recv side because targets have been
2261 		 * good and have never sent us a successful tmf response
2262 		 * then sent more data for the cmd.
2263 		 */
2264 		spin_lock_bh(&session->frwd_lock);
2265 		fail_scsi_task(task, DID_ABORT);
2266 		conn->tmf_state = TMF_INITIAL;
2267 		memset(hdr, 0, sizeof(*hdr));
2268 		spin_unlock_bh(&session->frwd_lock);
2269 		iscsi_start_tx(conn);
2270 		goto success_unlocked;
2271 	case TMF_TIMEDOUT:
2272 		spin_unlock_bh(&session->frwd_lock);
2273 		iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2274 		goto failed_unlocked;
2275 	case TMF_NOT_FOUND:
2276 		if (!sc->SCp.ptr) {
2277 			conn->tmf_state = TMF_INITIAL;
2278 			memset(hdr, 0, sizeof(*hdr));
2279 			/* task completed before tmf abort response */
2280 			ISCSI_DBG_EH(session, "sc completed while abort	in "
2281 					      "progress\n");
2282 			goto success;
2283 		}
2284 		/* fall through */
2285 	default:
2286 		conn->tmf_state = TMF_INITIAL;
2287 		goto failed;
2288 	}
2289 
2290 success:
2291 	spin_unlock_bh(&session->frwd_lock);
2292 success_unlocked:
2293 	ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n",
2294 		     sc, task->itt);
2295 	mutex_unlock(&session->eh_mutex);
2296 	return SUCCESS;
2297 
2298 failed:
2299 	spin_unlock_bh(&session->frwd_lock);
2300 failed_unlocked:
2301 	ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc,
2302 		     task ? task->itt : 0);
2303 	mutex_unlock(&session->eh_mutex);
2304 	return FAILED;
2305 }
2306 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
2307 
2308 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2309 {
2310 	memset(hdr, 0, sizeof(*hdr));
2311 	hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2312 	hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2313 	hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2314 	int_to_scsilun(sc->device->lun, &hdr->lun);
2315 	hdr->rtt = RESERVED_ITT;
2316 }
2317 
2318 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
2319 {
2320 	struct iscsi_cls_session *cls_session;
2321 	struct iscsi_session *session;
2322 	struct iscsi_conn *conn;
2323 	struct iscsi_tm *hdr;
2324 	int rc = FAILED;
2325 
2326 	cls_session = starget_to_session(scsi_target(sc->device));
2327 	session = cls_session->dd_data;
2328 
2329 	ISCSI_DBG_EH(session, "LU Reset [sc %p lun %llu]\n", sc,
2330 		     sc->device->lun);
2331 
2332 	mutex_lock(&session->eh_mutex);
2333 	spin_lock_bh(&session->frwd_lock);
2334 	/*
2335 	 * Just check if we are not logged in. We cannot check for
2336 	 * the phase because the reset could come from a ioctl.
2337 	 */
2338 	if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2339 		goto unlock;
2340 	conn = session->leadconn;
2341 
2342 	/* only have one tmf outstanding at a time */
2343 	if (conn->tmf_state != TMF_INITIAL)
2344 		goto unlock;
2345 	conn->tmf_state = TMF_QUEUED;
2346 
2347 	hdr = &conn->tmhdr;
2348 	iscsi_prep_lun_reset_pdu(sc, hdr);
2349 
2350 	if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2351 				    session->lu_reset_timeout)) {
2352 		rc = FAILED;
2353 		goto unlock;
2354 	}
2355 
2356 	switch (conn->tmf_state) {
2357 	case TMF_SUCCESS:
2358 		break;
2359 	case TMF_TIMEDOUT:
2360 		spin_unlock_bh(&session->frwd_lock);
2361 		iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2362 		goto done;
2363 	default:
2364 		conn->tmf_state = TMF_INITIAL;
2365 		goto unlock;
2366 	}
2367 
2368 	rc = SUCCESS;
2369 	spin_unlock_bh(&session->frwd_lock);
2370 
2371 	iscsi_suspend_tx(conn);
2372 
2373 	spin_lock_bh(&session->frwd_lock);
2374 	memset(hdr, 0, sizeof(*hdr));
2375 	fail_scsi_tasks(conn, sc->device->lun, DID_ERROR);
2376 	conn->tmf_state = TMF_INITIAL;
2377 	spin_unlock_bh(&session->frwd_lock);
2378 
2379 	iscsi_start_tx(conn);
2380 	goto done;
2381 
2382 unlock:
2383 	spin_unlock_bh(&session->frwd_lock);
2384 done:
2385 	ISCSI_DBG_EH(session, "dev reset result = %s\n",
2386 		     rc == SUCCESS ? "SUCCESS" : "FAILED");
2387 	mutex_unlock(&session->eh_mutex);
2388 	return rc;
2389 }
2390 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
2391 
2392 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
2393 {
2394 	struct iscsi_session *session = cls_session->dd_data;
2395 
2396 	spin_lock_bh(&session->frwd_lock);
2397 	if (session->state != ISCSI_STATE_LOGGED_IN) {
2398 		session->state = ISCSI_STATE_RECOVERY_FAILED;
2399 		if (session->leadconn)
2400 			wake_up(&session->leadconn->ehwait);
2401 	}
2402 	spin_unlock_bh(&session->frwd_lock);
2403 }
2404 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
2405 
2406 /**
2407  * iscsi_eh_session_reset - drop session and attempt relogin
2408  * @sc: scsi command
2409  *
2410  * This function will wait for a relogin, session termination from
2411  * userspace, or a recovery/replacement timeout.
2412  */
2413 int iscsi_eh_session_reset(struct scsi_cmnd *sc)
2414 {
2415 	struct iscsi_cls_session *cls_session;
2416 	struct iscsi_session *session;
2417 	struct iscsi_conn *conn;
2418 
2419 	cls_session = starget_to_session(scsi_target(sc->device));
2420 	session = cls_session->dd_data;
2421 	conn = session->leadconn;
2422 
2423 	mutex_lock(&session->eh_mutex);
2424 	spin_lock_bh(&session->frwd_lock);
2425 	if (session->state == ISCSI_STATE_TERMINATE) {
2426 failed:
2427 		ISCSI_DBG_EH(session,
2428 			     "failing session reset: Could not log back into "
2429 			     "%s [age %d]\n", session->targetname,
2430 			     session->age);
2431 		spin_unlock_bh(&session->frwd_lock);
2432 		mutex_unlock(&session->eh_mutex);
2433 		return FAILED;
2434 	}
2435 
2436 	spin_unlock_bh(&session->frwd_lock);
2437 	mutex_unlock(&session->eh_mutex);
2438 	/*
2439 	 * we drop the lock here but the leadconn cannot be destoyed while
2440 	 * we are in the scsi eh
2441 	 */
2442 	iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2443 
2444 	ISCSI_DBG_EH(session, "wait for relogin\n");
2445 	wait_event_interruptible(conn->ehwait,
2446 				 session->state == ISCSI_STATE_TERMINATE ||
2447 				 session->state == ISCSI_STATE_LOGGED_IN ||
2448 				 session->state == ISCSI_STATE_RECOVERY_FAILED);
2449 	if (signal_pending(current))
2450 		flush_signals(current);
2451 
2452 	mutex_lock(&session->eh_mutex);
2453 	spin_lock_bh(&session->frwd_lock);
2454 	if (session->state == ISCSI_STATE_LOGGED_IN) {
2455 		ISCSI_DBG_EH(session,
2456 			     "session reset succeeded for %s,%s\n",
2457 			     session->targetname, conn->persistent_address);
2458 	} else
2459 		goto failed;
2460 	spin_unlock_bh(&session->frwd_lock);
2461 	mutex_unlock(&session->eh_mutex);
2462 	return SUCCESS;
2463 }
2464 EXPORT_SYMBOL_GPL(iscsi_eh_session_reset);
2465 
2466 static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2467 {
2468 	memset(hdr, 0, sizeof(*hdr));
2469 	hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2470 	hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2471 	hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2472 	hdr->rtt = RESERVED_ITT;
2473 }
2474 
2475 /**
2476  * iscsi_eh_target_reset - reset target
2477  * @sc: scsi command
2478  *
2479  * This will attempt to send a warm target reset.
2480  */
2481 static int iscsi_eh_target_reset(struct scsi_cmnd *sc)
2482 {
2483 	struct iscsi_cls_session *cls_session;
2484 	struct iscsi_session *session;
2485 	struct iscsi_conn *conn;
2486 	struct iscsi_tm *hdr;
2487 	int rc = FAILED;
2488 
2489 	cls_session = starget_to_session(scsi_target(sc->device));
2490 	session = cls_session->dd_data;
2491 
2492 	ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc,
2493 		     session->targetname);
2494 
2495 	mutex_lock(&session->eh_mutex);
2496 	spin_lock_bh(&session->frwd_lock);
2497 	/*
2498 	 * Just check if we are not logged in. We cannot check for
2499 	 * the phase because the reset could come from a ioctl.
2500 	 */
2501 	if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2502 		goto unlock;
2503 	conn = session->leadconn;
2504 
2505 	/* only have one tmf outstanding at a time */
2506 	if (conn->tmf_state != TMF_INITIAL)
2507 		goto unlock;
2508 	conn->tmf_state = TMF_QUEUED;
2509 
2510 	hdr = &conn->tmhdr;
2511 	iscsi_prep_tgt_reset_pdu(sc, hdr);
2512 
2513 	if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2514 				    session->tgt_reset_timeout)) {
2515 		rc = FAILED;
2516 		goto unlock;
2517 	}
2518 
2519 	switch (conn->tmf_state) {
2520 	case TMF_SUCCESS:
2521 		break;
2522 	case TMF_TIMEDOUT:
2523 		spin_unlock_bh(&session->frwd_lock);
2524 		iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2525 		goto done;
2526 	default:
2527 		conn->tmf_state = TMF_INITIAL;
2528 		goto unlock;
2529 	}
2530 
2531 	rc = SUCCESS;
2532 	spin_unlock_bh(&session->frwd_lock);
2533 
2534 	iscsi_suspend_tx(conn);
2535 
2536 	spin_lock_bh(&session->frwd_lock);
2537 	memset(hdr, 0, sizeof(*hdr));
2538 	fail_scsi_tasks(conn, -1, DID_ERROR);
2539 	conn->tmf_state = TMF_INITIAL;
2540 	spin_unlock_bh(&session->frwd_lock);
2541 
2542 	iscsi_start_tx(conn);
2543 	goto done;
2544 
2545 unlock:
2546 	spin_unlock_bh(&session->frwd_lock);
2547 done:
2548 	ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname,
2549 		     rc == SUCCESS ? "SUCCESS" : "FAILED");
2550 	mutex_unlock(&session->eh_mutex);
2551 	return rc;
2552 }
2553 
2554 /**
2555  * iscsi_eh_recover_target - reset target and possibly the session
2556  * @sc: scsi command
2557  *
2558  * This will attempt to send a warm target reset. If that fails,
2559  * we will escalate to ERL0 session recovery.
2560  */
2561 int iscsi_eh_recover_target(struct scsi_cmnd *sc)
2562 {
2563 	int rc;
2564 
2565 	rc = iscsi_eh_target_reset(sc);
2566 	if (rc == FAILED)
2567 		rc = iscsi_eh_session_reset(sc);
2568 	return rc;
2569 }
2570 EXPORT_SYMBOL_GPL(iscsi_eh_recover_target);
2571 
2572 /*
2573  * Pre-allocate a pool of @max items of @item_size. By default, the pool
2574  * should be accessed via kfifo_{get,put} on q->queue.
2575  * Optionally, the caller can obtain the array of object pointers
2576  * by passing in a non-NULL @items pointer
2577  */
2578 int
2579 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
2580 {
2581 	int i, num_arrays = 1;
2582 
2583 	memset(q, 0, sizeof(*q));
2584 
2585 	q->max = max;
2586 
2587 	/* If the user passed an items pointer, he wants a copy of
2588 	 * the array. */
2589 	if (items)
2590 		num_arrays++;
2591 	q->pool = kvcalloc(num_arrays * max, sizeof(void *), GFP_KERNEL);
2592 	if (q->pool == NULL)
2593 		return -ENOMEM;
2594 
2595 	kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*));
2596 
2597 	for (i = 0; i < max; i++) {
2598 		q->pool[i] = kzalloc(item_size, GFP_KERNEL);
2599 		if (q->pool[i] == NULL) {
2600 			q->max = i;
2601 			goto enomem;
2602 		}
2603 		kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*));
2604 	}
2605 
2606 	if (items) {
2607 		*items = q->pool + max;
2608 		memcpy(*items, q->pool, max * sizeof(void *));
2609 	}
2610 
2611 	return 0;
2612 
2613 enomem:
2614 	iscsi_pool_free(q);
2615 	return -ENOMEM;
2616 }
2617 EXPORT_SYMBOL_GPL(iscsi_pool_init);
2618 
2619 void iscsi_pool_free(struct iscsi_pool *q)
2620 {
2621 	int i;
2622 
2623 	for (i = 0; i < q->max; i++)
2624 		kfree(q->pool[i]);
2625 	kvfree(q->pool);
2626 }
2627 EXPORT_SYMBOL_GPL(iscsi_pool_free);
2628 
2629 /**
2630  * iscsi_host_add - add host to system
2631  * @shost: scsi host
2632  * @pdev: parent device
2633  *
2634  * This should be called by partial offload and software iscsi drivers
2635  * to add a host to the system.
2636  */
2637 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
2638 {
2639 	if (!shost->can_queue)
2640 		shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
2641 
2642 	if (!shost->cmd_per_lun)
2643 		shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN;
2644 
2645 	return scsi_add_host(shost, pdev);
2646 }
2647 EXPORT_SYMBOL_GPL(iscsi_host_add);
2648 
2649 /**
2650  * iscsi_host_alloc - allocate a host and driver data
2651  * @sht: scsi host template
2652  * @dd_data_size: driver host data size
2653  * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue
2654  *
2655  * This should be called by partial offload and software iscsi drivers.
2656  * To access the driver specific memory use the iscsi_host_priv() macro.
2657  */
2658 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
2659 				   int dd_data_size, bool xmit_can_sleep)
2660 {
2661 	struct Scsi_Host *shost;
2662 	struct iscsi_host *ihost;
2663 
2664 	shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
2665 	if (!shost)
2666 		return NULL;
2667 	ihost = shost_priv(shost);
2668 
2669 	if (xmit_can_sleep) {
2670 		snprintf(ihost->workq_name, sizeof(ihost->workq_name),
2671 			"iscsi_q_%d", shost->host_no);
2672 		ihost->workq = create_singlethread_workqueue(ihost->workq_name);
2673 		if (!ihost->workq)
2674 			goto free_host;
2675 	}
2676 
2677 	spin_lock_init(&ihost->lock);
2678 	ihost->state = ISCSI_HOST_SETUP;
2679 	ihost->num_sessions = 0;
2680 	init_waitqueue_head(&ihost->session_removal_wq);
2681 	return shost;
2682 
2683 free_host:
2684 	scsi_host_put(shost);
2685 	return NULL;
2686 }
2687 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2688 
2689 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2690 {
2691 	iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST);
2692 }
2693 
2694 /**
2695  * iscsi_host_remove - remove host and sessions
2696  * @shost: scsi host
2697  *
2698  * If there are any sessions left, this will initiate the removal and wait
2699  * for the completion.
2700  */
2701 void iscsi_host_remove(struct Scsi_Host *shost)
2702 {
2703 	struct iscsi_host *ihost = shost_priv(shost);
2704 	unsigned long flags;
2705 
2706 	spin_lock_irqsave(&ihost->lock, flags);
2707 	ihost->state = ISCSI_HOST_REMOVED;
2708 	spin_unlock_irqrestore(&ihost->lock, flags);
2709 
2710 	iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2711 	wait_event_interruptible(ihost->session_removal_wq,
2712 				 ihost->num_sessions == 0);
2713 	if (signal_pending(current))
2714 		flush_signals(current);
2715 
2716 	scsi_remove_host(shost);
2717 	if (ihost->workq)
2718 		destroy_workqueue(ihost->workq);
2719 }
2720 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2721 
2722 void iscsi_host_free(struct Scsi_Host *shost)
2723 {
2724 	struct iscsi_host *ihost = shost_priv(shost);
2725 
2726 	kfree(ihost->netdev);
2727 	kfree(ihost->hwaddress);
2728 	kfree(ihost->initiatorname);
2729 	scsi_host_put(shost);
2730 }
2731 EXPORT_SYMBOL_GPL(iscsi_host_free);
2732 
2733 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2734 {
2735 	struct iscsi_host *ihost = shost_priv(shost);
2736 	unsigned long flags;
2737 
2738 	shost = scsi_host_get(shost);
2739 	if (!shost) {
2740 		printk(KERN_ERR "Invalid state. Cannot notify host removal "
2741 		      "of session teardown event because host already "
2742 		      "removed.\n");
2743 		return;
2744 	}
2745 
2746 	spin_lock_irqsave(&ihost->lock, flags);
2747 	ihost->num_sessions--;
2748 	if (ihost->num_sessions == 0)
2749 		wake_up(&ihost->session_removal_wq);
2750 	spin_unlock_irqrestore(&ihost->lock, flags);
2751 	scsi_host_put(shost);
2752 }
2753 
2754 /**
2755  * iscsi_session_setup - create iscsi cls session and host and session
2756  * @iscsit: iscsi transport template
2757  * @shost: scsi host
2758  * @cmds_max: session can queue
2759  * @dd_size: private driver data size, added to session allocation size
2760  * @cmd_task_size: LLD task private data size
2761  * @initial_cmdsn: initial CmdSN
2762  * @id: target ID to add to this session
2763  *
2764  * This can be used by software iscsi_transports that allocate
2765  * a session per scsi host.
2766  *
2767  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2768  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2769  * for nop handling and login/logout requests.
2770  */
2771 struct iscsi_cls_session *
2772 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2773 		    uint16_t cmds_max, int dd_size, int cmd_task_size,
2774 		    uint32_t initial_cmdsn, unsigned int id)
2775 {
2776 	struct iscsi_host *ihost = shost_priv(shost);
2777 	struct iscsi_session *session;
2778 	struct iscsi_cls_session *cls_session;
2779 	int cmd_i, scsi_cmds, total_cmds = cmds_max;
2780 	unsigned long flags;
2781 
2782 	spin_lock_irqsave(&ihost->lock, flags);
2783 	if (ihost->state == ISCSI_HOST_REMOVED) {
2784 		spin_unlock_irqrestore(&ihost->lock, flags);
2785 		return NULL;
2786 	}
2787 	ihost->num_sessions++;
2788 	spin_unlock_irqrestore(&ihost->lock, flags);
2789 
2790 	if (!total_cmds)
2791 		total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2792 	/*
2793 	 * The iscsi layer needs some tasks for nop handling and tmfs,
2794 	 * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2795 	 * + 1 command for scsi IO.
2796 	 */
2797 	if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2798 		printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2799 		       "must be a power of two that is at least %d.\n",
2800 		       total_cmds, ISCSI_TOTAL_CMDS_MIN);
2801 		goto dec_session_count;
2802 	}
2803 
2804 	if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2805 		printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2806 		       "must be a power of 2 less than or equal to %d.\n",
2807 		       cmds_max, ISCSI_TOTAL_CMDS_MAX);
2808 		total_cmds = ISCSI_TOTAL_CMDS_MAX;
2809 	}
2810 
2811 	if (!is_power_of_2(total_cmds)) {
2812 		printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2813 		       "must be a power of 2.\n", total_cmds);
2814 		total_cmds = rounddown_pow_of_two(total_cmds);
2815 		if (total_cmds < ISCSI_TOTAL_CMDS_MIN)
2816 			return NULL;
2817 		printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n",
2818 		       total_cmds);
2819 	}
2820 	scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2821 
2822 	cls_session = iscsi_alloc_session(shost, iscsit,
2823 					  sizeof(struct iscsi_session) +
2824 					  dd_size);
2825 	if (!cls_session)
2826 		goto dec_session_count;
2827 	session = cls_session->dd_data;
2828 	session->cls_session = cls_session;
2829 	session->host = shost;
2830 	session->state = ISCSI_STATE_FREE;
2831 	session->fast_abort = 1;
2832 	session->tgt_reset_timeout = 30;
2833 	session->lu_reset_timeout = 15;
2834 	session->abort_timeout = 10;
2835 	session->scsi_cmds_max = scsi_cmds;
2836 	session->cmds_max = total_cmds;
2837 	session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2838 	session->exp_cmdsn = initial_cmdsn + 1;
2839 	session->max_cmdsn = initial_cmdsn + 1;
2840 	session->max_r2t = 1;
2841 	session->tt = iscsit;
2842 	session->dd_data = cls_session->dd_data + sizeof(*session);
2843 
2844 	mutex_init(&session->eh_mutex);
2845 	spin_lock_init(&session->frwd_lock);
2846 	spin_lock_init(&session->back_lock);
2847 
2848 	/* initialize SCSI PDU commands pool */
2849 	if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2850 			    (void***)&session->cmds,
2851 			    cmd_task_size + sizeof(struct iscsi_task)))
2852 		goto cmdpool_alloc_fail;
2853 
2854 	/* pre-format cmds pool with ITT */
2855 	for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2856 		struct iscsi_task *task = session->cmds[cmd_i];
2857 
2858 		if (cmd_task_size)
2859 			task->dd_data = &task[1];
2860 		task->itt = cmd_i;
2861 		task->state = ISCSI_TASK_FREE;
2862 		INIT_LIST_HEAD(&task->running);
2863 	}
2864 
2865 	if (!try_module_get(iscsit->owner))
2866 		goto module_get_fail;
2867 
2868 	if (iscsi_add_session(cls_session, id))
2869 		goto cls_session_fail;
2870 
2871 	return cls_session;
2872 
2873 cls_session_fail:
2874 	module_put(iscsit->owner);
2875 module_get_fail:
2876 	iscsi_pool_free(&session->cmdpool);
2877 cmdpool_alloc_fail:
2878 	iscsi_free_session(cls_session);
2879 dec_session_count:
2880 	iscsi_host_dec_session_cnt(shost);
2881 	return NULL;
2882 }
2883 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2884 
2885 /**
2886  * iscsi_session_teardown - destroy session, host, and cls_session
2887  * @cls_session: iscsi session
2888  */
2889 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2890 {
2891 	struct iscsi_session *session = cls_session->dd_data;
2892 	struct module *owner = cls_session->transport->owner;
2893 	struct Scsi_Host *shost = session->host;
2894 
2895 	iscsi_pool_free(&session->cmdpool);
2896 
2897 	iscsi_remove_session(cls_session);
2898 
2899 	kfree(session->password);
2900 	kfree(session->password_in);
2901 	kfree(session->username);
2902 	kfree(session->username_in);
2903 	kfree(session->targetname);
2904 	kfree(session->targetalias);
2905 	kfree(session->initiatorname);
2906 	kfree(session->boot_root);
2907 	kfree(session->boot_nic);
2908 	kfree(session->boot_target);
2909 	kfree(session->ifacename);
2910 	kfree(session->portal_type);
2911 	kfree(session->discovery_parent_type);
2912 
2913 	iscsi_free_session(cls_session);
2914 
2915 	iscsi_host_dec_session_cnt(shost);
2916 	module_put(owner);
2917 }
2918 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2919 
2920 /**
2921  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2922  * @cls_session: iscsi_cls_session
2923  * @dd_size: private driver data size
2924  * @conn_idx: cid
2925  */
2926 struct iscsi_cls_conn *
2927 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2928 		 uint32_t conn_idx)
2929 {
2930 	struct iscsi_session *session = cls_session->dd_data;
2931 	struct iscsi_conn *conn;
2932 	struct iscsi_cls_conn *cls_conn;
2933 	char *data;
2934 
2935 	cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2936 				     conn_idx);
2937 	if (!cls_conn)
2938 		return NULL;
2939 	conn = cls_conn->dd_data;
2940 	memset(conn, 0, sizeof(*conn) + dd_size);
2941 
2942 	conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2943 	conn->session = session;
2944 	conn->cls_conn = cls_conn;
2945 	conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2946 	conn->id = conn_idx;
2947 	conn->exp_statsn = 0;
2948 	conn->tmf_state = TMF_INITIAL;
2949 
2950 	timer_setup(&conn->transport_timer, iscsi_check_transport_timeouts, 0);
2951 
2952 	INIT_LIST_HEAD(&conn->mgmtqueue);
2953 	INIT_LIST_HEAD(&conn->cmdqueue);
2954 	INIT_LIST_HEAD(&conn->requeue);
2955 	spin_lock_init(&conn->taskqueuelock);
2956 	INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2957 
2958 	/* allocate login_task used for the login/text sequences */
2959 	spin_lock_bh(&session->frwd_lock);
2960 	if (!kfifo_out(&session->cmdpool.queue,
2961                          (void*)&conn->login_task,
2962 			 sizeof(void*))) {
2963 		spin_unlock_bh(&session->frwd_lock);
2964 		goto login_task_alloc_fail;
2965 	}
2966 	spin_unlock_bh(&session->frwd_lock);
2967 
2968 	data = (char *) __get_free_pages(GFP_KERNEL,
2969 					 get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2970 	if (!data)
2971 		goto login_task_data_alloc_fail;
2972 	conn->login_task->data = conn->data = data;
2973 
2974 	timer_setup(&conn->tmf_timer, iscsi_tmf_timedout, 0);
2975 	init_waitqueue_head(&conn->ehwait);
2976 
2977 	return cls_conn;
2978 
2979 login_task_data_alloc_fail:
2980 	kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
2981 		    sizeof(void*));
2982 login_task_alloc_fail:
2983 	iscsi_destroy_conn(cls_conn);
2984 	return NULL;
2985 }
2986 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2987 
2988 /**
2989  * iscsi_conn_teardown - teardown iscsi connection
2990  * @cls_conn: iscsi class connection
2991  *
2992  * TODO: we may need to make this into a two step process
2993  * like scsi-mls remove + put host
2994  */
2995 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2996 {
2997 	struct iscsi_conn *conn = cls_conn->dd_data;
2998 	struct iscsi_session *session = conn->session;
2999 
3000 	del_timer_sync(&conn->transport_timer);
3001 
3002 	mutex_lock(&session->eh_mutex);
3003 	spin_lock_bh(&session->frwd_lock);
3004 	conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
3005 	if (session->leadconn == conn) {
3006 		/*
3007 		 * leading connection? then give up on recovery.
3008 		 */
3009 		session->state = ISCSI_STATE_TERMINATE;
3010 		wake_up(&conn->ehwait);
3011 	}
3012 	spin_unlock_bh(&session->frwd_lock);
3013 
3014 	/* flush queued up work because we free the connection below */
3015 	iscsi_suspend_tx(conn);
3016 
3017 	spin_lock_bh(&session->frwd_lock);
3018 	free_pages((unsigned long) conn->data,
3019 		   get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
3020 	kfree(conn->persistent_address);
3021 	kfree(conn->local_ipaddr);
3022 	/* regular RX path uses back_lock */
3023 	spin_lock_bh(&session->back_lock);
3024 	kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
3025 		    sizeof(void*));
3026 	spin_unlock_bh(&session->back_lock);
3027 	if (session->leadconn == conn)
3028 		session->leadconn = NULL;
3029 	spin_unlock_bh(&session->frwd_lock);
3030 	mutex_unlock(&session->eh_mutex);
3031 
3032 	iscsi_destroy_conn(cls_conn);
3033 }
3034 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
3035 
3036 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
3037 {
3038 	struct iscsi_conn *conn = cls_conn->dd_data;
3039 	struct iscsi_session *session = conn->session;
3040 
3041 	if (!session) {
3042 		iscsi_conn_printk(KERN_ERR, conn,
3043 				  "can't start unbound connection\n");
3044 		return -EPERM;
3045 	}
3046 
3047 	if ((session->imm_data_en || !session->initial_r2t_en) &&
3048 	     session->first_burst > session->max_burst) {
3049 		iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
3050 				  "first_burst %d max_burst %d\n",
3051 				  session->first_burst, session->max_burst);
3052 		return -EINVAL;
3053 	}
3054 
3055 	if (conn->ping_timeout && !conn->recv_timeout) {
3056 		iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
3057 				  "zero. Using 5 seconds\n.");
3058 		conn->recv_timeout = 5;
3059 	}
3060 
3061 	if (conn->recv_timeout && !conn->ping_timeout) {
3062 		iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
3063 				  "zero. Using 5 seconds.\n");
3064 		conn->ping_timeout = 5;
3065 	}
3066 
3067 	spin_lock_bh(&session->frwd_lock);
3068 	conn->c_stage = ISCSI_CONN_STARTED;
3069 	session->state = ISCSI_STATE_LOGGED_IN;
3070 	session->queued_cmdsn = session->cmdsn;
3071 
3072 	conn->last_recv = jiffies;
3073 	conn->last_ping = jiffies;
3074 	if (conn->recv_timeout && conn->ping_timeout)
3075 		mod_timer(&conn->transport_timer,
3076 			  jiffies + (conn->recv_timeout * HZ));
3077 
3078 	switch(conn->stop_stage) {
3079 	case STOP_CONN_RECOVER:
3080 		/*
3081 		 * unblock eh_abort() if it is blocked. re-try all
3082 		 * commands after successful recovery
3083 		 */
3084 		conn->stop_stage = 0;
3085 		conn->tmf_state = TMF_INITIAL;
3086 		session->age++;
3087 		if (session->age == 16)
3088 			session->age = 0;
3089 		break;
3090 	case STOP_CONN_TERM:
3091 		conn->stop_stage = 0;
3092 		break;
3093 	default:
3094 		break;
3095 	}
3096 	spin_unlock_bh(&session->frwd_lock);
3097 
3098 	iscsi_unblock_session(session->cls_session);
3099 	wake_up(&conn->ehwait);
3100 	return 0;
3101 }
3102 EXPORT_SYMBOL_GPL(iscsi_conn_start);
3103 
3104 static void
3105 fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn)
3106 {
3107 	struct iscsi_task *task;
3108 	int i, state;
3109 
3110 	for (i = 0; i < conn->session->cmds_max; i++) {
3111 		task = conn->session->cmds[i];
3112 		if (task->sc)
3113 			continue;
3114 
3115 		if (task->state == ISCSI_TASK_FREE)
3116 			continue;
3117 
3118 		ISCSI_DBG_SESSION(conn->session,
3119 				  "failing mgmt itt 0x%x state %d\n",
3120 				  task->itt, task->state);
3121 		state = ISCSI_TASK_ABRT_SESS_RECOV;
3122 		if (task->state == ISCSI_TASK_PENDING)
3123 			state = ISCSI_TASK_COMPLETED;
3124 		iscsi_complete_task(task, state);
3125 
3126 	}
3127 }
3128 
3129 static void iscsi_start_session_recovery(struct iscsi_session *session,
3130 					 struct iscsi_conn *conn, int flag)
3131 {
3132 	int old_stop_stage;
3133 
3134 	mutex_lock(&session->eh_mutex);
3135 	spin_lock_bh(&session->frwd_lock);
3136 	if (conn->stop_stage == STOP_CONN_TERM) {
3137 		spin_unlock_bh(&session->frwd_lock);
3138 		mutex_unlock(&session->eh_mutex);
3139 		return;
3140 	}
3141 
3142 	/*
3143 	 * When this is called for the in_login state, we only want to clean
3144 	 * up the login task and connection. We do not need to block and set
3145 	 * the recovery state again
3146 	 */
3147 	if (flag == STOP_CONN_TERM)
3148 		session->state = ISCSI_STATE_TERMINATE;
3149 	else if (conn->stop_stage != STOP_CONN_RECOVER)
3150 		session->state = ISCSI_STATE_IN_RECOVERY;
3151 
3152 	old_stop_stage = conn->stop_stage;
3153 	conn->stop_stage = flag;
3154 	spin_unlock_bh(&session->frwd_lock);
3155 
3156 	del_timer_sync(&conn->transport_timer);
3157 	iscsi_suspend_tx(conn);
3158 
3159 	spin_lock_bh(&session->frwd_lock);
3160 	conn->c_stage = ISCSI_CONN_STOPPED;
3161 	spin_unlock_bh(&session->frwd_lock);
3162 
3163 	/*
3164 	 * for connection level recovery we should not calculate
3165 	 * header digest. conn->hdr_size used for optimization
3166 	 * in hdr_extract() and will be re-negotiated at
3167 	 * set_param() time.
3168 	 */
3169 	if (flag == STOP_CONN_RECOVER) {
3170 		conn->hdrdgst_en = 0;
3171 		conn->datadgst_en = 0;
3172 		if (session->state == ISCSI_STATE_IN_RECOVERY &&
3173 		    old_stop_stage != STOP_CONN_RECOVER) {
3174 			ISCSI_DBG_SESSION(session, "blocking session\n");
3175 			iscsi_block_session(session->cls_session);
3176 		}
3177 	}
3178 
3179 	/*
3180 	 * flush queues.
3181 	 */
3182 	spin_lock_bh(&session->frwd_lock);
3183 	fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED);
3184 	fail_mgmt_tasks(session, conn);
3185 	memset(&conn->tmhdr, 0, sizeof(conn->tmhdr));
3186 	spin_unlock_bh(&session->frwd_lock);
3187 	mutex_unlock(&session->eh_mutex);
3188 }
3189 
3190 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
3191 {
3192 	struct iscsi_conn *conn = cls_conn->dd_data;
3193 	struct iscsi_session *session = conn->session;
3194 
3195 	switch (flag) {
3196 	case STOP_CONN_RECOVER:
3197 	case STOP_CONN_TERM:
3198 		iscsi_start_session_recovery(session, conn, flag);
3199 		break;
3200 	default:
3201 		iscsi_conn_printk(KERN_ERR, conn,
3202 				  "invalid stop flag %d\n", flag);
3203 	}
3204 }
3205 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
3206 
3207 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
3208 		    struct iscsi_cls_conn *cls_conn, int is_leading)
3209 {
3210 	struct iscsi_session *session = cls_session->dd_data;
3211 	struct iscsi_conn *conn = cls_conn->dd_data;
3212 
3213 	spin_lock_bh(&session->frwd_lock);
3214 	if (is_leading)
3215 		session->leadconn = conn;
3216 	spin_unlock_bh(&session->frwd_lock);
3217 
3218 	/*
3219 	 * Unblock xmitworker(), Login Phase will pass through.
3220 	 */
3221 	clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
3222 	clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
3223 	return 0;
3224 }
3225 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
3226 
3227 int iscsi_switch_str_param(char **param, char *new_val_buf)
3228 {
3229 	char *new_val;
3230 
3231 	if (*param) {
3232 		if (!strcmp(*param, new_val_buf))
3233 			return 0;
3234 	}
3235 
3236 	new_val = kstrdup(new_val_buf, GFP_NOIO);
3237 	if (!new_val)
3238 		return -ENOMEM;
3239 
3240 	kfree(*param);
3241 	*param = new_val;
3242 	return 0;
3243 }
3244 EXPORT_SYMBOL_GPL(iscsi_switch_str_param);
3245 
3246 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
3247 		    enum iscsi_param param, char *buf, int buflen)
3248 {
3249 	struct iscsi_conn *conn = cls_conn->dd_data;
3250 	struct iscsi_session *session = conn->session;
3251 	int val;
3252 
3253 	switch(param) {
3254 	case ISCSI_PARAM_FAST_ABORT:
3255 		sscanf(buf, "%d", &session->fast_abort);
3256 		break;
3257 	case ISCSI_PARAM_ABORT_TMO:
3258 		sscanf(buf, "%d", &session->abort_timeout);
3259 		break;
3260 	case ISCSI_PARAM_LU_RESET_TMO:
3261 		sscanf(buf, "%d", &session->lu_reset_timeout);
3262 		break;
3263 	case ISCSI_PARAM_TGT_RESET_TMO:
3264 		sscanf(buf, "%d", &session->tgt_reset_timeout);
3265 		break;
3266 	case ISCSI_PARAM_PING_TMO:
3267 		sscanf(buf, "%d", &conn->ping_timeout);
3268 		break;
3269 	case ISCSI_PARAM_RECV_TMO:
3270 		sscanf(buf, "%d", &conn->recv_timeout);
3271 		break;
3272 	case ISCSI_PARAM_MAX_RECV_DLENGTH:
3273 		sscanf(buf, "%d", &conn->max_recv_dlength);
3274 		break;
3275 	case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3276 		sscanf(buf, "%d", &conn->max_xmit_dlength);
3277 		break;
3278 	case ISCSI_PARAM_HDRDGST_EN:
3279 		sscanf(buf, "%d", &conn->hdrdgst_en);
3280 		break;
3281 	case ISCSI_PARAM_DATADGST_EN:
3282 		sscanf(buf, "%d", &conn->datadgst_en);
3283 		break;
3284 	case ISCSI_PARAM_INITIAL_R2T_EN:
3285 		sscanf(buf, "%d", &session->initial_r2t_en);
3286 		break;
3287 	case ISCSI_PARAM_MAX_R2T:
3288 		sscanf(buf, "%hu", &session->max_r2t);
3289 		break;
3290 	case ISCSI_PARAM_IMM_DATA_EN:
3291 		sscanf(buf, "%d", &session->imm_data_en);
3292 		break;
3293 	case ISCSI_PARAM_FIRST_BURST:
3294 		sscanf(buf, "%d", &session->first_burst);
3295 		break;
3296 	case ISCSI_PARAM_MAX_BURST:
3297 		sscanf(buf, "%d", &session->max_burst);
3298 		break;
3299 	case ISCSI_PARAM_PDU_INORDER_EN:
3300 		sscanf(buf, "%d", &session->pdu_inorder_en);
3301 		break;
3302 	case ISCSI_PARAM_DATASEQ_INORDER_EN:
3303 		sscanf(buf, "%d", &session->dataseq_inorder_en);
3304 		break;
3305 	case ISCSI_PARAM_ERL:
3306 		sscanf(buf, "%d", &session->erl);
3307 		break;
3308 	case ISCSI_PARAM_EXP_STATSN:
3309 		sscanf(buf, "%u", &conn->exp_statsn);
3310 		break;
3311 	case ISCSI_PARAM_USERNAME:
3312 		return iscsi_switch_str_param(&session->username, buf);
3313 	case ISCSI_PARAM_USERNAME_IN:
3314 		return iscsi_switch_str_param(&session->username_in, buf);
3315 	case ISCSI_PARAM_PASSWORD:
3316 		return iscsi_switch_str_param(&session->password, buf);
3317 	case ISCSI_PARAM_PASSWORD_IN:
3318 		return iscsi_switch_str_param(&session->password_in, buf);
3319 	case ISCSI_PARAM_TARGET_NAME:
3320 		return iscsi_switch_str_param(&session->targetname, buf);
3321 	case ISCSI_PARAM_TARGET_ALIAS:
3322 		return iscsi_switch_str_param(&session->targetalias, buf);
3323 	case ISCSI_PARAM_TPGT:
3324 		sscanf(buf, "%d", &session->tpgt);
3325 		break;
3326 	case ISCSI_PARAM_PERSISTENT_PORT:
3327 		sscanf(buf, "%d", &conn->persistent_port);
3328 		break;
3329 	case ISCSI_PARAM_PERSISTENT_ADDRESS:
3330 		return iscsi_switch_str_param(&conn->persistent_address, buf);
3331 	case ISCSI_PARAM_IFACE_NAME:
3332 		return iscsi_switch_str_param(&session->ifacename, buf);
3333 	case ISCSI_PARAM_INITIATOR_NAME:
3334 		return iscsi_switch_str_param(&session->initiatorname, buf);
3335 	case ISCSI_PARAM_BOOT_ROOT:
3336 		return iscsi_switch_str_param(&session->boot_root, buf);
3337 	case ISCSI_PARAM_BOOT_NIC:
3338 		return iscsi_switch_str_param(&session->boot_nic, buf);
3339 	case ISCSI_PARAM_BOOT_TARGET:
3340 		return iscsi_switch_str_param(&session->boot_target, buf);
3341 	case ISCSI_PARAM_PORTAL_TYPE:
3342 		return iscsi_switch_str_param(&session->portal_type, buf);
3343 	case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3344 		return iscsi_switch_str_param(&session->discovery_parent_type,
3345 					      buf);
3346 	case ISCSI_PARAM_DISCOVERY_SESS:
3347 		sscanf(buf, "%d", &val);
3348 		session->discovery_sess = !!val;
3349 		break;
3350 	case ISCSI_PARAM_LOCAL_IPADDR:
3351 		return iscsi_switch_str_param(&conn->local_ipaddr, buf);
3352 	default:
3353 		return -ENOSYS;
3354 	}
3355 
3356 	return 0;
3357 }
3358 EXPORT_SYMBOL_GPL(iscsi_set_param);
3359 
3360 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
3361 			    enum iscsi_param param, char *buf)
3362 {
3363 	struct iscsi_session *session = cls_session->dd_data;
3364 	int len;
3365 
3366 	switch(param) {
3367 	case ISCSI_PARAM_FAST_ABORT:
3368 		len = sprintf(buf, "%d\n", session->fast_abort);
3369 		break;
3370 	case ISCSI_PARAM_ABORT_TMO:
3371 		len = sprintf(buf, "%d\n", session->abort_timeout);
3372 		break;
3373 	case ISCSI_PARAM_LU_RESET_TMO:
3374 		len = sprintf(buf, "%d\n", session->lu_reset_timeout);
3375 		break;
3376 	case ISCSI_PARAM_TGT_RESET_TMO:
3377 		len = sprintf(buf, "%d\n", session->tgt_reset_timeout);
3378 		break;
3379 	case ISCSI_PARAM_INITIAL_R2T_EN:
3380 		len = sprintf(buf, "%d\n", session->initial_r2t_en);
3381 		break;
3382 	case ISCSI_PARAM_MAX_R2T:
3383 		len = sprintf(buf, "%hu\n", session->max_r2t);
3384 		break;
3385 	case ISCSI_PARAM_IMM_DATA_EN:
3386 		len = sprintf(buf, "%d\n", session->imm_data_en);
3387 		break;
3388 	case ISCSI_PARAM_FIRST_BURST:
3389 		len = sprintf(buf, "%u\n", session->first_burst);
3390 		break;
3391 	case ISCSI_PARAM_MAX_BURST:
3392 		len = sprintf(buf, "%u\n", session->max_burst);
3393 		break;
3394 	case ISCSI_PARAM_PDU_INORDER_EN:
3395 		len = sprintf(buf, "%d\n", session->pdu_inorder_en);
3396 		break;
3397 	case ISCSI_PARAM_DATASEQ_INORDER_EN:
3398 		len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
3399 		break;
3400 	case ISCSI_PARAM_DEF_TASKMGMT_TMO:
3401 		len = sprintf(buf, "%d\n", session->def_taskmgmt_tmo);
3402 		break;
3403 	case ISCSI_PARAM_ERL:
3404 		len = sprintf(buf, "%d\n", session->erl);
3405 		break;
3406 	case ISCSI_PARAM_TARGET_NAME:
3407 		len = sprintf(buf, "%s\n", session->targetname);
3408 		break;
3409 	case ISCSI_PARAM_TARGET_ALIAS:
3410 		len = sprintf(buf, "%s\n", session->targetalias);
3411 		break;
3412 	case ISCSI_PARAM_TPGT:
3413 		len = sprintf(buf, "%d\n", session->tpgt);
3414 		break;
3415 	case ISCSI_PARAM_USERNAME:
3416 		len = sprintf(buf, "%s\n", session->username);
3417 		break;
3418 	case ISCSI_PARAM_USERNAME_IN:
3419 		len = sprintf(buf, "%s\n", session->username_in);
3420 		break;
3421 	case ISCSI_PARAM_PASSWORD:
3422 		len = sprintf(buf, "%s\n", session->password);
3423 		break;
3424 	case ISCSI_PARAM_PASSWORD_IN:
3425 		len = sprintf(buf, "%s\n", session->password_in);
3426 		break;
3427 	case ISCSI_PARAM_IFACE_NAME:
3428 		len = sprintf(buf, "%s\n", session->ifacename);
3429 		break;
3430 	case ISCSI_PARAM_INITIATOR_NAME:
3431 		len = sprintf(buf, "%s\n", session->initiatorname);
3432 		break;
3433 	case ISCSI_PARAM_BOOT_ROOT:
3434 		len = sprintf(buf, "%s\n", session->boot_root);
3435 		break;
3436 	case ISCSI_PARAM_BOOT_NIC:
3437 		len = sprintf(buf, "%s\n", session->boot_nic);
3438 		break;
3439 	case ISCSI_PARAM_BOOT_TARGET:
3440 		len = sprintf(buf, "%s\n", session->boot_target);
3441 		break;
3442 	case ISCSI_PARAM_AUTO_SND_TGT_DISABLE:
3443 		len = sprintf(buf, "%u\n", session->auto_snd_tgt_disable);
3444 		break;
3445 	case ISCSI_PARAM_DISCOVERY_SESS:
3446 		len = sprintf(buf, "%u\n", session->discovery_sess);
3447 		break;
3448 	case ISCSI_PARAM_PORTAL_TYPE:
3449 		len = sprintf(buf, "%s\n", session->portal_type);
3450 		break;
3451 	case ISCSI_PARAM_CHAP_AUTH_EN:
3452 		len = sprintf(buf, "%u\n", session->chap_auth_en);
3453 		break;
3454 	case ISCSI_PARAM_DISCOVERY_LOGOUT_EN:
3455 		len = sprintf(buf, "%u\n", session->discovery_logout_en);
3456 		break;
3457 	case ISCSI_PARAM_BIDI_CHAP_EN:
3458 		len = sprintf(buf, "%u\n", session->bidi_chap_en);
3459 		break;
3460 	case ISCSI_PARAM_DISCOVERY_AUTH_OPTIONAL:
3461 		len = sprintf(buf, "%u\n", session->discovery_auth_optional);
3462 		break;
3463 	case ISCSI_PARAM_DEF_TIME2WAIT:
3464 		len = sprintf(buf, "%d\n", session->time2wait);
3465 		break;
3466 	case ISCSI_PARAM_DEF_TIME2RETAIN:
3467 		len = sprintf(buf, "%d\n", session->time2retain);
3468 		break;
3469 	case ISCSI_PARAM_TSID:
3470 		len = sprintf(buf, "%u\n", session->tsid);
3471 		break;
3472 	case ISCSI_PARAM_ISID:
3473 		len = sprintf(buf, "%02x%02x%02x%02x%02x%02x\n",
3474 			      session->isid[0], session->isid[1],
3475 			      session->isid[2], session->isid[3],
3476 			      session->isid[4], session->isid[5]);
3477 		break;
3478 	case ISCSI_PARAM_DISCOVERY_PARENT_IDX:
3479 		len = sprintf(buf, "%u\n", session->discovery_parent_idx);
3480 		break;
3481 	case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3482 		if (session->discovery_parent_type)
3483 			len = sprintf(buf, "%s\n",
3484 				      session->discovery_parent_type);
3485 		else
3486 			len = sprintf(buf, "\n");
3487 		break;
3488 	default:
3489 		return -ENOSYS;
3490 	}
3491 
3492 	return len;
3493 }
3494 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
3495 
3496 int iscsi_conn_get_addr_param(struct sockaddr_storage *addr,
3497 			      enum iscsi_param param, char *buf)
3498 {
3499 	struct sockaddr_in6 *sin6 = NULL;
3500 	struct sockaddr_in *sin = NULL;
3501 	int len;
3502 
3503 	switch (addr->ss_family) {
3504 	case AF_INET:
3505 		sin = (struct sockaddr_in *)addr;
3506 		break;
3507 	case AF_INET6:
3508 		sin6 = (struct sockaddr_in6 *)addr;
3509 		break;
3510 	default:
3511 		return -EINVAL;
3512 	}
3513 
3514 	switch (param) {
3515 	case ISCSI_PARAM_CONN_ADDRESS:
3516 	case ISCSI_HOST_PARAM_IPADDRESS:
3517 		if (sin)
3518 			len = sprintf(buf, "%pI4\n", &sin->sin_addr.s_addr);
3519 		else
3520 			len = sprintf(buf, "%pI6\n", &sin6->sin6_addr);
3521 		break;
3522 	case ISCSI_PARAM_CONN_PORT:
3523 	case ISCSI_PARAM_LOCAL_PORT:
3524 		if (sin)
3525 			len = sprintf(buf, "%hu\n", be16_to_cpu(sin->sin_port));
3526 		else
3527 			len = sprintf(buf, "%hu\n",
3528 				      be16_to_cpu(sin6->sin6_port));
3529 		break;
3530 	default:
3531 		return -EINVAL;
3532 	}
3533 
3534 	return len;
3535 }
3536 EXPORT_SYMBOL_GPL(iscsi_conn_get_addr_param);
3537 
3538 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
3539 			 enum iscsi_param param, char *buf)
3540 {
3541 	struct iscsi_conn *conn = cls_conn->dd_data;
3542 	int len;
3543 
3544 	switch(param) {
3545 	case ISCSI_PARAM_PING_TMO:
3546 		len = sprintf(buf, "%u\n", conn->ping_timeout);
3547 		break;
3548 	case ISCSI_PARAM_RECV_TMO:
3549 		len = sprintf(buf, "%u\n", conn->recv_timeout);
3550 		break;
3551 	case ISCSI_PARAM_MAX_RECV_DLENGTH:
3552 		len = sprintf(buf, "%u\n", conn->max_recv_dlength);
3553 		break;
3554 	case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3555 		len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
3556 		break;
3557 	case ISCSI_PARAM_HDRDGST_EN:
3558 		len = sprintf(buf, "%d\n", conn->hdrdgst_en);
3559 		break;
3560 	case ISCSI_PARAM_DATADGST_EN:
3561 		len = sprintf(buf, "%d\n", conn->datadgst_en);
3562 		break;
3563 	case ISCSI_PARAM_IFMARKER_EN:
3564 		len = sprintf(buf, "%d\n", conn->ifmarker_en);
3565 		break;
3566 	case ISCSI_PARAM_OFMARKER_EN:
3567 		len = sprintf(buf, "%d\n", conn->ofmarker_en);
3568 		break;
3569 	case ISCSI_PARAM_EXP_STATSN:
3570 		len = sprintf(buf, "%u\n", conn->exp_statsn);
3571 		break;
3572 	case ISCSI_PARAM_PERSISTENT_PORT:
3573 		len = sprintf(buf, "%d\n", conn->persistent_port);
3574 		break;
3575 	case ISCSI_PARAM_PERSISTENT_ADDRESS:
3576 		len = sprintf(buf, "%s\n", conn->persistent_address);
3577 		break;
3578 	case ISCSI_PARAM_STATSN:
3579 		len = sprintf(buf, "%u\n", conn->statsn);
3580 		break;
3581 	case ISCSI_PARAM_MAX_SEGMENT_SIZE:
3582 		len = sprintf(buf, "%u\n", conn->max_segment_size);
3583 		break;
3584 	case ISCSI_PARAM_KEEPALIVE_TMO:
3585 		len = sprintf(buf, "%u\n", conn->keepalive_tmo);
3586 		break;
3587 	case ISCSI_PARAM_LOCAL_PORT:
3588 		len = sprintf(buf, "%u\n", conn->local_port);
3589 		break;
3590 	case ISCSI_PARAM_TCP_TIMESTAMP_STAT:
3591 		len = sprintf(buf, "%u\n", conn->tcp_timestamp_stat);
3592 		break;
3593 	case ISCSI_PARAM_TCP_NAGLE_DISABLE:
3594 		len = sprintf(buf, "%u\n", conn->tcp_nagle_disable);
3595 		break;
3596 	case ISCSI_PARAM_TCP_WSF_DISABLE:
3597 		len = sprintf(buf, "%u\n", conn->tcp_wsf_disable);
3598 		break;
3599 	case ISCSI_PARAM_TCP_TIMER_SCALE:
3600 		len = sprintf(buf, "%u\n", conn->tcp_timer_scale);
3601 		break;
3602 	case ISCSI_PARAM_TCP_TIMESTAMP_EN:
3603 		len = sprintf(buf, "%u\n", conn->tcp_timestamp_en);
3604 		break;
3605 	case ISCSI_PARAM_IP_FRAGMENT_DISABLE:
3606 		len = sprintf(buf, "%u\n", conn->fragment_disable);
3607 		break;
3608 	case ISCSI_PARAM_IPV4_TOS:
3609 		len = sprintf(buf, "%u\n", conn->ipv4_tos);
3610 		break;
3611 	case ISCSI_PARAM_IPV6_TC:
3612 		len = sprintf(buf, "%u\n", conn->ipv6_traffic_class);
3613 		break;
3614 	case ISCSI_PARAM_IPV6_FLOW_LABEL:
3615 		len = sprintf(buf, "%u\n", conn->ipv6_flow_label);
3616 		break;
3617 	case ISCSI_PARAM_IS_FW_ASSIGNED_IPV6:
3618 		len = sprintf(buf, "%u\n", conn->is_fw_assigned_ipv6);
3619 		break;
3620 	case ISCSI_PARAM_TCP_XMIT_WSF:
3621 		len = sprintf(buf, "%u\n", conn->tcp_xmit_wsf);
3622 		break;
3623 	case ISCSI_PARAM_TCP_RECV_WSF:
3624 		len = sprintf(buf, "%u\n", conn->tcp_recv_wsf);
3625 		break;
3626 	case ISCSI_PARAM_LOCAL_IPADDR:
3627 		len = sprintf(buf, "%s\n", conn->local_ipaddr);
3628 		break;
3629 	default:
3630 		return -ENOSYS;
3631 	}
3632 
3633 	return len;
3634 }
3635 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
3636 
3637 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3638 			 char *buf)
3639 {
3640 	struct iscsi_host *ihost = shost_priv(shost);
3641 	int len;
3642 
3643 	switch (param) {
3644 	case ISCSI_HOST_PARAM_NETDEV_NAME:
3645 		len = sprintf(buf, "%s\n", ihost->netdev);
3646 		break;
3647 	case ISCSI_HOST_PARAM_HWADDRESS:
3648 		len = sprintf(buf, "%s\n", ihost->hwaddress);
3649 		break;
3650 	case ISCSI_HOST_PARAM_INITIATOR_NAME:
3651 		len = sprintf(buf, "%s\n", ihost->initiatorname);
3652 		break;
3653 	default:
3654 		return -ENOSYS;
3655 	}
3656 
3657 	return len;
3658 }
3659 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
3660 
3661 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3662 			 char *buf, int buflen)
3663 {
3664 	struct iscsi_host *ihost = shost_priv(shost);
3665 
3666 	switch (param) {
3667 	case ISCSI_HOST_PARAM_NETDEV_NAME:
3668 		return iscsi_switch_str_param(&ihost->netdev, buf);
3669 	case ISCSI_HOST_PARAM_HWADDRESS:
3670 		return iscsi_switch_str_param(&ihost->hwaddress, buf);
3671 	case ISCSI_HOST_PARAM_INITIATOR_NAME:
3672 		return iscsi_switch_str_param(&ihost->initiatorname, buf);
3673 	default:
3674 		return -ENOSYS;
3675 	}
3676 
3677 	return 0;
3678 }
3679 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
3680 
3681 MODULE_AUTHOR("Mike Christie");
3682 MODULE_DESCRIPTION("iSCSI library functions");
3683 MODULE_LICENSE("GPL");
3684