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