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