2 * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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
29 * The original netmap memory allocator, using a single large
30 * chunk of memory allocated with contigmalloc.
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.
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);
42 #define netmap_if_malloc(len) netmap_malloc(len, "nifp")
43 #define netmap_if_free(v) netmap_free((v), "nifp")
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");
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
58 struct netmap_buf_pool {
59 u_int total_buffers; /* total buffers. */
62 char *base; /* buffer base address */
63 uint32_t *bitmap; /* one bit per buffer, 1 means free */
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");
73 * Allocate n buffers from the ring, and fill the slot.
74 * Buffer 0 is the 'junk' buffer.
77 netmap_new_bufs(struct netmap_if *nifp __unused,
78 struct netmap_slot *slot, u_int n)
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 */
85 D("only %d out of %d buffers available", i, n);
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 */
96 for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ;
97 p->bitmap[bi] &= ~mask; /* slot in use */
99 slot[i].buf_idx = bi*32+j;
100 slot[i].len = p->bufsize;
101 slot[i].flags = NS_BUF_CHANGED;
104 ND("allocated %d buffers, %d available", n, p->free);
109 netmap_free_buf(struct netmap_if *nifp __unused, uint32_t i)
111 struct netmap_buf_pool *p = &nm_buf_pool;
114 if (i >= p->total_buffers) {
115 D("invalid free index %d", i);
119 mask = 1 << (i % 32);
120 if (p->bitmap[pos] & mask) {
121 D("slot %d already free", i);
124 p->bitmap[pos] |= mask;
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
133 int nmo_used; /* flag set on used memory objects. */
134 size_t nmo_size; /* size of the memory area reserved for the
136 void *nmo_data; /* pointer to the memory area. */
139 /* Wrap our memory objects to make them ``chainable``. */
140 TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj);
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
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
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))
166 /*------ netmap memory allocator -------*/
168 * Request for a chunk of memory.
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
176 * Return NULL on failure.
179 netmap_malloc(size_t size, __unused const char *msg)
181 struct netmap_mem_obj *mem_obj, *new_mem_obj;
185 TAILQ_FOREACH(mem_obj, &nm_mem->nm_molist, nmo_next) {
186 if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size)
189 new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
191 TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next);
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);
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,
203 free(mem_obj, M_NETMAP);
206 ret = new_mem_obj->nmo_data;
211 ND("%s: %d bytes at %p", msg, size, ret);
217 * Return the memory to the allocator.
219 * While freeing a memory object, we try to merge adjacent chunks in
220 * order to reduce memory fragmentation.
223 netmap_free(void *addr, const char *msg)
226 struct netmap_mem_obj *cur, *prev, *next;
229 D("NULL addr for %s", msg);
234 TAILQ_FOREACH(cur, &nm_mem->nm_molist, nmo_next) {
235 if (cur->nmo_data == addr && cur->nmo_used)
240 D("invalid addr %s %p", msg, addr);
244 size = cur->nmo_size;
247 /* merge current chunk of memory with the previous one,
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;
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);
265 ND("freed %s %d bytes at %p", msg, size, addr);
270 * Create and return a new ``netmap_if`` object, and possibly also
271 * rings and packet buffors.
273 * Return NULL on failure.
276 netmap_if_new(const char *ifname, struct netmap_adapter *na)
278 struct netmap_if *nifp;
279 struct netmap_ring *ring;
280 struct netmap_kring *kring;
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 */
287 * the descriptor is followed inline by an array of offsets
288 * to the tx and rx rings in the shared memory region.
290 len = sizeof(struct netmap_if) + (nrx + ntx) * sizeof(ssize_t);
291 nifp = netmap_if_malloc(len);
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);
300 (na->refcount)++; /* XXX atomic ? we are under lock */
301 if (na->refcount > 1)
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
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);
316 D("failed to allocate %d bytes for %s shadow ring",
320 netmap_if_free(nifp);
323 /* Check whether we have enough buffers */
324 len = ntx * na->num_tx_desc + nrx * na->num_rx_desc;
326 if (nm_buf_pool.free < len) {
328 netmap_free(buff, "not enough bufs");
332 * in the kring, store the pointers to the shared rings
333 * and initialize the rings. We are under NMA_LOCK().
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));
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;
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).
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);
360 ofs += sizeof(struct netmap_ring) +
361 numdesc * sizeof(struct netmap_slot);
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));
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);
384 // XXX initialize the selrecord structs.
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.
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;
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;
404 * Initialize the memory allocator.
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.
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.
416 netmap_memory_init(void)
418 struct netmap_mem_obj *mem_obj;
420 int i, n, sz = NETMAP_MEMORY_SIZE;
421 int extra_sz = 0; // space for rings and two spare buffers
423 for (; sz >= 1<<20; sz >>=1) {
425 extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
426 buf = contigmalloc(sz + extra_sz,
430 -1UL, /* high address */
431 PAGE_SIZE, /* alignment */
440 nm_mem = malloc(sizeof(struct netmap_mem_d), M_NETMAP,
442 mtx_init(&nm_mem->nm_mtx, "netmap memory allocator lock", NULL,
444 TAILQ_INIT(&nm_mem->nm_molist);
445 nm_mem->nm_buffer = buf;
446 nm_mem->nm_totalsize = sz;
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.
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;
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 */
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;
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);
474 /* allocate and initialize the bitmap. Entry 0 is considered
475 * always busy (used as default when there are no buffers left).
477 n = (nm_buf_pool.total_buffers + 31) / 32;
478 nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP,
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;
485 mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
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;
497 * Finalize the memory allocator.
499 * Free all the memory objects contained inside the list, and deallocate
500 * the pool of memory; finally free the memory allocator descriptor.
503 netmap_memory_fini(void)
505 struct netmap_mem_obj *mem_obj;
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,
515 free(mem_obj, M_NETMAP);
517 contigfree(nm_mem->nm_buffer, nm_mem->nm_totalsize, M_NETMAP);
518 // XXX mutex_destroy(nm_mtx);
519 free(nm_mem, M_NETMAP);
521 /*------------- end of memory allocator -----------------*/