Merge git://git.kernel.org/pub/scm/linux/kernel/git/sfrench/cifs-2.6
[linux-2.6] / drivers / infiniband / hw / ipath / ipath_verbs.c
1 /*
2  * Copyright (c) 2006, 2007, 2008 QLogic Corporation. All rights reserved.
3  * Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33
34 #include <rdma/ib_mad.h>
35 #include <rdma/ib_user_verbs.h>
36 #include <linux/io.h>
37 #include <linux/utsname.h>
38
39 #include "ipath_kernel.h"
40 #include "ipath_verbs.h"
41 #include "ipath_common.h"
42
43 static unsigned int ib_ipath_qp_table_size = 251;
44 module_param_named(qp_table_size, ib_ipath_qp_table_size, uint, S_IRUGO);
45 MODULE_PARM_DESC(qp_table_size, "QP table size");
46
47 unsigned int ib_ipath_lkey_table_size = 12;
48 module_param_named(lkey_table_size, ib_ipath_lkey_table_size, uint,
49                    S_IRUGO);
50 MODULE_PARM_DESC(lkey_table_size,
51                  "LKEY table size in bits (2^n, 1 <= n <= 23)");
52
53 static unsigned int ib_ipath_max_pds = 0xFFFF;
54 module_param_named(max_pds, ib_ipath_max_pds, uint, S_IWUSR | S_IRUGO);
55 MODULE_PARM_DESC(max_pds,
56                  "Maximum number of protection domains to support");
57
58 static unsigned int ib_ipath_max_ahs = 0xFFFF;
59 module_param_named(max_ahs, ib_ipath_max_ahs, uint, S_IWUSR | S_IRUGO);
60 MODULE_PARM_DESC(max_ahs, "Maximum number of address handles to support");
61
62 unsigned int ib_ipath_max_cqes = 0x2FFFF;
63 module_param_named(max_cqes, ib_ipath_max_cqes, uint, S_IWUSR | S_IRUGO);
64 MODULE_PARM_DESC(max_cqes,
65                  "Maximum number of completion queue entries to support");
66
67 unsigned int ib_ipath_max_cqs = 0x1FFFF;
68 module_param_named(max_cqs, ib_ipath_max_cqs, uint, S_IWUSR | S_IRUGO);
69 MODULE_PARM_DESC(max_cqs, "Maximum number of completion queues to support");
70
71 unsigned int ib_ipath_max_qp_wrs = 0x3FFF;
72 module_param_named(max_qp_wrs, ib_ipath_max_qp_wrs, uint,
73                    S_IWUSR | S_IRUGO);
74 MODULE_PARM_DESC(max_qp_wrs, "Maximum number of QP WRs to support");
75
76 unsigned int ib_ipath_max_qps = 16384;
77 module_param_named(max_qps, ib_ipath_max_qps, uint, S_IWUSR | S_IRUGO);
78 MODULE_PARM_DESC(max_qps, "Maximum number of QPs to support");
79
80 unsigned int ib_ipath_max_sges = 0x60;
81 module_param_named(max_sges, ib_ipath_max_sges, uint, S_IWUSR | S_IRUGO);
82 MODULE_PARM_DESC(max_sges, "Maximum number of SGEs to support");
83
84 unsigned int ib_ipath_max_mcast_grps = 16384;
85 module_param_named(max_mcast_grps, ib_ipath_max_mcast_grps, uint,
86                    S_IWUSR | S_IRUGO);
87 MODULE_PARM_DESC(max_mcast_grps,
88                  "Maximum number of multicast groups to support");
89
90 unsigned int ib_ipath_max_mcast_qp_attached = 16;
91 module_param_named(max_mcast_qp_attached, ib_ipath_max_mcast_qp_attached,
92                    uint, S_IWUSR | S_IRUGO);
93 MODULE_PARM_DESC(max_mcast_qp_attached,
94                  "Maximum number of attached QPs to support");
95
96 unsigned int ib_ipath_max_srqs = 1024;
97 module_param_named(max_srqs, ib_ipath_max_srqs, uint, S_IWUSR | S_IRUGO);
98 MODULE_PARM_DESC(max_srqs, "Maximum number of SRQs to support");
99
100 unsigned int ib_ipath_max_srq_sges = 128;
101 module_param_named(max_srq_sges, ib_ipath_max_srq_sges,
102                    uint, S_IWUSR | S_IRUGO);
103 MODULE_PARM_DESC(max_srq_sges, "Maximum number of SRQ SGEs to support");
104
105 unsigned int ib_ipath_max_srq_wrs = 0x1FFFF;
106 module_param_named(max_srq_wrs, ib_ipath_max_srq_wrs,
107                    uint, S_IWUSR | S_IRUGO);
108 MODULE_PARM_DESC(max_srq_wrs, "Maximum number of SRQ WRs support");
109
110 static unsigned int ib_ipath_disable_sma;
111 module_param_named(disable_sma, ib_ipath_disable_sma, uint, S_IWUSR | S_IRUGO);
112 MODULE_PARM_DESC(disable_sma, "Disable the SMA");
113
114 const int ib_ipath_state_ops[IB_QPS_ERR + 1] = {
115         [IB_QPS_RESET] = 0,
116         [IB_QPS_INIT] = IPATH_POST_RECV_OK,
117         [IB_QPS_RTR] = IPATH_POST_RECV_OK | IPATH_PROCESS_RECV_OK,
118         [IB_QPS_RTS] = IPATH_POST_RECV_OK | IPATH_PROCESS_RECV_OK |
119             IPATH_POST_SEND_OK | IPATH_PROCESS_SEND_OK,
120         [IB_QPS_SQD] = IPATH_POST_RECV_OK | IPATH_PROCESS_RECV_OK |
121             IPATH_POST_SEND_OK,
122         [IB_QPS_SQE] = IPATH_POST_RECV_OK | IPATH_PROCESS_RECV_OK,
123         [IB_QPS_ERR] = 0,
124 };
125
126 struct ipath_ucontext {
127         struct ib_ucontext ibucontext;
128 };
129
130 static inline struct ipath_ucontext *to_iucontext(struct ib_ucontext
131                                                   *ibucontext)
132 {
133         return container_of(ibucontext, struct ipath_ucontext, ibucontext);
134 }
135
136 /*
137  * Translate ib_wr_opcode into ib_wc_opcode.
138  */
139 const enum ib_wc_opcode ib_ipath_wc_opcode[] = {
140         [IB_WR_RDMA_WRITE] = IB_WC_RDMA_WRITE,
141         [IB_WR_RDMA_WRITE_WITH_IMM] = IB_WC_RDMA_WRITE,
142         [IB_WR_SEND] = IB_WC_SEND,
143         [IB_WR_SEND_WITH_IMM] = IB_WC_SEND,
144         [IB_WR_RDMA_READ] = IB_WC_RDMA_READ,
145         [IB_WR_ATOMIC_CMP_AND_SWP] = IB_WC_COMP_SWAP,
146         [IB_WR_ATOMIC_FETCH_AND_ADD] = IB_WC_FETCH_ADD
147 };
148
149 /*
150  * System image GUID.
151  */
152 static __be64 sys_image_guid;
153
154 /**
155  * ipath_copy_sge - copy data to SGE memory
156  * @ss: the SGE state
157  * @data: the data to copy
158  * @length: the length of the data
159  */
160 void ipath_copy_sge(struct ipath_sge_state *ss, void *data, u32 length)
161 {
162         struct ipath_sge *sge = &ss->sge;
163
164         while (length) {
165                 u32 len = sge->length;
166
167                 if (len > length)
168                         len = length;
169                 if (len > sge->sge_length)
170                         len = sge->sge_length;
171                 BUG_ON(len == 0);
172                 memcpy(sge->vaddr, data, len);
173                 sge->vaddr += len;
174                 sge->length -= len;
175                 sge->sge_length -= len;
176                 if (sge->sge_length == 0) {
177                         if (--ss->num_sge)
178                                 *sge = *ss->sg_list++;
179                 } else if (sge->length == 0 && sge->mr != NULL) {
180                         if (++sge->n >= IPATH_SEGSZ) {
181                                 if (++sge->m >= sge->mr->mapsz)
182                                         break;
183                                 sge->n = 0;
184                         }
185                         sge->vaddr =
186                                 sge->mr->map[sge->m]->segs[sge->n].vaddr;
187                         sge->length =
188                                 sge->mr->map[sge->m]->segs[sge->n].length;
189                 }
190                 data += len;
191                 length -= len;
192         }
193 }
194
195 /**
196  * ipath_skip_sge - skip over SGE memory - XXX almost dup of prev func
197  * @ss: the SGE state
198  * @length: the number of bytes to skip
199  */
200 void ipath_skip_sge(struct ipath_sge_state *ss, u32 length)
201 {
202         struct ipath_sge *sge = &ss->sge;
203
204         while (length) {
205                 u32 len = sge->length;
206
207                 if (len > length)
208                         len = length;
209                 if (len > sge->sge_length)
210                         len = sge->sge_length;
211                 BUG_ON(len == 0);
212                 sge->vaddr += len;
213                 sge->length -= len;
214                 sge->sge_length -= len;
215                 if (sge->sge_length == 0) {
216                         if (--ss->num_sge)
217                                 *sge = *ss->sg_list++;
218                 } else if (sge->length == 0 && sge->mr != NULL) {
219                         if (++sge->n >= IPATH_SEGSZ) {
220                                 if (++sge->m >= sge->mr->mapsz)
221                                         break;
222                                 sge->n = 0;
223                         }
224                         sge->vaddr =
225                                 sge->mr->map[sge->m]->segs[sge->n].vaddr;
226                         sge->length =
227                                 sge->mr->map[sge->m]->segs[sge->n].length;
228                 }
229                 length -= len;
230         }
231 }
232
233 static void ipath_flush_wqe(struct ipath_qp *qp, struct ib_send_wr *wr)
234 {
235         struct ib_wc wc;
236
237         memset(&wc, 0, sizeof(wc));
238         wc.wr_id = wr->wr_id;
239         wc.status = IB_WC_WR_FLUSH_ERR;
240         wc.opcode = ib_ipath_wc_opcode[wr->opcode];
241         wc.qp = &qp->ibqp;
242         ipath_cq_enter(to_icq(qp->ibqp.send_cq), &wc, 1);
243 }
244
245 /*
246  * Count the number of DMA descriptors needed to send length bytes of data.
247  * Don't modify the ipath_sge_state to get the count.
248  * Return zero if any of the segments is not aligned.
249  */
250 static u32 ipath_count_sge(struct ipath_sge_state *ss, u32 length)
251 {
252         struct ipath_sge *sg_list = ss->sg_list;
253         struct ipath_sge sge = ss->sge;
254         u8 num_sge = ss->num_sge;
255         u32 ndesc = 1;  /* count the header */
256
257         while (length) {
258                 u32 len = sge.length;
259
260                 if (len > length)
261                         len = length;
262                 if (len > sge.sge_length)
263                         len = sge.sge_length;
264                 BUG_ON(len == 0);
265                 if (((long) sge.vaddr & (sizeof(u32) - 1)) ||
266                     (len != length && (len & (sizeof(u32) - 1)))) {
267                         ndesc = 0;
268                         break;
269                 }
270                 ndesc++;
271                 sge.vaddr += len;
272                 sge.length -= len;
273                 sge.sge_length -= len;
274                 if (sge.sge_length == 0) {
275                         if (--num_sge)
276                                 sge = *sg_list++;
277                 } else if (sge.length == 0 && sge.mr != NULL) {
278                         if (++sge.n >= IPATH_SEGSZ) {
279                                 if (++sge.m >= sge.mr->mapsz)
280                                         break;
281                                 sge.n = 0;
282                         }
283                         sge.vaddr =
284                                 sge.mr->map[sge.m]->segs[sge.n].vaddr;
285                         sge.length =
286                                 sge.mr->map[sge.m]->segs[sge.n].length;
287                 }
288                 length -= len;
289         }
290         return ndesc;
291 }
292
293 /*
294  * Copy from the SGEs to the data buffer.
295  */
296 static void ipath_copy_from_sge(void *data, struct ipath_sge_state *ss,
297                                 u32 length)
298 {
299         struct ipath_sge *sge = &ss->sge;
300
301         while (length) {
302                 u32 len = sge->length;
303
304                 if (len > length)
305                         len = length;
306                 if (len > sge->sge_length)
307                         len = sge->sge_length;
308                 BUG_ON(len == 0);
309                 memcpy(data, sge->vaddr, len);
310                 sge->vaddr += len;
311                 sge->length -= len;
312                 sge->sge_length -= len;
313                 if (sge->sge_length == 0) {
314                         if (--ss->num_sge)
315                                 *sge = *ss->sg_list++;
316                 } else if (sge->length == 0 && sge->mr != NULL) {
317                         if (++sge->n >= IPATH_SEGSZ) {
318                                 if (++sge->m >= sge->mr->mapsz)
319                                         break;
320                                 sge->n = 0;
321                         }
322                         sge->vaddr =
323                                 sge->mr->map[sge->m]->segs[sge->n].vaddr;
324                         sge->length =
325                                 sge->mr->map[sge->m]->segs[sge->n].length;
326                 }
327                 data += len;
328                 length -= len;
329         }
330 }
331
332 /**
333  * ipath_post_one_send - post one RC, UC, or UD send work request
334  * @qp: the QP to post on
335  * @wr: the work request to send
336  */
337 static int ipath_post_one_send(struct ipath_qp *qp, struct ib_send_wr *wr)
338 {
339         struct ipath_swqe *wqe;
340         u32 next;
341         int i;
342         int j;
343         int acc;
344         int ret;
345         unsigned long flags;
346
347         spin_lock_irqsave(&qp->s_lock, flags);
348
349         /* Check that state is OK to post send. */
350         if (unlikely(!(ib_ipath_state_ops[qp->state] & IPATH_POST_SEND_OK))) {
351                 if (qp->state != IB_QPS_SQE && qp->state != IB_QPS_ERR)
352                         goto bail_inval;
353                 /* C10-96 says generate a flushed completion entry. */
354                 ipath_flush_wqe(qp, wr);
355                 ret = 0;
356                 goto bail;
357         }
358
359         /* IB spec says that num_sge == 0 is OK. */
360         if (wr->num_sge > qp->s_max_sge)
361                 goto bail_inval;
362
363         /*
364          * Don't allow RDMA reads or atomic operations on UC or
365          * undefined operations.
366          * Make sure buffer is large enough to hold the result for atomics.
367          */
368         if (qp->ibqp.qp_type == IB_QPT_UC) {
369                 if ((unsigned) wr->opcode >= IB_WR_RDMA_READ)
370                         goto bail_inval;
371         } else if (qp->ibqp.qp_type == IB_QPT_UD) {
372                 /* Check UD opcode */
373                 if (wr->opcode != IB_WR_SEND &&
374                     wr->opcode != IB_WR_SEND_WITH_IMM)
375                         goto bail_inval;
376                 /* Check UD destination address PD */
377                 if (qp->ibqp.pd != wr->wr.ud.ah->pd)
378                         goto bail_inval;
379         } else if ((unsigned) wr->opcode > IB_WR_ATOMIC_FETCH_AND_ADD)
380                 goto bail_inval;
381         else if (wr->opcode >= IB_WR_ATOMIC_CMP_AND_SWP &&
382                    (wr->num_sge == 0 ||
383                     wr->sg_list[0].length < sizeof(u64) ||
384                     wr->sg_list[0].addr & (sizeof(u64) - 1)))
385                 goto bail_inval;
386         else if (wr->opcode >= IB_WR_RDMA_READ && !qp->s_max_rd_atomic)
387                 goto bail_inval;
388
389         next = qp->s_head + 1;
390         if (next >= qp->s_size)
391                 next = 0;
392         if (next == qp->s_last) {
393                 ret = -ENOMEM;
394                 goto bail;
395         }
396
397         wqe = get_swqe_ptr(qp, qp->s_head);
398         wqe->wr = *wr;
399         wqe->length = 0;
400         if (wr->num_sge) {
401                 acc = wr->opcode >= IB_WR_RDMA_READ ?
402                         IB_ACCESS_LOCAL_WRITE : 0;
403                 for (i = 0, j = 0; i < wr->num_sge; i++) {
404                         u32 length = wr->sg_list[i].length;
405                         int ok;
406
407                         if (length == 0)
408                                 continue;
409                         ok = ipath_lkey_ok(qp, &wqe->sg_list[j],
410                                            &wr->sg_list[i], acc);
411                         if (!ok)
412                                 goto bail_inval;
413                         wqe->length += length;
414                         j++;
415                 }
416                 wqe->wr.num_sge = j;
417         }
418         if (qp->ibqp.qp_type == IB_QPT_UC ||
419             qp->ibqp.qp_type == IB_QPT_RC) {
420                 if (wqe->length > 0x80000000U)
421                         goto bail_inval;
422         } else if (wqe->length > to_idev(qp->ibqp.device)->dd->ipath_ibmtu)
423                 goto bail_inval;
424         wqe->ssn = qp->s_ssn++;
425         qp->s_head = next;
426
427         ret = 0;
428         goto bail;
429
430 bail_inval:
431         ret = -EINVAL;
432 bail:
433         spin_unlock_irqrestore(&qp->s_lock, flags);
434         return ret;
435 }
436
437 /**
438  * ipath_post_send - post a send on a QP
439  * @ibqp: the QP to post the send on
440  * @wr: the list of work requests to post
441  * @bad_wr: the first bad WR is put here
442  *
443  * This may be called from interrupt context.
444  */
445 static int ipath_post_send(struct ib_qp *ibqp, struct ib_send_wr *wr,
446                            struct ib_send_wr **bad_wr)
447 {
448         struct ipath_qp *qp = to_iqp(ibqp);
449         int err = 0;
450
451         for (; wr; wr = wr->next) {
452                 err = ipath_post_one_send(qp, wr);
453                 if (err) {
454                         *bad_wr = wr;
455                         goto bail;
456                 }
457         }
458
459         /* Try to do the send work in the caller's context. */
460         ipath_do_send((unsigned long) qp);
461
462 bail:
463         return err;
464 }
465
466 /**
467  * ipath_post_receive - post a receive on a QP
468  * @ibqp: the QP to post the receive on
469  * @wr: the WR to post
470  * @bad_wr: the first bad WR is put here
471  *
472  * This may be called from interrupt context.
473  */
474 static int ipath_post_receive(struct ib_qp *ibqp, struct ib_recv_wr *wr,
475                               struct ib_recv_wr **bad_wr)
476 {
477         struct ipath_qp *qp = to_iqp(ibqp);
478         struct ipath_rwq *wq = qp->r_rq.wq;
479         unsigned long flags;
480         int ret;
481
482         /* Check that state is OK to post receive. */
483         if (!(ib_ipath_state_ops[qp->state] & IPATH_POST_RECV_OK) || !wq) {
484                 *bad_wr = wr;
485                 ret = -EINVAL;
486                 goto bail;
487         }
488
489         for (; wr; wr = wr->next) {
490                 struct ipath_rwqe *wqe;
491                 u32 next;
492                 int i;
493
494                 if ((unsigned) wr->num_sge > qp->r_rq.max_sge) {
495                         *bad_wr = wr;
496                         ret = -EINVAL;
497                         goto bail;
498                 }
499
500                 spin_lock_irqsave(&qp->r_rq.lock, flags);
501                 next = wq->head + 1;
502                 if (next >= qp->r_rq.size)
503                         next = 0;
504                 if (next == wq->tail) {
505                         spin_unlock_irqrestore(&qp->r_rq.lock, flags);
506                         *bad_wr = wr;
507                         ret = -ENOMEM;
508                         goto bail;
509                 }
510
511                 wqe = get_rwqe_ptr(&qp->r_rq, wq->head);
512                 wqe->wr_id = wr->wr_id;
513                 wqe->num_sge = wr->num_sge;
514                 for (i = 0; i < wr->num_sge; i++)
515                         wqe->sg_list[i] = wr->sg_list[i];
516                 /* Make sure queue entry is written before the head index. */
517                 smp_wmb();
518                 wq->head = next;
519                 spin_unlock_irqrestore(&qp->r_rq.lock, flags);
520         }
521         ret = 0;
522
523 bail:
524         return ret;
525 }
526
527 /**
528  * ipath_qp_rcv - processing an incoming packet on a QP
529  * @dev: the device the packet came on
530  * @hdr: the packet header
531  * @has_grh: true if the packet has a GRH
532  * @data: the packet data
533  * @tlen: the packet length
534  * @qp: the QP the packet came on
535  *
536  * This is called from ipath_ib_rcv() to process an incoming packet
537  * for the given QP.
538  * Called at interrupt level.
539  */
540 static void ipath_qp_rcv(struct ipath_ibdev *dev,
541                          struct ipath_ib_header *hdr, int has_grh,
542                          void *data, u32 tlen, struct ipath_qp *qp)
543 {
544         /* Check for valid receive state. */
545         if (!(ib_ipath_state_ops[qp->state] & IPATH_PROCESS_RECV_OK)) {
546                 dev->n_pkt_drops++;
547                 return;
548         }
549
550         switch (qp->ibqp.qp_type) {
551         case IB_QPT_SMI:
552         case IB_QPT_GSI:
553                 if (ib_ipath_disable_sma)
554                         break;
555                 /* FALLTHROUGH */
556         case IB_QPT_UD:
557                 ipath_ud_rcv(dev, hdr, has_grh, data, tlen, qp);
558                 break;
559
560         case IB_QPT_RC:
561                 ipath_rc_rcv(dev, hdr, has_grh, data, tlen, qp);
562                 break;
563
564         case IB_QPT_UC:
565                 ipath_uc_rcv(dev, hdr, has_grh, data, tlen, qp);
566                 break;
567
568         default:
569                 break;
570         }
571 }
572
573 /**
574  * ipath_ib_rcv - process an incoming packet
575  * @arg: the device pointer
576  * @rhdr: the header of the packet
577  * @data: the packet data
578  * @tlen: the packet length
579  *
580  * This is called from ipath_kreceive() to process an incoming packet at
581  * interrupt level. Tlen is the length of the header + data + CRC in bytes.
582  */
583 void ipath_ib_rcv(struct ipath_ibdev *dev, void *rhdr, void *data,
584                   u32 tlen)
585 {
586         struct ipath_ib_header *hdr = rhdr;
587         struct ipath_other_headers *ohdr;
588         struct ipath_qp *qp;
589         u32 qp_num;
590         int lnh;
591         u8 opcode;
592         u16 lid;
593
594         if (unlikely(dev == NULL))
595                 goto bail;
596
597         if (unlikely(tlen < 24)) {      /* LRH+BTH+CRC */
598                 dev->rcv_errors++;
599                 goto bail;
600         }
601
602         /* Check for a valid destination LID (see ch. 7.11.1). */
603         lid = be16_to_cpu(hdr->lrh[1]);
604         if (lid < IPATH_MULTICAST_LID_BASE) {
605                 lid &= ~((1 << dev->dd->ipath_lmc) - 1);
606                 if (unlikely(lid != dev->dd->ipath_lid)) {
607                         dev->rcv_errors++;
608                         goto bail;
609                 }
610         }
611
612         /* Check for GRH */
613         lnh = be16_to_cpu(hdr->lrh[0]) & 3;
614         if (lnh == IPATH_LRH_BTH)
615                 ohdr = &hdr->u.oth;
616         else if (lnh == IPATH_LRH_GRH)
617                 ohdr = &hdr->u.l.oth;
618         else {
619                 dev->rcv_errors++;
620                 goto bail;
621         }
622
623         opcode = be32_to_cpu(ohdr->bth[0]) >> 24;
624         dev->opstats[opcode].n_bytes += tlen;
625         dev->opstats[opcode].n_packets++;
626
627         /* Get the destination QP number. */
628         qp_num = be32_to_cpu(ohdr->bth[1]) & IPATH_QPN_MASK;
629         if (qp_num == IPATH_MULTICAST_QPN) {
630                 struct ipath_mcast *mcast;
631                 struct ipath_mcast_qp *p;
632
633                 if (lnh != IPATH_LRH_GRH) {
634                         dev->n_pkt_drops++;
635                         goto bail;
636                 }
637                 mcast = ipath_mcast_find(&hdr->u.l.grh.dgid);
638                 if (mcast == NULL) {
639                         dev->n_pkt_drops++;
640                         goto bail;
641                 }
642                 dev->n_multicast_rcv++;
643                 list_for_each_entry_rcu(p, &mcast->qp_list, list)
644                         ipath_qp_rcv(dev, hdr, 1, data, tlen, p->qp);
645                 /*
646                  * Notify ipath_multicast_detach() if it is waiting for us
647                  * to finish.
648                  */
649                 if (atomic_dec_return(&mcast->refcount) <= 1)
650                         wake_up(&mcast->wait);
651         } else {
652                 qp = ipath_lookup_qpn(&dev->qp_table, qp_num);
653                 if (qp) {
654                         dev->n_unicast_rcv++;
655                         ipath_qp_rcv(dev, hdr, lnh == IPATH_LRH_GRH, data,
656                                      tlen, qp);
657                         /*
658                          * Notify ipath_destroy_qp() if it is waiting
659                          * for us to finish.
660                          */
661                         if (atomic_dec_and_test(&qp->refcount))
662                                 wake_up(&qp->wait);
663                 } else
664                         dev->n_pkt_drops++;
665         }
666
667 bail:;
668 }
669
670 /**
671  * ipath_ib_timer - verbs timer
672  * @arg: the device pointer
673  *
674  * This is called from ipath_do_rcv_timer() at interrupt level to check for
675  * QPs which need retransmits and to collect performance numbers.
676  */
677 static void ipath_ib_timer(struct ipath_ibdev *dev)
678 {
679         struct ipath_qp *resend = NULL;
680         struct list_head *last;
681         struct ipath_qp *qp;
682         unsigned long flags;
683
684         if (dev == NULL)
685                 return;
686
687         spin_lock_irqsave(&dev->pending_lock, flags);
688         /* Start filling the next pending queue. */
689         if (++dev->pending_index >= ARRAY_SIZE(dev->pending))
690                 dev->pending_index = 0;
691         /* Save any requests still in the new queue, they have timed out. */
692         last = &dev->pending[dev->pending_index];
693         while (!list_empty(last)) {
694                 qp = list_entry(last->next, struct ipath_qp, timerwait);
695                 list_del_init(&qp->timerwait);
696                 qp->timer_next = resend;
697                 resend = qp;
698                 atomic_inc(&qp->refcount);
699         }
700         last = &dev->rnrwait;
701         if (!list_empty(last)) {
702                 qp = list_entry(last->next, struct ipath_qp, timerwait);
703                 if (--qp->s_rnr_timeout == 0) {
704                         do {
705                                 list_del_init(&qp->timerwait);
706                                 tasklet_hi_schedule(&qp->s_task);
707                                 if (list_empty(last))
708                                         break;
709                                 qp = list_entry(last->next, struct ipath_qp,
710                                                 timerwait);
711                         } while (qp->s_rnr_timeout == 0);
712                 }
713         }
714         /*
715          * We should only be in the started state if pma_sample_start != 0
716          */
717         if (dev->pma_sample_status == IB_PMA_SAMPLE_STATUS_STARTED &&
718             --dev->pma_sample_start == 0) {
719                 dev->pma_sample_status = IB_PMA_SAMPLE_STATUS_RUNNING;
720                 ipath_snapshot_counters(dev->dd, &dev->ipath_sword,
721                                         &dev->ipath_rword,
722                                         &dev->ipath_spkts,
723                                         &dev->ipath_rpkts,
724                                         &dev->ipath_xmit_wait);
725         }
726         if (dev->pma_sample_status == IB_PMA_SAMPLE_STATUS_RUNNING) {
727                 if (dev->pma_sample_interval == 0) {
728                         u64 ta, tb, tc, td, te;
729
730                         dev->pma_sample_status = IB_PMA_SAMPLE_STATUS_DONE;
731                         ipath_snapshot_counters(dev->dd, &ta, &tb,
732                                                 &tc, &td, &te);
733
734                         dev->ipath_sword = ta - dev->ipath_sword;
735                         dev->ipath_rword = tb - dev->ipath_rword;
736                         dev->ipath_spkts = tc - dev->ipath_spkts;
737                         dev->ipath_rpkts = td - dev->ipath_rpkts;
738                         dev->ipath_xmit_wait = te - dev->ipath_xmit_wait;
739                 }
740                 else
741                         dev->pma_sample_interval--;
742         }
743         spin_unlock_irqrestore(&dev->pending_lock, flags);
744
745         /* XXX What if timer fires again while this is running? */
746         for (qp = resend; qp != NULL; qp = qp->timer_next) {
747                 struct ib_wc wc;
748
749                 spin_lock_irqsave(&qp->s_lock, flags);
750                 if (qp->s_last != qp->s_tail && qp->state == IB_QPS_RTS) {
751                         dev->n_timeouts++;
752                         ipath_restart_rc(qp, qp->s_last_psn + 1, &wc);
753                 }
754                 spin_unlock_irqrestore(&qp->s_lock, flags);
755
756                 /* Notify ipath_destroy_qp() if it is waiting. */
757                 if (atomic_dec_and_test(&qp->refcount))
758                         wake_up(&qp->wait);
759         }
760 }
761
762 static void update_sge(struct ipath_sge_state *ss, u32 length)
763 {
764         struct ipath_sge *sge = &ss->sge;
765
766         sge->vaddr += length;
767         sge->length -= length;
768         sge->sge_length -= length;
769         if (sge->sge_length == 0) {
770                 if (--ss->num_sge)
771                         *sge = *ss->sg_list++;
772         } else if (sge->length == 0 && sge->mr != NULL) {
773                 if (++sge->n >= IPATH_SEGSZ) {
774                         if (++sge->m >= sge->mr->mapsz)
775                                 return;
776                         sge->n = 0;
777                 }
778                 sge->vaddr = sge->mr->map[sge->m]->segs[sge->n].vaddr;
779                 sge->length = sge->mr->map[sge->m]->segs[sge->n].length;
780         }
781 }
782
783 #ifdef __LITTLE_ENDIAN
784 static inline u32 get_upper_bits(u32 data, u32 shift)
785 {
786         return data >> shift;
787 }
788
789 static inline u32 set_upper_bits(u32 data, u32 shift)
790 {
791         return data << shift;
792 }
793
794 static inline u32 clear_upper_bytes(u32 data, u32 n, u32 off)
795 {
796         data <<= ((sizeof(u32) - n) * BITS_PER_BYTE);
797         data >>= ((sizeof(u32) - n - off) * BITS_PER_BYTE);
798         return data;
799 }
800 #else
801 static inline u32 get_upper_bits(u32 data, u32 shift)
802 {
803         return data << shift;
804 }
805
806 static inline u32 set_upper_bits(u32 data, u32 shift)
807 {
808         return data >> shift;
809 }
810
811 static inline u32 clear_upper_bytes(u32 data, u32 n, u32 off)
812 {
813         data >>= ((sizeof(u32) - n) * BITS_PER_BYTE);
814         data <<= ((sizeof(u32) - n - off) * BITS_PER_BYTE);
815         return data;
816 }
817 #endif
818
819 static void copy_io(u32 __iomem *piobuf, struct ipath_sge_state *ss,
820                     u32 length, unsigned flush_wc)
821 {
822         u32 extra = 0;
823         u32 data = 0;
824         u32 last;
825
826         while (1) {
827                 u32 len = ss->sge.length;
828                 u32 off;
829
830                 if (len > length)
831                         len = length;
832                 if (len > ss->sge.sge_length)
833                         len = ss->sge.sge_length;
834                 BUG_ON(len == 0);
835                 /* If the source address is not aligned, try to align it. */
836                 off = (unsigned long)ss->sge.vaddr & (sizeof(u32) - 1);
837                 if (off) {
838                         u32 *addr = (u32 *)((unsigned long)ss->sge.vaddr &
839                                             ~(sizeof(u32) - 1));
840                         u32 v = get_upper_bits(*addr, off * BITS_PER_BYTE);
841                         u32 y;
842
843                         y = sizeof(u32) - off;
844                         if (len > y)
845                                 len = y;
846                         if (len + extra >= sizeof(u32)) {
847                                 data |= set_upper_bits(v, extra *
848                                                        BITS_PER_BYTE);
849                                 len = sizeof(u32) - extra;
850                                 if (len == length) {
851                                         last = data;
852                                         break;
853                                 }
854                                 __raw_writel(data, piobuf);
855                                 piobuf++;
856                                 extra = 0;
857                                 data = 0;
858                         } else {
859                                 /* Clear unused upper bytes */
860                                 data |= clear_upper_bytes(v, len, extra);
861                                 if (len == length) {
862                                         last = data;
863                                         break;
864                                 }
865                                 extra += len;
866                         }
867                 } else if (extra) {
868                         /* Source address is aligned. */
869                         u32 *addr = (u32 *) ss->sge.vaddr;
870                         int shift = extra * BITS_PER_BYTE;
871                         int ushift = 32 - shift;
872                         u32 l = len;
873
874                         while (l >= sizeof(u32)) {
875                                 u32 v = *addr;
876
877                                 data |= set_upper_bits(v, shift);
878                                 __raw_writel(data, piobuf);
879                                 data = get_upper_bits(v, ushift);
880                                 piobuf++;
881                                 addr++;
882                                 l -= sizeof(u32);
883                         }
884                         /*
885                          * We still have 'extra' number of bytes leftover.
886                          */
887                         if (l) {
888                                 u32 v = *addr;
889
890                                 if (l + extra >= sizeof(u32)) {
891                                         data |= set_upper_bits(v, shift);
892                                         len -= l + extra - sizeof(u32);
893                                         if (len == length) {
894                                                 last = data;
895                                                 break;
896                                         }
897                                         __raw_writel(data, piobuf);
898                                         piobuf++;
899                                         extra = 0;
900                                         data = 0;
901                                 } else {
902                                         /* Clear unused upper bytes */
903                                         data |= clear_upper_bytes(v, l,
904                                                                   extra);
905                                         if (len == length) {
906                                                 last = data;
907                                                 break;
908                                         }
909                                         extra += l;
910                                 }
911                         } else if (len == length) {
912                                 last = data;
913                                 break;
914                         }
915                 } else if (len == length) {
916                         u32 w;
917
918                         /*
919                          * Need to round up for the last dword in the
920                          * packet.
921                          */
922                         w = (len + 3) >> 2;
923                         __iowrite32_copy(piobuf, ss->sge.vaddr, w - 1);
924                         piobuf += w - 1;
925                         last = ((u32 *) ss->sge.vaddr)[w - 1];
926                         break;
927                 } else {
928                         u32 w = len >> 2;
929
930                         __iowrite32_copy(piobuf, ss->sge.vaddr, w);
931                         piobuf += w;
932
933                         extra = len & (sizeof(u32) - 1);
934                         if (extra) {
935                                 u32 v = ((u32 *) ss->sge.vaddr)[w];
936
937                                 /* Clear unused upper bytes */
938                                 data = clear_upper_bytes(v, extra, 0);
939                         }
940                 }
941                 update_sge(ss, len);
942                 length -= len;
943         }
944         /* Update address before sending packet. */
945         update_sge(ss, length);
946         if (flush_wc) {
947                 /* must flush early everything before trigger word */
948                 ipath_flush_wc();
949                 __raw_writel(last, piobuf);
950                 /* be sure trigger word is written */
951                 ipath_flush_wc();
952         } else
953                 __raw_writel(last, piobuf);
954 }
955
956 /*
957  * Convert IB rate to delay multiplier.
958  */
959 unsigned ipath_ib_rate_to_mult(enum ib_rate rate)
960 {
961         switch (rate) {
962         case IB_RATE_2_5_GBPS: return 8;
963         case IB_RATE_5_GBPS:   return 4;
964         case IB_RATE_10_GBPS:  return 2;
965         case IB_RATE_20_GBPS:  return 1;
966         default:               return 0;
967         }
968 }
969
970 /*
971  * Convert delay multiplier to IB rate
972  */
973 static enum ib_rate ipath_mult_to_ib_rate(unsigned mult)
974 {
975         switch (mult) {
976         case 8:  return IB_RATE_2_5_GBPS;
977         case 4:  return IB_RATE_5_GBPS;
978         case 2:  return IB_RATE_10_GBPS;
979         case 1:  return IB_RATE_20_GBPS;
980         default: return IB_RATE_PORT_CURRENT;
981         }
982 }
983
984 static inline struct ipath_verbs_txreq *get_txreq(struct ipath_ibdev *dev)
985 {
986         struct ipath_verbs_txreq *tx = NULL;
987         unsigned long flags;
988
989         spin_lock_irqsave(&dev->pending_lock, flags);
990         if (!list_empty(&dev->txreq_free)) {
991                 struct list_head *l = dev->txreq_free.next;
992
993                 list_del(l);
994                 tx = list_entry(l, struct ipath_verbs_txreq, txreq.list);
995         }
996         spin_unlock_irqrestore(&dev->pending_lock, flags);
997         return tx;
998 }
999
1000 static inline void put_txreq(struct ipath_ibdev *dev,
1001                              struct ipath_verbs_txreq *tx)
1002 {
1003         unsigned long flags;
1004
1005         spin_lock_irqsave(&dev->pending_lock, flags);
1006         list_add(&tx->txreq.list, &dev->txreq_free);
1007         spin_unlock_irqrestore(&dev->pending_lock, flags);
1008 }
1009
1010 static void sdma_complete(void *cookie, int status)
1011 {
1012         struct ipath_verbs_txreq *tx = cookie;
1013         struct ipath_qp *qp = tx->qp;
1014         struct ipath_ibdev *dev = to_idev(qp->ibqp.device);
1015
1016         /* Generate a completion queue entry if needed */
1017         if (qp->ibqp.qp_type != IB_QPT_RC && tx->wqe) {
1018                 enum ib_wc_status ibs = status == IPATH_SDMA_TXREQ_S_OK ?
1019                         IB_WC_SUCCESS : IB_WC_WR_FLUSH_ERR;
1020
1021                 ipath_send_complete(qp, tx->wqe, ibs);
1022         }
1023
1024         if (tx->txreq.flags & IPATH_SDMA_TXREQ_F_FREEBUF)
1025                 kfree(tx->txreq.map_addr);
1026         put_txreq(dev, tx);
1027
1028         if (atomic_dec_and_test(&qp->refcount))
1029                 wake_up(&qp->wait);
1030 }
1031
1032 /*
1033  * Compute the number of clock cycles of delay before sending the next packet.
1034  * The multipliers reflect the number of clocks for the fastest rate so
1035  * one tick at 4xDDR is 8 ticks at 1xSDR.
1036  * If the destination port will take longer to receive a packet than
1037  * the outgoing link can send it, we need to delay sending the next packet
1038  * by the difference in time it takes the receiver to receive and the sender
1039  * to send this packet.
1040  * Note that this delay is always correct for UC and RC but not always
1041  * optimal for UD. For UD, the destination HCA can be different for each
1042  * packet, in which case, we could send packets to a different destination
1043  * while "waiting" for the delay. The overhead for doing this without
1044  * HW support is more than just paying the cost of delaying some packets
1045  * unnecessarily.
1046  */
1047 static inline unsigned ipath_pkt_delay(u32 plen, u8 snd_mult, u8 rcv_mult)
1048 {
1049         return (rcv_mult > snd_mult) ?
1050                 (plen * (rcv_mult - snd_mult) + 1) >> 1 : 0;
1051 }
1052
1053 static int ipath_verbs_send_dma(struct ipath_qp *qp,
1054                                 struct ipath_ib_header *hdr, u32 hdrwords,
1055                                 struct ipath_sge_state *ss, u32 len,
1056                                 u32 plen, u32 dwords)
1057 {
1058         struct ipath_ibdev *dev = to_idev(qp->ibqp.device);
1059         struct ipath_devdata *dd = dev->dd;
1060         struct ipath_verbs_txreq *tx;
1061         u32 *piobuf;
1062         u32 control;
1063         u32 ndesc;
1064         int ret;
1065
1066         tx = qp->s_tx;
1067         if (tx) {
1068                 qp->s_tx = NULL;
1069                 /* resend previously constructed packet */
1070                 ret = ipath_sdma_verbs_send(dd, tx->ss, tx->len, tx);
1071                 if (ret)
1072                         qp->s_tx = tx;
1073                 goto bail;
1074         }
1075
1076         tx = get_txreq(dev);
1077         if (!tx) {
1078                 ret = -EBUSY;
1079                 goto bail;
1080         }
1081
1082         /*
1083          * Get the saved delay count we computed for the previous packet
1084          * and save the delay count for this packet to be used next time
1085          * we get here.
1086          */
1087         control = qp->s_pkt_delay;
1088         qp->s_pkt_delay = ipath_pkt_delay(plen, dd->delay_mult, qp->s_dmult);
1089
1090         tx->qp = qp;
1091         atomic_inc(&qp->refcount);
1092         tx->wqe = qp->s_wqe;
1093         tx->txreq.callback = sdma_complete;
1094         tx->txreq.callback_cookie = tx;
1095         tx->txreq.flags = IPATH_SDMA_TXREQ_F_HEADTOHOST |
1096                 IPATH_SDMA_TXREQ_F_INTREQ | IPATH_SDMA_TXREQ_F_FREEDESC;
1097         if (plen + 1 >= IPATH_SMALLBUF_DWORDS)
1098                 tx->txreq.flags |= IPATH_SDMA_TXREQ_F_USELARGEBUF;
1099
1100         /* VL15 packets bypass credit check */
1101         if ((be16_to_cpu(hdr->lrh[0]) >> 12) == 15) {
1102                 control |= 1ULL << 31;
1103                 tx->txreq.flags |= IPATH_SDMA_TXREQ_F_VL15;
1104         }
1105
1106         if (len) {
1107                 /*
1108                  * Don't try to DMA if it takes more descriptors than
1109                  * the queue holds.
1110                  */
1111                 ndesc = ipath_count_sge(ss, len);
1112                 if (ndesc >= dd->ipath_sdma_descq_cnt)
1113                         ndesc = 0;
1114         } else
1115                 ndesc = 1;
1116         if (ndesc) {
1117                 tx->hdr.pbc[0] = cpu_to_le32(plen);
1118                 tx->hdr.pbc[1] = cpu_to_le32(control);
1119                 memcpy(&tx->hdr.hdr, hdr, hdrwords << 2);
1120                 tx->txreq.sg_count = ndesc;
1121                 tx->map_len = (hdrwords + 2) << 2;
1122                 tx->txreq.map_addr = &tx->hdr;
1123                 ret = ipath_sdma_verbs_send(dd, ss, dwords, tx);
1124                 if (ret) {
1125                         /* save ss and length in dwords */
1126                         tx->ss = ss;
1127                         tx->len = dwords;
1128                         qp->s_tx = tx;
1129                 }
1130                 goto bail;
1131         }
1132
1133         /* Allocate a buffer and copy the header and payload to it. */
1134         tx->map_len = (plen + 1) << 2;
1135         piobuf = kmalloc(tx->map_len, GFP_ATOMIC);
1136         if (unlikely(piobuf == NULL)) {
1137                 ret = -EBUSY;
1138                 goto err_tx;
1139         }
1140         tx->txreq.map_addr = piobuf;
1141         tx->txreq.flags |= IPATH_SDMA_TXREQ_F_FREEBUF;
1142         tx->txreq.sg_count = 1;
1143
1144         *piobuf++ = (__force u32) cpu_to_le32(plen);
1145         *piobuf++ = (__force u32) cpu_to_le32(control);
1146         memcpy(piobuf, hdr, hdrwords << 2);
1147         ipath_copy_from_sge(piobuf + hdrwords, ss, len);
1148
1149         ret = ipath_sdma_verbs_send(dd, NULL, 0, tx);
1150         /*
1151          * If we couldn't queue the DMA request, save the info
1152          * and try again later rather than destroying the
1153          * buffer and undoing the side effects of the copy.
1154          */
1155         if (ret) {
1156                 tx->ss = NULL;
1157                 tx->len = 0;
1158                 qp->s_tx = tx;
1159         }
1160         dev->n_unaligned++;
1161         goto bail;
1162
1163 err_tx:
1164         if (atomic_dec_and_test(&qp->refcount))
1165                 wake_up(&qp->wait);
1166         put_txreq(dev, tx);
1167 bail:
1168         return ret;
1169 }
1170
1171 static int ipath_verbs_send_pio(struct ipath_qp *qp,
1172                                 struct ipath_ib_header *ibhdr, u32 hdrwords,
1173                                 struct ipath_sge_state *ss, u32 len,
1174                                 u32 plen, u32 dwords)
1175 {
1176         struct ipath_devdata *dd = to_idev(qp->ibqp.device)->dd;
1177         u32 *hdr = (u32 *) ibhdr;
1178         u32 __iomem *piobuf;
1179         unsigned flush_wc;
1180         u32 control;
1181         int ret;
1182
1183         piobuf = ipath_getpiobuf(dd, plen, NULL);
1184         if (unlikely(piobuf == NULL)) {
1185                 ret = -EBUSY;
1186                 goto bail;
1187         }
1188
1189         /*
1190          * Get the saved delay count we computed for the previous packet
1191          * and save the delay count for this packet to be used next time
1192          * we get here.
1193          */
1194         control = qp->s_pkt_delay;
1195         qp->s_pkt_delay = ipath_pkt_delay(plen, dd->delay_mult, qp->s_dmult);
1196
1197         /* VL15 packets bypass credit check */
1198         if ((be16_to_cpu(ibhdr->lrh[0]) >> 12) == 15)
1199                 control |= 1ULL << 31;
1200
1201         /*
1202          * Write the length to the control qword plus any needed flags.
1203          * We have to flush after the PBC for correctness on some cpus
1204          * or WC buffer can be written out of order.
1205          */
1206         writeq(((u64) control << 32) | plen, piobuf);
1207         piobuf += 2;
1208
1209         flush_wc = dd->ipath_flags & IPATH_PIO_FLUSH_WC;
1210         if (len == 0) {
1211                 /*
1212                  * If there is just the header portion, must flush before
1213                  * writing last word of header for correctness, and after
1214                  * the last header word (trigger word).
1215                  */
1216                 if (flush_wc) {
1217                         ipath_flush_wc();
1218                         __iowrite32_copy(piobuf, hdr, hdrwords - 1);
1219                         ipath_flush_wc();
1220                         __raw_writel(hdr[hdrwords - 1], piobuf + hdrwords - 1);
1221                         ipath_flush_wc();
1222                 } else
1223                         __iowrite32_copy(piobuf, hdr, hdrwords);
1224                 goto done;
1225         }
1226
1227         if (flush_wc)
1228                 ipath_flush_wc();
1229         __iowrite32_copy(piobuf, hdr, hdrwords);
1230         piobuf += hdrwords;
1231
1232         /* The common case is aligned and contained in one segment. */
1233         if (likely(ss->num_sge == 1 && len <= ss->sge.length &&
1234                    !((unsigned long)ss->sge.vaddr & (sizeof(u32) - 1)))) {
1235                 u32 *addr = (u32 *) ss->sge.vaddr;
1236
1237                 /* Update address before sending packet. */
1238                 update_sge(ss, len);
1239                 if (flush_wc) {
1240                         __iowrite32_copy(piobuf, addr, dwords - 1);
1241                         /* must flush early everything before trigger word */
1242                         ipath_flush_wc();
1243                         __raw_writel(addr[dwords - 1], piobuf + dwords - 1);
1244                         /* be sure trigger word is written */
1245                         ipath_flush_wc();
1246                 } else
1247                         __iowrite32_copy(piobuf, addr, dwords);
1248                 goto done;
1249         }
1250         copy_io(piobuf, ss, len, flush_wc);
1251 done:
1252         if (qp->s_wqe)
1253                 ipath_send_complete(qp, qp->s_wqe, IB_WC_SUCCESS);
1254         ret = 0;
1255 bail:
1256         return ret;
1257 }
1258
1259 /**
1260  * ipath_verbs_send - send a packet
1261  * @qp: the QP to send on
1262  * @hdr: the packet header
1263  * @hdrwords: the number of 32-bit words in the header
1264  * @ss: the SGE to send
1265  * @len: the length of the packet in bytes
1266  */
1267 int ipath_verbs_send(struct ipath_qp *qp, struct ipath_ib_header *hdr,
1268                      u32 hdrwords, struct ipath_sge_state *ss, u32 len)
1269 {
1270         struct ipath_devdata *dd = to_idev(qp->ibqp.device)->dd;
1271         u32 plen;
1272         int ret;
1273         u32 dwords = (len + 3) >> 2;
1274
1275         /*
1276          * Calculate the send buffer trigger address.
1277          * The +1 counts for the pbc control dword following the pbc length.
1278          */
1279         plen = hdrwords + dwords + 1;
1280
1281         /*
1282          * VL15 packets (IB_QPT_SMI) will always use PIO, so we
1283          * can defer SDMA restart until link goes ACTIVE without
1284          * worrying about just how we got there.
1285          */
1286         if (qp->ibqp.qp_type == IB_QPT_SMI)
1287                 ret = ipath_verbs_send_pio(qp, hdr, hdrwords, ss, len,
1288                                            plen, dwords);
1289         /* All non-VL15 packets are dropped if link is not ACTIVE */
1290         else if (!(dd->ipath_flags & IPATH_LINKACTIVE)) {
1291                 if (qp->s_wqe)
1292                         ipath_send_complete(qp, qp->s_wqe, IB_WC_SUCCESS);
1293                 ret = 0;
1294         } else if (dd->ipath_flags & IPATH_HAS_SEND_DMA)
1295                 ret = ipath_verbs_send_dma(qp, hdr, hdrwords, ss, len,
1296                                            plen, dwords);
1297         else
1298                 ret = ipath_verbs_send_pio(qp, hdr, hdrwords, ss, len,
1299                                            plen, dwords);
1300
1301         return ret;
1302 }
1303
1304 int ipath_snapshot_counters(struct ipath_devdata *dd, u64 *swords,
1305                             u64 *rwords, u64 *spkts, u64 *rpkts,
1306                             u64 *xmit_wait)
1307 {
1308         int ret;
1309
1310         if (!(dd->ipath_flags & IPATH_INITTED)) {
1311                 /* no hardware, freeze, etc. */
1312                 ret = -EINVAL;
1313                 goto bail;
1314         }
1315         *swords = ipath_snap_cntr(dd, dd->ipath_cregs->cr_wordsendcnt);
1316         *rwords = ipath_snap_cntr(dd, dd->ipath_cregs->cr_wordrcvcnt);
1317         *spkts = ipath_snap_cntr(dd, dd->ipath_cregs->cr_pktsendcnt);
1318         *rpkts = ipath_snap_cntr(dd, dd->ipath_cregs->cr_pktrcvcnt);
1319         *xmit_wait = ipath_snap_cntr(dd, dd->ipath_cregs->cr_sendstallcnt);
1320
1321         ret = 0;
1322
1323 bail:
1324         return ret;
1325 }
1326
1327 /**
1328  * ipath_get_counters - get various chip counters
1329  * @dd: the infinipath device
1330  * @cntrs: counters are placed here
1331  *
1332  * Return the counters needed by recv_pma_get_portcounters().
1333  */
1334 int ipath_get_counters(struct ipath_devdata *dd,
1335                        struct ipath_verbs_counters *cntrs)
1336 {
1337         struct ipath_cregs const *crp = dd->ipath_cregs;
1338         int ret;
1339
1340         if (!(dd->ipath_flags & IPATH_INITTED)) {
1341                 /* no hardware, freeze, etc. */
1342                 ret = -EINVAL;
1343                 goto bail;
1344         }
1345         cntrs->symbol_error_counter =
1346                 ipath_snap_cntr(dd, crp->cr_ibsymbolerrcnt);
1347         cntrs->link_error_recovery_counter =
1348                 ipath_snap_cntr(dd, crp->cr_iblinkerrrecovcnt);
1349         /*
1350          * The link downed counter counts when the other side downs the
1351          * connection.  We add in the number of times we downed the link
1352          * due to local link integrity errors to compensate.
1353          */
1354         cntrs->link_downed_counter =
1355                 ipath_snap_cntr(dd, crp->cr_iblinkdowncnt);
1356         cntrs->port_rcv_errors =
1357                 ipath_snap_cntr(dd, crp->cr_rxdroppktcnt) +
1358                 ipath_snap_cntr(dd, crp->cr_rcvovflcnt) +
1359                 ipath_snap_cntr(dd, crp->cr_portovflcnt) +
1360                 ipath_snap_cntr(dd, crp->cr_err_rlencnt) +
1361                 ipath_snap_cntr(dd, crp->cr_invalidrlencnt) +
1362                 ipath_snap_cntr(dd, crp->cr_errlinkcnt) +
1363                 ipath_snap_cntr(dd, crp->cr_erricrccnt) +
1364                 ipath_snap_cntr(dd, crp->cr_errvcrccnt) +
1365                 ipath_snap_cntr(dd, crp->cr_errlpcrccnt) +
1366                 ipath_snap_cntr(dd, crp->cr_badformatcnt) +
1367                 dd->ipath_rxfc_unsupvl_errs;
1368         if (crp->cr_rxotherlocalphyerrcnt)
1369                 cntrs->port_rcv_errors +=
1370                         ipath_snap_cntr(dd, crp->cr_rxotherlocalphyerrcnt);
1371         if (crp->cr_rxvlerrcnt)
1372                 cntrs->port_rcv_errors +=
1373                         ipath_snap_cntr(dd, crp->cr_rxvlerrcnt);
1374         cntrs->port_rcv_remphys_errors =
1375                 ipath_snap_cntr(dd, crp->cr_rcvebpcnt);
1376         cntrs->port_xmit_discards = ipath_snap_cntr(dd, crp->cr_unsupvlcnt);
1377         cntrs->port_xmit_data = ipath_snap_cntr(dd, crp->cr_wordsendcnt);
1378         cntrs->port_rcv_data = ipath_snap_cntr(dd, crp->cr_wordrcvcnt);
1379         cntrs->port_xmit_packets = ipath_snap_cntr(dd, crp->cr_pktsendcnt);
1380         cntrs->port_rcv_packets = ipath_snap_cntr(dd, crp->cr_pktrcvcnt);
1381         cntrs->local_link_integrity_errors =
1382                 crp->cr_locallinkintegrityerrcnt ?
1383                 ipath_snap_cntr(dd, crp->cr_locallinkintegrityerrcnt) :
1384                 ((dd->ipath_flags & IPATH_GPIO_ERRINTRS) ?
1385                  dd->ipath_lli_errs : dd->ipath_lli_errors);
1386         cntrs->excessive_buffer_overrun_errors =
1387                 crp->cr_excessbufferovflcnt ?
1388                 ipath_snap_cntr(dd, crp->cr_excessbufferovflcnt) :
1389                 dd->ipath_overrun_thresh_errs;
1390         cntrs->vl15_dropped = crp->cr_vl15droppedpktcnt ?
1391                 ipath_snap_cntr(dd, crp->cr_vl15droppedpktcnt) : 0;
1392
1393         ret = 0;
1394
1395 bail:
1396         return ret;
1397 }
1398
1399 /**
1400  * ipath_ib_piobufavail - callback when a PIO buffer is available
1401  * @arg: the device pointer
1402  *
1403  * This is called from ipath_intr() at interrupt level when a PIO buffer is
1404  * available after ipath_verbs_send() returned an error that no buffers were
1405  * available.  Return 1 if we consumed all the PIO buffers and we still have
1406  * QPs waiting for buffers (for now, just do a tasklet_hi_schedule and
1407  * return zero).
1408  */
1409 int ipath_ib_piobufavail(struct ipath_ibdev *dev)
1410 {
1411         struct ipath_qp *qp;
1412         unsigned long flags;
1413
1414         if (dev == NULL)
1415                 goto bail;
1416
1417         spin_lock_irqsave(&dev->pending_lock, flags);
1418         while (!list_empty(&dev->piowait)) {
1419                 qp = list_entry(dev->piowait.next, struct ipath_qp,
1420                                 piowait);
1421                 list_del_init(&qp->piowait);
1422                 clear_bit(IPATH_S_BUSY, &qp->s_busy);
1423                 tasklet_hi_schedule(&qp->s_task);
1424         }
1425         spin_unlock_irqrestore(&dev->pending_lock, flags);
1426
1427 bail:
1428         return 0;
1429 }
1430
1431 static int ipath_query_device(struct ib_device *ibdev,
1432                               struct ib_device_attr *props)
1433 {
1434         struct ipath_ibdev *dev = to_idev(ibdev);
1435
1436         memset(props, 0, sizeof(*props));
1437
1438         props->device_cap_flags = IB_DEVICE_BAD_PKEY_CNTR |
1439                 IB_DEVICE_BAD_QKEY_CNTR | IB_DEVICE_SHUTDOWN_PORT |
1440                 IB_DEVICE_SYS_IMAGE_GUID;
1441         props->page_size_cap = PAGE_SIZE;
1442         props->vendor_id = dev->dd->ipath_vendorid;
1443         props->vendor_part_id = dev->dd->ipath_deviceid;
1444         props->hw_ver = dev->dd->ipath_pcirev;
1445
1446         props->sys_image_guid = dev->sys_image_guid;
1447
1448         props->max_mr_size = ~0ull;
1449         props->max_qp = ib_ipath_max_qps;
1450         props->max_qp_wr = ib_ipath_max_qp_wrs;
1451         props->max_sge = ib_ipath_max_sges;
1452         props->max_cq = ib_ipath_max_cqs;
1453         props->max_ah = ib_ipath_max_ahs;
1454         props->max_cqe = ib_ipath_max_cqes;
1455         props->max_mr = dev->lk_table.max;
1456         props->max_fmr = dev->lk_table.max;
1457         props->max_map_per_fmr = 32767;
1458         props->max_pd = ib_ipath_max_pds;
1459         props->max_qp_rd_atom = IPATH_MAX_RDMA_ATOMIC;
1460         props->max_qp_init_rd_atom = 255;
1461         /* props->max_res_rd_atom */
1462         props->max_srq = ib_ipath_max_srqs;
1463         props->max_srq_wr = ib_ipath_max_srq_wrs;
1464         props->max_srq_sge = ib_ipath_max_srq_sges;
1465         /* props->local_ca_ack_delay */
1466         props->atomic_cap = IB_ATOMIC_GLOB;
1467         props->max_pkeys = ipath_get_npkeys(dev->dd);
1468         props->max_mcast_grp = ib_ipath_max_mcast_grps;
1469         props->max_mcast_qp_attach = ib_ipath_max_mcast_qp_attached;
1470         props->max_total_mcast_qp_attach = props->max_mcast_qp_attach *
1471                 props->max_mcast_grp;
1472
1473         return 0;
1474 }
1475
1476 const u8 ipath_cvt_physportstate[32] = {
1477         [INFINIPATH_IBCS_LT_STATE_DISABLED] = IB_PHYSPORTSTATE_DISABLED,
1478         [INFINIPATH_IBCS_LT_STATE_LINKUP] = IB_PHYSPORTSTATE_LINKUP,
1479         [INFINIPATH_IBCS_LT_STATE_POLLACTIVE] = IB_PHYSPORTSTATE_POLL,
1480         [INFINIPATH_IBCS_LT_STATE_POLLQUIET] = IB_PHYSPORTSTATE_POLL,
1481         [INFINIPATH_IBCS_LT_STATE_SLEEPDELAY] = IB_PHYSPORTSTATE_SLEEP,
1482         [INFINIPATH_IBCS_LT_STATE_SLEEPQUIET] = IB_PHYSPORTSTATE_SLEEP,
1483         [INFINIPATH_IBCS_LT_STATE_CFGDEBOUNCE] =
1484                 IB_PHYSPORTSTATE_CFG_TRAIN,
1485         [INFINIPATH_IBCS_LT_STATE_CFGRCVFCFG] =
1486                 IB_PHYSPORTSTATE_CFG_TRAIN,
1487         [INFINIPATH_IBCS_LT_STATE_CFGWAITRMT] =
1488                 IB_PHYSPORTSTATE_CFG_TRAIN,
1489         [INFINIPATH_IBCS_LT_STATE_CFGIDLE] = IB_PHYSPORTSTATE_CFG_TRAIN,
1490         [INFINIPATH_IBCS_LT_STATE_RECOVERRETRAIN] =
1491                 IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
1492         [INFINIPATH_IBCS_LT_STATE_RECOVERWAITRMT] =
1493                 IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
1494         [INFINIPATH_IBCS_LT_STATE_RECOVERIDLE] =
1495                 IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
1496         [0x10] = IB_PHYSPORTSTATE_CFG_TRAIN,
1497         [0x11] = IB_PHYSPORTSTATE_CFG_TRAIN,
1498         [0x12] = IB_PHYSPORTSTATE_CFG_TRAIN,
1499         [0x13] = IB_PHYSPORTSTATE_CFG_TRAIN,
1500         [0x14] = IB_PHYSPORTSTATE_CFG_TRAIN,
1501         [0x15] = IB_PHYSPORTSTATE_CFG_TRAIN,
1502         [0x16] = IB_PHYSPORTSTATE_CFG_TRAIN,
1503         [0x17] = IB_PHYSPORTSTATE_CFG_TRAIN
1504 };
1505
1506 u32 ipath_get_cr_errpkey(struct ipath_devdata *dd)
1507 {
1508         return ipath_read_creg32(dd, dd->ipath_cregs->cr_errpkey);
1509 }
1510
1511 static int ipath_query_port(struct ib_device *ibdev,
1512                             u8 port, struct ib_port_attr *props)
1513 {
1514         struct ipath_ibdev *dev = to_idev(ibdev);
1515         struct ipath_devdata *dd = dev->dd;
1516         enum ib_mtu mtu;
1517         u16 lid = dd->ipath_lid;
1518         u64 ibcstat;
1519
1520         memset(props, 0, sizeof(*props));
1521         props->lid = lid ? lid : __constant_be16_to_cpu(IB_LID_PERMISSIVE);
1522         props->lmc = dd->ipath_lmc;
1523         props->sm_lid = dev->sm_lid;
1524         props->sm_sl = dev->sm_sl;
1525         ibcstat = dd->ipath_lastibcstat;
1526         /* map LinkState to IB portinfo values.  */
1527         props->state = ipath_ib_linkstate(dd, ibcstat) + 1;
1528
1529         /* See phys_state_show() */
1530         props->phys_state = /* MEA: assumes shift == 0 */
1531                 ipath_cvt_physportstate[dd->ipath_lastibcstat &
1532                 dd->ibcs_lts_mask];
1533         props->port_cap_flags = dev->port_cap_flags;
1534         props->gid_tbl_len = 1;
1535         props->max_msg_sz = 0x80000000;
1536         props->pkey_tbl_len = ipath_get_npkeys(dd);
1537         props->bad_pkey_cntr = ipath_get_cr_errpkey(dd) -
1538                 dev->z_pkey_violations;
1539         props->qkey_viol_cntr = dev->qkey_violations;
1540         props->active_width = dd->ipath_link_width_active;
1541         /* See rate_show() */
1542         props->active_speed = dd->ipath_link_speed_active;
1543         props->max_vl_num = 1;          /* VLCap = VL0 */
1544         props->init_type_reply = 0;
1545
1546         props->max_mtu = ipath_mtu4096 ? IB_MTU_4096 : IB_MTU_2048;
1547         switch (dd->ipath_ibmtu) {
1548         case 4096:
1549                 mtu = IB_MTU_4096;
1550                 break;
1551         case 2048:
1552                 mtu = IB_MTU_2048;
1553                 break;
1554         case 1024:
1555                 mtu = IB_MTU_1024;
1556                 break;
1557         case 512:
1558                 mtu = IB_MTU_512;
1559                 break;
1560         case 256:
1561                 mtu = IB_MTU_256;
1562                 break;
1563         default:
1564                 mtu = IB_MTU_2048;
1565         }
1566         props->active_mtu = mtu;
1567         props->subnet_timeout = dev->subnet_timeout;
1568
1569         return 0;
1570 }
1571
1572 static int ipath_modify_device(struct ib_device *device,
1573                                int device_modify_mask,
1574                                struct ib_device_modify *device_modify)
1575 {
1576         int ret;
1577
1578         if (device_modify_mask & ~(IB_DEVICE_MODIFY_SYS_IMAGE_GUID |
1579                                    IB_DEVICE_MODIFY_NODE_DESC)) {
1580                 ret = -EOPNOTSUPP;
1581                 goto bail;
1582         }
1583
1584         if (device_modify_mask & IB_DEVICE_MODIFY_NODE_DESC)
1585                 memcpy(device->node_desc, device_modify->node_desc, 64);
1586
1587         if (device_modify_mask & IB_DEVICE_MODIFY_SYS_IMAGE_GUID)
1588                 to_idev(device)->sys_image_guid =
1589                         cpu_to_be64(device_modify->sys_image_guid);
1590
1591         ret = 0;
1592
1593 bail:
1594         return ret;
1595 }
1596
1597 static int ipath_modify_port(struct ib_device *ibdev,
1598                              u8 port, int port_modify_mask,
1599                              struct ib_port_modify *props)
1600 {
1601         struct ipath_ibdev *dev = to_idev(ibdev);
1602
1603         dev->port_cap_flags |= props->set_port_cap_mask;
1604         dev->port_cap_flags &= ~props->clr_port_cap_mask;
1605         if (port_modify_mask & IB_PORT_SHUTDOWN)
1606                 ipath_set_linkstate(dev->dd, IPATH_IB_LINKDOWN);
1607         if (port_modify_mask & IB_PORT_RESET_QKEY_CNTR)
1608                 dev->qkey_violations = 0;
1609         return 0;
1610 }
1611
1612 static int ipath_query_gid(struct ib_device *ibdev, u8 port,
1613                            int index, union ib_gid *gid)
1614 {
1615         struct ipath_ibdev *dev = to_idev(ibdev);
1616         int ret;
1617
1618         if (index >= 1) {
1619                 ret = -EINVAL;
1620                 goto bail;
1621         }
1622         gid->global.subnet_prefix = dev->gid_prefix;
1623         gid->global.interface_id = dev->dd->ipath_guid;
1624
1625         ret = 0;
1626
1627 bail:
1628         return ret;
1629 }
1630
1631 static struct ib_pd *ipath_alloc_pd(struct ib_device *ibdev,
1632                                     struct ib_ucontext *context,
1633                                     struct ib_udata *udata)
1634 {
1635         struct ipath_ibdev *dev = to_idev(ibdev);
1636         struct ipath_pd *pd;
1637         struct ib_pd *ret;
1638
1639         /*
1640          * This is actually totally arbitrary.  Some correctness tests
1641          * assume there's a maximum number of PDs that can be allocated.
1642          * We don't actually have this limit, but we fail the test if
1643          * we allow allocations of more than we report for this value.
1644          */
1645
1646         pd = kmalloc(sizeof *pd, GFP_KERNEL);
1647         if (!pd) {
1648                 ret = ERR_PTR(-ENOMEM);
1649                 goto bail;
1650         }
1651
1652         spin_lock(&dev->n_pds_lock);
1653         if (dev->n_pds_allocated == ib_ipath_max_pds) {
1654                 spin_unlock(&dev->n_pds_lock);
1655                 kfree(pd);
1656                 ret = ERR_PTR(-ENOMEM);
1657                 goto bail;
1658         }
1659
1660         dev->n_pds_allocated++;
1661         spin_unlock(&dev->n_pds_lock);
1662
1663         /* ib_alloc_pd() will initialize pd->ibpd. */
1664         pd->user = udata != NULL;
1665
1666         ret = &pd->ibpd;
1667
1668 bail:
1669         return ret;
1670 }
1671
1672 static int ipath_dealloc_pd(struct ib_pd *ibpd)
1673 {
1674         struct ipath_pd *pd = to_ipd(ibpd);
1675         struct ipath_ibdev *dev = to_idev(ibpd->device);
1676
1677         spin_lock(&dev->n_pds_lock);
1678         dev->n_pds_allocated--;
1679         spin_unlock(&dev->n_pds_lock);
1680
1681         kfree(pd);
1682
1683         return 0;
1684 }
1685
1686 /**
1687  * ipath_create_ah - create an address handle
1688  * @pd: the protection domain
1689  * @ah_attr: the attributes of the AH
1690  *
1691  * This may be called from interrupt context.
1692  */
1693 static struct ib_ah *ipath_create_ah(struct ib_pd *pd,
1694                                      struct ib_ah_attr *ah_attr)
1695 {
1696         struct ipath_ah *ah;
1697         struct ib_ah *ret;
1698         struct ipath_ibdev *dev = to_idev(pd->device);
1699         unsigned long flags;
1700
1701         /* A multicast address requires a GRH (see ch. 8.4.1). */
1702         if (ah_attr->dlid >= IPATH_MULTICAST_LID_BASE &&
1703             ah_attr->dlid != IPATH_PERMISSIVE_LID &&
1704             !(ah_attr->ah_flags & IB_AH_GRH)) {
1705                 ret = ERR_PTR(-EINVAL);
1706                 goto bail;
1707         }
1708
1709         if (ah_attr->dlid == 0) {
1710                 ret = ERR_PTR(-EINVAL);
1711                 goto bail;
1712         }
1713
1714         if (ah_attr->port_num < 1 ||
1715             ah_attr->port_num > pd->device->phys_port_cnt) {
1716                 ret = ERR_PTR(-EINVAL);
1717                 goto bail;
1718         }
1719
1720         ah = kmalloc(sizeof *ah, GFP_ATOMIC);
1721         if (!ah) {
1722                 ret = ERR_PTR(-ENOMEM);
1723                 goto bail;
1724         }
1725
1726         spin_lock_irqsave(&dev->n_ahs_lock, flags);
1727         if (dev->n_ahs_allocated == ib_ipath_max_ahs) {
1728                 spin_unlock_irqrestore(&dev->n_ahs_lock, flags);
1729                 kfree(ah);
1730                 ret = ERR_PTR(-ENOMEM);
1731                 goto bail;
1732         }
1733
1734         dev->n_ahs_allocated++;
1735         spin_unlock_irqrestore(&dev->n_ahs_lock, flags);
1736
1737         /* ib_create_ah() will initialize ah->ibah. */
1738         ah->attr = *ah_attr;
1739         ah->attr.static_rate = ipath_ib_rate_to_mult(ah_attr->static_rate);
1740
1741         ret = &ah->ibah;
1742
1743 bail:
1744         return ret;
1745 }
1746
1747 /**
1748  * ipath_destroy_ah - destroy an address handle
1749  * @ibah: the AH to destroy
1750  *
1751  * This may be called from interrupt context.
1752  */
1753 static int ipath_destroy_ah(struct ib_ah *ibah)
1754 {
1755         struct ipath_ibdev *dev = to_idev(ibah->device);
1756         struct ipath_ah *ah = to_iah(ibah);
1757         unsigned long flags;
1758
1759         spin_lock_irqsave(&dev->n_ahs_lock, flags);
1760         dev->n_ahs_allocated--;
1761         spin_unlock_irqrestore(&dev->n_ahs_lock, flags);
1762
1763         kfree(ah);
1764
1765         return 0;
1766 }
1767
1768 static int ipath_query_ah(struct ib_ah *ibah, struct ib_ah_attr *ah_attr)
1769 {
1770         struct ipath_ah *ah = to_iah(ibah);
1771
1772         *ah_attr = ah->attr;
1773         ah_attr->static_rate = ipath_mult_to_ib_rate(ah->attr.static_rate);
1774
1775         return 0;
1776 }
1777
1778 /**
1779  * ipath_get_npkeys - return the size of the PKEY table for port 0
1780  * @dd: the infinipath device
1781  */
1782 unsigned ipath_get_npkeys(struct ipath_devdata *dd)
1783 {
1784         return ARRAY_SIZE(dd->ipath_pd[0]->port_pkeys);
1785 }
1786
1787 /**
1788  * ipath_get_pkey - return the indexed PKEY from the port 0 PKEY table
1789  * @dd: the infinipath device
1790  * @index: the PKEY index
1791  */
1792 unsigned ipath_get_pkey(struct ipath_devdata *dd, unsigned index)
1793 {
1794         unsigned ret;
1795
1796         if (index >= ARRAY_SIZE(dd->ipath_pd[0]->port_pkeys))
1797                 ret = 0;
1798         else
1799                 ret = dd->ipath_pd[0]->port_pkeys[index];
1800
1801         return ret;
1802 }
1803
1804 static int ipath_query_pkey(struct ib_device *ibdev, u8 port, u16 index,
1805                             u16 *pkey)
1806 {
1807         struct ipath_ibdev *dev = to_idev(ibdev);
1808         int ret;
1809
1810         if (index >= ipath_get_npkeys(dev->dd)) {
1811                 ret = -EINVAL;
1812                 goto bail;
1813         }
1814
1815         *pkey = ipath_get_pkey(dev->dd, index);
1816         ret = 0;
1817
1818 bail:
1819         return ret;
1820 }
1821
1822 /**
1823  * ipath_alloc_ucontext - allocate a ucontest
1824  * @ibdev: the infiniband device
1825  * @udata: not used by the InfiniPath driver
1826  */
1827
1828 static struct ib_ucontext *ipath_alloc_ucontext(struct ib_device *ibdev,
1829                                                 struct ib_udata *udata)
1830 {
1831         struct ipath_ucontext *context;
1832         struct ib_ucontext *ret;
1833
1834         context = kmalloc(sizeof *context, GFP_KERNEL);
1835         if (!context) {
1836                 ret = ERR_PTR(-ENOMEM);
1837                 goto bail;
1838         }
1839
1840         ret = &context->ibucontext;
1841
1842 bail:
1843         return ret;
1844 }
1845
1846 static int ipath_dealloc_ucontext(struct ib_ucontext *context)
1847 {
1848         kfree(to_iucontext(context));
1849         return 0;
1850 }
1851
1852 static int ipath_verbs_register_sysfs(struct ib_device *dev);
1853
1854 static void __verbs_timer(unsigned long arg)
1855 {
1856         struct ipath_devdata *dd = (struct ipath_devdata *) arg;
1857
1858         /* Handle verbs layer timeouts. */
1859         ipath_ib_timer(dd->verbs_dev);
1860
1861         mod_timer(&dd->verbs_timer, jiffies + 1);
1862 }
1863
1864 static int enable_timer(struct ipath_devdata *dd)
1865 {
1866         /*
1867          * Early chips had a design flaw where the chip and kernel idea
1868          * of the tail register don't always agree, and therefore we won't
1869          * get an interrupt on the next packet received.
1870          * If the board supports per packet receive interrupts, use it.
1871          * Otherwise, the timer function periodically checks for packets
1872          * to cover this case.
1873          * Either way, the timer is needed for verbs layer related
1874          * processing.
1875          */
1876         if (dd->ipath_flags & IPATH_GPIO_INTR) {
1877                 ipath_write_kreg(dd, dd->ipath_kregs->kr_debugportselect,
1878                                  0x2074076542310ULL);
1879                 /* Enable GPIO bit 2 interrupt */
1880                 dd->ipath_gpio_mask |= (u64) (1 << IPATH_GPIO_PORT0_BIT);
1881                 ipath_write_kreg(dd, dd->ipath_kregs->kr_gpio_mask,
1882                                  dd->ipath_gpio_mask);
1883         }
1884
1885         init_timer(&dd->verbs_timer);
1886         dd->verbs_timer.function = __verbs_timer;
1887         dd->verbs_timer.data = (unsigned long)dd;
1888         dd->verbs_timer.expires = jiffies + 1;
1889         add_timer(&dd->verbs_timer);
1890
1891         return 0;
1892 }
1893
1894 static int disable_timer(struct ipath_devdata *dd)
1895 {
1896         /* Disable GPIO bit 2 interrupt */
1897         if (dd->ipath_flags & IPATH_GPIO_INTR) {
1898                 /* Disable GPIO bit 2 interrupt */
1899                 dd->ipath_gpio_mask &= ~((u64) (1 << IPATH_GPIO_PORT0_BIT));
1900                 ipath_write_kreg(dd, dd->ipath_kregs->kr_gpio_mask,
1901                                  dd->ipath_gpio_mask);
1902                 /*
1903                  * We might want to undo changes to debugportselect,
1904                  * but how?
1905                  */
1906         }
1907
1908         del_timer_sync(&dd->verbs_timer);
1909
1910         return 0;
1911 }
1912
1913 /**
1914  * ipath_register_ib_device - register our device with the infiniband core
1915  * @dd: the device data structure
1916  * Return the allocated ipath_ibdev pointer or NULL on error.
1917  */
1918 int ipath_register_ib_device(struct ipath_devdata *dd)
1919 {
1920         struct ipath_verbs_counters cntrs;
1921         struct ipath_ibdev *idev;
1922         struct ib_device *dev;
1923         struct ipath_verbs_txreq *tx;
1924         unsigned i;
1925         int ret;
1926
1927         idev = (struct ipath_ibdev *)ib_alloc_device(sizeof *idev);
1928         if (idev == NULL) {
1929                 ret = -ENOMEM;
1930                 goto bail;
1931         }
1932
1933         dev = &idev->ibdev;
1934
1935         if (dd->ipath_sdma_descq_cnt) {
1936                 tx = kmalloc(dd->ipath_sdma_descq_cnt * sizeof *tx,
1937                              GFP_KERNEL);
1938                 if (tx == NULL) {
1939                         ret = -ENOMEM;
1940                         goto err_tx;
1941                 }
1942         } else
1943                 tx = NULL;
1944         idev->txreq_bufs = tx;
1945
1946         /* Only need to initialize non-zero fields. */
1947         spin_lock_init(&idev->n_pds_lock);
1948         spin_lock_init(&idev->n_ahs_lock);
1949         spin_lock_init(&idev->n_cqs_lock);
1950         spin_lock_init(&idev->n_qps_lock);
1951         spin_lock_init(&idev->n_srqs_lock);
1952         spin_lock_init(&idev->n_mcast_grps_lock);
1953
1954         spin_lock_init(&idev->qp_table.lock);
1955         spin_lock_init(&idev->lk_table.lock);
1956         idev->sm_lid = __constant_be16_to_cpu(IB_LID_PERMISSIVE);
1957         /* Set the prefix to the default value (see ch. 4.1.1) */
1958         idev->gid_prefix = __constant_cpu_to_be64(0xfe80000000000000ULL);
1959
1960         ret = ipath_init_qp_table(idev, ib_ipath_qp_table_size);
1961         if (ret)
1962                 goto err_qp;
1963
1964         /*
1965          * The top ib_ipath_lkey_table_size bits are used to index the
1966          * table.  The lower 8 bits can be owned by the user (copied from
1967          * the LKEY).  The remaining bits act as a generation number or tag.
1968          */
1969         idev->lk_table.max = 1 << ib_ipath_lkey_table_size;
1970         idev->lk_table.table = kzalloc(idev->lk_table.max *
1971                                        sizeof(*idev->lk_table.table),
1972                                        GFP_KERNEL);
1973         if (idev->lk_table.table == NULL) {
1974                 ret = -ENOMEM;
1975                 goto err_lk;
1976         }
1977         INIT_LIST_HEAD(&idev->pending_mmaps);
1978         spin_lock_init(&idev->pending_lock);
1979         idev->mmap_offset = PAGE_SIZE;
1980         spin_lock_init(&idev->mmap_offset_lock);
1981         INIT_LIST_HEAD(&idev->pending[0]);
1982         INIT_LIST_HEAD(&idev->pending[1]);
1983         INIT_LIST_HEAD(&idev->pending[2]);
1984         INIT_LIST_HEAD(&idev->piowait);
1985         INIT_LIST_HEAD(&idev->rnrwait);
1986         INIT_LIST_HEAD(&idev->txreq_free);
1987         idev->pending_index = 0;
1988         idev->port_cap_flags =
1989                 IB_PORT_SYS_IMAGE_GUID_SUP | IB_PORT_CLIENT_REG_SUP;
1990         if (dd->ipath_flags & IPATH_HAS_LINK_LATENCY)
1991                 idev->port_cap_flags |= IB_PORT_LINK_LATENCY_SUP;
1992         idev->pma_counter_select[0] = IB_PMA_PORT_XMIT_DATA;
1993         idev->pma_counter_select[1] = IB_PMA_PORT_RCV_DATA;
1994         idev->pma_counter_select[2] = IB_PMA_PORT_XMIT_PKTS;
1995         idev->pma_counter_select[3] = IB_PMA_PORT_RCV_PKTS;
1996         idev->pma_counter_select[4] = IB_PMA_PORT_XMIT_WAIT;
1997
1998         /* Snapshot current HW counters to "clear" them. */
1999         ipath_get_counters(dd, &cntrs);
2000         idev->z_symbol_error_counter = cntrs.symbol_error_counter;
2001         idev->z_link_error_recovery_counter =
2002                 cntrs.link_error_recovery_counter;
2003         idev->z_link_downed_counter = cntrs.link_downed_counter;
2004         idev->z_port_rcv_errors = cntrs.port_rcv_errors;
2005         idev->z_port_rcv_remphys_errors =
2006                 cntrs.port_rcv_remphys_errors;
2007         idev->z_port_xmit_discards = cntrs.port_xmit_discards;
2008         idev->z_port_xmit_data = cntrs.port_xmit_data;
2009         idev->z_port_rcv_data = cntrs.port_rcv_data;
2010         idev->z_port_xmit_packets = cntrs.port_xmit_packets;
2011         idev->z_port_rcv_packets = cntrs.port_rcv_packets;
2012         idev->z_local_link_integrity_errors =
2013                 cntrs.local_link_integrity_errors;
2014         idev->z_excessive_buffer_overrun_errors =
2015                 cntrs.excessive_buffer_overrun_errors;
2016         idev->z_vl15_dropped = cntrs.vl15_dropped;
2017
2018         for (i = 0; i < dd->ipath_sdma_descq_cnt; i++, tx++)
2019                 list_add(&tx->txreq.list, &idev->txreq_free);
2020
2021         /*
2022          * The system image GUID is supposed to be the same for all
2023          * IB HCAs in a single system but since there can be other
2024          * device types in the system, we can't be sure this is unique.
2025          */
2026         if (!sys_image_guid)
2027                 sys_image_guid = dd->ipath_guid;
2028         idev->sys_image_guid = sys_image_guid;
2029         idev->ib_unit = dd->ipath_unit;
2030         idev->dd = dd;
2031
2032         strlcpy(dev->name, "ipath%d", IB_DEVICE_NAME_MAX);
2033         dev->owner = THIS_MODULE;
2034         dev->node_guid = dd->ipath_guid;
2035         dev->uverbs_abi_ver = IPATH_UVERBS_ABI_VERSION;
2036         dev->uverbs_cmd_mask =
2037                 (1ull << IB_USER_VERBS_CMD_GET_CONTEXT)         |
2038                 (1ull << IB_USER_VERBS_CMD_QUERY_DEVICE)        |
2039                 (1ull << IB_USER_VERBS_CMD_QUERY_PORT)          |
2040                 (1ull << IB_USER_VERBS_CMD_ALLOC_PD)            |
2041                 (1ull << IB_USER_VERBS_CMD_DEALLOC_PD)          |
2042                 (1ull << IB_USER_VERBS_CMD_CREATE_AH)           |
2043                 (1ull << IB_USER_VERBS_CMD_DESTROY_AH)          |
2044                 (1ull << IB_USER_VERBS_CMD_QUERY_AH)            |
2045                 (1ull << IB_USER_VERBS_CMD_REG_MR)              |
2046                 (1ull << IB_USER_VERBS_CMD_DEREG_MR)            |
2047                 (1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
2048                 (1ull << IB_USER_VERBS_CMD_CREATE_CQ)           |
2049                 (1ull << IB_USER_VERBS_CMD_RESIZE_CQ)           |
2050                 (1ull << IB_USER_VERBS_CMD_DESTROY_CQ)          |
2051                 (1ull << IB_USER_VERBS_CMD_POLL_CQ)             |
2052                 (1ull << IB_USER_VERBS_CMD_REQ_NOTIFY_CQ)       |
2053                 (1ull << IB_USER_VERBS_CMD_CREATE_QP)           |
2054                 (1ull << IB_USER_VERBS_CMD_QUERY_QP)            |
2055                 (1ull << IB_USER_VERBS_CMD_MODIFY_QP)           |
2056                 (1ull << IB_USER_VERBS_CMD_DESTROY_QP)          |
2057                 (1ull << IB_USER_VERBS_CMD_POST_SEND)           |
2058                 (1ull << IB_USER_VERBS_CMD_POST_RECV)           |
2059                 (1ull << IB_USER_VERBS_CMD_ATTACH_MCAST)        |
2060                 (1ull << IB_USER_VERBS_CMD_DETACH_MCAST)        |
2061                 (1ull << IB_USER_VERBS_CMD_CREATE_SRQ)          |
2062                 (1ull << IB_USER_VERBS_CMD_MODIFY_SRQ)          |
2063                 (1ull << IB_USER_VERBS_CMD_QUERY_SRQ)           |
2064                 (1ull << IB_USER_VERBS_CMD_DESTROY_SRQ)         |
2065                 (1ull << IB_USER_VERBS_CMD_POST_SRQ_RECV);
2066         dev->node_type = RDMA_NODE_IB_CA;
2067         dev->phys_port_cnt = 1;
2068         dev->num_comp_vectors = 1;
2069         dev->dma_device = &dd->pcidev->dev;
2070         dev->query_device = ipath_query_device;
2071         dev->modify_device = ipath_modify_device;
2072         dev->query_port = ipath_query_port;
2073         dev->modify_port = ipath_modify_port;
2074         dev->query_pkey = ipath_query_pkey;
2075         dev->query_gid = ipath_query_gid;
2076         dev->alloc_ucontext = ipath_alloc_ucontext;
2077         dev->dealloc_ucontext = ipath_dealloc_ucontext;
2078         dev->alloc_pd = ipath_alloc_pd;
2079         dev->dealloc_pd = ipath_dealloc_pd;
2080         dev->create_ah = ipath_create_ah;
2081         dev->destroy_ah = ipath_destroy_ah;
2082         dev->query_ah = ipath_query_ah;
2083         dev->create_srq = ipath_create_srq;
2084         dev->modify_srq = ipath_modify_srq;
2085         dev->query_srq = ipath_query_srq;
2086         dev->destroy_srq = ipath_destroy_srq;
2087         dev->create_qp = ipath_create_qp;
2088         dev->modify_qp = ipath_modify_qp;
2089         dev->query_qp = ipath_query_qp;
2090         dev->destroy_qp = ipath_destroy_qp;
2091         dev->post_send = ipath_post_send;
2092         dev->post_recv = ipath_post_receive;
2093         dev->post_srq_recv = ipath_post_srq_receive;
2094         dev->create_cq = ipath_create_cq;
2095         dev->destroy_cq = ipath_destroy_cq;
2096         dev->resize_cq = ipath_resize_cq;
2097         dev->poll_cq = ipath_poll_cq;
2098         dev->req_notify_cq = ipath_req_notify_cq;
2099         dev->get_dma_mr = ipath_get_dma_mr;
2100         dev->reg_phys_mr = ipath_reg_phys_mr;
2101         dev->reg_user_mr = ipath_reg_user_mr;
2102         dev->dereg_mr = ipath_dereg_mr;
2103         dev->alloc_fmr = ipath_alloc_fmr;
2104         dev->map_phys_fmr = ipath_map_phys_fmr;
2105         dev->unmap_fmr = ipath_unmap_fmr;
2106         dev->dealloc_fmr = ipath_dealloc_fmr;
2107         dev->attach_mcast = ipath_multicast_attach;
2108         dev->detach_mcast = ipath_multicast_detach;
2109         dev->process_mad = ipath_process_mad;
2110         dev->mmap = ipath_mmap;
2111         dev->dma_ops = &ipath_dma_mapping_ops;
2112
2113         snprintf(dev->node_desc, sizeof(dev->node_desc),
2114                  IPATH_IDSTR " %s", init_utsname()->nodename);
2115
2116         ret = ib_register_device(dev);
2117         if (ret)
2118                 goto err_reg;
2119
2120         if (ipath_verbs_register_sysfs(dev))
2121                 goto err_class;
2122
2123         enable_timer(dd);
2124
2125         goto bail;
2126
2127 err_class:
2128         ib_unregister_device(dev);
2129 err_reg:
2130         kfree(idev->lk_table.table);
2131 err_lk:
2132         kfree(idev->qp_table.table);
2133 err_qp:
2134         kfree(idev->txreq_bufs);
2135 err_tx:
2136         ib_dealloc_device(dev);
2137         ipath_dev_err(dd, "cannot register verbs: %d!\n", -ret);
2138         idev = NULL;
2139
2140 bail:
2141         dd->verbs_dev = idev;
2142         return ret;
2143 }
2144
2145 void ipath_unregister_ib_device(struct ipath_ibdev *dev)
2146 {
2147         struct ib_device *ibdev = &dev->ibdev;
2148
2149         disable_timer(dev->dd);
2150
2151         ib_unregister_device(ibdev);
2152
2153         if (!list_empty(&dev->pending[0]) ||
2154             !list_empty(&dev->pending[1]) ||
2155             !list_empty(&dev->pending[2]))
2156                 ipath_dev_err(dev->dd, "pending list not empty!\n");
2157         if (!list_empty(&dev->piowait))
2158                 ipath_dev_err(dev->dd, "piowait list not empty!\n");
2159         if (!list_empty(&dev->rnrwait))
2160                 ipath_dev_err(dev->dd, "rnrwait list not empty!\n");
2161         if (!ipath_mcast_tree_empty())
2162                 ipath_dev_err(dev->dd, "multicast table memory leak!\n");
2163         /*
2164          * Note that ipath_unregister_ib_device() can be called before all
2165          * the QPs are destroyed!
2166          */
2167         ipath_free_all_qps(&dev->qp_table);
2168         kfree(dev->qp_table.table);
2169         kfree(dev->lk_table.table);
2170         kfree(dev->txreq_bufs);
2171         ib_dealloc_device(ibdev);
2172 }
2173
2174 static ssize_t show_rev(struct device *device, struct device_attribute *attr,
2175                         char *buf)
2176 {
2177         struct ipath_ibdev *dev =
2178                 container_of(device, struct ipath_ibdev, ibdev.dev);
2179
2180         return sprintf(buf, "%x\n", dev->dd->ipath_pcirev);
2181 }
2182
2183 static ssize_t show_hca(struct device *device, struct device_attribute *attr,
2184                         char *buf)
2185 {
2186         struct ipath_ibdev *dev =
2187                 container_of(device, struct ipath_ibdev, ibdev.dev);
2188         int ret;
2189
2190         ret = dev->dd->ipath_f_get_boardname(dev->dd, buf, 128);
2191         if (ret < 0)
2192                 goto bail;
2193         strcat(buf, "\n");
2194         ret = strlen(buf);
2195
2196 bail:
2197         return ret;
2198 }
2199
2200 static ssize_t show_stats(struct device *device, struct device_attribute *attr,
2201                           char *buf)
2202 {
2203         struct ipath_ibdev *dev =
2204                 container_of(device, struct ipath_ibdev, ibdev.dev);
2205         int i;
2206         int len;
2207
2208         len = sprintf(buf,
2209                       "RC resends  %d\n"
2210                       "RC no QACK  %d\n"
2211                       "RC ACKs     %d\n"
2212                       "RC SEQ NAKs %d\n"
2213                       "RC RDMA seq %d\n"
2214                       "RC RNR NAKs %d\n"
2215                       "RC OTH NAKs %d\n"
2216                       "RC timeouts %d\n"
2217                       "RC RDMA dup %d\n"
2218                       "RC stalls   %d\n"
2219                       "piobuf wait %d\n"
2220                       "no piobuf   %d\n"
2221                       "unaligned   %d\n"
2222                       "PKT drops   %d\n"
2223                       "WQE errs    %d\n",
2224                       dev->n_rc_resends, dev->n_rc_qacks, dev->n_rc_acks,
2225                       dev->n_seq_naks, dev->n_rdma_seq, dev->n_rnr_naks,
2226                       dev->n_other_naks, dev->n_timeouts,
2227                       dev->n_rdma_dup_busy, dev->n_rc_stalls, dev->n_piowait,
2228                       dev->n_no_piobuf, dev->n_unaligned,
2229                       dev->n_pkt_drops, dev->n_wqe_errs);
2230         for (i = 0; i < ARRAY_SIZE(dev->opstats); i++) {
2231                 const struct ipath_opcode_stats *si = &dev->opstats[i];
2232
2233                 if (!si->n_packets && !si->n_bytes)
2234                         continue;
2235                 len += sprintf(buf + len, "%02x %llu/%llu\n", i,
2236                                (unsigned long long) si->n_packets,
2237                                (unsigned long long) si->n_bytes);
2238         }
2239         return len;
2240 }
2241
2242 static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
2243 static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
2244 static DEVICE_ATTR(board_id, S_IRUGO, show_hca, NULL);
2245 static DEVICE_ATTR(stats, S_IRUGO, show_stats, NULL);
2246
2247 static struct device_attribute *ipath_class_attributes[] = {
2248         &dev_attr_hw_rev,
2249         &dev_attr_hca_type,
2250         &dev_attr_board_id,
2251         &dev_attr_stats
2252 };
2253
2254 static int ipath_verbs_register_sysfs(struct ib_device *dev)
2255 {
2256         int i;
2257         int ret;
2258
2259         for (i = 0; i < ARRAY_SIZE(ipath_class_attributes); ++i)
2260                 if (device_create_file(&dev->dev,
2261                                        ipath_class_attributes[i])) {
2262                         ret = 1;
2263                         goto bail;
2264                 }
2265
2266         ret = 0;
2267
2268 bail:
2269         return ret;
2270 }