1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (C) 2018 Intel Corporation
3 
4 #include <linux/device.h>
5 
6 #include "ipu3.h"
7 #include "ipu3-css-pool.h"
8 #include "ipu3-dmamap.h"
9 
imgu_css_dma_buffer_resize(struct imgu_device * imgu,struct imgu_css_map * map,size_t size)10 int imgu_css_dma_buffer_resize(struct imgu_device *imgu,
11 			       struct imgu_css_map *map, size_t size)
12 {
13 	if (map->size < size && map->vaddr) {
14 		dev_warn(&imgu->pci_dev->dev, "dma buf resized from %zu to %zu",
15 			 map->size, size);
16 
17 		imgu_dmamap_free(imgu, map);
18 		if (!imgu_dmamap_alloc(imgu, map, size))
19 			return -ENOMEM;
20 	}
21 
22 	return 0;
23 }
24 
imgu_css_pool_cleanup(struct imgu_device * imgu,struct imgu_css_pool * pool)25 void imgu_css_pool_cleanup(struct imgu_device *imgu, struct imgu_css_pool *pool)
26 {
27 	unsigned int i;
28 
29 	for (i = 0; i < IPU3_CSS_POOL_SIZE; i++)
30 		imgu_dmamap_free(imgu, &pool->entry[i].param);
31 }
32 
imgu_css_pool_init(struct imgu_device * imgu,struct imgu_css_pool * pool,size_t size)33 int imgu_css_pool_init(struct imgu_device *imgu, struct imgu_css_pool *pool,
34 		       size_t size)
35 {
36 	unsigned int i;
37 
38 	for (i = 0; i < IPU3_CSS_POOL_SIZE; i++) {
39 		pool->entry[i].valid = false;
40 		if (size == 0) {
41 			pool->entry[i].param.vaddr = NULL;
42 			continue;
43 		}
44 
45 		if (!imgu_dmamap_alloc(imgu, &pool->entry[i].param, size))
46 			goto fail;
47 	}
48 
49 	pool->last = IPU3_CSS_POOL_SIZE;
50 
51 	return 0;
52 
53 fail:
54 	imgu_css_pool_cleanup(imgu, pool);
55 	return -ENOMEM;
56 }
57 
58 /*
59  * Allocate a new parameter via recycling the oldest entry in the pool.
60  */
imgu_css_pool_get(struct imgu_css_pool * pool)61 void imgu_css_pool_get(struct imgu_css_pool *pool)
62 {
63 	/* Get the oldest entry */
64 	u32 n = (pool->last + 1) % IPU3_CSS_POOL_SIZE;
65 
66 	pool->entry[n].valid = true;
67 	pool->last = n;
68 }
69 
70 /*
71  * Undo, for all practical purposes, the effect of pool_get().
72  */
imgu_css_pool_put(struct imgu_css_pool * pool)73 void imgu_css_pool_put(struct imgu_css_pool *pool)
74 {
75 	pool->entry[pool->last].valid = false;
76 	pool->last = (pool->last + IPU3_CSS_POOL_SIZE - 1) % IPU3_CSS_POOL_SIZE;
77 }
78 
79 /**
80  * imgu_css_pool_last - Retrieve the nth pool entry from last
81  *
82  * @pool: a pointer to &struct imgu_css_pool.
83  * @n: the distance to the last index.
84  *
85  * Returns:
86  *  The nth entry from last or null map to indicate no frame stored.
87  */
88 const struct imgu_css_map *
imgu_css_pool_last(struct imgu_css_pool * pool,unsigned int n)89 imgu_css_pool_last(struct imgu_css_pool *pool, unsigned int n)
90 {
91 	static const struct imgu_css_map null_map = { 0 };
92 	int i = (pool->last + IPU3_CSS_POOL_SIZE - n) % IPU3_CSS_POOL_SIZE;
93 
94 	WARN_ON(n >= IPU3_CSS_POOL_SIZE);
95 
96 	if (!pool->entry[i].valid)
97 		return &null_map;
98 
99 	return &pool->entry[i].param;
100 }
101