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/param.h>
34 #include <sys/kernel.h>
36 #include <sys/malloc.h>
39 #include <sys/sglist.h>
43 #include <vm/vm_page.h>
45 #include <vm/vm_map.h>
49 static MALLOC_DEFINE(M_SGLIST, "sglist", "scatter/gather lists");
52 * Convenience macros to save the state of an sglist so it can be restored
53 * if an append attempt fails. Since sglist's only grow we only need to
54 * save the current count of segments and the length of the ending segment.
55 * Earlier segments will not be changed by an append, and the only change
56 * that can occur to the ending segment is that it can be extended.
63 #define SGLIST_SAVE(sg, sgsave) do { \
64 (sgsave).sg_nseg = (sg)->sg_nseg; \
65 if ((sgsave).sg_nseg > 0) \
66 (sgsave).ss_len = (sg)->sg_segs[(sgsave).sg_nseg - 1].ss_len; \
68 (sgsave).ss_len = 0; \
71 #define SGLIST_RESTORE(sg, sgsave) do { \
72 (sg)->sg_nseg = (sgsave).sg_nseg; \
73 if ((sgsave).sg_nseg > 0) \
74 (sg)->sg_segs[(sgsave).sg_nseg - 1].ss_len = (sgsave).ss_len; \
78 * Append a single (paddr, len) to a sglist. sg is the list and ss is
79 * the current segment in the list. If we run out of segments then
80 * EFBIG will be returned.
83 _sglist_append_range(struct sglist *sg, struct sglist_seg **ssp,
84 vm_paddr_t paddr, size_t len)
86 struct sglist_seg *ss;
89 if (ss->ss_paddr + ss->ss_len == paddr)
92 if (sg->sg_nseg == sg->sg_maxseg)
104 * Worker routine to append a virtual address range (either kernel or
105 * user) to a scatter/gather list.
108 _sglist_append_buf(struct sglist *sg, void *buf, size_t len, pmap_t pmap,
111 struct sglist_seg *ss;
112 vm_offset_t vaddr, offset;
122 /* Do the first page. It may have an offset. */
123 vaddr = (vm_offset_t)buf;
124 offset = vaddr & PAGE_MASK;
126 paddr = pmap_extract(pmap, vaddr);
128 paddr = pmap_kextract(vaddr);
129 seglen = MIN(len, PAGE_SIZE - offset);
130 if (sg->sg_nseg == 0) {
132 ss->ss_paddr = paddr;
136 ss = &sg->sg_segs[sg->sg_nseg - 1];
137 error = _sglist_append_range(sg, &ss, paddr, seglen);
147 seglen = MIN(len, PAGE_SIZE);
149 paddr = pmap_extract(pmap, vaddr);
151 paddr = pmap_kextract(vaddr);
152 error = _sglist_append_range(sg, &ss, paddr, seglen);
165 * Determine the number of scatter/gather list elements needed to
166 * describe a kernel virtual address range.
169 sglist_count(void *buf, size_t len)
171 vm_offset_t vaddr, vendaddr;
172 vm_paddr_t lastaddr, paddr;
178 vaddr = trunc_page((vm_offset_t)buf);
179 vendaddr = (vm_offset_t)buf + len;
181 lastaddr = pmap_kextract(vaddr);
183 while (vaddr < vendaddr) {
184 paddr = pmap_kextract(vaddr);
185 if (lastaddr + PAGE_SIZE != paddr)
194 * Determine the number of scatter/gather list elements needed to
195 * describe a buffer backed by an array of VM pages.
198 sglist_count_vmpages(vm_page_t *m, size_t pgoff, size_t len)
200 vm_paddr_t lastaddr, paddr;
208 lastaddr = VM_PAGE_TO_PHYS(m[0]);
209 for (i = 1; len > PAGE_SIZE; len -= PAGE_SIZE, i++) {
210 paddr = VM_PAGE_TO_PHYS(m[i]);
211 if (lastaddr + PAGE_SIZE != paddr)
219 * Determine the number of scatter/gather list elements needed to
220 * describe an M_EXTPG mbuf.
223 sglist_count_mbuf_epg(struct mbuf *m, size_t off, size_t len)
225 vm_paddr_t nextaddr, paddr;
226 size_t seglen, segoff;
227 int i, nsegs, pglen, pgoff;
233 if (m->m_epg_hdrlen != 0) {
234 if (off >= m->m_epg_hdrlen) {
235 off -= m->m_epg_hdrlen;
237 seglen = m->m_epg_hdrlen - off;
239 seglen = MIN(seglen, len);
242 nsegs += sglist_count(&m->m_epg_hdr[segoff],
247 pgoff = m->m_epg_1st_off;
248 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
249 pglen = m_epg_pagelen(m, i, pgoff);
255 seglen = pglen - off;
256 segoff = pgoff + off;
258 seglen = MIN(seglen, len);
260 paddr = m->m_epg_pa[i] + segoff;
261 if (paddr != nextaddr)
263 nextaddr = paddr + seglen;
267 seglen = MIN(len, m->m_epg_trllen - off);
269 nsegs += sglist_count(&m->m_epg_trail[off], seglen);
271 KASSERT(len == 0, ("len != 0"));
276 * Allocate a scatter/gather list along with 'nsegs' segments. The
277 * 'mflags' parameters are the same as passed to malloc(9). The caller
278 * should use sglist_free() to free this list.
281 sglist_alloc(int nsegs, int mflags)
285 sg = malloc(sizeof(struct sglist) + nsegs * sizeof(struct sglist_seg),
289 sglist_init(sg, nsegs, (struct sglist_seg *)(sg + 1));
294 * Free a scatter/gather list allocated via sglist_allc().
297 sglist_free(struct sglist *sg)
303 if (refcount_release(&sg->sg_refs))
308 * Append the segments to describe a single kernel virtual address
309 * range to a scatter/gather list. If there are insufficient
310 * segments, then this fails with EFBIG.
313 sglist_append(struct sglist *sg, void *buf, size_t len)
318 if (sg->sg_maxseg == 0)
320 SGLIST_SAVE(sg, save);
321 error = _sglist_append_buf(sg, buf, len, NULL, NULL);
323 SGLIST_RESTORE(sg, save);
328 * Append the segments to describe a bio's data to a scatter/gather list.
329 * If there are insufficient segments, then this fails with EFBIG.
331 * NOTE: This function expects bio_bcount to be initialized.
334 sglist_append_bio(struct sglist *sg, struct bio *bp)
338 if ((bp->bio_flags & BIO_UNMAPPED) == 0)
339 error = sglist_append(sg, bp->bio_data, bp->bio_bcount);
341 error = sglist_append_vmpages(sg, bp->bio_ma,
342 bp->bio_ma_offset, bp->bio_bcount);
347 * Append a single physical address range to a scatter/gather list.
348 * If there are insufficient segments, then this fails with EFBIG.
351 sglist_append_phys(struct sglist *sg, vm_paddr_t paddr, size_t len)
353 struct sglist_seg *ss;
357 if (sg->sg_maxseg == 0)
362 if (sg->sg_nseg == 0) {
363 sg->sg_segs[0].ss_paddr = paddr;
364 sg->sg_segs[0].ss_len = len;
368 ss = &sg->sg_segs[sg->sg_nseg - 1];
369 SGLIST_SAVE(sg, save);
370 error = _sglist_append_range(sg, &ss, paddr, len);
372 SGLIST_RESTORE(sg, save);
377 * Append the segments of single multi-page mbuf.
378 * If there are insufficient segments, then this fails with EFBIG.
381 sglist_append_mbuf_epg(struct sglist *sg, struct mbuf *m, size_t off,
384 size_t seglen, segoff;
386 int error, i, pglen, pgoff;
391 if (m->m_epg_hdrlen != 0) {
392 if (off >= m->m_epg_hdrlen) {
393 off -= m->m_epg_hdrlen;
395 seglen = m->m_epg_hdrlen - off;
397 seglen = MIN(seglen, len);
400 error = sglist_append(sg,
401 &m->m_epg_hdr[segoff], seglen);
404 pgoff = m->m_epg_1st_off;
405 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
406 pglen = m_epg_pagelen(m, i, pgoff);
412 seglen = pglen - off;
413 segoff = pgoff + off;
415 seglen = MIN(seglen, len);
417 paddr = m->m_epg_pa[i] + segoff;
418 error = sglist_append_phys(sg, paddr, seglen);
421 if (error == 0 && len > 0) {
422 seglen = MIN(len, m->m_epg_trllen - off);
424 error = sglist_append(sg,
425 &m->m_epg_trail[off], seglen);
428 KASSERT(len == 0, ("len != 0"));
433 * Append the segments that describe a single mbuf chain to a
434 * scatter/gather list. If there are insufficient segments, then this
438 sglist_append_mbuf(struct sglist *sg, struct mbuf *m0)
444 if (sg->sg_maxseg == 0)
448 SGLIST_SAVE(sg, save);
449 for (m = m0; m != NULL; m = m->m_next) {
451 if ((m->m_flags & M_EXTPG) != 0)
452 error = sglist_append_mbuf_epg(sg, m,
453 mtod(m, vm_offset_t), m->m_len);
455 error = sglist_append(sg, m->m_data,
458 SGLIST_RESTORE(sg, save);
467 * Append the segments that describe a single mbuf to a scatter/gather
468 * list. If there are insufficient segments, then this fails with
472 sglist_append_single_mbuf(struct sglist *sg, struct mbuf *m)
474 if ((m->m_flags & M_EXTPG) != 0)
475 return (sglist_append_mbuf_epg(sg, m,
476 mtod(m, vm_offset_t), m->m_len));
478 return (sglist_append(sg, m->m_data, m->m_len));
482 * Append the segments that describe a buffer spanning an array of VM
483 * pages. The buffer begins at an offset of 'pgoff' in the first
487 sglist_append_vmpages(struct sglist *sg, vm_page_t *m, size_t pgoff,
491 struct sglist_seg *ss;
496 if (sg->sg_maxseg == 0)
501 SGLIST_SAVE(sg, save);
503 if (sg->sg_nseg == 0) {
504 seglen = min(PAGE_SIZE - pgoff, len);
505 sg->sg_segs[0].ss_paddr = VM_PAGE_TO_PHYS(m[0]) + pgoff;
506 sg->sg_segs[0].ss_len = seglen;
512 ss = &sg->sg_segs[sg->sg_nseg - 1];
513 for (; len > 0; i++, len -= seglen) {
514 seglen = min(PAGE_SIZE - pgoff, len);
515 paddr = VM_PAGE_TO_PHYS(m[i]) + pgoff;
516 error = _sglist_append_range(sg, &ss, paddr, seglen);
518 SGLIST_RESTORE(sg, save);
527 * Append the segments that describe a single user address range to a
528 * scatter/gather list. If there are insufficient segments, then this
532 sglist_append_user(struct sglist *sg, void *buf, size_t len, struct thread *td)
537 if (sg->sg_maxseg == 0)
539 SGLIST_SAVE(sg, save);
540 error = _sglist_append_buf(sg, buf, len,
541 vmspace_pmap(td->td_proc->p_vmspace), NULL);
543 SGLIST_RESTORE(sg, save);
548 * Append a subset of an existing scatter/gather list 'source' to a
549 * the scatter/gather list 'sg'. If there are insufficient segments,
550 * then this fails with EFBIG.
553 sglist_append_sglist(struct sglist *sg, struct sglist *source, size_t offset,
557 struct sglist_seg *ss;
561 if (sg->sg_maxseg == 0 || length == 0)
563 SGLIST_SAVE(sg, save);
565 ss = &sg->sg_segs[sg->sg_nseg - 1];
566 for (i = 0; i < source->sg_nseg; i++) {
567 if (offset >= source->sg_segs[i].ss_len) {
568 offset -= source->sg_segs[i].ss_len;
571 seglen = source->sg_segs[i].ss_len - offset;
574 error = _sglist_append_range(sg, &ss,
575 source->sg_segs[i].ss_paddr + offset, seglen);
586 SGLIST_RESTORE(sg, save);
591 * Append the segments that describe a single uio to a scatter/gather
592 * list. If there are insufficient segments, then this fails with
596 sglist_append_uio(struct sglist *sg, struct uio *uio)
600 size_t resid, minlen;
604 if (sg->sg_maxseg == 0)
607 resid = uio->uio_resid;
610 if (uio->uio_segflg == UIO_USERSPACE) {
611 KASSERT(uio->uio_td != NULL,
612 ("sglist_append_uio: USERSPACE but no thread"));
613 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
618 SGLIST_SAVE(sg, save);
619 for (i = 0; i < uio->uio_iovcnt && resid != 0; i++) {
621 * Now at the first iovec to load. Load each iovec
622 * until we have exhausted the residual count.
624 minlen = MIN(resid, iov[i].iov_len);
626 error = _sglist_append_buf(sg, iov[i].iov_base, minlen,
629 SGLIST_RESTORE(sg, save);
639 * Append the segments that describe at most 'resid' bytes from a
640 * single uio to a scatter/gather list. If there are insufficient
641 * segments, then only the amount that fits is appended.
644 sglist_consume_uio(struct sglist *sg, struct uio *uio, size_t resid)
651 if (sg->sg_maxseg == 0)
654 if (uio->uio_segflg == UIO_USERSPACE) {
655 KASSERT(uio->uio_td != NULL,
656 ("sglist_consume_uio: USERSPACE but no thread"));
657 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
662 while (resid > 0 && uio->uio_resid) {
674 * Try to append this iovec. If we run out of room,
675 * then break out of the loop.
677 error = _sglist_append_buf(sg, iov->iov_base, len, pmap, &done);
678 iov->iov_base = (char *)iov->iov_base + done;
679 iov->iov_len -= done;
680 uio->uio_resid -= done;
681 uio->uio_offset += done;
690 * Allocate and populate a scatter/gather list to describe a single
691 * kernel virtual address range.
694 sglist_build(void *buf, size_t len, int mflags)
702 nsegs = sglist_count(buf, len);
703 sg = sglist_alloc(nsegs, mflags);
706 if (sglist_append(sg, buf, len) != 0) {
714 * Clone a new copy of a scatter/gather list.
717 sglist_clone(struct sglist *sg, int mflags)
723 new = sglist_alloc(sg->sg_maxseg, mflags);
726 new->sg_nseg = sg->sg_nseg;
727 bcopy(sg->sg_segs, new->sg_segs, sizeof(struct sglist_seg) *
733 * Calculate the total length of the segments described in a
734 * scatter/gather list.
737 sglist_length(struct sglist *sg)
743 for (i = 0; i < sg->sg_nseg; i++)
744 space += sg->sg_segs[i].ss_len;
749 * Split a scatter/gather list into two lists. The scatter/gather
750 * entries for the first 'length' bytes of the 'original' list are
751 * stored in the '*head' list and are removed from 'original'.
753 * If '*head' is NULL, then a new list will be allocated using
754 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
755 * ENOMEM will be returned.
757 * If '*head' is not NULL, it should point to an empty sglist. If it
758 * does not have enough room for the remaining space, then EFBIG will
759 * be returned. If '*head' is not empty, then EINVAL will be
762 * If 'original' is shared (refcount > 1), then EDOOFUS will be
766 sglist_split(struct sglist *original, struct sglist **head, size_t length,
773 if (original->sg_refs > 1)
776 /* Figure out how big of a sglist '*head' has to hold. */
780 for (i = 0; i < original->sg_nseg; i++) {
781 space += original->sg_segs[i].ss_len;
783 if (space >= length) {
785 * If 'length' falls in the middle of a
786 * scatter/gather list entry, then 'split'
787 * holds how much of that entry will remain in
790 split = space - length;
795 /* Nothing to do, so leave head empty. */
800 sg = sglist_alloc(count, mflags);
806 if (sg->sg_maxseg < count)
808 if (sg->sg_nseg != 0)
812 /* Copy 'count' entries to 'sg' from 'original'. */
813 bcopy(original->sg_segs, sg->sg_segs, count *
814 sizeof(struct sglist_seg));
818 * If we had to split a list entry, fixup the last entry in
819 * 'sg' and the new first entry in 'original'. We also
820 * decrement 'count' by 1 since we will only be removing
821 * 'count - 1' segments from 'original' now.
825 sg->sg_segs[count].ss_len -= split;
826 original->sg_segs[count].ss_paddr =
827 sg->sg_segs[count].ss_paddr + split;
828 original->sg_segs[count].ss_len = split;
831 /* Trim 'count' entries from the front of 'original'. */
832 original->sg_nseg -= count;
833 bcopy(original->sg_segs + count, original->sg_segs, count *
834 sizeof(struct sglist_seg));
839 * Append the scatter/gather list elements in 'second' to the
840 * scatter/gather list 'first'. If there is not enough space in
841 * 'first', EFBIG is returned.
844 sglist_join(struct sglist *first, struct sglist *second)
846 struct sglist_seg *flast, *sfirst;
849 /* If 'second' is empty, there is nothing to do. */
850 if (second->sg_nseg == 0)
854 * If the first entry in 'second' can be appended to the last entry
855 * in 'first' then set append to '1'.
858 flast = &first->sg_segs[first->sg_nseg - 1];
859 sfirst = &second->sg_segs[0];
860 if (first->sg_nseg != 0 &&
861 flast->ss_paddr + flast->ss_len == sfirst->ss_paddr)
864 /* Make sure 'first' has enough room. */
865 if (first->sg_nseg + second->sg_nseg - append > first->sg_maxseg)
868 /* Merge last in 'first' and first in 'second' if needed. */
870 flast->ss_len += sfirst->ss_len;
872 /* Append new segments from 'second' to 'first'. */
873 bcopy(first->sg_segs + first->sg_nseg, second->sg_segs + append,
874 (second->sg_nseg - append) * sizeof(struct sglist_seg));
875 first->sg_nseg += second->sg_nseg - append;
876 sglist_reset(second);
881 * Generate a new scatter/gather list from a range of an existing
882 * scatter/gather list. The 'offset' and 'length' parameters specify
883 * the logical range of the 'original' list to extract. If that range
884 * is not a subset of the length of 'original', then EINVAL is
885 * returned. The new scatter/gather list is stored in '*slice'.
887 * If '*slice' is NULL, then a new list will be allocated using
888 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
889 * ENOMEM will be returned.
891 * If '*slice' is not NULL, it should point to an empty sglist. If it
892 * does not have enough room for the remaining space, then EFBIG will
893 * be returned. If '*slice' is not empty, then EINVAL will be
897 sglist_slice(struct sglist *original, struct sglist **slice, size_t offset,
898 size_t length, int mflags)
901 size_t space, end, foffs, loffs;
908 /* Figure out how many segments '*slice' needs to have. */
909 end = offset + length;
914 for (i = 0; i < original->sg_nseg; i++) {
915 space += original->sg_segs[i].ss_len;
916 if (space > offset) {
918 * When we hit the first segment, store its index
919 * in 'fseg' and the offset into the first segment
920 * of 'offset' in 'foffs'.
924 foffs = offset - (space -
925 original->sg_segs[i].ss_len);
926 CTR1(KTR_DEV, "sglist_slice: foffs = %08lx",
932 * When we hit the last segment, break out of
933 * the loop. Store the amount of extra space
934 * at the end of this segment in 'loffs'.
938 CTR1(KTR_DEV, "sglist_slice: loffs = %08lx",
945 /* If we never hit 'end', then 'length' ran off the end, so fail. */
949 if (*slice == NULL) {
950 sg = sglist_alloc(count, mflags);
956 if (sg->sg_maxseg < count)
958 if (sg->sg_nseg != 0)
963 * Copy over 'count' segments from 'original' starting at
966 bcopy(original->sg_segs + fseg, sg->sg_segs,
967 count * sizeof(struct sglist_seg));
970 /* Fixup first and last segments if needed. */
972 sg->sg_segs[0].ss_paddr += foffs;
973 sg->sg_segs[0].ss_len -= foffs;
974 CTR2(KTR_DEV, "sglist_slice seg[0]: %08lx:%08lx",
975 (long)sg->sg_segs[0].ss_paddr, sg->sg_segs[0].ss_len);
978 sg->sg_segs[count - 1].ss_len -= loffs;
979 CTR2(KTR_DEV, "sglist_slice seg[%d]: len %08x", count - 1,
980 sg->sg_segs[count - 1].ss_len);