IB/srp: consolidate state change code
[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 bool srp_change_state(struct srp_target_port *target,
445                             enum srp_target_state old,
446                             enum srp_target_state new)
447 {
448         bool changed = false;
449
450         spin_lock_irq(target->scsi_host->host_lock);
451         if (target->state == old) {
452                 target->state = new;
453                 changed = true;
454         }
455         spin_unlock_irq(target->scsi_host->host_lock);
456         return changed;
457 }
458
459 static void srp_remove_work(struct work_struct *work)
460 {
461         struct srp_target_port *target =
462                 container_of(work, struct srp_target_port, work);
463
464         if (!srp_change_state(target, SRP_TARGET_DEAD, SRP_TARGET_REMOVED))
465                 return;
466
467         spin_lock(&target->srp_host->target_lock);
468         list_del(&target->list);
469         spin_unlock(&target->srp_host->target_lock);
470
471         srp_remove_host(target->scsi_host);
472         scsi_remove_host(target->scsi_host);
473         ib_destroy_cm_id(target->cm_id);
474         srp_free_target_ib(target);
475         scsi_host_put(target->scsi_host);
476 }
477
478 static int srp_connect_target(struct srp_target_port *target)
479 {
480         int retries = 3;
481         int ret;
482
483         ret = srp_lookup_path(target);
484         if (ret)
485                 return ret;
486
487         while (1) {
488                 init_completion(&target->done);
489                 ret = srp_send_req(target);
490                 if (ret)
491                         return ret;
492                 wait_for_completion(&target->done);
493
494                 /*
495                  * The CM event handling code will set status to
496                  * SRP_PORT_REDIRECT if we get a port redirect REJ
497                  * back, or SRP_DLID_REDIRECT if we get a lid/qp
498                  * redirect REJ back.
499                  */
500                 switch (target->status) {
501                 case 0:
502                         return 0;
503
504                 case SRP_PORT_REDIRECT:
505                         ret = srp_lookup_path(target);
506                         if (ret)
507                                 return ret;
508                         break;
509
510                 case SRP_DLID_REDIRECT:
511                         break;
512
513                 case SRP_STALE_CONN:
514                         /* Our current CM id was stale, and is now in timewait.
515                          * Try to reconnect with a new one.
516                          */
517                         if (!retries-- || srp_new_cm_id(target)) {
518                                 shost_printk(KERN_ERR, target->scsi_host, PFX
519                                              "giving up on stale connection\n");
520                                 target->status = -ECONNRESET;
521                                 return target->status;
522                         }
523
524                         shost_printk(KERN_ERR, target->scsi_host, PFX
525                                      "retrying stale connection\n");
526                         break;
527
528                 default:
529                         return target->status;
530                 }
531         }
532 }
533
534 static void srp_unmap_data(struct scsi_cmnd *scmnd,
535                            struct srp_target_port *target,
536                            struct srp_request *req)
537 {
538         if (!scsi_sglist(scmnd) ||
539             (scmnd->sc_data_direction != DMA_TO_DEVICE &&
540              scmnd->sc_data_direction != DMA_FROM_DEVICE))
541                 return;
542
543         if (req->fmr) {
544                 ib_fmr_pool_unmap(req->fmr);
545                 req->fmr = NULL;
546         }
547
548         ib_dma_unmap_sg(target->srp_host->srp_dev->dev, scsi_sglist(scmnd),
549                         scsi_sg_count(scmnd), scmnd->sc_data_direction);
550 }
551
552 static void srp_remove_req(struct srp_target_port *target, struct srp_request *req)
553 {
554         srp_unmap_data(req->scmnd, target, req);
555         req->scmnd = NULL;
556         list_move_tail(&req->list, &target->free_reqs);
557 }
558
559 static void srp_reset_req(struct srp_target_port *target, struct srp_request *req)
560 {
561         req->scmnd->result = DID_RESET << 16;
562         req->scmnd->scsi_done(req->scmnd);
563         srp_remove_req(target, req);
564 }
565
566 static int srp_reconnect_target(struct srp_target_port *target)
567 {
568         struct ib_qp_attr qp_attr;
569         struct srp_request *req, *tmp;
570         struct ib_wc wc;
571         int ret;
572
573         if (!srp_change_state(target, SRP_TARGET_LIVE, SRP_TARGET_CONNECTING))
574                 return -EAGAIN;
575
576         srp_disconnect_target(target);
577         /*
578          * Now get a new local CM ID so that we avoid confusing the
579          * target in case things are really fouled up.
580          */
581         ret = srp_new_cm_id(target);
582         if (ret)
583                 goto err;
584
585         qp_attr.qp_state = IB_QPS_RESET;
586         ret = ib_modify_qp(target->qp, &qp_attr, IB_QP_STATE);
587         if (ret)
588                 goto err;
589
590         ret = srp_init_qp(target, target->qp);
591         if (ret)
592                 goto err;
593
594         while (ib_poll_cq(target->recv_cq, 1, &wc) > 0)
595                 ; /* nothing */
596         while (ib_poll_cq(target->send_cq, 1, &wc) > 0)
597                 ; /* nothing */
598
599         spin_lock_irq(target->scsi_host->host_lock);
600         list_for_each_entry_safe(req, tmp, &target->req_queue, list)
601                 srp_reset_req(target, req);
602         spin_unlock_irq(target->scsi_host->host_lock);
603
604         target->rx_head  = 0;
605         target->tx_head  = 0;
606         target->tx_tail  = 0;
607
608         target->qp_in_error = 0;
609         ret = srp_connect_target(target);
610         if (ret)
611                 goto err;
612
613         if (!srp_change_state(target, SRP_TARGET_CONNECTING, SRP_TARGET_LIVE))
614                 ret = -EAGAIN;
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
625          * are in the context of the SCSI error handler now, which
626          * will deadlock if we call scsi_remove_host().
627          *
628          * Schedule our work inside the lock to avoid a race with
629          * the flush_scheduled_work() in srp_remove_one().
630          */
631         spin_lock_irq(target->scsi_host->host_lock);
632         if (target->state == SRP_TARGET_CONNECTING) {
633                 target->state = SRP_TARGET_DEAD;
634                 INIT_WORK(&target->work, srp_remove_work);
635                 schedule_work(&target->work);
636         }
637         spin_unlock_irq(target->scsi_host->host_lock);
638
639         return ret;
640 }
641
642 static int srp_map_fmr(struct srp_target_port *target, struct scatterlist *scat,
643                        int sg_cnt, struct srp_request *req,
644                        struct srp_direct_buf *buf)
645 {
646         u64 io_addr = 0;
647         u64 *dma_pages;
648         u32 len;
649         int page_cnt;
650         int i, j;
651         int ret;
652         struct srp_device *dev = target->srp_host->srp_dev;
653         struct ib_device *ibdev = dev->dev;
654         struct scatterlist *sg;
655
656         if (!dev->fmr_pool)
657                 return -ENODEV;
658
659         if (srp_target_is_mellanox(target) &&
660             (ib_sg_dma_address(ibdev, &scat[0]) & ~dev->fmr_page_mask))
661                 return -EINVAL;
662
663         len = page_cnt = 0;
664         scsi_for_each_sg(req->scmnd, sg, sg_cnt, i) {
665                 unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
666
667                 if (ib_sg_dma_address(ibdev, sg) & ~dev->fmr_page_mask) {
668                         if (i > 0)
669                                 return -EINVAL;
670                         else
671                                 ++page_cnt;
672                 }
673                 if ((ib_sg_dma_address(ibdev, sg) + dma_len) &
674                     ~dev->fmr_page_mask) {
675                         if (i < sg_cnt - 1)
676                                 return -EINVAL;
677                         else
678                                 ++page_cnt;
679                 }
680
681                 len += dma_len;
682         }
683
684         page_cnt += len >> dev->fmr_page_shift;
685         if (page_cnt > SRP_FMR_SIZE)
686                 return -ENOMEM;
687
688         dma_pages = kmalloc(sizeof (u64) * page_cnt, GFP_ATOMIC);
689         if (!dma_pages)
690                 return -ENOMEM;
691
692         page_cnt = 0;
693         scsi_for_each_sg(req->scmnd, sg, sg_cnt, i) {
694                 unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
695
696                 for (j = 0; j < dma_len; j += dev->fmr_page_size)
697                         dma_pages[page_cnt++] =
698                                 (ib_sg_dma_address(ibdev, sg) &
699                                  dev->fmr_page_mask) + j;
700         }
701
702         req->fmr = ib_fmr_pool_map_phys(dev->fmr_pool,
703                                         dma_pages, page_cnt, io_addr);
704         if (IS_ERR(req->fmr)) {
705                 ret = PTR_ERR(req->fmr);
706                 req->fmr = NULL;
707                 goto out;
708         }
709
710         buf->va  = cpu_to_be64(ib_sg_dma_address(ibdev, &scat[0]) &
711                                ~dev->fmr_page_mask);
712         buf->key = cpu_to_be32(req->fmr->fmr->rkey);
713         buf->len = cpu_to_be32(len);
714
715         ret = 0;
716
717 out:
718         kfree(dma_pages);
719
720         return ret;
721 }
722
723 static int srp_map_data(struct scsi_cmnd *scmnd, struct srp_target_port *target,
724                         struct srp_request *req)
725 {
726         struct scatterlist *scat;
727         struct srp_cmd *cmd = req->cmd->buf;
728         int len, nents, count;
729         u8 fmt = SRP_DATA_DESC_DIRECT;
730         struct srp_device *dev;
731         struct ib_device *ibdev;
732
733         if (!scsi_sglist(scmnd) || scmnd->sc_data_direction == DMA_NONE)
734                 return sizeof (struct srp_cmd);
735
736         if (scmnd->sc_data_direction != DMA_FROM_DEVICE &&
737             scmnd->sc_data_direction != DMA_TO_DEVICE) {
738                 shost_printk(KERN_WARNING, target->scsi_host,
739                              PFX "Unhandled data direction %d\n",
740                              scmnd->sc_data_direction);
741                 return -EINVAL;
742         }
743
744         nents = scsi_sg_count(scmnd);
745         scat  = scsi_sglist(scmnd);
746
747         dev = target->srp_host->srp_dev;
748         ibdev = dev->dev;
749
750         count = ib_dma_map_sg(ibdev, scat, nents, scmnd->sc_data_direction);
751
752         fmt = SRP_DATA_DESC_DIRECT;
753         len = sizeof (struct srp_cmd) + sizeof (struct srp_direct_buf);
754
755         if (count == 1) {
756                 /*
757                  * The midlayer only generated a single gather/scatter
758                  * entry, or DMA mapping coalesced everything to a
759                  * single entry.  So a direct descriptor along with
760                  * the DMA MR suffices.
761                  */
762                 struct srp_direct_buf *buf = (void *) cmd->add_data;
763
764                 buf->va  = cpu_to_be64(ib_sg_dma_address(ibdev, scat));
765                 buf->key = cpu_to_be32(dev->mr->rkey);
766                 buf->len = cpu_to_be32(ib_sg_dma_len(ibdev, scat));
767         } else if (srp_map_fmr(target, scat, count, req,
768                                (void *) cmd->add_data)) {
769                 /*
770                  * FMR mapping failed, and the scatterlist has more
771                  * than one entry.  Generate an indirect memory
772                  * descriptor.
773                  */
774                 struct srp_indirect_buf *buf = (void *) cmd->add_data;
775                 struct scatterlist *sg;
776                 u32 datalen = 0;
777                 int i;
778
779                 fmt = SRP_DATA_DESC_INDIRECT;
780                 len = sizeof (struct srp_cmd) +
781                         sizeof (struct srp_indirect_buf) +
782                         count * sizeof (struct srp_direct_buf);
783
784                 scsi_for_each_sg(scmnd, sg, count, i) {
785                         unsigned int dma_len = ib_sg_dma_len(ibdev, sg);
786
787                         buf->desc_list[i].va  =
788                                 cpu_to_be64(ib_sg_dma_address(ibdev, sg));
789                         buf->desc_list[i].key =
790                                 cpu_to_be32(dev->mr->rkey);
791                         buf->desc_list[i].len = cpu_to_be32(dma_len);
792                         datalen += dma_len;
793                 }
794
795                 if (scmnd->sc_data_direction == DMA_TO_DEVICE)
796                         cmd->data_out_desc_cnt = count;
797                 else
798                         cmd->data_in_desc_cnt = count;
799
800                 buf->table_desc.va  =
801                         cpu_to_be64(req->cmd->dma + sizeof *cmd + sizeof *buf);
802                 buf->table_desc.key =
803                         cpu_to_be32(target->srp_host->srp_dev->mr->rkey);
804                 buf->table_desc.len =
805                         cpu_to_be32(count * sizeof (struct srp_direct_buf));
806
807                 buf->len = cpu_to_be32(datalen);
808         }
809
810         if (scmnd->sc_data_direction == DMA_TO_DEVICE)
811                 cmd->buf_fmt = fmt << 4;
812         else
813                 cmd->buf_fmt = fmt;
814
815         return len;
816 }
817
818 /*
819  * Must be called with target->scsi_host->host_lock held to protect
820  * req_lim and tx_head.  Lock cannot be dropped between call here and
821  * call to __srp_post_send().
822  *
823  * Note:
824  * An upper limit for the number of allocated information units for each
825  * request type is:
826  * - SRP_IU_CMD: SRP_CMD_SQ_SIZE, since the SCSI mid-layer never queues
827  *   more than Scsi_Host.can_queue requests.
828  * - SRP_IU_TSK_MGMT: SRP_TSK_MGMT_SQ_SIZE.
829  * - SRP_IU_RSP: 1, since a conforming SRP target never sends more than
830  *   one unanswered SRP request to an initiator.
831  */
832 static struct srp_iu *__srp_get_tx_iu(struct srp_target_port *target,
833                                       enum srp_iu_type iu_type)
834 {
835         s32 rsv = (iu_type == SRP_IU_TSK_MGMT) ? 0 : SRP_TSK_MGMT_SQ_SIZE;
836         struct srp_iu *iu;
837
838         srp_send_completion(target->send_cq, target);
839
840         if (target->tx_head - target->tx_tail >= SRP_SQ_SIZE)
841                 return NULL;
842
843         /* Initiator responses to target requests do not consume credits */
844         if (target->req_lim <= rsv && iu_type != SRP_IU_RSP) {
845                 ++target->zero_req_lim;
846                 return NULL;
847         }
848
849         iu = target->tx_ring[target->tx_head & SRP_SQ_MASK];
850         iu->type = iu_type;
851         return iu;
852 }
853
854 /*
855  * Must be called with target->scsi_host->host_lock held to protect
856  * req_lim and tx_head.
857  */
858 static int __srp_post_send(struct srp_target_port *target,
859                            struct srp_iu *iu, int len)
860 {
861         struct ib_sge list;
862         struct ib_send_wr wr, *bad_wr;
863         int ret = 0;
864
865         list.addr   = iu->dma;
866         list.length = len;
867         list.lkey   = target->srp_host->srp_dev->mr->lkey;
868
869         wr.next       = NULL;
870         wr.wr_id      = target->tx_head & SRP_SQ_MASK;
871         wr.sg_list    = &list;
872         wr.num_sge    = 1;
873         wr.opcode     = IB_WR_SEND;
874         wr.send_flags = IB_SEND_SIGNALED;
875
876         ret = ib_post_send(target->qp, &wr, &bad_wr);
877
878         if (!ret) {
879                 ++target->tx_head;
880                 if (iu->type != SRP_IU_RSP)
881                         --target->req_lim;
882         }
883
884         return ret;
885 }
886
887 static int srp_post_recv(struct srp_target_port *target)
888 {
889         unsigned long flags;
890         struct srp_iu *iu;
891         struct ib_sge list;
892         struct ib_recv_wr wr, *bad_wr;
893         unsigned int next;
894         int ret;
895
896         spin_lock_irqsave(target->scsi_host->host_lock, flags);
897
898         next     = target->rx_head & SRP_RQ_MASK;
899         wr.wr_id = next;
900         iu       = target->rx_ring[next];
901
902         list.addr   = iu->dma;
903         list.length = iu->size;
904         list.lkey   = target->srp_host->srp_dev->mr->lkey;
905
906         wr.next     = NULL;
907         wr.sg_list  = &list;
908         wr.num_sge  = 1;
909
910         ret = ib_post_recv(target->qp, &wr, &bad_wr);
911         if (!ret)
912                 ++target->rx_head;
913
914         spin_unlock_irqrestore(target->scsi_host->host_lock, flags);
915
916         return ret;
917 }
918
919 static void srp_process_rsp(struct srp_target_port *target, struct srp_rsp *rsp)
920 {
921         struct srp_request *req;
922         struct scsi_cmnd *scmnd;
923         unsigned long flags;
924         s32 delta;
925
926         delta = (s32) be32_to_cpu(rsp->req_lim_delta);
927
928         spin_lock_irqsave(target->scsi_host->host_lock, flags);
929
930         target->req_lim += delta;
931
932         if (unlikely(rsp->tag & SRP_TAG_TSK_MGMT)) {
933                 target->tsk_mgmt_status = -1;
934                 if (be32_to_cpu(rsp->resp_data_len) >= 4)
935                         target->tsk_mgmt_status = rsp->data[3];
936                 complete(&target->tsk_mgmt_done);
937         } else {
938                 req = &target->req_ring[rsp->tag];
939                 scmnd = req->scmnd;
940                 if (!scmnd)
941                         shost_printk(KERN_ERR, target->scsi_host,
942                                      "Null scmnd for RSP w/tag %016llx\n",
943                                      (unsigned long long) rsp->tag);
944                 scmnd->result = rsp->status;
945
946                 if (rsp->flags & SRP_RSP_FLAG_SNSVALID) {
947                         memcpy(scmnd->sense_buffer, rsp->data +
948                                be32_to_cpu(rsp->resp_data_len),
949                                min_t(int, be32_to_cpu(rsp->sense_data_len),
950                                      SCSI_SENSE_BUFFERSIZE));
951                 }
952
953                 if (rsp->flags & (SRP_RSP_FLAG_DOOVER | SRP_RSP_FLAG_DOUNDER))
954                         scsi_set_resid(scmnd, be32_to_cpu(rsp->data_out_res_cnt));
955                 else if (rsp->flags & (SRP_RSP_FLAG_DIOVER | SRP_RSP_FLAG_DIUNDER))
956                         scsi_set_resid(scmnd, be32_to_cpu(rsp->data_in_res_cnt));
957
958                 scmnd->host_scribble = NULL;
959                 scmnd->scsi_done(scmnd);
960                 srp_remove_req(target, req);
961         }
962
963         spin_unlock_irqrestore(target->scsi_host->host_lock, flags);
964 }
965
966 static int srp_response_common(struct srp_target_port *target, s32 req_delta,
967                                void *rsp, int len)
968 {
969         struct ib_device *dev;
970         unsigned long flags;
971         struct srp_iu *iu;
972         int err = 1;
973
974         dev = target->srp_host->srp_dev->dev;
975
976         spin_lock_irqsave(target->scsi_host->host_lock, flags);
977         target->req_lim += req_delta;
978
979         iu = __srp_get_tx_iu(target, SRP_IU_RSP);
980         if (!iu) {
981                 shost_printk(KERN_ERR, target->scsi_host, PFX
982                              "no IU available to send response\n");
983                 goto out;
984         }
985
986         ib_dma_sync_single_for_cpu(dev, iu->dma, len, DMA_TO_DEVICE);
987         memcpy(iu->buf, rsp, len);
988         ib_dma_sync_single_for_device(dev, iu->dma, len, DMA_TO_DEVICE);
989
990         err = __srp_post_send(target, iu, len);
991         if (err)
992                 shost_printk(KERN_ERR, target->scsi_host, PFX
993                              "unable to post response: %d\n", err);
994
995 out:
996         spin_unlock_irqrestore(target->scsi_host->host_lock, flags);
997         return err;
998 }
999
1000 static void srp_process_cred_req(struct srp_target_port *target,
1001                                  struct srp_cred_req *req)
1002 {
1003         struct srp_cred_rsp rsp = {
1004                 .opcode = SRP_CRED_RSP,
1005                 .tag = req->tag,
1006         };
1007         s32 delta = be32_to_cpu(req->req_lim_delta);
1008
1009         if (srp_response_common(target, delta, &rsp, sizeof rsp))
1010                 shost_printk(KERN_ERR, target->scsi_host, PFX
1011                              "problems processing SRP_CRED_REQ\n");
1012 }
1013
1014 static void srp_process_aer_req(struct srp_target_port *target,
1015                                 struct srp_aer_req *req)
1016 {
1017         struct srp_aer_rsp rsp = {
1018                 .opcode = SRP_AER_RSP,
1019                 .tag = req->tag,
1020         };
1021         s32 delta = be32_to_cpu(req->req_lim_delta);
1022
1023         shost_printk(KERN_ERR, target->scsi_host, PFX
1024                      "ignoring AER for LUN %llu\n", be64_to_cpu(req->lun));
1025
1026         if (srp_response_common(target, delta, &rsp, sizeof rsp))
1027                 shost_printk(KERN_ERR, target->scsi_host, PFX
1028                              "problems processing SRP_AER_REQ\n");
1029 }
1030
1031 static void srp_handle_recv(struct srp_target_port *target, struct ib_wc *wc)
1032 {
1033         struct ib_device *dev;
1034         struct srp_iu *iu;
1035         int res;
1036         u8 opcode;
1037
1038         iu = target->rx_ring[wc->wr_id];
1039
1040         dev = target->srp_host->srp_dev->dev;
1041         ib_dma_sync_single_for_cpu(dev, iu->dma, target->max_ti_iu_len,
1042                                    DMA_FROM_DEVICE);
1043
1044         opcode = *(u8 *) iu->buf;
1045
1046         if (0) {
1047                 shost_printk(KERN_ERR, target->scsi_host,
1048                              PFX "recv completion, opcode 0x%02x\n", opcode);
1049                 print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 8, 1,
1050                                iu->buf, wc->byte_len, true);
1051         }
1052
1053         switch (opcode) {
1054         case SRP_RSP:
1055                 srp_process_rsp(target, iu->buf);
1056                 break;
1057
1058         case SRP_CRED_REQ:
1059                 srp_process_cred_req(target, iu->buf);
1060                 break;
1061
1062         case SRP_AER_REQ:
1063                 srp_process_aer_req(target, iu->buf);
1064                 break;
1065
1066         case SRP_T_LOGOUT:
1067                 /* XXX Handle target logout */
1068                 shost_printk(KERN_WARNING, target->scsi_host,
1069                              PFX "Got target logout request\n");
1070                 break;
1071
1072         default:
1073                 shost_printk(KERN_WARNING, target->scsi_host,
1074                              PFX "Unhandled SRP opcode 0x%02x\n", opcode);
1075                 break;
1076         }
1077
1078         ib_dma_sync_single_for_device(dev, iu->dma, target->max_ti_iu_len,
1079                                       DMA_FROM_DEVICE);
1080
1081         res = srp_post_recv(target);
1082         if (res != 0)
1083                 shost_printk(KERN_ERR, target->scsi_host,
1084                              PFX "Recv failed with error code %d\n", res);
1085 }
1086
1087 static void srp_recv_completion(struct ib_cq *cq, void *target_ptr)
1088 {
1089         struct srp_target_port *target = target_ptr;
1090         struct ib_wc wc;
1091
1092         ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
1093         while (ib_poll_cq(cq, 1, &wc) > 0) {
1094                 if (wc.status) {
1095                         shost_printk(KERN_ERR, target->scsi_host,
1096                                      PFX "failed receive status %d\n",
1097                                      wc.status);
1098                         target->qp_in_error = 1;
1099                         break;
1100                 }
1101
1102                 srp_handle_recv(target, &wc);
1103         }
1104 }
1105
1106 static void srp_send_completion(struct ib_cq *cq, void *target_ptr)
1107 {
1108         struct srp_target_port *target = target_ptr;
1109         struct ib_wc wc;
1110
1111         while (ib_poll_cq(cq, 1, &wc) > 0) {
1112                 if (wc.status) {
1113                         shost_printk(KERN_ERR, target->scsi_host,
1114                                      PFX "failed send status %d\n",
1115                                      wc.status);
1116                         target->qp_in_error = 1;
1117                         break;
1118                 }
1119
1120                 ++target->tx_tail;
1121         }
1122 }
1123
1124 static int srp_queuecommand_lck(struct scsi_cmnd *scmnd,
1125                             void (*done)(struct scsi_cmnd *))
1126 {
1127         struct srp_target_port *target = host_to_target(scmnd->device->host);
1128         struct srp_request *req;
1129         struct srp_iu *iu;
1130         struct srp_cmd *cmd;
1131         struct ib_device *dev;
1132         int len;
1133
1134         if (target->state == SRP_TARGET_CONNECTING)
1135                 goto err;
1136
1137         if (target->state == SRP_TARGET_DEAD ||
1138             target->state == SRP_TARGET_REMOVED) {
1139                 scmnd->result = DID_BAD_TARGET << 16;
1140                 done(scmnd);
1141                 return 0;
1142         }
1143
1144         iu = __srp_get_tx_iu(target, SRP_IU_CMD);
1145         if (!iu)
1146                 goto err;
1147
1148         dev = target->srp_host->srp_dev->dev;
1149         ib_dma_sync_single_for_cpu(dev, iu->dma, srp_max_iu_len,
1150                                    DMA_TO_DEVICE);
1151
1152         req = list_first_entry(&target->free_reqs, struct srp_request, list);
1153
1154         scmnd->scsi_done     = done;
1155         scmnd->result        = 0;
1156         scmnd->host_scribble = (void *) req;
1157
1158         cmd = iu->buf;
1159         memset(cmd, 0, sizeof *cmd);
1160
1161         cmd->opcode = SRP_CMD;
1162         cmd->lun    = cpu_to_be64((u64) scmnd->device->lun << 48);
1163         cmd->tag    = req->index;
1164         memcpy(cmd->cdb, scmnd->cmnd, scmnd->cmd_len);
1165
1166         req->scmnd    = scmnd;
1167         req->cmd      = iu;
1168
1169         len = srp_map_data(scmnd, target, req);
1170         if (len < 0) {
1171                 shost_printk(KERN_ERR, target->scsi_host,
1172                              PFX "Failed to map data\n");
1173                 goto err;
1174         }
1175
1176         ib_dma_sync_single_for_device(dev, iu->dma, srp_max_iu_len,
1177                                       DMA_TO_DEVICE);
1178
1179         if (__srp_post_send(target, iu, len)) {
1180                 shost_printk(KERN_ERR, target->scsi_host, PFX "Send failed\n");
1181                 goto err_unmap;
1182         }
1183
1184         list_move_tail(&req->list, &target->req_queue);
1185
1186         return 0;
1187
1188 err_unmap:
1189         srp_unmap_data(scmnd, target, req);
1190
1191 err:
1192         return SCSI_MLQUEUE_HOST_BUSY;
1193 }
1194
1195 static DEF_SCSI_QCMD(srp_queuecommand)
1196
1197 static int srp_alloc_iu_bufs(struct srp_target_port *target)
1198 {
1199         int i;
1200
1201         for (i = 0; i < SRP_RQ_SIZE; ++i) {
1202                 target->rx_ring[i] = srp_alloc_iu(target->srp_host,
1203                                                   target->max_ti_iu_len,
1204                                                   GFP_KERNEL, DMA_FROM_DEVICE);
1205                 if (!target->rx_ring[i])
1206                         goto err;
1207         }
1208
1209         for (i = 0; i < SRP_SQ_SIZE; ++i) {
1210                 target->tx_ring[i] = srp_alloc_iu(target->srp_host,
1211                                                   srp_max_iu_len,
1212                                                   GFP_KERNEL, DMA_TO_DEVICE);
1213                 if (!target->tx_ring[i])
1214                         goto err;
1215         }
1216
1217         return 0;
1218
1219 err:
1220         for (i = 0; i < SRP_RQ_SIZE; ++i) {
1221                 srp_free_iu(target->srp_host, target->rx_ring[i]);
1222                 target->rx_ring[i] = NULL;
1223         }
1224
1225         for (i = 0; i < SRP_SQ_SIZE; ++i) {
1226                 srp_free_iu(target->srp_host, target->tx_ring[i]);
1227                 target->tx_ring[i] = NULL;
1228         }
1229
1230         return -ENOMEM;
1231 }
1232
1233 static void srp_cm_rej_handler(struct ib_cm_id *cm_id,
1234                                struct ib_cm_event *event,
1235                                struct srp_target_port *target)
1236 {
1237         struct Scsi_Host *shost = target->scsi_host;
1238         struct ib_class_port_info *cpi;
1239         int opcode;
1240
1241         switch (event->param.rej_rcvd.reason) {
1242         case IB_CM_REJ_PORT_CM_REDIRECT:
1243                 cpi = event->param.rej_rcvd.ari;
1244                 target->path.dlid = cpi->redirect_lid;
1245                 target->path.pkey = cpi->redirect_pkey;
1246                 cm_id->remote_cm_qpn = be32_to_cpu(cpi->redirect_qp) & 0x00ffffff;
1247                 memcpy(target->path.dgid.raw, cpi->redirect_gid, 16);
1248
1249                 target->status = target->path.dlid ?
1250                         SRP_DLID_REDIRECT : SRP_PORT_REDIRECT;
1251                 break;
1252
1253         case IB_CM_REJ_PORT_REDIRECT:
1254                 if (srp_target_is_topspin(target)) {
1255                         /*
1256                          * Topspin/Cisco SRP gateways incorrectly send
1257                          * reject reason code 25 when they mean 24
1258                          * (port redirect).
1259                          */
1260                         memcpy(target->path.dgid.raw,
1261                                event->param.rej_rcvd.ari, 16);
1262
1263                         shost_printk(KERN_DEBUG, shost,
1264                                      PFX "Topspin/Cisco redirect to target port GID %016llx%016llx\n",
1265                                      (unsigned long long) be64_to_cpu(target->path.dgid.global.subnet_prefix),
1266                                      (unsigned long long) be64_to_cpu(target->path.dgid.global.interface_id));
1267
1268                         target->status = SRP_PORT_REDIRECT;
1269                 } else {
1270                         shost_printk(KERN_WARNING, shost,
1271                                      "  REJ reason: IB_CM_REJ_PORT_REDIRECT\n");
1272                         target->status = -ECONNRESET;
1273                 }
1274                 break;
1275
1276         case IB_CM_REJ_DUPLICATE_LOCAL_COMM_ID:
1277                 shost_printk(KERN_WARNING, shost,
1278                             "  REJ reason: IB_CM_REJ_DUPLICATE_LOCAL_COMM_ID\n");
1279                 target->status = -ECONNRESET;
1280                 break;
1281
1282         case IB_CM_REJ_CONSUMER_DEFINED:
1283                 opcode = *(u8 *) event->private_data;
1284                 if (opcode == SRP_LOGIN_REJ) {
1285                         struct srp_login_rej *rej = event->private_data;
1286                         u32 reason = be32_to_cpu(rej->reason);
1287
1288                         if (reason == SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE)
1289                                 shost_printk(KERN_WARNING, shost,
1290                                              PFX "SRP_LOGIN_REJ: requested max_it_iu_len too large\n");
1291                         else
1292                                 shost_printk(KERN_WARNING, shost,
1293                                             PFX "SRP LOGIN REJECTED, reason 0x%08x\n", reason);
1294                 } else
1295                         shost_printk(KERN_WARNING, shost,
1296                                      "  REJ reason: IB_CM_REJ_CONSUMER_DEFINED,"
1297                                      " opcode 0x%02x\n", opcode);
1298                 target->status = -ECONNRESET;
1299                 break;
1300
1301         case IB_CM_REJ_STALE_CONN:
1302                 shost_printk(KERN_WARNING, shost, "  REJ reason: stale connection\n");
1303                 target->status = SRP_STALE_CONN;
1304                 break;
1305
1306         default:
1307                 shost_printk(KERN_WARNING, shost, "  REJ reason 0x%x\n",
1308                              event->param.rej_rcvd.reason);
1309                 target->status = -ECONNRESET;
1310         }
1311 }
1312
1313 static int srp_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
1314 {
1315         struct srp_target_port *target = cm_id->context;
1316         struct ib_qp_attr *qp_attr = NULL;
1317         int attr_mask = 0;
1318         int comp = 0;
1319         int opcode = 0;
1320         int i;
1321
1322         switch (event->event) {
1323         case IB_CM_REQ_ERROR:
1324                 shost_printk(KERN_DEBUG, target->scsi_host,
1325                              PFX "Sending CM REQ failed\n");
1326                 comp = 1;
1327                 target->status = -ECONNRESET;
1328                 break;
1329
1330         case IB_CM_REP_RECEIVED:
1331                 comp = 1;
1332                 opcode = *(u8 *) event->private_data;
1333
1334                 if (opcode == SRP_LOGIN_RSP) {
1335                         struct srp_login_rsp *rsp = event->private_data;
1336
1337                         target->max_ti_iu_len = be32_to_cpu(rsp->max_ti_iu_len);
1338                         target->req_lim       = be32_to_cpu(rsp->req_lim_delta);
1339
1340                         /*
1341                          * Reserve credits for task management so we don't
1342                          * bounce requests back to the SCSI mid-layer.
1343                          */
1344                         target->scsi_host->can_queue
1345                                 = min(target->req_lim - SRP_TSK_MGMT_SQ_SIZE,
1346                                       target->scsi_host->can_queue);
1347                 } else {
1348                         shost_printk(KERN_WARNING, target->scsi_host,
1349                                     PFX "Unhandled RSP opcode %#x\n", opcode);
1350                         target->status = -ECONNRESET;
1351                         break;
1352                 }
1353
1354                 if (!target->rx_ring[0]) {
1355                         target->status = srp_alloc_iu_bufs(target);
1356                         if (target->status)
1357                                 break;
1358                 }
1359
1360                 qp_attr = kmalloc(sizeof *qp_attr, GFP_KERNEL);
1361                 if (!qp_attr) {
1362                         target->status = -ENOMEM;
1363                         break;
1364                 }
1365
1366                 qp_attr->qp_state = IB_QPS_RTR;
1367                 target->status = ib_cm_init_qp_attr(cm_id, qp_attr, &attr_mask);
1368                 if (target->status)
1369                         break;
1370
1371                 target->status = ib_modify_qp(target->qp, qp_attr, attr_mask);
1372                 if (target->status)
1373                         break;
1374
1375                 for (i = 0; i < SRP_RQ_SIZE; i++) {
1376                         target->status = srp_post_recv(target);
1377                         if (target->status)
1378                                 break;
1379                 }
1380                 if (target->status)
1381                         break;
1382
1383                 qp_attr->qp_state = IB_QPS_RTS;
1384                 target->status = ib_cm_init_qp_attr(cm_id, qp_attr, &attr_mask);
1385                 if (target->status)
1386                         break;
1387
1388                 target->status = ib_modify_qp(target->qp, qp_attr, attr_mask);
1389                 if (target->status)
1390                         break;
1391
1392                 target->status = ib_send_cm_rtu(cm_id, NULL, 0);
1393                 if (target->status)
1394                         break;
1395
1396                 break;
1397
1398         case IB_CM_REJ_RECEIVED:
1399                 shost_printk(KERN_DEBUG, target->scsi_host, PFX "REJ received\n");
1400                 comp = 1;
1401
1402                 srp_cm_rej_handler(cm_id, event, target);
1403                 break;
1404
1405         case IB_CM_DREQ_RECEIVED:
1406                 shost_printk(KERN_WARNING, target->scsi_host,
1407                              PFX "DREQ received - connection closed\n");
1408                 if (ib_send_cm_drep(cm_id, NULL, 0))
1409                         shost_printk(KERN_ERR, target->scsi_host,
1410                                      PFX "Sending CM DREP failed\n");
1411                 break;
1412
1413         case IB_CM_TIMEWAIT_EXIT:
1414                 shost_printk(KERN_ERR, target->scsi_host,
1415                              PFX "connection closed\n");
1416
1417                 comp = 1;
1418                 target->status = 0;
1419                 break;
1420
1421         case IB_CM_MRA_RECEIVED:
1422         case IB_CM_DREQ_ERROR:
1423         case IB_CM_DREP_RECEIVED:
1424                 break;
1425
1426         default:
1427                 shost_printk(KERN_WARNING, target->scsi_host,
1428                              PFX "Unhandled CM event %d\n", event->event);
1429                 break;
1430         }
1431
1432         if (comp)
1433                 complete(&target->done);
1434
1435         kfree(qp_attr);
1436
1437         return 0;
1438 }
1439
1440 static int srp_send_tsk_mgmt(struct srp_target_port *target,
1441                              u64 req_tag, unsigned int lun, u8 func)
1442 {
1443         struct ib_device *dev = target->srp_host->srp_dev->dev;
1444         struct srp_iu *iu;
1445         struct srp_tsk_mgmt *tsk_mgmt;
1446
1447         spin_lock_irq(target->scsi_host->host_lock);
1448
1449         if (target->state == SRP_TARGET_DEAD ||
1450             target->state == SRP_TARGET_REMOVED)
1451                 goto out;
1452
1453         init_completion(&target->tsk_mgmt_done);
1454
1455         iu = __srp_get_tx_iu(target, SRP_IU_TSK_MGMT);
1456         if (!iu)
1457                 goto out;
1458
1459         ib_dma_sync_single_for_cpu(dev, iu->dma, sizeof *tsk_mgmt,
1460                                    DMA_TO_DEVICE);
1461         tsk_mgmt = iu->buf;
1462         memset(tsk_mgmt, 0, sizeof *tsk_mgmt);
1463
1464         tsk_mgmt->opcode        = SRP_TSK_MGMT;
1465         tsk_mgmt->lun           = cpu_to_be64((u64) lun << 48);
1466         tsk_mgmt->tag           = req_tag | SRP_TAG_TSK_MGMT;
1467         tsk_mgmt->tsk_mgmt_func = func;
1468         tsk_mgmt->task_tag      = req_tag;
1469
1470         ib_dma_sync_single_for_device(dev, iu->dma, sizeof *tsk_mgmt,
1471                                       DMA_TO_DEVICE);
1472         if (__srp_post_send(target, iu, sizeof *tsk_mgmt))
1473                 goto out;
1474
1475         spin_unlock_irq(target->scsi_host->host_lock);
1476
1477         if (!wait_for_completion_timeout(&target->tsk_mgmt_done,
1478                                          msecs_to_jiffies(SRP_ABORT_TIMEOUT_MS)))
1479                 return -1;
1480
1481         return 0;
1482
1483 out:
1484         spin_unlock_irq(target->scsi_host->host_lock);
1485         return -1;
1486 }
1487
1488 static int srp_abort(struct scsi_cmnd *scmnd)
1489 {
1490         struct srp_target_port *target = host_to_target(scmnd->device->host);
1491         struct srp_request *req = (struct srp_request *) scmnd->host_scribble;
1492         int ret = SUCCESS;
1493
1494         shost_printk(KERN_ERR, target->scsi_host, "SRP abort called\n");
1495
1496         if (!req || target->qp_in_error)
1497                 return FAILED;
1498         if (srp_send_tsk_mgmt(target, req->index, scmnd->device->lun,
1499                               SRP_TSK_ABORT_TASK))
1500                 return FAILED;
1501
1502         spin_lock_irq(target->scsi_host->host_lock);
1503
1504         if (req->scmnd) {
1505                 if (!target->tsk_mgmt_status) {
1506                         srp_remove_req(target, req);
1507                         scmnd->result = DID_ABORT << 16;
1508                 } else
1509                         ret = FAILED;
1510         }
1511
1512         spin_unlock_irq(target->scsi_host->host_lock);
1513
1514         return ret;
1515 }
1516
1517 static int srp_reset_device(struct scsi_cmnd *scmnd)
1518 {
1519         struct srp_target_port *target = host_to_target(scmnd->device->host);
1520         struct srp_request *req, *tmp;
1521
1522         shost_printk(KERN_ERR, target->scsi_host, "SRP reset_device called\n");
1523
1524         if (target->qp_in_error)
1525                 return FAILED;
1526         if (srp_send_tsk_mgmt(target, SRP_TAG_NO_REQ, scmnd->device->lun,
1527                               SRP_TSK_LUN_RESET))
1528                 return FAILED;
1529         if (target->tsk_mgmt_status)
1530                 return FAILED;
1531
1532         spin_lock_irq(target->scsi_host->host_lock);
1533
1534         list_for_each_entry_safe(req, tmp, &target->req_queue, list)
1535                 if (req->scmnd && req->scmnd->device == scmnd->device)
1536                         srp_reset_req(target, req);
1537
1538         spin_unlock_irq(target->scsi_host->host_lock);
1539
1540         return SUCCESS;
1541 }
1542
1543 static int srp_reset_host(struct scsi_cmnd *scmnd)
1544 {
1545         struct srp_target_port *target = host_to_target(scmnd->device->host);
1546         int ret = FAILED;
1547
1548         shost_printk(KERN_ERR, target->scsi_host, PFX "SRP reset_host called\n");
1549
1550         if (!srp_reconnect_target(target))
1551                 ret = SUCCESS;
1552
1553         return ret;
1554 }
1555
1556 static ssize_t show_id_ext(struct device *dev, struct device_attribute *attr,
1557                            char *buf)
1558 {
1559         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1560
1561         if (target->state == SRP_TARGET_DEAD ||
1562             target->state == SRP_TARGET_REMOVED)
1563                 return -ENODEV;
1564
1565         return sprintf(buf, "0x%016llx\n",
1566                        (unsigned long long) be64_to_cpu(target->id_ext));
1567 }
1568
1569 static ssize_t show_ioc_guid(struct device *dev, struct device_attribute *attr,
1570                              char *buf)
1571 {
1572         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1573
1574         if (target->state == SRP_TARGET_DEAD ||
1575             target->state == SRP_TARGET_REMOVED)
1576                 return -ENODEV;
1577
1578         return sprintf(buf, "0x%016llx\n",
1579                        (unsigned long long) be64_to_cpu(target->ioc_guid));
1580 }
1581
1582 static ssize_t show_service_id(struct device *dev,
1583                                struct device_attribute *attr, char *buf)
1584 {
1585         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1586
1587         if (target->state == SRP_TARGET_DEAD ||
1588             target->state == SRP_TARGET_REMOVED)
1589                 return -ENODEV;
1590
1591         return sprintf(buf, "0x%016llx\n",
1592                        (unsigned long long) be64_to_cpu(target->service_id));
1593 }
1594
1595 static ssize_t show_pkey(struct device *dev, struct device_attribute *attr,
1596                          char *buf)
1597 {
1598         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1599
1600         if (target->state == SRP_TARGET_DEAD ||
1601             target->state == SRP_TARGET_REMOVED)
1602                 return -ENODEV;
1603
1604         return sprintf(buf, "0x%04x\n", be16_to_cpu(target->path.pkey));
1605 }
1606
1607 static ssize_t show_dgid(struct device *dev, struct device_attribute *attr,
1608                          char *buf)
1609 {
1610         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1611
1612         if (target->state == SRP_TARGET_DEAD ||
1613             target->state == SRP_TARGET_REMOVED)
1614                 return -ENODEV;
1615
1616         return sprintf(buf, "%pI6\n", target->path.dgid.raw);
1617 }
1618
1619 static ssize_t show_orig_dgid(struct device *dev,
1620                               struct device_attribute *attr, char *buf)
1621 {
1622         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1623
1624         if (target->state == SRP_TARGET_DEAD ||
1625             target->state == SRP_TARGET_REMOVED)
1626                 return -ENODEV;
1627
1628         return sprintf(buf, "%pI6\n", target->orig_dgid);
1629 }
1630
1631 static ssize_t show_req_lim(struct device *dev,
1632                             struct device_attribute *attr, char *buf)
1633 {
1634         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1635
1636         if (target->state == SRP_TARGET_DEAD ||
1637             target->state == SRP_TARGET_REMOVED)
1638                 return -ENODEV;
1639
1640         return sprintf(buf, "%d\n", target->req_lim);
1641 }
1642
1643 static ssize_t show_zero_req_lim(struct device *dev,
1644                                  struct device_attribute *attr, char *buf)
1645 {
1646         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1647
1648         if (target->state == SRP_TARGET_DEAD ||
1649             target->state == SRP_TARGET_REMOVED)
1650                 return -ENODEV;
1651
1652         return sprintf(buf, "%d\n", target->zero_req_lim);
1653 }
1654
1655 static ssize_t show_local_ib_port(struct device *dev,
1656                                   struct device_attribute *attr, char *buf)
1657 {
1658         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1659
1660         return sprintf(buf, "%d\n", target->srp_host->port);
1661 }
1662
1663 static ssize_t show_local_ib_device(struct device *dev,
1664                                     struct device_attribute *attr, char *buf)
1665 {
1666         struct srp_target_port *target = host_to_target(class_to_shost(dev));
1667
1668         return sprintf(buf, "%s\n", target->srp_host->srp_dev->dev->name);
1669 }
1670
1671 static DEVICE_ATTR(id_ext,          S_IRUGO, show_id_ext,          NULL);
1672 static DEVICE_ATTR(ioc_guid,        S_IRUGO, show_ioc_guid,        NULL);
1673 static DEVICE_ATTR(service_id,      S_IRUGO, show_service_id,      NULL);
1674 static DEVICE_ATTR(pkey,            S_IRUGO, show_pkey,            NULL);
1675 static DEVICE_ATTR(dgid,            S_IRUGO, show_dgid,            NULL);
1676 static DEVICE_ATTR(orig_dgid,       S_IRUGO, show_orig_dgid,       NULL);
1677 static DEVICE_ATTR(req_lim,         S_IRUGO, show_req_lim,         NULL);
1678 static DEVICE_ATTR(zero_req_lim,    S_IRUGO, show_zero_req_lim,    NULL);
1679 static DEVICE_ATTR(local_ib_port,   S_IRUGO, show_local_ib_port,   NULL);
1680 static DEVICE_ATTR(local_ib_device, S_IRUGO, show_local_ib_device, NULL);
1681
1682 static struct device_attribute *srp_host_attrs[] = {
1683         &dev_attr_id_ext,
1684         &dev_attr_ioc_guid,
1685         &dev_attr_service_id,
1686         &dev_attr_pkey,
1687         &dev_attr_dgid,
1688         &dev_attr_orig_dgid,
1689         &dev_attr_req_lim,
1690         &dev_attr_zero_req_lim,
1691         &dev_attr_local_ib_port,
1692         &dev_attr_local_ib_device,
1693         NULL
1694 };
1695
1696 static struct scsi_host_template srp_template = {
1697         .module                         = THIS_MODULE,
1698         .name                           = "InfiniBand SRP initiator",
1699         .proc_name                      = DRV_NAME,
1700         .info                           = srp_target_info,
1701         .queuecommand                   = srp_queuecommand,
1702         .eh_abort_handler               = srp_abort,
1703         .eh_device_reset_handler        = srp_reset_device,
1704         .eh_host_reset_handler          = srp_reset_host,
1705         .can_queue                      = SRP_CMD_SQ_SIZE,
1706         .this_id                        = -1,
1707         .cmd_per_lun                    = SRP_CMD_SQ_SIZE,
1708         .use_clustering                 = ENABLE_CLUSTERING,
1709         .shost_attrs                    = srp_host_attrs
1710 };
1711
1712 static int srp_add_target(struct srp_host *host, struct srp_target_port *target)
1713 {
1714         struct srp_rport_identifiers ids;
1715         struct srp_rport *rport;
1716
1717         sprintf(target->target_name, "SRP.T10:%016llX",
1718                  (unsigned long long) be64_to_cpu(target->id_ext));
1719
1720         if (scsi_add_host(target->scsi_host, host->srp_dev->dev->dma_device))
1721                 return -ENODEV;
1722
1723         memcpy(ids.port_id, &target->id_ext, 8);
1724         memcpy(ids.port_id + 8, &target->ioc_guid, 8);
1725         ids.roles = SRP_RPORT_ROLE_TARGET;
1726         rport = srp_rport_add(target->scsi_host, &ids);
1727         if (IS_ERR(rport)) {
1728                 scsi_remove_host(target->scsi_host);
1729                 return PTR_ERR(rport);
1730         }
1731
1732         spin_lock(&host->target_lock);
1733         list_add_tail(&target->list, &host->target_list);
1734         spin_unlock(&host->target_lock);
1735
1736         target->state = SRP_TARGET_LIVE;
1737
1738         scsi_scan_target(&target->scsi_host->shost_gendev,
1739                          0, target->scsi_id, SCAN_WILD_CARD, 0);
1740
1741         return 0;
1742 }
1743
1744 static void srp_release_dev(struct device *dev)
1745 {
1746         struct srp_host *host =
1747                 container_of(dev, struct srp_host, dev);
1748
1749         complete(&host->released);
1750 }
1751
1752 static struct class srp_class = {
1753         .name    = "infiniband_srp",
1754         .dev_release = srp_release_dev
1755 };
1756
1757 /*
1758  * Target ports are added by writing
1759  *
1760  *     id_ext=<SRP ID ext>,ioc_guid=<SRP IOC GUID>,dgid=<dest GID>,
1761  *     pkey=<P_Key>,service_id=<service ID>
1762  *
1763  * to the add_target sysfs attribute.
1764  */
1765 enum {
1766         SRP_OPT_ERR             = 0,
1767         SRP_OPT_ID_EXT          = 1 << 0,
1768         SRP_OPT_IOC_GUID        = 1 << 1,
1769         SRP_OPT_DGID            = 1 << 2,
1770         SRP_OPT_PKEY            = 1 << 3,
1771         SRP_OPT_SERVICE_ID      = 1 << 4,
1772         SRP_OPT_MAX_SECT        = 1 << 5,
1773         SRP_OPT_MAX_CMD_PER_LUN = 1 << 6,
1774         SRP_OPT_IO_CLASS        = 1 << 7,
1775         SRP_OPT_INITIATOR_EXT   = 1 << 8,
1776         SRP_OPT_ALL             = (SRP_OPT_ID_EXT       |
1777                                    SRP_OPT_IOC_GUID     |
1778                                    SRP_OPT_DGID         |
1779                                    SRP_OPT_PKEY         |
1780                                    SRP_OPT_SERVICE_ID),
1781 };
1782
1783 static const match_table_t srp_opt_tokens = {
1784         { SRP_OPT_ID_EXT,               "id_ext=%s"             },
1785         { SRP_OPT_IOC_GUID,             "ioc_guid=%s"           },
1786         { SRP_OPT_DGID,                 "dgid=%s"               },
1787         { SRP_OPT_PKEY,                 "pkey=%x"               },
1788         { SRP_OPT_SERVICE_ID,           "service_id=%s"         },
1789         { SRP_OPT_MAX_SECT,             "max_sect=%d"           },
1790         { SRP_OPT_MAX_CMD_PER_LUN,      "max_cmd_per_lun=%d"    },
1791         { SRP_OPT_IO_CLASS,             "io_class=%x"           },
1792         { SRP_OPT_INITIATOR_EXT,        "initiator_ext=%s"      },
1793         { SRP_OPT_ERR,                  NULL                    }
1794 };
1795
1796 static int srp_parse_options(const char *buf, struct srp_target_port *target)
1797 {
1798         char *options, *sep_opt;
1799         char *p;
1800         char dgid[3];
1801         substring_t args[MAX_OPT_ARGS];
1802         int opt_mask = 0;
1803         int token;
1804         int ret = -EINVAL;
1805         int i;
1806
1807         options = kstrdup(buf, GFP_KERNEL);
1808         if (!options)
1809                 return -ENOMEM;
1810
1811         sep_opt = options;
1812         while ((p = strsep(&sep_opt, ",")) != NULL) {
1813                 if (!*p)
1814                         continue;
1815
1816                 token = match_token(p, srp_opt_tokens, args);
1817                 opt_mask |= token;
1818
1819                 switch (token) {
1820                 case SRP_OPT_ID_EXT:
1821                         p = match_strdup(args);
1822                         if (!p) {
1823                                 ret = -ENOMEM;
1824                                 goto out;
1825                         }
1826                         target->id_ext = cpu_to_be64(simple_strtoull(p, NULL, 16));
1827                         kfree(p);
1828                         break;
1829
1830                 case SRP_OPT_IOC_GUID:
1831                         p = match_strdup(args);
1832                         if (!p) {
1833                                 ret = -ENOMEM;
1834                                 goto out;
1835                         }
1836                         target->ioc_guid = cpu_to_be64(simple_strtoull(p, NULL, 16));
1837                         kfree(p);
1838                         break;
1839
1840                 case SRP_OPT_DGID:
1841                         p = match_strdup(args);
1842                         if (!p) {
1843                                 ret = -ENOMEM;
1844                                 goto out;
1845                         }
1846                         if (strlen(p) != 32) {
1847                                 printk(KERN_WARNING PFX "bad dest GID parameter '%s'\n", p);
1848                                 kfree(p);
1849                                 goto out;
1850                         }
1851
1852                         for (i = 0; i < 16; ++i) {
1853                                 strlcpy(dgid, p + i * 2, 3);
1854                                 target->path.dgid.raw[i] = simple_strtoul(dgid, NULL, 16);
1855                         }
1856                         kfree(p);
1857                         memcpy(target->orig_dgid, target->path.dgid.raw, 16);
1858                         break;
1859
1860                 case SRP_OPT_PKEY:
1861                         if (match_hex(args, &token)) {
1862                                 printk(KERN_WARNING PFX "bad P_Key parameter '%s'\n", p);
1863                                 goto out;
1864                         }
1865                         target->path.pkey = cpu_to_be16(token);
1866                         break;
1867
1868                 case SRP_OPT_SERVICE_ID:
1869                         p = match_strdup(args);
1870                         if (!p) {
1871                                 ret = -ENOMEM;
1872                                 goto out;
1873                         }
1874                         target->service_id = cpu_to_be64(simple_strtoull(p, NULL, 16));
1875                         target->path.service_id = target->service_id;
1876                         kfree(p);
1877                         break;
1878
1879                 case SRP_OPT_MAX_SECT:
1880                         if (match_int(args, &token)) {
1881                                 printk(KERN_WARNING PFX "bad max sect parameter '%s'\n", p);
1882                                 goto out;
1883                         }
1884                         target->scsi_host->max_sectors = token;
1885                         break;
1886
1887                 case SRP_OPT_MAX_CMD_PER_LUN:
1888                         if (match_int(args, &token)) {
1889                                 printk(KERN_WARNING PFX "bad max cmd_per_lun parameter '%s'\n", p);
1890                                 goto out;
1891                         }
1892                         target->scsi_host->cmd_per_lun = min(token, SRP_CMD_SQ_SIZE);
1893                         break;
1894
1895                 case SRP_OPT_IO_CLASS:
1896                         if (match_hex(args, &token)) {
1897                                 printk(KERN_WARNING PFX "bad  IO class parameter '%s' \n", p);
1898                                 goto out;
1899                         }
1900                         if (token != SRP_REV10_IB_IO_CLASS &&
1901                             token != SRP_REV16A_IB_IO_CLASS) {
1902                                 printk(KERN_WARNING PFX "unknown IO class parameter value"
1903                                        " %x specified (use %x or %x).\n",
1904                                        token, SRP_REV10_IB_IO_CLASS, SRP_REV16A_IB_IO_CLASS);
1905                                 goto out;
1906                         }
1907                         target->io_class = token;
1908                         break;
1909
1910                 case SRP_OPT_INITIATOR_EXT:
1911                         p = match_strdup(args);
1912                         if (!p) {
1913                                 ret = -ENOMEM;
1914                                 goto out;
1915                         }
1916                         target->initiator_ext = cpu_to_be64(simple_strtoull(p, NULL, 16));
1917                         kfree(p);
1918                         break;
1919
1920                 default:
1921                         printk(KERN_WARNING PFX "unknown parameter or missing value "
1922                                "'%s' in target creation request\n", p);
1923                         goto out;
1924                 }
1925         }
1926
1927         if ((opt_mask & SRP_OPT_ALL) == SRP_OPT_ALL)
1928                 ret = 0;
1929         else
1930                 for (i = 0; i < ARRAY_SIZE(srp_opt_tokens); ++i)
1931                         if ((srp_opt_tokens[i].token & SRP_OPT_ALL) &&
1932                             !(srp_opt_tokens[i].token & opt_mask))
1933                                 printk(KERN_WARNING PFX "target creation request is "
1934                                        "missing parameter '%s'\n",
1935                                        srp_opt_tokens[i].pattern);
1936
1937 out:
1938         kfree(options);
1939         return ret;
1940 }
1941
1942 static ssize_t srp_create_target(struct device *dev,
1943                                  struct device_attribute *attr,
1944                                  const char *buf, size_t count)
1945 {
1946         struct srp_host *host =
1947                 container_of(dev, struct srp_host, dev);
1948         struct Scsi_Host *target_host;
1949         struct srp_target_port *target;
1950         int ret;
1951         int i;
1952
1953         target_host = scsi_host_alloc(&srp_template,
1954                                       sizeof (struct srp_target_port));
1955         if (!target_host)
1956                 return -ENOMEM;
1957
1958         target_host->transportt = ib_srp_transport_template;
1959         target_host->max_lun     = SRP_MAX_LUN;
1960         target_host->max_cmd_len = sizeof ((struct srp_cmd *) (void *) 0L)->cdb;
1961
1962         target = host_to_target(target_host);
1963
1964         target->io_class   = SRP_REV16A_IB_IO_CLASS;
1965         target->scsi_host  = target_host;
1966         target->srp_host   = host;
1967
1968         INIT_LIST_HEAD(&target->free_reqs);
1969         INIT_LIST_HEAD(&target->req_queue);
1970         for (i = 0; i < SRP_CMD_SQ_SIZE; ++i) {
1971                 target->req_ring[i].index = i;
1972                 list_add_tail(&target->req_ring[i].list, &target->free_reqs);
1973         }
1974
1975         ret = srp_parse_options(buf, target);
1976         if (ret)
1977                 goto err;
1978
1979         ib_query_gid(host->srp_dev->dev, host->port, 0, &target->path.sgid);
1980
1981         shost_printk(KERN_DEBUG, target->scsi_host, PFX
1982                      "new target: id_ext %016llx ioc_guid %016llx pkey %04x "
1983                      "service_id %016llx dgid %pI6\n",
1984                (unsigned long long) be64_to_cpu(target->id_ext),
1985                (unsigned long long) be64_to_cpu(target->ioc_guid),
1986                be16_to_cpu(target->path.pkey),
1987                (unsigned long long) be64_to_cpu(target->service_id),
1988                target->path.dgid.raw);
1989
1990         ret = srp_create_target_ib(target);
1991         if (ret)
1992                 goto err;
1993
1994         ret = srp_new_cm_id(target);
1995         if (ret)
1996                 goto err_free;
1997
1998         target->qp_in_error = 0;
1999         ret = srp_connect_target(target);
2000         if (ret) {
2001                 shost_printk(KERN_ERR, target->scsi_host,
2002                              PFX "Connection failed\n");
2003                 goto err_cm_id;
2004         }
2005
2006         ret = srp_add_target(host, target);
2007         if (ret)
2008                 goto err_disconnect;
2009
2010         return count;
2011
2012 err_disconnect:
2013         srp_disconnect_target(target);
2014
2015 err_cm_id:
2016         ib_destroy_cm_id(target->cm_id);
2017
2018 err_free:
2019         srp_free_target_ib(target);
2020
2021 err:
2022         scsi_host_put(target_host);
2023
2024         return ret;
2025 }
2026
2027 static DEVICE_ATTR(add_target, S_IWUSR, NULL, srp_create_target);
2028
2029 static ssize_t show_ibdev(struct device *dev, struct device_attribute *attr,
2030                           char *buf)
2031 {
2032         struct srp_host *host = container_of(dev, struct srp_host, dev);
2033
2034         return sprintf(buf, "%s\n", host->srp_dev->dev->name);
2035 }
2036
2037 static DEVICE_ATTR(ibdev, S_IRUGO, show_ibdev, NULL);
2038
2039 static ssize_t show_port(struct device *dev, struct device_attribute *attr,
2040                          char *buf)
2041 {
2042         struct srp_host *host = container_of(dev, struct srp_host, dev);
2043
2044         return sprintf(buf, "%d\n", host->port);
2045 }
2046
2047 static DEVICE_ATTR(port, S_IRUGO, show_port, NULL);
2048
2049 static struct srp_host *srp_add_port(struct srp_device *device, u8 port)
2050 {
2051         struct srp_host *host;
2052
2053         host = kzalloc(sizeof *host, GFP_KERNEL);
2054         if (!host)
2055                 return NULL;
2056
2057         INIT_LIST_HEAD(&host->target_list);
2058         spin_lock_init(&host->target_lock);
2059         init_completion(&host->released);
2060         host->srp_dev = device;
2061         host->port = port;
2062
2063         host->dev.class = &srp_class;
2064         host->dev.parent = device->dev->dma_device;
2065         dev_set_name(&host->dev, "srp-%s-%d", device->dev->name, port);
2066
2067         if (device_register(&host->dev))
2068                 goto free_host;
2069         if (device_create_file(&host->dev, &dev_attr_add_target))
2070                 goto err_class;
2071         if (device_create_file(&host->dev, &dev_attr_ibdev))
2072                 goto err_class;
2073         if (device_create_file(&host->dev, &dev_attr_port))
2074                 goto err_class;
2075
2076         return host;
2077
2078 err_class:
2079         device_unregister(&host->dev);
2080
2081 free_host:
2082         kfree(host);
2083
2084         return NULL;
2085 }
2086
2087 static void srp_add_one(struct ib_device *device)
2088 {
2089         struct srp_device *srp_dev;
2090         struct ib_device_attr *dev_attr;
2091         struct ib_fmr_pool_param fmr_param;
2092         struct srp_host *host;
2093         int s, e, p;
2094
2095         dev_attr = kmalloc(sizeof *dev_attr, GFP_KERNEL);
2096         if (!dev_attr)
2097                 return;
2098
2099         if (ib_query_device(device, dev_attr)) {
2100                 printk(KERN_WARNING PFX "Query device failed for %s\n",
2101                        device->name);
2102                 goto free_attr;
2103         }
2104
2105         srp_dev = kmalloc(sizeof *srp_dev, GFP_KERNEL);
2106         if (!srp_dev)
2107                 goto free_attr;
2108
2109         /*
2110          * Use the smallest page size supported by the HCA, down to a
2111          * minimum of 512 bytes (which is the smallest sector that a
2112          * SCSI command will ever carry).
2113          */
2114         srp_dev->fmr_page_shift = max(9, ffs(dev_attr->page_size_cap) - 1);
2115         srp_dev->fmr_page_size  = 1 << srp_dev->fmr_page_shift;
2116         srp_dev->fmr_page_mask  = ~((u64) srp_dev->fmr_page_size - 1);
2117
2118         INIT_LIST_HEAD(&srp_dev->dev_list);
2119
2120         srp_dev->dev = device;
2121         srp_dev->pd  = ib_alloc_pd(device);
2122         if (IS_ERR(srp_dev->pd))
2123                 goto free_dev;
2124
2125         srp_dev->mr = ib_get_dma_mr(srp_dev->pd,
2126                                     IB_ACCESS_LOCAL_WRITE |
2127                                     IB_ACCESS_REMOTE_READ |
2128                                     IB_ACCESS_REMOTE_WRITE);
2129         if (IS_ERR(srp_dev->mr))
2130                 goto err_pd;
2131
2132         memset(&fmr_param, 0, sizeof fmr_param);
2133         fmr_param.pool_size         = SRP_FMR_POOL_SIZE;
2134         fmr_param.dirty_watermark   = SRP_FMR_DIRTY_SIZE;
2135         fmr_param.cache             = 1;
2136         fmr_param.max_pages_per_fmr = SRP_FMR_SIZE;
2137         fmr_param.page_shift        = srp_dev->fmr_page_shift;
2138         fmr_param.access            = (IB_ACCESS_LOCAL_WRITE |
2139                                        IB_ACCESS_REMOTE_WRITE |
2140                                        IB_ACCESS_REMOTE_READ);
2141
2142         srp_dev->fmr_pool = ib_create_fmr_pool(srp_dev->pd, &fmr_param);
2143         if (IS_ERR(srp_dev->fmr_pool))
2144                 srp_dev->fmr_pool = NULL;
2145
2146         if (device->node_type == RDMA_NODE_IB_SWITCH) {
2147                 s = 0;
2148                 e = 0;
2149         } else {
2150                 s = 1;
2151                 e = device->phys_port_cnt;
2152         }
2153
2154         for (p = s; p <= e; ++p) {
2155                 host = srp_add_port(srp_dev, p);
2156                 if (host)
2157                         list_add_tail(&host->list, &srp_dev->dev_list);
2158         }
2159
2160         ib_set_client_data(device, &srp_client, srp_dev);
2161
2162         goto free_attr;
2163
2164 err_pd:
2165         ib_dealloc_pd(srp_dev->pd);
2166
2167 free_dev:
2168         kfree(srp_dev);
2169
2170 free_attr:
2171         kfree(dev_attr);
2172 }
2173
2174 static void srp_remove_one(struct ib_device *device)
2175 {
2176         struct srp_device *srp_dev;
2177         struct srp_host *host, *tmp_host;
2178         LIST_HEAD(target_list);
2179         struct srp_target_port *target, *tmp_target;
2180
2181         srp_dev = ib_get_client_data(device, &srp_client);
2182
2183         list_for_each_entry_safe(host, tmp_host, &srp_dev->dev_list, list) {
2184                 device_unregister(&host->dev);
2185                 /*
2186                  * Wait for the sysfs entry to go away, so that no new
2187                  * target ports can be created.
2188                  */
2189                 wait_for_completion(&host->released);
2190
2191                 /*
2192                  * Mark all target ports as removed, so we stop queueing
2193                  * commands and don't try to reconnect.
2194                  */
2195                 spin_lock(&host->target_lock);
2196                 list_for_each_entry(target, &host->target_list, list) {
2197                         spin_lock_irq(target->scsi_host->host_lock);
2198                         target->state = SRP_TARGET_REMOVED;
2199                         spin_unlock_irq(target->scsi_host->host_lock);
2200                 }
2201                 spin_unlock(&host->target_lock);
2202
2203                 /*
2204                  * Wait for any reconnection tasks that may have
2205                  * started before we marked our target ports as
2206                  * removed, and any target port removal tasks.
2207                  */
2208                 flush_scheduled_work();
2209
2210                 list_for_each_entry_safe(target, tmp_target,
2211                                          &host->target_list, list) {
2212                         srp_remove_host(target->scsi_host);
2213                         scsi_remove_host(target->scsi_host);
2214                         srp_disconnect_target(target);
2215                         ib_destroy_cm_id(target->cm_id);
2216                         srp_free_target_ib(target);
2217                         scsi_host_put(target->scsi_host);
2218                 }
2219
2220                 kfree(host);
2221         }
2222
2223         if (srp_dev->fmr_pool)
2224                 ib_destroy_fmr_pool(srp_dev->fmr_pool);
2225         ib_dereg_mr(srp_dev->mr);
2226         ib_dealloc_pd(srp_dev->pd);
2227
2228         kfree(srp_dev);
2229 }
2230
2231 static struct srp_function_template ib_srp_transport_functions = {
2232 };
2233
2234 static int __init srp_init_module(void)
2235 {
2236         int ret;
2237
2238         BUILD_BUG_ON_NOT_POWER_OF_2(SRP_SQ_SIZE);
2239         BUILD_BUG_ON_NOT_POWER_OF_2(SRP_RQ_SIZE);
2240
2241         if (srp_sg_tablesize > 255) {
2242                 printk(KERN_WARNING PFX "Clamping srp_sg_tablesize to 255\n");
2243                 srp_sg_tablesize = 255;
2244         }
2245
2246         ib_srp_transport_template =
2247                 srp_attach_transport(&ib_srp_transport_functions);
2248         if (!ib_srp_transport_template)
2249                 return -ENOMEM;
2250
2251         srp_template.sg_tablesize = srp_sg_tablesize;
2252         srp_max_iu_len = (sizeof (struct srp_cmd) +
2253                           sizeof (struct srp_indirect_buf) +
2254                           srp_sg_tablesize * 16);
2255
2256         ret = class_register(&srp_class);
2257         if (ret) {
2258                 printk(KERN_ERR PFX "couldn't register class infiniband_srp\n");
2259                 srp_release_transport(ib_srp_transport_template);
2260                 return ret;
2261         }
2262
2263         ib_sa_register_client(&srp_sa_client);
2264
2265         ret = ib_register_client(&srp_client);
2266         if (ret) {
2267                 printk(KERN_ERR PFX "couldn't register IB client\n");
2268                 srp_release_transport(ib_srp_transport_template);
2269                 ib_sa_unregister_client(&srp_sa_client);
2270                 class_unregister(&srp_class);
2271                 return ret;
2272         }
2273
2274         return 0;
2275 }
2276
2277 static void __exit srp_cleanup_module(void)
2278 {
2279         ib_unregister_client(&srp_client);
2280         ib_sa_unregister_client(&srp_sa_client);
2281         class_unregister(&srp_class);
2282         srp_release_transport(ib_srp_transport_template);
2283 }
2284
2285 module_init(srp_init_module);
2286 module_exit(srp_cleanup_module);