GNU Linux-libre 4.9.309-gnu1
[releases.git] / drivers / infiniband / hw / hfi1 / pio.c
1 /*
2  * Copyright(c) 2015, 2016 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/delay.h>
49 #include "hfi.h"
50 #include "qp.h"
51 #include "trace.h"
52
53 #define SC_CTXT_PACKET_EGRESS_TIMEOUT 350 /* in chip cycles */
54
55 #define SC(name) SEND_CTXT_##name
56 /*
57  * Send Context functions
58  */
59 static void sc_wait_for_packet_egress(struct send_context *sc, int pause);
60
61 /*
62  * Set the CM reset bit and wait for it to clear.  Use the provided
63  * sendctrl register.  This routine has no locking.
64  */
65 void __cm_reset(struct hfi1_devdata *dd, u64 sendctrl)
66 {
67         write_csr(dd, SEND_CTRL, sendctrl | SEND_CTRL_CM_RESET_SMASK);
68         while (1) {
69                 udelay(1);
70                 sendctrl = read_csr(dd, SEND_CTRL);
71                 if ((sendctrl & SEND_CTRL_CM_RESET_SMASK) == 0)
72                         break;
73         }
74 }
75
76 /* defined in header release 48 and higher */
77 #ifndef SEND_CTRL_UNSUPPORTED_VL_SHIFT
78 #define SEND_CTRL_UNSUPPORTED_VL_SHIFT 3
79 #define SEND_CTRL_UNSUPPORTED_VL_MASK 0xffull
80 #define SEND_CTRL_UNSUPPORTED_VL_SMASK (SEND_CTRL_UNSUPPORTED_VL_MASK \
81                 << SEND_CTRL_UNSUPPORTED_VL_SHIFT)
82 #endif
83
84 /* global control of PIO send */
85 void pio_send_control(struct hfi1_devdata *dd, int op)
86 {
87         u64 reg, mask;
88         unsigned long flags;
89         int write = 1;  /* write sendctrl back */
90         int flush = 0;  /* re-read sendctrl to make sure it is flushed */
91         int i;
92
93         spin_lock_irqsave(&dd->sendctrl_lock, flags);
94
95         reg = read_csr(dd, SEND_CTRL);
96         switch (op) {
97         case PSC_GLOBAL_ENABLE:
98                 reg |= SEND_CTRL_SEND_ENABLE_SMASK;
99         /* Fall through */
100         case PSC_DATA_VL_ENABLE:
101                 mask = 0;
102                 for (i = 0; i < ARRAY_SIZE(dd->vld); i++)
103                         if (!dd->vld[i].mtu)
104                                 mask |= BIT_ULL(i);
105                 /* Disallow sending on VLs not enabled */
106                 mask = (mask & SEND_CTRL_UNSUPPORTED_VL_MASK) <<
107                         SEND_CTRL_UNSUPPORTED_VL_SHIFT;
108                 reg = (reg & ~SEND_CTRL_UNSUPPORTED_VL_SMASK) | mask;
109                 break;
110         case PSC_GLOBAL_DISABLE:
111                 reg &= ~SEND_CTRL_SEND_ENABLE_SMASK;
112                 break;
113         case PSC_GLOBAL_VLARB_ENABLE:
114                 reg |= SEND_CTRL_VL_ARBITER_ENABLE_SMASK;
115                 break;
116         case PSC_GLOBAL_VLARB_DISABLE:
117                 reg &= ~SEND_CTRL_VL_ARBITER_ENABLE_SMASK;
118                 break;
119         case PSC_CM_RESET:
120                 __cm_reset(dd, reg);
121                 write = 0; /* CSR already written (and flushed) */
122                 break;
123         case PSC_DATA_VL_DISABLE:
124                 reg |= SEND_CTRL_UNSUPPORTED_VL_SMASK;
125                 flush = 1;
126                 break;
127         default:
128                 dd_dev_err(dd, "%s: invalid control %d\n", __func__, op);
129                 break;
130         }
131
132         if (write) {
133                 write_csr(dd, SEND_CTRL, reg);
134                 if (flush)
135                         (void)read_csr(dd, SEND_CTRL); /* flush write */
136         }
137
138         spin_unlock_irqrestore(&dd->sendctrl_lock, flags);
139 }
140
141 /* number of send context memory pools */
142 #define NUM_SC_POOLS 2
143
144 /* Send Context Size (SCS) wildcards */
145 #define SCS_POOL_0 -1
146 #define SCS_POOL_1 -2
147
148 /* Send Context Count (SCC) wildcards */
149 #define SCC_PER_VL -1
150 #define SCC_PER_CPU  -2
151 #define SCC_PER_KRCVQ  -3
152
153 /* Send Context Size (SCS) constants */
154 #define SCS_ACK_CREDITS  32
155 #define SCS_VL15_CREDITS 102    /* 3 pkts of 2048B data + 128B header */
156
157 #define PIO_THRESHOLD_CEILING 4096
158
159 #define PIO_WAIT_BATCH_SIZE 5
160
161 /* default send context sizes */
162 static struct sc_config_sizes sc_config_sizes[SC_MAX] = {
163         [SC_KERNEL] = { .size  = SCS_POOL_0,    /* even divide, pool 0 */
164                         .count = SCC_PER_VL },  /* one per NUMA */
165         [SC_ACK]    = { .size  = SCS_ACK_CREDITS,
166                         .count = SCC_PER_KRCVQ },
167         [SC_USER]   = { .size  = SCS_POOL_0,    /* even divide, pool 0 */
168                         .count = SCC_PER_CPU }, /* one per CPU */
169         [SC_VL15]   = { .size  = SCS_VL15_CREDITS,
170                         .count = 1 },
171
172 };
173
174 /* send context memory pool configuration */
175 struct mem_pool_config {
176         int centipercent;       /* % of memory, in 100ths of 1% */
177         int absolute_blocks;    /* absolute block count */
178 };
179
180 /* default memory pool configuration: 100% in pool 0 */
181 static struct mem_pool_config sc_mem_pool_config[NUM_SC_POOLS] = {
182         /* centi%, abs blocks */
183         {  10000,     -1 },             /* pool 0 */
184         {      0,     -1 },             /* pool 1 */
185 };
186
187 /* memory pool information, used when calculating final sizes */
188 struct mem_pool_info {
189         int centipercent;       /*
190                                  * 100th of 1% of memory to use, -1 if blocks
191                                  * already set
192                                  */
193         int count;              /* count of contexts in the pool */
194         int blocks;             /* block size of the pool */
195         int size;               /* context size, in blocks */
196 };
197
198 /*
199  * Convert a pool wildcard to a valid pool index.  The wildcards
200  * start at -1 and increase negatively.  Map them as:
201  *      -1 => 0
202  *      -2 => 1
203  *      etc.
204  *
205  * Return -1 on non-wildcard input, otherwise convert to a pool number.
206  */
207 static int wildcard_to_pool(int wc)
208 {
209         if (wc >= 0)
210                 return -1;      /* non-wildcard */
211         return -wc - 1;
212 }
213
214 static const char *sc_type_names[SC_MAX] = {
215         "kernel",
216         "ack",
217         "user",
218         "vl15"
219 };
220
221 static const char *sc_type_name(int index)
222 {
223         if (index < 0 || index >= SC_MAX)
224                 return "unknown";
225         return sc_type_names[index];
226 }
227
228 /*
229  * Read the send context memory pool configuration and send context
230  * size configuration.  Replace any wildcards and come up with final
231  * counts and sizes for the send context types.
232  */
233 int init_sc_pools_and_sizes(struct hfi1_devdata *dd)
234 {
235         struct mem_pool_info mem_pool_info[NUM_SC_POOLS] = { { 0 } };
236         int total_blocks = (dd->chip_pio_mem_size / PIO_BLOCK_SIZE) - 1;
237         int total_contexts = 0;
238         int fixed_blocks;
239         int pool_blocks;
240         int used_blocks;
241         int cp_total;           /* centipercent total */
242         int ab_total;           /* absolute block total */
243         int extra;
244         int i;
245
246         /*
247          * When SDMA is enabled, kernel context pio packet size is capped by
248          * "piothreshold". Reduce pio buffer allocation for kernel context by
249          * setting it to a fixed size. The allocation allows 3-deep buffering
250          * of the largest pio packets plus up to 128 bytes header, sufficient
251          * to maintain verbs performance.
252          *
253          * When SDMA is disabled, keep the default pooling allocation.
254          */
255         if (HFI1_CAP_IS_KSET(SDMA)) {
256                 u16 max_pkt_size = (piothreshold < PIO_THRESHOLD_CEILING) ?
257                                          piothreshold : PIO_THRESHOLD_CEILING;
258                 sc_config_sizes[SC_KERNEL].size =
259                         3 * (max_pkt_size + 128) / PIO_BLOCK_SIZE;
260         }
261
262         /*
263          * Step 0:
264          *      - copy the centipercents/absolute sizes from the pool config
265          *      - sanity check these values
266          *      - add up centipercents, then later check for full value
267          *      - add up absolute blocks, then later check for over-commit
268          */
269         cp_total = 0;
270         ab_total = 0;
271         for (i = 0; i < NUM_SC_POOLS; i++) {
272                 int cp = sc_mem_pool_config[i].centipercent;
273                 int ab = sc_mem_pool_config[i].absolute_blocks;
274
275                 /*
276                  * A negative value is "unused" or "invalid".  Both *can*
277                  * be valid, but centipercent wins, so check that first
278                  */
279                 if (cp >= 0) {                  /* centipercent valid */
280                         cp_total += cp;
281                 } else if (ab >= 0) {           /* absolute blocks valid */
282                         ab_total += ab;
283                 } else {                        /* neither valid */
284                         dd_dev_err(
285                                 dd,
286                                 "Send context memory pool %d: both the block count and centipercent are invalid\n",
287                                 i);
288                         return -EINVAL;
289                 }
290
291                 mem_pool_info[i].centipercent = cp;
292                 mem_pool_info[i].blocks = ab;
293         }
294
295         /* do not use both % and absolute blocks for different pools */
296         if (cp_total != 0 && ab_total != 0) {
297                 dd_dev_err(
298                         dd,
299                         "All send context memory pools must be described as either centipercent or blocks, no mixing between pools\n");
300                 return -EINVAL;
301         }
302
303         /* if any percentages are present, they must add up to 100% x 100 */
304         if (cp_total != 0 && cp_total != 10000) {
305                 dd_dev_err(
306                         dd,
307                         "Send context memory pool centipercent is %d, expecting 10000\n",
308                         cp_total);
309                 return -EINVAL;
310         }
311
312         /* the absolute pool total cannot be more than the mem total */
313         if (ab_total > total_blocks) {
314                 dd_dev_err(
315                         dd,
316                         "Send context memory pool absolute block count %d is larger than the memory size %d\n",
317                         ab_total, total_blocks);
318                 return -EINVAL;
319         }
320
321         /*
322          * Step 2:
323          *      - copy from the context size config
324          *      - replace context type wildcard counts with real values
325          *      - add up non-memory pool block sizes
326          *      - add up memory pool user counts
327          */
328         fixed_blocks = 0;
329         for (i = 0; i < SC_MAX; i++) {
330                 int count = sc_config_sizes[i].count;
331                 int size = sc_config_sizes[i].size;
332                 int pool;
333
334                 /*
335                  * Sanity check count: Either a positive value or
336                  * one of the expected wildcards is valid.  The positive
337                  * value is checked later when we compare against total
338                  * memory available.
339                  */
340                 if (i == SC_ACK) {
341                         count = dd->n_krcv_queues;
342                 } else if (i == SC_KERNEL) {
343                         count = INIT_SC_PER_VL * num_vls;
344                 } else if (count == SCC_PER_CPU) {
345                         count = dd->num_rcv_contexts - dd->n_krcv_queues;
346                 } else if (count < 0) {
347                         dd_dev_err(
348                                 dd,
349                                 "%s send context invalid count wildcard %d\n",
350                                 sc_type_name(i), count);
351                         return -EINVAL;
352                 }
353                 if (total_contexts + count > dd->chip_send_contexts)
354                         count = dd->chip_send_contexts - total_contexts;
355
356                 total_contexts += count;
357
358                 /*
359                  * Sanity check pool: The conversion will return a pool
360                  * number or -1 if a fixed (non-negative) value.  The fixed
361                  * value is checked later when we compare against
362                  * total memory available.
363                  */
364                 pool = wildcard_to_pool(size);
365                 if (pool == -1) {                       /* non-wildcard */
366                         fixed_blocks += size * count;
367                 } else if (pool < NUM_SC_POOLS) {       /* valid wildcard */
368                         mem_pool_info[pool].count += count;
369                 } else {                                /* invalid wildcard */
370                         dd_dev_err(
371                                 dd,
372                                 "%s send context invalid pool wildcard %d\n",
373                                 sc_type_name(i), size);
374                         return -EINVAL;
375                 }
376
377                 dd->sc_sizes[i].count = count;
378                 dd->sc_sizes[i].size = size;
379         }
380         if (fixed_blocks > total_blocks) {
381                 dd_dev_err(
382                         dd,
383                         "Send context fixed block count, %u, larger than total block count %u\n",
384                         fixed_blocks, total_blocks);
385                 return -EINVAL;
386         }
387
388         /* step 3: calculate the blocks in the pools, and pool context sizes */
389         pool_blocks = total_blocks - fixed_blocks;
390         if (ab_total > pool_blocks) {
391                 dd_dev_err(
392                         dd,
393                         "Send context fixed pool sizes, %u, larger than pool block count %u\n",
394                         ab_total, pool_blocks);
395                 return -EINVAL;
396         }
397         /* subtract off the fixed pool blocks */
398         pool_blocks -= ab_total;
399
400         for (i = 0; i < NUM_SC_POOLS; i++) {
401                 struct mem_pool_info *pi = &mem_pool_info[i];
402
403                 /* % beats absolute blocks */
404                 if (pi->centipercent >= 0)
405                         pi->blocks = (pool_blocks * pi->centipercent) / 10000;
406
407                 if (pi->blocks == 0 && pi->count != 0) {
408                         dd_dev_err(
409                                 dd,
410                                 "Send context memory pool %d has %u contexts, but no blocks\n",
411                                 i, pi->count);
412                         return -EINVAL;
413                 }
414                 if (pi->count == 0) {
415                         /* warn about wasted blocks */
416                         if (pi->blocks != 0)
417                                 dd_dev_err(
418                                         dd,
419                                         "Send context memory pool %d has %u blocks, but zero contexts\n",
420                                         i, pi->blocks);
421                         pi->size = 0;
422                 } else {
423                         pi->size = pi->blocks / pi->count;
424                 }
425         }
426
427         /* step 4: fill in the context type sizes from the pool sizes */
428         used_blocks = 0;
429         for (i = 0; i < SC_MAX; i++) {
430                 if (dd->sc_sizes[i].size < 0) {
431                         unsigned pool = wildcard_to_pool(dd->sc_sizes[i].size);
432
433                         WARN_ON_ONCE(pool >= NUM_SC_POOLS);
434                         dd->sc_sizes[i].size = mem_pool_info[pool].size;
435                 }
436                 /* make sure we are not larger than what is allowed by the HW */
437 #define PIO_MAX_BLOCKS 1024
438                 if (dd->sc_sizes[i].size > PIO_MAX_BLOCKS)
439                         dd->sc_sizes[i].size = PIO_MAX_BLOCKS;
440
441                 /* calculate our total usage */
442                 used_blocks += dd->sc_sizes[i].size * dd->sc_sizes[i].count;
443         }
444         extra = total_blocks - used_blocks;
445         if (extra != 0)
446                 dd_dev_info(dd, "unused send context blocks: %d\n", extra);
447
448         return total_contexts;
449 }
450
451 int init_send_contexts(struct hfi1_devdata *dd)
452 {
453         u16 base;
454         int ret, i, j, context;
455
456         ret = init_credit_return(dd);
457         if (ret)
458                 return ret;
459
460         dd->hw_to_sw = kmalloc_array(TXE_NUM_CONTEXTS, sizeof(u8),
461                                         GFP_KERNEL);
462         dd->send_contexts = kcalloc(dd->num_send_contexts,
463                                         sizeof(struct send_context_info),
464                                         GFP_KERNEL);
465         if (!dd->send_contexts || !dd->hw_to_sw) {
466                 kfree(dd->hw_to_sw);
467                 kfree(dd->send_contexts);
468                 free_credit_return(dd);
469                 return -ENOMEM;
470         }
471
472         /* hardware context map starts with invalid send context indices */
473         for (i = 0; i < TXE_NUM_CONTEXTS; i++)
474                 dd->hw_to_sw[i] = INVALID_SCI;
475
476         /*
477          * All send contexts have their credit sizes.  Allocate credits
478          * for each context one after another from the global space.
479          */
480         context = 0;
481         base = 1;
482         for (i = 0; i < SC_MAX; i++) {
483                 struct sc_config_sizes *scs = &dd->sc_sizes[i];
484
485                 for (j = 0; j < scs->count; j++) {
486                         struct send_context_info *sci =
487                                                 &dd->send_contexts[context];
488                         sci->type = i;
489                         sci->base = base;
490                         sci->credits = scs->size;
491
492                         context++;
493                         base += scs->size;
494                 }
495         }
496
497         return 0;
498 }
499
500 /*
501  * Allocate a software index and hardware context of the given type.
502  *
503  * Must be called with dd->sc_lock held.
504  */
505 static int sc_hw_alloc(struct hfi1_devdata *dd, int type, u32 *sw_index,
506                        u32 *hw_context)
507 {
508         struct send_context_info *sci;
509         u32 index;
510         u32 context;
511
512         for (index = 0, sci = &dd->send_contexts[0];
513                         index < dd->num_send_contexts; index++, sci++) {
514                 if (sci->type == type && sci->allocated == 0) {
515                         sci->allocated = 1;
516                         /* use a 1:1 mapping, but make them non-equal */
517                         context = dd->chip_send_contexts - index - 1;
518                         dd->hw_to_sw[context] = index;
519                         *sw_index = index;
520                         *hw_context = context;
521                         return 0; /* success */
522                 }
523         }
524         dd_dev_err(dd, "Unable to locate a free type %d send context\n", type);
525         return -ENOSPC;
526 }
527
528 /*
529  * Free the send context given by its software index.
530  *
531  * Must be called with dd->sc_lock held.
532  */
533 static void sc_hw_free(struct hfi1_devdata *dd, u32 sw_index, u32 hw_context)
534 {
535         struct send_context_info *sci;
536
537         sci = &dd->send_contexts[sw_index];
538         if (!sci->allocated) {
539                 dd_dev_err(dd, "%s: sw_index %u not allocated? hw_context %u\n",
540                            __func__, sw_index, hw_context);
541         }
542         sci->allocated = 0;
543         dd->hw_to_sw[hw_context] = INVALID_SCI;
544 }
545
546 /* return the base context of a context in a group */
547 static inline u32 group_context(u32 context, u32 group)
548 {
549         return (context >> group) << group;
550 }
551
552 /* return the size of a group */
553 static inline u32 group_size(u32 group)
554 {
555         return 1 << group;
556 }
557
558 /*
559  * Obtain the credit return addresses, kernel virtual and bus, for the
560  * given sc.
561  *
562  * To understand this routine:
563  * o va and dma are arrays of struct credit_return.  One for each physical
564  *   send context, per NUMA.
565  * o Each send context always looks in its relative location in a struct
566  *   credit_return for its credit return.
567  * o Each send context in a group must have its return address CSR programmed
568  *   with the same value.  Use the address of the first send context in the
569  *   group.
570  */
571 static void cr_group_addresses(struct send_context *sc, dma_addr_t *dma)
572 {
573         u32 gc = group_context(sc->hw_context, sc->group);
574         u32 index = sc->hw_context & 0x7;
575
576         sc->hw_free = &sc->dd->cr_base[sc->node].va[gc].cr[index];
577         *dma = (unsigned long)
578                &((struct credit_return *)sc->dd->cr_base[sc->node].dma)[gc];
579 }
580
581 /*
582  * Work queue function triggered in error interrupt routine for
583  * kernel contexts.
584  */
585 static void sc_halted(struct work_struct *work)
586 {
587         struct send_context *sc;
588
589         sc = container_of(work, struct send_context, halt_work);
590         sc_restart(sc);
591 }
592
593 /*
594  * Calculate PIO block threshold for this send context using the given MTU.
595  * Trigger a return when one MTU plus optional header of credits remain.
596  *
597  * Parameter mtu is in bytes.
598  * Parameter hdrqentsize is in DWORDs.
599  *
600  * Return value is what to write into the CSR: trigger return when
601  * unreturned credits pass this count.
602  */
603 u32 sc_mtu_to_threshold(struct send_context *sc, u32 mtu, u32 hdrqentsize)
604 {
605         u32 release_credits;
606         u32 threshold;
607
608         /* add in the header size, then divide by the PIO block size */
609         mtu += hdrqentsize << 2;
610         release_credits = DIV_ROUND_UP(mtu, PIO_BLOCK_SIZE);
611
612         /* check against this context's credits */
613         if (sc->credits <= release_credits)
614                 threshold = 1;
615         else
616                 threshold = sc->credits - release_credits;
617
618         return threshold;
619 }
620
621 /*
622  * Calculate credit threshold in terms of percent of the allocated credits.
623  * Trigger when unreturned credits equal or exceed the percentage of the whole.
624  *
625  * Return value is what to write into the CSR: trigger return when
626  * unreturned credits pass this count.
627  */
628 u32 sc_percent_to_threshold(struct send_context *sc, u32 percent)
629 {
630         return (sc->credits * percent) / 100;
631 }
632
633 /*
634  * Set the credit return threshold.
635  */
636 void sc_set_cr_threshold(struct send_context *sc, u32 new_threshold)
637 {
638         unsigned long flags;
639         u32 old_threshold;
640         int force_return = 0;
641
642         spin_lock_irqsave(&sc->credit_ctrl_lock, flags);
643
644         old_threshold = (sc->credit_ctrl >>
645                                 SC(CREDIT_CTRL_THRESHOLD_SHIFT))
646                          & SC(CREDIT_CTRL_THRESHOLD_MASK);
647
648         if (new_threshold != old_threshold) {
649                 sc->credit_ctrl =
650                         (sc->credit_ctrl
651                                 & ~SC(CREDIT_CTRL_THRESHOLD_SMASK))
652                         | ((new_threshold
653                                 & SC(CREDIT_CTRL_THRESHOLD_MASK))
654                            << SC(CREDIT_CTRL_THRESHOLD_SHIFT));
655                 write_kctxt_csr(sc->dd, sc->hw_context,
656                                 SC(CREDIT_CTRL), sc->credit_ctrl);
657
658                 /* force a credit return on change to avoid a possible stall */
659                 force_return = 1;
660         }
661
662         spin_unlock_irqrestore(&sc->credit_ctrl_lock, flags);
663
664         if (force_return)
665                 sc_return_credits(sc);
666 }
667
668 /*
669  * set_pio_integrity
670  *
671  * Set the CHECK_ENABLE register for the send context 'sc'.
672  */
673 void set_pio_integrity(struct send_context *sc)
674 {
675         struct hfi1_devdata *dd = sc->dd;
676         u32 hw_context = sc->hw_context;
677         int type = sc->type;
678
679         write_kctxt_csr(dd, hw_context,
680                         SC(CHECK_ENABLE),
681                         hfi1_pkt_default_send_ctxt_mask(dd, type));
682 }
683
684 static u32 get_buffers_allocated(struct send_context *sc)
685 {
686         int cpu;
687         u32 ret = 0;
688
689         for_each_possible_cpu(cpu)
690                 ret += *per_cpu_ptr(sc->buffers_allocated, cpu);
691         return ret;
692 }
693
694 static void reset_buffers_allocated(struct send_context *sc)
695 {
696         int cpu;
697
698         for_each_possible_cpu(cpu)
699                 (*per_cpu_ptr(sc->buffers_allocated, cpu)) = 0;
700 }
701
702 /*
703  * Allocate a NUMA relative send context structure of the given type along
704  * with a HW context.
705  */
706 struct send_context *sc_alloc(struct hfi1_devdata *dd, int type,
707                               uint hdrqentsize, int numa)
708 {
709         struct send_context_info *sci;
710         struct send_context *sc = NULL;
711         dma_addr_t dma;
712         unsigned long flags;
713         u64 reg;
714         u32 thresh;
715         u32 sw_index;
716         u32 hw_context;
717         int ret;
718         u8 opval, opmask;
719
720         /* do not allocate while frozen */
721         if (dd->flags & HFI1_FROZEN)
722                 return NULL;
723
724         sc = kzalloc_node(sizeof(*sc), GFP_KERNEL, numa);
725         if (!sc)
726                 return NULL;
727
728         sc->buffers_allocated = alloc_percpu(u32);
729         if (!sc->buffers_allocated) {
730                 kfree(sc);
731                 dd_dev_err(dd,
732                            "Cannot allocate buffers_allocated per cpu counters\n"
733                           );
734                 return NULL;
735         }
736
737         spin_lock_irqsave(&dd->sc_lock, flags);
738         ret = sc_hw_alloc(dd, type, &sw_index, &hw_context);
739         if (ret) {
740                 spin_unlock_irqrestore(&dd->sc_lock, flags);
741                 free_percpu(sc->buffers_allocated);
742                 kfree(sc);
743                 return NULL;
744         }
745
746         sci = &dd->send_contexts[sw_index];
747         sci->sc = sc;
748
749         sc->dd = dd;
750         sc->node = numa;
751         sc->type = type;
752         spin_lock_init(&sc->alloc_lock);
753         spin_lock_init(&sc->release_lock);
754         spin_lock_init(&sc->credit_ctrl_lock);
755         INIT_LIST_HEAD(&sc->piowait);
756         INIT_WORK(&sc->halt_work, sc_halted);
757         init_waitqueue_head(&sc->halt_wait);
758
759         /* grouping is always single context for now */
760         sc->group = 0;
761
762         sc->sw_index = sw_index;
763         sc->hw_context = hw_context;
764         cr_group_addresses(sc, &dma);
765         sc->credits = sci->credits;
766
767 /* PIO Send Memory Address details */
768 #define PIO_ADDR_CONTEXT_MASK 0xfful
769 #define PIO_ADDR_CONTEXT_SHIFT 16
770         sc->base_addr = dd->piobase + ((hw_context & PIO_ADDR_CONTEXT_MASK)
771                                         << PIO_ADDR_CONTEXT_SHIFT);
772
773         /* set base and credits */
774         reg = ((sci->credits & SC(CTRL_CTXT_DEPTH_MASK))
775                                         << SC(CTRL_CTXT_DEPTH_SHIFT))
776                 | ((sci->base & SC(CTRL_CTXT_BASE_MASK))
777                                         << SC(CTRL_CTXT_BASE_SHIFT));
778         write_kctxt_csr(dd, hw_context, SC(CTRL), reg);
779
780         set_pio_integrity(sc);
781
782         /* unmask all errors */
783         write_kctxt_csr(dd, hw_context, SC(ERR_MASK), (u64)-1);
784
785         /* set the default partition key */
786         write_kctxt_csr(dd, hw_context, SC(CHECK_PARTITION_KEY),
787                         (SC(CHECK_PARTITION_KEY_VALUE_MASK) &
788                          DEFAULT_PKEY) <<
789                         SC(CHECK_PARTITION_KEY_VALUE_SHIFT));
790
791         /* per context type checks */
792         if (type == SC_USER) {
793                 opval = USER_OPCODE_CHECK_VAL;
794                 opmask = USER_OPCODE_CHECK_MASK;
795         } else {
796                 opval = OPCODE_CHECK_VAL_DISABLED;
797                 opmask = OPCODE_CHECK_MASK_DISABLED;
798         }
799
800         /* set the send context check opcode mask and value */
801         write_kctxt_csr(dd, hw_context, SC(CHECK_OPCODE),
802                         ((u64)opmask << SC(CHECK_OPCODE_MASK_SHIFT)) |
803                         ((u64)opval << SC(CHECK_OPCODE_VALUE_SHIFT)));
804
805         /* set up credit return */
806         reg = dma & SC(CREDIT_RETURN_ADDR_ADDRESS_SMASK);
807         write_kctxt_csr(dd, hw_context, SC(CREDIT_RETURN_ADDR), reg);
808
809         /*
810          * Calculate the initial credit return threshold.
811          *
812          * For Ack contexts, set a threshold for half the credits.
813          * For User contexts use the given percentage.  This has been
814          * sanitized on driver start-up.
815          * For Kernel contexts, use the default MTU plus a header
816          * or half the credits, whichever is smaller. This should
817          * work for both the 3-deep buffering allocation and the
818          * pooling allocation.
819          */
820         if (type == SC_ACK) {
821                 thresh = sc_percent_to_threshold(sc, 50);
822         } else if (type == SC_USER) {
823                 thresh = sc_percent_to_threshold(sc,
824                                                  user_credit_return_threshold);
825         } else { /* kernel */
826                 thresh = min(sc_percent_to_threshold(sc, 50),
827                              sc_mtu_to_threshold(sc, hfi1_max_mtu,
828                                                  hdrqentsize));
829         }
830         reg = thresh << SC(CREDIT_CTRL_THRESHOLD_SHIFT);
831         /* add in early return */
832         if (type == SC_USER && HFI1_CAP_IS_USET(EARLY_CREDIT_RETURN))
833                 reg |= SC(CREDIT_CTRL_EARLY_RETURN_SMASK);
834         else if (HFI1_CAP_IS_KSET(EARLY_CREDIT_RETURN)) /* kernel, ack */
835                 reg |= SC(CREDIT_CTRL_EARLY_RETURN_SMASK);
836
837         /* set up write-through credit_ctrl */
838         sc->credit_ctrl = reg;
839         write_kctxt_csr(dd, hw_context, SC(CREDIT_CTRL), reg);
840
841         /* User send contexts should not allow sending on VL15 */
842         if (type == SC_USER) {
843                 reg = 1ULL << 15;
844                 write_kctxt_csr(dd, hw_context, SC(CHECK_VL), reg);
845         }
846
847         spin_unlock_irqrestore(&dd->sc_lock, flags);
848
849         /*
850          * Allocate shadow ring to track outstanding PIO buffers _after_
851          * unlocking.  We don't know the size until the lock is held and
852          * we can't allocate while the lock is held.  No one is using
853          * the context yet, so allocate it now.
854          *
855          * User contexts do not get a shadow ring.
856          */
857         if (type != SC_USER) {
858                 /*
859                  * Size the shadow ring 1 larger than the number of credits
860                  * so head == tail can mean empty.
861                  */
862                 sc->sr_size = sci->credits + 1;
863                 sc->sr = kzalloc_node(sizeof(union pio_shadow_ring) *
864                                 sc->sr_size, GFP_KERNEL, numa);
865                 if (!sc->sr) {
866                         sc_free(sc);
867                         return NULL;
868                 }
869         }
870
871         hfi1_cdbg(PIO,
872                   "Send context %u(%u) %s group %u credits %u credit_ctrl 0x%llx threshold %u\n",
873                   sw_index,
874                   hw_context,
875                   sc_type_name(type),
876                   sc->group,
877                   sc->credits,
878                   sc->credit_ctrl,
879                   thresh);
880
881         return sc;
882 }
883
884 /* free a per-NUMA send context structure */
885 void sc_free(struct send_context *sc)
886 {
887         struct hfi1_devdata *dd;
888         unsigned long flags;
889         u32 sw_index;
890         u32 hw_context;
891
892         if (!sc)
893                 return;
894
895         sc->flags |= SCF_IN_FREE;       /* ensure no restarts */
896         dd = sc->dd;
897         if (!list_empty(&sc->piowait))
898                 dd_dev_err(dd, "piowait list not empty!\n");
899         sw_index = sc->sw_index;
900         hw_context = sc->hw_context;
901         sc_disable(sc); /* make sure the HW is disabled */
902         flush_work(&sc->halt_work);
903
904         spin_lock_irqsave(&dd->sc_lock, flags);
905         dd->send_contexts[sw_index].sc = NULL;
906
907         /* clear/disable all registers set in sc_alloc */
908         write_kctxt_csr(dd, hw_context, SC(CTRL), 0);
909         write_kctxt_csr(dd, hw_context, SC(CHECK_ENABLE), 0);
910         write_kctxt_csr(dd, hw_context, SC(ERR_MASK), 0);
911         write_kctxt_csr(dd, hw_context, SC(CHECK_PARTITION_KEY), 0);
912         write_kctxt_csr(dd, hw_context, SC(CHECK_OPCODE), 0);
913         write_kctxt_csr(dd, hw_context, SC(CREDIT_RETURN_ADDR), 0);
914         write_kctxt_csr(dd, hw_context, SC(CREDIT_CTRL), 0);
915
916         /* release the index and context for re-use */
917         sc_hw_free(dd, sw_index, hw_context);
918         spin_unlock_irqrestore(&dd->sc_lock, flags);
919
920         kfree(sc->sr);
921         free_percpu(sc->buffers_allocated);
922         kfree(sc);
923 }
924
925 /* disable the context */
926 void sc_disable(struct send_context *sc)
927 {
928         u64 reg;
929         unsigned long flags;
930         struct pio_buf *pbuf;
931
932         if (!sc)
933                 return;
934
935         /* do all steps, even if already disabled */
936         spin_lock_irqsave(&sc->alloc_lock, flags);
937         reg = read_kctxt_csr(sc->dd, sc->hw_context, SC(CTRL));
938         reg &= ~SC(CTRL_CTXT_ENABLE_SMASK);
939         sc->flags &= ~SCF_ENABLED;
940         sc_wait_for_packet_egress(sc, 1);
941         write_kctxt_csr(sc->dd, sc->hw_context, SC(CTRL), reg);
942         spin_unlock_irqrestore(&sc->alloc_lock, flags);
943
944         /*
945          * Flush any waiters.  Once the context is disabled,
946          * credit return interrupts are stopped (although there
947          * could be one in-process when the context is disabled).
948          * Wait one microsecond for any lingering interrupts, then
949          * proceed with the flush.
950          */
951         udelay(1);
952         spin_lock_irqsave(&sc->release_lock, flags);
953         if (sc->sr) {   /* this context has a shadow ring */
954                 while (sc->sr_tail != sc->sr_head) {
955                         pbuf = &sc->sr[sc->sr_tail].pbuf;
956                         if (pbuf->cb)
957                                 (*pbuf->cb)(pbuf->arg, PRC_SC_DISABLE);
958                         sc->sr_tail++;
959                         if (sc->sr_tail >= sc->sr_size)
960                                 sc->sr_tail = 0;
961                 }
962         }
963         spin_unlock_irqrestore(&sc->release_lock, flags);
964 }
965
966 /* return SendEgressCtxtStatus.PacketOccupancy */
967 #define packet_occupancy(r) \
968         (((r) & SEND_EGRESS_CTXT_STATUS_CTXT_EGRESS_PACKET_OCCUPANCY_SMASK)\
969         >> SEND_EGRESS_CTXT_STATUS_CTXT_EGRESS_PACKET_OCCUPANCY_SHIFT)
970
971 /* is egress halted on the context? */
972 #define egress_halted(r) \
973         ((r) & SEND_EGRESS_CTXT_STATUS_CTXT_EGRESS_HALT_STATUS_SMASK)
974
975 /* wait for packet egress, optionally pause for credit return  */
976 static void sc_wait_for_packet_egress(struct send_context *sc, int pause)
977 {
978         struct hfi1_devdata *dd = sc->dd;
979         u64 reg = 0;
980         u64 reg_prev;
981         u32 loop = 0;
982
983         while (1) {
984                 reg_prev = reg;
985                 reg = read_csr(dd, sc->hw_context * 8 +
986                                SEND_EGRESS_CTXT_STATUS);
987                 /* done if egress is stopped */
988                 if (egress_halted(reg))
989                         break;
990                 reg = packet_occupancy(reg);
991                 if (reg == 0)
992                         break;
993                 /* counter is reset if occupancy count changes */
994                 if (reg != reg_prev)
995                         loop = 0;
996                 if (loop > 50000) {
997                         /* timed out - bounce the link */
998                         dd_dev_err(dd,
999                                    "%s: context %u(%u) timeout waiting for packets to egress, remaining count %u, bouncing link\n",
1000                                    __func__, sc->sw_index,
1001                                    sc->hw_context, (u32)reg);
1002                         queue_work(dd->pport->hfi1_wq,
1003                                    &dd->pport->link_bounce_work);
1004                         break;
1005                 }
1006                 loop++;
1007                 udelay(1);
1008         }
1009
1010         if (pause)
1011                 /* Add additional delay to ensure chip returns all credits */
1012                 pause_for_credit_return(dd);
1013 }
1014
1015 void sc_wait(struct hfi1_devdata *dd)
1016 {
1017         int i;
1018
1019         for (i = 0; i < dd->num_send_contexts; i++) {
1020                 struct send_context *sc = dd->send_contexts[i].sc;
1021
1022                 if (!sc)
1023                         continue;
1024                 sc_wait_for_packet_egress(sc, 0);
1025         }
1026 }
1027
1028 /*
1029  * Restart a context after it has been halted due to error.
1030  *
1031  * If the first step fails - wait for the halt to be asserted, return early.
1032  * Otherwise complain about timeouts but keep going.
1033  *
1034  * It is expected that allocations (enabled flag bit) have been shut off
1035  * already (only applies to kernel contexts).
1036  */
1037 int sc_restart(struct send_context *sc)
1038 {
1039         struct hfi1_devdata *dd = sc->dd;
1040         u64 reg;
1041         u32 loop;
1042         int count;
1043
1044         /* bounce off if not halted, or being free'd */
1045         if (!(sc->flags & SCF_HALTED) || (sc->flags & SCF_IN_FREE))
1046                 return -EINVAL;
1047
1048         dd_dev_info(dd, "restarting send context %u(%u)\n", sc->sw_index,
1049                     sc->hw_context);
1050
1051         /*
1052          * Step 1: Wait for the context to actually halt.
1053          *
1054          * The error interrupt is asynchronous to actually setting halt
1055          * on the context.
1056          */
1057         loop = 0;
1058         while (1) {
1059                 reg = read_kctxt_csr(dd, sc->hw_context, SC(STATUS));
1060                 if (reg & SC(STATUS_CTXT_HALTED_SMASK))
1061                         break;
1062                 if (loop > 100) {
1063                         dd_dev_err(dd, "%s: context %u(%u) not halting, skipping\n",
1064                                    __func__, sc->sw_index, sc->hw_context);
1065                         return -ETIME;
1066                 }
1067                 loop++;
1068                 udelay(1);
1069         }
1070
1071         /*
1072          * Step 2: Ensure no users are still trying to write to PIO.
1073          *
1074          * For kernel contexts, we have already turned off buffer allocation.
1075          * Now wait for the buffer count to go to zero.
1076          *
1077          * For user contexts, the user handling code has cut off write access
1078          * to the context's PIO pages before calling this routine and will
1079          * restore write access after this routine returns.
1080          */
1081         if (sc->type != SC_USER) {
1082                 /* kernel context */
1083                 loop = 0;
1084                 while (1) {
1085                         count = get_buffers_allocated(sc);
1086                         if (count == 0)
1087                                 break;
1088                         if (loop > 100) {
1089                                 dd_dev_err(dd,
1090                                            "%s: context %u(%u) timeout waiting for PIO buffers to zero, remaining %d\n",
1091                                            __func__, sc->sw_index,
1092                                            sc->hw_context, count);
1093                         }
1094                         loop++;
1095                         udelay(1);
1096                 }
1097         }
1098
1099         /*
1100          * Step 3: Wait for all packets to egress.
1101          * This is done while disabling the send context
1102          *
1103          * Step 4: Disable the context
1104          *
1105          * This is a superset of the halt.  After the disable, the
1106          * errors can be cleared.
1107          */
1108         sc_disable(sc);
1109
1110         /*
1111          * Step 5: Enable the context
1112          *
1113          * This enable will clear the halted flag and per-send context
1114          * error flags.
1115          */
1116         return sc_enable(sc);
1117 }
1118
1119 /*
1120  * PIO freeze processing.  To be called after the TXE block is fully frozen.
1121  * Go through all frozen send contexts and disable them.  The contexts are
1122  * already stopped by the freeze.
1123  */
1124 void pio_freeze(struct hfi1_devdata *dd)
1125 {
1126         struct send_context *sc;
1127         int i;
1128
1129         for (i = 0; i < dd->num_send_contexts; i++) {
1130                 sc = dd->send_contexts[i].sc;
1131                 /*
1132                  * Don't disable unallocated, unfrozen, or user send contexts.
1133                  * User send contexts will be disabled when the process
1134                  * calls into the driver to reset its context.
1135                  */
1136                 if (!sc || !(sc->flags & SCF_FROZEN) || sc->type == SC_USER)
1137                         continue;
1138
1139                 /* only need to disable, the context is already stopped */
1140                 sc_disable(sc);
1141         }
1142 }
1143
1144 /*
1145  * Unfreeze PIO for kernel send contexts.  The precondition for calling this
1146  * is that all PIO send contexts have been disabled and the SPC freeze has
1147  * been cleared.  Now perform the last step and re-enable each kernel context.
1148  * User (PSM) processing will occur when PSM calls into the kernel to
1149  * acknowledge the freeze.
1150  */
1151 void pio_kernel_unfreeze(struct hfi1_devdata *dd)
1152 {
1153         struct send_context *sc;
1154         int i;
1155
1156         for (i = 0; i < dd->num_send_contexts; i++) {
1157                 sc = dd->send_contexts[i].sc;
1158                 if (!sc || !(sc->flags & SCF_FROZEN) || sc->type == SC_USER)
1159                         continue;
1160
1161                 sc_enable(sc);  /* will clear the sc frozen flag */
1162         }
1163 }
1164
1165 /*
1166  * Wait for the SendPioInitCtxt.PioInitInProgress bit to clear.
1167  * Returns:
1168  *      -ETIMEDOUT - if we wait too long
1169  *      -EIO       - if there was an error
1170  */
1171 static int pio_init_wait_progress(struct hfi1_devdata *dd)
1172 {
1173         u64 reg;
1174         int max, count = 0;
1175
1176         /* max is the longest possible HW init time / delay */
1177         max = (dd->icode == ICODE_FPGA_EMULATION) ? 120 : 5;
1178         while (1) {
1179                 reg = read_csr(dd, SEND_PIO_INIT_CTXT);
1180                 if (!(reg & SEND_PIO_INIT_CTXT_PIO_INIT_IN_PROGRESS_SMASK))
1181                         break;
1182                 if (count >= max)
1183                         return -ETIMEDOUT;
1184                 udelay(5);
1185                 count++;
1186         }
1187
1188         return reg & SEND_PIO_INIT_CTXT_PIO_INIT_ERR_SMASK ? -EIO : 0;
1189 }
1190
1191 /*
1192  * Reset all of the send contexts to their power-on state.  Used
1193  * only during manual init - no lock against sc_enable needed.
1194  */
1195 void pio_reset_all(struct hfi1_devdata *dd)
1196 {
1197         int ret;
1198
1199         /* make sure the init engine is not busy */
1200         ret = pio_init_wait_progress(dd);
1201         /* ignore any timeout */
1202         if (ret == -EIO) {
1203                 /* clear the error */
1204                 write_csr(dd, SEND_PIO_ERR_CLEAR,
1205                           SEND_PIO_ERR_CLEAR_PIO_INIT_SM_IN_ERR_SMASK);
1206         }
1207
1208         /* reset init all */
1209         write_csr(dd, SEND_PIO_INIT_CTXT,
1210                   SEND_PIO_INIT_CTXT_PIO_ALL_CTXT_INIT_SMASK);
1211         udelay(2);
1212         ret = pio_init_wait_progress(dd);
1213         if (ret < 0) {
1214                 dd_dev_err(dd,
1215                            "PIO send context init %s while initializing all PIO blocks\n",
1216                            ret == -ETIMEDOUT ? "is stuck" : "had an error");
1217         }
1218 }
1219
1220 /* enable the context */
1221 int sc_enable(struct send_context *sc)
1222 {
1223         u64 sc_ctrl, reg, pio;
1224         struct hfi1_devdata *dd;
1225         unsigned long flags;
1226         int ret = 0;
1227
1228         if (!sc)
1229                 return -EINVAL;
1230         dd = sc->dd;
1231
1232         /*
1233          * Obtain the allocator lock to guard against any allocation
1234          * attempts (which should not happen prior to context being
1235          * enabled). On the release/disable side we don't need to
1236          * worry about locking since the releaser will not do anything
1237          * if the context accounting values have not changed.
1238          */
1239         spin_lock_irqsave(&sc->alloc_lock, flags);
1240         sc_ctrl = read_kctxt_csr(dd, sc->hw_context, SC(CTRL));
1241         if ((sc_ctrl & SC(CTRL_CTXT_ENABLE_SMASK)))
1242                 goto unlock; /* already enabled */
1243
1244         /* IMPORTANT: only clear free and fill if transitioning 0 -> 1 */
1245
1246         *sc->hw_free = 0;
1247         sc->free = 0;
1248         sc->alloc_free = 0;
1249         sc->fill = 0;
1250         sc->sr_head = 0;
1251         sc->sr_tail = 0;
1252         sc->flags = 0;
1253         /* the alloc lock insures no fast path allocation */
1254         reset_buffers_allocated(sc);
1255
1256         /*
1257          * Clear all per-context errors.  Some of these will be set when
1258          * we are re-enabling after a context halt.  Now that the context
1259          * is disabled, the halt will not clear until after the PIO init
1260          * engine runs below.
1261          */
1262         reg = read_kctxt_csr(dd, sc->hw_context, SC(ERR_STATUS));
1263         if (reg)
1264                 write_kctxt_csr(dd, sc->hw_context, SC(ERR_CLEAR), reg);
1265
1266         /*
1267          * The HW PIO initialization engine can handle only one init
1268          * request at a time. Serialize access to each device's engine.
1269          */
1270         spin_lock(&dd->sc_init_lock);
1271         /*
1272          * Since access to this code block is serialized and
1273          * each access waits for the initialization to complete
1274          * before releasing the lock, the PIO initialization engine
1275          * should not be in use, so we don't have to wait for the
1276          * InProgress bit to go down.
1277          */
1278         pio = ((sc->hw_context & SEND_PIO_INIT_CTXT_PIO_CTXT_NUM_MASK) <<
1279                SEND_PIO_INIT_CTXT_PIO_CTXT_NUM_SHIFT) |
1280                 SEND_PIO_INIT_CTXT_PIO_SINGLE_CTXT_INIT_SMASK;
1281         write_csr(dd, SEND_PIO_INIT_CTXT, pio);
1282         /*
1283          * Wait until the engine is done.  Give the chip the required time
1284          * so, hopefully, we read the register just once.
1285          */
1286         udelay(2);
1287         ret = pio_init_wait_progress(dd);
1288         spin_unlock(&dd->sc_init_lock);
1289         if (ret) {
1290                 dd_dev_err(dd,
1291                            "sctxt%u(%u): Context not enabled due to init failure %d\n",
1292                            sc->sw_index, sc->hw_context, ret);
1293                 goto unlock;
1294         }
1295
1296         /*
1297          * All is well. Enable the context.
1298          */
1299         sc_ctrl |= SC(CTRL_CTXT_ENABLE_SMASK);
1300         write_kctxt_csr(dd, sc->hw_context, SC(CTRL), sc_ctrl);
1301         /*
1302          * Read SendCtxtCtrl to force the write out and prevent a timing
1303          * hazard where a PIO write may reach the context before the enable.
1304          */
1305         read_kctxt_csr(dd, sc->hw_context, SC(CTRL));
1306         sc->flags |= SCF_ENABLED;
1307
1308 unlock:
1309         spin_unlock_irqrestore(&sc->alloc_lock, flags);
1310
1311         return ret;
1312 }
1313
1314 /* force a credit return on the context */
1315 void sc_return_credits(struct send_context *sc)
1316 {
1317         if (!sc)
1318                 return;
1319
1320         /* a 0->1 transition schedules a credit return */
1321         write_kctxt_csr(sc->dd, sc->hw_context, SC(CREDIT_FORCE),
1322                         SC(CREDIT_FORCE_FORCE_RETURN_SMASK));
1323         /*
1324          * Ensure that the write is flushed and the credit return is
1325          * scheduled. We care more about the 0 -> 1 transition.
1326          */
1327         read_kctxt_csr(sc->dd, sc->hw_context, SC(CREDIT_FORCE));
1328         /* set back to 0 for next time */
1329         write_kctxt_csr(sc->dd, sc->hw_context, SC(CREDIT_FORCE), 0);
1330 }
1331
1332 /* allow all in-flight packets to drain on the context */
1333 void sc_flush(struct send_context *sc)
1334 {
1335         if (!sc)
1336                 return;
1337
1338         sc_wait_for_packet_egress(sc, 1);
1339 }
1340
1341 /* drop all packets on the context, no waiting until they are sent */
1342 void sc_drop(struct send_context *sc)
1343 {
1344         if (!sc)
1345                 return;
1346
1347         dd_dev_info(sc->dd, "%s: context %u(%u) - not implemented\n",
1348                     __func__, sc->sw_index, sc->hw_context);
1349 }
1350
1351 /*
1352  * Start the software reaction to a context halt or SPC freeze:
1353  *      - mark the context as halted or frozen
1354  *      - stop buffer allocations
1355  *
1356  * Called from the error interrupt.  Other work is deferred until
1357  * out of the interrupt.
1358  */
1359 void sc_stop(struct send_context *sc, int flag)
1360 {
1361         unsigned long flags;
1362
1363         /* mark the context */
1364         sc->flags |= flag;
1365
1366         /* stop buffer allocations */
1367         spin_lock_irqsave(&sc->alloc_lock, flags);
1368         sc->flags &= ~SCF_ENABLED;
1369         spin_unlock_irqrestore(&sc->alloc_lock, flags);
1370         wake_up(&sc->halt_wait);
1371 }
1372
1373 #define BLOCK_DWORDS (PIO_BLOCK_SIZE / sizeof(u32))
1374 #define dwords_to_blocks(x) DIV_ROUND_UP(x, BLOCK_DWORDS)
1375
1376 /*
1377  * The send context buffer "allocator".
1378  *
1379  * @sc: the PIO send context we are allocating from
1380  * @len: length of whole packet - including PBC - in dwords
1381  * @cb: optional callback to call when the buffer is finished sending
1382  * @arg: argument for cb
1383  *
1384  * Return a pointer to a PIO buffer if successful, NULL if not enough room.
1385  */
1386 struct pio_buf *sc_buffer_alloc(struct send_context *sc, u32 dw_len,
1387                                 pio_release_cb cb, void *arg)
1388 {
1389         struct pio_buf *pbuf = NULL;
1390         unsigned long flags;
1391         unsigned long avail;
1392         unsigned long blocks = dwords_to_blocks(dw_len);
1393         unsigned long start_fill;
1394         int trycount = 0;
1395         u32 head, next;
1396
1397         spin_lock_irqsave(&sc->alloc_lock, flags);
1398         if (!(sc->flags & SCF_ENABLED)) {
1399                 spin_unlock_irqrestore(&sc->alloc_lock, flags);
1400                 goto done;
1401         }
1402
1403 retry:
1404         avail = (unsigned long)sc->credits - (sc->fill - sc->alloc_free);
1405         if (blocks > avail) {
1406                 /* not enough room */
1407                 if (unlikely(trycount)) { /* already tried to get more room */
1408                         spin_unlock_irqrestore(&sc->alloc_lock, flags);
1409                         goto done;
1410                 }
1411                 /* copy from receiver cache line and recalculate */
1412                 sc->alloc_free = ACCESS_ONCE(sc->free);
1413                 avail =
1414                         (unsigned long)sc->credits -
1415                         (sc->fill - sc->alloc_free);
1416                 if (blocks > avail) {
1417                         /* still no room, actively update */
1418                         spin_unlock_irqrestore(&sc->alloc_lock, flags);
1419                         sc_release_update(sc);
1420                         spin_lock_irqsave(&sc->alloc_lock, flags);
1421                         sc->alloc_free = ACCESS_ONCE(sc->free);
1422                         trycount++;
1423                         goto retry;
1424                 }
1425         }
1426
1427         /* there is enough room */
1428
1429         preempt_disable();
1430         this_cpu_inc(*sc->buffers_allocated);
1431
1432         /* read this once */
1433         head = sc->sr_head;
1434
1435         /* "allocate" the buffer */
1436         start_fill = sc->fill;
1437         sc->fill += blocks;
1438
1439         /*
1440          * Fill the parts that the releaser looks at before moving the head.
1441          * The only necessary piece is the sent_at field.  The credits
1442          * we have just allocated cannot have been returned yet, so the
1443          * cb and arg will not be looked at for a "while".  Put them
1444          * on this side of the memory barrier anyway.
1445          */
1446         pbuf = &sc->sr[head].pbuf;
1447         pbuf->sent_at = sc->fill;
1448         pbuf->cb = cb;
1449         pbuf->arg = arg;
1450         pbuf->sc = sc;  /* could be filled in at sc->sr init time */
1451         /* make sure this is in memory before updating the head */
1452
1453         /* calculate next head index, do not store */
1454         next = head + 1;
1455         if (next >= sc->sr_size)
1456                 next = 0;
1457         /*
1458          * update the head - must be last! - the releaser can look at fields
1459          * in pbuf once we move the head
1460          */
1461         smp_wmb();
1462         sc->sr_head = next;
1463         spin_unlock_irqrestore(&sc->alloc_lock, flags);
1464
1465         /* finish filling in the buffer outside the lock */
1466         pbuf->start = sc->base_addr + ((start_fill % sc->credits)
1467                                                         * PIO_BLOCK_SIZE);
1468         pbuf->size = sc->credits * PIO_BLOCK_SIZE;
1469         pbuf->end = sc->base_addr + pbuf->size;
1470         pbuf->block_count = blocks;
1471         pbuf->qw_written = 0;
1472         pbuf->carry_bytes = 0;
1473         pbuf->carry.val64 = 0;
1474 done:
1475         return pbuf;
1476 }
1477
1478 /*
1479  * There are at least two entities that can turn on credit return
1480  * interrupts and they can overlap.  Avoid problems by implementing
1481  * a count scheme that is enforced by a lock.  The lock is needed because
1482  * the count and CSR write must be paired.
1483  */
1484
1485 /*
1486  * Start credit return interrupts.  This is managed by a count.  If already
1487  * on, just increment the count.
1488  */
1489 void sc_add_credit_return_intr(struct send_context *sc)
1490 {
1491         unsigned long flags;
1492
1493         /* lock must surround both the count change and the CSR update */
1494         spin_lock_irqsave(&sc->credit_ctrl_lock, flags);
1495         if (sc->credit_intr_count == 0) {
1496                 sc->credit_ctrl |= SC(CREDIT_CTRL_CREDIT_INTR_SMASK);
1497                 write_kctxt_csr(sc->dd, sc->hw_context,
1498                                 SC(CREDIT_CTRL), sc->credit_ctrl);
1499         }
1500         sc->credit_intr_count++;
1501         spin_unlock_irqrestore(&sc->credit_ctrl_lock, flags);
1502 }
1503
1504 /*
1505  * Stop credit return interrupts.  This is managed by a count.  Decrement the
1506  * count, if the last user, then turn the credit interrupts off.
1507  */
1508 void sc_del_credit_return_intr(struct send_context *sc)
1509 {
1510         unsigned long flags;
1511
1512         WARN_ON(sc->credit_intr_count == 0);
1513
1514         /* lock must surround both the count change and the CSR update */
1515         spin_lock_irqsave(&sc->credit_ctrl_lock, flags);
1516         sc->credit_intr_count--;
1517         if (sc->credit_intr_count == 0) {
1518                 sc->credit_ctrl &= ~SC(CREDIT_CTRL_CREDIT_INTR_SMASK);
1519                 write_kctxt_csr(sc->dd, sc->hw_context,
1520                                 SC(CREDIT_CTRL), sc->credit_ctrl);
1521         }
1522         spin_unlock_irqrestore(&sc->credit_ctrl_lock, flags);
1523 }
1524
1525 /*
1526  * The caller must be careful when calling this.  All needint calls
1527  * must be paired with !needint.
1528  */
1529 void hfi1_sc_wantpiobuf_intr(struct send_context *sc, u32 needint)
1530 {
1531         if (needint)
1532                 sc_add_credit_return_intr(sc);
1533         else
1534                 sc_del_credit_return_intr(sc);
1535         trace_hfi1_wantpiointr(sc, needint, sc->credit_ctrl);
1536         if (needint) {
1537                 mmiowb();
1538                 sc_return_credits(sc);
1539         }
1540 }
1541
1542 /**
1543  * sc_piobufavail - callback when a PIO buffer is available
1544  * @sc: the send context
1545  *
1546  * This is called from the interrupt handler when a PIO buffer is
1547  * available after hfi1_verbs_send() returned an error that no buffers were
1548  * available. Disable the interrupt if there are no more QPs waiting.
1549  */
1550 static void sc_piobufavail(struct send_context *sc)
1551 {
1552         struct hfi1_devdata *dd = sc->dd;
1553         struct hfi1_ibdev *dev = &dd->verbs_dev;
1554         struct list_head *list;
1555         struct rvt_qp *qps[PIO_WAIT_BATCH_SIZE];
1556         struct rvt_qp *qp;
1557         struct hfi1_qp_priv *priv;
1558         unsigned long flags;
1559         unsigned i, n = 0;
1560
1561         if (dd->send_contexts[sc->sw_index].type != SC_KERNEL &&
1562             dd->send_contexts[sc->sw_index].type != SC_VL15)
1563                 return;
1564         list = &sc->piowait;
1565         /*
1566          * Note: checking that the piowait list is empty and clearing
1567          * the buffer available interrupt needs to be atomic or we
1568          * could end up with QPs on the wait list with the interrupt
1569          * disabled.
1570          */
1571         write_seqlock_irqsave(&dev->iowait_lock, flags);
1572         while (!list_empty(list)) {
1573                 struct iowait *wait;
1574
1575                 if (n == ARRAY_SIZE(qps))
1576                         break;
1577                 wait = list_first_entry(list, struct iowait, list);
1578                 qp = iowait_to_qp(wait);
1579                 priv = qp->priv;
1580                 list_del_init(&priv->s_iowait.list);
1581                 /* refcount held until actual wake up */
1582                 qps[n++] = qp;
1583         }
1584         /*
1585          * If there had been waiters and there are more
1586          * insure that we redo the force to avoid a potential hang.
1587          */
1588         if (n) {
1589                 hfi1_sc_wantpiobuf_intr(sc, 0);
1590                 if (!list_empty(list))
1591                         hfi1_sc_wantpiobuf_intr(sc, 1);
1592         }
1593         write_sequnlock_irqrestore(&dev->iowait_lock, flags);
1594
1595         for (i = 0; i < n; i++)
1596                 hfi1_qp_wakeup(qps[i],
1597                                RVT_S_WAIT_PIO | RVT_S_WAIT_PIO_DRAIN);
1598 }
1599
1600 /* translate a send credit update to a bit code of reasons */
1601 static inline int fill_code(u64 hw_free)
1602 {
1603         int code = 0;
1604
1605         if (hw_free & CR_STATUS_SMASK)
1606                 code |= PRC_STATUS_ERR;
1607         if (hw_free & CR_CREDIT_RETURN_DUE_TO_PBC_SMASK)
1608                 code |= PRC_PBC;
1609         if (hw_free & CR_CREDIT_RETURN_DUE_TO_THRESHOLD_SMASK)
1610                 code |= PRC_THRESHOLD;
1611         if (hw_free & CR_CREDIT_RETURN_DUE_TO_ERR_SMASK)
1612                 code |= PRC_FILL_ERR;
1613         if (hw_free & CR_CREDIT_RETURN_DUE_TO_FORCE_SMASK)
1614                 code |= PRC_SC_DISABLE;
1615         return code;
1616 }
1617
1618 /* use the jiffies compare to get the wrap right */
1619 #define sent_before(a, b) time_before(a, b)     /* a < b */
1620
1621 /*
1622  * The send context buffer "releaser".
1623  */
1624 void sc_release_update(struct send_context *sc)
1625 {
1626         struct pio_buf *pbuf;
1627         u64 hw_free;
1628         u32 head, tail;
1629         unsigned long old_free;
1630         unsigned long free;
1631         unsigned long extra;
1632         unsigned long flags;
1633         int code;
1634
1635         if (!sc)
1636                 return;
1637
1638         spin_lock_irqsave(&sc->release_lock, flags);
1639         /* update free */
1640         hw_free = le64_to_cpu(*sc->hw_free);            /* volatile read */
1641         old_free = sc->free;
1642         extra = (((hw_free & CR_COUNTER_SMASK) >> CR_COUNTER_SHIFT)
1643                         - (old_free & CR_COUNTER_MASK))
1644                                 & CR_COUNTER_MASK;
1645         free = old_free + extra;
1646         trace_hfi1_piofree(sc, extra);
1647
1648         /* call sent buffer callbacks */
1649         code = -1;                              /* code not yet set */
1650         head = ACCESS_ONCE(sc->sr_head);        /* snapshot the head */
1651         tail = sc->sr_tail;
1652         while (head != tail) {
1653                 pbuf = &sc->sr[tail].pbuf;
1654
1655                 if (sent_before(free, pbuf->sent_at)) {
1656                         /* not sent yet */
1657                         break;
1658                 }
1659                 if (pbuf->cb) {
1660                         if (code < 0) /* fill in code on first user */
1661                                 code = fill_code(hw_free);
1662                         (*pbuf->cb)(pbuf->arg, code);
1663                 }
1664
1665                 tail++;
1666                 if (tail >= sc->sr_size)
1667                         tail = 0;
1668         }
1669         sc->sr_tail = tail;
1670         /* make sure tail is updated before free */
1671         smp_wmb();
1672         sc->free = free;
1673         spin_unlock_irqrestore(&sc->release_lock, flags);
1674         sc_piobufavail(sc);
1675 }
1676
1677 /*
1678  * Send context group releaser.  Argument is the send context that caused
1679  * the interrupt.  Called from the send context interrupt handler.
1680  *
1681  * Call release on all contexts in the group.
1682  *
1683  * This routine takes the sc_lock without an irqsave because it is only
1684  * called from an interrupt handler.  Adjust if that changes.
1685  */
1686 void sc_group_release_update(struct hfi1_devdata *dd, u32 hw_context)
1687 {
1688         struct send_context *sc;
1689         u32 sw_index;
1690         u32 gc, gc_end;
1691
1692         spin_lock(&dd->sc_lock);
1693         sw_index = dd->hw_to_sw[hw_context];
1694         if (unlikely(sw_index >= dd->num_send_contexts)) {
1695                 dd_dev_err(dd, "%s: invalid hw (%u) to sw (%u) mapping\n",
1696                            __func__, hw_context, sw_index);
1697                 goto done;
1698         }
1699         sc = dd->send_contexts[sw_index].sc;
1700         if (unlikely(!sc))
1701                 goto done;
1702
1703         gc = group_context(hw_context, sc->group);
1704         gc_end = gc + group_size(sc->group);
1705         for (; gc < gc_end; gc++) {
1706                 sw_index = dd->hw_to_sw[gc];
1707                 if (unlikely(sw_index >= dd->num_send_contexts)) {
1708                         dd_dev_err(dd,
1709                                    "%s: invalid hw (%u) to sw (%u) mapping\n",
1710                                    __func__, hw_context, sw_index);
1711                         continue;
1712                 }
1713                 sc_release_update(dd->send_contexts[sw_index].sc);
1714         }
1715 done:
1716         spin_unlock(&dd->sc_lock);
1717 }
1718
1719 /*
1720  * pio_select_send_context_vl() - select send context
1721  * @dd: devdata
1722  * @selector: a spreading factor
1723  * @vl: this vl
1724  *
1725  * This function returns a send context based on the selector and a vl.
1726  * The mapping fields are protected by RCU
1727  */
1728 struct send_context *pio_select_send_context_vl(struct hfi1_devdata *dd,
1729                                                 u32 selector, u8 vl)
1730 {
1731         struct pio_vl_map *m;
1732         struct pio_map_elem *e;
1733         struct send_context *rval;
1734
1735         /*
1736          * NOTE This should only happen if SC->VL changed after the initial
1737          * checks on the QP/AH
1738          * Default will return VL0's send context below
1739          */
1740         if (unlikely(vl >= num_vls)) {
1741                 rval = NULL;
1742                 goto done;
1743         }
1744
1745         rcu_read_lock();
1746         m = rcu_dereference(dd->pio_map);
1747         if (unlikely(!m)) {
1748                 rcu_read_unlock();
1749                 return dd->vld[0].sc;
1750         }
1751         e = m->map[vl & m->mask];
1752         rval = e->ksc[selector & e->mask];
1753         rcu_read_unlock();
1754
1755 done:
1756         rval = !rval ? dd->vld[0].sc : rval;
1757         return rval;
1758 }
1759
1760 /*
1761  * pio_select_send_context_sc() - select send context
1762  * @dd: devdata
1763  * @selector: a spreading factor
1764  * @sc5: the 5 bit sc
1765  *
1766  * This function returns an send context based on the selector and an sc
1767  */
1768 struct send_context *pio_select_send_context_sc(struct hfi1_devdata *dd,
1769                                                 u32 selector, u8 sc5)
1770 {
1771         u8 vl = sc_to_vlt(dd, sc5);
1772
1773         return pio_select_send_context_vl(dd, selector, vl);
1774 }
1775
1776 /*
1777  * Free the indicated map struct
1778  */
1779 static void pio_map_free(struct pio_vl_map *m)
1780 {
1781         int i;
1782
1783         for (i = 0; m && i < m->actual_vls; i++)
1784                 kfree(m->map[i]);
1785         kfree(m);
1786 }
1787
1788 /*
1789  * Handle RCU callback
1790  */
1791 static void pio_map_rcu_callback(struct rcu_head *list)
1792 {
1793         struct pio_vl_map *m = container_of(list, struct pio_vl_map, list);
1794
1795         pio_map_free(m);
1796 }
1797
1798 /*
1799  * Set credit return threshold for the kernel send context
1800  */
1801 static void set_threshold(struct hfi1_devdata *dd, int scontext, int i)
1802 {
1803         u32 thres;
1804
1805         thres = min(sc_percent_to_threshold(dd->kernel_send_context[scontext],
1806                                             50),
1807                     sc_mtu_to_threshold(dd->kernel_send_context[scontext],
1808                                         dd->vld[i].mtu,
1809                                         dd->rcd[0]->rcvhdrqentsize));
1810         sc_set_cr_threshold(dd->kernel_send_context[scontext], thres);
1811 }
1812
1813 /*
1814  * pio_map_init - called when #vls change
1815  * @dd: hfi1_devdata
1816  * @port: port number
1817  * @num_vls: number of vls
1818  * @vl_scontexts: per vl send context mapping (optional)
1819  *
1820  * This routine changes the mapping based on the number of vls.
1821  *
1822  * vl_scontexts is used to specify a non-uniform vl/send context
1823  * loading. NULL implies auto computing the loading and giving each
1824  * VL an uniform distribution of send contexts per VL.
1825  *
1826  * The auto algorithm computers the sc_per_vl and the number of extra
1827  * send contexts. Any extra send contexts are added from the last VL
1828  * on down
1829  *
1830  * rcu locking is used here to control access to the mapping fields.
1831  *
1832  * If either the num_vls or num_send_contexts are non-power of 2, the
1833  * array sizes in the struct pio_vl_map and the struct pio_map_elem are
1834  * rounded up to the next highest power of 2 and the first entry is
1835  * reused in a round robin fashion.
1836  *
1837  * If an error occurs the map change is not done and the mapping is not
1838  * chaged.
1839  *
1840  */
1841 int pio_map_init(struct hfi1_devdata *dd, u8 port, u8 num_vls, u8 *vl_scontexts)
1842 {
1843         int i, j;
1844         int extra, sc_per_vl;
1845         int scontext = 1;
1846         int num_kernel_send_contexts = 0;
1847         u8 lvl_scontexts[OPA_MAX_VLS];
1848         struct pio_vl_map *oldmap, *newmap;
1849
1850         if (!vl_scontexts) {
1851                 for (i = 0; i < dd->num_send_contexts; i++)
1852                         if (dd->send_contexts[i].type == SC_KERNEL)
1853                                 num_kernel_send_contexts++;
1854                 /* truncate divide */
1855                 sc_per_vl = num_kernel_send_contexts / num_vls;
1856                 /* extras */
1857                 extra = num_kernel_send_contexts % num_vls;
1858                 vl_scontexts = lvl_scontexts;
1859                 /* add extras from last vl down */
1860                 for (i = num_vls - 1; i >= 0; i--, extra--)
1861                         vl_scontexts[i] = sc_per_vl + (extra > 0 ? 1 : 0);
1862         }
1863         /* build new map */
1864         newmap = kzalloc(sizeof(*newmap) +
1865                          roundup_pow_of_two(num_vls) *
1866                          sizeof(struct pio_map_elem *),
1867                          GFP_KERNEL);
1868         if (!newmap)
1869                 goto bail;
1870         newmap->actual_vls = num_vls;
1871         newmap->vls = roundup_pow_of_two(num_vls);
1872         newmap->mask = (1 << ilog2(newmap->vls)) - 1;
1873         for (i = 0; i < newmap->vls; i++) {
1874                 /* save for wrap around */
1875                 int first_scontext = scontext;
1876
1877                 if (i < newmap->actual_vls) {
1878                         int sz = roundup_pow_of_two(vl_scontexts[i]);
1879
1880                         /* only allocate once */
1881                         newmap->map[i] = kzalloc(sizeof(*newmap->map[i]) +
1882                                                  sz * sizeof(struct
1883                                                              send_context *),
1884                                                  GFP_KERNEL);
1885                         if (!newmap->map[i])
1886                                 goto bail;
1887                         newmap->map[i]->mask = (1 << ilog2(sz)) - 1;
1888                         /*
1889                          * assign send contexts and
1890                          * adjust credit return threshold
1891                          */
1892                         for (j = 0; j < sz; j++) {
1893                                 if (dd->kernel_send_context[scontext]) {
1894                                         newmap->map[i]->ksc[j] =
1895                                         dd->kernel_send_context[scontext];
1896                                         set_threshold(dd, scontext, i);
1897                                 }
1898                                 if (++scontext >= first_scontext +
1899                                                   vl_scontexts[i])
1900                                         /* wrap back to first send context */
1901                                         scontext = first_scontext;
1902                         }
1903                 } else {
1904                         /* just re-use entry without allocating */
1905                         newmap->map[i] = newmap->map[i % num_vls];
1906                 }
1907                 scontext = first_scontext + vl_scontexts[i];
1908         }
1909         /* newmap in hand, save old map */
1910         spin_lock_irq(&dd->pio_map_lock);
1911         oldmap = rcu_dereference_protected(dd->pio_map,
1912                                            lockdep_is_held(&dd->pio_map_lock));
1913
1914         /* publish newmap */
1915         rcu_assign_pointer(dd->pio_map, newmap);
1916
1917         spin_unlock_irq(&dd->pio_map_lock);
1918         /* success, free any old map after grace period */
1919         if (oldmap)
1920                 call_rcu(&oldmap->list, pio_map_rcu_callback);
1921         return 0;
1922 bail:
1923         /* free any partial allocation */
1924         pio_map_free(newmap);
1925         return -ENOMEM;
1926 }
1927
1928 void free_pio_map(struct hfi1_devdata *dd)
1929 {
1930         /* Free PIO map if allocated */
1931         if (rcu_access_pointer(dd->pio_map)) {
1932                 spin_lock_irq(&dd->pio_map_lock);
1933                 pio_map_free(rcu_access_pointer(dd->pio_map));
1934                 RCU_INIT_POINTER(dd->pio_map, NULL);
1935                 spin_unlock_irq(&dd->pio_map_lock);
1936                 synchronize_rcu();
1937         }
1938         kfree(dd->kernel_send_context);
1939         dd->kernel_send_context = NULL;
1940 }
1941
1942 int init_pervl_scs(struct hfi1_devdata *dd)
1943 {
1944         int i;
1945         u64 mask, all_vl_mask = (u64)0x80ff; /* VLs 0-7, 15 */
1946         u64 data_vls_mask = (u64)0x00ff; /* VLs 0-7 */
1947         u32 ctxt;
1948         struct hfi1_pportdata *ppd = dd->pport;
1949
1950         dd->vld[15].sc = sc_alloc(dd, SC_VL15,
1951                                   dd->rcd[0]->rcvhdrqentsize, dd->node);
1952         if (!dd->vld[15].sc)
1953                 return -ENOMEM;
1954
1955         hfi1_init_ctxt(dd->vld[15].sc);
1956         dd->vld[15].mtu = enum_to_mtu(OPA_MTU_2048);
1957
1958         dd->kernel_send_context = kzalloc_node(dd->num_send_contexts *
1959                                         sizeof(struct send_context *),
1960                                         GFP_KERNEL, dd->node);
1961         if (!dd->kernel_send_context)
1962                 goto freesc15;
1963
1964         dd->kernel_send_context[0] = dd->vld[15].sc;
1965
1966         for (i = 0; i < num_vls; i++) {
1967                 /*
1968                  * Since this function does not deal with a specific
1969                  * receive context but we need the RcvHdrQ entry size,
1970                  * use the size from rcd[0]. It is guaranteed to be
1971                  * valid at this point and will remain the same for all
1972                  * receive contexts.
1973                  */
1974                 dd->vld[i].sc = sc_alloc(dd, SC_KERNEL,
1975                                          dd->rcd[0]->rcvhdrqentsize, dd->node);
1976                 if (!dd->vld[i].sc)
1977                         goto nomem;
1978                 dd->kernel_send_context[i + 1] = dd->vld[i].sc;
1979                 hfi1_init_ctxt(dd->vld[i].sc);
1980                 /* non VL15 start with the max MTU */
1981                 dd->vld[i].mtu = hfi1_max_mtu;
1982         }
1983         for (i = num_vls; i < INIT_SC_PER_VL * num_vls; i++) {
1984                 dd->kernel_send_context[i + 1] =
1985                 sc_alloc(dd, SC_KERNEL, dd->rcd[0]->rcvhdrqentsize, dd->node);
1986                 if (!dd->kernel_send_context[i + 1])
1987                         goto nomem;
1988                 hfi1_init_ctxt(dd->kernel_send_context[i + 1]);
1989         }
1990
1991         sc_enable(dd->vld[15].sc);
1992         ctxt = dd->vld[15].sc->hw_context;
1993         mask = all_vl_mask & ~(1LL << 15);
1994         write_kctxt_csr(dd, ctxt, SC(CHECK_VL), mask);
1995         dd_dev_info(dd,
1996                     "Using send context %u(%u) for VL15\n",
1997                     dd->vld[15].sc->sw_index, ctxt);
1998
1999         for (i = 0; i < num_vls; i++) {
2000                 sc_enable(dd->vld[i].sc);
2001                 ctxt = dd->vld[i].sc->hw_context;
2002                 mask = all_vl_mask & ~(data_vls_mask);
2003                 write_kctxt_csr(dd, ctxt, SC(CHECK_VL), mask);
2004         }
2005         for (i = num_vls; i < INIT_SC_PER_VL * num_vls; i++) {
2006                 sc_enable(dd->kernel_send_context[i + 1]);
2007                 ctxt = dd->kernel_send_context[i + 1]->hw_context;
2008                 mask = all_vl_mask & ~(data_vls_mask);
2009                 write_kctxt_csr(dd, ctxt, SC(CHECK_VL), mask);
2010         }
2011
2012         if (pio_map_init(dd, ppd->port - 1, num_vls, NULL))
2013                 goto nomem;
2014         return 0;
2015
2016 nomem:
2017         for (i = 0; i < num_vls; i++) {
2018                 sc_free(dd->vld[i].sc);
2019                 dd->vld[i].sc = NULL;
2020         }
2021
2022         for (i = num_vls; i < INIT_SC_PER_VL * num_vls; i++)
2023                 sc_free(dd->kernel_send_context[i + 1]);
2024
2025         kfree(dd->kernel_send_context);
2026         dd->kernel_send_context = NULL;
2027
2028 freesc15:
2029         sc_free(dd->vld[15].sc);
2030         return -ENOMEM;
2031 }
2032
2033 int init_credit_return(struct hfi1_devdata *dd)
2034 {
2035         int ret;
2036         int num_numa;
2037         int i;
2038
2039         num_numa = num_online_nodes();
2040         /* enforce the expectation that the numas are compact */
2041         for (i = 0; i < num_numa; i++) {
2042                 if (!node_online(i)) {
2043                         dd_dev_err(dd, "NUMA nodes are not compact\n");
2044                         ret = -EINVAL;
2045                         goto done;
2046                 }
2047         }
2048
2049         dd->cr_base = kcalloc(
2050                 num_numa,
2051                 sizeof(struct credit_return_base),
2052                 GFP_KERNEL);
2053         if (!dd->cr_base) {
2054                 dd_dev_err(dd, "Unable to allocate credit return base\n");
2055                 ret = -ENOMEM;
2056                 goto done;
2057         }
2058         for (i = 0; i < num_numa; i++) {
2059                 int bytes = TXE_NUM_CONTEXTS * sizeof(struct credit_return);
2060
2061                 set_dev_node(&dd->pcidev->dev, i);
2062                 dd->cr_base[i].va = dma_zalloc_coherent(
2063                                         &dd->pcidev->dev,
2064                                         bytes,
2065                                         &dd->cr_base[i].dma,
2066                                         GFP_KERNEL);
2067                 if (!dd->cr_base[i].va) {
2068                         set_dev_node(&dd->pcidev->dev, dd->node);
2069                         dd_dev_err(dd,
2070                                    "Unable to allocate credit return DMA range for NUMA %d\n",
2071                                    i);
2072                         ret = -ENOMEM;
2073                         goto done;
2074                 }
2075         }
2076         set_dev_node(&dd->pcidev->dev, dd->node);
2077
2078         ret = 0;
2079 done:
2080         return ret;
2081 }
2082
2083 void free_credit_return(struct hfi1_devdata *dd)
2084 {
2085         int num_numa;
2086         int i;
2087
2088         if (!dd->cr_base)
2089                 return;
2090
2091         num_numa = num_online_nodes();
2092         for (i = 0; i < num_numa; i++) {
2093                 if (dd->cr_base[i].va) {
2094                         dma_free_coherent(&dd->pcidev->dev,
2095                                           TXE_NUM_CONTEXTS *
2096                                           sizeof(struct credit_return),
2097                                           dd->cr_base[i].va,
2098                                           dd->cr_base[i].dma);
2099                 }
2100         }
2101         kfree(dd->cr_base);
2102         dd->cr_base = NULL;
2103 }