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