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