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