xref: /linux/drivers/net/wireless/intel/iwlwifi/pcie/tx.c (revision d7f39aee79f04eeaa42085728423501b33ac5be5)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /*
3  * Copyright (C) 2003-2014, 2018-2021, 2023-2024 Intel Corporation
4  * Copyright (C) 2013-2015 Intel Mobile Communications GmbH
5  * Copyright (C) 2016-2017 Intel Deutschland GmbH
6  */
7 #include <linux/etherdevice.h>
8 #include <linux/ieee80211.h>
9 #include <linux/dmapool.h>
10 #include <linux/slab.h>
11 #include <linux/sched.h>
12 #include <linux/tcp.h>
13 #include <net/ip6_checksum.h>
14 #include <net/tso.h>
15 
16 #include "fw/api/commands.h"
17 #include "fw/api/datapath.h"
18 #include "fw/api/debug.h"
19 #include "iwl-fh.h"
20 #include "iwl-debug.h"
21 #include "iwl-csr.h"
22 #include "iwl-prph.h"
23 #include "iwl-io.h"
24 #include "iwl-scd.h"
25 #include "iwl-op-mode.h"
26 #include "internal.h"
27 #include "fw/api/tx.h"
28 
29 /*************** DMA-QUEUE-GENERAL-FUNCTIONS  *****
30  * DMA services
31  *
32  * Theory of operation
33  *
34  * A Tx or Rx queue resides in host DRAM, and is comprised of a circular buffer
35  * of buffer descriptors, each of which points to one or more data buffers for
36  * the device to read from or fill.  Driver and device exchange status of each
37  * queue via "read" and "write" pointers.  Driver keeps minimum of 2 empty
38  * entries in each circular buffer, to protect against confusing empty and full
39  * queue states.
40  *
41  * The device reads or writes the data in the queues via the device's several
42  * DMA/FIFO channels.  Each queue is mapped to a single DMA channel.
43  *
44  * For Tx queue, there are low mark and high mark limits. If, after queuing
45  * the packet for Tx, free space become < low mark, Tx queue stopped. When
46  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
47  * Tx queue resumed.
48  *
49  ***************************************************/
50 
51 
52 int iwl_pcie_alloc_dma_ptr(struct iwl_trans *trans,
53 			   struct iwl_dma_ptr *ptr, size_t size)
54 {
55 	if (WARN_ON(ptr->addr))
56 		return -EINVAL;
57 
58 	ptr->addr = dma_alloc_coherent(trans->dev, size,
59 				       &ptr->dma, GFP_KERNEL);
60 	if (!ptr->addr)
61 		return -ENOMEM;
62 	ptr->size = size;
63 	return 0;
64 }
65 
66 void iwl_pcie_free_dma_ptr(struct iwl_trans *trans, struct iwl_dma_ptr *ptr)
67 {
68 	if (unlikely(!ptr->addr))
69 		return;
70 
71 	dma_free_coherent(trans->dev, ptr->size, ptr->addr, ptr->dma);
72 	memset(ptr, 0, sizeof(*ptr));
73 }
74 
75 /*
76  * iwl_pcie_txq_inc_wr_ptr - Send new write index to hardware
77  */
78 static void iwl_pcie_txq_inc_wr_ptr(struct iwl_trans *trans,
79 				    struct iwl_txq *txq)
80 {
81 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
82 	u32 reg = 0;
83 	int txq_id = txq->id;
84 
85 	lockdep_assert_held(&txq->lock);
86 
87 	/*
88 	 * explicitly wake up the NIC if:
89 	 * 1. shadow registers aren't enabled
90 	 * 2. NIC is woken up for CMD regardless of shadow outside this function
91 	 * 3. there is a chance that the NIC is asleep
92 	 */
93 	if (!trans->trans_cfg->base_params->shadow_reg_enable &&
94 	    txq_id != trans_pcie->txqs.cmd.q_id &&
95 	    test_bit(STATUS_TPOWER_PMI, &trans->status)) {
96 		/*
97 		 * wake up nic if it's powered down ...
98 		 * uCode will wake up, and interrupt us again, so next
99 		 * time we'll skip this part.
100 		 */
101 		reg = iwl_read32(trans, CSR_UCODE_DRV_GP1);
102 
103 		if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
104 			IWL_DEBUG_INFO(trans, "Tx queue %d requesting wakeup, GP1 = 0x%x\n",
105 				       txq_id, reg);
106 			iwl_set_bit(trans, CSR_GP_CNTRL,
107 				    CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
108 			txq->need_update = true;
109 			return;
110 		}
111 	}
112 
113 	/*
114 	 * if not in power-save mode, uCode will never sleep when we're
115 	 * trying to tx (during RFKILL, we're not trying to tx).
116 	 */
117 	IWL_DEBUG_TX(trans, "Q:%d WR: 0x%x\n", txq_id, txq->write_ptr);
118 	if (!txq->block)
119 		iwl_write32(trans, HBUS_TARG_WRPTR,
120 			    txq->write_ptr | (txq_id << 8));
121 }
122 
123 void iwl_pcie_txq_check_wrptrs(struct iwl_trans *trans)
124 {
125 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
126 	int i;
127 
128 	for (i = 0; i < trans->trans_cfg->base_params->num_of_queues; i++) {
129 		struct iwl_txq *txq = trans_pcie->txqs.txq[i];
130 
131 		if (!test_bit(i, trans_pcie->txqs.queue_used))
132 			continue;
133 
134 		spin_lock_bh(&txq->lock);
135 		if (txq->need_update) {
136 			iwl_pcie_txq_inc_wr_ptr(trans, txq);
137 			txq->need_update = false;
138 		}
139 		spin_unlock_bh(&txq->lock);
140 	}
141 }
142 
143 static inline void iwl_pcie_gen1_tfd_set_tb(struct iwl_tfd *tfd,
144 					    u8 idx, dma_addr_t addr, u16 len)
145 {
146 	struct iwl_tfd_tb *tb = &tfd->tbs[idx];
147 	u16 hi_n_len = len << 4;
148 
149 	put_unaligned_le32(addr, &tb->lo);
150 	hi_n_len |= iwl_get_dma_hi_addr(addr);
151 
152 	tb->hi_n_len = cpu_to_le16(hi_n_len);
153 
154 	tfd->num_tbs = idx + 1;
155 }
156 
157 static inline u8 iwl_txq_gen1_tfd_get_num_tbs(struct iwl_tfd *tfd)
158 {
159 	return tfd->num_tbs & 0x1f;
160 }
161 
162 static int iwl_pcie_txq_build_tfd(struct iwl_trans *trans, struct iwl_txq *txq,
163 				  dma_addr_t addr, u16 len, bool reset)
164 {
165 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
166 	void *tfd;
167 	u32 num_tbs;
168 
169 	tfd = (u8 *)txq->tfds + trans_pcie->txqs.tfd.size * txq->write_ptr;
170 
171 	if (reset)
172 		memset(tfd, 0, trans_pcie->txqs.tfd.size);
173 
174 	num_tbs = iwl_txq_gen1_tfd_get_num_tbs(tfd);
175 
176 	/* Each TFD can point to a maximum max_tbs Tx buffers */
177 	if (num_tbs >= trans_pcie->txqs.tfd.max_tbs) {
178 		IWL_ERR(trans, "Error can not send more than %d chunks\n",
179 			trans_pcie->txqs.tfd.max_tbs);
180 		return -EINVAL;
181 	}
182 
183 	if (WARN(addr & ~IWL_TX_DMA_MASK,
184 		 "Unaligned address = %llx\n", (unsigned long long)addr))
185 		return -EINVAL;
186 
187 	iwl_pcie_gen1_tfd_set_tb(tfd, num_tbs, addr, len);
188 
189 	return num_tbs;
190 }
191 
192 static void iwl_pcie_clear_cmd_in_flight(struct iwl_trans *trans)
193 {
194 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
195 
196 	if (!trans->trans_cfg->base_params->apmg_wake_up_wa)
197 		return;
198 
199 	spin_lock(&trans_pcie->reg_lock);
200 
201 	if (WARN_ON(!trans_pcie->cmd_hold_nic_awake)) {
202 		spin_unlock(&trans_pcie->reg_lock);
203 		return;
204 	}
205 
206 	trans_pcie->cmd_hold_nic_awake = false;
207 	__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
208 				   CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
209 	spin_unlock(&trans_pcie->reg_lock);
210 }
211 
212 void iwl_pcie_free_tso_page(struct iwl_trans *trans, struct sk_buff *skb)
213 {
214 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
215 	struct page **page_ptr;
216 	struct page *next;
217 
218 	page_ptr = (void *)((u8 *)skb->cb + trans_pcie->txqs.page_offs);
219 	next = *page_ptr;
220 	*page_ptr = NULL;
221 
222 	while (next) {
223 		struct page *tmp = next;
224 
225 		next = *(void **)((u8 *)page_address(next) + PAGE_SIZE -
226 				  sizeof(void *));
227 		__free_page(tmp);
228 	}
229 }
230 
231 static inline dma_addr_t
232 iwl_txq_gen1_tfd_tb_get_addr(struct iwl_tfd *tfd, u8 idx)
233 {
234 	struct iwl_tfd_tb *tb = &tfd->tbs[idx];
235 	dma_addr_t addr;
236 	dma_addr_t hi_len;
237 
238 	addr = get_unaligned_le32(&tb->lo);
239 
240 	if (sizeof(dma_addr_t) <= sizeof(u32))
241 		return addr;
242 
243 	hi_len = le16_to_cpu(tb->hi_n_len) & 0xF;
244 
245 	/*
246 	 * shift by 16 twice to avoid warnings on 32-bit
247 	 * (where this code never runs anyway due to the
248 	 * if statement above)
249 	 */
250 	return addr | ((hi_len << 16) << 16);
251 }
252 
253 static void iwl_txq_set_tfd_invalid_gen1(struct iwl_trans *trans,
254 					 struct iwl_tfd *tfd)
255 {
256 	tfd->num_tbs = 0;
257 
258 	iwl_pcie_gen1_tfd_set_tb(tfd, 0, trans->invalid_tx_cmd.dma,
259 				 trans->invalid_tx_cmd.size);
260 }
261 
262 static void iwl_txq_gen1_tfd_unmap(struct iwl_trans *trans,
263 				   struct iwl_cmd_meta *meta,
264 				   struct iwl_txq *txq, int index)
265 {
266 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
267 	int i, num_tbs;
268 	struct iwl_tfd *tfd = iwl_txq_get_tfd(trans, txq, index);
269 
270 	/* Sanity check on number of chunks */
271 	num_tbs = iwl_txq_gen1_tfd_get_num_tbs(tfd);
272 
273 	if (num_tbs > trans_pcie->txqs.tfd.max_tbs) {
274 		IWL_ERR(trans, "Too many chunks: %i\n", num_tbs);
275 		/* @todo issue fatal error, it is quite serious situation */
276 		return;
277 	}
278 
279 	/* first TB is never freed - it's the bidirectional DMA data */
280 
281 	for (i = 1; i < num_tbs; i++) {
282 		if (meta->tbs & BIT(i))
283 			dma_unmap_page(trans->dev,
284 				       iwl_txq_gen1_tfd_tb_get_addr(tfd, i),
285 				       iwl_txq_gen1_tfd_tb_get_len(trans,
286 								   tfd, i),
287 				       DMA_TO_DEVICE);
288 		else
289 			dma_unmap_single(trans->dev,
290 					 iwl_txq_gen1_tfd_tb_get_addr(tfd, i),
291 					 iwl_txq_gen1_tfd_tb_get_len(trans,
292 								     tfd, i),
293 					 DMA_TO_DEVICE);
294 	}
295 
296 	meta->tbs = 0;
297 
298 	iwl_txq_set_tfd_invalid_gen1(trans, tfd);
299 }
300 
301 /**
302  * iwl_txq_free_tfd - Free all chunks referenced by TFD [txq->q.read_ptr]
303  * @trans: transport private data
304  * @txq: tx queue
305  *
306  * Does NOT advance any TFD circular buffer read/write indexes
307  * Does NOT free the TFD itself (which is within circular buffer)
308  */
309 static void iwl_txq_free_tfd(struct iwl_trans *trans, struct iwl_txq *txq)
310 {
311 	/* rd_ptr is bounded by TFD_QUEUE_SIZE_MAX and
312 	 * idx is bounded by n_window
313 	 */
314 	int rd_ptr = txq->read_ptr;
315 	int idx = iwl_txq_get_cmd_index(txq, rd_ptr);
316 	struct sk_buff *skb;
317 
318 	lockdep_assert_held(&txq->lock);
319 
320 	if (!txq->entries)
321 		return;
322 
323 	/* We have only q->n_window txq->entries, but we use
324 	 * TFD_QUEUE_SIZE_MAX tfds
325 	 */
326 	if (trans->trans_cfg->gen2)
327 		iwl_txq_gen2_tfd_unmap(trans, &txq->entries[idx].meta,
328 				       iwl_txq_get_tfd(trans, txq, rd_ptr));
329 	else
330 		iwl_txq_gen1_tfd_unmap(trans, &txq->entries[idx].meta,
331 				       txq, rd_ptr);
332 
333 	/* free SKB */
334 	skb = txq->entries[idx].skb;
335 
336 	/* Can be called from irqs-disabled context
337 	 * If skb is not NULL, it means that the whole queue is being
338 	 * freed and that the queue is not empty - free the skb
339 	 */
340 	if (skb) {
341 		iwl_op_mode_free_skb(trans->op_mode, skb);
342 		txq->entries[idx].skb = NULL;
343 	}
344 }
345 
346 /*
347  * iwl_pcie_txq_unmap -  Unmap any remaining DMA mappings and free skb's
348  */
349 static void iwl_pcie_txq_unmap(struct iwl_trans *trans, int txq_id)
350 {
351 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
352 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
353 
354 	if (!txq) {
355 		IWL_ERR(trans, "Trying to free a queue that wasn't allocated?\n");
356 		return;
357 	}
358 
359 	spin_lock_bh(&txq->lock);
360 	while (txq->write_ptr != txq->read_ptr) {
361 		IWL_DEBUG_TX_REPLY(trans, "Q %d Free %d\n",
362 				   txq_id, txq->read_ptr);
363 
364 		if (txq_id != trans_pcie->txqs.cmd.q_id) {
365 			struct sk_buff *skb = txq->entries[txq->read_ptr].skb;
366 
367 			if (WARN_ON_ONCE(!skb))
368 				continue;
369 
370 			iwl_pcie_free_tso_page(trans, skb);
371 		}
372 		iwl_txq_free_tfd(trans, txq);
373 		txq->read_ptr = iwl_txq_inc_wrap(trans, txq->read_ptr);
374 
375 		if (txq->read_ptr == txq->write_ptr &&
376 		    txq_id == trans_pcie->txqs.cmd.q_id)
377 			iwl_pcie_clear_cmd_in_flight(trans);
378 	}
379 
380 	while (!skb_queue_empty(&txq->overflow_q)) {
381 		struct sk_buff *skb = __skb_dequeue(&txq->overflow_q);
382 
383 		iwl_op_mode_free_skb(trans->op_mode, skb);
384 	}
385 
386 	spin_unlock_bh(&txq->lock);
387 
388 	/* just in case - this queue may have been stopped */
389 	iwl_trans_pcie_wake_queue(trans, txq);
390 }
391 
392 /*
393  * iwl_pcie_txq_free - Deallocate DMA queue.
394  * @txq: Transmit queue to deallocate.
395  *
396  * Empty queue by removing and destroying all BD's.
397  * Free all buffers.
398  * 0-fill, but do not free "txq" descriptor structure.
399  */
400 static void iwl_pcie_txq_free(struct iwl_trans *trans, int txq_id)
401 {
402 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
403 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
404 	struct device *dev = trans->dev;
405 	int i;
406 
407 	if (WARN_ON(!txq))
408 		return;
409 
410 	iwl_pcie_txq_unmap(trans, txq_id);
411 
412 	/* De-alloc array of command/tx buffers */
413 	if (txq_id == trans_pcie->txqs.cmd.q_id)
414 		for (i = 0; i < txq->n_window; i++) {
415 			kfree_sensitive(txq->entries[i].cmd);
416 			kfree_sensitive(txq->entries[i].free_buf);
417 		}
418 
419 	/* De-alloc circular buffer of TFDs */
420 	if (txq->tfds) {
421 		dma_free_coherent(dev,
422 				  trans_pcie->txqs.tfd.size *
423 				  trans->trans_cfg->base_params->max_tfd_queue_size,
424 				  txq->tfds, txq->dma_addr);
425 		txq->dma_addr = 0;
426 		txq->tfds = NULL;
427 
428 		dma_free_coherent(dev,
429 				  sizeof(*txq->first_tb_bufs) * txq->n_window,
430 				  txq->first_tb_bufs, txq->first_tb_dma);
431 	}
432 
433 	kfree(txq->entries);
434 	txq->entries = NULL;
435 
436 	del_timer_sync(&txq->stuck_timer);
437 
438 	/* 0-fill queue descriptor structure */
439 	memset(txq, 0, sizeof(*txq));
440 }
441 
442 void iwl_pcie_tx_start(struct iwl_trans *trans, u32 scd_base_addr)
443 {
444 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
445 	int nq = trans->trans_cfg->base_params->num_of_queues;
446 	int chan;
447 	u32 reg_val;
448 	int clear_dwords = (SCD_TRANS_TBL_OFFSET_QUEUE(nq) -
449 				SCD_CONTEXT_MEM_LOWER_BOUND) / sizeof(u32);
450 
451 	/* make sure all queue are not stopped/used */
452 	memset(trans_pcie->txqs.queue_stopped, 0,
453 	       sizeof(trans_pcie->txqs.queue_stopped));
454 	memset(trans_pcie->txqs.queue_used, 0,
455 	       sizeof(trans_pcie->txqs.queue_used));
456 
457 	trans_pcie->scd_base_addr =
458 		iwl_read_prph(trans, SCD_SRAM_BASE_ADDR);
459 
460 	WARN_ON(scd_base_addr != 0 &&
461 		scd_base_addr != trans_pcie->scd_base_addr);
462 
463 	/* reset context data, TX status and translation data */
464 	iwl_trans_write_mem(trans, trans_pcie->scd_base_addr +
465 				   SCD_CONTEXT_MEM_LOWER_BOUND,
466 			    NULL, clear_dwords);
467 
468 	iwl_write_prph(trans, SCD_DRAM_BASE_ADDR,
469 		       trans_pcie->txqs.scd_bc_tbls.dma >> 10);
470 
471 	/* The chain extension of the SCD doesn't work well. This feature is
472 	 * enabled by default by the HW, so we need to disable it manually.
473 	 */
474 	if (trans->trans_cfg->base_params->scd_chain_ext_wa)
475 		iwl_write_prph(trans, SCD_CHAINEXT_EN, 0);
476 
477 	iwl_trans_ac_txq_enable(trans, trans_pcie->txqs.cmd.q_id,
478 				trans_pcie->txqs.cmd.fifo,
479 				trans_pcie->txqs.cmd.wdg_timeout);
480 
481 	/* Activate all Tx DMA/FIFO channels */
482 	iwl_scd_activate_fifos(trans);
483 
484 	/* Enable DMA channel */
485 	for (chan = 0; chan < FH_TCSR_CHNL_NUM; chan++)
486 		iwl_write_direct32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(chan),
487 				   FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
488 				   FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE);
489 
490 	/* Update FH chicken bits */
491 	reg_val = iwl_read_direct32(trans, FH_TX_CHICKEN_BITS_REG);
492 	iwl_write_direct32(trans, FH_TX_CHICKEN_BITS_REG,
493 			   reg_val | FH_TX_CHICKEN_BITS_SCD_AUTO_RETRY_EN);
494 
495 	/* Enable L1-Active */
496 	if (trans->trans_cfg->device_family < IWL_DEVICE_FAMILY_8000)
497 		iwl_clear_bits_prph(trans, APMG_PCIDEV_STT_REG,
498 				    APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
499 }
500 
501 void iwl_trans_pcie_tx_reset(struct iwl_trans *trans)
502 {
503 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
504 	int txq_id;
505 
506 	/*
507 	 * we should never get here in gen2 trans mode return early to avoid
508 	 * having invalid accesses
509 	 */
510 	if (WARN_ON_ONCE(trans->trans_cfg->gen2))
511 		return;
512 
513 	for (txq_id = 0; txq_id < trans->trans_cfg->base_params->num_of_queues;
514 	     txq_id++) {
515 		struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
516 		if (trans->trans_cfg->gen2)
517 			iwl_write_direct64(trans,
518 					   FH_MEM_CBBC_QUEUE(trans, txq_id),
519 					   txq->dma_addr);
520 		else
521 			iwl_write_direct32(trans,
522 					   FH_MEM_CBBC_QUEUE(trans, txq_id),
523 					   txq->dma_addr >> 8);
524 		iwl_pcie_txq_unmap(trans, txq_id);
525 		txq->read_ptr = 0;
526 		txq->write_ptr = 0;
527 	}
528 
529 	/* Tell NIC where to find the "keep warm" buffer */
530 	iwl_write_direct32(trans, FH_KW_MEM_ADDR_REG,
531 			   trans_pcie->kw.dma >> 4);
532 
533 	/*
534 	 * Send 0 as the scd_base_addr since the device may have be reset
535 	 * while we were in WoWLAN in which case SCD_SRAM_BASE_ADDR will
536 	 * contain garbage.
537 	 */
538 	iwl_pcie_tx_start(trans, 0);
539 }
540 
541 static void iwl_pcie_tx_stop_fh(struct iwl_trans *trans)
542 {
543 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
544 	int ch, ret;
545 	u32 mask = 0;
546 
547 	spin_lock_bh(&trans_pcie->irq_lock);
548 
549 	if (!iwl_trans_grab_nic_access(trans))
550 		goto out;
551 
552 	/* Stop each Tx DMA channel */
553 	for (ch = 0; ch < FH_TCSR_CHNL_NUM; ch++) {
554 		iwl_write32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(ch), 0x0);
555 		mask |= FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(ch);
556 	}
557 
558 	/* Wait for DMA channels to be idle */
559 	ret = iwl_poll_bit(trans, FH_TSSR_TX_STATUS_REG, mask, mask, 5000);
560 	if (ret < 0)
561 		IWL_ERR(trans,
562 			"Failing on timeout while stopping DMA channel %d [0x%08x]\n",
563 			ch, iwl_read32(trans, FH_TSSR_TX_STATUS_REG));
564 
565 	iwl_trans_release_nic_access(trans);
566 
567 out:
568 	spin_unlock_bh(&trans_pcie->irq_lock);
569 }
570 
571 /*
572  * iwl_pcie_tx_stop - Stop all Tx DMA channels
573  */
574 int iwl_pcie_tx_stop(struct iwl_trans *trans)
575 {
576 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
577 	int txq_id;
578 
579 	/* Turn off all Tx DMA fifos */
580 	iwl_scd_deactivate_fifos(trans);
581 
582 	/* Turn off all Tx DMA channels */
583 	iwl_pcie_tx_stop_fh(trans);
584 
585 	/*
586 	 * This function can be called before the op_mode disabled the
587 	 * queues. This happens when we have an rfkill interrupt.
588 	 * Since we stop Tx altogether - mark the queues as stopped.
589 	 */
590 	memset(trans_pcie->txqs.queue_stopped, 0,
591 	       sizeof(trans_pcie->txqs.queue_stopped));
592 	memset(trans_pcie->txqs.queue_used, 0,
593 	       sizeof(trans_pcie->txqs.queue_used));
594 
595 	/* This can happen: start_hw, stop_device */
596 	if (!trans_pcie->txq_memory)
597 		return 0;
598 
599 	/* Unmap DMA from host system and free skb's */
600 	for (txq_id = 0; txq_id < trans->trans_cfg->base_params->num_of_queues;
601 	     txq_id++)
602 		iwl_pcie_txq_unmap(trans, txq_id);
603 
604 	return 0;
605 }
606 
607 /*
608  * iwl_trans_tx_free - Free TXQ Context
609  *
610  * Destroy all TX DMA queues and structures
611  */
612 void iwl_pcie_tx_free(struct iwl_trans *trans)
613 {
614 	int txq_id;
615 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
616 
617 	memset(trans_pcie->txqs.queue_used, 0,
618 	       sizeof(trans_pcie->txqs.queue_used));
619 
620 	/* Tx queues */
621 	if (trans_pcie->txq_memory) {
622 		for (txq_id = 0;
623 		     txq_id < trans->trans_cfg->base_params->num_of_queues;
624 		     txq_id++) {
625 			iwl_pcie_txq_free(trans, txq_id);
626 			trans_pcie->txqs.txq[txq_id] = NULL;
627 		}
628 	}
629 
630 	kfree(trans_pcie->txq_memory);
631 	trans_pcie->txq_memory = NULL;
632 
633 	iwl_pcie_free_dma_ptr(trans, &trans_pcie->kw);
634 
635 	iwl_pcie_free_dma_ptr(trans, &trans_pcie->txqs.scd_bc_tbls);
636 }
637 
638 void iwl_txq_log_scd_error(struct iwl_trans *trans, struct iwl_txq *txq)
639 {
640 	u32 txq_id = txq->id;
641 	u32 status;
642 	bool active;
643 	u8 fifo;
644 
645 	if (trans->trans_cfg->gen2) {
646 		IWL_ERR(trans, "Queue %d is stuck %d %d\n", txq_id,
647 			txq->read_ptr, txq->write_ptr);
648 		/* TODO: access new SCD registers and dump them */
649 		return;
650 	}
651 
652 	status = iwl_read_prph(trans, SCD_QUEUE_STATUS_BITS(txq_id));
653 	fifo = (status >> SCD_QUEUE_STTS_REG_POS_TXF) & 0x7;
654 	active = !!(status & BIT(SCD_QUEUE_STTS_REG_POS_ACTIVE));
655 
656 	IWL_ERR(trans,
657 		"Queue %d is %sactive on fifo %d and stuck for %u ms. SW [%d, %d] HW [%d, %d] FH TRB=0x0%x\n",
658 		txq_id, active ? "" : "in", fifo,
659 		jiffies_to_msecs(txq->wd_timeout),
660 		txq->read_ptr, txq->write_ptr,
661 		iwl_read_prph(trans, SCD_QUEUE_RDPTR(txq_id)) &
662 			(trans->trans_cfg->base_params->max_tfd_queue_size - 1),
663 			iwl_read_prph(trans, SCD_QUEUE_WRPTR(txq_id)) &
664 			(trans->trans_cfg->base_params->max_tfd_queue_size - 1),
665 			iwl_read_direct32(trans, FH_TX_TRB_REG(fifo)));
666 }
667 
668 static void iwl_txq_stuck_timer(struct timer_list *t)
669 {
670 	struct iwl_txq *txq = from_timer(txq, t, stuck_timer);
671 	struct iwl_trans *trans = txq->trans;
672 
673 	spin_lock(&txq->lock);
674 	/* check if triggered erroneously */
675 	if (txq->read_ptr == txq->write_ptr) {
676 		spin_unlock(&txq->lock);
677 		return;
678 	}
679 	spin_unlock(&txq->lock);
680 
681 	iwl_txq_log_scd_error(trans, txq);
682 
683 	iwl_force_nmi(trans);
684 }
685 
686 int iwl_pcie_txq_alloc(struct iwl_trans *trans, struct iwl_txq *txq,
687 		       int slots_num, bool cmd_queue)
688 {
689 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
690 	size_t num_entries = trans->trans_cfg->gen2 ?
691 		slots_num : trans->trans_cfg->base_params->max_tfd_queue_size;
692 	size_t tfd_sz;
693 	size_t tb0_buf_sz;
694 	int i;
695 
696 	if (WARN_ONCE(slots_num <= 0, "Invalid slots num:%d\n", slots_num))
697 		return -EINVAL;
698 
699 	if (WARN_ON(txq->entries || txq->tfds))
700 		return -EINVAL;
701 
702 	tfd_sz = trans_pcie->txqs.tfd.size * num_entries;
703 
704 	timer_setup(&txq->stuck_timer, iwl_txq_stuck_timer, 0);
705 	txq->trans = trans;
706 
707 	txq->n_window = slots_num;
708 
709 	txq->entries = kcalloc(slots_num,
710 			       sizeof(struct iwl_pcie_txq_entry),
711 			       GFP_KERNEL);
712 
713 	if (!txq->entries)
714 		goto error;
715 
716 	if (cmd_queue)
717 		for (i = 0; i < slots_num; i++) {
718 			txq->entries[i].cmd =
719 				kmalloc(sizeof(struct iwl_device_cmd),
720 					GFP_KERNEL);
721 			if (!txq->entries[i].cmd)
722 				goto error;
723 		}
724 
725 	/* Circular buffer of transmit frame descriptors (TFDs),
726 	 * shared with device
727 	 */
728 	txq->tfds = dma_alloc_coherent(trans->dev, tfd_sz,
729 				       &txq->dma_addr, GFP_KERNEL);
730 	if (!txq->tfds)
731 		goto error;
732 
733 	BUILD_BUG_ON(sizeof(*txq->first_tb_bufs) != IWL_FIRST_TB_SIZE_ALIGN);
734 
735 	tb0_buf_sz = sizeof(*txq->first_tb_bufs) * slots_num;
736 
737 	txq->first_tb_bufs = dma_alloc_coherent(trans->dev, tb0_buf_sz,
738 						&txq->first_tb_dma,
739 						GFP_KERNEL);
740 	if (!txq->first_tb_bufs)
741 		goto err_free_tfds;
742 
743 	for (i = 0; i < num_entries; i++) {
744 		void *tfd = iwl_txq_get_tfd(trans, txq, i);
745 
746 		if (trans->trans_cfg->gen2)
747 			iwl_txq_set_tfd_invalid_gen2(trans, tfd);
748 		else
749 			iwl_txq_set_tfd_invalid_gen1(trans, tfd);
750 	}
751 
752 	return 0;
753 err_free_tfds:
754 	dma_free_coherent(trans->dev, tfd_sz, txq->tfds, txq->dma_addr);
755 	txq->tfds = NULL;
756 error:
757 	if (txq->entries && cmd_queue)
758 		for (i = 0; i < slots_num; i++)
759 			kfree(txq->entries[i].cmd);
760 	kfree(txq->entries);
761 	txq->entries = NULL;
762 
763 	return -ENOMEM;
764 }
765 
766 /*
767  * iwl_pcie_tx_alloc - allocate TX context
768  * Allocate all Tx DMA structures and initialize them
769  */
770 static int iwl_pcie_tx_alloc(struct iwl_trans *trans)
771 {
772 	int ret;
773 	int txq_id, slots_num;
774 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
775 	u16 bc_tbls_size = trans->trans_cfg->base_params->num_of_queues;
776 
777 	if (WARN_ON(trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210))
778 		return -EINVAL;
779 
780 	bc_tbls_size *= sizeof(struct iwlagn_scd_bc_tbl);
781 
782 	/*It is not allowed to alloc twice, so warn when this happens.
783 	 * We cannot rely on the previous allocation, so free and fail */
784 	if (WARN_ON(trans_pcie->txq_memory)) {
785 		ret = -EINVAL;
786 		goto error;
787 	}
788 
789 	ret = iwl_pcie_alloc_dma_ptr(trans, &trans_pcie->txqs.scd_bc_tbls,
790 				     bc_tbls_size);
791 	if (ret) {
792 		IWL_ERR(trans, "Scheduler BC Table allocation failed\n");
793 		goto error;
794 	}
795 
796 	/* Alloc keep-warm buffer */
797 	ret = iwl_pcie_alloc_dma_ptr(trans, &trans_pcie->kw, IWL_KW_SIZE);
798 	if (ret) {
799 		IWL_ERR(trans, "Keep Warm allocation failed\n");
800 		goto error;
801 	}
802 
803 	trans_pcie->txq_memory =
804 		kcalloc(trans->trans_cfg->base_params->num_of_queues,
805 			sizeof(struct iwl_txq), GFP_KERNEL);
806 	if (!trans_pcie->txq_memory) {
807 		IWL_ERR(trans, "Not enough memory for txq\n");
808 		ret = -ENOMEM;
809 		goto error;
810 	}
811 
812 	/* Alloc and init all Tx queues, including the command queue (#4/#9) */
813 	for (txq_id = 0; txq_id < trans->trans_cfg->base_params->num_of_queues;
814 	     txq_id++) {
815 		bool cmd_queue = (txq_id == trans_pcie->txqs.cmd.q_id);
816 
817 		if (cmd_queue)
818 			slots_num = max_t(u32, IWL_CMD_QUEUE_SIZE,
819 					  trans->cfg->min_txq_size);
820 		else
821 			slots_num = max_t(u32, IWL_DEFAULT_QUEUE_SIZE,
822 					  trans->cfg->min_ba_txq_size);
823 		trans_pcie->txqs.txq[txq_id] = &trans_pcie->txq_memory[txq_id];
824 		ret = iwl_pcie_txq_alloc(trans, trans_pcie->txqs.txq[txq_id],
825 					 slots_num, cmd_queue);
826 		if (ret) {
827 			IWL_ERR(trans, "Tx %d queue alloc failed\n", txq_id);
828 			goto error;
829 		}
830 		trans_pcie->txqs.txq[txq_id]->id = txq_id;
831 	}
832 
833 	return 0;
834 
835 error:
836 	iwl_pcie_tx_free(trans);
837 
838 	return ret;
839 }
840 
841 /*
842  * iwl_queue_init - Initialize queue's high/low-water and read/write indexes
843  */
844 static int iwl_queue_init(struct iwl_txq *q, int slots_num)
845 {
846 	q->n_window = slots_num;
847 
848 	/* slots_num must be power-of-two size, otherwise
849 	 * iwl_txq_get_cmd_index is broken.
850 	 */
851 	if (WARN_ON(!is_power_of_2(slots_num)))
852 		return -EINVAL;
853 
854 	q->low_mark = q->n_window / 4;
855 	if (q->low_mark < 4)
856 		q->low_mark = 4;
857 
858 	q->high_mark = q->n_window / 8;
859 	if (q->high_mark < 2)
860 		q->high_mark = 2;
861 
862 	q->write_ptr = 0;
863 	q->read_ptr = 0;
864 
865 	return 0;
866 }
867 
868 int iwl_txq_init(struct iwl_trans *trans, struct iwl_txq *txq,
869 		 int slots_num, bool cmd_queue)
870 {
871 	u32 tfd_queue_max_size =
872 		trans->trans_cfg->base_params->max_tfd_queue_size;
873 	int ret;
874 
875 	txq->need_update = false;
876 
877 	/* max_tfd_queue_size must be power-of-two size, otherwise
878 	 * iwl_txq_inc_wrap and iwl_txq_dec_wrap are broken.
879 	 */
880 	if (WARN_ONCE(tfd_queue_max_size & (tfd_queue_max_size - 1),
881 		      "Max tfd queue size must be a power of two, but is %d",
882 		      tfd_queue_max_size))
883 		return -EINVAL;
884 
885 	/* Initialize queue's high/low-water marks, and head/tail indexes */
886 	ret = iwl_queue_init(txq, slots_num);
887 	if (ret)
888 		return ret;
889 
890 	spin_lock_init(&txq->lock);
891 
892 	if (cmd_queue) {
893 		static struct lock_class_key iwl_txq_cmd_queue_lock_class;
894 
895 		lockdep_set_class(&txq->lock, &iwl_txq_cmd_queue_lock_class);
896 	}
897 
898 	__skb_queue_head_init(&txq->overflow_q);
899 
900 	return 0;
901 }
902 
903 int iwl_pcie_tx_init(struct iwl_trans *trans)
904 {
905 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
906 	int ret;
907 	int txq_id, slots_num;
908 	bool alloc = false;
909 
910 	if (!trans_pcie->txq_memory) {
911 		ret = iwl_pcie_tx_alloc(trans);
912 		if (ret)
913 			goto error;
914 		alloc = true;
915 	}
916 
917 	spin_lock_bh(&trans_pcie->irq_lock);
918 
919 	/* Turn off all Tx DMA fifos */
920 	iwl_scd_deactivate_fifos(trans);
921 
922 	/* Tell NIC where to find the "keep warm" buffer */
923 	iwl_write_direct32(trans, FH_KW_MEM_ADDR_REG,
924 			   trans_pcie->kw.dma >> 4);
925 
926 	spin_unlock_bh(&trans_pcie->irq_lock);
927 
928 	/* Alloc and init all Tx queues, including the command queue (#4/#9) */
929 	for (txq_id = 0; txq_id < trans->trans_cfg->base_params->num_of_queues;
930 	     txq_id++) {
931 		bool cmd_queue = (txq_id == trans_pcie->txqs.cmd.q_id);
932 
933 		if (cmd_queue)
934 			slots_num = max_t(u32, IWL_CMD_QUEUE_SIZE,
935 					  trans->cfg->min_txq_size);
936 		else
937 			slots_num = max_t(u32, IWL_DEFAULT_QUEUE_SIZE,
938 					  trans->cfg->min_ba_txq_size);
939 		ret = iwl_txq_init(trans, trans_pcie->txqs.txq[txq_id], slots_num,
940 				   cmd_queue);
941 		if (ret) {
942 			IWL_ERR(trans, "Tx %d queue init failed\n", txq_id);
943 			goto error;
944 		}
945 
946 		/*
947 		 * Tell nic where to find circular buffer of TFDs for a
948 		 * given Tx queue, and enable the DMA channel used for that
949 		 * queue.
950 		 * Circular buffer (TFD queue in DRAM) physical base address
951 		 */
952 		iwl_write_direct32(trans, FH_MEM_CBBC_QUEUE(trans, txq_id),
953 				   trans_pcie->txqs.txq[txq_id]->dma_addr >> 8);
954 	}
955 
956 	iwl_set_bits_prph(trans, SCD_GP_CTRL, SCD_GP_CTRL_AUTO_ACTIVE_MODE);
957 	if (trans->trans_cfg->base_params->num_of_queues > 20)
958 		iwl_set_bits_prph(trans, SCD_GP_CTRL,
959 				  SCD_GP_CTRL_ENABLE_31_QUEUES);
960 
961 	return 0;
962 error:
963 	/*Upon error, free only if we allocated something */
964 	if (alloc)
965 		iwl_pcie_tx_free(trans);
966 	return ret;
967 }
968 
969 static int iwl_pcie_set_cmd_in_flight(struct iwl_trans *trans,
970 				      const struct iwl_host_cmd *cmd)
971 {
972 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
973 
974 	/* Make sure the NIC is still alive in the bus */
975 	if (test_bit(STATUS_TRANS_DEAD, &trans->status))
976 		return -ENODEV;
977 
978 	if (!trans->trans_cfg->base_params->apmg_wake_up_wa)
979 		return 0;
980 
981 	/*
982 	 * wake up the NIC to make sure that the firmware will see the host
983 	 * command - we will let the NIC sleep once all the host commands
984 	 * returned. This needs to be done only on NICs that have
985 	 * apmg_wake_up_wa set (see above.)
986 	 */
987 	if (!_iwl_trans_pcie_grab_nic_access(trans))
988 		return -EIO;
989 
990 	/*
991 	 * In iwl_trans_grab_nic_access(), we've acquired the reg_lock.
992 	 * There, we also returned immediately if cmd_hold_nic_awake is
993 	 * already true, so it's OK to unconditionally set it to true.
994 	 */
995 	trans_pcie->cmd_hold_nic_awake = true;
996 	spin_unlock(&trans_pcie->reg_lock);
997 
998 	return 0;
999 }
1000 
1001 static void iwl_txq_progress(struct iwl_txq *txq)
1002 {
1003 	lockdep_assert_held(&txq->lock);
1004 
1005 	if (!txq->wd_timeout)
1006 		return;
1007 
1008 	/*
1009 	 * station is asleep and we send data - that must
1010 	 * be uAPSD or PS-Poll. Don't rearm the timer.
1011 	 */
1012 	if (txq->frozen)
1013 		return;
1014 
1015 	/*
1016 	 * if empty delete timer, otherwise move timer forward
1017 	 * since we're making progress on this queue
1018 	 */
1019 	if (txq->read_ptr == txq->write_ptr)
1020 		del_timer(&txq->stuck_timer);
1021 	else
1022 		mod_timer(&txq->stuck_timer, jiffies + txq->wd_timeout);
1023 }
1024 
1025 static inline bool iwl_txq_used(const struct iwl_txq *q, int i)
1026 {
1027 	int index = iwl_txq_get_cmd_index(q, i);
1028 	int r = iwl_txq_get_cmd_index(q, q->read_ptr);
1029 	int w = iwl_txq_get_cmd_index(q, q->write_ptr);
1030 
1031 	return w >= r ?
1032 		(index >= r && index < w) :
1033 		!(index < r && index >= w);
1034 }
1035 
1036 /*
1037  * iwl_pcie_cmdq_reclaim - Reclaim TX command queue entries already Tx'd
1038  *
1039  * When FW advances 'R' index, all entries between old and new 'R' index
1040  * need to be reclaimed. As result, some free space forms.  If there is
1041  * enough free space (> low mark), wake the stack that feeds us.
1042  */
1043 static void iwl_pcie_cmdq_reclaim(struct iwl_trans *trans, int txq_id, int idx)
1044 {
1045 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1046 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
1047 	int nfreed = 0;
1048 	u16 r;
1049 
1050 	lockdep_assert_held(&txq->lock);
1051 
1052 	idx = iwl_txq_get_cmd_index(txq, idx);
1053 	r = iwl_txq_get_cmd_index(txq, txq->read_ptr);
1054 
1055 	if (idx >= trans->trans_cfg->base_params->max_tfd_queue_size ||
1056 	    (!iwl_txq_used(txq, idx))) {
1057 		WARN_ONCE(test_bit(txq_id, trans_pcie->txqs.queue_used),
1058 			  "%s: Read index for DMA queue txq id (%d), index %d is out of range [0-%d] %d %d.\n",
1059 			  __func__, txq_id, idx,
1060 			  trans->trans_cfg->base_params->max_tfd_queue_size,
1061 			  txq->write_ptr, txq->read_ptr);
1062 		return;
1063 	}
1064 
1065 	for (idx = iwl_txq_inc_wrap(trans, idx); r != idx;
1066 	     r = iwl_txq_inc_wrap(trans, r)) {
1067 		txq->read_ptr = iwl_txq_inc_wrap(trans, txq->read_ptr);
1068 
1069 		if (nfreed++ > 0) {
1070 			IWL_ERR(trans, "HCMD skipped: index (%d) %d %d\n",
1071 				idx, txq->write_ptr, r);
1072 			iwl_force_nmi(trans);
1073 		}
1074 	}
1075 
1076 	if (txq->read_ptr == txq->write_ptr)
1077 		iwl_pcie_clear_cmd_in_flight(trans);
1078 
1079 	iwl_txq_progress(txq);
1080 }
1081 
1082 static int iwl_pcie_txq_set_ratid_map(struct iwl_trans *trans, u16 ra_tid,
1083 				 u16 txq_id)
1084 {
1085 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1086 	u32 tbl_dw_addr;
1087 	u32 tbl_dw;
1088 	u16 scd_q2ratid;
1089 
1090 	scd_q2ratid = ra_tid & SCD_QUEUE_RA_TID_MAP_RATID_MSK;
1091 
1092 	tbl_dw_addr = trans_pcie->scd_base_addr +
1093 			SCD_TRANS_TBL_OFFSET_QUEUE(txq_id);
1094 
1095 	tbl_dw = iwl_trans_read_mem32(trans, tbl_dw_addr);
1096 
1097 	if (txq_id & 0x1)
1098 		tbl_dw = (scd_q2ratid << 16) | (tbl_dw & 0x0000FFFF);
1099 	else
1100 		tbl_dw = scd_q2ratid | (tbl_dw & 0xFFFF0000);
1101 
1102 	iwl_trans_write_mem32(trans, tbl_dw_addr, tbl_dw);
1103 
1104 	return 0;
1105 }
1106 
1107 /* Receiver address (actually, Rx station's index into station table),
1108  * combined with Traffic ID (QOS priority), in format used by Tx Scheduler */
1109 #define BUILD_RAxTID(sta_id, tid)	(((sta_id) << 4) + (tid))
1110 
1111 bool iwl_trans_pcie_txq_enable(struct iwl_trans *trans, int txq_id, u16 ssn,
1112 			       const struct iwl_trans_txq_scd_cfg *cfg,
1113 			       unsigned int wdg_timeout)
1114 {
1115 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1116 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
1117 	int fifo = -1;
1118 	bool scd_bug = false;
1119 
1120 	if (test_and_set_bit(txq_id, trans_pcie->txqs.queue_used))
1121 		WARN_ONCE(1, "queue %d already used - expect issues", txq_id);
1122 
1123 	txq->wd_timeout = msecs_to_jiffies(wdg_timeout);
1124 
1125 	if (cfg) {
1126 		fifo = cfg->fifo;
1127 
1128 		/* Disable the scheduler prior configuring the cmd queue */
1129 		if (txq_id == trans_pcie->txqs.cmd.q_id &&
1130 		    trans_pcie->scd_set_active)
1131 			iwl_scd_enable_set_active(trans, 0);
1132 
1133 		/* Stop this Tx queue before configuring it */
1134 		iwl_scd_txq_set_inactive(trans, txq_id);
1135 
1136 		/* Set this queue as a chain-building queue unless it is CMD */
1137 		if (txq_id != trans_pcie->txqs.cmd.q_id)
1138 			iwl_scd_txq_set_chain(trans, txq_id);
1139 
1140 		if (cfg->aggregate) {
1141 			u16 ra_tid = BUILD_RAxTID(cfg->sta_id, cfg->tid);
1142 
1143 			/* Map receiver-address / traffic-ID to this queue */
1144 			iwl_pcie_txq_set_ratid_map(trans, ra_tid, txq_id);
1145 
1146 			/* enable aggregations for the queue */
1147 			iwl_scd_txq_enable_agg(trans, txq_id);
1148 			txq->ampdu = true;
1149 		} else {
1150 			/*
1151 			 * disable aggregations for the queue, this will also
1152 			 * make the ra_tid mapping configuration irrelevant
1153 			 * since it is now a non-AGG queue.
1154 			 */
1155 			iwl_scd_txq_disable_agg(trans, txq_id);
1156 
1157 			ssn = txq->read_ptr;
1158 		}
1159 	} else {
1160 		/*
1161 		 * If we need to move the SCD write pointer by steps of
1162 		 * 0x40, 0x80 or 0xc0, it gets stuck. Avoids this and let
1163 		 * the op_mode know by returning true later.
1164 		 * Do this only in case cfg is NULL since this trick can
1165 		 * be done only if we have DQA enabled which is true for mvm
1166 		 * only. And mvm never sets a cfg pointer.
1167 		 * This is really ugly, but this is the easiest way out for
1168 		 * this sad hardware issue.
1169 		 * This bug has been fixed on devices 9000 and up.
1170 		 */
1171 		scd_bug = !trans->trans_cfg->mq_rx_supported &&
1172 			!((ssn - txq->write_ptr) & 0x3f) &&
1173 			(ssn != txq->write_ptr);
1174 		if (scd_bug)
1175 			ssn++;
1176 	}
1177 
1178 	/* Place first TFD at index corresponding to start sequence number.
1179 	 * Assumes that ssn_idx is valid (!= 0xFFF) */
1180 	txq->read_ptr = (ssn & 0xff);
1181 	txq->write_ptr = (ssn & 0xff);
1182 	iwl_write_direct32(trans, HBUS_TARG_WRPTR,
1183 			   (ssn & 0xff) | (txq_id << 8));
1184 
1185 	if (cfg) {
1186 		u8 frame_limit = cfg->frame_limit;
1187 
1188 		iwl_write_prph(trans, SCD_QUEUE_RDPTR(txq_id), ssn);
1189 
1190 		/* Set up Tx window size and frame limit for this queue */
1191 		iwl_trans_write_mem32(trans, trans_pcie->scd_base_addr +
1192 				SCD_CONTEXT_QUEUE_OFFSET(txq_id), 0);
1193 		iwl_trans_write_mem32(trans,
1194 			trans_pcie->scd_base_addr +
1195 			SCD_CONTEXT_QUEUE_OFFSET(txq_id) + sizeof(u32),
1196 			SCD_QUEUE_CTX_REG2_VAL(WIN_SIZE, frame_limit) |
1197 			SCD_QUEUE_CTX_REG2_VAL(FRAME_LIMIT, frame_limit));
1198 
1199 		/* Set up status area in SRAM, map to Tx DMA/FIFO, activate */
1200 		iwl_write_prph(trans, SCD_QUEUE_STATUS_BITS(txq_id),
1201 			       (1 << SCD_QUEUE_STTS_REG_POS_ACTIVE) |
1202 			       (cfg->fifo << SCD_QUEUE_STTS_REG_POS_TXF) |
1203 			       (1 << SCD_QUEUE_STTS_REG_POS_WSL) |
1204 			       SCD_QUEUE_STTS_REG_MSK);
1205 
1206 		/* enable the scheduler for this queue (only) */
1207 		if (txq_id == trans_pcie->txqs.cmd.q_id &&
1208 		    trans_pcie->scd_set_active)
1209 			iwl_scd_enable_set_active(trans, BIT(txq_id));
1210 
1211 		IWL_DEBUG_TX_QUEUES(trans,
1212 				    "Activate queue %d on FIFO %d WrPtr: %d\n",
1213 				    txq_id, fifo, ssn & 0xff);
1214 	} else {
1215 		IWL_DEBUG_TX_QUEUES(trans,
1216 				    "Activate queue %d WrPtr: %d\n",
1217 				    txq_id, ssn & 0xff);
1218 	}
1219 
1220 	return scd_bug;
1221 }
1222 
1223 void iwl_trans_pcie_txq_set_shared_mode(struct iwl_trans *trans, u32 txq_id,
1224 					bool shared_mode)
1225 {
1226 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1227 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
1228 
1229 	txq->ampdu = !shared_mode;
1230 }
1231 
1232 void iwl_trans_pcie_txq_disable(struct iwl_trans *trans, int txq_id,
1233 				bool configure_scd)
1234 {
1235 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1236 	u32 stts_addr = trans_pcie->scd_base_addr +
1237 			SCD_TX_STTS_QUEUE_OFFSET(txq_id);
1238 	static const u32 zero_val[4] = {};
1239 
1240 	trans_pcie->txqs.txq[txq_id]->frozen_expiry_remainder = 0;
1241 	trans_pcie->txqs.txq[txq_id]->frozen = false;
1242 
1243 	/*
1244 	 * Upon HW Rfkill - we stop the device, and then stop the queues
1245 	 * in the op_mode. Just for the sake of the simplicity of the op_mode,
1246 	 * allow the op_mode to call txq_disable after it already called
1247 	 * stop_device.
1248 	 */
1249 	if (!test_and_clear_bit(txq_id, trans_pcie->txqs.queue_used)) {
1250 		WARN_ONCE(test_bit(STATUS_DEVICE_ENABLED, &trans->status),
1251 			  "queue %d not used", txq_id);
1252 		return;
1253 	}
1254 
1255 	if (configure_scd) {
1256 		iwl_scd_txq_set_inactive(trans, txq_id);
1257 
1258 		iwl_trans_write_mem(trans, stts_addr, (const void *)zero_val,
1259 				    ARRAY_SIZE(zero_val));
1260 	}
1261 
1262 	iwl_pcie_txq_unmap(trans, txq_id);
1263 	trans_pcie->txqs.txq[txq_id]->ampdu = false;
1264 
1265 	IWL_DEBUG_TX_QUEUES(trans, "Deactivate queue %d\n", txq_id);
1266 }
1267 
1268 /*************** HOST COMMAND QUEUE FUNCTIONS   *****/
1269 
1270 static void iwl_trans_pcie_block_txq_ptrs(struct iwl_trans *trans, bool block)
1271 {
1272 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1273 	int i;
1274 
1275 	for (i = 0; i < trans->trans_cfg->base_params->num_of_queues; i++) {
1276 		struct iwl_txq *txq = trans_pcie->txqs.txq[i];
1277 
1278 		if (i == trans_pcie->txqs.cmd.q_id)
1279 			continue;
1280 
1281 		/* we skip the command queue (obviously) so it's OK to nest */
1282 		spin_lock_nested(&txq->lock, 1);
1283 
1284 		if (!block && !(WARN_ON_ONCE(!txq->block))) {
1285 			txq->block--;
1286 			if (!txq->block) {
1287 				iwl_write32(trans, HBUS_TARG_WRPTR,
1288 					    txq->write_ptr | (i << 8));
1289 			}
1290 		} else if (block) {
1291 			txq->block++;
1292 		}
1293 
1294 		spin_unlock(&txq->lock);
1295 	}
1296 }
1297 
1298 /*
1299  * iwl_pcie_enqueue_hcmd - enqueue a uCode command
1300  * @priv: device private data point
1301  * @cmd: a pointer to the ucode command structure
1302  *
1303  * The function returns < 0 values to indicate the operation
1304  * failed. On success, it returns the index (>= 0) of command in the
1305  * command queue.
1306  */
1307 int iwl_pcie_enqueue_hcmd(struct iwl_trans *trans,
1308 			  struct iwl_host_cmd *cmd)
1309 {
1310 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1311 	struct iwl_txq *txq = trans_pcie->txqs.txq[trans_pcie->txqs.cmd.q_id];
1312 	struct iwl_device_cmd *out_cmd;
1313 	struct iwl_cmd_meta *out_meta;
1314 	void *dup_buf = NULL;
1315 	dma_addr_t phys_addr;
1316 	int idx;
1317 	u16 copy_size, cmd_size, tb0_size;
1318 	bool had_nocopy = false;
1319 	u8 group_id = iwl_cmd_groupid(cmd->id);
1320 	int i, ret;
1321 	u32 cmd_pos;
1322 	const u8 *cmddata[IWL_MAX_CMD_TBS_PER_TFD];
1323 	u16 cmdlen[IWL_MAX_CMD_TBS_PER_TFD];
1324 	unsigned long flags;
1325 
1326 	if (WARN(!trans->wide_cmd_header &&
1327 		 group_id > IWL_ALWAYS_LONG_GROUP,
1328 		 "unsupported wide command %#x\n", cmd->id))
1329 		return -EINVAL;
1330 
1331 	if (group_id != 0) {
1332 		copy_size = sizeof(struct iwl_cmd_header_wide);
1333 		cmd_size = sizeof(struct iwl_cmd_header_wide);
1334 	} else {
1335 		copy_size = sizeof(struct iwl_cmd_header);
1336 		cmd_size = sizeof(struct iwl_cmd_header);
1337 	}
1338 
1339 	/* need one for the header if the first is NOCOPY */
1340 	BUILD_BUG_ON(IWL_MAX_CMD_TBS_PER_TFD > IWL_NUM_OF_TBS - 1);
1341 
1342 	for (i = 0; i < IWL_MAX_CMD_TBS_PER_TFD; i++) {
1343 		cmddata[i] = cmd->data[i];
1344 		cmdlen[i] = cmd->len[i];
1345 
1346 		if (!cmd->len[i])
1347 			continue;
1348 
1349 		/* need at least IWL_FIRST_TB_SIZE copied */
1350 		if (copy_size < IWL_FIRST_TB_SIZE) {
1351 			int copy = IWL_FIRST_TB_SIZE - copy_size;
1352 
1353 			if (copy > cmdlen[i])
1354 				copy = cmdlen[i];
1355 			cmdlen[i] -= copy;
1356 			cmddata[i] += copy;
1357 			copy_size += copy;
1358 		}
1359 
1360 		if (cmd->dataflags[i] & IWL_HCMD_DFL_NOCOPY) {
1361 			had_nocopy = true;
1362 			if (WARN_ON(cmd->dataflags[i] & IWL_HCMD_DFL_DUP)) {
1363 				idx = -EINVAL;
1364 				goto free_dup_buf;
1365 			}
1366 		} else if (cmd->dataflags[i] & IWL_HCMD_DFL_DUP) {
1367 			/*
1368 			 * This is also a chunk that isn't copied
1369 			 * to the static buffer so set had_nocopy.
1370 			 */
1371 			had_nocopy = true;
1372 
1373 			/* only allowed once */
1374 			if (WARN_ON(dup_buf)) {
1375 				idx = -EINVAL;
1376 				goto free_dup_buf;
1377 			}
1378 
1379 			dup_buf = kmemdup(cmddata[i], cmdlen[i],
1380 					  GFP_ATOMIC);
1381 			if (!dup_buf)
1382 				return -ENOMEM;
1383 		} else {
1384 			/* NOCOPY must not be followed by normal! */
1385 			if (WARN_ON(had_nocopy)) {
1386 				idx = -EINVAL;
1387 				goto free_dup_buf;
1388 			}
1389 			copy_size += cmdlen[i];
1390 		}
1391 		cmd_size += cmd->len[i];
1392 	}
1393 
1394 	/*
1395 	 * If any of the command structures end up being larger than
1396 	 * the TFD_MAX_PAYLOAD_SIZE and they aren't dynamically
1397 	 * allocated into separate TFDs, then we will need to
1398 	 * increase the size of the buffers.
1399 	 */
1400 	if (WARN(copy_size > TFD_MAX_PAYLOAD_SIZE,
1401 		 "Command %s (%#x) is too large (%d bytes)\n",
1402 		 iwl_get_cmd_string(trans, cmd->id),
1403 		 cmd->id, copy_size)) {
1404 		idx = -EINVAL;
1405 		goto free_dup_buf;
1406 	}
1407 
1408 	spin_lock_irqsave(&txq->lock, flags);
1409 
1410 	if (iwl_txq_space(trans, txq) < ((cmd->flags & CMD_ASYNC) ? 2 : 1)) {
1411 		spin_unlock_irqrestore(&txq->lock, flags);
1412 
1413 		IWL_ERR(trans, "No space in command queue\n");
1414 		iwl_op_mode_cmd_queue_full(trans->op_mode);
1415 		idx = -ENOSPC;
1416 		goto free_dup_buf;
1417 	}
1418 
1419 	idx = iwl_txq_get_cmd_index(txq, txq->write_ptr);
1420 	out_cmd = txq->entries[idx].cmd;
1421 	out_meta = &txq->entries[idx].meta;
1422 
1423 	memset(out_meta, 0, sizeof(*out_meta));	/* re-initialize to NULL */
1424 	if (cmd->flags & CMD_WANT_SKB)
1425 		out_meta->source = cmd;
1426 
1427 	/* set up the header */
1428 	if (group_id != 0) {
1429 		out_cmd->hdr_wide.cmd = iwl_cmd_opcode(cmd->id);
1430 		out_cmd->hdr_wide.group_id = group_id;
1431 		out_cmd->hdr_wide.version = iwl_cmd_version(cmd->id);
1432 		out_cmd->hdr_wide.length =
1433 			cpu_to_le16(cmd_size -
1434 				    sizeof(struct iwl_cmd_header_wide));
1435 		out_cmd->hdr_wide.reserved = 0;
1436 		out_cmd->hdr_wide.sequence =
1437 			cpu_to_le16(QUEUE_TO_SEQ(trans_pcie->txqs.cmd.q_id) |
1438 						 INDEX_TO_SEQ(txq->write_ptr));
1439 
1440 		cmd_pos = sizeof(struct iwl_cmd_header_wide);
1441 		copy_size = sizeof(struct iwl_cmd_header_wide);
1442 	} else {
1443 		out_cmd->hdr.cmd = iwl_cmd_opcode(cmd->id);
1444 		out_cmd->hdr.sequence =
1445 			cpu_to_le16(QUEUE_TO_SEQ(trans_pcie->txqs.cmd.q_id) |
1446 						 INDEX_TO_SEQ(txq->write_ptr));
1447 		out_cmd->hdr.group_id = 0;
1448 
1449 		cmd_pos = sizeof(struct iwl_cmd_header);
1450 		copy_size = sizeof(struct iwl_cmd_header);
1451 	}
1452 
1453 	/* and copy the data that needs to be copied */
1454 	for (i = 0; i < IWL_MAX_CMD_TBS_PER_TFD; i++) {
1455 		int copy;
1456 
1457 		if (!cmd->len[i])
1458 			continue;
1459 
1460 		/* copy everything if not nocopy/dup */
1461 		if (!(cmd->dataflags[i] & (IWL_HCMD_DFL_NOCOPY |
1462 					   IWL_HCMD_DFL_DUP))) {
1463 			copy = cmd->len[i];
1464 
1465 			memcpy((u8 *)out_cmd + cmd_pos, cmd->data[i], copy);
1466 			cmd_pos += copy;
1467 			copy_size += copy;
1468 			continue;
1469 		}
1470 
1471 		/*
1472 		 * Otherwise we need at least IWL_FIRST_TB_SIZE copied
1473 		 * in total (for bi-directional DMA), but copy up to what
1474 		 * we can fit into the payload for debug dump purposes.
1475 		 */
1476 		copy = min_t(int, TFD_MAX_PAYLOAD_SIZE - cmd_pos, cmd->len[i]);
1477 
1478 		memcpy((u8 *)out_cmd + cmd_pos, cmd->data[i], copy);
1479 		cmd_pos += copy;
1480 
1481 		/* However, treat copy_size the proper way, we need it below */
1482 		if (copy_size < IWL_FIRST_TB_SIZE) {
1483 			copy = IWL_FIRST_TB_SIZE - copy_size;
1484 
1485 			if (copy > cmd->len[i])
1486 				copy = cmd->len[i];
1487 			copy_size += copy;
1488 		}
1489 	}
1490 
1491 	IWL_DEBUG_HC(trans,
1492 		     "Sending command %s (%.2x.%.2x), seq: 0x%04X, %d bytes at %d[%d]:%d\n",
1493 		     iwl_get_cmd_string(trans, cmd->id),
1494 		     group_id, out_cmd->hdr.cmd,
1495 		     le16_to_cpu(out_cmd->hdr.sequence),
1496 		     cmd_size, txq->write_ptr, idx, trans_pcie->txqs.cmd.q_id);
1497 
1498 	/* start the TFD with the minimum copy bytes */
1499 	tb0_size = min_t(int, copy_size, IWL_FIRST_TB_SIZE);
1500 	memcpy(&txq->first_tb_bufs[idx], &out_cmd->hdr, tb0_size);
1501 	iwl_pcie_txq_build_tfd(trans, txq,
1502 			       iwl_txq_get_first_tb_dma(txq, idx),
1503 			       tb0_size, true);
1504 
1505 	/* map first command fragment, if any remains */
1506 	if (copy_size > tb0_size) {
1507 		phys_addr = dma_map_single(trans->dev,
1508 					   ((u8 *)&out_cmd->hdr) + tb0_size,
1509 					   copy_size - tb0_size,
1510 					   DMA_TO_DEVICE);
1511 		if (dma_mapping_error(trans->dev, phys_addr)) {
1512 			iwl_txq_gen1_tfd_unmap(trans, out_meta, txq,
1513 					       txq->write_ptr);
1514 			idx = -ENOMEM;
1515 			goto out;
1516 		}
1517 
1518 		iwl_pcie_txq_build_tfd(trans, txq, phys_addr,
1519 				       copy_size - tb0_size, false);
1520 	}
1521 
1522 	/* map the remaining (adjusted) nocopy/dup fragments */
1523 	for (i = 0; i < IWL_MAX_CMD_TBS_PER_TFD; i++) {
1524 		void *data = (void *)(uintptr_t)cmddata[i];
1525 
1526 		if (!cmdlen[i])
1527 			continue;
1528 		if (!(cmd->dataflags[i] & (IWL_HCMD_DFL_NOCOPY |
1529 					   IWL_HCMD_DFL_DUP)))
1530 			continue;
1531 		if (cmd->dataflags[i] & IWL_HCMD_DFL_DUP)
1532 			data = dup_buf;
1533 		phys_addr = dma_map_single(trans->dev, data,
1534 					   cmdlen[i], DMA_TO_DEVICE);
1535 		if (dma_mapping_error(trans->dev, phys_addr)) {
1536 			iwl_txq_gen1_tfd_unmap(trans, out_meta, txq,
1537 					       txq->write_ptr);
1538 			idx = -ENOMEM;
1539 			goto out;
1540 		}
1541 
1542 		iwl_pcie_txq_build_tfd(trans, txq, phys_addr, cmdlen[i], false);
1543 	}
1544 
1545 	BUILD_BUG_ON(IWL_TFH_NUM_TBS > sizeof(out_meta->tbs) * BITS_PER_BYTE);
1546 	out_meta->flags = cmd->flags;
1547 	if (WARN_ON_ONCE(txq->entries[idx].free_buf))
1548 		kfree_sensitive(txq->entries[idx].free_buf);
1549 	txq->entries[idx].free_buf = dup_buf;
1550 
1551 	trace_iwlwifi_dev_hcmd(trans->dev, cmd, cmd_size, &out_cmd->hdr_wide);
1552 
1553 	/* start timer if queue currently empty */
1554 	if (txq->read_ptr == txq->write_ptr && txq->wd_timeout)
1555 		mod_timer(&txq->stuck_timer, jiffies + txq->wd_timeout);
1556 
1557 	ret = iwl_pcie_set_cmd_in_flight(trans, cmd);
1558 	if (ret < 0) {
1559 		idx = ret;
1560 		goto out;
1561 	}
1562 
1563 	if (cmd->flags & CMD_BLOCK_TXQS)
1564 		iwl_trans_pcie_block_txq_ptrs(trans, true);
1565 
1566 	/* Increment and update queue's write index */
1567 	txq->write_ptr = iwl_txq_inc_wrap(trans, txq->write_ptr);
1568 	iwl_pcie_txq_inc_wr_ptr(trans, txq);
1569 
1570  out:
1571 	spin_unlock_irqrestore(&txq->lock, flags);
1572  free_dup_buf:
1573 	if (idx < 0)
1574 		kfree(dup_buf);
1575 	return idx;
1576 }
1577 
1578 /*
1579  * iwl_pcie_hcmd_complete - Pull unused buffers off the queue and reclaim them
1580  * @rxb: Rx buffer to reclaim
1581  */
1582 void iwl_pcie_hcmd_complete(struct iwl_trans *trans,
1583 			    struct iwl_rx_cmd_buffer *rxb)
1584 {
1585 	struct iwl_rx_packet *pkt = rxb_addr(rxb);
1586 	u16 sequence = le16_to_cpu(pkt->hdr.sequence);
1587 	u8 group_id;
1588 	u32 cmd_id;
1589 	int txq_id = SEQ_TO_QUEUE(sequence);
1590 	int index = SEQ_TO_INDEX(sequence);
1591 	int cmd_index;
1592 	struct iwl_device_cmd *cmd;
1593 	struct iwl_cmd_meta *meta;
1594 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1595 	struct iwl_txq *txq = trans_pcie->txqs.txq[trans_pcie->txqs.cmd.q_id];
1596 
1597 	/* If a Tx command is being handled and it isn't in the actual
1598 	 * command queue then there a command routing bug has been introduced
1599 	 * in the queue management code. */
1600 	if (WARN(txq_id != trans_pcie->txqs.cmd.q_id,
1601 		 "wrong command queue %d (should be %d), sequence 0x%X readp=%d writep=%d\n",
1602 		 txq_id, trans_pcie->txqs.cmd.q_id, sequence, txq->read_ptr,
1603 		 txq->write_ptr)) {
1604 		iwl_print_hex_error(trans, pkt, 32);
1605 		return;
1606 	}
1607 
1608 	spin_lock_bh(&txq->lock);
1609 
1610 	cmd_index = iwl_txq_get_cmd_index(txq, index);
1611 	cmd = txq->entries[cmd_index].cmd;
1612 	meta = &txq->entries[cmd_index].meta;
1613 	group_id = cmd->hdr.group_id;
1614 	cmd_id = WIDE_ID(group_id, cmd->hdr.cmd);
1615 
1616 	if (trans->trans_cfg->gen2)
1617 		iwl_txq_gen2_tfd_unmap(trans, meta,
1618 				       iwl_txq_get_tfd(trans, txq, index));
1619 	else
1620 		iwl_txq_gen1_tfd_unmap(trans, meta, txq, index);
1621 
1622 	/* Input error checking is done when commands are added to queue. */
1623 	if (meta->flags & CMD_WANT_SKB) {
1624 		struct page *p = rxb_steal_page(rxb);
1625 
1626 		meta->source->resp_pkt = pkt;
1627 		meta->source->_rx_page_addr = (unsigned long)page_address(p);
1628 		meta->source->_rx_page_order = trans_pcie->rx_page_order;
1629 	}
1630 
1631 	if (meta->flags & CMD_BLOCK_TXQS)
1632 		iwl_trans_pcie_block_txq_ptrs(trans, false);
1633 
1634 	iwl_pcie_cmdq_reclaim(trans, txq_id, index);
1635 
1636 	if (!(meta->flags & CMD_ASYNC)) {
1637 		if (!test_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status)) {
1638 			IWL_WARN(trans,
1639 				 "HCMD_ACTIVE already clear for command %s\n",
1640 				 iwl_get_cmd_string(trans, cmd_id));
1641 		}
1642 		clear_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status);
1643 		IWL_DEBUG_INFO(trans, "Clearing HCMD_ACTIVE for command %s\n",
1644 			       iwl_get_cmd_string(trans, cmd_id));
1645 		wake_up(&trans->wait_command_queue);
1646 	}
1647 
1648 	meta->flags = 0;
1649 
1650 	spin_unlock_bh(&txq->lock);
1651 }
1652 
1653 static int iwl_fill_data_tbs(struct iwl_trans *trans, struct sk_buff *skb,
1654 			     struct iwl_txq *txq, u8 hdr_len,
1655 			     struct iwl_cmd_meta *out_meta)
1656 {
1657 	u16 head_tb_len;
1658 	int i;
1659 
1660 	/*
1661 	 * Set up TFD's third entry to point directly to remainder
1662 	 * of skb's head, if any
1663 	 */
1664 	head_tb_len = skb_headlen(skb) - hdr_len;
1665 
1666 	if (head_tb_len > 0) {
1667 		dma_addr_t tb_phys = dma_map_single(trans->dev,
1668 						    skb->data + hdr_len,
1669 						    head_tb_len, DMA_TO_DEVICE);
1670 		if (unlikely(dma_mapping_error(trans->dev, tb_phys)))
1671 			return -EINVAL;
1672 		trace_iwlwifi_dev_tx_tb(trans->dev, skb, skb->data + hdr_len,
1673 					tb_phys, head_tb_len);
1674 		iwl_pcie_txq_build_tfd(trans, txq, tb_phys, head_tb_len, false);
1675 	}
1676 
1677 	/* set up the remaining entries to point to the data */
1678 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1679 		const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1680 		dma_addr_t tb_phys;
1681 		int tb_idx;
1682 
1683 		if (!skb_frag_size(frag))
1684 			continue;
1685 
1686 		tb_phys = skb_frag_dma_map(trans->dev, frag, 0,
1687 					   skb_frag_size(frag), DMA_TO_DEVICE);
1688 
1689 		if (unlikely(dma_mapping_error(trans->dev, tb_phys)))
1690 			return -EINVAL;
1691 		trace_iwlwifi_dev_tx_tb(trans->dev, skb, skb_frag_address(frag),
1692 					tb_phys, skb_frag_size(frag));
1693 		tb_idx = iwl_pcie_txq_build_tfd(trans, txq, tb_phys,
1694 						skb_frag_size(frag), false);
1695 		if (tb_idx < 0)
1696 			return tb_idx;
1697 
1698 		out_meta->tbs |= BIT(tb_idx);
1699 	}
1700 
1701 	return 0;
1702 }
1703 
1704 #ifdef CONFIG_INET
1705 struct iwl_tso_hdr_page *iwl_pcie_get_page_hdr(struct iwl_trans *trans,
1706 					       size_t len, struct sk_buff *skb)
1707 {
1708 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1709 	struct iwl_tso_hdr_page *p = this_cpu_ptr(trans_pcie->txqs.tso_hdr_page);
1710 	struct page **page_ptr;
1711 
1712 	page_ptr = (void *)((u8 *)skb->cb + trans_pcie->txqs.page_offs);
1713 
1714 	if (WARN_ON(*page_ptr))
1715 		return NULL;
1716 
1717 	if (!p->page)
1718 		goto alloc;
1719 
1720 	/*
1721 	 * Check if there's enough room on this page
1722 	 *
1723 	 * Note that we put a page chaining pointer *last* in the
1724 	 * page - we need it somewhere, and if it's there then we
1725 	 * avoid DMA mapping the last bits of the page which may
1726 	 * trigger the 32-bit boundary hardware bug.
1727 	 *
1728 	 * (see also get_workaround_page() in tx-gen2.c)
1729 	 */
1730 	if (p->pos + len < (u8 *)page_address(p->page) + PAGE_SIZE -
1731 			   sizeof(void *))
1732 		goto out;
1733 
1734 	/* We don't have enough room on this page, get a new one. */
1735 	__free_page(p->page);
1736 
1737 alloc:
1738 	p->page = alloc_page(GFP_ATOMIC);
1739 	if (!p->page)
1740 		return NULL;
1741 	p->pos = page_address(p->page);
1742 	/* set the chaining pointer to NULL */
1743 	*(void **)((u8 *)page_address(p->page) + PAGE_SIZE - sizeof(void *)) = NULL;
1744 out:
1745 	*page_ptr = p->page;
1746 	get_page(p->page);
1747 	return p;
1748 }
1749 
1750 static int iwl_fill_data_tbs_amsdu(struct iwl_trans *trans, struct sk_buff *skb,
1751 				   struct iwl_txq *txq, u8 hdr_len,
1752 				   struct iwl_cmd_meta *out_meta,
1753 				   struct iwl_device_tx_cmd *dev_cmd,
1754 				   u16 tb1_len)
1755 {
1756 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1757 	struct iwl_tx_cmd *tx_cmd = (void *)dev_cmd->payload;
1758 	struct ieee80211_hdr *hdr = (void *)skb->data;
1759 	unsigned int snap_ip_tcp_hdrlen, ip_hdrlen, total_len, hdr_room;
1760 	unsigned int mss = skb_shinfo(skb)->gso_size;
1761 	u16 length, iv_len, amsdu_pad;
1762 	u8 *start_hdr;
1763 	struct iwl_tso_hdr_page *hdr_page;
1764 	struct tso_t tso;
1765 
1766 	/* if the packet is protected, then it must be CCMP or GCMP */
1767 	BUILD_BUG_ON(IEEE80211_CCMP_HDR_LEN != IEEE80211_GCMP_HDR_LEN);
1768 	iv_len = ieee80211_has_protected(hdr->frame_control) ?
1769 		IEEE80211_CCMP_HDR_LEN : 0;
1770 
1771 	trace_iwlwifi_dev_tx(trans->dev, skb,
1772 			     iwl_txq_get_tfd(trans, txq, txq->write_ptr),
1773 			     trans_pcie->txqs.tfd.size,
1774 			     &dev_cmd->hdr, IWL_FIRST_TB_SIZE + tb1_len, 0);
1775 
1776 	ip_hdrlen = skb_network_header_len(skb);
1777 	snap_ip_tcp_hdrlen = 8 + ip_hdrlen + tcp_hdrlen(skb);
1778 	total_len = skb->len - snap_ip_tcp_hdrlen - hdr_len - iv_len;
1779 	amsdu_pad = 0;
1780 
1781 	/* total amount of header we may need for this A-MSDU */
1782 	hdr_room = DIV_ROUND_UP(total_len, mss) *
1783 		(3 + snap_ip_tcp_hdrlen + sizeof(struct ethhdr)) + iv_len;
1784 
1785 	/* Our device supports 9 segments at most, it will fit in 1 page */
1786 	hdr_page = iwl_pcie_get_page_hdr(trans, hdr_room, skb);
1787 	if (!hdr_page)
1788 		return -ENOMEM;
1789 
1790 	start_hdr = hdr_page->pos;
1791 	memcpy(hdr_page->pos, skb->data + hdr_len, iv_len);
1792 	hdr_page->pos += iv_len;
1793 
1794 	/*
1795 	 * Pull the ieee80211 header + IV to be able to use TSO core,
1796 	 * we will restore it for the tx_status flow.
1797 	 */
1798 	skb_pull(skb, hdr_len + iv_len);
1799 
1800 	/*
1801 	 * Remove the length of all the headers that we don't actually
1802 	 * have in the MPDU by themselves, but that we duplicate into
1803 	 * all the different MSDUs inside the A-MSDU.
1804 	 */
1805 	le16_add_cpu(&tx_cmd->len, -snap_ip_tcp_hdrlen);
1806 
1807 	tso_start(skb, &tso);
1808 
1809 	while (total_len) {
1810 		/* this is the data left for this subframe */
1811 		unsigned int data_left =
1812 			min_t(unsigned int, mss, total_len);
1813 		unsigned int hdr_tb_len;
1814 		dma_addr_t hdr_tb_phys;
1815 		u8 *subf_hdrs_start = hdr_page->pos;
1816 
1817 		total_len -= data_left;
1818 
1819 		memset(hdr_page->pos, 0, amsdu_pad);
1820 		hdr_page->pos += amsdu_pad;
1821 		amsdu_pad = (4 - (sizeof(struct ethhdr) + snap_ip_tcp_hdrlen +
1822 				  data_left)) & 0x3;
1823 		ether_addr_copy(hdr_page->pos, ieee80211_get_DA(hdr));
1824 		hdr_page->pos += ETH_ALEN;
1825 		ether_addr_copy(hdr_page->pos, ieee80211_get_SA(hdr));
1826 		hdr_page->pos += ETH_ALEN;
1827 
1828 		length = snap_ip_tcp_hdrlen + data_left;
1829 		*((__be16 *)hdr_page->pos) = cpu_to_be16(length);
1830 		hdr_page->pos += sizeof(length);
1831 
1832 		/*
1833 		 * This will copy the SNAP as well which will be considered
1834 		 * as MAC header.
1835 		 */
1836 		tso_build_hdr(skb, hdr_page->pos, &tso, data_left, !total_len);
1837 
1838 		hdr_page->pos += snap_ip_tcp_hdrlen;
1839 
1840 		hdr_tb_len = hdr_page->pos - start_hdr;
1841 		hdr_tb_phys = dma_map_single(trans->dev, start_hdr,
1842 					     hdr_tb_len, DMA_TO_DEVICE);
1843 		if (unlikely(dma_mapping_error(trans->dev, hdr_tb_phys)))
1844 			return -EINVAL;
1845 		iwl_pcie_txq_build_tfd(trans, txq, hdr_tb_phys,
1846 				       hdr_tb_len, false);
1847 		trace_iwlwifi_dev_tx_tb(trans->dev, skb, start_hdr,
1848 					hdr_tb_phys, hdr_tb_len);
1849 		/* add this subframe's headers' length to the tx_cmd */
1850 		le16_add_cpu(&tx_cmd->len, hdr_page->pos - subf_hdrs_start);
1851 
1852 		/* prepare the start_hdr for the next subframe */
1853 		start_hdr = hdr_page->pos;
1854 
1855 		/* put the payload */
1856 		while (data_left) {
1857 			unsigned int size = min_t(unsigned int, tso.size,
1858 						  data_left);
1859 			dma_addr_t tb_phys;
1860 
1861 			tb_phys = dma_map_single(trans->dev, tso.data,
1862 						 size, DMA_TO_DEVICE);
1863 			if (unlikely(dma_mapping_error(trans->dev, tb_phys)))
1864 				return -EINVAL;
1865 
1866 			iwl_pcie_txq_build_tfd(trans, txq, tb_phys,
1867 					       size, false);
1868 			trace_iwlwifi_dev_tx_tb(trans->dev, skb, tso.data,
1869 						tb_phys, size);
1870 
1871 			data_left -= size;
1872 			tso_build_data(skb, &tso, size);
1873 		}
1874 	}
1875 
1876 	/* re -add the WiFi header and IV */
1877 	skb_push(skb, hdr_len + iv_len);
1878 
1879 	return 0;
1880 }
1881 #else /* CONFIG_INET */
1882 static int iwl_fill_data_tbs_amsdu(struct iwl_trans *trans, struct sk_buff *skb,
1883 				   struct iwl_txq *txq, u8 hdr_len,
1884 				   struct iwl_cmd_meta *out_meta,
1885 				   struct iwl_device_tx_cmd *dev_cmd,
1886 				   u16 tb1_len)
1887 {
1888 	/* No A-MSDU without CONFIG_INET */
1889 	WARN_ON(1);
1890 
1891 	return -1;
1892 }
1893 #endif /* CONFIG_INET */
1894 
1895 #define IWL_TX_CRC_SIZE 4
1896 #define IWL_TX_DELIMITER_SIZE 4
1897 
1898 /*
1899  * iwl_txq_gen1_update_byte_cnt_tbl - Set up entry in Tx byte-count array
1900  */
1901 static void iwl_txq_gen1_update_byte_cnt_tbl(struct iwl_trans *trans,
1902 					     struct iwl_txq *txq, u16 byte_cnt,
1903 					     int num_tbs)
1904 {
1905 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1906 	struct iwlagn_scd_bc_tbl *scd_bc_tbl;
1907 	int write_ptr = txq->write_ptr;
1908 	int txq_id = txq->id;
1909 	u8 sec_ctl = 0;
1910 	u16 len = byte_cnt + IWL_TX_CRC_SIZE + IWL_TX_DELIMITER_SIZE;
1911 	__le16 bc_ent;
1912 	struct iwl_device_tx_cmd *dev_cmd = txq->entries[txq->write_ptr].cmd;
1913 	struct iwl_tx_cmd *tx_cmd = (void *)dev_cmd->payload;
1914 	u8 sta_id = tx_cmd->sta_id;
1915 
1916 	scd_bc_tbl = trans_pcie->txqs.scd_bc_tbls.addr;
1917 
1918 	sec_ctl = tx_cmd->sec_ctl;
1919 
1920 	switch (sec_ctl & TX_CMD_SEC_MSK) {
1921 	case TX_CMD_SEC_CCM:
1922 		len += IEEE80211_CCMP_MIC_LEN;
1923 		break;
1924 	case TX_CMD_SEC_TKIP:
1925 		len += IEEE80211_TKIP_ICV_LEN;
1926 		break;
1927 	case TX_CMD_SEC_WEP:
1928 		len += IEEE80211_WEP_IV_LEN + IEEE80211_WEP_ICV_LEN;
1929 		break;
1930 	}
1931 	if (trans_pcie->txqs.bc_table_dword)
1932 		len = DIV_ROUND_UP(len, 4);
1933 
1934 	if (WARN_ON(len > 0xFFF || write_ptr >= TFD_QUEUE_SIZE_MAX))
1935 		return;
1936 
1937 	bc_ent = cpu_to_le16(len | (sta_id << 12));
1938 
1939 	scd_bc_tbl[txq_id].tfd_offset[write_ptr] = bc_ent;
1940 
1941 	if (write_ptr < TFD_QUEUE_SIZE_BC_DUP)
1942 		scd_bc_tbl[txq_id].tfd_offset[TFD_QUEUE_SIZE_MAX + write_ptr] =
1943 			bc_ent;
1944 }
1945 
1946 int iwl_trans_pcie_tx(struct iwl_trans *trans, struct sk_buff *skb,
1947 		      struct iwl_device_tx_cmd *dev_cmd, int txq_id)
1948 {
1949 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1950 	struct ieee80211_hdr *hdr;
1951 	struct iwl_tx_cmd *tx_cmd = (struct iwl_tx_cmd *)dev_cmd->payload;
1952 	struct iwl_cmd_meta *out_meta;
1953 	struct iwl_txq *txq;
1954 	dma_addr_t tb0_phys, tb1_phys, scratch_phys;
1955 	void *tb1_addr;
1956 	void *tfd;
1957 	u16 len, tb1_len;
1958 	bool wait_write_ptr;
1959 	__le16 fc;
1960 	u8 hdr_len;
1961 	u16 wifi_seq;
1962 	bool amsdu;
1963 
1964 	txq = trans_pcie->txqs.txq[txq_id];
1965 
1966 	if (WARN_ONCE(!test_bit(txq_id, trans_pcie->txqs.queue_used),
1967 		      "TX on unused queue %d\n", txq_id))
1968 		return -EINVAL;
1969 
1970 	if (skb_is_nonlinear(skb) &&
1971 	    skb_shinfo(skb)->nr_frags > IWL_TRANS_PCIE_MAX_FRAGS(trans_pcie) &&
1972 	    __skb_linearize(skb))
1973 		return -ENOMEM;
1974 
1975 	/* mac80211 always puts the full header into the SKB's head,
1976 	 * so there's no need to check if it's readable there
1977 	 */
1978 	hdr = (struct ieee80211_hdr *)skb->data;
1979 	fc = hdr->frame_control;
1980 	hdr_len = ieee80211_hdrlen(fc);
1981 
1982 	spin_lock(&txq->lock);
1983 
1984 	if (iwl_txq_space(trans, txq) < txq->high_mark) {
1985 		iwl_txq_stop(trans, txq);
1986 
1987 		/* don't put the packet on the ring, if there is no room */
1988 		if (unlikely(iwl_txq_space(trans, txq) < 3)) {
1989 			struct iwl_device_tx_cmd **dev_cmd_ptr;
1990 
1991 			dev_cmd_ptr = (void *)((u8 *)skb->cb +
1992 					       trans_pcie->txqs.dev_cmd_offs);
1993 
1994 			*dev_cmd_ptr = dev_cmd;
1995 			__skb_queue_tail(&txq->overflow_q, skb);
1996 
1997 			spin_unlock(&txq->lock);
1998 			return 0;
1999 		}
2000 	}
2001 
2002 	/* In AGG mode, the index in the ring must correspond to the WiFi
2003 	 * sequence number. This is a HW requirements to help the SCD to parse
2004 	 * the BA.
2005 	 * Check here that the packets are in the right place on the ring.
2006 	 */
2007 	wifi_seq = IEEE80211_SEQ_TO_SN(le16_to_cpu(hdr->seq_ctrl));
2008 	WARN_ONCE(txq->ampdu &&
2009 		  (wifi_seq & 0xff) != txq->write_ptr,
2010 		  "Q: %d WiFi Seq %d tfdNum %d",
2011 		  txq_id, wifi_seq, txq->write_ptr);
2012 
2013 	/* Set up driver data for this TFD */
2014 	txq->entries[txq->write_ptr].skb = skb;
2015 	txq->entries[txq->write_ptr].cmd = dev_cmd;
2016 
2017 	dev_cmd->hdr.sequence =
2018 		cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
2019 			    INDEX_TO_SEQ(txq->write_ptr)));
2020 
2021 	tb0_phys = iwl_txq_get_first_tb_dma(txq, txq->write_ptr);
2022 	scratch_phys = tb0_phys + sizeof(struct iwl_cmd_header) +
2023 		       offsetof(struct iwl_tx_cmd, scratch);
2024 
2025 	tx_cmd->dram_lsb_ptr = cpu_to_le32(scratch_phys);
2026 	tx_cmd->dram_msb_ptr = iwl_get_dma_hi_addr(scratch_phys);
2027 
2028 	/* Set up first empty entry in queue's array of Tx/cmd buffers */
2029 	out_meta = &txq->entries[txq->write_ptr].meta;
2030 	out_meta->flags = 0;
2031 
2032 	/*
2033 	 * The second TB (tb1) points to the remainder of the TX command
2034 	 * and the 802.11 header - dword aligned size
2035 	 * (This calculation modifies the TX command, so do it before the
2036 	 * setup of the first TB)
2037 	 */
2038 	len = sizeof(struct iwl_tx_cmd) + sizeof(struct iwl_cmd_header) +
2039 	      hdr_len - IWL_FIRST_TB_SIZE;
2040 	/* do not align A-MSDU to dword as the subframe header aligns it */
2041 	amsdu = ieee80211_is_data_qos(fc) &&
2042 		(*ieee80211_get_qos_ctl(hdr) &
2043 		 IEEE80211_QOS_CTL_A_MSDU_PRESENT);
2044 	if (!amsdu) {
2045 		tb1_len = ALIGN(len, 4);
2046 		/* Tell NIC about any 2-byte padding after MAC header */
2047 		if (tb1_len != len)
2048 			tx_cmd->tx_flags |= cpu_to_le32(TX_CMD_FLG_MH_PAD);
2049 	} else {
2050 		tb1_len = len;
2051 	}
2052 
2053 	/*
2054 	 * The first TB points to bi-directional DMA data, we'll
2055 	 * memcpy the data into it later.
2056 	 */
2057 	iwl_pcie_txq_build_tfd(trans, txq, tb0_phys,
2058 			       IWL_FIRST_TB_SIZE, true);
2059 
2060 	/* there must be data left over for TB1 or this code must be changed */
2061 	BUILD_BUG_ON(sizeof(struct iwl_tx_cmd) < IWL_FIRST_TB_SIZE);
2062 	BUILD_BUG_ON(sizeof(struct iwl_cmd_header) +
2063 		     offsetofend(struct iwl_tx_cmd, scratch) >
2064 		     IWL_FIRST_TB_SIZE);
2065 
2066 	/* map the data for TB1 */
2067 	tb1_addr = ((u8 *)&dev_cmd->hdr) + IWL_FIRST_TB_SIZE;
2068 	tb1_phys = dma_map_single(trans->dev, tb1_addr, tb1_len, DMA_TO_DEVICE);
2069 	if (unlikely(dma_mapping_error(trans->dev, tb1_phys)))
2070 		goto out_err;
2071 	iwl_pcie_txq_build_tfd(trans, txq, tb1_phys, tb1_len, false);
2072 
2073 	trace_iwlwifi_dev_tx(trans->dev, skb,
2074 			     iwl_txq_get_tfd(trans, txq, txq->write_ptr),
2075 			     trans_pcie->txqs.tfd.size,
2076 			     &dev_cmd->hdr, IWL_FIRST_TB_SIZE + tb1_len,
2077 			     hdr_len);
2078 
2079 	/*
2080 	 * If gso_size wasn't set, don't give the frame "amsdu treatment"
2081 	 * (adding subframes, etc.).
2082 	 * This can happen in some testing flows when the amsdu was already
2083 	 * pre-built, and we just need to send the resulting skb.
2084 	 */
2085 	if (amsdu && skb_shinfo(skb)->gso_size) {
2086 		if (unlikely(iwl_fill_data_tbs_amsdu(trans, skb, txq, hdr_len,
2087 						     out_meta, dev_cmd,
2088 						     tb1_len)))
2089 			goto out_err;
2090 	} else {
2091 		struct sk_buff *frag;
2092 
2093 		if (unlikely(iwl_fill_data_tbs(trans, skb, txq, hdr_len,
2094 					       out_meta)))
2095 			goto out_err;
2096 
2097 		skb_walk_frags(skb, frag) {
2098 			if (unlikely(iwl_fill_data_tbs(trans, frag, txq, 0,
2099 						       out_meta)))
2100 				goto out_err;
2101 		}
2102 	}
2103 
2104 	/* building the A-MSDU might have changed this data, so memcpy it now */
2105 	memcpy(&txq->first_tb_bufs[txq->write_ptr], dev_cmd, IWL_FIRST_TB_SIZE);
2106 
2107 	tfd = iwl_txq_get_tfd(trans, txq, txq->write_ptr);
2108 	/* Set up entry for this TFD in Tx byte-count array */
2109 	iwl_txq_gen1_update_byte_cnt_tbl(trans, txq, le16_to_cpu(tx_cmd->len),
2110 					 iwl_txq_gen1_tfd_get_num_tbs(tfd));
2111 
2112 	wait_write_ptr = ieee80211_has_morefrags(fc);
2113 
2114 	/* start timer if queue currently empty */
2115 	if (txq->read_ptr == txq->write_ptr && txq->wd_timeout) {
2116 		/*
2117 		 * If the TXQ is active, then set the timer, if not,
2118 		 * set the timer in remainder so that the timer will
2119 		 * be armed with the right value when the station will
2120 		 * wake up.
2121 		 */
2122 		if (!txq->frozen)
2123 			mod_timer(&txq->stuck_timer,
2124 				  jiffies + txq->wd_timeout);
2125 		else
2126 			txq->frozen_expiry_remainder = txq->wd_timeout;
2127 	}
2128 
2129 	/* Tell device the write index *just past* this latest filled TFD */
2130 	txq->write_ptr = iwl_txq_inc_wrap(trans, txq->write_ptr);
2131 	if (!wait_write_ptr)
2132 		iwl_pcie_txq_inc_wr_ptr(trans, txq);
2133 
2134 	/*
2135 	 * At this point the frame is "transmitted" successfully
2136 	 * and we will get a TX status notification eventually.
2137 	 */
2138 	spin_unlock(&txq->lock);
2139 	return 0;
2140 out_err:
2141 	iwl_txq_gen1_tfd_unmap(trans, out_meta, txq, txq->write_ptr);
2142 	spin_unlock(&txq->lock);
2143 	return -1;
2144 }
2145 
2146 static void iwl_txq_gen1_inval_byte_cnt_tbl(struct iwl_trans *trans,
2147 					    struct iwl_txq *txq)
2148 {
2149 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2150 	struct iwlagn_scd_bc_tbl *scd_bc_tbl = trans_pcie->txqs.scd_bc_tbls.addr;
2151 	int txq_id = txq->id;
2152 	int read_ptr = txq->read_ptr;
2153 	u8 sta_id = 0;
2154 	__le16 bc_ent;
2155 	struct iwl_device_tx_cmd *dev_cmd = txq->entries[read_ptr].cmd;
2156 	struct iwl_tx_cmd *tx_cmd = (void *)dev_cmd->payload;
2157 
2158 	WARN_ON(read_ptr >= TFD_QUEUE_SIZE_MAX);
2159 
2160 	if (txq_id != trans_pcie->txqs.cmd.q_id)
2161 		sta_id = tx_cmd->sta_id;
2162 
2163 	bc_ent = cpu_to_le16(1 | (sta_id << 12));
2164 
2165 	scd_bc_tbl[txq_id].tfd_offset[read_ptr] = bc_ent;
2166 
2167 	if (read_ptr < TFD_QUEUE_SIZE_BC_DUP)
2168 		scd_bc_tbl[txq_id].tfd_offset[TFD_QUEUE_SIZE_MAX + read_ptr] =
2169 			bc_ent;
2170 }
2171 
2172 /* Frees buffers until index _not_ inclusive */
2173 void iwl_pcie_reclaim(struct iwl_trans *trans, int txq_id, int ssn,
2174 		      struct sk_buff_head *skbs, bool is_flush)
2175 {
2176 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2177 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
2178 	int tfd_num, read_ptr, last_to_free;
2179 
2180 	/* This function is not meant to release cmd queue*/
2181 	if (WARN_ON(txq_id == trans_pcie->txqs.cmd.q_id))
2182 		return;
2183 
2184 	if (WARN_ON(!txq))
2185 		return;
2186 
2187 	tfd_num = iwl_txq_get_cmd_index(txq, ssn);
2188 
2189 	spin_lock_bh(&txq->lock);
2190 	read_ptr = iwl_txq_get_cmd_index(txq, txq->read_ptr);
2191 
2192 	if (!test_bit(txq_id, trans_pcie->txqs.queue_used)) {
2193 		IWL_DEBUG_TX_QUEUES(trans, "Q %d inactive - ignoring idx %d\n",
2194 				    txq_id, ssn);
2195 		goto out;
2196 	}
2197 
2198 	if (read_ptr == tfd_num)
2199 		goto out;
2200 
2201 	IWL_DEBUG_TX_REPLY(trans, "[Q %d] %d (%d) -> %d (%d)\n",
2202 			   txq_id, read_ptr, txq->read_ptr, tfd_num, ssn);
2203 
2204 	/* Since we free until index _not_ inclusive, the one before index is
2205 	 * the last we will free. This one must be used
2206 	 */
2207 	last_to_free = iwl_txq_dec_wrap(trans, tfd_num);
2208 
2209 	if (!iwl_txq_used(txq, last_to_free)) {
2210 		IWL_ERR(trans,
2211 			"%s: Read index for txq id (%d), last_to_free %d is out of range [0-%d] %d %d.\n",
2212 			__func__, txq_id, last_to_free,
2213 			trans->trans_cfg->base_params->max_tfd_queue_size,
2214 			txq->write_ptr, txq->read_ptr);
2215 
2216 		iwl_op_mode_time_point(trans->op_mode,
2217 				       IWL_FW_INI_TIME_POINT_FAKE_TX,
2218 				       NULL);
2219 		goto out;
2220 	}
2221 
2222 	if (WARN_ON(!skb_queue_empty(skbs)))
2223 		goto out;
2224 
2225 	for (;
2226 	     read_ptr != tfd_num;
2227 	     txq->read_ptr = iwl_txq_inc_wrap(trans, txq->read_ptr),
2228 	     read_ptr = iwl_txq_get_cmd_index(txq, txq->read_ptr)) {
2229 		struct sk_buff *skb = txq->entries[read_ptr].skb;
2230 
2231 		if (WARN_ONCE(!skb, "no SKB at %d (%d) on queue %d\n",
2232 			      read_ptr, txq->read_ptr, txq_id))
2233 			continue;
2234 
2235 		iwl_pcie_free_tso_page(trans, skb);
2236 
2237 		__skb_queue_tail(skbs, skb);
2238 
2239 		txq->entries[read_ptr].skb = NULL;
2240 
2241 		if (!trans->trans_cfg->gen2)
2242 			iwl_txq_gen1_inval_byte_cnt_tbl(trans, txq);
2243 
2244 		iwl_txq_free_tfd(trans, txq);
2245 	}
2246 
2247 	iwl_txq_progress(txq);
2248 
2249 	if (iwl_txq_space(trans, txq) > txq->low_mark &&
2250 	    test_bit(txq_id, trans_pcie->txqs.queue_stopped)) {
2251 		struct sk_buff_head overflow_skbs;
2252 		struct sk_buff *skb;
2253 
2254 		__skb_queue_head_init(&overflow_skbs);
2255 		skb_queue_splice_init(&txq->overflow_q,
2256 				      is_flush ? skbs : &overflow_skbs);
2257 
2258 		/*
2259 		 * We are going to transmit from the overflow queue.
2260 		 * Remember this state so that wait_for_txq_empty will know we
2261 		 * are adding more packets to the TFD queue. It cannot rely on
2262 		 * the state of &txq->overflow_q, as we just emptied it, but
2263 		 * haven't TXed the content yet.
2264 		 */
2265 		txq->overflow_tx = true;
2266 
2267 		/*
2268 		 * This is tricky: we are in reclaim path which is non
2269 		 * re-entrant, so noone will try to take the access the
2270 		 * txq data from that path. We stopped tx, so we can't
2271 		 * have tx as well. Bottom line, we can unlock and re-lock
2272 		 * later.
2273 		 */
2274 		spin_unlock_bh(&txq->lock);
2275 
2276 		while ((skb = __skb_dequeue(&overflow_skbs))) {
2277 			struct iwl_device_tx_cmd *dev_cmd_ptr;
2278 
2279 			dev_cmd_ptr = *(void **)((u8 *)skb->cb +
2280 						 trans_pcie->txqs.dev_cmd_offs);
2281 
2282 			/*
2283 			 * Note that we can very well be overflowing again.
2284 			 * In that case, iwl_txq_space will be small again
2285 			 * and we won't wake mac80211's queue.
2286 			 */
2287 			iwl_trans_tx(trans, skb, dev_cmd_ptr, txq_id);
2288 		}
2289 
2290 		if (iwl_txq_space(trans, txq) > txq->low_mark)
2291 			iwl_trans_pcie_wake_queue(trans, txq);
2292 
2293 		spin_lock_bh(&txq->lock);
2294 		txq->overflow_tx = false;
2295 	}
2296 
2297 out:
2298 	spin_unlock_bh(&txq->lock);
2299 }
2300 
2301 /* Set wr_ptr of specific device and txq  */
2302 void iwl_pcie_set_q_ptrs(struct iwl_trans *trans, int txq_id, int ptr)
2303 {
2304 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2305 	struct iwl_txq *txq = trans_pcie->txqs.txq[txq_id];
2306 
2307 	spin_lock_bh(&txq->lock);
2308 
2309 	txq->write_ptr = ptr;
2310 	txq->read_ptr = txq->write_ptr;
2311 
2312 	spin_unlock_bh(&txq->lock);
2313 }
2314 
2315 void iwl_pcie_freeze_txq_timer(struct iwl_trans *trans,
2316 			       unsigned long txqs, bool freeze)
2317 {
2318 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2319 	int queue;
2320 
2321 	for_each_set_bit(queue, &txqs, BITS_PER_LONG) {
2322 		struct iwl_txq *txq = trans_pcie->txqs.txq[queue];
2323 		unsigned long now;
2324 
2325 		spin_lock_bh(&txq->lock);
2326 
2327 		now = jiffies;
2328 
2329 		if (txq->frozen == freeze)
2330 			goto next_queue;
2331 
2332 		IWL_DEBUG_TX_QUEUES(trans, "%s TXQ %d\n",
2333 				    freeze ? "Freezing" : "Waking", queue);
2334 
2335 		txq->frozen = freeze;
2336 
2337 		if (txq->read_ptr == txq->write_ptr)
2338 			goto next_queue;
2339 
2340 		if (freeze) {
2341 			if (unlikely(time_after(now,
2342 						txq->stuck_timer.expires))) {
2343 				/*
2344 				 * The timer should have fired, maybe it is
2345 				 * spinning right now on the lock.
2346 				 */
2347 				goto next_queue;
2348 			}
2349 			/* remember how long until the timer fires */
2350 			txq->frozen_expiry_remainder =
2351 				txq->stuck_timer.expires - now;
2352 			del_timer(&txq->stuck_timer);
2353 			goto next_queue;
2354 		}
2355 
2356 		/*
2357 		 * Wake a non-empty queue -> arm timer with the
2358 		 * remainder before it froze
2359 		 */
2360 		mod_timer(&txq->stuck_timer,
2361 			  now + txq->frozen_expiry_remainder);
2362 
2363 next_queue:
2364 		spin_unlock_bh(&txq->lock);
2365 	}
2366 }
2367 
2368 #define HOST_COMPLETE_TIMEOUT	(2 * HZ)
2369 
2370 static int iwl_trans_pcie_send_hcmd_sync(struct iwl_trans *trans,
2371 					 struct iwl_host_cmd *cmd)
2372 {
2373 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2374 	const char *cmd_str = iwl_get_cmd_string(trans, cmd->id);
2375 	struct iwl_txq *txq = trans_pcie->txqs.txq[trans_pcie->txqs.cmd.q_id];
2376 	int cmd_idx;
2377 	int ret;
2378 
2379 	IWL_DEBUG_INFO(trans, "Attempting to send sync command %s\n", cmd_str);
2380 
2381 	if (WARN(test_and_set_bit(STATUS_SYNC_HCMD_ACTIVE,
2382 				  &trans->status),
2383 		 "Command %s: a command is already active!\n", cmd_str))
2384 		return -EIO;
2385 
2386 	IWL_DEBUG_INFO(trans, "Setting HCMD_ACTIVE for command %s\n", cmd_str);
2387 
2388 	if (trans->trans_cfg->gen2)
2389 		cmd_idx = iwl_pcie_gen2_enqueue_hcmd(trans, cmd);
2390 	else
2391 		cmd_idx = iwl_pcie_enqueue_hcmd(trans, cmd);
2392 
2393 	if (cmd_idx < 0) {
2394 		ret = cmd_idx;
2395 		clear_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status);
2396 		IWL_ERR(trans, "Error sending %s: enqueue_hcmd failed: %d\n",
2397 			cmd_str, ret);
2398 		return ret;
2399 	}
2400 
2401 	ret = wait_event_timeout(trans->wait_command_queue,
2402 				 !test_bit(STATUS_SYNC_HCMD_ACTIVE,
2403 					   &trans->status),
2404 				 HOST_COMPLETE_TIMEOUT);
2405 	if (!ret) {
2406 		IWL_ERR(trans, "Error sending %s: time out after %dms.\n",
2407 			cmd_str, jiffies_to_msecs(HOST_COMPLETE_TIMEOUT));
2408 
2409 		IWL_ERR(trans, "Current CMD queue read_ptr %d write_ptr %d\n",
2410 			txq->read_ptr, txq->write_ptr);
2411 
2412 		clear_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status);
2413 		IWL_DEBUG_INFO(trans, "Clearing HCMD_ACTIVE for command %s\n",
2414 			       cmd_str);
2415 		ret = -ETIMEDOUT;
2416 
2417 		iwl_trans_sync_nmi(trans);
2418 		goto cancel;
2419 	}
2420 
2421 	if (test_bit(STATUS_FW_ERROR, &trans->status)) {
2422 		if (!test_and_clear_bit(STATUS_SUPPRESS_CMD_ERROR_ONCE,
2423 					&trans->status)) {
2424 			IWL_ERR(trans, "FW error in SYNC CMD %s\n", cmd_str);
2425 			dump_stack();
2426 		}
2427 		ret = -EIO;
2428 		goto cancel;
2429 	}
2430 
2431 	if (!(cmd->flags & CMD_SEND_IN_RFKILL) &&
2432 	    test_bit(STATUS_RFKILL_OPMODE, &trans->status)) {
2433 		IWL_DEBUG_RF_KILL(trans, "RFKILL in SYNC CMD... no rsp\n");
2434 		ret = -ERFKILL;
2435 		goto cancel;
2436 	}
2437 
2438 	if ((cmd->flags & CMD_WANT_SKB) && !cmd->resp_pkt) {
2439 		IWL_ERR(trans, "Error: Response NULL in '%s'\n", cmd_str);
2440 		ret = -EIO;
2441 		goto cancel;
2442 	}
2443 
2444 	return 0;
2445 
2446 cancel:
2447 	if (cmd->flags & CMD_WANT_SKB) {
2448 		/*
2449 		 * Cancel the CMD_WANT_SKB flag for the cmd in the
2450 		 * TX cmd queue. Otherwise in case the cmd comes
2451 		 * in later, it will possibly set an invalid
2452 		 * address (cmd->meta.source).
2453 		 */
2454 		txq->entries[cmd_idx].meta.flags &= ~CMD_WANT_SKB;
2455 	}
2456 
2457 	if (cmd->resp_pkt) {
2458 		iwl_free_resp(cmd);
2459 		cmd->resp_pkt = NULL;
2460 	}
2461 
2462 	return ret;
2463 }
2464 
2465 int iwl_trans_pcie_send_hcmd(struct iwl_trans *trans,
2466 			     struct iwl_host_cmd *cmd)
2467 {
2468 	/* Make sure the NIC is still alive in the bus */
2469 	if (test_bit(STATUS_TRANS_DEAD, &trans->status))
2470 		return -ENODEV;
2471 
2472 	if (!(cmd->flags & CMD_SEND_IN_RFKILL) &&
2473 	    test_bit(STATUS_RFKILL_OPMODE, &trans->status)) {
2474 		IWL_DEBUG_RF_KILL(trans, "Dropping CMD 0x%x: RF KILL\n",
2475 				  cmd->id);
2476 		return -ERFKILL;
2477 	}
2478 
2479 	if (unlikely(trans->system_pm_mode == IWL_PLAT_PM_MODE_D3 &&
2480 		     !(cmd->flags & CMD_SEND_IN_D3))) {
2481 		IWL_DEBUG_WOWLAN(trans, "Dropping CMD 0x%x: D3\n", cmd->id);
2482 		return -EHOSTDOWN;
2483 	}
2484 
2485 	if (cmd->flags & CMD_ASYNC) {
2486 		int ret;
2487 
2488 		/* An asynchronous command can not expect an SKB to be set. */
2489 		if (WARN_ON(cmd->flags & CMD_WANT_SKB))
2490 			return -EINVAL;
2491 
2492 		if (trans->trans_cfg->gen2)
2493 			ret = iwl_pcie_gen2_enqueue_hcmd(trans, cmd);
2494 		else
2495 			ret = iwl_pcie_enqueue_hcmd(trans, cmd);
2496 
2497 		if (ret < 0) {
2498 			IWL_ERR(trans,
2499 				"Error sending %s: enqueue_hcmd failed: %d\n",
2500 				iwl_get_cmd_string(trans, cmd->id), ret);
2501 			return ret;
2502 		}
2503 		return 0;
2504 	}
2505 
2506 	return iwl_trans_pcie_send_hcmd_sync(trans, cmd);
2507 }
2508 IWL_EXPORT_SYMBOL(iwl_trans_pcie_send_hcmd);
2509