1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007 Jens Axboe <jens.axboe@oracle.com>
5 * Scatterlist handling helpers.
7 #include <linux/export.h>
8 #include <linux/slab.h>
9 #include <linux/scatterlist.h>
10 #include <linux/highmem.h>
11 #include <linux/kmemleak.h>
12 #include <linux/bvec.h>
13 #include <linux/uio.h>
14 #include <linux/folio_queue.h>
17 * sg_nents - return total count of entries in scatterlist
18 * @sg: The scatterlist
21 * Allows to know how many entries are in sg, taking into account
25 int sg_nents(struct scatterlist *sg)
28 for (nents = 0; sg; sg = sg_next(sg))
32 EXPORT_SYMBOL(sg_nents);
35 * sg_nents_for_len - return total count of entries in scatterlist
36 * needed to satisfy the supplied length
37 * @sg: The scatterlist
38 * @len: The total required length
41 * Determines the number of entries in sg that are required to meet
42 * the supplied length, taking into account chaining as well
45 * the number of sg entries needed, negative error on failure
48 int sg_nents_for_len(struct scatterlist *sg, u64 len)
56 for (nents = 0, total = 0; sg; sg = sg_next(sg)) {
65 EXPORT_SYMBOL(sg_nents_for_len);
68 * sg_last - return the last scatterlist entry in a list
69 * @sgl: First entry in the scatterlist
70 * @nents: Number of entries in the scatterlist
73 * Should only be used casually, it (currently) scans the entire list
74 * to get the last entry.
76 * Note that the @sgl pointer passed in need not be the first one,
77 * the important bit is that @nents denotes the number of entries that
81 struct scatterlist *sg_last(struct scatterlist *sgl, unsigned int nents)
83 struct scatterlist *sg, *ret = NULL;
86 for_each_sg(sgl, sg, nents, i)
89 BUG_ON(!sg_is_last(ret));
92 EXPORT_SYMBOL(sg_last);
95 * sg_init_table - Initialize SG table
97 * @nents: Number of entries in table
100 * If this is part of a chained sg table, sg_mark_end() should be
101 * used only on the last table part.
104 void sg_init_table(struct scatterlist *sgl, unsigned int nents)
106 memset(sgl, 0, sizeof(*sgl) * nents);
107 sg_init_marker(sgl, nents);
109 EXPORT_SYMBOL(sg_init_table);
112 * sg_init_one - Initialize a single entry sg list
114 * @buf: Virtual address for IO
118 void sg_init_one(struct scatterlist *sg, const void *buf, unsigned int buflen)
120 sg_init_table(sg, 1);
121 sg_set_buf(sg, buf, buflen);
123 EXPORT_SYMBOL(sg_init_one);
126 * The default behaviour of sg_alloc_table() is to use these kmalloc/kfree
129 static struct scatterlist *sg_kmalloc(unsigned int nents, gfp_t gfp_mask)
131 if (nents == SG_MAX_SINGLE_ALLOC) {
133 * Kmemleak doesn't track page allocations as they are not
134 * commonly used (in a raw form) for kernel data structures.
135 * As we chain together a list of pages and then a normal
136 * kmalloc (tracked by kmemleak), in order to for that last
137 * allocation not to become decoupled (and thus a
138 * false-positive) we need to inform kmemleak of all the
139 * intermediate allocations.
141 void *ptr = (void *) __get_free_page(gfp_mask);
142 kmemleak_alloc(ptr, PAGE_SIZE, 1, gfp_mask);
145 return kmalloc_array(nents, sizeof(struct scatterlist),
149 static void sg_kfree(struct scatterlist *sg, unsigned int nents)
151 if (nents == SG_MAX_SINGLE_ALLOC) {
153 free_page((unsigned long) sg);
159 * __sg_free_table - Free a previously mapped sg table
160 * @table: The sg table header to use
161 * @max_ents: The maximum number of entries per single scatterlist
162 * @nents_first_chunk: Number of entries int the (preallocated) first
163 * scatterlist chunk, 0 means no such preallocated first chunk
164 * @free_fn: Free function
165 * @num_ents: Number of entries in the table
168 * Free an sg table previously allocated and setup with
169 * __sg_alloc_table(). The @max_ents value must be identical to
170 * that previously used with __sg_alloc_table().
173 void __sg_free_table(struct sg_table *table, unsigned int max_ents,
174 unsigned int nents_first_chunk, sg_free_fn *free_fn,
175 unsigned int num_ents)
177 struct scatterlist *sgl, *next;
178 unsigned curr_max_ents = nents_first_chunk ?: max_ents;
180 if (unlikely(!table->sgl))
185 unsigned int alloc_size = num_ents;
186 unsigned int sg_size;
189 * If we have more than max_ents segments left,
190 * then assign 'next' to the sg table after the current one.
191 * sg_size is then one less than alloc size, since the last
192 * element is the chain pointer.
194 if (alloc_size > curr_max_ents) {
195 next = sg_chain_ptr(&sgl[curr_max_ents - 1]);
196 alloc_size = curr_max_ents;
197 sg_size = alloc_size - 1;
199 sg_size = alloc_size;
204 if (nents_first_chunk)
205 nents_first_chunk = 0;
207 free_fn(sgl, alloc_size);
209 curr_max_ents = max_ents;
214 EXPORT_SYMBOL(__sg_free_table);
217 * sg_free_append_table - Free a previously allocated append sg table.
218 * @table: The mapped sg append table header
221 void sg_free_append_table(struct sg_append_table *table)
223 __sg_free_table(&table->sgt, SG_MAX_SINGLE_ALLOC, 0, sg_kfree,
226 EXPORT_SYMBOL(sg_free_append_table);
230 * sg_free_table - Free a previously allocated sg table
231 * @table: The mapped sg table header
234 void sg_free_table(struct sg_table *table)
236 __sg_free_table(table, SG_MAX_SINGLE_ALLOC, 0, sg_kfree,
239 EXPORT_SYMBOL(sg_free_table);
242 * __sg_alloc_table - Allocate and initialize an sg table with given allocator
243 * @table: The sg table header to use
244 * @nents: Number of entries in sg list
245 * @max_ents: The maximum number of entries the allocator returns per call
246 * @first_chunk: first SGL if preallocated (may be %NULL)
247 * @nents_first_chunk: Number of entries in the (preallocated) first
248 * scatterlist chunk, 0 means no such preallocated chunk provided by user
249 * @gfp_mask: GFP allocation mask
250 * @alloc_fn: Allocator to use
253 * This function returns a @table @nents long. The allocator is
254 * defined to return scatterlist chunks of maximum size @max_ents.
255 * Thus if @nents is bigger than @max_ents, the scatterlists will be
256 * chained in units of @max_ents.
259 * If this function returns non-0 (eg failure), the caller must call
260 * __sg_free_table() to cleanup any leftover allocations.
263 int __sg_alloc_table(struct sg_table *table, unsigned int nents,
264 unsigned int max_ents, struct scatterlist *first_chunk,
265 unsigned int nents_first_chunk, gfp_t gfp_mask,
266 sg_alloc_fn *alloc_fn)
268 struct scatterlist *sg, *prv;
270 unsigned curr_max_ents = nents_first_chunk ?: max_ents;
271 unsigned prv_max_ents;
273 memset(table, 0, sizeof(*table));
277 #ifdef CONFIG_ARCH_NO_SG_CHAIN
278 if (WARN_ON_ONCE(nents > max_ents))
285 unsigned int sg_size, alloc_size = left;
287 if (alloc_size > curr_max_ents) {
288 alloc_size = curr_max_ents;
289 sg_size = alloc_size - 1;
291 sg_size = alloc_size;
299 sg = alloc_fn(alloc_size, gfp_mask);
303 * Adjust entry count to reflect that the last
304 * entry of the previous table won't be used for
305 * linkage. Without this, sg_kfree() may get
309 table->nents = ++table->orig_nents;
314 sg_init_table(sg, alloc_size);
315 table->nents = table->orig_nents += sg_size;
318 * If this is the first mapping, assign the sg table header.
319 * If this is not the first mapping, chain previous part.
322 sg_chain(prv, prv_max_ents, sg);
327 * If no more entries after this one, mark the end
330 sg_mark_end(&sg[sg_size - 1]);
333 prv_max_ents = curr_max_ents;
334 curr_max_ents = max_ents;
339 EXPORT_SYMBOL(__sg_alloc_table);
342 * sg_alloc_table - Allocate and initialize an sg table
343 * @table: The sg table header to use
344 * @nents: Number of entries in sg list
345 * @gfp_mask: GFP allocation mask
348 * Allocate and initialize an sg table. If @nents is larger than
349 * SG_MAX_SINGLE_ALLOC a chained sg table will be setup.
352 int sg_alloc_table(struct sg_table *table, unsigned int nents, gfp_t gfp_mask)
356 ret = __sg_alloc_table(table, nents, SG_MAX_SINGLE_ALLOC,
357 NULL, 0, gfp_mask, sg_kmalloc);
359 sg_free_table(table);
362 EXPORT_SYMBOL(sg_alloc_table);
364 static struct scatterlist *get_next_sg(struct sg_append_table *table,
365 struct scatterlist *cur,
366 unsigned long needed_sges,
369 struct scatterlist *new_sg, *next_sg;
370 unsigned int alloc_size;
373 next_sg = sg_next(cur);
374 /* Check if last entry should be keeped for chainning */
375 if (!sg_is_last(next_sg) || needed_sges == 1)
379 alloc_size = min_t(unsigned long, needed_sges, SG_MAX_SINGLE_ALLOC);
380 new_sg = sg_kmalloc(alloc_size, gfp_mask);
382 return ERR_PTR(-ENOMEM);
383 sg_init_table(new_sg, alloc_size);
385 table->total_nents += alloc_size - 1;
386 __sg_chain(next_sg, new_sg);
388 table->sgt.sgl = new_sg;
389 table->total_nents = alloc_size;
394 static bool pages_are_mergeable(struct page *a, struct page *b)
396 if (page_to_pfn(a) != page_to_pfn(b) + 1)
398 if (!zone_device_pages_have_same_pgmap(a, b))
404 * sg_alloc_append_table_from_pages - Allocate and initialize an append sg
405 * table from an array of pages
406 * @sgt_append: The sg append table to use
407 * @pages: Pointer to an array of page pointers
408 * @n_pages: Number of pages in the pages array
409 * @offset: Offset from start of the first page to the start of a buffer
410 * @size: Number of valid bytes in the buffer (after offset)
411 * @max_segment: Maximum size of a scatterlist element in bytes
412 * @left_pages: Left pages caller have to set after this call
413 * @gfp_mask: GFP allocation mask
416 * In the first call it allocate and initialize an sg table from a list of
417 * pages, else reuse the scatterlist from sgt_append. Contiguous ranges of
418 * the pages are squashed into a single scatterlist entry up to the maximum
419 * size specified in @max_segment. A user may provide an offset at a start
420 * and a size of valid data in a buffer specified by the page array. The
421 * returned sg table is released by sg_free_append_table
424 * 0 on success, negative error on failure
427 * If this function returns non-0 (eg failure), the caller must call
428 * sg_free_append_table() to cleanup any leftover allocations.
430 * In the fist call, sgt_append must by initialized.
432 int sg_alloc_append_table_from_pages(struct sg_append_table *sgt_append,
433 struct page **pages, unsigned int n_pages, unsigned int offset,
434 unsigned long size, unsigned int max_segment,
435 unsigned int left_pages, gfp_t gfp_mask)
437 unsigned int chunks, cur_page, seg_len, i, prv_len = 0;
438 unsigned int added_nents = 0;
439 struct scatterlist *s = sgt_append->prv;
440 struct page *last_pg;
443 * The algorithm below requires max_segment to be aligned to PAGE_SIZE
444 * otherwise it can overshoot.
446 max_segment = ALIGN_DOWN(max_segment, PAGE_SIZE);
447 if (WARN_ON(max_segment < PAGE_SIZE))
450 if (IS_ENABLED(CONFIG_ARCH_NO_SG_CHAIN) && sgt_append->prv)
453 if (sgt_append->prv) {
454 unsigned long next_pfn;
459 /* Merge contiguous pages into the last SG */
460 prv_len = sgt_append->prv->length;
461 next_pfn = (sg_phys(sgt_append->prv) + prv_len) / PAGE_SIZE;
462 if (page_to_pfn(pages[0]) == next_pfn) {
463 last_pg = pfn_to_page(next_pfn - 1);
464 while (n_pages && pages_are_mergeable(pages[0], last_pg)) {
465 if (sgt_append->prv->length + PAGE_SIZE > max_segment)
467 sgt_append->prv->length += PAGE_SIZE;
477 /* compute number of contiguous chunks */
480 for (i = 1; i < n_pages; i++) {
481 seg_len += PAGE_SIZE;
482 if (seg_len >= max_segment ||
483 !pages_are_mergeable(pages[i], pages[i - 1])) {
489 /* merging chunks and putting them into the scatterlist */
491 for (i = 0; i < chunks; i++) {
492 unsigned int j, chunk_size;
494 /* look for the end of the current chunk */
496 for (j = cur_page + 1; j < n_pages; j++) {
497 seg_len += PAGE_SIZE;
498 if (seg_len >= max_segment ||
499 !pages_are_mergeable(pages[j], pages[j - 1]))
503 /* Pass how many chunks might be left */
504 s = get_next_sg(sgt_append, s, chunks - i + left_pages,
508 * Adjust entry length to be as before function was
512 sgt_append->prv->length = prv_len;
515 chunk_size = ((j - cur_page) << PAGE_SHIFT) - offset;
516 sg_set_page(s, pages[cur_page],
517 min_t(unsigned long, size, chunk_size), offset);
523 sgt_append->sgt.nents += added_nents;
524 sgt_append->sgt.orig_nents = sgt_append->sgt.nents;
531 EXPORT_SYMBOL(sg_alloc_append_table_from_pages);
534 * sg_alloc_table_from_pages_segment - Allocate and initialize an sg table from
535 * an array of pages and given maximum
537 * @sgt: The sg table header to use
538 * @pages: Pointer to an array of page pointers
539 * @n_pages: Number of pages in the pages array
540 * @offset: Offset from start of the first page to the start of a buffer
541 * @size: Number of valid bytes in the buffer (after offset)
542 * @max_segment: Maximum size of a scatterlist element in bytes
543 * @gfp_mask: GFP allocation mask
546 * Allocate and initialize an sg table from a list of pages. Contiguous
547 * ranges of the pages are squashed into a single scatterlist node up to the
548 * maximum size specified in @max_segment. A user may provide an offset at a
549 * start and a size of valid data in a buffer specified by the page array.
551 * The returned sg table is released by sg_free_table.
554 * 0 on success, negative error on failure
556 int sg_alloc_table_from_pages_segment(struct sg_table *sgt, struct page **pages,
557 unsigned int n_pages, unsigned int offset,
558 unsigned long size, unsigned int max_segment,
561 struct sg_append_table append = {};
564 err = sg_alloc_append_table_from_pages(&append, pages, n_pages, offset,
565 size, max_segment, 0, gfp_mask);
567 sg_free_append_table(&append);
570 memcpy(sgt, &append.sgt, sizeof(*sgt));
571 WARN_ON(append.total_nents != sgt->orig_nents);
574 EXPORT_SYMBOL(sg_alloc_table_from_pages_segment);
576 #ifdef CONFIG_SGL_ALLOC
579 * sgl_alloc_order - allocate a scatterlist and its pages
580 * @length: Length in bytes of the scatterlist. Must be at least one
581 * @order: Second argument for alloc_pages()
582 * @chainable: Whether or not to allocate an extra element in the scatterlist
583 * for scatterlist chaining purposes
584 * @gfp: Memory allocation flags
585 * @nent_p: [out] Number of entries in the scatterlist that have pages
587 * Returns: A pointer to an initialized scatterlist or %NULL upon failure.
589 struct scatterlist *sgl_alloc_order(unsigned long long length,
590 unsigned int order, bool chainable,
591 gfp_t gfp, unsigned int *nent_p)
593 struct scatterlist *sgl, *sg;
595 unsigned int nent, nalloc;
598 nent = round_up(length, PAGE_SIZE << order) >> (PAGE_SHIFT + order);
599 /* Check for integer overflow */
600 if (length > (nent << (PAGE_SHIFT + order)))
604 /* Check for integer overflow */
605 if (nalloc + 1 < nalloc)
609 sgl = kmalloc_array(nalloc, sizeof(struct scatterlist),
614 sg_init_table(sgl, nalloc);
617 elem_len = min_t(u64, length, PAGE_SIZE << order);
618 page = alloc_pages(gfp, order);
620 sgl_free_order(sgl, order);
624 sg_set_page(sg, page, elem_len, 0);
628 WARN_ONCE(length, "length = %lld\n", length);
633 EXPORT_SYMBOL(sgl_alloc_order);
636 * sgl_alloc - allocate a scatterlist and its pages
637 * @length: Length in bytes of the scatterlist
638 * @gfp: Memory allocation flags
639 * @nent_p: [out] Number of entries in the scatterlist
641 * Returns: A pointer to an initialized scatterlist or %NULL upon failure.
643 struct scatterlist *sgl_alloc(unsigned long long length, gfp_t gfp,
644 unsigned int *nent_p)
646 return sgl_alloc_order(length, 0, false, gfp, nent_p);
648 EXPORT_SYMBOL(sgl_alloc);
651 * sgl_free_n_order - free a scatterlist and its pages
652 * @sgl: Scatterlist with one or more elements
653 * @nents: Maximum number of elements to free
654 * @order: Second argument for __free_pages()
657 * - If several scatterlists have been chained and each chain element is
658 * freed separately then it's essential to set nents correctly to avoid that a
659 * page would get freed twice.
660 * - All pages in a chained scatterlist can be freed at once by setting @nents
663 void sgl_free_n_order(struct scatterlist *sgl, int nents, int order)
665 struct scatterlist *sg;
669 for_each_sg(sgl, sg, nents, i) {
674 __free_pages(page, order);
678 EXPORT_SYMBOL(sgl_free_n_order);
681 * sgl_free_order - free a scatterlist and its pages
682 * @sgl: Scatterlist with one or more elements
683 * @order: Second argument for __free_pages()
685 void sgl_free_order(struct scatterlist *sgl, int order)
687 sgl_free_n_order(sgl, INT_MAX, order);
689 EXPORT_SYMBOL(sgl_free_order);
692 * sgl_free - free a scatterlist and its pages
693 * @sgl: Scatterlist with one or more elements
695 void sgl_free(struct scatterlist *sgl)
697 sgl_free_order(sgl, 0);
699 EXPORT_SYMBOL(sgl_free);
701 #endif /* CONFIG_SGL_ALLOC */
703 void __sg_page_iter_start(struct sg_page_iter *piter,
704 struct scatterlist *sglist, unsigned int nents,
705 unsigned long pgoffset)
707 piter->__pg_advance = 0;
708 piter->__nents = nents;
711 piter->sg_pgoffset = pgoffset;
713 EXPORT_SYMBOL(__sg_page_iter_start);
715 static int sg_page_count(struct scatterlist *sg)
717 return PAGE_ALIGN(sg->offset + sg->length) >> PAGE_SHIFT;
720 bool __sg_page_iter_next(struct sg_page_iter *piter)
722 if (!piter->__nents || !piter->sg)
725 piter->sg_pgoffset += piter->__pg_advance;
726 piter->__pg_advance = 1;
728 while (piter->sg_pgoffset >= sg_page_count(piter->sg)) {
729 piter->sg_pgoffset -= sg_page_count(piter->sg);
730 piter->sg = sg_next(piter->sg);
731 if (!--piter->__nents || !piter->sg)
737 EXPORT_SYMBOL(__sg_page_iter_next);
739 static int sg_dma_page_count(struct scatterlist *sg)
741 return PAGE_ALIGN(sg->offset + sg_dma_len(sg)) >> PAGE_SHIFT;
744 bool __sg_page_iter_dma_next(struct sg_dma_page_iter *dma_iter)
746 struct sg_page_iter *piter = &dma_iter->base;
748 if (!piter->__nents || !piter->sg)
751 piter->sg_pgoffset += piter->__pg_advance;
752 piter->__pg_advance = 1;
754 while (piter->sg_pgoffset >= sg_dma_page_count(piter->sg)) {
755 piter->sg_pgoffset -= sg_dma_page_count(piter->sg);
756 piter->sg = sg_next(piter->sg);
757 if (!--piter->__nents || !piter->sg)
763 EXPORT_SYMBOL(__sg_page_iter_dma_next);
766 * sg_miter_start - start mapping iteration over a sg list
767 * @miter: sg mapping iter to be started
768 * @sgl: sg list to iterate over
769 * @nents: number of sg entries
770 * @flags: sg iterator flags
773 * Starts mapping iterator @miter.
778 void sg_miter_start(struct sg_mapping_iter *miter, struct scatterlist *sgl,
779 unsigned int nents, unsigned int flags)
781 memset(miter, 0, sizeof(struct sg_mapping_iter));
783 __sg_page_iter_start(&miter->piter, sgl, nents, 0);
784 WARN_ON(!(flags & (SG_MITER_TO_SG | SG_MITER_FROM_SG)));
785 miter->__flags = flags;
787 EXPORT_SYMBOL(sg_miter_start);
789 static bool sg_miter_get_next_page(struct sg_mapping_iter *miter)
791 if (!miter->__remaining) {
792 struct scatterlist *sg;
794 if (!__sg_page_iter_next(&miter->piter))
797 sg = miter->piter.sg;
799 miter->__offset = miter->piter.sg_pgoffset ? 0 : sg->offset;
800 miter->piter.sg_pgoffset += miter->__offset >> PAGE_SHIFT;
801 miter->__offset &= PAGE_SIZE - 1;
802 miter->__remaining = sg->offset + sg->length -
803 (miter->piter.sg_pgoffset << PAGE_SHIFT) -
805 miter->__remaining = min_t(unsigned long, miter->__remaining,
806 PAGE_SIZE - miter->__offset);
813 * sg_miter_skip - reposition mapping iterator
814 * @miter: sg mapping iter to be skipped
815 * @offset: number of bytes to plus the current location
818 * Sets the offset of @miter to its current location plus @offset bytes.
819 * If mapping iterator @miter has been proceeded by sg_miter_next(), this
826 * true if @miter contains the valid mapping. false if end of sg
829 bool sg_miter_skip(struct sg_mapping_iter *miter, off_t offset)
831 sg_miter_stop(miter);
836 if (!sg_miter_get_next_page(miter))
839 consumed = min_t(off_t, offset, miter->__remaining);
840 miter->__offset += consumed;
841 miter->__remaining -= consumed;
847 EXPORT_SYMBOL(sg_miter_skip);
850 * sg_miter_next - proceed mapping iterator to the next mapping
851 * @miter: sg mapping iter to proceed
854 * Proceeds @miter to the next mapping. @miter should have been started
855 * using sg_miter_start(). On successful return, @miter->page,
856 * @miter->addr and @miter->length point to the current mapping.
859 * May sleep if !SG_MITER_ATOMIC && !SG_MITER_LOCAL.
862 * true if @miter contains the next mapping. false if end of sg
865 bool sg_miter_next(struct sg_mapping_iter *miter)
867 sg_miter_stop(miter);
870 * Get to the next page if necessary.
871 * __remaining, __offset is adjusted by sg_miter_stop
873 if (!sg_miter_get_next_page(miter))
876 miter->page = sg_page_iter_page(&miter->piter);
877 miter->consumed = miter->length = miter->__remaining;
879 if (miter->__flags & SG_MITER_ATOMIC)
880 miter->addr = kmap_atomic(miter->page) + miter->__offset;
881 else if (miter->__flags & SG_MITER_LOCAL)
882 miter->addr = kmap_local_page(miter->page) + miter->__offset;
884 miter->addr = kmap(miter->page) + miter->__offset;
888 EXPORT_SYMBOL(sg_miter_next);
891 * sg_miter_stop - stop mapping iteration
892 * @miter: sg mapping iter to be stopped
895 * Stops mapping iterator @miter. @miter should have been started
896 * using sg_miter_start(). A stopped iteration can be resumed by
897 * calling sg_miter_next() on it. This is useful when resources (kmap)
898 * need to be released during iteration.
901 * Don't care otherwise.
903 void sg_miter_stop(struct sg_mapping_iter *miter)
905 WARN_ON(miter->consumed > miter->length);
907 /* drop resources from the last iteration */
909 miter->__offset += miter->consumed;
910 miter->__remaining -= miter->consumed;
912 if (miter->__flags & SG_MITER_TO_SG)
913 flush_dcache_page(miter->page);
915 if (miter->__flags & SG_MITER_ATOMIC) {
916 WARN_ON_ONCE(!pagefault_disabled());
917 kunmap_atomic(miter->addr);
918 } else if (miter->__flags & SG_MITER_LOCAL)
919 kunmap_local(miter->addr);
929 EXPORT_SYMBOL(sg_miter_stop);
932 * sg_copy_buffer - Copy data between a linear buffer and an SG list
934 * @nents: Number of SG entries
935 * @buf: Where to copy from
936 * @buflen: The number of bytes to copy
937 * @skip: Number of bytes to skip before copying
938 * @to_buffer: transfer direction (true == from an sg list to a
939 * buffer, false == from a buffer to an sg list)
941 * Returns the number of copied bytes.
944 size_t sg_copy_buffer(struct scatterlist *sgl, unsigned int nents, void *buf,
945 size_t buflen, off_t skip, bool to_buffer)
947 unsigned int offset = 0;
948 struct sg_mapping_iter miter;
949 unsigned int sg_flags = SG_MITER_LOCAL;
952 sg_flags |= SG_MITER_FROM_SG;
954 sg_flags |= SG_MITER_TO_SG;
956 sg_miter_start(&miter, sgl, nents, sg_flags);
958 if (!sg_miter_skip(&miter, skip))
961 while ((offset < buflen) && sg_miter_next(&miter)) {
964 len = min(miter.length, buflen - offset);
967 memcpy(buf + offset, miter.addr, len);
969 memcpy(miter.addr, buf + offset, len);
974 sg_miter_stop(&miter);
978 EXPORT_SYMBOL(sg_copy_buffer);
981 * sg_copy_from_buffer - Copy from a linear buffer to an SG list
983 * @nents: Number of SG entries
984 * @buf: Where to copy from
985 * @buflen: The number of bytes to copy
987 * Returns the number of copied bytes.
990 size_t sg_copy_from_buffer(struct scatterlist *sgl, unsigned int nents,
991 const void *buf, size_t buflen)
993 return sg_copy_buffer(sgl, nents, (void *)buf, buflen, 0, false);
995 EXPORT_SYMBOL(sg_copy_from_buffer);
998 * sg_copy_to_buffer - Copy from an SG list to a linear buffer
1000 * @nents: Number of SG entries
1001 * @buf: Where to copy to
1002 * @buflen: The number of bytes to copy
1004 * Returns the number of copied bytes.
1007 size_t sg_copy_to_buffer(struct scatterlist *sgl, unsigned int nents,
1008 void *buf, size_t buflen)
1010 return sg_copy_buffer(sgl, nents, buf, buflen, 0, true);
1012 EXPORT_SYMBOL(sg_copy_to_buffer);
1015 * sg_pcopy_from_buffer - Copy from a linear buffer to an SG list
1017 * @nents: Number of SG entries
1018 * @buf: Where to copy from
1019 * @buflen: The number of bytes to copy
1020 * @skip: Number of bytes to skip before copying
1022 * Returns the number of copied bytes.
1025 size_t sg_pcopy_from_buffer(struct scatterlist *sgl, unsigned int nents,
1026 const void *buf, size_t buflen, off_t skip)
1028 return sg_copy_buffer(sgl, nents, (void *)buf, buflen, skip, false);
1030 EXPORT_SYMBOL(sg_pcopy_from_buffer);
1033 * sg_pcopy_to_buffer - Copy from an SG list to a linear buffer
1035 * @nents: Number of SG entries
1036 * @buf: Where to copy to
1037 * @buflen: The number of bytes to copy
1038 * @skip: Number of bytes to skip before copying
1040 * Returns the number of copied bytes.
1043 size_t sg_pcopy_to_buffer(struct scatterlist *sgl, unsigned int nents,
1044 void *buf, size_t buflen, off_t skip)
1046 return sg_copy_buffer(sgl, nents, buf, buflen, skip, true);
1048 EXPORT_SYMBOL(sg_pcopy_to_buffer);
1051 * sg_zero_buffer - Zero-out a part of a SG list
1053 * @nents: Number of SG entries
1054 * @buflen: The number of bytes to zero out
1055 * @skip: Number of bytes to skip before zeroing
1057 * Returns the number of bytes zeroed.
1059 size_t sg_zero_buffer(struct scatterlist *sgl, unsigned int nents,
1060 size_t buflen, off_t skip)
1062 unsigned int offset = 0;
1063 struct sg_mapping_iter miter;
1064 unsigned int sg_flags = SG_MITER_LOCAL | SG_MITER_TO_SG;
1066 sg_miter_start(&miter, sgl, nents, sg_flags);
1068 if (!sg_miter_skip(&miter, skip))
1071 while (offset < buflen && sg_miter_next(&miter)) {
1074 len = min(miter.length, buflen - offset);
1075 memset(miter.addr, 0, len);
1080 sg_miter_stop(&miter);
1083 EXPORT_SYMBOL(sg_zero_buffer);
1086 * Extract and pin a list of up to sg_max pages from UBUF- or IOVEC-class
1087 * iterators, and add them to the scatterlist.
1089 static ssize_t extract_user_to_sg(struct iov_iter *iter,
1091 struct sg_table *sgtable,
1092 unsigned int sg_max,
1093 iov_iter_extraction_t extraction_flags)
1095 struct scatterlist *sg = sgtable->sgl + sgtable->nents;
1096 struct page **pages;
1097 unsigned int npages;
1098 ssize_t ret = 0, res;
1101 /* We decant the page list into the tail of the scatterlist */
1102 pages = (void *)sgtable->sgl +
1103 array_size(sg_max, sizeof(struct scatterlist));
1107 res = iov_iter_extract_pages(iter, &pages, maxsize, sg_max,
1108 extraction_flags, &off);
1115 npages = DIV_ROUND_UP(off + len, PAGE_SIZE);
1118 for (; npages > 0; npages--) {
1119 struct page *page = *pages;
1120 size_t seg = min_t(size_t, PAGE_SIZE - off, len);
1123 sg_set_page(sg, page, seg, off);
1129 } while (maxsize > 0 && sg_max > 0);
1134 while (sgtable->nents > sgtable->orig_nents)
1135 unpin_user_page(sg_page(&sgtable->sgl[--sgtable->nents]));
1140 * Extract up to sg_max pages from a BVEC-type iterator and add them to the
1141 * scatterlist. The pages are not pinned.
1143 static ssize_t extract_bvec_to_sg(struct iov_iter *iter,
1145 struct sg_table *sgtable,
1146 unsigned int sg_max,
1147 iov_iter_extraction_t extraction_flags)
1149 const struct bio_vec *bv = iter->bvec;
1150 struct scatterlist *sg = sgtable->sgl + sgtable->nents;
1151 unsigned long start = iter->iov_offset;
1155 for (i = 0; i < iter->nr_segs; i++) {
1164 len = min_t(size_t, maxsize, len - start);
1165 off = bv[i].bv_offset + start;
1167 sg_set_page(sg, bv[i].bv_page, len, off);
1174 if (maxsize <= 0 || sg_max == 0)
1180 iov_iter_advance(iter, ret);
1185 * Extract up to sg_max pages from a KVEC-type iterator and add them to the
1186 * scatterlist. This can deal with vmalloc'd buffers as well as kmalloc'd or
1187 * static buffers. The pages are not pinned.
1189 static ssize_t extract_kvec_to_sg(struct iov_iter *iter,
1191 struct sg_table *sgtable,
1192 unsigned int sg_max,
1193 iov_iter_extraction_t extraction_flags)
1195 const struct kvec *kv = iter->kvec;
1196 struct scatterlist *sg = sgtable->sgl + sgtable->nents;
1197 unsigned long start = iter->iov_offset;
1201 for (i = 0; i < iter->nr_segs; i++) {
1203 unsigned long kaddr;
1204 size_t off, len, seg;
1206 len = kv[i].iov_len;
1212 kaddr = (unsigned long)kv[i].iov_base + start;
1213 off = kaddr & ~PAGE_MASK;
1214 len = min_t(size_t, maxsize, len - start);
1220 seg = min_t(size_t, len, PAGE_SIZE - off);
1221 if (is_vmalloc_or_module_addr((void *)kaddr))
1222 page = vmalloc_to_page((void *)kaddr);
1224 page = virt_to_page((void *)kaddr);
1226 sg_set_page(sg, page, len, off);
1234 } while (len > 0 && sg_max > 0);
1236 if (maxsize <= 0 || sg_max == 0)
1242 iov_iter_advance(iter, ret);
1247 * Extract up to sg_max folios from an FOLIOQ-type iterator and add them to
1248 * the scatterlist. The pages are not pinned.
1250 static ssize_t extract_folioq_to_sg(struct iov_iter *iter,
1252 struct sg_table *sgtable,
1253 unsigned int sg_max,
1254 iov_iter_extraction_t extraction_flags)
1256 const struct folio_queue *folioq = iter->folioq;
1257 struct scatterlist *sg = sgtable->sgl + sgtable->nents;
1258 unsigned int slot = iter->folioq_slot;
1260 size_t offset = iter->iov_offset;
1264 if (slot >= folioq_nr_slots(folioq)) {
1265 folioq = folioq->next;
1266 if (WARN_ON_ONCE(!folioq))
1272 struct folio *folio = folioq_folio(folioq, slot);
1273 size_t fsize = folioq_folio_size(folioq, slot);
1275 if (offset < fsize) {
1276 size_t part = umin(maxsize - ret, fsize - offset);
1278 sg_set_page(sg, folio_page(folio, 0), part, offset);
1286 if (offset >= fsize) {
1289 if (slot >= folioq_nr_slots(folioq)) {
1290 if (!folioq->next) {
1291 WARN_ON_ONCE(ret < iter->count);
1294 folioq = folioq->next;
1298 } while (sg_max > 0 && ret < maxsize);
1300 iter->folioq = folioq;
1301 iter->folioq_slot = slot;
1302 iter->iov_offset = offset;
1308 * Extract up to sg_max folios from an XARRAY-type iterator and add them to
1309 * the scatterlist. The pages are not pinned.
1311 static ssize_t extract_xarray_to_sg(struct iov_iter *iter,
1313 struct sg_table *sgtable,
1314 unsigned int sg_max,
1315 iov_iter_extraction_t extraction_flags)
1317 struct scatterlist *sg = sgtable->sgl + sgtable->nents;
1318 struct xarray *xa = iter->xarray;
1319 struct folio *folio;
1320 loff_t start = iter->xarray_start + iter->iov_offset;
1321 pgoff_t index = start / PAGE_SIZE;
1324 XA_STATE(xas, xa, index);
1328 xas_for_each(&xas, folio, ULONG_MAX) {
1329 if (xas_retry(&xas, folio))
1331 if (WARN_ON(xa_is_value(folio)))
1333 if (WARN_ON(folio_test_hugetlb(folio)))
1336 offset = offset_in_folio(folio, start);
1337 len = min_t(size_t, maxsize, folio_size(folio) - offset);
1339 sg_set_page(sg, folio_page(folio, 0), len, offset);
1346 if (maxsize <= 0 || sg_max == 0)
1352 iov_iter_advance(iter, ret);
1357 * extract_iter_to_sg - Extract pages from an iterator and add to an sglist
1358 * @iter: The iterator to extract from
1359 * @maxsize: The amount of iterator to copy
1360 * @sgtable: The scatterlist table to fill in
1361 * @sg_max: Maximum number of elements in @sgtable that may be filled
1362 * @extraction_flags: Flags to qualify the request
1364 * Extract the page fragments from the given amount of the source iterator and
1365 * add them to a scatterlist that refers to all of those bits, to a maximum
1366 * addition of @sg_max elements.
1368 * The pages referred to by UBUF- and IOVEC-type iterators are extracted and
1369 * pinned; BVEC-, KVEC-, FOLIOQ- and XARRAY-type are extracted but aren't
1370 * pinned; DISCARD-type is not supported.
1372 * No end mark is placed on the scatterlist; that's left to the caller.
1374 * @extraction_flags can have ITER_ALLOW_P2PDMA set to request peer-to-peer DMA
1375 * be allowed on the pages extracted.
1377 * If successful, @sgtable->nents is updated to include the number of elements
1378 * added and the number of bytes added is returned. @sgtable->orig_nents is
1381 * The iov_iter_extract_mode() function should be used to query how cleanup
1382 * should be performed.
1384 ssize_t extract_iter_to_sg(struct iov_iter *iter, size_t maxsize,
1385 struct sg_table *sgtable, unsigned int sg_max,
1386 iov_iter_extraction_t extraction_flags)
1391 switch (iov_iter_type(iter)) {
1394 return extract_user_to_sg(iter, maxsize, sgtable, sg_max,
1397 return extract_bvec_to_sg(iter, maxsize, sgtable, sg_max,
1400 return extract_kvec_to_sg(iter, maxsize, sgtable, sg_max,
1403 return extract_folioq_to_sg(iter, maxsize, sgtable, sg_max,
1406 return extract_xarray_to_sg(iter, maxsize, sgtable, sg_max,
1409 pr_err("%s(%u) unsupported\n", __func__, iov_iter_type(iter));
1414 EXPORT_SYMBOL_GPL(extract_iter_to_sg);