[PATCH 5/6] lib/scatterlist: Add sg_trim_table

Tvrtko Ursulin tursulin at ursulin.net
Wed Oct 19 13:53:29 UTC 2016


From: Tvrtko Ursulin <tvrtko.ursulin at intel.com>

In cases where it is hard to know to minimum numbers of ents
table will need to hold at sg_alloc_time, and we end up with
a table with unused sg entries at its end, this function will
trim (free) the unused sg entry blocks and adjust the
table->orig_nents down.

v2: Fixed chain walking logic.

Signed-off-by: Tvrtko Ursulin <tvrtko.ursulin at intel.com>
---
 include/linux/scatterlist.h |  2 ++
 lib/scatterlist.c           | 48 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+)

diff --git a/include/linux/scatterlist.h b/include/linux/scatterlist.h
index cb3c8fe6acd7..b344ecc8eddf 100644
--- a/include/linux/scatterlist.h
+++ b/include/linux/scatterlist.h
@@ -266,6 +266,8 @@ int sg_alloc_table_from_pages(struct sg_table *sgt,
 	unsigned long offset, unsigned long size,
 	gfp_t gfp_mask);
 
+void sg_trim_table(struct sg_table *);
+
 size_t sg_copy_buffer(struct scatterlist *sgl, unsigned int nents, void *buf,
 		      size_t buflen, off_t skip, bool to_buffer);
 
diff --git a/lib/scatterlist.c b/lib/scatterlist.c
index 004fc70fc56a..c0d987e438a6 100644
--- a/lib/scatterlist.c
+++ b/lib/scatterlist.c
@@ -243,6 +243,54 @@ void __sg_free_table(struct sg_table *table, unsigned int max_ents,
 EXPORT_SYMBOL(__sg_free_table);
 
 /**
+ * sg_trim_table - Free unused sg table entries at the end of the table
+ * @table:	The sg table header to use
+ *
+ *  Description:
+ *    In cases where it is hard to know to minimum numbers of ents table will
+ *    need to hold at sg_alloc_time, and we end up with a table with unused sg
+ *    entries at its end, this function will trim (free) the unused sg entry
+ *    blocks and adjust the table->orig_nents down.
+ *
+ **/
+void sg_trim_table(struct sg_table *table)
+{
+	struct scatterlist *sgl, *next, *prev = NULL;
+	unsigned int seen_nents = 0;
+	unsigned int remain_nents = table->orig_nents;
+
+	sgl = table->sgl;
+	while (sgl) {
+		unsigned int alloc_size, sg_size;
+
+		if (remain_nents > SG_MAX_SINGLE_ALLOC) {
+			next = sg_chain_ptr(&sgl[SG_MAX_SINGLE_ALLOC - 1]);
+			alloc_size = SG_MAX_SINGLE_ALLOC;
+			sg_size = alloc_size - 1;
+		} else {
+			sg_size = alloc_size = remain_nents;
+			next = NULL;
+		}
+
+		remain_nents -= sg_size;
+
+		if (seen_nents >= table->nents) {
+			if (prev)
+				sg_mark_end(prev);
+			prev = NULL;
+			table->orig_nents -= sg_size;
+			sg_kfree(sgl, alloc_size);
+		} else {
+			prev = sgl;
+		}
+
+		seen_nents += sg_size;
+		sgl = next;
+	}
+}
+EXPORT_SYMBOL(sg_trim_table);
+
+/**
  * sg_free_table - Free a previously allocated sg table
  * @table:	The mapped sg table header
  *
-- 
2.7.4



More information about the Intel-gfx-trybot mailing list