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