xref: /freebsd/sys/dev/mana/mana_en.c (revision 19fae0f66023a97a9b464b3beeeabb2081f575b3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2021 Microsoft Corp.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/bus.h>
36 #include <sys/kernel.h>
37 #include <sys/kthread.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/smp.h>
41 #include <sys/socket.h>
42 #include <sys/sockio.h>
43 #include <sys/time.h>
44 #include <sys/eventhandler.h>
45 
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 #include <machine/in_cksum.h>
49 
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_types.h>
53 #include <net/if_vlan_var.h>
54 #ifdef RSS
55 #include <net/rss_config.h>
56 #endif
57 
58 #include <netinet/in_systm.h>
59 #include <netinet/in.h>
60 #include <netinet/if_ether.h>
61 #include <netinet/ip.h>
62 #include <netinet/ip6.h>
63 #include <netinet/tcp.h>
64 #include <netinet/udp.h>
65 
66 #include "mana.h"
67 #include "mana_sysctl.h"
68 
69 static int mana_up(struct mana_port_context *apc);
70 static int mana_down(struct mana_port_context *apc);
71 
72 static void
73 mana_rss_key_fill(void *k, size_t size)
74 {
75 	static bool rss_key_generated = false;
76 	static uint8_t rss_key[MANA_HASH_KEY_SIZE];
77 
78 	KASSERT(size <= MANA_HASH_KEY_SIZE,
79 	    ("Request more buytes than MANA RSS key can hold"));
80 
81 	if (!rss_key_generated) {
82 		arc4random_buf(rss_key, MANA_HASH_KEY_SIZE);
83 		rss_key_generated = true;
84 	}
85 	memcpy(k, rss_key, size);
86 }
87 
88 static int
89 mana_ifmedia_change(if_t ifp __unused)
90 {
91 	return EOPNOTSUPP;
92 }
93 
94 static void
95 mana_ifmedia_status(if_t ifp, struct ifmediareq *ifmr)
96 {
97 	struct mana_port_context *apc = if_getsoftc(ifp);
98 
99 	if (!apc) {
100 		if_printf(ifp, "Port not available\n");
101 		return;
102 	}
103 
104 	MANA_APC_LOCK_LOCK(apc);
105 
106 	ifmr->ifm_status = IFM_AVALID;
107 	ifmr->ifm_active = IFM_ETHER;
108 
109 	if (!apc->port_is_up) {
110 		MANA_APC_LOCK_UNLOCK(apc);
111 		mana_dbg(NULL, "Port %u link is down\n", apc->port_idx);
112 		return;
113 	}
114 
115 	ifmr->ifm_status |= IFM_ACTIVE;
116 	ifmr->ifm_active |= IFM_100G_DR | IFM_FDX;
117 
118 	MANA_APC_LOCK_UNLOCK(apc);
119 }
120 
121 static uint64_t
122 mana_get_counter(if_t ifp, ift_counter cnt)
123 {
124 	struct mana_port_context *apc = if_getsoftc(ifp);
125 	struct mana_port_stats *stats = &apc->port_stats;
126 
127 	switch (cnt) {
128 	case IFCOUNTER_IPACKETS:
129 		return (counter_u64_fetch(stats->rx_packets));
130 	case IFCOUNTER_OPACKETS:
131 		return (counter_u64_fetch(stats->tx_packets));
132 	case IFCOUNTER_IBYTES:
133 		return (counter_u64_fetch(stats->rx_bytes));
134 	case IFCOUNTER_OBYTES:
135 		return (counter_u64_fetch(stats->tx_bytes));
136 	case IFCOUNTER_IQDROPS:
137 		return (counter_u64_fetch(stats->rx_drops));
138 	case IFCOUNTER_OQDROPS:
139 		return (counter_u64_fetch(stats->tx_drops));
140 	default:
141 		return (if_get_counter_default(ifp, cnt));
142 	}
143 }
144 
145 static void
146 mana_qflush(if_t ifp)
147 {
148 	if_qflush(ifp);
149 }
150 
151 int
152 mana_restart(struct mana_port_context *apc)
153 {
154 	int rc = 0;
155 
156 	MANA_APC_LOCK_LOCK(apc);
157 	if (apc->port_is_up)
158 		 mana_down(apc);
159 
160 	rc = mana_up(apc);
161 	MANA_APC_LOCK_UNLOCK(apc);
162 
163 	return (rc);
164 }
165 
166 static int
167 mana_ioctl(if_t ifp, u_long command, caddr_t data)
168 {
169 	struct mana_port_context *apc = if_getsoftc(ifp);
170 	struct ifrsskey *ifrk;
171 	struct ifrsshash *ifrh;
172 	struct ifreq *ifr;
173 	uint16_t new_mtu;
174 	int rc = 0;
175 
176 	switch (command) {
177 	case SIOCSIFMTU:
178 		ifr = (struct ifreq *)data;
179 		new_mtu = ifr->ifr_mtu;
180 		if (if_getmtu(ifp) == new_mtu)
181 			break;
182 		if ((new_mtu + 18 > MAX_FRAME_SIZE) ||
183 		    (new_mtu + 18 < MIN_FRAME_SIZE)) {
184 			if_printf(ifp, "Invalid MTU. new_mtu: %d, "
185 			    "max allowed: %d, min allowed: %d\n",
186 			    new_mtu, MAX_FRAME_SIZE - 18, MIN_FRAME_SIZE - 18);
187 			return EINVAL;
188 		}
189 		MANA_APC_LOCK_LOCK(apc);
190 		if (apc->port_is_up)
191 			mana_down(apc);
192 
193 		apc->frame_size = new_mtu + 18;
194 		if_setmtu(ifp, new_mtu);
195 		mana_dbg(NULL, "Set MTU to %d\n", new_mtu);
196 
197 		rc = mana_up(apc);
198 		MANA_APC_LOCK_UNLOCK(apc);
199 		break;
200 
201 	case SIOCSIFFLAGS:
202 		if (if_getflags(ifp) & IFF_UP) {
203 			if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
204 				MANA_APC_LOCK_LOCK(apc);
205 				if (!apc->port_is_up)
206 					rc = mana_up(apc);
207 				MANA_APC_LOCK_UNLOCK(apc);
208 			}
209 		} else {
210 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
211 				MANA_APC_LOCK_LOCK(apc);
212 				if (apc->port_is_up)
213 					mana_down(apc);
214 				MANA_APC_LOCK_UNLOCK(apc);
215 			}
216 		}
217 		break;
218 
219 	case SIOCSIFMEDIA:
220 	case SIOCGIFMEDIA:
221 	case SIOCGIFXMEDIA:
222 		ifr = (struct ifreq *)data;
223 		rc = ifmedia_ioctl(ifp, ifr, &apc->media, command);
224 		break;
225 
226 	case SIOCGIFRSSKEY:
227 		ifrk = (struct ifrsskey *)data;
228 		ifrk->ifrk_func = RSS_FUNC_TOEPLITZ;
229 		ifrk->ifrk_keylen = MANA_HASH_KEY_SIZE;
230 		memcpy(ifrk->ifrk_key, apc->hashkey, MANA_HASH_KEY_SIZE);
231 		break;
232 
233 	case SIOCGIFRSSHASH:
234 		ifrh = (struct ifrsshash *)data;
235 		ifrh->ifrh_func = RSS_FUNC_TOEPLITZ;
236 		ifrh->ifrh_types =
237 		    RSS_TYPE_TCP_IPV4 |
238 		    RSS_TYPE_UDP_IPV4 |
239 		    RSS_TYPE_TCP_IPV6 |
240 		    RSS_TYPE_UDP_IPV6;
241 		break;
242 
243 	default:
244 		rc = ether_ioctl(ifp, command, data);
245 		break;
246 	}
247 
248 	return (rc);
249 }
250 
251 static inline void
252 mana_alloc_counters(counter_u64_t *begin, int size)
253 {
254 	counter_u64_t *end = (counter_u64_t *)((char *)begin + size);
255 
256 	for (; begin < end; ++begin)
257 		*begin = counter_u64_alloc(M_WAITOK);
258 }
259 
260 static inline void
261 mana_free_counters(counter_u64_t *begin, int size)
262 {
263 	counter_u64_t *end = (counter_u64_t *)((char *)begin + size);
264 
265 	for (; begin < end; ++begin)
266 		counter_u64_free(*begin);
267 }
268 
269 static bool
270 mana_can_tx(struct gdma_queue *wq)
271 {
272 	return mana_gd_wq_avail_space(wq) >= MAX_TX_WQE_SIZE;
273 }
274 
275 static inline int
276 mana_tx_map_mbuf(struct mana_port_context *apc,
277     struct mana_send_buf_info *tx_info,
278     struct mbuf **m_head, struct mana_tx_package *tp,
279     struct mana_stats *tx_stats)
280 {
281 	struct gdma_dev *gd = apc->ac->gdma_dev;
282 	bus_dma_segment_t segs[MAX_MBUF_FRAGS];
283 	struct mbuf *m = *m_head;
284 	int err, nsegs, i;
285 
286 	err = bus_dmamap_load_mbuf_sg(apc->tx_buf_tag, tx_info->dma_map,
287 	    m, segs, &nsegs, BUS_DMA_NOWAIT);
288 	if (err == EFBIG) {
289 		struct mbuf *m_new;
290 
291 		counter_u64_add(tx_stats->collapse, 1);
292 		m_new = m_collapse(m, M_NOWAIT, MAX_MBUF_FRAGS);
293 		if (unlikely(m_new == NULL)) {
294 			counter_u64_add(tx_stats->collapse_err, 1);
295 			return ENOBUFS;
296 		} else {
297 			*m_head = m = m_new;
298 		}
299 
300 		mana_warn(NULL,
301 		    "Too many segs in orig mbuf, m_collapse called\n");
302 
303 		err = bus_dmamap_load_mbuf_sg(apc->tx_buf_tag,
304 		    tx_info->dma_map, m, segs, &nsegs, BUS_DMA_NOWAIT);
305 	}
306 	if (!err) {
307 		for (i = 0; i < nsegs; i++) {
308 			tp->wqe_req.sgl[i].address = segs[i].ds_addr;
309 			tp->wqe_req.sgl[i].mem_key = gd->gpa_mkey;
310 			tp->wqe_req.sgl[i].size = segs[i].ds_len;
311 		}
312 		tp->wqe_req.num_sge = nsegs;
313 
314 		tx_info->mbuf = *m_head;
315 
316 		bus_dmamap_sync(apc->tx_buf_tag, tx_info->dma_map,
317 		    BUS_DMASYNC_PREWRITE);
318 	}
319 
320 	return err;
321 }
322 
323 static inline void
324 mana_tx_unmap_mbuf(struct mana_port_context *apc,
325     struct mana_send_buf_info *tx_info)
326 {
327 	bus_dmamap_sync(apc->tx_buf_tag, tx_info->dma_map,
328 	    BUS_DMASYNC_POSTWRITE);
329 	bus_dmamap_unload(apc->tx_buf_tag, tx_info->dma_map);
330 	if (tx_info->mbuf) {
331 		m_freem(tx_info->mbuf);
332 		tx_info->mbuf = NULL;
333 	}
334 }
335 
336 static inline int
337 mana_load_rx_mbuf(struct mana_port_context *apc, struct mana_rxq *rxq,
338     struct mana_recv_buf_oob *rx_oob, bool alloc_mbuf)
339 {
340 	bus_dma_segment_t segs[1];
341 	struct mbuf *mbuf;
342 	int nsegs, err;
343 	uint32_t mlen;
344 
345 	if (alloc_mbuf) {
346 		mbuf = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, rxq->datasize);
347 		if (unlikely(mbuf == NULL)) {
348 			mbuf = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
349 			if (unlikely(mbuf == NULL)) {
350 				return ENOMEM;
351 			}
352 			mlen = MCLBYTES;
353 		} else {
354 			mlen = rxq->datasize;
355 		}
356 
357 		mbuf->m_pkthdr.len = mbuf->m_len = mlen;
358 	} else {
359 		if (rx_oob->mbuf) {
360 			mbuf = rx_oob->mbuf;
361 			mlen = rx_oob->mbuf->m_pkthdr.len;
362 		} else {
363 			return ENOMEM;
364 		}
365 	}
366 
367 	err = bus_dmamap_load_mbuf_sg(apc->rx_buf_tag, rx_oob->dma_map,
368 	    mbuf, segs, &nsegs, BUS_DMA_NOWAIT);
369 
370 	if (unlikely((err != 0) || (nsegs != 1))) {
371 		mana_warn(NULL, "Failed to map mbuf, error: %d, "
372 		    "nsegs: %d\n", err, nsegs);
373 		counter_u64_add(rxq->stats.dma_mapping_err, 1);
374 		goto error;
375 	}
376 
377 	bus_dmamap_sync(apc->rx_buf_tag, rx_oob->dma_map,
378 	    BUS_DMASYNC_PREREAD);
379 
380 	rx_oob->mbuf = mbuf;
381 	rx_oob->num_sge = 1;
382 	rx_oob->sgl[0].address = segs[0].ds_addr;
383 	rx_oob->sgl[0].size = mlen;
384 	rx_oob->sgl[0].mem_key = apc->ac->gdma_dev->gpa_mkey;
385 
386 	return 0;
387 
388 error:
389 	m_freem(mbuf);
390 	return EFAULT;
391 }
392 
393 static inline void
394 mana_unload_rx_mbuf(struct mana_port_context *apc, struct mana_rxq *rxq,
395     struct mana_recv_buf_oob *rx_oob, bool free_mbuf)
396 {
397 	bus_dmamap_sync(apc->rx_buf_tag, rx_oob->dma_map,
398 	    BUS_DMASYNC_POSTREAD);
399 	bus_dmamap_unload(apc->rx_buf_tag, rx_oob->dma_map);
400 
401 	if (free_mbuf && rx_oob->mbuf) {
402 		m_freem(rx_oob->mbuf);
403 		rx_oob->mbuf = NULL;
404 	}
405 }
406 
407 
408 /* Use couple mbuf PH_loc spaces for l3 and l4 protocal type */
409 #define MANA_L3_PROTO(_mbuf)	((_mbuf)->m_pkthdr.PH_loc.sixteen[0])
410 #define MANA_L4_PROTO(_mbuf)	((_mbuf)->m_pkthdr.PH_loc.sixteen[1])
411 
412 #define MANA_TXQ_FULL	(IFF_DRV_RUNNING | IFF_DRV_OACTIVE)
413 
414 static void
415 mana_xmit(struct mana_txq *txq)
416 {
417 	enum mana_tx_pkt_format pkt_fmt = MANA_SHORT_PKT_FMT;
418 	struct mana_send_buf_info *tx_info;
419 	if_t ndev = txq->ndev;
420 	struct mbuf *mbuf;
421 	struct mana_port_context *apc = if_getsoftc(ndev);
422 	struct mana_port_stats *port_stats = &apc->port_stats;
423 	struct gdma_dev *gd = apc->ac->gdma_dev;
424 	uint64_t packets, bytes;
425 	uint16_t next_to_use;
426 	struct mana_tx_package pkg = {};
427 	struct mana_stats *tx_stats;
428 	struct gdma_queue *gdma_sq;
429 	struct mana_cq *cq;
430 	int err, len;
431 
432 	gdma_sq = txq->gdma_sq;
433 	cq = &apc->tx_qp[txq->idx].tx_cq;
434 	tx_stats = &txq->stats;
435 
436 	packets = 0;
437 	bytes = 0;
438 	next_to_use = txq->next_to_use;
439 
440 	while ((mbuf = drbr_peek(ndev, txq->txq_br)) != NULL) {
441 		if (!apc->port_is_up ||
442 		    (if_getdrvflags(ndev) & MANA_TXQ_FULL) != IFF_DRV_RUNNING) {
443 			drbr_putback(ndev, txq->txq_br, mbuf);
444 			break;
445 		}
446 
447 		if (!mana_can_tx(gdma_sq)) {
448 			/* SQ is full. Set the IFF_DRV_OACTIVE flag */
449 			if_setdrvflagbits(apc->ndev, IFF_DRV_OACTIVE, 0);
450 			counter_u64_add(tx_stats->stop, 1);
451 			uint64_t stops = counter_u64_fetch(tx_stats->stop);
452 			uint64_t wakeups = counter_u64_fetch(tx_stats->wakeup);
453 #define MANA_TXQ_STOP_THRESHOLD		50
454 			if (stops > MANA_TXQ_STOP_THRESHOLD && wakeups > 0 &&
455 			    stops > wakeups && txq->alt_txq_idx == txq->idx) {
456 				txq->alt_txq_idx =
457 				    (txq->idx + (stops / wakeups))
458 				    % apc->num_queues;
459 				counter_u64_add(tx_stats->alt_chg, 1);
460 			}
461 
462 			drbr_putback(ndev, txq->txq_br, mbuf);
463 
464 			taskqueue_enqueue(cq->cleanup_tq, &cq->cleanup_task);
465 			break;
466 		}
467 
468 		tx_info = &txq->tx_buf_info[next_to_use];
469 
470 		memset(&pkg, 0, sizeof(struct mana_tx_package));
471 		pkg.wqe_req.sgl = pkg.sgl_array;
472 
473 		err = mana_tx_map_mbuf(apc, tx_info, &mbuf, &pkg, tx_stats);
474 		if (unlikely(err)) {
475 			mana_dbg(NULL,
476 			    "Failed to map tx mbuf, err %d\n", err);
477 
478 			counter_u64_add(tx_stats->dma_mapping_err, 1);
479 
480 			/* The mbuf is still there. Free it */
481 			m_freem(mbuf);
482 			/* Advance the drbr queue */
483 			drbr_advance(ndev, txq->txq_br);
484 			continue;
485 		}
486 
487 		pkg.tx_oob.s_oob.vcq_num = cq->gdma_id;
488 		pkg.tx_oob.s_oob.vsq_frame = txq->vsq_frame;
489 
490 		if (txq->vp_offset > MANA_SHORT_VPORT_OFFSET_MAX) {
491 			pkg.tx_oob.l_oob.long_vp_offset = txq->vp_offset;
492 			pkt_fmt = MANA_LONG_PKT_FMT;
493 		} else {
494 			pkg.tx_oob.s_oob.short_vp_offset = txq->vp_offset;
495 		}
496 
497 		pkg.tx_oob.s_oob.pkt_fmt = pkt_fmt;
498 
499 		if (pkt_fmt == MANA_SHORT_PKT_FMT)
500 			pkg.wqe_req.inline_oob_size = sizeof(struct mana_tx_short_oob);
501 		else
502 			pkg.wqe_req.inline_oob_size = sizeof(struct mana_tx_oob);
503 
504 		pkg.wqe_req.inline_oob_data = &pkg.tx_oob;
505 		pkg.wqe_req.flags = 0;
506 		pkg.wqe_req.client_data_unit = 0;
507 
508 		if (mbuf->m_pkthdr.csum_flags & CSUM_TSO) {
509 			if (MANA_L3_PROTO(mbuf) == ETHERTYPE_IP)
510 				pkg.tx_oob.s_oob.is_outer_ipv4 = 1;
511 			else
512 				pkg.tx_oob.s_oob.is_outer_ipv6 = 1;
513 
514 			pkg.tx_oob.s_oob.comp_iphdr_csum = 1;
515 			pkg.tx_oob.s_oob.comp_tcp_csum = 1;
516 			pkg.tx_oob.s_oob.trans_off = mbuf->m_pkthdr.l3hlen;
517 
518 			pkg.wqe_req.client_data_unit = mbuf->m_pkthdr.tso_segsz;
519 			pkg.wqe_req.flags = GDMA_WR_OOB_IN_SGL | GDMA_WR_PAD_BY_SGE0;
520 		} else if (mbuf->m_pkthdr.csum_flags &
521 		    (CSUM_IP_UDP | CSUM_IP_TCP | CSUM_IP6_UDP | CSUM_IP6_TCP)) {
522 			if (MANA_L3_PROTO(mbuf) == ETHERTYPE_IP) {
523 				pkg.tx_oob.s_oob.is_outer_ipv4 = 1;
524 				pkg.tx_oob.s_oob.comp_iphdr_csum = 1;
525 			} else {
526 				pkg.tx_oob.s_oob.is_outer_ipv6 = 1;
527 			}
528 
529 			if (MANA_L4_PROTO(mbuf) == IPPROTO_TCP) {
530 				pkg.tx_oob.s_oob.comp_tcp_csum = 1;
531 				pkg.tx_oob.s_oob.trans_off =
532 				    mbuf->m_pkthdr.l3hlen;
533 			} else {
534 				pkg.tx_oob.s_oob.comp_udp_csum = 1;
535 			}
536 		} else if (mbuf->m_pkthdr.csum_flags & CSUM_IP) {
537 			pkg.tx_oob.s_oob.is_outer_ipv4 = 1;
538 			pkg.tx_oob.s_oob.comp_iphdr_csum = 1;
539 		} else {
540 			if (MANA_L3_PROTO(mbuf) == ETHERTYPE_IP)
541 				pkg.tx_oob.s_oob.is_outer_ipv4 = 1;
542 			else if (MANA_L3_PROTO(mbuf) == ETHERTYPE_IPV6)
543 				pkg.tx_oob.s_oob.is_outer_ipv6 = 1;
544 		}
545 
546 		len = mbuf->m_pkthdr.len;
547 
548 		err = mana_gd_post_work_request(gdma_sq, &pkg.wqe_req,
549 		    (struct gdma_posted_wqe_info *)&tx_info->wqe_inf);
550 		if (unlikely(err)) {
551 			/* Should not happen */
552 			if_printf(ndev, "Failed to post TX OOB: %d\n", err);
553 
554 			mana_tx_unmap_mbuf(apc, tx_info);
555 
556 			drbr_advance(ndev, txq->txq_br);
557 			continue;
558 		}
559 
560 		next_to_use =
561 		    (next_to_use + 1) % MAX_SEND_BUFFERS_PER_QUEUE;
562 
563 		(void)atomic_inc_return(&txq->pending_sends);
564 
565 		drbr_advance(ndev, txq->txq_br);
566 
567 		mana_gd_wq_ring_doorbell(gd->gdma_context, gdma_sq);
568 
569 		packets++;
570 		bytes += len;
571 	}
572 
573 	counter_enter();
574 	counter_u64_add_protected(tx_stats->packets, packets);
575 	counter_u64_add_protected(port_stats->tx_packets, packets);
576 	counter_u64_add_protected(tx_stats->bytes, bytes);
577 	counter_u64_add_protected(port_stats->tx_bytes, bytes);
578 	counter_exit();
579 
580 	txq->next_to_use = next_to_use;
581 }
582 
583 static void
584 mana_xmit_taskfunc(void *arg, int pending)
585 {
586 	struct mana_txq *txq = (struct mana_txq *)arg;
587 	if_t ndev = txq->ndev;
588 	struct mana_port_context *apc = if_getsoftc(ndev);
589 
590 	while (!drbr_empty(ndev, txq->txq_br) && apc->port_is_up &&
591 	    (if_getdrvflags(ndev) & MANA_TXQ_FULL) == IFF_DRV_RUNNING) {
592 		mtx_lock(&txq->txq_mtx);
593 		mana_xmit(txq);
594 		mtx_unlock(&txq->txq_mtx);
595 	}
596 }
597 
598 #define PULLUP_HDR(m, len)				\
599 do {							\
600 	if (unlikely((m)->m_len < (len))) {		\
601 		(m) = m_pullup((m), (len));		\
602 		if ((m) == NULL)			\
603 			return (NULL);			\
604 	}						\
605 } while (0)
606 
607 /*
608  * If this function failed, the mbuf would be freed.
609  */
610 static inline struct mbuf *
611 mana_tso_fixup(struct mbuf *mbuf)
612 {
613 	struct ether_vlan_header *eh = mtod(mbuf, struct ether_vlan_header *);
614 	struct tcphdr *th;
615 	uint16_t etype;
616 	int ehlen;
617 
618 	if (eh->evl_encap_proto == ntohs(ETHERTYPE_VLAN)) {
619 		etype = ntohs(eh->evl_proto);
620 		ehlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
621 	} else {
622 		etype = ntohs(eh->evl_encap_proto);
623 		ehlen = ETHER_HDR_LEN;
624 	}
625 
626 	if (etype == ETHERTYPE_IP) {
627 		struct ip *ip;
628 		int iphlen;
629 
630 		PULLUP_HDR(mbuf, ehlen + sizeof(*ip));
631 		ip = mtodo(mbuf, ehlen);
632 		iphlen = ip->ip_hl << 2;
633 		mbuf->m_pkthdr.l3hlen = ehlen + iphlen;
634 
635 		PULLUP_HDR(mbuf, ehlen + iphlen + sizeof(*th));
636 		th = mtodo(mbuf, ehlen + iphlen);
637 
638 		ip->ip_len = 0;
639 		ip->ip_sum = 0;
640 		th->th_sum = in_pseudo(ip->ip_src.s_addr,
641 		    ip->ip_dst.s_addr, htons(IPPROTO_TCP));
642 	} else if (etype == ETHERTYPE_IPV6) {
643 		struct ip6_hdr *ip6;
644 
645 		PULLUP_HDR(mbuf, ehlen + sizeof(*ip6) + sizeof(*th));
646 		ip6 = mtodo(mbuf, ehlen);
647 		if (ip6->ip6_nxt != IPPROTO_TCP) {
648 			/* Realy something wrong, just return */
649 			mana_dbg(NULL, "TSO mbuf not TCP, freed.\n");
650 			m_freem(mbuf);
651 			return NULL;
652 		}
653 		mbuf->m_pkthdr.l3hlen = ehlen + sizeof(*ip6);
654 
655 		th = mtodo(mbuf, ehlen + sizeof(*ip6));
656 
657 		ip6->ip6_plen = 0;
658 		th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
659 	} else {
660 		/* CSUM_TSO is set but not IP protocol. */
661 		mana_warn(NULL, "TSO mbuf not right, freed.\n");
662 		m_freem(mbuf);
663 		return NULL;
664 	}
665 
666 	MANA_L3_PROTO(mbuf) = etype;
667 
668 	return (mbuf);
669 }
670 
671 /*
672  * If this function failed, the mbuf would be freed.
673  */
674 static inline struct mbuf *
675 mana_mbuf_csum_check(struct mbuf *mbuf)
676 {
677 	struct ether_vlan_header *eh = mtod(mbuf, struct ether_vlan_header *);
678 	struct mbuf *mbuf_next;
679 	uint16_t etype;
680 	int offset;
681 	int ehlen;
682 
683 	if (eh->evl_encap_proto == ntohs(ETHERTYPE_VLAN)) {
684 		etype = ntohs(eh->evl_proto);
685 		ehlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
686 	} else {
687 		etype = ntohs(eh->evl_encap_proto);
688 		ehlen = ETHER_HDR_LEN;
689 	}
690 
691 	mbuf_next = m_getptr(mbuf, ehlen, &offset);
692 
693 	MANA_L4_PROTO(mbuf) = 0;
694 	if (etype == ETHERTYPE_IP) {
695 		const struct ip *ip;
696 		int iphlen;
697 
698 		ip = (struct ip *)(mtodo(mbuf_next, offset));
699 		iphlen = ip->ip_hl << 2;
700 		mbuf->m_pkthdr.l3hlen = ehlen + iphlen;
701 
702 		MANA_L4_PROTO(mbuf) = ip->ip_p;
703 	} else if (etype == ETHERTYPE_IPV6) {
704 		const struct ip6_hdr *ip6;
705 
706 		ip6 = (struct ip6_hdr *)(mtodo(mbuf_next, offset));
707 		mbuf->m_pkthdr.l3hlen = ehlen + sizeof(*ip6);
708 
709 		MANA_L4_PROTO(mbuf) = ip6->ip6_nxt;
710 	} else {
711 		MANA_L4_PROTO(mbuf) = 0;
712 	}
713 
714 	MANA_L3_PROTO(mbuf) = etype;
715 
716 	return (mbuf);
717 }
718 
719 static int
720 mana_start_xmit(if_t ifp, struct mbuf *m)
721 {
722 	struct mana_port_context *apc = if_getsoftc(ifp);
723 	struct mana_txq *txq;
724 	int is_drbr_empty;
725 	uint16_t txq_id;
726 	int err;
727 
728 	if (unlikely((!apc->port_is_up) ||
729 	    (if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0))
730 		return ENODEV;
731 
732 	if (m->m_pkthdr.csum_flags & CSUM_TSO) {
733 		m = mana_tso_fixup(m);
734 		if (unlikely(m == NULL)) {
735 			counter_enter();
736 			counter_u64_add_protected(apc->port_stats.tx_drops, 1);
737 			counter_exit();
738 			return EIO;
739 		}
740 	} else {
741 		m = mana_mbuf_csum_check(m);
742 		if (unlikely(m == NULL)) {
743 			counter_enter();
744 			counter_u64_add_protected(apc->port_stats.tx_drops, 1);
745 			counter_exit();
746 			return EIO;
747 		}
748 	}
749 
750 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
751 		uint32_t hash = m->m_pkthdr.flowid;
752 		txq_id = apc->indir_table[(hash) & MANA_INDIRECT_TABLE_MASK] %
753 		    apc->num_queues;
754 	} else {
755 		txq_id = m->m_pkthdr.flowid % apc->num_queues;
756 	}
757 
758 	if (apc->enable_tx_altq)
759 		txq_id = apc->tx_qp[txq_id].txq.alt_txq_idx;
760 
761 	txq = &apc->tx_qp[txq_id].txq;
762 
763 	is_drbr_empty = drbr_empty(ifp, txq->txq_br);
764 	err = drbr_enqueue(ifp, txq->txq_br, m);
765 	if (unlikely(err)) {
766 		mana_warn(NULL, "txq %u failed to enqueue: %d\n",
767 		    txq_id, err);
768 		taskqueue_enqueue(txq->enqueue_tq, &txq->enqueue_task);
769 		return err;
770 	}
771 
772 	if (is_drbr_empty && mtx_trylock(&txq->txq_mtx)) {
773 		mana_xmit(txq);
774 		mtx_unlock(&txq->txq_mtx);
775 	} else {
776 		taskqueue_enqueue(txq->enqueue_tq, &txq->enqueue_task);
777 	}
778 
779 	return 0;
780 }
781 
782 static void
783 mana_cleanup_port_context(struct mana_port_context *apc)
784 {
785 	bus_dma_tag_destroy(apc->tx_buf_tag);
786 	bus_dma_tag_destroy(apc->rx_buf_tag);
787 	apc->rx_buf_tag = NULL;
788 
789 	free(apc->rxqs, M_DEVBUF);
790 	apc->rxqs = NULL;
791 
792 	mana_free_counters((counter_u64_t *)&apc->port_stats,
793 	    sizeof(struct mana_port_stats));
794 }
795 
796 static int
797 mana_init_port_context(struct mana_port_context *apc)
798 {
799 	device_t dev = apc->ac->gdma_dev->gdma_context->dev;
800 	uint32_t tso_maxsize;
801 	int err;
802 
803 	tso_maxsize = MAX_MBUF_FRAGS * MANA_TSO_MAXSEG_SZ -
804 	    (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
805 
806 	/* Create DMA tag for tx bufs */
807 	err = bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
808 	    1, 0,			/* alignment, boundary	*/
809 	    BUS_SPACE_MAXADDR,		/* lowaddr		*/
810 	    BUS_SPACE_MAXADDR,		/* highaddr		*/
811 	    NULL, NULL,			/* filter, filterarg	*/
812 	    tso_maxsize,		/* maxsize		*/
813 	    MAX_MBUF_FRAGS,		/* nsegments		*/
814 	    tso_maxsize,		/* maxsegsize		*/
815 	    0,				/* flags		*/
816 	    NULL, NULL,			/* lockfunc, lockfuncarg*/
817 	    &apc->tx_buf_tag);
818 	if (unlikely(err)) {
819 		device_printf(dev, "Feiled to create TX DMA tag\n");
820 		return err;
821 	}
822 
823 	/* Create DMA tag for rx bufs */
824 	err = bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
825 	    64, 0,			/* alignment, boundary	*/
826 	    BUS_SPACE_MAXADDR,		/* lowaddr		*/
827 	    BUS_SPACE_MAXADDR,		/* highaddr		*/
828 	    NULL, NULL,			/* filter, filterarg	*/
829 	    MJUMPAGESIZE,		/* maxsize		*/
830 	    1,				/* nsegments		*/
831 	    MJUMPAGESIZE,		/* maxsegsize		*/
832 	    0,				/* flags		*/
833 	    NULL, NULL,			/* lockfunc, lockfuncarg*/
834 	    &apc->rx_buf_tag);
835 	if (unlikely(err)) {
836 		device_printf(dev, "Feiled to create RX DMA tag\n");
837 		return err;
838 	}
839 
840 	apc->rxqs = mallocarray(apc->num_queues, sizeof(struct mana_rxq *),
841 	    M_DEVBUF, M_WAITOK | M_ZERO);
842 
843 	if (!apc->rxqs) {
844 		bus_dma_tag_destroy(apc->tx_buf_tag);
845 		bus_dma_tag_destroy(apc->rx_buf_tag);
846 		apc->rx_buf_tag = NULL;
847 		return ENOMEM;
848 	}
849 
850 	return 0;
851 }
852 
853 static int
854 mana_send_request(struct mana_context *ac, void *in_buf,
855     uint32_t in_len, void *out_buf, uint32_t out_len)
856 {
857 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
858 	struct gdma_resp_hdr *resp = out_buf;
859 	struct gdma_req_hdr *req = in_buf;
860 	device_t dev = gc->dev;
861 	static atomic_t activity_id;
862 	int err;
863 
864 	req->dev_id = gc->mana.dev_id;
865 	req->activity_id = atomic_inc_return(&activity_id);
866 
867 	mana_dbg(NULL, "activity_id  = %u\n", activity_id);
868 
869 	err = mana_gd_send_request(gc, in_len, in_buf, out_len,
870 	    out_buf);
871 	if (err || resp->status) {
872 		device_printf(dev, "Failed to send mana message: %d, 0x%x\n",
873 			err, resp->status);
874 		return err ? err : EPROTO;
875 	}
876 
877 	if (req->dev_id.as_uint32 != resp->dev_id.as_uint32 ||
878 	    req->activity_id != resp->activity_id) {
879 		device_printf(dev,
880 		    "Unexpected mana message response: %x,%x,%x,%x\n",
881 		    req->dev_id.as_uint32, resp->dev_id.as_uint32,
882 		    req->activity_id, resp->activity_id);
883 		return EPROTO;
884 	}
885 
886 	return 0;
887 }
888 
889 static int
890 mana_verify_resp_hdr(const struct gdma_resp_hdr *resp_hdr,
891     const enum mana_command_code expected_code,
892     const uint32_t min_size)
893 {
894 	if (resp_hdr->response.msg_type != expected_code)
895 		return EPROTO;
896 
897 	if (resp_hdr->response.msg_version < GDMA_MESSAGE_V1)
898 		return EPROTO;
899 
900 	if (resp_hdr->response.msg_size < min_size)
901 		return EPROTO;
902 
903 	return 0;
904 }
905 
906 static int
907 mana_query_device_cfg(struct mana_context *ac, uint32_t proto_major_ver,
908     uint32_t proto_minor_ver, uint32_t proto_micro_ver,
909     uint16_t *max_num_vports)
910 {
911 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
912 	struct mana_query_device_cfg_resp resp = {};
913 	struct mana_query_device_cfg_req req = {};
914 	device_t dev = gc->dev;
915 	int err = 0;
916 
917 	mana_gd_init_req_hdr(&req.hdr, MANA_QUERY_DEV_CONFIG,
918 	    sizeof(req), sizeof(resp));
919 	req.proto_major_ver = proto_major_ver;
920 	req.proto_minor_ver = proto_minor_ver;
921 	req.proto_micro_ver = proto_micro_ver;
922 
923 	err = mana_send_request(ac, &req, sizeof(req), &resp, sizeof(resp));
924 	if (err) {
925 		device_printf(dev, "Failed to query config: %d", err);
926 		return err;
927 	}
928 
929 	err = mana_verify_resp_hdr(&resp.hdr, MANA_QUERY_DEV_CONFIG,
930 	    sizeof(resp));
931 	if (err || resp.hdr.status) {
932 		device_printf(dev, "Invalid query result: %d, 0x%x\n", err,
933 		    resp.hdr.status);
934 		if (!err)
935 			err = EPROTO;
936 		return err;
937 	}
938 
939 	*max_num_vports = resp.max_num_vports;
940 
941 	mana_dbg(NULL, "mana max_num_vports from device = %d\n",
942 	    *max_num_vports);
943 
944 	return 0;
945 }
946 
947 static int
948 mana_query_vport_cfg(struct mana_port_context *apc, uint32_t vport_index,
949     uint32_t *max_sq, uint32_t *max_rq, uint32_t *num_indir_entry)
950 {
951 	struct mana_query_vport_cfg_resp resp = {};
952 	struct mana_query_vport_cfg_req req = {};
953 	int err;
954 
955 	mana_gd_init_req_hdr(&req.hdr, MANA_QUERY_VPORT_CONFIG,
956 	    sizeof(req), sizeof(resp));
957 
958 	req.vport_index = vport_index;
959 
960 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
961 	    sizeof(resp));
962 	if (err)
963 		return err;
964 
965 	err = mana_verify_resp_hdr(&resp.hdr, MANA_QUERY_VPORT_CONFIG,
966 	    sizeof(resp));
967 	if (err)
968 		return err;
969 
970 	if (resp.hdr.status)
971 		return EPROTO;
972 
973 	*max_sq = resp.max_num_sq;
974 	*max_rq = resp.max_num_rq;
975 	*num_indir_entry = resp.num_indirection_ent;
976 
977 	apc->port_handle = resp.vport;
978 	memcpy(apc->mac_addr, resp.mac_addr, ETHER_ADDR_LEN);
979 
980 	return 0;
981 }
982 
983 void
984 mana_uncfg_vport(struct mana_port_context *apc)
985 {
986 	apc->vport_use_count--;
987 	if (apc->vport_use_count < 0) {
988 		mana_err(NULL,
989 		    "WARNING: vport_use_count less than 0: %u\n",
990 		    apc->vport_use_count);
991 	}
992 }
993 
994 int
995 mana_cfg_vport(struct mana_port_context *apc, uint32_t protection_dom_id,
996     uint32_t doorbell_pg_id)
997 {
998 	struct mana_config_vport_resp resp = {};
999 	struct mana_config_vport_req req = {};
1000 	int err;
1001 
1002 	/* This function is used to program the Ethernet port in the hardware
1003 	 * table. It can be called from the Ethernet driver or the RDMA driver.
1004 	 *
1005 	 * For Ethernet usage, the hardware supports only one active user on a
1006 	 * physical port. The driver checks on the port usage before programming
1007 	 * the hardware when creating the RAW QP (RDMA driver) or exposing the
1008 	 * device to kernel NET layer (Ethernet driver).
1009 	 *
1010 	 * Because the RDMA driver doesn't know in advance which QP type the
1011 	 * user will create, it exposes the device with all its ports. The user
1012 	 * may not be able to create RAW QP on a port if this port is already
1013 	 * in used by the Ethernet driver from the kernel.
1014 	 *
1015 	 * This physical port limitation only applies to the RAW QP. For RC QP,
1016 	 * the hardware doesn't have this limitation. The user can create RC
1017 	 * QPs on a physical port up to the hardware limits independent of the
1018 	 * Ethernet usage on the same port.
1019 	 */
1020 	if (apc->vport_use_count > 0) {
1021 		return EBUSY;
1022 	}
1023 	apc->vport_use_count++;
1024 
1025 	mana_gd_init_req_hdr(&req.hdr, MANA_CONFIG_VPORT_TX,
1026 	    sizeof(req), sizeof(resp));
1027 	req.vport = apc->port_handle;
1028 	req.pdid = protection_dom_id;
1029 	req.doorbell_pageid = doorbell_pg_id;
1030 
1031 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1032 	    sizeof(resp));
1033 	if (err) {
1034 		if_printf(apc->ndev, "Failed to configure vPort: %d\n", err);
1035 		goto out;
1036 	}
1037 
1038 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_TX,
1039 	    sizeof(resp));
1040 	if (err || resp.hdr.status) {
1041 		if_printf(apc->ndev, "Failed to configure vPort: %d, 0x%x\n",
1042 		    err, resp.hdr.status);
1043 		if (!err)
1044 			err = EPROTO;
1045 
1046 		goto out;
1047 	}
1048 
1049 	apc->tx_shortform_allowed = resp.short_form_allowed;
1050 	apc->tx_vp_offset = resp.tx_vport_offset;
1051 
1052 	if_printf(apc->ndev, "Configured vPort %ju PD %u DB %u\n",
1053 	    apc->port_handle, protection_dom_id, doorbell_pg_id);
1054 
1055 out:
1056 	if (err)
1057 		mana_uncfg_vport(apc);
1058 
1059 	return err;
1060 }
1061 
1062 static int
1063 mana_cfg_vport_steering(struct mana_port_context *apc,
1064     enum TRI_STATE rx,
1065     bool update_default_rxobj, bool update_key,
1066     bool update_tab)
1067 {
1068 	uint16_t num_entries = MANA_INDIRECT_TABLE_SIZE;
1069 	struct mana_cfg_rx_steer_req *req = NULL;
1070 	struct mana_cfg_rx_steer_resp resp = {};
1071 	if_t ndev = apc->ndev;
1072 	mana_handle_t *req_indir_tab;
1073 	uint32_t req_buf_size;
1074 	int err;
1075 
1076 	req_buf_size = sizeof(*req) + sizeof(mana_handle_t) * num_entries;
1077 	req = malloc(req_buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
1078 	if (!req)
1079 		return ENOMEM;
1080 
1081 	mana_gd_init_req_hdr(&req->hdr, MANA_CONFIG_VPORT_RX, req_buf_size,
1082 	    sizeof(resp));
1083 
1084 	req->vport = apc->port_handle;
1085 	req->num_indir_entries = num_entries;
1086 	req->indir_tab_offset = sizeof(*req);
1087 	req->rx_enable = rx;
1088 	req->rss_enable = apc->rss_state;
1089 	req->update_default_rxobj = update_default_rxobj;
1090 	req->update_hashkey = update_key;
1091 	req->update_indir_tab = update_tab;
1092 	req->default_rxobj = apc->default_rxobj;
1093 
1094 	if (update_key)
1095 		memcpy(&req->hashkey, apc->hashkey, MANA_HASH_KEY_SIZE);
1096 
1097 	if (update_tab) {
1098 		req_indir_tab = (mana_handle_t *)(req + 1);
1099 		memcpy(req_indir_tab, apc->rxobj_table,
1100 		       req->num_indir_entries * sizeof(mana_handle_t));
1101 	}
1102 
1103 	err = mana_send_request(apc->ac, req, req_buf_size, &resp,
1104 	    sizeof(resp));
1105 	if (err) {
1106 		if_printf(ndev, "Failed to configure vPort RX: %d\n", err);
1107 		goto out;
1108 	}
1109 
1110 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_RX,
1111 	    sizeof(resp));
1112 	if (err) {
1113 		if_printf(ndev, "vPort RX configuration failed: %d\n", err);
1114 		goto out;
1115 	}
1116 
1117 	if (resp.hdr.status) {
1118 		if_printf(ndev, "vPort RX configuration failed: 0x%x\n",
1119 		    resp.hdr.status);
1120 		err = EPROTO;
1121 	}
1122 
1123 	if_printf(ndev, "Configured steering vPort %ju entries %u\n",
1124 	    apc->port_handle, num_entries);
1125 
1126 out:
1127 	free(req, M_DEVBUF);
1128 	return err;
1129 }
1130 
1131 int
1132 mana_create_wq_obj(struct mana_port_context *apc,
1133     mana_handle_t vport,
1134     uint32_t wq_type, struct mana_obj_spec *wq_spec,
1135     struct mana_obj_spec *cq_spec,
1136     mana_handle_t *wq_obj)
1137 {
1138 	struct mana_create_wqobj_resp resp = {};
1139 	struct mana_create_wqobj_req req = {};
1140 	if_t ndev = apc->ndev;
1141 	int err;
1142 
1143 	mana_gd_init_req_hdr(&req.hdr, MANA_CREATE_WQ_OBJ,
1144 	    sizeof(req), sizeof(resp));
1145 	req.vport = vport;
1146 	req.wq_type = wq_type;
1147 	req.wq_gdma_region = wq_spec->gdma_region;
1148 	req.cq_gdma_region = cq_spec->gdma_region;
1149 	req.wq_size = wq_spec->queue_size;
1150 	req.cq_size = cq_spec->queue_size;
1151 	req.cq_moderation_ctx_id = cq_spec->modr_ctx_id;
1152 	req.cq_parent_qid = cq_spec->attached_eq;
1153 
1154 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1155 	    sizeof(resp));
1156 	if (err) {
1157 		if_printf(ndev, "Failed to create WQ object: %d\n", err);
1158 		goto out;
1159 	}
1160 
1161 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CREATE_WQ_OBJ,
1162 	    sizeof(resp));
1163 	if (err || resp.hdr.status) {
1164 		if_printf(ndev, "Failed to create WQ object: %d, 0x%x\n", err,
1165 		    resp.hdr.status);
1166 		if (!err)
1167 			err = EPROTO;
1168 		goto out;
1169 	}
1170 
1171 	if (resp.wq_obj == INVALID_MANA_HANDLE) {
1172 		if_printf(ndev, "Got an invalid WQ object handle\n");
1173 		err = EPROTO;
1174 		goto out;
1175 	}
1176 
1177 	*wq_obj = resp.wq_obj;
1178 	wq_spec->queue_index = resp.wq_id;
1179 	cq_spec->queue_index = resp.cq_id;
1180 
1181 	return 0;
1182 out:
1183 	return err;
1184 }
1185 
1186 void
1187 mana_destroy_wq_obj(struct mana_port_context *apc, uint32_t wq_type,
1188     mana_handle_t wq_obj)
1189 {
1190 	struct mana_destroy_wqobj_resp resp = {};
1191 	struct mana_destroy_wqobj_req req = {};
1192 	if_t ndev = apc->ndev;
1193 	int err;
1194 
1195 	mana_gd_init_req_hdr(&req.hdr, MANA_DESTROY_WQ_OBJ,
1196 	    sizeof(req), sizeof(resp));
1197 	req.wq_type = wq_type;
1198 	req.wq_obj_handle = wq_obj;
1199 
1200 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1201 	    sizeof(resp));
1202 	if (err) {
1203 		if_printf(ndev, "Failed to destroy WQ object: %d\n", err);
1204 		return;
1205 	}
1206 
1207 	err = mana_verify_resp_hdr(&resp.hdr, MANA_DESTROY_WQ_OBJ,
1208 	    sizeof(resp));
1209 	if (err || resp.hdr.status)
1210 		if_printf(ndev, "Failed to destroy WQ object: %d, 0x%x\n",
1211 		    err, resp.hdr.status);
1212 }
1213 
1214 static void
1215 mana_destroy_eq(struct mana_context *ac)
1216 {
1217 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
1218 	struct gdma_queue *eq;
1219 	int i;
1220 
1221 	if (!ac->eqs)
1222 		return;
1223 
1224 	for (i = 0; i < gc->max_num_queues; i++) {
1225 		eq = ac->eqs[i].eq;
1226 		if (!eq)
1227 			continue;
1228 
1229 		mana_gd_destroy_queue(gc, eq);
1230 	}
1231 
1232 	free(ac->eqs, M_DEVBUF);
1233 	ac->eqs = NULL;
1234 }
1235 
1236 static int
1237 mana_create_eq(struct mana_context *ac)
1238 {
1239 	struct gdma_dev *gd = ac->gdma_dev;
1240 	struct gdma_context *gc = gd->gdma_context;
1241 	struct gdma_queue_spec spec = {};
1242 	int err;
1243 	int i;
1244 
1245 	ac->eqs = mallocarray(gc->max_num_queues, sizeof(struct mana_eq),
1246 	    M_DEVBUF, M_WAITOK | M_ZERO);
1247 	if (!ac->eqs)
1248 		return ENOMEM;
1249 
1250 	spec.type = GDMA_EQ;
1251 	spec.monitor_avl_buf = false;
1252 	spec.queue_size = EQ_SIZE;
1253 	spec.eq.callback = NULL;
1254 	spec.eq.context = ac->eqs;
1255 	spec.eq.log2_throttle_limit = LOG2_EQ_THROTTLE;
1256 
1257 	for (i = 0; i < gc->max_num_queues; i++) {
1258 		err = mana_gd_create_mana_eq(gd, &spec, &ac->eqs[i].eq);
1259 		if (err)
1260 			goto out;
1261 	}
1262 
1263 	return 0;
1264 out:
1265 	mana_destroy_eq(ac);
1266 	return err;
1267 }
1268 
1269 static int
1270 mana_fence_rq(struct mana_port_context *apc, struct mana_rxq *rxq)
1271 {
1272 	struct mana_fence_rq_resp resp = {};
1273 	struct mana_fence_rq_req req = {};
1274 	int err;
1275 
1276 	init_completion(&rxq->fence_event);
1277 
1278 	mana_gd_init_req_hdr(&req.hdr, MANA_FENCE_RQ,
1279 	    sizeof(req), sizeof(resp));
1280 	req.wq_obj_handle = rxq->rxobj;
1281 
1282 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1283 	    sizeof(resp));
1284 	if (err) {
1285 		if_printf(apc->ndev, "Failed to fence RQ %u: %d\n",
1286 		    rxq->rxq_idx, err);
1287 		return err;
1288 	}
1289 
1290 	err = mana_verify_resp_hdr(&resp.hdr, MANA_FENCE_RQ, sizeof(resp));
1291 	if (err || resp.hdr.status) {
1292 		if_printf(apc->ndev, "Failed to fence RQ %u: %d, 0x%x\n",
1293 		    rxq->rxq_idx, err, resp.hdr.status);
1294 		if (!err)
1295 			err = EPROTO;
1296 
1297 		return err;
1298 	}
1299 
1300 	if (wait_for_completion_timeout(&rxq->fence_event, 10 * hz)) {
1301 		if_printf(apc->ndev, "Failed to fence RQ %u: timed out\n",
1302 		    rxq->rxq_idx);
1303 		return ETIMEDOUT;
1304         }
1305 
1306 	return 0;
1307 }
1308 
1309 static void
1310 mana_fence_rqs(struct mana_port_context *apc)
1311 {
1312 	unsigned int rxq_idx;
1313 	struct mana_rxq *rxq;
1314 	int err;
1315 
1316 	for (rxq_idx = 0; rxq_idx < apc->num_queues; rxq_idx++) {
1317 		rxq = apc->rxqs[rxq_idx];
1318 		err = mana_fence_rq(apc, rxq);
1319 
1320 		/* In case of any error, use sleep instead. */
1321 		if (err)
1322 			gdma_msleep(100);
1323 	}
1324 }
1325 
1326 static int
1327 mana_move_wq_tail(struct gdma_queue *wq, uint32_t num_units)
1328 {
1329 	uint32_t used_space_old;
1330 	uint32_t used_space_new;
1331 
1332 	used_space_old = wq->head - wq->tail;
1333 	used_space_new = wq->head - (wq->tail + num_units);
1334 
1335 	if (used_space_new > used_space_old) {
1336 		mana_err(NULL,
1337 		    "WARNING: new used space %u greater than old one %u\n",
1338 		    used_space_new, used_space_old);
1339 		return ERANGE;
1340 	}
1341 
1342 	wq->tail += num_units;
1343 	return 0;
1344 }
1345 
1346 static void
1347 mana_poll_tx_cq(struct mana_cq *cq)
1348 {
1349 	struct gdma_comp *completions = cq->gdma_comp_buf;
1350 	struct gdma_posted_wqe_info *wqe_info;
1351 	struct mana_send_buf_info *tx_info;
1352 	unsigned int pkt_transmitted = 0;
1353 	unsigned int wqe_unit_cnt = 0;
1354 	struct mana_txq *txq = cq->txq;
1355 	struct mana_port_context *apc;
1356 	uint16_t next_to_complete;
1357 	if_t ndev;
1358 	int comp_read;
1359 	int txq_idx = txq->idx;;
1360 	int i;
1361 	int sa_drop = 0;
1362 
1363 	struct gdma_queue *gdma_wq;
1364 	unsigned int avail_space;
1365 	bool txq_full = false;
1366 
1367 	ndev = txq->ndev;
1368 	apc = if_getsoftc(ndev);
1369 
1370 	comp_read = mana_gd_poll_cq(cq->gdma_cq, completions,
1371 	    CQE_POLLING_BUFFER);
1372 
1373 	if (comp_read < 1)
1374 		return;
1375 
1376 	next_to_complete = txq->next_to_complete;
1377 
1378 	for (i = 0; i < comp_read; i++) {
1379 		struct mana_tx_comp_oob *cqe_oob;
1380 
1381 		if (!completions[i].is_sq) {
1382 			mana_err(NULL, "WARNING: Not for SQ\n");
1383 			return;
1384 		}
1385 
1386 		cqe_oob = (struct mana_tx_comp_oob *)completions[i].cqe_data;
1387 		if (cqe_oob->cqe_hdr.client_type !=
1388 				 MANA_CQE_COMPLETION) {
1389 			mana_err(NULL,
1390 			    "WARNING: Invalid CQE client type %u\n",
1391 			    cqe_oob->cqe_hdr.client_type);
1392 			return;
1393 		}
1394 
1395 		switch (cqe_oob->cqe_hdr.cqe_type) {
1396 		case CQE_TX_OKAY:
1397 			break;
1398 
1399 		case CQE_TX_SA_DROP:
1400 		case CQE_TX_MTU_DROP:
1401 		case CQE_TX_INVALID_OOB:
1402 		case CQE_TX_INVALID_ETH_TYPE:
1403 		case CQE_TX_HDR_PROCESSING_ERROR:
1404 		case CQE_TX_VF_DISABLED:
1405 		case CQE_TX_VPORT_IDX_OUT_OF_RANGE:
1406 		case CQE_TX_VPORT_DISABLED:
1407 		case CQE_TX_VLAN_TAGGING_VIOLATION:
1408 			sa_drop ++;
1409 			mana_err(NULL,
1410 			    "TX: txq %d CQE error %d, ntc = %d, "
1411 			    "pending sends = %d: err ignored.\n",
1412 			    txq_idx, cqe_oob->cqe_hdr.cqe_type,
1413 			    next_to_complete, txq->pending_sends);
1414 			break;
1415 
1416 		default:
1417 			/* If the CQE type is unexpected, log an error,
1418 			 * and go through the error path.
1419 			 */
1420 			mana_err(NULL,
1421 			    "ERROR: TX: Unexpected CQE type %d: HW BUG?\n",
1422 			    cqe_oob->cqe_hdr.cqe_type);
1423 			return;
1424 		}
1425 		if (txq->gdma_txq_id != completions[i].wq_num) {
1426 			mana_dbg(NULL,
1427 			    "txq gdma id not match completion wq num: "
1428 			    "%d != %d\n",
1429 			    txq->gdma_txq_id, completions[i].wq_num);
1430 			break;
1431 		}
1432 
1433 		tx_info = &txq->tx_buf_info[next_to_complete];
1434 		if (!tx_info->mbuf) {
1435 			mana_err(NULL,
1436 			    "WARNING: txq %d Empty mbuf on tx_info: %u, "
1437 			    "ntu = %u, pending_sends = %d, "
1438 			    "transmitted = %d, sa_drop = %d, i = %d, comp_read = %d\n",
1439 			    txq_idx, next_to_complete, txq->next_to_use,
1440 			    txq->pending_sends, pkt_transmitted, sa_drop,
1441 			    i, comp_read);
1442 			break;
1443 		}
1444 
1445 		wqe_info = &tx_info->wqe_inf;
1446 		wqe_unit_cnt += wqe_info->wqe_size_in_bu;
1447 
1448 		mana_tx_unmap_mbuf(apc, tx_info);
1449 		mb();
1450 
1451 		next_to_complete =
1452 		    (next_to_complete + 1) % MAX_SEND_BUFFERS_PER_QUEUE;
1453 
1454 		pkt_transmitted++;
1455 	}
1456 
1457 	txq->next_to_complete = next_to_complete;
1458 
1459 	if (wqe_unit_cnt == 0) {
1460 		mana_err(NULL,
1461 		    "WARNING: TX ring not proceeding!\n");
1462 		return;
1463 	}
1464 
1465 	mana_move_wq_tail(txq->gdma_sq, wqe_unit_cnt);
1466 
1467 	/* Ensure tail updated before checking q stop */
1468 	wmb();
1469 
1470 	gdma_wq = txq->gdma_sq;
1471 	avail_space = mana_gd_wq_avail_space(gdma_wq);
1472 
1473 
1474 	if ((if_getdrvflags(ndev) & MANA_TXQ_FULL) == MANA_TXQ_FULL) {
1475 		txq_full = true;
1476 	}
1477 
1478 	/* Ensure checking txq_full before apc->port_is_up. */
1479 	rmb();
1480 
1481 	if (txq_full && apc->port_is_up && avail_space >= MAX_TX_WQE_SIZE) {
1482 		/* Grab the txq lock and re-test */
1483 		mtx_lock(&txq->txq_mtx);
1484 		avail_space = mana_gd_wq_avail_space(gdma_wq);
1485 
1486 		if ((if_getdrvflags(ndev) & MANA_TXQ_FULL) == MANA_TXQ_FULL &&
1487 		    apc->port_is_up && avail_space >= MAX_TX_WQE_SIZE) {
1488 			/* Clear the Q full flag */
1489 			if_setdrvflagbits(apc->ndev, IFF_DRV_RUNNING,
1490 			    IFF_DRV_OACTIVE);
1491 			counter_u64_add(txq->stats.wakeup, 1);
1492 			if (txq->alt_txq_idx != txq->idx) {
1493 				uint64_t stops = counter_u64_fetch(txq->stats.stop);
1494 				uint64_t wakeups = counter_u64_fetch(txq->stats.wakeup);
1495 				/* Reset alt_txq_idx back if it is not overloaded */
1496 				if (stops < wakeups) {
1497 					txq->alt_txq_idx = txq->idx;
1498 					counter_u64_add(txq->stats.alt_reset, 1);
1499 				}
1500 			}
1501 			rmb();
1502 			/* Schedule a tx enqueue task */
1503 			taskqueue_enqueue(txq->enqueue_tq, &txq->enqueue_task);
1504 		}
1505 		mtx_unlock(&txq->txq_mtx);
1506 	}
1507 
1508 	if (atomic_sub_return(pkt_transmitted, &txq->pending_sends) < 0)
1509 		mana_err(NULL,
1510 		    "WARNING: TX %d pending_sends error: %d\n",
1511 		    txq->idx, txq->pending_sends);
1512 
1513 	cq->work_done = pkt_transmitted;
1514 }
1515 
1516 static void
1517 mana_post_pkt_rxq(struct mana_rxq *rxq)
1518 {
1519 	struct mana_recv_buf_oob *recv_buf_oob;
1520 	uint32_t curr_index;
1521 	int err;
1522 
1523 	curr_index = rxq->buf_index++;
1524 	if (rxq->buf_index == rxq->num_rx_buf)
1525 		rxq->buf_index = 0;
1526 
1527 	recv_buf_oob = &rxq->rx_oobs[curr_index];
1528 
1529 	err = mana_gd_post_and_ring(rxq->gdma_rq, &recv_buf_oob->wqe_req,
1530 	    &recv_buf_oob->wqe_inf);
1531 	if (err) {
1532 		mana_err(NULL, "WARNING: rxq %u post pkt err %d\n",
1533 		    rxq->rxq_idx, err);
1534 		return;
1535 	}
1536 
1537 	if (recv_buf_oob->wqe_inf.wqe_size_in_bu != 1) {
1538 		mana_err(NULL, "WARNING: rxq %u wqe_size_in_bu %u\n",
1539 		    rxq->rxq_idx, recv_buf_oob->wqe_inf.wqe_size_in_bu);
1540 	}
1541 }
1542 
1543 static void
1544 mana_rx_mbuf(struct mbuf *mbuf, struct mana_rxcomp_oob *cqe,
1545     struct mana_rxq *rxq)
1546 {
1547 	struct mana_stats *rx_stats = &rxq->stats;
1548 	if_t ndev = rxq->ndev;
1549 	uint32_t pkt_len = cqe->ppi[0].pkt_len;
1550 	uint16_t rxq_idx = rxq->rxq_idx;
1551 	struct mana_port_context *apc;
1552 	bool do_lro = false;
1553 	bool do_if_input;
1554 
1555 	apc = if_getsoftc(ndev);
1556 	rxq->rx_cq.work_done++;
1557 
1558 	if (!mbuf) {
1559 		return;
1560 	}
1561 
1562 	mbuf->m_flags |= M_PKTHDR;
1563 	mbuf->m_pkthdr.len = pkt_len;
1564 	mbuf->m_len = pkt_len;
1565 	mbuf->m_pkthdr.rcvif = ndev;
1566 
1567 	if ((if_getcapenable(ndev) & IFCAP_RXCSUM ||
1568 	    if_getcapenable(ndev) & IFCAP_RXCSUM_IPV6) &&
1569 	    (cqe->rx_iphdr_csum_succeed)) {
1570 		mbuf->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
1571 		mbuf->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1572 		if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed) {
1573 			mbuf->m_pkthdr.csum_flags |=
1574 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1575 			mbuf->m_pkthdr.csum_data = 0xffff;
1576 
1577 			if (cqe->rx_tcp_csum_succeed)
1578 				do_lro = true;
1579 		}
1580 	}
1581 
1582 	if (cqe->rx_hashtype != 0) {
1583 		mbuf->m_pkthdr.flowid = cqe->ppi[0].pkt_hash;
1584 
1585 		uint16_t hashtype = cqe->rx_hashtype;
1586 		if (hashtype & NDIS_HASH_IPV4_MASK) {
1587 			hashtype &= NDIS_HASH_IPV4_MASK;
1588 			switch (hashtype) {
1589 			case NDIS_HASH_TCP_IPV4:
1590 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV4);
1591 				break;
1592 			case NDIS_HASH_UDP_IPV4:
1593 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV4);
1594 				break;
1595 			default:
1596 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV4);
1597 			}
1598 		} else if (hashtype & NDIS_HASH_IPV6_MASK) {
1599 			hashtype &= NDIS_HASH_IPV6_MASK;
1600 			switch (hashtype) {
1601 			case NDIS_HASH_TCP_IPV6:
1602 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV6);
1603 				break;
1604 			case NDIS_HASH_TCP_IPV6_EX:
1605 				M_HASHTYPE_SET(mbuf,
1606 				    M_HASHTYPE_RSS_TCP_IPV6_EX);
1607 				break;
1608 			case NDIS_HASH_UDP_IPV6:
1609 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV6);
1610 				break;
1611 			case NDIS_HASH_UDP_IPV6_EX:
1612 				M_HASHTYPE_SET(mbuf,
1613 				    M_HASHTYPE_RSS_UDP_IPV6_EX);
1614 				break;
1615 			default:
1616 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV6);
1617 			}
1618 		} else {
1619 			M_HASHTYPE_SET(mbuf, M_HASHTYPE_OPAQUE_HASH);
1620 		}
1621 	} else {
1622 		mbuf->m_pkthdr.flowid = rxq_idx;
1623 		M_HASHTYPE_SET(mbuf, M_HASHTYPE_NONE);
1624 	}
1625 
1626 	do_if_input = true;
1627 	if ((if_getcapenable(ndev) & IFCAP_LRO) && do_lro) {
1628 		if (rxq->lro.lro_cnt != 0 &&
1629 		    tcp_lro_rx(&rxq->lro, mbuf, 0) == 0)
1630 			do_if_input = false;
1631 	}
1632 	if (do_if_input) {
1633 		if_input(ndev, mbuf);
1634 	}
1635 
1636 	counter_enter();
1637 	counter_u64_add_protected(rx_stats->packets, 1);
1638 	counter_u64_add_protected(apc->port_stats.rx_packets, 1);
1639 	counter_u64_add_protected(rx_stats->bytes, pkt_len);
1640 	counter_u64_add_protected(apc->port_stats.rx_bytes, pkt_len);
1641 	counter_exit();
1642 }
1643 
1644 static void
1645 mana_process_rx_cqe(struct mana_rxq *rxq, struct mana_cq *cq,
1646     struct gdma_comp *cqe)
1647 {
1648 	struct mana_rxcomp_oob *oob = (struct mana_rxcomp_oob *)cqe->cqe_data;
1649 	struct mana_recv_buf_oob *rxbuf_oob;
1650 	if_t ndev = rxq->ndev;
1651 	struct mana_port_context *apc;
1652 	struct mbuf *old_mbuf;
1653 	uint32_t curr, pktlen;
1654 	int err;
1655 
1656 	switch (oob->cqe_hdr.cqe_type) {
1657 	case CQE_RX_OKAY:
1658 		break;
1659 
1660 	case CQE_RX_TRUNCATED:
1661 		apc = if_getsoftc(ndev);
1662 		counter_u64_add(apc->port_stats.rx_drops, 1);
1663 		rxbuf_oob = &rxq->rx_oobs[rxq->buf_index];
1664 		if_printf(ndev, "Dropped a truncated packet\n");
1665 		goto drop;
1666 
1667 	case CQE_RX_COALESCED_4:
1668 		if_printf(ndev, "RX coalescing is unsupported\n");
1669 		return;
1670 
1671 	case CQE_RX_OBJECT_FENCE:
1672 		complete(&rxq->fence_event);
1673 		return;
1674 
1675 	default:
1676 		if_printf(ndev, "Unknown RX CQE type = %d\n",
1677 		    oob->cqe_hdr.cqe_type);
1678 		return;
1679 	}
1680 
1681 	if (oob->cqe_hdr.cqe_type != CQE_RX_OKAY)
1682 		return;
1683 
1684 	pktlen = oob->ppi[0].pkt_len;
1685 
1686 	if (pktlen == 0) {
1687 		/* data packets should never have packetlength of zero */
1688 		if_printf(ndev, "RX pkt len=0, rq=%u, cq=%u, rxobj=0x%jx\n",
1689 		    rxq->gdma_id, cq->gdma_id, rxq->rxobj);
1690 		return;
1691 	}
1692 
1693 	curr = rxq->buf_index;
1694 	rxbuf_oob = &rxq->rx_oobs[curr];
1695 	if (rxbuf_oob->wqe_inf.wqe_size_in_bu != 1) {
1696 		mana_err(NULL, "WARNING: Rx Incorrect complete "
1697 		    "WQE size %u\n",
1698 		    rxbuf_oob->wqe_inf.wqe_size_in_bu);
1699 	}
1700 
1701 	apc = if_getsoftc(ndev);
1702 
1703 	old_mbuf = rxbuf_oob->mbuf;
1704 
1705 	/* Unload DMA map for the old mbuf */
1706 	mana_unload_rx_mbuf(apc, rxq, rxbuf_oob, false);
1707 
1708 	/* Load a new mbuf to replace the old one */
1709 	err = mana_load_rx_mbuf(apc, rxq, rxbuf_oob, true);
1710 	if (err) {
1711 		mana_dbg(NULL,
1712 		    "failed to load rx mbuf, err = %d, packet dropped.\n",
1713 		    err);
1714 		counter_u64_add(rxq->stats.mbuf_alloc_fail, 1);
1715 		/*
1716 		 * Failed to load new mbuf, rxbuf_oob->mbuf is still
1717 		 * pointing to the old one. Drop the packet.
1718 		 */
1719 		 old_mbuf = NULL;
1720 		 /* Reload the existing mbuf */
1721 		 mana_load_rx_mbuf(apc, rxq, rxbuf_oob, false);
1722 	}
1723 
1724 	mana_rx_mbuf(old_mbuf, oob, rxq);
1725 
1726 drop:
1727 	mana_move_wq_tail(rxq->gdma_rq, rxbuf_oob->wqe_inf.wqe_size_in_bu);
1728 
1729 	mana_post_pkt_rxq(rxq);
1730 }
1731 
1732 static void
1733 mana_poll_rx_cq(struct mana_cq *cq)
1734 {
1735 	struct gdma_comp *comp = cq->gdma_comp_buf;
1736 	int comp_read, i;
1737 
1738 	comp_read = mana_gd_poll_cq(cq->gdma_cq, comp, CQE_POLLING_BUFFER);
1739 	KASSERT(comp_read <= CQE_POLLING_BUFFER,
1740 	    ("comp_read %d great than buf size %d",
1741 	    comp_read, CQE_POLLING_BUFFER));
1742 
1743 	for (i = 0; i < comp_read; i++) {
1744 		if (comp[i].is_sq == true) {
1745 			mana_err(NULL,
1746 			    "WARNING: CQE not for receive queue\n");
1747 			return;
1748 		}
1749 
1750 		/* verify recv cqe references the right rxq */
1751 		if (comp[i].wq_num != cq->rxq->gdma_id) {
1752 			mana_err(NULL,
1753 			    "WARNING: Received CQE %d  not for "
1754 			    "this receive queue %d\n",
1755 			    comp[i].wq_num,  cq->rxq->gdma_id);
1756 			return;
1757 		}
1758 
1759 		mana_process_rx_cqe(cq->rxq, cq, &comp[i]);
1760 	}
1761 
1762 	tcp_lro_flush_all(&cq->rxq->lro);
1763 }
1764 
1765 static void
1766 mana_cq_handler(void *context, struct gdma_queue *gdma_queue)
1767 {
1768 	struct mana_cq *cq = context;
1769 	uint8_t arm_bit;
1770 
1771 	KASSERT(cq->gdma_cq == gdma_queue,
1772 	    ("cq do not match %p, %p", cq->gdma_cq, gdma_queue));
1773 
1774 	if (cq->type == MANA_CQ_TYPE_RX) {
1775 		mana_poll_rx_cq(cq);
1776 	} else {
1777 		mana_poll_tx_cq(cq);
1778 	}
1779 
1780 	if (cq->work_done < cq->budget && cq->do_not_ring_db == false)
1781 		arm_bit = SET_ARM_BIT;
1782 	else
1783 		arm_bit = 0;
1784 
1785 	mana_gd_ring_cq(gdma_queue, arm_bit);
1786 }
1787 
1788 #define MANA_POLL_BUDGET	8
1789 #define MANA_RX_BUDGET		256
1790 #define MANA_TX_BUDGET		MAX_SEND_BUFFERS_PER_QUEUE
1791 
1792 static void
1793 mana_poll(void *arg, int pending)
1794 {
1795 	struct mana_cq *cq = arg;
1796 	int i;
1797 
1798 	cq->work_done = 0;
1799 	if (cq->type == MANA_CQ_TYPE_RX) {
1800 		cq->budget = MANA_RX_BUDGET;
1801 	} else {
1802 		cq->budget = MANA_TX_BUDGET;
1803 	}
1804 
1805 	for (i = 0; i < MANA_POLL_BUDGET; i++) {
1806 		/*
1807 		 * If this is the last loop, set the budget big enough
1808 		 * so it will arm the CQ any way.
1809 		 */
1810 		if (i == (MANA_POLL_BUDGET - 1))
1811 			cq->budget = CQE_POLLING_BUFFER + 1;
1812 
1813 		mana_cq_handler(cq, cq->gdma_cq);
1814 
1815 		if (cq->work_done < cq->budget)
1816 			break;
1817 
1818 		cq->work_done = 0;
1819 	}
1820 }
1821 
1822 static void
1823 mana_schedule_task(void *arg, struct gdma_queue *gdma_queue)
1824 {
1825 	struct mana_cq *cq = arg;
1826 
1827 	taskqueue_enqueue(cq->cleanup_tq, &cq->cleanup_task);
1828 }
1829 
1830 static void
1831 mana_deinit_cq(struct mana_port_context *apc, struct mana_cq *cq)
1832 {
1833 	struct gdma_dev *gd = apc->ac->gdma_dev;
1834 
1835 	if (!cq->gdma_cq)
1836 		return;
1837 
1838 	/* Drain cleanup taskqueue */
1839 	if (cq->cleanup_tq) {
1840 		while (taskqueue_cancel(cq->cleanup_tq,
1841 		    &cq->cleanup_task, NULL)) {
1842 			taskqueue_drain(cq->cleanup_tq,
1843 			    &cq->cleanup_task);
1844 		}
1845 
1846 		taskqueue_free(cq->cleanup_tq);
1847 	}
1848 
1849 	mana_gd_destroy_queue(gd->gdma_context, cq->gdma_cq);
1850 }
1851 
1852 static void
1853 mana_deinit_txq(struct mana_port_context *apc, struct mana_txq *txq)
1854 {
1855 	struct gdma_dev *gd = apc->ac->gdma_dev;
1856 	struct mana_send_buf_info *txbuf_info;
1857 	uint32_t pending_sends;
1858 	int i;
1859 
1860 	if (!txq->gdma_sq)
1861 		return;
1862 
1863 	if ((pending_sends = atomic_read(&txq->pending_sends)) > 0) {
1864 		mana_err(NULL,
1865 		    "WARNING: txq pending sends not zero: %u\n",
1866 		    pending_sends);
1867 	}
1868 
1869 	if (txq->next_to_use != txq->next_to_complete) {
1870 		mana_err(NULL,
1871 		    "WARNING: txq buf not completed, "
1872 		    "next use %u, next complete %u\n",
1873 		    txq->next_to_use, txq->next_to_complete);
1874 	}
1875 
1876 	/* Flush buf ring. Grab txq mtx lock */
1877 	if (txq->txq_br) {
1878 		mtx_lock(&txq->txq_mtx);
1879 		drbr_flush(apc->ndev, txq->txq_br);
1880 		mtx_unlock(&txq->txq_mtx);
1881 		buf_ring_free(txq->txq_br, M_DEVBUF);
1882 	}
1883 
1884 	/* Drain taskqueue */
1885 	if (txq->enqueue_tq) {
1886 		while (taskqueue_cancel(txq->enqueue_tq,
1887 		    &txq->enqueue_task, NULL)) {
1888 			taskqueue_drain(txq->enqueue_tq,
1889 			    &txq->enqueue_task);
1890 		}
1891 
1892 		taskqueue_free(txq->enqueue_tq);
1893 	}
1894 
1895 	if (txq->tx_buf_info) {
1896 		/* Free all mbufs which are still in-flight */
1897 		for (i = 0; i < MAX_SEND_BUFFERS_PER_QUEUE; i++) {
1898 			txbuf_info = &txq->tx_buf_info[i];
1899 			if (txbuf_info->mbuf) {
1900 				mana_tx_unmap_mbuf(apc, txbuf_info);
1901 			}
1902 		}
1903 
1904 		free(txq->tx_buf_info, M_DEVBUF);
1905 	}
1906 
1907 	mana_free_counters((counter_u64_t *)&txq->stats,
1908 	    sizeof(txq->stats));
1909 
1910 	mana_gd_destroy_queue(gd->gdma_context, txq->gdma_sq);
1911 
1912 	mtx_destroy(&txq->txq_mtx);
1913 }
1914 
1915 static void
1916 mana_destroy_txq(struct mana_port_context *apc)
1917 {
1918 	int i;
1919 
1920 	if (!apc->tx_qp)
1921 		return;
1922 
1923 	for (i = 0; i < apc->num_queues; i++) {
1924 		mana_destroy_wq_obj(apc, GDMA_SQ, apc->tx_qp[i].tx_object);
1925 
1926 		mana_deinit_cq(apc, &apc->tx_qp[i].tx_cq);
1927 
1928 		mana_deinit_txq(apc, &apc->tx_qp[i].txq);
1929 	}
1930 
1931 	free(apc->tx_qp, M_DEVBUF);
1932 	apc->tx_qp = NULL;
1933 }
1934 
1935 static int
1936 mana_create_txq(struct mana_port_context *apc, if_t net)
1937 {
1938 	struct mana_context *ac = apc->ac;
1939 	struct gdma_dev *gd = ac->gdma_dev;
1940 	struct mana_obj_spec wq_spec;
1941 	struct mana_obj_spec cq_spec;
1942 	struct gdma_queue_spec spec;
1943 	struct gdma_context *gc;
1944 	struct mana_txq *txq;
1945 	struct mana_cq *cq;
1946 	uint32_t txq_size;
1947 	uint32_t cq_size;
1948 	int err;
1949 	int i;
1950 
1951 	apc->tx_qp = mallocarray(apc->num_queues, sizeof(struct mana_tx_qp),
1952 	    M_DEVBUF, M_WAITOK | M_ZERO);
1953 	if (!apc->tx_qp)
1954 		return ENOMEM;
1955 
1956 	/*  The minimum size of the WQE is 32 bytes, hence
1957 	 *  MAX_SEND_BUFFERS_PER_QUEUE represents the maximum number of WQEs
1958 	 *  the SQ can store. This value is then used to size other queues
1959 	 *  to prevent overflow.
1960 	 */
1961 	txq_size = MAX_SEND_BUFFERS_PER_QUEUE * 32;
1962 	KASSERT(IS_ALIGNED(txq_size, PAGE_SIZE),
1963 	    ("txq size not page aligned"));
1964 
1965 	cq_size = MAX_SEND_BUFFERS_PER_QUEUE * COMP_ENTRY_SIZE;
1966 	cq_size = ALIGN(cq_size, PAGE_SIZE);
1967 
1968 	gc = gd->gdma_context;
1969 
1970 	for (i = 0; i < apc->num_queues; i++) {
1971 		apc->tx_qp[i].tx_object = INVALID_MANA_HANDLE;
1972 
1973 		/* Create SQ */
1974 		txq = &apc->tx_qp[i].txq;
1975 
1976 		txq->ndev = net;
1977 		txq->vp_offset = apc->tx_vp_offset;
1978 		txq->idx = i;
1979 		txq->alt_txq_idx = i;
1980 
1981 		memset(&spec, 0, sizeof(spec));
1982 		spec.type = GDMA_SQ;
1983 		spec.monitor_avl_buf = true;
1984 		spec.queue_size = txq_size;
1985 		err = mana_gd_create_mana_wq_cq(gd, &spec, &txq->gdma_sq);
1986 		if (err)
1987 			goto out;
1988 
1989 		/* Create SQ's CQ */
1990 		cq = &apc->tx_qp[i].tx_cq;
1991 		cq->type = MANA_CQ_TYPE_TX;
1992 
1993 		cq->txq = txq;
1994 
1995 		memset(&spec, 0, sizeof(spec));
1996 		spec.type = GDMA_CQ;
1997 		spec.monitor_avl_buf = false;
1998 		spec.queue_size = cq_size;
1999 		spec.cq.callback = mana_schedule_task;
2000 		spec.cq.parent_eq = ac->eqs[i].eq;
2001 		spec.cq.context = cq;
2002 		err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
2003 		if (err)
2004 			goto out;
2005 
2006 		memset(&wq_spec, 0, sizeof(wq_spec));
2007 		memset(&cq_spec, 0, sizeof(cq_spec));
2008 
2009 		wq_spec.gdma_region = txq->gdma_sq->mem_info.dma_region_handle;
2010 		wq_spec.queue_size = txq->gdma_sq->queue_size;
2011 
2012 		cq_spec.gdma_region = cq->gdma_cq->mem_info.dma_region_handle;
2013 		cq_spec.queue_size = cq->gdma_cq->queue_size;
2014 		cq_spec.modr_ctx_id = 0;
2015 		cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
2016 
2017 		err = mana_create_wq_obj(apc, apc->port_handle, GDMA_SQ,
2018 		    &wq_spec, &cq_spec, &apc->tx_qp[i].tx_object);
2019 
2020 		if (err)
2021 			goto out;
2022 
2023 		txq->gdma_sq->id = wq_spec.queue_index;
2024 		cq->gdma_cq->id = cq_spec.queue_index;
2025 
2026 		txq->gdma_sq->mem_info.dma_region_handle =
2027 		    GDMA_INVALID_DMA_REGION;
2028 		cq->gdma_cq->mem_info.dma_region_handle =
2029 		    GDMA_INVALID_DMA_REGION;
2030 
2031 		txq->gdma_txq_id = txq->gdma_sq->id;
2032 
2033 		cq->gdma_id = cq->gdma_cq->id;
2034 
2035 		mana_dbg(NULL,
2036 		    "txq %d, txq gdma id %d, txq cq gdma id %d\n",
2037 		    i, txq->gdma_txq_id, cq->gdma_id);;
2038 
2039 		if (cq->gdma_id >= gc->max_num_cqs) {
2040 			if_printf(net, "CQ id %u too large.\n", cq->gdma_id);
2041 			err = EINVAL;
2042 			goto out;
2043 		}
2044 
2045 		gc->cq_table[cq->gdma_id] = cq->gdma_cq;
2046 
2047 		/* Initialize tx specific data */
2048 		txq->tx_buf_info = malloc(MAX_SEND_BUFFERS_PER_QUEUE *
2049 		    sizeof(struct mana_send_buf_info),
2050 		    M_DEVBUF, M_WAITOK | M_ZERO);
2051 		if (unlikely(txq->tx_buf_info == NULL)) {
2052 			if_printf(net,
2053 			    "Failed to allocate tx buf info for SQ %u\n",
2054 			    txq->gdma_sq->id);
2055 			err = ENOMEM;
2056 			goto out;
2057 		}
2058 
2059 
2060 		snprintf(txq->txq_mtx_name, nitems(txq->txq_mtx_name),
2061 		    "mana:tx(%d)", i);
2062 		mtx_init(&txq->txq_mtx, txq->txq_mtx_name, NULL, MTX_DEF);
2063 
2064 		txq->txq_br = buf_ring_alloc(4 * MAX_SEND_BUFFERS_PER_QUEUE,
2065 		    M_DEVBUF, M_WAITOK, &txq->txq_mtx);
2066 		if (unlikely(txq->txq_br == NULL)) {
2067 			if_printf(net,
2068 			    "Failed to allocate buf ring for SQ %u\n",
2069 			    txq->gdma_sq->id);
2070 			err = ENOMEM;
2071 			goto out;
2072 		}
2073 
2074 		/* Allocate taskqueue for deferred send */
2075 		TASK_INIT(&txq->enqueue_task, 0, mana_xmit_taskfunc, txq);
2076 		txq->enqueue_tq = taskqueue_create_fast("mana_tx_enque",
2077 		    M_NOWAIT, taskqueue_thread_enqueue, &txq->enqueue_tq);
2078 		if (unlikely(txq->enqueue_tq == NULL)) {
2079 			if_printf(net,
2080 			    "Unable to create tx %d enqueue task queue\n", i);
2081 			err = ENOMEM;
2082 			goto out;
2083 		}
2084 		taskqueue_start_threads(&txq->enqueue_tq, 1, PI_NET,
2085 		    "mana txq p%u-tx%d", apc->port_idx, i);
2086 
2087 		mana_alloc_counters((counter_u64_t *)&txq->stats,
2088 		    sizeof(txq->stats));
2089 
2090 		/* Allocate and start the cleanup task on CQ */
2091 		cq->do_not_ring_db = false;
2092 
2093 		NET_TASK_INIT(&cq->cleanup_task, 0, mana_poll, cq);
2094 		cq->cleanup_tq =
2095 		    taskqueue_create_fast("mana tx cq cleanup",
2096 		    M_WAITOK, taskqueue_thread_enqueue,
2097 		    &cq->cleanup_tq);
2098 
2099 		if (apc->last_tx_cq_bind_cpu < 0)
2100 			apc->last_tx_cq_bind_cpu = CPU_FIRST();
2101 		cq->cpu = apc->last_tx_cq_bind_cpu;
2102 		apc->last_tx_cq_bind_cpu = CPU_NEXT(apc->last_tx_cq_bind_cpu);
2103 
2104 		if (apc->bind_cleanup_thread_cpu) {
2105 			cpuset_t cpu_mask;
2106 			CPU_SETOF(cq->cpu, &cpu_mask);
2107 			taskqueue_start_threads_cpuset(&cq->cleanup_tq,
2108 			    1, PI_NET, &cpu_mask,
2109 			    "mana cq p%u-tx%u-cpu%d",
2110 			    apc->port_idx, txq->idx, cq->cpu);
2111 		} else {
2112 			taskqueue_start_threads(&cq->cleanup_tq, 1,
2113 			    PI_NET, "mana cq p%u-tx%u",
2114 			    apc->port_idx, txq->idx);
2115 		}
2116 
2117 		mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
2118 	}
2119 
2120 	return 0;
2121 out:
2122 	mana_destroy_txq(apc);
2123 	return err;
2124 }
2125 
2126 static void
2127 mana_destroy_rxq(struct mana_port_context *apc, struct mana_rxq *rxq,
2128     bool validate_state)
2129 {
2130 	struct gdma_context *gc = apc->ac->gdma_dev->gdma_context;
2131 	struct mana_recv_buf_oob *rx_oob;
2132 	int i;
2133 
2134 	if (!rxq)
2135 		return;
2136 
2137 	if (validate_state) {
2138 		/*
2139 		 * XXX Cancel and drain cleanup task queue here.
2140 		 */
2141 		;
2142 	}
2143 
2144 	mana_destroy_wq_obj(apc, GDMA_RQ, rxq->rxobj);
2145 
2146 	mana_deinit_cq(apc, &rxq->rx_cq);
2147 
2148 	mana_free_counters((counter_u64_t *)&rxq->stats,
2149 	    sizeof(rxq->stats));
2150 
2151 	/* Free LRO resources */
2152 	tcp_lro_free(&rxq->lro);
2153 
2154 	for (i = 0; i < rxq->num_rx_buf; i++) {
2155 		rx_oob = &rxq->rx_oobs[i];
2156 
2157 		if (rx_oob->mbuf)
2158 			mana_unload_rx_mbuf(apc, rxq, rx_oob, true);
2159 
2160 		bus_dmamap_destroy(apc->rx_buf_tag, rx_oob->dma_map);
2161 	}
2162 
2163 	if (rxq->gdma_rq)
2164 		mana_gd_destroy_queue(gc, rxq->gdma_rq);
2165 
2166 	free(rxq, M_DEVBUF);
2167 }
2168 
2169 #define MANA_WQE_HEADER_SIZE 16
2170 #define MANA_WQE_SGE_SIZE 16
2171 
2172 static int
2173 mana_alloc_rx_wqe(struct mana_port_context *apc,
2174     struct mana_rxq *rxq, uint32_t *rxq_size, uint32_t *cq_size)
2175 {
2176 	struct mana_recv_buf_oob *rx_oob;
2177 	uint32_t buf_idx;
2178 	int err;
2179 
2180 	if (rxq->datasize == 0 || rxq->datasize > PAGE_SIZE) {
2181 		mana_err(NULL,
2182 		    "WARNING: Invalid rxq datasize %u\n", rxq->datasize);
2183 	}
2184 
2185 	*rxq_size = 0;
2186 	*cq_size = 0;
2187 
2188 	for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
2189 		rx_oob = &rxq->rx_oobs[buf_idx];
2190 		memset(rx_oob, 0, sizeof(*rx_oob));
2191 
2192 		err = bus_dmamap_create(apc->rx_buf_tag, 0,
2193 		    &rx_oob->dma_map);
2194 		if (err) {
2195 			mana_err(NULL,
2196 			    "Failed to  create rx DMA map for buf %d\n",
2197 			    buf_idx);
2198 			return err;
2199 		}
2200 
2201 		err = mana_load_rx_mbuf(apc, rxq, rx_oob, true);
2202 		if (err) {
2203 			mana_err(NULL,
2204 			    "Failed to  create rx DMA map for buf %d\n",
2205 			    buf_idx);
2206 			bus_dmamap_destroy(apc->rx_buf_tag, rx_oob->dma_map);
2207 			return err;
2208 		}
2209 
2210 		rx_oob->wqe_req.sgl = rx_oob->sgl;
2211 		rx_oob->wqe_req.num_sge = rx_oob->num_sge;
2212 		rx_oob->wqe_req.inline_oob_size = 0;
2213 		rx_oob->wqe_req.inline_oob_data = NULL;
2214 		rx_oob->wqe_req.flags = 0;
2215 		rx_oob->wqe_req.client_data_unit = 0;
2216 
2217 		*rxq_size += ALIGN(MANA_WQE_HEADER_SIZE +
2218 				   MANA_WQE_SGE_SIZE * rx_oob->num_sge, 32);
2219 		*cq_size += COMP_ENTRY_SIZE;
2220 	}
2221 
2222 	return 0;
2223 }
2224 
2225 static int
2226 mana_push_wqe(struct mana_rxq *rxq)
2227 {
2228 	struct mana_recv_buf_oob *rx_oob;
2229 	uint32_t buf_idx;
2230 	int err;
2231 
2232 	for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
2233 		rx_oob = &rxq->rx_oobs[buf_idx];
2234 
2235 		err = mana_gd_post_and_ring(rxq->gdma_rq, &rx_oob->wqe_req,
2236 		    &rx_oob->wqe_inf);
2237 		if (err)
2238 			return ENOSPC;
2239 	}
2240 
2241 	return 0;
2242 }
2243 
2244 static struct mana_rxq *
2245 mana_create_rxq(struct mana_port_context *apc, uint32_t rxq_idx,
2246     struct mana_eq *eq, if_t ndev)
2247 {
2248 	struct gdma_dev *gd = apc->ac->gdma_dev;
2249 	struct mana_obj_spec wq_spec;
2250 	struct mana_obj_spec cq_spec;
2251 	struct gdma_queue_spec spec;
2252 	struct mana_cq *cq = NULL;
2253 	uint32_t cq_size, rq_size;
2254 	struct gdma_context *gc;
2255 	struct mana_rxq *rxq;
2256 	int err;
2257 
2258 	gc = gd->gdma_context;
2259 
2260 	rxq = malloc(sizeof(*rxq) +
2261 	    RX_BUFFERS_PER_QUEUE * sizeof(struct mana_recv_buf_oob),
2262 	    M_DEVBUF, M_WAITOK | M_ZERO);
2263 	if (!rxq)
2264 		return NULL;
2265 
2266 	rxq->ndev = ndev;
2267 	rxq->num_rx_buf = RX_BUFFERS_PER_QUEUE;
2268 	rxq->rxq_idx = rxq_idx;
2269 	/*
2270 	 * Minimum size is MCLBYTES(2048) bytes for a mbuf cluster.
2271 	 * Now we just allow maximum size of 4096.
2272 	 */
2273 	rxq->datasize = ALIGN(apc->frame_size, MCLBYTES);
2274 	if (rxq->datasize > MAX_FRAME_SIZE)
2275 		rxq->datasize = MAX_FRAME_SIZE;
2276 
2277 	mana_dbg(NULL, "Setting rxq %d datasize %d\n",
2278 	    rxq_idx, rxq->datasize);
2279 
2280 	rxq->rxobj = INVALID_MANA_HANDLE;
2281 
2282 	err = mana_alloc_rx_wqe(apc, rxq, &rq_size, &cq_size);
2283 	if (err)
2284 		goto out;
2285 
2286 	/* Create LRO for the RQ */
2287 	if (if_getcapenable(ndev) & IFCAP_LRO) {
2288 		err = tcp_lro_init(&rxq->lro);
2289 		if (err) {
2290 			if_printf(ndev, "Failed to create LRO for rxq %d\n",
2291 			    rxq_idx);
2292 		} else {
2293 			rxq->lro.ifp = ndev;
2294 		}
2295 	}
2296 
2297 	mana_alloc_counters((counter_u64_t *)&rxq->stats,
2298 	    sizeof(rxq->stats));
2299 
2300 	rq_size = ALIGN(rq_size, PAGE_SIZE);
2301 	cq_size = ALIGN(cq_size, PAGE_SIZE);
2302 
2303 	/* Create RQ */
2304 	memset(&spec, 0, sizeof(spec));
2305 	spec.type = GDMA_RQ;
2306 	spec.monitor_avl_buf = true;
2307 	spec.queue_size = rq_size;
2308 	err = mana_gd_create_mana_wq_cq(gd, &spec, &rxq->gdma_rq);
2309 	if (err)
2310 		goto out;
2311 
2312 	/* Create RQ's CQ */
2313 	cq = &rxq->rx_cq;
2314 	cq->type = MANA_CQ_TYPE_RX;
2315 	cq->rxq = rxq;
2316 
2317 	memset(&spec, 0, sizeof(spec));
2318 	spec.type = GDMA_CQ;
2319 	spec.monitor_avl_buf = false;
2320 	spec.queue_size = cq_size;
2321 	spec.cq.callback = mana_schedule_task;
2322 	spec.cq.parent_eq = eq->eq;
2323 	spec.cq.context = cq;
2324 	err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
2325 	if (err)
2326 		goto out;
2327 
2328 	memset(&wq_spec, 0, sizeof(wq_spec));
2329 	memset(&cq_spec, 0, sizeof(cq_spec));
2330 	wq_spec.gdma_region = rxq->gdma_rq->mem_info.dma_region_handle;
2331 	wq_spec.queue_size = rxq->gdma_rq->queue_size;
2332 
2333 	cq_spec.gdma_region = cq->gdma_cq->mem_info.dma_region_handle;
2334 	cq_spec.queue_size = cq->gdma_cq->queue_size;
2335 	cq_spec.modr_ctx_id = 0;
2336 	cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
2337 
2338 	err = mana_create_wq_obj(apc, apc->port_handle, GDMA_RQ,
2339 	    &wq_spec, &cq_spec, &rxq->rxobj);
2340 	if (err)
2341 		goto out;
2342 
2343 	rxq->gdma_rq->id = wq_spec.queue_index;
2344 	cq->gdma_cq->id = cq_spec.queue_index;
2345 
2346 	rxq->gdma_rq->mem_info.dma_region_handle = GDMA_INVALID_DMA_REGION;
2347 	cq->gdma_cq->mem_info.dma_region_handle = GDMA_INVALID_DMA_REGION;
2348 
2349 	rxq->gdma_id = rxq->gdma_rq->id;
2350 	cq->gdma_id = cq->gdma_cq->id;
2351 
2352 	err = mana_push_wqe(rxq);
2353 	if (err)
2354 		goto out;
2355 
2356 	if (cq->gdma_id >= gc->max_num_cqs) {
2357 		err = EINVAL;
2358 		goto out;
2359 	}
2360 
2361 	gc->cq_table[cq->gdma_id] = cq->gdma_cq;
2362 
2363 	/* Allocate and start the cleanup task on CQ */
2364 	cq->do_not_ring_db = false;
2365 
2366 	NET_TASK_INIT(&cq->cleanup_task, 0, mana_poll, cq);
2367 	cq->cleanup_tq =
2368 	    taskqueue_create_fast("mana rx cq cleanup",
2369 	    M_WAITOK, taskqueue_thread_enqueue,
2370 	    &cq->cleanup_tq);
2371 
2372 	if (apc->last_rx_cq_bind_cpu < 0)
2373 		apc->last_rx_cq_bind_cpu = CPU_FIRST();
2374 	cq->cpu = apc->last_rx_cq_bind_cpu;
2375 	apc->last_rx_cq_bind_cpu = CPU_NEXT(apc->last_rx_cq_bind_cpu);
2376 
2377 	if (apc->bind_cleanup_thread_cpu) {
2378 		cpuset_t cpu_mask;
2379 		CPU_SETOF(cq->cpu, &cpu_mask);
2380 		taskqueue_start_threads_cpuset(&cq->cleanup_tq,
2381 		    1, PI_NET, &cpu_mask,
2382 		    "mana cq p%u-rx%u-cpu%d",
2383 		    apc->port_idx, rxq->rxq_idx, cq->cpu);
2384 	} else {
2385 		taskqueue_start_threads(&cq->cleanup_tq, 1,
2386 		    PI_NET, "mana cq p%u-rx%u",
2387 		    apc->port_idx, rxq->rxq_idx);
2388 	}
2389 
2390 	mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
2391 out:
2392 	if (!err)
2393 		return rxq;
2394 
2395 	if_printf(ndev, "Failed to create RXQ: err = %d\n", err);
2396 
2397 	mana_destroy_rxq(apc, rxq, false);
2398 
2399 	if (cq)
2400 		mana_deinit_cq(apc, cq);
2401 
2402 	return NULL;
2403 }
2404 
2405 static int
2406 mana_add_rx_queues(struct mana_port_context *apc, if_t ndev)
2407 {
2408 	struct mana_context *ac = apc->ac;
2409 	struct mana_rxq *rxq;
2410 	int err = 0;
2411 	int i;
2412 
2413 	for (i = 0; i < apc->num_queues; i++) {
2414 		rxq = mana_create_rxq(apc, i, &ac->eqs[i], ndev);
2415 		if (!rxq) {
2416 			err = ENOMEM;
2417 			goto out;
2418 		}
2419 
2420 		apc->rxqs[i] = rxq;
2421 	}
2422 
2423 	apc->default_rxobj = apc->rxqs[0]->rxobj;
2424 out:
2425 	return err;
2426 }
2427 
2428 static void
2429 mana_destroy_vport(struct mana_port_context *apc)
2430 {
2431 	struct mana_rxq *rxq;
2432 	uint32_t rxq_idx;
2433 
2434 	for (rxq_idx = 0; rxq_idx < apc->num_queues; rxq_idx++) {
2435 		rxq = apc->rxqs[rxq_idx];
2436 		if (!rxq)
2437 			continue;
2438 
2439 		mana_destroy_rxq(apc, rxq, true);
2440 		apc->rxqs[rxq_idx] = NULL;
2441 	}
2442 
2443 	mana_destroy_txq(apc);
2444 
2445 	mana_uncfg_vport(apc);
2446 }
2447 
2448 static int
2449 mana_create_vport(struct mana_port_context *apc, if_t net)
2450 {
2451 	struct gdma_dev *gd = apc->ac->gdma_dev;
2452 	int err;
2453 
2454 	apc->default_rxobj = INVALID_MANA_HANDLE;
2455 
2456 	err = mana_cfg_vport(apc, gd->pdid, gd->doorbell);
2457 	if (err)
2458 		return err;
2459 
2460 	return mana_create_txq(apc, net);
2461 }
2462 
2463 
2464 static void mana_rss_table_init(struct mana_port_context *apc)
2465 {
2466 	int i;
2467 
2468 	for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
2469 		apc->indir_table[i] = i % apc->num_queues;
2470 }
2471 
2472 int mana_config_rss(struct mana_port_context *apc, enum TRI_STATE rx,
2473 		    bool update_hash, bool update_tab)
2474 {
2475 	uint32_t queue_idx;
2476 	int err;
2477 	int i;
2478 
2479 	if (update_tab) {
2480 		for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++) {
2481 			queue_idx = apc->indir_table[i];
2482 			apc->rxobj_table[i] = apc->rxqs[queue_idx]->rxobj;
2483 		}
2484 	}
2485 
2486 	err = mana_cfg_vport_steering(apc, rx, true, update_hash, update_tab);
2487 	if (err)
2488 		return err;
2489 
2490 	mana_fence_rqs(apc);
2491 
2492 	return 0;
2493 }
2494 
2495 static int
2496 mana_init_port(if_t ndev)
2497 {
2498 	struct mana_port_context *apc = if_getsoftc(ndev);
2499 	uint32_t max_txq, max_rxq, max_queues;
2500 	int port_idx = apc->port_idx;
2501 	uint32_t num_indirect_entries;
2502 	int err;
2503 
2504 	err = mana_init_port_context(apc);
2505 	if (err)
2506 		return err;
2507 
2508 	err = mana_query_vport_cfg(apc, port_idx, &max_txq, &max_rxq,
2509 	    &num_indirect_entries);
2510 	if (err) {
2511 		if_printf(ndev, "Failed to query info for vPort %d\n",
2512 		    port_idx);
2513 		goto reset_apc;
2514 	}
2515 
2516 	max_queues = min_t(uint32_t, max_txq, max_rxq);
2517 	if (apc->max_queues > max_queues)
2518 		apc->max_queues = max_queues;
2519 
2520 	if (apc->num_queues > apc->max_queues)
2521 		apc->num_queues = apc->max_queues;
2522 
2523 	return 0;
2524 
2525 reset_apc:
2526 	bus_dma_tag_destroy(apc->rx_buf_tag);
2527 	apc->rx_buf_tag = NULL;
2528 	free(apc->rxqs, M_DEVBUF);
2529 	apc->rxqs = NULL;
2530 	return err;
2531 }
2532 
2533 int
2534 mana_alloc_queues(if_t ndev)
2535 {
2536 	struct mana_port_context *apc = if_getsoftc(ndev);
2537 	int err;
2538 
2539 	err = mana_create_vport(apc, ndev);
2540 	if (err)
2541 		return err;
2542 
2543 	err = mana_add_rx_queues(apc, ndev);
2544 	if (err)
2545 		goto destroy_vport;
2546 
2547 	apc->rss_state = apc->num_queues > 1 ? TRI_STATE_TRUE : TRI_STATE_FALSE;
2548 
2549 	mana_rss_table_init(apc);
2550 
2551 	err = mana_config_rss(apc, TRI_STATE_TRUE, true, true);
2552 	if (err)
2553 		goto destroy_vport;
2554 
2555 	return 0;
2556 
2557 destroy_vport:
2558 	mana_destroy_vport(apc);
2559 	return err;
2560 }
2561 
2562 static int
2563 mana_up(struct mana_port_context *apc)
2564 {
2565 	int err;
2566 
2567 	mana_dbg(NULL, "mana_up called\n");
2568 
2569 	err = mana_alloc_queues(apc->ndev);
2570 	if (err) {
2571 		mana_err(NULL, "Faile alloc mana queues: %d\n", err);
2572 		return err;
2573 	}
2574 
2575 	/* Add queue specific sysctl */
2576 	mana_sysctl_add_queues(apc);
2577 
2578 	apc->port_is_up = true;
2579 
2580 	/* Ensure port state updated before txq state */
2581 	wmb();
2582 
2583 	if_link_state_change(apc->ndev, LINK_STATE_UP);
2584 	if_setdrvflagbits(apc->ndev, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
2585 
2586 	return 0;
2587 }
2588 
2589 
2590 static void
2591 mana_init(void *arg)
2592 {
2593 	struct mana_port_context *apc = (struct mana_port_context *)arg;
2594 
2595 	MANA_APC_LOCK_LOCK(apc);
2596 	if (!apc->port_is_up) {
2597 		mana_up(apc);
2598 	}
2599 	MANA_APC_LOCK_UNLOCK(apc);
2600 }
2601 
2602 static int
2603 mana_dealloc_queues(if_t ndev)
2604 {
2605 	struct mana_port_context *apc = if_getsoftc(ndev);
2606 	struct mana_txq *txq;
2607 	int i, err;
2608 
2609 	if (apc->port_is_up)
2610 		return EINVAL;
2611 
2612 	/* No packet can be transmitted now since apc->port_is_up is false.
2613 	 * There is still a tiny chance that mana_poll_tx_cq() can re-enable
2614 	 * a txq because it may not timely see apc->port_is_up being cleared
2615 	 * to false, but it doesn't matter since mana_start_xmit() drops any
2616 	 * new packets due to apc->port_is_up being false.
2617 	 *
2618 	 * Drain all the in-flight TX packets
2619 	 */
2620 	for (i = 0; i < apc->num_queues; i++) {
2621 		txq = &apc->tx_qp[i].txq;
2622 
2623 		struct mana_cq *tx_cq = &apc->tx_qp[i].tx_cq;
2624 		struct mana_cq *rx_cq = &(apc->rxqs[i]->rx_cq);
2625 
2626 		tx_cq->do_not_ring_db = true;
2627 		rx_cq->do_not_ring_db = true;
2628 
2629 		/* Schedule a cleanup task */
2630 		taskqueue_enqueue(tx_cq->cleanup_tq, &tx_cq->cleanup_task);
2631 
2632 		while (atomic_read(&txq->pending_sends) > 0)
2633 			usleep_range(1000, 2000);
2634 	}
2635 
2636 	/* We're 100% sure the queues can no longer be woken up, because
2637 	 * we're sure now mana_poll_tx_cq() can't be running.
2638 	 */
2639 
2640 	apc->rss_state = TRI_STATE_FALSE;
2641 	err = mana_config_rss(apc, TRI_STATE_FALSE, false, false);
2642 	if (err) {
2643 		if_printf(ndev, "Failed to disable vPort: %d\n", err);
2644 		return err;
2645 	}
2646 
2647 	mana_destroy_vport(apc);
2648 
2649 	return 0;
2650 }
2651 
2652 static int
2653 mana_down(struct mana_port_context *apc)
2654 {
2655 	int err = 0;
2656 
2657 	apc->port_st_save = apc->port_is_up;
2658 	apc->port_is_up = false;
2659 
2660 	/* Ensure port state updated before txq state */
2661 	wmb();
2662 
2663 	if (apc->port_st_save) {
2664 		if_setdrvflagbits(apc->ndev, IFF_DRV_OACTIVE,
2665 		    IFF_DRV_RUNNING);
2666 		if_link_state_change(apc->ndev, LINK_STATE_DOWN);
2667 
2668 		mana_sysctl_free_queues(apc);
2669 
2670 		err = mana_dealloc_queues(apc->ndev);
2671 		if (err) {
2672 			if_printf(apc->ndev,
2673 			    "Failed to bring down mana interface: %d\n", err);
2674 		}
2675 	}
2676 
2677 	return err;
2678 }
2679 
2680 int
2681 mana_detach(if_t ndev)
2682 {
2683 	struct mana_port_context *apc = if_getsoftc(ndev);
2684 	int err;
2685 
2686 	ether_ifdetach(ndev);
2687 
2688 	if (!apc)
2689 		return 0;
2690 
2691 	MANA_APC_LOCK_LOCK(apc);
2692 	err = mana_down(apc);
2693 	MANA_APC_LOCK_UNLOCK(apc);
2694 
2695 	mana_cleanup_port_context(apc);
2696 
2697 	MANA_APC_LOCK_DESTROY(apc);
2698 
2699 	free(apc, M_DEVBUF);
2700 
2701 	return err;
2702 }
2703 
2704 static int
2705 mana_probe_port(struct mana_context *ac, int port_idx,
2706     if_t *ndev_storage)
2707 {
2708 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
2709 	struct mana_port_context *apc;
2710 	if_t ndev;
2711 	int err;
2712 
2713 	ndev = if_alloc_dev(IFT_ETHER, gc->dev);
2714 	if (!ndev) {
2715 		mana_err(NULL, "Failed to allocate ifnet struct\n");
2716 		return ENOMEM;
2717 	}
2718 
2719 	*ndev_storage = ndev;
2720 
2721 	apc = malloc(sizeof(*apc), M_DEVBUF, M_WAITOK | M_ZERO);
2722 	if (!apc) {
2723 		mana_err(NULL, "Failed to allocate port context\n");
2724 		err = ENOMEM;
2725 		goto free_net;
2726 	}
2727 
2728 	apc->ac = ac;
2729 	apc->ndev = ndev;
2730 	apc->max_queues = gc->max_num_queues;
2731 	apc->num_queues = min_t(unsigned int,
2732 	    gc->max_num_queues, MANA_MAX_NUM_QUEUES);
2733 	apc->port_handle = INVALID_MANA_HANDLE;
2734 	apc->port_idx = port_idx;
2735 	apc->frame_size = DEFAULT_FRAME_SIZE;
2736 	apc->last_tx_cq_bind_cpu = -1;
2737 	apc->last_rx_cq_bind_cpu = -1;
2738 	apc->vport_use_count = 0;
2739 
2740 	MANA_APC_LOCK_INIT(apc);
2741 
2742 	if_initname(ndev, device_get_name(gc->dev), port_idx);
2743 	if_setdev(ndev,gc->dev);
2744 	if_setsoftc(ndev, apc);
2745 
2746 	if_setflags(ndev, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2747 	if_setinitfn(ndev, mana_init);
2748 	if_settransmitfn(ndev, mana_start_xmit);
2749 	if_setqflushfn(ndev, mana_qflush);
2750 	if_setioctlfn(ndev, mana_ioctl);
2751 	if_setgetcounterfn(ndev, mana_get_counter);
2752 
2753 	if_setmtu(ndev, ETHERMTU);
2754 	if_setbaudrate(ndev, IF_Gbps(100));
2755 
2756 	mana_rss_key_fill(apc->hashkey, MANA_HASH_KEY_SIZE);
2757 
2758 	err = mana_init_port(ndev);
2759 	if (err)
2760 		goto reset_apc;
2761 
2762 	if_setcapabilitiesbit(ndev,
2763 	    IFCAP_TXCSUM | IFCAP_TXCSUM_IPV6 |
2764 	    IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6 |
2765 	    IFCAP_TSO4 | IFCAP_TSO6 |
2766 	    IFCAP_LRO | IFCAP_LINKSTATE, 0);
2767 
2768 	/* Enable all available capabilities by default. */
2769 	if_setcapenable(ndev, if_getcapabilities(ndev));
2770 
2771 	/* TSO parameters */
2772 	if_sethwtsomax(ndev, MAX_MBUF_FRAGS * MANA_TSO_MAXSEG_SZ -
2773 	    (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN));
2774 	if_sethwtsomaxsegcount(ndev, MAX_MBUF_FRAGS);
2775 	if_sethwtsomaxsegsize(ndev, PAGE_SIZE);
2776 
2777 	ifmedia_init(&apc->media, IFM_IMASK,
2778 	    mana_ifmedia_change, mana_ifmedia_status);
2779 	ifmedia_add(&apc->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2780 	ifmedia_set(&apc->media, IFM_ETHER | IFM_AUTO);
2781 
2782 	ether_ifattach(ndev, apc->mac_addr);
2783 
2784 	/* Initialize statistics */
2785 	mana_alloc_counters((counter_u64_t *)&apc->port_stats,
2786 	    sizeof(struct mana_port_stats));
2787 	mana_sysctl_add_port(apc);
2788 
2789 	/* Tell the stack that the interface is not active */
2790 	if_setdrvflagbits(ndev, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2791 
2792 	return 0;
2793 
2794 reset_apc:
2795 	free(apc, M_DEVBUF);
2796 free_net:
2797 	*ndev_storage = NULL;
2798 	if_printf(ndev, "Failed to probe vPort %d: %d\n", port_idx, err);
2799 	if_free(ndev);
2800 	return err;
2801 }
2802 
2803 int mana_probe(struct gdma_dev *gd)
2804 {
2805 	struct gdma_context *gc = gd->gdma_context;
2806 	device_t dev = gc->dev;
2807 	struct mana_context *ac;
2808 	int err;
2809 	int i;
2810 
2811 	device_printf(dev, "%s protocol version: %d.%d.%d\n", DEVICE_NAME,
2812 		 MANA_MAJOR_VERSION, MANA_MINOR_VERSION, MANA_MICRO_VERSION);
2813 
2814 	err = mana_gd_register_device(gd);
2815 	if (err)
2816 		return err;
2817 
2818 	ac = malloc(sizeof(*ac), M_DEVBUF, M_WAITOK | M_ZERO);
2819 	if (!ac)
2820 		return ENOMEM;
2821 
2822 	ac->gdma_dev = gd;
2823 	ac->num_ports = 1;
2824 	gd->driver_data = ac;
2825 
2826 	err = mana_create_eq(ac);
2827 	if (err)
2828 		goto out;
2829 
2830 	err = mana_query_device_cfg(ac, MANA_MAJOR_VERSION, MANA_MINOR_VERSION,
2831 	    MANA_MICRO_VERSION, &ac->num_ports);
2832 	if (err)
2833 		goto out;
2834 
2835 	if (ac->num_ports > MAX_PORTS_IN_MANA_DEV)
2836 		ac->num_ports = MAX_PORTS_IN_MANA_DEV;
2837 
2838 	for (i = 0; i < ac->num_ports; i++) {
2839 		err = mana_probe_port(ac, i, &ac->ports[i]);
2840 		if (err) {
2841 			device_printf(dev,
2842 			    "Failed to probe mana port %d\n", i);
2843 			break;
2844 		}
2845 	}
2846 
2847 out:
2848 	if (err)
2849 		mana_remove(gd);
2850 
2851 	return err;
2852 }
2853 
2854 void
2855 mana_remove(struct gdma_dev *gd)
2856 {
2857 	struct gdma_context *gc = gd->gdma_context;
2858 	struct mana_context *ac = gd->driver_data;
2859 	device_t dev = gc->dev;
2860 	if_t ndev;
2861 	int i;
2862 
2863 	for (i = 0; i < ac->num_ports; i++) {
2864 		ndev = ac->ports[i];
2865 		if (!ndev) {
2866 			if (i == 0)
2867 				device_printf(dev, "No net device to remove\n");
2868 			goto out;
2869 		}
2870 
2871 		mana_detach(ndev);
2872 
2873 		if_free(ndev);
2874 	}
2875 
2876 	mana_destroy_eq(ac);
2877 
2878 out:
2879 	mana_gd_deregister_device(gd);
2880 	gd->driver_data = NULL;
2881 	gd->gdma_context = NULL;
2882 	free(ac, M_DEVBUF);
2883 }
2884