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