+ if (!mbuf_steal(m, num))
+ bmap |= (1 << m);
+ }
+ }
+
+ lck_mtx_unlock(mbuf_mlock);
+
+ if (bmap != 0) {
+ /* signal the domains to drain */
+ net_drain_domains();
+
+ /* Sigh; we have no other choices but to ask mcache to purge */
+ for (m = 0; m < NELEM(mbuf_table); m++) {
+ if ((bmap & (1 << m)) &&
+ mcache_purge_cache(m_cache(m), TRUE)) {
+ lck_mtx_lock(mbuf_mlock);
+ m_purge_cnt(m)++;
+ mbstat.m_drain++;
+ lck_mtx_unlock(mbuf_mlock);
+ }
+ }
+ } else {
+ /*
+ * Request mcache to reap extra elements from all of its caches;
+ * note that all reaps are serialized and happen only at a fixed
+ * interval.
+ */
+ mcache_reap();
+ }
+ lck_mtx_lock(mbuf_mlock);
+}
+
+static inline struct mbuf *
+m_get_common(int wait, short type, int hdr)
+{
+ struct mbuf *m;
+ int mcflags = MSLEEPF(wait);
+
+ /* Is this due to a non-blocking retry? If so, then try harder */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ m = mcache_alloc(m_cache(MC_MBUF), mcflags);
+ if (m != NULL) {
+ MBUF_INIT(m, hdr, type);
+ mtype_stat_inc(type);
+ mtype_stat_dec(MT_FREE);
+#if CONFIG_MACF_NET
+ if (hdr && mac_init_mbuf(m, wait) != 0) {
+ m_free(m);
+ return (NULL);
+ }
+#endif /* MAC_NET */
+ }
+ return (m);
+}
+
+/*
+ * Space allocation routines; these are also available as macros
+ * for critical paths.
+ */
+#define _M_GET(wait, type) m_get_common(wait, type, 0)
+#define _M_GETHDR(wait, type) m_get_common(wait, type, 1)
+#define _M_RETRY(wait, type) _M_GET(wait, type)
+#define _M_RETRYHDR(wait, type) _M_GETHDR(wait, type)
+#define _MGET(m, how, type) ((m) = _M_GET(how, type))
+#define _MGETHDR(m, how, type) ((m) = _M_GETHDR(how, type))
+
+struct mbuf *
+m_get(int wait, int type)
+{
+ return (_M_GET(wait, type));
+}
+
+struct mbuf *
+m_gethdr(int wait, int type)
+{
+ return (_M_GETHDR(wait, type));
+}
+
+struct mbuf *
+m_retry(int wait, int type)
+{
+ return (_M_RETRY(wait, type));
+}
+
+struct mbuf *
+m_retryhdr(int wait, int type)
+{
+ return (_M_RETRYHDR(wait, type));
+}
+
+struct mbuf *
+m_getclr(int wait, int type)
+{
+ struct mbuf *m;
+
+ _MGET(m, wait, type);
+ if (m != NULL)
+ bzero(MTOD(m, caddr_t), MLEN);
+ return (m);
+}
+
+static int
+m_free_paired(struct mbuf *m)
+{
+ VERIFY((m->m_flags & M_EXT) && (MEXT_FLAGS(m) & EXTF_PAIRED));
+
+ membar_sync();
+ if (MEXT_PMBUF(m) == m) {
+ volatile UInt16 *addr = (volatile UInt16 *)&MEXT_PREF(m);
+ int16_t oprefcnt, prefcnt;
+
+ /*
+ * Paired ref count might be negative in case we lose
+ * against another thread clearing MEXT_PMBUF, in the
+ * event it occurs after the above memory barrier sync.
+ * In that case just ignore as things have been unpaired.
+ */
+ do {
+ oprefcnt = *addr;
+ prefcnt = oprefcnt - 1;
+ } while (!OSCompareAndSwap16(oprefcnt, prefcnt, addr));
+
+ if (prefcnt > 1) {
+ return (1);
+ } else if (prefcnt == 1) {
+ (*(m_get_ext_free(m)))(m->m_ext.ext_buf,
+ m->m_ext.ext_size, m_get_ext_arg(m));
+ return (1);
+ } else if (prefcnt == 0) {
+ VERIFY(MBUF_IS_PAIRED(m));
+
+ /*
+ * Restore minref to its natural value, so that
+ * the caller will be able to free the cluster
+ * as appropriate.
+ */
+ MEXT_MINREF(m) = 0;
+
+ /*
+ * Clear MEXT_PMBUF, but leave EXTF_PAIRED intact
+ * as it is immutable. atomic_set_ptr also causes
+ * memory barrier sync.
+ */
+ atomic_set_ptr(&MEXT_PMBUF(m), NULL);
+
+ switch (m->m_ext.ext_size) {
+ case MCLBYTES:
+ m_set_ext(m, m_get_rfa(m), NULL, NULL);
+ break;
+
+ case MBIGCLBYTES:
+ m_set_ext(m, m_get_rfa(m), m_bigfree, NULL);
+ break;
+
+ case M16KCLBYTES:
+ m_set_ext(m, m_get_rfa(m), m_16kfree, NULL);
+ break;
+
+ default:
+ VERIFY(0);
+ /* NOTREACHED */
+ }
+ }
+ }
+
+ /*
+ * Tell caller the unpair has occurred, and that the reference
+ * count on the external cluster held for the paired mbuf should
+ * now be dropped.
+ */
+ return (0);
+}
+
+struct mbuf *
+m_free(struct mbuf *m)
+{
+ struct mbuf *n = m->m_next;
+
+ if (m->m_type == MT_FREE)
+ panic("m_free: freeing an already freed mbuf");
+
+ if (m->m_flags & M_PKTHDR) {
+ /* Check for scratch area overflow */
+ m_redzone_verify(m);
+ /* Free the aux data and tags if there is any */
+ m_tag_delete_chain(m, NULL);
+
+ m_do_tx_compl_callback(m, NULL);
+ }
+
+ if (m->m_flags & M_EXT) {
+ u_int16_t refcnt;
+ u_int32_t composite;
+ m_ext_free_func_t m_free_func;
+
+ if (MBUF_IS_PAIRED(m) && m_free_paired(m))
+ return (n);
+
+ refcnt = m_decref(m);
+ composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
+ m_free_func = m_get_ext_free(m);
+
+ if (refcnt == MEXT_MINREF(m) && !composite) {
+ if (m_free_func == NULL) {
+ mcache_free(m_cache(MC_CL), m->m_ext.ext_buf);
+ } else if (m_free_func == m_bigfree) {
+ mcache_free(m_cache(MC_BIGCL),
+ m->m_ext.ext_buf);
+ } else if (m_free_func == m_16kfree) {
+ mcache_free(m_cache(MC_16KCL),
+ m->m_ext.ext_buf);
+ } else {
+ (*m_free_func)(m->m_ext.ext_buf,
+ m->m_ext.ext_size, m_get_ext_arg(m));
+ }
+ mcache_free(ref_cache, m_get_rfa(m));
+ m_set_ext(m, NULL, NULL, NULL);
+ } else if (refcnt == MEXT_MINREF(m) && composite) {
+ VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED));
+ VERIFY(m->m_type != MT_FREE);
+
+ mtype_stat_dec(m->m_type);
+ mtype_stat_inc(MT_FREE);
+
+ m->m_type = MT_FREE;
+ m->m_flags = M_EXT;
+ m->m_len = 0;
+ m->m_next = m->m_nextpkt = NULL;
+
+ MEXT_FLAGS(m) &= ~EXTF_READONLY;
+
+ /* "Free" into the intermediate cache */
+ if (m_free_func == NULL) {
+ mcache_free(m_cache(MC_MBUF_CL), m);
+ } else if (m_free_func == m_bigfree) {
+ mcache_free(m_cache(MC_MBUF_BIGCL), m);
+ } else {
+ VERIFY(m_free_func == m_16kfree);
+ mcache_free(m_cache(MC_MBUF_16KCL), m);
+ }
+ return (n);
+ }
+ }
+
+ if (m->m_type != MT_FREE) {
+ mtype_stat_dec(m->m_type);
+ mtype_stat_inc(MT_FREE);
+ }
+
+ m->m_type = MT_FREE;
+ m->m_flags = m->m_len = 0;
+ m->m_next = m->m_nextpkt = NULL;
+
+ mcache_free(m_cache(MC_MBUF), m);
+
+ return (n);
+}
+
+__private_extern__ struct mbuf *
+m_clattach(struct mbuf *m, int type, caddr_t extbuf,
+ void (*extfree)(caddr_t, u_int, caddr_t), u_int extsize, caddr_t extarg,
+ int wait, int pair)
+{
+ struct ext_ref *rfa = NULL;
+
+ /*
+ * If pairing is requested and an existing mbuf is provided, reject
+ * it if it's already been paired to another cluster. Otherwise,
+ * allocate a new one or free any existing below.
+ */
+ if ((m != NULL && MBUF_IS_PAIRED(m)) ||
+ (m == NULL && (m = _M_GETHDR(wait, type)) == NULL))
+ return (NULL);
+
+ if (m->m_flags & M_EXT) {
+ u_int16_t refcnt;
+ u_int32_t composite;
+ m_ext_free_func_t m_free_func;
+
+ refcnt = m_decref(m);
+ composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
+ VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED) && MEXT_PMBUF(m) == NULL);
+ m_free_func = m_get_ext_free(m);
+ if (refcnt == MEXT_MINREF(m) && !composite) {
+ if (m_free_func == NULL) {
+ mcache_free(m_cache(MC_CL), m->m_ext.ext_buf);
+ } else if (m_free_func == m_bigfree) {
+ mcache_free(m_cache(MC_BIGCL),
+ m->m_ext.ext_buf);
+ } else if (m_free_func == m_16kfree) {
+ mcache_free(m_cache(MC_16KCL),
+ m->m_ext.ext_buf);
+ } else {
+ (*m_free_func)(m->m_ext.ext_buf,
+ m->m_ext.ext_size, m_get_ext_arg(m));
+ }
+ /* Re-use the reference structure */
+ rfa = m_get_rfa(m);
+ } else if (refcnt == MEXT_MINREF(m) && composite) {
+ VERIFY(m->m_type != MT_FREE);
+
+ mtype_stat_dec(m->m_type);
+ mtype_stat_inc(MT_FREE);
+
+ m->m_type = MT_FREE;
+ m->m_flags = M_EXT;
+ m->m_len = 0;
+ m->m_next = m->m_nextpkt = NULL;
+
+ MEXT_FLAGS(m) &= ~EXTF_READONLY;
+
+ /* "Free" into the intermediate cache */
+ if (m_free_func == NULL) {
+ mcache_free(m_cache(MC_MBUF_CL), m);
+ } else if (m_free_func == m_bigfree) {
+ mcache_free(m_cache(MC_MBUF_BIGCL), m);
+ } else {
+ VERIFY(m_free_func == m_16kfree);
+ mcache_free(m_cache(MC_MBUF_16KCL), m);
+ }
+ /*
+ * Allocate a new mbuf, since we didn't divorce
+ * the composite mbuf + cluster pair above.
+ */
+ if ((m = _M_GETHDR(wait, type)) == NULL)
+ return (NULL);
+ }
+ }
+
+ if (rfa == NULL &&
+ (rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL) {
+ m_free(m);
+ return (NULL);
+ }
+
+ if (!pair) {
+ MEXT_INIT(m, extbuf, extsize, extfree, extarg, rfa,
+ 0, 1, 0, 0, 0, NULL);
+ } else {
+ MEXT_INIT(m, extbuf, extsize, extfree, (caddr_t)m, rfa,
+ 1, 1, 1, EXTF_PAIRED, 0, m);
+ }
+
+ return (m);
+}
+
+/*
+ * Perform `fast' allocation mbuf clusters from a cache of recently-freed
+ * clusters. (If the cache is empty, new clusters are allocated en-masse.)
+ */
+struct mbuf *
+m_getcl(int wait, int type, int flags)
+{
+ struct mbuf *m;
+ int mcflags = MSLEEPF(wait);
+ int hdr = (flags & M_PKTHDR);
+
+ /* Is this due to a non-blocking retry? If so, then try harder */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ m = mcache_alloc(m_cache(MC_MBUF_CL), mcflags);
+ if (m != NULL) {
+ u_int16_t flag;
+ struct ext_ref *rfa;
+ void *cl;
+
+ VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
+ cl = m->m_ext.ext_buf;
+ rfa = m_get_rfa(m);
+
+ ASSERT(cl != NULL && rfa != NULL);
+ VERIFY(MBUF_IS_COMPOSITE(m) && m_get_ext_free(m) == NULL);
+
+ flag = MEXT_FLAGS(m);
+
+ MBUF_INIT(m, hdr, type);
+ MBUF_CL_INIT(m, cl, rfa, 1, flag);
+
+ mtype_stat_inc(type);
+ mtype_stat_dec(MT_FREE);
+#if CONFIG_MACF_NET
+ if (hdr && mac_init_mbuf(m, wait) != 0) {
+ m_freem(m);
+ return (NULL);
+ }
+#endif /* MAC_NET */
+ }
+ return (m);
+}
+
+/* m_mclget() add an mbuf cluster to a normal mbuf */
+struct mbuf *
+m_mclget(struct mbuf *m, int wait)
+{
+ struct ext_ref *rfa;
+
+ if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL)
+ return (m);
+
+ m->m_ext.ext_buf = m_mclalloc(wait);
+ if (m->m_ext.ext_buf != NULL) {
+ MBUF_CL_INIT(m, m->m_ext.ext_buf, rfa, 1, 0);
+ } else {
+ mcache_free(ref_cache, rfa);
+ }
+ return (m);
+}
+
+/* Allocate an mbuf cluster */
+caddr_t
+m_mclalloc(int wait)
+{
+ int mcflags = MSLEEPF(wait);
+
+ /* Is this due to a non-blocking retry? If so, then try harder */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ return (mcache_alloc(m_cache(MC_CL), mcflags));
+}
+
+/* Free an mbuf cluster */
+void
+m_mclfree(caddr_t p)
+{
+ mcache_free(m_cache(MC_CL), p);
+}
+
+/*
+ * mcl_hasreference() checks if a cluster of an mbuf is referenced by
+ * another mbuf; see comments in m_incref() regarding EXTF_READONLY.
+ */
+int
+m_mclhasreference(struct mbuf *m)
+{
+ if (!(m->m_flags & M_EXT))
+ return (0);
+
+ ASSERT(m_get_rfa(m) != NULL);
+
+ return ((MEXT_FLAGS(m) & EXTF_READONLY) ? 1 : 0);
+}
+
+__private_extern__ caddr_t
+m_bigalloc(int wait)
+{
+ int mcflags = MSLEEPF(wait);
+
+ /* Is this due to a non-blocking retry? If so, then try harder */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ return (mcache_alloc(m_cache(MC_BIGCL), mcflags));
+}
+
+__private_extern__ void
+m_bigfree(caddr_t p, __unused u_int size, __unused caddr_t arg)
+{
+ mcache_free(m_cache(MC_BIGCL), p);
+}
+
+/* m_mbigget() add an 4KB mbuf cluster to a normal mbuf */
+__private_extern__ struct mbuf *
+m_mbigget(struct mbuf *m, int wait)
+{
+ struct ext_ref *rfa;
+
+ if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL)
+ return (m);
+
+ m->m_ext.ext_buf = m_bigalloc(wait);
+ if (m->m_ext.ext_buf != NULL) {
+ MBUF_BIGCL_INIT(m, m->m_ext.ext_buf, rfa, 1, 0);
+ } else {
+ mcache_free(ref_cache, rfa);
+ }
+ return (m);
+}
+
+__private_extern__ caddr_t
+m_16kalloc(int wait)
+{
+ int mcflags = MSLEEPF(wait);
+
+ /* Is this due to a non-blocking retry? If so, then try harder */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ return (mcache_alloc(m_cache(MC_16KCL), mcflags));
+}
+
+__private_extern__ void
+m_16kfree(caddr_t p, __unused u_int size, __unused caddr_t arg)
+{
+ mcache_free(m_cache(MC_16KCL), p);
+}
+
+/* m_m16kget() add a 16KB mbuf cluster to a normal mbuf */
+__private_extern__ struct mbuf *
+m_m16kget(struct mbuf *m, int wait)
+{
+ struct ext_ref *rfa;
+
+ if ((rfa = mcache_alloc(ref_cache, MSLEEPF(wait))) == NULL)
+ return (m);
+
+ m->m_ext.ext_buf = m_16kalloc(wait);
+ if (m->m_ext.ext_buf != NULL) {
+ MBUF_16KCL_INIT(m, m->m_ext.ext_buf, rfa, 1, 0);
+ } else {
+ mcache_free(ref_cache, rfa);
+ }
+ return (m);
+}
+
+/*
+ * "Move" mbuf pkthdr from "from" to "to".
+ * "from" must have M_PKTHDR set, and "to" must be empty.
+ */
+void
+m_copy_pkthdr(struct mbuf *to, struct mbuf *from)
+{
+ VERIFY(from->m_flags & M_PKTHDR);
+
+ /* Check for scratch area overflow */
+ m_redzone_verify(from);
+
+ if (to->m_flags & M_PKTHDR) {
+ /* Check for scratch area overflow */
+ m_redzone_verify(to);
+ /* We will be taking over the tags of 'to' */
+ m_tag_delete_chain(to, NULL);
+ }
+ to->m_pkthdr = from->m_pkthdr; /* especially tags */
+ m_classifier_init(from, 0); /* purge classifier info */
+ m_tag_init(from, 1); /* purge all tags from src */
+ m_scratch_init(from); /* clear src scratch area */
+ to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
+ if ((to->m_flags & M_EXT) == 0)
+ to->m_data = to->m_pktdat;
+ m_redzone_init(to); /* setup red zone on dst */
+}
+
+/*
+ * Duplicate "from"'s mbuf pkthdr in "to".
+ * "from" must have M_PKTHDR set, and "to" must be empty.
+ * In particular, this does a deep copy of the packet tags.
+ */
+static int
+m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
+{
+ VERIFY(from->m_flags & M_PKTHDR);
+
+ /* Check for scratch area overflow */
+ m_redzone_verify(from);
+
+ if (to->m_flags & M_PKTHDR) {
+ /* Check for scratch area overflow */
+ m_redzone_verify(to);
+ /* We will be taking over the tags of 'to' */
+ m_tag_delete_chain(to, NULL);
+ }
+ to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
+ if ((to->m_flags & M_EXT) == 0)
+ to->m_data = to->m_pktdat;
+ to->m_pkthdr = from->m_pkthdr;
+ m_redzone_init(to); /* setup red zone on dst */
+ m_tag_init(to, 0); /* preserve dst static tags */
+ return (m_tag_copy_chain(to, from, how));
+}
+
+void
+m_copy_pftag(struct mbuf *to, struct mbuf *from)
+{
+ memcpy(m_pftag(to), m_pftag(from), sizeof(struct pf_mtag));
+#if PF_ECN
+ m_pftag(to)->pftag_hdr = NULL;
+ m_pftag(to)->pftag_flags &= ~(PF_TAG_HDR_INET|PF_TAG_HDR_INET6);
+#endif /* PF_ECN */
+}
+
+void
+m_classifier_init(struct mbuf *m, uint32_t pktf_mask)
+{
+ VERIFY(m->m_flags & M_PKTHDR);
+
+ m->m_pkthdr.pkt_proto = 0;
+ m->m_pkthdr.pkt_flowsrc = 0;
+ m->m_pkthdr.pkt_flowid = 0;
+ m->m_pkthdr.pkt_flags &= pktf_mask; /* caller-defined mask */
+ /* preserve service class and interface info for loopback packets */
+ if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP))
+ (void) m_set_service_class(m, MBUF_SC_BE);
+ if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO))
+ m->m_pkthdr.pkt_ifainfo = 0;
+ /*
+ * Preserve timestamp if requested
+ */
+ if (!(m->m_pkthdr.pkt_flags & PKTF_TS_VALID))
+ m->m_pkthdr.pkt_timestamp = 0;
+}
+
+void
+m_copy_classifier(struct mbuf *to, struct mbuf *from)
+{
+ VERIFY(to->m_flags & M_PKTHDR);
+ VERIFY(from->m_flags & M_PKTHDR);
+
+ to->m_pkthdr.pkt_proto = from->m_pkthdr.pkt_proto;
+ to->m_pkthdr.pkt_flowsrc = from->m_pkthdr.pkt_flowsrc;
+ to->m_pkthdr.pkt_flowid = from->m_pkthdr.pkt_flowid;
+ to->m_pkthdr.pkt_flags = from->m_pkthdr.pkt_flags;
+ (void) m_set_service_class(to, from->m_pkthdr.pkt_svc);
+ to->m_pkthdr.pkt_ifainfo = from->m_pkthdr.pkt_ifainfo;
+}
+
+/*
+ * Return a list of mbuf hdrs that point to clusters. Try for num_needed;
+ * if wantall is not set, return whatever number were available. Set up the
+ * first num_with_pkthdrs with mbuf hdrs configured as packet headers; these
+ * are chained on the m_nextpkt field. Any packets requested beyond this
+ * are chained onto the last packet header's m_next field. The size of
+ * the cluster is controlled by the parameter bufsize.
+ */
+__private_extern__ struct mbuf *
+m_getpackets_internal(unsigned int *num_needed, int num_with_pkthdrs,
+ int wait, int wantall, size_t bufsize)
+{
+ struct mbuf *m;
+ struct mbuf **np, *top;
+ unsigned int pnum, needed = *num_needed;
+ mcache_obj_t *mp_list = NULL;
+ int mcflags = MSLEEPF(wait);
+ u_int16_t flag;
+ struct ext_ref *rfa;
+ mcache_t *cp;
+ void *cl;
+
+ ASSERT(bufsize == m_maxsize(MC_CL) ||
+ bufsize == m_maxsize(MC_BIGCL) ||
+ bufsize == m_maxsize(MC_16KCL));
+
+ /*
+ * Caller must first check for njcl because this
+ * routine is internal and not exposed/used via KPI.
+ */
+ VERIFY(bufsize != m_maxsize(MC_16KCL) || njcl > 0);
+
+ top = NULL;
+ np = ⊤
+ pnum = 0;
+
+ /*
+ * The caller doesn't want all the requested buffers; only some.
+ * Try hard to get what we can, but don't block. This effectively
+ * overrides MCR_SLEEP, since this thread will not go to sleep
+ * if we can't get all the buffers.
+ */
+ if (!wantall || (mcflags & MCR_NOSLEEP))
+ mcflags |= MCR_TRYHARD;
+
+ /* Allocate the composite mbuf + cluster elements from the cache */
+ if (bufsize == m_maxsize(MC_CL))
+ cp = m_cache(MC_MBUF_CL);
+ else if (bufsize == m_maxsize(MC_BIGCL))
+ cp = m_cache(MC_MBUF_BIGCL);
+ else
+ cp = m_cache(MC_MBUF_16KCL);
+ needed = mcache_alloc_ext(cp, &mp_list, needed, mcflags);
+
+ for (pnum = 0; pnum < needed; pnum++) {
+ m = (struct mbuf *)mp_list;
+ mp_list = mp_list->obj_next;
+
+ VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
+ cl = m->m_ext.ext_buf;
+ rfa = m_get_rfa(m);
+
+ ASSERT(cl != NULL && rfa != NULL);
+ VERIFY(MBUF_IS_COMPOSITE(m));
+
+ flag = MEXT_FLAGS(m);
+
+ MBUF_INIT(m, num_with_pkthdrs, MT_DATA);
+ if (bufsize == m_maxsize(MC_16KCL)) {
+ MBUF_16KCL_INIT(m, cl, rfa, 1, flag);
+ } else if (bufsize == m_maxsize(MC_BIGCL)) {
+ MBUF_BIGCL_INIT(m, cl, rfa, 1, flag);
+ } else {
+ MBUF_CL_INIT(m, cl, rfa, 1, flag);
+ }
+
+ if (num_with_pkthdrs > 0) {
+ --num_with_pkthdrs;
+#if CONFIG_MACF_NET
+ if (mac_mbuf_label_init(m, wait) != 0) {
+ m_freem(m);
+ break;
+ }
+#endif /* MAC_NET */
+ }
+
+ *np = m;
+ if (num_with_pkthdrs > 0)
+ np = &m->m_nextpkt;
+ else
+ np = &m->m_next;
+ }
+ ASSERT(pnum != *num_needed || mp_list == NULL);
+ if (mp_list != NULL)
+ mcache_free_ext(cp, mp_list);
+
+ if (pnum > 0) {
+ mtype_stat_add(MT_DATA, pnum);
+ mtype_stat_sub(MT_FREE, pnum);
+ }
+
+ if (wantall && (pnum != *num_needed)) {
+ if (top != NULL)
+ m_freem_list(top);
+ return (NULL);
+ }
+
+ if (pnum > *num_needed) {
+ printf("%s: File a radar related to <rdar://10146739>. \
+ needed = %u, pnum = %u, num_needed = %u \n",
+ __func__, needed, pnum, *num_needed);
+ }
+
+ *num_needed = pnum;
+ return (top);
+}
+
+/*
+ * Return list of mbuf linked by m_nextpkt. Try for numlist, and if
+ * wantall is not set, return whatever number were available. The size of
+ * each mbuf in the list is controlled by the parameter packetlen. Each
+ * mbuf of the list may have a chain of mbufs linked by m_next. Each mbuf
+ * in the chain is called a segment. If maxsegments is not null and the
+ * value pointed to is not null, this specify the maximum number of segments
+ * for a chain of mbufs. If maxsegments is zero or the value pointed to
+ * is zero the caller does not have any restriction on the number of segments.
+ * The actual number of segments of a mbuf chain is return in the value
+ * pointed to by maxsegments.
+ */
+__private_extern__ struct mbuf *
+m_allocpacket_internal(unsigned int *numlist, size_t packetlen,
+ unsigned int *maxsegments, int wait, int wantall, size_t wantsize)
+{
+ struct mbuf **np, *top, *first = NULL;
+ size_t bufsize, r_bufsize;
+ unsigned int num = 0;
+ unsigned int nsegs = 0;
+ unsigned int needed, resid;
+ int mcflags = MSLEEPF(wait);
+ mcache_obj_t *mp_list = NULL, *rmp_list = NULL;
+ mcache_t *cp = NULL, *rcp = NULL;
+
+ if (*numlist == 0)
+ return (NULL);
+
+ top = NULL;
+ np = ⊤
+
+ if (wantsize == 0) {
+ if (packetlen <= MINCLSIZE) {
+ bufsize = packetlen;
+ } else if (packetlen > m_maxsize(MC_CL)) {
+ /* Use 4KB if jumbo cluster pool isn't available */
+ if (packetlen <= m_maxsize(MC_BIGCL) || njcl == 0)
+ bufsize = m_maxsize(MC_BIGCL);
+ else
+ bufsize = m_maxsize(MC_16KCL);
+ } else {
+ bufsize = m_maxsize(MC_CL);
+ }
+ } else if (wantsize == m_maxsize(MC_CL) ||
+ wantsize == m_maxsize(MC_BIGCL) ||
+ (wantsize == m_maxsize(MC_16KCL) && njcl > 0)) {
+ bufsize = wantsize;
+ } else {
+ return (NULL);
+ }
+
+ if (bufsize <= MHLEN) {
+ nsegs = 1;
+ } else if (bufsize <= MINCLSIZE) {
+ if (maxsegments != NULL && *maxsegments == 1) {
+ bufsize = m_maxsize(MC_CL);
+ nsegs = 1;
+ } else {
+ nsegs = 2;
+ }
+ } else if (bufsize == m_maxsize(MC_16KCL)) {
+ VERIFY(njcl > 0);
+ nsegs = ((packetlen - 1) >> M16KCLSHIFT) + 1;
+ } else if (bufsize == m_maxsize(MC_BIGCL)) {
+ nsegs = ((packetlen - 1) >> MBIGCLSHIFT) + 1;
+ } else {
+ nsegs = ((packetlen - 1) >> MCLSHIFT) + 1;
+ }
+ if (maxsegments != NULL) {
+ if (*maxsegments && nsegs > *maxsegments) {
+ *maxsegments = nsegs;
+ return (NULL);
+ }
+ *maxsegments = nsegs;
+ }
+
+ /*
+ * The caller doesn't want all the requested buffers; only some.
+ * Try hard to get what we can, but don't block. This effectively
+ * overrides MCR_SLEEP, since this thread will not go to sleep
+ * if we can't get all the buffers.
+ */
+ if (!wantall || (mcflags & MCR_NOSLEEP))
+ mcflags |= MCR_TRYHARD;
+
+ /*
+ * Simple case where all elements in the lists/chains are mbufs.
+ * Unless bufsize is greater than MHLEN, each segment chain is made
+ * up of exactly 1 mbuf. Otherwise, each segment chain is made up
+ * of 2 mbufs; the second one is used for the residual data, i.e.
+ * the remaining data that cannot fit into the first mbuf.
+ */
+ if (bufsize <= MINCLSIZE) {
+ /* Allocate the elements in one shot from the mbuf cache */
+ ASSERT(bufsize <= MHLEN || nsegs == 2);
+ cp = m_cache(MC_MBUF);
+ needed = mcache_alloc_ext(cp, &mp_list,
+ (*numlist) * nsegs, mcflags);
+
+ /*
+ * The number of elements must be even if we are to use an
+ * mbuf (instead of a cluster) to store the residual data.
+ * If we couldn't allocate the requested number of mbufs,
+ * trim the number down (if it's odd) in order to avoid
+ * creating a partial segment chain.
+ */
+ if (bufsize > MHLEN && (needed & 0x1))
+ needed--;
+
+ while (num < needed) {
+ struct mbuf *m;
+
+ m = (struct mbuf *)mp_list;
+ mp_list = mp_list->obj_next;
+ ASSERT(m != NULL);
+
+ MBUF_INIT(m, 1, MT_DATA);
+#if CONFIG_MACF_NET
+ if (mac_init_mbuf(m, wait) != 0) {
+ m_free(m);
+ break;
+ }
+#endif /* MAC_NET */
+ num++;
+ if (bufsize > MHLEN) {
+ /* A second mbuf for this segment chain */
+ m->m_next = (struct mbuf *)mp_list;
+ mp_list = mp_list->obj_next;
+ ASSERT(m->m_next != NULL);
+
+ MBUF_INIT(m->m_next, 0, MT_DATA);
+ num++;
+ }
+ *np = m;
+ np = &m->m_nextpkt;
+ }
+ ASSERT(num != *numlist || mp_list == NULL);
+
+ if (num > 0) {
+ mtype_stat_add(MT_DATA, num);
+ mtype_stat_sub(MT_FREE, num);
+ }
+ num /= nsegs;
+
+ /* We've got them all; return to caller */
+ if (num == *numlist)
+ return (top);
+
+ goto fail;
+ }
+
+ /*
+ * Complex cases where elements are made up of one or more composite
+ * mbufs + cluster, depending on packetlen. Each N-segment chain can
+ * be illustrated as follows:
+ *
+ * [mbuf + cluster 1] [mbuf + cluster 2] ... [mbuf + cluster N]
+ *
+ * Every composite mbuf + cluster element comes from the intermediate
+ * cache (either MC_MBUF_CL or MC_MBUF_BIGCL). For space efficiency,
+ * the last composite element will come from the MC_MBUF_CL cache,
+ * unless the residual data is larger than 2KB where we use the
+ * big cluster composite cache (MC_MBUF_BIGCL) instead. Residual
+ * data is defined as extra data beyond the first element that cannot
+ * fit into the previous element, i.e. there is no residual data if
+ * the chain only has 1 segment.
+ */
+ r_bufsize = bufsize;
+ resid = packetlen > bufsize ? packetlen % bufsize : 0;
+ if (resid > 0) {
+ /* There is residual data; figure out the cluster size */
+ if (wantsize == 0 && packetlen > MINCLSIZE) {
+ /*
+ * Caller didn't request that all of the segments
+ * in the chain use the same cluster size; use the
+ * smaller of the cluster sizes.
+ */
+ if (njcl > 0 && resid > m_maxsize(MC_BIGCL))
+ r_bufsize = m_maxsize(MC_16KCL);
+ else if (resid > m_maxsize(MC_CL))
+ r_bufsize = m_maxsize(MC_BIGCL);
+ else
+ r_bufsize = m_maxsize(MC_CL);
+ } else {
+ /* Use the same cluster size as the other segments */
+ resid = 0;
+ }
+ }
+
+ needed = *numlist;
+ if (resid > 0) {
+ /*
+ * Attempt to allocate composite mbuf + cluster elements for
+ * the residual data in each chain; record the number of such
+ * elements that can be allocated so that we know how many
+ * segment chains we can afford to create.
+ */
+ if (r_bufsize <= m_maxsize(MC_CL))
+ rcp = m_cache(MC_MBUF_CL);
+ else if (r_bufsize <= m_maxsize(MC_BIGCL))
+ rcp = m_cache(MC_MBUF_BIGCL);
+ else
+ rcp = m_cache(MC_MBUF_16KCL);
+ needed = mcache_alloc_ext(rcp, &rmp_list, *numlist, mcflags);
+
+ if (needed == 0)
+ goto fail;
+
+ /* This is temporarily reduced for calculation */
+ ASSERT(nsegs > 1);
+ nsegs--;
+ }
+
+ /*
+ * Attempt to allocate the rest of the composite mbuf + cluster
+ * elements for the number of segment chains that we need.
+ */
+ if (bufsize <= m_maxsize(MC_CL))
+ cp = m_cache(MC_MBUF_CL);
+ else if (bufsize <= m_maxsize(MC_BIGCL))
+ cp = m_cache(MC_MBUF_BIGCL);
+ else
+ cp = m_cache(MC_MBUF_16KCL);
+ needed = mcache_alloc_ext(cp, &mp_list, needed * nsegs, mcflags);
+
+ /* Round it down to avoid creating a partial segment chain */
+ needed = (needed / nsegs) * nsegs;
+ if (needed == 0)
+ goto fail;
+
+ if (resid > 0) {
+ /*
+ * We're about to construct the chain(s); take into account
+ * the number of segments we have created above to hold the
+ * residual data for each chain, as well as restore the
+ * original count of segments per chain.
+ */
+ ASSERT(nsegs > 0);
+ needed += needed / nsegs;
+ nsegs++;
+ }
+
+ for (;;) {
+ struct mbuf *m;
+ u_int16_t flag;
+ struct ext_ref *rfa;
+ void *cl;
+ int pkthdr;
+ m_ext_free_func_t m_free_func;
+
+ ++num;
+ if (nsegs == 1 || (num % nsegs) != 0 || resid == 0) {
+ m = (struct mbuf *)mp_list;
+ mp_list = mp_list->obj_next;
+ } else {
+ m = (struct mbuf *)rmp_list;
+ rmp_list = rmp_list->obj_next;
+ }
+ m_free_func = m_get_ext_free(m);
+ ASSERT(m != NULL);
+ VERIFY(m->m_type == MT_FREE && m->m_flags == M_EXT);
+ VERIFY(m_free_func == NULL || m_free_func == m_bigfree ||
+ m_free_func == m_16kfree);
+
+ cl = m->m_ext.ext_buf;
+ rfa = m_get_rfa(m);
+
+ ASSERT(cl != NULL && rfa != NULL);
+ VERIFY(MBUF_IS_COMPOSITE(m));
+
+ flag = MEXT_FLAGS(m);
+
+ pkthdr = (nsegs == 1 || (num % nsegs) == 1);
+ if (pkthdr)
+ first = m;
+ MBUF_INIT(m, pkthdr, MT_DATA);
+ if (m_free_func == m_16kfree) {
+ MBUF_16KCL_INIT(m, cl, rfa, 1, flag);
+ } else if (m_free_func == m_bigfree) {
+ MBUF_BIGCL_INIT(m, cl, rfa, 1, flag);
+ } else {
+ MBUF_CL_INIT(m, cl, rfa, 1, flag);
+ }
+#if CONFIG_MACF_NET
+ if (pkthdr && mac_init_mbuf(m, wait) != 0) {
+ --num;
+ m_freem(m);
+ break;
+ }
+#endif /* MAC_NET */
+
+ *np = m;
+ if ((num % nsegs) == 0)
+ np = &first->m_nextpkt;
+ else
+ np = &m->m_next;
+
+ if (num == needed)
+ break;
+ }
+
+ if (num > 0) {
+ mtype_stat_add(MT_DATA, num);
+ mtype_stat_sub(MT_FREE, num);
+ }
+
+ num /= nsegs;
+
+ /* We've got them all; return to caller */
+ if (num == *numlist) {
+ ASSERT(mp_list == NULL && rmp_list == NULL);
+ return (top);
+ }
+
+fail:
+ /* Free up what's left of the above */
+ if (mp_list != NULL)
+ mcache_free_ext(cp, mp_list);
+ if (rmp_list != NULL)
+ mcache_free_ext(rcp, rmp_list);
+ if (wantall && top != NULL) {
+ m_freem(top);
+ return (NULL);
+ }
+ *numlist = num;
+ return (top);
+}
+
+/*
+ * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
+ * packets on receive ring.
+ */
+__private_extern__ struct mbuf *
+m_getpacket_how(int wait)
+{
+ unsigned int num_needed = 1;
+
+ return (m_getpackets_internal(&num_needed, 1, wait, 1,
+ m_maxsize(MC_CL)));
+}
+
+/*
+ * Best effort to get a mbuf cluster + pkthdr. Used by drivers to allocated
+ * packets on receive ring.
+ */
+struct mbuf *
+m_getpacket(void)
+{
+ unsigned int num_needed = 1;
+
+ return (m_getpackets_internal(&num_needed, 1, M_WAIT, 1,
+ m_maxsize(MC_CL)));
+}
+
+/*
+ * Return a list of mbuf hdrs that point to clusters. Try for num_needed;
+ * if this can't be met, return whatever number were available. Set up the
+ * first num_with_pkthdrs with mbuf hdrs configured as packet headers. These
+ * are chained on the m_nextpkt field. Any packets requested beyond this are
+ * chained onto the last packet header's m_next field.
+ */
+struct mbuf *
+m_getpackets(int num_needed, int num_with_pkthdrs, int how)
+{
+ unsigned int n = num_needed;
+
+ return (m_getpackets_internal(&n, num_with_pkthdrs, how, 0,
+ m_maxsize(MC_CL)));
+}
+
+/*
+ * Return a list of mbuf hdrs set up as packet hdrs chained together
+ * on the m_nextpkt field
+ */
+struct mbuf *
+m_getpackethdrs(int num_needed, int how)
+{
+ struct mbuf *m;
+ struct mbuf **np, *top;
+
+ top = NULL;
+ np = ⊤
+
+ while (num_needed--) {
+ m = _M_RETRYHDR(how, MT_DATA);
+ if (m == NULL)
+ break;
+
+ *np = m;
+ np = &m->m_nextpkt;
+ }
+
+ return (top);
+}
+
+/*
+ * Free an mbuf list (m_nextpkt) while following m_next. Returns the count
+ * for mbufs packets freed. Used by the drivers.
+ */
+int
+m_freem_list(struct mbuf *m)
+{
+ struct mbuf *nextpkt;
+ mcache_obj_t *mp_list = NULL;
+ mcache_obj_t *mcl_list = NULL;
+ mcache_obj_t *mbc_list = NULL;
+ mcache_obj_t *m16k_list = NULL;
+ mcache_obj_t *m_mcl_list = NULL;
+ mcache_obj_t *m_mbc_list = NULL;
+ mcache_obj_t *m_m16k_list = NULL;
+ mcache_obj_t *ref_list = NULL;
+ int pktcount = 0;
+ int mt_free = 0, mt_data = 0, mt_header = 0, mt_soname = 0, mt_tag = 0;
+
+ while (m != NULL) {
+ pktcount++;
+
+ nextpkt = m->m_nextpkt;
+ m->m_nextpkt = NULL;
+
+ while (m != NULL) {
+ struct mbuf *next = m->m_next;
+ mcache_obj_t *o, *rfa;
+ u_int32_t composite;
+ u_int16_t refcnt;
+ m_ext_free_func_t m_free_func;
+
+ if (m->m_type == MT_FREE)
+ panic("m_free: freeing an already freed mbuf");
+
+ if (m->m_flags & M_PKTHDR) {
+ /* Check for scratch area overflow */
+ m_redzone_verify(m);
+ /* Free the aux data and tags if there is any */
+ m_tag_delete_chain(m, NULL);
+ }
+
+ if (!(m->m_flags & M_EXT)) {
+ mt_free++;
+ goto simple_free;
+ }
+
+ if (MBUF_IS_PAIRED(m) && m_free_paired(m)) {
+ m = next;
+ continue;
+ }
+
+ mt_free++;
+
+ o = (mcache_obj_t *)(void *)m->m_ext.ext_buf;
+ refcnt = m_decref(m);
+ composite = (MEXT_FLAGS(m) & EXTF_COMPOSITE);
+ m_free_func = m_get_ext_free(m);
+ if (refcnt == MEXT_MINREF(m) && !composite) {
+ if (m_free_func == NULL) {
+ o->obj_next = mcl_list;
+ mcl_list = o;
+ } else if (m_free_func == m_bigfree) {
+ o->obj_next = mbc_list;
+ mbc_list = o;
+ } else if (m_free_func == m_16kfree) {
+ o->obj_next = m16k_list;
+ m16k_list = o;
+ } else {
+ (*(m_free_func))((caddr_t)o,
+ m->m_ext.ext_size,
+ m_get_ext_arg(m));
+ }
+ rfa = (mcache_obj_t *)(void *)m_get_rfa(m);
+ rfa->obj_next = ref_list;
+ ref_list = rfa;
+ m_set_ext(m, NULL, NULL, NULL);
+ } else if (refcnt == MEXT_MINREF(m) && composite) {
+ VERIFY(!(MEXT_FLAGS(m) & EXTF_PAIRED));
+ VERIFY(m->m_type != MT_FREE);
+ /*
+ * Amortize the costs of atomic operations
+ * by doing them at the end, if possible.
+ */
+ if (m->m_type == MT_DATA)
+ mt_data++;
+ else if (m->m_type == MT_HEADER)
+ mt_header++;
+ else if (m->m_type == MT_SONAME)
+ mt_soname++;
+ else if (m->m_type == MT_TAG)
+ mt_tag++;
+ else
+ mtype_stat_dec(m->m_type);
+
+ m->m_type = MT_FREE;
+ m->m_flags = M_EXT;
+ m->m_len = 0;
+ m->m_next = m->m_nextpkt = NULL;
+
+ MEXT_FLAGS(m) &= ~EXTF_READONLY;
+
+ /* "Free" into the intermediate cache */
+ o = (mcache_obj_t *)m;
+ if (m_free_func == NULL) {
+ o->obj_next = m_mcl_list;
+ m_mcl_list = o;
+ } else if (m_free_func == m_bigfree) {
+ o->obj_next = m_mbc_list;
+ m_mbc_list = o;
+ } else {
+ VERIFY(m_free_func == m_16kfree);
+ o->obj_next = m_m16k_list;
+ m_m16k_list = o;
+ }
+ m = next;
+ continue;
+ }
+simple_free:
+ /*
+ * Amortize the costs of atomic operations
+ * by doing them at the end, if possible.
+ */
+ if (m->m_type == MT_DATA)
+ mt_data++;
+ else if (m->m_type == MT_HEADER)
+ mt_header++;
+ else if (m->m_type == MT_SONAME)
+ mt_soname++;
+ else if (m->m_type == MT_TAG)
+ mt_tag++;
+ else if (m->m_type != MT_FREE)
+ mtype_stat_dec(m->m_type);
+
+ m->m_type = MT_FREE;
+ m->m_flags = m->m_len = 0;
+ m->m_next = m->m_nextpkt = NULL;
+
+ ((mcache_obj_t *)m)->obj_next = mp_list;
+ mp_list = (mcache_obj_t *)m;
+
+ m = next;
+ }
+
+ m = nextpkt;
+ }
+
+ if (mt_free > 0)
+ mtype_stat_add(MT_FREE, mt_free);
+ if (mt_data > 0)
+ mtype_stat_sub(MT_DATA, mt_data);
+ if (mt_header > 0)
+ mtype_stat_sub(MT_HEADER, mt_header);
+ if (mt_soname > 0)
+ mtype_stat_sub(MT_SONAME, mt_soname);
+ if (mt_tag > 0)
+ mtype_stat_sub(MT_TAG, mt_tag);
+
+ if (mp_list != NULL)
+ mcache_free_ext(m_cache(MC_MBUF), mp_list);
+ if (mcl_list != NULL)
+ mcache_free_ext(m_cache(MC_CL), mcl_list);
+ if (mbc_list != NULL)
+ mcache_free_ext(m_cache(MC_BIGCL), mbc_list);
+ if (m16k_list != NULL)
+ mcache_free_ext(m_cache(MC_16KCL), m16k_list);
+ if (m_mcl_list != NULL)
+ mcache_free_ext(m_cache(MC_MBUF_CL), m_mcl_list);
+ if (m_mbc_list != NULL)
+ mcache_free_ext(m_cache(MC_MBUF_BIGCL), m_mbc_list);
+ if (m_m16k_list != NULL)
+ mcache_free_ext(m_cache(MC_MBUF_16KCL), m_m16k_list);
+ if (ref_list != NULL)
+ mcache_free_ext(ref_cache, ref_list);
+
+ return (pktcount);
+}
+
+void
+m_freem(struct mbuf *m)
+{
+ while (m != NULL)
+ m = m_free(m);
+}
+
+/*
+ * Mbuffer utility routines.
+ */
+
+/*
+ * Compute the amount of space available before the current start
+ * of data in an mbuf.
+ */
+int
+m_leadingspace(struct mbuf *m)
+{
+ if (m->m_flags & M_EXT) {
+ if (MCLHASREFERENCE(m))
+ return (0);
+ return (m->m_data - m->m_ext.ext_buf);
+ }
+ if (m->m_flags & M_PKTHDR)
+ return (m->m_data - m->m_pktdat);
+ return (m->m_data - m->m_dat);
+}
+
+/*
+ * Compute the amount of space available after the end of data in an mbuf.
+ */
+int
+m_trailingspace(struct mbuf *m)
+{
+ if (m->m_flags & M_EXT) {
+ if (MCLHASREFERENCE(m))
+ return (0);
+ return (m->m_ext.ext_buf + m->m_ext.ext_size -
+ (m->m_data + m->m_len));
+ }
+ return (&m->m_dat[MLEN] - (m->m_data + m->m_len));
+}
+
+/*
+ * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain,
+ * copy junk along. Does not adjust packet header length.
+ */
+struct mbuf *
+m_prepend(struct mbuf *m, int len, int how)
+{
+ struct mbuf *mn;
+
+ _MGET(mn, how, m->m_type);
+ if (mn == NULL) {
+ m_freem(m);
+ return (NULL);
+ }
+ if (m->m_flags & M_PKTHDR) {
+ M_COPY_PKTHDR(mn, m);
+ m->m_flags &= ~M_PKTHDR;
+ }
+ mn->m_next = m;
+ m = mn;
+ if (m->m_flags & M_PKTHDR) {
+ VERIFY(len <= MHLEN);
+ MH_ALIGN(m, len);
+ } else {
+ VERIFY(len <= MLEN);
+ M_ALIGN(m, len);
+ }
+ m->m_len = len;
+ return (m);
+}
+
+/*
+ * Replacement for old M_PREPEND macro: allocate new mbuf to prepend to
+ * chain, copy junk along, and adjust length.
+ */
+struct mbuf *
+m_prepend_2(struct mbuf *m, int len, int how, int align)
+{
+ if (M_LEADINGSPACE(m) >= len &&
+ (!align || IS_P2ALIGNED((m->m_data - len), sizeof(u_int32_t)))) {
+ m->m_data -= len;
+ m->m_len += len;
+ } else {
+ m = m_prepend(m, len, how);
+ }
+ if ((m) && (m->m_flags & M_PKTHDR))
+ m->m_pkthdr.len += len;
+ return (m);
+}
+
+/*
+ * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
+ * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
+ * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
+ */
+int MCFail;
+
+struct mbuf *
+m_copym_mode(struct mbuf *m, int off0, int len, int wait, uint32_t mode)
+{
+ struct mbuf *n, *mhdr = NULL, **np;
+ int off = off0;
+ struct mbuf *top;
+ int copyhdr = 0;
+
+ if (off < 0 || len < 0)
+ panic("m_copym: invalid offset %d or len %d", off, len);
+
+ VERIFY((mode != M_COPYM_MUST_COPY_HDR &&
+ mode != M_COPYM_MUST_MOVE_HDR) || (m->m_flags & M_PKTHDR));
+
+ if ((off == 0 && (m->m_flags & M_PKTHDR)) ||
+ mode == M_COPYM_MUST_COPY_HDR || mode == M_COPYM_MUST_MOVE_HDR) {
+ mhdr = m;
+ copyhdr = 1;
+ }
+
+ while (off >= m->m_len) {
+ if (m->m_next == NULL)
+ panic("m_copym: invalid mbuf chain");
+ off -= m->m_len;
+ m = m->m_next;
+ }
+ np = ⊤
+ top = NULL;
+
+ while (len > 0) {
+ if (m == NULL) {
+ if (len != M_COPYALL)
+ panic("m_copym: len != M_COPYALL");
+ break;
+ }
+
+ if (copyhdr)
+ n = _M_RETRYHDR(wait, m->m_type);
+ else
+ n = _M_RETRY(wait, m->m_type);
+ *np = n;
+
+ if (n == NULL)
+ goto nospace;
+
+ if (copyhdr != 0) {
+ if ((mode == M_COPYM_MOVE_HDR) ||
+ (mode == M_COPYM_MUST_MOVE_HDR)) {
+ M_COPY_PKTHDR(n, mhdr);
+ } else if ((mode == M_COPYM_COPY_HDR) ||
+ (mode == M_COPYM_MUST_COPY_HDR)) {
+ if (m_dup_pkthdr(n, mhdr, wait) == 0)
+ goto nospace;
+ }
+ if (len == M_COPYALL)
+ n->m_pkthdr.len -= off0;
+ else
+ n->m_pkthdr.len = len;
+ copyhdr = 0;
+ /*
+ * There is data to copy from the packet header mbuf
+ * if it is empty or it is before the starting offset
+ */
+ if (mhdr != m) {
+ np = &n->m_next;
+ continue;
+ }
+ }
+ n->m_len = MIN(len, (m->m_len - off));
+ if (m->m_flags & M_EXT) {
+ n->m_ext = m->m_ext;
+ m_incref(m);
+ n->m_data = m->m_data + off;
+ n->m_flags |= M_EXT;
+ } else {
+ /*
+ * Limit to the capacity of the destination
+ */
+ if (n->m_flags & M_PKTHDR)
+ n->m_len = MIN(n->m_len, MHLEN);
+ else
+ n->m_len = MIN(n->m_len, MLEN);
+
+ if (MTOD(n, char *) + n->m_len > ((char *)n) + MSIZE)
+ panic("%s n %p copy overflow",
+ __func__, n);
+
+ bcopy(MTOD(m, caddr_t)+off, MTOD(n, caddr_t),
+ (unsigned)n->m_len);
+ }
+ if (len != M_COPYALL)
+ len -= n->m_len;
+ off = 0;
+ m = m->m_next;
+ np = &n->m_next;
+ }
+
+ if (top == NULL)
+ MCFail++;
+
+ return (top);
+nospace:
+
+ m_freem(top);
+ MCFail++;
+ return (NULL);
+}
+
+
+struct mbuf *
+m_copym(struct mbuf *m, int off0, int len, int wait)
+{
+ return (m_copym_mode(m, off0, len, wait, M_COPYM_MOVE_HDR));
+}
+
+/*
+ * Equivalent to m_copym except that all necessary mbuf hdrs are allocated
+ * within this routine also, the last mbuf and offset accessed are passed
+ * out and can be passed back in to avoid having to rescan the entire mbuf
+ * list (normally hung off of the socket)
+ */
+struct mbuf *
+m_copym_with_hdrs(struct mbuf *m0, int off0, int len0, int wait,
+ struct mbuf **m_lastm, int *m_off, uint32_t mode)
+{
+ struct mbuf *m = m0, *n, **np = NULL;
+ int off = off0, len = len0;
+ struct mbuf *top = NULL;
+ int mcflags = MSLEEPF(wait);
+ int copyhdr = 0;
+ int type = 0;
+ mcache_obj_t *list = NULL;
+ int needed = 0;
+
+ if (off == 0 && (m->m_flags & M_PKTHDR))
+ copyhdr = 1;
+
+ if (m_lastm != NULL && *m_lastm != NULL) {
+ m = *m_lastm;
+ off = *m_off;
+ } else {
+ while (off >= m->m_len) {
+ off -= m->m_len;
+ m = m->m_next;
+ }
+ }
+
+ n = m;
+ while (len > 0) {
+ needed++;
+ ASSERT(n != NULL);
+ len -= MIN(len, (n->m_len - ((needed == 1) ? off : 0)));
+ n = n->m_next;
+ }
+ needed++;
+ len = len0;
+
+ /*
+ * If the caller doesn't want to be put to sleep, mark it with
+ * MCR_TRYHARD so that we may reclaim buffers from other places
+ * before giving up.
+ */
+ if (mcflags & MCR_NOSLEEP)
+ mcflags |= MCR_TRYHARD;
+
+ if (mcache_alloc_ext(m_cache(MC_MBUF), &list, needed,
+ mcflags) != needed)
+ goto nospace;
+
+ needed = 0;
+ while (len > 0) {
+ n = (struct mbuf *)list;
+ list = list->obj_next;
+ ASSERT(n != NULL && m != NULL);
+
+ type = (top == NULL) ? MT_HEADER : m->m_type;
+ MBUF_INIT(n, (top == NULL), type);
+#if CONFIG_MACF_NET
+ if (top == NULL && mac_mbuf_label_init(n, wait) != 0) {
+ mtype_stat_inc(MT_HEADER);
+ mtype_stat_dec(MT_FREE);
+ m_free(n);
+ goto nospace;
+ }
+#endif /* MAC_NET */
+
+ if (top == NULL) {
+ top = n;
+ np = &top->m_next;
+ continue;
+ } else {
+ needed++;
+ *np = n;
+ }
+
+ if (copyhdr) {
+ if ((mode == M_COPYM_MOVE_HDR) ||
+ (mode == M_COPYM_MUST_MOVE_HDR)) {
+ M_COPY_PKTHDR(n, m);
+ } else if ((mode == M_COPYM_COPY_HDR) ||
+ (mode == M_COPYM_MUST_COPY_HDR)) {
+ if (m_dup_pkthdr(n, m, wait) == 0)
+ goto nospace;
+ }
+ n->m_pkthdr.len = len;
+ copyhdr = 0;
+ }
+ n->m_len = MIN(len, (m->m_len - off));
+
+ if (m->m_flags & M_EXT) {
+ n->m_ext = m->m_ext;
+ m_incref(m);
+ n->m_data = m->m_data + off;
+ n->m_flags |= M_EXT;
+ } else {
+ if (MTOD(n, char *) + n->m_len > ((char *)n) + MSIZE)
+ panic("%s n %p copy overflow",
+ __func__, n);
+
+ bcopy(MTOD(m, caddr_t)+off, MTOD(n, caddr_t),
+ (unsigned)n->m_len);
+ }
+ len -= n->m_len;
+
+ if (len == 0) {
+ if (m_lastm != NULL && m_off != NULL) {
+ if ((off + n->m_len) == m->m_len) {
+ *m_lastm = m->m_next;
+ *m_off = 0;
+ } else {
+ *m_lastm = m;
+ *m_off = off + n->m_len;
+ }
+ }
+ break;
+ }
+ off = 0;
+ m = m->m_next;
+ np = &n->m_next;
+ }
+
+ mtype_stat_inc(MT_HEADER);
+ mtype_stat_add(type, needed);
+ mtype_stat_sub(MT_FREE, needed + 1);
+
+ ASSERT(list == NULL);
+ return (top);
+
+nospace:
+ if (list != NULL)
+ mcache_free_ext(m_cache(MC_MBUF), list);
+ if (top != NULL)
+ m_freem(top);
+ MCFail++;
+ return (NULL);
+}
+
+/*
+ * Copy data from an mbuf chain starting "off" bytes from the beginning,
+ * continuing for "len" bytes, into the indicated buffer.
+ */
+void
+m_copydata(struct mbuf *m, int off, int len, void *vp)
+{
+ int off0 = off, len0 = len;
+ struct mbuf *m0 = m;
+ unsigned count;
+ char *cp = vp;
+
+ if (__improbable(off < 0 || len < 0)) {
+ panic("%s: invalid offset %d or len %d", __func__, off, len);
+ /* NOTREACHED */
+ }
+
+ while (off > 0) {
+ if (__improbable(m == NULL)) {
+ panic("%s: invalid mbuf chain %p [off %d, len %d]",
+ __func__, m0, off0, len0);
+ /* NOTREACHED */
+ }
+ if (off < m->m_len)
+ break;
+ off -= m->m_len;
+ m = m->m_next;
+ }
+ while (len > 0) {
+ if (__improbable(m == NULL)) {
+ panic("%s: invalid mbuf chain %p [off %d, len %d]",
+ __func__, m0, off0, len0);
+ /* NOTREACHED */
+ }
+ count = MIN(m->m_len - off, len);
+ bcopy(MTOD(m, caddr_t) + off, cp, count);
+ len -= count;
+ cp += count;
+ off = 0;
+ m = m->m_next;
+ }
+}
+
+/*
+ * Concatenate mbuf chain n to m. Both chains must be of the same type
+ * (e.g. MT_DATA). Any m_pkthdr is not updated.
+ */
+void
+m_cat(struct mbuf *m, struct mbuf *n)
+{
+ while (m->m_next)
+ m = m->m_next;
+ while (n) {
+ if ((m->m_flags & M_EXT) ||
+ m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
+ /* just join the two chains */
+ m->m_next = n;
+ return;
+ }
+ /* splat the data from one into the other */
+ bcopy(MTOD(n, caddr_t), MTOD(m, caddr_t) + m->m_len,
+ (u_int)n->m_len);
+ m->m_len += n->m_len;
+ n = m_free(n);
+ }
+}
+
+void
+m_adj(struct mbuf *mp, int req_len)
+{
+ int len = req_len;
+ struct mbuf *m;
+ int count;
+
+ if ((m = mp) == NULL)
+ return;
+ if (len >= 0) {
+ /*
+ * Trim from head.
+ */
+ while (m != NULL && len > 0) {
+ if (m->m_len <= len) {
+ len -= m->m_len;
+ m->m_len = 0;
+ m = m->m_next;
+ } else {
+ m->m_len -= len;
+ m->m_data += len;
+ len = 0;
+ }
+ }
+ m = mp;
+ if (m->m_flags & M_PKTHDR)
+ m->m_pkthdr.len -= (req_len - len);
+ } else {
+ /*
+ * Trim from tail. Scan the mbuf chain,
+ * calculating its length and finding the last mbuf.
+ * If the adjustment only affects this mbuf, then just
+ * adjust and return. Otherwise, rescan and truncate
+ * after the remaining size.
+ */
+ len = -len;
+ count = 0;
+ for (;;) {
+ count += m->m_len;
+ if (m->m_next == (struct mbuf *)0)
+ break;
+ m = m->m_next;
+ }
+ if (m->m_len >= len) {
+ m->m_len -= len;
+ m = mp;
+ if (m->m_flags & M_PKTHDR)
+ m->m_pkthdr.len -= len;
+ return;
+ }
+ count -= len;
+ if (count < 0)
+ count = 0;
+ /*
+ * Correct length for chain is "count".
+ * Find the mbuf with last data, adjust its length,
+ * and toss data from remaining mbufs on chain.
+ */
+ m = mp;
+ if (m->m_flags & M_PKTHDR)
+ m->m_pkthdr.len = count;
+ for (; m; m = m->m_next) {
+ if (m->m_len >= count) {
+ m->m_len = count;
+ break;
+ }
+ count -= m->m_len;
+ }
+ while ((m = m->m_next))
+ m->m_len = 0;
+ }
+}
+
+/*
+ * Rearange an mbuf chain so that len bytes are contiguous
+ * and in the data area of an mbuf (so that mtod and dtom
+ * will work for a structure of size len). Returns the resulting
+ * mbuf chain on success, frees it and returns null on failure.
+ * If there is room, it will add up to max_protohdr-len extra bytes to the
+ * contiguous region in an attempt to avoid being called next time.
+ */
+int MPFail;
+
+struct mbuf *
+m_pullup(struct mbuf *n, int len)
+{
+ struct mbuf *m;
+ int count;
+ int space;
+
+ /*
+ * If first mbuf has no cluster, and has room for len bytes
+ * without shifting current data, pullup into it,
+ * otherwise allocate a new mbuf to prepend to the chain.
+ */
+ if ((n->m_flags & M_EXT) == 0 &&
+ n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
+ if (n->m_len >= len)
+ return (n);
+ m = n;
+ n = n->m_next;
+ len -= m->m_len;
+ } else {
+ if (len > MHLEN)
+ goto bad;
+ _MGET(m, M_DONTWAIT, n->m_type);
+ if (m == 0)
+ goto bad;
+ m->m_len = 0;
+ if (n->m_flags & M_PKTHDR) {
+ M_COPY_PKTHDR(m, n);
+ n->m_flags &= ~M_PKTHDR;
+ }
+ }
+ space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
+ do {
+ count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
+ bcopy(MTOD(n, caddr_t), MTOD(m, caddr_t) + m->m_len,
+ (unsigned)count);
+ len -= count;
+ m->m_len += count;
+ n->m_len -= count;
+ space -= count;
+ if (n->m_len)
+ n->m_data += count;
+ else
+ n = m_free(n);
+ } while (len > 0 && n);
+ if (len > 0) {
+ (void) m_free(m);
+ goto bad;
+ }
+ m->m_next = n;
+ return (m);
+bad:
+ m_freem(n);
+ MPFail++;
+ return (0);
+}
+
+/*
+ * Like m_pullup(), except a new mbuf is always allocated, and we allow
+ * the amount of empty space before the data in the new mbuf to be specified
+ * (in the event that the caller expects to prepend later).
+ */
+__private_extern__ int MSFail = 0;
+
+__private_extern__ struct mbuf *
+m_copyup(struct mbuf *n, int len, int dstoff)
+{
+ struct mbuf *m;
+ int count, space;
+
+ if (len > (MHLEN - dstoff))
+ goto bad;
+ MGET(m, M_DONTWAIT, n->m_type);
+ if (m == NULL)
+ goto bad;
+ m->m_len = 0;
+ if (n->m_flags & M_PKTHDR) {
+ m_copy_pkthdr(m, n);
+ n->m_flags &= ~M_PKTHDR;
+ }
+ m->m_data += dstoff;
+ space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
+ do {
+ count = min(min(max(len, max_protohdr), space), n->m_len);
+ memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
+ (unsigned)count);
+ len -= count;
+ m->m_len += count;
+ n->m_len -= count;
+ space -= count;
+ if (n->m_len)
+ n->m_data += count;
+ else
+ n = m_free(n);
+ } while (len > 0 && n);
+ if (len > 0) {
+ (void) m_free(m);
+ goto bad;
+ }
+ m->m_next = n;
+ return (m);
+bad:
+ m_freem(n);
+ MSFail++;
+ return (NULL);
+}
+
+/*
+ * Partition an mbuf chain in two pieces, returning the tail --
+ * all but the first len0 bytes. In case of failure, it returns NULL and
+ * attempts to restore the chain to its original state.
+ */
+struct mbuf *
+m_split(struct mbuf *m0, int len0, int wait)
+{
+ return (m_split0(m0, len0, wait, 1));
+}
+
+static struct mbuf *
+m_split0(struct mbuf *m0, int len0, int wait, int copyhdr)
+{
+ struct mbuf *m, *n;
+ unsigned len = len0, remain;
+
+ for (m = m0; m && len > m->m_len; m = m->m_next)
+ len -= m->m_len;
+ if (m == NULL)
+ return (NULL);
+ remain = m->m_len - len;
+ if (copyhdr && (m0->m_flags & M_PKTHDR)) {
+ _MGETHDR(n, wait, m0->m_type);
+ if (n == NULL)
+ return (NULL);
+ n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
+ n->m_pkthdr.len = m0->m_pkthdr.len - len0;
+ m0->m_pkthdr.len = len0;
+ if (m->m_flags & M_EXT)
+ goto extpacket;
+ if (remain > MHLEN) {
+ /* m can't be the lead packet */
+ MH_ALIGN(n, 0);
+ n->m_next = m_split(m, len, wait);
+ if (n->m_next == NULL) {
+ (void) m_free(n);
+ return (NULL);
+ } else
+ return (n);
+ } else
+ MH_ALIGN(n, remain);
+ } else if (remain == 0) {
+ n = m->m_next;
+ m->m_next = NULL;
+ return (n);
+ } else {
+ _MGET(n, wait, m->m_type);
+ if (n == NULL)
+ return (NULL);
+ M_ALIGN(n, remain);
+ }
+extpacket:
+ if (m->m_flags & M_EXT) {
+ n->m_flags |= M_EXT;
+ n->m_ext = m->m_ext;
+ m_incref(m);
+ n->m_data = m->m_data + len;
+ } else {
+ bcopy(MTOD(m, caddr_t) + len, MTOD(n, caddr_t), remain);
+ }
+ n->m_len = remain;
+ m->m_len = len;
+ n->m_next = m->m_next;
+ m->m_next = NULL;
+ return (n);
+}
+
+/*
+ * Routine to copy from device local memory into mbufs.
+ */
+struct mbuf *
+m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
+ void (*copy)(const void *, void *, size_t))
+{
+ struct mbuf *m;
+ struct mbuf *top = NULL, **mp = ⊤
+ int off = off0, len;
+ char *cp;
+ char *epkt;
+
+ cp = buf;
+ epkt = cp + totlen;
+ if (off) {
+ /*
+ * If 'off' is non-zero, packet is trailer-encapsulated,
+ * so we have to skip the type and length fields.
+ */
+ cp += off + 2 * sizeof (u_int16_t);
+ totlen -= 2 * sizeof (u_int16_t);
+ }
+ _MGETHDR(m, M_DONTWAIT, MT_DATA);
+ if (m == NULL)
+ return (NULL);
+ m->m_pkthdr.rcvif = ifp;
+ m->m_pkthdr.len = totlen;
+ m->m_len = MHLEN;
+
+ while (totlen > 0) {
+ if (top != NULL) {
+ _MGET(m, M_DONTWAIT, MT_DATA);
+ if (m == NULL) {
+ m_freem(top);
+ return (NULL);
+ }
+ m->m_len = MLEN;
+ }
+ len = MIN(totlen, epkt - cp);
+ if (len >= MINCLSIZE) {
+ MCLGET(m, M_DONTWAIT);
+ if (m->m_flags & M_EXT) {
+ m->m_len = len = MIN(len, m_maxsize(MC_CL));
+ } else {
+ /* give up when it's out of cluster mbufs */
+ if (top != NULL)
+ m_freem(top);
+ m_freem(m);
+ return (NULL);
+ }
+ } else {
+ /*
+ * Place initial small packet/header at end of mbuf.
+ */
+ if (len < m->m_len) {
+ if (top == NULL &&
+ len + max_linkhdr <= m->m_len)
+ m->m_data += max_linkhdr;
+ m->m_len = len;
+ } else {
+ len = m->m_len;
+ }
+ }
+ if (copy)
+ copy(cp, MTOD(m, caddr_t), (unsigned)len);
+ else
+ bcopy(cp, MTOD(m, caddr_t), (unsigned)len);
+ cp += len;
+ *mp = m;
+ mp = &m->m_next;
+ totlen -= len;
+ if (cp == epkt)
+ cp = buf;
+ }
+ return (top);
+}
+
+#ifndef MBUF_GROWTH_NORMAL_THRESH
+#define MBUF_GROWTH_NORMAL_THRESH 25
+#endif
+
+/*
+ * Cluster freelist allocation check.
+ */
+static int
+m_howmany(int num, size_t bufsize)
+{
+ int i = 0, j = 0;
+ u_int32_t m_mbclusters, m_clusters, m_bigclusters, m_16kclusters;
+ u_int32_t m_mbfree, m_clfree, m_bigclfree, m_16kclfree;
+ u_int32_t sumclusters, freeclusters;
+ u_int32_t percent_pool, percent_kmem;
+ u_int32_t mb_growth, mb_growth_thresh;
+
+ VERIFY(bufsize == m_maxsize(MC_BIGCL) ||
+ bufsize == m_maxsize(MC_16KCL));
+
+ LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
+
+ /* Numbers in 2K cluster units */
+ m_mbclusters = m_total(MC_MBUF) >> NMBPCLSHIFT;
+ m_clusters = m_total(MC_CL);
+ m_bigclusters = m_total(MC_BIGCL) << NCLPBGSHIFT;
+ m_16kclusters = m_total(MC_16KCL);
+ sumclusters = m_mbclusters + m_clusters + m_bigclusters;
+
+ m_mbfree = m_infree(MC_MBUF) >> NMBPCLSHIFT;
+ m_clfree = m_infree(MC_CL);
+ m_bigclfree = m_infree(MC_BIGCL) << NCLPBGSHIFT;
+ m_16kclfree = m_infree(MC_16KCL);
+ freeclusters = m_mbfree + m_clfree + m_bigclfree;
+
+ /* Bail if we've maxed out the mbuf memory map */
+ if ((bufsize == m_maxsize(MC_BIGCL) && sumclusters >= nclusters) ||
+ (njcl > 0 && bufsize == m_maxsize(MC_16KCL) &&
+ (m_16kclusters << NCLPJCLSHIFT) >= njcl)) {
+ return (0);
+ }
+
+ if (bufsize == m_maxsize(MC_BIGCL)) {
+ /* Under minimum */
+ if (m_bigclusters < m_minlimit(MC_BIGCL))
+ return (m_minlimit(MC_BIGCL) - m_bigclusters);
+
+ percent_pool =
+ ((sumclusters - freeclusters) * 100) / sumclusters;
+ percent_kmem = (sumclusters * 100) / nclusters;
+
+ /*
+ * If a light/normal user, grow conservatively (75%)
+ * If a heavy user, grow aggressively (50%)
+ */
+ if (percent_kmem < MBUF_GROWTH_NORMAL_THRESH)
+ mb_growth = MB_GROWTH_NORMAL;
+ else
+ mb_growth = MB_GROWTH_AGGRESSIVE;
+
+ if (percent_kmem < 5) {
+ /* For initial allocations */
+ i = num;
+ } else {
+ /* Return if >= MBIGCL_LOWAT clusters available */
+ if (m_infree(MC_BIGCL) >= MBIGCL_LOWAT &&
+ m_total(MC_BIGCL) >=
+ MBIGCL_LOWAT + m_minlimit(MC_BIGCL))
+ return (0);
+
+ /* Ensure at least num clusters are accessible */
+ if (num >= m_infree(MC_BIGCL))
+ i = num - m_infree(MC_BIGCL);
+ if (num > m_total(MC_BIGCL) - m_minlimit(MC_BIGCL))
+ j = num - (m_total(MC_BIGCL) -
+ m_minlimit(MC_BIGCL));
+
+ i = MAX(i, j);
+
+ /*
+ * Grow pool if percent_pool > 75 (normal growth)
+ * or percent_pool > 50 (aggressive growth).
+ */
+ mb_growth_thresh = 100 - (100 / (1 << mb_growth));
+ if (percent_pool > mb_growth_thresh)
+ j = ((sumclusters + num) >> mb_growth) -
+ freeclusters;
+ i = MAX(i, j);
+ }
+
+ /* Check to ensure we didn't go over limits */
+ if (i + m_bigclusters >= m_maxlimit(MC_BIGCL))
+ i = m_maxlimit(MC_BIGCL) - m_bigclusters;
+ if ((i << 1) + sumclusters >= nclusters)
+ i = (nclusters - sumclusters) >> 1;
+ VERIFY((m_total(MC_BIGCL) + i) <= m_maxlimit(MC_BIGCL));
+ VERIFY(sumclusters + (i << 1) <= nclusters);
+
+ } else { /* 16K CL */
+ VERIFY(njcl > 0);
+ /* Ensure at least num clusters are available */
+ if (num >= m_16kclfree)
+ i = num - m_16kclfree;
+
+ /* Always grow 16KCL pool aggressively */
+ if (((m_16kclusters + num) >> 1) > m_16kclfree)
+ j = ((m_16kclusters + num) >> 1) - m_16kclfree;
+ i = MAX(i, j);
+
+ /* Check to ensure we don't go over limit */
+ if ((i + m_total(MC_16KCL)) >= m_maxlimit(MC_16KCL))
+ i = m_maxlimit(MC_16KCL) - m_total(MC_16KCL);
+ }
+ return (i);
+}
+/*
+ * Return the number of bytes in the mbuf chain, m.
+ */
+unsigned int
+m_length(struct mbuf *m)
+{
+ struct mbuf *m0;
+ unsigned int pktlen;
+
+ if (m->m_flags & M_PKTHDR)
+ return (m->m_pkthdr.len);
+
+ pktlen = 0;
+ for (m0 = m; m0 != NULL; m0 = m0->m_next)
+ pktlen += m0->m_len;
+ return (pktlen);
+}
+
+/*
+ * Copy data from a buffer back into the indicated mbuf chain,
+ * starting "off" bytes from the beginning, extending the mbuf
+ * chain if necessary.
+ */
+void
+m_copyback(struct mbuf *m0, int off, int len, const void *cp)
+{
+#if DEBUG
+ struct mbuf *origm = m0;
+ int error;
+#endif /* DEBUG */
+
+ if (m0 == NULL)
+ return;
+
+#if DEBUG
+ error =
+#endif /* DEBUG */
+ m_copyback0(&m0, off, len, cp,
+ M_COPYBACK0_COPYBACK | M_COPYBACK0_EXTEND, M_DONTWAIT);
+
+#if DEBUG
+ if (error != 0 || (m0 != NULL && origm != m0))
+ panic("m_copyback");
+#endif /* DEBUG */
+}
+
+struct mbuf *
+m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
+{
+ int error;
+
+ /* don't support chain expansion */
+ VERIFY(off + len <= m_length(m0));
+
+ error = m_copyback0(&m0, off, len, cp,
+ M_COPYBACK0_COPYBACK | M_COPYBACK0_COW, how);
+ if (error) {
+ /*
+ * no way to recover from partial success.
+ * just free the chain.
+ */
+ m_freem(m0);
+ return (NULL);
+ }
+ return (m0);
+}
+
+/*
+ * m_makewritable: ensure the specified range writable.
+ */
+int
+m_makewritable(struct mbuf **mp, int off, int len, int how)
+{
+ int error;
+#if DEBUG
+ struct mbuf *n;
+ int origlen, reslen;
+
+ origlen = m_length(*mp);
+#endif /* DEBUG */
+
+#if 0 /* M_COPYALL is large enough */
+ if (len == M_COPYALL)
+ len = m_length(*mp) - off; /* XXX */
+#endif
+
+ error = m_copyback0(mp, off, len, NULL,
+ M_COPYBACK0_PRESERVE | M_COPYBACK0_COW, how);
+
+#if DEBUG
+ reslen = 0;
+ for (n = *mp; n; n = n->m_next)
+ reslen += n->m_len;
+ if (origlen != reslen)
+ panic("m_makewritable: length changed");
+ if (((*mp)->m_flags & M_PKTHDR) && reslen != (*mp)->m_pkthdr.len)
+ panic("m_makewritable: inconsist");
+#endif /* DEBUG */
+
+ return (error);
+}
+
+static int
+m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
+ int how)
+{
+ int mlen;
+ struct mbuf *m, *n;
+ struct mbuf **mp;
+ int totlen = 0;
+ const char *cp = vp;
+
+ VERIFY(mp0 != NULL);
+ VERIFY(*mp0 != NULL);
+ VERIFY((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
+ VERIFY((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
+
+ /*
+ * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
+ * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
+ */
+
+ VERIFY((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
+
+ mp = mp0;
+ m = *mp;
+ while (off > (mlen = m->m_len)) {
+ off -= mlen;
+ totlen += mlen;
+ if (m->m_next == NULL) {
+ int tspace;
+extend:
+ if (!(flags & M_COPYBACK0_EXTEND))
+ goto out;
+
+ /*
+ * try to make some space at the end of "m".
+ */
+
+ mlen = m->m_len;
+ if (off + len >= MINCLSIZE &&
+ !(m->m_flags & M_EXT) && m->m_len == 0) {
+ MCLGET(m, how);
+ }
+ tspace = M_TRAILINGSPACE(m);
+ if (tspace > 0) {
+ tspace = MIN(tspace, off + len);
+ VERIFY(tspace > 0);
+ bzero(mtod(m, char *) + m->m_len,
+ MIN(off, tspace));
+ m->m_len += tspace;
+ off += mlen;
+ totlen -= mlen;
+ continue;
+ }
+
+ /*
+ * need to allocate an mbuf.
+ */
+
+ if (off + len >= MINCLSIZE) {
+ n = m_getcl(how, m->m_type, 0);
+ } else {
+ n = _M_GET(how, m->m_type);
+ }
+ if (n == NULL) {
+ goto out;
+ }
+ n->m_len = 0;
+ n->m_len = MIN(M_TRAILINGSPACE(n), off + len);
+ bzero(mtod(n, char *), MIN(n->m_len, off));
+ m->m_next = n;
+ }
+ mp = &m->m_next;
+ m = m->m_next;
+ }
+ while (len > 0) {
+ mlen = m->m_len - off;
+ if (mlen != 0 && m_mclhasreference(m)) {
+ char *datap;
+ int eatlen;
+
+ /*
+ * this mbuf is read-only.
+ * allocate a new writable mbuf and try again.
+ */
+
+#if DIAGNOSTIC
+ if (!(flags & M_COPYBACK0_COW))
+ panic("m_copyback0: read-only");
+#endif /* DIAGNOSTIC */
+
+ /*
+ * if we're going to write into the middle of
+ * a mbuf, split it first.
+ */
+ if (off > 0 && len < mlen) {
+ n = m_split0(m, off, how, 0);
+ if (n == NULL)
+ goto enobufs;
+ m->m_next = n;
+ mp = &m->m_next;
+ m = n;
+ off = 0;
+ continue;
+ }
+
+ /*
+ * XXX TODO coalesce into the trailingspace of
+ * the previous mbuf when possible.
+ */
+
+ /*
+ * allocate a new mbuf. copy packet header if needed.
+ */
+ n = _M_GET(how, m->m_type);
+ if (n == NULL)
+ goto enobufs;
+ if (off == 0 && (m->m_flags & M_PKTHDR)) {
+ M_COPY_PKTHDR(n, m);
+ n->m_len = MHLEN;
+ } else {
+ if (len >= MINCLSIZE)
+ MCLGET(n, M_DONTWAIT);
+ n->m_len =
+ (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
+ }
+ if (n->m_len > len)
+ n->m_len = len;
+
+ /*
+ * free the region which has been overwritten.
+ * copying data from old mbufs if requested.
+ */
+ if (flags & M_COPYBACK0_PRESERVE)
+ datap = mtod(n, char *);
+ else
+ datap = NULL;
+ eatlen = n->m_len;
+ VERIFY(off == 0 || eatlen >= mlen);
+ if (off > 0) {
+ VERIFY(len >= mlen);
+ m->m_len = off;
+ m->m_next = n;
+ if (datap) {
+ m_copydata(m, off, mlen, datap);
+ datap += mlen;
+ }
+ eatlen -= mlen;
+ mp = &m->m_next;
+ m = m->m_next;
+ }
+ while (m != NULL && m_mclhasreference(m) &&
+ n->m_type == m->m_type && eatlen > 0) {
+ mlen = MIN(eatlen, m->m_len);
+ if (datap) {
+ m_copydata(m, 0, mlen, datap);
+ datap += mlen;
+ }
+ m->m_data += mlen;
+ m->m_len -= mlen;
+ eatlen -= mlen;
+ if (m->m_len == 0)
+ *mp = m = m_free(m);
+ }
+ if (eatlen > 0)
+ n->m_len -= eatlen;
+ n->m_next = m;
+ *mp = m = n;
+ continue;
+ }
+ mlen = MIN(mlen, len);
+ if (flags & M_COPYBACK0_COPYBACK) {
+ bcopy(cp, mtod(m, caddr_t) + off, (unsigned)mlen);
+ cp += mlen;
+ }
+ len -= mlen;
+ mlen += off;
+ off = 0;
+ totlen += mlen;
+ if (len == 0)
+ break;
+ if (m->m_next == NULL) {
+ goto extend;
+ }
+ mp = &m->m_next;
+ m = m->m_next;
+ }
+out:
+ if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
+ VERIFY(flags & M_COPYBACK0_EXTEND);
+ m->m_pkthdr.len = totlen;
+ }
+
+ return (0);
+
+enobufs:
+ return (ENOBUFS);
+}
+
+uint64_t
+mcl_to_paddr(char *addr)
+{
+ vm_offset_t base_phys;
+
+ if (!MBUF_IN_MAP(addr))
+ return (0);
+ base_phys = mcl_paddr[atop_64(addr - (char *)mbutl)];
+
+ if (base_phys == 0)
+ return (0);
+ return ((uint64_t)(ptoa_64(base_phys) | ((uint64_t)addr & PAGE_MASK)));
+}
+
+/*
+ * Dup the mbuf chain passed in. The whole thing. No cute additional cruft.
+ * And really copy the thing. That way, we don't "precompute" checksums
+ * for unsuspecting consumers. Assumption: m->m_nextpkt == 0. Trick: for
+ * small packets, don't dup into a cluster. That way received packets
+ * don't take up too much room in the sockbuf (cf. sbspace()).
+ */
+int MDFail;
+
+struct mbuf *
+m_dup(struct mbuf *m, int how)
+{
+ struct mbuf *n, **np;
+ struct mbuf *top;
+ int copyhdr = 0;
+
+ np = ⊤
+ top = NULL;
+ if (m->m_flags & M_PKTHDR)
+ copyhdr = 1;
+
+ /*
+ * Quick check: if we have one mbuf and its data fits in an
+ * mbuf with packet header, just copy and go.
+ */
+ if (m->m_next == NULL) {
+ /* Then just move the data into an mbuf and be done... */
+ if (copyhdr) {
+ if (m->m_pkthdr.len <= MHLEN && m->m_len <= MHLEN) {
+ if ((n = _M_GETHDR(how, m->m_type)) == NULL)
+ return (NULL);
+ n->m_len = m->m_len;
+ m_dup_pkthdr(n, m, how);
+ bcopy(m->m_data, n->m_data, m->m_len);
+ return (n);
+ }
+ } else if (m->m_len <= MLEN) {
+ if ((n = _M_GET(how, m->m_type)) == NULL)
+ return (NULL);
+ bcopy(m->m_data, n->m_data, m->m_len);
+ n->m_len = m->m_len;
+ return (n);
+ }
+ }
+ while (m != NULL) {
+#if BLUE_DEBUG
+ printf("<%x: %x, %x, %x\n", m, m->m_flags, m->m_len,
+ m->m_data);
+#endif
+ if (copyhdr)
+ n = _M_GETHDR(how, m->m_type);
+ else
+ n = _M_GET(how, m->m_type);
+ if (n == NULL)
+ goto nospace;
+ if (m->m_flags & M_EXT) {
+ if (m->m_len <= m_maxsize(MC_CL))
+ MCLGET(n, how);
+ else if (m->m_len <= m_maxsize(MC_BIGCL))
+ n = m_mbigget(n, how);
+ else if (m->m_len <= m_maxsize(MC_16KCL) && njcl > 0)
+ n = m_m16kget(n, how);
+ if (!(n->m_flags & M_EXT)) {
+ (void) m_free(n);
+ goto nospace;
+ }
+ }
+ *np = n;
+ if (copyhdr) {
+ /* Don't use M_COPY_PKTHDR: preserve m_data */
+ m_dup_pkthdr(n, m, how);
+ copyhdr = 0;
+ if (!(n->m_flags & M_EXT))
+ n->m_data = n->m_pktdat;
+ }
+ n->m_len = m->m_len;
+ /*
+ * Get the dup on the same bdry as the original
+ * Assume that the two mbufs have the same offset to data area
+ * (up to word boundaries)
+ */
+ bcopy(MTOD(m, caddr_t), MTOD(n, caddr_t), (unsigned)n->m_len);
+ m = m->m_next;
+ np = &n->m_next;
+#if BLUE_DEBUG
+ printf(">%x: %x, %x, %x\n", n, n->m_flags, n->m_len,
+ n->m_data);
+#endif
+ }
+
+ if (top == NULL)
+ MDFail++;
+ return (top);
+
+nospace:
+ m_freem(top);
+ MDFail++;
+ return (NULL);
+}
+
+#define MBUF_MULTIPAGES(m) \
+ (((m)->m_flags & M_EXT) && \
+ ((IS_P2ALIGNED((m)->m_data, PAGE_SIZE) \
+ && (m)->m_len > PAGE_SIZE) || \
+ (!IS_P2ALIGNED((m)->m_data, PAGE_SIZE) && \
+ P2ROUNDUP((m)->m_data, PAGE_SIZE) < ((uintptr_t)(m)->m_data + (m)->m_len))))
+
+static struct mbuf *
+m_expand(struct mbuf *m, struct mbuf **last)
+{
+ struct mbuf *top = NULL;
+ struct mbuf **nm = ⊤
+ uintptr_t data0, data;
+ unsigned int len0, len;
+
+ VERIFY(MBUF_MULTIPAGES(m));
+ VERIFY(m->m_next == NULL);
+ data0 = (uintptr_t)m->m_data;
+ len0 = m->m_len;
+ *last = top;
+
+ for (;;) {
+ struct mbuf *n;
+
+ data = data0;
+ if (IS_P2ALIGNED(data, PAGE_SIZE) && len0 > PAGE_SIZE)
+ len = PAGE_SIZE;
+ else if (!IS_P2ALIGNED(data, PAGE_SIZE) &&
+ P2ROUNDUP(data, PAGE_SIZE) < (data + len0))
+ len = P2ROUNDUP(data, PAGE_SIZE) - data;
+ else
+ len = len0;
+
+ VERIFY(len > 0);
+ VERIFY(m->m_flags & M_EXT);
+ m->m_data = (void *)data;
+ m->m_len = len;
+
+ *nm = *last = m;
+ nm = &m->m_next;
+ m->m_next = NULL;
+
+ data0 += len;
+ len0 -= len;
+ if (len0 == 0)
+ break;
+
+ n = _M_RETRY(M_DONTWAIT, MT_DATA);
+ if (n == NULL) {
+ m_freem(top);
+ top = *last = NULL;
+ break;
+ }
+
+ n->m_ext = m->m_ext;
+ m_incref(m);
+ n->m_flags |= M_EXT;
+ m = n;
+ }
+ return (top);
+}
+
+struct mbuf *
+m_normalize(struct mbuf *m)
+{
+ struct mbuf *top = NULL;
+ struct mbuf **nm = ⊤
+ boolean_t expanded = FALSE;
+
+ while (m != NULL) {
+ struct mbuf *n;
+
+ n = m->m_next;
+ m->m_next = NULL;
+
+ /* Does the data cross one or more page boundaries? */
+ if (MBUF_MULTIPAGES(m)) {
+ struct mbuf *last;
+ if ((m = m_expand(m, &last)) == NULL) {
+ m_freem(n);
+ m_freem(top);
+ top = NULL;
+ break;
+ }
+ *nm = m;
+ nm = &last->m_next;
+ expanded = TRUE;
+ } else {
+ *nm = m;
+ nm = &m->m_next;
+ }
+ m = n;
+ }
+ if (expanded)
+ atomic_add_32(&mb_normalized, 1);
+ return (top);
+}
+
+/*
+ * Append the specified data to the indicated mbuf chain,
+ * Extend the mbuf chain if the new data does not fit in
+ * existing space.
+ *
+ * Return 1 if able to complete the job; otherwise 0.
+ */
+int
+m_append(struct mbuf *m0, int len, caddr_t cp)
+{
+ struct mbuf *m, *n;
+ int remainder, space;
+
+ for (m = m0; m->m_next != NULL; m = m->m_next)
+ ;
+ remainder = len;
+ space = M_TRAILINGSPACE(m);
+ if (space > 0) {
+ /*
+ * Copy into available space.
+ */
+ if (space > remainder)
+ space = remainder;
+ bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
+ m->m_len += space;
+ cp += space;
+ remainder -= space;
+ }
+ while (remainder > 0) {
+ /*
+ * Allocate a new mbuf; could check space
+ * and allocate a cluster instead.
+ */
+ n = m_get(M_WAITOK, m->m_type);
+ if (n == NULL)
+ break;
+ n->m_len = min(MLEN, remainder);
+ bcopy(cp, mtod(n, caddr_t), n->m_len);
+ cp += n->m_len;
+ remainder -= n->m_len;
+ m->m_next = n;
+ m = n;
+ }
+ if (m0->m_flags & M_PKTHDR)
+ m0->m_pkthdr.len += len - remainder;
+ return (remainder == 0);
+}
+
+struct mbuf *
+m_last(struct mbuf *m)
+{
+ while (m->m_next != NULL)
+ m = m->m_next;
+ return (m);
+}
+
+unsigned int
+m_fixhdr(struct mbuf *m0)
+{
+ u_int len;
+
+ VERIFY(m0->m_flags & M_PKTHDR);
+
+ len = m_length2(m0, NULL);
+ m0->m_pkthdr.len = len;
+ return (len);
+}
+
+unsigned int
+m_length2(struct mbuf *m0, struct mbuf **last)
+{
+ struct mbuf *m;
+ u_int len;
+
+ len = 0;
+ for (m = m0; m != NULL; m = m->m_next) {
+ len += m->m_len;
+ if (m->m_next == NULL)
+ break;
+ }
+ if (last != NULL)
+ *last = m;
+ return (len);
+}
+
+/*
+ * Defragment a mbuf chain, returning the shortest possible chain of mbufs
+ * and clusters. If allocation fails and this cannot be completed, NULL will
+ * be returned, but the passed in chain will be unchanged. Upon success,
+ * the original chain will be freed, and the new chain will be returned.
+ *
+ * If a non-packet header is passed in, the original mbuf (chain?) will
+ * be returned unharmed.
+ *
+ * If offset is specfied, the first mbuf in the chain will have a leading
+ * space of the amount stated by the "off" parameter.
+ *
+ * This routine requires that the m_pkthdr.header field of the original
+ * mbuf chain is cleared by the caller.
+ */
+struct mbuf *
+m_defrag_offset(struct mbuf *m0, u_int32_t off, int how)
+{
+ struct mbuf *m_new = NULL, *m_final = NULL;
+ int progress = 0, length, pktlen;
+
+ if (!(m0->m_flags & M_PKTHDR))
+ return (m0);
+
+ VERIFY(off < MHLEN);
+ m_fixhdr(m0); /* Needed sanity check */
+
+ pktlen = m0->m_pkthdr.len + off;
+ if (pktlen > MHLEN)
+ m_final = m_getcl(how, MT_DATA, M_PKTHDR);
+ else
+ m_final = m_gethdr(how, MT_DATA);
+
+ if (m_final == NULL)
+ goto nospace;
+
+ if (off > 0) {
+ pktlen -= off;
+ m_final->m_data += off;
+ }
+
+ /*
+ * Caller must have handled the contents pointed to by this
+ * pointer before coming here, as otherwise it will point to
+ * the original mbuf which will get freed upon success.
+ */
+ VERIFY(m0->m_pkthdr.pkt_hdr == NULL);
+
+ if (m_dup_pkthdr(m_final, m0, how) == 0)
+ goto nospace;
+
+ m_new = m_final;
+
+ while (progress < pktlen) {
+ length = pktlen - progress;
+ if (length > MCLBYTES)
+ length = MCLBYTES;
+ length -= ((m_new == m_final) ? off : 0);
+ if (length < 0)
+ goto nospace;
+
+ if (m_new == NULL) {
+ if (length > MLEN)
+ m_new = m_getcl(how, MT_DATA, 0);
+ else
+ m_new = m_get(how, MT_DATA);
+ if (m_new == NULL)
+ goto nospace;
+ }
+
+ m_copydata(m0, progress, length, mtod(m_new, caddr_t));
+ progress += length;
+ m_new->m_len = length;
+ if (m_new != m_final)
+ m_cat(m_final, m_new);
+ m_new = NULL;
+ }
+ m_freem(m0);
+ m0 = m_final;
+ return (m0);
+nospace:
+ if (m_final)
+ m_freem(m_final);
+ return (NULL);
+}
+
+struct mbuf *
+m_defrag(struct mbuf *m0, int how)
+{
+ return (m_defrag_offset(m0, 0, how));
+}
+
+void
+m_mchtype(struct mbuf *m, int t)
+{
+ mtype_stat_inc(t);
+ mtype_stat_dec(m->m_type);
+ (m)->m_type = t;
+}
+
+void *
+m_mtod(struct mbuf *m)
+{
+ return (MTOD(m, void *));
+}
+
+struct mbuf *
+m_dtom(void *x)
+{
+ return ((struct mbuf *)((uintptr_t)(x) & ~(MSIZE-1)));
+}
+
+void
+m_mcheck(struct mbuf *m)
+{
+ _MCHECK(m);
+}
+
+/*
+ * Return a pointer to mbuf/offset of location in mbuf chain.
+ */
+struct mbuf *
+m_getptr(struct mbuf *m, int loc, int *off)
+{
+
+ while (loc >= 0) {
+ /* Normal end of search. */
+ if (m->m_len > loc) {
+ *off = loc;
+ return (m);
+ } else {
+ loc -= m->m_len;
+ if (m->m_next == NULL) {
+ if (loc == 0) {
+ /* Point at the end of valid data. */
+ *off = m->m_len;
+ return (m);
+ }
+ return (NULL);
+ }
+ m = m->m_next;
+ }
+ }
+ return (NULL);
+}
+
+/*
+ * Inform the corresponding mcache(s) that there's a waiter below.
+ */
+static void
+mbuf_waiter_inc(mbuf_class_t class, boolean_t comp)
+{
+ mcache_waiter_inc(m_cache(class));
+ if (comp) {
+ if (class == MC_CL) {
+ mcache_waiter_inc(m_cache(MC_MBUF_CL));
+ } else if (class == MC_BIGCL) {
+ mcache_waiter_inc(m_cache(MC_MBUF_BIGCL));
+ } else if (class == MC_16KCL) {
+ mcache_waiter_inc(m_cache(MC_MBUF_16KCL));
+ } else {
+ mcache_waiter_inc(m_cache(MC_MBUF_CL));
+ mcache_waiter_inc(m_cache(MC_MBUF_BIGCL));
+ }
+ }
+}
+
+/*
+ * Inform the corresponding mcache(s) that there's no more waiter below.
+ */
+static void
+mbuf_waiter_dec(mbuf_class_t class, boolean_t comp)
+{
+ mcache_waiter_dec(m_cache(class));
+ if (comp) {
+ if (class == MC_CL) {
+ mcache_waiter_dec(m_cache(MC_MBUF_CL));
+ } else if (class == MC_BIGCL) {
+ mcache_waiter_dec(m_cache(MC_MBUF_BIGCL));
+ } else if (class == MC_16KCL) {
+ mcache_waiter_dec(m_cache(MC_MBUF_16KCL));
+ } else {
+ mcache_waiter_dec(m_cache(MC_MBUF_CL));
+ mcache_waiter_dec(m_cache(MC_MBUF_BIGCL));
+ }
+ }
+}
+
+/*
+ * Called during slab (blocking and non-blocking) allocation. If there
+ * is at least one waiter, and the time since the first waiter is blocked
+ * is greater than the watchdog timeout, panic the system.
+ */
+static void
+mbuf_watchdog(void)
+{
+ struct timeval now;
+ unsigned int since;
+
+ if (mb_waiters == 0 || !mb_watchdog)
+ return;
+
+ microuptime(&now);
+ since = now.tv_sec - mb_wdtstart.tv_sec;
+ if (since >= MB_WDT_MAXTIME) {
+ panic_plain("%s: %d waiters stuck for %u secs\n%s", __func__,
+ mb_waiters, since, mbuf_dump());
+ /* NOTREACHED */
+ }
+}
+
+/*
+ * Called during blocking allocation. Returns TRUE if one or more objects
+ * are available at the per-CPU caches layer and that allocation should be
+ * retried at that level.
+ */
+static boolean_t
+mbuf_sleep(mbuf_class_t class, unsigned int num, int wait)
+{
+ boolean_t mcache_retry = FALSE;
+
+ LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
+
+ /* Check if there's anything at the cache layer */
+ if (mbuf_cached_above(class, wait)) {
+ mcache_retry = TRUE;
+ goto done;
+ }
+
+ /* Nothing? Then try hard to get it from somewhere */
+ m_reclaim(class, num, (wait & MCR_COMP));
+
+ /* We tried hard and got something? */
+ if (m_infree(class) > 0) {
+ mbstat.m_wait++;
+ goto done;
+ } else if (mbuf_cached_above(class, wait)) {
+ mbstat.m_wait++;
+ mcache_retry = TRUE;
+ goto done;
+ } else if (wait & MCR_TRYHARD) {
+ mcache_retry = TRUE;
+ goto done;
+ }
+
+ /*
+ * There's really nothing for us right now; inform the
+ * cache(s) that there is a waiter below and go to sleep.
+ */
+ mbuf_waiter_inc(class, (wait & MCR_COMP));
+
+ VERIFY(!(wait & MCR_NOSLEEP));
+
+ /*
+ * If this is the first waiter, arm the watchdog timer. Otherwise
+ * check if we need to panic the system due to watchdog timeout.
+ */
+ if (mb_waiters == 0)
+ microuptime(&mb_wdtstart);
+ else
+ mbuf_watchdog();
+
+ mb_waiters++;
+ m_region_expand(class) += m_total(class) + num;
+ /* wake up the worker thread */
+ if (class > MC_MBUF && mbuf_worker_ready &&
+ mbuf_worker_needs_wakeup) {
+ wakeup((caddr_t)&mbuf_worker_needs_wakeup);
+ mbuf_worker_needs_wakeup = FALSE;
+ }
+
+ (void) msleep(mb_waitchan, mbuf_mlock, (PZERO-1), m_cname(class), NULL);
+
+ /* We are now up; stop getting notified until next round */
+ mbuf_waiter_dec(class, (wait & MCR_COMP));
+
+ /* We waited and got something */
+ if (m_infree(class) > 0) {
+ mbstat.m_wait++;
+ goto done;
+ } else if (mbuf_cached_above(class, wait)) {
+ mbstat.m_wait++;
+ mcache_retry = TRUE;
+ }
+done:
+ return (mcache_retry);
+}
+
+__attribute__((noreturn))
+static void
+mbuf_worker_thread(void)
+{
+ int mbuf_expand;
+
+ while (1) {
+ lck_mtx_lock(mbuf_mlock);
+ mbuf_worker_run_cnt++;
+ mbuf_expand = 0;
+ if (m_region_expand(MC_CL) > 0) {
+ int n;
+ mb_expand_cl_cnt++;
+ /* Adjust to current number of cluster in use */
+ n = m_region_expand(MC_CL) -
+ (m_total(MC_CL) - m_infree(MC_CL));
+ if ((n + m_total(MC_CL)) > m_maxlimit(MC_CL))
+ n = m_maxlimit(MC_CL) - m_total(MC_CL);
+ if (n > 0) {
+ mb_expand_cl_total += n;
+ }
+ m_region_expand(MC_CL) = 0;
+
+ if (n > 0 && freelist_populate(MC_CL, n, M_WAIT) > 0)
+ mbuf_expand++;
+ }
+ if (m_region_expand(MC_BIGCL) > 0) {
+ int n;
+ mb_expand_bigcl_cnt++;
+ /* Adjust to current number of 4 KB cluster in use */
+ n = m_region_expand(MC_BIGCL) -
+ (m_total(MC_BIGCL) - m_infree(MC_BIGCL));
+ if ((n + m_total(MC_BIGCL)) > m_maxlimit(MC_BIGCL))
+ n = m_maxlimit(MC_BIGCL) - m_total(MC_BIGCL);
+ if (n > 0) {
+ mb_expand_bigcl_total += n;
+ }
+ m_region_expand(MC_BIGCL) = 0;
+
+ if (n > 0 && freelist_populate(MC_BIGCL, n, M_WAIT) > 0)
+ mbuf_expand++;
+ }
+ if (m_region_expand(MC_16KCL) > 0) {
+ int n;
+ mb_expand_16kcl_cnt++;
+ /* Adjust to current number of 16 KB cluster in use */
+ n = m_region_expand(MC_16KCL) -
+ (m_total(MC_16KCL) - m_infree(MC_16KCL));
+ if ((n + m_total(MC_16KCL)) > m_maxlimit(MC_16KCL))
+ n = m_maxlimit(MC_16KCL) - m_total(MC_16KCL);
+ if (n > 0) {
+ mb_expand_16kcl_total += n;
+ }
+ m_region_expand(MC_16KCL) = 0;
+
+ if (n > 0)
+ (void) freelist_populate(MC_16KCL, n, M_WAIT);
+ }
+
+ /*
+ * Because we can run out of memory before filling the mbuf
+ * map, we should not allocate more clusters than they are
+ * mbufs -- otherwise we could have a large number of useless
+ * clusters allocated.
+ */
+ if (mbuf_expand) {
+ while (m_total(MC_MBUF) <
+ (m_total(MC_BIGCL) + m_total(MC_CL))) {
+ mb_expand_cnt++;
+ if (freelist_populate(MC_MBUF, 1, M_WAIT) == 0)
+ break;
+ }
+ }
+
+ mbuf_worker_needs_wakeup = TRUE;
+ /*
+ * If there's a deadlock and we're not sending / receiving
+ * packets, net_uptime() won't be updated. Update it here
+ * so we are sure it's correct.
+ */
+ net_update_uptime();
+ mbuf_worker_last_runtime = net_uptime();
+ assert_wait((caddr_t)&mbuf_worker_needs_wakeup,
+ THREAD_UNINT);
+ lck_mtx_unlock(mbuf_mlock);
+ (void) thread_block((thread_continue_t)mbuf_worker_thread);
+ }
+}
+
+__attribute__((noreturn))
+static void
+mbuf_worker_thread_init(void)
+{
+ mbuf_worker_ready++;
+ mbuf_worker_thread();
+}
+
+static mcl_slab_t *
+slab_get(void *buf)
+{
+ mcl_slabg_t *slg;
+ unsigned int ix, k;
+
+ LCK_MTX_ASSERT(mbuf_mlock, LCK_MTX_ASSERT_OWNED);
+
+ VERIFY(MBUF_IN_MAP(buf));
+ ix = ((unsigned char *)buf - mbutl) >> MBSHIFT;
+ VERIFY(ix < maxslabgrp);
+
+ if ((slg = slabstbl[ix]) == NULL) {
+ /*
+ * In the current implementation, we never shrink the slabs
+ * table; if we attempt to reallocate a cluster group when
+ * it's already allocated, panic since this is a sign of a
+ * memory corruption (slabstbl[ix] got nullified).
+ */
+ ++slabgrp;
+ VERIFY(ix < slabgrp);
+ /*
+ * Slabs expansion can only be done single threaded; when
+ * we get here, it must be as a result of m_clalloc() which
+ * is serialized and therefore mb_clalloc_busy must be set.
+ */
+ VERIFY(mb_clalloc_busy);
+ lck_mtx_unlock(mbuf_mlock);
+
+ /* This is a new buffer; create the slabs group for it */
+ MALLOC(slg, mcl_slabg_t *, sizeof (*slg), M_TEMP,
+ M_WAITOK | M_ZERO);
+ MALLOC(slg->slg_slab, mcl_slab_t *, sizeof(mcl_slab_t) * NSLABSPMB,
+ M_TEMP, M_WAITOK | M_ZERO);
+ VERIFY(slg != NULL && slg->slg_slab != NULL);
+
+ lck_mtx_lock(mbuf_mlock);
+ /*
+ * No other thread could have gone into m_clalloc() after
+ * we dropped the lock above, so verify that it's true.
+ */
+ VERIFY(mb_clalloc_busy);
+
+ slabstbl[ix] = slg;
+
+ /* Chain each slab in the group to its forward neighbor */
+ for (k = 1; k < NSLABSPMB; k++)
+ slg->slg_slab[k - 1].sl_next = &slg->slg_slab[k];
+ VERIFY(slg->slg_slab[NSLABSPMB - 1].sl_next == NULL);
+
+ /* And chain the last slab in the previous group to this */
+ if (ix > 0) {
+ VERIFY(slabstbl[ix - 1]->
+ slg_slab[NSLABSPMB - 1].sl_next == NULL);
+ slabstbl[ix - 1]->slg_slab[NSLABSPMB - 1].sl_next =
+ &slg->slg_slab[0];
+ }
+ }
+
+ ix = MTOPG(buf) % NSLABSPMB;
+ VERIFY(ix < NSLABSPMB);
+
+ return (&slg->slg_slab[ix]);
+}
+
+static void
+slab_init(mcl_slab_t *sp, mbuf_class_t class, u_int32_t flags,
+ void *base, void *head, unsigned int len, int refcnt, int chunks)
+{
+ sp->sl_class = class;
+ sp->sl_flags = flags;
+ sp->sl_base = base;
+ sp->sl_head = head;
+ sp->sl_len = len;
+ sp->sl_refcnt = refcnt;
+ sp->sl_chunks = chunks;
+ slab_detach(sp);
+}
+
+static void
+slab_insert(mcl_slab_t *sp, mbuf_class_t class)
+{
+ VERIFY(slab_is_detached(sp));
+ m_slab_cnt(class)++;
+ TAILQ_INSERT_TAIL(&m_slablist(class), sp, sl_link);
+ sp->sl_flags &= ~SLF_DETACHED;
+
+ /*
+ * If a buffer spans multiple contiguous pages then mark them as
+ * detached too
+ */
+ if (class == MC_16KCL) {
+ int k;
+ for (k = 1; k < NSLABSP16KB; k++) {
+ sp = sp->sl_next;
+ /* Next slab must already be present */
+ VERIFY(sp != NULL && slab_is_detached(sp));
+ sp->sl_flags &= ~SLF_DETACHED;
+ }
+ }
+}
+
+static void
+slab_remove(mcl_slab_t *sp, mbuf_class_t class)
+{
+ int k;
+ VERIFY(!slab_is_detached(sp));
+ VERIFY(m_slab_cnt(class) > 0);
+ m_slab_cnt(class)--;
+ TAILQ_REMOVE(&m_slablist(class), sp, sl_link);
+ slab_detach(sp);
+ if (class == MC_16KCL) {
+ for (k = 1; k < NSLABSP16KB; k++) {
+ sp = sp->sl_next;
+ /* Next slab must already be present */
+ VERIFY(sp != NULL);
+ VERIFY(!slab_is_detached(sp));
+ slab_detach(sp);
+ }
+ }
+}
+
+static boolean_t
+slab_inrange(mcl_slab_t *sp, void *buf)
+{
+ return ((uintptr_t)buf >= (uintptr_t)sp->sl_base &&
+ (uintptr_t)buf < ((uintptr_t)sp->sl_base + sp->sl_len));
+}
+
+#undef panic
+
+static void
+slab_nextptr_panic(mcl_slab_t *sp, void *addr)
+{
+ int i;
+ unsigned int chunk_len = sp->sl_len / sp->sl_chunks;
+ uintptr_t buf = (uintptr_t)sp->sl_base;
+
+ for (i = 0; i < sp->sl_chunks; i++, buf += chunk_len) {
+ void *next = ((mcache_obj_t *)buf)->obj_next;
+ if (next != addr)
+ continue;
+ if (!mclverify) {
+ if (next != NULL && !MBUF_IN_MAP(next)) {
+ mcache_t *cp = m_cache(sp->sl_class);
+ panic("%s: %s buffer %p in slab %p modified "
+ "after free at offset 0: %p out of range "
+ "[%p-%p)\n", __func__, cp->mc_name,
+ (void *)buf, sp, next, mbutl, embutl);
+ /* NOTREACHED */
+ }
+ } else {
+ mcache_audit_t *mca = mcl_audit_buf2mca(sp->sl_class,
+ (mcache_obj_t *)buf);
+ mcl_audit_verify_nextptr(next, mca);
+ }
+ }
+}
+
+static void
+slab_detach(mcl_slab_t *sp)
+{
+ sp->sl_link.tqe_next = (mcl_slab_t *)-1;
+ sp->sl_link.tqe_prev = (mcl_slab_t **)-1;
+ sp->sl_flags |= SLF_DETACHED;
+}
+
+static boolean_t
+slab_is_detached(mcl_slab_t *sp)
+{
+ return ((intptr_t)sp->sl_link.tqe_next == -1 &&
+ (intptr_t)sp->sl_link.tqe_prev == -1 &&
+ (sp->sl_flags & SLF_DETACHED));
+}
+
+static void
+mcl_audit_init(void *buf, mcache_audit_t **mca_list,
+ mcache_obj_t **con_list, size_t con_size, unsigned int num)
+{
+ mcache_audit_t *mca, *mca_tail;
+ mcache_obj_t *con = NULL;
+ boolean_t save_contents = (con_list != NULL);
+ unsigned int i, ix;
+
+ ASSERT(num <= NMBPG);
+ ASSERT(con_list == NULL || con_size != 0);
+
+ ix = MTOPG(buf);
+ VERIFY(ix < maxclaudit);
+
+ /* Make sure we haven't been here before */
+ for (i = 0; i < num; i++)
+ VERIFY(mclaudit[ix].cl_audit[i] == NULL);
+
+ mca = mca_tail = *mca_list;
+ if (save_contents)
+ con = *con_list;
+
+ for (i = 0; i < num; i++) {
+ mcache_audit_t *next;
+
+ next = mca->mca_next;
+ bzero(mca, sizeof (*mca));
+ mca->mca_next = next;
+ mclaudit[ix].cl_audit[i] = mca;
+
+ /* Attach the contents buffer if requested */
+ if (save_contents) {
+ mcl_saved_contents_t *msc =
+ (mcl_saved_contents_t *)(void *)con;
+
+ VERIFY(msc != NULL);
+ VERIFY(IS_P2ALIGNED(msc, sizeof (u_int64_t)));
+ VERIFY(con_size == sizeof (*msc));
+ mca->mca_contents_size = con_size;
+ mca->mca_contents = msc;
+ con = con->obj_next;
+ bzero(mca->mca_contents, mca->mca_contents_size);
+ }
+
+ mca_tail = mca;
+ mca = mca->mca_next;
+ }
+
+ if (save_contents)
+ *con_list = con;
+
+ *mca_list = mca_tail->mca_next;
+ mca_tail->mca_next = NULL;
+}
+
+static void
+mcl_audit_free(void *buf, unsigned int num)
+{
+ unsigned int i, ix;
+ mcache_audit_t *mca, *mca_list;
+
+ ix = MTOPG(buf);
+ VERIFY(ix < maxclaudit);
+
+ if (mclaudit[ix].cl_audit[0] != NULL) {
+ mca_list = mclaudit[ix].cl_audit[0];
+ for (i = 0; i < num; i++) {
+ mca = mclaudit[ix].cl_audit[i];
+ mclaudit[ix].cl_audit[i] = NULL;
+ if (mca->mca_contents)
+ mcache_free(mcl_audit_con_cache,
+ mca->mca_contents);
+ }
+ mcache_free_ext(mcache_audit_cache,
+ (mcache_obj_t *)mca_list);
+ }
+}
+
+/*
+ * Given an address of a buffer (mbuf/2KB/4KB/16KB), return
+ * the corresponding audit structure for that buffer.
+ */
+static mcache_audit_t *
+mcl_audit_buf2mca(mbuf_class_t class, mcache_obj_t *mobj)
+{
+ mcache_audit_t *mca = NULL;
+ int ix = MTOPG(mobj), m_idx = 0;
+ unsigned char *page_addr;
+
+ VERIFY(ix < maxclaudit);
+ VERIFY(IS_P2ALIGNED(mobj, MIN(m_maxsize(class), PAGE_SIZE)));
+
+ page_addr = PGTOM(ix);
+
+ switch (class) {
+ case MC_MBUF:
+ /*
+ * For the mbuf case, find the index of the page
+ * used by the mbuf and use that index to locate the
+ * base address of the page. Then find out the
+ * mbuf index relative to the page base and use
+ * it to locate the audit structure.
+ */
+ m_idx = MBPAGEIDX(page_addr, mobj);
+ VERIFY(m_idx < (int)NMBPG);
+ mca = mclaudit[ix].cl_audit[m_idx];
+ break;
+
+ case MC_CL:
+ /*
+ * Same thing as above, but for 2KB clusters in a page.
+ */
+ m_idx = CLPAGEIDX(page_addr, mobj);
+ VERIFY(m_idx < (int)NCLPG);
+ mca = mclaudit[ix].cl_audit[m_idx];
+ break;
+
+ case MC_BIGCL:
+ m_idx = BCLPAGEIDX(page_addr, mobj);
+ VERIFY(m_idx < (int)NBCLPG);
+ mca = mclaudit[ix].cl_audit[m_idx];
+ break;
+ case MC_16KCL:
+ /*
+ * Same as above, but only return the first element.
+ */
+ mca = mclaudit[ix].cl_audit[0];
+ break;
+
+ default:
+ VERIFY(0);
+ /* NOTREACHED */
+ }
+
+ return (mca);
+}
+
+static void
+mcl_audit_mbuf(mcache_audit_t *mca, void *addr, boolean_t composite,
+ boolean_t alloc)
+{
+ struct mbuf *m = addr;
+ mcache_obj_t *next = ((mcache_obj_t *)m)->obj_next;
+
+ VERIFY(mca->mca_contents != NULL &&
+ mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
+
+ if (mclverify)
+ mcl_audit_verify_nextptr(next, mca);
+
+ if (!alloc) {
+ /* Save constructed mbuf fields */
+ mcl_audit_save_mbuf(m, mca);
+ if (mclverify) {
+ mcache_set_pattern(MCACHE_FREE_PATTERN, m,
+ m_maxsize(MC_MBUF));
+ }
+ ((mcache_obj_t *)m)->obj_next = next;
+ return;
+ }
+
+ /* Check if the buffer has been corrupted while in freelist */
+ if (mclverify) {
+ mcache_audit_free_verify_set(mca, addr, 0, m_maxsize(MC_MBUF));
+ }
+ /* Restore constructed mbuf fields */
+ mcl_audit_restore_mbuf(m, mca, composite);
+}
+
+static void
+mcl_audit_restore_mbuf(struct mbuf *m, mcache_audit_t *mca, boolean_t composite)
+{
+ struct mbuf *ms = MCA_SAVED_MBUF_PTR(mca);
+
+ if (composite) {
+ struct mbuf *next = m->m_next;
+ VERIFY(ms->m_flags == M_EXT && m_get_rfa(ms) != NULL &&
+ MBUF_IS_COMPOSITE(ms));
+ VERIFY(mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
+ /*
+ * We could have hand-picked the mbuf fields and restore
+ * them individually, but that will be a maintenance
+ * headache. Instead, restore everything that was saved;
+ * the mbuf layer will recheck and reinitialize anyway.
+ */
+ bcopy(ms, m, MCA_SAVED_MBUF_SIZE);
+ m->m_next = next;
+ } else {
+ /*
+ * For a regular mbuf (no cluster attached) there's nothing
+ * to restore other than the type field, which is expected
+ * to be MT_FREE.
+ */
+ m->m_type = ms->m_type;
+ }
+ _MCHECK(m);
+}
+
+static void
+mcl_audit_save_mbuf(struct mbuf *m, mcache_audit_t *mca)
+{
+ VERIFY(mca->mca_contents_size == AUDIT_CONTENTS_SIZE);
+ _MCHECK(m);
+ bcopy(m, MCA_SAVED_MBUF_PTR(mca), MCA_SAVED_MBUF_SIZE);
+}
+
+static void
+mcl_audit_cluster(mcache_audit_t *mca, void *addr, size_t size, boolean_t alloc,
+ boolean_t save_next)
+{
+ mcache_obj_t *next = ((mcache_obj_t *)addr)->obj_next;
+
+ if (!alloc) {
+ if (mclverify) {
+ mcache_set_pattern(MCACHE_FREE_PATTERN, addr, size);
+ }
+ if (save_next) {
+ mcl_audit_verify_nextptr(next, mca);
+ ((mcache_obj_t *)addr)->obj_next = next;
+ }
+ } else if (mclverify) {
+ /* Check if the buffer has been corrupted while in freelist */
+ mcl_audit_verify_nextptr(next, mca);
+ mcache_audit_free_verify_set(mca, addr, 0, size);
+ }
+}
+
+static void
+mcl_audit_scratch(mcache_audit_t *mca)
+{
+ void *stack[MCACHE_STACK_DEPTH + 1];
+ mcl_scratch_audit_t *msa;
+ struct timeval now;
+
+ VERIFY(mca->mca_contents != NULL);
+ msa = MCA_SAVED_SCRATCH_PTR(mca);
+
+ msa->msa_pthread = msa->msa_thread;
+ msa->msa_thread = current_thread();
+ bcopy(msa->msa_stack, msa->msa_pstack, sizeof (msa->msa_pstack));
+ msa->msa_pdepth = msa->msa_depth;
+ bzero(stack, sizeof (stack));
+ msa->msa_depth = OSBacktrace(stack, MCACHE_STACK_DEPTH + 1) - 1;
+ bcopy(&stack[1], msa->msa_stack, sizeof (msa->msa_stack));
+
+ msa->msa_ptstamp = msa->msa_tstamp;
+ microuptime(&now);
+ /* tstamp is in ms relative to base_ts */
+ msa->msa_tstamp = ((now.tv_usec - mb_start.tv_usec) / 1000);
+ if ((now.tv_sec - mb_start.tv_sec) > 0)
+ msa->msa_tstamp += ((now.tv_sec - mb_start.tv_sec) * 1000);
+}
+
+static void
+mcl_audit_mcheck_panic(struct mbuf *m)
+{
+ mcache_audit_t *mca;
+
+ MRANGE(m);
+ mca = mcl_audit_buf2mca(MC_MBUF, (mcache_obj_t *)m);
+
+ panic("mcl_audit: freed mbuf %p with type 0x%x (instead of 0x%x)\n%s\n",
+ m, (u_int16_t)m->m_type, MT_FREE, mcache_dump_mca(mca));
+ /* NOTREACHED */
+}
+
+static void
+mcl_audit_verify_nextptr(void *next, mcache_audit_t *mca)
+{
+ if (next != NULL && !MBUF_IN_MAP(next) &&
+ (next != (void *)MCACHE_FREE_PATTERN || !mclverify)) {
+ panic("mcl_audit: buffer %p modified after free at offset 0: "
+ "%p out of range [%p-%p)\n%s\n",
+ mca->mca_addr, next, mbutl, embutl, mcache_dump_mca(mca));
+ /* NOTREACHED */
+ }
+}
+
+/* This function turns on mbuf leak detection */
+static void
+mleak_activate(void)
+{
+ mleak_table.mleak_sample_factor = MLEAK_SAMPLE_FACTOR;
+ PE_parse_boot_argn("mleak_sample_factor",
+ &mleak_table.mleak_sample_factor,
+ sizeof (mleak_table.mleak_sample_factor));
+
+ if (mleak_table.mleak_sample_factor == 0)
+ mclfindleak = 0;
+
+ if (mclfindleak == 0)
+ return;
+
+ vm_size_t alloc_size =
+ mleak_alloc_buckets * sizeof (struct mallocation);
+ vm_size_t trace_size = mleak_trace_buckets * sizeof (struct mtrace);
+
+ MALLOC(mleak_allocations, struct mallocation *, alloc_size,
+ M_TEMP, M_WAITOK | M_ZERO);
+ VERIFY(mleak_allocations != NULL);
+
+ MALLOC(mleak_traces, struct mtrace *, trace_size,
+ M_TEMP, M_WAITOK | M_ZERO);
+ VERIFY(mleak_traces != NULL);
+
+ MALLOC(mleak_stat, mleak_stat_t *, MLEAK_STAT_SIZE(MLEAK_NUM_TRACES),
+ M_TEMP, M_WAITOK | M_ZERO);
+ VERIFY(mleak_stat != NULL);
+ mleak_stat->ml_cnt = MLEAK_NUM_TRACES;
+#ifdef __LP64__
+ mleak_stat->ml_isaddr64 = 1;
+#endif /* __LP64__ */
+}
+
+static void
+mleak_logger(u_int32_t num, mcache_obj_t *addr, boolean_t alloc)
+{
+ int temp;
+
+ if (mclfindleak == 0)
+ return;
+
+ if (!alloc)
+ return (mleak_free(addr));
+
+ temp = atomic_add_32_ov(&mleak_table.mleak_capture, 1);
+
+ if ((temp % mleak_table.mleak_sample_factor) == 0 && addr != NULL) {
+ uintptr_t bt[MLEAK_STACK_DEPTH];
+ int logged = backtrace(bt, MLEAK_STACK_DEPTH);
+ mleak_log(bt, addr, logged, num);
+ }
+}
+
+/*
+ * This function records the allocation in the mleak_allocations table
+ * and the backtrace in the mleak_traces table; if allocation slot is in use,
+ * replace old allocation with new one if the trace slot is in use, return
+ * (or increment refcount if same trace).
+ */
+static boolean_t
+mleak_log(uintptr_t *bt, mcache_obj_t *addr, uint32_t depth, int num)
+{
+ struct mallocation *allocation;
+ struct mtrace *trace;
+ uint32_t trace_index;
+
+ /* Quit if someone else modifying the tables */
+ if (!lck_mtx_try_lock_spin(mleak_lock)) {
+ mleak_table.total_conflicts++;
+ return (FALSE);
+ }
+
+ allocation = &mleak_allocations[hashaddr((uintptr_t)addr,
+ mleak_alloc_buckets)];
+ trace_index = hashbacktrace(bt, depth, mleak_trace_buckets);
+ trace = &mleak_traces[trace_index];
+
+ VERIFY(allocation <= &mleak_allocations[mleak_alloc_buckets - 1]);
+ VERIFY(trace <= &mleak_traces[mleak_trace_buckets - 1]);
+
+ allocation->hitcount++;
+ trace->hitcount++;
+
+ /*
+ * If the allocation bucket we want is occupied
+ * and the occupier has the same trace, just bail.
+ */
+ if (allocation->element != NULL &&
+ trace_index == allocation->trace_index) {
+ mleak_table.alloc_collisions++;
+ lck_mtx_unlock(mleak_lock);
+ return (TRUE);
+ }
+
+ /*
+ * Store the backtrace in the traces array;
+ * Size of zero = trace bucket is free.
+ */
+ if (trace->allocs > 0 &&
+ bcmp(trace->addr, bt, (depth * sizeof (uintptr_t))) != 0) {
+ /* Different, unique trace, but the same hash! Bail out. */
+ trace->collisions++;
+ mleak_table.trace_collisions++;
+ lck_mtx_unlock(mleak_lock);
+ return (TRUE);
+ } else if (trace->allocs > 0) {
+ /* Same trace, already added, so increment refcount */
+ trace->allocs++;
+ } else {
+ /* Found an unused trace bucket, so record the trace here */
+ if (trace->depth != 0) {
+ /* this slot previously used but not currently in use */
+ mleak_table.trace_overwrites++;
+ }
+ mleak_table.trace_recorded++;
+ trace->allocs = 1;
+ memcpy(trace->addr, bt, (depth * sizeof (uintptr_t)));
+ trace->depth = depth;
+ trace->collisions = 0;
+ }
+
+ /* Step 2: Store the allocation record in the allocations array */
+ if (allocation->element != NULL) {
+ /*
+ * Replace an existing allocation. No need to preserve
+ * because only a subset of the allocations are being
+ * recorded anyway.
+ */
+ mleak_table.alloc_collisions++;
+ } else if (allocation->trace_index != 0) {
+ mleak_table.alloc_overwrites++;
+ }
+ allocation->element = addr;
+ allocation->trace_index = trace_index;
+ allocation->count = num;
+ mleak_table.alloc_recorded++;
+ mleak_table.outstanding_allocs++;
+
+ lck_mtx_unlock(mleak_lock);
+ return (TRUE);
+}
+
+static void
+mleak_free(mcache_obj_t *addr)
+{
+ while (addr != NULL) {
+ struct mallocation *allocation = &mleak_allocations
+ [hashaddr((uintptr_t)addr, mleak_alloc_buckets)];
+
+ if (allocation->element == addr &&
+ allocation->trace_index < mleak_trace_buckets) {
+ lck_mtx_lock_spin(mleak_lock);
+ if (allocation->element == addr &&
+ allocation->trace_index < mleak_trace_buckets) {
+ struct mtrace *trace;
+ trace = &mleak_traces[allocation->trace_index];
+ /* allocs = 0 means trace bucket is unused */
+ if (trace->allocs > 0)
+ trace->allocs--;
+ if (trace->allocs == 0)
+ trace->depth = 0;
+ /* NULL element means alloc bucket is unused */
+ allocation->element = NULL;
+ mleak_table.outstanding_allocs--;
+ }
+ lck_mtx_unlock(mleak_lock);
+ }
+ addr = addr->obj_next;
+ }
+}
+
+static void
+mleak_sort_traces()
+{
+ int i, j, k;
+ struct mtrace *swap;
+
+ for(i = 0; i < MLEAK_NUM_TRACES; i++)
+ mleak_top_trace[i] = NULL;
+
+ for(i = 0, j = 0; j < MLEAK_NUM_TRACES && i < mleak_trace_buckets; i++)
+ {
+ if (mleak_traces[i].allocs <= 0)
+ continue;
+
+ mleak_top_trace[j] = &mleak_traces[i];
+ for (k = j; k > 0; k--) {
+ if (mleak_top_trace[k]->allocs <=
+ mleak_top_trace[k-1]->allocs)
+ break;
+
+ swap = mleak_top_trace[k-1];
+ mleak_top_trace[k-1] = mleak_top_trace[k];
+ mleak_top_trace[k] = swap;
+ }
+ j++;
+ }
+
+ j--;
+ for(; i < mleak_trace_buckets; i++) {
+ if (mleak_traces[i].allocs <= mleak_top_trace[j]->allocs)
+ continue;
+
+ mleak_top_trace[j] = &mleak_traces[i];
+
+ for (k = j; k > 0; k--) {
+ if (mleak_top_trace[k]->allocs <=
+ mleak_top_trace[k-1]->allocs)
+ break;
+
+ swap = mleak_top_trace[k-1];
+ mleak_top_trace[k-1] = mleak_top_trace[k];
+ mleak_top_trace[k] = swap;
+ }
+ }
+}
+
+static void
+mleak_update_stats()
+{
+ mleak_trace_stat_t *mltr;
+ int i;
+
+ VERIFY(mleak_stat != NULL);
+#ifdef __LP64__
+ VERIFY(mleak_stat->ml_isaddr64);
+#else
+ VERIFY(!mleak_stat->ml_isaddr64);
+#endif /* !__LP64__ */
+ VERIFY(mleak_stat->ml_cnt == MLEAK_NUM_TRACES);
+
+ mleak_sort_traces();
+
+ mltr = &mleak_stat->ml_trace[0];
+ bzero(mltr, sizeof (*mltr) * MLEAK_NUM_TRACES);
+ for (i = 0; i < MLEAK_NUM_TRACES; i++) {
+ int j;
+
+ if (mleak_top_trace[i] == NULL ||
+ mleak_top_trace[i]->allocs == 0)
+ continue;
+
+ mltr->mltr_collisions = mleak_top_trace[i]->collisions;
+ mltr->mltr_hitcount = mleak_top_trace[i]->hitcount;
+ mltr->mltr_allocs = mleak_top_trace[i]->allocs;
+ mltr->mltr_depth = mleak_top_trace[i]->depth;
+
+ VERIFY(mltr->mltr_depth <= MLEAK_STACK_DEPTH);
+ for (j = 0; j < mltr->mltr_depth; j++)
+ mltr->mltr_addr[j] = mleak_top_trace[i]->addr[j];
+
+ mltr++;
+ }
+}
+
+static struct mbtypes {
+ int mt_type;
+ const char *mt_name;
+} mbtypes[] = {
+ { MT_DATA, "data" },
+ { MT_OOBDATA, "oob data" },
+ { MT_CONTROL, "ancillary data" },
+ { MT_HEADER, "packet headers" },
+ { MT_SOCKET, "socket structures" },
+ { MT_PCB, "protocol control blocks" },
+ { MT_RTABLE, "routing table entries" },
+ { MT_HTABLE, "IMP host table entries" },
+ { MT_ATABLE, "address resolution tables" },
+ { MT_FTABLE, "fragment reassembly queue headers" },
+ { MT_SONAME, "socket names and addresses" },
+ { MT_SOOPTS, "socket options" },
+ { MT_RIGHTS, "access rights" },
+ { MT_IFADDR, "interface addresses" },
+ { MT_TAG, "packet tags" },
+ { 0, NULL }
+};
+
+#define MBUF_DUMP_BUF_CHK() { \
+ clen -= k; \
+ if (clen < 1) \
+ goto done; \
+ c += k; \
+}
+
+static char *
+mbuf_dump(void)
+{
+ unsigned long totmem = 0, totfree = 0, totmbufs, totused, totpct,
+ totreturned = 0;
+ u_int32_t m_mbufs = 0, m_clfree = 0, m_bigclfree = 0;
+ u_int32_t m_mbufclfree = 0, m_mbufbigclfree = 0;
+ u_int32_t m_16kclusters = 0, m_16kclfree = 0, m_mbuf16kclfree = 0;
+ int nmbtypes = sizeof (mbstat.m_mtypes) / sizeof (short);
+ uint8_t seen[256];
+ struct mbtypes *mp;
+ mb_class_stat_t *sp;
+ mleak_trace_stat_t *mltr;
+ char *c = mbuf_dump_buf;
+ int i, k, clen = MBUF_DUMP_BUF_SIZE;
+
+ mbuf_dump_buf[0] = '\0';
+
+ /* synchronize all statistics in the mbuf table */
+ mbuf_stat_sync();
+ mbuf_mtypes_sync(TRUE);
+
+ sp = &mb_stat->mbs_class[0];
+ for (i = 0; i < mb_stat->mbs_cnt; i++, sp++) {
+ u_int32_t mem;
+
+ if (m_class(i) == MC_MBUF) {
+ m_mbufs = sp->mbcl_active;
+ } else if (m_class(i) == MC_CL) {
+ m_clfree = sp->mbcl_total - sp->mbcl_active;
+ } else if (m_class(i) == MC_BIGCL) {
+ m_bigclfree = sp->mbcl_total - sp->mbcl_active;
+ } else if (njcl > 0 && m_class(i) == MC_16KCL) {
+ m_16kclfree = sp->mbcl_total - sp->mbcl_active;
+ m_16kclusters = sp->mbcl_total;
+ } else if (m_class(i) == MC_MBUF_CL) {
+ m_mbufclfree = sp->mbcl_total - sp->mbcl_active;
+ } else if (m_class(i) == MC_MBUF_BIGCL) {
+ m_mbufbigclfree = sp->mbcl_total - sp->mbcl_active;
+ } else if (njcl > 0 && m_class(i) == MC_MBUF_16KCL) {
+ m_mbuf16kclfree = sp->mbcl_total - sp->mbcl_active;
+ }
+
+ mem = sp->mbcl_ctotal * sp->mbcl_size;
+ totmem += mem;
+ totfree += (sp->mbcl_mc_cached + sp->mbcl_infree) *
+ sp->mbcl_size;
+ totreturned += sp->mbcl_release_cnt;
+
+ }
+
+ /* adjust free counts to include composite caches */
+ m_clfree += m_mbufclfree;
+ m_bigclfree += m_mbufbigclfree;
+ m_16kclfree += m_mbuf16kclfree;
+
+ totmbufs = 0;
+ for (mp = mbtypes; mp->mt_name != NULL; mp++)
+ totmbufs += mbstat.m_mtypes[mp->mt_type];
+ if (totmbufs > m_mbufs)
+ totmbufs = m_mbufs;
+ k = snprintf(c, clen, "%lu/%u mbufs in use:\n", totmbufs, m_mbufs);
+ MBUF_DUMP_BUF_CHK();
+
+ bzero(&seen, sizeof (seen));
+ for (mp = mbtypes; mp->mt_name != NULL; mp++) {
+ if (mbstat.m_mtypes[mp->mt_type] != 0) {
+ seen[mp->mt_type] = 1;
+ k = snprintf(c, clen, "\t%u mbufs allocated to %s\n",
+ mbstat.m_mtypes[mp->mt_type], mp->mt_name);
+ MBUF_DUMP_BUF_CHK();
+ }
+ }
+ seen[MT_FREE] = 1;
+ for (i = 0; i < nmbtypes; i++)
+ if (!seen[i] && mbstat.m_mtypes[i] != 0) {
+ k = snprintf(c, clen, "\t%u mbufs allocated to "
+ "<mbuf type %d>\n", mbstat.m_mtypes[i], i);
+ MBUF_DUMP_BUF_CHK();
+ }
+ if ((m_mbufs - totmbufs) > 0) {
+ k = snprintf(c, clen, "\t%lu mbufs allocated to caches\n",
+ m_mbufs - totmbufs);
+ MBUF_DUMP_BUF_CHK();
+ }
+ k = snprintf(c, clen, "%u/%u mbuf 2KB clusters in use\n"
+ "%u/%u mbuf 4KB clusters in use\n",
+ (unsigned int)(mbstat.m_clusters - m_clfree),
+ (unsigned int)mbstat.m_clusters,
+ (unsigned int)(mbstat.m_bigclusters - m_bigclfree),
+ (unsigned int)mbstat.m_bigclusters);
+ MBUF_DUMP_BUF_CHK();
+
+ if (njcl > 0) {
+ k = snprintf(c, clen, "%u/%u mbuf %uKB clusters in use\n",
+ m_16kclusters - m_16kclfree, m_16kclusters,
+ njclbytes / 1024);
+ MBUF_DUMP_BUF_CHK();
+ }
+ totused = totmem - totfree;
+ if (totmem == 0) {
+ totpct = 0;
+ } else if (totused < (ULONG_MAX / 100)) {
+ totpct = (totused * 100) / totmem;
+ } else {
+ u_long totmem1 = totmem / 100;
+ u_long totused1 = totused / 100;
+ totpct = (totused1 * 100) / totmem1;
+ }
+ k = snprintf(c, clen, "%lu KB allocated to network (approx. %lu%% "
+ "in use)\n", totmem / 1024, totpct);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "%lu KB returned to the system\n",
+ totreturned / 1024);
+ MBUF_DUMP_BUF_CHK();
+
+ net_update_uptime();
+ k = snprintf(c, clen,
+ "VM allocation failures: contiguous %u, normal %u, one page %u\n",
+ mb_kmem_contig_failed, mb_kmem_failed, mb_kmem_one_failed);
+ MBUF_DUMP_BUF_CHK();
+ if (mb_kmem_contig_failed_ts || mb_kmem_failed_ts ||
+ mb_kmem_one_failed_ts) {
+ k = snprintf(c, clen,
+ "VM allocation failure timestamps: contiguous %llu "
+ "(size %llu), normal %llu (size %llu), one page %llu "
+ "(now %llu)\n",
+ mb_kmem_contig_failed_ts, mb_kmem_contig_failed_size,
+ mb_kmem_failed_ts, mb_kmem_failed_size,
+ mb_kmem_one_failed_ts, net_uptime());
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen,
+ "VM return codes: ");
+ MBUF_DUMP_BUF_CHK();
+ for (i = 0;
+ i < sizeof(mb_kmem_stats) / sizeof(mb_kmem_stats[0]);
+ i++) {
+ k = snprintf(c, clen, "%s: %u ", mb_kmem_stats_labels[i],
+ mb_kmem_stats[i]);
+ MBUF_DUMP_BUF_CHK();
+ }
+ k = snprintf(c, clen, "\n");
+ MBUF_DUMP_BUF_CHK();
+ }
+ k = snprintf(c, clen,
+ "worker thread runs: %u, expansions: %llu, cl %llu/%llu, "
+ "bigcl %llu/%llu, 16k %llu/%llu\n", mbuf_worker_run_cnt,
+ mb_expand_cnt, mb_expand_cl_cnt, mb_expand_cl_total,
+ mb_expand_bigcl_cnt, mb_expand_bigcl_total, mb_expand_16kcl_cnt,
+ mb_expand_16kcl_total);
+ MBUF_DUMP_BUF_CHK();
+ if (mbuf_worker_last_runtime != 0) {
+ k = snprintf(c, clen, "worker thread last run time: "
+ "%llu (%llu seconds ago)\n",
+ mbuf_worker_last_runtime,
+ net_uptime() - mbuf_worker_last_runtime);
+ MBUF_DUMP_BUF_CHK();
+ }
+
+ /* mbuf leak detection statistics */
+ mleak_update_stats();
+
+ k = snprintf(c, clen, "\nmbuf leak detection table:\n");
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\ttotal captured: %u (one per %u)\n",
+ mleak_table.mleak_capture / mleak_table.mleak_sample_factor,
+ mleak_table.mleak_sample_factor);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\ttotal allocs outstanding: %llu\n",
+ mleak_table.outstanding_allocs);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\tnew hash recorded: %llu allocs, %llu traces\n",
+ mleak_table.alloc_recorded, mleak_table.trace_recorded);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\thash collisions: %llu allocs, %llu traces\n",
+ mleak_table.alloc_collisions, mleak_table.trace_collisions);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\toverwrites: %llu allocs, %llu traces\n",
+ mleak_table.alloc_overwrites, mleak_table.trace_overwrites);
+ MBUF_DUMP_BUF_CHK();
+ k = snprintf(c, clen, "\tlock conflicts: %llu\n\n",
+ mleak_table.total_conflicts);
+ MBUF_DUMP_BUF_CHK();
+
+ k = snprintf(c, clen, "top %d outstanding traces:\n",
+ mleak_stat->ml_cnt);
+ MBUF_DUMP_BUF_CHK();
+ for (i = 0; i < mleak_stat->ml_cnt; i++) {
+ mltr = &mleak_stat->ml_trace[i];
+ k = snprintf(c, clen, "[%d] %llu outstanding alloc(s), "
+ "%llu hit(s), %llu collision(s)\n", (i + 1),
+ mltr->mltr_allocs, mltr->mltr_hitcount,
+ mltr->mltr_collisions);
+ MBUF_DUMP_BUF_CHK();
+ }
+
+ if (mleak_stat->ml_isaddr64)
+ k = snprintf(c, clen, MB_LEAK_HDR_64);
+ else
+ k = snprintf(c, clen, MB_LEAK_HDR_32);
+ MBUF_DUMP_BUF_CHK();
+
+ for (i = 0; i < MLEAK_STACK_DEPTH; i++) {
+ int j;
+ k = snprintf(c, clen, "%2d: ", (i + 1));
+ MBUF_DUMP_BUF_CHK();
+ for (j = 0; j < mleak_stat->ml_cnt; j++) {
+ mltr = &mleak_stat->ml_trace[j];
+ if (i < mltr->mltr_depth) {
+ if (mleak_stat->ml_isaddr64) {
+ k = snprintf(c, clen, "0x%0llx ",
+ (uint64_t)VM_KERNEL_UNSLIDE(
+ mltr->mltr_addr[i]));
+ } else {
+ k = snprintf(c, clen,
+ "0x%08x ",
+ (uint32_t)VM_KERNEL_UNSLIDE(
+ mltr->mltr_addr[i]));
+ }
+ } else {
+ if (mleak_stat->ml_isaddr64)
+ k = snprintf(c, clen,
+ MB_LEAK_SPACING_64);
+ else
+ k = snprintf(c, clen,
+ MB_LEAK_SPACING_32);
+ }
+ MBUF_DUMP_BUF_CHK();