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