2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2008 Yahoo!, Inc.
6 * Written by: John Baldwin <jhb@FreeBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the author nor the names of any co-contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/kernel.h>
39 #include <sys/malloc.h>
42 #include <sys/sglist.h>
46 #include <vm/vm_page.h>
48 #include <vm/vm_map.h>
52 static MALLOC_DEFINE(M_SGLIST, "sglist", "scatter/gather lists");
55 * Convenience macros to save the state of an sglist so it can be restored
56 * if an append attempt fails. Since sglist's only grow we only need to
57 * save the current count of segments and the length of the ending segment.
58 * Earlier segments will not be changed by an append, and the only change
59 * that can occur to the ending segment is that it can be extended.
66 #define SGLIST_SAVE(sg, sgsave) do { \
67 (sgsave).sg_nseg = (sg)->sg_nseg; \
68 if ((sgsave).sg_nseg > 0) \
69 (sgsave).ss_len = (sg)->sg_segs[(sgsave).sg_nseg - 1].ss_len; \
71 (sgsave).ss_len = 0; \
74 #define SGLIST_RESTORE(sg, sgsave) do { \
75 (sg)->sg_nseg = (sgsave).sg_nseg; \
76 if ((sgsave).sg_nseg > 0) \
77 (sg)->sg_segs[(sgsave).sg_nseg - 1].ss_len = (sgsave).ss_len; \
81 * Append a single (paddr, len) to a sglist. sg is the list and ss is
82 * the current segment in the list. If we run out of segments then
83 * EFBIG will be returned.
86 _sglist_append_range(struct sglist *sg, struct sglist_seg **ssp,
87 vm_paddr_t paddr, size_t len)
89 struct sglist_seg *ss;
92 if (ss->ss_paddr + ss->ss_len == paddr)
95 if (sg->sg_nseg == sg->sg_maxseg)
107 * Worker routine to append a virtual address range (either kernel or
108 * user) to a scatter/gather list.
111 _sglist_append_buf(struct sglist *sg, void *buf, size_t len, pmap_t pmap,
114 struct sglist_seg *ss;
115 vm_offset_t vaddr, offset;
125 /* Do the first page. It may have an offset. */
126 vaddr = (vm_offset_t)buf;
127 offset = vaddr & PAGE_MASK;
129 paddr = pmap_extract(pmap, vaddr);
131 paddr = pmap_kextract(vaddr);
132 seglen = MIN(len, PAGE_SIZE - offset);
133 if (sg->sg_nseg == 0) {
135 ss->ss_paddr = paddr;
139 ss = &sg->sg_segs[sg->sg_nseg - 1];
140 error = _sglist_append_range(sg, &ss, paddr, seglen);
150 seglen = MIN(len, PAGE_SIZE);
152 paddr = pmap_extract(pmap, vaddr);
154 paddr = pmap_kextract(vaddr);
155 error = _sglist_append_range(sg, &ss, paddr, seglen);
168 * Determine the number of scatter/gather list elements needed to
169 * describe a kernel virtual address range.
172 sglist_count(void *buf, size_t len)
174 vm_offset_t vaddr, vendaddr;
175 vm_paddr_t lastaddr, paddr;
181 vaddr = trunc_page((vm_offset_t)buf);
182 vendaddr = (vm_offset_t)buf + len;
184 lastaddr = pmap_kextract(vaddr);
186 while (vaddr < vendaddr) {
187 paddr = pmap_kextract(vaddr);
188 if (lastaddr + PAGE_SIZE != paddr)
197 * Determine the number of scatter/gather list elements needed to
198 * describe a buffer backed by an array of VM pages.
201 sglist_count_vmpages(vm_page_t *m, size_t pgoff, size_t len)
203 vm_paddr_t lastaddr, paddr;
211 lastaddr = VM_PAGE_TO_PHYS(m[0]);
212 for (i = 1; len > PAGE_SIZE; len -= PAGE_SIZE, i++) {
213 paddr = VM_PAGE_TO_PHYS(m[i]);
214 if (lastaddr + PAGE_SIZE != paddr)
222 * Allocate a scatter/gather list along with 'nsegs' segments. The
223 * 'mflags' parameters are the same as passed to malloc(9). The caller
224 * should use sglist_free() to free this list.
227 sglist_alloc(int nsegs, int mflags)
231 sg = malloc(sizeof(struct sglist) + nsegs * sizeof(struct sglist_seg),
235 sglist_init(sg, nsegs, (struct sglist_seg *)(sg + 1));
240 * Free a scatter/gather list allocated via sglist_allc().
243 sglist_free(struct sglist *sg)
249 if (refcount_release(&sg->sg_refs))
254 * Append the segments to describe a single kernel virtual address
255 * range to a scatter/gather list. If there are insufficient
256 * segments, then this fails with EFBIG.
259 sglist_append(struct sglist *sg, void *buf, size_t len)
264 if (sg->sg_maxseg == 0)
266 SGLIST_SAVE(sg, save);
267 error = _sglist_append_buf(sg, buf, len, NULL, NULL);
269 SGLIST_RESTORE(sg, save);
274 * Append the segments to describe a bio's data to a scatter/gather list.
275 * If there are insufficient segments, then this fails with EFBIG.
277 * NOTE: This function expects bio_bcount to be initialized.
280 sglist_append_bio(struct sglist *sg, struct bio *bp)
284 if ((bp->bio_flags & BIO_UNMAPPED) == 0)
285 error = sglist_append(sg, bp->bio_data, bp->bio_bcount);
287 error = sglist_append_vmpages(sg, bp->bio_ma,
288 bp->bio_ma_offset, bp->bio_bcount);
293 * Append a single physical address range to a scatter/gather list.
294 * If there are insufficient segments, then this fails with EFBIG.
297 sglist_append_phys(struct sglist *sg, vm_paddr_t paddr, size_t len)
299 struct sglist_seg *ss;
303 if (sg->sg_maxseg == 0)
308 if (sg->sg_nseg == 0) {
309 sg->sg_segs[0].ss_paddr = paddr;
310 sg->sg_segs[0].ss_len = len;
314 ss = &sg->sg_segs[sg->sg_nseg - 1];
315 SGLIST_SAVE(sg, save);
316 error = _sglist_append_range(sg, &ss, paddr, len);
318 SGLIST_RESTORE(sg, save);
323 * Append the segments that describe a single mbuf chain to a
324 * scatter/gather list. If there are insufficient segments, then this
328 sglist_append_mbuf(struct sglist *sg, struct mbuf *m0)
334 if (sg->sg_maxseg == 0)
338 SGLIST_SAVE(sg, save);
339 for (m = m0; m != NULL; m = m->m_next) {
341 error = sglist_append(sg, m->m_data, m->m_len);
343 SGLIST_RESTORE(sg, save);
352 * Append the segments that describe a buffer spanning an array of VM
353 * pages. The buffer begins at an offset of 'pgoff' in the first
357 sglist_append_vmpages(struct sglist *sg, vm_page_t *m, size_t pgoff,
361 struct sglist_seg *ss;
366 if (sg->sg_maxseg == 0)
371 SGLIST_SAVE(sg, save);
373 if (sg->sg_nseg == 0) {
374 seglen = min(PAGE_SIZE - pgoff, len);
375 sg->sg_segs[0].ss_paddr = VM_PAGE_TO_PHYS(m[0]) + pgoff;
376 sg->sg_segs[0].ss_len = seglen;
382 ss = &sg->sg_segs[sg->sg_nseg - 1];
383 for (; len > 0; i++, len -= seglen) {
384 seglen = min(PAGE_SIZE - pgoff, len);
385 paddr = VM_PAGE_TO_PHYS(m[i]) + pgoff;
386 error = _sglist_append_range(sg, &ss, paddr, seglen);
388 SGLIST_RESTORE(sg, save);
397 * Append the segments that describe a single user address range to a
398 * scatter/gather list. If there are insufficient segments, then this
402 sglist_append_user(struct sglist *sg, void *buf, size_t len, struct thread *td)
407 if (sg->sg_maxseg == 0)
409 SGLIST_SAVE(sg, save);
410 error = _sglist_append_buf(sg, buf, len,
411 vmspace_pmap(td->td_proc->p_vmspace), NULL);
413 SGLIST_RESTORE(sg, save);
418 * Append a subset of an existing scatter/gather list 'source' to a
419 * the scatter/gather list 'sg'. If there are insufficient segments,
420 * then this fails with EFBIG.
423 sglist_append_sglist(struct sglist *sg, struct sglist *source, size_t offset,
427 struct sglist_seg *ss;
431 if (sg->sg_maxseg == 0 || length == 0)
433 SGLIST_SAVE(sg, save);
435 ss = &sg->sg_segs[sg->sg_nseg - 1];
436 for (i = 0; i < source->sg_nseg; i++) {
437 if (offset >= source->sg_segs[i].ss_len) {
438 offset -= source->sg_segs[i].ss_len;
441 seglen = source->sg_segs[i].ss_len - offset;
444 error = _sglist_append_range(sg, &ss,
445 source->sg_segs[i].ss_paddr + offset, seglen);
456 SGLIST_RESTORE(sg, save);
461 * Append the segments that describe a single uio to a scatter/gather
462 * list. If there are insufficient segments, then this fails with
466 sglist_append_uio(struct sglist *sg, struct uio *uio)
470 size_t resid, minlen;
474 if (sg->sg_maxseg == 0)
477 resid = uio->uio_resid;
480 if (uio->uio_segflg == UIO_USERSPACE) {
481 KASSERT(uio->uio_td != NULL,
482 ("sglist_append_uio: USERSPACE but no thread"));
483 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
488 SGLIST_SAVE(sg, save);
489 for (i = 0; i < uio->uio_iovcnt && resid != 0; i++) {
491 * Now at the first iovec to load. Load each iovec
492 * until we have exhausted the residual count.
494 minlen = MIN(resid, iov[i].iov_len);
496 error = _sglist_append_buf(sg, iov[i].iov_base, minlen,
499 SGLIST_RESTORE(sg, save);
509 * Append the segments that describe at most 'resid' bytes from a
510 * single uio to a scatter/gather list. If there are insufficient
511 * segments, then only the amount that fits is appended.
514 sglist_consume_uio(struct sglist *sg, struct uio *uio, size_t resid)
521 if (sg->sg_maxseg == 0)
524 if (uio->uio_segflg == UIO_USERSPACE) {
525 KASSERT(uio->uio_td != NULL,
526 ("sglist_consume_uio: USERSPACE but no thread"));
527 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
532 while (resid > 0 && uio->uio_resid) {
544 * Try to append this iovec. If we run out of room,
545 * then break out of the loop.
547 error = _sglist_append_buf(sg, iov->iov_base, len, pmap, &done);
548 iov->iov_base = (char *)iov->iov_base + done;
549 iov->iov_len -= done;
550 uio->uio_resid -= done;
551 uio->uio_offset += done;
560 * Allocate and populate a scatter/gather list to describe a single
561 * kernel virtual address range.
564 sglist_build(void *buf, size_t len, int mflags)
572 nsegs = sglist_count(buf, len);
573 sg = sglist_alloc(nsegs, mflags);
576 if (sglist_append(sg, buf, len) != 0) {
584 * Clone a new copy of a scatter/gather list.
587 sglist_clone(struct sglist *sg, int mflags)
593 new = sglist_alloc(sg->sg_maxseg, mflags);
596 new->sg_nseg = sg->sg_nseg;
597 bcopy(sg->sg_segs, new->sg_segs, sizeof(struct sglist_seg) *
603 * Calculate the total length of the segments described in a
604 * scatter/gather list.
607 sglist_length(struct sglist *sg)
613 for (i = 0; i < sg->sg_nseg; i++)
614 space += sg->sg_segs[i].ss_len;
619 * Split a scatter/gather list into two lists. The scatter/gather
620 * entries for the first 'length' bytes of the 'original' list are
621 * stored in the '*head' list and are removed from 'original'.
623 * If '*head' is NULL, then a new list will be allocated using
624 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
625 * ENOMEM will be returned.
627 * If '*head' is not NULL, it should point to an empty sglist. If it
628 * does not have enough room for the remaining space, then EFBIG will
629 * be returned. If '*head' is not empty, then EINVAL will be
632 * If 'original' is shared (refcount > 1), then EDOOFUS will be
636 sglist_split(struct sglist *original, struct sglist **head, size_t length,
643 if (original->sg_refs > 1)
646 /* Figure out how big of a sglist '*head' has to hold. */
650 for (i = 0; i < original->sg_nseg; i++) {
651 space += original->sg_segs[i].ss_len;
653 if (space >= length) {
655 * If 'length' falls in the middle of a
656 * scatter/gather list entry, then 'split'
657 * holds how much of that entry will remain in
660 split = space - length;
665 /* Nothing to do, so leave head empty. */
670 sg = sglist_alloc(count, mflags);
676 if (sg->sg_maxseg < count)
678 if (sg->sg_nseg != 0)
682 /* Copy 'count' entries to 'sg' from 'original'. */
683 bcopy(original->sg_segs, sg->sg_segs, count *
684 sizeof(struct sglist_seg));
688 * If we had to split a list entry, fixup the last entry in
689 * 'sg' and the new first entry in 'original'. We also
690 * decrement 'count' by 1 since we will only be removing
691 * 'count - 1' segments from 'original' now.
695 sg->sg_segs[count].ss_len -= split;
696 original->sg_segs[count].ss_paddr =
697 sg->sg_segs[count].ss_paddr + split;
698 original->sg_segs[count].ss_len = split;
701 /* Trim 'count' entries from the front of 'original'. */
702 original->sg_nseg -= count;
703 bcopy(original->sg_segs + count, original->sg_segs, count *
704 sizeof(struct sglist_seg));
709 * Append the scatter/gather list elements in 'second' to the
710 * scatter/gather list 'first'. If there is not enough space in
711 * 'first', EFBIG is returned.
714 sglist_join(struct sglist *first, struct sglist *second)
716 struct sglist_seg *flast, *sfirst;
719 /* If 'second' is empty, there is nothing to do. */
720 if (second->sg_nseg == 0)
724 * If the first entry in 'second' can be appended to the last entry
725 * in 'first' then set append to '1'.
728 flast = &first->sg_segs[first->sg_nseg - 1];
729 sfirst = &second->sg_segs[0];
730 if (first->sg_nseg != 0 &&
731 flast->ss_paddr + flast->ss_len == sfirst->ss_paddr)
734 /* Make sure 'first' has enough room. */
735 if (first->sg_nseg + second->sg_nseg - append > first->sg_maxseg)
738 /* Merge last in 'first' and first in 'second' if needed. */
740 flast->ss_len += sfirst->ss_len;
742 /* Append new segments from 'second' to 'first'. */
743 bcopy(first->sg_segs + first->sg_nseg, second->sg_segs + append,
744 (second->sg_nseg - append) * sizeof(struct sglist_seg));
745 first->sg_nseg += second->sg_nseg - append;
746 sglist_reset(second);
751 * Generate a new scatter/gather list from a range of an existing
752 * scatter/gather list. The 'offset' and 'length' parameters specify
753 * the logical range of the 'original' list to extract. If that range
754 * is not a subset of the length of 'original', then EINVAL is
755 * returned. The new scatter/gather list is stored in '*slice'.
757 * If '*slice' is NULL, then a new list will be allocated using
758 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
759 * ENOMEM will be returned.
761 * If '*slice' is not NULL, it should point to an empty sglist. If it
762 * does not have enough room for the remaining space, then EFBIG will
763 * be returned. If '*slice' is not empty, then EINVAL will be
767 sglist_slice(struct sglist *original, struct sglist **slice, size_t offset,
768 size_t length, int mflags)
771 size_t space, end, foffs, loffs;
778 /* Figure out how many segments '*slice' needs to have. */
779 end = offset + length;
784 for (i = 0; i < original->sg_nseg; i++) {
785 space += original->sg_segs[i].ss_len;
786 if (space > offset) {
788 * When we hit the first segment, store its index
789 * in 'fseg' and the offset into the first segment
790 * of 'offset' in 'foffs'.
794 foffs = offset - (space -
795 original->sg_segs[i].ss_len);
796 CTR1(KTR_DEV, "sglist_slice: foffs = %08lx",
802 * When we hit the last segment, break out of
803 * the loop. Store the amount of extra space
804 * at the end of this segment in 'loffs'.
808 CTR1(KTR_DEV, "sglist_slice: loffs = %08lx",
815 /* If we never hit 'end', then 'length' ran off the end, so fail. */
819 if (*slice == NULL) {
820 sg = sglist_alloc(count, mflags);
826 if (sg->sg_maxseg < count)
828 if (sg->sg_nseg != 0)
833 * Copy over 'count' segments from 'original' starting at
836 bcopy(original->sg_segs + fseg, sg->sg_segs,
837 count * sizeof(struct sglist_seg));
840 /* Fixup first and last segments if needed. */
842 sg->sg_segs[0].ss_paddr += foffs;
843 sg->sg_segs[0].ss_len -= foffs;
844 CTR2(KTR_DEV, "sglist_slice seg[0]: %08lx:%08lx",
845 (long)sg->sg_segs[0].ss_paddr, sg->sg_segs[0].ss_len);
848 sg->sg_segs[count - 1].ss_len -= loffs;
849 CTR2(KTR_DEV, "sglist_slice seg[%d]: len %08x", count - 1,
850 sg->sg_segs[count - 1].ss_len);