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