Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / netproto / ipsec / ipsec_mbuf.c
1 /*-
2  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/netipsec/ipsec_mbuf.c,v 1.5.2.2 2003/03/28 20:32:53 sam Exp $
27  */
28
29 /*
30  * IPsec-specific mbuf routines.
31  */
32
33 #include "opt_param.h"
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/mbuf.h>
38 #include <sys/socket.h>
39
40 #include <net/route.h>
41 #include <netinet/in.h>
42
43 #include <netipsec/ipsec.h>
44
45 extern  struct mbuf *m_getptr(struct mbuf *, int, int *);
46
47 /*
48  * Create a writable copy of the mbuf chain.  While doing this
49  * we compact the chain with a goal of producing a chain with
50  * at most two mbufs.  The second mbuf in this chain is likely
51  * to be a cluster.  The primary purpose of this work is to create
52  * a writable packet for encryption, compression, etc.  The
53  * secondary goal is to linearize the data so the data can be
54  * passed to crypto hardware in the most efficient manner possible.
55  */
56 struct mbuf *
57 m_clone(struct mbuf *m0)
58 {
59         struct mbuf *m, *mprev;
60         struct mbuf *n, *mfirst, *mlast;
61         int len, off;
62
63         KASSERT(m0 != NULL, ("m_clone: null mbuf"));
64
65         mprev = NULL;
66         for (m = m0; m != NULL; m = mprev->m_next) {
67                 /*
68                  * Regular mbufs are ignored unless there's a cluster
69                  * in front of it that we can use to coalesce.  We do
70                  * the latter mainly so later clusters can be coalesced
71                  * also w/o having to handle them specially (i.e. convert
72                  * mbuf+cluster -> cluster).  This optimization is heavily
73                  * influenced by the assumption that we're running over
74                  * Ethernet where MCLBYTES is large enough that the max
75                  * packet size will permit lots of coalescing into a
76                  * single cluster.  This in turn permits efficient
77                  * crypto operations, especially when using hardware.
78                  */
79                 if ((m->m_flags & M_EXT) == 0) {
80                         if (mprev && (mprev->m_flags & M_EXT) &&
81                             m->m_len <= M_TRAILINGSPACE(mprev)) {
82                                 /* XXX: this ignores mbuf types */
83                                 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
84                                        mtod(m, caddr_t), m->m_len);
85                                 mprev->m_len += m->m_len;
86                                 mprev->m_next = m->m_next;      /* unlink from chain */
87                                 m_free(m);                      /* reclaim mbuf */
88                                 newipsecstat.ips_mbcoalesced++;
89                         } else {
90                                 mprev = m;
91                         }
92                         continue;
93                 }
94                 /*
95                  * Writable mbufs are left alone (for now).  Note
96                  * that for 4.x systems it's not possible to identify
97                  * whether or not mbufs with external buffers are
98                  * writable unless they use clusters.
99                  */
100                 if (M_EXT_WRITABLE(m)) {
101                         mprev = m;
102                         continue;
103                 }
104
105                 /*
106                  * Not writable, replace with a copy or coalesce with
107                  * the previous mbuf if possible (since we have to copy
108                  * it anyway, we try to reduce the number of mbufs and
109                  * clusters so that future work is easier).
110                  */
111                 KASSERT(m->m_flags & M_EXT,
112                         ("m_clone: m_flags 0x%x", m->m_flags));
113                 /* NB: we only coalesce into a cluster or larger */
114                 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
115                     m->m_len <= M_TRAILINGSPACE(mprev)) {
116                         /* XXX: this ignores mbuf types */
117                         memcpy(mtod(mprev, caddr_t) + mprev->m_len,
118                                mtod(m, caddr_t), m->m_len);
119                         mprev->m_len += m->m_len;
120                         mprev->m_next = m->m_next;      /* unlink from chain */
121                         m_free(m);                      /* reclaim mbuf */
122                         newipsecstat.ips_clcoalesced++;
123                         continue;
124                 }
125
126                 /*
127                  * Allocate new space to hold the copy...
128                  */
129                 /* XXX why can M_PKTHDR be set past the first mbuf? */
130                 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
131                         /*
132                          * NB: if a packet header is present we must
133                          * allocate the mbuf separately from any cluster
134                          * because M_MOVE_PKTHDR will smash the data
135                          * pointer and drop the M_EXT marker.
136                          */
137                         MGETHDR(n, M_DONTWAIT, m->m_type);
138                         if (n == NULL) {
139                                 m_freem(m0);
140                                 return (NULL);
141                         }
142                         M_MOVE_PKTHDR(n, m);
143                         MCLGET(n, M_DONTWAIT);
144                         if ((n->m_flags & M_EXT) == 0) {
145                                 m_free(n);
146                                 m_freem(m0);
147                                 return (NULL);
148                         }
149                 } else {
150                         n = m_getcl(M_DONTWAIT, m->m_type, m->m_flags);
151                         if (n == NULL) {
152                                 m_freem(m0);
153                                 return (NULL);
154                         }
155                 }
156                 /*
157                  * ... and copy the data.  We deal with jumbo mbufs
158                  * (i.e. m_len > MCLBYTES) by splitting them into
159                  * clusters.  We could just malloc a buffer and make
160                  * it external but too many device drivers don't know
161                  * how to break up the non-contiguous memory when
162                  * doing DMA.
163                  */
164                 len = m->m_len;
165                 off = 0;
166                 mfirst = n;
167                 mlast = NULL;
168                 for (;;) {
169                         int cc = min(len, MCLBYTES);
170                         memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
171                         n->m_len = cc;
172                         if (mlast != NULL)
173                                 mlast->m_next = n;
174                         mlast = n;      
175                         newipsecstat.ips_clcopied++;
176
177                         len -= cc;
178                         if (len <= 0)
179                                 break;
180                         off += cc;
181
182                         n = m_getcl(M_DONTWAIT, m->m_type, m->m_flags);
183                         if (n == NULL) {
184                                 m_freem(mfirst);
185                                 m_freem(m0);
186                                 return (NULL);
187                         }
188                 }
189                 n->m_next = m->m_next; 
190                 if (mprev == NULL)
191                         m0 = mfirst;            /* new head of chain */
192                 else
193                         mprev->m_next = mfirst; /* replace old mbuf */
194                 m_free(m);                      /* release old mbuf */
195                 mprev = mfirst;
196         }
197         return (m0);
198 }
199
200 /*
201  * Make space for a new header of length hlen at skip bytes
202  * into the packet.  When doing this we allocate new mbufs only
203  * when absolutely necessary.  The mbuf where the new header
204  * is to go is returned together with an offset into the mbuf.
205  * If NULL is returned then the mbuf chain may have been modified;
206  * the caller is assumed to always free the chain.
207  */
208 struct mbuf *
209 m_makespace(struct mbuf *m0, int skip, int hlen, int *off)
210 {
211         struct mbuf *m;
212         unsigned remain;
213
214         KASSERT(m0 != NULL, ("m_dmakespace: null mbuf"));
215         KASSERT(hlen < MHLEN, ("m_makespace: hlen too big: %u", hlen));
216
217         for (m = m0; m && skip > m->m_len; m = m->m_next)
218                 skip -= m->m_len;
219         if (m == NULL)
220                 return (NULL);
221         /*
222          * At this point skip is the offset into the mbuf m
223          * where the new header should be placed.  Figure out
224          * if there's space to insert the new header.  If so,
225          * and copying the remainder makese sense then do so.
226          * Otherwise insert a new mbuf in the chain, splitting
227          * the contents of m as needed.
228          */
229         remain = m->m_len - skip;               /* data to move */
230         if (hlen > M_TRAILINGSPACE(m)) {
231                 struct mbuf *n;
232
233                 /* XXX code doesn't handle clusters XXX */
234                 KASSERT(remain < MLEN,
235                         ("m_makespace: remainder too big: %u", remain));
236                 /*
237                  * Not enough space in m, split the contents
238                  * of m, inserting new mbufs as required.
239                  *
240                  * NB: this ignores mbuf types.
241                  */
242                 MGET(n, M_DONTWAIT, MT_DATA);
243                 if (n == NULL)
244                         return (NULL);
245                 n->m_next = m->m_next;          /* splice new mbuf */
246                 m->m_next = n;
247                 newipsecstat.ips_mbinserted++;
248                 if (hlen <= M_TRAILINGSPACE(m) + remain) {
249                         /*
250                          * New header fits in the old mbuf if we copy
251                          * the remainder; just do the copy to the new
252                          * mbuf and we're good to go.
253                          */
254                         memcpy(mtod(n, caddr_t),
255                                mtod(m, caddr_t) + skip, remain);
256                         n->m_len = remain;
257                         m->m_len = skip + hlen;
258                         *off = skip;
259                 } else {
260                         /*
261                          * No space in the old mbuf for the new header.
262                          * Make space in the new mbuf and check the
263                          * remainder'd data fits too.  If not then we
264                          * must allocate an additional mbuf (yech).
265                          */
266                         n->m_len = 0;
267                         if (remain + hlen > M_TRAILINGSPACE(n)) {
268                                 struct mbuf *n2;
269
270                                 MGET(n2, M_DONTWAIT, MT_DATA);
271                                 /* NB: new mbuf is on chain, let caller free */
272                                 if (n2 == NULL)
273                                         return (NULL);
274                                 n2->m_len = 0;
275                                 memcpy(mtod(n2, caddr_t),
276                                        mtod(m, caddr_t) + skip, remain);
277                                 n2->m_len = remain;
278                                 /* splice in second mbuf */
279                                 n2->m_next = n->m_next;
280                                 n->m_next = n2;
281                                 newipsecstat.ips_mbinserted++;
282                         } else {
283                                 memcpy(mtod(n, caddr_t) + hlen,
284                                        mtod(m, caddr_t) + skip, remain);
285                                 n->m_len += remain;
286                         }
287                         m->m_len -= remain;
288                         n->m_len += hlen;
289                         m = n;                  /* header is at front ... */
290                         *off = 0;               /* ... of new mbuf */
291                 }
292         } else {
293                 /*
294                  * Copy the remainder to the back of the mbuf
295                  * so there's space to write the new header.
296                  */
297                 /* XXX can this be memcpy? does it handle overlap? */
298                 ovbcopy(mtod(m, caddr_t) + skip,
299                         mtod(m, caddr_t) + skip + hlen, remain);
300                 m->m_len += hlen;
301                 *off = skip;
302         }
303         m0->m_pkthdr.len += hlen;               /* adjust packet length */
304         return m;
305 }
306
307 /*
308  * m_pad(m, n) pads <m> with <n> bytes at the end. The packet header
309  * length is updated, and a pointer to the first byte of the padding
310  * (which is guaranteed to be all in one mbuf) is returned.
311  */
312 caddr_t
313 m_pad(struct mbuf *m, int n)
314 {
315         register struct mbuf *m0, *m1;
316         register int len, pad;
317         caddr_t retval;
318
319         if (n <= 0) {  /* No stupid arguments. */
320                 DPRINTF(("m_pad: pad length invalid (%d)\n", n));
321                 m_freem(m);
322                 return NULL;
323         }
324
325         len = m->m_pkthdr.len;
326         pad = n;
327         m0 = m;
328
329         while (m0->m_len < len) {
330 KASSERT(m0->m_next != NULL, ("m_pad: m0 null, len %u m_len %u", len, m0->m_len));/*XXX*/
331                 len -= m0->m_len;
332                 m0 = m0->m_next;
333         }
334
335         if (m0->m_len != len) {
336                 DPRINTF(("m_pad: length mismatch (should be %d instead of %d)\n",
337                     m->m_pkthdr.len, m->m_pkthdr.len + m0->m_len - len));
338
339                 m_freem(m);
340                 return NULL;
341         }
342
343         /* Check for zero-length trailing mbufs, and find the last one. */
344         for (m1 = m0; m1->m_next; m1 = m1->m_next) {
345                 if (m1->m_next->m_len != 0) {
346                         DPRINTF(("m_pad: length mismatch (should be %d "
347                             "instead of %d)\n",
348                             m->m_pkthdr.len,
349                             m->m_pkthdr.len + m1->m_next->m_len));
350
351                         m_freem(m);
352                         return NULL;
353                 }
354
355                 m0 = m1->m_next;
356         }
357
358         if (pad > M_TRAILINGSPACE(m0)) {
359                 /* Add an mbuf to the chain. */
360                 MGET(m1, M_DONTWAIT, MT_DATA);
361                 if (m1 == 0) {
362                         m_freem(m0);
363                         DPRINTF(("m_pad: unable to get extra mbuf\n"));
364                         return NULL;
365                 }
366
367                 m0->m_next = m1;
368                 m0 = m1;
369                 m0->m_len = 0;
370         }
371
372         retval = m0->m_data + m0->m_len;
373         m0->m_len += pad;
374         m->m_pkthdr.len += pad;
375
376         return retval;
377 }
378
379 /*
380  * Remove hlen data at offset skip in the packet.  This is used by
381  * the protocols strip protocol headers and associated data (e.g. IV,
382  * authenticator) on input.
383  */
384 int
385 m_striphdr(struct mbuf *m, int skip, int hlen)
386 {
387         struct mbuf *m1;
388         int roff;
389
390         /* Find beginning of header */
391         m1 = m_getptr(m, skip, &roff);
392         if (m1 == NULL)
393                 return (EINVAL);
394
395         /* Remove the header and associated data from the mbuf. */
396         if (roff == 0) {
397                 /* The header was at the beginning of the mbuf */
398                 newipsecstat.ips_input_front++;
399                 m_adj(m1, hlen);
400                 if ((m1->m_flags & M_PKTHDR) == 0)
401                         m->m_pkthdr.len -= hlen;
402         } else if (roff + hlen >= m1->m_len) {
403                 struct mbuf *mo;
404
405                 /*
406                  * Part or all of the header is at the end of this mbuf,
407                  * so first let's remove the remainder of the header from
408                  * the beginning of the remainder of the mbuf chain, if any.
409                  */
410                 newipsecstat.ips_input_end++;
411                 if (roff + hlen > m1->m_len) {
412                         /* Adjust the next mbuf by the remainder */
413                         m_adj(m1->m_next, roff + hlen - m1->m_len);
414
415                         /* The second mbuf is guaranteed not to have a pkthdr... */
416                         m->m_pkthdr.len -= (roff + hlen - m1->m_len);
417                 }
418
419                 /* Now, let's unlink the mbuf chain for a second...*/
420                 mo = m1->m_next;
421                 m1->m_next = NULL;
422
423                 /* ...and trim the end of the first part of the chain...sick */
424                 m_adj(m1, -(m1->m_len - roff));
425                 if ((m1->m_flags & M_PKTHDR) == 0)
426                         m->m_pkthdr.len -= (m1->m_len - roff);
427
428                 /* Finally, let's relink */
429                 m1->m_next = mo;
430         } else {
431                 /*
432                  * The header lies in the "middle" of the mbuf; copy
433                  * the remainder of the mbuf down over the header.
434                  */
435                 newipsecstat.ips_input_middle++;
436                 bcopy(mtod(m1, u_char *) + roff + hlen,
437                       mtod(m1, u_char *) + roff,
438                       m1->m_len - (roff + hlen));
439                 m1->m_len -= hlen;
440                 m->m_pkthdr.len -= hlen;
441         }
442         return (0);
443 }
444
445 /*
446  * Diagnostic routine to check mbuf alignment as required by the
447  * crypto device drivers (that use DMA).
448  */
449 void
450 m_checkalignment(const char* where, struct mbuf *m0, int off, int len)
451 {
452         int roff;
453         struct mbuf *m = m_getptr(m0, off, &roff);
454         caddr_t addr;
455
456         if (m == NULL)
457                 return;
458         printf("%s (off %u len %u): ", where, off, len);
459         addr = mtod(m, caddr_t) + roff;
460         do {
461                 int mlen;
462
463                 if (((uintptr_t) addr) & 3) {
464                         printf("addr misaligned %p,", addr);
465                         break;
466                 }
467                 mlen = m->m_len;
468                 if (mlen > len)
469                         mlen = len;
470                 len -= mlen;
471                 if (len && (mlen & 3)) {
472                         printf("len mismatch %u,", mlen);
473                         break;
474                 }
475                 m = m->m_next;
476                 addr = m ? mtod(m, caddr_t) : NULL;
477         } while (m && len > 0);
478         for (m = m0; m; m = m->m_next)
479                 printf(" [%p:%u]", mtod(m, caddr_t), m->m_len);
480         printf("\n");
481 }