xref: /freebsd/sys/dev/mana/gdma_main.c (revision 08aba0aec7b7f676ccc3f7886f59f277d668d5b4)
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/module.h>
41 #include <sys/rman.h>
42 #include <sys/smp.h>
43 #include <sys/socket.h>
44 #include <sys/sysctl.h>
45 #include <sys/taskqueue.h>
46 #include <sys/time.h>
47 #include <sys/eventhandler.h>
48 
49 #include <machine/bus.h>
50 #include <machine/resource.h>
51 #include <machine/in_cksum.h>
52 
53 #include <net/if.h>
54 #include <net/if_var.h>
55 
56 #include <dev/pci/pcivar.h>
57 #include <dev/pci/pcireg.h>
58 
59 #include "gdma_util.h"
60 #include "mana.h"
61 
62 
63 static mana_vendor_id_t mana_id_table[] = {
64     { PCI_VENDOR_ID_MICROSOFT, PCI_DEV_ID_MANA_VF},
65     /* Last entry */
66     { 0, 0}
67 };
68 
69 static inline uint32_t
70 mana_gd_r32(struct gdma_context *g, uint64_t offset)
71 {
72 	uint32_t v = bus_space_read_4(g->gd_bus.bar0_t,
73 	    g->gd_bus.bar0_h, offset);
74 	rmb();
75 	return (v);
76 }
77 
78 #if defined(__amd64__)
79 static inline uint64_t
80 mana_gd_r64(struct gdma_context *g, uint64_t offset)
81 {
82 	uint64_t v = bus_space_read_8(g->gd_bus.bar0_t,
83 	    g->gd_bus.bar0_h, offset);
84 	rmb();
85 	return (v);
86 }
87 #else
88 static inline uint64_t
89 mana_gd_r64(struct gdma_context *g, uint64_t offset)
90 {
91 	uint64_t v;
92 	uint32_t *vp = (uint32_t *)&v;
93 
94 	*vp =  mana_gd_r32(g, offset);
95 	*(vp + 1) = mana_gd_r32(g, offset + 4);
96 	rmb();
97 	return (v);
98 }
99 #endif
100 
101 static int
102 mana_gd_query_max_resources(device_t dev)
103 {
104 	struct gdma_context *gc = device_get_softc(dev);
105 	struct gdma_query_max_resources_resp resp = {};
106 	struct gdma_general_req req = {};
107 	int err;
108 
109 	mana_gd_init_req_hdr(&req.hdr, GDMA_QUERY_MAX_RESOURCES,
110 	    sizeof(req), sizeof(resp));
111 
112 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
113 	if (err || resp.hdr.status) {
114 		device_printf(gc->dev,
115 		   "Failed to query resource info: %d, 0x%x\n",
116 		   err, resp.hdr.status);
117 		return err ? err : EPROTO;
118 	}
119 
120 	mana_dbg(NULL, "max_msix %u, max_eq %u, max_cq %u, "
121 	    "max_sq %u, max_rq %u\n",
122 	    resp.max_msix, resp.max_eq, resp.max_cq,
123 	    resp.max_sq, resp.max_rq);
124 
125 	if (gc->num_msix_usable > resp.max_msix)
126 		gc->num_msix_usable = resp.max_msix;
127 
128 	if (gc->num_msix_usable <= 1)
129 		return ENOSPC;
130 
131 	gc->max_num_queues = mp_ncpus;
132 	if (gc->max_num_queues > MANA_MAX_NUM_QUEUES)
133 		gc->max_num_queues = MANA_MAX_NUM_QUEUES;
134 
135 	if (gc->max_num_queues > resp.max_eq)
136 		gc->max_num_queues = resp.max_eq;
137 
138 	if (gc->max_num_queues > resp.max_cq)
139 		gc->max_num_queues = resp.max_cq;
140 
141 	if (gc->max_num_queues > resp.max_sq)
142 		gc->max_num_queues = resp.max_sq;
143 
144 	if (gc->max_num_queues > resp.max_rq)
145 		gc->max_num_queues = resp.max_rq;
146 
147 	return 0;
148 }
149 
150 static int
151 mana_gd_detect_devices(device_t dev)
152 {
153 	struct gdma_context *gc = device_get_softc(dev);
154 	struct gdma_list_devices_resp resp = {};
155 	struct gdma_general_req req = {};
156 	struct gdma_dev_id gd_dev;
157 	uint32_t i, max_num_devs;
158 	uint16_t dev_type;
159 	int err;
160 
161 	mana_gd_init_req_hdr(&req.hdr, GDMA_LIST_DEVICES, sizeof(req),
162 	    sizeof(resp));
163 
164 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
165 	if (err || resp.hdr.status) {
166 		device_printf(gc->dev,
167 		    "Failed to detect devices: %d, 0x%x\n", err,
168 		    resp.hdr.status);
169 		return err ? err : EPROTO;
170 	}
171 
172 	max_num_devs = min_t(uint32_t, MAX_NUM_GDMA_DEVICES, resp.num_of_devs);
173 
174 	for (i = 0; i < max_num_devs; i++) {
175 		gd_dev = resp.devs[i];
176 		dev_type = gd_dev.type;
177 
178 		mana_dbg(NULL, "gdma dev %d, type %u\n",
179 		    i, dev_type);
180 
181 		/* HWC is already detected in mana_hwc_create_channel(). */
182 		if (dev_type == GDMA_DEVICE_HWC)
183 			continue;
184 
185 		if (dev_type == GDMA_DEVICE_MANA) {
186 			gc->mana.gdma_context = gc;
187 			gc->mana.dev_id = gd_dev;
188 		}
189 	}
190 
191 	return gc->mana.dev_id.type == 0 ? ENODEV : 0;
192 }
193 
194 int
195 mana_gd_send_request(struct gdma_context *gc, uint32_t req_len,
196     const void *req, uint32_t resp_len, void *resp)
197 {
198 	struct hw_channel_context *hwc = gc->hwc.driver_data;
199 
200 	return mana_hwc_send_request(hwc, req_len, req, resp_len, resp);
201 }
202 
203 void
204 mana_gd_dma_map_paddr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
205 {
206 	bus_addr_t *paddr = arg;
207 
208 	if (error)
209 		return;
210 
211 	KASSERT(nseg == 1, ("too many segments %d!", nseg));
212 	*paddr = segs->ds_addr;
213 }
214 
215 int
216 mana_gd_alloc_memory(struct gdma_context *gc, unsigned int length,
217     struct gdma_mem_info *gmi)
218 {
219 	bus_addr_t dma_handle;
220 	void *buf;
221 	int err;
222 
223 	if (!gc || !gmi)
224 		return EINVAL;
225 
226 	if (length < PAGE_SIZE || (length != roundup_pow_of_two(length)))
227 		return EINVAL;
228 
229 	err = bus_dma_tag_create(bus_get_dma_tag(gc->dev),	/* parent */
230 	    PAGE_SIZE, 0,		/* alignment, boundary	*/
231 	    BUS_SPACE_MAXADDR,		/* lowaddr		*/
232 	    BUS_SPACE_MAXADDR,		/* highaddr		*/
233 	    NULL, NULL,			/* filter, filterarg	*/
234 	    length,			/* maxsize		*/
235 	    1,				/* nsegments		*/
236 	    length,			/* maxsegsize		*/
237 	    0,				/* flags		*/
238 	    NULL, NULL,			/* lockfunc, lockfuncarg*/
239 	    &gmi->dma_tag);
240 	if (err) {
241 		device_printf(gc->dev,
242 		    "failed to create dma tag, err: %d\n", err);
243 		return (err);
244 	}
245 
246 	/*
247 	 * Must have BUS_DMA_ZERO flag to clear the dma memory.
248 	 * Otherwise the queue overflow detection mechanism does
249 	 * not work.
250 	 */
251 	err = bus_dmamem_alloc(gmi->dma_tag, &buf,
252 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &gmi->dma_map);
253 	if (err) {
254 		device_printf(gc->dev,
255 		    "failed to alloc dma mem, err: %d\n", err);
256 		bus_dma_tag_destroy(gmi->dma_tag);
257 		return (err);
258 	}
259 
260 	err = bus_dmamap_load(gmi->dma_tag, gmi->dma_map, buf,
261 	    length, mana_gd_dma_map_paddr, &dma_handle, BUS_DMA_NOWAIT);
262 	if (err) {
263 		device_printf(gc->dev,
264 		    "failed to load dma mem, err: %d\n", err);
265 		bus_dmamem_free(gmi->dma_tag, buf, gmi->dma_map);
266 		bus_dma_tag_destroy(gmi->dma_tag);
267 		return (err);
268 	}
269 
270 	gmi->dev = gc->dev;
271 	gmi->dma_handle = dma_handle;
272 	gmi->virt_addr = buf;
273 	gmi->length = length;
274 
275 	return 0;
276 }
277 
278 void
279 mana_gd_free_memory(struct gdma_mem_info *gmi)
280 {
281 	bus_dmamap_unload(gmi->dma_tag, gmi->dma_map);
282 	bus_dmamem_free(gmi->dma_tag, gmi->virt_addr, gmi->dma_map);
283 	bus_dma_tag_destroy(gmi->dma_tag);
284 }
285 
286 static int
287 mana_gd_create_hw_eq(struct gdma_context *gc,
288     struct gdma_queue *queue)
289 {
290 	struct gdma_create_queue_resp resp = {};
291 	struct gdma_create_queue_req req = {};
292 	int err;
293 
294 	if (queue->type != GDMA_EQ)
295 		return EINVAL;
296 
297 	mana_gd_init_req_hdr(&req.hdr, GDMA_CREATE_QUEUE,
298 			     sizeof(req), sizeof(resp));
299 
300 	req.hdr.dev_id = queue->gdma_dev->dev_id;
301 	req.type = queue->type;
302 	req.pdid = queue->gdma_dev->pdid;
303 	req.doolbell_id = queue->gdma_dev->doorbell;
304 	req.gdma_region = queue->mem_info.gdma_region;
305 	req.queue_size = queue->queue_size;
306 	req.log2_throttle_limit = queue->eq.log2_throttle_limit;
307 	req.eq_pci_msix_index = queue->eq.msix_index;
308 
309 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
310 	if (err || resp.hdr.status) {
311 		device_printf(gc->dev,
312 		    "Failed to create queue: %d, 0x%x\n",
313 		    err, resp.hdr.status);
314 		return err ? err : EPROTO;
315 	}
316 
317 	queue->id = resp.queue_index;
318 	queue->eq.disable_needed = true;
319 	queue->mem_info.gdma_region = GDMA_INVALID_DMA_REGION;
320 	return 0;
321 }
322 
323 static
324 int mana_gd_disable_queue(struct gdma_queue *queue)
325 {
326 	struct gdma_context *gc = queue->gdma_dev->gdma_context;
327 	struct gdma_disable_queue_req req = {};
328 	struct gdma_general_resp resp = {};
329 	int err;
330 
331 	if (queue->type != GDMA_EQ)
332 		mana_warn(NULL, "Not event queue type 0x%x\n",
333 		    queue->type);
334 
335 	mana_gd_init_req_hdr(&req.hdr, GDMA_DISABLE_QUEUE,
336 	    sizeof(req), sizeof(resp));
337 
338 	req.hdr.dev_id = queue->gdma_dev->dev_id;
339 	req.type = queue->type;
340 	req.queue_index =  queue->id;
341 	req.alloc_res_id_on_creation = 1;
342 
343 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
344 	if (err || resp.hdr.status) {
345 		device_printf(gc->dev,
346 		    "Failed to disable queue: %d, 0x%x\n", err,
347 		    resp.hdr.status);
348 		return err ? err : EPROTO;
349 	}
350 
351 	return 0;
352 }
353 
354 #define DOORBELL_OFFSET_SQ	0x0
355 #define DOORBELL_OFFSET_RQ	0x400
356 #define DOORBELL_OFFSET_CQ	0x800
357 #define DOORBELL_OFFSET_EQ	0xFF8
358 
359 static void
360 mana_gd_ring_doorbell(struct gdma_context *gc, uint32_t db_index,
361     enum gdma_queue_type q_type, uint32_t qid,
362     uint32_t tail_ptr, uint8_t num_req)
363 {
364 	union gdma_doorbell_entry e = {};
365 	void __iomem *addr;
366 
367 	addr = (char *)gc->db_page_base + gc->db_page_size * db_index;
368 	switch (q_type) {
369 	case GDMA_EQ:
370 		e.eq.id = qid;
371 		e.eq.tail_ptr = tail_ptr;
372 		e.eq.arm = num_req;
373 
374 		addr = (char *)addr + DOORBELL_OFFSET_EQ;
375 		break;
376 
377 	case GDMA_CQ:
378 		e.cq.id = qid;
379 		e.cq.tail_ptr = tail_ptr;
380 		e.cq.arm = num_req;
381 
382 		addr = (char *)addr + DOORBELL_OFFSET_CQ;
383 		break;
384 
385 	case GDMA_RQ:
386 		e.rq.id = qid;
387 		e.rq.tail_ptr = tail_ptr;
388 		e.rq.wqe_cnt = num_req;
389 
390 		addr = (char *)addr + DOORBELL_OFFSET_RQ;
391 		break;
392 
393 	case GDMA_SQ:
394 		e.sq.id = qid;
395 		e.sq.tail_ptr = tail_ptr;
396 
397 		addr = (char *)addr + DOORBELL_OFFSET_SQ;
398 		break;
399 
400 	default:
401 		mana_warn(NULL, "Invalid queue type 0x%x\n", q_type);
402 		return;
403 	}
404 
405 	/* Ensure all writes are done before ring doorbell */
406 	wmb();
407 
408 #if defined(__amd64__)
409 	writeq(addr, e.as_uint64);
410 #else
411 	uint32_t *p = (uint32_t *)&e.as_uint64;
412 	writel(addr, *p);
413 	writel((char *)addr + 4, *(p + 1));
414 #endif
415 }
416 
417 void
418 mana_gd_wq_ring_doorbell(struct gdma_context *gc, struct gdma_queue *queue)
419 {
420 	mana_gd_ring_doorbell(gc, queue->gdma_dev->doorbell, queue->type,
421 	    queue->id, queue->head * GDMA_WQE_BU_SIZE, 1);
422 }
423 
424 void
425 mana_gd_ring_cq(struct gdma_queue *cq, uint8_t arm_bit)
426 {
427 	struct gdma_context *gc = cq->gdma_dev->gdma_context;
428 
429 	uint32_t num_cqe = cq->queue_size / GDMA_CQE_SIZE;
430 
431 	uint32_t head = cq->head % (num_cqe << GDMA_CQE_OWNER_BITS);
432 
433 	mana_gd_ring_doorbell(gc, cq->gdma_dev->doorbell, cq->type, cq->id,
434 	    head, arm_bit);
435 }
436 
437 static void
438 mana_gd_process_eqe(struct gdma_queue *eq)
439 {
440 	uint32_t head = eq->head % (eq->queue_size / GDMA_EQE_SIZE);
441 	struct gdma_context *gc = eq->gdma_dev->gdma_context;
442 	struct gdma_eqe *eq_eqe_ptr = eq->queue_mem_ptr;
443 	union gdma_eqe_info eqe_info;
444 	enum gdma_eqe_type type;
445 	struct gdma_event event;
446 	struct gdma_queue *cq;
447 	struct gdma_eqe *eqe;
448 	uint32_t cq_id;
449 
450 	eqe = &eq_eqe_ptr[head];
451 	eqe_info.as_uint32 = eqe->eqe_info;
452 	type = eqe_info.type;
453 
454 	switch (type) {
455 	case GDMA_EQE_COMPLETION:
456 		cq_id = eqe->details[0] & 0xFFFFFF;
457 		if (cq_id >= gc->max_num_cqs) {
458 			mana_warn(NULL,
459 			    "failed: cq_id %u > max_num_cqs %u\n",
460 			    cq_id, gc->max_num_cqs);
461 			break;
462 		}
463 
464 		cq = gc->cq_table[cq_id];
465 		if (!cq || cq->type != GDMA_CQ || cq->id != cq_id) {
466 			mana_warn(NULL,
467 			    "failed: invalid cq_id %u\n", cq_id);
468 			break;
469 		}
470 
471 		if (cq->cq.callback)
472 			cq->cq.callback(cq->cq.context, cq);
473 
474 		break;
475 
476 	case GDMA_EQE_TEST_EVENT:
477 		gc->test_event_eq_id = eq->id;
478 
479 		mana_dbg(NULL,
480 		    "EQE TEST EVENT received for EQ %u\n", eq->id);
481 
482 		complete(&gc->eq_test_event);
483 		break;
484 
485 	case GDMA_EQE_HWC_INIT_EQ_ID_DB:
486 	case GDMA_EQE_HWC_INIT_DATA:
487 	case GDMA_EQE_HWC_INIT_DONE:
488 		if (!eq->eq.callback)
489 			break;
490 
491 		event.type = type;
492 		memcpy(&event.details, &eqe->details, GDMA_EVENT_DATA_SIZE);
493 		eq->eq.callback(eq->eq.context, eq, &event);
494 		break;
495 
496 	default:
497 		break;
498 	}
499 }
500 
501 static void
502 mana_gd_process_eq_events(void *arg)
503 {
504 	uint32_t owner_bits, new_bits, old_bits;
505 	union gdma_eqe_info eqe_info;
506 	struct gdma_eqe *eq_eqe_ptr;
507 	struct gdma_queue *eq = arg;
508 	struct gdma_context *gc;
509 	uint32_t head, num_eqe;
510 	struct gdma_eqe *eqe;
511 	int i, j;
512 
513 	gc = eq->gdma_dev->gdma_context;
514 
515 	num_eqe = eq->queue_size / GDMA_EQE_SIZE;
516 	eq_eqe_ptr = eq->queue_mem_ptr;
517 
518 	bus_dmamap_sync(eq->mem_info.dma_tag, eq->mem_info.dma_map,
519 	    BUS_DMASYNC_POSTREAD);
520 
521 	/* Process up to 5 EQEs at a time, and update the HW head. */
522 	for (i = 0; i < 5; i++) {
523 		eqe = &eq_eqe_ptr[eq->head % num_eqe];
524 		eqe_info.as_uint32 = eqe->eqe_info;
525 		owner_bits = eqe_info.owner_bits;
526 
527 		old_bits = (eq->head / num_eqe - 1) & GDMA_EQE_OWNER_MASK;
528 
529 		/* No more entries */
530 		if (owner_bits == old_bits)
531 			break;
532 
533 		new_bits = (eq->head / num_eqe) & GDMA_EQE_OWNER_MASK;
534 		if (owner_bits != new_bits) {
535 			/* Something wrong. Log for debugging purpose */
536 			device_printf(gc->dev,
537 			    "EQ %d: overflow detected, "
538 			    "i = %d, eq->head = %u "
539 			    "got owner_bits = %u, new_bits = %u "
540 			    "eqe addr %p, eqe->eqe_info 0x%x, "
541 			    "eqe type = %x, reserved1 = %x, client_id = %x, "
542 			    "reserved2 = %x, owner_bits = %x\n",
543 			    eq->id, i, eq->head,
544 			    owner_bits, new_bits,
545 			    eqe, eqe->eqe_info,
546 			    eqe_info.type, eqe_info.reserved1,
547 			    eqe_info.client_id, eqe_info.reserved2,
548 			    eqe_info.owner_bits);
549 
550 			uint32_t *eqe_dump = (uint32_t *) eq_eqe_ptr;
551 			for (j = 0; j < 20; j++) {
552 				device_printf(gc->dev, "%p: %x\t%x\t%x\t%x\n",
553 				    &eqe_dump[j * 4], eqe_dump[j * 4], eqe_dump[j * 4 + 1],
554 				    eqe_dump[j * 4 + 2], eqe_dump[j * 4 + 3]);
555 			}
556 			break;
557 		}
558 
559 		rmb();
560 
561 		mana_gd_process_eqe(eq);
562 
563 		eq->head++;
564 	}
565 
566 	bus_dmamap_sync(eq->mem_info.dma_tag, eq->mem_info.dma_map,
567 	    BUS_DMASYNC_PREREAD);
568 
569 	head = eq->head % (num_eqe << GDMA_EQE_OWNER_BITS);
570 
571 	mana_gd_ring_doorbell(gc, eq->gdma_dev->doorbell, eq->type, eq->id,
572 	    head, SET_ARM_BIT);
573 }
574 
575 static int
576 mana_gd_register_irq(struct gdma_queue *queue,
577     const struct gdma_queue_spec *spec)
578 {
579 	struct gdma_dev *gd = queue->gdma_dev;
580 	struct gdma_irq_context *gic;
581 	struct gdma_context *gc;
582 	struct gdma_resource *r;
583 	unsigned int msi_index;
584 	int err;
585 
586 	gc = gd->gdma_context;
587 	r = &gc->msix_resource;
588 
589 	mtx_lock_spin(&r->lock_spin);
590 
591 	msi_index = find_first_zero_bit(r->map, r->size);
592 	if (msi_index >= r->size) {
593 		err = ENOSPC;
594 	} else {
595 		bitmap_set(r->map, msi_index, 1);
596 		queue->eq.msix_index = msi_index;
597 		err = 0;
598 	}
599 
600 	mtx_unlock_spin(&r->lock_spin);
601 
602 	if (err)
603 		return err;
604 
605 	if (unlikely(msi_index >= gc->num_msix_usable)) {
606 		device_printf(gc->dev,
607 		    "chose an invalid msix index %d, usable %d\n",
608 		    msi_index, gc->num_msix_usable);
609 		return ENOSPC;
610 	}
611 
612 	gic = &gc->irq_contexts[msi_index];
613 
614 	if (unlikely(gic->handler || gic->arg)) {
615 		device_printf(gc->dev,
616 		    "interrupt handler or arg already assigned, "
617 		    "msix index: %d\n", msi_index);
618 	}
619 
620 	gic->arg = queue;
621 
622 	gic->handler = mana_gd_process_eq_events;
623 
624 	mana_dbg(NULL, "registered msix index %d vector %d irq %ju\n",
625 	    msi_index, gic->msix_e.vector, rman_get_start(gic->res));
626 
627 	return 0;
628 }
629 
630 static void
631 mana_gd_deregiser_irq(struct gdma_queue *queue)
632 {
633 	struct gdma_dev *gd = queue->gdma_dev;
634 	struct gdma_irq_context *gic;
635 	struct gdma_context *gc;
636 	struct gdma_resource *r;
637 	unsigned int msix_index;
638 
639 	gc = gd->gdma_context;
640 	r = &gc->msix_resource;
641 
642 	/* At most num_online_cpus() + 1 interrupts are used. */
643 	msix_index = queue->eq.msix_index;
644 	if (unlikely(msix_index >= gc->num_msix_usable))
645 		return;
646 
647 	gic = &gc->irq_contexts[msix_index];
648 	gic->handler = NULL;
649 	gic->arg = NULL;
650 
651 	mtx_lock_spin(&r->lock_spin);
652 	bitmap_clear(r->map, msix_index, 1);
653 	mtx_unlock_spin(&r->lock_spin);
654 
655 	queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
656 
657 	mana_dbg(NULL, "deregistered msix index %d vector %d irq %ju\n",
658 	    msix_index, gic->msix_e.vector, rman_get_start(gic->res));
659 }
660 
661 int
662 mana_gd_test_eq(struct gdma_context *gc, struct gdma_queue *eq)
663 {
664 	struct gdma_generate_test_event_req req = {};
665 	struct gdma_general_resp resp = {};
666 	device_t dev = gc->dev;
667 	int err;
668 
669 	sx_xlock(&gc->eq_test_event_sx);
670 
671 	init_completion(&gc->eq_test_event);
672 	gc->test_event_eq_id = INVALID_QUEUE_ID;
673 
674 	mana_gd_init_req_hdr(&req.hdr, GDMA_GENERATE_TEST_EQE,
675 			     sizeof(req), sizeof(resp));
676 
677 	req.hdr.dev_id = eq->gdma_dev->dev_id;
678 	req.queue_index = eq->id;
679 
680 	err = mana_gd_send_request(gc, sizeof(req), &req,
681 	    sizeof(resp), &resp);
682 	if (err) {
683 		device_printf(dev, "test_eq failed: %d\n", err);
684 		goto out;
685 	}
686 
687 	err = EPROTO;
688 
689 	if (resp.hdr.status) {
690 		device_printf(dev, "test_eq failed: 0x%x\n",
691 		    resp.hdr.status);
692 		goto out;
693 	}
694 
695 	if (wait_for_completion_timeout(&gc->eq_test_event, 30 * hz)) {
696 		device_printf(dev, "test_eq timed out on queue %d\n",
697 		    eq->id);
698 		goto out;
699 	}
700 
701 	if (eq->id != gc->test_event_eq_id) {
702 		device_printf(dev,
703 		    "test_eq got an event on wrong queue %d (%d)\n",
704 		    gc->test_event_eq_id, eq->id);
705 		goto out;
706 	}
707 
708 	err = 0;
709 out:
710 	sx_xunlock(&gc->eq_test_event_sx);
711 	return err;
712 }
713 
714 static void
715 mana_gd_destroy_eq(struct gdma_context *gc, bool flush_evenets,
716     struct gdma_queue *queue)
717 {
718 	int err;
719 
720 	if (flush_evenets) {
721 		err = mana_gd_test_eq(gc, queue);
722 		if (err)
723 			device_printf(gc->dev,
724 			    "Failed to flush EQ: %d\n", err);
725 	}
726 
727 	mana_gd_deregiser_irq(queue);
728 
729 	if (queue->eq.disable_needed)
730 		mana_gd_disable_queue(queue);
731 }
732 
733 static int mana_gd_create_eq(struct gdma_dev *gd,
734     const struct gdma_queue_spec *spec,
735     bool create_hwq, struct gdma_queue *queue)
736 {
737 	struct gdma_context *gc = gd->gdma_context;
738 	device_t dev = gc->dev;
739 	uint32_t log2_num_entries;
740 	int err;
741 
742 	queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
743 
744 	log2_num_entries = ilog2(queue->queue_size / GDMA_EQE_SIZE);
745 
746 	if (spec->eq.log2_throttle_limit > log2_num_entries) {
747 		device_printf(dev,
748 		    "EQ throttling limit (%lu) > maximum EQE (%u)\n",
749 		    spec->eq.log2_throttle_limit, log2_num_entries);
750 		return EINVAL;
751 	}
752 
753 	err = mana_gd_register_irq(queue, spec);
754 	if (err) {
755 		device_printf(dev, "Failed to register irq: %d\n", err);
756 		return err;
757 	}
758 
759 	queue->eq.callback = spec->eq.callback;
760 	queue->eq.context = spec->eq.context;
761 	queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
762 	queue->eq.log2_throttle_limit = spec->eq.log2_throttle_limit ?: 1;
763 
764 	if (create_hwq) {
765 		err = mana_gd_create_hw_eq(gc, queue);
766 		if (err)
767 			goto out;
768 
769 		err = mana_gd_test_eq(gc, queue);
770 		if (err)
771 			goto out;
772 	}
773 
774 	return 0;
775 out:
776 	device_printf(dev, "Failed to create EQ: %d\n", err);
777 	mana_gd_destroy_eq(gc, false, queue);
778 	return err;
779 }
780 
781 static void
782 mana_gd_create_cq(const struct gdma_queue_spec *spec,
783     struct gdma_queue *queue)
784 {
785 	uint32_t log2_num_entries = ilog2(spec->queue_size / GDMA_CQE_SIZE);
786 
787 	queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
788 	queue->cq.parent = spec->cq.parent_eq;
789 	queue->cq.context = spec->cq.context;
790 	queue->cq.callback = spec->cq.callback;
791 }
792 
793 static void
794 mana_gd_destroy_cq(struct gdma_context *gc,
795     struct gdma_queue *queue)
796 {
797 	uint32_t id = queue->id;
798 
799 	if (id >= gc->max_num_cqs)
800 		return;
801 
802 	if (!gc->cq_table[id])
803 		return;
804 
805 	gc->cq_table[id] = NULL;
806 }
807 
808 int mana_gd_create_hwc_queue(struct gdma_dev *gd,
809     const struct gdma_queue_spec *spec,
810     struct gdma_queue **queue_ptr)
811 {
812 	struct gdma_context *gc = gd->gdma_context;
813 	struct gdma_mem_info *gmi;
814 	struct gdma_queue *queue;
815 	int err;
816 
817 	queue = malloc(sizeof(*queue), M_DEVBUF, M_WAITOK | M_ZERO);
818 	if (!queue)
819 		return ENOMEM;
820 
821 	gmi = &queue->mem_info;
822 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
823 	if (err)
824 		goto free_q;
825 
826 	queue->head = 0;
827 	queue->tail = 0;
828 	queue->queue_mem_ptr = gmi->virt_addr;
829 	queue->queue_size = spec->queue_size;
830 	queue->monitor_avl_buf = spec->monitor_avl_buf;
831 	queue->type = spec->type;
832 	queue->gdma_dev = gd;
833 
834 	if (spec->type == GDMA_EQ)
835 		err = mana_gd_create_eq(gd, spec, false, queue);
836 	else if (spec->type == GDMA_CQ)
837 		mana_gd_create_cq(spec, queue);
838 
839 	if (err)
840 		goto out;
841 
842 	*queue_ptr = queue;
843 	return 0;
844 out:
845 	mana_gd_free_memory(gmi);
846 free_q:
847 	free(queue, M_DEVBUF);
848 	return err;
849 }
850 
851 static void
852 mana_gd_destroy_dma_region(struct gdma_context *gc, uint64_t gdma_region)
853 {
854 	struct gdma_destroy_dma_region_req req = {};
855 	struct gdma_general_resp resp = {};
856 	int err;
857 
858 	if (gdma_region == GDMA_INVALID_DMA_REGION)
859 		return;
860 
861 	mana_gd_init_req_hdr(&req.hdr, GDMA_DESTROY_DMA_REGION, sizeof(req),
862 	    sizeof(resp));
863 	req.gdma_region = gdma_region;
864 
865 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp),
866 	    &resp);
867 	if (err || resp.hdr.status)
868 		device_printf(gc->dev,
869 		    "Failed to destroy DMA region: %d, 0x%x\n",
870 		    err, resp.hdr.status);
871 }
872 
873 static int
874 mana_gd_create_dma_region(struct gdma_dev *gd,
875     struct gdma_mem_info *gmi)
876 {
877 	unsigned int num_page = gmi->length / PAGE_SIZE;
878 	struct gdma_create_dma_region_req *req = NULL;
879 	struct gdma_create_dma_region_resp resp = {};
880 	struct gdma_context *gc = gd->gdma_context;
881 	struct hw_channel_context *hwc;
882 	uint32_t length = gmi->length;
883 	uint32_t req_msg_size;
884 	int err;
885 	int i;
886 
887 	if (length < PAGE_SIZE || !is_power_of_2(length)) {
888 		mana_err(NULL, "gmi size incorrect: %u\n", length);
889 		return EINVAL;
890 	}
891 
892 	if (offset_in_page((uint64_t)gmi->virt_addr) != 0) {
893 		mana_err(NULL, "gmi not page aligned: %p\n",
894 		    gmi->virt_addr);
895 		return EINVAL;
896 	}
897 
898 	hwc = gc->hwc.driver_data;
899 	req_msg_size = sizeof(*req) + num_page * sizeof(uint64_t);
900 	if (req_msg_size > hwc->max_req_msg_size) {
901 		mana_err(NULL, "req msg size too large: %u, %u\n",
902 		    req_msg_size, hwc->max_req_msg_size);
903 		return EINVAL;
904 	}
905 
906 	req = malloc(req_msg_size, M_DEVBUF, M_WAITOK | M_ZERO);
907 	if (!req)
908 		return ENOMEM;
909 
910 	mana_gd_init_req_hdr(&req->hdr, GDMA_CREATE_DMA_REGION,
911 	    req_msg_size, sizeof(resp));
912 	req->length = length;
913 	req->offset_in_page = 0;
914 	req->gdma_page_type = GDMA_PAGE_TYPE_4K;
915 	req->page_count = num_page;
916 	req->page_addr_list_len = num_page;
917 
918 	for (i = 0; i < num_page; i++)
919 		req->page_addr_list[i] = gmi->dma_handle +  i * PAGE_SIZE;
920 
921 	err = mana_gd_send_request(gc, req_msg_size, req, sizeof(resp), &resp);
922 	if (err)
923 		goto out;
924 
925 	if (resp.hdr.status || resp.gdma_region == GDMA_INVALID_DMA_REGION) {
926 		device_printf(gc->dev, "Failed to create DMA region: 0x%x\n",
927 			resp.hdr.status);
928 		err = EPROTO;
929 		goto out;
930 	}
931 
932 	gmi->gdma_region = resp.gdma_region;
933 out:
934 	free(req, M_DEVBUF);
935 	return err;
936 }
937 
938 int
939 mana_gd_create_mana_eq(struct gdma_dev *gd,
940     const struct gdma_queue_spec *spec,
941     struct gdma_queue **queue_ptr)
942 {
943 	struct gdma_context *gc = gd->gdma_context;
944 	struct gdma_mem_info *gmi;
945 	struct gdma_queue *queue;
946 	int err;
947 
948 	if (spec->type != GDMA_EQ)
949 		return EINVAL;
950 
951 	queue = malloc(sizeof(*queue),  M_DEVBUF, M_WAITOK | M_ZERO);
952 	if (!queue)
953 		return ENOMEM;
954 
955 	gmi = &queue->mem_info;
956 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
957 	if (err)
958 		goto free_q;
959 
960 	err = mana_gd_create_dma_region(gd, gmi);
961 	if (err)
962 		goto out;
963 
964 	queue->head = 0;
965 	queue->tail = 0;
966 	queue->queue_mem_ptr = gmi->virt_addr;
967 	queue->queue_size = spec->queue_size;
968 	queue->monitor_avl_buf = spec->monitor_avl_buf;
969 	queue->type = spec->type;
970 	queue->gdma_dev = gd;
971 
972 	err = mana_gd_create_eq(gd, spec, true, queue);
973 	if (err)
974 		goto out;
975 
976 	*queue_ptr = queue;
977 	return 0;
978 
979 out:
980 	mana_gd_free_memory(gmi);
981 free_q:
982 	free(queue, M_DEVBUF);
983 	return err;
984 }
985 
986 int mana_gd_create_mana_wq_cq(struct gdma_dev *gd,
987     const struct gdma_queue_spec *spec,
988     struct gdma_queue **queue_ptr)
989 {
990 	struct gdma_context *gc = gd->gdma_context;
991 	struct gdma_mem_info *gmi;
992 	struct gdma_queue *queue;
993 	int err;
994 
995 	if (spec->type != GDMA_CQ && spec->type != GDMA_SQ &&
996 	    spec->type != GDMA_RQ)
997 		return EINVAL;
998 
999 	queue = malloc(sizeof(*queue), M_DEVBUF, M_WAITOK | M_ZERO);
1000 	if (!queue)
1001 		return ENOMEM;
1002 
1003 	gmi = &queue->mem_info;
1004 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
1005 	if (err)
1006 		goto free_q;
1007 
1008 	err = mana_gd_create_dma_region(gd, gmi);
1009 	if (err)
1010 		goto out;
1011 
1012 	queue->head = 0;
1013 	queue->tail = 0;
1014 	queue->queue_mem_ptr = gmi->virt_addr;
1015 	queue->queue_size = spec->queue_size;
1016 	queue->monitor_avl_buf = spec->monitor_avl_buf;
1017 	queue->type = spec->type;
1018 	queue->gdma_dev = gd;
1019 
1020 	if (spec->type == GDMA_CQ)
1021 		mana_gd_create_cq(spec, queue);
1022 
1023 	*queue_ptr = queue;
1024 	return 0;
1025 
1026 out:
1027 	mana_gd_free_memory(gmi);
1028 free_q:
1029 	free(queue, M_DEVBUF);
1030 	return err;
1031 }
1032 
1033 void
1034 mana_gd_destroy_queue(struct gdma_context *gc, struct gdma_queue *queue)
1035 {
1036 	struct gdma_mem_info *gmi = &queue->mem_info;
1037 
1038 	switch (queue->type) {
1039 	case GDMA_EQ:
1040 		mana_gd_destroy_eq(gc, queue->eq.disable_needed, queue);
1041 		break;
1042 
1043 	case GDMA_CQ:
1044 		mana_gd_destroy_cq(gc, queue);
1045 		break;
1046 
1047 	case GDMA_RQ:
1048 		break;
1049 
1050 	case GDMA_SQ:
1051 		break;
1052 
1053 	default:
1054 		device_printf(gc->dev,
1055 		    "Can't destroy unknown queue: type = %d\n",
1056 		    queue->type);
1057 		return;
1058 	}
1059 
1060 	mana_gd_destroy_dma_region(gc, gmi->gdma_region);
1061 	mana_gd_free_memory(gmi);
1062 	free(queue, M_DEVBUF);
1063 }
1064 
1065 #define OS_MAJOR_DIV		100000
1066 #define OS_BUILD_MOD		1000
1067 
1068 int
1069 mana_gd_verify_vf_version(device_t dev)
1070 {
1071 	struct gdma_context *gc = device_get_softc(dev);
1072 	struct gdma_verify_ver_resp resp = {};
1073 	struct gdma_verify_ver_req req = {};
1074 	int err;
1075 
1076 	mana_gd_init_req_hdr(&req.hdr, GDMA_VERIFY_VF_DRIVER_VERSION,
1077 	    sizeof(req), sizeof(resp));
1078 
1079 	req.protocol_ver_min = GDMA_PROTOCOL_FIRST;
1080 	req.protocol_ver_max = GDMA_PROTOCOL_LAST;
1081 
1082 	req.drv_ver = 0;	/* Unused */
1083 	req.os_type = 0x30;	/* Other */
1084 	req.os_ver_major = osreldate / OS_MAJOR_DIV;
1085 	req.os_ver_minor = (osreldate % OS_MAJOR_DIV) / OS_BUILD_MOD;
1086 	req.os_ver_build = osreldate % OS_BUILD_MOD;
1087 	strncpy(req.os_ver_str1, ostype, sizeof(req.os_ver_str1) - 1);
1088 	strncpy(req.os_ver_str2, osrelease, sizeof(req.os_ver_str2) - 1);
1089 
1090 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1091 	if (err || resp.hdr.status) {
1092 		device_printf(gc->dev,
1093 		    "VfVerifyVersionOutput: %d, status=0x%x\n",
1094 		    err, resp.hdr.status);
1095 		return err ? err : EPROTO;
1096 	}
1097 
1098 	return 0;
1099 }
1100 
1101 int
1102 mana_gd_register_device(struct gdma_dev *gd)
1103 {
1104 	struct gdma_context *gc = gd->gdma_context;
1105 	struct gdma_register_device_resp resp = {};
1106 	struct gdma_general_req req = {};
1107 	int err;
1108 
1109 	gd->pdid = INVALID_PDID;
1110 	gd->doorbell = INVALID_DOORBELL;
1111 	gd->gpa_mkey = INVALID_MEM_KEY;
1112 
1113 	mana_gd_init_req_hdr(&req.hdr, GDMA_REGISTER_DEVICE, sizeof(req),
1114 	    sizeof(resp));
1115 
1116 	req.hdr.dev_id = gd->dev_id;
1117 
1118 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1119 	if (err || resp.hdr.status) {
1120 		device_printf(gc->dev,
1121 		    "gdma_register_device_resp failed: %d, 0x%x\n",
1122 		    err, resp.hdr.status);
1123 		return err ? err : -EPROTO;
1124 	}
1125 
1126 	gd->pdid = resp.pdid;
1127 	gd->gpa_mkey = resp.gpa_mkey;
1128 	gd->doorbell = resp.db_id;
1129 
1130 	mana_dbg(NULL, "mana device pdid %u, gpa_mkey %u, doorbell %u \n",
1131 	    gd->pdid, gd->gpa_mkey, gd->doorbell);
1132 
1133 	return 0;
1134 }
1135 
1136 int
1137 mana_gd_deregister_device(struct gdma_dev *gd)
1138 {
1139 	struct gdma_context *gc = gd->gdma_context;
1140 	struct gdma_general_resp resp = {};
1141 	struct gdma_general_req req = {};
1142 	int err;
1143 
1144 	if (gd->pdid == INVALID_PDID)
1145 		return EINVAL;
1146 
1147 	mana_gd_init_req_hdr(&req.hdr, GDMA_DEREGISTER_DEVICE, sizeof(req),
1148 	    sizeof(resp));
1149 
1150 	req.hdr.dev_id = gd->dev_id;
1151 
1152 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1153 	if (err || resp.hdr.status) {
1154 		device_printf(gc->dev,
1155 		    "Failed to deregister device: %d, 0x%x\n",
1156 		    err, resp.hdr.status);
1157 		if (!err)
1158 			err = EPROTO;
1159 	}
1160 
1161 	gd->pdid = INVALID_PDID;
1162 	gd->doorbell = INVALID_DOORBELL;
1163 	gd->gpa_mkey = INVALID_MEM_KEY;
1164 
1165 	return err;
1166 }
1167 
1168 uint32_t
1169 mana_gd_wq_avail_space(struct gdma_queue *wq)
1170 {
1171 	uint32_t used_space = (wq->head - wq->tail) * GDMA_WQE_BU_SIZE;
1172 	uint32_t wq_size = wq->queue_size;
1173 
1174 	if (used_space > wq_size) {
1175 		mana_warn(NULL, "failed: used space %u > queue size %u\n",
1176 		    used_space, wq_size);
1177 	}
1178 
1179 	return wq_size - used_space;
1180 }
1181 
1182 uint8_t *
1183 mana_gd_get_wqe_ptr(const struct gdma_queue *wq, uint32_t wqe_offset)
1184 {
1185 	uint32_t offset =
1186 	    (wqe_offset * GDMA_WQE_BU_SIZE) & (wq->queue_size - 1);
1187 
1188 	if ((offset + GDMA_WQE_BU_SIZE) > wq->queue_size) {
1189 		mana_warn(NULL, "failed: write end out of queue bound %u, "
1190 		    "queue size %u\n",
1191 		    offset + GDMA_WQE_BU_SIZE, wq->queue_size);
1192 	}
1193 
1194 	return (uint8_t *)wq->queue_mem_ptr + offset;
1195 }
1196 
1197 static uint32_t
1198 mana_gd_write_client_oob(const struct gdma_wqe_request *wqe_req,
1199     enum gdma_queue_type q_type,
1200     uint32_t client_oob_size, uint32_t sgl_data_size,
1201     uint8_t *wqe_ptr)
1202 {
1203 	bool oob_in_sgl = !!(wqe_req->flags & GDMA_WR_OOB_IN_SGL);
1204 	bool pad_data = !!(wqe_req->flags & GDMA_WR_PAD_BY_SGE0);
1205 	struct gdma_wqe *header = (struct gdma_wqe *)wqe_ptr;
1206 	uint8_t *ptr;
1207 
1208 	memset(header, 0, sizeof(struct gdma_wqe));
1209 	header->num_sge = wqe_req->num_sge;
1210 	header->inline_oob_size_div4 = client_oob_size / sizeof(uint32_t);
1211 
1212 	if (oob_in_sgl) {
1213 		if (!pad_data || wqe_req->num_sge < 2) {
1214 			mana_warn(NULL, "no pad_data or num_sge < 2\n");
1215 		}
1216 
1217 		header->client_oob_in_sgl = 1;
1218 
1219 		if (pad_data)
1220 			header->last_vbytes = wqe_req->sgl[0].size;
1221 	}
1222 
1223 	if (q_type == GDMA_SQ)
1224 		header->client_data_unit = wqe_req->client_data_unit;
1225 
1226 	/*
1227 	 * The size of gdma_wqe + client_oob_size must be less than or equal
1228 	 * to one Basic Unit (i.e. 32 bytes), so the pointer can't go beyond
1229 	 * the queue memory buffer boundary.
1230 	 */
1231 	ptr = wqe_ptr + sizeof(header);
1232 
1233 	if (wqe_req->inline_oob_data && wqe_req->inline_oob_size > 0) {
1234 		memcpy(ptr, wqe_req->inline_oob_data, wqe_req->inline_oob_size);
1235 
1236 		if (client_oob_size > wqe_req->inline_oob_size)
1237 			memset(ptr + wqe_req->inline_oob_size, 0,
1238 			       client_oob_size - wqe_req->inline_oob_size);
1239 	}
1240 
1241 	return sizeof(header) + client_oob_size;
1242 }
1243 
1244 static void
1245 mana_gd_write_sgl(struct gdma_queue *wq, uint8_t *wqe_ptr,
1246     const struct gdma_wqe_request *wqe_req)
1247 {
1248 	uint32_t sgl_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
1249 	const uint8_t *address = (uint8_t *)wqe_req->sgl;
1250 	uint8_t *base_ptr, *end_ptr;
1251 	uint32_t size_to_end;
1252 
1253 	base_ptr = wq->queue_mem_ptr;
1254 	end_ptr = base_ptr + wq->queue_size;
1255 	size_to_end = (uint32_t)(end_ptr - wqe_ptr);
1256 
1257 	if (size_to_end < sgl_size) {
1258 		memcpy(wqe_ptr, address, size_to_end);
1259 
1260 		wqe_ptr = base_ptr;
1261 		address += size_to_end;
1262 		sgl_size -= size_to_end;
1263 	}
1264 
1265 	memcpy(wqe_ptr, address, sgl_size);
1266 }
1267 
1268 int
1269 mana_gd_post_work_request(struct gdma_queue *wq,
1270     const struct gdma_wqe_request *wqe_req,
1271     struct gdma_posted_wqe_info *wqe_info)
1272 {
1273 	uint32_t client_oob_size = wqe_req->inline_oob_size;
1274 	struct gdma_context *gc;
1275 	uint32_t sgl_data_size;
1276 	uint32_t max_wqe_size;
1277 	uint32_t wqe_size;
1278 	uint8_t *wqe_ptr;
1279 
1280 	if (wqe_req->num_sge == 0)
1281 		return EINVAL;
1282 
1283 	if (wq->type == GDMA_RQ) {
1284 		if (client_oob_size != 0)
1285 			return EINVAL;
1286 
1287 		client_oob_size = INLINE_OOB_SMALL_SIZE;
1288 
1289 		max_wqe_size = GDMA_MAX_RQE_SIZE;
1290 	} else {
1291 		if (client_oob_size != INLINE_OOB_SMALL_SIZE &&
1292 		    client_oob_size != INLINE_OOB_LARGE_SIZE)
1293 			return EINVAL;
1294 
1295 		max_wqe_size = GDMA_MAX_SQE_SIZE;
1296 	}
1297 
1298 	sgl_data_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
1299 	wqe_size = ALIGN(sizeof(struct gdma_wqe) + client_oob_size +
1300 	    sgl_data_size, GDMA_WQE_BU_SIZE);
1301 	if (wqe_size > max_wqe_size)
1302 		return EINVAL;
1303 
1304 	if (wq->monitor_avl_buf && wqe_size > mana_gd_wq_avail_space(wq)) {
1305 		gc = wq->gdma_dev->gdma_context;
1306 		device_printf(gc->dev, "unsuccessful flow control!\n");
1307 		return ENOSPC;
1308 	}
1309 
1310 	if (wqe_info)
1311 		wqe_info->wqe_size_in_bu = wqe_size / GDMA_WQE_BU_SIZE;
1312 
1313 	wqe_ptr = mana_gd_get_wqe_ptr(wq, wq->head);
1314 	wqe_ptr += mana_gd_write_client_oob(wqe_req, wq->type, client_oob_size,
1315 	    sgl_data_size, wqe_ptr);
1316 	if (wqe_ptr >= (uint8_t *)wq->queue_mem_ptr + wq->queue_size)
1317 		wqe_ptr -= wq->queue_size;
1318 
1319 	mana_gd_write_sgl(wq, wqe_ptr, wqe_req);
1320 
1321 	wq->head += wqe_size / GDMA_WQE_BU_SIZE;
1322 
1323 	bus_dmamap_sync(wq->mem_info.dma_tag, wq->mem_info.dma_map,
1324 	    BUS_DMASYNC_PREWRITE);
1325 
1326 	return 0;
1327 }
1328 
1329 int
1330 mana_gd_post_and_ring(struct gdma_queue *queue,
1331     const struct gdma_wqe_request *wqe_req,
1332     struct gdma_posted_wqe_info *wqe_info)
1333 {
1334 	struct gdma_context *gc = queue->gdma_dev->gdma_context;
1335 	int err;
1336 
1337 	err = mana_gd_post_work_request(queue, wqe_req, wqe_info);
1338 	if (err)
1339 		return err;
1340 
1341 	mana_gd_wq_ring_doorbell(gc, queue);
1342 
1343 	return 0;
1344 }
1345 
1346 static int
1347 mana_gd_read_cqe(struct gdma_queue *cq, struct gdma_comp *comp)
1348 {
1349 	unsigned int num_cqe = cq->queue_size / sizeof(struct gdma_cqe);
1350 	struct gdma_cqe *cq_cqe = cq->queue_mem_ptr;
1351 	uint32_t owner_bits, new_bits, old_bits;
1352 	struct gdma_cqe *cqe;
1353 
1354 	cqe = &cq_cqe[cq->head % num_cqe];
1355 	owner_bits = cqe->cqe_info.owner_bits;
1356 
1357 	old_bits = (cq->head / num_cqe - 1) & GDMA_CQE_OWNER_MASK;
1358 	/* Return 0 if no more entries. */
1359 	if (owner_bits == old_bits)
1360 		return 0;
1361 
1362 	new_bits = (cq->head / num_cqe) & GDMA_CQE_OWNER_MASK;
1363 	/* Return -1 if overflow detected. */
1364 	if (owner_bits != new_bits) {
1365 		mana_warn(NULL,
1366 		    "overflow detected! owner_bits %u != new_bits %u\n",
1367 		    owner_bits, new_bits);
1368 		return -1;
1369 	}
1370 
1371 	rmb();
1372 
1373 	comp->wq_num = cqe->cqe_info.wq_num;
1374 	comp->is_sq = cqe->cqe_info.is_sq;
1375 	memcpy(comp->cqe_data, cqe->cqe_data, GDMA_COMP_DATA_SIZE);
1376 
1377 	return 1;
1378 }
1379 
1380 int
1381 mana_gd_poll_cq(struct gdma_queue *cq, struct gdma_comp *comp, int num_cqe)
1382 {
1383 	int cqe_idx;
1384 	int ret;
1385 
1386 	bus_dmamap_sync(cq->mem_info.dma_tag, cq->mem_info.dma_map,
1387 	    BUS_DMASYNC_POSTREAD);
1388 
1389 	for (cqe_idx = 0; cqe_idx < num_cqe; cqe_idx++) {
1390 		ret = mana_gd_read_cqe(cq, &comp[cqe_idx]);
1391 
1392 		if (ret < 0) {
1393 			cq->head -= cqe_idx;
1394 			return ret;
1395 		}
1396 
1397 		if (ret == 0)
1398 			break;
1399 
1400 		cq->head++;
1401 	}
1402 
1403 	return cqe_idx;
1404 }
1405 
1406 static void
1407 mana_gd_intr(void *arg)
1408 {
1409 	struct gdma_irq_context *gic = arg;
1410 
1411 	if (gic->handler) {
1412 		gic->handler(gic->arg);
1413 	}
1414 }
1415 
1416 int
1417 mana_gd_alloc_res_map(uint32_t res_avail,
1418     struct gdma_resource *r, const char *lock_name)
1419 {
1420 	int n = howmany(res_avail, BITS_PER_LONG);
1421 
1422 	r->map =
1423 	    malloc(n * sizeof(unsigned long), M_DEVBUF, M_WAITOK | M_ZERO);
1424 	if (!r->map)
1425 		return ENOMEM;
1426 
1427 	r->size = res_avail;
1428 	mtx_init(&r->lock_spin, lock_name, NULL, MTX_SPIN);
1429 
1430 	mana_dbg(NULL,
1431 	    "total res %u, total number of unsigned longs %u\n",
1432 	    r->size, n);
1433 	return (0);
1434 }
1435 
1436 void
1437 mana_gd_free_res_map(struct gdma_resource *r)
1438 {
1439 	if (!r || !r->map)
1440 		return;
1441 
1442 	free(r->map, M_DEVBUF);
1443 	r->map = NULL;
1444 	r->size = 0;
1445 }
1446 
1447 static void
1448 mana_gd_init_registers(struct gdma_context *gc)
1449 {
1450 	uint64_t bar0_va = rman_get_bushandle(gc->bar0);
1451 
1452 	gc->db_page_size = mana_gd_r32(gc, GDMA_REG_DB_PAGE_SIZE) & 0xFFFF;
1453 
1454 	gc->db_page_base =
1455 	    (void *) (bar0_va + mana_gd_r64(gc, GDMA_REG_DB_PAGE_OFFSET));
1456 
1457 	gc->shm_base =
1458 	    (void *) (bar0_va + mana_gd_r64(gc, GDMA_REG_SHM_OFFSET));
1459 
1460 	mana_dbg(NULL, "db_page_size 0x%xx, db_page_base %p,"
1461 		    " shm_base %p\n",
1462 		    gc->db_page_size, gc->db_page_base, gc->shm_base);
1463 }
1464 
1465 static struct resource *
1466 mana_gd_alloc_bar(device_t dev, int bar)
1467 {
1468 	struct resource *res = NULL;
1469 	struct pci_map *pm;
1470 	int rid, type;
1471 
1472 	if (bar < 0 || bar > PCIR_MAX_BAR_0)
1473 		goto alloc_bar_out;
1474 
1475 	pm = pci_find_bar(dev, PCIR_BAR(bar));
1476 	if (!pm)
1477 		goto alloc_bar_out;
1478 
1479 	if (PCI_BAR_IO(pm->pm_value))
1480 		type = SYS_RES_IOPORT;
1481 	else
1482 		type = SYS_RES_MEMORY;
1483 	if (type < 0)
1484 		goto alloc_bar_out;
1485 
1486 	rid = PCIR_BAR(bar);
1487 	res = bus_alloc_resource_any(dev, type, &rid, RF_ACTIVE);
1488 #if defined(__amd64__)
1489 	if (res)
1490 		mana_dbg(NULL, "bar %d: rid 0x%x, type 0x%jx,"
1491 		    " handle 0x%jx\n",
1492 		    bar, rid, res->r_bustag, res->r_bushandle);
1493 #endif
1494 
1495 alloc_bar_out:
1496 	return (res);
1497 }
1498 
1499 static void
1500 mana_gd_free_pci_res(struct gdma_context *gc)
1501 {
1502 	if (!gc || gc->dev)
1503 		return;
1504 
1505 	if (gc->bar0 != NULL) {
1506 		bus_release_resource(gc->dev, SYS_RES_MEMORY,
1507 		    PCIR_BAR(GDMA_BAR0), gc->bar0);
1508 	}
1509 
1510 	if (gc->msix != NULL) {
1511 		bus_release_resource(gc->dev, SYS_RES_MEMORY,
1512 		    gc->msix_rid, gc->msix);
1513 	}
1514 }
1515 
1516 static int
1517 mana_gd_setup_irqs(device_t dev)
1518 {
1519 	unsigned int max_queues_per_port = mp_ncpus;
1520 	struct gdma_context *gc = device_get_softc(dev);
1521 	struct gdma_irq_context *gic;
1522 	unsigned int max_irqs;
1523 	int nvec;
1524 	int rc, rcc, i;
1525 
1526 	if (max_queues_per_port > MANA_MAX_NUM_QUEUES)
1527 		max_queues_per_port = MANA_MAX_NUM_QUEUES;
1528 
1529 	/* Need 1 interrupt for the Hardware communication Channel (HWC) */
1530 	max_irqs = max_queues_per_port + 1;
1531 
1532 	nvec = max_irqs;
1533 	rc = pci_alloc_msix(dev, &nvec);
1534 	if (unlikely(rc != 0)) {
1535 		device_printf(dev,
1536 		    "Failed to allocate MSIX, vectors %d, error: %d\n",
1537 		    nvec, rc);
1538 		rc = ENOSPC;
1539 		goto err_setup_irq_alloc;
1540 	}
1541 
1542 	if (nvec != max_irqs) {
1543 		if (nvec == 1) {
1544 			device_printf(dev,
1545 			    "Not enough number of MSI-x allocated: %d\n",
1546 			    nvec);
1547 			rc = ENOSPC;
1548 			goto err_setup_irq_release;
1549 		}
1550 		device_printf(dev, "Allocated only %d MSI-x (%d requested)\n",
1551 		    nvec, max_irqs);
1552 	}
1553 
1554 	gc->irq_contexts = malloc(nvec * sizeof(struct gdma_irq_context),
1555 	    M_DEVBUF, M_WAITOK | M_ZERO);
1556 	if (!gc->irq_contexts) {
1557 		rc = ENOMEM;
1558 		goto err_setup_irq_release;
1559 	}
1560 
1561 	for (i = 0; i < nvec; i++) {
1562 		gic = &gc->irq_contexts[i];
1563 		gic->msix_e.entry = i;
1564 		/* Vector starts from 1. */
1565 		gic->msix_e.vector = i + 1;
1566 		gic->handler = NULL;
1567 		gic->arg = NULL;
1568 
1569 		gic->res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
1570 		    &gic->msix_e.vector, RF_ACTIVE | RF_SHAREABLE);
1571 		if (unlikely(gic->res == NULL)) {
1572 			rc = ENOMEM;
1573 			device_printf(dev, "could not allocate resource "
1574 			    "for irq vector %d\n", gic->msix_e.vector);
1575 			goto err_setup_irq;
1576 		}
1577 
1578 		rc = bus_setup_intr(dev, gic->res,
1579 		    INTR_TYPE_NET | INTR_MPSAFE, NULL, mana_gd_intr,
1580 		    gic, &gic->cookie);
1581 		if (unlikely(rc != 0)) {
1582 			device_printf(dev, "failed to register interrupt "
1583 			    "handler for irq %ju vector %d: error %d\n",
1584 			    rman_get_start(gic->res), gic->msix_e.vector, rc);
1585 			goto err_setup_irq;
1586 		}
1587 		gic->requested = true;
1588 
1589 		mana_dbg(NULL, "added msix vector %d irq %ju\n",
1590 		    gic->msix_e.vector, rman_get_start(gic->res));
1591 	}
1592 
1593 	rc = mana_gd_alloc_res_map(nvec, &gc->msix_resource,
1594 	    "gdma msix res lock");
1595 	if (rc != 0) {
1596 		device_printf(dev, "failed to allocate memory "
1597 		    "for msix bitmap\n");
1598 		goto err_setup_irq;
1599 	}
1600 
1601 	gc->max_num_msix = nvec;
1602 	gc->num_msix_usable = nvec;
1603 
1604 	mana_dbg(NULL, "setup %d msix interrupts\n", nvec);
1605 
1606 	return (0);
1607 
1608 err_setup_irq:
1609 	for (; i >= 0; i--) {
1610 		gic = &gc->irq_contexts[i];
1611 		rcc = 0;
1612 
1613 		/*
1614 		 * If gic->requested is true, we need to free both intr and
1615 		 * resources.
1616 		 */
1617 		if (gic->requested)
1618 			rcc = bus_teardown_intr(dev, gic->res, gic->cookie);
1619 		if (unlikely(rcc != 0))
1620 			device_printf(dev, "could not release "
1621 			    "irq vector %d, error: %d\n",
1622 			    gic->msix_e.vector, rcc);
1623 
1624 		rcc = 0;
1625 		if (gic->res != NULL) {
1626 			rcc = bus_release_resource(dev, SYS_RES_IRQ,
1627 			    gic->msix_e.vector, gic->res);
1628 		}
1629 		if (unlikely(rcc != 0))
1630 			device_printf(dev, "dev has no parent while "
1631 			    "releasing resource for irq vector %d\n",
1632 			    gic->msix_e.vector);
1633 		gic->requested = false;
1634 		gic->res = NULL;
1635 	}
1636 
1637 	free(gc->irq_contexts, M_DEVBUF);
1638 	gc->irq_contexts = NULL;
1639 err_setup_irq_release:
1640 	pci_release_msi(dev);
1641 err_setup_irq_alloc:
1642 	return (rc);
1643 }
1644 
1645 static void
1646 mana_gd_remove_irqs(device_t dev)
1647 {
1648 	struct gdma_context *gc = device_get_softc(dev);
1649 	struct gdma_irq_context *gic;
1650 	int rc, i;
1651 
1652 	mana_gd_free_res_map(&gc->msix_resource);
1653 
1654 	for (i = 0; i < gc->max_num_msix; i++) {
1655 		gic = &gc->irq_contexts[i];
1656 		if (gic->requested) {
1657 			rc = bus_teardown_intr(dev, gic->res, gic->cookie);
1658 			if (unlikely(rc != 0)) {
1659 				device_printf(dev, "failed to tear down "
1660 				    "irq vector %d, error: %d\n",
1661 				    gic->msix_e.vector, rc);
1662 			}
1663 			gic->requested = false;
1664 		}
1665 
1666 		if (gic->res != NULL) {
1667 			rc = bus_release_resource(dev, SYS_RES_IRQ,
1668 			    gic->msix_e.vector, gic->res);
1669 			if (unlikely(rc != 0)) {
1670 				device_printf(dev, "dev has no parent while "
1671 				    "releasing resource for irq vector %d\n",
1672 				    gic->msix_e.vector);
1673 			}
1674 			gic->res = NULL;
1675 		}
1676 	}
1677 
1678 	gc->max_num_msix = 0;
1679 	gc->num_msix_usable = 0;
1680 	free(gc->irq_contexts, M_DEVBUF);
1681 	gc->irq_contexts = NULL;
1682 
1683 	pci_release_msi(dev);
1684 }
1685 
1686 static int
1687 mana_gd_probe(device_t dev)
1688 {
1689 	mana_vendor_id_t *ent;
1690 	char		adapter_name[60];
1691 	uint16_t	pci_vendor_id = 0;
1692 	uint16_t	pci_device_id = 0;
1693 
1694 	pci_vendor_id = pci_get_vendor(dev);
1695 	pci_device_id = pci_get_device(dev);
1696 
1697 	ent = mana_id_table;
1698 	while (ent->vendor_id != 0) {
1699 		if ((pci_vendor_id == ent->vendor_id) &&
1700 		    (pci_device_id == ent->device_id)) {
1701 			mana_dbg(NULL, "vendor=%x device=%x\n",
1702 			    pci_vendor_id, pci_device_id);
1703 
1704 			sprintf(adapter_name, DEVICE_DESC);
1705 			device_set_desc_copy(dev, adapter_name);
1706 			return (BUS_PROBE_DEFAULT);
1707 		}
1708 
1709 		ent++;
1710 	}
1711 
1712 	return (ENXIO);
1713 }
1714 
1715 /**
1716  * mana_attach - Device Initialization Routine
1717  * @dev: device information struct
1718  *
1719  * Returns 0 on success, otherwise on failure.
1720  *
1721  * mana_attach initializes a GDMA adapter identified by a device structure.
1722  **/
1723 static int
1724 mana_gd_attach(device_t dev)
1725 {
1726 	struct gdma_context *gc;
1727 	int msix_rid;
1728 	int rc;
1729 
1730 	gc = device_get_softc(dev);
1731 	gc->dev = dev;
1732 
1733 	pci_enable_io(dev, SYS_RES_IOPORT);
1734 	pci_enable_io(dev, SYS_RES_MEMORY);
1735 
1736 	pci_enable_busmaster(dev);
1737 
1738 	gc->bar0 = mana_gd_alloc_bar(dev, GDMA_BAR0);
1739 	if (unlikely(gc->bar0 == NULL)) {
1740 		device_printf(dev,
1741 		    "unable to allocate bus resource for bar0!\n");
1742 		rc = ENOMEM;
1743 		goto err_disable_dev;
1744 	}
1745 
1746 	/* Store bar0 tage and handle for quick access */
1747 	gc->gd_bus.bar0_t = rman_get_bustag(gc->bar0);
1748 	gc->gd_bus.bar0_h = rman_get_bushandle(gc->bar0);
1749 
1750 	/* Map MSI-x vector table */
1751 	msix_rid = pci_msix_table_bar(dev);
1752 
1753 	mana_dbg(NULL, "msix_rid 0x%x\n", msix_rid);
1754 
1755 	gc->msix = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1756 	    &msix_rid, RF_ACTIVE);
1757 	if (unlikely(gc->msix == NULL)) {
1758 		device_printf(dev,
1759 		    "unable to allocate bus resource for msix!\n");
1760 		rc = ENOMEM;
1761 		goto err_free_pci_res;
1762 	}
1763 	gc->msix_rid = msix_rid;
1764 
1765 	if (unlikely(gc->gd_bus.bar0_h  == 0)) {
1766 		device_printf(dev, "failed to map bar0!\n");
1767 		rc = ENXIO;
1768 		goto err_free_pci_res;
1769 	}
1770 
1771 	mana_gd_init_registers(gc);
1772 
1773 	mana_smc_init(&gc->shm_channel, gc->dev, gc->shm_base);
1774 
1775 	rc = mana_gd_setup_irqs(dev);
1776 	if (rc) {
1777 		goto err_free_pci_res;
1778 	}
1779 
1780 	sx_init(&gc->eq_test_event_sx, "gdma test event sx");
1781 
1782 	rc = mana_hwc_create_channel(gc);
1783 	if (rc) {
1784 		mana_dbg(NULL, "Failed to create hwc channel\n");
1785 		if (rc == EIO)
1786 			goto err_clean_up_gdma;
1787 		else
1788 			goto err_remove_irq;
1789 	}
1790 
1791 	rc = mana_gd_verify_vf_version(dev);
1792 	if (rc) {
1793 		mana_dbg(NULL, "Failed to verify vf\n");
1794 		goto err_clean_up_gdma;
1795 	}
1796 
1797 	rc = mana_gd_query_max_resources(dev);
1798 	if (rc) {
1799 		mana_dbg(NULL, "Failed to query max resources\n");
1800 		goto err_clean_up_gdma;
1801 	}
1802 
1803 	rc = mana_gd_detect_devices(dev);
1804 	if (rc) {
1805 		mana_dbg(NULL, "Failed to detect  mana device\n");
1806 		goto err_clean_up_gdma;
1807 	}
1808 
1809 	rc = mana_probe(&gc->mana);
1810 	if (rc) {
1811 		mana_dbg(NULL, "Failed to probe mana device\n");
1812 		goto err_clean_up_gdma;
1813 	}
1814 
1815 	return (0);
1816 
1817 err_clean_up_gdma:
1818 	mana_hwc_destroy_channel(gc);
1819 err_remove_irq:
1820 	mana_gd_remove_irqs(dev);
1821 err_free_pci_res:
1822 	mana_gd_free_pci_res(gc);
1823 err_disable_dev:
1824 	pci_disable_busmaster(dev);
1825 
1826 	return(rc);
1827 }
1828 
1829 /**
1830  * mana_detach - Device Removal Routine
1831  * @pdev: device information struct
1832  *
1833  * mana_detach is called by the device subsystem to alert the driver
1834  * that it should release a PCI device.
1835  **/
1836 static int
1837 mana_gd_detach(device_t dev)
1838 {
1839 	struct gdma_context *gc = device_get_softc(dev);
1840 
1841 	mana_remove(&gc->mana);
1842 
1843 	mana_hwc_destroy_channel(gc);
1844 
1845 	mana_gd_remove_irqs(dev);
1846 
1847 	mana_gd_free_pci_res(gc);
1848 
1849 	pci_disable_busmaster(dev);
1850 
1851 	return (bus_generic_detach(dev));
1852 }
1853 
1854 
1855 /*********************************************************************
1856  *  FreeBSD Device Interface Entry Points
1857  *********************************************************************/
1858 
1859 static device_method_t mana_methods[] = {
1860     /* Device interface */
1861     DEVMETHOD(device_probe, mana_gd_probe),
1862     DEVMETHOD(device_attach, mana_gd_attach),
1863     DEVMETHOD(device_detach, mana_gd_detach),
1864     DEVMETHOD_END
1865 };
1866 
1867 static driver_t mana_driver = {
1868     "mana", mana_methods, sizeof(struct gdma_context),
1869 };
1870 
1871 DRIVER_MODULE(mana, pci, mana_driver, 0, 0);
1872 MODULE_PNP_INFO("U16:vendor;U16:device", pci, mana, mana_id_table,
1873     nitems(mana_id_table) - 1);
1874 MODULE_DEPEND(mana, pci, 1, 1, 1);
1875 MODULE_DEPEND(mana, ether, 1, 1, 1);
1876 
1877 /*********************************************************************/
1878