1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (c) 2021, NVIDIA Corporation.
6 #include <linux/device.h>
7 #include <linux/kref.h>
9 #include <linux/of_platform.h>
10 #include <linux/pid.h>
11 #include <linux/slab.h>
16 int host1x_memory_context_list_init(struct host1x *host1x)
18 struct host1x_memory_context_list *cdl = &host1x->context_list;
19 struct device_node *node = host1x->dev->of_node;
20 struct host1x_memory_context *ctx;
26 mutex_init(&cdl->lock);
28 err = of_property_count_u32_elems(node, "iommu-map");
32 cdl->devs = kcalloc(err, sizeof(*cdl->devs), GFP_KERNEL);
37 for (i = 0; i < cdl->len; i++) {
38 struct iommu_fwspec *fwspec;
44 device_initialize(&ctx->dev);
47 * Due to an issue with T194 NVENC, only 38 bits can be used.
48 * Anyway, 256GiB of IOVA ought to be enough for anyone.
50 ctx->dma_mask = DMA_BIT_MASK(38);
51 ctx->dev.dma_mask = &ctx->dma_mask;
52 ctx->dev.coherent_dma_mask = ctx->dma_mask;
53 dev_set_name(&ctx->dev, "host1x-ctx.%d", i);
54 ctx->dev.bus = &host1x_context_device_bus_type;
55 ctx->dev.parent = host1x->dev;
57 dma_set_max_seg_size(&ctx->dev, UINT_MAX);
59 err = device_add(&ctx->dev);
61 dev_err(host1x->dev, "could not add context device %d: %d\n", i, err);
65 err = of_dma_configure_id(&ctx->dev, node, true, &i);
67 dev_err(host1x->dev, "IOMMU configuration failed for context device %d: %d\n",
69 device_del(&ctx->dev);
73 fwspec = dev_iommu_fwspec_get(&ctx->dev);
74 if (!fwspec || !device_iommu_mapped(&ctx->dev)) {
75 dev_err(host1x->dev, "Context device %d has no IOMMU!\n", i);
76 device_del(&ctx->dev);
80 ctx->stream_id = fwspec->ids[0] & 0xffff;
87 device_del(&cdl->devs[i].dev);
95 void host1x_memory_context_list_free(struct host1x_memory_context_list *cdl)
99 for (i = 0; i < cdl->len; i++)
100 device_del(&cdl->devs[i].dev);
106 struct host1x_memory_context *host1x_memory_context_alloc(struct host1x *host1x,
110 struct host1x_memory_context_list *cdl = &host1x->context_list;
111 struct host1x_memory_context *free = NULL;
115 return ERR_PTR(-EOPNOTSUPP);
117 mutex_lock(&cdl->lock);
119 for (i = 0; i < cdl->len; i++) {
120 struct host1x_memory_context *cd = &cdl->devs[i];
122 if (cd->dev.iommu->iommu_dev != dev->iommu->iommu_dev)
125 if (cd->owner == pid) {
126 refcount_inc(&cd->ref);
127 mutex_unlock(&cdl->lock);
129 } else if (!cd->owner && !free) {
135 mutex_unlock(&cdl->lock);
136 return ERR_PTR(-EBUSY);
139 refcount_set(&free->ref, 1);
140 free->owner = get_pid(pid);
142 mutex_unlock(&cdl->lock);
146 EXPORT_SYMBOL_GPL(host1x_memory_context_alloc);
148 void host1x_memory_context_get(struct host1x_memory_context *cd)
150 refcount_inc(&cd->ref);
152 EXPORT_SYMBOL_GPL(host1x_memory_context_get);
154 void host1x_memory_context_put(struct host1x_memory_context *cd)
156 struct host1x_memory_context_list *cdl = &cd->host->context_list;
158 if (refcount_dec_and_mutex_lock(&cd->ref, &cdl->lock)) {
161 mutex_unlock(&cdl->lock);
164 EXPORT_SYMBOL_GPL(host1x_memory_context_put);