]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - sys/dev/netmap/netmap_mem1.c
MFC: r238933
[FreeBSD/releng/9.1.git] / sys / dev / netmap / netmap_mem1.c
1 /*
2  * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *   1. Redistributions of source code must retain the above copyright
8  *      notice, this list of conditions and the following disclaimer.
9  *   2. Redistributions in binary form must reproduce the above copyright
10  *      notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25
26 /*
27  * $FreeBSD$
28  *
29  * The original netmap memory allocator, using a single large
30  * chunk of memory allocated with contigmalloc.
31  */
32
33 /*
34  * Default amount of memory pre-allocated by the module.
35  * We start with a large size and then shrink our demand
36  * according to what is avalable when the module is loaded.
37  */
38 #define NETMAP_MEMORY_SIZE (64 * 1024 * PAGE_SIZE)
39 static void * netmap_malloc(size_t size, const char *msg);
40 static void netmap_free(void *addr, const char *msg);
41
42 #define netmap_if_malloc(len)   netmap_malloc(len, "nifp")
43 #define netmap_if_free(v)       netmap_free((v), "nifp")
44
45 #define netmap_ring_malloc(len) netmap_malloc(len, "ring")
46 #define netmap_free_rings(na)           \
47         netmap_free((na)->tx_rings[0].ring, "shadow rings");
48
49 /*
50  * Allocator for a pool of packet buffers. For each buffer we have
51  * one entry in the bitmap to signal the state. Allocation scans
52  * the bitmap, but since this is done only on attach, we are not
53  * too worried about performance
54  * XXX if we need to allocate small blocks, a translation
55  * table is used both for kernel virtual address and physical
56  * addresses.
57  */
58 struct netmap_buf_pool {
59         u_int total_buffers;    /* total buffers. */
60         u_int free;
61         u_int bufsize;
62         char *base;             /* buffer base address */
63         uint32_t *bitmap;       /* one bit per buffer, 1 means free */
64 };
65 struct netmap_buf_pool nm_buf_pool;
66 SYSCTL_INT(_dev_netmap, OID_AUTO, total_buffers,
67     CTLFLAG_RD, &nm_buf_pool.total_buffers, 0, "total_buffers");
68 SYSCTL_INT(_dev_netmap, OID_AUTO, free_buffers,
69     CTLFLAG_RD, &nm_buf_pool.free, 0, "free_buffers");
70
71
72 /*
73  * Allocate n buffers from the ring, and fill the slot.
74  * Buffer 0 is the 'junk' buffer.
75  */
76 static void
77 netmap_new_bufs(struct netmap_if *nifp __unused,
78                 struct netmap_slot *slot, u_int n)
79 {
80         struct netmap_buf_pool *p = &nm_buf_pool;
81         uint32_t bi = 0;                /* index in the bitmap */
82         uint32_t mask, j, i = 0;        /* slot counter */
83
84         if (n > p->free) {
85                 D("only %d out of %d buffers available", i, n);
86                 return;
87         }
88         /* termination is guaranteed by p->free */
89         while (i < n && p->free > 0) {
90                 uint32_t cur = p->bitmap[bi];
91                 if (cur == 0) { /* bitmask is fully used */
92                         bi++;
93                         continue;
94                 }
95                 /* locate a slot */
96                 for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ;
97                 p->bitmap[bi] &= ~mask;         /* slot in use */
98                 p->free--;
99                 slot[i].buf_idx = bi*32+j;
100                 slot[i].len = p->bufsize;
101                 slot[i].flags = NS_BUF_CHANGED;
102                 i++;
103         }
104         ND("allocated %d buffers, %d available", n, p->free);
105 }
106
107
108 static void
109 netmap_free_buf(struct netmap_if *nifp __unused, uint32_t i)
110 {
111         struct netmap_buf_pool *p = &nm_buf_pool;
112
113         uint32_t pos, mask;
114         if (i >= p->total_buffers) {
115                 D("invalid free index %d", i);
116                 return;
117         }
118         pos = i / 32;
119         mask = 1 << (i % 32);
120         if (p->bitmap[pos] & mask) {
121                 D("slot %d already free", i);
122                 return;
123         }
124         p->bitmap[pos] |= mask;
125         p->free++;
126 }
127
128
129 /* Descriptor of the memory objects handled by our memory allocator. */
130 struct netmap_mem_obj {
131         TAILQ_ENTRY(netmap_mem_obj) nmo_next; /* next object in the
132                                                  chain. */
133         int nmo_used; /* flag set on used memory objects. */
134         size_t nmo_size; /* size of the memory area reserved for the
135                             object. */
136         void *nmo_data; /* pointer to the memory area. */
137 };
138
139 /* Wrap our memory objects to make them ``chainable``. */
140 TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj);
141
142
143 /* Descriptor of our custom memory allocator. */
144 struct netmap_mem_d {
145         struct mtx nm_mtx; /* lock used to handle the chain of memory
146                               objects. */
147         struct netmap_mem_obj_h nm_molist; /* list of memory objects */
148         size_t nm_size; /* total amount of memory used for rings etc. */
149         size_t nm_totalsize; /* total amount of allocated memory
150                 (the difference is used for buffers) */
151         size_t nm_buf_start; /* offset of packet buffers.
152                         This is page-aligned. */
153         size_t nm_buf_len; /* total memory for buffers */
154         void *nm_buffer; /* pointer to the whole pre-allocated memory
155                             area. */
156 };
157
158 /* Shorthand to compute a netmap interface offset. */
159 #define netmap_if_offset(v)                                     \
160     ((char *) (v) - (char *) nm_mem->nm_buffer)
161 /* .. and get a physical address given a memory offset */
162 #define netmap_ofstophys(o)                                     \
163     (vtophys(nm_mem->nm_buffer) + (o))
164
165
166 /*------ netmap memory allocator -------*/
167 /*
168  * Request for a chunk of memory.
169  *
170  * Memory objects are arranged into a list, hence we need to walk this
171  * list until we find an object with the needed amount of data free.
172  * This sounds like a completely inefficient implementation, but given
173  * the fact that data allocation is done once, we can handle it
174  * flawlessly.
175  *
176  * Return NULL on failure.
177  */
178 static void *
179 netmap_malloc(size_t size, __unused const char *msg)
180 {
181         struct netmap_mem_obj *mem_obj, *new_mem_obj;
182         void *ret = NULL;
183
184         NMA_LOCK();
185         TAILQ_FOREACH(mem_obj, &nm_mem->nm_molist, nmo_next) {
186                 if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size)
187                         continue;
188
189                 new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
190                                      M_WAITOK | M_ZERO);
191                 TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next);
192
193                 new_mem_obj->nmo_used = 1;
194                 new_mem_obj->nmo_size = size;
195                 new_mem_obj->nmo_data = mem_obj->nmo_data;
196                 memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size);
197
198                 mem_obj->nmo_size -= size;
199                 mem_obj->nmo_data = (char *) mem_obj->nmo_data + size;
200                 if (mem_obj->nmo_size == 0) {
201                         TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj,
202                                      nmo_next);
203                         free(mem_obj, M_NETMAP);
204                 }
205
206                 ret = new_mem_obj->nmo_data;
207
208                 break;
209         }
210         NMA_UNLOCK();
211         ND("%s: %d bytes at %p", msg, size, ret);
212
213         return (ret);
214 }
215
216 /*
217  * Return the memory to the allocator.
218  *
219  * While freeing a memory object, we try to merge adjacent chunks in
220  * order to reduce memory fragmentation.
221  */
222 static void
223 netmap_free(void *addr, const char *msg)
224 {
225         size_t size;
226         struct netmap_mem_obj *cur, *prev, *next;
227
228         if (addr == NULL) {
229                 D("NULL addr for %s", msg);
230                 return;
231         }
232
233         NMA_LOCK();
234         TAILQ_FOREACH(cur, &nm_mem->nm_molist, nmo_next) {
235                 if (cur->nmo_data == addr && cur->nmo_used)
236                         break;
237         }
238         if (cur == NULL) {
239                 NMA_UNLOCK();
240                 D("invalid addr %s %p", msg, addr);
241                 return;
242         }
243
244         size = cur->nmo_size;
245         cur->nmo_used = 0;
246
247         /* merge current chunk of memory with the previous one,
248            if present. */
249         prev = TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next);
250         if (prev && prev->nmo_used == 0) {
251                 TAILQ_REMOVE(&nm_mem->nm_molist, cur, nmo_next);
252                 prev->nmo_size += cur->nmo_size;
253                 free(cur, M_NETMAP);
254                 cur = prev;
255         }
256
257         /* merge with the next one */
258         next = TAILQ_NEXT(cur, nmo_next);
259         if (next && next->nmo_used == 0) {
260                 TAILQ_REMOVE(&nm_mem->nm_molist, next, nmo_next);
261                 cur->nmo_size += next->nmo_size;
262                 free(next, M_NETMAP);
263         }
264         NMA_UNLOCK();
265         ND("freed %s %d bytes at %p", msg, size, addr);
266 }
267
268
269 /*
270  * Create and return a new ``netmap_if`` object, and possibly also
271  * rings and packet buffors.
272  *
273  * Return NULL on failure.
274  */
275 static void *
276 netmap_if_new(const char *ifname, struct netmap_adapter *na)
277 {
278         struct netmap_if *nifp;
279         struct netmap_ring *ring;
280         struct netmap_kring *kring;
281         char *buff;
282         u_int i, len, ofs, numdesc;
283         u_int nrx = na->num_rx_rings + 1; /* shorthand, include stack queue */
284         u_int ntx = na->num_tx_rings + 1; /* shorthand, include stack queue */
285
286         /*
287          * the descriptor is followed inline by an array of offsets
288          * to the tx and rx rings in the shared memory region.
289          */
290         len = sizeof(struct netmap_if) + (nrx + ntx) * sizeof(ssize_t);
291         nifp = netmap_if_malloc(len);
292         if (nifp == NULL)
293                 return (NULL);
294
295         /* initialize base fields */
296         *(int *)(uintptr_t)&nifp->ni_rx_rings = na->num_rx_rings;
297         *(int *)(uintptr_t)&nifp->ni_tx_rings = na->num_tx_rings;
298         strncpy(nifp->ni_name, ifname, IFNAMSIZ);
299
300         (na->refcount)++;       /* XXX atomic ? we are under lock */
301         if (na->refcount > 1)
302                 goto final;
303
304         /*
305          * First instance. Allocate the netmap rings
306          * (one for each hw queue, one pair for the host).
307          * The rings are contiguous, but have variable size.
308          * The entire block is reachable at
309          *      na->tx_rings[0]
310          */
311         len = (ntx + nrx) * sizeof(struct netmap_ring) +
312               (ntx * na->num_tx_desc + nrx * na->num_rx_desc) *
313                    sizeof(struct netmap_slot);
314         buff = netmap_ring_malloc(len);
315         if (buff == NULL) {
316                 D("failed to allocate %d bytes for %s shadow ring",
317                         len, ifname);
318 error:
319                 (na->refcount)--;
320                 netmap_if_free(nifp);
321                 return (NULL);
322         }
323         /* Check whether we have enough buffers */
324         len = ntx * na->num_tx_desc + nrx * na->num_rx_desc;
325         NMA_LOCK();
326         if (nm_buf_pool.free < len) {
327                 NMA_UNLOCK();
328                 netmap_free(buff, "not enough bufs");
329                 goto error;
330         }
331         /*
332          * in the kring, store the pointers to the shared rings
333          * and initialize the rings. We are under NMA_LOCK().
334          */
335         ofs = 0;
336         for (i = 0; i < ntx; i++) { /* Transmit rings */
337                 kring = &na->tx_rings[i];
338                 numdesc = na->num_tx_desc;
339                 bzero(kring, sizeof(*kring));
340                 kring->na = na;
341
342                 ring = kring->ring = (struct netmap_ring *)(buff + ofs);
343                 *(ssize_t *)(uintptr_t)&ring->buf_ofs =
344                         nm_buf_pool.base - (char *)ring;
345                 ND("txring[%d] at %p ofs %d", i, ring, ring->buf_ofs);
346                 *(uint32_t *)(uintptr_t)&ring->num_slots =
347                         kring->nkr_num_slots = numdesc;
348
349                 /*
350                  * IMPORTANT:
351                  * Always keep one slot empty, so we can detect new
352                  * transmissions comparing cur and nr_hwcur (they are
353                  * the same only if there are no new transmissions).
354                  */
355                 ring->avail = kring->nr_hwavail = numdesc - 1;
356                 ring->cur = kring->nr_hwcur = 0;
357                 *(uint16_t *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE;
358                 netmap_new_bufs(nifp, ring->slot, numdesc);
359
360                 ofs += sizeof(struct netmap_ring) +
361                         numdesc * sizeof(struct netmap_slot);
362         }
363
364         for (i = 0; i < nrx; i++) { /* Receive rings */
365                 kring = &na->rx_rings[i];
366                 numdesc = na->num_rx_desc;
367                 bzero(kring, sizeof(*kring));
368                 kring->na = na;
369
370                 ring = kring->ring = (struct netmap_ring *)(buff + ofs);
371                 *(ssize_t *)(uintptr_t)&ring->buf_ofs =
372                         nm_buf_pool.base - (char *)ring;
373                 ND("rxring[%d] at %p offset %d", i, ring, ring->buf_ofs);
374                 *(uint32_t *)(uintptr_t)&ring->num_slots =
375                         kring->nkr_num_slots = numdesc;
376                 ring->cur = kring->nr_hwcur = 0;
377                 ring->avail = kring->nr_hwavail = 0; /* empty */
378                 *(uint16_t *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE;
379                 netmap_new_bufs(nifp, ring->slot, numdesc);
380                 ofs += sizeof(struct netmap_ring) +
381                         numdesc * sizeof(struct netmap_slot);
382         }
383         NMA_UNLOCK();
384         // XXX initialize the selrecord structs.
385
386 final:
387         /*
388          * fill the slots for the rx and tx queues. They contain the offset
389          * between the ring and nifp, so the information is usable in
390          * userspace to reach the ring from the nifp.
391          */
392         for (i = 0; i < ntx; i++) {
393                 *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] =
394                         (char *)na->tx_rings[i].ring - (char *)nifp;
395         }
396         for (i = 0; i < nrx; i++) {
397                 *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+ntx] =
398                         (char *)na->rx_rings[i].ring - (char *)nifp;
399         }
400         return (nifp);
401 }
402
403 /*
404  * Initialize the memory allocator.
405  *
406  * Create the descriptor for the memory , allocate the pool of memory
407  * and initialize the list of memory objects with a single chunk
408  * containing the whole pre-allocated memory marked as free.
409  *
410  * Start with a large size, then halve as needed if we fail to
411  * allocate the block. While halving, always add one extra page
412  * because buffers 0 and 1 are used for special purposes.
413  * Return 0 on success, errno otherwise.
414  */
415 static int
416 netmap_memory_init(void)
417 {
418         struct netmap_mem_obj *mem_obj;
419         void *buf = NULL;
420         int i, n, sz = NETMAP_MEMORY_SIZE;
421         int extra_sz = 0; // space for rings and two spare buffers
422
423         for (; sz >= 1<<20; sz >>=1) {
424                 extra_sz = sz/200;
425                 extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
426                 buf = contigmalloc(sz + extra_sz,
427                              M_NETMAP,
428                              M_WAITOK | M_ZERO,
429                              0, /* low address */
430                              -1UL, /* high address */
431                              PAGE_SIZE, /* alignment */
432                              0 /* boundary */
433                             );
434                 if (buf)
435                         break;
436         }
437         if (buf == NULL)
438                 return (ENOMEM);
439         sz += extra_sz;
440         nm_mem = malloc(sizeof(struct netmap_mem_d), M_NETMAP,
441                               M_WAITOK | M_ZERO);
442         mtx_init(&nm_mem->nm_mtx, "netmap memory allocator lock", NULL,
443                  MTX_DEF);
444         TAILQ_INIT(&nm_mem->nm_molist);
445         nm_mem->nm_buffer = buf;
446         nm_mem->nm_totalsize = sz;
447
448         /*
449          * A buffer takes 2k, a slot takes 8 bytes + ring overhead,
450          * so the ratio is 200:1. In other words, we can use 1/200 of
451          * the memory for the rings, and the rest for the buffers,
452          * and be sure we never run out.
453          */
454         nm_mem->nm_size = sz/200;
455         nm_mem->nm_buf_start =
456                 (nm_mem->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
457         nm_mem->nm_buf_len = sz - nm_mem->nm_buf_start;
458
459         nm_buf_pool.base = nm_mem->nm_buffer;
460         nm_buf_pool.base += nm_mem->nm_buf_start;
461         netmap_buffer_base = nm_buf_pool.base;
462         D("netmap_buffer_base %p (offset %d)",
463                 netmap_buffer_base, (int)nm_mem->nm_buf_start);
464         /* number of buffers, they all start as free */
465
466         netmap_total_buffers = nm_buf_pool.total_buffers =
467                 nm_mem->nm_buf_len / NETMAP_BUF_SIZE;
468         nm_buf_pool.bufsize = NETMAP_BUF_SIZE;
469
470         D("Have %d MB, use %dKB for rings, %d buffers at %p",
471                 (sz >> 20), (int)(nm_mem->nm_size >> 10),
472                 nm_buf_pool.total_buffers, nm_buf_pool.base);
473
474         /* allocate and initialize the bitmap. Entry 0 is considered
475          * always busy (used as default when there are no buffers left).
476          */
477         n = (nm_buf_pool.total_buffers + 31) / 32;
478         nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP,
479                          M_WAITOK | M_ZERO);
480         nm_buf_pool.bitmap[0] = ~3; /* slot 0 and 1 always busy */
481         for (i = 1; i < n; i++)
482                 nm_buf_pool.bitmap[i] = ~0;
483         nm_buf_pool.free = nm_buf_pool.total_buffers - 2;
484         
485         mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
486                          M_WAITOK | M_ZERO);
487         TAILQ_INSERT_HEAD(&nm_mem->nm_molist, mem_obj, nmo_next);
488         mem_obj->nmo_used = 0;
489         mem_obj->nmo_size = nm_mem->nm_size;
490         mem_obj->nmo_data = nm_mem->nm_buffer;
491
492         return (0);
493 }
494
495
496 /*
497  * Finalize the memory allocator.
498  *
499  * Free all the memory objects contained inside the list, and deallocate
500  * the pool of memory; finally free the memory allocator descriptor.
501  */
502 static void
503 netmap_memory_fini(void)
504 {
505         struct netmap_mem_obj *mem_obj;
506
507         while (!TAILQ_EMPTY(&nm_mem->nm_molist)) {
508                 mem_obj = TAILQ_FIRST(&nm_mem->nm_molist);
509                 TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj, nmo_next);
510                 if (mem_obj->nmo_used == 1) {
511                         printf("netmap: leaked %d bytes at %p\n",
512                                (int)mem_obj->nmo_size,
513                                mem_obj->nmo_data);
514                 }
515                 free(mem_obj, M_NETMAP);
516         }
517         contigfree(nm_mem->nm_buffer, nm_mem->nm_totalsize, M_NETMAP);
518         // XXX mutex_destroy(nm_mtx);
519         free(nm_mem, M_NETMAP);
520 }
521 /*------------- end of memory allocator -----------------*/