xref: /freebsd/sys/dev/mana/gdma_main.c (revision f4c129f5fb1669b284d76a838b1e509f97c2d299)
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 		mana_gd_process_eqe(eq);
560 
561 		eq->head++;
562 	}
563 
564 	bus_dmamap_sync(eq->mem_info.dma_tag, eq->mem_info.dma_map,
565 	    BUS_DMASYNC_PREREAD);
566 
567 	head = eq->head % (num_eqe << GDMA_EQE_OWNER_BITS);
568 
569 	mana_gd_ring_doorbell(gc, eq->gdma_dev->doorbell, eq->type, eq->id,
570 	    head, SET_ARM_BIT);
571 }
572 
573 static int
574 mana_gd_register_irq(struct gdma_queue *queue,
575     const struct gdma_queue_spec *spec)
576 {
577 	struct gdma_dev *gd = queue->gdma_dev;
578 	struct gdma_irq_context *gic;
579 	struct gdma_context *gc;
580 	struct gdma_resource *r;
581 	unsigned int msi_index;
582 	int err;
583 
584 	gc = gd->gdma_context;
585 	r = &gc->msix_resource;
586 
587 	mtx_lock_spin(&r->lock_spin);
588 
589 	msi_index = find_first_zero_bit(r->map, r->size);
590 	if (msi_index >= r->size) {
591 		err = ENOSPC;
592 	} else {
593 		bitmap_set(r->map, msi_index, 1);
594 		queue->eq.msix_index = msi_index;
595 		err = 0;
596 	}
597 
598 	mtx_unlock_spin(&r->lock_spin);
599 
600 	if (err)
601 		return err;
602 
603 	if (unlikely(msi_index >= gc->num_msix_usable)) {
604 		device_printf(gc->dev,
605 		    "chose an invalid msix index %d, usable %d\n",
606 		    msi_index, gc->num_msix_usable);
607 		return ENOSPC;
608 	}
609 
610 	gic = &gc->irq_contexts[msi_index];
611 
612 	if (unlikely(gic->handler || gic->arg)) {
613 		device_printf(gc->dev,
614 		    "interrupt handler or arg already assigned, "
615 		    "msix index: %d\n", msi_index);
616 	}
617 
618 	gic->arg = queue;
619 
620 	gic->handler = mana_gd_process_eq_events;
621 
622 	mana_dbg(NULL, "registered msix index %d vector %d irq %ju\n",
623 	    msi_index, gic->msix_e.vector, rman_get_start(gic->res));
624 
625 	return 0;
626 }
627 
628 static void
629 mana_gd_deregiser_irq(struct gdma_queue *queue)
630 {
631 	struct gdma_dev *gd = queue->gdma_dev;
632 	struct gdma_irq_context *gic;
633 	struct gdma_context *gc;
634 	struct gdma_resource *r;
635 	unsigned int msix_index;
636 
637 	gc = gd->gdma_context;
638 	r = &gc->msix_resource;
639 
640 	/* At most num_online_cpus() + 1 interrupts are used. */
641 	msix_index = queue->eq.msix_index;
642 	if (unlikely(msix_index >= gc->num_msix_usable))
643 		return;
644 
645 	gic = &gc->irq_contexts[msix_index];
646 	gic->handler = NULL;
647 	gic->arg = NULL;
648 
649 	mtx_lock_spin(&r->lock_spin);
650 	bitmap_clear(r->map, msix_index, 1);
651 	mtx_unlock_spin(&r->lock_spin);
652 
653 	queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
654 
655 	mana_dbg(NULL, "deregistered msix index %d vector %d irq %ju\n",
656 	    msix_index, gic->msix_e.vector, rman_get_start(gic->res));
657 }
658 
659 int
660 mana_gd_test_eq(struct gdma_context *gc, struct gdma_queue *eq)
661 {
662 	struct gdma_generate_test_event_req req = {};
663 	struct gdma_general_resp resp = {};
664 	device_t dev = gc->dev;
665 	int err;
666 
667 	sx_xlock(&gc->eq_test_event_sx);
668 
669 	init_completion(&gc->eq_test_event);
670 	gc->test_event_eq_id = INVALID_QUEUE_ID;
671 
672 	mana_gd_init_req_hdr(&req.hdr, GDMA_GENERATE_TEST_EQE,
673 			     sizeof(req), sizeof(resp));
674 
675 	req.hdr.dev_id = eq->gdma_dev->dev_id;
676 	req.queue_index = eq->id;
677 
678 	err = mana_gd_send_request(gc, sizeof(req), &req,
679 	    sizeof(resp), &resp);
680 	if (err) {
681 		device_printf(dev, "test_eq failed: %d\n", err);
682 		goto out;
683 	}
684 
685 	err = EPROTO;
686 
687 	if (resp.hdr.status) {
688 		device_printf(dev, "test_eq failed: 0x%x\n",
689 		    resp.hdr.status);
690 		goto out;
691 	}
692 
693 	if (wait_for_completion_timeout(&gc->eq_test_event, 30 * hz)) {
694 		device_printf(dev, "test_eq timed out on queue %d\n",
695 		    eq->id);
696 		goto out;
697 	}
698 
699 	if (eq->id != gc->test_event_eq_id) {
700 		device_printf(dev,
701 		    "test_eq got an event on wrong queue %d (%d)\n",
702 		    gc->test_event_eq_id, eq->id);
703 		goto out;
704 	}
705 
706 	err = 0;
707 out:
708 	sx_xunlock(&gc->eq_test_event_sx);
709 	return err;
710 }
711 
712 static void
713 mana_gd_destroy_eq(struct gdma_context *gc, bool flush_evenets,
714     struct gdma_queue *queue)
715 {
716 	int err;
717 
718 	if (flush_evenets) {
719 		err = mana_gd_test_eq(gc, queue);
720 		if (err)
721 			device_printf(gc->dev,
722 			    "Failed to flush EQ: %d\n", err);
723 	}
724 
725 	mana_gd_deregiser_irq(queue);
726 
727 	if (queue->eq.disable_needed)
728 		mana_gd_disable_queue(queue);
729 }
730 
731 static int mana_gd_create_eq(struct gdma_dev *gd,
732     const struct gdma_queue_spec *spec,
733     bool create_hwq, struct gdma_queue *queue)
734 {
735 	struct gdma_context *gc = gd->gdma_context;
736 	device_t dev = gc->dev;
737 	uint32_t log2_num_entries;
738 	int err;
739 
740 	queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
741 
742 	log2_num_entries = ilog2(queue->queue_size / GDMA_EQE_SIZE);
743 
744 	if (spec->eq.log2_throttle_limit > log2_num_entries) {
745 		device_printf(dev,
746 		    "EQ throttling limit (%lu) > maximum EQE (%u)\n",
747 		    spec->eq.log2_throttle_limit, log2_num_entries);
748 		return EINVAL;
749 	}
750 
751 	err = mana_gd_register_irq(queue, spec);
752 	if (err) {
753 		device_printf(dev, "Failed to register irq: %d\n", err);
754 		return err;
755 	}
756 
757 	queue->eq.callback = spec->eq.callback;
758 	queue->eq.context = spec->eq.context;
759 	queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
760 	queue->eq.log2_throttle_limit = spec->eq.log2_throttle_limit ?: 1;
761 
762 	if (create_hwq) {
763 		err = mana_gd_create_hw_eq(gc, queue);
764 		if (err)
765 			goto out;
766 
767 		err = mana_gd_test_eq(gc, queue);
768 		if (err)
769 			goto out;
770 	}
771 
772 	return 0;
773 out:
774 	device_printf(dev, "Failed to create EQ: %d\n", err);
775 	mana_gd_destroy_eq(gc, false, queue);
776 	return err;
777 }
778 
779 static void
780 mana_gd_create_cq(const struct gdma_queue_spec *spec,
781     struct gdma_queue *queue)
782 {
783 	uint32_t log2_num_entries = ilog2(spec->queue_size / GDMA_CQE_SIZE);
784 
785 	queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
786 	queue->cq.parent = spec->cq.parent_eq;
787 	queue->cq.context = spec->cq.context;
788 	queue->cq.callback = spec->cq.callback;
789 }
790 
791 static void
792 mana_gd_destroy_cq(struct gdma_context *gc,
793     struct gdma_queue *queue)
794 {
795 	uint32_t id = queue->id;
796 
797 	if (id >= gc->max_num_cqs)
798 		return;
799 
800 	if (!gc->cq_table[id])
801 		return;
802 
803 	gc->cq_table[id] = NULL;
804 }
805 
806 int mana_gd_create_hwc_queue(struct gdma_dev *gd,
807     const struct gdma_queue_spec *spec,
808     struct gdma_queue **queue_ptr)
809 {
810 	struct gdma_context *gc = gd->gdma_context;
811 	struct gdma_mem_info *gmi;
812 	struct gdma_queue *queue;
813 	int err;
814 
815 	queue = malloc(sizeof(*queue), M_DEVBUF, M_WAITOK | M_ZERO);
816 	if (!queue)
817 		return ENOMEM;
818 
819 	gmi = &queue->mem_info;
820 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
821 	if (err)
822 		goto free_q;
823 
824 	queue->head = 0;
825 	queue->tail = 0;
826 	queue->queue_mem_ptr = gmi->virt_addr;
827 	queue->queue_size = spec->queue_size;
828 	queue->monitor_avl_buf = spec->monitor_avl_buf;
829 	queue->type = spec->type;
830 	queue->gdma_dev = gd;
831 
832 	if (spec->type == GDMA_EQ)
833 		err = mana_gd_create_eq(gd, spec, false, queue);
834 	else if (spec->type == GDMA_CQ)
835 		mana_gd_create_cq(spec, queue);
836 
837 	if (err)
838 		goto out;
839 
840 	*queue_ptr = queue;
841 	return 0;
842 out:
843 	mana_gd_free_memory(gmi);
844 free_q:
845 	free(queue, M_DEVBUF);
846 	return err;
847 }
848 
849 static void
850 mana_gd_destroy_dma_region(struct gdma_context *gc, uint64_t gdma_region)
851 {
852 	struct gdma_destroy_dma_region_req req = {};
853 	struct gdma_general_resp resp = {};
854 	int err;
855 
856 	if (gdma_region == GDMA_INVALID_DMA_REGION)
857 		return;
858 
859 	mana_gd_init_req_hdr(&req.hdr, GDMA_DESTROY_DMA_REGION, sizeof(req),
860 	    sizeof(resp));
861 	req.gdma_region = gdma_region;
862 
863 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp),
864 	    &resp);
865 	if (err || resp.hdr.status)
866 		device_printf(gc->dev,
867 		    "Failed to destroy DMA region: %d, 0x%x\n",
868 		    err, resp.hdr.status);
869 }
870 
871 static int
872 mana_gd_create_dma_region(struct gdma_dev *gd,
873     struct gdma_mem_info *gmi)
874 {
875 	unsigned int num_page = gmi->length / PAGE_SIZE;
876 	struct gdma_create_dma_region_req *req = NULL;
877 	struct gdma_create_dma_region_resp resp = {};
878 	struct gdma_context *gc = gd->gdma_context;
879 	struct hw_channel_context *hwc;
880 	uint32_t length = gmi->length;
881 	uint32_t req_msg_size;
882 	int err;
883 	int i;
884 
885 	if (length < PAGE_SIZE || !is_power_of_2(length)) {
886 		mana_err(NULL, "gmi size incorrect: %u\n", length);
887 		return EINVAL;
888 	}
889 
890 	if (offset_in_page((uint64_t)gmi->virt_addr) != 0) {
891 		mana_err(NULL, "gmi not page aligned: %p\n",
892 		    gmi->virt_addr);
893 		return EINVAL;
894 	}
895 
896 	hwc = gc->hwc.driver_data;
897 	req_msg_size = sizeof(*req) + num_page * sizeof(uint64_t);
898 	if (req_msg_size > hwc->max_req_msg_size) {
899 		mana_err(NULL, "req msg size too large: %u, %u\n",
900 		    req_msg_size, hwc->max_req_msg_size);
901 		return EINVAL;
902 	}
903 
904 	req = malloc(req_msg_size, M_DEVBUF, M_WAITOK | M_ZERO);
905 	if (!req)
906 		return ENOMEM;
907 
908 	mana_gd_init_req_hdr(&req->hdr, GDMA_CREATE_DMA_REGION,
909 	    req_msg_size, sizeof(resp));
910 	req->length = length;
911 	req->offset_in_page = 0;
912 	req->gdma_page_type = GDMA_PAGE_TYPE_4K;
913 	req->page_count = num_page;
914 	req->page_addr_list_len = num_page;
915 
916 	for (i = 0; i < num_page; i++)
917 		req->page_addr_list[i] = gmi->dma_handle +  i * PAGE_SIZE;
918 
919 	err = mana_gd_send_request(gc, req_msg_size, req, sizeof(resp), &resp);
920 	if (err)
921 		goto out;
922 
923 	if (resp.hdr.status || resp.gdma_region == GDMA_INVALID_DMA_REGION) {
924 		device_printf(gc->dev, "Failed to create DMA region: 0x%x\n",
925 			resp.hdr.status);
926 		err = EPROTO;
927 		goto out;
928 	}
929 
930 	gmi->gdma_region = resp.gdma_region;
931 out:
932 	free(req, M_DEVBUF);
933 	return err;
934 }
935 
936 int
937 mana_gd_create_mana_eq(struct gdma_dev *gd,
938     const struct gdma_queue_spec *spec,
939     struct gdma_queue **queue_ptr)
940 {
941 	struct gdma_context *gc = gd->gdma_context;
942 	struct gdma_mem_info *gmi;
943 	struct gdma_queue *queue;
944 	int err;
945 
946 	if (spec->type != GDMA_EQ)
947 		return EINVAL;
948 
949 	queue = malloc(sizeof(*queue),  M_DEVBUF, M_WAITOK | M_ZERO);
950 	if (!queue)
951 		return ENOMEM;
952 
953 	gmi = &queue->mem_info;
954 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
955 	if (err)
956 		goto free_q;
957 
958 	err = mana_gd_create_dma_region(gd, gmi);
959 	if (err)
960 		goto out;
961 
962 	queue->head = 0;
963 	queue->tail = 0;
964 	queue->queue_mem_ptr = gmi->virt_addr;
965 	queue->queue_size = spec->queue_size;
966 	queue->monitor_avl_buf = spec->monitor_avl_buf;
967 	queue->type = spec->type;
968 	queue->gdma_dev = gd;
969 
970 	err = mana_gd_create_eq(gd, spec, true, queue);
971 	if (err)
972 		goto out;
973 
974 	*queue_ptr = queue;
975 	return 0;
976 
977 out:
978 	mana_gd_free_memory(gmi);
979 free_q:
980 	free(queue, M_DEVBUF);
981 	return err;
982 }
983 
984 int mana_gd_create_mana_wq_cq(struct gdma_dev *gd,
985     const struct gdma_queue_spec *spec,
986     struct gdma_queue **queue_ptr)
987 {
988 	struct gdma_context *gc = gd->gdma_context;
989 	struct gdma_mem_info *gmi;
990 	struct gdma_queue *queue;
991 	int err;
992 
993 	if (spec->type != GDMA_CQ && spec->type != GDMA_SQ &&
994 	    spec->type != GDMA_RQ)
995 		return EINVAL;
996 
997 	queue = malloc(sizeof(*queue), M_DEVBUF, M_WAITOK | M_ZERO);
998 	if (!queue)
999 		return ENOMEM;
1000 
1001 	gmi = &queue->mem_info;
1002 	err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
1003 	if (err)
1004 		goto free_q;
1005 
1006 	err = mana_gd_create_dma_region(gd, gmi);
1007 	if (err)
1008 		goto out;
1009 
1010 	queue->head = 0;
1011 	queue->tail = 0;
1012 	queue->queue_mem_ptr = gmi->virt_addr;
1013 	queue->queue_size = spec->queue_size;
1014 	queue->monitor_avl_buf = spec->monitor_avl_buf;
1015 	queue->type = spec->type;
1016 	queue->gdma_dev = gd;
1017 
1018 	if (spec->type == GDMA_CQ)
1019 		mana_gd_create_cq(spec, queue);
1020 
1021 	*queue_ptr = queue;
1022 	return 0;
1023 
1024 out:
1025 	mana_gd_free_memory(gmi);
1026 free_q:
1027 	free(queue, M_DEVBUF);
1028 	return err;
1029 }
1030 
1031 void
1032 mana_gd_destroy_queue(struct gdma_context *gc, struct gdma_queue *queue)
1033 {
1034 	struct gdma_mem_info *gmi = &queue->mem_info;
1035 
1036 	switch (queue->type) {
1037 	case GDMA_EQ:
1038 		mana_gd_destroy_eq(gc, queue->eq.disable_needed, queue);
1039 		break;
1040 
1041 	case GDMA_CQ:
1042 		mana_gd_destroy_cq(gc, queue);
1043 		break;
1044 
1045 	case GDMA_RQ:
1046 		break;
1047 
1048 	case GDMA_SQ:
1049 		break;
1050 
1051 	default:
1052 		device_printf(gc->dev,
1053 		    "Can't destroy unknown queue: type = %d\n",
1054 		    queue->type);
1055 		return;
1056 	}
1057 
1058 	mana_gd_destroy_dma_region(gc, gmi->gdma_region);
1059 	mana_gd_free_memory(gmi);
1060 	free(queue, M_DEVBUF);
1061 }
1062 
1063 int
1064 mana_gd_verify_vf_version(device_t dev)
1065 {
1066 	struct gdma_context *gc = device_get_softc(dev);
1067 	struct gdma_verify_ver_resp resp = {};
1068 	struct gdma_verify_ver_req req = {};
1069 	int err;
1070 
1071 	mana_gd_init_req_hdr(&req.hdr, GDMA_VERIFY_VF_DRIVER_VERSION,
1072 	    sizeof(req), sizeof(resp));
1073 
1074 	req.protocol_ver_min = GDMA_PROTOCOL_FIRST;
1075 	req.protocol_ver_max = GDMA_PROTOCOL_LAST;
1076 
1077 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1078 	if (err || resp.hdr.status) {
1079 		device_printf(gc->dev,
1080 		    "VfVerifyVersionOutput: %d, status=0x%x\n",
1081 		    err, resp.hdr.status);
1082 		return err ? err : EPROTO;
1083 	}
1084 
1085 	return 0;
1086 }
1087 
1088 int
1089 mana_gd_register_device(struct gdma_dev *gd)
1090 {
1091 	struct gdma_context *gc = gd->gdma_context;
1092 	struct gdma_register_device_resp resp = {};
1093 	struct gdma_general_req req = {};
1094 	int err;
1095 
1096 	gd->pdid = INVALID_PDID;
1097 	gd->doorbell = INVALID_DOORBELL;
1098 	gd->gpa_mkey = INVALID_MEM_KEY;
1099 
1100 	mana_gd_init_req_hdr(&req.hdr, GDMA_REGISTER_DEVICE, sizeof(req),
1101 	    sizeof(resp));
1102 
1103 	req.hdr.dev_id = gd->dev_id;
1104 
1105 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1106 	if (err || resp.hdr.status) {
1107 		device_printf(gc->dev,
1108 		    "gdma_register_device_resp failed: %d, 0x%x\n",
1109 		    err, resp.hdr.status);
1110 		return err ? err : -EPROTO;
1111 	}
1112 
1113 	gd->pdid = resp.pdid;
1114 	gd->gpa_mkey = resp.gpa_mkey;
1115 	gd->doorbell = resp.db_id;
1116 
1117 	mana_dbg(NULL, "mana device pdid %u, gpa_mkey %u, doorbell %u \n",
1118 	    gd->pdid, gd->gpa_mkey, gd->doorbell);
1119 
1120 	return 0;
1121 }
1122 
1123 int
1124 mana_gd_deregister_device(struct gdma_dev *gd)
1125 {
1126 	struct gdma_context *gc = gd->gdma_context;
1127 	struct gdma_general_resp resp = {};
1128 	struct gdma_general_req req = {};
1129 	int err;
1130 
1131 	if (gd->pdid == INVALID_PDID)
1132 		return EINVAL;
1133 
1134 	mana_gd_init_req_hdr(&req.hdr, GDMA_DEREGISTER_DEVICE, sizeof(req),
1135 	    sizeof(resp));
1136 
1137 	req.hdr.dev_id = gd->dev_id;
1138 
1139 	err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
1140 	if (err || resp.hdr.status) {
1141 		device_printf(gc->dev,
1142 		    "Failed to deregister device: %d, 0x%x\n",
1143 		    err, resp.hdr.status);
1144 		if (!err)
1145 			err = EPROTO;
1146 	}
1147 
1148 	gd->pdid = INVALID_PDID;
1149 	gd->doorbell = INVALID_DOORBELL;
1150 	gd->gpa_mkey = INVALID_MEM_KEY;
1151 
1152 	return err;
1153 }
1154 
1155 uint32_t
1156 mana_gd_wq_avail_space(struct gdma_queue *wq)
1157 {
1158 	uint32_t used_space = (wq->head - wq->tail) * GDMA_WQE_BU_SIZE;
1159 	uint32_t wq_size = wq->queue_size;
1160 
1161 	if (used_space > wq_size) {
1162 		mana_warn(NULL, "failed: used space %u > queue size %u\n",
1163 		    used_space, wq_size);
1164 	}
1165 
1166 	return wq_size - used_space;
1167 }
1168 
1169 uint8_t *
1170 mana_gd_get_wqe_ptr(const struct gdma_queue *wq, uint32_t wqe_offset)
1171 {
1172 	uint32_t offset =
1173 	    (wqe_offset * GDMA_WQE_BU_SIZE) & (wq->queue_size - 1);
1174 
1175 	if ((offset + GDMA_WQE_BU_SIZE) > wq->queue_size) {
1176 		mana_warn(NULL, "failed: write end out of queue bound %u, "
1177 		    "queue size %u\n",
1178 		    offset + GDMA_WQE_BU_SIZE, wq->queue_size);
1179 	}
1180 
1181 	return (uint8_t *)wq->queue_mem_ptr + offset;
1182 }
1183 
1184 static uint32_t
1185 mana_gd_write_client_oob(const struct gdma_wqe_request *wqe_req,
1186     enum gdma_queue_type q_type,
1187     uint32_t client_oob_size, uint32_t sgl_data_size,
1188     uint8_t *wqe_ptr)
1189 {
1190 	bool oob_in_sgl = !!(wqe_req->flags & GDMA_WR_OOB_IN_SGL);
1191 	bool pad_data = !!(wqe_req->flags & GDMA_WR_PAD_BY_SGE0);
1192 	struct gdma_wqe *header = (struct gdma_wqe *)wqe_ptr;
1193 	uint8_t *ptr;
1194 
1195 	memset(header, 0, sizeof(struct gdma_wqe));
1196 	header->num_sge = wqe_req->num_sge;
1197 	header->inline_oob_size_div4 = client_oob_size / sizeof(uint32_t);
1198 
1199 	if (oob_in_sgl) {
1200 		if (!pad_data || wqe_req->num_sge < 2) {
1201 			mana_warn(NULL, "no pad_data or num_sge < 2\n");
1202 		}
1203 
1204 		header->client_oob_in_sgl = 1;
1205 
1206 		if (pad_data)
1207 			header->last_vbytes = wqe_req->sgl[0].size;
1208 	}
1209 
1210 	if (q_type == GDMA_SQ)
1211 		header->client_data_unit = wqe_req->client_data_unit;
1212 
1213 	/*
1214 	 * The size of gdma_wqe + client_oob_size must be less than or equal
1215 	 * to one Basic Unit (i.e. 32 bytes), so the pointer can't go beyond
1216 	 * the queue memory buffer boundary.
1217 	 */
1218 	ptr = wqe_ptr + sizeof(header);
1219 
1220 	if (wqe_req->inline_oob_data && wqe_req->inline_oob_size > 0) {
1221 		memcpy(ptr, wqe_req->inline_oob_data, wqe_req->inline_oob_size);
1222 
1223 		if (client_oob_size > wqe_req->inline_oob_size)
1224 			memset(ptr + wqe_req->inline_oob_size, 0,
1225 			       client_oob_size - wqe_req->inline_oob_size);
1226 	}
1227 
1228 	return sizeof(header) + client_oob_size;
1229 }
1230 
1231 static void
1232 mana_gd_write_sgl(struct gdma_queue *wq, uint8_t *wqe_ptr,
1233     const struct gdma_wqe_request *wqe_req)
1234 {
1235 	uint32_t sgl_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
1236 	const uint8_t *address = (uint8_t *)wqe_req->sgl;
1237 	uint8_t *base_ptr, *end_ptr;
1238 	uint32_t size_to_end;
1239 
1240 	base_ptr = wq->queue_mem_ptr;
1241 	end_ptr = base_ptr + wq->queue_size;
1242 	size_to_end = (uint32_t)(end_ptr - wqe_ptr);
1243 
1244 	if (size_to_end < sgl_size) {
1245 		memcpy(wqe_ptr, address, size_to_end);
1246 
1247 		wqe_ptr = base_ptr;
1248 		address += size_to_end;
1249 		sgl_size -= size_to_end;
1250 	}
1251 
1252 	memcpy(wqe_ptr, address, sgl_size);
1253 }
1254 
1255 int
1256 mana_gd_post_work_request(struct gdma_queue *wq,
1257     const struct gdma_wqe_request *wqe_req,
1258     struct gdma_posted_wqe_info *wqe_info)
1259 {
1260 	uint32_t client_oob_size = wqe_req->inline_oob_size;
1261 	struct gdma_context *gc;
1262 	uint32_t sgl_data_size;
1263 	uint32_t max_wqe_size;
1264 	uint32_t wqe_size;
1265 	uint8_t *wqe_ptr;
1266 
1267 	if (wqe_req->num_sge == 0)
1268 		return EINVAL;
1269 
1270 	if (wq->type == GDMA_RQ) {
1271 		if (client_oob_size != 0)
1272 			return EINVAL;
1273 
1274 		client_oob_size = INLINE_OOB_SMALL_SIZE;
1275 
1276 		max_wqe_size = GDMA_MAX_RQE_SIZE;
1277 	} else {
1278 		if (client_oob_size != INLINE_OOB_SMALL_SIZE &&
1279 		    client_oob_size != INLINE_OOB_LARGE_SIZE)
1280 			return EINVAL;
1281 
1282 		max_wqe_size = GDMA_MAX_SQE_SIZE;
1283 	}
1284 
1285 	sgl_data_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
1286 	wqe_size = ALIGN(sizeof(struct gdma_wqe) + client_oob_size +
1287 	    sgl_data_size, GDMA_WQE_BU_SIZE);
1288 	if (wqe_size > max_wqe_size)
1289 		return EINVAL;
1290 
1291 	if (wq->monitor_avl_buf && wqe_size > mana_gd_wq_avail_space(wq)) {
1292 		gc = wq->gdma_dev->gdma_context;
1293 		device_printf(gc->dev, "unsuccessful flow control!\n");
1294 		return ENOSPC;
1295 	}
1296 
1297 	if (wqe_info)
1298 		wqe_info->wqe_size_in_bu = wqe_size / GDMA_WQE_BU_SIZE;
1299 
1300 	wqe_ptr = mana_gd_get_wqe_ptr(wq, wq->head);
1301 	wqe_ptr += mana_gd_write_client_oob(wqe_req, wq->type, client_oob_size,
1302 	    sgl_data_size, wqe_ptr);
1303 	if (wqe_ptr >= (uint8_t *)wq->queue_mem_ptr + wq->queue_size)
1304 		wqe_ptr -= wq->queue_size;
1305 
1306 	mana_gd_write_sgl(wq, wqe_ptr, wqe_req);
1307 
1308 	wq->head += wqe_size / GDMA_WQE_BU_SIZE;
1309 
1310 	bus_dmamap_sync(wq->mem_info.dma_tag, wq->mem_info.dma_map,
1311 	    BUS_DMASYNC_PREWRITE);
1312 
1313 	return 0;
1314 }
1315 
1316 int
1317 mana_gd_post_and_ring(struct gdma_queue *queue,
1318     const struct gdma_wqe_request *wqe_req,
1319     struct gdma_posted_wqe_info *wqe_info)
1320 {
1321 	struct gdma_context *gc = queue->gdma_dev->gdma_context;
1322 	int err;
1323 
1324 	err = mana_gd_post_work_request(queue, wqe_req, wqe_info);
1325 	if (err)
1326 		return err;
1327 
1328 	mana_gd_wq_ring_doorbell(gc, queue);
1329 
1330 	return 0;
1331 }
1332 
1333 static int
1334 mana_gd_read_cqe(struct gdma_queue *cq, struct gdma_comp *comp)
1335 {
1336 	unsigned int num_cqe = cq->queue_size / sizeof(struct gdma_cqe);
1337 	struct gdma_cqe *cq_cqe = cq->queue_mem_ptr;
1338 	uint32_t owner_bits, new_bits, old_bits;
1339 	struct gdma_cqe *cqe;
1340 
1341 	cqe = &cq_cqe[cq->head % num_cqe];
1342 	owner_bits = cqe->cqe_info.owner_bits;
1343 
1344 	old_bits = (cq->head / num_cqe - 1) & GDMA_CQE_OWNER_MASK;
1345 	/* Return 0 if no more entries. */
1346 	if (owner_bits == old_bits)
1347 		return 0;
1348 
1349 	new_bits = (cq->head / num_cqe) & GDMA_CQE_OWNER_MASK;
1350 	/* Return -1 if overflow detected. */
1351 	if (owner_bits != new_bits)
1352 		return -1;
1353 
1354 	comp->wq_num = cqe->cqe_info.wq_num;
1355 	comp->is_sq = cqe->cqe_info.is_sq;
1356 	memcpy(comp->cqe_data, cqe->cqe_data, GDMA_COMP_DATA_SIZE);
1357 
1358 	return 1;
1359 }
1360 
1361 int
1362 mana_gd_poll_cq(struct gdma_queue *cq, struct gdma_comp *comp, int num_cqe)
1363 {
1364 	int cqe_idx;
1365 	int ret;
1366 
1367 	bus_dmamap_sync(cq->mem_info.dma_tag, cq->mem_info.dma_map,
1368 	    BUS_DMASYNC_POSTREAD);
1369 
1370 	for (cqe_idx = 0; cqe_idx < num_cqe; cqe_idx++) {
1371 		ret = mana_gd_read_cqe(cq, &comp[cqe_idx]);
1372 
1373 		if (ret < 0) {
1374 			cq->head -= cqe_idx;
1375 			return ret;
1376 		}
1377 
1378 		if (ret == 0)
1379 			break;
1380 
1381 		cq->head++;
1382 	}
1383 
1384 	return cqe_idx;
1385 }
1386 
1387 static void
1388 mana_gd_intr(void *arg)
1389 {
1390 	struct gdma_irq_context *gic = arg;
1391 
1392 	if (gic->handler) {
1393 		gic->handler(gic->arg);
1394 	}
1395 }
1396 
1397 int
1398 mana_gd_alloc_res_map(uint32_t res_avail,
1399     struct gdma_resource *r, const char *lock_name)
1400 {
1401 	int n = howmany(res_avail, BITS_PER_LONG);
1402 
1403 	r->map =
1404 	    malloc(n * sizeof(unsigned long), M_DEVBUF, M_WAITOK | M_ZERO);
1405 	if (!r->map)
1406 		return ENOMEM;
1407 
1408 	r->size = res_avail;
1409 	mtx_init(&r->lock_spin, lock_name, NULL, MTX_SPIN);
1410 
1411 	mana_dbg(NULL,
1412 	    "total res %u, total number of unsigned longs %u\n",
1413 	    r->size, n);
1414 	return (0);
1415 }
1416 
1417 void
1418 mana_gd_free_res_map(struct gdma_resource *r)
1419 {
1420 	if (!r || !r->map)
1421 		return;
1422 
1423 	free(r->map, M_DEVBUF);
1424 	r->map = NULL;
1425 	r->size = 0;
1426 }
1427 
1428 static void
1429 mana_gd_init_registers(struct gdma_context *gc)
1430 {
1431 	uint64_t bar0_va = rman_get_bushandle(gc->bar0);
1432 
1433 	gc->db_page_size = mana_gd_r32(gc, GDMA_REG_DB_PAGE_SIZE) & 0xFFFF;
1434 
1435 	gc->db_page_base =
1436 	    (void *) (bar0_va + mana_gd_r64(gc, GDMA_REG_DB_PAGE_OFFSET));
1437 
1438 	gc->shm_base =
1439 	    (void *) (bar0_va + mana_gd_r64(gc, GDMA_REG_SHM_OFFSET));
1440 
1441 	mana_dbg(NULL, "db_page_size 0x%xx, db_page_base %p,"
1442 		    " shm_base %p\n",
1443 		    gc->db_page_size, gc->db_page_base, gc->shm_base);
1444 }
1445 
1446 static struct resource *
1447 mana_gd_alloc_bar(device_t dev, int bar)
1448 {
1449 	struct resource *res = NULL;
1450 	struct pci_map *pm;
1451 	int rid, type;
1452 
1453 	if (bar < 0 || bar > PCIR_MAX_BAR_0)
1454 		goto alloc_bar_out;
1455 
1456 	pm = pci_find_bar(dev, PCIR_BAR(bar));
1457 	if (!pm)
1458 		goto alloc_bar_out;
1459 
1460 	if (PCI_BAR_IO(pm->pm_value))
1461 		type = SYS_RES_IOPORT;
1462 	else
1463 		type = SYS_RES_MEMORY;
1464 	if (type < 0)
1465 		goto alloc_bar_out;
1466 
1467 	rid = PCIR_BAR(bar);
1468 	res = bus_alloc_resource_any(dev, type, &rid, RF_ACTIVE);
1469 #if defined(__amd64__)
1470 	if (res)
1471 		mana_dbg(NULL, "bar %d: rid 0x%x, type 0x%jx,"
1472 		    " handle 0x%jx\n",
1473 		    bar, rid, res->r_bustag, res->r_bushandle);
1474 #endif
1475 
1476 alloc_bar_out:
1477 	return (res);
1478 }
1479 
1480 static void
1481 mana_gd_free_pci_res(struct gdma_context *gc)
1482 {
1483 	if (!gc || gc->dev)
1484 		return;
1485 
1486 	if (gc->bar0 != NULL) {
1487 		bus_release_resource(gc->dev, SYS_RES_MEMORY,
1488 		    PCIR_BAR(GDMA_BAR0), gc->bar0);
1489 	}
1490 
1491 	if (gc->msix != NULL) {
1492 		bus_release_resource(gc->dev, SYS_RES_MEMORY,
1493 		    gc->msix_rid, gc->msix);
1494 	}
1495 }
1496 
1497 static int
1498 mana_gd_setup_irqs(device_t dev)
1499 {
1500 	unsigned int max_queues_per_port = mp_ncpus;
1501 	struct gdma_context *gc = device_get_softc(dev);
1502 	struct gdma_irq_context *gic;
1503 	unsigned int max_irqs;
1504 	int nvec;
1505 	int rc, rcc, i;
1506 
1507 	if (max_queues_per_port > MANA_MAX_NUM_QUEUES)
1508 		max_queues_per_port = MANA_MAX_NUM_QUEUES;
1509 
1510 	/* Need 1 interrupt for the Hardware communication Channel (HWC) */
1511 	max_irqs = max_queues_per_port + 1;
1512 
1513 	nvec = max_irqs;
1514 	rc = pci_alloc_msix(dev, &nvec);
1515 	if (unlikely(rc != 0)) {
1516 		device_printf(dev,
1517 		    "Failed to allocate MSIX, vectors %d, error: %d\n",
1518 		    nvec, rc);
1519 		rc = ENOSPC;
1520 		goto err_setup_irq_alloc;
1521 	}
1522 
1523 	if (nvec != max_irqs) {
1524 		if (nvec == 1) {
1525 			device_printf(dev,
1526 			    "Not enough number of MSI-x allocated: %d\n",
1527 			    nvec);
1528 			rc = ENOSPC;
1529 			goto err_setup_irq_release;
1530 		}
1531 		device_printf(dev, "Allocated only %d MSI-x (%d requested)\n",
1532 		    nvec, max_irqs);
1533 	}
1534 
1535 	gc->irq_contexts = malloc(nvec * sizeof(struct gdma_irq_context),
1536 	    M_DEVBUF, M_WAITOK | M_ZERO);
1537 	if (!gc->irq_contexts) {
1538 		rc = ENOMEM;
1539 		goto err_setup_irq_release;
1540 	}
1541 
1542 	for (i = 0; i < nvec; i++) {
1543 		gic = &gc->irq_contexts[i];
1544 		gic->msix_e.entry = i;
1545 		/* Vector starts from 1. */
1546 		gic->msix_e.vector = i + 1;
1547 		gic->handler = NULL;
1548 		gic->arg = NULL;
1549 
1550 		gic->res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
1551 		    &gic->msix_e.vector, RF_ACTIVE | RF_SHAREABLE);
1552 		if (unlikely(gic->res == NULL)) {
1553 			rc = ENOMEM;
1554 			device_printf(dev, "could not allocate resource "
1555 			    "for irq vector %d\n", gic->msix_e.vector);
1556 			goto err_setup_irq;
1557 		}
1558 
1559 		rc = bus_setup_intr(dev, gic->res,
1560 		    INTR_TYPE_NET | INTR_MPSAFE, NULL, mana_gd_intr,
1561 		    gic, &gic->cookie);
1562 		if (unlikely(rc != 0)) {
1563 			device_printf(dev, "failed to register interrupt "
1564 			    "handler for irq %ju vector %d: error %d\n",
1565 			    rman_get_start(gic->res), gic->msix_e.vector, rc);
1566 			goto err_setup_irq;
1567 		}
1568 		gic->requested = true;
1569 
1570 		mana_dbg(NULL, "added msix vector %d irq %ju\n",
1571 		    gic->msix_e.vector, rman_get_start(gic->res));
1572 	}
1573 
1574 	rc = mana_gd_alloc_res_map(nvec, &gc->msix_resource,
1575 	    "gdma msix res lock");
1576 	if (rc != 0) {
1577 		device_printf(dev, "failed to allocate memory "
1578 		    "for msix bitmap\n");
1579 		goto err_setup_irq;
1580 	}
1581 
1582 	gc->max_num_msix = nvec;
1583 	gc->num_msix_usable = nvec;
1584 
1585 	mana_dbg(NULL, "setup %d msix interrupts\n", nvec);
1586 
1587 	return (0);
1588 
1589 err_setup_irq:
1590 	for (; i >= 0; i--) {
1591 		gic = &gc->irq_contexts[i];
1592 		rcc = 0;
1593 
1594 		/*
1595 		 * If gic->requested is true, we need to free both intr and
1596 		 * resources.
1597 		 */
1598 		if (gic->requested)
1599 			rcc = bus_teardown_intr(dev, gic->res, gic->cookie);
1600 		if (unlikely(rcc != 0))
1601 			device_printf(dev, "could not release "
1602 			    "irq vector %d, error: %d\n",
1603 			    gic->msix_e.vector, rcc);
1604 
1605 		rcc = 0;
1606 		if (gic->res != NULL) {
1607 			rcc = bus_release_resource(dev, SYS_RES_IRQ,
1608 			    gic->msix_e.vector, gic->res);
1609 		}
1610 		if (unlikely(rcc != 0))
1611 			device_printf(dev, "dev has no parent while "
1612 			    "releasing resource for irq vector %d\n",
1613 			    gic->msix_e.vector);
1614 		gic->requested = false;
1615 		gic->res = NULL;
1616 	}
1617 
1618 	free(gc->irq_contexts, M_DEVBUF);
1619 	gc->irq_contexts = NULL;
1620 err_setup_irq_release:
1621 	pci_release_msi(dev);
1622 err_setup_irq_alloc:
1623 	return (rc);
1624 }
1625 
1626 static void
1627 mana_gd_remove_irqs(device_t dev)
1628 {
1629 	struct gdma_context *gc = device_get_softc(dev);
1630 	struct gdma_irq_context *gic;
1631 	int rc, i;
1632 
1633 	mana_gd_free_res_map(&gc->msix_resource);
1634 
1635 	for (i = 0; i < gc->max_num_msix; i++) {
1636 		gic = &gc->irq_contexts[i];
1637 		if (gic->requested) {
1638 			rc = bus_teardown_intr(dev, gic->res, gic->cookie);
1639 			if (unlikely(rc != 0)) {
1640 				device_printf(dev, "failed to tear down "
1641 				    "irq vector %d, error: %d\n",
1642 				    gic->msix_e.vector, rc);
1643 			}
1644 			gic->requested = false;
1645 		}
1646 
1647 		if (gic->res != NULL) {
1648 			rc = bus_release_resource(dev, SYS_RES_IRQ,
1649 			    gic->msix_e.vector, gic->res);
1650 			if (unlikely(rc != 0)) {
1651 				device_printf(dev, "dev has no parent while "
1652 				    "releasing resource for irq vector %d\n",
1653 				    gic->msix_e.vector);
1654 			}
1655 			gic->res = NULL;
1656 		}
1657 	}
1658 
1659 	gc->max_num_msix = 0;
1660 	gc->num_msix_usable = 0;
1661 	free(gc->irq_contexts, M_DEVBUF);
1662 	gc->irq_contexts = NULL;
1663 
1664 	pci_release_msi(dev);
1665 }
1666 
1667 static int
1668 mana_gd_probe(device_t dev)
1669 {
1670 	mana_vendor_id_t *ent;
1671 	char		adapter_name[60];
1672 	uint16_t	pci_vendor_id = 0;
1673 	uint16_t	pci_device_id = 0;
1674 
1675 	pci_vendor_id = pci_get_vendor(dev);
1676 	pci_device_id = pci_get_device(dev);
1677 
1678 	ent = mana_id_table;
1679 	while (ent->vendor_id != 0) {
1680 		if ((pci_vendor_id == ent->vendor_id) &&
1681 		    (pci_device_id == ent->device_id)) {
1682 			mana_dbg(NULL, "vendor=%x device=%x\n",
1683 			    pci_vendor_id, pci_device_id);
1684 
1685 			sprintf(adapter_name, DEVICE_DESC);
1686 			device_set_desc_copy(dev, adapter_name);
1687 			return (BUS_PROBE_DEFAULT);
1688 		}
1689 
1690 		ent++;
1691 	}
1692 
1693 	return (ENXIO);
1694 }
1695 
1696 /**
1697  * mana_attach - Device Initialization Routine
1698  * @dev: device information struct
1699  *
1700  * Returns 0 on success, otherwise on failure.
1701  *
1702  * mana_attach initializes a GDMA adapter identified by a device structure.
1703  **/
1704 static int
1705 mana_gd_attach(device_t dev)
1706 {
1707 	struct gdma_context *gc;
1708 	int msix_rid;
1709 	int rc;
1710 
1711 	gc = device_get_softc(dev);
1712 	gc->dev = dev;
1713 
1714 	pci_enable_io(dev, SYS_RES_IOPORT);
1715 	pci_enable_io(dev, SYS_RES_MEMORY);
1716 
1717 	pci_enable_busmaster(dev);
1718 
1719 	gc->bar0 = mana_gd_alloc_bar(dev, GDMA_BAR0);
1720 	if (unlikely(gc->bar0 == NULL)) {
1721 		device_printf(dev,
1722 		    "unable to allocate bus resource for bar0!\n");
1723 		rc = ENOMEM;
1724 		goto err_disable_dev;
1725 	}
1726 
1727 	/* Store bar0 tage and handle for quick access */
1728 	gc->gd_bus.bar0_t = rman_get_bustag(gc->bar0);
1729 	gc->gd_bus.bar0_h = rman_get_bushandle(gc->bar0);
1730 
1731 	/* Map MSI-x vector table */
1732 	msix_rid = pci_msix_table_bar(dev);
1733 
1734 	mana_dbg(NULL, "msix_rid 0x%x\n", msix_rid);
1735 
1736 	gc->msix = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1737 	    &msix_rid, RF_ACTIVE);
1738 	if (unlikely(gc->msix == NULL)) {
1739 		device_printf(dev,
1740 		    "unable to allocate bus resource for msix!\n");
1741 		rc = ENOMEM;
1742 		goto err_free_pci_res;
1743 	}
1744 	gc->msix_rid = msix_rid;
1745 
1746 	if (unlikely(gc->gd_bus.bar0_h  == 0)) {
1747 		device_printf(dev, "failed to map bar0!\n");
1748 		rc = ENXIO;
1749 		goto err_free_pci_res;
1750 	}
1751 
1752 	mana_gd_init_registers(gc);
1753 
1754 	mana_smc_init(&gc->shm_channel, gc->dev, gc->shm_base);
1755 
1756 	rc = mana_gd_setup_irqs(dev);
1757 	if (rc) {
1758 		goto err_free_pci_res;
1759 	}
1760 
1761 	sx_init(&gc->eq_test_event_sx, "gdma test event sx");
1762 
1763 	rc = mana_hwc_create_channel(gc);
1764 	if (rc) {
1765 		mana_dbg(NULL, "Failed to create hwc channel\n");
1766 		if (rc == EIO)
1767 			goto err_clean_up_gdma;
1768 		else
1769 			goto err_remove_irq;
1770 	}
1771 
1772 	rc = mana_gd_verify_vf_version(dev);
1773 	if (rc) {
1774 		mana_dbg(NULL, "Failed to verify vf\n");
1775 		goto err_clean_up_gdma;
1776 	}
1777 
1778 	rc = mana_gd_query_max_resources(dev);
1779 	if (rc) {
1780 		mana_dbg(NULL, "Failed to query max resources\n");
1781 		goto err_clean_up_gdma;
1782 	}
1783 
1784 	rc = mana_gd_detect_devices(dev);
1785 	if (rc) {
1786 		mana_dbg(NULL, "Failed to detect  mana device\n");
1787 		goto err_clean_up_gdma;
1788 	}
1789 
1790 	rc = mana_probe(&gc->mana);
1791 	if (rc) {
1792 		mana_dbg(NULL, "Failed to probe mana device\n");
1793 		goto err_clean_up_gdma;
1794 	}
1795 
1796 	return (0);
1797 
1798 err_clean_up_gdma:
1799 	mana_hwc_destroy_channel(gc);
1800 	if (gc->cq_table)
1801 		free(gc->cq_table, M_DEVBUF);
1802 	gc->cq_table = NULL;
1803 err_remove_irq:
1804 	mana_gd_remove_irqs(dev);
1805 err_free_pci_res:
1806 	mana_gd_free_pci_res(gc);
1807 err_disable_dev:
1808 	pci_disable_busmaster(dev);
1809 
1810 	return(rc);
1811 }
1812 
1813 /**
1814  * mana_detach - Device Removal Routine
1815  * @pdev: device information struct
1816  *
1817  * mana_detach is called by the device subsystem to alert the driver
1818  * that it should release a PCI device.
1819  **/
1820 static int
1821 mana_gd_detach(device_t dev)
1822 {
1823 	struct gdma_context *gc = device_get_softc(dev);
1824 
1825 	mana_remove(&gc->mana);
1826 
1827 	mana_hwc_destroy_channel(gc);
1828 	free(gc->cq_table, M_DEVBUF);
1829 	gc->cq_table = NULL;
1830 
1831 	mana_gd_remove_irqs(dev);
1832 
1833 	mana_gd_free_pci_res(gc);
1834 
1835 	pci_disable_busmaster(dev);
1836 
1837 	return (bus_generic_detach(dev));
1838 }
1839 
1840 
1841 /*********************************************************************
1842  *  FreeBSD Device Interface Entry Points
1843  *********************************************************************/
1844 
1845 static device_method_t mana_methods[] = {
1846     /* Device interface */
1847     DEVMETHOD(device_probe, mana_gd_probe),
1848     DEVMETHOD(device_attach, mana_gd_attach),
1849     DEVMETHOD(device_detach, mana_gd_detach),
1850     DEVMETHOD_END
1851 };
1852 
1853 static driver_t mana_driver = {
1854     "mana", mana_methods, sizeof(struct gdma_context),
1855 };
1856 
1857 devclass_t mana_devclass;
1858 DRIVER_MODULE(mana, pci, mana_driver, mana_devclass, 0, 0);
1859 MODULE_PNP_INFO("U16:vendor;U16:device", pci, mana, mana_id_table,
1860     nitems(mana_id_table) - 1);
1861 MODULE_DEPEND(mana, pci, 1, 1, 1);
1862 MODULE_DEPEND(mana, ether, 1, 1, 1);
1863 
1864 /*********************************************************************/
1865