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 * Determine the number of scatter/gather list elements needed to
223 * describe an M_EXTPG mbuf.
226 sglist_count_mbuf_epg(struct mbuf *m, size_t off, size_t len)
228 vm_paddr_t nextaddr, paddr;
229 size_t seglen, segoff;
230 int i, nsegs, pglen, pgoff;
236 if (m->m_epg_hdrlen != 0) {
237 if (off >= m->m_epg_hdrlen) {
238 off -= m->m_epg_hdrlen;
240 seglen = m->m_epg_hdrlen - off;
242 seglen = MIN(seglen, len);
245 nsegs += sglist_count(&m->m_epg_hdr[segoff],
250 pgoff = m->m_epg_1st_off;
251 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
252 pglen = m_epg_pagelen(m, i, pgoff);
258 seglen = pglen - off;
259 segoff = pgoff + off;
261 seglen = MIN(seglen, len);
263 paddr = m->m_epg_pa[i] + segoff;
264 if (paddr != nextaddr)
266 nextaddr = paddr + seglen;
270 seglen = MIN(len, m->m_epg_trllen - off);
272 nsegs += sglist_count(&m->m_epg_trail[off], seglen);
274 KASSERT(len == 0, ("len != 0"));
279 * Allocate a scatter/gather list along with 'nsegs' segments. The
280 * 'mflags' parameters are the same as passed to malloc(9). The caller
281 * should use sglist_free() to free this list.
284 sglist_alloc(int nsegs, int mflags)
288 sg = malloc(sizeof(struct sglist) + nsegs * sizeof(struct sglist_seg),
292 sglist_init(sg, nsegs, (struct sglist_seg *)(sg + 1));
297 * Free a scatter/gather list allocated via sglist_allc().
300 sglist_free(struct sglist *sg)
306 if (refcount_release(&sg->sg_refs))
311 * Append the segments to describe a single kernel virtual address
312 * range to a scatter/gather list. If there are insufficient
313 * segments, then this fails with EFBIG.
316 sglist_append(struct sglist *sg, void *buf, size_t len)
321 if (sg->sg_maxseg == 0)
323 SGLIST_SAVE(sg, save);
324 error = _sglist_append_buf(sg, buf, len, NULL, NULL);
326 SGLIST_RESTORE(sg, save);
331 * Append the segments to describe a bio's data to a scatter/gather list.
332 * If there are insufficient segments, then this fails with EFBIG.
334 * NOTE: This function expects bio_bcount to be initialized.
337 sglist_append_bio(struct sglist *sg, struct bio *bp)
341 if ((bp->bio_flags & BIO_UNMAPPED) == 0)
342 error = sglist_append(sg, bp->bio_data, bp->bio_bcount);
344 error = sglist_append_vmpages(sg, bp->bio_ma,
345 bp->bio_ma_offset, bp->bio_bcount);
350 * Append a single physical address range to a scatter/gather list.
351 * If there are insufficient segments, then this fails with EFBIG.
354 sglist_append_phys(struct sglist *sg, vm_paddr_t paddr, size_t len)
356 struct sglist_seg *ss;
360 if (sg->sg_maxseg == 0)
365 if (sg->sg_nseg == 0) {
366 sg->sg_segs[0].ss_paddr = paddr;
367 sg->sg_segs[0].ss_len = len;
371 ss = &sg->sg_segs[sg->sg_nseg - 1];
372 SGLIST_SAVE(sg, save);
373 error = _sglist_append_range(sg, &ss, paddr, len);
375 SGLIST_RESTORE(sg, save);
380 * Append the segments of single multi-page mbuf.
381 * If there are insufficient segments, then this fails with EFBIG.
384 sglist_append_mbuf_epg(struct sglist *sg, struct mbuf *m, size_t off,
387 size_t seglen, segoff;
389 int error, i, pglen, pgoff;
394 if (m->m_epg_hdrlen != 0) {
395 if (off >= m->m_epg_hdrlen) {
396 off -= m->m_epg_hdrlen;
398 seglen = m->m_epg_hdrlen - off;
400 seglen = MIN(seglen, len);
403 error = sglist_append(sg,
404 &m->m_epg_hdr[segoff], seglen);
407 pgoff = m->m_epg_1st_off;
408 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
409 pglen = m_epg_pagelen(m, i, pgoff);
415 seglen = pglen - off;
416 segoff = pgoff + off;
418 seglen = MIN(seglen, len);
420 paddr = m->m_epg_pa[i] + segoff;
421 error = sglist_append_phys(sg, paddr, seglen);
424 if (error == 0 && len > 0) {
425 seglen = MIN(len, m->m_epg_trllen - off);
427 error = sglist_append(sg,
428 &m->m_epg_trail[off], seglen);
431 KASSERT(len == 0, ("len != 0"));
436 * Append the segments that describe a single mbuf chain to a
437 * scatter/gather list. If there are insufficient segments, then this
441 sglist_append_mbuf(struct sglist *sg, struct mbuf *m0)
447 if (sg->sg_maxseg == 0)
451 SGLIST_SAVE(sg, save);
452 for (m = m0; m != NULL; m = m->m_next) {
454 if ((m->m_flags & M_EXTPG) != 0)
455 error = sglist_append_mbuf_epg(sg, m,
456 mtod(m, vm_offset_t), m->m_len);
458 error = sglist_append(sg, m->m_data,
461 SGLIST_RESTORE(sg, save);
470 * Append the segments that describe a buffer spanning an array of VM
471 * pages. The buffer begins at an offset of 'pgoff' in the first
475 sglist_append_vmpages(struct sglist *sg, vm_page_t *m, size_t pgoff,
479 struct sglist_seg *ss;
484 if (sg->sg_maxseg == 0)
489 SGLIST_SAVE(sg, save);
491 if (sg->sg_nseg == 0) {
492 seglen = min(PAGE_SIZE - pgoff, len);
493 sg->sg_segs[0].ss_paddr = VM_PAGE_TO_PHYS(m[0]) + pgoff;
494 sg->sg_segs[0].ss_len = seglen;
500 ss = &sg->sg_segs[sg->sg_nseg - 1];
501 for (; len > 0; i++, len -= seglen) {
502 seglen = min(PAGE_SIZE - pgoff, len);
503 paddr = VM_PAGE_TO_PHYS(m[i]) + pgoff;
504 error = _sglist_append_range(sg, &ss, paddr, seglen);
506 SGLIST_RESTORE(sg, save);
515 * Append the segments that describe a single user address range to a
516 * scatter/gather list. If there are insufficient segments, then this
520 sglist_append_user(struct sglist *sg, void *buf, size_t len, struct thread *td)
525 if (sg->sg_maxseg == 0)
527 SGLIST_SAVE(sg, save);
528 error = _sglist_append_buf(sg, buf, len,
529 vmspace_pmap(td->td_proc->p_vmspace), NULL);
531 SGLIST_RESTORE(sg, save);
536 * Append a subset of an existing scatter/gather list 'source' to a
537 * the scatter/gather list 'sg'. If there are insufficient segments,
538 * then this fails with EFBIG.
541 sglist_append_sglist(struct sglist *sg, struct sglist *source, size_t offset,
545 struct sglist_seg *ss;
549 if (sg->sg_maxseg == 0 || length == 0)
551 SGLIST_SAVE(sg, save);
553 ss = &sg->sg_segs[sg->sg_nseg - 1];
554 for (i = 0; i < source->sg_nseg; i++) {
555 if (offset >= source->sg_segs[i].ss_len) {
556 offset -= source->sg_segs[i].ss_len;
559 seglen = source->sg_segs[i].ss_len - offset;
562 error = _sglist_append_range(sg, &ss,
563 source->sg_segs[i].ss_paddr + offset, seglen);
574 SGLIST_RESTORE(sg, save);
579 * Append the segments that describe a single uio to a scatter/gather
580 * list. If there are insufficient segments, then this fails with
584 sglist_append_uio(struct sglist *sg, struct uio *uio)
588 size_t resid, minlen;
592 if (sg->sg_maxseg == 0)
595 resid = uio->uio_resid;
598 if (uio->uio_segflg == UIO_USERSPACE) {
599 KASSERT(uio->uio_td != NULL,
600 ("sglist_append_uio: USERSPACE but no thread"));
601 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
606 SGLIST_SAVE(sg, save);
607 for (i = 0; i < uio->uio_iovcnt && resid != 0; i++) {
609 * Now at the first iovec to load. Load each iovec
610 * until we have exhausted the residual count.
612 minlen = MIN(resid, iov[i].iov_len);
614 error = _sglist_append_buf(sg, iov[i].iov_base, minlen,
617 SGLIST_RESTORE(sg, save);
627 * Append the segments that describe at most 'resid' bytes from a
628 * single uio to a scatter/gather list. If there are insufficient
629 * segments, then only the amount that fits is appended.
632 sglist_consume_uio(struct sglist *sg, struct uio *uio, size_t resid)
639 if (sg->sg_maxseg == 0)
642 if (uio->uio_segflg == UIO_USERSPACE) {
643 KASSERT(uio->uio_td != NULL,
644 ("sglist_consume_uio: USERSPACE but no thread"));
645 pmap = vmspace_pmap(uio->uio_td->td_proc->p_vmspace);
650 while (resid > 0 && uio->uio_resid) {
662 * Try to append this iovec. If we run out of room,
663 * then break out of the loop.
665 error = _sglist_append_buf(sg, iov->iov_base, len, pmap, &done);
666 iov->iov_base = (char *)iov->iov_base + done;
667 iov->iov_len -= done;
668 uio->uio_resid -= done;
669 uio->uio_offset += done;
678 * Allocate and populate a scatter/gather list to describe a single
679 * kernel virtual address range.
682 sglist_build(void *buf, size_t len, int mflags)
690 nsegs = sglist_count(buf, len);
691 sg = sglist_alloc(nsegs, mflags);
694 if (sglist_append(sg, buf, len) != 0) {
702 * Clone a new copy of a scatter/gather list.
705 sglist_clone(struct sglist *sg, int mflags)
711 new = sglist_alloc(sg->sg_maxseg, mflags);
714 new->sg_nseg = sg->sg_nseg;
715 bcopy(sg->sg_segs, new->sg_segs, sizeof(struct sglist_seg) *
721 * Calculate the total length of the segments described in a
722 * scatter/gather list.
725 sglist_length(struct sglist *sg)
731 for (i = 0; i < sg->sg_nseg; i++)
732 space += sg->sg_segs[i].ss_len;
737 * Split a scatter/gather list into two lists. The scatter/gather
738 * entries for the first 'length' bytes of the 'original' list are
739 * stored in the '*head' list and are removed from 'original'.
741 * If '*head' is NULL, then a new list will be allocated using
742 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
743 * ENOMEM will be returned.
745 * If '*head' is not NULL, it should point to an empty sglist. If it
746 * does not have enough room for the remaining space, then EFBIG will
747 * be returned. If '*head' is not empty, then EINVAL will be
750 * If 'original' is shared (refcount > 1), then EDOOFUS will be
754 sglist_split(struct sglist *original, struct sglist **head, size_t length,
761 if (original->sg_refs > 1)
764 /* Figure out how big of a sglist '*head' has to hold. */
768 for (i = 0; i < original->sg_nseg; i++) {
769 space += original->sg_segs[i].ss_len;
771 if (space >= length) {
773 * If 'length' falls in the middle of a
774 * scatter/gather list entry, then 'split'
775 * holds how much of that entry will remain in
778 split = space - length;
783 /* Nothing to do, so leave head empty. */
788 sg = sglist_alloc(count, mflags);
794 if (sg->sg_maxseg < count)
796 if (sg->sg_nseg != 0)
800 /* Copy 'count' entries to 'sg' from 'original'. */
801 bcopy(original->sg_segs, sg->sg_segs, count *
802 sizeof(struct sglist_seg));
806 * If we had to split a list entry, fixup the last entry in
807 * 'sg' and the new first entry in 'original'. We also
808 * decrement 'count' by 1 since we will only be removing
809 * 'count - 1' segments from 'original' now.
813 sg->sg_segs[count].ss_len -= split;
814 original->sg_segs[count].ss_paddr =
815 sg->sg_segs[count].ss_paddr + split;
816 original->sg_segs[count].ss_len = split;
819 /* Trim 'count' entries from the front of 'original'. */
820 original->sg_nseg -= count;
821 bcopy(original->sg_segs + count, original->sg_segs, count *
822 sizeof(struct sglist_seg));
827 * Append the scatter/gather list elements in 'second' to the
828 * scatter/gather list 'first'. If there is not enough space in
829 * 'first', EFBIG is returned.
832 sglist_join(struct sglist *first, struct sglist *second)
834 struct sglist_seg *flast, *sfirst;
837 /* If 'second' is empty, there is nothing to do. */
838 if (second->sg_nseg == 0)
842 * If the first entry in 'second' can be appended to the last entry
843 * in 'first' then set append to '1'.
846 flast = &first->sg_segs[first->sg_nseg - 1];
847 sfirst = &second->sg_segs[0];
848 if (first->sg_nseg != 0 &&
849 flast->ss_paddr + flast->ss_len == sfirst->ss_paddr)
852 /* Make sure 'first' has enough room. */
853 if (first->sg_nseg + second->sg_nseg - append > first->sg_maxseg)
856 /* Merge last in 'first' and first in 'second' if needed. */
858 flast->ss_len += sfirst->ss_len;
860 /* Append new segments from 'second' to 'first'. */
861 bcopy(first->sg_segs + first->sg_nseg, second->sg_segs + append,
862 (second->sg_nseg - append) * sizeof(struct sglist_seg));
863 first->sg_nseg += second->sg_nseg - append;
864 sglist_reset(second);
869 * Generate a new scatter/gather list from a range of an existing
870 * scatter/gather list. The 'offset' and 'length' parameters specify
871 * the logical range of the 'original' list to extract. If that range
872 * is not a subset of the length of 'original', then EINVAL is
873 * returned. The new scatter/gather list is stored in '*slice'.
875 * If '*slice' is NULL, then a new list will be allocated using
876 * 'mflags'. If M_NOWAIT is specified and the allocation fails,
877 * ENOMEM will be returned.
879 * If '*slice' is not NULL, it should point to an empty sglist. If it
880 * does not have enough room for the remaining space, then EFBIG will
881 * be returned. If '*slice' is not empty, then EINVAL will be
885 sglist_slice(struct sglist *original, struct sglist **slice, size_t offset,
886 size_t length, int mflags)
889 size_t space, end, foffs, loffs;
896 /* Figure out how many segments '*slice' needs to have. */
897 end = offset + length;
902 for (i = 0; i < original->sg_nseg; i++) {
903 space += original->sg_segs[i].ss_len;
904 if (space > offset) {
906 * When we hit the first segment, store its index
907 * in 'fseg' and the offset into the first segment
908 * of 'offset' in 'foffs'.
912 foffs = offset - (space -
913 original->sg_segs[i].ss_len);
914 CTR1(KTR_DEV, "sglist_slice: foffs = %08lx",
920 * When we hit the last segment, break out of
921 * the loop. Store the amount of extra space
922 * at the end of this segment in 'loffs'.
926 CTR1(KTR_DEV, "sglist_slice: loffs = %08lx",
933 /* If we never hit 'end', then 'length' ran off the end, so fail. */
937 if (*slice == NULL) {
938 sg = sglist_alloc(count, mflags);
944 if (sg->sg_maxseg < count)
946 if (sg->sg_nseg != 0)
951 * Copy over 'count' segments from 'original' starting at
954 bcopy(original->sg_segs + fseg, sg->sg_segs,
955 count * sizeof(struct sglist_seg));
958 /* Fixup first and last segments if needed. */
960 sg->sg_segs[0].ss_paddr += foffs;
961 sg->sg_segs[0].ss_len -= foffs;
962 CTR2(KTR_DEV, "sglist_slice seg[0]: %08lx:%08lx",
963 (long)sg->sg_segs[0].ss_paddr, sg->sg_segs[0].ss_len);
966 sg->sg_segs[count - 1].ss_len -= loffs;
967 CTR2(KTR_DEV, "sglist_slice seg[%d]: len %08x", count - 1,
968 sg->sg_segs[count - 1].ss_len);