| 1 | // SPDX-License-Identifier: GPL-2.0 |
| 2 | /* Copyright (C) 2018-2025, Advanced Micro Devices, Inc. */ |
| 3 | |
| 4 | #include <linux/dma-mapping.h> |
| 5 | |
| 6 | #include "ionic_queue.h" |
| 7 | |
| 8 | int ionic_queue_init(struct ionic_queue *q, struct device *dma_dev, |
| 9 | int depth, size_t stride) |
| 10 | { |
| 11 | if (depth < 0 || depth > 0xffff) |
| 12 | return -EINVAL; |
| 13 | |
| 14 | if (stride == 0 || stride > 0x10000) |
| 15 | return -EINVAL; |
| 16 | |
| 17 | if (depth == 0) |
| 18 | depth = 1; |
| 19 | |
| 20 | q->depth_log2 = order_base_2(depth + 1); |
| 21 | q->stride_log2 = order_base_2(stride); |
| 22 | |
| 23 | if (q->depth_log2 + q->stride_log2 < PAGE_SHIFT) |
| 24 | q->depth_log2 = PAGE_SHIFT - q->stride_log2; |
| 25 | |
| 26 | if (q->depth_log2 > 16 || q->stride_log2 > 16) |
| 27 | return -EINVAL; |
| 28 | |
| 29 | q->size = BIT_ULL(q->depth_log2 + q->stride_log2); |
| 30 | q->mask = BIT(q->depth_log2) - 1; |
| 31 | |
| 32 | q->ptr = dma_alloc_coherent(dev: dma_dev, size: q->size, dma_handle: &q->dma, GFP_KERNEL); |
| 33 | if (!q->ptr) |
| 34 | return -ENOMEM; |
| 35 | |
| 36 | /* it will always be page aligned, but just to be sure... */ |
| 37 | if (!PAGE_ALIGNED(q->ptr)) { |
| 38 | dma_free_coherent(dev: dma_dev, size: q->size, cpu_addr: q->ptr, dma_handle: q->dma); |
| 39 | return -ENOMEM; |
| 40 | } |
| 41 | |
| 42 | q->prod = 0; |
| 43 | q->cons = 0; |
| 44 | q->dbell = 0; |
| 45 | |
| 46 | return 0; |
| 47 | } |
| 48 | |
| 49 | void ionic_queue_destroy(struct ionic_queue *q, struct device *dma_dev) |
| 50 | { |
| 51 | dma_free_coherent(dev: dma_dev, size: q->size, cpu_addr: q->ptr, dma_handle: q->dma); |
| 52 | } |
| 53 | |