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