1// SPDX-License-Identifier:    GPL-2.0
2/*
3 * Copyright (C) 2018 Marvell International Ltd.
4 */
5
6#include <dm.h>
7#include <errno.h>
8#include <malloc.h>
9#include <misc.h>
10#include <net.h>
11#include <asm/io.h>
12
13#include "rvu.h"
14
15int qmem_alloc(struct qmem *q, u32 qsize, size_t entry_sz)
16{
17	q->base = memalign(CONFIG_SYS_CACHELINE_SIZE, qsize * entry_sz);
18	if (!q->base)
19		return -ENOMEM;
20	q->entry_sz = entry_sz;
21	q->qsize = qsize;
22	q->alloc_sz = (size_t)qsize * entry_sz;
23	q->iova = (dma_addr_t)(q->base);
24	debug("NIX: qmem alloc for (%d * %d = %ld bytes) at %p\n",
25	      q->qsize, q->entry_sz, q->alloc_sz, q->base);
26	return 0;
27}
28
29void qmem_free(struct qmem *q)
30{
31	if (q->base)
32		free(q->base);
33	memset(q, 0, sizeof(*q));
34}
35
36/**
37 * Allocates an admin queue for instructions and results
38 *
39 * @param	aq	admin queue to allocate for
40 * @param	qsize	Number of entries in the queue
41 * @param	inst_size	Size of each instruction
42 * @param	res_size	Size of each result
43 *
44 * Return:	-ENOMEM on error, 0 on success
45 */
46int rvu_aq_alloc(struct admin_queue *aq, unsigned int qsize,
47		 size_t inst_size, size_t res_size)
48{
49	int err;
50
51	err = qmem_alloc(&aq->inst, qsize, inst_size);
52	if (err)
53		return err;
54	err = qmem_alloc(&aq->res, qsize, res_size);
55	if (err)
56		qmem_free(&aq->inst);
57
58	return err;
59}
60
61/**
62 * Frees an admin queue
63 *
64 * @param	aq	Admin queue to free
65 */
66void rvu_aq_free(struct admin_queue *aq)
67{
68	qmem_free(&aq->inst);
69	qmem_free(&aq->res);
70	memset(aq, 0, sizeof(*aq));
71}
72