xref: /freebsd/sys/dev/mana/mana_en.c (revision 81b22a98)
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(struct ifnet *ifp __unused)
90 {
91 	return EOPNOTSUPP;
92 }
93 
94 static void
95 mana_ifmedia_status(struct ifnet *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(struct ifnet *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(struct ifnet *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(struct ifnet *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 (ifp->if_mtu == 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 (ifp->if_flags & IFF_UP) {
203 			if ((ifp->if_drv_flags & 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 (ifp->if_drv_flags & 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 	struct ifnet *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 	struct ifnet *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(struct ifnet *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 static int
984 mana_cfg_vport(struct mana_port_context *apc, uint32_t protection_dom_id,
985     uint32_t doorbell_pg_id)
986 {
987 	struct mana_config_vport_resp resp = {};
988 	struct mana_config_vport_req req = {};
989 	int err;
990 
991 	mana_gd_init_req_hdr(&req.hdr, MANA_CONFIG_VPORT_TX,
992 	    sizeof(req), sizeof(resp));
993 	req.vport = apc->port_handle;
994 	req.pdid = protection_dom_id;
995 	req.doorbell_pageid = doorbell_pg_id;
996 
997 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
998 	    sizeof(resp));
999 	if (err) {
1000 		if_printf(apc->ndev, "Failed to configure vPort: %d\n", err);
1001 		goto out;
1002 	}
1003 
1004 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_TX,
1005 	    sizeof(resp));
1006 	if (err || resp.hdr.status) {
1007 		if_printf(apc->ndev, "Failed to configure vPort: %d, 0x%x\n",
1008 		    err, resp.hdr.status);
1009 		if (!err)
1010 			err = EPROTO;
1011 
1012 		goto out;
1013 	}
1014 
1015 	apc->tx_shortform_allowed = resp.short_form_allowed;
1016 	apc->tx_vp_offset = resp.tx_vport_offset;
1017 out:
1018 	return err;
1019 }
1020 
1021 static int
1022 mana_cfg_vport_steering(struct mana_port_context *apc,
1023     enum TRI_STATE rx,
1024     bool update_default_rxobj, bool update_key,
1025     bool update_tab)
1026 {
1027 	uint16_t num_entries = MANA_INDIRECT_TABLE_SIZE;
1028 	struct mana_cfg_rx_steer_req *req = NULL;
1029 	struct mana_cfg_rx_steer_resp resp = {};
1030 	struct ifnet *ndev = apc->ndev;
1031 	mana_handle_t *req_indir_tab;
1032 	uint32_t req_buf_size;
1033 	int err;
1034 
1035 	req_buf_size = sizeof(*req) + sizeof(mana_handle_t) * num_entries;
1036 	req = malloc(req_buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
1037 	if (!req)
1038 		return ENOMEM;
1039 
1040 	mana_gd_init_req_hdr(&req->hdr, MANA_CONFIG_VPORT_RX, req_buf_size,
1041 	    sizeof(resp));
1042 
1043 	req->vport = apc->port_handle;
1044 	req->num_indir_entries = num_entries;
1045 	req->indir_tab_offset = sizeof(*req);
1046 	req->rx_enable = rx;
1047 	req->rss_enable = apc->rss_state;
1048 	req->update_default_rxobj = update_default_rxobj;
1049 	req->update_hashkey = update_key;
1050 	req->update_indir_tab = update_tab;
1051 	req->default_rxobj = apc->default_rxobj;
1052 
1053 	if (update_key)
1054 		memcpy(&req->hashkey, apc->hashkey, MANA_HASH_KEY_SIZE);
1055 
1056 	if (update_tab) {
1057 		req_indir_tab = (mana_handle_t *)(req + 1);
1058 		memcpy(req_indir_tab, apc->rxobj_table,
1059 		       req->num_indir_entries * sizeof(mana_handle_t));
1060 	}
1061 
1062 	err = mana_send_request(apc->ac, req, req_buf_size, &resp,
1063 	    sizeof(resp));
1064 	if (err) {
1065 		if_printf(ndev, "Failed to configure vPort RX: %d\n", err);
1066 		goto out;
1067 	}
1068 
1069 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_RX,
1070 	    sizeof(resp));
1071 	if (err) {
1072 		if_printf(ndev, "vPort RX configuration failed: %d\n", err);
1073 		goto out;
1074 	}
1075 
1076 	if (resp.hdr.status) {
1077 		if_printf(ndev, "vPort RX configuration failed: 0x%x\n",
1078 		    resp.hdr.status);
1079 		err = EPROTO;
1080 	}
1081 out:
1082 	free(req, M_DEVBUF);
1083 	return err;
1084 }
1085 
1086 static int
1087 mana_create_wq_obj(struct mana_port_context *apc,
1088     mana_handle_t vport,
1089     uint32_t wq_type, struct mana_obj_spec *wq_spec,
1090     struct mana_obj_spec *cq_spec,
1091     mana_handle_t *wq_obj)
1092 {
1093 	struct mana_create_wqobj_resp resp = {};
1094 	struct mana_create_wqobj_req req = {};
1095 	struct ifnet *ndev = apc->ndev;
1096 	int err;
1097 
1098 	mana_gd_init_req_hdr(&req.hdr, MANA_CREATE_WQ_OBJ,
1099 	    sizeof(req), sizeof(resp));
1100 	req.vport = vport;
1101 	req.wq_type = wq_type;
1102 	req.wq_gdma_region = wq_spec->gdma_region;
1103 	req.cq_gdma_region = cq_spec->gdma_region;
1104 	req.wq_size = wq_spec->queue_size;
1105 	req.cq_size = cq_spec->queue_size;
1106 	req.cq_moderation_ctx_id = cq_spec->modr_ctx_id;
1107 	req.cq_parent_qid = cq_spec->attached_eq;
1108 
1109 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1110 	    sizeof(resp));
1111 	if (err) {
1112 		if_printf(ndev, "Failed to create WQ object: %d\n", err);
1113 		goto out;
1114 	}
1115 
1116 	err = mana_verify_resp_hdr(&resp.hdr, MANA_CREATE_WQ_OBJ,
1117 	    sizeof(resp));
1118 	if (err || resp.hdr.status) {
1119 		if_printf(ndev, "Failed to create WQ object: %d, 0x%x\n", err,
1120 		    resp.hdr.status);
1121 		if (!err)
1122 			err = EPROTO;
1123 		goto out;
1124 	}
1125 
1126 	if (resp.wq_obj == INVALID_MANA_HANDLE) {
1127 		if_printf(ndev, "Got an invalid WQ object handle\n");
1128 		err = EPROTO;
1129 		goto out;
1130 	}
1131 
1132 	*wq_obj = resp.wq_obj;
1133 	wq_spec->queue_index = resp.wq_id;
1134 	cq_spec->queue_index = resp.cq_id;
1135 
1136 	return 0;
1137 out:
1138 	return err;
1139 }
1140 
1141 static void
1142 mana_destroy_wq_obj(struct mana_port_context *apc, uint32_t wq_type,
1143     mana_handle_t wq_obj)
1144 {
1145 	struct mana_destroy_wqobj_resp resp = {};
1146 	struct mana_destroy_wqobj_req req = {};
1147 	struct ifnet *ndev = apc->ndev;
1148 	int err;
1149 
1150 	mana_gd_init_req_hdr(&req.hdr, MANA_DESTROY_WQ_OBJ,
1151 	    sizeof(req), sizeof(resp));
1152 	req.wq_type = wq_type;
1153 	req.wq_obj_handle = wq_obj;
1154 
1155 	err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
1156 	    sizeof(resp));
1157 	if (err) {
1158 		if_printf(ndev, "Failed to destroy WQ object: %d\n", err);
1159 		return;
1160 	}
1161 
1162 	err = mana_verify_resp_hdr(&resp.hdr, MANA_DESTROY_WQ_OBJ,
1163 	    sizeof(resp));
1164 	if (err || resp.hdr.status)
1165 		if_printf(ndev, "Failed to destroy WQ object: %d, 0x%x\n",
1166 		    err, resp.hdr.status);
1167 }
1168 
1169 static void
1170 mana_destroy_eq(struct mana_context *ac)
1171 {
1172 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
1173 	struct gdma_queue *eq;
1174 	int i;
1175 
1176 	if (!ac->eqs)
1177 		return;
1178 
1179 	for (i = 0; i < gc->max_num_queues; i++) {
1180 		eq = ac->eqs[i].eq;
1181 		if (!eq)
1182 			continue;
1183 
1184 		mana_gd_destroy_queue(gc, eq);
1185 	}
1186 
1187 	free(ac->eqs, M_DEVBUF);
1188 	ac->eqs = NULL;
1189 }
1190 
1191 static int
1192 mana_create_eq(struct mana_context *ac)
1193 {
1194 	struct gdma_dev *gd = ac->gdma_dev;
1195 	struct gdma_context *gc = gd->gdma_context;
1196 	struct gdma_queue_spec spec = {};
1197 	int err;
1198 	int i;
1199 
1200 	ac->eqs = mallocarray(gc->max_num_queues, sizeof(struct mana_eq),
1201 	    M_DEVBUF, M_WAITOK | M_ZERO);
1202 	if (!ac->eqs)
1203 		return ENOMEM;
1204 
1205 	spec.type = GDMA_EQ;
1206 	spec.monitor_avl_buf = false;
1207 	spec.queue_size = EQ_SIZE;
1208 	spec.eq.callback = NULL;
1209 	spec.eq.context = ac->eqs;
1210 	spec.eq.log2_throttle_limit = LOG2_EQ_THROTTLE;
1211 
1212 	for (i = 0; i < gc->max_num_queues; i++) {
1213 		err = mana_gd_create_mana_eq(gd, &spec, &ac->eqs[i].eq);
1214 		if (err)
1215 			goto out;
1216 	}
1217 
1218 	return 0;
1219 out:
1220 	mana_destroy_eq(ac);
1221 	return err;
1222 }
1223 
1224 static int
1225 mana_move_wq_tail(struct gdma_queue *wq, uint32_t num_units)
1226 {
1227 	uint32_t used_space_old;
1228 	uint32_t used_space_new;
1229 
1230 	used_space_old = wq->head - wq->tail;
1231 	used_space_new = wq->head - (wq->tail + num_units);
1232 
1233 	if (used_space_new > used_space_old) {
1234 		mana_err(NULL,
1235 		    "WARNING: new used space %u greater than old one %u\n",
1236 		    used_space_new, used_space_old);
1237 		return ERANGE;
1238 	}
1239 
1240 	wq->tail += num_units;
1241 	return 0;
1242 }
1243 
1244 static void
1245 mana_poll_tx_cq(struct mana_cq *cq)
1246 {
1247 	struct gdma_comp *completions = cq->gdma_comp_buf;
1248 	struct gdma_posted_wqe_info *wqe_info;
1249 	struct mana_send_buf_info *tx_info;
1250 	unsigned int pkt_transmitted = 0;
1251 	unsigned int wqe_unit_cnt = 0;
1252 	struct mana_txq *txq = cq->txq;
1253 	struct mana_port_context *apc;
1254 	uint16_t next_to_complete;
1255 	struct ifnet *ndev;
1256 	int comp_read;
1257 	int txq_idx = txq->idx;;
1258 	int i;
1259 	int sa_drop = 0;
1260 
1261 	struct gdma_queue *gdma_wq;
1262 	unsigned int avail_space;
1263 	bool txq_full = false;
1264 
1265 	ndev = txq->ndev;
1266 	apc = if_getsoftc(ndev);
1267 
1268 	comp_read = mana_gd_poll_cq(cq->gdma_cq, completions,
1269 	    CQE_POLLING_BUFFER);
1270 
1271 	if (comp_read < 1)
1272 		return;
1273 
1274 	next_to_complete = txq->next_to_complete;
1275 
1276 	for (i = 0; i < comp_read; i++) {
1277 		struct mana_tx_comp_oob *cqe_oob;
1278 
1279 		if (!completions[i].is_sq) {
1280 			mana_err(NULL, "WARNING: Not for SQ\n");
1281 			return;
1282 		}
1283 
1284 		cqe_oob = (struct mana_tx_comp_oob *)completions[i].cqe_data;
1285 		if (cqe_oob->cqe_hdr.client_type !=
1286 				 MANA_CQE_COMPLETION) {
1287 			mana_err(NULL,
1288 			    "WARNING: Invalid CQE client type %u\n",
1289 			    cqe_oob->cqe_hdr.client_type);
1290 			return;
1291 		}
1292 
1293 		switch (cqe_oob->cqe_hdr.cqe_type) {
1294 		case CQE_TX_OKAY:
1295 			break;
1296 
1297 		case CQE_TX_SA_DROP:
1298 		case CQE_TX_MTU_DROP:
1299 		case CQE_TX_INVALID_OOB:
1300 		case CQE_TX_INVALID_ETH_TYPE:
1301 		case CQE_TX_HDR_PROCESSING_ERROR:
1302 		case CQE_TX_VF_DISABLED:
1303 		case CQE_TX_VPORT_IDX_OUT_OF_RANGE:
1304 		case CQE_TX_VPORT_DISABLED:
1305 		case CQE_TX_VLAN_TAGGING_VIOLATION:
1306 			sa_drop ++;
1307 			mana_err(NULL,
1308 			    "TX: txq %d CQE error %d, ntc = %d, "
1309 			    "pending sends = %d: err ignored.\n",
1310 			    txq_idx, cqe_oob->cqe_hdr.cqe_type,
1311 			    next_to_complete, txq->pending_sends);
1312 			break;
1313 
1314 		default:
1315 			/* If the CQE type is unexpected, log an error,
1316 			 * and go through the error path.
1317 			 */
1318 			mana_err(NULL,
1319 			    "ERROR: TX: Unexpected CQE type %d: HW BUG?\n",
1320 			    cqe_oob->cqe_hdr.cqe_type);
1321 			return;
1322 		}
1323 		if (txq->gdma_txq_id != completions[i].wq_num) {
1324 			mana_dbg(NULL,
1325 			    "txq gdma id not match completion wq num: "
1326 			    "%d != %d\n",
1327 			    txq->gdma_txq_id, completions[i].wq_num);
1328 			break;
1329 		}
1330 
1331 		tx_info = &txq->tx_buf_info[next_to_complete];
1332 		if (!tx_info->mbuf) {
1333 			mana_err(NULL,
1334 			    "WARNING: txq %d Empty mbuf on tx_info: %u, "
1335 			    "ntu = %u, pending_sends = %d, "
1336 			    "transmitted = %d, sa_drop = %d, i = %d, comp_read = %d\n",
1337 			    txq_idx, next_to_complete, txq->next_to_use,
1338 			    txq->pending_sends, pkt_transmitted, sa_drop,
1339 			    i, comp_read);
1340 			break;
1341 		}
1342 
1343 		wqe_info = &tx_info->wqe_inf;
1344 		wqe_unit_cnt += wqe_info->wqe_size_in_bu;
1345 
1346 		mana_tx_unmap_mbuf(apc, tx_info);
1347 		mb();
1348 
1349 		next_to_complete =
1350 		    (next_to_complete + 1) % MAX_SEND_BUFFERS_PER_QUEUE;
1351 
1352 		pkt_transmitted++;
1353 	}
1354 
1355 	txq->next_to_complete = next_to_complete;
1356 
1357 	if (wqe_unit_cnt == 0) {
1358 		mana_err(NULL,
1359 		    "WARNING: TX ring not proceeding!\n");
1360 		return;
1361 	}
1362 
1363 	mana_move_wq_tail(txq->gdma_sq, wqe_unit_cnt);
1364 
1365 	/* Ensure tail updated before checking q stop */
1366 	wmb();
1367 
1368 	gdma_wq = txq->gdma_sq;
1369 	avail_space = mana_gd_wq_avail_space(gdma_wq);
1370 
1371 
1372 	if ((if_getdrvflags(ndev) & MANA_TXQ_FULL) == MANA_TXQ_FULL) {
1373 		txq_full = true;
1374 	}
1375 
1376 	/* Ensure checking txq_full before apc->port_is_up. */
1377 	rmb();
1378 
1379 	if (txq_full && apc->port_is_up && avail_space >= MAX_TX_WQE_SIZE) {
1380 		/* Grab the txq lock and re-test */
1381 		mtx_lock(&txq->txq_mtx);
1382 		avail_space = mana_gd_wq_avail_space(gdma_wq);
1383 
1384 		if ((if_getdrvflags(ndev) & MANA_TXQ_FULL) == MANA_TXQ_FULL &&
1385 		    apc->port_is_up && avail_space >= MAX_TX_WQE_SIZE) {
1386 			/* Clear the Q full flag */
1387 			if_setdrvflagbits(apc->ndev, IFF_DRV_RUNNING,
1388 			    IFF_DRV_OACTIVE);
1389 			counter_u64_add(txq->stats.wakeup, 1);
1390 			if (txq->alt_txq_idx != txq->idx) {
1391 				uint64_t stops = counter_u64_fetch(txq->stats.stop);
1392 				uint64_t wakeups = counter_u64_fetch(txq->stats.wakeup);
1393 				/* Reset alt_txq_idx back if it is not overloaded */
1394 				if (stops < wakeups) {
1395 					txq->alt_txq_idx = txq->idx;
1396 					counter_u64_add(txq->stats.alt_reset, 1);
1397 				}
1398 			}
1399 			rmb();
1400 			/* Schedule a tx enqueue task */
1401 			taskqueue_enqueue(txq->enqueue_tq, &txq->enqueue_task);
1402 		}
1403 		mtx_unlock(&txq->txq_mtx);
1404 	}
1405 
1406 	if (atomic_sub_return(pkt_transmitted, &txq->pending_sends) < 0)
1407 		mana_err(NULL,
1408 		    "WARNING: TX %d pending_sends error: %d\n",
1409 		    txq->idx, txq->pending_sends);
1410 
1411 	cq->work_done = pkt_transmitted;
1412 }
1413 
1414 static void
1415 mana_post_pkt_rxq(struct mana_rxq *rxq)
1416 {
1417 	struct mana_recv_buf_oob *recv_buf_oob;
1418 	uint32_t curr_index;
1419 	int err;
1420 
1421 	curr_index = rxq->buf_index++;
1422 	if (rxq->buf_index == rxq->num_rx_buf)
1423 		rxq->buf_index = 0;
1424 
1425 	recv_buf_oob = &rxq->rx_oobs[curr_index];
1426 
1427 	err = mana_gd_post_and_ring(rxq->gdma_rq, &recv_buf_oob->wqe_req,
1428 	    &recv_buf_oob->wqe_inf);
1429 	if (err) {
1430 		mana_err(NULL, "WARNING: rxq %u post pkt err %d\n",
1431 		    rxq->rxq_idx, err);
1432 		return;
1433 	}
1434 
1435 	if (recv_buf_oob->wqe_inf.wqe_size_in_bu != 1) {
1436 		mana_err(NULL, "WARNING: rxq %u wqe_size_in_bu %u\n",
1437 		    rxq->rxq_idx, recv_buf_oob->wqe_inf.wqe_size_in_bu);
1438 	}
1439 }
1440 
1441 static void
1442 mana_rx_mbuf(struct mbuf *mbuf, struct mana_rxcomp_oob *cqe,
1443     struct mana_rxq *rxq)
1444 {
1445 	struct mana_stats *rx_stats = &rxq->stats;
1446 	struct ifnet *ndev = rxq->ndev;
1447 	uint32_t pkt_len = cqe->ppi[0].pkt_len;
1448 	uint16_t rxq_idx = rxq->rxq_idx;
1449 	struct mana_port_context *apc;
1450 	bool do_lro = false;
1451 	bool do_if_input;
1452 
1453 	apc = if_getsoftc(ndev);
1454 	rxq->rx_cq.work_done++;
1455 
1456 	if (!mbuf) {
1457 		return;
1458 	}
1459 
1460 	mbuf->m_flags |= M_PKTHDR;
1461 	mbuf->m_pkthdr.len = pkt_len;
1462 	mbuf->m_len = pkt_len;
1463 	mbuf->m_pkthdr.rcvif = ndev;
1464 
1465 	if ((ndev->if_capenable & IFCAP_RXCSUM ||
1466 	    ndev->if_capenable & IFCAP_RXCSUM_IPV6) &&
1467 	    (cqe->rx_iphdr_csum_succeed)) {
1468 		mbuf->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
1469 		mbuf->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1470 		if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed) {
1471 			mbuf->m_pkthdr.csum_flags |=
1472 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1473 			mbuf->m_pkthdr.csum_data = 0xffff;
1474 
1475 			if (cqe->rx_tcp_csum_succeed)
1476 				do_lro = true;
1477 		}
1478 	}
1479 
1480 	if (cqe->rx_hashtype != 0) {
1481 		mbuf->m_pkthdr.flowid = cqe->ppi[0].pkt_hash;
1482 
1483 		uint16_t hashtype = cqe->rx_hashtype;
1484 		if (hashtype & NDIS_HASH_IPV4_MASK) {
1485 			hashtype &= NDIS_HASH_IPV4_MASK;
1486 			switch (hashtype) {
1487 			case NDIS_HASH_TCP_IPV4:
1488 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV4);
1489 				break;
1490 			case NDIS_HASH_UDP_IPV4:
1491 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV4);
1492 				break;
1493 			default:
1494 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV4);
1495 			}
1496 		} else if (hashtype & NDIS_HASH_IPV6_MASK) {
1497 			hashtype &= NDIS_HASH_IPV6_MASK;
1498 			switch (hashtype) {
1499 			case NDIS_HASH_TCP_IPV6:
1500 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV6);
1501 				break;
1502 			case NDIS_HASH_TCP_IPV6_EX:
1503 				M_HASHTYPE_SET(mbuf,
1504 				    M_HASHTYPE_RSS_TCP_IPV6_EX);
1505 				break;
1506 			case NDIS_HASH_UDP_IPV6:
1507 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV6);
1508 				break;
1509 			case NDIS_HASH_UDP_IPV6_EX:
1510 				M_HASHTYPE_SET(mbuf,
1511 				    M_HASHTYPE_RSS_UDP_IPV6_EX);
1512 				break;
1513 			default:
1514 				M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV6);
1515 			}
1516 		} else {
1517 			M_HASHTYPE_SET(mbuf, M_HASHTYPE_OPAQUE_HASH);
1518 		}
1519 	} else {
1520 		mbuf->m_pkthdr.flowid = rxq_idx;
1521 		M_HASHTYPE_SET(mbuf, M_HASHTYPE_NONE);
1522 	}
1523 
1524 	do_if_input = true;
1525 	if ((ndev->if_capenable & IFCAP_LRO) && do_lro) {
1526 		if (rxq->lro.lro_cnt != 0 &&
1527 		    tcp_lro_rx(&rxq->lro, mbuf, 0) == 0)
1528 			do_if_input = false;
1529 	}
1530 	if (do_if_input) {
1531 		ndev->if_input(ndev, mbuf);
1532 	}
1533 
1534 	counter_enter();
1535 	counter_u64_add_protected(rx_stats->packets, 1);
1536 	counter_u64_add_protected(apc->port_stats.rx_packets, 1);
1537 	counter_u64_add_protected(rx_stats->bytes, pkt_len);
1538 	counter_u64_add_protected(apc->port_stats.rx_bytes, pkt_len);
1539 	counter_exit();
1540 }
1541 
1542 static void
1543 mana_process_rx_cqe(struct mana_rxq *rxq, struct mana_cq *cq,
1544     struct gdma_comp *cqe)
1545 {
1546 	struct mana_rxcomp_oob *oob = (struct mana_rxcomp_oob *)cqe->cqe_data;
1547 	struct mana_recv_buf_oob *rxbuf_oob;
1548 	struct ifnet *ndev = rxq->ndev;
1549 	struct mana_port_context *apc;
1550 	struct mbuf *old_mbuf;
1551 	uint32_t curr, pktlen;
1552 	int err;
1553 
1554 	switch (oob->cqe_hdr.cqe_type) {
1555 	case CQE_RX_OKAY:
1556 		break;
1557 
1558 	case CQE_RX_TRUNCATED:
1559 		if_printf(ndev, "Dropped a truncated packet\n");
1560 		return;
1561 
1562 	case CQE_RX_COALESCED_4:
1563 		if_printf(ndev, "RX coalescing is unsupported\n");
1564 		return;
1565 
1566 	case CQE_RX_OBJECT_FENCE:
1567 		if_printf(ndev, "RX Fencing is unsupported\n");
1568 		return;
1569 
1570 	default:
1571 		if_printf(ndev, "Unknown RX CQE type = %d\n",
1572 		    oob->cqe_hdr.cqe_type);
1573 		return;
1574 	}
1575 
1576 	if (oob->cqe_hdr.cqe_type != CQE_RX_OKAY)
1577 		return;
1578 
1579 	pktlen = oob->ppi[0].pkt_len;
1580 
1581 	if (pktlen == 0) {
1582 		/* data packets should never have packetlength of zero */
1583 #if defined(__amd64__)
1584 		if_printf(ndev, "RX pkt len=0, rq=%u, cq=%u, rxobj=0x%lx\n",
1585 		    rxq->gdma_id, cq->gdma_id, rxq->rxobj);
1586 #else
1587 		if_printf(ndev, "RX pkt len=0, rq=%u, cq=%u, rxobj=0x%llx\n",
1588 		    rxq->gdma_id, cq->gdma_id, rxq->rxobj);
1589 #endif
1590 		return;
1591 	}
1592 
1593 	curr = rxq->buf_index;
1594 	rxbuf_oob = &rxq->rx_oobs[curr];
1595 	if (rxbuf_oob->wqe_inf.wqe_size_in_bu != 1) {
1596 		mana_err(NULL, "WARNING: Rx Incorrect complete "
1597 		    "WQE size %u\n",
1598 		    rxbuf_oob->wqe_inf.wqe_size_in_bu);
1599 	}
1600 
1601 	apc = if_getsoftc(ndev);
1602 
1603 	old_mbuf = rxbuf_oob->mbuf;
1604 
1605 	/* Unload DMA map for the old mbuf */
1606 	mana_unload_rx_mbuf(apc, rxq, rxbuf_oob, false);
1607 
1608 	/* Load a new mbuf to replace the old one */
1609 	err = mana_load_rx_mbuf(apc, rxq, rxbuf_oob, true);
1610 	if (err) {
1611 		mana_dbg(NULL,
1612 		    "failed to load rx mbuf, err = %d, packet dropped.\n",
1613 		    err);
1614 		counter_u64_add(rxq->stats.mbuf_alloc_fail, 1);
1615 		/*
1616 		 * Failed to load new mbuf, rxbuf_oob->mbuf is still
1617 		 * pointing to the old one. Drop the packet.
1618 		 */
1619 		 old_mbuf = NULL;
1620 		 /* Reload the existing mbuf */
1621 		 mana_load_rx_mbuf(apc, rxq, rxbuf_oob, false);
1622 	}
1623 
1624 	mana_rx_mbuf(old_mbuf, oob, rxq);
1625 
1626 	mana_move_wq_tail(rxq->gdma_rq, rxbuf_oob->wqe_inf.wqe_size_in_bu);
1627 
1628 	mana_post_pkt_rxq(rxq);
1629 }
1630 
1631 static void
1632 mana_poll_rx_cq(struct mana_cq *cq)
1633 {
1634 	struct gdma_comp *comp = cq->gdma_comp_buf;
1635 	int comp_read, i;
1636 
1637 	comp_read = mana_gd_poll_cq(cq->gdma_cq, comp, CQE_POLLING_BUFFER);
1638 	KASSERT(comp_read <= CQE_POLLING_BUFFER,
1639 	    ("comp_read %d great than buf size %d",
1640 	    comp_read, CQE_POLLING_BUFFER));
1641 
1642 	for (i = 0; i < comp_read; i++) {
1643 		if (comp[i].is_sq == true) {
1644 			mana_err(NULL,
1645 			    "WARNING: CQE not for receive queue\n");
1646 			return;
1647 		}
1648 
1649 		/* verify recv cqe references the right rxq */
1650 		if (comp[i].wq_num != cq->rxq->gdma_id) {
1651 			mana_err(NULL,
1652 			    "WARNING: Received CQE %d  not for "
1653 			    "this receive queue %d\n",
1654 			    comp[i].wq_num,  cq->rxq->gdma_id);
1655 			return;
1656 		}
1657 
1658 		mana_process_rx_cqe(cq->rxq, cq, &comp[i]);
1659 	}
1660 
1661 	tcp_lro_flush_all(&cq->rxq->lro);
1662 }
1663 
1664 static void
1665 mana_cq_handler(void *context, struct gdma_queue *gdma_queue)
1666 {
1667 	struct mana_cq *cq = context;
1668 	uint8_t arm_bit;
1669 
1670 	KASSERT(cq->gdma_cq == gdma_queue,
1671 	    ("cq do not match %p, %p", cq->gdma_cq, gdma_queue));
1672 
1673 	if (cq->type == MANA_CQ_TYPE_RX) {
1674 		mana_poll_rx_cq(cq);
1675 	} else {
1676 		mana_poll_tx_cq(cq);
1677 	}
1678 
1679 	if (cq->work_done < cq->budget && cq->do_not_ring_db == false)
1680 		arm_bit = SET_ARM_BIT;
1681 	else
1682 		arm_bit = 0;
1683 
1684 	mana_gd_ring_cq(gdma_queue, arm_bit);
1685 }
1686 
1687 #define MANA_POLL_BUDGET	8
1688 #define MANA_RX_BUDGET		256
1689 #define MANA_TX_BUDGET		MAX_SEND_BUFFERS_PER_QUEUE
1690 
1691 static void
1692 mana_poll(void *arg, int pending)
1693 {
1694 	struct mana_cq *cq = arg;
1695 	int i;
1696 
1697 	cq->work_done = 0;
1698 	if (cq->type == MANA_CQ_TYPE_RX) {
1699 		cq->budget = MANA_RX_BUDGET;
1700 	} else {
1701 		cq->budget = MANA_TX_BUDGET;
1702 	}
1703 
1704 	for (i = 0; i < MANA_POLL_BUDGET; i++) {
1705 		/*
1706 		 * If this is the last loop, set the budget big enough
1707 		 * so it will arm the CQ any way.
1708 		 */
1709 		if (i == (MANA_POLL_BUDGET - 1))
1710 			cq->budget = CQE_POLLING_BUFFER + 1;
1711 
1712 		mana_cq_handler(cq, cq->gdma_cq);
1713 
1714 		if (cq->work_done < cq->budget)
1715 			break;
1716 
1717 		cq->work_done = 0;
1718 	}
1719 }
1720 
1721 static void
1722 mana_schedule_task(void *arg, struct gdma_queue *gdma_queue)
1723 {
1724 	struct mana_cq *cq = arg;
1725 
1726 	taskqueue_enqueue(cq->cleanup_tq, &cq->cleanup_task);
1727 }
1728 
1729 static void
1730 mana_deinit_cq(struct mana_port_context *apc, struct mana_cq *cq)
1731 {
1732 	struct gdma_dev *gd = apc->ac->gdma_dev;
1733 
1734 	if (!cq->gdma_cq)
1735 		return;
1736 
1737 	/* Drain cleanup taskqueue */
1738 	if (cq->cleanup_tq) {
1739 		while (taskqueue_cancel(cq->cleanup_tq,
1740 		    &cq->cleanup_task, NULL)) {
1741 			taskqueue_drain(cq->cleanup_tq,
1742 			    &cq->cleanup_task);
1743 		}
1744 
1745 		taskqueue_free(cq->cleanup_tq);
1746 	}
1747 
1748 	mana_gd_destroy_queue(gd->gdma_context, cq->gdma_cq);
1749 }
1750 
1751 static void
1752 mana_deinit_txq(struct mana_port_context *apc, struct mana_txq *txq)
1753 {
1754 	struct gdma_dev *gd = apc->ac->gdma_dev;
1755 	struct mana_send_buf_info *txbuf_info;
1756 	uint32_t pending_sends;
1757 	int i;
1758 
1759 	if (!txq->gdma_sq)
1760 		return;
1761 
1762 	if ((pending_sends = atomic_read(&txq->pending_sends)) > 0) {
1763 		mana_err(NULL,
1764 		    "WARNING: txq pending sends not zero: %u\n",
1765 		    pending_sends);
1766 	}
1767 
1768 	if (txq->next_to_use != txq->next_to_complete) {
1769 		mana_err(NULL,
1770 		    "WARNING: txq buf not completed, "
1771 		    "next use %u, next complete %u\n",
1772 		    txq->next_to_use, txq->next_to_complete);
1773 	}
1774 
1775 	/* Flush buf ring. Grab txq mtx lock */
1776 	if (txq->txq_br) {
1777 		mtx_lock(&txq->txq_mtx);
1778 		drbr_flush(apc->ndev, txq->txq_br);
1779 		mtx_unlock(&txq->txq_mtx);
1780 		buf_ring_free(txq->txq_br, M_DEVBUF);
1781 	}
1782 
1783 	/* Drain taskqueue */
1784 	if (txq->enqueue_tq) {
1785 		while (taskqueue_cancel(txq->enqueue_tq,
1786 		    &txq->enqueue_task, NULL)) {
1787 			taskqueue_drain(txq->enqueue_tq,
1788 			    &txq->enqueue_task);
1789 		}
1790 
1791 		taskqueue_free(txq->enqueue_tq);
1792 	}
1793 
1794 	if (txq->tx_buf_info) {
1795 		/* Free all mbufs which are still in-flight */
1796 		for (i = 0; i < MAX_SEND_BUFFERS_PER_QUEUE; i++) {
1797 			txbuf_info = &txq->tx_buf_info[i];
1798 			if (txbuf_info->mbuf) {
1799 				mana_tx_unmap_mbuf(apc, txbuf_info);
1800 			}
1801 		}
1802 
1803 		free(txq->tx_buf_info, M_DEVBUF);
1804 	}
1805 
1806 	mana_free_counters((counter_u64_t *)&txq->stats,
1807 	    sizeof(txq->stats));
1808 
1809 	mana_gd_destroy_queue(gd->gdma_context, txq->gdma_sq);
1810 
1811 	mtx_destroy(&txq->txq_mtx);
1812 }
1813 
1814 static void
1815 mana_destroy_txq(struct mana_port_context *apc)
1816 {
1817 	int i;
1818 
1819 	if (!apc->tx_qp)
1820 		return;
1821 
1822 	for (i = 0; i < apc->num_queues; i++) {
1823 		mana_destroy_wq_obj(apc, GDMA_SQ, apc->tx_qp[i].tx_object);
1824 
1825 		mana_deinit_cq(apc, &apc->tx_qp[i].tx_cq);
1826 
1827 		mana_deinit_txq(apc, &apc->tx_qp[i].txq);
1828 	}
1829 
1830 	free(apc->tx_qp, M_DEVBUF);
1831 	apc->tx_qp = NULL;
1832 }
1833 
1834 static int
1835 mana_create_txq(struct mana_port_context *apc, struct ifnet *net)
1836 {
1837 	struct mana_context *ac = apc->ac;
1838 	struct gdma_dev *gd = ac->gdma_dev;
1839 	struct mana_obj_spec wq_spec;
1840 	struct mana_obj_spec cq_spec;
1841 	struct gdma_queue_spec spec;
1842 	struct gdma_context *gc;
1843 	struct mana_txq *txq;
1844 	struct mana_cq *cq;
1845 	uint32_t txq_size;
1846 	uint32_t cq_size;
1847 	int err;
1848 	int i;
1849 
1850 	apc->tx_qp = mallocarray(apc->num_queues, sizeof(struct mana_tx_qp),
1851 	    M_DEVBUF, M_WAITOK | M_ZERO);
1852 	if (!apc->tx_qp)
1853 		return ENOMEM;
1854 
1855 	/*  The minimum size of the WQE is 32 bytes, hence
1856 	 *  MAX_SEND_BUFFERS_PER_QUEUE represents the maximum number of WQEs
1857 	 *  the SQ can store. This value is then used to size other queues
1858 	 *  to prevent overflow.
1859 	 */
1860 	txq_size = MAX_SEND_BUFFERS_PER_QUEUE * 32;
1861 	KASSERT(IS_ALIGNED(txq_size, PAGE_SIZE),
1862 	    ("txq size not page aligned"));
1863 
1864 	cq_size = MAX_SEND_BUFFERS_PER_QUEUE * COMP_ENTRY_SIZE;
1865 	cq_size = ALIGN(cq_size, PAGE_SIZE);
1866 
1867 	gc = gd->gdma_context;
1868 
1869 	for (i = 0; i < apc->num_queues; i++) {
1870 		apc->tx_qp[i].tx_object = INVALID_MANA_HANDLE;
1871 
1872 		/* Create SQ */
1873 		txq = &apc->tx_qp[i].txq;
1874 
1875 		txq->ndev = net;
1876 		txq->vp_offset = apc->tx_vp_offset;
1877 		txq->idx = i;
1878 		txq->alt_txq_idx = i;
1879 
1880 		memset(&spec, 0, sizeof(spec));
1881 		spec.type = GDMA_SQ;
1882 		spec.monitor_avl_buf = true;
1883 		spec.queue_size = txq_size;
1884 		err = mana_gd_create_mana_wq_cq(gd, &spec, &txq->gdma_sq);
1885 		if (err)
1886 			goto out;
1887 
1888 		/* Create SQ's CQ */
1889 		cq = &apc->tx_qp[i].tx_cq;
1890 		cq->type = MANA_CQ_TYPE_TX;
1891 
1892 		cq->txq = txq;
1893 
1894 		memset(&spec, 0, sizeof(spec));
1895 		spec.type = GDMA_CQ;
1896 		spec.monitor_avl_buf = false;
1897 		spec.queue_size = cq_size;
1898 		spec.cq.callback = mana_schedule_task;
1899 		spec.cq.parent_eq = ac->eqs[i].eq;
1900 		spec.cq.context = cq;
1901 		err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
1902 		if (err)
1903 			goto out;
1904 
1905 		memset(&wq_spec, 0, sizeof(wq_spec));
1906 		memset(&cq_spec, 0, sizeof(cq_spec));
1907 
1908 		wq_spec.gdma_region = txq->gdma_sq->mem_info.gdma_region;
1909 		wq_spec.queue_size = txq->gdma_sq->queue_size;
1910 
1911 		cq_spec.gdma_region = cq->gdma_cq->mem_info.gdma_region;
1912 		cq_spec.queue_size = cq->gdma_cq->queue_size;
1913 		cq_spec.modr_ctx_id = 0;
1914 		cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
1915 
1916 		err = mana_create_wq_obj(apc, apc->port_handle, GDMA_SQ,
1917 		    &wq_spec, &cq_spec, &apc->tx_qp[i].tx_object);
1918 
1919 		if (err)
1920 			goto out;
1921 
1922 		txq->gdma_sq->id = wq_spec.queue_index;
1923 		cq->gdma_cq->id = cq_spec.queue_index;
1924 
1925 		txq->gdma_sq->mem_info.gdma_region = GDMA_INVALID_DMA_REGION;
1926 		cq->gdma_cq->mem_info.gdma_region = GDMA_INVALID_DMA_REGION;
1927 
1928 		txq->gdma_txq_id = txq->gdma_sq->id;
1929 
1930 		cq->gdma_id = cq->gdma_cq->id;
1931 
1932 		mana_dbg(NULL,
1933 		    "txq %d, txq gdma id %d, txq cq gdma id %d\n",
1934 		    i, txq->gdma_txq_id, cq->gdma_id);;
1935 
1936 		if (cq->gdma_id >= gc->max_num_cqs) {
1937 			if_printf(net, "CQ id %u too large.\n", cq->gdma_id);
1938 			return EINVAL;
1939 		}
1940 
1941 		gc->cq_table[cq->gdma_id] = cq->gdma_cq;
1942 
1943 		/* Initialize tx specific data */
1944 		txq->tx_buf_info = malloc(MAX_SEND_BUFFERS_PER_QUEUE *
1945 		    sizeof(struct mana_send_buf_info),
1946 		    M_DEVBUF, M_WAITOK | M_ZERO);
1947 		if (unlikely(txq->tx_buf_info == NULL)) {
1948 			if_printf(net,
1949 			    "Failed to allocate tx buf info for SQ %u\n",
1950 			    txq->gdma_sq->id);
1951 			err = ENOMEM;
1952 			goto out;
1953 		}
1954 
1955 
1956 		snprintf(txq->txq_mtx_name, nitems(txq->txq_mtx_name),
1957 		    "mana:tx(%d)", i);
1958 		mtx_init(&txq->txq_mtx, txq->txq_mtx_name, NULL, MTX_DEF);
1959 
1960 		txq->txq_br = buf_ring_alloc(4 * MAX_SEND_BUFFERS_PER_QUEUE,
1961 		    M_DEVBUF, M_WAITOK, &txq->txq_mtx);
1962 		if (unlikely(txq->txq_br == NULL)) {
1963 			if_printf(net,
1964 			    "Failed to allocate buf ring for SQ %u\n",
1965 			    txq->gdma_sq->id);
1966 			err = ENOMEM;
1967 			goto out;
1968 		}
1969 
1970 		/* Allocate taskqueue for deferred send */
1971 		TASK_INIT(&txq->enqueue_task, 0, mana_xmit_taskfunc, txq);
1972 		txq->enqueue_tq = taskqueue_create_fast("mana_tx_enque",
1973 		    M_NOWAIT, taskqueue_thread_enqueue, &txq->enqueue_tq);
1974 		if (unlikely(txq->enqueue_tq == NULL)) {
1975 			if_printf(net,
1976 			    "Unable to create tx %d enqueue task queue\n", i);
1977 			err = ENOMEM;
1978 			goto out;
1979 		}
1980 		taskqueue_start_threads(&txq->enqueue_tq, 1, PI_NET,
1981 		    "mana txq p%u-tx%d", apc->port_idx, i);
1982 
1983 		mana_alloc_counters((counter_u64_t *)&txq->stats,
1984 		    sizeof(txq->stats));
1985 
1986 		/* Allocate and start the cleanup task on CQ */
1987 		cq->do_not_ring_db = false;
1988 
1989 		NET_TASK_INIT(&cq->cleanup_task, 0, mana_poll, cq);
1990 		cq->cleanup_tq =
1991 		    taskqueue_create_fast("mana tx cq cleanup",
1992 		    M_WAITOK, taskqueue_thread_enqueue,
1993 		    &cq->cleanup_tq);
1994 
1995 		if (apc->last_tx_cq_bind_cpu < 0)
1996 			apc->last_tx_cq_bind_cpu = CPU_FIRST();
1997 		cq->cpu = apc->last_tx_cq_bind_cpu;
1998 		apc->last_tx_cq_bind_cpu = CPU_NEXT(apc->last_tx_cq_bind_cpu);
1999 
2000 		if (apc->bind_cleanup_thread_cpu) {
2001 			cpuset_t cpu_mask;
2002 			CPU_SETOF(cq->cpu, &cpu_mask);
2003 			taskqueue_start_threads_cpuset(&cq->cleanup_tq,
2004 			    1, PI_NET, &cpu_mask,
2005 			    "mana cq p%u-tx%u-cpu%d",
2006 			    apc->port_idx, txq->idx, cq->cpu);
2007 		} else {
2008 			taskqueue_start_threads(&cq->cleanup_tq, 1,
2009 			    PI_NET, "mana cq p%u-tx%u",
2010 			    apc->port_idx, txq->idx);
2011 		}
2012 
2013 		mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
2014 	}
2015 
2016 	return 0;
2017 out:
2018 	mana_destroy_txq(apc);
2019 	return err;
2020 }
2021 
2022 static void
2023 mana_destroy_rxq(struct mana_port_context *apc, struct mana_rxq *rxq,
2024     bool validate_state)
2025 {
2026 	struct gdma_context *gc = apc->ac->gdma_dev->gdma_context;
2027 	struct mana_recv_buf_oob *rx_oob;
2028 	int i;
2029 
2030 	if (!rxq)
2031 		return;
2032 
2033 	if (validate_state) {
2034 		/*
2035 		 * XXX Cancel and drain cleanup task queue here.
2036 		 */
2037 		;
2038 	}
2039 
2040 	mana_destroy_wq_obj(apc, GDMA_RQ, rxq->rxobj);
2041 
2042 	mana_deinit_cq(apc, &rxq->rx_cq);
2043 
2044 	mana_free_counters((counter_u64_t *)&rxq->stats,
2045 	    sizeof(rxq->stats));
2046 
2047 	/* Free LRO resources */
2048 	tcp_lro_free(&rxq->lro);
2049 
2050 	for (i = 0; i < rxq->num_rx_buf; i++) {
2051 		rx_oob = &rxq->rx_oobs[i];
2052 
2053 		if (rx_oob->mbuf)
2054 			mana_unload_rx_mbuf(apc, rxq, rx_oob, true);
2055 
2056 		bus_dmamap_destroy(apc->rx_buf_tag, rx_oob->dma_map);
2057 	}
2058 
2059 	if (rxq->gdma_rq)
2060 		mana_gd_destroy_queue(gc, rxq->gdma_rq);
2061 
2062 	free(rxq, M_DEVBUF);
2063 }
2064 
2065 #define MANA_WQE_HEADER_SIZE 16
2066 #define MANA_WQE_SGE_SIZE 16
2067 
2068 static int
2069 mana_alloc_rx_wqe(struct mana_port_context *apc,
2070     struct mana_rxq *rxq, uint32_t *rxq_size, uint32_t *cq_size)
2071 {
2072 	struct mana_recv_buf_oob *rx_oob;
2073 	uint32_t buf_idx;
2074 	int err;
2075 
2076 	if (rxq->datasize == 0 || rxq->datasize > PAGE_SIZE) {
2077 		mana_err(NULL,
2078 		    "WARNING: Invalid rxq datasize %u\n", rxq->datasize);
2079 	}
2080 
2081 	*rxq_size = 0;
2082 	*cq_size = 0;
2083 
2084 	for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
2085 		rx_oob = &rxq->rx_oobs[buf_idx];
2086 		memset(rx_oob, 0, sizeof(*rx_oob));
2087 
2088 		err = bus_dmamap_create(apc->rx_buf_tag, 0,
2089 		    &rx_oob->dma_map);
2090 		if (err) {
2091 			mana_err(NULL,
2092 			    "Failed to  create rx DMA map for buf %d\n",
2093 			    buf_idx);
2094 			return err;
2095 		}
2096 
2097 		err = mana_load_rx_mbuf(apc, rxq, rx_oob, true);
2098 		if (err) {
2099 			mana_err(NULL,
2100 			    "Failed to  create rx DMA map for buf %d\n",
2101 			    buf_idx);
2102 			bus_dmamap_destroy(apc->rx_buf_tag, rx_oob->dma_map);
2103 			return err;
2104 		}
2105 
2106 		rx_oob->wqe_req.sgl = rx_oob->sgl;
2107 		rx_oob->wqe_req.num_sge = rx_oob->num_sge;
2108 		rx_oob->wqe_req.inline_oob_size = 0;
2109 		rx_oob->wqe_req.inline_oob_data = NULL;
2110 		rx_oob->wqe_req.flags = 0;
2111 		rx_oob->wqe_req.client_data_unit = 0;
2112 
2113 		*rxq_size += ALIGN(MANA_WQE_HEADER_SIZE +
2114 				   MANA_WQE_SGE_SIZE * rx_oob->num_sge, 32);
2115 		*cq_size += COMP_ENTRY_SIZE;
2116 	}
2117 
2118 	return 0;
2119 }
2120 
2121 static int
2122 mana_push_wqe(struct mana_rxq *rxq)
2123 {
2124 	struct mana_recv_buf_oob *rx_oob;
2125 	uint32_t buf_idx;
2126 	int err;
2127 
2128 	for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
2129 		rx_oob = &rxq->rx_oobs[buf_idx];
2130 
2131 		err = mana_gd_post_and_ring(rxq->gdma_rq, &rx_oob->wqe_req,
2132 		    &rx_oob->wqe_inf);
2133 		if (err)
2134 			return ENOSPC;
2135 	}
2136 
2137 	return 0;
2138 }
2139 
2140 static struct mana_rxq *
2141 mana_create_rxq(struct mana_port_context *apc, uint32_t rxq_idx,
2142     struct mana_eq *eq, struct ifnet *ndev)
2143 {
2144 	struct gdma_dev *gd = apc->ac->gdma_dev;
2145 	struct mana_obj_spec wq_spec;
2146 	struct mana_obj_spec cq_spec;
2147 	struct gdma_queue_spec spec;
2148 	struct mana_cq *cq = NULL;
2149 	uint32_t cq_size, rq_size;
2150 	struct gdma_context *gc;
2151 	struct mana_rxq *rxq;
2152 	int err;
2153 
2154 	gc = gd->gdma_context;
2155 
2156 	rxq = malloc(sizeof(*rxq) +
2157 	    RX_BUFFERS_PER_QUEUE * sizeof(struct mana_recv_buf_oob),
2158 	    M_DEVBUF, M_WAITOK | M_ZERO);
2159 	if (!rxq)
2160 		return NULL;
2161 
2162 	rxq->ndev = ndev;
2163 	rxq->num_rx_buf = RX_BUFFERS_PER_QUEUE;
2164 	rxq->rxq_idx = rxq_idx;
2165 	/*
2166 	 * Minimum size is MCLBYTES(2048) bytes for a mbuf cluster.
2167 	 * Now we just allow maximum size of 4096.
2168 	 */
2169 	rxq->datasize = ALIGN(apc->frame_size, MCLBYTES);
2170 	if (rxq->datasize > MAX_FRAME_SIZE)
2171 		rxq->datasize = MAX_FRAME_SIZE;
2172 
2173 	mana_dbg(NULL, "Setting rxq %d datasize %d\n",
2174 	    rxq_idx, rxq->datasize);
2175 
2176 	rxq->rxobj = INVALID_MANA_HANDLE;
2177 
2178 	err = mana_alloc_rx_wqe(apc, rxq, &rq_size, &cq_size);
2179 	if (err)
2180 		goto out;
2181 
2182 	/* Create LRO for the RQ */
2183 	if (ndev->if_capenable & IFCAP_LRO) {
2184 		err = tcp_lro_init(&rxq->lro);
2185 		if (err) {
2186 			if_printf(ndev, "Failed to create LRO for rxq %d\n",
2187 			    rxq_idx);
2188 		} else {
2189 			rxq->lro.ifp = ndev;
2190 		}
2191 	}
2192 
2193 	mana_alloc_counters((counter_u64_t *)&rxq->stats,
2194 	    sizeof(rxq->stats));
2195 
2196 	rq_size = ALIGN(rq_size, PAGE_SIZE);
2197 	cq_size = ALIGN(cq_size, PAGE_SIZE);
2198 
2199 	/* Create RQ */
2200 	memset(&spec, 0, sizeof(spec));
2201 	spec.type = GDMA_RQ;
2202 	spec.monitor_avl_buf = true;
2203 	spec.queue_size = rq_size;
2204 	err = mana_gd_create_mana_wq_cq(gd, &spec, &rxq->gdma_rq);
2205 	if (err)
2206 		goto out;
2207 
2208 	/* Create RQ's CQ */
2209 	cq = &rxq->rx_cq;
2210 	cq->type = MANA_CQ_TYPE_RX;
2211 	cq->rxq = rxq;
2212 
2213 	memset(&spec, 0, sizeof(spec));
2214 	spec.type = GDMA_CQ;
2215 	spec.monitor_avl_buf = false;
2216 	spec.queue_size = cq_size;
2217 	spec.cq.callback = mana_schedule_task;
2218 	spec.cq.parent_eq = eq->eq;
2219 	spec.cq.context = cq;
2220 	err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
2221 	if (err)
2222 		goto out;
2223 
2224 	memset(&wq_spec, 0, sizeof(wq_spec));
2225 	memset(&cq_spec, 0, sizeof(cq_spec));
2226 	wq_spec.gdma_region = rxq->gdma_rq->mem_info.gdma_region;
2227 	wq_spec.queue_size = rxq->gdma_rq->queue_size;
2228 
2229 	cq_spec.gdma_region = cq->gdma_cq->mem_info.gdma_region;
2230 	cq_spec.queue_size = cq->gdma_cq->queue_size;
2231 	cq_spec.modr_ctx_id = 0;
2232 	cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
2233 
2234 	err = mana_create_wq_obj(apc, apc->port_handle, GDMA_RQ,
2235 	    &wq_spec, &cq_spec, &rxq->rxobj);
2236 	if (err)
2237 		goto out;
2238 
2239 	rxq->gdma_rq->id = wq_spec.queue_index;
2240 	cq->gdma_cq->id = cq_spec.queue_index;
2241 
2242 	rxq->gdma_rq->mem_info.gdma_region = GDMA_INVALID_DMA_REGION;
2243 	cq->gdma_cq->mem_info.gdma_region = GDMA_INVALID_DMA_REGION;
2244 
2245 	rxq->gdma_id = rxq->gdma_rq->id;
2246 	cq->gdma_id = cq->gdma_cq->id;
2247 
2248 	err = mana_push_wqe(rxq);
2249 	if (err)
2250 		goto out;
2251 
2252 	if (cq->gdma_id >= gc->max_num_cqs)
2253 		goto out;
2254 
2255 	gc->cq_table[cq->gdma_id] = cq->gdma_cq;
2256 
2257 	/* Allocate and start the cleanup task on CQ */
2258 	cq->do_not_ring_db = false;
2259 
2260 	NET_TASK_INIT(&cq->cleanup_task, 0, mana_poll, cq);
2261 	cq->cleanup_tq =
2262 	    taskqueue_create_fast("mana rx cq cleanup",
2263 	    M_WAITOK, taskqueue_thread_enqueue,
2264 	    &cq->cleanup_tq);
2265 
2266 	if (apc->last_rx_cq_bind_cpu < 0)
2267 		apc->last_rx_cq_bind_cpu = CPU_FIRST();
2268 	cq->cpu = apc->last_rx_cq_bind_cpu;
2269 	apc->last_rx_cq_bind_cpu = CPU_NEXT(apc->last_rx_cq_bind_cpu);
2270 
2271 	if (apc->bind_cleanup_thread_cpu) {
2272 		cpuset_t cpu_mask;
2273 		CPU_SETOF(cq->cpu, &cpu_mask);
2274 		taskqueue_start_threads_cpuset(&cq->cleanup_tq,
2275 		    1, PI_NET, &cpu_mask,
2276 		    "mana cq p%u-rx%u-cpu%d",
2277 		    apc->port_idx, rxq->rxq_idx, cq->cpu);
2278 	} else {
2279 		taskqueue_start_threads(&cq->cleanup_tq, 1,
2280 		    PI_NET, "mana cq p%u-rx%u",
2281 		    apc->port_idx, rxq->rxq_idx);
2282 	}
2283 
2284 	mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
2285 out:
2286 	if (!err)
2287 		return rxq;
2288 
2289 	if_printf(ndev, "Failed to create RXQ: err = %d\n", err);
2290 
2291 	mana_destroy_rxq(apc, rxq, false);
2292 
2293 	if (cq)
2294 		mana_deinit_cq(apc, cq);
2295 
2296 	return NULL;
2297 }
2298 
2299 static int
2300 mana_add_rx_queues(struct mana_port_context *apc, struct ifnet *ndev)
2301 {
2302 	struct mana_context *ac = apc->ac;
2303 	struct mana_rxq *rxq;
2304 	int err = 0;
2305 	int i;
2306 
2307 	for (i = 0; i < apc->num_queues; i++) {
2308 		rxq = mana_create_rxq(apc, i, &ac->eqs[i], ndev);
2309 		if (!rxq) {
2310 			err = ENOMEM;
2311 			goto out;
2312 		}
2313 
2314 		apc->rxqs[i] = rxq;
2315 	}
2316 
2317 	apc->default_rxobj = apc->rxqs[0]->rxobj;
2318 out:
2319 	return err;
2320 }
2321 
2322 static void
2323 mana_destroy_vport(struct mana_port_context *apc)
2324 {
2325 	struct mana_rxq *rxq;
2326 	uint32_t rxq_idx;
2327 
2328 	for (rxq_idx = 0; rxq_idx < apc->num_queues; rxq_idx++) {
2329 		rxq = apc->rxqs[rxq_idx];
2330 		if (!rxq)
2331 			continue;
2332 
2333 		mana_destroy_rxq(apc, rxq, true);
2334 		apc->rxqs[rxq_idx] = NULL;
2335 	}
2336 
2337 	mana_destroy_txq(apc);
2338 }
2339 
2340 static int
2341 mana_create_vport(struct mana_port_context *apc, struct ifnet *net)
2342 {
2343 	struct gdma_dev *gd = apc->ac->gdma_dev;
2344 	int err;
2345 
2346 	apc->default_rxobj = INVALID_MANA_HANDLE;
2347 
2348 	err = mana_cfg_vport(apc, gd->pdid, gd->doorbell);
2349 	if (err)
2350 		return err;
2351 
2352 	return mana_create_txq(apc, net);
2353 }
2354 
2355 
2356 static void mana_rss_table_init(struct mana_port_context *apc)
2357 {
2358 	int i;
2359 
2360 	for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
2361 		apc->indir_table[i] = i % apc->num_queues;
2362 }
2363 
2364 int mana_config_rss(struct mana_port_context *apc, enum TRI_STATE rx,
2365 		    bool update_hash, bool update_tab)
2366 {
2367 	uint32_t queue_idx;
2368 	int i;
2369 
2370 	if (update_tab) {
2371 		for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++) {
2372 			queue_idx = apc->indir_table[i];
2373 			apc->rxobj_table[i] = apc->rxqs[queue_idx]->rxobj;
2374 		}
2375 	}
2376 
2377 	return mana_cfg_vport_steering(apc, rx, true, update_hash, update_tab);
2378 }
2379 
2380 static int
2381 mana_init_port(struct ifnet *ndev)
2382 {
2383 	struct mana_port_context *apc = if_getsoftc(ndev);
2384 	uint32_t max_txq, max_rxq, max_queues;
2385 	int port_idx = apc->port_idx;
2386 	uint32_t num_indirect_entries;
2387 	int err;
2388 
2389 	err = mana_init_port_context(apc);
2390 	if (err)
2391 		return err;
2392 
2393 	err = mana_query_vport_cfg(apc, port_idx, &max_txq, &max_rxq,
2394 	    &num_indirect_entries);
2395 	if (err) {
2396 		if_printf(ndev, "Failed to query info for vPort 0\n");
2397 		goto reset_apc;
2398 	}
2399 
2400 	max_queues = min_t(uint32_t, max_txq, max_rxq);
2401 	if (apc->max_queues > max_queues)
2402 		apc->max_queues = max_queues;
2403 
2404 	if (apc->num_queues > apc->max_queues)
2405 		apc->num_queues = apc->max_queues;
2406 
2407 	return 0;
2408 
2409 reset_apc:
2410 	bus_dma_tag_destroy(apc->rx_buf_tag);
2411 	apc->rx_buf_tag = NULL;
2412 	free(apc->rxqs, M_DEVBUF);
2413 	apc->rxqs = NULL;
2414 	return err;
2415 }
2416 
2417 int
2418 mana_alloc_queues(struct ifnet *ndev)
2419 {
2420 	struct mana_port_context *apc = if_getsoftc(ndev);
2421 	int err;
2422 
2423 	err = mana_create_vport(apc, ndev);
2424 	if (err)
2425 		return err;
2426 
2427 	err = mana_add_rx_queues(apc, ndev);
2428 	if (err)
2429 		goto destroy_vport;
2430 
2431 	apc->rss_state = apc->num_queues > 1 ? TRI_STATE_TRUE : TRI_STATE_FALSE;
2432 
2433 	mana_rss_table_init(apc);
2434 
2435 	err = mana_config_rss(apc, TRI_STATE_TRUE, true, true);
2436 	if (err)
2437 		goto destroy_vport;
2438 
2439 	return 0;
2440 
2441 destroy_vport:
2442 	mana_destroy_vport(apc);
2443 	return err;
2444 }
2445 
2446 static int
2447 mana_up(struct mana_port_context *apc)
2448 {
2449 	int err;
2450 
2451 	mana_dbg(NULL, "mana_up called\n");
2452 
2453 	err = mana_alloc_queues(apc->ndev);
2454 	if (err) {
2455 		mana_err(NULL, "Faile alloc mana queues: %d\n", err);
2456 		return err;
2457 	}
2458 
2459 	/* Add queue specific sysctl */
2460 	mana_sysctl_add_queues(apc);
2461 
2462 	apc->port_is_up = true;
2463 
2464 	/* Ensure port state updated before txq state */
2465 	wmb();
2466 
2467 	if_link_state_change(apc->ndev, LINK_STATE_UP);
2468 	if_setdrvflagbits(apc->ndev, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
2469 
2470 	return 0;
2471 }
2472 
2473 
2474 static void
2475 mana_init(void *arg)
2476 {
2477 	struct mana_port_context *apc = (struct mana_port_context *)arg;
2478 
2479 	MANA_APC_LOCK_LOCK(apc);
2480 	if (!apc->port_is_up) {
2481 		mana_up(apc);
2482 	}
2483 	MANA_APC_LOCK_UNLOCK(apc);
2484 }
2485 
2486 static int
2487 mana_dealloc_queues(struct ifnet *ndev)
2488 {
2489 	struct mana_port_context *apc = if_getsoftc(ndev);
2490 	struct mana_txq *txq;
2491 	int i, err;
2492 
2493 	if (apc->port_is_up)
2494 		return EINVAL;
2495 
2496 	/* No packet can be transmitted now since apc->port_is_up is false.
2497 	 * There is still a tiny chance that mana_poll_tx_cq() can re-enable
2498 	 * a txq because it may not timely see apc->port_is_up being cleared
2499 	 * to false, but it doesn't matter since mana_start_xmit() drops any
2500 	 * new packets due to apc->port_is_up being false.
2501 	 *
2502 	 * Drain all the in-flight TX packets
2503 	 */
2504 	for (i = 0; i < apc->num_queues; i++) {
2505 		txq = &apc->tx_qp[i].txq;
2506 
2507 		struct mana_cq *tx_cq = &apc->tx_qp[i].tx_cq;
2508 		struct mana_cq *rx_cq = &(apc->rxqs[i]->rx_cq);
2509 
2510 		tx_cq->do_not_ring_db = true;
2511 		rx_cq->do_not_ring_db = true;
2512 
2513 		/* Schedule a cleanup task */
2514 		taskqueue_enqueue(tx_cq->cleanup_tq, &tx_cq->cleanup_task);
2515 
2516 		while (atomic_read(&txq->pending_sends) > 0)
2517 			usleep_range(1000, 2000);
2518 	}
2519 
2520 	/* We're 100% sure the queues can no longer be woken up, because
2521 	 * we're sure now mana_poll_tx_cq() can't be running.
2522 	 */
2523 
2524 	apc->rss_state = TRI_STATE_FALSE;
2525 	err = mana_config_rss(apc, TRI_STATE_FALSE, false, false);
2526 	if (err) {
2527 		if_printf(ndev, "Failed to disable vPort: %d\n", err);
2528 		return err;
2529 	}
2530 
2531 	/* TODO: Implement RX fencing */
2532 	gdma_msleep(1000);
2533 
2534 	mana_destroy_vport(apc);
2535 
2536 	return 0;
2537 }
2538 
2539 static int
2540 mana_down(struct mana_port_context *apc)
2541 {
2542 	int err = 0;
2543 
2544 	apc->port_st_save = apc->port_is_up;
2545 	apc->port_is_up = false;
2546 
2547 	/* Ensure port state updated before txq state */
2548 	wmb();
2549 
2550 	if (apc->port_st_save) {
2551 		if_setdrvflagbits(apc->ndev, IFF_DRV_OACTIVE,
2552 		    IFF_DRV_RUNNING);
2553 		if_link_state_change(apc->ndev, LINK_STATE_DOWN);
2554 
2555 		mana_sysctl_free_queues(apc);
2556 
2557 		err = mana_dealloc_queues(apc->ndev);
2558 		if (err) {
2559 			if_printf(apc->ndev,
2560 			    "Failed to bring down mana interface: %d\n", err);
2561 		}
2562 	}
2563 
2564 	return err;
2565 }
2566 
2567 int
2568 mana_detach(struct ifnet *ndev)
2569 {
2570 	struct mana_port_context *apc = if_getsoftc(ndev);
2571 	int err;
2572 
2573 	ether_ifdetach(ndev);
2574 
2575 	if (!apc)
2576 		return 0;
2577 
2578 	MANA_APC_LOCK_LOCK(apc);
2579 	err = mana_down(apc);
2580 	MANA_APC_LOCK_UNLOCK(apc);
2581 
2582 	mana_cleanup_port_context(apc);
2583 
2584 	MANA_APC_LOCK_DESTROY(apc);
2585 
2586 	free(apc, M_DEVBUF);
2587 
2588 	return err;
2589 }
2590 
2591 static int
2592 mana_probe_port(struct mana_context *ac, int port_idx,
2593     struct ifnet **ndev_storage)
2594 {
2595 	struct gdma_context *gc = ac->gdma_dev->gdma_context;
2596 	struct mana_port_context *apc;
2597 	struct ifnet *ndev;
2598 	int err;
2599 
2600 	ndev = if_alloc_dev(IFT_ETHER, gc->dev);
2601 	if (!ndev) {
2602 		mana_err(NULL, "Failed to allocate ifnet struct\n");
2603 		return ENOMEM;
2604 	}
2605 
2606 	*ndev_storage = ndev;
2607 
2608 	apc = malloc(sizeof(*apc), M_DEVBUF, M_WAITOK | M_ZERO);
2609 	if (!apc) {
2610 		mana_err(NULL, "Failed to allocate port context\n");
2611 		err = ENOMEM;
2612 		goto free_net;
2613 	}
2614 
2615 	apc->ac = ac;
2616 	apc->ndev = ndev;
2617 	apc->max_queues = gc->max_num_queues;
2618 	apc->num_queues = min_t(unsigned int,
2619 	    gc->max_num_queues, MANA_MAX_NUM_QUEUES);
2620 	apc->port_handle = INVALID_MANA_HANDLE;
2621 	apc->port_idx = port_idx;
2622 	apc->frame_size = DEFAULT_FRAME_SIZE;
2623 	apc->last_tx_cq_bind_cpu = -1;
2624 	apc->last_rx_cq_bind_cpu = -1;
2625 
2626 	MANA_APC_LOCK_INIT(apc);
2627 
2628 	if_initname(ndev, device_get_name(gc->dev), port_idx);
2629 	if_setdev(ndev,gc->dev);
2630 	if_setsoftc(ndev, apc);
2631 
2632 	if_setflags(ndev, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2633 	if_setinitfn(ndev, mana_init);
2634 	if_settransmitfn(ndev, mana_start_xmit);
2635 	if_setqflushfn(ndev, mana_qflush);
2636 	if_setioctlfn(ndev, mana_ioctl);
2637 	if_setgetcounterfn(ndev, mana_get_counter);
2638 
2639 	if_setmtu(ndev, ETHERMTU);
2640 	if_setbaudrate(ndev, IF_Gbps(100));
2641 
2642 	mana_rss_key_fill(apc->hashkey, MANA_HASH_KEY_SIZE);
2643 
2644 	err = mana_init_port(ndev);
2645 	if (err)
2646 		goto reset_apc;
2647 
2648 	ndev->if_capabilities |= IFCAP_TXCSUM | IFCAP_TXCSUM_IPV6;
2649 	ndev->if_capabilities |= IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6;
2650 	ndev->if_capabilities |= IFCAP_TSO4 | IFCAP_TSO6;
2651 
2652 	ndev->if_capabilities |= IFCAP_LRO | IFCAP_LINKSTATE;
2653 
2654 	/* Enable all available capabilities by default. */
2655 	ndev->if_capenable = ndev->if_capabilities;
2656 
2657 	/* TSO parameters */
2658 	ndev->if_hw_tsomax = MAX_MBUF_FRAGS * MANA_TSO_MAXSEG_SZ -
2659 	    (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
2660 	ndev->if_hw_tsomaxsegcount = MAX_MBUF_FRAGS;
2661 	ndev->if_hw_tsomaxsegsize = PAGE_SIZE;
2662 
2663 	ifmedia_init(&apc->media, IFM_IMASK,
2664 	    mana_ifmedia_change, mana_ifmedia_status);
2665 	ifmedia_add(&apc->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2666 	ifmedia_set(&apc->media, IFM_ETHER | IFM_AUTO);
2667 
2668 	ether_ifattach(ndev, apc->mac_addr);
2669 
2670 	/* Initialize statistics */
2671 	mana_alloc_counters((counter_u64_t *)&apc->port_stats,
2672 	    sizeof(struct mana_port_stats));
2673 	mana_sysctl_add_port(apc);
2674 
2675 	/* Tell the stack that the interface is not active */
2676 	if_setdrvflagbits(ndev, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2677 
2678 	return 0;
2679 
2680 reset_apc:
2681 	free(apc, M_DEVBUF);
2682 free_net:
2683 	*ndev_storage = NULL;
2684 	if_printf(ndev, "Failed to probe vPort %d: %d\n", port_idx, err);
2685 	if_free(ndev);
2686 	return err;
2687 }
2688 
2689 int mana_probe(struct gdma_dev *gd)
2690 {
2691 	struct gdma_context *gc = gd->gdma_context;
2692 	device_t dev = gc->dev;
2693 	struct mana_context *ac;
2694 	int err;
2695 	int i;
2696 
2697 	device_printf(dev, "%s protocol version: %d.%d.%d\n", DEVICE_NAME,
2698 		 MANA_MAJOR_VERSION, MANA_MINOR_VERSION, MANA_MICRO_VERSION);
2699 
2700 	err = mana_gd_register_device(gd);
2701 	if (err)
2702 		return err;
2703 
2704 	ac = malloc(sizeof(*ac), M_DEVBUF, M_WAITOK | M_ZERO);
2705 	if (!ac)
2706 		return ENOMEM;
2707 
2708 	ac->gdma_dev = gd;
2709 	ac->num_ports = 1;
2710 	gd->driver_data = ac;
2711 
2712 	err = mana_create_eq(ac);
2713 	if (err)
2714 		goto out;
2715 
2716 	err = mana_query_device_cfg(ac, MANA_MAJOR_VERSION, MANA_MINOR_VERSION,
2717 	    MANA_MICRO_VERSION, &ac->num_ports);
2718 	if (err)
2719 		goto out;
2720 
2721 	if (ac->num_ports > MAX_PORTS_IN_MANA_DEV)
2722 		ac->num_ports = MAX_PORTS_IN_MANA_DEV;
2723 
2724 	for (i = 0; i < ac->num_ports; i++) {
2725 		err = mana_probe_port(ac, i, &ac->ports[i]);
2726 		if (err) {
2727 			device_printf(dev,
2728 			    "Failed to probe mana port %d\n", i);
2729 			break;
2730 		}
2731 	}
2732 
2733 out:
2734 	if (err)
2735 		mana_remove(gd);
2736 
2737 	return err;
2738 }
2739 
2740 void
2741 mana_remove(struct gdma_dev *gd)
2742 {
2743 	struct gdma_context *gc = gd->gdma_context;
2744 	struct mana_context *ac = gd->driver_data;
2745 	device_t dev = gc->dev;
2746 	struct ifnet *ndev;
2747 	int i;
2748 
2749 	for (i = 0; i < ac->num_ports; i++) {
2750 		ndev = ac->ports[i];
2751 		if (!ndev) {
2752 			if (i == 0)
2753 				device_printf(dev, "No net device to remove\n");
2754 			goto out;
2755 		}
2756 
2757 		mana_detach(ndev);
2758 
2759 		if_free(ndev);
2760 	}
2761 
2762 	mana_destroy_eq(ac);
2763 
2764 out:
2765 	mana_gd_deregister_device(gd);
2766 	gd->driver_data = NULL;
2767 	gd->gdma_context = NULL;
2768 	free(ac, M_DEVBUF);
2769 }
2770