]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/infiniband/hw/hfi1/init.c
scsi: cxgb4i: libcxgbi: in error case RST tcp conn
[karo-tx-linux.git] / drivers / infiniband / hw / hfi1 / init.c
1 /*
2  * Copyright(c) 2015-2017 Intel Corporation.
3  *
4  * This file is provided under a dual BSD/GPLv2 license.  When using or
5  * redistributing this file, you may do so under either license.
6  *
7  * GPL LICENSE SUMMARY
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * BSD LICENSE
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  *  - Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  *  - Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *  - Neither the name of Intel Corporation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
37  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
38  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
41  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
42  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47
48 #include <linux/pci.h>
49 #include <linux/netdevice.h>
50 #include <linux/vmalloc.h>
51 #include <linux/delay.h>
52 #include <linux/idr.h>
53 #include <linux/module.h>
54 #include <linux/printk.h>
55 #include <linux/hrtimer.h>
56 #include <rdma/rdma_vt.h>
57
58 #include "hfi.h"
59 #include "device.h"
60 #include "common.h"
61 #include "trace.h"
62 #include "mad.h"
63 #include "sdma.h"
64 #include "debugfs.h"
65 #include "verbs.h"
66 #include "aspm.h"
67 #include "affinity.h"
68 #include "vnic.h"
69
70 #undef pr_fmt
71 #define pr_fmt(fmt) DRIVER_NAME ": " fmt
72
73 /*
74  * min buffers we want to have per context, after driver
75  */
76 #define HFI1_MIN_USER_CTXT_BUFCNT 7
77
78 #define HFI1_MIN_HDRQ_EGRBUF_CNT 2
79 #define HFI1_MAX_HDRQ_EGRBUF_CNT 16352
80 #define HFI1_MIN_EAGER_BUFFER_SIZE (4 * 1024) /* 4KB */
81 #define HFI1_MAX_EAGER_BUFFER_SIZE (256 * 1024) /* 256KB */
82
83 /*
84  * Number of user receive contexts we are configured to use (to allow for more
85  * pio buffers per ctxt, etc.)  Zero means use one user context per CPU.
86  */
87 int num_user_contexts = -1;
88 module_param_named(num_user_contexts, num_user_contexts, uint, S_IRUGO);
89 MODULE_PARM_DESC(
90         num_user_contexts, "Set max number of user contexts to use");
91
92 uint krcvqs[RXE_NUM_DATA_VL];
93 int krcvqsset;
94 module_param_array(krcvqs, uint, &krcvqsset, S_IRUGO);
95 MODULE_PARM_DESC(krcvqs, "Array of the number of non-control kernel receive queues by VL");
96
97 /* computed based on above array */
98 unsigned long n_krcvqs;
99
100 static unsigned hfi1_rcvarr_split = 25;
101 module_param_named(rcvarr_split, hfi1_rcvarr_split, uint, S_IRUGO);
102 MODULE_PARM_DESC(rcvarr_split, "Percent of context's RcvArray entries used for Eager buffers");
103
104 static uint eager_buffer_size = (2 << 20); /* 2MB */
105 module_param(eager_buffer_size, uint, S_IRUGO);
106 MODULE_PARM_DESC(eager_buffer_size, "Size of the eager buffers, default: 2MB");
107
108 static uint rcvhdrcnt = 2048; /* 2x the max eager buffer count */
109 module_param_named(rcvhdrcnt, rcvhdrcnt, uint, S_IRUGO);
110 MODULE_PARM_DESC(rcvhdrcnt, "Receive header queue count (default 2048)");
111
112 static uint hfi1_hdrq_entsize = 32;
113 module_param_named(hdrq_entsize, hfi1_hdrq_entsize, uint, S_IRUGO);
114 MODULE_PARM_DESC(hdrq_entsize, "Size of header queue entries: 2 - 8B, 16 - 64B (default), 32 - 128B");
115
116 unsigned int user_credit_return_threshold = 33; /* default is 33% */
117 module_param(user_credit_return_threshold, uint, S_IRUGO);
118 MODULE_PARM_DESC(user_credit_return_threshold, "Credit return threshold for user send contexts, return when unreturned credits passes this many blocks (in percent of allocated blocks, 0 is off)");
119
120 static inline u64 encode_rcv_header_entry_size(u16);
121
122 static struct idr hfi1_unit_table;
123 u32 hfi1_cpulist_count;
124 unsigned long *hfi1_cpulist;
125
126 /*
127  * Common code for creating the receive context array.
128  */
129 int hfi1_create_ctxts(struct hfi1_devdata *dd)
130 {
131         unsigned i;
132         int ret;
133
134         /* Control context has to be always 0 */
135         BUILD_BUG_ON(HFI1_CTRL_CTXT != 0);
136
137         dd->rcd = kzalloc_node(dd->num_rcv_contexts * sizeof(*dd->rcd),
138                                GFP_KERNEL, dd->node);
139         if (!dd->rcd)
140                 goto nomem;
141
142         /* create one or more kernel contexts */
143         for (i = 0; i < dd->first_dyn_alloc_ctxt; ++i) {
144                 struct hfi1_pportdata *ppd;
145                 struct hfi1_ctxtdata *rcd;
146
147                 ppd = dd->pport + (i % dd->num_pports);
148
149                 /* dd->rcd[i] gets assigned inside the callee */
150                 rcd = hfi1_create_ctxtdata(ppd, i, dd->node);
151                 if (!rcd) {
152                         dd_dev_err(dd,
153                                    "Unable to allocate kernel receive context, failing\n");
154                         goto nomem;
155                 }
156                 /*
157                  * Set up the kernel context flags here and now because they
158                  * use default values for all receive side memories.  User
159                  * contexts will be handled as they are created.
160                  */
161                 rcd->flags = HFI1_CAP_KGET(MULTI_PKT_EGR) |
162                         HFI1_CAP_KGET(NODROP_RHQ_FULL) |
163                         HFI1_CAP_KGET(NODROP_EGR_FULL) |
164                         HFI1_CAP_KGET(DMA_RTAIL);
165
166                 /* Control context must use DMA_RTAIL */
167                 if (rcd->ctxt == HFI1_CTRL_CTXT)
168                         rcd->flags |= HFI1_CAP_DMA_RTAIL;
169                 rcd->seq_cnt = 1;
170
171                 rcd->sc = sc_alloc(dd, SC_ACK, rcd->rcvhdrqentsize, dd->node);
172                 if (!rcd->sc) {
173                         dd_dev_err(dd,
174                                    "Unable to allocate kernel send context, failing\n");
175                         goto nomem;
176                 }
177
178                 ret = hfi1_init_ctxt(rcd->sc);
179                 if (ret < 0) {
180                         dd_dev_err(dd,
181                                    "Failed to setup kernel receive context, failing\n");
182                         ret = -EFAULT;
183                         goto bail;
184                 }
185         }
186
187         /*
188          * Initialize aspm, to be done after gen3 transition and setting up
189          * contexts and before enabling interrupts
190          */
191         aspm_init(dd);
192
193         return 0;
194 nomem:
195         ret = -ENOMEM;
196 bail:
197         if (dd->rcd) {
198                 for (i = 0; i < dd->num_rcv_contexts; ++i)
199                         hfi1_free_ctxtdata(dd, dd->rcd[i]);
200         }
201         kfree(dd->rcd);
202         dd->rcd = NULL;
203         return ret;
204 }
205
206 /*
207  * Common code for user and kernel context setup.
208  */
209 struct hfi1_ctxtdata *hfi1_create_ctxtdata(struct hfi1_pportdata *ppd, u32 ctxt,
210                                            int numa)
211 {
212         struct hfi1_devdata *dd = ppd->dd;
213         struct hfi1_ctxtdata *rcd;
214         unsigned kctxt_ngroups = 0;
215         u32 base;
216
217         if (dd->rcv_entries.nctxt_extra >
218             dd->num_rcv_contexts - dd->first_dyn_alloc_ctxt)
219                 kctxt_ngroups = (dd->rcv_entries.nctxt_extra -
220                          (dd->num_rcv_contexts - dd->first_dyn_alloc_ctxt));
221         rcd = kzalloc_node(sizeof(*rcd), GFP_KERNEL, numa);
222         if (rcd) {
223                 u32 rcvtids, max_entries;
224
225                 hfi1_cdbg(PROC, "setting up context %u\n", ctxt);
226
227                 INIT_LIST_HEAD(&rcd->qp_wait_list);
228                 rcd->ppd = ppd;
229                 rcd->dd = dd;
230                 rcd->cnt = 1;
231                 rcd->ctxt = ctxt;
232                 dd->rcd[ctxt] = rcd;
233                 rcd->numa_id = numa;
234                 rcd->rcv_array_groups = dd->rcv_entries.ngroups;
235
236                 mutex_init(&rcd->exp_lock);
237
238                 /*
239                  * Calculate the context's RcvArray entry starting point.
240                  * We do this here because we have to take into account all
241                  * the RcvArray entries that previous context would have
242                  * taken and we have to account for any extra groups assigned
243                  * to the static (kernel) or dynamic (vnic/user) contexts.
244                  */
245                 if (ctxt < dd->first_dyn_alloc_ctxt) {
246                         if (ctxt < kctxt_ngroups) {
247                                 base = ctxt * (dd->rcv_entries.ngroups + 1);
248                                 rcd->rcv_array_groups++;
249                         } else {
250                                 base = kctxt_ngroups +
251                                         (ctxt * dd->rcv_entries.ngroups);
252                         }
253                 } else {
254                         u16 ct = ctxt - dd->first_dyn_alloc_ctxt;
255
256                         base = ((dd->n_krcv_queues * dd->rcv_entries.ngroups) +
257                                 kctxt_ngroups);
258                         if (ct < dd->rcv_entries.nctxt_extra) {
259                                 base += ct * (dd->rcv_entries.ngroups + 1);
260                                 rcd->rcv_array_groups++;
261                         } else {
262                                 base += dd->rcv_entries.nctxt_extra +
263                                         (ct * dd->rcv_entries.ngroups);
264                         }
265                 }
266                 rcd->eager_base = base * dd->rcv_entries.group_size;
267
268                 rcd->rcvhdrq_cnt = rcvhdrcnt;
269                 rcd->rcvhdrqentsize = hfi1_hdrq_entsize;
270                 /*
271                  * Simple Eager buffer allocation: we have already pre-allocated
272                  * the number of RcvArray entry groups. Each ctxtdata structure
273                  * holds the number of groups for that context.
274                  *
275                  * To follow CSR requirements and maintain cacheline alignment,
276                  * make sure all sizes and bases are multiples of group_size.
277                  *
278                  * The expected entry count is what is left after assigning
279                  * eager.
280                  */
281                 max_entries = rcd->rcv_array_groups *
282                         dd->rcv_entries.group_size;
283                 rcvtids = ((max_entries * hfi1_rcvarr_split) / 100);
284                 rcd->egrbufs.count = round_down(rcvtids,
285                                                 dd->rcv_entries.group_size);
286                 if (rcd->egrbufs.count > MAX_EAGER_ENTRIES) {
287                         dd_dev_err(dd, "ctxt%u: requested too many RcvArray entries.\n",
288                                    rcd->ctxt);
289                         rcd->egrbufs.count = MAX_EAGER_ENTRIES;
290                 }
291                 hfi1_cdbg(PROC,
292                           "ctxt%u: max Eager buffer RcvArray entries: %u\n",
293                           rcd->ctxt, rcd->egrbufs.count);
294
295                 /*
296                  * Allocate array that will hold the eager buffer accounting
297                  * data.
298                  * This will allocate the maximum possible buffer count based
299                  * on the value of the RcvArray split parameter.
300                  * The resulting value will be rounded down to the closest
301                  * multiple of dd->rcv_entries.group_size.
302                  */
303                 rcd->egrbufs.buffers = kzalloc_node(
304                         rcd->egrbufs.count * sizeof(*rcd->egrbufs.buffers),
305                         GFP_KERNEL, numa);
306                 if (!rcd->egrbufs.buffers)
307                         goto bail;
308                 rcd->egrbufs.rcvtids = kzalloc_node(
309                                 rcd->egrbufs.count *
310                                 sizeof(*rcd->egrbufs.rcvtids),
311                                 GFP_KERNEL, numa);
312                 if (!rcd->egrbufs.rcvtids)
313                         goto bail;
314                 rcd->egrbufs.size = eager_buffer_size;
315                 /*
316                  * The size of the buffers programmed into the RcvArray
317                  * entries needs to be big enough to handle the highest
318                  * MTU supported.
319                  */
320                 if (rcd->egrbufs.size < hfi1_max_mtu) {
321                         rcd->egrbufs.size = __roundup_pow_of_two(hfi1_max_mtu);
322                         hfi1_cdbg(PROC,
323                                   "ctxt%u: eager bufs size too small. Adjusting to %zu\n",
324                                     rcd->ctxt, rcd->egrbufs.size);
325                 }
326                 rcd->egrbufs.rcvtid_size = HFI1_MAX_EAGER_BUFFER_SIZE;
327
328                 /* Applicable only for statically created kernel contexts */
329                 if (ctxt < dd->first_dyn_alloc_ctxt) {
330                         rcd->opstats = kzalloc_node(sizeof(*rcd->opstats),
331                                                     GFP_KERNEL, numa);
332                         if (!rcd->opstats)
333                                 goto bail;
334                 }
335         }
336         return rcd;
337 bail:
338         dd->rcd[ctxt] = NULL;
339         kfree(rcd->egrbufs.rcvtids);
340         kfree(rcd->egrbufs.buffers);
341         kfree(rcd);
342         return NULL;
343 }
344
345 /*
346  * Convert a receive header entry size that to the encoding used in the CSR.
347  *
348  * Return a zero if the given size is invalid.
349  */
350 static inline u64 encode_rcv_header_entry_size(u16 size)
351 {
352         /* there are only 3 valid receive header entry sizes */
353         if (size == 2)
354                 return 1;
355         if (size == 16)
356                 return 2;
357         else if (size == 32)
358                 return 4;
359         return 0; /* invalid */
360 }
361
362 /*
363  * Select the largest ccti value over all SLs to determine the intra-
364  * packet gap for the link.
365  *
366  * called with cca_timer_lock held (to protect access to cca_timer
367  * array), and rcu_read_lock() (to protect access to cc_state).
368  */
369 void set_link_ipg(struct hfi1_pportdata *ppd)
370 {
371         struct hfi1_devdata *dd = ppd->dd;
372         struct cc_state *cc_state;
373         int i;
374         u16 cce, ccti_limit, max_ccti = 0;
375         u16 shift, mult;
376         u64 src;
377         u32 current_egress_rate; /* Mbits /sec */
378         u32 max_pkt_time;
379         /*
380          * max_pkt_time is the maximum packet egress time in units
381          * of the fabric clock period 1/(805 MHz).
382          */
383
384         cc_state = get_cc_state(ppd);
385
386         if (!cc_state)
387                 /*
388                  * This should _never_ happen - rcu_read_lock() is held,
389                  * and set_link_ipg() should not be called if cc_state
390                  * is NULL.
391                  */
392                 return;
393
394         for (i = 0; i < OPA_MAX_SLS; i++) {
395                 u16 ccti = ppd->cca_timer[i].ccti;
396
397                 if (ccti > max_ccti)
398                         max_ccti = ccti;
399         }
400
401         ccti_limit = cc_state->cct.ccti_limit;
402         if (max_ccti > ccti_limit)
403                 max_ccti = ccti_limit;
404
405         cce = cc_state->cct.entries[max_ccti].entry;
406         shift = (cce & 0xc000) >> 14;
407         mult = (cce & 0x3fff);
408
409         current_egress_rate = active_egress_rate(ppd);
410
411         max_pkt_time = egress_cycles(ppd->ibmaxlen, current_egress_rate);
412
413         src = (max_pkt_time >> shift) * mult;
414
415         src &= SEND_STATIC_RATE_CONTROL_CSR_SRC_RELOAD_SMASK;
416         src <<= SEND_STATIC_RATE_CONTROL_CSR_SRC_RELOAD_SHIFT;
417
418         write_csr(dd, SEND_STATIC_RATE_CONTROL, src);
419 }
420
421 static enum hrtimer_restart cca_timer_fn(struct hrtimer *t)
422 {
423         struct cca_timer *cca_timer;
424         struct hfi1_pportdata *ppd;
425         int sl;
426         u16 ccti_timer, ccti_min;
427         struct cc_state *cc_state;
428         unsigned long flags;
429         enum hrtimer_restart ret = HRTIMER_NORESTART;
430
431         cca_timer = container_of(t, struct cca_timer, hrtimer);
432         ppd = cca_timer->ppd;
433         sl = cca_timer->sl;
434
435         rcu_read_lock();
436
437         cc_state = get_cc_state(ppd);
438
439         if (!cc_state) {
440                 rcu_read_unlock();
441                 return HRTIMER_NORESTART;
442         }
443
444         /*
445          * 1) decrement ccti for SL
446          * 2) calculate IPG for link (set_link_ipg())
447          * 3) restart timer, unless ccti is at min value
448          */
449
450         ccti_min = cc_state->cong_setting.entries[sl].ccti_min;
451         ccti_timer = cc_state->cong_setting.entries[sl].ccti_timer;
452
453         spin_lock_irqsave(&ppd->cca_timer_lock, flags);
454
455         if (cca_timer->ccti > ccti_min) {
456                 cca_timer->ccti--;
457                 set_link_ipg(ppd);
458         }
459
460         if (cca_timer->ccti > ccti_min) {
461                 unsigned long nsec = 1024 * ccti_timer;
462                 /* ccti_timer is in units of 1.024 usec */
463                 hrtimer_forward_now(t, ns_to_ktime(nsec));
464                 ret = HRTIMER_RESTART;
465         }
466
467         spin_unlock_irqrestore(&ppd->cca_timer_lock, flags);
468         rcu_read_unlock();
469         return ret;
470 }
471
472 /*
473  * Common code for initializing the physical port structure.
474  */
475 void hfi1_init_pportdata(struct pci_dev *pdev, struct hfi1_pportdata *ppd,
476                          struct hfi1_devdata *dd, u8 hw_pidx, u8 port)
477 {
478         int i;
479         uint default_pkey_idx;
480         struct cc_state *cc_state;
481
482         ppd->dd = dd;
483         ppd->hw_pidx = hw_pidx;
484         ppd->port = port; /* IB port number, not index */
485
486         default_pkey_idx = 1;
487
488         ppd->pkeys[default_pkey_idx] = DEFAULT_P_KEY;
489         ppd->part_enforce |= HFI1_PART_ENFORCE_IN;
490         ppd->part_enforce |= HFI1_PART_ENFORCE_OUT;
491
492         if (loopback) {
493                 hfi1_early_err(&pdev->dev,
494                                "Faking data partition 0x8001 in idx %u\n",
495                                !default_pkey_idx);
496                 ppd->pkeys[!default_pkey_idx] = 0x8001;
497         }
498
499         INIT_WORK(&ppd->link_vc_work, handle_verify_cap);
500         INIT_WORK(&ppd->link_up_work, handle_link_up);
501         INIT_WORK(&ppd->link_down_work, handle_link_down);
502         INIT_WORK(&ppd->freeze_work, handle_freeze);
503         INIT_WORK(&ppd->link_downgrade_work, handle_link_downgrade);
504         INIT_WORK(&ppd->sma_message_work, handle_sma_message);
505         INIT_WORK(&ppd->link_bounce_work, handle_link_bounce);
506         INIT_DELAYED_WORK(&ppd->start_link_work, handle_start_link);
507         INIT_WORK(&ppd->linkstate_active_work, receive_interrupt_work);
508         INIT_WORK(&ppd->qsfp_info.qsfp_work, qsfp_event);
509
510         mutex_init(&ppd->hls_lock);
511         spin_lock_init(&ppd->qsfp_info.qsfp_lock);
512
513         ppd->qsfp_info.ppd = ppd;
514         ppd->sm_trap_qp = 0x0;
515         ppd->sa_qp = 0x1;
516
517         ppd->hfi1_wq = NULL;
518
519         spin_lock_init(&ppd->cca_timer_lock);
520
521         for (i = 0; i < OPA_MAX_SLS; i++) {
522                 hrtimer_init(&ppd->cca_timer[i].hrtimer, CLOCK_MONOTONIC,
523                              HRTIMER_MODE_REL);
524                 ppd->cca_timer[i].ppd = ppd;
525                 ppd->cca_timer[i].sl = i;
526                 ppd->cca_timer[i].ccti = 0;
527                 ppd->cca_timer[i].hrtimer.function = cca_timer_fn;
528         }
529
530         ppd->cc_max_table_entries = IB_CC_TABLE_CAP_DEFAULT;
531
532         spin_lock_init(&ppd->cc_state_lock);
533         spin_lock_init(&ppd->cc_log_lock);
534         cc_state = kzalloc(sizeof(*cc_state), GFP_KERNEL);
535         RCU_INIT_POINTER(ppd->cc_state, cc_state);
536         if (!cc_state)
537                 goto bail;
538         return;
539
540 bail:
541
542         hfi1_early_err(&pdev->dev,
543                        "Congestion Control Agent disabled for port %d\n", port);
544 }
545
546 /*
547  * Do initialization for device that is only needed on
548  * first detect, not on resets.
549  */
550 static int loadtime_init(struct hfi1_devdata *dd)
551 {
552         return 0;
553 }
554
555 /**
556  * init_after_reset - re-initialize after a reset
557  * @dd: the hfi1_ib device
558  *
559  * sanity check at least some of the values after reset, and
560  * ensure no receive or transmit (explicitly, in case reset
561  * failed
562  */
563 static int init_after_reset(struct hfi1_devdata *dd)
564 {
565         int i;
566
567         /*
568          * Ensure chip does no sends or receives, tail updates, or
569          * pioavail updates while we re-initialize.  This is mostly
570          * for the driver data structures, not chip registers.
571          */
572         for (i = 0; i < dd->num_rcv_contexts; i++)
573                 hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_DIS |
574                                   HFI1_RCVCTRL_INTRAVAIL_DIS |
575                                   HFI1_RCVCTRL_TAILUPD_DIS, i);
576         pio_send_control(dd, PSC_GLOBAL_DISABLE);
577         for (i = 0; i < dd->num_send_contexts; i++)
578                 sc_disable(dd->send_contexts[i].sc);
579
580         return 0;
581 }
582
583 static void enable_chip(struct hfi1_devdata *dd)
584 {
585         u32 rcvmask;
586         u32 i;
587
588         /* enable PIO send */
589         pio_send_control(dd, PSC_GLOBAL_ENABLE);
590
591         /*
592          * Enable kernel ctxts' receive and receive interrupt.
593          * Other ctxts done as user opens and initializes them.
594          */
595         for (i = 0; i < dd->first_dyn_alloc_ctxt; ++i) {
596                 rcvmask = HFI1_RCVCTRL_CTXT_ENB | HFI1_RCVCTRL_INTRAVAIL_ENB;
597                 rcvmask |= HFI1_CAP_KGET_MASK(dd->rcd[i]->flags, DMA_RTAIL) ?
598                         HFI1_RCVCTRL_TAILUPD_ENB : HFI1_RCVCTRL_TAILUPD_DIS;
599                 if (!HFI1_CAP_KGET_MASK(dd->rcd[i]->flags, MULTI_PKT_EGR))
600                         rcvmask |= HFI1_RCVCTRL_ONE_PKT_EGR_ENB;
601                 if (HFI1_CAP_KGET_MASK(dd->rcd[i]->flags, NODROP_RHQ_FULL))
602                         rcvmask |= HFI1_RCVCTRL_NO_RHQ_DROP_ENB;
603                 if (HFI1_CAP_KGET_MASK(dd->rcd[i]->flags, NODROP_EGR_FULL))
604                         rcvmask |= HFI1_RCVCTRL_NO_EGR_DROP_ENB;
605                 hfi1_rcvctrl(dd, rcvmask, i);
606                 sc_enable(dd->rcd[i]->sc);
607         }
608 }
609
610 /**
611  * create_workqueues - create per port workqueues
612  * @dd: the hfi1_ib device
613  */
614 static int create_workqueues(struct hfi1_devdata *dd)
615 {
616         int pidx;
617         struct hfi1_pportdata *ppd;
618
619         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
620                 ppd = dd->pport + pidx;
621                 if (!ppd->hfi1_wq) {
622                         ppd->hfi1_wq =
623                                 alloc_workqueue(
624                                     "hfi%d_%d",
625                                     WQ_SYSFS | WQ_HIGHPRI | WQ_CPU_INTENSIVE,
626                                     dd->num_sdma,
627                                     dd->unit, pidx);
628                         if (!ppd->hfi1_wq)
629                                 goto wq_error;
630                 }
631         }
632         return 0;
633 wq_error:
634         pr_err("alloc_workqueue failed for port %d\n", pidx + 1);
635         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
636                 ppd = dd->pport + pidx;
637                 if (ppd->hfi1_wq) {
638                         destroy_workqueue(ppd->hfi1_wq);
639                         ppd->hfi1_wq = NULL;
640                 }
641         }
642         return -ENOMEM;
643 }
644
645 /**
646  * hfi1_init - do the actual initialization sequence on the chip
647  * @dd: the hfi1_ib device
648  * @reinit: re-initializing, so don't allocate new memory
649  *
650  * Do the actual initialization sequence on the chip.  This is done
651  * both from the init routine called from the PCI infrastructure, and
652  * when we reset the chip, or detect that it was reset internally,
653  * or it's administratively re-enabled.
654  *
655  * Memory allocation here and in called routines is only done in
656  * the first case (reinit == 0).  We have to be careful, because even
657  * without memory allocation, we need to re-write all the chip registers
658  * TIDs, etc. after the reset or enable has completed.
659  */
660 int hfi1_init(struct hfi1_devdata *dd, int reinit)
661 {
662         int ret = 0, pidx, lastfail = 0;
663         unsigned i, len;
664         struct hfi1_ctxtdata *rcd;
665         struct hfi1_pportdata *ppd;
666
667         /* Set up recv low level handlers */
668         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_EXPECTED] =
669                                                 kdeth_process_expected;
670         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_EAGER] =
671                                                 kdeth_process_eager;
672         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_IB] = process_receive_ib;
673         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_ERROR] =
674                                                 process_receive_error;
675         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_BYPASS] =
676                                                 process_receive_bypass;
677         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_INVALID5] =
678                                                 process_receive_invalid;
679         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_INVALID6] =
680                                                 process_receive_invalid;
681         dd->normal_rhf_rcv_functions[RHF_RCV_TYPE_INVALID7] =
682                                                 process_receive_invalid;
683         dd->rhf_rcv_function_map = dd->normal_rhf_rcv_functions;
684
685         /* Set up send low level handlers */
686         dd->process_pio_send = hfi1_verbs_send_pio;
687         dd->process_dma_send = hfi1_verbs_send_dma;
688         dd->pio_inline_send = pio_copy;
689         dd->process_vnic_dma_send = hfi1_vnic_send_dma;
690
691         if (is_ax(dd)) {
692                 atomic_set(&dd->drop_packet, DROP_PACKET_ON);
693                 dd->do_drop = 1;
694         } else {
695                 atomic_set(&dd->drop_packet, DROP_PACKET_OFF);
696                 dd->do_drop = 0;
697         }
698
699         /* make sure the link is not "up" */
700         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
701                 ppd = dd->pport + pidx;
702                 ppd->linkup = 0;
703         }
704
705         if (reinit)
706                 ret = init_after_reset(dd);
707         else
708                 ret = loadtime_init(dd);
709         if (ret)
710                 goto done;
711
712         /* allocate dummy tail memory for all receive contexts */
713         dd->rcvhdrtail_dummy_kvaddr = dma_zalloc_coherent(
714                 &dd->pcidev->dev, sizeof(u64),
715                 &dd->rcvhdrtail_dummy_dma,
716                 GFP_KERNEL);
717
718         if (!dd->rcvhdrtail_dummy_kvaddr) {
719                 dd_dev_err(dd, "cannot allocate dummy tail memory\n");
720                 ret = -ENOMEM;
721                 goto done;
722         }
723
724         /* dd->rcd can be NULL if early initialization failed */
725         for (i = 0; dd->rcd && i < dd->first_dyn_alloc_ctxt; ++i) {
726                 /*
727                  * Set up the (kernel) rcvhdr queue and egr TIDs.  If doing
728                  * re-init, the simplest way to handle this is to free
729                  * existing, and re-allocate.
730                  * Need to re-create rest of ctxt 0 ctxtdata as well.
731                  */
732                 rcd = dd->rcd[i];
733                 if (!rcd)
734                         continue;
735
736                 rcd->do_interrupt = &handle_receive_interrupt;
737
738                 lastfail = hfi1_create_rcvhdrq(dd, rcd);
739                 if (!lastfail)
740                         lastfail = hfi1_setup_eagerbufs(rcd);
741                 if (lastfail) {
742                         dd_dev_err(dd,
743                                    "failed to allocate kernel ctxt's rcvhdrq and/or egr bufs\n");
744                         ret = lastfail;
745                 }
746         }
747
748         /* Allocate enough memory for user event notification. */
749         len = PAGE_ALIGN(dd->chip_rcv_contexts * HFI1_MAX_SHARED_CTXTS *
750                          sizeof(*dd->events));
751         dd->events = vmalloc_user(len);
752         if (!dd->events)
753                 dd_dev_err(dd, "Failed to allocate user events page\n");
754         /*
755          * Allocate a page for device and port status.
756          * Page will be shared amongst all user processes.
757          */
758         dd->status = vmalloc_user(PAGE_SIZE);
759         if (!dd->status)
760                 dd_dev_err(dd, "Failed to allocate dev status page\n");
761         else
762                 dd->freezelen = PAGE_SIZE - (sizeof(*dd->status) -
763                                              sizeof(dd->status->freezemsg));
764         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
765                 ppd = dd->pport + pidx;
766                 if (dd->status)
767                         /* Currently, we only have one port */
768                         ppd->statusp = &dd->status->port;
769
770                 set_mtu(ppd);
771         }
772
773         /* enable chip even if we have an error, so we can debug cause */
774         enable_chip(dd);
775
776 done:
777         /*
778          * Set status even if port serdes is not initialized
779          * so that diags will work.
780          */
781         if (dd->status)
782                 dd->status->dev |= HFI1_STATUS_CHIP_PRESENT |
783                         HFI1_STATUS_INITTED;
784         if (!ret) {
785                 /* enable all interrupts from the chip */
786                 set_intr_state(dd, 1);
787
788                 /* chip is OK for user apps; mark it as initialized */
789                 for (pidx = 0; pidx < dd->num_pports; ++pidx) {
790                         ppd = dd->pport + pidx;
791
792                         /*
793                          * start the serdes - must be after interrupts are
794                          * enabled so we are notified when the link goes up
795                          */
796                         lastfail = bringup_serdes(ppd);
797                         if (lastfail)
798                                 dd_dev_info(dd,
799                                             "Failed to bring up port %u\n",
800                                             ppd->port);
801
802                         /*
803                          * Set status even if port serdes is not initialized
804                          * so that diags will work.
805                          */
806                         if (ppd->statusp)
807                                 *ppd->statusp |= HFI1_STATUS_CHIP_PRESENT |
808                                                         HFI1_STATUS_INITTED;
809                         if (!ppd->link_speed_enabled)
810                                 continue;
811                 }
812         }
813
814         /* if ret is non-zero, we probably should do some cleanup here... */
815         return ret;
816 }
817
818 static inline struct hfi1_devdata *__hfi1_lookup(int unit)
819 {
820         return idr_find(&hfi1_unit_table, unit);
821 }
822
823 struct hfi1_devdata *hfi1_lookup(int unit)
824 {
825         struct hfi1_devdata *dd;
826         unsigned long flags;
827
828         spin_lock_irqsave(&hfi1_devs_lock, flags);
829         dd = __hfi1_lookup(unit);
830         spin_unlock_irqrestore(&hfi1_devs_lock, flags);
831
832         return dd;
833 }
834
835 /*
836  * Stop the timers during unit shutdown, or after an error late
837  * in initialization.
838  */
839 static void stop_timers(struct hfi1_devdata *dd)
840 {
841         struct hfi1_pportdata *ppd;
842         int pidx;
843
844         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
845                 ppd = dd->pport + pidx;
846                 if (ppd->led_override_timer.data) {
847                         del_timer_sync(&ppd->led_override_timer);
848                         atomic_set(&ppd->led_override_timer_active, 0);
849                 }
850         }
851 }
852
853 /**
854  * shutdown_device - shut down a device
855  * @dd: the hfi1_ib device
856  *
857  * This is called to make the device quiet when we are about to
858  * unload the driver, and also when the device is administratively
859  * disabled.   It does not free any data structures.
860  * Everything it does has to be setup again by hfi1_init(dd, 1)
861  */
862 static void shutdown_device(struct hfi1_devdata *dd)
863 {
864         struct hfi1_pportdata *ppd;
865         unsigned pidx;
866         int i;
867
868         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
869                 ppd = dd->pport + pidx;
870
871                 ppd->linkup = 0;
872                 if (ppd->statusp)
873                         *ppd->statusp &= ~(HFI1_STATUS_IB_CONF |
874                                            HFI1_STATUS_IB_READY);
875         }
876         dd->flags &= ~HFI1_INITTED;
877
878         /* mask interrupts, but not errors */
879         set_intr_state(dd, 0);
880
881         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
882                 ppd = dd->pport + pidx;
883                 for (i = 0; i < dd->num_rcv_contexts; i++)
884                         hfi1_rcvctrl(dd, HFI1_RCVCTRL_TAILUPD_DIS |
885                                           HFI1_RCVCTRL_CTXT_DIS |
886                                           HFI1_RCVCTRL_INTRAVAIL_DIS |
887                                           HFI1_RCVCTRL_PKEY_DIS |
888                                           HFI1_RCVCTRL_ONE_PKT_EGR_DIS, i);
889                 /*
890                  * Gracefully stop all sends allowing any in progress to
891                  * trickle out first.
892                  */
893                 for (i = 0; i < dd->num_send_contexts; i++)
894                         sc_flush(dd->send_contexts[i].sc);
895         }
896
897         /*
898          * Enough for anything that's going to trickle out to have actually
899          * done so.
900          */
901         udelay(20);
902
903         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
904                 ppd = dd->pport + pidx;
905
906                 /* disable all contexts */
907                 for (i = 0; i < dd->num_send_contexts; i++)
908                         sc_disable(dd->send_contexts[i].sc);
909                 /* disable the send device */
910                 pio_send_control(dd, PSC_GLOBAL_DISABLE);
911
912                 shutdown_led_override(ppd);
913
914                 /*
915                  * Clear SerdesEnable.
916                  * We can't count on interrupts since we are stopping.
917                  */
918                 hfi1_quiet_serdes(ppd);
919
920                 if (ppd->hfi1_wq) {
921                         destroy_workqueue(ppd->hfi1_wq);
922                         ppd->hfi1_wq = NULL;
923                 }
924         }
925         sdma_exit(dd);
926 }
927
928 /**
929  * hfi1_free_ctxtdata - free a context's allocated data
930  * @dd: the hfi1_ib device
931  * @rcd: the ctxtdata structure
932  *
933  * free up any allocated data for a context
934  * This should not touch anything that would affect a simultaneous
935  * re-allocation of context data, because it is called after hfi1_mutex
936  * is released (and can be called from reinit as well).
937  * It should never change any chip state, or global driver state.
938  */
939 void hfi1_free_ctxtdata(struct hfi1_devdata *dd, struct hfi1_ctxtdata *rcd)
940 {
941         unsigned e;
942
943         if (!rcd)
944                 return;
945
946         if (rcd->rcvhdrq) {
947                 dma_free_coherent(&dd->pcidev->dev, rcd->rcvhdrq_size,
948                                   rcd->rcvhdrq, rcd->rcvhdrq_dma);
949                 rcd->rcvhdrq = NULL;
950                 if (rcd->rcvhdrtail_kvaddr) {
951                         dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE,
952                                           (void *)rcd->rcvhdrtail_kvaddr,
953                                           rcd->rcvhdrqtailaddr_dma);
954                         rcd->rcvhdrtail_kvaddr = NULL;
955                 }
956         }
957
958         /* all the RcvArray entries should have been cleared by now */
959         kfree(rcd->egrbufs.rcvtids);
960
961         for (e = 0; e < rcd->egrbufs.alloced; e++) {
962                 if (rcd->egrbufs.buffers[e].dma)
963                         dma_free_coherent(&dd->pcidev->dev,
964                                           rcd->egrbufs.buffers[e].len,
965                                           rcd->egrbufs.buffers[e].addr,
966                                           rcd->egrbufs.buffers[e].dma);
967         }
968         kfree(rcd->egrbufs.buffers);
969
970         sc_free(rcd->sc);
971         vfree(rcd->user_event_mask);
972         vfree(rcd->subctxt_uregbase);
973         vfree(rcd->subctxt_rcvegrbuf);
974         vfree(rcd->subctxt_rcvhdr_base);
975         kfree(rcd->opstats);
976         kfree(rcd);
977 }
978
979 /*
980  * Release our hold on the shared asic data.  If we are the last one,
981  * return the structure to be finalized outside the lock.  Must be
982  * holding hfi1_devs_lock.
983  */
984 static struct hfi1_asic_data *release_asic_data(struct hfi1_devdata *dd)
985 {
986         struct hfi1_asic_data *ad;
987         int other;
988
989         if (!dd->asic_data)
990                 return NULL;
991         dd->asic_data->dds[dd->hfi1_id] = NULL;
992         other = dd->hfi1_id ? 0 : 1;
993         ad = dd->asic_data;
994         dd->asic_data = NULL;
995         /* return NULL if the other dd still has a link */
996         return ad->dds[other] ? NULL : ad;
997 }
998
999 static void finalize_asic_data(struct hfi1_devdata *dd,
1000                                struct hfi1_asic_data *ad)
1001 {
1002         clean_up_i2c(dd, ad);
1003         kfree(ad);
1004 }
1005
1006 static void __hfi1_free_devdata(struct kobject *kobj)
1007 {
1008         struct hfi1_devdata *dd =
1009                 container_of(kobj, struct hfi1_devdata, kobj);
1010         struct hfi1_asic_data *ad;
1011         unsigned long flags;
1012
1013         spin_lock_irqsave(&hfi1_devs_lock, flags);
1014         idr_remove(&hfi1_unit_table, dd->unit);
1015         list_del(&dd->list);
1016         ad = release_asic_data(dd);
1017         spin_unlock_irqrestore(&hfi1_devs_lock, flags);
1018         if (ad)
1019                 finalize_asic_data(dd, ad);
1020         free_platform_config(dd);
1021         rcu_barrier(); /* wait for rcu callbacks to complete */
1022         free_percpu(dd->int_counter);
1023         free_percpu(dd->rcv_limit);
1024         free_percpu(dd->send_schedule);
1025         rvt_dealloc_device(&dd->verbs_dev.rdi);
1026 }
1027
1028 static struct kobj_type hfi1_devdata_type = {
1029         .release = __hfi1_free_devdata,
1030 };
1031
1032 void hfi1_free_devdata(struct hfi1_devdata *dd)
1033 {
1034         kobject_put(&dd->kobj);
1035 }
1036
1037 /*
1038  * Allocate our primary per-unit data structure.  Must be done via verbs
1039  * allocator, because the verbs cleanup process both does cleanup and
1040  * free of the data structure.
1041  * "extra" is for chip-specific data.
1042  *
1043  * Use the idr mechanism to get a unit number for this unit.
1044  */
1045 struct hfi1_devdata *hfi1_alloc_devdata(struct pci_dev *pdev, size_t extra)
1046 {
1047         unsigned long flags;
1048         struct hfi1_devdata *dd;
1049         int ret, nports;
1050
1051         /* extra is * number of ports */
1052         nports = extra / sizeof(struct hfi1_pportdata);
1053
1054         dd = (struct hfi1_devdata *)rvt_alloc_device(sizeof(*dd) + extra,
1055                                                      nports);
1056         if (!dd)
1057                 return ERR_PTR(-ENOMEM);
1058         dd->num_pports = nports;
1059         dd->pport = (struct hfi1_pportdata *)(dd + 1);
1060
1061         INIT_LIST_HEAD(&dd->list);
1062         idr_preload(GFP_KERNEL);
1063         spin_lock_irqsave(&hfi1_devs_lock, flags);
1064
1065         ret = idr_alloc(&hfi1_unit_table, dd, 0, 0, GFP_NOWAIT);
1066         if (ret >= 0) {
1067                 dd->unit = ret;
1068                 list_add(&dd->list, &hfi1_dev_list);
1069         }
1070
1071         spin_unlock_irqrestore(&hfi1_devs_lock, flags);
1072         idr_preload_end();
1073
1074         if (ret < 0) {
1075                 hfi1_early_err(&pdev->dev,
1076                                "Could not allocate unit ID: error %d\n", -ret);
1077                 goto bail;
1078         }
1079         /*
1080          * Initialize all locks for the device. This needs to be as early as
1081          * possible so locks are usable.
1082          */
1083         spin_lock_init(&dd->sc_lock);
1084         spin_lock_init(&dd->sendctrl_lock);
1085         spin_lock_init(&dd->rcvctrl_lock);
1086         spin_lock_init(&dd->uctxt_lock);
1087         spin_lock_init(&dd->hfi1_diag_trans_lock);
1088         spin_lock_init(&dd->sc_init_lock);
1089         spin_lock_init(&dd->dc8051_memlock);
1090         seqlock_init(&dd->sc2vl_lock);
1091         spin_lock_init(&dd->sde_map_lock);
1092         spin_lock_init(&dd->pio_map_lock);
1093         mutex_init(&dd->dc8051_lock);
1094         init_waitqueue_head(&dd->event_queue);
1095
1096         dd->int_counter = alloc_percpu(u64);
1097         if (!dd->int_counter) {
1098                 ret = -ENOMEM;
1099                 hfi1_early_err(&pdev->dev,
1100                                "Could not allocate per-cpu int_counter\n");
1101                 goto bail;
1102         }
1103
1104         dd->rcv_limit = alloc_percpu(u64);
1105         if (!dd->rcv_limit) {
1106                 ret = -ENOMEM;
1107                 hfi1_early_err(&pdev->dev,
1108                                "Could not allocate per-cpu rcv_limit\n");
1109                 goto bail;
1110         }
1111
1112         dd->send_schedule = alloc_percpu(u64);
1113         if (!dd->send_schedule) {
1114                 ret = -ENOMEM;
1115                 hfi1_early_err(&pdev->dev,
1116                                "Could not allocate per-cpu int_counter\n");
1117                 goto bail;
1118         }
1119
1120         if (!hfi1_cpulist_count) {
1121                 u32 count = num_online_cpus();
1122
1123                 hfi1_cpulist = kcalloc(BITS_TO_LONGS(count), sizeof(long),
1124                                        GFP_KERNEL);
1125                 if (hfi1_cpulist)
1126                         hfi1_cpulist_count = count;
1127                 else
1128                         hfi1_early_err(
1129                         &pdev->dev,
1130                         "Could not alloc cpulist info, cpu affinity might be wrong\n");
1131         }
1132         kobject_init(&dd->kobj, &hfi1_devdata_type);
1133         return dd;
1134
1135 bail:
1136         if (!list_empty(&dd->list))
1137                 list_del_init(&dd->list);
1138         rvt_dealloc_device(&dd->verbs_dev.rdi);
1139         return ERR_PTR(ret);
1140 }
1141
1142 /*
1143  * Called from freeze mode handlers, and from PCI error
1144  * reporting code.  Should be paranoid about state of
1145  * system and data structures.
1146  */
1147 void hfi1_disable_after_error(struct hfi1_devdata *dd)
1148 {
1149         if (dd->flags & HFI1_INITTED) {
1150                 u32 pidx;
1151
1152                 dd->flags &= ~HFI1_INITTED;
1153                 if (dd->pport)
1154                         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
1155                                 struct hfi1_pportdata *ppd;
1156
1157                                 ppd = dd->pport + pidx;
1158                                 if (dd->flags & HFI1_PRESENT)
1159                                         set_link_state(ppd, HLS_DN_DISABLE);
1160
1161                                 if (ppd->statusp)
1162                                         *ppd->statusp &= ~HFI1_STATUS_IB_READY;
1163                         }
1164         }
1165
1166         /*
1167          * Mark as having had an error for driver, and also
1168          * for /sys and status word mapped to user programs.
1169          * This marks unit as not usable, until reset.
1170          */
1171         if (dd->status)
1172                 dd->status->dev |= HFI1_STATUS_HWERROR;
1173 }
1174
1175 static void remove_one(struct pci_dev *);
1176 static int init_one(struct pci_dev *, const struct pci_device_id *);
1177
1178 #define DRIVER_LOAD_MSG "Intel " DRIVER_NAME " loaded: "
1179 #define PFX DRIVER_NAME ": "
1180
1181 const struct pci_device_id hfi1_pci_tbl[] = {
1182         { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL0) },
1183         { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL1) },
1184         { 0, }
1185 };
1186
1187 MODULE_DEVICE_TABLE(pci, hfi1_pci_tbl);
1188
1189 static struct pci_driver hfi1_pci_driver = {
1190         .name = DRIVER_NAME,
1191         .probe = init_one,
1192         .remove = remove_one,
1193         .id_table = hfi1_pci_tbl,
1194         .err_handler = &hfi1_pci_err_handler,
1195 };
1196
1197 static void __init compute_krcvqs(void)
1198 {
1199         int i;
1200
1201         for (i = 0; i < krcvqsset; i++)
1202                 n_krcvqs += krcvqs[i];
1203 }
1204
1205 /*
1206  * Do all the generic driver unit- and chip-independent memory
1207  * allocation and initialization.
1208  */
1209 static int __init hfi1_mod_init(void)
1210 {
1211         int ret;
1212
1213         ret = dev_init();
1214         if (ret)
1215                 goto bail;
1216
1217         ret = node_affinity_init();
1218         if (ret)
1219                 goto bail;
1220
1221         /* validate max MTU before any devices start */
1222         if (!valid_opa_max_mtu(hfi1_max_mtu)) {
1223                 pr_err("Invalid max_mtu 0x%x, using 0x%x instead\n",
1224                        hfi1_max_mtu, HFI1_DEFAULT_MAX_MTU);
1225                 hfi1_max_mtu = HFI1_DEFAULT_MAX_MTU;
1226         }
1227         /* valid CUs run from 1-128 in powers of 2 */
1228         if (hfi1_cu > 128 || !is_power_of_2(hfi1_cu))
1229                 hfi1_cu = 1;
1230         /* valid credit return threshold is 0-100, variable is unsigned */
1231         if (user_credit_return_threshold > 100)
1232                 user_credit_return_threshold = 100;
1233
1234         compute_krcvqs();
1235         /*
1236          * sanitize receive interrupt count, time must wait until after
1237          * the hardware type is known
1238          */
1239         if (rcv_intr_count > RCV_HDR_HEAD_COUNTER_MASK)
1240                 rcv_intr_count = RCV_HDR_HEAD_COUNTER_MASK;
1241         /* reject invalid combinations */
1242         if (rcv_intr_count == 0 && rcv_intr_timeout == 0) {
1243                 pr_err("Invalid mode: both receive interrupt count and available timeout are zero - setting interrupt count to 1\n");
1244                 rcv_intr_count = 1;
1245         }
1246         if (rcv_intr_count > 1 && rcv_intr_timeout == 0) {
1247                 /*
1248                  * Avoid indefinite packet delivery by requiring a timeout
1249                  * if count is > 1.
1250                  */
1251                 pr_err("Invalid mode: receive interrupt count greater than 1 and available timeout is zero - setting available timeout to 1\n");
1252                 rcv_intr_timeout = 1;
1253         }
1254         if (rcv_intr_dynamic && !(rcv_intr_count > 1 && rcv_intr_timeout > 0)) {
1255                 /*
1256                  * The dynamic algorithm expects a non-zero timeout
1257                  * and a count > 1.
1258                  */
1259                 pr_err("Invalid mode: dynamic receive interrupt mitigation with invalid count and timeout - turning dynamic off\n");
1260                 rcv_intr_dynamic = 0;
1261         }
1262
1263         /* sanitize link CRC options */
1264         link_crc_mask &= SUPPORTED_CRCS;
1265
1266         /*
1267          * These must be called before the driver is registered with
1268          * the PCI subsystem.
1269          */
1270         idr_init(&hfi1_unit_table);
1271
1272         hfi1_dbg_init();
1273         ret = hfi1_wss_init();
1274         if (ret < 0)
1275                 goto bail_wss;
1276         ret = pci_register_driver(&hfi1_pci_driver);
1277         if (ret < 0) {
1278                 pr_err("Unable to register driver: error %d\n", -ret);
1279                 goto bail_dev;
1280         }
1281         goto bail; /* all OK */
1282
1283 bail_dev:
1284         hfi1_wss_exit();
1285 bail_wss:
1286         hfi1_dbg_exit();
1287         idr_destroy(&hfi1_unit_table);
1288         dev_cleanup();
1289 bail:
1290         return ret;
1291 }
1292
1293 module_init(hfi1_mod_init);
1294
1295 /*
1296  * Do the non-unit driver cleanup, memory free, etc. at unload.
1297  */
1298 static void __exit hfi1_mod_cleanup(void)
1299 {
1300         pci_unregister_driver(&hfi1_pci_driver);
1301         node_affinity_destroy();
1302         hfi1_wss_exit();
1303         hfi1_dbg_exit();
1304         hfi1_cpulist_count = 0;
1305         kfree(hfi1_cpulist);
1306
1307         idr_destroy(&hfi1_unit_table);
1308         dispose_firmware();     /* asymmetric with obtain_firmware() */
1309         dev_cleanup();
1310 }
1311
1312 module_exit(hfi1_mod_cleanup);
1313
1314 /* this can only be called after a successful initialization */
1315 static void cleanup_device_data(struct hfi1_devdata *dd)
1316 {
1317         int ctxt;
1318         int pidx;
1319         struct hfi1_ctxtdata **tmp;
1320         unsigned long flags;
1321
1322         /* users can't do anything more with chip */
1323         for (pidx = 0; pidx < dd->num_pports; ++pidx) {
1324                 struct hfi1_pportdata *ppd = &dd->pport[pidx];
1325                 struct cc_state *cc_state;
1326                 int i;
1327
1328                 if (ppd->statusp)
1329                         *ppd->statusp &= ~HFI1_STATUS_CHIP_PRESENT;
1330
1331                 for (i = 0; i < OPA_MAX_SLS; i++)
1332                         hrtimer_cancel(&ppd->cca_timer[i].hrtimer);
1333
1334                 spin_lock(&ppd->cc_state_lock);
1335                 cc_state = get_cc_state_protected(ppd);
1336                 RCU_INIT_POINTER(ppd->cc_state, NULL);
1337                 spin_unlock(&ppd->cc_state_lock);
1338
1339                 if (cc_state)
1340                         kfree_rcu(cc_state, rcu);
1341         }
1342
1343         free_credit_return(dd);
1344
1345         /*
1346          * Free any resources still in use (usually just kernel contexts)
1347          * at unload; we do for ctxtcnt, because that's what we allocate.
1348          * We acquire lock to be really paranoid that rcd isn't being
1349          * accessed from some interrupt-related code (that should not happen,
1350          * but best to be sure).
1351          */
1352         spin_lock_irqsave(&dd->uctxt_lock, flags);
1353         tmp = dd->rcd;
1354         dd->rcd = NULL;
1355         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
1356
1357         if (dd->rcvhdrtail_dummy_kvaddr) {
1358                 dma_free_coherent(&dd->pcidev->dev, sizeof(u64),
1359                                   (void *)dd->rcvhdrtail_dummy_kvaddr,
1360                                   dd->rcvhdrtail_dummy_dma);
1361                 dd->rcvhdrtail_dummy_kvaddr = NULL;
1362         }
1363
1364         for (ctxt = 0; tmp && ctxt < dd->num_rcv_contexts; ctxt++) {
1365                 struct hfi1_ctxtdata *rcd = tmp[ctxt];
1366
1367                 tmp[ctxt] = NULL; /* debugging paranoia */
1368                 if (rcd) {
1369                         hfi1_clear_tids(rcd);
1370                         hfi1_free_ctxtdata(dd, rcd);
1371                 }
1372         }
1373         kfree(tmp);
1374         free_pio_map(dd);
1375         /* must follow rcv context free - need to remove rcv's hooks */
1376         for (ctxt = 0; ctxt < dd->num_send_contexts; ctxt++)
1377                 sc_free(dd->send_contexts[ctxt].sc);
1378         dd->num_send_contexts = 0;
1379         kfree(dd->send_contexts);
1380         dd->send_contexts = NULL;
1381         kfree(dd->hw_to_sw);
1382         dd->hw_to_sw = NULL;
1383         kfree(dd->boardname);
1384         vfree(dd->events);
1385         vfree(dd->status);
1386 }
1387
1388 /*
1389  * Clean up on unit shutdown, or error during unit load after
1390  * successful initialization.
1391  */
1392 static void postinit_cleanup(struct hfi1_devdata *dd)
1393 {
1394         hfi1_start_cleanup(dd);
1395
1396         hfi1_pcie_ddcleanup(dd);
1397         hfi1_pcie_cleanup(dd->pcidev);
1398
1399         cleanup_device_data(dd);
1400
1401         hfi1_free_devdata(dd);
1402 }
1403
1404 static int init_validate_rcvhdrcnt(struct device *dev, uint thecnt)
1405 {
1406         if (thecnt <= HFI1_MIN_HDRQ_EGRBUF_CNT) {
1407                 hfi1_early_err(dev, "Receive header queue count too small\n");
1408                 return -EINVAL;
1409         }
1410
1411         if (thecnt > HFI1_MAX_HDRQ_EGRBUF_CNT) {
1412                 hfi1_early_err(dev,
1413                                "Receive header queue count cannot be greater than %u\n",
1414                                HFI1_MAX_HDRQ_EGRBUF_CNT);
1415                 return -EINVAL;
1416         }
1417
1418         if (thecnt % HDRQ_INCREMENT) {
1419                 hfi1_early_err(dev, "Receive header queue count %d must be divisible by %lu\n",
1420                                thecnt, HDRQ_INCREMENT);
1421                 return -EINVAL;
1422         }
1423
1424         return 0;
1425 }
1426
1427 static int init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
1428 {
1429         int ret = 0, j, pidx, initfail;
1430         struct hfi1_devdata *dd;
1431         struct hfi1_pportdata *ppd;
1432
1433         /* First, lock the non-writable module parameters */
1434         HFI1_CAP_LOCK();
1435
1436         /* Validate dev ids */
1437         if (!(ent->device == PCI_DEVICE_ID_INTEL0 ||
1438               ent->device == PCI_DEVICE_ID_INTEL1)) {
1439                 hfi1_early_err(&pdev->dev,
1440                                "Failing on unknown Intel deviceid 0x%x\n",
1441                                ent->device);
1442                 ret = -ENODEV;
1443                 goto bail;
1444         }
1445
1446         /* Validate some global module parameters */
1447         ret = init_validate_rcvhdrcnt(&pdev->dev, rcvhdrcnt);
1448         if (ret)
1449                 goto bail;
1450
1451         /* use the encoding function as a sanitization check */
1452         if (!encode_rcv_header_entry_size(hfi1_hdrq_entsize)) {
1453                 hfi1_early_err(&pdev->dev, "Invalid HdrQ Entry size %u\n",
1454                                hfi1_hdrq_entsize);
1455                 ret = -EINVAL;
1456                 goto bail;
1457         }
1458
1459         /* The receive eager buffer size must be set before the receive
1460          * contexts are created.
1461          *
1462          * Set the eager buffer size.  Validate that it falls in a range
1463          * allowed by the hardware - all powers of 2 between the min and
1464          * max.  The maximum valid MTU is within the eager buffer range
1465          * so we do not need to cap the max_mtu by an eager buffer size
1466          * setting.
1467          */
1468         if (eager_buffer_size) {
1469                 if (!is_power_of_2(eager_buffer_size))
1470                         eager_buffer_size =
1471                                 roundup_pow_of_two(eager_buffer_size);
1472                 eager_buffer_size =
1473                         clamp_val(eager_buffer_size,
1474                                   MIN_EAGER_BUFFER * 8,
1475                                   MAX_EAGER_BUFFER_TOTAL);
1476                 hfi1_early_info(&pdev->dev, "Eager buffer size %u\n",
1477                                 eager_buffer_size);
1478         } else {
1479                 hfi1_early_err(&pdev->dev, "Invalid Eager buffer size of 0\n");
1480                 ret = -EINVAL;
1481                 goto bail;
1482         }
1483
1484         /* restrict value of hfi1_rcvarr_split */
1485         hfi1_rcvarr_split = clamp_val(hfi1_rcvarr_split, 0, 100);
1486
1487         ret = hfi1_pcie_init(pdev, ent);
1488         if (ret)
1489                 goto bail;
1490
1491         /*
1492          * Do device-specific initialization, function table setup, dd
1493          * allocation, etc.
1494          */
1495         dd = hfi1_init_dd(pdev, ent);
1496
1497         if (IS_ERR(dd)) {
1498                 ret = PTR_ERR(dd);
1499                 goto clean_bail; /* error already printed */
1500         }
1501
1502         ret = create_workqueues(dd);
1503         if (ret)
1504                 goto clean_bail;
1505
1506         /* do the generic initialization */
1507         initfail = hfi1_init(dd, 0);
1508
1509         /* setup vnic */
1510         hfi1_vnic_setup(dd);
1511
1512         ret = hfi1_register_ib_device(dd);
1513
1514         /*
1515          * Now ready for use.  this should be cleared whenever we
1516          * detect a reset, or initiate one.  If earlier failure,
1517          * we still create devices, so diags, etc. can be used
1518          * to determine cause of problem.
1519          */
1520         if (!initfail && !ret) {
1521                 dd->flags |= HFI1_INITTED;
1522                 /* create debufs files after init and ib register */
1523                 hfi1_dbg_ibdev_init(&dd->verbs_dev);
1524         }
1525
1526         j = hfi1_device_create(dd);
1527         if (j)
1528                 dd_dev_err(dd, "Failed to create /dev devices: %d\n", -j);
1529
1530         if (initfail || ret) {
1531                 stop_timers(dd);
1532                 flush_workqueue(ib_wq);
1533                 for (pidx = 0; pidx < dd->num_pports; ++pidx) {
1534                         hfi1_quiet_serdes(dd->pport + pidx);
1535                         ppd = dd->pport + pidx;
1536                         if (ppd->hfi1_wq) {
1537                                 destroy_workqueue(ppd->hfi1_wq);
1538                                 ppd->hfi1_wq = NULL;
1539                         }
1540                 }
1541                 if (!j)
1542                         hfi1_device_remove(dd);
1543                 if (!ret)
1544                         hfi1_unregister_ib_device(dd);
1545                 hfi1_vnic_cleanup(dd);
1546                 postinit_cleanup(dd);
1547                 if (initfail)
1548                         ret = initfail;
1549                 goto bail;      /* everything already cleaned */
1550         }
1551
1552         sdma_start(dd);
1553
1554         return 0;
1555
1556 clean_bail:
1557         hfi1_pcie_cleanup(pdev);
1558 bail:
1559         return ret;
1560 }
1561
1562 static void wait_for_clients(struct hfi1_devdata *dd)
1563 {
1564         /*
1565          * Remove the device init value and complete the device if there is
1566          * no clients or wait for active clients to finish.
1567          */
1568         if (atomic_dec_and_test(&dd->user_refcount))
1569                 complete(&dd->user_comp);
1570
1571         wait_for_completion(&dd->user_comp);
1572 }
1573
1574 static void remove_one(struct pci_dev *pdev)
1575 {
1576         struct hfi1_devdata *dd = pci_get_drvdata(pdev);
1577
1578         /* close debugfs files before ib unregister */
1579         hfi1_dbg_ibdev_exit(&dd->verbs_dev);
1580
1581         /* remove the /dev hfi1 interface */
1582         hfi1_device_remove(dd);
1583
1584         /* wait for existing user space clients to finish */
1585         wait_for_clients(dd);
1586
1587         /* unregister from IB core */
1588         hfi1_unregister_ib_device(dd);
1589
1590         /* cleanup vnic */
1591         hfi1_vnic_cleanup(dd);
1592
1593         /*
1594          * Disable the IB link, disable interrupts on the device,
1595          * clear dma engines, etc.
1596          */
1597         shutdown_device(dd);
1598
1599         stop_timers(dd);
1600
1601         /* wait until all of our (qsfp) queue_work() calls complete */
1602         flush_workqueue(ib_wq);
1603
1604         postinit_cleanup(dd);
1605 }
1606
1607 /**
1608  * hfi1_create_rcvhdrq - create a receive header queue
1609  * @dd: the hfi1_ib device
1610  * @rcd: the context data
1611  *
1612  * This must be contiguous memory (from an i/o perspective), and must be
1613  * DMA'able (which means for some systems, it will go through an IOMMU,
1614  * or be forced into a low address range).
1615  */
1616 int hfi1_create_rcvhdrq(struct hfi1_devdata *dd, struct hfi1_ctxtdata *rcd)
1617 {
1618         unsigned amt;
1619         u64 reg;
1620
1621         if (!rcd->rcvhdrq) {
1622                 dma_addr_t dma_hdrqtail;
1623                 gfp_t gfp_flags;
1624
1625                 /*
1626                  * rcvhdrqentsize is in DWs, so we have to convert to bytes
1627                  * (* sizeof(u32)).
1628                  */
1629                 amt = PAGE_ALIGN(rcd->rcvhdrq_cnt * rcd->rcvhdrqentsize *
1630                                  sizeof(u32));
1631
1632                 if ((rcd->ctxt < dd->first_dyn_alloc_ctxt) ||
1633                     (rcd->sc && (rcd->sc->type == SC_KERNEL)))
1634                         gfp_flags = GFP_KERNEL;
1635                 else
1636                         gfp_flags = GFP_USER;
1637                 rcd->rcvhdrq = dma_zalloc_coherent(
1638                         &dd->pcidev->dev, amt, &rcd->rcvhdrq_dma,
1639                         gfp_flags | __GFP_COMP);
1640
1641                 if (!rcd->rcvhdrq) {
1642                         dd_dev_err(dd,
1643                                    "attempt to allocate %d bytes for ctxt %u rcvhdrq failed\n",
1644                                    amt, rcd->ctxt);
1645                         goto bail;
1646                 }
1647
1648                 if (HFI1_CAP_KGET_MASK(rcd->flags, DMA_RTAIL)) {
1649                         rcd->rcvhdrtail_kvaddr = dma_zalloc_coherent(
1650                                 &dd->pcidev->dev, PAGE_SIZE, &dma_hdrqtail,
1651                                 gfp_flags);
1652                         if (!rcd->rcvhdrtail_kvaddr)
1653                                 goto bail_free;
1654                         rcd->rcvhdrqtailaddr_dma = dma_hdrqtail;
1655                 }
1656
1657                 rcd->rcvhdrq_size = amt;
1658         }
1659         /*
1660          * These values are per-context:
1661          *      RcvHdrCnt
1662          *      RcvHdrEntSize
1663          *      RcvHdrSize
1664          */
1665         reg = ((u64)(rcd->rcvhdrq_cnt >> HDRQ_SIZE_SHIFT)
1666                         & RCV_HDR_CNT_CNT_MASK)
1667                 << RCV_HDR_CNT_CNT_SHIFT;
1668         write_kctxt_csr(dd, rcd->ctxt, RCV_HDR_CNT, reg);
1669         reg = (encode_rcv_header_entry_size(rcd->rcvhdrqentsize)
1670                         & RCV_HDR_ENT_SIZE_ENT_SIZE_MASK)
1671                 << RCV_HDR_ENT_SIZE_ENT_SIZE_SHIFT;
1672         write_kctxt_csr(dd, rcd->ctxt, RCV_HDR_ENT_SIZE, reg);
1673         reg = (dd->rcvhdrsize & RCV_HDR_SIZE_HDR_SIZE_MASK)
1674                 << RCV_HDR_SIZE_HDR_SIZE_SHIFT;
1675         write_kctxt_csr(dd, rcd->ctxt, RCV_HDR_SIZE, reg);
1676
1677         /*
1678          * Program dummy tail address for every receive context
1679          * before enabling any receive context
1680          */
1681         write_kctxt_csr(dd, rcd->ctxt, RCV_HDR_TAIL_ADDR,
1682                         dd->rcvhdrtail_dummy_dma);
1683
1684         return 0;
1685
1686 bail_free:
1687         dd_dev_err(dd,
1688                    "attempt to allocate 1 page for ctxt %u rcvhdrqtailaddr failed\n",
1689                    rcd->ctxt);
1690         vfree(rcd->user_event_mask);
1691         rcd->user_event_mask = NULL;
1692         dma_free_coherent(&dd->pcidev->dev, amt, rcd->rcvhdrq,
1693                           rcd->rcvhdrq_dma);
1694         rcd->rcvhdrq = NULL;
1695 bail:
1696         return -ENOMEM;
1697 }
1698
1699 /**
1700  * allocate eager buffers, both kernel and user contexts.
1701  * @rcd: the context we are setting up.
1702  *
1703  * Allocate the eager TID buffers and program them into hip.
1704  * They are no longer completely contiguous, we do multiple allocation
1705  * calls.  Otherwise we get the OOM code involved, by asking for too
1706  * much per call, with disastrous results on some kernels.
1707  */
1708 int hfi1_setup_eagerbufs(struct hfi1_ctxtdata *rcd)
1709 {
1710         struct hfi1_devdata *dd = rcd->dd;
1711         u32 max_entries, egrtop, alloced_bytes = 0, idx = 0;
1712         gfp_t gfp_flags;
1713         u16 order;
1714         int ret = 0;
1715         u16 round_mtu = roundup_pow_of_two(hfi1_max_mtu);
1716
1717         /*
1718          * GFP_USER, but without GFP_FS, so buffer cache can be
1719          * coalesced (we hope); otherwise, even at order 4,
1720          * heavy filesystem activity makes these fail, and we can
1721          * use compound pages.
1722          */
1723         gfp_flags = __GFP_RECLAIM | __GFP_IO | __GFP_COMP;
1724
1725         /*
1726          * The minimum size of the eager buffers is a groups of MTU-sized
1727          * buffers.
1728          * The global eager_buffer_size parameter is checked against the
1729          * theoretical lower limit of the value. Here, we check against the
1730          * MTU.
1731          */
1732         if (rcd->egrbufs.size < (round_mtu * dd->rcv_entries.group_size))
1733                 rcd->egrbufs.size = round_mtu * dd->rcv_entries.group_size;
1734         /*
1735          * If using one-pkt-per-egr-buffer, lower the eager buffer
1736          * size to the max MTU (page-aligned).
1737          */
1738         if (!HFI1_CAP_KGET_MASK(rcd->flags, MULTI_PKT_EGR))
1739                 rcd->egrbufs.rcvtid_size = round_mtu;
1740
1741         /*
1742          * Eager buffers sizes of 1MB or less require smaller TID sizes
1743          * to satisfy the "multiple of 8 RcvArray entries" requirement.
1744          */
1745         if (rcd->egrbufs.size <= (1 << 20))
1746                 rcd->egrbufs.rcvtid_size = max((unsigned long)round_mtu,
1747                         rounddown_pow_of_two(rcd->egrbufs.size / 8));
1748
1749         while (alloced_bytes < rcd->egrbufs.size &&
1750                rcd->egrbufs.alloced < rcd->egrbufs.count) {
1751                 rcd->egrbufs.buffers[idx].addr =
1752                         dma_zalloc_coherent(&dd->pcidev->dev,
1753                                             rcd->egrbufs.rcvtid_size,
1754                                             &rcd->egrbufs.buffers[idx].dma,
1755                                             gfp_flags);
1756                 if (rcd->egrbufs.buffers[idx].addr) {
1757                         rcd->egrbufs.buffers[idx].len =
1758                                 rcd->egrbufs.rcvtid_size;
1759                         rcd->egrbufs.rcvtids[rcd->egrbufs.alloced].addr =
1760                                 rcd->egrbufs.buffers[idx].addr;
1761                         rcd->egrbufs.rcvtids[rcd->egrbufs.alloced].dma =
1762                                 rcd->egrbufs.buffers[idx].dma;
1763                         rcd->egrbufs.alloced++;
1764                         alloced_bytes += rcd->egrbufs.rcvtid_size;
1765                         idx++;
1766                 } else {
1767                         u32 new_size, i, j;
1768                         u64 offset = 0;
1769
1770                         /*
1771                          * Fail the eager buffer allocation if:
1772                          *   - we are already using the lowest acceptable size
1773                          *   - we are using one-pkt-per-egr-buffer (this implies
1774                          *     that we are accepting only one size)
1775                          */
1776                         if (rcd->egrbufs.rcvtid_size == round_mtu ||
1777                             !HFI1_CAP_KGET_MASK(rcd->flags, MULTI_PKT_EGR)) {
1778                                 dd_dev_err(dd, "ctxt%u: Failed to allocate eager buffers\n",
1779                                            rcd->ctxt);
1780                                 goto bail_rcvegrbuf_phys;
1781                         }
1782
1783                         new_size = rcd->egrbufs.rcvtid_size / 2;
1784
1785                         /*
1786                          * If the first attempt to allocate memory failed, don't
1787                          * fail everything but continue with the next lower
1788                          * size.
1789                          */
1790                         if (idx == 0) {
1791                                 rcd->egrbufs.rcvtid_size = new_size;
1792                                 continue;
1793                         }
1794
1795                         /*
1796                          * Re-partition already allocated buffers to a smaller
1797                          * size.
1798                          */
1799                         rcd->egrbufs.alloced = 0;
1800                         for (i = 0, j = 0, offset = 0; j < idx; i++) {
1801                                 if (i >= rcd->egrbufs.count)
1802                                         break;
1803                                 rcd->egrbufs.rcvtids[i].dma =
1804                                         rcd->egrbufs.buffers[j].dma + offset;
1805                                 rcd->egrbufs.rcvtids[i].addr =
1806                                         rcd->egrbufs.buffers[j].addr + offset;
1807                                 rcd->egrbufs.alloced++;
1808                                 if ((rcd->egrbufs.buffers[j].dma + offset +
1809                                      new_size) ==
1810                                     (rcd->egrbufs.buffers[j].dma +
1811                                      rcd->egrbufs.buffers[j].len)) {
1812                                         j++;
1813                                         offset = 0;
1814                                 } else {
1815                                         offset += new_size;
1816                                 }
1817                         }
1818                         rcd->egrbufs.rcvtid_size = new_size;
1819                 }
1820         }
1821         rcd->egrbufs.numbufs = idx;
1822         rcd->egrbufs.size = alloced_bytes;
1823
1824         hfi1_cdbg(PROC,
1825                   "ctxt%u: Alloced %u rcv tid entries @ %uKB, total %zuKB\n",
1826                   rcd->ctxt, rcd->egrbufs.alloced,
1827                   rcd->egrbufs.rcvtid_size / 1024, rcd->egrbufs.size / 1024);
1828
1829         /*
1830          * Set the contexts rcv array head update threshold to the closest
1831          * power of 2 (so we can use a mask instead of modulo) below half
1832          * the allocated entries.
1833          */
1834         rcd->egrbufs.threshold =
1835                 rounddown_pow_of_two(rcd->egrbufs.alloced / 2);
1836         /*
1837          * Compute the expected RcvArray entry base. This is done after
1838          * allocating the eager buffers in order to maximize the
1839          * expected RcvArray entries for the context.
1840          */
1841         max_entries = rcd->rcv_array_groups * dd->rcv_entries.group_size;
1842         egrtop = roundup(rcd->egrbufs.alloced, dd->rcv_entries.group_size);
1843         rcd->expected_count = max_entries - egrtop;
1844         if (rcd->expected_count > MAX_TID_PAIR_ENTRIES * 2)
1845                 rcd->expected_count = MAX_TID_PAIR_ENTRIES * 2;
1846
1847         rcd->expected_base = rcd->eager_base + egrtop;
1848         hfi1_cdbg(PROC, "ctxt%u: eager:%u, exp:%u, egrbase:%u, expbase:%u\n",
1849                   rcd->ctxt, rcd->egrbufs.alloced, rcd->expected_count,
1850                   rcd->eager_base, rcd->expected_base);
1851
1852         if (!hfi1_rcvbuf_validate(rcd->egrbufs.rcvtid_size, PT_EAGER, &order)) {
1853                 hfi1_cdbg(PROC,
1854                           "ctxt%u: current Eager buffer size is invalid %u\n",
1855                           rcd->ctxt, rcd->egrbufs.rcvtid_size);
1856                 ret = -EINVAL;
1857                 goto bail;
1858         }
1859
1860         for (idx = 0; idx < rcd->egrbufs.alloced; idx++) {
1861                 hfi1_put_tid(dd, rcd->eager_base + idx, PT_EAGER,
1862                              rcd->egrbufs.rcvtids[idx].dma, order);
1863                 cond_resched();
1864         }
1865         goto bail;
1866
1867 bail_rcvegrbuf_phys:
1868         for (idx = 0; idx < rcd->egrbufs.alloced &&
1869              rcd->egrbufs.buffers[idx].addr;
1870              idx++) {
1871                 dma_free_coherent(&dd->pcidev->dev,
1872                                   rcd->egrbufs.buffers[idx].len,
1873                                   rcd->egrbufs.buffers[idx].addr,
1874                                   rcd->egrbufs.buffers[idx].dma);
1875                 rcd->egrbufs.buffers[idx].addr = NULL;
1876                 rcd->egrbufs.buffers[idx].dma = 0;
1877                 rcd->egrbufs.buffers[idx].len = 0;
1878         }
1879 bail:
1880         return ret;
1881 }