xref: /openbmc/linux/drivers/scsi/libfc/fc_fcp.c (revision 69642c2a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright(c) 2007 Intel Corporation. All rights reserved.
4  * Copyright(c) 2008 Red Hat, Inc.  All rights reserved.
5  * Copyright(c) 2008 Mike Christie
6  *
7  * Maintained at www.Open-FCoE.org
8  */
9 
10 #include <linux/module.h>
11 #include <linux/delay.h>
12 #include <linux/kernel.h>
13 #include <linux/types.h>
14 #include <linux/spinlock.h>
15 #include <linux/scatterlist.h>
16 #include <linux/err.h>
17 #include <linux/crc32.h>
18 #include <linux/slab.h>
19 
20 #include <scsi/scsi_tcq.h>
21 #include <scsi/scsi.h>
22 #include <scsi/scsi_host.h>
23 #include <scsi/scsi_device.h>
24 #include <scsi/scsi_cmnd.h>
25 
26 #include <scsi/fc/fc_fc2.h>
27 
28 #include <scsi/libfc.h>
29 
30 #include "fc_encode.h"
31 #include "fc_libfc.h"
32 
33 static struct kmem_cache *scsi_pkt_cachep;
34 
35 /* SRB state definitions */
36 #define FC_SRB_FREE		0		/* cmd is free */
37 #define FC_SRB_CMD_SENT		(1 << 0)	/* cmd has been sent */
38 #define FC_SRB_RCV_STATUS	(1 << 1)	/* response has arrived */
39 #define FC_SRB_ABORT_PENDING	(1 << 2)	/* cmd abort sent to device */
40 #define FC_SRB_ABORTED		(1 << 3)	/* abort acknowledged */
41 #define FC_SRB_DISCONTIG	(1 << 4)	/* non-sequential data recvd */
42 #define FC_SRB_COMPL		(1 << 5)	/* fc_io_compl has been run */
43 #define FC_SRB_FCP_PROCESSING_TMO (1 << 6)	/* timer function processing */
44 
45 #define FC_SRB_READ		(1 << 1)
46 #define FC_SRB_WRITE		(1 << 0)
47 
48 static struct libfc_cmd_priv *libfc_priv(struct scsi_cmnd *cmd)
49 {
50 	return scsi_cmd_priv(cmd);
51 }
52 
53 /**
54  * struct fc_fcp_internal - FCP layer internal data
55  * @scsi_pkt_pool: Memory pool to draw FCP packets from
56  * @scsi_queue_lock: Protects the scsi_pkt_queue
57  * @scsi_pkt_queue: Current FCP packets
58  * @last_can_queue_ramp_down_time: ramp down time
59  * @last_can_queue_ramp_up_time: ramp up time
60  * @max_can_queue: max can_queue size
61  */
62 struct fc_fcp_internal {
63 	mempool_t		*scsi_pkt_pool;
64 	spinlock_t		scsi_queue_lock;
65 	struct list_head	scsi_pkt_queue;
66 	unsigned long		last_can_queue_ramp_down_time;
67 	unsigned long		last_can_queue_ramp_up_time;
68 	int			max_can_queue;
69 };
70 
71 #define fc_get_scsi_internal(x)	((struct fc_fcp_internal *)(x)->scsi_priv)
72 
73 /*
74  * function prototypes
75  * FC scsi I/O related functions
76  */
77 static void fc_fcp_recv_data(struct fc_fcp_pkt *, struct fc_frame *);
78 static void fc_fcp_recv(struct fc_seq *, struct fc_frame *, void *);
79 static void fc_fcp_resp(struct fc_fcp_pkt *, struct fc_frame *);
80 static void fc_fcp_complete_locked(struct fc_fcp_pkt *);
81 static void fc_tm_done(struct fc_seq *, struct fc_frame *, void *);
82 static void fc_fcp_error(struct fc_fcp_pkt *, struct fc_frame *);
83 static void fc_fcp_recovery(struct fc_fcp_pkt *, u8 code);
84 static void fc_fcp_timeout(struct timer_list *);
85 static void fc_fcp_rec(struct fc_fcp_pkt *);
86 static void fc_fcp_rec_error(struct fc_fcp_pkt *, struct fc_frame *);
87 static void fc_fcp_rec_resp(struct fc_seq *, struct fc_frame *, void *);
88 static void fc_io_compl(struct fc_fcp_pkt *);
89 
90 static void fc_fcp_srr(struct fc_fcp_pkt *, enum fc_rctl, u32);
91 static void fc_fcp_srr_resp(struct fc_seq *, struct fc_frame *, void *);
92 static void fc_fcp_srr_error(struct fc_fcp_pkt *, struct fc_frame *);
93 
94 /*
95  * command status codes
96  */
97 #define FC_COMPLETE		0
98 #define FC_CMD_ABORTED		1
99 #define FC_CMD_RESET		2
100 #define FC_CMD_PLOGO		3
101 #define FC_SNS_RCV		4
102 #define FC_TRANS_ERR		5
103 #define FC_DATA_OVRRUN		6
104 #define FC_DATA_UNDRUN		7
105 #define FC_ERROR		8
106 #define FC_HRD_ERROR		9
107 #define FC_CRC_ERROR		10
108 #define FC_TIMED_OUT		11
109 #define FC_TRANS_RESET		12
110 
111 /*
112  * Error recovery timeout values.
113  */
114 #define FC_SCSI_TM_TOV		(10 * HZ)
115 #define FC_HOST_RESET_TIMEOUT	(30 * HZ)
116 #define FC_CAN_QUEUE_PERIOD	(60 * HZ)
117 
118 #define FC_MAX_ERROR_CNT	5
119 #define FC_MAX_RECOV_RETRY	3
120 
121 #define FC_FCP_DFLT_QUEUE_DEPTH 32
122 
123 /**
124  * fc_fcp_pkt_alloc() - Allocate a fcp_pkt
125  * @lport: The local port that the FCP packet is for
126  * @gfp:   GFP flags for allocation
127  *
128  * Return value: fcp_pkt structure or null on allocation failure.
129  * Context:	 Can be called from process context, no lock is required.
130  */
131 static struct fc_fcp_pkt *fc_fcp_pkt_alloc(struct fc_lport *lport, gfp_t gfp)
132 {
133 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
134 	struct fc_fcp_pkt *fsp;
135 
136 	fsp = mempool_alloc(si->scsi_pkt_pool, gfp);
137 	if (fsp) {
138 		memset(fsp, 0, sizeof(*fsp));
139 		fsp->lp = lport;
140 		fsp->xfer_ddp = FC_XID_UNKNOWN;
141 		refcount_set(&fsp->ref_cnt, 1);
142 		timer_setup(&fsp->timer, NULL, 0);
143 		INIT_LIST_HEAD(&fsp->list);
144 		spin_lock_init(&fsp->scsi_pkt_lock);
145 	} else {
146 		per_cpu_ptr(lport->stats, get_cpu())->FcpPktAllocFails++;
147 		put_cpu();
148 	}
149 	return fsp;
150 }
151 
152 /**
153  * fc_fcp_pkt_release() - Release hold on a fcp_pkt
154  * @fsp: The FCP packet to be released
155  *
156  * Context: Can be called from process or interrupt context,
157  *	    no lock is required.
158  */
159 static void fc_fcp_pkt_release(struct fc_fcp_pkt *fsp)
160 {
161 	if (refcount_dec_and_test(&fsp->ref_cnt)) {
162 		struct fc_fcp_internal *si = fc_get_scsi_internal(fsp->lp);
163 
164 		mempool_free(fsp, si->scsi_pkt_pool);
165 	}
166 }
167 
168 /**
169  * fc_fcp_pkt_hold() - Hold a fcp_pkt
170  * @fsp: The FCP packet to be held
171  */
172 static void fc_fcp_pkt_hold(struct fc_fcp_pkt *fsp)
173 {
174 	refcount_inc(&fsp->ref_cnt);
175 }
176 
177 /**
178  * fc_fcp_pkt_destroy() - Release hold on a fcp_pkt
179  * @seq: The sequence that the FCP packet is on (required by destructor API)
180  * @fsp: The FCP packet to be released
181  *
182  * This routine is called by a destructor callback in the fc_exch_seq_send()
183  * routine of the libfc Transport Template. The 'struct fc_seq' is a required
184  * argument even though it is not used by this routine.
185  *
186  * Context: No locking required.
187  */
188 static void fc_fcp_pkt_destroy(struct fc_seq *seq, void *fsp)
189 {
190 	fc_fcp_pkt_release(fsp);
191 }
192 
193 /**
194  * fc_fcp_lock_pkt() - Lock a fcp_pkt and increase its reference count
195  * @fsp: The FCP packet to be locked and incremented
196  *
197  * We should only return error if we return a command to SCSI-ml before
198  * getting a response. This can happen in cases where we send a abort, but
199  * do not wait for the response and the abort and command can be passing
200  * each other on the wire/network-layer.
201  *
202  * Note: this function locks the packet and gets a reference to allow
203  * callers to call the completion function while the lock is held and
204  * not have to worry about the packets refcount.
205  *
206  * TODO: Maybe we should just have callers grab/release the lock and
207  * have a function that they call to verify the fsp and grab a ref if
208  * needed.
209  */
210 static inline int fc_fcp_lock_pkt(struct fc_fcp_pkt *fsp)
211 {
212 	spin_lock_bh(&fsp->scsi_pkt_lock);
213 	if (fsp->state & FC_SRB_COMPL) {
214 		spin_unlock_bh(&fsp->scsi_pkt_lock);
215 		return -EPERM;
216 	}
217 
218 	fc_fcp_pkt_hold(fsp);
219 	return 0;
220 }
221 
222 /**
223  * fc_fcp_unlock_pkt() - Release a fcp_pkt's lock and decrement its
224  *			 reference count
225  * @fsp: The FCP packet to be unlocked and decremented
226  */
227 static inline void fc_fcp_unlock_pkt(struct fc_fcp_pkt *fsp)
228 {
229 	spin_unlock_bh(&fsp->scsi_pkt_lock);
230 	fc_fcp_pkt_release(fsp);
231 }
232 
233 /**
234  * fc_fcp_timer_set() - Start a timer for a fcp_pkt
235  * @fsp:   The FCP packet to start a timer for
236  * @delay: The timeout period in jiffies
237  */
238 static void fc_fcp_timer_set(struct fc_fcp_pkt *fsp, unsigned long delay)
239 {
240 	if (!(fsp->state & FC_SRB_COMPL)) {
241 		mod_timer(&fsp->timer, jiffies + delay);
242 		fsp->timer_delay = delay;
243 	}
244 }
245 
246 static void fc_fcp_abort_done(struct fc_fcp_pkt *fsp)
247 {
248 	fsp->state |= FC_SRB_ABORTED;
249 	fsp->state &= ~FC_SRB_ABORT_PENDING;
250 
251 	if (fsp->wait_for_comp)
252 		complete(&fsp->tm_done);
253 	else
254 		fc_fcp_complete_locked(fsp);
255 }
256 
257 /**
258  * fc_fcp_send_abort() - Send an abort for exchanges associated with a
259  *			 fcp_pkt
260  * @fsp: The FCP packet to abort exchanges on
261  */
262 static int fc_fcp_send_abort(struct fc_fcp_pkt *fsp)
263 {
264 	int rc;
265 
266 	if (!fsp->seq_ptr)
267 		return -EINVAL;
268 
269 	per_cpu_ptr(fsp->lp->stats, get_cpu())->FcpPktAborts++;
270 	put_cpu();
271 
272 	fsp->state |= FC_SRB_ABORT_PENDING;
273 	rc = fc_seq_exch_abort(fsp->seq_ptr, 0);
274 	/*
275 	 * fc_seq_exch_abort() might return -ENXIO if
276 	 * the sequence is already completed
277 	 */
278 	if (rc == -ENXIO) {
279 		fc_fcp_abort_done(fsp);
280 		rc = 0;
281 	}
282 	return rc;
283 }
284 
285 /**
286  * fc_fcp_retry_cmd() - Retry a fcp_pkt
287  * @fsp: The FCP packet to be retried
288  * @status_code: The FCP status code to set
289  *
290  * Sets the status code to be FC_ERROR and then calls
291  * fc_fcp_complete_locked() which in turn calls fc_io_compl().
292  * fc_io_compl() will notify the SCSI-ml that the I/O is done.
293  * The SCSI-ml will retry the command.
294  */
295 static void fc_fcp_retry_cmd(struct fc_fcp_pkt *fsp, int status_code)
296 {
297 	if (fsp->seq_ptr) {
298 		fc_exch_done(fsp->seq_ptr);
299 		fsp->seq_ptr = NULL;
300 	}
301 
302 	fsp->state &= ~FC_SRB_ABORT_PENDING;
303 	fsp->io_status = 0;
304 	fsp->status_code = status_code;
305 	fc_fcp_complete_locked(fsp);
306 }
307 
308 /**
309  * fc_fcp_ddp_setup() - Calls a LLD's ddp_setup routine to set up DDP context
310  * @fsp: The FCP packet that will manage the DDP frames
311  * @xid: The XID that will be used for the DDP exchange
312  */
313 void fc_fcp_ddp_setup(struct fc_fcp_pkt *fsp, u16 xid)
314 {
315 	struct fc_lport *lport;
316 
317 	lport = fsp->lp;
318 	if ((fsp->req_flags & FC_SRB_READ) &&
319 	    (lport->lro_enabled) && (lport->tt.ddp_setup)) {
320 		if (lport->tt.ddp_setup(lport, xid, scsi_sglist(fsp->cmd),
321 					scsi_sg_count(fsp->cmd)))
322 			fsp->xfer_ddp = xid;
323 	}
324 }
325 
326 /**
327  * fc_fcp_ddp_done() - Calls a LLD's ddp_done routine to release any
328  *		       DDP related resources for a fcp_pkt
329  * @fsp: The FCP packet that DDP had been used on
330  */
331 void fc_fcp_ddp_done(struct fc_fcp_pkt *fsp)
332 {
333 	struct fc_lport *lport;
334 
335 	if (!fsp)
336 		return;
337 
338 	if (fsp->xfer_ddp == FC_XID_UNKNOWN)
339 		return;
340 
341 	lport = fsp->lp;
342 	if (lport->tt.ddp_done) {
343 		fsp->xfer_len = lport->tt.ddp_done(lport, fsp->xfer_ddp);
344 		fsp->xfer_ddp = FC_XID_UNKNOWN;
345 	}
346 }
347 
348 /**
349  * fc_fcp_can_queue_ramp_up() - increases can_queue
350  * @lport: lport to ramp up can_queue
351  */
352 static void fc_fcp_can_queue_ramp_up(struct fc_lport *lport)
353 {
354 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
355 	unsigned long flags;
356 	int can_queue;
357 
358 	spin_lock_irqsave(lport->host->host_lock, flags);
359 
360 	if (si->last_can_queue_ramp_up_time &&
361 	    (time_before(jiffies, si->last_can_queue_ramp_up_time +
362 			 FC_CAN_QUEUE_PERIOD)))
363 		goto unlock;
364 
365 	if (time_before(jiffies, si->last_can_queue_ramp_down_time +
366 			FC_CAN_QUEUE_PERIOD))
367 		goto unlock;
368 
369 	si->last_can_queue_ramp_up_time = jiffies;
370 
371 	can_queue = lport->host->can_queue << 1;
372 	if (can_queue >= si->max_can_queue) {
373 		can_queue = si->max_can_queue;
374 		si->last_can_queue_ramp_down_time = 0;
375 	}
376 	lport->host->can_queue = can_queue;
377 	shost_printk(KERN_ERR, lport->host, "libfc: increased "
378 		     "can_queue to %d.\n", can_queue);
379 
380 unlock:
381 	spin_unlock_irqrestore(lport->host->host_lock, flags);
382 }
383 
384 /**
385  * fc_fcp_can_queue_ramp_down() - reduces can_queue
386  * @lport: lport to reduce can_queue
387  *
388  * If we are getting memory allocation failures, then we may
389  * be trying to execute too many commands. We let the running
390  * commands complete or timeout, then try again with a reduced
391  * can_queue. Eventually we will hit the point where we run
392  * on all reserved structs.
393  */
394 static bool fc_fcp_can_queue_ramp_down(struct fc_lport *lport)
395 {
396 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
397 	unsigned long flags;
398 	int can_queue;
399 	bool changed = false;
400 
401 	spin_lock_irqsave(lport->host->host_lock, flags);
402 
403 	if (si->last_can_queue_ramp_down_time &&
404 	    (time_before(jiffies, si->last_can_queue_ramp_down_time +
405 			 FC_CAN_QUEUE_PERIOD)))
406 		goto unlock;
407 
408 	si->last_can_queue_ramp_down_time = jiffies;
409 
410 	can_queue = lport->host->can_queue;
411 	can_queue >>= 1;
412 	if (!can_queue)
413 		can_queue = 1;
414 	lport->host->can_queue = can_queue;
415 	changed = true;
416 
417 unlock:
418 	spin_unlock_irqrestore(lport->host->host_lock, flags);
419 	return changed;
420 }
421 
422 /*
423  * fc_fcp_frame_alloc() -  Allocates fc_frame structure and buffer.
424  * @lport:	fc lport struct
425  * @len:	payload length
426  *
427  * Allocates fc_frame structure and buffer but if fails to allocate
428  * then reduce can_queue.
429  */
430 static inline struct fc_frame *fc_fcp_frame_alloc(struct fc_lport *lport,
431 						  size_t len)
432 {
433 	struct fc_frame *fp;
434 
435 	fp = fc_frame_alloc(lport, len);
436 	if (likely(fp))
437 		return fp;
438 
439 	per_cpu_ptr(lport->stats, get_cpu())->FcpFrameAllocFails++;
440 	put_cpu();
441 	/* error case */
442 	fc_fcp_can_queue_ramp_down(lport);
443 	shost_printk(KERN_ERR, lport->host,
444 		     "libfc: Could not allocate frame, "
445 		     "reducing can_queue to %d.\n", lport->host->can_queue);
446 	return NULL;
447 }
448 
449 /**
450  * get_fsp_rec_tov() - Helper function to get REC_TOV
451  * @fsp: the FCP packet
452  *
453  * Returns rec tov in jiffies as rpriv->e_d_tov + 1 second
454  */
455 static inline unsigned int get_fsp_rec_tov(struct fc_fcp_pkt *fsp)
456 {
457 	struct fc_rport_libfc_priv *rpriv = fsp->rport->dd_data;
458 	unsigned int e_d_tov = FC_DEF_E_D_TOV;
459 
460 	if (rpriv && rpriv->e_d_tov > e_d_tov)
461 		e_d_tov = rpriv->e_d_tov;
462 	return msecs_to_jiffies(e_d_tov) + HZ;
463 }
464 
465 /**
466  * fc_fcp_recv_data() - Handler for receiving SCSI-FCP data from a target
467  * @fsp: The FCP packet the data is on
468  * @fp:	 The data frame
469  */
470 static void fc_fcp_recv_data(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
471 {
472 	struct scsi_cmnd *sc = fsp->cmd;
473 	struct fc_lport *lport = fsp->lp;
474 	struct fc_stats *stats;
475 	struct fc_frame_header *fh;
476 	size_t start_offset;
477 	size_t offset;
478 	u32 crc;
479 	u32 copy_len = 0;
480 	size_t len;
481 	void *buf;
482 	struct scatterlist *sg;
483 	u32 nents;
484 	u8 host_bcode = FC_COMPLETE;
485 
486 	fh = fc_frame_header_get(fp);
487 	offset = ntohl(fh->fh_parm_offset);
488 	start_offset = offset;
489 	len = fr_len(fp) - sizeof(*fh);
490 	buf = fc_frame_payload_get(fp, 0);
491 
492 	/*
493 	 * if this I/O is ddped then clear it and initiate recovery since data
494 	 * frames are expected to be placed directly in that case.
495 	 *
496 	 * Indicate error to scsi-ml because something went wrong with the
497 	 * ddp handling to get us here.
498 	 */
499 	if (fsp->xfer_ddp != FC_XID_UNKNOWN) {
500 		fc_fcp_ddp_done(fsp);
501 		FC_FCP_DBG(fsp, "DDP I/O in fc_fcp_recv_data set ERROR\n");
502 		host_bcode = FC_ERROR;
503 		goto err;
504 	}
505 	if (offset + len > fsp->data_len) {
506 		/* this should never happen */
507 		if ((fr_flags(fp) & FCPHF_CRC_UNCHECKED) &&
508 		    fc_frame_crc_check(fp))
509 			goto crc_err;
510 		FC_FCP_DBG(fsp, "data received past end. len %zx offset %zx "
511 			   "data_len %x\n", len, offset, fsp->data_len);
512 
513 		/* Data is corrupted indicate scsi-ml should retry */
514 		host_bcode = FC_DATA_OVRRUN;
515 		goto err;
516 	}
517 	if (offset != fsp->xfer_len)
518 		fsp->state |= FC_SRB_DISCONTIG;
519 
520 	sg = scsi_sglist(sc);
521 	nents = scsi_sg_count(sc);
522 
523 	if (!(fr_flags(fp) & FCPHF_CRC_UNCHECKED)) {
524 		copy_len = fc_copy_buffer_to_sglist(buf, len, sg, &nents,
525 						    &offset, NULL);
526 	} else {
527 		crc = crc32(~0, (u8 *) fh, sizeof(*fh));
528 		copy_len = fc_copy_buffer_to_sglist(buf, len, sg, &nents,
529 						    &offset, &crc);
530 		buf = fc_frame_payload_get(fp, 0);
531 		if (len % 4)
532 			crc = crc32(crc, buf + len, 4 - (len % 4));
533 
534 		if (~crc != le32_to_cpu(fr_crc(fp))) {
535 crc_err:
536 			stats = per_cpu_ptr(lport->stats, get_cpu());
537 			stats->ErrorFrames++;
538 			/* per cpu count, not total count, but OK for limit */
539 			if (stats->InvalidCRCCount++ < FC_MAX_ERROR_CNT)
540 				printk(KERN_WARNING "libfc: CRC error on data "
541 				       "frame for port (%6.6x)\n",
542 				       lport->port_id);
543 			put_cpu();
544 			/*
545 			 * Assume the frame is total garbage.
546 			 * We may have copied it over the good part
547 			 * of the buffer.
548 			 * If so, we need to retry the entire operation.
549 			 * Otherwise, ignore it.
550 			 */
551 			if (fsp->state & FC_SRB_DISCONTIG) {
552 				host_bcode = FC_CRC_ERROR;
553 				goto err;
554 			}
555 			return;
556 		}
557 	}
558 
559 	if (fsp->xfer_contig_end == start_offset)
560 		fsp->xfer_contig_end += copy_len;
561 	fsp->xfer_len += copy_len;
562 
563 	/*
564 	 * In the very rare event that this data arrived after the response
565 	 * and completes the transfer, call the completion handler.
566 	 */
567 	if (unlikely(fsp->state & FC_SRB_RCV_STATUS) &&
568 	    fsp->xfer_len == fsp->data_len - fsp->scsi_resid) {
569 		FC_FCP_DBG( fsp, "complete out-of-order sequence\n" );
570 		fc_fcp_complete_locked(fsp);
571 	}
572 	return;
573 err:
574 	fc_fcp_recovery(fsp, host_bcode);
575 }
576 
577 /**
578  * fc_fcp_send_data() - Send SCSI data to a target
579  * @fsp:      The FCP packet the data is on
580  * @seq:      The sequence the data is to be sent on
581  * @offset:   The starting offset for this data request
582  * @seq_blen: The burst length for this data request
583  *
584  * Called after receiving a Transfer Ready data descriptor.
585  * If the LLD is capable of sequence offload then send down the
586  * seq_blen amount of data in single frame, otherwise send
587  * multiple frames of the maximum frame payload supported by
588  * the target port.
589  */
590 static int fc_fcp_send_data(struct fc_fcp_pkt *fsp, struct fc_seq *seq,
591 			    size_t offset, size_t seq_blen)
592 {
593 	struct fc_exch *ep;
594 	struct scsi_cmnd *sc;
595 	struct scatterlist *sg;
596 	struct fc_frame *fp = NULL;
597 	struct fc_lport *lport = fsp->lp;
598 	struct page *page;
599 	size_t remaining;
600 	size_t t_blen;
601 	size_t tlen;
602 	size_t sg_bytes;
603 	size_t frame_offset, fh_parm_offset;
604 	size_t off;
605 	int error;
606 	void *data = NULL;
607 	void *page_addr;
608 	int using_sg = lport->sg_supp;
609 	u32 f_ctl;
610 
611 	WARN_ON(seq_blen <= 0);
612 	if (unlikely(offset + seq_blen > fsp->data_len)) {
613 		/* this should never happen */
614 		FC_FCP_DBG(fsp, "xfer-ready past end. seq_blen %zx "
615 			   "offset %zx\n", seq_blen, offset);
616 		fc_fcp_send_abort(fsp);
617 		return 0;
618 	} else if (offset != fsp->xfer_len) {
619 		/* Out of Order Data Request - no problem, but unexpected. */
620 		FC_FCP_DBG(fsp, "xfer-ready non-contiguous. "
621 			   "seq_blen %zx offset %zx\n", seq_blen, offset);
622 	}
623 
624 	/*
625 	 * if LLD is capable of seq_offload then set transport
626 	 * burst length (t_blen) to seq_blen, otherwise set t_blen
627 	 * to max FC frame payload previously set in fsp->max_payload.
628 	 */
629 	t_blen = fsp->max_payload;
630 	if (lport->seq_offload) {
631 		t_blen = min(seq_blen, (size_t)lport->lso_max);
632 		FC_FCP_DBG(fsp, "fsp=%p:lso:blen=%zx lso_max=0x%x t_blen=%zx\n",
633 			   fsp, seq_blen, lport->lso_max, t_blen);
634 	}
635 
636 	if (t_blen > 512)
637 		t_blen &= ~(512 - 1);	/* round down to block size */
638 	sc = fsp->cmd;
639 
640 	remaining = seq_blen;
641 	fh_parm_offset = frame_offset = offset;
642 	tlen = 0;
643 	seq = fc_seq_start_next(seq);
644 	f_ctl = FC_FC_REL_OFF;
645 	WARN_ON(!seq);
646 
647 	sg = scsi_sglist(sc);
648 
649 	while (remaining > 0 && sg) {
650 		if (offset >= sg->length) {
651 			offset -= sg->length;
652 			sg = sg_next(sg);
653 			continue;
654 		}
655 		if (!fp) {
656 			tlen = min(t_blen, remaining);
657 
658 			/*
659 			 * TODO.  Temporary workaround.	 fc_seq_send() can't
660 			 * handle odd lengths in non-linear skbs.
661 			 * This will be the final fragment only.
662 			 */
663 			if (tlen % 4)
664 				using_sg = 0;
665 			fp = fc_frame_alloc(lport, using_sg ? 0 : tlen);
666 			if (!fp)
667 				return -ENOMEM;
668 
669 			data = fc_frame_header_get(fp) + 1;
670 			fh_parm_offset = frame_offset;
671 			fr_max_payload(fp) = fsp->max_payload;
672 		}
673 
674 		off = offset + sg->offset;
675 		sg_bytes = min(tlen, sg->length - offset);
676 		sg_bytes = min(sg_bytes,
677 			       (size_t) (PAGE_SIZE - (off & ~PAGE_MASK)));
678 		page = sg_page(sg) + (off >> PAGE_SHIFT);
679 		if (using_sg) {
680 			get_page(page);
681 			skb_fill_page_desc(fp_skb(fp),
682 					   skb_shinfo(fp_skb(fp))->nr_frags,
683 					   page, off & ~PAGE_MASK, sg_bytes);
684 			fp_skb(fp)->data_len += sg_bytes;
685 			fr_len(fp) += sg_bytes;
686 			fp_skb(fp)->truesize += PAGE_SIZE;
687 		} else {
688 			/*
689 			 * The scatterlist item may be bigger than PAGE_SIZE,
690 			 * but we must not cross pages inside the kmap.
691 			 */
692 			page_addr = kmap_atomic(page);
693 			memcpy(data, (char *)page_addr + (off & ~PAGE_MASK),
694 			       sg_bytes);
695 			kunmap_atomic(page_addr);
696 			data += sg_bytes;
697 		}
698 		offset += sg_bytes;
699 		frame_offset += sg_bytes;
700 		tlen -= sg_bytes;
701 		remaining -= sg_bytes;
702 
703 		if ((skb_shinfo(fp_skb(fp))->nr_frags < FC_FRAME_SG_LEN) &&
704 		    (tlen))
705 			continue;
706 
707 		/*
708 		 * Send sequence with transfer sequence initiative in case
709 		 * this is last FCP frame of the sequence.
710 		 */
711 		if (remaining == 0)
712 			f_ctl |= FC_FC_SEQ_INIT | FC_FC_END_SEQ;
713 
714 		ep = fc_seq_exch(seq);
715 		fc_fill_fc_hdr(fp, FC_RCTL_DD_SOL_DATA, ep->did, ep->sid,
716 			       FC_TYPE_FCP, f_ctl, fh_parm_offset);
717 
718 		/*
719 		 * send fragment using for a sequence.
720 		 */
721 		error = fc_seq_send(lport, seq, fp);
722 		if (error) {
723 			WARN_ON(1);		/* send error should be rare */
724 			return error;
725 		}
726 		fp = NULL;
727 	}
728 	fsp->xfer_len += seq_blen;	/* premature count? */
729 	return 0;
730 }
731 
732 /**
733  * fc_fcp_abts_resp() - Receive an ABTS response
734  * @fsp: The FCP packet that is being aborted
735  * @fp:	 The response frame
736  */
737 static void fc_fcp_abts_resp(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
738 {
739 	int ba_done = 1;
740 	struct fc_ba_rjt *brp;
741 	struct fc_frame_header *fh;
742 
743 	fh = fc_frame_header_get(fp);
744 	switch (fh->fh_r_ctl) {
745 	case FC_RCTL_BA_ACC:
746 		break;
747 	case FC_RCTL_BA_RJT:
748 		brp = fc_frame_payload_get(fp, sizeof(*brp));
749 		if (brp && brp->br_reason == FC_BA_RJT_LOG_ERR)
750 			break;
751 		fallthrough;
752 	default:
753 		/*
754 		 * we will let the command timeout
755 		 * and scsi-ml recover in this case,
756 		 * therefore cleared the ba_done flag.
757 		 */
758 		ba_done = 0;
759 	}
760 
761 	if (ba_done)
762 		fc_fcp_abort_done(fsp);
763 }
764 
765 /**
766  * fc_fcp_recv() - Receive an FCP frame
767  * @seq: The sequence the frame is on
768  * @fp:	 The received frame
769  * @arg: The related FCP packet
770  *
771  * Context: Called from Soft IRQ context. Can not be called
772  *	    holding the FCP packet list lock.
773  */
774 static void fc_fcp_recv(struct fc_seq *seq, struct fc_frame *fp, void *arg)
775 {
776 	struct fc_fcp_pkt *fsp = (struct fc_fcp_pkt *)arg;
777 	struct fc_lport *lport = fsp->lp;
778 	struct fc_frame_header *fh;
779 	struct fcp_txrdy *dd;
780 	u8 r_ctl;
781 	int rc = 0;
782 
783 	if (IS_ERR(fp)) {
784 		fc_fcp_error(fsp, fp);
785 		return;
786 	}
787 
788 	fh = fc_frame_header_get(fp);
789 	r_ctl = fh->fh_r_ctl;
790 
791 	if (lport->state != LPORT_ST_READY) {
792 		FC_FCP_DBG(fsp, "lport state %d, ignoring r_ctl %x\n",
793 			   lport->state, r_ctl);
794 		goto out;
795 	}
796 	if (fc_fcp_lock_pkt(fsp))
797 		goto out;
798 
799 	if (fh->fh_type == FC_TYPE_BLS) {
800 		fc_fcp_abts_resp(fsp, fp);
801 		goto unlock;
802 	}
803 
804 	if (fsp->state & (FC_SRB_ABORTED | FC_SRB_ABORT_PENDING)) {
805 		FC_FCP_DBG(fsp, "command aborted, ignoring r_ctl %x\n", r_ctl);
806 		goto unlock;
807 	}
808 
809 	if (r_ctl == FC_RCTL_DD_DATA_DESC) {
810 		/*
811 		 * received XFER RDY from the target
812 		 * need to send data to the target
813 		 */
814 		WARN_ON(fr_flags(fp) & FCPHF_CRC_UNCHECKED);
815 		dd = fc_frame_payload_get(fp, sizeof(*dd));
816 		WARN_ON(!dd);
817 
818 		rc = fc_fcp_send_data(fsp, seq,
819 				      (size_t) ntohl(dd->ft_data_ro),
820 				      (size_t) ntohl(dd->ft_burst_len));
821 		if (!rc)
822 			seq->rec_data = fsp->xfer_len;
823 	} else if (r_ctl == FC_RCTL_DD_SOL_DATA) {
824 		/*
825 		 * received a DATA frame
826 		 * next we will copy the data to the system buffer
827 		 */
828 		WARN_ON(fr_len(fp) < sizeof(*fh));	/* len may be 0 */
829 		fc_fcp_recv_data(fsp, fp);
830 		seq->rec_data = fsp->xfer_contig_end;
831 	} else if (r_ctl == FC_RCTL_DD_CMD_STATUS) {
832 		WARN_ON(fr_flags(fp) & FCPHF_CRC_UNCHECKED);
833 
834 		fc_fcp_resp(fsp, fp);
835 	} else {
836 		FC_FCP_DBG(fsp, "unexpected frame.  r_ctl %x\n", r_ctl);
837 	}
838 unlock:
839 	fc_fcp_unlock_pkt(fsp);
840 out:
841 	fc_frame_free(fp);
842 }
843 
844 /**
845  * fc_fcp_resp() - Handler for FCP responses
846  * @fsp: The FCP packet the response is for
847  * @fp:	 The response frame
848  */
849 static void fc_fcp_resp(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
850 {
851 	struct fc_frame_header *fh;
852 	struct fcp_resp *fc_rp;
853 	struct fcp_resp_ext *rp_ex;
854 	struct fcp_resp_rsp_info *fc_rp_info;
855 	u32 plen;
856 	u32 expected_len;
857 	u32 respl = 0;
858 	u32 snsl = 0;
859 	u8 flags = 0;
860 
861 	plen = fr_len(fp);
862 	fh = (struct fc_frame_header *)fr_hdr(fp);
863 	if (unlikely(plen < sizeof(*fh) + sizeof(*fc_rp)))
864 		goto len_err;
865 	plen -= sizeof(*fh);
866 	fc_rp = (struct fcp_resp *)(fh + 1);
867 	fsp->cdb_status = fc_rp->fr_status;
868 	flags = fc_rp->fr_flags;
869 	fsp->scsi_comp_flags = flags;
870 	expected_len = fsp->data_len;
871 
872 	/* if ddp, update xfer len */
873 	fc_fcp_ddp_done(fsp);
874 
875 	if (unlikely((flags & ~FCP_CONF_REQ) || fc_rp->fr_status)) {
876 		rp_ex = (void *)(fc_rp + 1);
877 		if (flags & (FCP_RSP_LEN_VAL | FCP_SNS_LEN_VAL)) {
878 			if (plen < sizeof(*fc_rp) + sizeof(*rp_ex))
879 				goto len_err;
880 			fc_rp_info = (struct fcp_resp_rsp_info *)(rp_ex + 1);
881 			if (flags & FCP_RSP_LEN_VAL) {
882 				respl = ntohl(rp_ex->fr_rsp_len);
883 				if ((respl != FCP_RESP_RSP_INFO_LEN4) &&
884 				    (respl != FCP_RESP_RSP_INFO_LEN8))
885 					goto len_err;
886 				if (fsp->wait_for_comp) {
887 					/* Abuse cdb_status for rsp code */
888 					fsp->cdb_status = fc_rp_info->rsp_code;
889 					complete(&fsp->tm_done);
890 					/*
891 					 * tmfs will not have any scsi cmd so
892 					 * exit here
893 					 */
894 					return;
895 				}
896 			}
897 			if (flags & FCP_SNS_LEN_VAL) {
898 				snsl = ntohl(rp_ex->fr_sns_len);
899 				if (snsl > SCSI_SENSE_BUFFERSIZE)
900 					snsl = SCSI_SENSE_BUFFERSIZE;
901 				memcpy(fsp->cmd->sense_buffer,
902 				       (char *)fc_rp_info + respl, snsl);
903 			}
904 		}
905 		if (flags & (FCP_RESID_UNDER | FCP_RESID_OVER)) {
906 			if (plen < sizeof(*fc_rp) + sizeof(rp_ex->fr_resid))
907 				goto len_err;
908 			if (flags & FCP_RESID_UNDER) {
909 				fsp->scsi_resid = ntohl(rp_ex->fr_resid);
910 				/*
911 				 * The cmnd->underflow is the minimum number of
912 				 * bytes that must be transferred for this
913 				 * command.  Provided a sense condition is not
914 				 * present, make sure the actual amount
915 				 * transferred is at least the underflow value
916 				 * or fail.
917 				 */
918 				if (!(flags & FCP_SNS_LEN_VAL) &&
919 				    (fc_rp->fr_status == 0) &&
920 				    (scsi_bufflen(fsp->cmd) -
921 				     fsp->scsi_resid) < fsp->cmd->underflow)
922 					goto err;
923 				expected_len -= fsp->scsi_resid;
924 			} else {
925 				fsp->status_code = FC_ERROR;
926 			}
927 		}
928 	}
929 	fsp->state |= FC_SRB_RCV_STATUS;
930 
931 	/*
932 	 * Check for missing or extra data frames.
933 	 */
934 	if (unlikely(fsp->cdb_status == SAM_STAT_GOOD &&
935 		     fsp->xfer_len != expected_len)) {
936 		if (fsp->xfer_len < expected_len) {
937 			/*
938 			 * Some data may be queued locally,
939 			 * Wait a at least one jiffy to see if it is delivered.
940 			 * If this expires without data, we may do SRR.
941 			 */
942 			if (fsp->lp->qfull) {
943 				FC_FCP_DBG(fsp, "tgt %6.6x queue busy retry\n",
944 					   fsp->rport->port_id);
945 				return;
946 			}
947 			FC_FCP_DBG(fsp, "tgt %6.6x xfer len %zx data underrun "
948 				   "len %x, data len %x\n",
949 				   fsp->rport->port_id,
950 				   fsp->xfer_len, expected_len, fsp->data_len);
951 			fc_fcp_timer_set(fsp, get_fsp_rec_tov(fsp));
952 			return;
953 		}
954 		fsp->status_code = FC_DATA_OVRRUN;
955 		FC_FCP_DBG(fsp, "tgt %6.6x xfer len %zx greater than expected, "
956 			   "len %x, data len %x\n",
957 			   fsp->rport->port_id,
958 			   fsp->xfer_len, expected_len, fsp->data_len);
959 	}
960 	fc_fcp_complete_locked(fsp);
961 	return;
962 
963 len_err:
964 	FC_FCP_DBG(fsp, "short FCP response. flags 0x%x len %u respl %u "
965 		   "snsl %u\n", flags, fr_len(fp), respl, snsl);
966 err:
967 	fsp->status_code = FC_ERROR;
968 	fc_fcp_complete_locked(fsp);
969 }
970 
971 /**
972  * fc_fcp_complete_locked() - Complete processing of a fcp_pkt with the
973  *			      fcp_pkt lock held
974  * @fsp: The FCP packet to be completed
975  *
976  * This function may sleep if a timer is pending. The packet lock must be
977  * held, and the host lock must not be held.
978  */
979 static void fc_fcp_complete_locked(struct fc_fcp_pkt *fsp)
980 {
981 	struct fc_lport *lport = fsp->lp;
982 	struct fc_seq *seq;
983 	struct fc_exch *ep;
984 	u32 f_ctl;
985 
986 	if (fsp->state & FC_SRB_ABORT_PENDING)
987 		return;
988 
989 	if (fsp->state & FC_SRB_ABORTED) {
990 		if (!fsp->status_code)
991 			fsp->status_code = FC_CMD_ABORTED;
992 	} else {
993 		/*
994 		 * Test for transport underrun, independent of response
995 		 * underrun status.
996 		 */
997 		if (fsp->cdb_status == SAM_STAT_GOOD &&
998 		    fsp->xfer_len < fsp->data_len && !fsp->io_status &&
999 		    (!(fsp->scsi_comp_flags & FCP_RESID_UNDER) ||
1000 		     fsp->xfer_len < fsp->data_len - fsp->scsi_resid)) {
1001 			FC_FCP_DBG(fsp, "data underrun, xfer %zx data %x\n",
1002 				    fsp->xfer_len, fsp->data_len);
1003 			fsp->status_code = FC_DATA_UNDRUN;
1004 		}
1005 	}
1006 
1007 	seq = fsp->seq_ptr;
1008 	if (seq) {
1009 		fsp->seq_ptr = NULL;
1010 		if (unlikely(fsp->scsi_comp_flags & FCP_CONF_REQ)) {
1011 			struct fc_frame *conf_frame;
1012 			struct fc_seq *csp;
1013 
1014 			csp = fc_seq_start_next(seq);
1015 			conf_frame = fc_fcp_frame_alloc(fsp->lp, 0);
1016 			if (conf_frame) {
1017 				f_ctl = FC_FC_SEQ_INIT;
1018 				f_ctl |= FC_FC_LAST_SEQ | FC_FC_END_SEQ;
1019 				ep = fc_seq_exch(seq);
1020 				fc_fill_fc_hdr(conf_frame, FC_RCTL_DD_SOL_CTL,
1021 					       ep->did, ep->sid,
1022 					       FC_TYPE_FCP, f_ctl, 0);
1023 				fc_seq_send(lport, csp, conf_frame);
1024 			}
1025 		}
1026 		fc_exch_done(seq);
1027 	}
1028 	/*
1029 	 * Some resets driven by SCSI are not I/Os and do not have
1030 	 * SCSI commands associated with the requests. We should not
1031 	 * call I/O completion if we do not have a SCSI command.
1032 	 */
1033 	if (fsp->cmd)
1034 		fc_io_compl(fsp);
1035 }
1036 
1037 /**
1038  * fc_fcp_cleanup_cmd() - Cancel the active exchange on a fcp_pkt
1039  * @fsp:   The FCP packet whose exchanges should be canceled
1040  * @error: The reason for the cancellation
1041  */
1042 static void fc_fcp_cleanup_cmd(struct fc_fcp_pkt *fsp, int error)
1043 {
1044 	if (fsp->seq_ptr) {
1045 		fc_exch_done(fsp->seq_ptr);
1046 		fsp->seq_ptr = NULL;
1047 	}
1048 	fsp->status_code = error;
1049 }
1050 
1051 /**
1052  * fc_fcp_cleanup_each_cmd() - Cancel all exchanges on a local port
1053  * @lport: The local port whose exchanges should be canceled
1054  * @id:	   The target's ID
1055  * @lun:   The LUN
1056  * @error: The reason for cancellation
1057  *
1058  * If lun or id is -1, they are ignored.
1059  */
1060 static void fc_fcp_cleanup_each_cmd(struct fc_lport *lport, unsigned int id,
1061 				    unsigned int lun, int error)
1062 {
1063 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
1064 	struct fc_fcp_pkt *fsp;
1065 	struct scsi_cmnd *sc_cmd;
1066 	unsigned long flags;
1067 
1068 	spin_lock_irqsave(&si->scsi_queue_lock, flags);
1069 restart:
1070 	list_for_each_entry(fsp, &si->scsi_pkt_queue, list) {
1071 		sc_cmd = fsp->cmd;
1072 		if (id != -1 && scmd_id(sc_cmd) != id)
1073 			continue;
1074 
1075 		if (lun != -1 && sc_cmd->device->lun != lun)
1076 			continue;
1077 
1078 		fc_fcp_pkt_hold(fsp);
1079 		spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
1080 
1081 		spin_lock_bh(&fsp->scsi_pkt_lock);
1082 		if (!(fsp->state & FC_SRB_COMPL)) {
1083 			fsp->state |= FC_SRB_COMPL;
1084 			/*
1085 			 * TODO: dropping scsi_pkt_lock and then reacquiring
1086 			 * again around fc_fcp_cleanup_cmd() is required,
1087 			 * since fc_fcp_cleanup_cmd() calls into
1088 			 * fc_seq_set_resp() and that func preempts cpu using
1089 			 * schedule. May be schedule and related code should be
1090 			 * removed instead of unlocking here to avoid scheduling
1091 			 * while atomic bug.
1092 			 */
1093 			spin_unlock_bh(&fsp->scsi_pkt_lock);
1094 
1095 			fc_fcp_cleanup_cmd(fsp, error);
1096 
1097 			spin_lock_bh(&fsp->scsi_pkt_lock);
1098 			fc_io_compl(fsp);
1099 		}
1100 		spin_unlock_bh(&fsp->scsi_pkt_lock);
1101 
1102 		fc_fcp_pkt_release(fsp);
1103 		spin_lock_irqsave(&si->scsi_queue_lock, flags);
1104 		/*
1105 		 * while we dropped the lock multiple pkts could
1106 		 * have been released, so we have to start over.
1107 		 */
1108 		goto restart;
1109 	}
1110 	spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
1111 }
1112 
1113 /**
1114  * fc_fcp_abort_io() - Abort all FCP-SCSI exchanges on a local port
1115  * @lport: The local port whose exchanges are to be aborted
1116  */
1117 static void fc_fcp_abort_io(struct fc_lport *lport)
1118 {
1119 	fc_fcp_cleanup_each_cmd(lport, -1, -1, FC_HRD_ERROR);
1120 }
1121 
1122 /**
1123  * fc_fcp_pkt_send() - Send a fcp_pkt
1124  * @lport: The local port to send the FCP packet on
1125  * @fsp:   The FCP packet to send
1126  *
1127  * Return:  Zero for success and -1 for failure
1128  * Locks:   Called without locks held
1129  */
1130 static int fc_fcp_pkt_send(struct fc_lport *lport, struct fc_fcp_pkt *fsp)
1131 {
1132 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
1133 	unsigned long flags;
1134 	int rc;
1135 
1136 	libfc_priv(fsp->cmd)->fsp = fsp;
1137 	fsp->cdb_cmd.fc_dl = htonl(fsp->data_len);
1138 	fsp->cdb_cmd.fc_flags = fsp->req_flags & ~FCP_CFL_LEN_MASK;
1139 
1140 	int_to_scsilun(fsp->cmd->device->lun, &fsp->cdb_cmd.fc_lun);
1141 	memcpy(fsp->cdb_cmd.fc_cdb, fsp->cmd->cmnd, fsp->cmd->cmd_len);
1142 
1143 	spin_lock_irqsave(&si->scsi_queue_lock, flags);
1144 	list_add_tail(&fsp->list, &si->scsi_pkt_queue);
1145 	spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
1146 	rc = lport->tt.fcp_cmd_send(lport, fsp, fc_fcp_recv);
1147 	if (unlikely(rc)) {
1148 		spin_lock_irqsave(&si->scsi_queue_lock, flags);
1149 		libfc_priv(fsp->cmd)->fsp = NULL;
1150 		list_del(&fsp->list);
1151 		spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
1152 	}
1153 
1154 	return rc;
1155 }
1156 
1157 /**
1158  * fc_fcp_cmd_send() - Send a FCP command
1159  * @lport: The local port to send the command on
1160  * @fsp:   The FCP packet the command is on
1161  * @resp:  The handler for the response
1162  */
1163 static int fc_fcp_cmd_send(struct fc_lport *lport, struct fc_fcp_pkt *fsp,
1164 			   void (*resp)(struct fc_seq *,
1165 					struct fc_frame *fp,
1166 					void *arg))
1167 {
1168 	struct fc_frame *fp;
1169 	struct fc_seq *seq;
1170 	struct fc_rport *rport;
1171 	struct fc_rport_libfc_priv *rpriv;
1172 	const size_t len = sizeof(fsp->cdb_cmd);
1173 	int rc = 0;
1174 
1175 	if (fc_fcp_lock_pkt(fsp))
1176 		return 0;
1177 
1178 	fp = fc_fcp_frame_alloc(lport, sizeof(fsp->cdb_cmd));
1179 	if (!fp) {
1180 		rc = -1;
1181 		goto unlock;
1182 	}
1183 
1184 	memcpy(fc_frame_payload_get(fp, len), &fsp->cdb_cmd, len);
1185 	fr_fsp(fp) = fsp;
1186 	rport = fsp->rport;
1187 	fsp->max_payload = rport->maxframe_size;
1188 	rpriv = rport->dd_data;
1189 
1190 	fc_fill_fc_hdr(fp, FC_RCTL_DD_UNSOL_CMD, rport->port_id,
1191 		       rpriv->local_port->port_id, FC_TYPE_FCP,
1192 		       FC_FCTL_REQ, 0);
1193 
1194 	seq = fc_exch_seq_send(lport, fp, resp, fc_fcp_pkt_destroy, fsp, 0);
1195 	if (!seq) {
1196 		rc = -1;
1197 		goto unlock;
1198 	}
1199 	fsp->seq_ptr = seq;
1200 	fc_fcp_pkt_hold(fsp);	/* hold for fc_fcp_pkt_destroy */
1201 
1202 	fsp->timer.function = fc_fcp_timeout;
1203 	if (rpriv->flags & FC_RP_FLAGS_REC_SUPPORTED)
1204 		fc_fcp_timer_set(fsp, get_fsp_rec_tov(fsp));
1205 
1206 unlock:
1207 	fc_fcp_unlock_pkt(fsp);
1208 	return rc;
1209 }
1210 
1211 /**
1212  * fc_fcp_error() - Handler for FCP layer errors
1213  * @fsp: The FCP packet the error is on
1214  * @fp:	 The frame that has errored
1215  */
1216 static void fc_fcp_error(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
1217 {
1218 	int error = PTR_ERR(fp);
1219 
1220 	if (fc_fcp_lock_pkt(fsp))
1221 		return;
1222 
1223 	if (error == -FC_EX_CLOSED) {
1224 		fc_fcp_retry_cmd(fsp, FC_ERROR);
1225 		goto unlock;
1226 	}
1227 
1228 	/*
1229 	 * clear abort pending, because the lower layer
1230 	 * decided to force completion.
1231 	 */
1232 	fsp->state &= ~FC_SRB_ABORT_PENDING;
1233 	fsp->status_code = FC_CMD_PLOGO;
1234 	fc_fcp_complete_locked(fsp);
1235 unlock:
1236 	fc_fcp_unlock_pkt(fsp);
1237 }
1238 
1239 /**
1240  * fc_fcp_pkt_abort() - Abort a fcp_pkt
1241  * @fsp:   The FCP packet to abort on
1242  *
1243  * Called to send an abort and then wait for abort completion
1244  */
1245 static int fc_fcp_pkt_abort(struct fc_fcp_pkt *fsp)
1246 {
1247 	int rc = FAILED;
1248 	unsigned long ticks_left;
1249 
1250 	FC_FCP_DBG(fsp, "pkt abort state %x\n", fsp->state);
1251 	if (fc_fcp_send_abort(fsp)) {
1252 		FC_FCP_DBG(fsp, "failed to send abort\n");
1253 		return FAILED;
1254 	}
1255 
1256 	if (fsp->state & FC_SRB_ABORTED) {
1257 		FC_FCP_DBG(fsp, "target abort cmd  completed\n");
1258 		return SUCCESS;
1259 	}
1260 
1261 	init_completion(&fsp->tm_done);
1262 	fsp->wait_for_comp = 1;
1263 
1264 	spin_unlock_bh(&fsp->scsi_pkt_lock);
1265 	ticks_left = wait_for_completion_timeout(&fsp->tm_done,
1266 							FC_SCSI_TM_TOV);
1267 	spin_lock_bh(&fsp->scsi_pkt_lock);
1268 	fsp->wait_for_comp = 0;
1269 
1270 	if (!ticks_left) {
1271 		FC_FCP_DBG(fsp, "target abort cmd  failed\n");
1272 	} else if (fsp->state & FC_SRB_ABORTED) {
1273 		FC_FCP_DBG(fsp, "target abort cmd  passed\n");
1274 		rc = SUCCESS;
1275 		fc_fcp_complete_locked(fsp);
1276 	}
1277 
1278 	return rc;
1279 }
1280 
1281 /**
1282  * fc_lun_reset_send() - Send LUN reset command
1283  * @t: Timer context used to fetch the FSP packet
1284  */
1285 static void fc_lun_reset_send(struct timer_list *t)
1286 {
1287 	struct fc_fcp_pkt *fsp = from_timer(fsp, t, timer);
1288 	struct fc_lport *lport = fsp->lp;
1289 
1290 	if (lport->tt.fcp_cmd_send(lport, fsp, fc_tm_done)) {
1291 		if (fsp->recov_retry++ >= FC_MAX_RECOV_RETRY)
1292 			return;
1293 		if (fc_fcp_lock_pkt(fsp))
1294 			return;
1295 		fsp->timer.function = fc_lun_reset_send;
1296 		fc_fcp_timer_set(fsp, get_fsp_rec_tov(fsp));
1297 		fc_fcp_unlock_pkt(fsp);
1298 	}
1299 }
1300 
1301 /**
1302  * fc_lun_reset() - Send a LUN RESET command to a device
1303  *		    and wait for the reply
1304  * @lport: The local port to sent the command on
1305  * @fsp:   The FCP packet that identifies the LUN to be reset
1306  * @id:	   The SCSI command ID
1307  * @lun:   The LUN ID to be reset
1308  */
1309 static int fc_lun_reset(struct fc_lport *lport, struct fc_fcp_pkt *fsp,
1310 			unsigned int id, unsigned int lun)
1311 {
1312 	int rc;
1313 
1314 	fsp->cdb_cmd.fc_dl = htonl(fsp->data_len);
1315 	fsp->cdb_cmd.fc_tm_flags = FCP_TMF_LUN_RESET;
1316 	int_to_scsilun(lun, &fsp->cdb_cmd.fc_lun);
1317 
1318 	fsp->wait_for_comp = 1;
1319 	init_completion(&fsp->tm_done);
1320 
1321 	fc_lun_reset_send(&fsp->timer);
1322 
1323 	/*
1324 	 * wait for completion of reset
1325 	 * after that make sure all commands are terminated
1326 	 */
1327 	rc = wait_for_completion_timeout(&fsp->tm_done, FC_SCSI_TM_TOV);
1328 
1329 	spin_lock_bh(&fsp->scsi_pkt_lock);
1330 	fsp->state |= FC_SRB_COMPL;
1331 	spin_unlock_bh(&fsp->scsi_pkt_lock);
1332 
1333 	del_timer_sync(&fsp->timer);
1334 
1335 	spin_lock_bh(&fsp->scsi_pkt_lock);
1336 	if (fsp->seq_ptr) {
1337 		fc_exch_done(fsp->seq_ptr);
1338 		fsp->seq_ptr = NULL;
1339 	}
1340 	fsp->wait_for_comp = 0;
1341 	spin_unlock_bh(&fsp->scsi_pkt_lock);
1342 
1343 	if (!rc) {
1344 		FC_SCSI_DBG(lport, "lun reset failed\n");
1345 		return FAILED;
1346 	}
1347 
1348 	/* cdb_status holds the tmf's rsp code */
1349 	if (fsp->cdb_status != FCP_TMF_CMPL)
1350 		return FAILED;
1351 
1352 	FC_SCSI_DBG(lport, "lun reset to lun %u completed\n", lun);
1353 	fc_fcp_cleanup_each_cmd(lport, id, lun, FC_CMD_ABORTED);
1354 	return SUCCESS;
1355 }
1356 
1357 /**
1358  * fc_tm_done() - Task Management response handler
1359  * @seq: The sequence that the response is on
1360  * @fp:	 The response frame
1361  * @arg: The FCP packet the response is for
1362  */
1363 static void fc_tm_done(struct fc_seq *seq, struct fc_frame *fp, void *arg)
1364 {
1365 	struct fc_fcp_pkt *fsp = arg;
1366 	struct fc_frame_header *fh;
1367 
1368 	if (IS_ERR(fp)) {
1369 		/*
1370 		 * If there is an error just let it timeout or wait
1371 		 * for TMF to be aborted if it timedout.
1372 		 *
1373 		 * scsi-eh will escalate for when either happens.
1374 		 */
1375 		return;
1376 	}
1377 
1378 	if (fc_fcp_lock_pkt(fsp))
1379 		goto out;
1380 
1381 	/*
1382 	 * raced with eh timeout handler.
1383 	 */
1384 	if (!fsp->seq_ptr || !fsp->wait_for_comp)
1385 		goto out_unlock;
1386 
1387 	fh = fc_frame_header_get(fp);
1388 	if (fh->fh_type != FC_TYPE_BLS)
1389 		fc_fcp_resp(fsp, fp);
1390 	fsp->seq_ptr = NULL;
1391 	fc_exch_done(seq);
1392 out_unlock:
1393 	fc_fcp_unlock_pkt(fsp);
1394 out:
1395 	fc_frame_free(fp);
1396 }
1397 
1398 /**
1399  * fc_fcp_cleanup() - Cleanup all FCP exchanges on a local port
1400  * @lport: The local port to be cleaned up
1401  */
1402 static void fc_fcp_cleanup(struct fc_lport *lport)
1403 {
1404 	fc_fcp_cleanup_each_cmd(lport, -1, -1, FC_ERROR);
1405 }
1406 
1407 /**
1408  * fc_fcp_timeout() - Handler for fcp_pkt timeouts
1409  * @t: Timer context used to fetch the FSP packet
1410  *
1411  * If REC is supported then just issue it and return. The REC exchange will
1412  * complete or time out and recovery can continue at that point. Otherwise,
1413  * if the response has been received without all the data it has been
1414  * ER_TIMEOUT since the response was received. If the response has not been
1415  * received we see if data was received recently. If it has been then we
1416  * continue waiting, otherwise, we abort the command.
1417  */
1418 static void fc_fcp_timeout(struct timer_list *t)
1419 {
1420 	struct fc_fcp_pkt *fsp = from_timer(fsp, t, timer);
1421 	struct fc_rport *rport = fsp->rport;
1422 	struct fc_rport_libfc_priv *rpriv = rport->dd_data;
1423 
1424 	if (fc_fcp_lock_pkt(fsp))
1425 		return;
1426 
1427 	if (fsp->cdb_cmd.fc_tm_flags)
1428 		goto unlock;
1429 
1430 	if (fsp->lp->qfull) {
1431 		FC_FCP_DBG(fsp, "fcp timeout, resetting timer delay %d\n",
1432 			   fsp->timer_delay);
1433 		fsp->timer.function = fc_fcp_timeout;
1434 		fc_fcp_timer_set(fsp, fsp->timer_delay);
1435 		goto unlock;
1436 	}
1437 	FC_FCP_DBG(fsp, "fcp timeout, delay %d flags %x state %x\n",
1438 		   fsp->timer_delay, rpriv->flags, fsp->state);
1439 	fsp->state |= FC_SRB_FCP_PROCESSING_TMO;
1440 
1441 	if (rpriv->flags & FC_RP_FLAGS_REC_SUPPORTED)
1442 		fc_fcp_rec(fsp);
1443 	else if (fsp->state & FC_SRB_RCV_STATUS)
1444 		fc_fcp_complete_locked(fsp);
1445 	else
1446 		fc_fcp_recovery(fsp, FC_TIMED_OUT);
1447 	fsp->state &= ~FC_SRB_FCP_PROCESSING_TMO;
1448 unlock:
1449 	fc_fcp_unlock_pkt(fsp);
1450 }
1451 
1452 /**
1453  * fc_fcp_rec() - Send a REC ELS request
1454  * @fsp: The FCP packet to send the REC request on
1455  */
1456 static void fc_fcp_rec(struct fc_fcp_pkt *fsp)
1457 {
1458 	struct fc_lport *lport;
1459 	struct fc_frame *fp;
1460 	struct fc_rport *rport;
1461 	struct fc_rport_libfc_priv *rpriv;
1462 
1463 	lport = fsp->lp;
1464 	rport = fsp->rport;
1465 	rpriv = rport->dd_data;
1466 	if (!fsp->seq_ptr || rpriv->rp_state != RPORT_ST_READY) {
1467 		fsp->status_code = FC_HRD_ERROR;
1468 		fsp->io_status = 0;
1469 		fc_fcp_complete_locked(fsp);
1470 		return;
1471 	}
1472 
1473 	fp = fc_fcp_frame_alloc(lport, sizeof(struct fc_els_rec));
1474 	if (!fp)
1475 		goto retry;
1476 
1477 	fr_seq(fp) = fsp->seq_ptr;
1478 	fc_fill_fc_hdr(fp, FC_RCTL_ELS_REQ, rport->port_id,
1479 		       rpriv->local_port->port_id, FC_TYPE_ELS,
1480 		       FC_FCTL_REQ, 0);
1481 	if (lport->tt.elsct_send(lport, rport->port_id, fp, ELS_REC,
1482 				 fc_fcp_rec_resp, fsp,
1483 				 2 * lport->r_a_tov)) {
1484 		fc_fcp_pkt_hold(fsp);		/* hold while REC outstanding */
1485 		return;
1486 	}
1487 retry:
1488 	if (fsp->recov_retry++ < FC_MAX_RECOV_RETRY)
1489 		fc_fcp_timer_set(fsp, get_fsp_rec_tov(fsp));
1490 	else
1491 		fc_fcp_recovery(fsp, FC_TIMED_OUT);
1492 }
1493 
1494 /**
1495  * fc_fcp_rec_resp() - Handler for REC ELS responses
1496  * @seq: The sequence the response is on
1497  * @fp:	 The response frame
1498  * @arg: The FCP packet the response is on
1499  *
1500  * If the response is a reject then the scsi layer will handle
1501  * the timeout. If the response is a LS_ACC then if the I/O was not completed
1502  * set the timeout and return. If the I/O was completed then complete the
1503  * exchange and tell the SCSI layer.
1504  */
1505 static void fc_fcp_rec_resp(struct fc_seq *seq, struct fc_frame *fp, void *arg)
1506 {
1507 	struct fc_fcp_pkt *fsp = (struct fc_fcp_pkt *)arg;
1508 	struct fc_els_rec_acc *recp;
1509 	struct fc_els_ls_rjt *rjt;
1510 	u32 e_stat;
1511 	u8 opcode;
1512 	u32 offset;
1513 	enum dma_data_direction data_dir;
1514 	enum fc_rctl r_ctl;
1515 	struct fc_rport_libfc_priv *rpriv;
1516 
1517 	if (IS_ERR(fp)) {
1518 		fc_fcp_rec_error(fsp, fp);
1519 		return;
1520 	}
1521 
1522 	if (fc_fcp_lock_pkt(fsp))
1523 		goto out;
1524 
1525 	fsp->recov_retry = 0;
1526 	opcode = fc_frame_payload_op(fp);
1527 	if (opcode == ELS_LS_RJT) {
1528 		rjt = fc_frame_payload_get(fp, sizeof(*rjt));
1529 		switch (rjt->er_reason) {
1530 		default:
1531 			FC_FCP_DBG(fsp,
1532 				   "device %x invalid REC reject %d/%d\n",
1533 				   fsp->rport->port_id, rjt->er_reason,
1534 				   rjt->er_explan);
1535 			fallthrough;
1536 		case ELS_RJT_UNSUP:
1537 			FC_FCP_DBG(fsp, "device does not support REC\n");
1538 			rpriv = fsp->rport->dd_data;
1539 			/*
1540 			 * if we do not spport RECs or got some bogus
1541 			 * reason then resetup timer so we check for
1542 			 * making progress.
1543 			 */
1544 			rpriv->flags &= ~FC_RP_FLAGS_REC_SUPPORTED;
1545 			break;
1546 		case ELS_RJT_LOGIC:
1547 		case ELS_RJT_UNAB:
1548 			FC_FCP_DBG(fsp, "device %x REC reject %d/%d\n",
1549 				   fsp->rport->port_id, rjt->er_reason,
1550 				   rjt->er_explan);
1551 			/*
1552 			 * If response got lost or is stuck in the
1553 			 * queue somewhere we have no idea if and when
1554 			 * the response will be received. So quarantine
1555 			 * the xid and retry the command.
1556 			 */
1557 			if (rjt->er_explan == ELS_EXPL_OXID_RXID) {
1558 				struct fc_exch *ep = fc_seq_exch(fsp->seq_ptr);
1559 				ep->state |= FC_EX_QUARANTINE;
1560 				fsp->state |= FC_SRB_ABORTED;
1561 				fc_fcp_retry_cmd(fsp, FC_TRANS_RESET);
1562 				break;
1563 			}
1564 			fc_fcp_recovery(fsp, FC_TRANS_RESET);
1565 			break;
1566 		}
1567 	} else if (opcode == ELS_LS_ACC) {
1568 		if (fsp->state & FC_SRB_ABORTED)
1569 			goto unlock_out;
1570 
1571 		data_dir = fsp->cmd->sc_data_direction;
1572 		recp = fc_frame_payload_get(fp, sizeof(*recp));
1573 		offset = ntohl(recp->reca_fc4value);
1574 		e_stat = ntohl(recp->reca_e_stat);
1575 
1576 		if (e_stat & ESB_ST_COMPLETE) {
1577 
1578 			/*
1579 			 * The exchange is complete.
1580 			 *
1581 			 * For output, we must've lost the response.
1582 			 * For input, all data must've been sent.
1583 			 * We lost may have lost the response
1584 			 * (and a confirmation was requested) and maybe
1585 			 * some data.
1586 			 *
1587 			 * If all data received, send SRR
1588 			 * asking for response.	 If partial data received,
1589 			 * or gaps, SRR requests data at start of gap.
1590 			 * Recovery via SRR relies on in-order-delivery.
1591 			 */
1592 			if (data_dir == DMA_TO_DEVICE) {
1593 				r_ctl = FC_RCTL_DD_CMD_STATUS;
1594 			} else if (fsp->xfer_contig_end == offset) {
1595 				r_ctl = FC_RCTL_DD_CMD_STATUS;
1596 			} else {
1597 				offset = fsp->xfer_contig_end;
1598 				r_ctl = FC_RCTL_DD_SOL_DATA;
1599 			}
1600 			fc_fcp_srr(fsp, r_ctl, offset);
1601 		} else if (e_stat & ESB_ST_SEQ_INIT) {
1602 			/*
1603 			 * The remote port has the initiative, so just
1604 			 * keep waiting for it to complete.
1605 			 */
1606 			fc_fcp_timer_set(fsp,  get_fsp_rec_tov(fsp));
1607 		} else {
1608 
1609 			/*
1610 			 * The exchange is incomplete, we have seq. initiative.
1611 			 * Lost response with requested confirmation,
1612 			 * lost confirmation, lost transfer ready or
1613 			 * lost write data.
1614 			 *
1615 			 * For output, if not all data was received, ask
1616 			 * for transfer ready to be repeated.
1617 			 *
1618 			 * If we received or sent all the data, send SRR to
1619 			 * request response.
1620 			 *
1621 			 * If we lost a response, we may have lost some read
1622 			 * data as well.
1623 			 */
1624 			r_ctl = FC_RCTL_DD_SOL_DATA;
1625 			if (data_dir == DMA_TO_DEVICE) {
1626 				r_ctl = FC_RCTL_DD_CMD_STATUS;
1627 				if (offset < fsp->data_len)
1628 					r_ctl = FC_RCTL_DD_DATA_DESC;
1629 			} else if (offset == fsp->xfer_contig_end) {
1630 				r_ctl = FC_RCTL_DD_CMD_STATUS;
1631 			} else if (fsp->xfer_contig_end < offset) {
1632 				offset = fsp->xfer_contig_end;
1633 			}
1634 			fc_fcp_srr(fsp, r_ctl, offset);
1635 		}
1636 	}
1637 unlock_out:
1638 	fc_fcp_unlock_pkt(fsp);
1639 out:
1640 	fc_fcp_pkt_release(fsp);	/* drop hold for outstanding REC */
1641 	fc_frame_free(fp);
1642 }
1643 
1644 /**
1645  * fc_fcp_rec_error() - Handler for REC errors
1646  * @fsp: The FCP packet the error is on
1647  * @fp:	 The REC frame
1648  */
1649 static void fc_fcp_rec_error(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
1650 {
1651 	int error = PTR_ERR(fp);
1652 
1653 	if (fc_fcp_lock_pkt(fsp))
1654 		goto out;
1655 
1656 	switch (error) {
1657 	case -FC_EX_CLOSED:
1658 		FC_FCP_DBG(fsp, "REC %p fid %6.6x exchange closed\n",
1659 			   fsp, fsp->rport->port_id);
1660 		fc_fcp_retry_cmd(fsp, FC_ERROR);
1661 		break;
1662 
1663 	default:
1664 		FC_FCP_DBG(fsp, "REC %p fid %6.6x error unexpected error %d\n",
1665 			   fsp, fsp->rport->port_id, error);
1666 		fsp->status_code = FC_CMD_PLOGO;
1667 		fallthrough;
1668 
1669 	case -FC_EX_TIMEOUT:
1670 		/*
1671 		 * Assume REC or LS_ACC was lost.
1672 		 * The exchange manager will have aborted REC, so retry.
1673 		 */
1674 		FC_FCP_DBG(fsp, "REC %p fid %6.6x exchange timeout retry %d/%d\n",
1675 			   fsp, fsp->rport->port_id, fsp->recov_retry,
1676 			   FC_MAX_RECOV_RETRY);
1677 		if (fsp->recov_retry++ < FC_MAX_RECOV_RETRY)
1678 			fc_fcp_rec(fsp);
1679 		else
1680 			fc_fcp_recovery(fsp, FC_ERROR);
1681 		break;
1682 	}
1683 	fc_fcp_unlock_pkt(fsp);
1684 out:
1685 	fc_fcp_pkt_release(fsp);	/* drop hold for outstanding REC */
1686 }
1687 
1688 /**
1689  * fc_fcp_recovery() - Handler for fcp_pkt recovery
1690  * @fsp: The FCP pkt that needs to be aborted
1691  * @code: The FCP status code to set
1692  */
1693 static void fc_fcp_recovery(struct fc_fcp_pkt *fsp, u8 code)
1694 {
1695 	FC_FCP_DBG(fsp, "start recovery code %x\n", code);
1696 	fsp->status_code = code;
1697 	fsp->cdb_status = 0;
1698 	fsp->io_status = 0;
1699 	/*
1700 	 * if this fails then we let the scsi command timer fire and
1701 	 * scsi-ml escalate.
1702 	 */
1703 	fc_fcp_send_abort(fsp);
1704 }
1705 
1706 /**
1707  * fc_fcp_srr() - Send a SRR request (Sequence Retransmission Request)
1708  * @fsp:   The FCP packet the SRR is to be sent on
1709  * @r_ctl: The R_CTL field for the SRR request
1710  * @offset: The SRR relative offset
1711  * This is called after receiving status but insufficient data, or
1712  * when expecting status but the request has timed out.
1713  */
1714 static void fc_fcp_srr(struct fc_fcp_pkt *fsp, enum fc_rctl r_ctl, u32 offset)
1715 {
1716 	struct fc_lport *lport = fsp->lp;
1717 	struct fc_rport *rport;
1718 	struct fc_rport_libfc_priv *rpriv;
1719 	struct fc_exch *ep = fc_seq_exch(fsp->seq_ptr);
1720 	struct fc_seq *seq;
1721 	struct fcp_srr *srr;
1722 	struct fc_frame *fp;
1723 
1724 	rport = fsp->rport;
1725 	rpriv = rport->dd_data;
1726 
1727 	if (!(rpriv->flags & FC_RP_FLAGS_RETRY) ||
1728 	    rpriv->rp_state != RPORT_ST_READY)
1729 		goto retry;			/* shouldn't happen */
1730 	fp = fc_fcp_frame_alloc(lport, sizeof(*srr));
1731 	if (!fp)
1732 		goto retry;
1733 
1734 	srr = fc_frame_payload_get(fp, sizeof(*srr));
1735 	memset(srr, 0, sizeof(*srr));
1736 	srr->srr_op = ELS_SRR;
1737 	srr->srr_ox_id = htons(ep->oxid);
1738 	srr->srr_rx_id = htons(ep->rxid);
1739 	srr->srr_r_ctl = r_ctl;
1740 	srr->srr_rel_off = htonl(offset);
1741 
1742 	fc_fill_fc_hdr(fp, FC_RCTL_ELS4_REQ, rport->port_id,
1743 		       rpriv->local_port->port_id, FC_TYPE_FCP,
1744 		       FC_FCTL_REQ, 0);
1745 
1746 	seq = fc_exch_seq_send(lport, fp, fc_fcp_srr_resp,
1747 			       fc_fcp_pkt_destroy,
1748 			       fsp, get_fsp_rec_tov(fsp));
1749 	if (!seq)
1750 		goto retry;
1751 
1752 	fsp->recov_seq = seq;
1753 	fsp->xfer_len = offset;
1754 	fsp->xfer_contig_end = offset;
1755 	fsp->state &= ~FC_SRB_RCV_STATUS;
1756 	fc_fcp_pkt_hold(fsp);		/* hold for outstanding SRR */
1757 	return;
1758 retry:
1759 	fc_fcp_retry_cmd(fsp, FC_TRANS_RESET);
1760 }
1761 
1762 /**
1763  * fc_fcp_srr_resp() - Handler for SRR response
1764  * @seq: The sequence the SRR is on
1765  * @fp:	 The SRR frame
1766  * @arg: The FCP packet the SRR is on
1767  */
1768 static void fc_fcp_srr_resp(struct fc_seq *seq, struct fc_frame *fp, void *arg)
1769 {
1770 	struct fc_fcp_pkt *fsp = arg;
1771 	struct fc_frame_header *fh;
1772 
1773 	if (IS_ERR(fp)) {
1774 		fc_fcp_srr_error(fsp, fp);
1775 		return;
1776 	}
1777 
1778 	if (fc_fcp_lock_pkt(fsp))
1779 		goto out;
1780 
1781 	fh = fc_frame_header_get(fp);
1782 	/*
1783 	 * BUG? fc_fcp_srr_error calls fc_exch_done which would release
1784 	 * the ep. But if fc_fcp_srr_error had got -FC_EX_TIMEOUT,
1785 	 * then fc_exch_timeout would be sending an abort. The fc_exch_done
1786 	 * call by fc_fcp_srr_error would prevent fc_exch.c from seeing
1787 	 * an abort response though.
1788 	 */
1789 	if (fh->fh_type == FC_TYPE_BLS) {
1790 		fc_fcp_unlock_pkt(fsp);
1791 		return;
1792 	}
1793 
1794 	switch (fc_frame_payload_op(fp)) {
1795 	case ELS_LS_ACC:
1796 		fsp->recov_retry = 0;
1797 		fc_fcp_timer_set(fsp, get_fsp_rec_tov(fsp));
1798 		break;
1799 	case ELS_LS_RJT:
1800 	default:
1801 		fc_fcp_recovery(fsp, FC_ERROR);
1802 		break;
1803 	}
1804 	fc_fcp_unlock_pkt(fsp);
1805 out:
1806 	fc_exch_done(seq);
1807 	fc_frame_free(fp);
1808 }
1809 
1810 /**
1811  * fc_fcp_srr_error() - Handler for SRR errors
1812  * @fsp: The FCP packet that the SRR error is on
1813  * @fp:	 The SRR frame
1814  */
1815 static void fc_fcp_srr_error(struct fc_fcp_pkt *fsp, struct fc_frame *fp)
1816 {
1817 	if (fc_fcp_lock_pkt(fsp))
1818 		goto out;
1819 	switch (PTR_ERR(fp)) {
1820 	case -FC_EX_TIMEOUT:
1821 		FC_FCP_DBG(fsp, "SRR timeout, retries %d\n", fsp->recov_retry);
1822 		if (fsp->recov_retry++ < FC_MAX_RECOV_RETRY)
1823 			fc_fcp_rec(fsp);
1824 		else
1825 			fc_fcp_recovery(fsp, FC_TIMED_OUT);
1826 		break;
1827 	case -FC_EX_CLOSED:			/* e.g., link failure */
1828 		FC_FCP_DBG(fsp, "SRR error, exchange closed\n");
1829 		fallthrough;
1830 	default:
1831 		fc_fcp_retry_cmd(fsp, FC_ERROR);
1832 		break;
1833 	}
1834 	fc_fcp_unlock_pkt(fsp);
1835 out:
1836 	fc_exch_done(fsp->recov_seq);
1837 }
1838 
1839 /**
1840  * fc_fcp_lport_queue_ready() - Determine if the lport and it's queue is ready
1841  * @lport: The local port to be checked
1842  */
1843 static inline int fc_fcp_lport_queue_ready(struct fc_lport *lport)
1844 {
1845 	/* lock ? */
1846 	return (lport->state == LPORT_ST_READY) &&
1847 		lport->link_up && !lport->qfull;
1848 }
1849 
1850 /**
1851  * fc_queuecommand() - The queuecommand function of the SCSI template
1852  * @shost: The Scsi_Host that the command was issued to
1853  * @sc_cmd:   The scsi_cmnd to be executed
1854  *
1855  * This is the i/o strategy routine, called by the SCSI layer.
1856  */
1857 int fc_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *sc_cmd)
1858 {
1859 	struct fc_lport *lport = shost_priv(shost);
1860 	struct fc_rport *rport = starget_to_rport(scsi_target(sc_cmd->device));
1861 	struct fc_fcp_pkt *fsp;
1862 	int rval;
1863 	int rc = 0;
1864 	struct fc_stats *stats;
1865 
1866 	rval = fc_remote_port_chkready(rport);
1867 	if (rval) {
1868 		sc_cmd->result = rval;
1869 		scsi_done(sc_cmd);
1870 		return 0;
1871 	}
1872 
1873 	if (!*(struct fc_remote_port **)rport->dd_data) {
1874 		/*
1875 		 * rport is transitioning from blocked/deleted to
1876 		 * online
1877 		 */
1878 		sc_cmd->result = DID_IMM_RETRY << 16;
1879 		scsi_done(sc_cmd);
1880 		goto out;
1881 	}
1882 
1883 	if (!fc_fcp_lport_queue_ready(lport)) {
1884 		if (lport->qfull) {
1885 			if (fc_fcp_can_queue_ramp_down(lport))
1886 				shost_printk(KERN_ERR, lport->host,
1887 					     "libfc: queue full, "
1888 					     "reducing can_queue to %d.\n",
1889 					     lport->host->can_queue);
1890 		}
1891 		rc = SCSI_MLQUEUE_HOST_BUSY;
1892 		goto out;
1893 	}
1894 
1895 	fsp = fc_fcp_pkt_alloc(lport, GFP_ATOMIC);
1896 	if (fsp == NULL) {
1897 		rc = SCSI_MLQUEUE_HOST_BUSY;
1898 		goto out;
1899 	}
1900 
1901 	/*
1902 	 * build the libfc request pkt
1903 	 */
1904 	fsp->cmd = sc_cmd;	/* save the cmd */
1905 	fsp->rport = rport;	/* set the remote port ptr */
1906 
1907 	/*
1908 	 * set up the transfer length
1909 	 */
1910 	fsp->data_len = scsi_bufflen(sc_cmd);
1911 	fsp->xfer_len = 0;
1912 
1913 	/*
1914 	 * setup the data direction
1915 	 */
1916 	stats = per_cpu_ptr(lport->stats, get_cpu());
1917 	if (sc_cmd->sc_data_direction == DMA_FROM_DEVICE) {
1918 		fsp->req_flags = FC_SRB_READ;
1919 		stats->InputRequests++;
1920 		stats->InputBytes += fsp->data_len;
1921 	} else if (sc_cmd->sc_data_direction == DMA_TO_DEVICE) {
1922 		fsp->req_flags = FC_SRB_WRITE;
1923 		stats->OutputRequests++;
1924 		stats->OutputBytes += fsp->data_len;
1925 	} else {
1926 		fsp->req_flags = 0;
1927 		stats->ControlRequests++;
1928 	}
1929 	put_cpu();
1930 
1931 	/*
1932 	 * send it to the lower layer
1933 	 * if we get -1 return then put the request in the pending
1934 	 * queue.
1935 	 */
1936 	rval = fc_fcp_pkt_send(lport, fsp);
1937 	if (rval != 0) {
1938 		fsp->state = FC_SRB_FREE;
1939 		fc_fcp_pkt_release(fsp);
1940 		rc = SCSI_MLQUEUE_HOST_BUSY;
1941 	}
1942 out:
1943 	return rc;
1944 }
1945 EXPORT_SYMBOL(fc_queuecommand);
1946 
1947 /**
1948  * fc_io_compl() - Handle responses for completed commands
1949  * @fsp: The FCP packet that is complete
1950  *
1951  * Translates fcp_pkt errors to a Linux SCSI errors.
1952  * The fcp packet lock must be held when calling.
1953  */
1954 static void fc_io_compl(struct fc_fcp_pkt *fsp)
1955 {
1956 	struct fc_fcp_internal *si;
1957 	struct scsi_cmnd *sc_cmd;
1958 	struct fc_lport *lport;
1959 	unsigned long flags;
1960 
1961 	/* release outstanding ddp context */
1962 	fc_fcp_ddp_done(fsp);
1963 
1964 	fsp->state |= FC_SRB_COMPL;
1965 	if (!(fsp->state & FC_SRB_FCP_PROCESSING_TMO)) {
1966 		spin_unlock_bh(&fsp->scsi_pkt_lock);
1967 		del_timer_sync(&fsp->timer);
1968 		spin_lock_bh(&fsp->scsi_pkt_lock);
1969 	}
1970 
1971 	lport = fsp->lp;
1972 	si = fc_get_scsi_internal(lport);
1973 
1974 	/*
1975 	 * if can_queue ramp down is done then try can_queue ramp up
1976 	 * since commands are completing now.
1977 	 */
1978 	if (si->last_can_queue_ramp_down_time)
1979 		fc_fcp_can_queue_ramp_up(lport);
1980 
1981 	sc_cmd = fsp->cmd;
1982 	libfc_priv(sc_cmd)->status = fsp->cdb_status;
1983 	switch (fsp->status_code) {
1984 	case FC_COMPLETE:
1985 		if (fsp->cdb_status == 0) {
1986 			/*
1987 			 * good I/O status
1988 			 */
1989 			sc_cmd->result = DID_OK << 16;
1990 			if (fsp->scsi_resid)
1991 				libfc_priv(sc_cmd)->resid_len = fsp->scsi_resid;
1992 		} else {
1993 			/*
1994 			 * transport level I/O was ok but scsi
1995 			 * has non zero status
1996 			 */
1997 			sc_cmd->result = (DID_OK << 16) | fsp->cdb_status;
1998 		}
1999 		break;
2000 	case FC_ERROR:
2001 		FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml "
2002 			   "due to FC_ERROR\n");
2003 		sc_cmd->result = DID_ERROR << 16;
2004 		break;
2005 	case FC_DATA_UNDRUN:
2006 		if ((fsp->cdb_status == 0) && !(fsp->req_flags & FC_SRB_READ)) {
2007 			/*
2008 			 * scsi status is good but transport level
2009 			 * underrun.
2010 			 */
2011 			if (fsp->state & FC_SRB_RCV_STATUS) {
2012 				sc_cmd->result = DID_OK << 16;
2013 			} else {
2014 				FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml"
2015 					   " due to FC_DATA_UNDRUN (trans)\n");
2016 				sc_cmd->result = DID_ERROR << 16;
2017 			}
2018 		} else {
2019 			/*
2020 			 * scsi got underrun, this is an error
2021 			 */
2022 			FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml "
2023 				   "due to FC_DATA_UNDRUN (scsi)\n");
2024 			libfc_priv(sc_cmd)->resid_len = fsp->scsi_resid;
2025 			sc_cmd->result = (DID_ERROR << 16) | fsp->cdb_status;
2026 		}
2027 		break;
2028 	case FC_DATA_OVRRUN:
2029 		/*
2030 		 * overrun is an error
2031 		 */
2032 		FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml "
2033 			   "due to FC_DATA_OVRRUN\n");
2034 		sc_cmd->result = (DID_ERROR << 16) | fsp->cdb_status;
2035 		break;
2036 	case FC_CMD_ABORTED:
2037 		if (host_byte(sc_cmd->result) == DID_TIME_OUT)
2038 			FC_FCP_DBG(fsp, "Returning DID_TIME_OUT to scsi-ml "
2039 				   "due to FC_CMD_ABORTED\n");
2040 		else {
2041 			FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml "
2042 				   "due to FC_CMD_ABORTED\n");
2043 			set_host_byte(sc_cmd, DID_ERROR);
2044 		}
2045 		sc_cmd->result |= fsp->io_status;
2046 		break;
2047 	case FC_CMD_RESET:
2048 		FC_FCP_DBG(fsp, "Returning DID_RESET to scsi-ml "
2049 			   "due to FC_CMD_RESET\n");
2050 		sc_cmd->result = (DID_RESET << 16);
2051 		break;
2052 	case FC_TRANS_RESET:
2053 		FC_FCP_DBG(fsp, "Returning DID_SOFT_ERROR to scsi-ml "
2054 			   "due to FC_TRANS_RESET\n");
2055 		sc_cmd->result = (DID_SOFT_ERROR << 16);
2056 		break;
2057 	case FC_HRD_ERROR:
2058 		FC_FCP_DBG(fsp, "Returning DID_NO_CONNECT to scsi-ml "
2059 			   "due to FC_HRD_ERROR\n");
2060 		sc_cmd->result = (DID_NO_CONNECT << 16);
2061 		break;
2062 	case FC_CRC_ERROR:
2063 		FC_FCP_DBG(fsp, "Returning DID_PARITY to scsi-ml "
2064 			   "due to FC_CRC_ERROR\n");
2065 		sc_cmd->result = (DID_PARITY << 16);
2066 		break;
2067 	case FC_TIMED_OUT:
2068 		FC_FCP_DBG(fsp, "Returning DID_BUS_BUSY to scsi-ml "
2069 			   "due to FC_TIMED_OUT\n");
2070 		sc_cmd->result = (DID_BUS_BUSY << 16) | fsp->io_status;
2071 		break;
2072 	default:
2073 		FC_FCP_DBG(fsp, "Returning DID_ERROR to scsi-ml "
2074 			   "due to unknown error\n");
2075 		sc_cmd->result = (DID_ERROR << 16);
2076 		break;
2077 	}
2078 
2079 	if (lport->state != LPORT_ST_READY && fsp->status_code != FC_COMPLETE)
2080 		sc_cmd->result = (DID_TRANSPORT_DISRUPTED << 16);
2081 
2082 	spin_lock_irqsave(&si->scsi_queue_lock, flags);
2083 	list_del(&fsp->list);
2084 	libfc_priv(sc_cmd)->fsp = NULL;
2085 	spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
2086 	scsi_done(sc_cmd);
2087 
2088 	/* release ref from initial allocation in queue command */
2089 	fc_fcp_pkt_release(fsp);
2090 }
2091 
2092 /**
2093  * fc_eh_abort() - Abort a command
2094  * @sc_cmd: The SCSI command to abort
2095  *
2096  * From SCSI host template.
2097  * Send an ABTS to the target device and wait for the response.
2098  */
2099 int fc_eh_abort(struct scsi_cmnd *sc_cmd)
2100 {
2101 	struct fc_fcp_pkt *fsp;
2102 	struct fc_lport *lport;
2103 	struct fc_fcp_internal *si;
2104 	int rc = FAILED;
2105 	unsigned long flags;
2106 	int rval;
2107 
2108 	rval = fc_block_scsi_eh(sc_cmd);
2109 	if (rval)
2110 		return rval;
2111 
2112 	lport = shost_priv(sc_cmd->device->host);
2113 	if (lport->state != LPORT_ST_READY)
2114 		return rc;
2115 	else if (!lport->link_up)
2116 		return rc;
2117 
2118 	si = fc_get_scsi_internal(lport);
2119 	spin_lock_irqsave(&si->scsi_queue_lock, flags);
2120 	fsp = libfc_priv(sc_cmd)->fsp;
2121 	if (!fsp) {
2122 		/* command completed while scsi eh was setting up */
2123 		spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
2124 		return SUCCESS;
2125 	}
2126 	/* grab a ref so the fsp and sc_cmd cannot be released from under us */
2127 	fc_fcp_pkt_hold(fsp);
2128 	spin_unlock_irqrestore(&si->scsi_queue_lock, flags);
2129 
2130 	if (fc_fcp_lock_pkt(fsp)) {
2131 		/* completed while we were waiting for timer to be deleted */
2132 		rc = SUCCESS;
2133 		goto release_pkt;
2134 	}
2135 
2136 	rc = fc_fcp_pkt_abort(fsp);
2137 	fc_fcp_unlock_pkt(fsp);
2138 
2139 release_pkt:
2140 	fc_fcp_pkt_release(fsp);
2141 	return rc;
2142 }
2143 EXPORT_SYMBOL(fc_eh_abort);
2144 
2145 /**
2146  * fc_eh_device_reset() - Reset a single LUN
2147  * @sc_cmd: The SCSI command which identifies the device whose
2148  *	    LUN is to be reset
2149  *
2150  * Set from SCSI host template.
2151  */
2152 int fc_eh_device_reset(struct scsi_cmnd *sc_cmd)
2153 {
2154 	struct fc_lport *lport;
2155 	struct fc_fcp_pkt *fsp;
2156 	struct fc_rport *rport = starget_to_rport(scsi_target(sc_cmd->device));
2157 	int rc = FAILED;
2158 	int rval;
2159 
2160 	rval = fc_block_scsi_eh(sc_cmd);
2161 	if (rval)
2162 		return rval;
2163 
2164 	lport = shost_priv(sc_cmd->device->host);
2165 
2166 	if (lport->state != LPORT_ST_READY)
2167 		return rc;
2168 
2169 	FC_SCSI_DBG(lport, "Resetting rport (%6.6x)\n", rport->port_id);
2170 
2171 	fsp = fc_fcp_pkt_alloc(lport, GFP_NOIO);
2172 	if (fsp == NULL) {
2173 		printk(KERN_WARNING "libfc: could not allocate scsi_pkt\n");
2174 		goto out;
2175 	}
2176 
2177 	/*
2178 	 * Build the libfc request pkt. Do not set the scsi cmnd, because
2179 	 * the sc passed in is not setup for execution like when sent
2180 	 * through the queuecommand callout.
2181 	 */
2182 	fsp->rport = rport;	/* set the remote port ptr */
2183 
2184 	/*
2185 	 * flush outstanding commands
2186 	 */
2187 	rc = fc_lun_reset(lport, fsp, scmd_id(sc_cmd), sc_cmd->device->lun);
2188 	fsp->state = FC_SRB_FREE;
2189 	fc_fcp_pkt_release(fsp);
2190 
2191 out:
2192 	return rc;
2193 }
2194 EXPORT_SYMBOL(fc_eh_device_reset);
2195 
2196 /**
2197  * fc_eh_host_reset() - Reset a Scsi_Host.
2198  * @sc_cmd: The SCSI command that identifies the SCSI host to be reset
2199  */
2200 int fc_eh_host_reset(struct scsi_cmnd *sc_cmd)
2201 {
2202 	struct Scsi_Host *shost = sc_cmd->device->host;
2203 	struct fc_lport *lport = shost_priv(shost);
2204 	unsigned long wait_tmo;
2205 
2206 	FC_SCSI_DBG(lport, "Resetting host\n");
2207 
2208 	fc_lport_reset(lport);
2209 	wait_tmo = jiffies + FC_HOST_RESET_TIMEOUT;
2210 	while (!fc_fcp_lport_queue_ready(lport) && time_before(jiffies,
2211 							       wait_tmo))
2212 		msleep(1000);
2213 
2214 	if (fc_fcp_lport_queue_ready(lport)) {
2215 		shost_printk(KERN_INFO, shost, "libfc: Host reset succeeded "
2216 			     "on port (%6.6x)\n", lport->port_id);
2217 		return SUCCESS;
2218 	} else {
2219 		shost_printk(KERN_INFO, shost, "libfc: Host reset failed, "
2220 			     "port (%6.6x) is not ready.\n",
2221 			     lport->port_id);
2222 		return FAILED;
2223 	}
2224 }
2225 EXPORT_SYMBOL(fc_eh_host_reset);
2226 
2227 /**
2228  * fc_slave_alloc() - Configure the queue depth of a Scsi_Host
2229  * @sdev: The SCSI device that identifies the SCSI host
2230  *
2231  * Configures queue depth based on host's cmd_per_len. If not set
2232  * then we use the libfc default.
2233  */
2234 int fc_slave_alloc(struct scsi_device *sdev)
2235 {
2236 	struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
2237 
2238 	if (!rport || fc_remote_port_chkready(rport))
2239 		return -ENXIO;
2240 
2241 	scsi_change_queue_depth(sdev, FC_FCP_DFLT_QUEUE_DEPTH);
2242 	return 0;
2243 }
2244 EXPORT_SYMBOL(fc_slave_alloc);
2245 
2246 /**
2247  * fc_fcp_destroy() - Tear down the FCP layer for a given local port
2248  * @lport: The local port that no longer needs the FCP layer
2249  */
2250 void fc_fcp_destroy(struct fc_lport *lport)
2251 {
2252 	struct fc_fcp_internal *si = fc_get_scsi_internal(lport);
2253 
2254 	if (!list_empty(&si->scsi_pkt_queue))
2255 		printk(KERN_ERR "libfc: Leaked SCSI packets when destroying "
2256 		       "port (%6.6x)\n", lport->port_id);
2257 
2258 	mempool_destroy(si->scsi_pkt_pool);
2259 	kfree(si);
2260 	lport->scsi_priv = NULL;
2261 }
2262 EXPORT_SYMBOL(fc_fcp_destroy);
2263 
2264 int fc_setup_fcp(void)
2265 {
2266 	int rc = 0;
2267 
2268 	scsi_pkt_cachep = kmem_cache_create("libfc_fcp_pkt",
2269 					    sizeof(struct fc_fcp_pkt),
2270 					    0, SLAB_HWCACHE_ALIGN, NULL);
2271 	if (!scsi_pkt_cachep) {
2272 		printk(KERN_ERR "libfc: Unable to allocate SRB cache, "
2273 		       "module load failed!");
2274 		rc = -ENOMEM;
2275 	}
2276 
2277 	return rc;
2278 }
2279 
2280 void fc_destroy_fcp(void)
2281 {
2282 	kmem_cache_destroy(scsi_pkt_cachep);
2283 }
2284 
2285 /**
2286  * fc_fcp_init() - Initialize the FCP layer for a local port
2287  * @lport: The local port to initialize the exchange layer for
2288  */
2289 int fc_fcp_init(struct fc_lport *lport)
2290 {
2291 	int rc;
2292 	struct fc_fcp_internal *si;
2293 
2294 	if (!lport->tt.fcp_cmd_send)
2295 		lport->tt.fcp_cmd_send = fc_fcp_cmd_send;
2296 
2297 	if (!lport->tt.fcp_cleanup)
2298 		lport->tt.fcp_cleanup = fc_fcp_cleanup;
2299 
2300 	if (!lport->tt.fcp_abort_io)
2301 		lport->tt.fcp_abort_io = fc_fcp_abort_io;
2302 
2303 	si = kzalloc(sizeof(struct fc_fcp_internal), GFP_KERNEL);
2304 	if (!si)
2305 		return -ENOMEM;
2306 	lport->scsi_priv = si;
2307 	si->max_can_queue = lport->host->can_queue;
2308 	INIT_LIST_HEAD(&si->scsi_pkt_queue);
2309 	spin_lock_init(&si->scsi_queue_lock);
2310 
2311 	si->scsi_pkt_pool = mempool_create_slab_pool(2, scsi_pkt_cachep);
2312 	if (!si->scsi_pkt_pool) {
2313 		rc = -ENOMEM;
2314 		goto free_internal;
2315 	}
2316 	return 0;
2317 
2318 free_internal:
2319 	kfree(si);
2320 	return rc;
2321 }
2322 EXPORT_SYMBOL(fc_fcp_init);
2323