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