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