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