1// SPDX-License-Identifier: GPL-2.0-or-later
2/*******************************************************************************
3 * This file contains error recovery level one used by the iSCSI Target driver.
4 *
5 * (c) Copyright 2007-2013 Datera, Inc.
6 *
7 * Author: Nicholas A. Bellinger <nab@linux-iscsi.org>
8 *
9 ******************************************************************************/
10
11#include <linux/list.h>
12#include <linux/slab.h>
13#include <scsi/iscsi_proto.h>
14#include <target/target_core_base.h>
15#include <target/target_core_fabric.h>
16#include <target/iscsi/iscsi_transport.h>
17
18#include <target/iscsi/iscsi_target_core.h>
19#include "iscsi_target_seq_pdu_list.h"
20#include "iscsi_target_datain_values.h"
21#include "iscsi_target_device.h"
22#include "iscsi_target_tpg.h"
23#include "iscsi_target_util.h"
24#include "iscsi_target_erl0.h"
25#include "iscsi_target_erl1.h"
26#include "iscsi_target_erl2.h"
27#include "iscsi_target.h"
28
29#define OFFLOAD_BUF_SIZE	32768U
30
31/*
32 *	Used to dump excess datain payload for certain error recovery
33 *	situations.  Receive in OFFLOAD_BUF_SIZE max of datain per rx_data().
34 *
35 *	dump_padding_digest denotes if padding and data digests need
36 *	to be dumped.
37 */
38int iscsit_dump_data_payload(
39	struct iscsit_conn *conn,
40	u32 buf_len,
41	int dump_padding_digest)
42{
43	char *buf;
44	int ret = DATAOUT_WITHIN_COMMAND_RECOVERY, rx_got;
45	u32 length, offset = 0, size;
46	struct kvec iov;
47
48	if (conn->sess->sess_ops->RDMAExtensions)
49		return 0;
50
51	if (dump_padding_digest) {
52		buf_len = ALIGN(buf_len, 4);
53		if (conn->conn_ops->DataDigest)
54			buf_len += ISCSI_CRC_LEN;
55	}
56
57	length = min(buf_len, OFFLOAD_BUF_SIZE);
58
59	buf = kzalloc(length, GFP_ATOMIC);
60	if (!buf) {
61		pr_err("Unable to allocate %u bytes for offload"
62				" buffer.\n", length);
63		return -1;
64	}
65	memset(&iov, 0, sizeof(struct kvec));
66
67	while (offset < buf_len) {
68		size = min(buf_len - offset, length);
69
70		iov.iov_len = size;
71		iov.iov_base = buf;
72
73		rx_got = rx_data(conn, &iov, 1, size);
74		if (rx_got != size) {
75			ret = DATAOUT_CANNOT_RECOVER;
76			break;
77		}
78
79		offset += size;
80	}
81
82	kfree(buf);
83	return ret;
84}
85
86/*
87 *	Used for retransmitting R2Ts from a R2T SNACK request.
88 */
89static int iscsit_send_recovery_r2t_for_snack(
90	struct iscsit_cmd *cmd,
91	struct iscsi_r2t *r2t)
92{
93	/*
94	 * If the struct iscsi_r2t has not been sent yet, we can safely
95	 * ignore retransmission
96	 * of the R2TSN in question.
97	 */
98	spin_lock_bh(&cmd->r2t_lock);
99	if (!r2t->sent_r2t) {
100		spin_unlock_bh(&cmd->r2t_lock);
101		return 0;
102	}
103	r2t->sent_r2t = 0;
104	spin_unlock_bh(&cmd->r2t_lock);
105
106	iscsit_add_cmd_to_immediate_queue(cmd, cmd->conn, ISTATE_SEND_R2T);
107
108	return 0;
109}
110
111static int iscsit_handle_r2t_snack(
112	struct iscsit_cmd *cmd,
113	unsigned char *buf,
114	u32 begrun,
115	u32 runlength)
116{
117	u32 last_r2tsn;
118	struct iscsi_r2t *r2t;
119
120	/*
121	 * Make sure the initiator is not requesting retransmission
122	 * of R2TSNs already acknowledged by a TMR TASK_REASSIGN.
123	 */
124	if ((cmd->cmd_flags & ICF_GOT_DATACK_SNACK) &&
125	    (begrun <= cmd->acked_data_sn)) {
126		pr_err("ITT: 0x%08x, R2T SNACK requesting"
127			" retransmission of R2TSN: 0x%08x to 0x%08x but already"
128			" acked to  R2TSN: 0x%08x by TMR TASK_REASSIGN,"
129			" protocol error.\n", cmd->init_task_tag, begrun,
130			(begrun + runlength), cmd->acked_data_sn);
131
132		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
133	}
134
135	if (runlength) {
136		if ((begrun + runlength) > cmd->r2t_sn) {
137			pr_err("Command ITT: 0x%08x received R2T SNACK"
138			" with BegRun: 0x%08x, RunLength: 0x%08x, exceeds"
139			" current R2TSN: 0x%08x, protocol error.\n",
140			cmd->init_task_tag, begrun, runlength, cmd->r2t_sn);
141			return iscsit_reject_cmd(cmd,
142					ISCSI_REASON_BOOKMARK_INVALID, buf);
143		}
144		last_r2tsn = (begrun + runlength);
145	} else
146		last_r2tsn = cmd->r2t_sn;
147
148	while (begrun < last_r2tsn) {
149		r2t = iscsit_get_holder_for_r2tsn(cmd, begrun);
150		if (!r2t)
151			return -1;
152		if (iscsit_send_recovery_r2t_for_snack(cmd, r2t) < 0)
153			return -1;
154
155		begrun++;
156	}
157
158	return 0;
159}
160
161/*
162 *	Generates Offsets and NextBurstLength based on Begrun and Runlength
163 *	carried in a Data SNACK or ExpDataSN in TMR TASK_REASSIGN.
164 *
165 *	For DataSequenceInOrder=Yes and DataPDUInOrder=[Yes,No] only.
166 *
167 *	FIXME: How is this handled for a RData SNACK?
168 */
169int iscsit_create_recovery_datain_values_datasequenceinorder_yes(
170	struct iscsit_cmd *cmd,
171	struct iscsi_datain_req *dr)
172{
173	u32 data_sn = 0, data_sn_count = 0;
174	u32 pdu_start = 0, seq_no = 0;
175	u32 begrun = dr->begrun;
176	struct iscsit_conn *conn = cmd->conn;
177
178	while (begrun > data_sn++) {
179		data_sn_count++;
180		if ((dr->next_burst_len +
181		     conn->conn_ops->MaxRecvDataSegmentLength) <
182		     conn->sess->sess_ops->MaxBurstLength) {
183			dr->read_data_done +=
184				conn->conn_ops->MaxRecvDataSegmentLength;
185			dr->next_burst_len +=
186				conn->conn_ops->MaxRecvDataSegmentLength;
187		} else {
188			dr->read_data_done +=
189				(conn->sess->sess_ops->MaxBurstLength -
190				 dr->next_burst_len);
191			dr->next_burst_len = 0;
192			pdu_start += data_sn_count;
193			data_sn_count = 0;
194			seq_no++;
195		}
196	}
197
198	if (!conn->sess->sess_ops->DataPDUInOrder) {
199		cmd->seq_no = seq_no;
200		cmd->pdu_start = pdu_start;
201		cmd->pdu_send_order = data_sn_count;
202	}
203
204	return 0;
205}
206
207/*
208 *	Generates Offsets and NextBurstLength based on Begrun and Runlength
209 *	carried in a Data SNACK or ExpDataSN in TMR TASK_REASSIGN.
210 *
211 *	For DataSequenceInOrder=No and DataPDUInOrder=[Yes,No] only.
212 *
213 *	FIXME: How is this handled for a RData SNACK?
214 */
215int iscsit_create_recovery_datain_values_datasequenceinorder_no(
216	struct iscsit_cmd *cmd,
217	struct iscsi_datain_req *dr)
218{
219	int found_seq = 0, i;
220	u32 data_sn, read_data_done = 0, seq_send_order = 0;
221	u32 begrun = dr->begrun;
222	u32 runlength = dr->runlength;
223	struct iscsit_conn *conn = cmd->conn;
224	struct iscsi_seq *first_seq = NULL, *seq = NULL;
225
226	if (!cmd->seq_list) {
227		pr_err("struct iscsit_cmd->seq_list is NULL!\n");
228		return -1;
229	}
230
231	/*
232	 * Calculate read_data_done for all sequences containing a
233	 * first_datasn and last_datasn less than the BegRun.
234	 *
235	 * Locate the struct iscsi_seq the BegRun lies within and calculate
236	 * NextBurstLenghth up to the DataSN based on MaxRecvDataSegmentLength.
237	 *
238	 * Also use struct iscsi_seq->seq_send_order to determine where to start.
239	 */
240	for (i = 0; i < cmd->seq_count; i++) {
241		seq = &cmd->seq_list[i];
242
243		if (!seq->seq_send_order)
244			first_seq = seq;
245
246		/*
247		 * No data has been transferred for this DataIN sequence, so the
248		 * seq->first_datasn and seq->last_datasn have not been set.
249		 */
250		if (!seq->sent) {
251			pr_err("Ignoring non-sent sequence 0x%08x ->"
252				" 0x%08x\n\n", seq->first_datasn,
253				seq->last_datasn);
254			continue;
255		}
256
257		/*
258		 * This DataIN sequence is precedes the received BegRun, add the
259		 * total xfer_len of the sequence to read_data_done and reset
260		 * seq->pdu_send_order.
261		 */
262		if ((seq->first_datasn < begrun) &&
263				(seq->last_datasn < begrun)) {
264			pr_err("Pre BegRun sequence 0x%08x ->"
265				" 0x%08x\n", seq->first_datasn,
266				seq->last_datasn);
267
268			read_data_done += cmd->seq_list[i].xfer_len;
269			seq->next_burst_len = seq->pdu_send_order = 0;
270			continue;
271		}
272
273		/*
274		 * The BegRun lies within this DataIN sequence.
275		 */
276		if ((seq->first_datasn <= begrun) &&
277				(seq->last_datasn >= begrun)) {
278			pr_err("Found sequence begrun: 0x%08x in"
279				" 0x%08x -> 0x%08x\n", begrun,
280				seq->first_datasn, seq->last_datasn);
281
282			seq_send_order = seq->seq_send_order;
283			data_sn = seq->first_datasn;
284			seq->next_burst_len = seq->pdu_send_order = 0;
285			found_seq = 1;
286
287			/*
288			 * For DataPDUInOrder=Yes, while the first DataSN of
289			 * the sequence is less than the received BegRun, add
290			 * the MaxRecvDataSegmentLength to read_data_done and
291			 * to the sequence's next_burst_len;
292			 *
293			 * For DataPDUInOrder=No, while the first DataSN of the
294			 * sequence is less than the received BegRun, find the
295			 * struct iscsi_pdu of the DataSN in question and add the
296			 * MaxRecvDataSegmentLength to read_data_done and to the
297			 * sequence's next_burst_len;
298			 */
299			if (conn->sess->sess_ops->DataPDUInOrder) {
300				while (data_sn < begrun) {
301					seq->pdu_send_order++;
302					read_data_done +=
303						conn->conn_ops->MaxRecvDataSegmentLength;
304					seq->next_burst_len +=
305						conn->conn_ops->MaxRecvDataSegmentLength;
306					data_sn++;
307				}
308			} else {
309				int j;
310				struct iscsi_pdu *pdu;
311
312				while (data_sn < begrun) {
313					seq->pdu_send_order++;
314
315					for (j = 0; j < seq->pdu_count; j++) {
316						pdu = &cmd->pdu_list[
317							seq->pdu_start + j];
318						if (pdu->data_sn == data_sn) {
319							read_data_done +=
320								pdu->length;
321							seq->next_burst_len +=
322								pdu->length;
323						}
324					}
325					data_sn++;
326				}
327			}
328			continue;
329		}
330
331		/*
332		 * This DataIN sequence is larger than the received BegRun,
333		 * reset seq->pdu_send_order and continue.
334		 */
335		if ((seq->first_datasn > begrun) ||
336				(seq->last_datasn > begrun)) {
337			pr_err("Post BegRun sequence 0x%08x -> 0x%08x\n",
338					seq->first_datasn, seq->last_datasn);
339
340			seq->next_burst_len = seq->pdu_send_order = 0;
341			continue;
342		}
343	}
344
345	if (!found_seq) {
346		if (!begrun) {
347			if (!first_seq) {
348				pr_err("ITT: 0x%08x, Begrun: 0x%08x"
349					" but first_seq is NULL\n",
350					cmd->init_task_tag, begrun);
351				return -1;
352			}
353			seq_send_order = first_seq->seq_send_order;
354			seq->next_burst_len = seq->pdu_send_order = 0;
355			goto done;
356		}
357
358		pr_err("Unable to locate struct iscsi_seq for ITT: 0x%08x,"
359			" BegRun: 0x%08x, RunLength: 0x%08x while"
360			" DataSequenceInOrder=No and DataPDUInOrder=%s.\n",
361				cmd->init_task_tag, begrun, runlength,
362			(conn->sess->sess_ops->DataPDUInOrder) ? "Yes" : "No");
363		return -1;
364	}
365
366done:
367	dr->read_data_done = read_data_done;
368	dr->seq_send_order = seq_send_order;
369
370	return 0;
371}
372
373static int iscsit_handle_recovery_datain(
374	struct iscsit_cmd *cmd,
375	unsigned char *buf,
376	u32 begrun,
377	u32 runlength)
378{
379	struct iscsit_conn *conn = cmd->conn;
380	struct iscsi_datain_req *dr;
381	struct se_cmd *se_cmd = &cmd->se_cmd;
382
383	if (!(se_cmd->transport_state & CMD_T_COMPLETE)) {
384		pr_err("Ignoring ITT: 0x%08x Data SNACK\n",
385				cmd->init_task_tag);
386		return 0;
387	}
388
389	/*
390	 * Make sure the initiator is not requesting retransmission
391	 * of DataSNs already acknowledged by a Data ACK SNACK.
392	 */
393	if ((cmd->cmd_flags & ICF_GOT_DATACK_SNACK) &&
394	    (begrun <= cmd->acked_data_sn)) {
395		pr_err("ITT: 0x%08x, Data SNACK requesting"
396			" retransmission of DataSN: 0x%08x to 0x%08x but"
397			" already acked to DataSN: 0x%08x by Data ACK SNACK,"
398			" protocol error.\n", cmd->init_task_tag, begrun,
399			(begrun + runlength), cmd->acked_data_sn);
400
401		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
402	}
403
404	/*
405	 * Make sure BegRun and RunLength in the Data SNACK are sane.
406	 * Note: (cmd->data_sn - 1) will carry the maximum DataSN sent.
407	 */
408	if ((begrun + runlength) > (cmd->data_sn - 1)) {
409		pr_err("Initiator requesting BegRun: 0x%08x, RunLength"
410			": 0x%08x greater than maximum DataSN: 0x%08x.\n",
411				begrun, runlength, (cmd->data_sn - 1));
412		return iscsit_reject_cmd(cmd, ISCSI_REASON_BOOKMARK_INVALID,
413					 buf);
414	}
415
416	dr = iscsit_allocate_datain_req();
417	if (!dr)
418		return iscsit_reject_cmd(cmd, ISCSI_REASON_BOOKMARK_NO_RESOURCES,
419					 buf);
420
421	dr->data_sn = dr->begrun = begrun;
422	dr->runlength = runlength;
423	dr->generate_recovery_values = 1;
424	dr->recovery = DATAIN_WITHIN_COMMAND_RECOVERY;
425
426	iscsit_attach_datain_req(cmd, dr);
427
428	cmd->i_state = ISTATE_SEND_DATAIN;
429	iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
430
431	return 0;
432}
433
434int iscsit_handle_recovery_datain_or_r2t(
435	struct iscsit_conn *conn,
436	unsigned char *buf,
437	itt_t init_task_tag,
438	u32 targ_xfer_tag,
439	u32 begrun,
440	u32 runlength)
441{
442	struct iscsit_cmd *cmd;
443
444	cmd = iscsit_find_cmd_from_itt(conn, init_task_tag);
445	if (!cmd)
446		return 0;
447
448	/*
449	 * FIXME: This will not work for bidi commands.
450	 */
451	switch (cmd->data_direction) {
452	case DMA_TO_DEVICE:
453		return iscsit_handle_r2t_snack(cmd, buf, begrun, runlength);
454	case DMA_FROM_DEVICE:
455		return iscsit_handle_recovery_datain(cmd, buf, begrun,
456				runlength);
457	default:
458		pr_err("Unknown cmd->data_direction: 0x%02x\n",
459				cmd->data_direction);
460		return -1;
461	}
462
463	return 0;
464}
465
466/* #warning FIXME: Status SNACK needs to be dependent on OPCODE!!! */
467int iscsit_handle_status_snack(
468	struct iscsit_conn *conn,
469	itt_t init_task_tag,
470	u32 targ_xfer_tag,
471	u32 begrun,
472	u32 runlength)
473{
474	struct iscsit_cmd *cmd = NULL;
475	u32 last_statsn;
476	int found_cmd;
477
478	if (!begrun) {
479		begrun = conn->exp_statsn;
480	} else if (conn->exp_statsn > begrun) {
481		pr_err("Got Status SNACK Begrun: 0x%08x, RunLength:"
482			" 0x%08x but already got ExpStatSN: 0x%08x on CID:"
483			" %hu.\n", begrun, runlength, conn->exp_statsn,
484			conn->cid);
485		return 0;
486	}
487
488	last_statsn = (!runlength) ? conn->stat_sn : (begrun + runlength);
489
490	while (begrun < last_statsn) {
491		found_cmd = 0;
492
493		spin_lock_bh(&conn->cmd_lock);
494		list_for_each_entry(cmd, &conn->conn_cmd_list, i_conn_node) {
495			if (cmd->stat_sn == begrun) {
496				found_cmd = 1;
497				break;
498			}
499		}
500		spin_unlock_bh(&conn->cmd_lock);
501
502		if (!found_cmd) {
503			pr_err("Unable to find StatSN: 0x%08x for"
504				" a Status SNACK, assuming this was a"
505				" protactic SNACK for an untransmitted"
506				" StatSN, ignoring.\n", begrun);
507			begrun++;
508			continue;
509		}
510
511		spin_lock_bh(&cmd->istate_lock);
512		if (cmd->i_state == ISTATE_SEND_DATAIN) {
513			spin_unlock_bh(&cmd->istate_lock);
514			pr_err("Ignoring Status SNACK for BegRun:"
515				" 0x%08x, RunLength: 0x%08x, assuming this was"
516				" a protactic SNACK for an untransmitted"
517				" StatSN\n", begrun, runlength);
518			begrun++;
519			continue;
520		}
521		spin_unlock_bh(&cmd->istate_lock);
522
523		cmd->i_state = ISTATE_SEND_STATUS_RECOVERY;
524		iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
525		begrun++;
526	}
527
528	return 0;
529}
530
531int iscsit_handle_data_ack(
532	struct iscsit_conn *conn,
533	u32 targ_xfer_tag,
534	u32 begrun,
535	u32 runlength)
536{
537	struct iscsit_cmd *cmd = NULL;
538
539	cmd = iscsit_find_cmd_from_ttt(conn, targ_xfer_tag);
540	if (!cmd) {
541		pr_err("Data ACK SNACK for TTT: 0x%08x is"
542			" invalid.\n", targ_xfer_tag);
543		return -1;
544	}
545
546	if (begrun <= cmd->acked_data_sn) {
547		pr_err("ITT: 0x%08x Data ACK SNACK BegRUN: 0x%08x is"
548			" less than the already acked DataSN: 0x%08x.\n",
549			cmd->init_task_tag, begrun, cmd->acked_data_sn);
550		return -1;
551	}
552
553	/*
554	 * For Data ACK SNACK, BegRun is the next expected DataSN.
555	 * (see iSCSI v19: 10.16.6)
556	 */
557	cmd->cmd_flags |= ICF_GOT_DATACK_SNACK;
558	cmd->acked_data_sn = (begrun - 1);
559
560	pr_debug("Received Data ACK SNACK for ITT: 0x%08x,"
561		" updated acked DataSN to 0x%08x.\n",
562			cmd->init_task_tag, cmd->acked_data_sn);
563
564	return 0;
565}
566
567static int iscsit_send_recovery_r2t(
568	struct iscsit_cmd *cmd,
569	u32 offset,
570	u32 xfer_len)
571{
572	int ret;
573
574	spin_lock_bh(&cmd->r2t_lock);
575	ret = iscsit_add_r2t_to_list(cmd, offset, xfer_len, 1, 0);
576	spin_unlock_bh(&cmd->r2t_lock);
577
578	return ret;
579}
580
581int iscsit_dataout_datapduinorder_no_fbit(
582	struct iscsit_cmd *cmd,
583	struct iscsi_pdu *pdu)
584{
585	int i, send_recovery_r2t = 0, recovery = 0;
586	u32 length = 0, offset = 0, pdu_count = 0;
587	struct iscsit_conn *conn = cmd->conn;
588	struct iscsi_pdu *first_pdu = NULL;
589
590	/*
591	 * Get an struct iscsi_pdu pointer to the first PDU, and total PDU count
592	 * of the DataOUT sequence.
593	 */
594	if (conn->sess->sess_ops->DataSequenceInOrder) {
595		for (i = 0; i < cmd->pdu_count; i++) {
596			if (cmd->pdu_list[i].seq_no == pdu->seq_no) {
597				if (!first_pdu)
598					first_pdu = &cmd->pdu_list[i];
599				pdu_count++;
600			} else if (pdu_count)
601				break;
602		}
603	} else {
604		struct iscsi_seq *seq = cmd->seq_ptr;
605
606		first_pdu = &cmd->pdu_list[seq->pdu_start];
607		pdu_count = seq->pdu_count;
608	}
609
610	if (!first_pdu || !pdu_count)
611		return DATAOUT_CANNOT_RECOVER;
612
613	/*
614	 * Loop through the ending DataOUT Sequence checking each struct iscsi_pdu.
615	 * The following ugly logic does batching of not received PDUs.
616	 */
617	for (i = 0; i < pdu_count; i++) {
618		if (first_pdu[i].status == ISCSI_PDU_RECEIVED_OK) {
619			if (!send_recovery_r2t)
620				continue;
621
622			if (iscsit_send_recovery_r2t(cmd, offset, length) < 0)
623				return DATAOUT_CANNOT_RECOVER;
624
625			send_recovery_r2t = length = offset = 0;
626			continue;
627		}
628		/*
629		 * Set recovery = 1 for any missing, CRC failed, or timed
630		 * out PDUs to let the DataOUT logic know that this sequence
631		 * has not been completed yet.
632		 *
633		 * Also, only send a Recovery R2T for ISCSI_PDU_NOT_RECEIVED.
634		 * We assume if the PDU either failed CRC or timed out
635		 * that a Recovery R2T has already been sent.
636		 */
637		recovery = 1;
638
639		if (first_pdu[i].status != ISCSI_PDU_NOT_RECEIVED)
640			continue;
641
642		if (!offset)
643			offset = first_pdu[i].offset;
644		length += first_pdu[i].length;
645
646		send_recovery_r2t = 1;
647	}
648
649	if (send_recovery_r2t)
650		if (iscsit_send_recovery_r2t(cmd, offset, length) < 0)
651			return DATAOUT_CANNOT_RECOVER;
652
653	return (!recovery) ? DATAOUT_NORMAL : DATAOUT_WITHIN_COMMAND_RECOVERY;
654}
655
656static int iscsit_recalculate_dataout_values(
657	struct iscsit_cmd *cmd,
658	u32 pdu_offset,
659	u32 pdu_length,
660	u32 *r2t_offset,
661	u32 *r2t_length)
662{
663	int i;
664	struct iscsit_conn *conn = cmd->conn;
665	struct iscsi_pdu *pdu = NULL;
666
667	if (conn->sess->sess_ops->DataSequenceInOrder) {
668		cmd->data_sn = 0;
669
670		if (conn->sess->sess_ops->DataPDUInOrder) {
671			*r2t_offset = cmd->write_data_done;
672			*r2t_length = (cmd->seq_end_offset -
673					cmd->write_data_done);
674			return 0;
675		}
676
677		*r2t_offset = cmd->seq_start_offset;
678		*r2t_length = (cmd->seq_end_offset - cmd->seq_start_offset);
679
680		for (i = 0; i < cmd->pdu_count; i++) {
681			pdu = &cmd->pdu_list[i];
682
683			if (pdu->status != ISCSI_PDU_RECEIVED_OK)
684				continue;
685
686			if ((pdu->offset >= cmd->seq_start_offset) &&
687			   ((pdu->offset + pdu->length) <=
688			     cmd->seq_end_offset)) {
689				if (!cmd->unsolicited_data)
690					cmd->next_burst_len -= pdu->length;
691				else
692					cmd->first_burst_len -= pdu->length;
693
694				cmd->write_data_done -= pdu->length;
695				pdu->status = ISCSI_PDU_NOT_RECEIVED;
696			}
697		}
698	} else {
699		struct iscsi_seq *seq = NULL;
700
701		seq = iscsit_get_seq_holder(cmd, pdu_offset, pdu_length);
702		if (!seq)
703			return -1;
704
705		*r2t_offset = seq->orig_offset;
706		*r2t_length = seq->xfer_len;
707
708		cmd->write_data_done -= (seq->offset - seq->orig_offset);
709		if (cmd->immediate_data)
710			cmd->first_burst_len = cmd->write_data_done;
711
712		seq->data_sn = 0;
713		seq->offset = seq->orig_offset;
714		seq->next_burst_len = 0;
715		seq->status = DATAOUT_SEQUENCE_WITHIN_COMMAND_RECOVERY;
716
717		if (conn->sess->sess_ops->DataPDUInOrder)
718			return 0;
719
720		for (i = 0; i < seq->pdu_count; i++) {
721			pdu = &cmd->pdu_list[i+seq->pdu_start];
722
723			if (pdu->status != ISCSI_PDU_RECEIVED_OK)
724				continue;
725
726			pdu->status = ISCSI_PDU_NOT_RECEIVED;
727		}
728	}
729
730	return 0;
731}
732
733int iscsit_recover_dataout_sequence(
734	struct iscsit_cmd *cmd,
735	u32 pdu_offset,
736	u32 pdu_length)
737{
738	u32 r2t_length = 0, r2t_offset = 0;
739
740	spin_lock_bh(&cmd->istate_lock);
741	cmd->cmd_flags |= ICF_WITHIN_COMMAND_RECOVERY;
742	spin_unlock_bh(&cmd->istate_lock);
743
744	if (iscsit_recalculate_dataout_values(cmd, pdu_offset, pdu_length,
745			&r2t_offset, &r2t_length) < 0)
746		return DATAOUT_CANNOT_RECOVER;
747
748	iscsit_send_recovery_r2t(cmd, r2t_offset, r2t_length);
749
750	return DATAOUT_WITHIN_COMMAND_RECOVERY;
751}
752
753static struct iscsi_ooo_cmdsn *iscsit_allocate_ooo_cmdsn(void)
754{
755	struct iscsi_ooo_cmdsn *ooo_cmdsn = NULL;
756
757	ooo_cmdsn = kmem_cache_zalloc(lio_ooo_cache, GFP_ATOMIC);
758	if (!ooo_cmdsn) {
759		pr_err("Unable to allocate memory for"
760			" struct iscsi_ooo_cmdsn.\n");
761		return NULL;
762	}
763	INIT_LIST_HEAD(&ooo_cmdsn->ooo_list);
764
765	return ooo_cmdsn;
766}
767
768static int iscsit_attach_ooo_cmdsn(
769	struct iscsit_session *sess,
770	struct iscsi_ooo_cmdsn *ooo_cmdsn)
771{
772	struct iscsi_ooo_cmdsn *ooo_tail, *ooo_tmp;
773
774	lockdep_assert_held(&sess->cmdsn_mutex);
775
776	/*
777	 * We attach the struct iscsi_ooo_cmdsn entry to the out of order
778	 * list in increasing CmdSN order.
779	 * This allows iscsi_execute_ooo_cmdsns() to detect any
780	 * additional CmdSN holes while performing delayed execution.
781	 */
782	if (list_empty(&sess->sess_ooo_cmdsn_list))
783		list_add_tail(&ooo_cmdsn->ooo_list,
784				&sess->sess_ooo_cmdsn_list);
785	else {
786		ooo_tail = list_entry(sess->sess_ooo_cmdsn_list.prev,
787				typeof(*ooo_tail), ooo_list);
788		/*
789		 * CmdSN is greater than the tail of the list.
790		 */
791		if (iscsi_sna_lt(ooo_tail->cmdsn, ooo_cmdsn->cmdsn))
792			list_add_tail(&ooo_cmdsn->ooo_list,
793					&sess->sess_ooo_cmdsn_list);
794		else {
795			/*
796			 * CmdSN is either lower than the head,  or somewhere
797			 * in the middle.
798			 */
799			list_for_each_entry(ooo_tmp, &sess->sess_ooo_cmdsn_list,
800						ooo_list) {
801				if (iscsi_sna_lt(ooo_tmp->cmdsn, ooo_cmdsn->cmdsn))
802					continue;
803
804				/* Insert before this entry */
805				list_add(&ooo_cmdsn->ooo_list,
806					ooo_tmp->ooo_list.prev);
807				break;
808			}
809		}
810	}
811
812	return 0;
813}
814
815/*
816 *	Removes an struct iscsi_ooo_cmdsn from a session's list,
817 *	called with struct iscsit_session->cmdsn_mutex held.
818 */
819void iscsit_remove_ooo_cmdsn(
820	struct iscsit_session *sess,
821	struct iscsi_ooo_cmdsn *ooo_cmdsn)
822{
823	list_del(&ooo_cmdsn->ooo_list);
824	kmem_cache_free(lio_ooo_cache, ooo_cmdsn);
825}
826
827void iscsit_clear_ooo_cmdsns_for_conn(struct iscsit_conn *conn)
828{
829	struct iscsi_ooo_cmdsn *ooo_cmdsn;
830	struct iscsit_session *sess = conn->sess;
831
832	mutex_lock(&sess->cmdsn_mutex);
833	list_for_each_entry(ooo_cmdsn, &sess->sess_ooo_cmdsn_list, ooo_list) {
834		if (ooo_cmdsn->cid != conn->cid)
835			continue;
836
837		ooo_cmdsn->cmd = NULL;
838	}
839	mutex_unlock(&sess->cmdsn_mutex);
840}
841
842int iscsit_execute_ooo_cmdsns(struct iscsit_session *sess)
843{
844	int ooo_count = 0;
845	struct iscsit_cmd *cmd = NULL;
846	struct iscsi_ooo_cmdsn *ooo_cmdsn, *ooo_cmdsn_tmp;
847
848	lockdep_assert_held(&sess->cmdsn_mutex);
849
850	list_for_each_entry_safe(ooo_cmdsn, ooo_cmdsn_tmp,
851				&sess->sess_ooo_cmdsn_list, ooo_list) {
852		if (ooo_cmdsn->cmdsn != sess->exp_cmd_sn)
853			continue;
854
855		if (!ooo_cmdsn->cmd) {
856			sess->exp_cmd_sn++;
857			iscsit_remove_ooo_cmdsn(sess, ooo_cmdsn);
858			continue;
859		}
860
861		cmd = ooo_cmdsn->cmd;
862		cmd->i_state = cmd->deferred_i_state;
863		ooo_count++;
864		sess->exp_cmd_sn++;
865		pr_debug("Executing out of order CmdSN: 0x%08x,"
866			" incremented ExpCmdSN to 0x%08x.\n",
867			cmd->cmd_sn, sess->exp_cmd_sn);
868
869		iscsit_remove_ooo_cmdsn(sess, ooo_cmdsn);
870
871		if (iscsit_execute_cmd(cmd, 1) < 0)
872			return -1;
873	}
874
875	return ooo_count;
876}
877
878/*
879 *	Called either:
880 *
881 *	1. With sess->cmdsn_mutex held from iscsi_execute_ooo_cmdsns()
882 *	or iscsi_check_received_cmdsn().
883 *	2. With no locks held directly from iscsi_handle_XXX_pdu() functions
884 *	for immediate commands.
885 */
886int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo)
887{
888	struct se_cmd *se_cmd = &cmd->se_cmd;
889	struct iscsit_conn *conn = cmd->conn;
890	int lr = 0;
891
892	spin_lock_bh(&cmd->istate_lock);
893	if (ooo)
894		cmd->cmd_flags &= ~ICF_OOO_CMDSN;
895
896	switch (cmd->iscsi_opcode) {
897	case ISCSI_OP_SCSI_CMD:
898		/*
899		 * Go ahead and send the CHECK_CONDITION status for
900		 * any SCSI CDB exceptions that may have occurred.
901		 */
902		if (cmd->sense_reason) {
903			if (cmd->sense_reason == TCM_RESERVATION_CONFLICT) {
904				cmd->i_state = ISTATE_SEND_STATUS;
905				spin_unlock_bh(&cmd->istate_lock);
906				iscsit_add_cmd_to_response_queue(cmd, cmd->conn,
907						cmd->i_state);
908				return 0;
909			}
910			spin_unlock_bh(&cmd->istate_lock);
911			if (cmd->se_cmd.transport_state & CMD_T_ABORTED)
912				return 0;
913			return transport_send_check_condition_and_sense(se_cmd,
914					cmd->sense_reason, 0);
915		}
916		/*
917		 * Special case for delayed CmdSN with Immediate
918		 * Data and/or Unsolicited Data Out attached.
919		 */
920		if (cmd->immediate_data) {
921			if (cmd->cmd_flags & ICF_GOT_LAST_DATAOUT) {
922				spin_unlock_bh(&cmd->istate_lock);
923				target_execute_cmd(&cmd->se_cmd);
924				return 0;
925			}
926			spin_unlock_bh(&cmd->istate_lock);
927
928			if (!(cmd->cmd_flags &
929					ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) {
930				if (cmd->se_cmd.transport_state & CMD_T_ABORTED)
931					return 0;
932
933				iscsit_set_dataout_sequence_values(cmd);
934				conn->conn_transport->iscsit_get_dataout(conn, cmd, false);
935			}
936			return 0;
937		}
938		/*
939		 * The default handler.
940		 */
941		spin_unlock_bh(&cmd->istate_lock);
942
943		if ((cmd->data_direction == DMA_TO_DEVICE) &&
944		    !(cmd->cmd_flags & ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) {
945			if (cmd->se_cmd.transport_state & CMD_T_ABORTED)
946				return 0;
947
948			iscsit_set_unsolicited_dataout(cmd);
949		}
950		return target_submit(&cmd->se_cmd);
951
952	case ISCSI_OP_NOOP_OUT:
953	case ISCSI_OP_TEXT:
954		spin_unlock_bh(&cmd->istate_lock);
955		iscsit_add_cmd_to_response_queue(cmd, cmd->conn, cmd->i_state);
956		break;
957	case ISCSI_OP_SCSI_TMFUNC:
958		if (cmd->se_cmd.se_tmr_req->response) {
959			spin_unlock_bh(&cmd->istate_lock);
960			iscsit_add_cmd_to_response_queue(cmd, cmd->conn,
961					cmd->i_state);
962			return 0;
963		}
964		spin_unlock_bh(&cmd->istate_lock);
965
966		return transport_generic_handle_tmr(&cmd->se_cmd);
967	case ISCSI_OP_LOGOUT:
968		spin_unlock_bh(&cmd->istate_lock);
969		switch (cmd->logout_reason) {
970		case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
971			lr = iscsit_logout_closesession(cmd, cmd->conn);
972			break;
973		case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
974			lr = iscsit_logout_closeconnection(cmd, cmd->conn);
975			break;
976		case ISCSI_LOGOUT_REASON_RECOVERY:
977			lr = iscsit_logout_removeconnforrecovery(cmd, cmd->conn);
978			break;
979		default:
980			pr_err("Unknown iSCSI Logout Request Code:"
981				" 0x%02x\n", cmd->logout_reason);
982			return -1;
983		}
984
985		return lr;
986	default:
987		spin_unlock_bh(&cmd->istate_lock);
988		pr_err("Cannot perform out of order execution for"
989		" unknown iSCSI Opcode: 0x%02x\n", cmd->iscsi_opcode);
990		return -1;
991	}
992
993	return 0;
994}
995
996void iscsit_free_all_ooo_cmdsns(struct iscsit_session *sess)
997{
998	struct iscsi_ooo_cmdsn *ooo_cmdsn, *ooo_cmdsn_tmp;
999
1000	mutex_lock(&sess->cmdsn_mutex);
1001	list_for_each_entry_safe(ooo_cmdsn, ooo_cmdsn_tmp,
1002			&sess->sess_ooo_cmdsn_list, ooo_list) {
1003
1004		list_del(&ooo_cmdsn->ooo_list);
1005		kmem_cache_free(lio_ooo_cache, ooo_cmdsn);
1006	}
1007	mutex_unlock(&sess->cmdsn_mutex);
1008}
1009
1010int iscsit_handle_ooo_cmdsn(
1011	struct iscsit_session *sess,
1012	struct iscsit_cmd *cmd,
1013	u32 cmdsn)
1014{
1015	int batch = 0;
1016	struct iscsi_ooo_cmdsn *ooo_cmdsn = NULL, *ooo_tail = NULL;
1017
1018	cmd->deferred_i_state		= cmd->i_state;
1019	cmd->i_state			= ISTATE_DEFERRED_CMD;
1020	cmd->cmd_flags			|= ICF_OOO_CMDSN;
1021
1022	if (list_empty(&sess->sess_ooo_cmdsn_list))
1023		batch = 1;
1024	else {
1025		ooo_tail = list_entry(sess->sess_ooo_cmdsn_list.prev,
1026				typeof(*ooo_tail), ooo_list);
1027		if (ooo_tail->cmdsn != (cmdsn - 1))
1028			batch = 1;
1029	}
1030
1031	ooo_cmdsn = iscsit_allocate_ooo_cmdsn();
1032	if (!ooo_cmdsn)
1033		return -ENOMEM;
1034
1035	ooo_cmdsn->cmd			= cmd;
1036	ooo_cmdsn->batch_count		= (batch) ?
1037					  (cmdsn - sess->exp_cmd_sn) : 1;
1038	ooo_cmdsn->cid			= cmd->conn->cid;
1039	ooo_cmdsn->exp_cmdsn		= sess->exp_cmd_sn;
1040	ooo_cmdsn->cmdsn		= cmdsn;
1041
1042	if (iscsit_attach_ooo_cmdsn(sess, ooo_cmdsn) < 0) {
1043		kmem_cache_free(lio_ooo_cache, ooo_cmdsn);
1044		return -ENOMEM;
1045	}
1046
1047	return 0;
1048}
1049
1050static int iscsit_set_dataout_timeout_values(
1051	struct iscsit_cmd *cmd,
1052	u32 *offset,
1053	u32 *length)
1054{
1055	struct iscsit_conn *conn = cmd->conn;
1056	struct iscsi_r2t *r2t;
1057
1058	if (cmd->unsolicited_data) {
1059		*offset = 0;
1060		*length = (conn->sess->sess_ops->FirstBurstLength >
1061			   cmd->se_cmd.data_length) ?
1062			   cmd->se_cmd.data_length :
1063			   conn->sess->sess_ops->FirstBurstLength;
1064		return 0;
1065	}
1066
1067	spin_lock_bh(&cmd->r2t_lock);
1068	if (list_empty(&cmd->cmd_r2t_list)) {
1069		pr_err("cmd->cmd_r2t_list is empty!\n");
1070		spin_unlock_bh(&cmd->r2t_lock);
1071		return -1;
1072	}
1073
1074	list_for_each_entry(r2t, &cmd->cmd_r2t_list, r2t_list) {
1075		if (r2t->sent_r2t && !r2t->recovery_r2t && !r2t->seq_complete) {
1076			*offset = r2t->offset;
1077			*length = r2t->xfer_len;
1078			spin_unlock_bh(&cmd->r2t_lock);
1079			return 0;
1080		}
1081	}
1082	spin_unlock_bh(&cmd->r2t_lock);
1083
1084	pr_err("Unable to locate any incomplete DataOUT"
1085		" sequences for ITT: 0x%08x.\n", cmd->init_task_tag);
1086
1087	return -1;
1088}
1089
1090/*
1091 *	NOTE: Called from interrupt (timer) context.
1092 */
1093void iscsit_handle_dataout_timeout(struct timer_list *t)
1094{
1095	u32 pdu_length = 0, pdu_offset = 0;
1096	u32 r2t_length = 0, r2t_offset = 0;
1097	struct iscsit_cmd *cmd = from_timer(cmd, t, dataout_timer);
1098	struct iscsit_conn *conn = cmd->conn;
1099	struct iscsit_session *sess = NULL;
1100	struct iscsi_node_attrib *na;
1101
1102	iscsit_inc_conn_usage_count(conn);
1103
1104	spin_lock_bh(&cmd->dataout_timeout_lock);
1105	if (cmd->dataout_timer_flags & ISCSI_TF_STOP) {
1106		spin_unlock_bh(&cmd->dataout_timeout_lock);
1107		iscsit_dec_conn_usage_count(conn);
1108		return;
1109	}
1110	cmd->dataout_timer_flags &= ~ISCSI_TF_RUNNING;
1111	sess = conn->sess;
1112	na = iscsit_tpg_get_node_attrib(sess);
1113
1114	if (!sess->sess_ops->ErrorRecoveryLevel) {
1115		pr_err("Unable to recover from DataOut timeout while"
1116			" in ERL=0, closing iSCSI connection for I_T Nexus"
1117			" %s,i,0x%6phN,%s,t,0x%02x\n",
1118			sess->sess_ops->InitiatorName, sess->isid,
1119			sess->tpg->tpg_tiqn->tiqn, (u32)sess->tpg->tpgt);
1120		goto failure;
1121	}
1122
1123	if (++cmd->dataout_timeout_retries == na->dataout_timeout_retries) {
1124		pr_err("Command ITT: 0x%08x exceeded max retries"
1125			" for DataOUT timeout %u, closing iSCSI connection for"
1126			" I_T Nexus %s,i,0x%6phN,%s,t,0x%02x\n",
1127			cmd->init_task_tag, na->dataout_timeout_retries,
1128			sess->sess_ops->InitiatorName, sess->isid,
1129			sess->tpg->tpg_tiqn->tiqn, (u32)sess->tpg->tpgt);
1130		goto failure;
1131	}
1132
1133	cmd->cmd_flags |= ICF_WITHIN_COMMAND_RECOVERY;
1134
1135	if (conn->sess->sess_ops->DataSequenceInOrder) {
1136		if (conn->sess->sess_ops->DataPDUInOrder) {
1137			pdu_offset = cmd->write_data_done;
1138			if ((pdu_offset + (conn->sess->sess_ops->MaxBurstLength -
1139			     cmd->next_burst_len)) > cmd->se_cmd.data_length)
1140				pdu_length = (cmd->se_cmd.data_length -
1141					cmd->write_data_done);
1142			else
1143				pdu_length = (conn->sess->sess_ops->MaxBurstLength -
1144						cmd->next_burst_len);
1145		} else {
1146			pdu_offset = cmd->seq_start_offset;
1147			pdu_length = (cmd->seq_end_offset -
1148				cmd->seq_start_offset);
1149		}
1150	} else {
1151		if (iscsit_set_dataout_timeout_values(cmd, &pdu_offset,
1152				&pdu_length) < 0)
1153			goto failure;
1154	}
1155
1156	if (iscsit_recalculate_dataout_values(cmd, pdu_offset, pdu_length,
1157			&r2t_offset, &r2t_length) < 0)
1158		goto failure;
1159
1160	pr_debug("Command ITT: 0x%08x timed out waiting for"
1161		" completion of %sDataOUT Sequence Offset: %u, Length: %u\n",
1162		cmd->init_task_tag, (cmd->unsolicited_data) ? "Unsolicited " :
1163		"", r2t_offset, r2t_length);
1164
1165	if (iscsit_send_recovery_r2t(cmd, r2t_offset, r2t_length) < 0)
1166		goto failure;
1167
1168	iscsit_start_dataout_timer(cmd, conn);
1169	spin_unlock_bh(&cmd->dataout_timeout_lock);
1170	iscsit_dec_conn_usage_count(conn);
1171
1172	return;
1173
1174failure:
1175	spin_unlock_bh(&cmd->dataout_timeout_lock);
1176	iscsit_fill_cxn_timeout_err_stats(sess);
1177	iscsit_cause_connection_reinstatement(conn, 0);
1178	iscsit_dec_conn_usage_count(conn);
1179}
1180
1181void iscsit_mod_dataout_timer(struct iscsit_cmd *cmd)
1182{
1183	struct iscsit_conn *conn = cmd->conn;
1184	struct iscsit_session *sess = conn->sess;
1185	struct iscsi_node_attrib *na = iscsit_tpg_get_node_attrib(sess);
1186
1187	spin_lock_bh(&cmd->dataout_timeout_lock);
1188	if (!(cmd->dataout_timer_flags & ISCSI_TF_RUNNING)) {
1189		spin_unlock_bh(&cmd->dataout_timeout_lock);
1190		return;
1191	}
1192
1193	mod_timer(&cmd->dataout_timer,
1194		(get_jiffies_64() + na->dataout_timeout * HZ));
1195	pr_debug("Updated DataOUT timer for ITT: 0x%08x",
1196			cmd->init_task_tag);
1197	spin_unlock_bh(&cmd->dataout_timeout_lock);
1198}
1199
1200void iscsit_start_dataout_timer(
1201	struct iscsit_cmd *cmd,
1202	struct iscsit_conn *conn)
1203{
1204	struct iscsit_session *sess = conn->sess;
1205	struct iscsi_node_attrib *na = iscsit_tpg_get_node_attrib(sess);
1206
1207	lockdep_assert_held(&cmd->dataout_timeout_lock);
1208
1209	if (cmd->dataout_timer_flags & ISCSI_TF_RUNNING)
1210		return;
1211
1212	pr_debug("Starting DataOUT timer for ITT: 0x%08x on"
1213		" CID: %hu.\n", cmd->init_task_tag, conn->cid);
1214
1215	cmd->dataout_timer_flags &= ~ISCSI_TF_STOP;
1216	cmd->dataout_timer_flags |= ISCSI_TF_RUNNING;
1217	mod_timer(&cmd->dataout_timer, jiffies + na->dataout_timeout * HZ);
1218}
1219
1220void iscsit_stop_dataout_timer(struct iscsit_cmd *cmd)
1221{
1222	spin_lock_bh(&cmd->dataout_timeout_lock);
1223	if (!(cmd->dataout_timer_flags & ISCSI_TF_RUNNING)) {
1224		spin_unlock_bh(&cmd->dataout_timeout_lock);
1225		return;
1226	}
1227	cmd->dataout_timer_flags |= ISCSI_TF_STOP;
1228	spin_unlock_bh(&cmd->dataout_timeout_lock);
1229
1230	del_timer_sync(&cmd->dataout_timer);
1231
1232	spin_lock_bh(&cmd->dataout_timeout_lock);
1233	cmd->dataout_timer_flags &= ~ISCSI_TF_RUNNING;
1234	pr_debug("Stopped DataOUT Timer for ITT: 0x%08x\n",
1235			cmd->init_task_tag);
1236	spin_unlock_bh(&cmd->dataout_timeout_lock);
1237}
1238EXPORT_SYMBOL(iscsit_stop_dataout_timer);
1239