]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/infiniband/ulp/srp/ib_srp.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi-misc-2.6
[linux-2.6-omap-h63xx.git] / drivers / infiniband / ulp / srp / ib_srp.c
1 /*
2  * Copyright (c) 2005 Cisco Systems.  All rights reserved.
3  *
4  * This software is available to you under a choice of one of two
5  * licenses.  You may choose to be licensed under the terms of the GNU
6  * General Public License (GPL) Version 2, available from the file
7  * COPYING in the main directory of this source tree, or the
8  * OpenIB.org BSD license below:
9  *
10  *     Redistribution and use in source and binary forms, with or
11  *     without modification, are permitted provided that the following
12  *     conditions are met:
13  *
14  *      - Redistributions of source code must retain the above
15  *        copyright notice, this list of conditions and the following
16  *        disclaimer.
17  *
18  *      - Redistributions in binary form must reproduce the above
19  *        copyright notice, this list of conditions and the following
20  *        disclaimer in the documentation and/or other materials
21  *        provided with the distribution.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
27  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
29  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30  * SOFTWARE.
31  *
32  * $Id: ib_srp.c 3932 2005-11-01 17:19:29Z roland $
33  */
34
35 #include <linux/module.h>
36 #include <linux/init.h>
37 #include <linux/slab.h>
38 #include <linux/err.h>
39 #include <linux/string.h>
40 #include <linux/parser.h>
41 #include <linux/random.h>
42 #include <linux/jiffies.h>
43
44 #include <asm/atomic.h>
45
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_dbg.h>
49 #include <scsi/srp.h>
50 #include <scsi/scsi_transport_srp.h>
51
52 #include <rdma/ib_cache.h>
53
54 #include "ib_srp.h"
55
56 #define DRV_NAME        "ib_srp"
57 #define PFX             DRV_NAME ": "
58 #define DRV_VERSION     "0.2"
59 #define DRV_RELDATE     "November 1, 2005"
60
61 MODULE_AUTHOR("Roland Dreier");
62 MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol initiator "
63                    "v" DRV_VERSION " (" DRV_RELDATE ")");
64 MODULE_LICENSE("Dual BSD/GPL");
65
66 static int srp_sg_tablesize = SRP_DEF_SG_TABLESIZE;
67 static int srp_max_iu_len;
68
69 module_param(srp_sg_tablesize, int, 0444);
70 MODULE_PARM_DESC(srp_sg_tablesize,
71                  "Max number of gather/scatter entries per I/O (default is 12)");
72
73 static int topspin_workarounds = 1;
74
75 module_param(topspin_workarounds, int, 0444);
76 MODULE_PARM_DESC(topspin_workarounds,
77                  "Enable workarounds for Topspin/Cisco SRP target bugs if != 0");
78
79 static int mellanox_workarounds = 1;
80
81 module_param(mellanox_workarounds, int, 0444);
82 MODULE_PARM_DESC(mellanox_workarounds,
83                  "Enable workarounds for Mellanox SRP target bugs if != 0");
84
85 static void srp_add_one(struct ib_device *device);
86 static void srp_remove_one(struct ib_device *device);
87 static void srp_completion(struct ib_cq *cq, void *target_ptr);
88 static int srp_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event);
89
90 static struct scsi_transport_template *ib_srp_transport_template;
91
92 static struct ib_client srp_client = {
93         .name   = "srp",
94         .add    = srp_add_one,
95         .remove = srp_remove_one
96 };
97
98 static struct ib_sa_client srp_sa_client;
99
100 static inline struct srp_target_port *host_to_target(struct Scsi_Host *host)
101 {
102         return (struct srp_target_port *) host->hostdata;
103 }
104
105 static const char *srp_target_info(struct Scsi_Host *host)
106 {
107         return host_to_target(host)->target_name;
108 }
109
110 static int srp_target_is_topspin(struct srp_target_port *target)
111 {
112         static const u8 topspin_oui[3] = { 0x00, 0x05, 0xad };
113         static const u8 cisco_oui[3]   = { 0x00, 0x1b, 0x0d };
114
115         return topspin_workarounds &&
116                 (!memcmp(&target->ioc_guid, topspin_oui, sizeof topspin_oui) ||
117                  !memcmp(&target->ioc_guid, cisco_oui, sizeof cisco_oui));
118 }
119
120 static int srp_target_is_mellanox(struct srp_target_port *target)
121 {
122         static const u8 mellanox_oui[3] = { 0x00, 0x02, 0xc9 };
123
124         return mellanox_workarounds &&
125                 !memcmp(&target->ioc_guid, mellanox_oui, sizeof mellanox_oui);
126 }
127
128 static struct srp_iu *srp_alloc_iu(struct srp_host *host, size_t size,
129                                    gfp_t gfp_mask,
130                                    enum dma_data_direction direction)
131 {
132         struct srp_iu *iu;
133
134         iu = kmalloc(sizeof *iu, gfp_mask);
135         if (!iu)
136                 goto out;
137
138         iu->buf = kzalloc(size, gfp_mask);
139         if (!iu->buf)
140                 goto out_free_iu;
141
142         iu->dma = ib_dma_map_single(host->dev->dev, iu->buf, size, direction);
143         if (ib_dma_mapping_error(host->dev->dev, iu->dma))
144                 goto out_free_buf;
145
146         iu->size      = size;
147         iu->direction = direction;
148
149         return iu;
150
151 out_free_buf:
152         kfree(iu->buf);
153 out_free_iu:
154         kfree(iu);
155 out:
156         return NULL;
157 }
158
159 static void srp_free_iu(struct srp_host *host, struct srp_iu *iu)
160 {
161         if (!iu)
162                 return;
163
164         ib_dma_unmap_single(host->dev->dev, iu->dma, iu->size, iu->direction);
165         kfree(iu->buf);
166         kfree(iu);
167 }
168
169 static void srp_qp_event(struct ib_event *event, void *context)
170 {
171         printk(KERN_ERR PFX "QP event %d\n", event->event);
172 }
173
174 static int srp_init_qp(struct srp_target_port *target,
175                        struct ib_qp *qp)
176 {
177         struct ib_qp_attr *attr;
178         int ret;
179
180         attr = kmalloc(sizeof *attr, GFP_KERNEL);
181         if (!attr)
182                 return -ENOMEM;
183
184         ret = ib_find_cached_pkey(target->srp_host->dev->dev,
185                                   target->srp_host->port,
186                                   be16_to_cpu(target->path.pkey),
187                                   &attr->pkey_index);
188         if (ret)
189                 goto out;
190
191         attr->qp_state        = IB_QPS_INIT;
192         attr->qp_access_flags = (IB_ACCESS_REMOTE_READ |
193                                     IB_ACCESS_REMOTE_WRITE);
194         attr->port_num        = target->srp_host->port;
195
196         ret = ib_modify_qp(qp, attr,
197                            IB_QP_STATE          |
198                            IB_QP_PKEY_INDEX     |
199                            IB_QP_ACCESS_FLAGS   |
200                            IB_QP_PORT);
201
202 out:
203         kfree(attr);
204         return ret;
205 }
206
207 static int srp_create_target_ib(struct srp_target_port *target)
208 {
209         struct ib_qp_init_attr *init_attr;
210         int ret;
211
212         init_attr = kzalloc(sizeof *init_attr, GFP_KERNEL);
213         if (!init_attr)
214                 return -ENOMEM;
215
216         target->cq = ib_create_cq(target->srp_host->dev->dev, srp_completion,
217                                   NULL, target, SRP_CQ_SIZE, 0);
218         if (IS_ERR(target->cq)) {
219                 ret = PTR_ERR(target->cq);
220                 goto out;
221         }
222
223         ib_req_notify_cq(target->cq, IB_CQ_NEXT_COMP);
224
225         init_attr->event_handler       = srp_qp_event;
226         init_attr->cap.max_send_wr     = SRP_SQ_SIZE;
227         init_attr->cap.max_recv_wr     = SRP_RQ_SIZE;
228         init_attr->cap.max_recv_sge    = 1;
229         init_attr->cap.max_send_sge    = 1;
230         init_attr->sq_sig_type         = IB_SIGNAL_ALL_WR;
231         init_attr->qp_type             = IB_QPT_RC;
232         init_attr->send_cq             = target->cq;
233         init_attr->recv_cq             = target->cq;
234
235         target->qp = ib_create_qp(target->srp_host->dev->pd, init_attr);
236         if (IS_ERR(target->qp)) {
237                 ret = PTR_ERR(target->qp);
238                 ib_destroy_cq(target->cq);
239                 goto out;
240         }
241
242         ret = srp_init_qp(target, target->qp);
243         if (ret) {
244                 ib_destroy_qp(target->qp);
245                 ib_destroy_cq(target->cq);
246                 goto out;
247         }
248
249 out:
250         kfree(init_attr);
251         return ret;
252 }
253
254 static void srp_free_target_ib(struct srp_target_port *target)
255 {
256         int i;
257
258         ib_destroy_qp(target->qp);
259         ib_destroy_cq(target->cq);
260
261         for (i = 0; i < SRP_RQ_SIZE; ++i)
262                 srp_free_iu(target->srp_host, target->rx_ring[i]);
263         for (i = 0; i < SRP_SQ_SIZE + 1; ++i)
264                 srp_free_iu(target->srp_host, target->tx_ring[i]);
265 }
266
267 static void srp_path_rec_completion(int status,
268                                     struct ib_sa_path_rec *pathrec,
269                                     void *target_ptr)
270 {
271         struct srp_target_port *target = target_ptr;
272
273         target->status = status;
274         if (status)
275                 shost_printk(KERN_ERR, target->scsi_host,
276                              PFX "Got failed path rec status %d\n", status);
277         else
278                 target->path = *pathrec;
279         complete(&target->done);
280 }
281
282 static int srp_lookup_path(struct srp_target_port *target)
283 {
284         target->path.numb_path = 1;
285
286         init_completion(&target->done);
287
288         target->path_query_id = ib_sa_path_rec_get(&srp_sa_client,
289                                                    target->srp_host->dev->dev,
290                                                    target->srp_host->port,
291                                                    &target->path,
292                                                    IB_SA_PATH_REC_SERVICE_ID    |
293                                                    IB_SA_PATH_REC_DGID          |
294                                                    IB_SA_PATH_REC_SGID          |
295                                                    IB_SA_PATH_REC_NUMB_PATH     |
296                                                    IB_SA_PATH_REC_PKEY,
297                                                    SRP_PATH_REC_TIMEOUT_MS,
298                                                    GFP_KERNEL,
299                                                    srp_path_rec_completion,
300                                                    target, &target->path_query);
301         if (target->path_query_id < 0)
302                 return target->path_query_id;
303
304         wait_for_completion(&target->done);
305
306         if (target->status < 0)
307                 shost_printk(KERN_WARNING, target->scsi_host,
308                              PFX "Path record query failed\n");
309
310         return target->status;
311 }
312
313 static int srp_send_req(struct srp_target_port *target)
314 {
315         struct {
316                 struct ib_cm_req_param param;
317                 struct srp_login_req   priv;
318         } *req = NULL;
319         int status;
320
321         req = kzalloc(sizeof *req, GFP_KERNEL);
322         if (!req)
323                 return -ENOMEM;
324
325         req->param.primary_path               = &target->path;
326         req->param.alternate_path             = NULL;
327         req->param.service_id                 = target->service_id;
328         req->param.qp_num                     = target->qp->qp_num;
329         req->param.qp_type                    = target->qp->qp_type;
330         req->param.private_data               = &req->priv;
331         req->param.private_data_len           = sizeof req->priv;
332         req->param.flow_control               = 1;
333
334         get_random_bytes(&req->param.starting_psn, 4);
335         req->param.starting_psn              &= 0xffffff;
336
337         /*
338          * Pick some arbitrary defaults here; we could make these
339          * module parameters if anyone cared about setting them.
340          */
341         req->param.responder_resources        = 4;
342         req->param.remote_cm_response_timeout = 20;
343         req->param.local_cm_response_timeout  = 20;
344         req->param.retry_count                = 7;
345         req->param.rnr_retry_count            = 7;
346         req->param.max_cm_retries             = 15;
347
348         req->priv.opcode        = SRP_LOGIN_REQ;
349         req->priv.tag           = 0;
350         req->priv.req_it_iu_len = cpu_to_be32(srp_max_iu_len);
351         req->priv.req_buf_fmt   = cpu_to_be16(SRP_BUF_FORMAT_DIRECT |
352                                               SRP_BUF_FORMAT_INDIRECT);
353         /*
354          * In the published SRP specification (draft rev. 16a), the
355          * port identifier format is 8 bytes of ID extension followed
356          * by 8 bytes of GUID.  Older drafts put the two halves in the
357          * opposite order, so that the GUID comes first.
358          *
359          * Targets conforming to these obsolete drafts can be
360          * recognized by the I/O Class they report.
361          */
362         if (target->io_class == SRP_REV10_IB_IO_CLASS) {
363                 memcpy(req->priv.initiator_port_id,
364                        &target->path.sgid.global.interface_id, 8);
365                 memcpy(req->priv.initiator_port_id + 8,
366                        &target->initiator_ext, 8);
367                 memcpy(req->priv.target_port_id,     &target->ioc_guid, 8);
368                 memcpy(req->priv.target_port_id + 8, &target->id_ext, 8);
369         } else {
370                 memcpy(req->priv.initiator_port_id,
371                        &target->initiator_ext, 8);
372                 memcpy(req->priv.initiator_port_id + 8,
373                        &target->path.sgid.global.interface_id, 8);
374                 memcpy(req->priv.target_port_id,     &target->id_ext, 8);
375                 memcpy(req->priv.target_port_id + 8, &target->ioc_guid, 8);
376         }
377
378         /*
379          * Topspin/Cisco SRP targets will reject our login unless we
380          * zero out the first 8 bytes of our initiator port ID and set
381          * the second 8 bytes to the local node GUID.
382          */
383         if (srp_target_is_topspin(target)) {
384                 shost_printk(KERN_DEBUG, target->scsi_host,
385                              PFX "Topspin/Cisco initiator port ID workaround "
386                              "activated for target GUID %016llx\n",
387                              (unsigned long long) be64_to_cpu(target->ioc_guid));
388                 memset(req->priv.initiator_port_id, 0, 8);
389                 memcpy(req->priv.initiator_port_id + 8,
390                        &target->srp_host->dev->dev->node_guid, 8);
391         }
392
393         status = ib_send_cm_req(target->cm_id, &req->param);
394
395         kfree(req);
396
397         return status;
398 }
399
400 static void srp_disconnect_target(struct srp_target_port *target)
401 {
402         /* XXX should send SRP_I_LOGOUT request */
403
404         init_completion(&target->done);
405         if (ib_send_cm_dreq(target->cm_id, NULL, 0)) {
406                 shost_printk(KERN_DEBUG, target->scsi_host,
407                              PFX "Sending CM DREQ failed\n");
408                 return;
409         }
410         wait_for_completion(&target->done);
411 }
412
413 static void srp_remove_work(struct work_struct *work)
414 {
415         struct srp_target_port *target =
416                 container_of(work, struct srp_target_port, work);
417
418         spin_lock_irq(target->scsi_host->host_lock);
419         if (target->state != SRP_TARGET_DEAD) {
420                 spin_unlock_irq(target->scsi_host->host_lock);
421                 return;
422         }
423         target->state = SRP_TARGET_REMOVED;
424         spin_unlock_irq(target->scsi_host->host_lock);
425
426         spin_lock(&target->srp_host->target_lock);
427         list_del(&target->list);
428         spin_unlock(&target->srp_host->target_lock);
429
430         srp_remove_host(target->scsi_host);
431         scsi_remove_host(target->scsi_host);
432         ib_destroy_cm_id(target->cm_id);
433         srp_free_target_ib(target);
434         scsi_host_put(target->scsi_host);
435 }
436
437 static int srp_connect_target(struct srp_target_port *target)
438 {
439         int ret;
440
441         ret = srp_lookup_path(target);
442         if (ret)
443                 return ret;
444
445         while (1) {
446                 init_completion(&target->done);
447                 ret = srp_send_req(target);
448                 if (ret)
449                         return ret;
450                 wait_for_completion(&target->done);
451
452                 /*
453                  * The CM event handling code will set status to
454                  * SRP_PORT_REDIRECT if we get a port redirect REJ
455                  * back, or SRP_DLID_REDIRECT if we get a lid/qp
456                  * redirect REJ back.
457                  */
458                 switch (target->status) {
459                 case 0:
460                         return 0;
461
462                 case SRP_PORT_REDIRECT:
463                         ret = srp_lookup_path(target);
464                         if (ret)
465                                 return ret;
466                         break;
467
468                 case SRP_DLID_REDIRECT:
469                         break;
470
471                 default:
472                         return target->status;
473                 }
474         }
475 }
476
477 static void srp_unmap_data(struct scsi_cmnd *scmnd,
478                            struct srp_target_port *target,
479                            struct srp_request *req)
480 {
481         if (!scsi_sglist(scmnd) ||
482             (scmnd->sc_data_direction != DMA_TO_DEVICE &&
483              scmnd->sc_data_direction != DMA_FROM_DEVICE))
484                 return;
485
486         if (req->fmr) {
487                 ib_fmr_pool_unmap(req->fmr);
488                 req->fmr = NULL;
489         }
490
491         ib_dma_unmap_sg(target->srp_host->dev->dev, scsi_sglist(scmnd),
492                         scsi_sg_count(scmnd), scmnd->sc_data_direction);
493 }
494
495 static void srp_remove_req(struct srp_target_port *target, struct srp_request *req)
496 {
497         srp_unmap_data(req->scmnd, target, req);
498         list_move_tail(&req->list, &target->free_reqs);
499 }
500
501 static void srp_reset_req(struct srp_target_port *target, struct srp_request *req)
502 {
503         req->scmnd->result = DID_RESET << 16;
504         req->scmnd->scsi_done(req->scmnd);
505         srp_remove_req(target, req);
506 }
507
508 static int srp_reconnect_target(struct srp_target_port *target)
509 {
510         struct ib_cm_id *new_cm_id;
511         struct ib_qp_attr qp_attr;
512         struct srp_request *req, *tmp;
513         struct ib_wc wc;
514         int ret;
515
516         spin_lock_irq(target->scsi_host->host_lock);
517         if (target->state != SRP_TARGET_LIVE) {
518                 spin_unlock_irq(target->scsi_host->host_lock);
519                 return -EAGAIN;
520         }
521         target->state = SRP_TARGET_CONNECTING;
522         spin_unlock_irq(target->scsi_host->host_lock);
523
524         srp_disconnect_target(target);
525         /*
526          * Now get a new local CM ID so that we avoid confusing the
527          * target in case things are really fouled up.
528          */
529         new_cm_id = ib_create_cm_id(target->srp_host->dev->dev,
530                                     srp_cm_handler, target);
531         if (IS_ERR(new_cm_id)) {
532                 ret = PTR_ERR(new_cm_id);
533                 goto err;
534         }
535         ib_destroy_cm_id(target->cm_id);
536         target->cm_id = new_cm_id;
537
538         qp_attr.qp_state = IB_QPS_RESET;
539         ret = ib_modify_qp(target->qp, &qp_attr, IB_QP_STATE);
540         if (ret)
541                 goto err;
542
543         ret = srp_init_qp(target, target->qp);
544         if (ret)
545                 goto err;
546
547         while (ib_poll_cq(target->cq, 1, &wc) > 0)
548                 ; /* nothing */
549
550         spin_lock_irq(target->scsi_host->host_lock);
551         list_for_each_entry_safe(req, tmp, &target->req_queue, list)
552                 srp_reset_req(target, req);
553         spin_unlock_irq(target->scsi_host->host_lock);
554
555         target->rx_head  = 0;
556         target->tx_head  = 0;
557         target->tx_tail  = 0;
558
559         target->qp_in_error = 0;
560         ret = srp_connect_target(target);
561         if (ret)
562                 goto err;
563
564         spin_lock_irq(target->scsi_host->host_lock);
565         if (target->state == SRP_TARGET_CONNECTING) {
566                 ret = 0;
567                 target->state = SRP_TARGET_LIVE;
568         } else
569                 ret = -EAGAIN;
570         spin_unlock_irq(target->scsi_host->host_lock);
571
572         return ret;
573
574 err:
575         shost_printk(KERN_ERR, target->scsi_host,
576                      PFX "reconnect failed (%d), removing target port.\n", ret);
577
578         /*
579          * We couldn't reconnect, so kill our target port off.
580          * However, we have to defer the real removal because we might
581          * be in the context of the SCSI error handler now, which
582          * would deadlock if we call scsi_remove_host().
583          */
584         spin_lock_irq(target->scsi_host->host_lock);
585         if (target->state == SRP_TARGET_CONNECTING) {
586                 target->state = SRP_TARGET_DEAD;
587                 INIT_WORK(&target->work, srp_remove_work);
588                 schedule_work(&target->work);
589         }
590         spin_unlock_irq(target->scsi_host->host_lock);
591
592         return ret;
593 }
594
595 static int srp_map_fmr(struct srp_target_port *target, struct scatterlist *scat,
596                        int sg_cnt, struct srp_request *req,
597                        struct srp_direct_buf *buf)
598 {
599         u64 io_addr = 0;
600         u64 *dma_pages;
601         u32 len;
602         int page_cnt;
603         int i, j;
604         int ret;
605         struct srp_device *dev = target->srp_host->dev;
606         struct ib_device *ibdev = dev->dev;
607         struct scatterlist *sg;
608
609         if (!dev->fmr_pool)
610                 return -ENODEV;
611
612         if (srp_target_is_mellanox(target) &&
613             (ib_sg_dma_address(ibdev, &scat[0]) & ~dev->fmr_page_mask))
614                 return -EINVAL;
615
616         len = page_cnt = 0;
617         scsi_for_each_sg(req->scmnd, sg, sg_cnt, i) {
618                 unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
619
620                 if (ib_sg_dma_address(ibdev, sg) & ~dev->fmr_page_mask) {
621                         if (i > 0)
622                                 return -EINVAL;
623                         else
624                                 ++page_cnt;
625                 }
626                 if ((ib_sg_dma_address(ibdev, sg) + dma_len) &
627                     ~dev->fmr_page_mask) {
628                         if (i < sg_cnt - 1)
629                                 return -EINVAL;
630                         else
631                                 ++page_cnt;
632                 }
633
634                 len += dma_len;
635         }
636
637         page_cnt += len >> dev->fmr_page_shift;
638         if (page_cnt > SRP_FMR_SIZE)
639                 return -ENOMEM;
640
641         dma_pages = kmalloc(sizeof (u64) * page_cnt, GFP_ATOMIC);
642         if (!dma_pages)
643                 return -ENOMEM;
644
645         page_cnt = 0;
646         scsi_for_each_sg(req->scmnd, sg, sg_cnt, i) {
647                 unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
648
649                 for (j = 0; j < dma_len; j += dev->fmr_page_size)
650                         dma_pages[page_cnt++] =
651                                 (ib_sg_dma_address(ibdev, sg) &
652                                  dev->fmr_page_mask) + j;
653         }
654
655         req->fmr = ib_fmr_pool_map_phys(dev->fmr_pool,
656                                         dma_pages, page_cnt, io_addr);
657         if (IS_ERR(req->fmr)) {
658                 ret = PTR_ERR(req->fmr);
659                 req->fmr = NULL;
660                 goto out;
661         }
662
663         buf->va  = cpu_to_be64(ib_sg_dma_address(ibdev, &scat[0]) &
664                                ~dev->fmr_page_mask);
665         buf->key = cpu_to_be32(req->fmr->fmr->rkey);
666         buf->len = cpu_to_be32(len);
667
668         ret = 0;
669
670 out:
671         kfree(dma_pages);
672
673         return ret;
674 }
675
676 static int srp_map_data(struct scsi_cmnd *scmnd, struct srp_target_port *target,
677                         struct srp_request *req)
678 {
679         struct scatterlist *scat;
680         struct srp_cmd *cmd = req->cmd->buf;
681         int len, nents, count;
682         u8 fmt = SRP_DATA_DESC_DIRECT;
683         struct srp_device *dev;
684         struct ib_device *ibdev;
685
686         if (!scsi_sglist(scmnd) || scmnd->sc_data_direction == DMA_NONE)
687                 return sizeof (struct srp_cmd);
688
689         if (scmnd->sc_data_direction != DMA_FROM_DEVICE &&
690             scmnd->sc_data_direction != DMA_TO_DEVICE) {
691                 shost_printk(KERN_WARNING, target->scsi_host,
692                              PFX "Unhandled data direction %d\n",
693                              scmnd->sc_data_direction);
694                 return -EINVAL;
695         }
696
697         nents = scsi_sg_count(scmnd);
698         scat  = scsi_sglist(scmnd);
699
700         dev = target->srp_host->dev;
701         ibdev = dev->dev;
702
703         count = ib_dma_map_sg(ibdev, scat, nents, scmnd->sc_data_direction);
704
705         fmt = SRP_DATA_DESC_DIRECT;
706         len = sizeof (struct srp_cmd) + sizeof (struct srp_direct_buf);
707
708         if (count == 1) {
709                 /*
710                  * The midlayer only generated a single gather/scatter
711                  * entry, or DMA mapping coalesced everything to a
712                  * single entry.  So a direct descriptor along with
713                  * the DMA MR suffices.
714                  */
715                 struct srp_direct_buf *buf = (void *) cmd->add_data;
716
717                 buf->va  = cpu_to_be64(ib_sg_dma_address(ibdev, scat));
718                 buf->key = cpu_to_be32(dev->mr->rkey);
719                 buf->len = cpu_to_be32(ib_sg_dma_len(ibdev, scat));
720         } else if (srp_map_fmr(target, scat, count, req,
721                                (void *) cmd->add_data)) {
722                 /*
723                  * FMR mapping failed, and the scatterlist has more
724                  * than one entry.  Generate an indirect memory
725                  * descriptor.
726                  */
727                 struct srp_indirect_buf *buf = (void *) cmd->add_data;
728                 struct scatterlist *sg;
729                 u32 datalen = 0;
730                 int i;
731
732                 fmt = SRP_DATA_DESC_INDIRECT;
733                 len = sizeof (struct srp_cmd) +
734                         sizeof (struct srp_indirect_buf) +
735                         count * sizeof (struct srp_direct_buf);
736
737                 scsi_for_each_sg(scmnd, sg, count, i) {
738                         unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
739
740                         buf->desc_list[i].va  =
741                                 cpu_to_be64(ib_sg_dma_address(ibdev, sg));
742                         buf->desc_list[i].key =
743                                 cpu_to_be32(dev->mr->rkey);
744                         buf->desc_list[i].len = cpu_to_be32(dma_len);
745                         datalen += dma_len;
746                 }
747
748                 if (scmnd->sc_data_direction == DMA_TO_DEVICE)
749                         cmd->data_out_desc_cnt = count;
750                 else
751                         cmd->data_in_desc_cnt = count;
752
753                 buf->table_desc.va  =
754                         cpu_to_be64(req->cmd->dma + sizeof *cmd + sizeof *buf);
755                 buf->table_desc.key =
756                         cpu_to_be32(target->srp_host->dev->mr->rkey);
757                 buf->table_desc.len =
758                         cpu_to_be32(count * sizeof (struct srp_direct_buf));
759
760                 buf->len = cpu_to_be32(datalen);
761         }
762
763         if (scmnd->sc_data_direction == DMA_TO_DEVICE)
764                 cmd->buf_fmt = fmt << 4;
765         else
766                 cmd->buf_fmt = fmt;
767
768         return len;
769 }
770
771 static void srp_process_rsp(struct srp_target_port *target, struct srp_rsp *rsp)
772 {
773         struct srp_request *req;
774         struct scsi_cmnd *scmnd;
775         unsigned long flags;
776         s32 delta;
777
778         delta = (s32) be32_to_cpu(rsp->req_lim_delta);
779
780         spin_lock_irqsave(target->scsi_host->host_lock, flags);
781
782         target->req_lim += delta;
783
784         req = &target->req_ring[rsp->tag & ~SRP_TAG_TSK_MGMT];
785
786         if (unlikely(rsp->tag & SRP_TAG_TSK_MGMT)) {
787                 if (be32_to_cpu(rsp->resp_data_len) < 4)
788                         req->tsk_status = -1;
789                 else
790                         req->tsk_status = rsp->data[3];
791                 complete(&req->done);
792         } else {
793                 scmnd = req->scmnd;
794                 if (!scmnd)
795                         shost_printk(KERN_ERR, target->scsi_host,
796                                      "Null scmnd for RSP w/tag %016llx\n",
797                                      (unsigned long long) rsp->tag);
798                 scmnd->result = rsp->status;
799
800                 if (rsp->flags & SRP_RSP_FLAG_SNSVALID) {
801                         memcpy(scmnd->sense_buffer, rsp->data +
802                                be32_to_cpu(rsp->resp_data_len),
803                                min_t(int, be32_to_cpu(rsp->sense_data_len),
804                                      SCSI_SENSE_BUFFERSIZE));
805                 }
806
807                 if (rsp->flags & (SRP_RSP_FLAG_DOOVER | SRP_RSP_FLAG_DOUNDER))
808                         scsi_set_resid(scmnd, be32_to_cpu(rsp->data_out_res_cnt));
809                 else if (rsp->flags & (SRP_RSP_FLAG_DIOVER | SRP_RSP_FLAG_DIUNDER))
810                         scsi_set_resid(scmnd, be32_to_cpu(rsp->data_in_res_cnt));
811
812                 if (!req->tsk_mgmt) {
813                         scmnd->host_scribble = (void *) -1L;
814                         scmnd->scsi_done(scmnd);
815
816                         srp_remove_req(target, req);
817                 } else
818                         req->cmd_done = 1;
819         }
820
821         spin_unlock_irqrestore(target->scsi_host->host_lock, flags);
822 }
823
824 static void srp_handle_recv(struct srp_target_port *target, struct ib_wc *wc)
825 {
826         struct ib_device *dev;
827         struct srp_iu *iu;
828         u8 opcode;
829
830         iu = target->rx_ring[wc->wr_id & ~SRP_OP_RECV];
831
832         dev = target->srp_host->dev->dev;
833         ib_dma_sync_single_for_cpu(dev, iu->dma, target->max_ti_iu_len,
834                                    DMA_FROM_DEVICE);
835
836         opcode = *(u8 *) iu->buf;
837
838         if (0) {
839                 int i;
840
841                 shost_printk(KERN_ERR, target->scsi_host,
842                              PFX "recv completion, opcode 0x%02x\n", opcode);
843
844                 for (i = 0; i < wc->byte_len; ++i) {
845                         if (i % 8 == 0)
846                                 printk(KERN_ERR "  [%02x] ", i);
847                         printk(" %02x", ((u8 *) iu->buf)[i]);
848                         if ((i + 1) % 8 == 0)
849                                 printk("\n");
850                 }
851
852                 if (wc->byte_len % 8)
853                         printk("\n");
854         }
855
856         switch (opcode) {
857         case SRP_RSP:
858                 srp_process_rsp(target, iu->buf);
859                 break;
860
861         case SRP_T_LOGOUT:
862                 /* XXX Handle target logout */
863                 shost_printk(KERN_WARNING, target->scsi_host,
864                              PFX "Got target logout request\n");
865                 break;
866
867         default:
868                 shost_printk(KERN_WARNING, target->scsi_host,
869                              PFX "Unhandled SRP opcode 0x%02x\n", opcode);
870                 break;
871         }
872
873         ib_dma_sync_single_for_device(dev, iu->dma, target->max_ti_iu_len,
874                                       DMA_FROM_DEVICE);
875 }
876
877 static void srp_completion(struct ib_cq *cq, void *target_ptr)
878 {
879         struct srp_target_port *target = target_ptr;
880         struct ib_wc wc;
881
882         ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
883         while (ib_poll_cq(cq, 1, &wc) > 0) {
884                 if (wc.status) {
885                         shost_printk(KERN_ERR, target->scsi_host,
886                                      PFX "failed %s status %d\n",
887                                      wc.wr_id & SRP_OP_RECV ? "receive" : "send",
888                                      wc.status);
889                         target->qp_in_error = 1;
890                         break;
891                 }
892
893                 if (wc.wr_id & SRP_OP_RECV)
894                         srp_handle_recv(target, &wc);
895                 else
896                         ++target->tx_tail;
897         }
898 }
899
900 static int __srp_post_recv(struct srp_target_port *target)
901 {
902         struct srp_iu *iu;
903         struct ib_sge list;
904         struct ib_recv_wr wr, *bad_wr;
905         unsigned int next;
906         int ret;
907
908         next     = target->rx_head & (SRP_RQ_SIZE - 1);
909         wr.wr_id = next | SRP_OP_RECV;
910         iu       = target->rx_ring[next];
911
912         list.addr   = iu->dma;
913         list.length = iu->size;
914         list.lkey   = target->srp_host->dev->mr->lkey;
915
916         wr.next     = NULL;
917         wr.sg_list  = &list;
918         wr.num_sge  = 1;
919
920         ret = ib_post_recv(target->qp, &wr, &bad_wr);
921         if (!ret)
922                 ++target->rx_head;
923
924         return ret;
925 }
926
927 static int srp_post_recv(struct srp_target_port *target)
928 {
929         unsigned long flags;
930         int ret;
931
932         spin_lock_irqsave(target->scsi_host->host_lock, flags);
933         ret = __srp_post_recv(target);
934         spin_unlock_irqrestore(target->scsi_host->host_lock, flags);
935
936         return ret;
937 }
938
939 /*
940  * Must be called with target->scsi_host->host_lock held to protect
941  * req_lim and tx_head.  Lock cannot be dropped between call here and
942  * call to __srp_post_send().
943  */
944 static struct srp_iu *__srp_get_tx_iu(struct srp_target_port *target,
945                                         enum srp_request_type req_type)
946 {
947         s32 min = (req_type == SRP_REQ_TASK_MGMT) ? 1 : 2;
948
949         if (target->tx_head - target->tx_tail >= SRP_SQ_SIZE)
950                 return NULL;
951
952         if (target->req_lim < min) {
953                 ++target->zero_req_lim;
954                 return NULL;
955         }
956
957         return target->tx_ring[target->tx_head & SRP_SQ_SIZE];
958 }
959
960 /*
961  * Must be called with target->scsi_host->host_lock held to protect
962  * req_lim and tx_head.
963  */
964 static int __srp_post_send(struct srp_target_port *target,
965                            struct srp_iu *iu, int len)
966 {
967         struct ib_sge list;
968         struct ib_send_wr wr, *bad_wr;
969         int ret = 0;
970
971         list.addr   = iu->dma;
972         list.length = len;
973         list.lkey   = target->srp_host->dev->mr->lkey;
974
975         wr.next       = NULL;
976         wr.wr_id      = target->tx_head & SRP_SQ_SIZE;
977         wr.sg_list    = &list;
978         wr.num_sge    = 1;
979         wr.opcode     = IB_WR_SEND;
980         wr.send_flags = IB_SEND_SIGNALED;
981
982         ret = ib_post_send(target->qp, &wr, &bad_wr);
983
984         if (!ret) {
985                 ++target->tx_head;
986                 --target->req_lim;
987         }
988
989         return ret;
990 }
991
992 static int srp_queuecommand(struct scsi_cmnd *scmnd,
993                             void (*done)(struct scsi_cmnd *))
994 {
995         struct srp_target_port *target = host_to_target(scmnd->device->host);
996         struct srp_request *req;
997         struct srp_iu *iu;
998         struct srp_cmd *cmd;
999         struct ib_device *dev;
1000         int len;
1001
1002         if (target->state == SRP_TARGET_CONNECTING)
1003                 goto err;
1004
1005         if (target->state == SRP_TARGET_DEAD ||
1006             target->state == SRP_TARGET_REMOVED) {
1007                 scmnd->result = DID_BAD_TARGET << 16;
1008                 done(scmnd);
1009                 return 0;
1010         }
1011
1012         iu = __srp_get_tx_iu(target, SRP_REQ_NORMAL);
1013         if (!iu)
1014                 goto err;
1015
1016         dev = target->srp_host->dev->dev;
1017         ib_dma_sync_single_for_cpu(dev, iu->dma, srp_max_iu_len,
1018                                    DMA_TO_DEVICE);
1019
1020         req = list_entry(target->free_reqs.next, struct srp_request, list);
1021
1022         scmnd->scsi_done     = done;
1023         scmnd->result        = 0;
1024         scmnd->host_scribble = (void *) (long) req->index;
1025
1026         cmd = iu->buf;
1027         memset(cmd, 0, sizeof *cmd);
1028
1029         cmd->opcode = SRP_CMD;
1030         cmd->lun    = cpu_to_be64((u64) scmnd->device->lun << 48);
1031         cmd->tag    = req->index;
1032         memcpy(cmd->cdb, scmnd->cmnd, scmnd->cmd_len);
1033
1034         req->scmnd    = scmnd;
1035         req->cmd      = iu;
1036         req->cmd_done = 0;
1037         req->tsk_mgmt = NULL;
1038
1039         len = srp_map_data(scmnd, target, req);
1040         if (len < 0) {
1041                 shost_printk(KERN_ERR, target->scsi_host,
1042                              PFX "Failed to map data\n");
1043                 goto err;
1044         }
1045
1046         if (__srp_post_recv(target)) {
1047                 shost_printk(KERN_ERR, target->scsi_host, PFX "Recv failed\n");
1048                 goto err_unmap;
1049         }
1050
1051         ib_dma_sync_single_for_device(dev, iu->dma, srp_max_iu_len,
1052                                       DMA_TO_DEVICE);
1053
1054         if (__srp_post_send(target, iu, len)) {
1055                 shost_printk(KERN_ERR, target->scsi_host, PFX "Send failed\n");
1056                 goto err_unmap;
1057         }
1058
1059         list_move_tail(&req->list, &target->req_queue);
1060
1061         return 0;
1062
1063 err_unmap:
1064         srp_unmap_data(scmnd, target, req);
1065
1066 err:
1067         return SCSI_MLQUEUE_HOST_BUSY;
1068 }
1069
1070 static int srp_alloc_iu_bufs(struct srp_target_port *target)
1071 {
1072         int i;
1073
1074         for (i = 0; i < SRP_RQ_SIZE; ++i) {
1075                 target->rx_ring[i] = srp_alloc_iu(target->srp_host,
1076                                                   target->max_ti_iu_len,
1077                                                   GFP_KERNEL, DMA_FROM_DEVICE);
1078                 if (!target->rx_ring[i])
1079                         goto err;
1080         }
1081
1082         for (i = 0; i < SRP_SQ_SIZE + 1; ++i) {
1083                 target->tx_ring[i] = srp_alloc_iu(target->srp_host,
1084                                                   srp_max_iu_len,
1085                                                   GFP_KERNEL, DMA_TO_DEVICE);
1086                 if (!target->tx_ring[i])
1087                         goto err;
1088         }
1089
1090         return 0;
1091
1092 err:
1093         for (i = 0; i < SRP_RQ_SIZE; ++i) {
1094                 srp_free_iu(target->srp_host, target->rx_ring[i]);
1095                 target->rx_ring[i] = NULL;
1096         }
1097
1098         for (i = 0; i < SRP_SQ_SIZE + 1; ++i) {
1099                 srp_free_iu(target->srp_host, target->tx_ring[i]);
1100                 target->tx_ring[i] = NULL;
1101         }
1102
1103         return -ENOMEM;
1104 }
1105
1106 static void srp_cm_rej_handler(struct ib_cm_id *cm_id,
1107                                struct ib_cm_event *event,
1108                                struct srp_target_port *target)
1109 {
1110         struct Scsi_Host *shost = target->scsi_host;
1111         struct ib_class_port_info *cpi;
1112         int opcode;
1113
1114         switch (event->param.rej_rcvd.reason) {
1115         case IB_CM_REJ_PORT_CM_REDIRECT:
1116                 cpi = event->param.rej_rcvd.ari;
1117                 target->path.dlid = cpi->redirect_lid;
1118                 target->path.pkey = cpi->redirect_pkey;
1119                 cm_id->remote_cm_qpn = be32_to_cpu(cpi->redirect_qp) & 0x00ffffff;
1120                 memcpy(target->path.dgid.raw, cpi->redirect_gid, 16);
1121
1122                 target->status = target->path.dlid ?
1123                         SRP_DLID_REDIRECT : SRP_PORT_REDIRECT;
1124                 break;
1125
1126         case IB_CM_REJ_PORT_REDIRECT:
1127                 if (srp_target_is_topspin(target)) {
1128                         /*
1129                          * Topspin/Cisco SRP gateways incorrectly send
1130                          * reject reason code 25 when they mean 24
1131                          * (port redirect).
1132                          */
1133                         memcpy(target->path.dgid.raw,
1134                                event->param.rej_rcvd.ari, 16);
1135
1136                         shost_printk(KERN_DEBUG, shost,
1137                                      PFX "Topspin/Cisco redirect to target port GID %016llx%016llx\n",
1138                                      (unsigned long long) be64_to_cpu(target->path.dgid.global.subnet_prefix),
1139                                      (unsigned long long) be64_to_cpu(target->path.dgid.global.interface_id));
1140
1141                         target->status = SRP_PORT_REDIRECT;
1142                 } else {
1143                         shost_printk(KERN_WARNING, shost,
1144                                      "  REJ reason: IB_CM_REJ_PORT_REDIRECT\n");
1145                         target->status = -ECONNRESET;
1146                 }
1147                 break;
1148
1149         case IB_CM_REJ_DUPLICATE_LOCAL_COMM_ID:
1150                 shost_printk(KERN_WARNING, shost,
1151                             "  REJ reason: IB_CM_REJ_DUPLICATE_LOCAL_COMM_ID\n");
1152                 target->status = -ECONNRESET;
1153                 break;
1154
1155         case IB_CM_REJ_CONSUMER_DEFINED:
1156                 opcode = *(u8 *) event->private_data;
1157                 if (opcode == SRP_LOGIN_REJ) {
1158                         struct srp_login_rej *rej = event->private_data;
1159                         u32 reason = be32_to_cpu(rej->reason);
1160
1161                         if (reason == SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE)
1162                                 shost_printk(KERN_WARNING, shost,
1163                                              PFX "SRP_LOGIN_REJ: requested max_it_iu_len too large\n");
1164                         else
1165                                 shost_printk(KERN_WARNING, shost,
1166                                             PFX "SRP LOGIN REJECTED, reason 0x%08x\n", reason);
1167                 } else
1168                         shost_printk(KERN_WARNING, shost,
1169                                      "  REJ reason: IB_CM_REJ_CONSUMER_DEFINED,"
1170                                      " opcode 0x%02x\n", opcode);
1171                 target->status = -ECONNRESET;
1172                 break;
1173
1174         default:
1175                 shost_printk(KERN_WARNING, shost, "  REJ reason 0x%x\n",
1176                              event->param.rej_rcvd.reason);
1177                 target->status = -ECONNRESET;
1178         }
1179 }
1180
1181 static int srp_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
1182 {
1183         struct srp_target_port *target = cm_id->context;
1184         struct ib_qp_attr *qp_attr = NULL;
1185         int attr_mask = 0;
1186         int comp = 0;
1187         int opcode = 0;
1188
1189         switch (event->event) {
1190         case IB_CM_REQ_ERROR:
1191                 shost_printk(KERN_DEBUG, target->scsi_host,
1192                              PFX "Sending CM REQ failed\n");
1193                 comp = 1;
1194                 target->status = -ECONNRESET;
1195                 break;
1196
1197         case IB_CM_REP_RECEIVED:
1198                 comp = 1;
1199                 opcode = *(u8 *) event->private_data;
1200
1201                 if (opcode == SRP_LOGIN_RSP) {
1202                         struct srp_login_rsp *rsp = event->private_data;
1203
1204                         target->max_ti_iu_len = be32_to_cpu(rsp->max_ti_iu_len);
1205                         target->req_lim       = be32_to_cpu(rsp->req_lim_delta);
1206
1207                         target->scsi_host->can_queue = min(target->req_lim,
1208                                                            target->scsi_host->can_queue);
1209                 } else {
1210                         shost_printk(KERN_WARNING, target->scsi_host,
1211                                     PFX "Unhandled RSP opcode %#x\n", opcode);
1212                         target->status = -ECONNRESET;
1213                         break;
1214                 }
1215
1216                 if (!target->rx_ring[0]) {
1217                         target->status = srp_alloc_iu_bufs(target);
1218                         if (target->status)
1219                                 break;
1220                 }
1221
1222                 qp_attr = kmalloc(sizeof *qp_attr, GFP_KERNEL);
1223                 if (!qp_attr) {
1224                         target->status = -ENOMEM;
1225                         break;
1226                 }
1227
1228                 qp_attr->qp_state = IB_QPS_RTR;
1229                 target->status = ib_cm_init_qp_attr(cm_id, qp_attr, &attr_mask);
1230                 if (target->status)
1231                         break;
1232
1233                 target->status = ib_modify_qp(target->qp, qp_attr, attr_mask);
1234                 if (target->status)
1235                         break;
1236
1237                 target->status = srp_post_recv(target);
1238                 if (target->status)
1239                         break;
1240
1241                 qp_attr->qp_state = IB_QPS_RTS;
1242                 target->status = ib_cm_init_qp_attr(cm_id, qp_attr, &attr_mask);
1243                 if (target->status)
1244                         break;
1245
1246                 target->status = ib_modify_qp(target->qp, qp_attr, attr_mask);
1247                 if (target->status)
1248                         break;
1249
1250                 target->status = ib_send_cm_rtu(cm_id, NULL, 0);
1251                 if (target->status)
1252                         break;
1253
1254                 break;
1255
1256         case IB_CM_REJ_RECEIVED:
1257                 shost_printk(KERN_DEBUG, target->scsi_host, PFX "REJ received\n");
1258                 comp = 1;
1259
1260                 srp_cm_rej_handler(cm_id, event, target);
1261                 break;
1262
1263         case IB_CM_DREQ_RECEIVED:
1264                 shost_printk(KERN_WARNING, target->scsi_host,
1265                              PFX "DREQ received - connection closed\n");
1266                 if (ib_send_cm_drep(cm_id, NULL, 0))
1267                         shost_printk(KERN_ERR, target->scsi_host,
1268                                      PFX "Sending CM DREP failed\n");
1269                 break;
1270
1271         case IB_CM_TIMEWAIT_EXIT:
1272                 shost_printk(KERN_ERR, target->scsi_host,
1273                              PFX "connection closed\n");
1274
1275                 comp = 1;
1276                 target->status = 0;
1277                 break;
1278
1279         case IB_CM_MRA_RECEIVED:
1280         case IB_CM_DREQ_ERROR:
1281         case IB_CM_DREP_RECEIVED:
1282                 break;
1283
1284         default:
1285                 shost_printk(KERN_WARNING, target->scsi_host,
1286                              PFX "Unhandled CM event %d\n", event->event);
1287                 break;
1288         }
1289
1290         if (comp)
1291                 complete(&target->done);
1292
1293         kfree(qp_attr);
1294
1295         return 0;
1296 }
1297
1298 static int srp_send_tsk_mgmt(struct srp_target_port *target,
1299                              struct srp_request *req, u8 func)
1300 {
1301         struct srp_iu *iu;
1302         struct srp_tsk_mgmt *tsk_mgmt;
1303
1304         spin_lock_irq(target->scsi_host->host_lock);
1305
1306         if (target->state == SRP_TARGET_DEAD ||
1307             target->state == SRP_TARGET_REMOVED) {
1308                 req->scmnd->result = DID_BAD_TARGET << 16;
1309                 goto out;
1310         }
1311
1312         init_completion(&req->done);
1313
1314         iu = __srp_get_tx_iu(target, SRP_REQ_TASK_MGMT);
1315         if (!iu)
1316                 goto out;
1317
1318         tsk_mgmt = iu->buf;
1319         memset(tsk_mgmt, 0, sizeof *tsk_mgmt);
1320
1321         tsk_mgmt->opcode        = SRP_TSK_MGMT;
1322         tsk_mgmt->lun           = cpu_to_be64((u64) req->scmnd->device->lun << 48);
1323         tsk_mgmt->tag           = req->index | SRP_TAG_TSK_MGMT;
1324         tsk_mgmt->tsk_mgmt_func = func;
1325         tsk_mgmt->task_tag      = req->index;
1326
1327         if (__srp_post_send(target, iu, sizeof *tsk_mgmt))
1328                 goto out;
1329
1330         req->tsk_mgmt = iu;
1331
1332         spin_unlock_irq(target->scsi_host->host_lock);
1333
1334         if (!wait_for_completion_timeout(&req->done,
1335                                          msecs_to_jiffies(SRP_ABORT_TIMEOUT_MS)))
1336                 return -1;
1337
1338         return 0;
1339
1340 out:
1341         spin_unlock_irq(target->scsi_host->host_lock);
1342         return -1;
1343 }
1344
1345 static int srp_find_req(struct srp_target_port *target,
1346                         struct scsi_cmnd *scmnd,
1347                         struct srp_request **req)
1348 {
1349         if (scmnd->host_scribble == (void *) -1L)
1350                 return -1;
1351
1352         *req = &target->req_ring[(long) scmnd->host_scribble];
1353
1354         return 0;
1355 }
1356
1357 static int srp_abort(struct scsi_cmnd *scmnd)
1358 {
1359         struct srp_target_port *target = host_to_target(scmnd->device->host);
1360         struct srp_request *req;
1361         int ret = SUCCESS;
1362
1363         shost_printk(KERN_ERR, target->scsi_host, "SRP abort called\n");
1364
1365         if (target->qp_in_error)
1366                 return FAILED;
1367         if (srp_find_req(target, scmnd, &req))
1368                 return FAILED;
1369         if (srp_send_tsk_mgmt(target, req, SRP_TSK_ABORT_TASK))
1370                 return FAILED;
1371
1372         spin_lock_irq(target->scsi_host->host_lock);
1373
1374         if (req->cmd_done) {
1375                 srp_remove_req(target, req);
1376                 scmnd->scsi_done(scmnd);
1377         } else if (!req->tsk_status) {
1378                 srp_remove_req(target, req);
1379                 scmnd->result = DID_ABORT << 16;
1380         } else
1381                 ret = FAILED;
1382
1383         spin_unlock_irq(target->scsi_host->host_lock);
1384
1385         return ret;
1386 }
1387
1388 static int srp_reset_device(struct scsi_cmnd *scmnd)
1389 {
1390         struct srp_target_port *target = host_to_target(scmnd->device->host);
1391         struct srp_request *req, *tmp;
1392
1393         shost_printk(KERN_ERR, target->scsi_host, "SRP reset_device called\n");
1394
1395         if (target->qp_in_error)
1396                 return FAILED;
1397         if (srp_find_req(target, scmnd, &req))
1398                 return FAILED;
1399         if (srp_send_tsk_mgmt(target, req, SRP_TSK_LUN_RESET))
1400                 return FAILED;
1401         if (req->tsk_status)
1402                 return FAILED;
1403
1404         spin_lock_irq(target->scsi_host->host_lock);
1405
1406         list_for_each_entry_safe(req, tmp, &target->req_queue, list)
1407                 if (req->scmnd->device == scmnd->device)
1408                         srp_reset_req(target, req);
1409
1410         spin_unlock_irq(target->scsi_host->host_lock);
1411
1412         return SUCCESS;
1413 }
1414
1415 static int srp_reset_host(struct scsi_cmnd *scmnd)
1416 {
1417         struct srp_target_port *target = host_to_target(scmnd->device->host);
1418         int ret = FAILED;
1419
1420         shost_printk(KERN_ERR, target->scsi_host, PFX "SRP reset_host called\n");
1421
1422         if (!srp_reconnect_target(target))
1423                 ret = SUCCESS;
1424
1425         return ret;
1426 }
1427
1428 static ssize_t show_id_ext(struct class_device *cdev, char *buf)
1429 {
1430         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1431
1432         if (target->state == SRP_TARGET_DEAD ||
1433             target->state == SRP_TARGET_REMOVED)
1434                 return -ENODEV;
1435
1436         return sprintf(buf, "0x%016llx\n",
1437                        (unsigned long long) be64_to_cpu(target->id_ext));
1438 }
1439
1440 static ssize_t show_ioc_guid(struct class_device *cdev, char *buf)
1441 {
1442         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1443
1444         if (target->state == SRP_TARGET_DEAD ||
1445             target->state == SRP_TARGET_REMOVED)
1446                 return -ENODEV;
1447
1448         return sprintf(buf, "0x%016llx\n",
1449                        (unsigned long long) be64_to_cpu(target->ioc_guid));
1450 }
1451
1452 static ssize_t show_service_id(struct class_device *cdev, char *buf)
1453 {
1454         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1455
1456         if (target->state == SRP_TARGET_DEAD ||
1457             target->state == SRP_TARGET_REMOVED)
1458                 return -ENODEV;
1459
1460         return sprintf(buf, "0x%016llx\n",
1461                        (unsigned long long) be64_to_cpu(target->service_id));
1462 }
1463
1464 static ssize_t show_pkey(struct class_device *cdev, char *buf)
1465 {
1466         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1467
1468         if (target->state == SRP_TARGET_DEAD ||
1469             target->state == SRP_TARGET_REMOVED)
1470                 return -ENODEV;
1471
1472         return sprintf(buf, "0x%04x\n", be16_to_cpu(target->path.pkey));
1473 }
1474
1475 static ssize_t show_dgid(struct class_device *cdev, char *buf)
1476 {
1477         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1478
1479         if (target->state == SRP_TARGET_DEAD ||
1480             target->state == SRP_TARGET_REMOVED)
1481                 return -ENODEV;
1482
1483         return sprintf(buf, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n",
1484                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[0]),
1485                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[1]),
1486                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[2]),
1487                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[3]),
1488                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[4]),
1489                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[5]),
1490                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[6]),
1491                        be16_to_cpu(((__be16 *) target->path.dgid.raw)[7]));
1492 }
1493
1494 static ssize_t show_orig_dgid(struct class_device *cdev, char *buf)
1495 {
1496         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1497
1498         if (target->state == SRP_TARGET_DEAD ||
1499             target->state == SRP_TARGET_REMOVED)
1500                 return -ENODEV;
1501
1502         return sprintf(buf, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n",
1503                        be16_to_cpu(target->orig_dgid[0]),
1504                        be16_to_cpu(target->orig_dgid[1]),
1505                        be16_to_cpu(target->orig_dgid[2]),
1506                        be16_to_cpu(target->orig_dgid[3]),
1507                        be16_to_cpu(target->orig_dgid[4]),
1508                        be16_to_cpu(target->orig_dgid[5]),
1509                        be16_to_cpu(target->orig_dgid[6]),
1510                        be16_to_cpu(target->orig_dgid[7]));
1511 }
1512
1513 static ssize_t show_zero_req_lim(struct class_device *cdev, char *buf)
1514 {
1515         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1516
1517         if (target->state == SRP_TARGET_DEAD ||
1518             target->state == SRP_TARGET_REMOVED)
1519                 return -ENODEV;
1520
1521         return sprintf(buf, "%d\n", target->zero_req_lim);
1522 }
1523
1524 static ssize_t show_local_ib_port(struct class_device *cdev, char *buf)
1525 {
1526         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1527
1528         return sprintf(buf, "%d\n", target->srp_host->port);
1529 }
1530
1531 static ssize_t show_local_ib_device(struct class_device *cdev, char *buf)
1532 {
1533         struct srp_target_port *target = host_to_target(class_to_shost(cdev));
1534
1535         return sprintf(buf, "%s\n", target->srp_host->dev->dev->name);
1536 }
1537
1538 static CLASS_DEVICE_ATTR(id_ext,          S_IRUGO, show_id_ext,          NULL);
1539 static CLASS_DEVICE_ATTR(ioc_guid,        S_IRUGO, show_ioc_guid,        NULL);
1540 static CLASS_DEVICE_ATTR(service_id,      S_IRUGO, show_service_id,      NULL);
1541 static CLASS_DEVICE_ATTR(pkey,            S_IRUGO, show_pkey,            NULL);
1542 static CLASS_DEVICE_ATTR(dgid,            S_IRUGO, show_dgid,            NULL);
1543 static CLASS_DEVICE_ATTR(orig_dgid,       S_IRUGO, show_orig_dgid,       NULL);
1544 static CLASS_DEVICE_ATTR(zero_req_lim,    S_IRUGO, show_zero_req_lim,    NULL);
1545 static CLASS_DEVICE_ATTR(local_ib_port,   S_IRUGO, show_local_ib_port,   NULL);
1546 static CLASS_DEVICE_ATTR(local_ib_device, S_IRUGO, show_local_ib_device, NULL);
1547
1548 static struct class_device_attribute *srp_host_attrs[] = {
1549         &class_device_attr_id_ext,
1550         &class_device_attr_ioc_guid,
1551         &class_device_attr_service_id,
1552         &class_device_attr_pkey,
1553         &class_device_attr_dgid,
1554         &class_device_attr_orig_dgid,
1555         &class_device_attr_zero_req_lim,
1556         &class_device_attr_local_ib_port,
1557         &class_device_attr_local_ib_device,
1558         NULL
1559 };
1560
1561 static struct scsi_host_template srp_template = {
1562         .module                         = THIS_MODULE,
1563         .name                           = "InfiniBand SRP initiator",
1564         .proc_name                      = DRV_NAME,
1565         .info                           = srp_target_info,
1566         .queuecommand                   = srp_queuecommand,
1567         .eh_abort_handler               = srp_abort,
1568         .eh_device_reset_handler        = srp_reset_device,
1569         .eh_host_reset_handler          = srp_reset_host,
1570         .can_queue                      = SRP_SQ_SIZE,
1571         .this_id                        = -1,
1572         .cmd_per_lun                    = SRP_SQ_SIZE,
1573         .use_clustering                 = ENABLE_CLUSTERING,
1574         .use_sg_chaining                = ENABLE_SG_CHAINING,
1575         .shost_attrs                    = srp_host_attrs
1576 };
1577
1578 static int srp_add_target(struct srp_host *host, struct srp_target_port *target)
1579 {
1580         struct srp_rport_identifiers ids;
1581         struct srp_rport *rport;
1582
1583         sprintf(target->target_name, "SRP.T10:%016llX",
1584                  (unsigned long long) be64_to_cpu(target->id_ext));
1585
1586         if (scsi_add_host(target->scsi_host, host->dev->dev->dma_device))
1587                 return -ENODEV;
1588
1589         memcpy(ids.port_id, &target->id_ext, 8);
1590         memcpy(ids.port_id + 8, &target->ioc_guid, 8);
1591         ids.roles = SRP_RPORT_ROLE_TARGET;
1592         rport = srp_rport_add(target->scsi_host, &ids);
1593         if (IS_ERR(rport)) {
1594                 scsi_remove_host(target->scsi_host);
1595                 return PTR_ERR(rport);
1596         }
1597
1598         spin_lock(&host->target_lock);
1599         list_add_tail(&target->list, &host->target_list);
1600         spin_unlock(&host->target_lock);
1601
1602         target->state = SRP_TARGET_LIVE;
1603
1604         scsi_scan_target(&target->scsi_host->shost_gendev,
1605                          0, target->scsi_id, SCAN_WILD_CARD, 0);
1606
1607         return 0;
1608 }
1609
1610 static void srp_release_class_dev(struct class_device *class_dev)
1611 {
1612         struct srp_host *host =
1613                 container_of(class_dev, struct srp_host, class_dev);
1614
1615         complete(&host->released);
1616 }
1617
1618 static struct class srp_class = {
1619         .name    = "infiniband_srp",
1620         .release = srp_release_class_dev
1621 };
1622
1623 /*
1624  * Target ports are added by writing
1625  *
1626  *     id_ext=<SRP ID ext>,ioc_guid=<SRP IOC GUID>,dgid=<dest GID>,
1627  *     pkey=<P_Key>,service_id=<service ID>
1628  *
1629  * to the add_target sysfs attribute.
1630  */
1631 enum {
1632         SRP_OPT_ERR             = 0,
1633         SRP_OPT_ID_EXT          = 1 << 0,
1634         SRP_OPT_IOC_GUID        = 1 << 1,
1635         SRP_OPT_DGID            = 1 << 2,
1636         SRP_OPT_PKEY            = 1 << 3,
1637         SRP_OPT_SERVICE_ID      = 1 << 4,
1638         SRP_OPT_MAX_SECT        = 1 << 5,
1639         SRP_OPT_MAX_CMD_PER_LUN = 1 << 6,
1640         SRP_OPT_IO_CLASS        = 1 << 7,
1641         SRP_OPT_INITIATOR_EXT   = 1 << 8,
1642         SRP_OPT_ALL             = (SRP_OPT_ID_EXT       |
1643                                    SRP_OPT_IOC_GUID     |
1644                                    SRP_OPT_DGID         |
1645                                    SRP_OPT_PKEY         |
1646                                    SRP_OPT_SERVICE_ID),
1647 };
1648
1649 static match_table_t srp_opt_tokens = {
1650         { SRP_OPT_ID_EXT,               "id_ext=%s"             },
1651         { SRP_OPT_IOC_GUID,             "ioc_guid=%s"           },
1652         { SRP_OPT_DGID,                 "dgid=%s"               },
1653         { SRP_OPT_PKEY,                 "pkey=%x"               },
1654         { SRP_OPT_SERVICE_ID,           "service_id=%s"         },
1655         { SRP_OPT_MAX_SECT,             "max_sect=%d"           },
1656         { SRP_OPT_MAX_CMD_PER_LUN,      "max_cmd_per_lun=%d"    },
1657         { SRP_OPT_IO_CLASS,             "io_class=%x"           },
1658         { SRP_OPT_INITIATOR_EXT,        "initiator_ext=%s"      },
1659         { SRP_OPT_ERR,                  NULL                    }
1660 };
1661
1662 static int srp_parse_options(const char *buf, struct srp_target_port *target)
1663 {
1664         char *options, *sep_opt;
1665         char *p;
1666         char dgid[3];
1667         substring_t args[MAX_OPT_ARGS];
1668         int opt_mask = 0;
1669         int token;
1670         int ret = -EINVAL;
1671         int i;
1672
1673         options = kstrdup(buf, GFP_KERNEL);
1674         if (!options)
1675                 return -ENOMEM;
1676
1677         sep_opt = options;
1678         while ((p = strsep(&sep_opt, ",")) != NULL) {
1679                 if (!*p)
1680                         continue;
1681
1682                 token = match_token(p, srp_opt_tokens, args);
1683                 opt_mask |= token;
1684
1685                 switch (token) {
1686                 case SRP_OPT_ID_EXT:
1687                         p = match_strdup(args);
1688                         if (!p) {
1689                                 ret = -ENOMEM;
1690                                 goto out;
1691                         }
1692                         target->id_ext = cpu_to_be64(simple_strtoull(p, NULL, 16));
1693                         kfree(p);
1694                         break;
1695
1696                 case SRP_OPT_IOC_GUID:
1697                         p = match_strdup(args);
1698                         if (!p) {
1699                                 ret = -ENOMEM;
1700                                 goto out;
1701                         }
1702                         target->ioc_guid = cpu_to_be64(simple_strtoull(p, NULL, 16));
1703                         kfree(p);
1704                         break;
1705
1706                 case SRP_OPT_DGID:
1707                         p = match_strdup(args);
1708                         if (!p) {
1709                                 ret = -ENOMEM;
1710                                 goto out;
1711                         }
1712                         if (strlen(p) != 32) {
1713                                 printk(KERN_WARNING PFX "bad dest GID parameter '%s'\n", p);
1714                                 kfree(p);
1715                                 goto out;
1716                         }
1717
1718                         for (i = 0; i < 16; ++i) {
1719                                 strlcpy(dgid, p + i * 2, 3);
1720                                 target->path.dgid.raw[i] = simple_strtoul(dgid, NULL, 16);
1721                         }
1722                         kfree(p);
1723                         memcpy(target->orig_dgid, target->path.dgid.raw, 16);
1724                         break;
1725
1726                 case SRP_OPT_PKEY:
1727                         if (match_hex(args, &token)) {
1728                                 printk(KERN_WARNING PFX "bad P_Key parameter '%s'\n", p);
1729                                 goto out;
1730                         }
1731                         target->path.pkey = cpu_to_be16(token);
1732                         break;
1733
1734                 case SRP_OPT_SERVICE_ID:
1735                         p = match_strdup(args);
1736                         if (!p) {
1737                                 ret = -ENOMEM;
1738                                 goto out;
1739                         }
1740                         target->service_id = cpu_to_be64(simple_strtoull(p, NULL, 16));
1741                         target->path.service_id = target->service_id;
1742                         kfree(p);
1743                         break;
1744
1745                 case SRP_OPT_MAX_SECT:
1746                         if (match_int(args, &token)) {
1747                                 printk(KERN_WARNING PFX "bad max sect parameter '%s'\n", p);
1748                                 goto out;
1749                         }
1750                         target->scsi_host->max_sectors = token;
1751                         break;
1752
1753                 case SRP_OPT_MAX_CMD_PER_LUN:
1754                         if (match_int(args, &token)) {
1755                                 printk(KERN_WARNING PFX "bad max cmd_per_lun parameter '%s'\n", p);
1756                                 goto out;
1757                         }
1758                         target->scsi_host->cmd_per_lun = min(token, SRP_SQ_SIZE);
1759                         break;
1760
1761                 case SRP_OPT_IO_CLASS:
1762                         if (match_hex(args, &token)) {
1763                                 printk(KERN_WARNING PFX "bad  IO class parameter '%s' \n", p);
1764                                 goto out;
1765                         }
1766                         if (token != SRP_REV10_IB_IO_CLASS &&
1767                             token != SRP_REV16A_IB_IO_CLASS) {
1768                                 printk(KERN_WARNING PFX "unknown IO class parameter value"
1769                                        " %x specified (use %x or %x).\n",
1770                                        token, SRP_REV10_IB_IO_CLASS, SRP_REV16A_IB_IO_CLASS);
1771                                 goto out;
1772                         }
1773                         target->io_class = token;
1774                         break;
1775
1776                 case SRP_OPT_INITIATOR_EXT:
1777                         p = match_strdup(args);
1778                         if (!p) {
1779                                 ret = -ENOMEM;
1780                                 goto out;
1781                         }
1782                         target->initiator_ext = cpu_to_be64(simple_strtoull(p, NULL, 16));
1783                         kfree(p);
1784                         break;
1785
1786                 default:
1787                         printk(KERN_WARNING PFX "unknown parameter or missing value "
1788                                "'%s' in target creation request\n", p);
1789                         goto out;
1790                 }
1791         }
1792
1793         if ((opt_mask & SRP_OPT_ALL) == SRP_OPT_ALL)
1794                 ret = 0;
1795         else
1796                 for (i = 0; i < ARRAY_SIZE(srp_opt_tokens); ++i)
1797                         if ((srp_opt_tokens[i].token & SRP_OPT_ALL) &&
1798                             !(srp_opt_tokens[i].token & opt_mask))
1799                                 printk(KERN_WARNING PFX "target creation request is "
1800                                        "missing parameter '%s'\n",
1801                                        srp_opt_tokens[i].pattern);
1802
1803 out:
1804         kfree(options);
1805         return ret;
1806 }
1807
1808 static ssize_t srp_create_target(struct class_device *class_dev,
1809                                  const char *buf, size_t count)
1810 {
1811         struct srp_host *host =
1812                 container_of(class_dev, struct srp_host, class_dev);
1813         struct Scsi_Host *target_host;
1814         struct srp_target_port *target;
1815         int ret;
1816         int i;
1817
1818         target_host = scsi_host_alloc(&srp_template,
1819                                       sizeof (struct srp_target_port));
1820         if (!target_host)
1821                 return -ENOMEM;
1822
1823         target_host->transportt = ib_srp_transport_template;
1824         target_host->max_lun     = SRP_MAX_LUN;
1825         target_host->max_cmd_len = sizeof ((struct srp_cmd *) (void *) 0L)->cdb;
1826
1827         target = host_to_target(target_host);
1828
1829         target->io_class   = SRP_REV16A_IB_IO_CLASS;
1830         target->scsi_host  = target_host;
1831         target->srp_host   = host;
1832
1833         INIT_LIST_HEAD(&target->free_reqs);
1834         INIT_LIST_HEAD(&target->req_queue);
1835         for (i = 0; i < SRP_SQ_SIZE; ++i) {
1836                 target->req_ring[i].index = i;
1837                 list_add_tail(&target->req_ring[i].list, &target->free_reqs);
1838         }
1839
1840         ret = srp_parse_options(buf, target);
1841         if (ret)
1842                 goto err;
1843
1844         ib_get_cached_gid(host->dev->dev, host->port, 0, &target->path.sgid);
1845
1846         shost_printk(KERN_DEBUG, target->scsi_host, PFX
1847                      "new target: id_ext %016llx ioc_guid %016llx pkey %04x "
1848                      "service_id %016llx dgid %04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n",
1849                (unsigned long long) be64_to_cpu(target->id_ext),
1850                (unsigned long long) be64_to_cpu(target->ioc_guid),
1851                be16_to_cpu(target->path.pkey),
1852                (unsigned long long) be64_to_cpu(target->service_id),
1853                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[0]),
1854                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[2]),
1855                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[4]),
1856                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[6]),
1857                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[8]),
1858                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[10]),
1859                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[12]),
1860                (int) be16_to_cpu(*(__be16 *) &target->path.dgid.raw[14]));
1861
1862         ret = srp_create_target_ib(target);
1863         if (ret)
1864                 goto err;
1865
1866         target->cm_id = ib_create_cm_id(host->dev->dev, srp_cm_handler, target);
1867         if (IS_ERR(target->cm_id)) {
1868                 ret = PTR_ERR(target->cm_id);
1869                 goto err_free;
1870         }
1871
1872         target->qp_in_error = 0;
1873         ret = srp_connect_target(target);
1874         if (ret) {
1875                 shost_printk(KERN_ERR, target->scsi_host,
1876                              PFX "Connection failed\n");
1877                 goto err_cm_id;
1878         }
1879
1880         ret = srp_add_target(host, target);
1881         if (ret)
1882                 goto err_disconnect;
1883
1884         return count;
1885
1886 err_disconnect:
1887         srp_disconnect_target(target);
1888
1889 err_cm_id:
1890         ib_destroy_cm_id(target->cm_id);
1891
1892 err_free:
1893         srp_free_target_ib(target);
1894
1895 err:
1896         scsi_host_put(target_host);
1897
1898         return ret;
1899 }
1900
1901 static CLASS_DEVICE_ATTR(add_target, S_IWUSR, NULL, srp_create_target);
1902
1903 static ssize_t show_ibdev(struct class_device *class_dev, char *buf)
1904 {
1905         struct srp_host *host =
1906                 container_of(class_dev, struct srp_host, class_dev);
1907
1908         return sprintf(buf, "%s\n", host->dev->dev->name);
1909 }
1910
1911 static CLASS_DEVICE_ATTR(ibdev, S_IRUGO, show_ibdev, NULL);
1912
1913 static ssize_t show_port(struct class_device *class_dev, char *buf)
1914 {
1915         struct srp_host *host =
1916                 container_of(class_dev, struct srp_host, class_dev);
1917
1918         return sprintf(buf, "%d\n", host->port);
1919 }
1920
1921 static CLASS_DEVICE_ATTR(port, S_IRUGO, show_port, NULL);
1922
1923 static struct srp_host *srp_add_port(struct srp_device *device, u8 port)
1924 {
1925         struct srp_host *host;
1926
1927         host = kzalloc(sizeof *host, GFP_KERNEL);
1928         if (!host)
1929                 return NULL;
1930
1931         INIT_LIST_HEAD(&host->target_list);
1932         spin_lock_init(&host->target_lock);
1933         init_completion(&host->released);
1934         host->dev  = device;
1935         host->port = port;
1936
1937         host->class_dev.class = &srp_class;
1938         host->class_dev.dev   = device->dev->dma_device;
1939         snprintf(host->class_dev.class_id, BUS_ID_SIZE, "srp-%s-%d",
1940                  device->dev->name, port);
1941
1942         if (class_device_register(&host->class_dev))
1943                 goto free_host;
1944         if (class_device_create_file(&host->class_dev, &class_device_attr_add_target))
1945                 goto err_class;
1946         if (class_device_create_file(&host->class_dev, &class_device_attr_ibdev))
1947                 goto err_class;
1948         if (class_device_create_file(&host->class_dev, &class_device_attr_port))
1949                 goto err_class;
1950
1951         return host;
1952
1953 err_class:
1954         class_device_unregister(&host->class_dev);
1955
1956 free_host:
1957         kfree(host);
1958
1959         return NULL;
1960 }
1961
1962 static void srp_add_one(struct ib_device *device)
1963 {
1964         struct srp_device *srp_dev;
1965         struct ib_device_attr *dev_attr;
1966         struct ib_fmr_pool_param fmr_param;
1967         struct srp_host *host;
1968         int s, e, p;
1969
1970         dev_attr = kmalloc(sizeof *dev_attr, GFP_KERNEL);
1971         if (!dev_attr)
1972                 return;
1973
1974         if (ib_query_device(device, dev_attr)) {
1975                 printk(KERN_WARNING PFX "Query device failed for %s\n",
1976                        device->name);
1977                 goto free_attr;
1978         }
1979
1980         srp_dev = kmalloc(sizeof *srp_dev, GFP_KERNEL);
1981         if (!srp_dev)
1982                 goto free_attr;
1983
1984         /*
1985          * Use the smallest page size supported by the HCA, down to a
1986          * minimum of 512 bytes (which is the smallest sector that a
1987          * SCSI command will ever carry).
1988          */
1989         srp_dev->fmr_page_shift = max(9, ffs(dev_attr->page_size_cap) - 1);
1990         srp_dev->fmr_page_size  = 1 << srp_dev->fmr_page_shift;
1991         srp_dev->fmr_page_mask  = ~((u64) srp_dev->fmr_page_size - 1);
1992
1993         INIT_LIST_HEAD(&srp_dev->dev_list);
1994
1995         srp_dev->dev = device;
1996         srp_dev->pd  = ib_alloc_pd(device);
1997         if (IS_ERR(srp_dev->pd))
1998                 goto free_dev;
1999
2000         srp_dev->mr = ib_get_dma_mr(srp_dev->pd,
2001                                     IB_ACCESS_LOCAL_WRITE |
2002                                     IB_ACCESS_REMOTE_READ |
2003                                     IB_ACCESS_REMOTE_WRITE);
2004         if (IS_ERR(srp_dev->mr))
2005                 goto err_pd;
2006
2007         memset(&fmr_param, 0, sizeof fmr_param);
2008         fmr_param.pool_size         = SRP_FMR_POOL_SIZE;
2009         fmr_param.dirty_watermark   = SRP_FMR_DIRTY_SIZE;
2010         fmr_param.cache             = 1;
2011         fmr_param.max_pages_per_fmr = SRP_FMR_SIZE;
2012         fmr_param.page_shift        = srp_dev->fmr_page_shift;
2013         fmr_param.access            = (IB_ACCESS_LOCAL_WRITE |
2014                                        IB_ACCESS_REMOTE_WRITE |
2015                                        IB_ACCESS_REMOTE_READ);
2016
2017         srp_dev->fmr_pool = ib_create_fmr_pool(srp_dev->pd, &fmr_param);
2018         if (IS_ERR(srp_dev->fmr_pool))
2019                 srp_dev->fmr_pool = NULL;
2020
2021         if (device->node_type == RDMA_NODE_IB_SWITCH) {
2022                 s = 0;
2023                 e = 0;
2024         } else {
2025                 s = 1;
2026                 e = device->phys_port_cnt;
2027         }
2028
2029         for (p = s; p <= e; ++p) {
2030                 host = srp_add_port(srp_dev, p);
2031                 if (host)
2032                         list_add_tail(&host->list, &srp_dev->dev_list);
2033         }
2034
2035         ib_set_client_data(device, &srp_client, srp_dev);
2036
2037         goto free_attr;
2038
2039 err_pd:
2040         ib_dealloc_pd(srp_dev->pd);
2041
2042 free_dev:
2043         kfree(srp_dev);
2044
2045 free_attr:
2046         kfree(dev_attr);
2047 }
2048
2049 static void srp_remove_one(struct ib_device *device)
2050 {
2051         struct srp_device *srp_dev;
2052         struct srp_host *host, *tmp_host;
2053         LIST_HEAD(target_list);
2054         struct srp_target_port *target, *tmp_target;
2055
2056         srp_dev = ib_get_client_data(device, &srp_client);
2057
2058         list_for_each_entry_safe(host, tmp_host, &srp_dev->dev_list, list) {
2059                 class_device_unregister(&host->class_dev);
2060                 /*
2061                  * Wait for the sysfs entry to go away, so that no new
2062                  * target ports can be created.
2063                  */
2064                 wait_for_completion(&host->released);
2065
2066                 /*
2067                  * Mark all target ports as removed, so we stop queueing
2068                  * commands and don't try to reconnect.
2069                  */
2070                 spin_lock(&host->target_lock);
2071                 list_for_each_entry(target, &host->target_list, list) {
2072                         spin_lock_irq(target->scsi_host->host_lock);
2073                         target->state = SRP_TARGET_REMOVED;
2074                         spin_unlock_irq(target->scsi_host->host_lock);
2075                 }
2076                 spin_unlock(&host->target_lock);
2077
2078                 /*
2079                  * Wait for any reconnection tasks that may have
2080                  * started before we marked our target ports as
2081                  * removed, and any target port removal tasks.
2082                  */
2083                 flush_scheduled_work();
2084
2085                 list_for_each_entry_safe(target, tmp_target,
2086                                          &host->target_list, list) {
2087                         srp_remove_host(target->scsi_host);
2088                         scsi_remove_host(target->scsi_host);
2089                         srp_disconnect_target(target);
2090                         ib_destroy_cm_id(target->cm_id);
2091                         srp_free_target_ib(target);
2092                         scsi_host_put(target->scsi_host);
2093                 }
2094
2095                 kfree(host);
2096         }
2097
2098         if (srp_dev->fmr_pool)
2099                 ib_destroy_fmr_pool(srp_dev->fmr_pool);
2100         ib_dereg_mr(srp_dev->mr);
2101         ib_dealloc_pd(srp_dev->pd);
2102
2103         kfree(srp_dev);
2104 }
2105
2106 static struct srp_function_template ib_srp_transport_functions = {
2107 };
2108
2109 static int __init srp_init_module(void)
2110 {
2111         int ret;
2112
2113         ib_srp_transport_template =
2114                 srp_attach_transport(&ib_srp_transport_functions);
2115         if (!ib_srp_transport_template)
2116                 return -ENOMEM;
2117
2118         srp_template.sg_tablesize = srp_sg_tablesize;
2119         srp_max_iu_len = (sizeof (struct srp_cmd) +
2120                           sizeof (struct srp_indirect_buf) +
2121                           srp_sg_tablesize * 16);
2122
2123         ret = class_register(&srp_class);
2124         if (ret) {
2125                 printk(KERN_ERR PFX "couldn't register class infiniband_srp\n");
2126                 srp_release_transport(ib_srp_transport_template);
2127                 return ret;
2128         }
2129
2130         ib_sa_register_client(&srp_sa_client);
2131
2132         ret = ib_register_client(&srp_client);
2133         if (ret) {
2134                 printk(KERN_ERR PFX "couldn't register IB client\n");
2135                 srp_release_transport(ib_srp_transport_template);
2136                 ib_sa_unregister_client(&srp_sa_client);
2137                 class_unregister(&srp_class);
2138                 return ret;
2139         }
2140
2141         return 0;
2142 }
2143
2144 static void __exit srp_cleanup_module(void)
2145 {
2146         ib_unregister_client(&srp_client);
2147         ib_sa_unregister_client(&srp_sa_client);
2148         class_unregister(&srp_class);
2149         srp_release_transport(ib_srp_transport_template);
2150 }
2151
2152 module_init(srp_init_module);
2153 module_exit(srp_cleanup_module);