GNU Linux-libre 4.9.287-gnu1
[releases.git] / drivers / infiniband / hw / hfi1 / sdma.c
1 /*
2  * Copyright(c) 2015, 2016 Intel Corporation.
3  *
4  * This file is provided under a dual BSD/GPLv2 license.  When using or
5  * redistributing this file, you may do so under either license.
6  *
7  * GPL LICENSE SUMMARY
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * BSD LICENSE
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  *  - Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  *  - Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *  - Neither the name of Intel Corporation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
37  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
38  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
41  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
42  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47
48 #include <linux/spinlock.h>
49 #include <linux/seqlock.h>
50 #include <linux/netdevice.h>
51 #include <linux/moduleparam.h>
52 #include <linux/bitops.h>
53 #include <linux/timer.h>
54 #include <linux/vmalloc.h>
55 #include <linux/highmem.h>
56
57 #include "hfi.h"
58 #include "common.h"
59 #include "qp.h"
60 #include "sdma.h"
61 #include "iowait.h"
62 #include "trace.h"
63
64 /* must be a power of 2 >= 64 <= 32768 */
65 #define SDMA_DESCQ_CNT 2048
66 #define SDMA_DESC_INTR 64
67 #define INVALID_TAIL 0xffff
68
69 static uint sdma_descq_cnt = SDMA_DESCQ_CNT;
70 module_param(sdma_descq_cnt, uint, S_IRUGO);
71 MODULE_PARM_DESC(sdma_descq_cnt, "Number of SDMA descq entries");
72
73 static uint sdma_idle_cnt = 250;
74 module_param(sdma_idle_cnt, uint, S_IRUGO);
75 MODULE_PARM_DESC(sdma_idle_cnt, "sdma interrupt idle delay (ns,default 250)");
76
77 uint mod_num_sdma;
78 module_param_named(num_sdma, mod_num_sdma, uint, S_IRUGO);
79 MODULE_PARM_DESC(num_sdma, "Set max number SDMA engines to use");
80
81 static uint sdma_desct_intr = SDMA_DESC_INTR;
82 module_param_named(desct_intr, sdma_desct_intr, uint, S_IRUGO | S_IWUSR);
83 MODULE_PARM_DESC(desct_intr, "Number of SDMA descriptor before interrupt");
84
85 #define SDMA_WAIT_BATCH_SIZE 20
86 /* max wait time for a SDMA engine to indicate it has halted */
87 #define SDMA_ERR_HALT_TIMEOUT 10 /* ms */
88 /* all SDMA engine errors that cause a halt */
89
90 #define SD(name) SEND_DMA_##name
91 #define ALL_SDMA_ENG_HALT_ERRS \
92         (SD(ENG_ERR_STATUS_SDMA_WRONG_DW_ERR_SMASK) \
93         | SD(ENG_ERR_STATUS_SDMA_GEN_MISMATCH_ERR_SMASK) \
94         | SD(ENG_ERR_STATUS_SDMA_TOO_LONG_ERR_SMASK) \
95         | SD(ENG_ERR_STATUS_SDMA_TAIL_OUT_OF_BOUNDS_ERR_SMASK) \
96         | SD(ENG_ERR_STATUS_SDMA_FIRST_DESC_ERR_SMASK) \
97         | SD(ENG_ERR_STATUS_SDMA_MEM_READ_ERR_SMASK) \
98         | SD(ENG_ERR_STATUS_SDMA_HALT_ERR_SMASK) \
99         | SD(ENG_ERR_STATUS_SDMA_LENGTH_MISMATCH_ERR_SMASK) \
100         | SD(ENG_ERR_STATUS_SDMA_PACKET_DESC_OVERFLOW_ERR_SMASK) \
101         | SD(ENG_ERR_STATUS_SDMA_HEADER_SELECT_ERR_SMASK) \
102         | SD(ENG_ERR_STATUS_SDMA_HEADER_ADDRESS_ERR_SMASK) \
103         | SD(ENG_ERR_STATUS_SDMA_HEADER_LENGTH_ERR_SMASK) \
104         | SD(ENG_ERR_STATUS_SDMA_TIMEOUT_ERR_SMASK) \
105         | SD(ENG_ERR_STATUS_SDMA_DESC_TABLE_UNC_ERR_SMASK) \
106         | SD(ENG_ERR_STATUS_SDMA_ASSEMBLY_UNC_ERR_SMASK) \
107         | SD(ENG_ERR_STATUS_SDMA_PACKET_TRACKING_UNC_ERR_SMASK) \
108         | SD(ENG_ERR_STATUS_SDMA_HEADER_STORAGE_UNC_ERR_SMASK) \
109         | SD(ENG_ERR_STATUS_SDMA_HEADER_REQUEST_FIFO_UNC_ERR_SMASK))
110
111 /* sdma_sendctrl operations */
112 #define SDMA_SENDCTRL_OP_ENABLE    BIT(0)
113 #define SDMA_SENDCTRL_OP_INTENABLE BIT(1)
114 #define SDMA_SENDCTRL_OP_HALT      BIT(2)
115 #define SDMA_SENDCTRL_OP_CLEANUP   BIT(3)
116
117 /* handle long defines */
118 #define SDMA_EGRESS_PACKET_OCCUPANCY_SMASK \
119 SEND_EGRESS_SEND_DMA_STATUS_SDMA_EGRESS_PACKET_OCCUPANCY_SMASK
120 #define SDMA_EGRESS_PACKET_OCCUPANCY_SHIFT \
121 SEND_EGRESS_SEND_DMA_STATUS_SDMA_EGRESS_PACKET_OCCUPANCY_SHIFT
122
123 static const char * const sdma_state_names[] = {
124         [sdma_state_s00_hw_down]                = "s00_HwDown",
125         [sdma_state_s10_hw_start_up_halt_wait]  = "s10_HwStartUpHaltWait",
126         [sdma_state_s15_hw_start_up_clean_wait] = "s15_HwStartUpCleanWait",
127         [sdma_state_s20_idle]                   = "s20_Idle",
128         [sdma_state_s30_sw_clean_up_wait]       = "s30_SwCleanUpWait",
129         [sdma_state_s40_hw_clean_up_wait]       = "s40_HwCleanUpWait",
130         [sdma_state_s50_hw_halt_wait]           = "s50_HwHaltWait",
131         [sdma_state_s60_idle_halt_wait]         = "s60_IdleHaltWait",
132         [sdma_state_s80_hw_freeze]              = "s80_HwFreeze",
133         [sdma_state_s82_freeze_sw_clean]        = "s82_FreezeSwClean",
134         [sdma_state_s99_running]                = "s99_Running",
135 };
136
137 #ifdef CONFIG_SDMA_VERBOSITY
138 static const char * const sdma_event_names[] = {
139         [sdma_event_e00_go_hw_down]   = "e00_GoHwDown",
140         [sdma_event_e10_go_hw_start]  = "e10_GoHwStart",
141         [sdma_event_e15_hw_halt_done] = "e15_HwHaltDone",
142         [sdma_event_e25_hw_clean_up_done] = "e25_HwCleanUpDone",
143         [sdma_event_e30_go_running]   = "e30_GoRunning",
144         [sdma_event_e40_sw_cleaned]   = "e40_SwCleaned",
145         [sdma_event_e50_hw_cleaned]   = "e50_HwCleaned",
146         [sdma_event_e60_hw_halted]    = "e60_HwHalted",
147         [sdma_event_e70_go_idle]      = "e70_GoIdle",
148         [sdma_event_e80_hw_freeze]    = "e80_HwFreeze",
149         [sdma_event_e81_hw_frozen]    = "e81_HwFrozen",
150         [sdma_event_e82_hw_unfreeze]  = "e82_HwUnfreeze",
151         [sdma_event_e85_link_down]    = "e85_LinkDown",
152         [sdma_event_e90_sw_halted]    = "e90_SwHalted",
153 };
154 #endif
155
156 static const struct sdma_set_state_action sdma_action_table[] = {
157         [sdma_state_s00_hw_down] = {
158                 .go_s99_running_tofalse = 1,
159                 .op_enable = 0,
160                 .op_intenable = 0,
161                 .op_halt = 0,
162                 .op_cleanup = 0,
163         },
164         [sdma_state_s10_hw_start_up_halt_wait] = {
165                 .op_enable = 0,
166                 .op_intenable = 0,
167                 .op_halt = 1,
168                 .op_cleanup = 0,
169         },
170         [sdma_state_s15_hw_start_up_clean_wait] = {
171                 .op_enable = 0,
172                 .op_intenable = 1,
173                 .op_halt = 0,
174                 .op_cleanup = 1,
175         },
176         [sdma_state_s20_idle] = {
177                 .op_enable = 0,
178                 .op_intenable = 1,
179                 .op_halt = 0,
180                 .op_cleanup = 0,
181         },
182         [sdma_state_s30_sw_clean_up_wait] = {
183                 .op_enable = 0,
184                 .op_intenable = 0,
185                 .op_halt = 0,
186                 .op_cleanup = 0,
187         },
188         [sdma_state_s40_hw_clean_up_wait] = {
189                 .op_enable = 0,
190                 .op_intenable = 0,
191                 .op_halt = 0,
192                 .op_cleanup = 1,
193         },
194         [sdma_state_s50_hw_halt_wait] = {
195                 .op_enable = 0,
196                 .op_intenable = 0,
197                 .op_halt = 0,
198                 .op_cleanup = 0,
199         },
200         [sdma_state_s60_idle_halt_wait] = {
201                 .go_s99_running_tofalse = 1,
202                 .op_enable = 0,
203                 .op_intenable = 0,
204                 .op_halt = 1,
205                 .op_cleanup = 0,
206         },
207         [sdma_state_s80_hw_freeze] = {
208                 .op_enable = 0,
209                 .op_intenable = 0,
210                 .op_halt = 0,
211                 .op_cleanup = 0,
212         },
213         [sdma_state_s82_freeze_sw_clean] = {
214                 .op_enable = 0,
215                 .op_intenable = 0,
216                 .op_halt = 0,
217                 .op_cleanup = 0,
218         },
219         [sdma_state_s99_running] = {
220                 .op_enable = 1,
221                 .op_intenable = 1,
222                 .op_halt = 0,
223                 .op_cleanup = 0,
224                 .go_s99_running_totrue = 1,
225         },
226 };
227
228 #define SDMA_TAIL_UPDATE_THRESH 0x1F
229
230 /* declare all statics here rather than keep sorting */
231 static void sdma_complete(struct kref *);
232 static void sdma_finalput(struct sdma_state *);
233 static void sdma_get(struct sdma_state *);
234 static void sdma_hw_clean_up_task(unsigned long);
235 static void sdma_put(struct sdma_state *);
236 static void sdma_set_state(struct sdma_engine *, enum sdma_states);
237 static void sdma_start_hw_clean_up(struct sdma_engine *);
238 static void sdma_sw_clean_up_task(unsigned long);
239 static void sdma_sendctrl(struct sdma_engine *, unsigned);
240 static void init_sdma_regs(struct sdma_engine *, u32, uint);
241 static void sdma_process_event(
242         struct sdma_engine *sde,
243         enum sdma_events event);
244 static void __sdma_process_event(
245         struct sdma_engine *sde,
246         enum sdma_events event);
247 static void dump_sdma_state(struct sdma_engine *sde);
248 static void sdma_make_progress(struct sdma_engine *sde, u64 status);
249 static void sdma_desc_avail(struct sdma_engine *sde, unsigned avail);
250 static void sdma_flush_descq(struct sdma_engine *sde);
251
252 /**
253  * sdma_state_name() - return state string from enum
254  * @state: state
255  */
256 static const char *sdma_state_name(enum sdma_states state)
257 {
258         return sdma_state_names[state];
259 }
260
261 static void sdma_get(struct sdma_state *ss)
262 {
263         kref_get(&ss->kref);
264 }
265
266 static void sdma_complete(struct kref *kref)
267 {
268         struct sdma_state *ss =
269                 container_of(kref, struct sdma_state, kref);
270
271         complete(&ss->comp);
272 }
273
274 static void sdma_put(struct sdma_state *ss)
275 {
276         kref_put(&ss->kref, sdma_complete);
277 }
278
279 static void sdma_finalput(struct sdma_state *ss)
280 {
281         sdma_put(ss);
282         wait_for_completion(&ss->comp);
283 }
284
285 static inline void write_sde_csr(
286         struct sdma_engine *sde,
287         u32 offset0,
288         u64 value)
289 {
290         write_kctxt_csr(sde->dd, sde->this_idx, offset0, value);
291 }
292
293 static inline u64 read_sde_csr(
294         struct sdma_engine *sde,
295         u32 offset0)
296 {
297         return read_kctxt_csr(sde->dd, sde->this_idx, offset0);
298 }
299
300 /*
301  * sdma_wait_for_packet_egress() - wait for the VL FIFO occupancy for
302  * sdma engine 'sde' to drop to 0.
303  */
304 static void sdma_wait_for_packet_egress(struct sdma_engine *sde,
305                                         int pause)
306 {
307         u64 off = 8 * sde->this_idx;
308         struct hfi1_devdata *dd = sde->dd;
309         int lcnt = 0;
310         u64 reg_prev;
311         u64 reg = 0;
312
313         while (1) {
314                 reg_prev = reg;
315                 reg = read_csr(dd, off + SEND_EGRESS_SEND_DMA_STATUS);
316
317                 reg &= SDMA_EGRESS_PACKET_OCCUPANCY_SMASK;
318                 reg >>= SDMA_EGRESS_PACKET_OCCUPANCY_SHIFT;
319                 if (reg == 0)
320                         break;
321                 /* counter is reest if accupancy count changes */
322                 if (reg != reg_prev)
323                         lcnt = 0;
324                 if (lcnt++ > 500) {
325                         /* timed out - bounce the link */
326                         dd_dev_err(dd, "%s: engine %u timeout waiting for packets to egress, remaining count %u, bouncing link\n",
327                                    __func__, sde->this_idx, (u32)reg);
328                         queue_work(dd->pport->hfi1_wq,
329                                    &dd->pport->link_bounce_work);
330                         break;
331                 }
332                 udelay(1);
333         }
334 }
335
336 /*
337  * sdma_wait() - wait for packet egress to complete for all SDMA engines,
338  * and pause for credit return.
339  */
340 void sdma_wait(struct hfi1_devdata *dd)
341 {
342         int i;
343
344         for (i = 0; i < dd->num_sdma; i++) {
345                 struct sdma_engine *sde = &dd->per_sdma[i];
346
347                 sdma_wait_for_packet_egress(sde, 0);
348         }
349 }
350
351 static inline void sdma_set_desc_cnt(struct sdma_engine *sde, unsigned cnt)
352 {
353         u64 reg;
354
355         if (!(sde->dd->flags & HFI1_HAS_SDMA_TIMEOUT))
356                 return;
357         reg = cnt;
358         reg &= SD(DESC_CNT_CNT_MASK);
359         reg <<= SD(DESC_CNT_CNT_SHIFT);
360         write_sde_csr(sde, SD(DESC_CNT), reg);
361 }
362
363 static inline void complete_tx(struct sdma_engine *sde,
364                                struct sdma_txreq *tx,
365                                int res)
366 {
367         /* protect against complete modifying */
368         struct iowait *wait = tx->wait;
369         callback_t complete = tx->complete;
370
371 #ifdef CONFIG_HFI1_DEBUG_SDMA_ORDER
372         trace_hfi1_sdma_out_sn(sde, tx->sn);
373         if (WARN_ON_ONCE(sde->head_sn != tx->sn))
374                 dd_dev_err(sde->dd, "expected %llu got %llu\n",
375                            sde->head_sn, tx->sn);
376         sde->head_sn++;
377 #endif
378         sdma_txclean(sde->dd, tx);
379         if (complete)
380                 (*complete)(tx, res);
381         if (wait && iowait_sdma_dec(wait))
382                 iowait_drain_wakeup(wait);
383 }
384
385 /*
386  * Complete all the sdma requests with a SDMA_TXREQ_S_ABORTED status
387  *
388  * Depending on timing there can be txreqs in two places:
389  * - in the descq ring
390  * - in the flush list
391  *
392  * To avoid ordering issues the descq ring needs to be flushed
393  * first followed by the flush list.
394  *
395  * This routine is called from two places
396  * - From a work queue item
397  * - Directly from the state machine just before setting the
398  *   state to running
399  *
400  * Must be called with head_lock held
401  *
402  */
403 static void sdma_flush(struct sdma_engine *sde)
404 {
405         struct sdma_txreq *txp, *txp_next;
406         LIST_HEAD(flushlist);
407         unsigned long flags;
408
409         /* flush from head to tail */
410         sdma_flush_descq(sde);
411         spin_lock_irqsave(&sde->flushlist_lock, flags);
412         /* copy flush list */
413         list_splice_init(&sde->flushlist, &flushlist);
414         spin_unlock_irqrestore(&sde->flushlist_lock, flags);
415         /* flush from flush list */
416         list_for_each_entry_safe(txp, txp_next, &flushlist, list)
417                 complete_tx(sde, txp, SDMA_TXREQ_S_ABORTED);
418 }
419
420 /*
421  * Fields a work request for flushing the descq ring
422  * and the flush list
423  *
424  * If the engine has been brought to running during
425  * the scheduling delay, the flush is ignored, assuming
426  * that the process of bringing the engine to running
427  * would have done this flush prior to going to running.
428  *
429  */
430 static void sdma_field_flush(struct work_struct *work)
431 {
432         unsigned long flags;
433         struct sdma_engine *sde =
434                 container_of(work, struct sdma_engine, flush_worker);
435
436         write_seqlock_irqsave(&sde->head_lock, flags);
437         if (!__sdma_running(sde))
438                 sdma_flush(sde);
439         write_sequnlock_irqrestore(&sde->head_lock, flags);
440 }
441
442 static void sdma_err_halt_wait(struct work_struct *work)
443 {
444         struct sdma_engine *sde = container_of(work, struct sdma_engine,
445                                                 err_halt_worker);
446         u64 statuscsr;
447         unsigned long timeout;
448
449         timeout = jiffies + msecs_to_jiffies(SDMA_ERR_HALT_TIMEOUT);
450         while (1) {
451                 statuscsr = read_sde_csr(sde, SD(STATUS));
452                 statuscsr &= SD(STATUS_ENG_HALTED_SMASK);
453                 if (statuscsr)
454                         break;
455                 if (time_after(jiffies, timeout)) {
456                         dd_dev_err(sde->dd,
457                                    "SDMA engine %d - timeout waiting for engine to halt\n",
458                                    sde->this_idx);
459                         /*
460                          * Continue anyway.  This could happen if there was
461                          * an uncorrectable error in the wrong spot.
462                          */
463                         break;
464                 }
465                 usleep_range(80, 120);
466         }
467
468         sdma_process_event(sde, sdma_event_e15_hw_halt_done);
469 }
470
471 static void sdma_err_progress_check_schedule(struct sdma_engine *sde)
472 {
473         if (!is_bx(sde->dd) && HFI1_CAP_IS_KSET(SDMA_AHG)) {
474                 unsigned index;
475                 struct hfi1_devdata *dd = sde->dd;
476
477                 for (index = 0; index < dd->num_sdma; index++) {
478                         struct sdma_engine *curr_sdma = &dd->per_sdma[index];
479
480                         if (curr_sdma != sde)
481                                 curr_sdma->progress_check_head =
482                                                         curr_sdma->descq_head;
483                 }
484                 dd_dev_err(sde->dd,
485                            "SDMA engine %d - check scheduled\n",
486                                 sde->this_idx);
487                 mod_timer(&sde->err_progress_check_timer, jiffies + 10);
488         }
489 }
490
491 static void sdma_err_progress_check(unsigned long data)
492 {
493         unsigned index;
494         struct sdma_engine *sde = (struct sdma_engine *)data;
495
496         dd_dev_err(sde->dd, "SDE progress check event\n");
497         for (index = 0; index < sde->dd->num_sdma; index++) {
498                 struct sdma_engine *curr_sde = &sde->dd->per_sdma[index];
499                 unsigned long flags;
500
501                 /* check progress on each engine except the current one */
502                 if (curr_sde == sde)
503                         continue;
504                 /*
505                  * We must lock interrupts when acquiring sde->lock,
506                  * to avoid a deadlock if interrupt triggers and spins on
507                  * the same lock on same CPU
508                  */
509                 spin_lock_irqsave(&curr_sde->tail_lock, flags);
510                 write_seqlock(&curr_sde->head_lock);
511
512                 /* skip non-running queues */
513                 if (curr_sde->state.current_state != sdma_state_s99_running) {
514                         write_sequnlock(&curr_sde->head_lock);
515                         spin_unlock_irqrestore(&curr_sde->tail_lock, flags);
516                         continue;
517                 }
518
519                 if ((curr_sde->descq_head != curr_sde->descq_tail) &&
520                     (curr_sde->descq_head ==
521                                 curr_sde->progress_check_head))
522                         __sdma_process_event(curr_sde,
523                                              sdma_event_e90_sw_halted);
524                 write_sequnlock(&curr_sde->head_lock);
525                 spin_unlock_irqrestore(&curr_sde->tail_lock, flags);
526         }
527         schedule_work(&sde->err_halt_worker);
528 }
529
530 static void sdma_hw_clean_up_task(unsigned long opaque)
531 {
532         struct sdma_engine *sde = (struct sdma_engine *)opaque;
533         u64 statuscsr;
534
535         while (1) {
536 #ifdef CONFIG_SDMA_VERBOSITY
537                 dd_dev_err(sde->dd, "CONFIG SDMA(%u) %s:%d %s()\n",
538                            sde->this_idx, slashstrip(__FILE__), __LINE__,
539                         __func__);
540 #endif
541                 statuscsr = read_sde_csr(sde, SD(STATUS));
542                 statuscsr &= SD(STATUS_ENG_CLEANED_UP_SMASK);
543                 if (statuscsr)
544                         break;
545                 udelay(10);
546         }
547
548         sdma_process_event(sde, sdma_event_e25_hw_clean_up_done);
549 }
550
551 static inline struct sdma_txreq *get_txhead(struct sdma_engine *sde)
552 {
553         smp_read_barrier_depends(); /* see sdma_update_tail() */
554         return sde->tx_ring[sde->tx_head & sde->sdma_mask];
555 }
556
557 /*
558  * flush ring for recovery
559  */
560 static void sdma_flush_descq(struct sdma_engine *sde)
561 {
562         u16 head, tail;
563         int progress = 0;
564         struct sdma_txreq *txp = get_txhead(sde);
565
566         /* The reason for some of the complexity of this code is that
567          * not all descriptors have corresponding txps.  So, we have to
568          * be able to skip over descs until we wander into the range of
569          * the next txp on the list.
570          */
571         head = sde->descq_head & sde->sdma_mask;
572         tail = sde->descq_tail & sde->sdma_mask;
573         while (head != tail) {
574                 /* advance head, wrap if needed */
575                 head = ++sde->descq_head & sde->sdma_mask;
576                 /* if now past this txp's descs, do the callback */
577                 if (txp && txp->next_descq_idx == head) {
578                         /* remove from list */
579                         sde->tx_ring[sde->tx_head++ & sde->sdma_mask] = NULL;
580                         complete_tx(sde, txp, SDMA_TXREQ_S_ABORTED);
581                         trace_hfi1_sdma_progress(sde, head, tail, txp);
582                         txp = get_txhead(sde);
583                 }
584                 progress++;
585         }
586         if (progress)
587                 sdma_desc_avail(sde, sdma_descq_freecnt(sde));
588 }
589
590 static void sdma_sw_clean_up_task(unsigned long opaque)
591 {
592         struct sdma_engine *sde = (struct sdma_engine *)opaque;
593         unsigned long flags;
594
595         spin_lock_irqsave(&sde->tail_lock, flags);
596         write_seqlock(&sde->head_lock);
597
598         /*
599          * At this point, the following should always be true:
600          * - We are halted, so no more descriptors are getting retired.
601          * - We are not running, so no one is submitting new work.
602          * - Only we can send the e40_sw_cleaned, so we can't start
603          *   running again until we say so.  So, the active list and
604          *   descq are ours to play with.
605          */
606
607         /*
608          * In the error clean up sequence, software clean must be called
609          * before the hardware clean so we can use the hardware head in
610          * the progress routine.  A hardware clean or SPC unfreeze will
611          * reset the hardware head.
612          *
613          * Process all retired requests. The progress routine will use the
614          * latest physical hardware head - we are not running so speed does
615          * not matter.
616          */
617         sdma_make_progress(sde, 0);
618
619         sdma_flush(sde);
620
621         /*
622          * Reset our notion of head and tail.
623          * Note that the HW registers have been reset via an earlier
624          * clean up.
625          */
626         sde->descq_tail = 0;
627         sde->descq_head = 0;
628         sde->desc_avail = sdma_descq_freecnt(sde);
629         *sde->head_dma = 0;
630
631         __sdma_process_event(sde, sdma_event_e40_sw_cleaned);
632
633         write_sequnlock(&sde->head_lock);
634         spin_unlock_irqrestore(&sde->tail_lock, flags);
635 }
636
637 static void sdma_sw_tear_down(struct sdma_engine *sde)
638 {
639         struct sdma_state *ss = &sde->state;
640
641         /* Releasing this reference means the state machine has stopped. */
642         sdma_put(ss);
643
644         /* stop waiting for all unfreeze events to complete */
645         atomic_set(&sde->dd->sdma_unfreeze_count, -1);
646         wake_up_interruptible(&sde->dd->sdma_unfreeze_wq);
647 }
648
649 static void sdma_start_hw_clean_up(struct sdma_engine *sde)
650 {
651         tasklet_hi_schedule(&sde->sdma_hw_clean_up_task);
652 }
653
654 static void sdma_set_state(struct sdma_engine *sde,
655                            enum sdma_states next_state)
656 {
657         struct sdma_state *ss = &sde->state;
658         const struct sdma_set_state_action *action = sdma_action_table;
659         unsigned op = 0;
660
661         trace_hfi1_sdma_state(
662                 sde,
663                 sdma_state_names[ss->current_state],
664                 sdma_state_names[next_state]);
665
666         /* debugging bookkeeping */
667         ss->previous_state = ss->current_state;
668         ss->previous_op = ss->current_op;
669         ss->current_state = next_state;
670
671         if (ss->previous_state != sdma_state_s99_running &&
672             next_state == sdma_state_s99_running)
673                 sdma_flush(sde);
674
675         if (action[next_state].op_enable)
676                 op |= SDMA_SENDCTRL_OP_ENABLE;
677
678         if (action[next_state].op_intenable)
679                 op |= SDMA_SENDCTRL_OP_INTENABLE;
680
681         if (action[next_state].op_halt)
682                 op |= SDMA_SENDCTRL_OP_HALT;
683
684         if (action[next_state].op_cleanup)
685                 op |= SDMA_SENDCTRL_OP_CLEANUP;
686
687         if (action[next_state].go_s99_running_tofalse)
688                 ss->go_s99_running = 0;
689
690         if (action[next_state].go_s99_running_totrue)
691                 ss->go_s99_running = 1;
692
693         ss->current_op = op;
694         sdma_sendctrl(sde, ss->current_op);
695 }
696
697 /**
698  * sdma_get_descq_cnt() - called when device probed
699  *
700  * Return a validated descq count.
701  *
702  * This is currently only used in the verbs initialization to build the tx
703  * list.
704  *
705  * This will probably be deleted in favor of a more scalable approach to
706  * alloc tx's.
707  *
708  */
709 u16 sdma_get_descq_cnt(void)
710 {
711         u16 count = sdma_descq_cnt;
712
713         if (!count)
714                 return SDMA_DESCQ_CNT;
715         /* count must be a power of 2 greater than 64 and less than
716          * 32768.   Otherwise return default.
717          */
718         if (!is_power_of_2(count))
719                 return SDMA_DESCQ_CNT;
720         if (count < 64 || count > 32768)
721                 return SDMA_DESCQ_CNT;
722         return count;
723 }
724
725 /**
726  * sdma_engine_get_vl() - return vl for a given sdma engine
727  * @sde: sdma engine
728  *
729  * This function returns the vl mapped to a given engine, or an error if
730  * the mapping can't be found. The mapping fields are protected by RCU.
731  */
732 int sdma_engine_get_vl(struct sdma_engine *sde)
733 {
734         struct hfi1_devdata *dd = sde->dd;
735         struct sdma_vl_map *m;
736         u8 vl;
737
738         if (sde->this_idx >= TXE_NUM_SDMA_ENGINES)
739                 return -EINVAL;
740
741         rcu_read_lock();
742         m = rcu_dereference(dd->sdma_map);
743         if (unlikely(!m)) {
744                 rcu_read_unlock();
745                 return -EINVAL;
746         }
747         vl = m->engine_to_vl[sde->this_idx];
748         rcu_read_unlock();
749
750         return vl;
751 }
752
753 /**
754  * sdma_select_engine_vl() - select sdma engine
755  * @dd: devdata
756  * @selector: a spreading factor
757  * @vl: this vl
758  *
759  *
760  * This function returns an engine based on the selector and a vl.  The
761  * mapping fields are protected by RCU.
762  */
763 struct sdma_engine *sdma_select_engine_vl(
764         struct hfi1_devdata *dd,
765         u32 selector,
766         u8 vl)
767 {
768         struct sdma_vl_map *m;
769         struct sdma_map_elem *e;
770         struct sdma_engine *rval;
771
772         /* NOTE This should only happen if SC->VL changed after the initial
773          *      checks on the QP/AH
774          *      Default will return engine 0 below
775          */
776         if (vl >= num_vls) {
777                 rval = NULL;
778                 goto done;
779         }
780
781         rcu_read_lock();
782         m = rcu_dereference(dd->sdma_map);
783         if (unlikely(!m)) {
784                 rcu_read_unlock();
785                 return &dd->per_sdma[0];
786         }
787         e = m->map[vl & m->mask];
788         rval = e->sde[selector & e->mask];
789         rcu_read_unlock();
790
791 done:
792         rval =  !rval ? &dd->per_sdma[0] : rval;
793         trace_hfi1_sdma_engine_select(dd, selector, vl, rval->this_idx);
794         return rval;
795 }
796
797 /**
798  * sdma_select_engine_sc() - select sdma engine
799  * @dd: devdata
800  * @selector: a spreading factor
801  * @sc5: the 5 bit sc
802  *
803  *
804  * This function returns an engine based on the selector and an sc.
805  */
806 struct sdma_engine *sdma_select_engine_sc(
807         struct hfi1_devdata *dd,
808         u32 selector,
809         u8 sc5)
810 {
811         u8 vl = sc_to_vlt(dd, sc5);
812
813         return sdma_select_engine_vl(dd, selector, vl);
814 }
815
816 struct sdma_rht_map_elem {
817         u32 mask;
818         u8 ctr;
819         struct sdma_engine *sde[0];
820 };
821
822 struct sdma_rht_node {
823         unsigned long cpu_id;
824         struct sdma_rht_map_elem *map[HFI1_MAX_VLS_SUPPORTED];
825         struct rhash_head node;
826 };
827
828 #define NR_CPUS_HINT 192
829
830 static const struct rhashtable_params sdma_rht_params = {
831         .nelem_hint = NR_CPUS_HINT,
832         .head_offset = offsetof(struct sdma_rht_node, node),
833         .key_offset = offsetof(struct sdma_rht_node, cpu_id),
834         .key_len = FIELD_SIZEOF(struct sdma_rht_node, cpu_id),
835         .max_size = NR_CPUS,
836         .min_size = 8,
837         .automatic_shrinking = true,
838 };
839
840 /*
841  * sdma_select_user_engine() - select sdma engine based on user setup
842  * @dd: devdata
843  * @selector: a spreading factor
844  * @vl: this vl
845  *
846  * This function returns an sdma engine for a user sdma request.
847  * User defined sdma engine affinity setting is honored when applicable,
848  * otherwise system default sdma engine mapping is used. To ensure correct
849  * ordering, the mapping from <selector, vl> to sde must remain unchanged.
850  */
851 struct sdma_engine *sdma_select_user_engine(struct hfi1_devdata *dd,
852                                             u32 selector, u8 vl)
853 {
854         struct sdma_rht_node *rht_node;
855         struct sdma_engine *sde = NULL;
856         const struct cpumask *current_mask = tsk_cpus_allowed(current);
857         unsigned long cpu_id;
858
859         /*
860          * To ensure that always the same sdma engine(s) will be
861          * selected make sure the process is pinned to this CPU only.
862          */
863         if (cpumask_weight(current_mask) != 1)
864                 goto out;
865
866         cpu_id = smp_processor_id();
867         rcu_read_lock();
868         rht_node = rhashtable_lookup_fast(&dd->sdma_rht, &cpu_id,
869                                           sdma_rht_params);
870
871         if (rht_node && rht_node->map[vl]) {
872                 struct sdma_rht_map_elem *map = rht_node->map[vl];
873
874                 sde = map->sde[selector & map->mask];
875         }
876         rcu_read_unlock();
877
878         if (sde)
879                 return sde;
880
881 out:
882         return sdma_select_engine_vl(dd, selector, vl);
883 }
884
885 static void sdma_populate_sde_map(struct sdma_rht_map_elem *map)
886 {
887         int i;
888
889         for (i = 0; i < roundup_pow_of_two(map->ctr ? : 1) - map->ctr; i++)
890                 map->sde[map->ctr + i] = map->sde[i];
891 }
892
893 static void sdma_cleanup_sde_map(struct sdma_rht_map_elem *map,
894                                  struct sdma_engine *sde)
895 {
896         unsigned int i, pow;
897
898         /* only need to check the first ctr entries for a match */
899         for (i = 0; i < map->ctr; i++) {
900                 if (map->sde[i] == sde) {
901                         memmove(&map->sde[i], &map->sde[i + 1],
902                                 (map->ctr - i - 1) * sizeof(map->sde[0]));
903                         map->ctr--;
904                         pow = roundup_pow_of_two(map->ctr ? : 1);
905                         map->mask = pow - 1;
906                         sdma_populate_sde_map(map);
907                         break;
908                 }
909         }
910 }
911
912 /*
913  * Prevents concurrent reads and writes of the sdma engine cpu_mask
914  */
915 static DEFINE_MUTEX(process_to_sde_mutex);
916
917 ssize_t sdma_set_cpu_to_sde_map(struct sdma_engine *sde, const char *buf,
918                                 size_t count)
919 {
920         struct hfi1_devdata *dd = sde->dd;
921         cpumask_var_t mask, new_mask;
922         unsigned long cpu;
923         int ret, vl, sz;
924
925         vl = sdma_engine_get_vl(sde);
926         if (unlikely(vl < 0))
927                 return -EINVAL;
928
929         ret = zalloc_cpumask_var(&mask, GFP_KERNEL);
930         if (!ret)
931                 return -ENOMEM;
932
933         ret = zalloc_cpumask_var(&new_mask, GFP_KERNEL);
934         if (!ret) {
935                 free_cpumask_var(mask);
936                 return -ENOMEM;
937         }
938         ret = cpulist_parse(buf, mask);
939         if (ret)
940                 goto out_free;
941
942         if (!cpumask_subset(mask, cpu_online_mask)) {
943                 dd_dev_warn(sde->dd, "Invalid CPU mask\n");
944                 ret = -EINVAL;
945                 goto out_free;
946         }
947
948         sz = sizeof(struct sdma_rht_map_elem) +
949                         (TXE_NUM_SDMA_ENGINES * sizeof(struct sdma_engine *));
950
951         mutex_lock(&process_to_sde_mutex);
952
953         for_each_cpu(cpu, mask) {
954                 struct sdma_rht_node *rht_node;
955
956                 /* Check if we have this already mapped */
957                 if (cpumask_test_cpu(cpu, &sde->cpu_mask)) {
958                         cpumask_set_cpu(cpu, new_mask);
959                         continue;
960                 }
961
962                 rht_node = rhashtable_lookup_fast(&dd->sdma_rht, &cpu,
963                                                   sdma_rht_params);
964                 if (!rht_node) {
965                         rht_node = kzalloc(sizeof(*rht_node), GFP_KERNEL);
966                         if (!rht_node) {
967                                 ret = -ENOMEM;
968                                 goto out;
969                         }
970
971                         rht_node->map[vl] = kzalloc(sz, GFP_KERNEL);
972                         if (!rht_node->map[vl]) {
973                                 kfree(rht_node);
974                                 ret = -ENOMEM;
975                                 goto out;
976                         }
977                         rht_node->cpu_id = cpu;
978                         rht_node->map[vl]->mask = 0;
979                         rht_node->map[vl]->ctr = 1;
980                         rht_node->map[vl]->sde[0] = sde;
981
982                         ret = rhashtable_insert_fast(&dd->sdma_rht,
983                                                      &rht_node->node,
984                                                      sdma_rht_params);
985                         if (ret) {
986                                 kfree(rht_node->map[vl]);
987                                 kfree(rht_node);
988                                 dd_dev_err(sde->dd, "Failed to set process to sde affinity for cpu %lu\n",
989                                            cpu);
990                                 goto out;
991                         }
992
993                 } else {
994                         int ctr, pow;
995
996                         /* Add new user mappings */
997                         if (!rht_node->map[vl])
998                                 rht_node->map[vl] = kzalloc(sz, GFP_KERNEL);
999
1000                         if (!rht_node->map[vl]) {
1001                                 ret = -ENOMEM;
1002                                 goto out;
1003                         }
1004
1005                         rht_node->map[vl]->ctr++;
1006                         ctr = rht_node->map[vl]->ctr;
1007                         rht_node->map[vl]->sde[ctr - 1] = sde;
1008                         pow = roundup_pow_of_two(ctr);
1009                         rht_node->map[vl]->mask = pow - 1;
1010
1011                         /* Populate the sde map table */
1012                         sdma_populate_sde_map(rht_node->map[vl]);
1013                 }
1014                 cpumask_set_cpu(cpu, new_mask);
1015         }
1016
1017         /* Clean up old mappings */
1018         for_each_cpu(cpu, cpu_online_mask) {
1019                 struct sdma_rht_node *rht_node;
1020
1021                 /* Don't cleanup sdes that are set in the new mask */
1022                 if (cpumask_test_cpu(cpu, mask))
1023                         continue;
1024
1025                 rht_node = rhashtable_lookup_fast(&dd->sdma_rht, &cpu,
1026                                                   sdma_rht_params);
1027                 if (rht_node) {
1028                         bool empty = true;
1029                         int i;
1030
1031                         /* Remove mappings for old sde */
1032                         for (i = 0; i < HFI1_MAX_VLS_SUPPORTED; i++)
1033                                 if (rht_node->map[i])
1034                                         sdma_cleanup_sde_map(rht_node->map[i],
1035                                                              sde);
1036
1037                         /* Free empty hash table entries */
1038                         for (i = 0; i < HFI1_MAX_VLS_SUPPORTED; i++) {
1039                                 if (!rht_node->map[i])
1040                                         continue;
1041
1042                                 if (rht_node->map[i]->ctr) {
1043                                         empty = false;
1044                                         break;
1045                                 }
1046                         }
1047
1048                         if (empty) {
1049                                 ret = rhashtable_remove_fast(&dd->sdma_rht,
1050                                                              &rht_node->node,
1051                                                              sdma_rht_params);
1052                                 WARN_ON(ret);
1053
1054                                 for (i = 0; i < HFI1_MAX_VLS_SUPPORTED; i++)
1055                                         kfree(rht_node->map[i]);
1056
1057                                 kfree(rht_node);
1058                         }
1059                 }
1060         }
1061
1062         cpumask_copy(&sde->cpu_mask, new_mask);
1063 out:
1064         mutex_unlock(&process_to_sde_mutex);
1065 out_free:
1066         free_cpumask_var(mask);
1067         free_cpumask_var(new_mask);
1068         return ret ? : strnlen(buf, PAGE_SIZE);
1069 }
1070
1071 ssize_t sdma_get_cpu_to_sde_map(struct sdma_engine *sde, char *buf)
1072 {
1073         mutex_lock(&process_to_sde_mutex);
1074         if (cpumask_empty(&sde->cpu_mask))
1075                 snprintf(buf, PAGE_SIZE, "%s\n", "empty");
1076         else
1077                 cpumap_print_to_pagebuf(true, buf, &sde->cpu_mask);
1078         mutex_unlock(&process_to_sde_mutex);
1079         return strnlen(buf, PAGE_SIZE);
1080 }
1081
1082 static void sdma_rht_free(void *ptr, void *arg)
1083 {
1084         struct sdma_rht_node *rht_node = ptr;
1085         int i;
1086
1087         for (i = 0; i < HFI1_MAX_VLS_SUPPORTED; i++)
1088                 kfree(rht_node->map[i]);
1089
1090         kfree(rht_node);
1091 }
1092
1093 /**
1094  * sdma_seqfile_dump_cpu_list() - debugfs dump the cpu to sdma mappings
1095  * @s: seq file
1096  * @dd: hfi1_devdata
1097  * @cpuid: cpu id
1098  *
1099  * This routine dumps the process to sde mappings per cpu
1100  */
1101 void sdma_seqfile_dump_cpu_list(struct seq_file *s,
1102                                 struct hfi1_devdata *dd,
1103                                 unsigned long cpuid)
1104 {
1105         struct sdma_rht_node *rht_node;
1106         int i, j;
1107
1108         rht_node = rhashtable_lookup_fast(&dd->sdma_rht, &cpuid,
1109                                           sdma_rht_params);
1110         if (!rht_node)
1111                 return;
1112
1113         seq_printf(s, "cpu%3lu: ", cpuid);
1114         for (i = 0; i < HFI1_MAX_VLS_SUPPORTED; i++) {
1115                 if (!rht_node->map[i] || !rht_node->map[i]->ctr)
1116                         continue;
1117
1118                 seq_printf(s, " vl%d: [", i);
1119
1120                 for (j = 0; j < rht_node->map[i]->ctr; j++) {
1121                         if (!rht_node->map[i]->sde[j])
1122                                 continue;
1123
1124                         if (j > 0)
1125                                 seq_puts(s, ",");
1126
1127                         seq_printf(s, " sdma%2d",
1128                                    rht_node->map[i]->sde[j]->this_idx);
1129                 }
1130                 seq_puts(s, " ]");
1131         }
1132
1133         seq_puts(s, "\n");
1134 }
1135
1136 /*
1137  * Free the indicated map struct
1138  */
1139 static void sdma_map_free(struct sdma_vl_map *m)
1140 {
1141         int i;
1142
1143         for (i = 0; m && i < m->actual_vls; i++)
1144                 kfree(m->map[i]);
1145         kfree(m);
1146 }
1147
1148 /*
1149  * Handle RCU callback
1150  */
1151 static void sdma_map_rcu_callback(struct rcu_head *list)
1152 {
1153         struct sdma_vl_map *m = container_of(list, struct sdma_vl_map, list);
1154
1155         sdma_map_free(m);
1156 }
1157
1158 /**
1159  * sdma_map_init - called when # vls change
1160  * @dd: hfi1_devdata
1161  * @port: port number
1162  * @num_vls: number of vls
1163  * @vl_engines: per vl engine mapping (optional)
1164  *
1165  * This routine changes the mapping based on the number of vls.
1166  *
1167  * vl_engines is used to specify a non-uniform vl/engine loading. NULL
1168  * implies auto computing the loading and giving each VLs a uniform
1169  * distribution of engines per VL.
1170  *
1171  * The auto algorithm computes the sde_per_vl and the number of extra
1172  * engines.  Any extra engines are added from the last VL on down.
1173  *
1174  * rcu locking is used here to control access to the mapping fields.
1175  *
1176  * If either the num_vls or num_sdma are non-power of 2, the array sizes
1177  * in the struct sdma_vl_map and the struct sdma_map_elem are rounded
1178  * up to the next highest power of 2 and the first entry is reused
1179  * in a round robin fashion.
1180  *
1181  * If an error occurs the map change is not done and the mapping is
1182  * not changed.
1183  *
1184  */
1185 int sdma_map_init(struct hfi1_devdata *dd, u8 port, u8 num_vls, u8 *vl_engines)
1186 {
1187         int i, j;
1188         int extra, sde_per_vl;
1189         int engine = 0;
1190         u8 lvl_engines[OPA_MAX_VLS];
1191         struct sdma_vl_map *oldmap, *newmap;
1192
1193         if (!(dd->flags & HFI1_HAS_SEND_DMA))
1194                 return 0;
1195
1196         if (!vl_engines) {
1197                 /* truncate divide */
1198                 sde_per_vl = dd->num_sdma / num_vls;
1199                 /* extras */
1200                 extra = dd->num_sdma % num_vls;
1201                 vl_engines = lvl_engines;
1202                 /* add extras from last vl down */
1203                 for (i = num_vls - 1; i >= 0; i--, extra--)
1204                         vl_engines[i] = sde_per_vl + (extra > 0 ? 1 : 0);
1205         }
1206         /* build new map */
1207         newmap = kzalloc(
1208                 sizeof(struct sdma_vl_map) +
1209                         roundup_pow_of_two(num_vls) *
1210                         sizeof(struct sdma_map_elem *),
1211                 GFP_KERNEL);
1212         if (!newmap)
1213                 goto bail;
1214         newmap->actual_vls = num_vls;
1215         newmap->vls = roundup_pow_of_two(num_vls);
1216         newmap->mask = (1 << ilog2(newmap->vls)) - 1;
1217         /* initialize back-map */
1218         for (i = 0; i < TXE_NUM_SDMA_ENGINES; i++)
1219                 newmap->engine_to_vl[i] = -1;
1220         for (i = 0; i < newmap->vls; i++) {
1221                 /* save for wrap around */
1222                 int first_engine = engine;
1223
1224                 if (i < newmap->actual_vls) {
1225                         int sz = roundup_pow_of_two(vl_engines[i]);
1226
1227                         /* only allocate once */
1228                         newmap->map[i] = kzalloc(
1229                                 sizeof(struct sdma_map_elem) +
1230                                         sz * sizeof(struct sdma_engine *),
1231                                 GFP_KERNEL);
1232                         if (!newmap->map[i])
1233                                 goto bail;
1234                         newmap->map[i]->mask = (1 << ilog2(sz)) - 1;
1235                         /* assign engines */
1236                         for (j = 0; j < sz; j++) {
1237                                 newmap->map[i]->sde[j] =
1238                                         &dd->per_sdma[engine];
1239                                 if (++engine >= first_engine + vl_engines[i])
1240                                         /* wrap back to first engine */
1241                                         engine = first_engine;
1242                         }
1243                         /* assign back-map */
1244                         for (j = 0; j < vl_engines[i]; j++)
1245                                 newmap->engine_to_vl[first_engine + j] = i;
1246                 } else {
1247                         /* just re-use entry without allocating */
1248                         newmap->map[i] = newmap->map[i % num_vls];
1249                 }
1250                 engine = first_engine + vl_engines[i];
1251         }
1252         /* newmap in hand, save old map */
1253         spin_lock_irq(&dd->sde_map_lock);
1254         oldmap = rcu_dereference_protected(dd->sdma_map,
1255                                            lockdep_is_held(&dd->sde_map_lock));
1256
1257         /* publish newmap */
1258         rcu_assign_pointer(dd->sdma_map, newmap);
1259
1260         spin_unlock_irq(&dd->sde_map_lock);
1261         /* success, free any old map after grace period */
1262         if (oldmap)
1263                 call_rcu(&oldmap->list, sdma_map_rcu_callback);
1264         return 0;
1265 bail:
1266         /* free any partial allocation */
1267         sdma_map_free(newmap);
1268         return -ENOMEM;
1269 }
1270
1271 /*
1272  * Clean up allocated memory.
1273  *
1274  * This routine is can be called regardless of the success of sdma_init()
1275  *
1276  */
1277 static void sdma_clean(struct hfi1_devdata *dd, size_t num_engines)
1278 {
1279         size_t i;
1280         struct sdma_engine *sde;
1281
1282         if (dd->sdma_pad_dma) {
1283                 dma_free_coherent(&dd->pcidev->dev, 4,
1284                                   (void *)dd->sdma_pad_dma,
1285                                   dd->sdma_pad_phys);
1286                 dd->sdma_pad_dma = NULL;
1287                 dd->sdma_pad_phys = 0;
1288         }
1289         if (dd->sdma_heads_dma) {
1290                 dma_free_coherent(&dd->pcidev->dev, dd->sdma_heads_size,
1291                                   (void *)dd->sdma_heads_dma,
1292                                   dd->sdma_heads_phys);
1293                 dd->sdma_heads_dma = NULL;
1294                 dd->sdma_heads_phys = 0;
1295         }
1296         for (i = 0; dd->per_sdma && i < num_engines; ++i) {
1297                 sde = &dd->per_sdma[i];
1298
1299                 sde->head_dma = NULL;
1300                 sde->head_phys = 0;
1301
1302                 if (sde->descq) {
1303                         dma_free_coherent(
1304                                 &dd->pcidev->dev,
1305                                 sde->descq_cnt * sizeof(u64[2]),
1306                                 sde->descq,
1307                                 sde->descq_phys
1308                         );
1309                         sde->descq = NULL;
1310                         sde->descq_phys = 0;
1311                 }
1312                 kvfree(sde->tx_ring);
1313                 sde->tx_ring = NULL;
1314         }
1315         spin_lock_irq(&dd->sde_map_lock);
1316         sdma_map_free(rcu_access_pointer(dd->sdma_map));
1317         RCU_INIT_POINTER(dd->sdma_map, NULL);
1318         spin_unlock_irq(&dd->sde_map_lock);
1319         synchronize_rcu();
1320         kfree(dd->per_sdma);
1321         dd->per_sdma = NULL;
1322 }
1323
1324 /**
1325  * sdma_init() - called when device probed
1326  * @dd: hfi1_devdata
1327  * @port: port number (currently only zero)
1328  *
1329  * sdma_init initializes the specified number of engines.
1330  *
1331  * The code initializes each sde, its csrs.  Interrupts
1332  * are not required to be enabled.
1333  *
1334  * Returns:
1335  * 0 - success, -errno on failure
1336  */
1337 int sdma_init(struct hfi1_devdata *dd, u8 port)
1338 {
1339         unsigned this_idx;
1340         struct sdma_engine *sde;
1341         u16 descq_cnt;
1342         void *curr_head;
1343         struct hfi1_pportdata *ppd = dd->pport + port;
1344         u32 per_sdma_credits;
1345         uint idle_cnt = sdma_idle_cnt;
1346         size_t num_engines = dd->chip_sdma_engines;
1347
1348         if (!HFI1_CAP_IS_KSET(SDMA)) {
1349                 HFI1_CAP_CLEAR(SDMA_AHG);
1350                 return 0;
1351         }
1352         if (mod_num_sdma &&
1353             /* can't exceed chip support */
1354             mod_num_sdma <= dd->chip_sdma_engines &&
1355             /* count must be >= vls */
1356             mod_num_sdma >= num_vls)
1357                 num_engines = mod_num_sdma;
1358
1359         dd_dev_info(dd, "SDMA mod_num_sdma: %u\n", mod_num_sdma);
1360         dd_dev_info(dd, "SDMA chip_sdma_engines: %u\n", dd->chip_sdma_engines);
1361         dd_dev_info(dd, "SDMA chip_sdma_mem_size: %u\n",
1362                     dd->chip_sdma_mem_size);
1363
1364         per_sdma_credits =
1365                 dd->chip_sdma_mem_size / (num_engines * SDMA_BLOCK_SIZE);
1366
1367         /* set up freeze waitqueue */
1368         init_waitqueue_head(&dd->sdma_unfreeze_wq);
1369         atomic_set(&dd->sdma_unfreeze_count, 0);
1370
1371         descq_cnt = sdma_get_descq_cnt();
1372         dd_dev_info(dd, "SDMA engines %zu descq_cnt %u\n",
1373                     num_engines, descq_cnt);
1374
1375         /* alloc memory for array of send engines */
1376         dd->per_sdma = kcalloc(num_engines, sizeof(*dd->per_sdma), GFP_KERNEL);
1377         if (!dd->per_sdma)
1378                 return -ENOMEM;
1379
1380         idle_cnt = ns_to_cclock(dd, idle_cnt);
1381         if (!sdma_desct_intr)
1382                 sdma_desct_intr = SDMA_DESC_INTR;
1383
1384         /* Allocate memory for SendDMA descriptor FIFOs */
1385         for (this_idx = 0; this_idx < num_engines; ++this_idx) {
1386                 sde = &dd->per_sdma[this_idx];
1387                 sde->dd = dd;
1388                 sde->ppd = ppd;
1389                 sde->this_idx = this_idx;
1390                 sde->descq_cnt = descq_cnt;
1391                 sde->desc_avail = sdma_descq_freecnt(sde);
1392                 sde->sdma_shift = ilog2(descq_cnt);
1393                 sde->sdma_mask = (1 << sde->sdma_shift) - 1;
1394
1395                 /* Create a mask specifically for each interrupt source */
1396                 sde->int_mask = (u64)1 << (0 * TXE_NUM_SDMA_ENGINES +
1397                                            this_idx);
1398                 sde->progress_mask = (u64)1 << (1 * TXE_NUM_SDMA_ENGINES +
1399                                                 this_idx);
1400                 sde->idle_mask = (u64)1 << (2 * TXE_NUM_SDMA_ENGINES +
1401                                             this_idx);
1402                 /* Create a combined mask to cover all 3 interrupt sources */
1403                 sde->imask = sde->int_mask | sde->progress_mask |
1404                              sde->idle_mask;
1405
1406                 spin_lock_init(&sde->tail_lock);
1407                 seqlock_init(&sde->head_lock);
1408                 spin_lock_init(&sde->senddmactrl_lock);
1409                 spin_lock_init(&sde->flushlist_lock);
1410                 /* insure there is always a zero bit */
1411                 sde->ahg_bits = 0xfffffffe00000000ULL;
1412
1413                 sdma_set_state(sde, sdma_state_s00_hw_down);
1414
1415                 /* set up reference counting */
1416                 kref_init(&sde->state.kref);
1417                 init_completion(&sde->state.comp);
1418
1419                 INIT_LIST_HEAD(&sde->flushlist);
1420                 INIT_LIST_HEAD(&sde->dmawait);
1421
1422                 sde->tail_csr =
1423                         get_kctxt_csr_addr(dd, this_idx, SD(TAIL));
1424
1425                 if (idle_cnt)
1426                         dd->default_desc1 =
1427                                 SDMA_DESC1_HEAD_TO_HOST_FLAG;
1428                 else
1429                         dd->default_desc1 =
1430                                 SDMA_DESC1_INT_REQ_FLAG;
1431
1432                 tasklet_init(&sde->sdma_hw_clean_up_task, sdma_hw_clean_up_task,
1433                              (unsigned long)sde);
1434
1435                 tasklet_init(&sde->sdma_sw_clean_up_task, sdma_sw_clean_up_task,
1436                              (unsigned long)sde);
1437                 INIT_WORK(&sde->err_halt_worker, sdma_err_halt_wait);
1438                 INIT_WORK(&sde->flush_worker, sdma_field_flush);
1439
1440                 sde->progress_check_head = 0;
1441
1442                 setup_timer(&sde->err_progress_check_timer,
1443                             sdma_err_progress_check, (unsigned long)sde);
1444
1445                 sde->descq = dma_zalloc_coherent(
1446                         &dd->pcidev->dev,
1447                         descq_cnt * sizeof(u64[2]),
1448                         &sde->descq_phys,
1449                         GFP_KERNEL
1450                 );
1451                 if (!sde->descq)
1452                         goto bail;
1453                 sde->tx_ring =
1454                         kcalloc(descq_cnt, sizeof(struct sdma_txreq *),
1455                                 GFP_KERNEL);
1456                 if (!sde->tx_ring)
1457                         sde->tx_ring =
1458                                 vzalloc(
1459                                         sizeof(struct sdma_txreq *) *
1460                                         descq_cnt);
1461                 if (!sde->tx_ring)
1462                         goto bail;
1463         }
1464
1465         dd->sdma_heads_size = L1_CACHE_BYTES * num_engines;
1466         /* Allocate memory for DMA of head registers to memory */
1467         dd->sdma_heads_dma = dma_zalloc_coherent(
1468                 &dd->pcidev->dev,
1469                 dd->sdma_heads_size,
1470                 &dd->sdma_heads_phys,
1471                 GFP_KERNEL
1472         );
1473         if (!dd->sdma_heads_dma) {
1474                 dd_dev_err(dd, "failed to allocate SendDMA head memory\n");
1475                 goto bail;
1476         }
1477
1478         /* Allocate memory for pad */
1479         dd->sdma_pad_dma = dma_zalloc_coherent(
1480                 &dd->pcidev->dev,
1481                 sizeof(u32),
1482                 &dd->sdma_pad_phys,
1483                 GFP_KERNEL
1484         );
1485         if (!dd->sdma_pad_dma) {
1486                 dd_dev_err(dd, "failed to allocate SendDMA pad memory\n");
1487                 goto bail;
1488         }
1489
1490         /* assign each engine to different cacheline and init registers */
1491         curr_head = (void *)dd->sdma_heads_dma;
1492         for (this_idx = 0; this_idx < num_engines; ++this_idx) {
1493                 unsigned long phys_offset;
1494
1495                 sde = &dd->per_sdma[this_idx];
1496
1497                 sde->head_dma = curr_head;
1498                 curr_head += L1_CACHE_BYTES;
1499                 phys_offset = (unsigned long)sde->head_dma -
1500                               (unsigned long)dd->sdma_heads_dma;
1501                 sde->head_phys = dd->sdma_heads_phys + phys_offset;
1502                 init_sdma_regs(sde, per_sdma_credits, idle_cnt);
1503         }
1504         dd->flags |= HFI1_HAS_SEND_DMA;
1505         dd->flags |= idle_cnt ? HFI1_HAS_SDMA_TIMEOUT : 0;
1506         dd->num_sdma = num_engines;
1507         if (sdma_map_init(dd, port, ppd->vls_operational, NULL))
1508                 goto bail;
1509
1510         if (rhashtable_init(&dd->sdma_rht, &sdma_rht_params))
1511                 goto bail;
1512
1513         dd_dev_info(dd, "SDMA num_sdma: %u\n", dd->num_sdma);
1514         return 0;
1515
1516 bail:
1517         sdma_clean(dd, num_engines);
1518         return -ENOMEM;
1519 }
1520
1521 /**
1522  * sdma_all_running() - called when the link goes up
1523  * @dd: hfi1_devdata
1524  *
1525  * This routine moves all engines to the running state.
1526  */
1527 void sdma_all_running(struct hfi1_devdata *dd)
1528 {
1529         struct sdma_engine *sde;
1530         unsigned int i;
1531
1532         /* move all engines to running */
1533         for (i = 0; i < dd->num_sdma; ++i) {
1534                 sde = &dd->per_sdma[i];
1535                 sdma_process_event(sde, sdma_event_e30_go_running);
1536         }
1537 }
1538
1539 /**
1540  * sdma_all_idle() - called when the link goes down
1541  * @dd: hfi1_devdata
1542  *
1543  * This routine moves all engines to the idle state.
1544  */
1545 void sdma_all_idle(struct hfi1_devdata *dd)
1546 {
1547         struct sdma_engine *sde;
1548         unsigned int i;
1549
1550         /* idle all engines */
1551         for (i = 0; i < dd->num_sdma; ++i) {
1552                 sde = &dd->per_sdma[i];
1553                 sdma_process_event(sde, sdma_event_e70_go_idle);
1554         }
1555 }
1556
1557 /**
1558  * sdma_start() - called to kick off state processing for all engines
1559  * @dd: hfi1_devdata
1560  *
1561  * This routine is for kicking off the state processing for all required
1562  * sdma engines.  Interrupts need to be working at this point.
1563  *
1564  */
1565 void sdma_start(struct hfi1_devdata *dd)
1566 {
1567         unsigned i;
1568         struct sdma_engine *sde;
1569
1570         /* kick off the engines state processing */
1571         for (i = 0; i < dd->num_sdma; ++i) {
1572                 sde = &dd->per_sdma[i];
1573                 sdma_process_event(sde, sdma_event_e10_go_hw_start);
1574         }
1575 }
1576
1577 /**
1578  * sdma_exit() - used when module is removed
1579  * @dd: hfi1_devdata
1580  */
1581 void sdma_exit(struct hfi1_devdata *dd)
1582 {
1583         unsigned this_idx;
1584         struct sdma_engine *sde;
1585
1586         for (this_idx = 0; dd->per_sdma && this_idx < dd->num_sdma;
1587                         ++this_idx) {
1588                 sde = &dd->per_sdma[this_idx];
1589                 if (!list_empty(&sde->dmawait))
1590                         dd_dev_err(dd, "sde %u: dmawait list not empty!\n",
1591                                    sde->this_idx);
1592                 sdma_process_event(sde, sdma_event_e00_go_hw_down);
1593
1594                 del_timer_sync(&sde->err_progress_check_timer);
1595
1596                 /*
1597                  * This waits for the state machine to exit so it is not
1598                  * necessary to kill the sdma_sw_clean_up_task to make sure
1599                  * it is not running.
1600                  */
1601                 sdma_finalput(&sde->state);
1602         }
1603         sdma_clean(dd, dd->num_sdma);
1604         rhashtable_free_and_destroy(&dd->sdma_rht, sdma_rht_free, NULL);
1605 }
1606
1607 /*
1608  * unmap the indicated descriptor
1609  */
1610 static inline void sdma_unmap_desc(
1611         struct hfi1_devdata *dd,
1612         struct sdma_desc *descp)
1613 {
1614         switch (sdma_mapping_type(descp)) {
1615         case SDMA_MAP_SINGLE:
1616                 dma_unmap_single(
1617                         &dd->pcidev->dev,
1618                         sdma_mapping_addr(descp),
1619                         sdma_mapping_len(descp),
1620                         DMA_TO_DEVICE);
1621                 break;
1622         case SDMA_MAP_PAGE:
1623                 dma_unmap_page(
1624                         &dd->pcidev->dev,
1625                         sdma_mapping_addr(descp),
1626                         sdma_mapping_len(descp),
1627                         DMA_TO_DEVICE);
1628                 break;
1629         }
1630 }
1631
1632 /*
1633  * return the mode as indicated by the first
1634  * descriptor in the tx.
1635  */
1636 static inline u8 ahg_mode(struct sdma_txreq *tx)
1637 {
1638         return (tx->descp[0].qw[1] & SDMA_DESC1_HEADER_MODE_SMASK)
1639                 >> SDMA_DESC1_HEADER_MODE_SHIFT;
1640 }
1641
1642 /**
1643  * sdma_txclean() - clean tx of mappings, descp *kmalloc's
1644  * @dd: hfi1_devdata for unmapping
1645  * @tx: tx request to clean
1646  *
1647  * This is used in the progress routine to clean the tx or
1648  * by the ULP to toss an in-process tx build.
1649  *
1650  * The code can be called multiple times without issue.
1651  *
1652  */
1653 void sdma_txclean(
1654         struct hfi1_devdata *dd,
1655         struct sdma_txreq *tx)
1656 {
1657         u16 i;
1658
1659         if (tx->num_desc) {
1660                 u8 skip = 0, mode = ahg_mode(tx);
1661
1662                 /* unmap first */
1663                 sdma_unmap_desc(dd, &tx->descp[0]);
1664                 /* determine number of AHG descriptors to skip */
1665                 if (mode > SDMA_AHG_APPLY_UPDATE1)
1666                         skip = mode >> 1;
1667                 for (i = 1 + skip; i < tx->num_desc; i++)
1668                         sdma_unmap_desc(dd, &tx->descp[i]);
1669                 tx->num_desc = 0;
1670         }
1671         kfree(tx->coalesce_buf);
1672         tx->coalesce_buf = NULL;
1673         /* kmalloc'ed descp */
1674         if (unlikely(tx->desc_limit > ARRAY_SIZE(tx->descs))) {
1675                 tx->desc_limit = ARRAY_SIZE(tx->descs);
1676                 kfree(tx->descp);
1677         }
1678 }
1679
1680 static inline u16 sdma_gethead(struct sdma_engine *sde)
1681 {
1682         struct hfi1_devdata *dd = sde->dd;
1683         int use_dmahead;
1684         u16 hwhead;
1685
1686 #ifdef CONFIG_SDMA_VERBOSITY
1687         dd_dev_err(sde->dd, "CONFIG SDMA(%u) %s:%d %s()\n",
1688                    sde->this_idx, slashstrip(__FILE__), __LINE__, __func__);
1689 #endif
1690
1691 retry:
1692         use_dmahead = HFI1_CAP_IS_KSET(USE_SDMA_HEAD) && __sdma_running(sde) &&
1693                                         (dd->flags & HFI1_HAS_SDMA_TIMEOUT);
1694         hwhead = use_dmahead ?
1695                 (u16)le64_to_cpu(*sde->head_dma) :
1696                 (u16)read_sde_csr(sde, SD(HEAD));
1697
1698         if (unlikely(HFI1_CAP_IS_KSET(SDMA_HEAD_CHECK))) {
1699                 u16 cnt;
1700                 u16 swtail;
1701                 u16 swhead;
1702                 int sane;
1703
1704                 swhead = sde->descq_head & sde->sdma_mask;
1705                 /* this code is really bad for cache line trading */
1706                 swtail = ACCESS_ONCE(sde->descq_tail) & sde->sdma_mask;
1707                 cnt = sde->descq_cnt;
1708
1709                 if (swhead < swtail)
1710                         /* not wrapped */
1711                         sane = (hwhead >= swhead) & (hwhead <= swtail);
1712                 else if (swhead > swtail)
1713                         /* wrapped around */
1714                         sane = ((hwhead >= swhead) && (hwhead < cnt)) ||
1715                                 (hwhead <= swtail);
1716                 else
1717                         /* empty */
1718                         sane = (hwhead == swhead);
1719
1720                 if (unlikely(!sane)) {
1721                         dd_dev_err(dd, "SDMA(%u) bad head (%s) hwhd=%hu swhd=%hu swtl=%hu cnt=%hu\n",
1722                                    sde->this_idx,
1723                                    use_dmahead ? "dma" : "kreg",
1724                                    hwhead, swhead, swtail, cnt);
1725                         if (use_dmahead) {
1726                                 /* try one more time, using csr */
1727                                 use_dmahead = 0;
1728                                 goto retry;
1729                         }
1730                         /* proceed as if no progress */
1731                         hwhead = swhead;
1732                 }
1733         }
1734         return hwhead;
1735 }
1736
1737 /*
1738  * This is called when there are send DMA descriptors that might be
1739  * available.
1740  *
1741  * This is called with head_lock held.
1742  */
1743 static void sdma_desc_avail(struct sdma_engine *sde, unsigned avail)
1744 {
1745         struct iowait *wait, *nw;
1746         struct iowait *waits[SDMA_WAIT_BATCH_SIZE];
1747         unsigned i, n = 0, seq;
1748         struct sdma_txreq *stx;
1749         struct hfi1_ibdev *dev = &sde->dd->verbs_dev;
1750
1751 #ifdef CONFIG_SDMA_VERBOSITY
1752         dd_dev_err(sde->dd, "CONFIG SDMA(%u) %s:%d %s()\n", sde->this_idx,
1753                    slashstrip(__FILE__), __LINE__, __func__);
1754         dd_dev_err(sde->dd, "avail: %u\n", avail);
1755 #endif
1756
1757         do {
1758                 seq = read_seqbegin(&dev->iowait_lock);
1759                 if (!list_empty(&sde->dmawait)) {
1760                         /* at least one item */
1761                         write_seqlock(&dev->iowait_lock);
1762                         /* Harvest waiters wanting DMA descriptors */
1763                         list_for_each_entry_safe(
1764                                         wait,
1765                                         nw,
1766                                         &sde->dmawait,
1767                                         list) {
1768                                 u16 num_desc = 0;
1769
1770                                 if (!wait->wakeup)
1771                                         continue;
1772                                 if (n == ARRAY_SIZE(waits))
1773                                         break;
1774                                 if (!list_empty(&wait->tx_head)) {
1775                                         stx = list_first_entry(
1776                                                 &wait->tx_head,
1777                                                 struct sdma_txreq,
1778                                                 list);
1779                                         num_desc = stx->num_desc;
1780                                 }
1781                                 if (num_desc > avail)
1782                                         break;
1783                                 avail -= num_desc;
1784                                 list_del_init(&wait->list);
1785                                 waits[n++] = wait;
1786                         }
1787                         write_sequnlock(&dev->iowait_lock);
1788                         break;
1789                 }
1790         } while (read_seqretry(&dev->iowait_lock, seq));
1791
1792         for (i = 0; i < n; i++)
1793                 waits[i]->wakeup(waits[i], SDMA_AVAIL_REASON);
1794 }
1795
1796 /* head_lock must be held */
1797 static void sdma_make_progress(struct sdma_engine *sde, u64 status)
1798 {
1799         struct sdma_txreq *txp = NULL;
1800         int progress = 0;
1801         u16 hwhead, swhead;
1802         int idle_check_done = 0;
1803
1804         hwhead = sdma_gethead(sde);
1805
1806         /* The reason for some of the complexity of this code is that
1807          * not all descriptors have corresponding txps.  So, we have to
1808          * be able to skip over descs until we wander into the range of
1809          * the next txp on the list.
1810          */
1811
1812 retry:
1813         txp = get_txhead(sde);
1814         swhead = sde->descq_head & sde->sdma_mask;
1815         trace_hfi1_sdma_progress(sde, hwhead, swhead, txp);
1816         while (swhead != hwhead) {
1817                 /* advance head, wrap if needed */
1818                 swhead = ++sde->descq_head & sde->sdma_mask;
1819
1820                 /* if now past this txp's descs, do the callback */
1821                 if (txp && txp->next_descq_idx == swhead) {
1822                         /* remove from list */
1823                         sde->tx_ring[sde->tx_head++ & sde->sdma_mask] = NULL;
1824                         complete_tx(sde, txp, SDMA_TXREQ_S_OK);
1825                         /* see if there is another txp */
1826                         txp = get_txhead(sde);
1827                 }
1828                 trace_hfi1_sdma_progress(sde, hwhead, swhead, txp);
1829                 progress++;
1830         }
1831
1832         /*
1833          * The SDMA idle interrupt is not guaranteed to be ordered with respect
1834          * to updates to the the dma_head location in host memory. The head
1835          * value read might not be fully up to date. If there are pending
1836          * descriptors and the SDMA idle interrupt fired then read from the
1837          * CSR SDMA head instead to get the latest value from the hardware.
1838          * The hardware SDMA head should be read at most once in this invocation
1839          * of sdma_make_progress(..) which is ensured by idle_check_done flag
1840          */
1841         if ((status & sde->idle_mask) && !idle_check_done) {
1842                 u16 swtail;
1843
1844                 swtail = ACCESS_ONCE(sde->descq_tail) & sde->sdma_mask;
1845                 if (swtail != hwhead) {
1846                         hwhead = (u16)read_sde_csr(sde, SD(HEAD));
1847                         idle_check_done = 1;
1848                         goto retry;
1849                 }
1850         }
1851
1852         sde->last_status = status;
1853         if (progress)
1854                 sdma_desc_avail(sde, sdma_descq_freecnt(sde));
1855 }
1856
1857 /*
1858  * sdma_engine_interrupt() - interrupt handler for engine
1859  * @sde: sdma engine
1860  * @status: sdma interrupt reason
1861  *
1862  * Status is a mask of the 3 possible interrupts for this engine.  It will
1863  * contain bits _only_ for this SDMA engine.  It will contain at least one
1864  * bit, it may contain more.
1865  */
1866 void sdma_engine_interrupt(struct sdma_engine *sde, u64 status)
1867 {
1868         trace_hfi1_sdma_engine_interrupt(sde, status);
1869         write_seqlock(&sde->head_lock);
1870         sdma_set_desc_cnt(sde, sdma_desct_intr);
1871         if (status & sde->idle_mask)
1872                 sde->idle_int_cnt++;
1873         else if (status & sde->progress_mask)
1874                 sde->progress_int_cnt++;
1875         else if (status & sde->int_mask)
1876                 sde->sdma_int_cnt++;
1877         sdma_make_progress(sde, status);
1878         write_sequnlock(&sde->head_lock);
1879 }
1880
1881 /**
1882  * sdma_engine_error() - error handler for engine
1883  * @sde: sdma engine
1884  * @status: sdma interrupt reason
1885  */
1886 void sdma_engine_error(struct sdma_engine *sde, u64 status)
1887 {
1888         unsigned long flags;
1889
1890 #ifdef CONFIG_SDMA_VERBOSITY
1891         dd_dev_err(sde->dd, "CONFIG SDMA(%u) error status 0x%llx state %s\n",
1892                    sde->this_idx,
1893                    (unsigned long long)status,
1894                    sdma_state_names[sde->state.current_state]);
1895 #endif
1896         spin_lock_irqsave(&sde->tail_lock, flags);
1897         write_seqlock(&sde->head_lock);
1898         if (status & ALL_SDMA_ENG_HALT_ERRS)
1899                 __sdma_process_event(sde, sdma_event_e60_hw_halted);
1900         if (status & ~SD(ENG_ERR_STATUS_SDMA_HALT_ERR_SMASK)) {
1901                 dd_dev_err(sde->dd,
1902                            "SDMA (%u) engine error: 0x%llx state %s\n",
1903                            sde->this_idx,
1904                            (unsigned long long)status,
1905                            sdma_state_names[sde->state.current_state]);
1906                 dump_sdma_state(sde);
1907         }
1908         write_sequnlock(&sde->head_lock);
1909         spin_unlock_irqrestore(&sde->tail_lock, flags);
1910 }
1911
1912 static void sdma_sendctrl(struct sdma_engine *sde, unsigned op)
1913 {
1914         u64 set_senddmactrl = 0;
1915         u64 clr_senddmactrl = 0;
1916         unsigned long flags;
1917
1918 #ifdef CONFIG_SDMA_VERBOSITY
1919         dd_dev_err(sde->dd, "CONFIG SDMA(%u) senddmactrl E=%d I=%d H=%d C=%d\n",
1920                    sde->this_idx,
1921                    (op & SDMA_SENDCTRL_OP_ENABLE) ? 1 : 0,
1922                    (op & SDMA_SENDCTRL_OP_INTENABLE) ? 1 : 0,
1923                    (op & SDMA_SENDCTRL_OP_HALT) ? 1 : 0,
1924                    (op & SDMA_SENDCTRL_OP_CLEANUP) ? 1 : 0);
1925 #endif
1926
1927         if (op & SDMA_SENDCTRL_OP_ENABLE)
1928                 set_senddmactrl |= SD(CTRL_SDMA_ENABLE_SMASK);
1929         else
1930                 clr_senddmactrl |= SD(CTRL_SDMA_ENABLE_SMASK);
1931
1932         if (op & SDMA_SENDCTRL_OP_INTENABLE)
1933                 set_senddmactrl |= SD(CTRL_SDMA_INT_ENABLE_SMASK);
1934         else
1935                 clr_senddmactrl |= SD(CTRL_SDMA_INT_ENABLE_SMASK);
1936
1937         if (op & SDMA_SENDCTRL_OP_HALT)
1938                 set_senddmactrl |= SD(CTRL_SDMA_HALT_SMASK);
1939         else
1940                 clr_senddmactrl |= SD(CTRL_SDMA_HALT_SMASK);
1941
1942         spin_lock_irqsave(&sde->senddmactrl_lock, flags);
1943
1944         sde->p_senddmactrl |= set_senddmactrl;
1945         sde->p_senddmactrl &= ~clr_senddmactrl;
1946
1947         if (op & SDMA_SENDCTRL_OP_CLEANUP)
1948                 write_sde_csr(sde, SD(CTRL),
1949                               sde->p_senddmactrl |
1950                               SD(CTRL_SDMA_CLEANUP_SMASK));
1951         else
1952                 write_sde_csr(sde, SD(CTRL), sde->p_senddmactrl);
1953
1954         spin_unlock_irqrestore(&sde->senddmactrl_lock, flags);
1955
1956 #ifdef CONFIG_SDMA_VERBOSITY
1957         sdma_dumpstate(sde);
1958 #endif
1959 }
1960
1961 static void sdma_setlengen(struct sdma_engine *sde)
1962 {
1963 #ifdef CONFIG_SDMA_VERBOSITY
1964         dd_dev_err(sde->dd, "CONFIG SDMA(%u) %s:%d %s()\n",
1965                    sde->this_idx, slashstrip(__FILE__), __LINE__, __func__);
1966 #endif
1967
1968         /*
1969          * Set SendDmaLenGen and clear-then-set the MSB of the generation
1970          * count to enable generation checking and load the internal
1971          * generation counter.
1972          */
1973         write_sde_csr(sde, SD(LEN_GEN),
1974                       (sde->descq_cnt / 64) << SD(LEN_GEN_LENGTH_SHIFT));
1975         write_sde_csr(sde, SD(LEN_GEN),
1976                       ((sde->descq_cnt / 64) << SD(LEN_GEN_LENGTH_SHIFT)) |
1977                       (4ULL << SD(LEN_GEN_GENERATION_SHIFT)));
1978 }
1979
1980 static inline void sdma_update_tail(struct sdma_engine *sde, u16 tail)
1981 {
1982         /* Commit writes to memory and advance the tail on the chip */
1983         smp_wmb(); /* see get_txhead() */
1984         writeq(tail, sde->tail_csr);
1985 }
1986
1987 /*
1988  * This is called when changing to state s10_hw_start_up_halt_wait as
1989  * a result of send buffer errors or send DMA descriptor errors.
1990  */
1991 static void sdma_hw_start_up(struct sdma_engine *sde)
1992 {
1993         u64 reg;
1994
1995 #ifdef CONFIG_SDMA_VERBOSITY
1996         dd_dev_err(sde->dd, "CONFIG SDMA(%u) %s:%d %s()\n",
1997                    sde->this_idx, slashstrip(__FILE__), __LINE__, __func__);
1998 #endif
1999
2000         sdma_setlengen(sde);
2001         sdma_update_tail(sde, 0); /* Set SendDmaTail */
2002         *sde->head_dma = 0;
2003
2004         reg = SD(ENG_ERR_CLEAR_SDMA_HEADER_REQUEST_FIFO_UNC_ERR_MASK) <<
2005               SD(ENG_ERR_CLEAR_SDMA_HEADER_REQUEST_FIFO_UNC_ERR_SHIFT);
2006         write_sde_csr(sde, SD(ENG_ERR_CLEAR), reg);
2007 }
2008
2009 /*
2010  * set_sdma_integrity
2011  *
2012  * Set the SEND_DMA_CHECK_ENABLE register for send DMA engine 'sde'.
2013  */
2014 static void set_sdma_integrity(struct sdma_engine *sde)
2015 {
2016         struct hfi1_devdata *dd = sde->dd;
2017
2018         write_sde_csr(sde, SD(CHECK_ENABLE),
2019                       hfi1_pkt_base_sdma_integrity(dd));
2020 }
2021
2022 static void init_sdma_regs(
2023         struct sdma_engine *sde,
2024         u32 credits,
2025         uint idle_cnt)
2026 {
2027         u8 opval, opmask;
2028 #ifdef CONFIG_SDMA_VERBOSITY
2029         struct hfi1_devdata *dd = sde->dd;
2030
2031         dd_dev_err(dd, "CONFIG SDMA(%u) %s:%d %s()\n",
2032                    sde->this_idx, slashstrip(__FILE__), __LINE__, __func__);
2033 #endif
2034
2035         write_sde_csr(sde, SD(BASE_ADDR), sde->descq_phys);
2036         sdma_setlengen(sde);
2037         sdma_update_tail(sde, 0); /* Set SendDmaTail */
2038         write_sde_csr(sde, SD(RELOAD_CNT), idle_cnt);
2039         write_sde_csr(sde, SD(DESC_CNT), 0);
2040         write_sde_csr(sde, SD(HEAD_ADDR), sde->head_phys);
2041         write_sde_csr(sde, SD(MEMORY),
2042                       ((u64)credits << SD(MEMORY_SDMA_MEMORY_CNT_SHIFT)) |
2043                       ((u64)(credits * sde->this_idx) <<
2044                        SD(MEMORY_SDMA_MEMORY_INDEX_SHIFT)));
2045         write_sde_csr(sde, SD(ENG_ERR_MASK), ~0ull);
2046         set_sdma_integrity(sde);
2047         opmask = OPCODE_CHECK_MASK_DISABLED;
2048         opval = OPCODE_CHECK_VAL_DISABLED;
2049         write_sde_csr(sde, SD(CHECK_OPCODE),
2050                       (opmask << SEND_CTXT_CHECK_OPCODE_MASK_SHIFT) |
2051                       (opval << SEND_CTXT_CHECK_OPCODE_VALUE_SHIFT));
2052 }
2053
2054 #ifdef CONFIG_SDMA_VERBOSITY
2055
2056 #define sdma_dumpstate_helper0(reg) do { \
2057                 csr = read_csr(sde->dd, reg); \
2058                 dd_dev_err(sde->dd, "%36s     0x%016llx\n", #reg, csr); \
2059         } while (0)
2060
2061 #define sdma_dumpstate_helper(reg) do { \
2062                 csr = read_sde_csr(sde, reg); \
2063                 dd_dev_err(sde->dd, "%36s[%02u] 0x%016llx\n", \
2064                         #reg, sde->this_idx, csr); \
2065         } while (0)
2066
2067 #define sdma_dumpstate_helper2(reg) do { \
2068                 csr = read_csr(sde->dd, reg + (8 * i)); \
2069                 dd_dev_err(sde->dd, "%33s_%02u     0x%016llx\n", \
2070                                 #reg, i, csr); \
2071         } while (0)
2072
2073 void sdma_dumpstate(struct sdma_engine *sde)
2074 {
2075         u64 csr;
2076         unsigned i;
2077
2078         sdma_dumpstate_helper(SD(CTRL));
2079         sdma_dumpstate_helper(SD(STATUS));
2080         sdma_dumpstate_helper0(SD(ERR_STATUS));
2081         sdma_dumpstate_helper0(SD(ERR_MASK));
2082         sdma_dumpstate_helper(SD(ENG_ERR_STATUS));
2083         sdma_dumpstate_helper(SD(ENG_ERR_MASK));
2084
2085         for (i = 0; i < CCE_NUM_INT_CSRS; ++i) {
2086                 sdma_dumpstate_helper2(CCE_INT_STATUS);
2087                 sdma_dumpstate_helper2(CCE_INT_MASK);
2088                 sdma_dumpstate_helper2(CCE_INT_BLOCKED);
2089         }
2090
2091         sdma_dumpstate_helper(SD(TAIL));
2092         sdma_dumpstate_helper(SD(HEAD));
2093         sdma_dumpstate_helper(SD(PRIORITY_THLD));
2094         sdma_dumpstate_helper(SD(IDLE_CNT));
2095         sdma_dumpstate_helper(SD(RELOAD_CNT));
2096         sdma_dumpstate_helper(SD(DESC_CNT));
2097         sdma_dumpstate_helper(SD(DESC_FETCHED_CNT));
2098         sdma_dumpstate_helper(SD(MEMORY));
2099         sdma_dumpstate_helper0(SD(ENGINES));
2100         sdma_dumpstate_helper0(SD(MEM_SIZE));
2101         /* sdma_dumpstate_helper(SEND_EGRESS_SEND_DMA_STATUS);  */
2102         sdma_dumpstate_helper(SD(BASE_ADDR));
2103         sdma_dumpstate_helper(SD(LEN_GEN));
2104         sdma_dumpstate_helper(SD(HEAD_ADDR));
2105         sdma_dumpstate_helper(SD(CHECK_ENABLE));
2106         sdma_dumpstate_helper(SD(CHECK_VL));
2107         sdma_dumpstate_helper(SD(CHECK_JOB_KEY));
2108         sdma_dumpstate_helper(SD(CHECK_PARTITION_KEY));
2109         sdma_dumpstate_helper(SD(CHECK_SLID));
2110         sdma_dumpstate_helper(SD(CHECK_OPCODE));
2111 }
2112 #endif
2113
2114 static void dump_sdma_state(struct sdma_engine *sde)
2115 {
2116         struct hw_sdma_desc *descq;
2117         struct hw_sdma_desc *descqp;
2118         u64 desc[2];
2119         u64 addr;
2120         u8 gen;
2121         u16 len;
2122         u16 head, tail, cnt;
2123
2124         head = sde->descq_head & sde->sdma_mask;
2125         tail = sde->descq_tail & sde->sdma_mask;
2126         cnt = sdma_descq_freecnt(sde);
2127         descq = sde->descq;
2128
2129         dd_dev_err(sde->dd,
2130                    "SDMA (%u) descq_head: %u descq_tail: %u freecnt: %u FLE %d\n",
2131                    sde->this_idx, head, tail, cnt,
2132                    !list_empty(&sde->flushlist));
2133
2134         /* print info for each entry in the descriptor queue */
2135         while (head != tail) {
2136                 char flags[6] = { 'x', 'x', 'x', 'x', 0 };
2137
2138                 descqp = &sde->descq[head];
2139                 desc[0] = le64_to_cpu(descqp->qw[0]);
2140                 desc[1] = le64_to_cpu(descqp->qw[1]);
2141                 flags[0] = (desc[1] & SDMA_DESC1_INT_REQ_FLAG) ? 'I' : '-';
2142                 flags[1] = (desc[1] & SDMA_DESC1_HEAD_TO_HOST_FLAG) ?
2143                                 'H' : '-';
2144                 flags[2] = (desc[0] & SDMA_DESC0_FIRST_DESC_FLAG) ? 'F' : '-';
2145                 flags[3] = (desc[0] & SDMA_DESC0_LAST_DESC_FLAG) ? 'L' : '-';
2146                 addr = (desc[0] >> SDMA_DESC0_PHY_ADDR_SHIFT)
2147                         & SDMA_DESC0_PHY_ADDR_MASK;
2148                 gen = (desc[1] >> SDMA_DESC1_GENERATION_SHIFT)
2149                         & SDMA_DESC1_GENERATION_MASK;
2150                 len = (desc[0] >> SDMA_DESC0_BYTE_COUNT_SHIFT)
2151                         & SDMA_DESC0_BYTE_COUNT_MASK;
2152                 dd_dev_err(sde->dd,
2153                            "SDMA sdmadesc[%u]: flags:%s addr:0x%016llx gen:%u len:%u bytes\n",
2154                            head, flags, addr, gen, len);
2155                 dd_dev_err(sde->dd,
2156                            "\tdesc0:0x%016llx desc1 0x%016llx\n",
2157                            desc[0], desc[1]);
2158                 if (desc[0] & SDMA_DESC0_FIRST_DESC_FLAG)
2159                         dd_dev_err(sde->dd,
2160                                    "\taidx: %u amode: %u alen: %u\n",
2161                                    (u8)((desc[1] &
2162                                          SDMA_DESC1_HEADER_INDEX_SMASK) >>
2163                                         SDMA_DESC1_HEADER_INDEX_SHIFT),
2164                                    (u8)((desc[1] &
2165                                          SDMA_DESC1_HEADER_MODE_SMASK) >>
2166                                         SDMA_DESC1_HEADER_MODE_SHIFT),
2167                                    (u8)((desc[1] &
2168                                          SDMA_DESC1_HEADER_DWS_SMASK) >>
2169                                         SDMA_DESC1_HEADER_DWS_SHIFT));
2170                 head++;
2171                 head &= sde->sdma_mask;
2172         }
2173 }
2174
2175 #define SDE_FMT \
2176         "SDE %u CPU %d STE %s C 0x%llx S 0x%016llx E 0x%llx T(HW) 0x%llx T(SW) 0x%x H(HW) 0x%llx H(SW) 0x%x H(D) 0x%llx DM 0x%llx GL 0x%llx R 0x%llx LIS 0x%llx AHGI 0x%llx TXT %u TXH %u DT %u DH %u FLNE %d DQF %u SLC 0x%llx\n"
2177 /**
2178  * sdma_seqfile_dump_sde() - debugfs dump of sde
2179  * @s: seq file
2180  * @sde: send dma engine to dump
2181  *
2182  * This routine dumps the sde to the indicated seq file.
2183  */
2184 void sdma_seqfile_dump_sde(struct seq_file *s, struct sdma_engine *sde)
2185 {
2186         u16 head, tail;
2187         struct hw_sdma_desc *descqp;
2188         u64 desc[2];
2189         u64 addr;
2190         u8 gen;
2191         u16 len;
2192
2193         head = sde->descq_head & sde->sdma_mask;
2194         tail = ACCESS_ONCE(sde->descq_tail) & sde->sdma_mask;
2195         seq_printf(s, SDE_FMT, sde->this_idx,
2196                    sde->cpu,
2197                    sdma_state_name(sde->state.current_state),
2198                    (unsigned long long)read_sde_csr(sde, SD(CTRL)),
2199                    (unsigned long long)read_sde_csr(sde, SD(STATUS)),
2200                    (unsigned long long)read_sde_csr(sde, SD(ENG_ERR_STATUS)),
2201                    (unsigned long long)read_sde_csr(sde, SD(TAIL)), tail,
2202                    (unsigned long long)read_sde_csr(sde, SD(HEAD)), head,
2203                    (unsigned long long)le64_to_cpu(*sde->head_dma),
2204                    (unsigned long long)read_sde_csr(sde, SD(MEMORY)),
2205                    (unsigned long long)read_sde_csr(sde, SD(LEN_GEN)),
2206                    (unsigned long long)read_sde_csr(sde, SD(RELOAD_CNT)),
2207                    (unsigned long long)sde->last_status,
2208                    (unsigned long long)sde->ahg_bits,
2209                    sde->tx_tail,
2210                    sde->tx_head,
2211                    sde->descq_tail,
2212                    sde->descq_head,
2213                    !list_empty(&sde->flushlist),
2214                    sde->descq_full_count,
2215                    (unsigned long long)read_sde_csr(sde, SEND_DMA_CHECK_SLID));
2216
2217         /* print info for each entry in the descriptor queue */
2218         while (head != tail) {
2219                 char flags[6] = { 'x', 'x', 'x', 'x', 0 };
2220
2221                 descqp = &sde->descq[head];
2222                 desc[0] = le64_to_cpu(descqp->qw[0]);
2223                 desc[1] = le64_to_cpu(descqp->qw[1]);
2224                 flags[0] = (desc[1] & SDMA_DESC1_INT_REQ_FLAG) ? 'I' : '-';
2225                 flags[1] = (desc[1] & SDMA_DESC1_HEAD_TO_HOST_FLAG) ?
2226                                 'H' : '-';
2227                 flags[2] = (desc[0] & SDMA_DESC0_FIRST_DESC_FLAG) ? 'F' : '-';
2228                 flags[3] = (desc[0] & SDMA_DESC0_LAST_DESC_FLAG) ? 'L' : '-';
2229                 addr = (desc[0] >> SDMA_DESC0_PHY_ADDR_SHIFT)
2230                         & SDMA_DESC0_PHY_ADDR_MASK;
2231                 gen = (desc[1] >> SDMA_DESC1_GENERATION_SHIFT)
2232                         & SDMA_DESC1_GENERATION_MASK;
2233                 len = (desc[0] >> SDMA_DESC0_BYTE_COUNT_SHIFT)
2234                         & SDMA_DESC0_BYTE_COUNT_MASK;
2235                 seq_printf(s,
2236                            "\tdesc[%u]: flags:%s addr:0x%016llx gen:%u len:%u bytes\n",
2237                            head, flags, addr, gen, len);
2238                 if (desc[0] & SDMA_DESC0_FIRST_DESC_FLAG)
2239                         seq_printf(s, "\t\tahgidx: %u ahgmode: %u\n",
2240                                    (u8)((desc[1] &
2241                                          SDMA_DESC1_HEADER_INDEX_SMASK) >>
2242                                         SDMA_DESC1_HEADER_INDEX_SHIFT),
2243                                    (u8)((desc[1] &
2244                                          SDMA_DESC1_HEADER_MODE_SMASK) >>
2245                                         SDMA_DESC1_HEADER_MODE_SHIFT));
2246                 head = (head + 1) & sde->sdma_mask;
2247         }
2248 }
2249
2250 /*
2251  * add the generation number into
2252  * the qw1 and return
2253  */
2254 static inline u64 add_gen(struct sdma_engine *sde, u64 qw1)
2255 {
2256         u8 generation = (sde->descq_tail >> sde->sdma_shift) & 3;
2257
2258         qw1 &= ~SDMA_DESC1_GENERATION_SMASK;
2259         qw1 |= ((u64)generation & SDMA_DESC1_GENERATION_MASK)
2260                         << SDMA_DESC1_GENERATION_SHIFT;
2261         return qw1;
2262 }
2263
2264 /*
2265  * This routine submits the indicated tx
2266  *
2267  * Space has already been guaranteed and
2268  * tail side of ring is locked.
2269  *
2270  * The hardware tail update is done
2271  * in the caller and that is facilitated
2272  * by returning the new tail.
2273  *
2274  * There is special case logic for ahg
2275  * to not add the generation number for
2276  * up to 2 descriptors that follow the
2277  * first descriptor.
2278  *
2279  */
2280 static inline u16 submit_tx(struct sdma_engine *sde, struct sdma_txreq *tx)
2281 {
2282         int i;
2283         u16 tail;
2284         struct sdma_desc *descp = tx->descp;
2285         u8 skip = 0, mode = ahg_mode(tx);
2286
2287         tail = sde->descq_tail & sde->sdma_mask;
2288         sde->descq[tail].qw[0] = cpu_to_le64(descp->qw[0]);
2289         sde->descq[tail].qw[1] = cpu_to_le64(add_gen(sde, descp->qw[1]));
2290         trace_hfi1_sdma_descriptor(sde, descp->qw[0], descp->qw[1],
2291                                    tail, &sde->descq[tail]);
2292         tail = ++sde->descq_tail & sde->sdma_mask;
2293         descp++;
2294         if (mode > SDMA_AHG_APPLY_UPDATE1)
2295                 skip = mode >> 1;
2296         for (i = 1; i < tx->num_desc; i++, descp++) {
2297                 u64 qw1;
2298
2299                 sde->descq[tail].qw[0] = cpu_to_le64(descp->qw[0]);
2300                 if (skip) {
2301                         /* edits don't have generation */
2302                         qw1 = descp->qw[1];
2303                         skip--;
2304                 } else {
2305                         /* replace generation with real one for non-edits */
2306                         qw1 = add_gen(sde, descp->qw[1]);
2307                 }
2308                 sde->descq[tail].qw[1] = cpu_to_le64(qw1);
2309                 trace_hfi1_sdma_descriptor(sde, descp->qw[0], qw1,
2310                                            tail, &sde->descq[tail]);
2311                 tail = ++sde->descq_tail & sde->sdma_mask;
2312         }
2313         tx->next_descq_idx = tail;
2314 #ifdef CONFIG_HFI1_DEBUG_SDMA_ORDER
2315         tx->sn = sde->tail_sn++;
2316         trace_hfi1_sdma_in_sn(sde, tx->sn);
2317         WARN_ON_ONCE(sde->tx_ring[sde->tx_tail & sde->sdma_mask]);
2318 #endif
2319         sde->tx_ring[sde->tx_tail++ & sde->sdma_mask] = tx;
2320         sde->desc_avail -= tx->num_desc;
2321         return tail;
2322 }
2323
2324 /*
2325  * Check for progress
2326  */
2327 static int sdma_check_progress(
2328         struct sdma_engine *sde,
2329         struct iowait *wait,
2330         struct sdma_txreq *tx)
2331 {
2332         int ret;
2333
2334         sde->desc_avail = sdma_descq_freecnt(sde);
2335         if (tx->num_desc <= sde->desc_avail)
2336                 return -EAGAIN;
2337         /* pulse the head_lock */
2338         if (wait && wait->sleep) {
2339                 unsigned seq;
2340
2341                 seq = raw_seqcount_begin(
2342                         (const seqcount_t *)&sde->head_lock.seqcount);
2343                 ret = wait->sleep(sde, wait, tx, seq);
2344                 if (ret == -EAGAIN)
2345                         sde->desc_avail = sdma_descq_freecnt(sde);
2346         } else {
2347                 ret = -EBUSY;
2348         }
2349         return ret;
2350 }
2351
2352 /**
2353  * sdma_send_txreq() - submit a tx req to ring
2354  * @sde: sdma engine to use
2355  * @wait: wait structure to use when full (may be NULL)
2356  * @tx: sdma_txreq to submit
2357  *
2358  * The call submits the tx into the ring.  If a iowait structure is non-NULL
2359  * the packet will be queued to the list in wait.
2360  *
2361  * Return:
2362  * 0 - Success, -EINVAL - sdma_txreq incomplete, -EBUSY - no space in
2363  * ring (wait == NULL)
2364  * -EIOCBQUEUED - tx queued to iowait, -ECOMM bad sdma state
2365  */
2366 int sdma_send_txreq(struct sdma_engine *sde,
2367                     struct iowait *wait,
2368                     struct sdma_txreq *tx)
2369 {
2370         int ret = 0;
2371         u16 tail;
2372         unsigned long flags;
2373
2374         /* user should have supplied entire packet */
2375         if (unlikely(tx->tlen))
2376                 return -EINVAL;
2377         tx->wait = wait;
2378         spin_lock_irqsave(&sde->tail_lock, flags);
2379 retry:
2380         if (unlikely(!__sdma_running(sde)))
2381                 goto unlock_noconn;
2382         if (unlikely(tx->num_desc > sde->desc_avail))
2383                 goto nodesc;
2384         tail = submit_tx(sde, tx);
2385         if (wait)
2386                 iowait_sdma_inc(wait);
2387         sdma_update_tail(sde, tail);
2388 unlock:
2389         spin_unlock_irqrestore(&sde->tail_lock, flags);
2390         return ret;
2391 unlock_noconn:
2392         if (wait)
2393                 iowait_sdma_inc(wait);
2394         tx->next_descq_idx = 0;
2395 #ifdef CONFIG_HFI1_DEBUG_SDMA_ORDER
2396         tx->sn = sde->tail_sn++;
2397         trace_hfi1_sdma_in_sn(sde, tx->sn);
2398 #endif
2399         spin_lock(&sde->flushlist_lock);
2400         list_add_tail(&tx->list, &sde->flushlist);
2401         spin_unlock(&sde->flushlist_lock);
2402         if (wait) {
2403                 wait->tx_count++;
2404                 wait->count += tx->num_desc;
2405         }
2406         queue_work_on(sde->cpu, system_highpri_wq, &sde->flush_worker);
2407         ret = -ECOMM;
2408         goto unlock;
2409 nodesc:
2410         ret = sdma_check_progress(sde, wait, tx);
2411         if (ret == -EAGAIN) {
2412                 ret = 0;
2413                 goto retry;
2414         }
2415         sde->descq_full_count++;
2416         goto unlock;
2417 }
2418
2419 /**
2420  * sdma_send_txlist() - submit a list of tx req to ring
2421  * @sde: sdma engine to use
2422  * @wait: wait structure to use when full (may be NULL)
2423  * @tx_list: list of sdma_txreqs to submit
2424  * @count: pointer to a u32 which, after return will contain the total number of
2425  *         sdma_txreqs removed from the tx_list. This will include sdma_txreqs
2426  *         whose SDMA descriptors are submitted to the ring and the sdma_txreqs
2427  *         which are added to SDMA engine flush list if the SDMA engine state is
2428  *         not running.
2429  *
2430  * The call submits the list into the ring.
2431  *
2432  * If the iowait structure is non-NULL and not equal to the iowait list
2433  * the unprocessed part of the list  will be appended to the list in wait.
2434  *
2435  * In all cases, the tx_list will be updated so the head of the tx_list is
2436  * the list of descriptors that have yet to be transmitted.
2437  *
2438  * The intent of this call is to provide a more efficient
2439  * way of submitting multiple packets to SDMA while holding the tail
2440  * side locking.
2441  *
2442  * Return:
2443  * 0 - Success,
2444  * -EINVAL - sdma_txreq incomplete, -EBUSY - no space in ring (wait == NULL)
2445  * -EIOCBQUEUED - tx queued to iowait, -ECOMM bad sdma state
2446  */
2447 int sdma_send_txlist(struct sdma_engine *sde, struct iowait *wait,
2448                      struct list_head *tx_list, u32 *count_out)
2449 {
2450         struct sdma_txreq *tx, *tx_next;
2451         int ret = 0;
2452         unsigned long flags;
2453         u16 tail = INVALID_TAIL;
2454         u32 submit_count = 0, flush_count = 0, total_count;
2455
2456         spin_lock_irqsave(&sde->tail_lock, flags);
2457 retry:
2458         list_for_each_entry_safe(tx, tx_next, tx_list, list) {
2459                 tx->wait = wait;
2460                 if (unlikely(!__sdma_running(sde)))
2461                         goto unlock_noconn;
2462                 if (unlikely(tx->num_desc > sde->desc_avail))
2463                         goto nodesc;
2464                 if (unlikely(tx->tlen)) {
2465                         ret = -EINVAL;
2466                         goto update_tail;
2467                 }
2468                 list_del_init(&tx->list);
2469                 tail = submit_tx(sde, tx);
2470                 submit_count++;
2471                 if (tail != INVALID_TAIL &&
2472                     (submit_count & SDMA_TAIL_UPDATE_THRESH) == 0) {
2473                         sdma_update_tail(sde, tail);
2474                         tail = INVALID_TAIL;
2475                 }
2476         }
2477 update_tail:
2478         total_count = submit_count + flush_count;
2479         if (wait)
2480                 iowait_sdma_add(wait, total_count);
2481         if (tail != INVALID_TAIL)
2482                 sdma_update_tail(sde, tail);
2483         spin_unlock_irqrestore(&sde->tail_lock, flags);
2484         *count_out = total_count;
2485         return ret;
2486 unlock_noconn:
2487         spin_lock(&sde->flushlist_lock);
2488         list_for_each_entry_safe(tx, tx_next, tx_list, list) {
2489                 tx->wait = wait;
2490                 list_del_init(&tx->list);
2491                 tx->next_descq_idx = 0;
2492 #ifdef CONFIG_HFI1_DEBUG_SDMA_ORDER
2493                 tx->sn = sde->tail_sn++;
2494                 trace_hfi1_sdma_in_sn(sde, tx->sn);
2495 #endif
2496                 list_add_tail(&tx->list, &sde->flushlist);
2497                 flush_count++;
2498                 if (wait) {
2499                         wait->tx_count++;
2500                         wait->count += tx->num_desc;
2501                 }
2502         }
2503         spin_unlock(&sde->flushlist_lock);
2504         queue_work_on(sde->cpu, system_highpri_wq, &sde->flush_worker);
2505         ret = -ECOMM;
2506         goto update_tail;
2507 nodesc:
2508         ret = sdma_check_progress(sde, wait, tx);
2509         if (ret == -EAGAIN) {
2510                 ret = 0;
2511                 goto retry;
2512         }
2513         sde->descq_full_count++;
2514         goto update_tail;
2515 }
2516
2517 static void sdma_process_event(struct sdma_engine *sde, enum sdma_events event)
2518 {
2519         unsigned long flags;
2520
2521         spin_lock_irqsave(&sde->tail_lock, flags);
2522         write_seqlock(&sde->head_lock);
2523
2524         __sdma_process_event(sde, event);
2525
2526         if (sde->state.current_state == sdma_state_s99_running)
2527                 sdma_desc_avail(sde, sdma_descq_freecnt(sde));
2528
2529         write_sequnlock(&sde->head_lock);
2530         spin_unlock_irqrestore(&sde->tail_lock, flags);
2531 }
2532
2533 static void __sdma_process_event(struct sdma_engine *sde,
2534                                  enum sdma_events event)
2535 {
2536         struct sdma_state *ss = &sde->state;
2537         int need_progress = 0;
2538
2539         /* CONFIG SDMA temporary */
2540 #ifdef CONFIG_SDMA_VERBOSITY
2541         dd_dev_err(sde->dd, "CONFIG SDMA(%u) [%s] %s\n", sde->this_idx,
2542                    sdma_state_names[ss->current_state],
2543                    sdma_event_names[event]);
2544 #endif
2545
2546         switch (ss->current_state) {
2547         case sdma_state_s00_hw_down:
2548                 switch (event) {
2549                 case sdma_event_e00_go_hw_down:
2550                         break;
2551                 case sdma_event_e30_go_running:
2552                         /*
2553                          * If down, but running requested (usually result
2554                          * of link up, then we need to start up.
2555                          * This can happen when hw down is requested while
2556                          * bringing the link up with traffic active on
2557                          * 7220, e.g.
2558                          */
2559                         ss->go_s99_running = 1;
2560                         /* fall through and start dma engine */
2561                 case sdma_event_e10_go_hw_start:
2562                         /* This reference means the state machine is started */
2563                         sdma_get(&sde->state);
2564                         sdma_set_state(sde,
2565                                        sdma_state_s10_hw_start_up_halt_wait);
2566                         break;
2567                 case sdma_event_e15_hw_halt_done:
2568                         break;
2569                 case sdma_event_e25_hw_clean_up_done:
2570                         break;
2571                 case sdma_event_e40_sw_cleaned:
2572                         sdma_sw_tear_down(sde);
2573                         break;
2574                 case sdma_event_e50_hw_cleaned:
2575                         break;
2576                 case sdma_event_e60_hw_halted:
2577                         break;
2578                 case sdma_event_e70_go_idle:
2579                         break;
2580                 case sdma_event_e80_hw_freeze:
2581                         break;
2582                 case sdma_event_e81_hw_frozen:
2583                         break;
2584                 case sdma_event_e82_hw_unfreeze:
2585                         break;
2586                 case sdma_event_e85_link_down:
2587                         break;
2588                 case sdma_event_e90_sw_halted:
2589                         break;
2590                 }
2591                 break;
2592
2593         case sdma_state_s10_hw_start_up_halt_wait:
2594                 switch (event) {
2595                 case sdma_event_e00_go_hw_down:
2596                         sdma_set_state(sde, sdma_state_s00_hw_down);
2597                         sdma_sw_tear_down(sde);
2598                         break;
2599                 case sdma_event_e10_go_hw_start:
2600                         break;
2601                 case sdma_event_e15_hw_halt_done:
2602                         sdma_set_state(sde,
2603                                        sdma_state_s15_hw_start_up_clean_wait);
2604                         sdma_start_hw_clean_up(sde);
2605                         break;
2606                 case sdma_event_e25_hw_clean_up_done:
2607                         break;
2608                 case sdma_event_e30_go_running:
2609                         ss->go_s99_running = 1;
2610                         break;
2611                 case sdma_event_e40_sw_cleaned:
2612                         break;
2613                 case sdma_event_e50_hw_cleaned:
2614                         break;
2615                 case sdma_event_e60_hw_halted:
2616                         schedule_work(&sde->err_halt_worker);
2617                         break;
2618                 case sdma_event_e70_go_idle:
2619                         ss->go_s99_running = 0;
2620                         break;
2621                 case sdma_event_e80_hw_freeze:
2622                         break;
2623                 case sdma_event_e81_hw_frozen:
2624                         break;
2625                 case sdma_event_e82_hw_unfreeze:
2626                         break;
2627                 case sdma_event_e85_link_down:
2628                         break;
2629                 case sdma_event_e90_sw_halted:
2630                         break;
2631                 }
2632                 break;
2633
2634         case sdma_state_s15_hw_start_up_clean_wait:
2635                 switch (event) {
2636                 case sdma_event_e00_go_hw_down:
2637                         sdma_set_state(sde, sdma_state_s00_hw_down);
2638                         sdma_sw_tear_down(sde);
2639                         break;
2640                 case sdma_event_e10_go_hw_start:
2641                         break;
2642                 case sdma_event_e15_hw_halt_done:
2643                         break;
2644                 case sdma_event_e25_hw_clean_up_done:
2645                         sdma_hw_start_up(sde);
2646                         sdma_set_state(sde, ss->go_s99_running ?
2647                                        sdma_state_s99_running :
2648                                        sdma_state_s20_idle);
2649                         break;
2650                 case sdma_event_e30_go_running:
2651                         ss->go_s99_running = 1;
2652                         break;
2653                 case sdma_event_e40_sw_cleaned:
2654                         break;
2655                 case sdma_event_e50_hw_cleaned:
2656                         break;
2657                 case sdma_event_e60_hw_halted:
2658                         break;
2659                 case sdma_event_e70_go_idle:
2660                         ss->go_s99_running = 0;
2661                         break;
2662                 case sdma_event_e80_hw_freeze:
2663                         break;
2664                 case sdma_event_e81_hw_frozen:
2665                         break;
2666                 case sdma_event_e82_hw_unfreeze:
2667                         break;
2668                 case sdma_event_e85_link_down:
2669                         break;
2670                 case sdma_event_e90_sw_halted:
2671                         break;
2672                 }
2673                 break;
2674
2675         case sdma_state_s20_idle:
2676                 switch (event) {
2677                 case sdma_event_e00_go_hw_down:
2678                         sdma_set_state(sde, sdma_state_s00_hw_down);
2679                         sdma_sw_tear_down(sde);
2680                         break;
2681                 case sdma_event_e10_go_hw_start:
2682                         break;
2683                 case sdma_event_e15_hw_halt_done:
2684                         break;
2685                 case sdma_event_e25_hw_clean_up_done:
2686                         break;
2687                 case sdma_event_e30_go_running:
2688                         sdma_set_state(sde, sdma_state_s99_running);
2689                         ss->go_s99_running = 1;
2690                         break;
2691                 case sdma_event_e40_sw_cleaned:
2692                         break;
2693                 case sdma_event_e50_hw_cleaned:
2694                         break;
2695                 case sdma_event_e60_hw_halted:
2696                         sdma_set_state(sde, sdma_state_s50_hw_halt_wait);
2697                         schedule_work(&sde->err_halt_worker);
2698                         break;
2699                 case sdma_event_e70_go_idle:
2700                         break;
2701                 case sdma_event_e85_link_down:
2702                         /* fall through */
2703                 case sdma_event_e80_hw_freeze:
2704                         sdma_set_state(sde, sdma_state_s80_hw_freeze);
2705                         atomic_dec(&sde->dd->sdma_unfreeze_count);
2706                         wake_up_interruptible(&sde->dd->sdma_unfreeze_wq);
2707                         break;
2708                 case sdma_event_e81_hw_frozen:
2709                         break;
2710                 case sdma_event_e82_hw_unfreeze:
2711                         break;
2712                 case sdma_event_e90_sw_halted:
2713                         break;
2714                 }
2715                 break;
2716
2717         case sdma_state_s30_sw_clean_up_wait:
2718                 switch (event) {
2719                 case sdma_event_e00_go_hw_down:
2720                         sdma_set_state(sde, sdma_state_s00_hw_down);
2721                         break;
2722                 case sdma_event_e10_go_hw_start:
2723                         break;
2724                 case sdma_event_e15_hw_halt_done:
2725                         break;
2726                 case sdma_event_e25_hw_clean_up_done:
2727                         break;
2728                 case sdma_event_e30_go_running:
2729                         ss->go_s99_running = 1;
2730                         break;
2731                 case sdma_event_e40_sw_cleaned:
2732                         sdma_set_state(sde, sdma_state_s40_hw_clean_up_wait);
2733                         sdma_start_hw_clean_up(sde);
2734                         break;
2735                 case sdma_event_e50_hw_cleaned:
2736                         break;
2737                 case sdma_event_e60_hw_halted:
2738                         break;
2739                 case sdma_event_e70_go_idle:
2740                         ss->go_s99_running = 0;
2741                         break;
2742                 case sdma_event_e80_hw_freeze:
2743                         break;
2744                 case sdma_event_e81_hw_frozen:
2745                         break;
2746                 case sdma_event_e82_hw_unfreeze:
2747                         break;
2748                 case sdma_event_e85_link_down:
2749                         ss->go_s99_running = 0;
2750                         break;
2751                 case sdma_event_e90_sw_halted:
2752                         break;
2753                 }
2754                 break;
2755
2756         case sdma_state_s40_hw_clean_up_wait:
2757                 switch (event) {
2758                 case sdma_event_e00_go_hw_down:
2759                         sdma_set_state(sde, sdma_state_s00_hw_down);
2760                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2761                         break;
2762                 case sdma_event_e10_go_hw_start:
2763                         break;
2764                 case sdma_event_e15_hw_halt_done:
2765                         break;
2766                 case sdma_event_e25_hw_clean_up_done:
2767                         sdma_hw_start_up(sde);
2768                         sdma_set_state(sde, ss->go_s99_running ?
2769                                        sdma_state_s99_running :
2770                                        sdma_state_s20_idle);
2771                         break;
2772                 case sdma_event_e30_go_running:
2773                         ss->go_s99_running = 1;
2774                         break;
2775                 case sdma_event_e40_sw_cleaned:
2776                         break;
2777                 case sdma_event_e50_hw_cleaned:
2778                         break;
2779                 case sdma_event_e60_hw_halted:
2780                         break;
2781                 case sdma_event_e70_go_idle:
2782                         ss->go_s99_running = 0;
2783                         break;
2784                 case sdma_event_e80_hw_freeze:
2785                         break;
2786                 case sdma_event_e81_hw_frozen:
2787                         break;
2788                 case sdma_event_e82_hw_unfreeze:
2789                         break;
2790                 case sdma_event_e85_link_down:
2791                         ss->go_s99_running = 0;
2792                         break;
2793                 case sdma_event_e90_sw_halted:
2794                         break;
2795                 }
2796                 break;
2797
2798         case sdma_state_s50_hw_halt_wait:
2799                 switch (event) {
2800                 case sdma_event_e00_go_hw_down:
2801                         sdma_set_state(sde, sdma_state_s00_hw_down);
2802                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2803                         break;
2804                 case sdma_event_e10_go_hw_start:
2805                         break;
2806                 case sdma_event_e15_hw_halt_done:
2807                         sdma_set_state(sde, sdma_state_s30_sw_clean_up_wait);
2808                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2809                         break;
2810                 case sdma_event_e25_hw_clean_up_done:
2811                         break;
2812                 case sdma_event_e30_go_running:
2813                         ss->go_s99_running = 1;
2814                         break;
2815                 case sdma_event_e40_sw_cleaned:
2816                         break;
2817                 case sdma_event_e50_hw_cleaned:
2818                         break;
2819                 case sdma_event_e60_hw_halted:
2820                         schedule_work(&sde->err_halt_worker);
2821                         break;
2822                 case sdma_event_e70_go_idle:
2823                         ss->go_s99_running = 0;
2824                         break;
2825                 case sdma_event_e80_hw_freeze:
2826                         break;
2827                 case sdma_event_e81_hw_frozen:
2828                         break;
2829                 case sdma_event_e82_hw_unfreeze:
2830                         break;
2831                 case sdma_event_e85_link_down:
2832                         ss->go_s99_running = 0;
2833                         break;
2834                 case sdma_event_e90_sw_halted:
2835                         break;
2836                 }
2837                 break;
2838
2839         case sdma_state_s60_idle_halt_wait:
2840                 switch (event) {
2841                 case sdma_event_e00_go_hw_down:
2842                         sdma_set_state(sde, sdma_state_s00_hw_down);
2843                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2844                         break;
2845                 case sdma_event_e10_go_hw_start:
2846                         break;
2847                 case sdma_event_e15_hw_halt_done:
2848                         sdma_set_state(sde, sdma_state_s30_sw_clean_up_wait);
2849                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2850                         break;
2851                 case sdma_event_e25_hw_clean_up_done:
2852                         break;
2853                 case sdma_event_e30_go_running:
2854                         ss->go_s99_running = 1;
2855                         break;
2856                 case sdma_event_e40_sw_cleaned:
2857                         break;
2858                 case sdma_event_e50_hw_cleaned:
2859                         break;
2860                 case sdma_event_e60_hw_halted:
2861                         schedule_work(&sde->err_halt_worker);
2862                         break;
2863                 case sdma_event_e70_go_idle:
2864                         ss->go_s99_running = 0;
2865                         break;
2866                 case sdma_event_e80_hw_freeze:
2867                         break;
2868                 case sdma_event_e81_hw_frozen:
2869                         break;
2870                 case sdma_event_e82_hw_unfreeze:
2871                         break;
2872                 case sdma_event_e85_link_down:
2873                         break;
2874                 case sdma_event_e90_sw_halted:
2875                         break;
2876                 }
2877                 break;
2878
2879         case sdma_state_s80_hw_freeze:
2880                 switch (event) {
2881                 case sdma_event_e00_go_hw_down:
2882                         sdma_set_state(sde, sdma_state_s00_hw_down);
2883                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2884                         break;
2885                 case sdma_event_e10_go_hw_start:
2886                         break;
2887                 case sdma_event_e15_hw_halt_done:
2888                         break;
2889                 case sdma_event_e25_hw_clean_up_done:
2890                         break;
2891                 case sdma_event_e30_go_running:
2892                         ss->go_s99_running = 1;
2893                         break;
2894                 case sdma_event_e40_sw_cleaned:
2895                         break;
2896                 case sdma_event_e50_hw_cleaned:
2897                         break;
2898                 case sdma_event_e60_hw_halted:
2899                         break;
2900                 case sdma_event_e70_go_idle:
2901                         ss->go_s99_running = 0;
2902                         break;
2903                 case sdma_event_e80_hw_freeze:
2904                         break;
2905                 case sdma_event_e81_hw_frozen:
2906                         sdma_set_state(sde, sdma_state_s82_freeze_sw_clean);
2907                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2908                         break;
2909                 case sdma_event_e82_hw_unfreeze:
2910                         break;
2911                 case sdma_event_e85_link_down:
2912                         break;
2913                 case sdma_event_e90_sw_halted:
2914                         break;
2915                 }
2916                 break;
2917
2918         case sdma_state_s82_freeze_sw_clean:
2919                 switch (event) {
2920                 case sdma_event_e00_go_hw_down:
2921                         sdma_set_state(sde, sdma_state_s00_hw_down);
2922                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2923                         break;
2924                 case sdma_event_e10_go_hw_start:
2925                         break;
2926                 case sdma_event_e15_hw_halt_done:
2927                         break;
2928                 case sdma_event_e25_hw_clean_up_done:
2929                         break;
2930                 case sdma_event_e30_go_running:
2931                         ss->go_s99_running = 1;
2932                         break;
2933                 case sdma_event_e40_sw_cleaned:
2934                         /* notify caller this engine is done cleaning */
2935                         atomic_dec(&sde->dd->sdma_unfreeze_count);
2936                         wake_up_interruptible(&sde->dd->sdma_unfreeze_wq);
2937                         break;
2938                 case sdma_event_e50_hw_cleaned:
2939                         break;
2940                 case sdma_event_e60_hw_halted:
2941                         break;
2942                 case sdma_event_e70_go_idle:
2943                         ss->go_s99_running = 0;
2944                         break;
2945                 case sdma_event_e80_hw_freeze:
2946                         break;
2947                 case sdma_event_e81_hw_frozen:
2948                         break;
2949                 case sdma_event_e82_hw_unfreeze:
2950                         sdma_hw_start_up(sde);
2951                         sdma_set_state(sde, ss->go_s99_running ?
2952                                        sdma_state_s99_running :
2953                                        sdma_state_s20_idle);
2954                         break;
2955                 case sdma_event_e85_link_down:
2956                         break;
2957                 case sdma_event_e90_sw_halted:
2958                         break;
2959                 }
2960                 break;
2961
2962         case sdma_state_s99_running:
2963                 switch (event) {
2964                 case sdma_event_e00_go_hw_down:
2965                         sdma_set_state(sde, sdma_state_s00_hw_down);
2966                         tasklet_hi_schedule(&sde->sdma_sw_clean_up_task);
2967                         break;
2968                 case sdma_event_e10_go_hw_start:
2969                         break;
2970                 case sdma_event_e15_hw_halt_done:
2971                         break;
2972                 case sdma_event_e25_hw_clean_up_done:
2973                         break;
2974                 case sdma_event_e30_go_running:
2975                         break;
2976                 case sdma_event_e40_sw_cleaned:
2977                         break;
2978                 case sdma_event_e50_hw_cleaned:
2979                         break;
2980                 case sdma_event_e60_hw_halted:
2981                         need_progress = 1;
2982                         sdma_err_progress_check_schedule(sde);
2983                 case sdma_event_e90_sw_halted:
2984                         /*
2985                         * SW initiated halt does not perform engines
2986                         * progress check
2987                         */
2988                         sdma_set_state(sde, sdma_state_s50_hw_halt_wait);
2989                         schedule_work(&sde->err_halt_worker);
2990                         break;
2991                 case sdma_event_e70_go_idle:
2992                         sdma_set_state(sde, sdma_state_s60_idle_halt_wait);
2993                         break;
2994                 case sdma_event_e85_link_down:
2995                         ss->go_s99_running = 0;
2996                         /* fall through */
2997                 case sdma_event_e80_hw_freeze:
2998                         sdma_set_state(sde, sdma_state_s80_hw_freeze);
2999                         atomic_dec(&sde->dd->sdma_unfreeze_count);
3000                         wake_up_interruptible(&sde->dd->sdma_unfreeze_wq);
3001                         break;
3002                 case sdma_event_e81_hw_frozen:
3003                         break;
3004                 case sdma_event_e82_hw_unfreeze:
3005                         break;
3006                 }
3007                 break;
3008         }
3009
3010         ss->last_event = event;
3011         if (need_progress)
3012                 sdma_make_progress(sde, 0);
3013 }
3014
3015 /*
3016  * _extend_sdma_tx_descs() - helper to extend txreq
3017  *
3018  * This is called once the initial nominal allocation
3019  * of descriptors in the sdma_txreq is exhausted.
3020  *
3021  * The code will bump the allocation up to the max
3022  * of MAX_DESC (64) descriptors. There doesn't seem
3023  * much point in an interim step. The last descriptor
3024  * is reserved for coalesce buffer in order to support
3025  * cases where input packet has >MAX_DESC iovecs.
3026  *
3027  */
3028 static int _extend_sdma_tx_descs(struct hfi1_devdata *dd, struct sdma_txreq *tx)
3029 {
3030         int i;
3031         struct sdma_desc *descp;
3032
3033         /* Handle last descriptor */
3034         if (unlikely((tx->num_desc == (MAX_DESC - 1)))) {
3035                 /* if tlen is 0, it is for padding, release last descriptor */
3036                 if (!tx->tlen) {
3037                         tx->desc_limit = MAX_DESC;
3038                 } else if (!tx->coalesce_buf) {
3039                         /* allocate coalesce buffer with space for padding */
3040                         tx->coalesce_buf = kmalloc(tx->tlen + sizeof(u32),
3041                                                    GFP_ATOMIC);
3042                         if (!tx->coalesce_buf)
3043                                 goto enomem;
3044                         tx->coalesce_idx = 0;
3045                 }
3046                 return 0;
3047         }
3048
3049         if (unlikely(tx->num_desc == MAX_DESC))
3050                 goto enomem;
3051
3052         descp = kmalloc_array(MAX_DESC, sizeof(struct sdma_desc), GFP_ATOMIC);
3053         if (!descp)
3054                 goto enomem;
3055         tx->descp = descp;
3056
3057         /* reserve last descriptor for coalescing */
3058         tx->desc_limit = MAX_DESC - 1;
3059         /* copy ones already built */
3060         for (i = 0; i < tx->num_desc; i++)
3061                 tx->descp[i] = tx->descs[i];
3062         return 0;
3063 enomem:
3064         sdma_txclean(dd, tx);
3065         return -ENOMEM;
3066 }
3067
3068 /*
3069  * ext_coal_sdma_tx_descs() - extend or coalesce sdma tx descriptors
3070  *
3071  * This is called once the initial nominal allocation of descriptors
3072  * in the sdma_txreq is exhausted.
3073  *
3074  * This function calls _extend_sdma_tx_descs to extend or allocate
3075  * coalesce buffer. If there is a allocated coalesce buffer, it will
3076  * copy the input packet data into the coalesce buffer. It also adds
3077  * coalesce buffer descriptor once when whole packet is received.
3078  *
3079  * Return:
3080  * <0 - error
3081  * 0 - coalescing, don't populate descriptor
3082  * 1 - continue with populating descriptor
3083  */
3084 int ext_coal_sdma_tx_descs(struct hfi1_devdata *dd, struct sdma_txreq *tx,
3085                            int type, void *kvaddr, struct page *page,
3086                            unsigned long offset, u16 len)
3087 {
3088         int pad_len, rval;
3089         dma_addr_t addr;
3090
3091         rval = _extend_sdma_tx_descs(dd, tx);
3092         if (rval) {
3093                 sdma_txclean(dd, tx);
3094                 return rval;
3095         }
3096
3097         /* If coalesce buffer is allocated, copy data into it */
3098         if (tx->coalesce_buf) {
3099                 if (type == SDMA_MAP_NONE) {
3100                         sdma_txclean(dd, tx);
3101                         return -EINVAL;
3102                 }
3103
3104                 if (type == SDMA_MAP_PAGE) {
3105                         kvaddr = kmap(page);
3106                         kvaddr += offset;
3107                 } else if (WARN_ON(!kvaddr)) {
3108                         sdma_txclean(dd, tx);
3109                         return -EINVAL;
3110                 }
3111
3112                 memcpy(tx->coalesce_buf + tx->coalesce_idx, kvaddr, len);
3113                 tx->coalesce_idx += len;
3114                 if (type == SDMA_MAP_PAGE)
3115                         kunmap(page);
3116
3117                 /* If there is more data, return */
3118                 if (tx->tlen - tx->coalesce_idx)
3119                         return 0;
3120
3121                 /* Whole packet is received; add any padding */
3122                 pad_len = tx->packet_len & (sizeof(u32) - 1);
3123                 if (pad_len) {
3124                         pad_len = sizeof(u32) - pad_len;
3125                         memset(tx->coalesce_buf + tx->coalesce_idx, 0, pad_len);
3126                         /* padding is taken care of for coalescing case */
3127                         tx->packet_len += pad_len;
3128                         tx->tlen += pad_len;
3129                 }
3130
3131                 /* dma map the coalesce buffer */
3132                 addr = dma_map_single(&dd->pcidev->dev,
3133                                       tx->coalesce_buf,
3134                                       tx->tlen,
3135                                       DMA_TO_DEVICE);
3136
3137                 if (unlikely(dma_mapping_error(&dd->pcidev->dev, addr))) {
3138                         sdma_txclean(dd, tx);
3139                         return -ENOSPC;
3140                 }
3141
3142                 /* Add descriptor for coalesce buffer */
3143                 tx->desc_limit = MAX_DESC;
3144                 return _sdma_txadd_daddr(dd, SDMA_MAP_SINGLE, tx,
3145                                          addr, tx->tlen);
3146         }
3147
3148         return 1;
3149 }
3150
3151 /* Update sdes when the lmc changes */
3152 void sdma_update_lmc(struct hfi1_devdata *dd, u64 mask, u32 lid)
3153 {
3154         struct sdma_engine *sde;
3155         int i;
3156         u64 sreg;
3157
3158         sreg = ((mask & SD(CHECK_SLID_MASK_MASK)) <<
3159                 SD(CHECK_SLID_MASK_SHIFT)) |
3160                 (((lid & mask) & SD(CHECK_SLID_VALUE_MASK)) <<
3161                 SD(CHECK_SLID_VALUE_SHIFT));
3162
3163         for (i = 0; i < dd->num_sdma; i++) {
3164                 hfi1_cdbg(LINKVERB, "SendDmaEngine[%d].SLID_CHECK = 0x%x",
3165                           i, (u32)sreg);
3166                 sde = &dd->per_sdma[i];
3167                 write_sde_csr(sde, SD(CHECK_SLID), sreg);
3168         }
3169 }
3170
3171 /* tx not dword sized - pad */
3172 int _pad_sdma_tx_descs(struct hfi1_devdata *dd, struct sdma_txreq *tx)
3173 {
3174         int rval = 0;
3175
3176         tx->num_desc++;
3177         if ((unlikely(tx->num_desc == tx->desc_limit))) {
3178                 rval = _extend_sdma_tx_descs(dd, tx);
3179                 if (rval) {
3180                         sdma_txclean(dd, tx);
3181                         return rval;
3182                 }
3183         }
3184         /* finish the one just added */
3185         make_tx_sdma_desc(
3186                 tx,
3187                 SDMA_MAP_NONE,
3188                 dd->sdma_pad_phys,
3189                 sizeof(u32) - (tx->packet_len & (sizeof(u32) - 1)));
3190         _sdma_close_tx(dd, tx);
3191         return rval;
3192 }
3193
3194 /*
3195  * Add ahg to the sdma_txreq
3196  *
3197  * The logic will consume up to 3
3198  * descriptors at the beginning of
3199  * sdma_txreq.
3200  */
3201 void _sdma_txreq_ahgadd(
3202         struct sdma_txreq *tx,
3203         u8 num_ahg,
3204         u8 ahg_entry,
3205         u32 *ahg,
3206         u8 ahg_hlen)
3207 {
3208         u32 i, shift = 0, desc = 0;
3209         u8 mode;
3210
3211         WARN_ON_ONCE(num_ahg > 9 || (ahg_hlen & 3) || ahg_hlen == 4);
3212         /* compute mode */
3213         if (num_ahg == 1)
3214                 mode = SDMA_AHG_APPLY_UPDATE1;
3215         else if (num_ahg <= 5)
3216                 mode = SDMA_AHG_APPLY_UPDATE2;
3217         else
3218                 mode = SDMA_AHG_APPLY_UPDATE3;
3219         tx->num_desc++;
3220         /* initialize to consumed descriptors to zero */
3221         switch (mode) {
3222         case SDMA_AHG_APPLY_UPDATE3:
3223                 tx->num_desc++;
3224                 tx->descs[2].qw[0] = 0;
3225                 tx->descs[2].qw[1] = 0;
3226                 /* FALLTHROUGH */
3227         case SDMA_AHG_APPLY_UPDATE2:
3228                 tx->num_desc++;
3229                 tx->descs[1].qw[0] = 0;
3230                 tx->descs[1].qw[1] = 0;
3231                 break;
3232         }
3233         ahg_hlen >>= 2;
3234         tx->descs[0].qw[1] |=
3235                 (((u64)ahg_entry & SDMA_DESC1_HEADER_INDEX_MASK)
3236                         << SDMA_DESC1_HEADER_INDEX_SHIFT) |
3237                 (((u64)ahg_hlen & SDMA_DESC1_HEADER_DWS_MASK)
3238                         << SDMA_DESC1_HEADER_DWS_SHIFT) |
3239                 (((u64)mode & SDMA_DESC1_HEADER_MODE_MASK)
3240                         << SDMA_DESC1_HEADER_MODE_SHIFT) |
3241                 (((u64)ahg[0] & SDMA_DESC1_HEADER_UPDATE1_MASK)
3242                         << SDMA_DESC1_HEADER_UPDATE1_SHIFT);
3243         for (i = 0; i < (num_ahg - 1); i++) {
3244                 if (!shift && !(i & 2))
3245                         desc++;
3246                 tx->descs[desc].qw[!!(i & 2)] |=
3247                         (((u64)ahg[i + 1])
3248                                 << shift);
3249                 shift = (shift + 32) & 63;
3250         }
3251 }
3252
3253 /**
3254  * sdma_ahg_alloc - allocate an AHG entry
3255  * @sde: engine to allocate from
3256  *
3257  * Return:
3258  * 0-31 when successful, -EOPNOTSUPP if AHG is not enabled,
3259  * -ENOSPC if an entry is not available
3260  */
3261 int sdma_ahg_alloc(struct sdma_engine *sde)
3262 {
3263         int nr;
3264         int oldbit;
3265
3266         if (!sde) {
3267                 trace_hfi1_ahg_allocate(sde, -EINVAL);
3268                 return -EINVAL;
3269         }
3270         while (1) {
3271                 nr = ffz(ACCESS_ONCE(sde->ahg_bits));
3272                 if (nr > 31) {
3273                         trace_hfi1_ahg_allocate(sde, -ENOSPC);
3274                         return -ENOSPC;
3275                 }
3276                 oldbit = test_and_set_bit(nr, &sde->ahg_bits);
3277                 if (!oldbit)
3278                         break;
3279                 cpu_relax();
3280         }
3281         trace_hfi1_ahg_allocate(sde, nr);
3282         return nr;
3283 }
3284
3285 /**
3286  * sdma_ahg_free - free an AHG entry
3287  * @sde: engine to return AHG entry
3288  * @ahg_index: index to free
3289  *
3290  * This routine frees the indicate AHG entry.
3291  */
3292 void sdma_ahg_free(struct sdma_engine *sde, int ahg_index)
3293 {
3294         if (!sde)
3295                 return;
3296         trace_hfi1_ahg_deallocate(sde, ahg_index);
3297         if (ahg_index < 0 || ahg_index > 31)
3298                 return;
3299         clear_bit(ahg_index, &sde->ahg_bits);
3300 }
3301
3302 /*
3303  * SPC freeze handling for SDMA engines.  Called when the driver knows
3304  * the SPC is going into a freeze but before the freeze is fully
3305  * settled.  Generally an error interrupt.
3306  *
3307  * This event will pull the engine out of running so no more entries can be
3308  * added to the engine's queue.
3309  */
3310 void sdma_freeze_notify(struct hfi1_devdata *dd, int link_down)
3311 {
3312         int i;
3313         enum sdma_events event = link_down ? sdma_event_e85_link_down :
3314                                              sdma_event_e80_hw_freeze;
3315
3316         /* set up the wait but do not wait here */
3317         atomic_set(&dd->sdma_unfreeze_count, dd->num_sdma);
3318
3319         /* tell all engines to stop running and wait */
3320         for (i = 0; i < dd->num_sdma; i++)
3321                 sdma_process_event(&dd->per_sdma[i], event);
3322
3323         /* sdma_freeze() will wait for all engines to have stopped */
3324 }
3325
3326 /*
3327  * SPC freeze handling for SDMA engines.  Called when the driver knows
3328  * the SPC is fully frozen.
3329  */
3330 void sdma_freeze(struct hfi1_devdata *dd)
3331 {
3332         int i;
3333         int ret;
3334
3335         /*
3336          * Make sure all engines have moved out of the running state before
3337          * continuing.
3338          */
3339         ret = wait_event_interruptible(dd->sdma_unfreeze_wq,
3340                                        atomic_read(&dd->sdma_unfreeze_count) <=
3341                                        0);
3342         /* interrupted or count is negative, then unloading - just exit */
3343         if (ret || atomic_read(&dd->sdma_unfreeze_count) < 0)
3344                 return;
3345
3346         /* set up the count for the next wait */
3347         atomic_set(&dd->sdma_unfreeze_count, dd->num_sdma);
3348
3349         /* tell all engines that the SPC is frozen, they can start cleaning */
3350         for (i = 0; i < dd->num_sdma; i++)
3351                 sdma_process_event(&dd->per_sdma[i], sdma_event_e81_hw_frozen);
3352
3353         /*
3354          * Wait for everyone to finish software clean before exiting.  The
3355          * software clean will read engine CSRs, so must be completed before
3356          * the next step, which will clear the engine CSRs.
3357          */
3358         (void)wait_event_interruptible(dd->sdma_unfreeze_wq,
3359                                 atomic_read(&dd->sdma_unfreeze_count) <= 0);
3360         /* no need to check results - done no matter what */
3361 }
3362
3363 /*
3364  * SPC freeze handling for the SDMA engines.  Called after the SPC is unfrozen.
3365  *
3366  * The SPC freeze acts like a SDMA halt and a hardware clean combined.  All
3367  * that is left is a software clean.  We could do it after the SPC is fully
3368  * frozen, but then we'd have to add another state to wait for the unfreeze.
3369  * Instead, just defer the software clean until the unfreeze step.
3370  */
3371 void sdma_unfreeze(struct hfi1_devdata *dd)
3372 {
3373         int i;
3374
3375         /* tell all engines start freeze clean up */
3376         for (i = 0; i < dd->num_sdma; i++)
3377                 sdma_process_event(&dd->per_sdma[i],
3378                                    sdma_event_e82_hw_unfreeze);
3379 }
3380
3381 /**
3382  * _sdma_engine_progress_schedule() - schedule progress on engine
3383  * @sde: sdma_engine to schedule progress
3384  *
3385  */
3386 void _sdma_engine_progress_schedule(
3387         struct sdma_engine *sde)
3388 {
3389         trace_hfi1_sdma_engine_progress(sde, sde->progress_mask);
3390         /* assume we have selected a good cpu */
3391         write_csr(sde->dd,
3392                   CCE_INT_FORCE + (8 * (IS_SDMA_START / 64)),
3393                   sde->progress_mask);
3394 }