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