xref: /freebsd-13-stable/sys/dev/netmap/netmap_mem2.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2012-2014 Matteo Landi
5  * Copyright (C) 2012-2016 Luigi Rizzo
6  * Copyright (C) 2012-2016 Giuseppe Lettieri
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *   1. Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *   2. Redistributions in binary form must reproduce the above copyright
15  *      notice, this list of conditions and the following disclaimer in the
16  *      documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #ifdef linux
32 #include "bsd_glue.h"
33 #endif /* linux */
34 
35 #ifdef __APPLE__
36 #include "osx_glue.h"
37 #endif /* __APPLE__ */
38 
39 #ifdef __FreeBSD__
40 #include <sys/cdefs.h> /* prerequisite */
41 #include <sys/types.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>		/* MALLOC_DEFINE */
44 #include <sys/proc.h>
45 #include <vm/vm.h>	/* vtophys */
46 #include <vm/pmap.h>	/* vtophys */
47 #include <sys/socket.h> /* sockaddrs */
48 #include <sys/selinfo.h>
49 #include <sys/sysctl.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/vnet.h>
53 #include <machine/bus.h>	/* bus_dmamap_* */
54 
55 /* M_NETMAP only used in here */
56 MALLOC_DECLARE(M_NETMAP);
57 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map");
58 
59 #endif /* __FreeBSD__ */
60 
61 #ifdef _WIN32
62 #include <win_glue.h>
63 #endif
64 
65 #include <net/netmap.h>
66 #include <dev/netmap/netmap_kern.h>
67 #include <net/netmap_virt.h>
68 #include "netmap_mem2.h"
69 
70 #ifdef _WIN32_USE_SMALL_GENERIC_DEVICES_MEMORY
71 #define NETMAP_BUF_MAX_NUM  8*4096      /* if too big takes too much time to allocate */
72 #else
73 #define NETMAP_BUF_MAX_NUM 20*4096*2	/* large machine */
74 #endif
75 
76 #define NETMAP_POOL_MAX_NAMSZ	32
77 
78 
79 enum {
80 	NETMAP_IF_POOL   = 0,
81 	NETMAP_RING_POOL,
82 	NETMAP_BUF_POOL,
83 	NETMAP_POOLS_NR
84 };
85 
86 
87 struct netmap_obj_params {
88 	u_int size;
89 	u_int num;
90 
91 	u_int last_size;
92 	u_int last_num;
93 };
94 
95 struct netmap_obj_pool {
96 	char name[NETMAP_POOL_MAX_NAMSZ];	/* name of the allocator */
97 
98 	/* ---------------------------------------------------*/
99 	/* these are only meaningful if the pool is finalized */
100 	/* (see 'finalized' field in netmap_mem_d)            */
101 	size_t memtotal;	/* actual total memory space */
102 
103 	struct lut_entry *lut;  /* virt,phys addresses, objtotal entries */
104 	uint32_t *bitmap;       /* one bit per buffer, 1 means free */
105 	uint32_t *invalid_bitmap;/* one bit per buffer, 1 means invalid */
106 	uint32_t bitmap_slots;	/* number of uint32 entries in bitmap */
107 
108 	u_int objtotal;         /* actual total number of objects. */
109 	u_int numclusters;	/* actual number of clusters */
110 	u_int objfree;          /* number of free objects. */
111 
112 	int	alloc_done;	/* we have allocated the memory */
113 	/* ---------------------------------------------------*/
114 
115 	/* limits */
116 	u_int objminsize;	/* minimum object size */
117 	u_int objmaxsize;	/* maximum object size */
118 	u_int nummin;		/* minimum number of objects */
119 	u_int nummax;		/* maximum number of objects */
120 
121 	/* these are changed only by config */
122 	u_int _objtotal;	/* total number of objects */
123 	u_int _objsize;		/* object size */
124 	u_int _clustsize;       /* cluster size */
125 	u_int _clustentries;    /* objects per cluster */
126 	u_int _numclusters;	/* number of clusters */
127 
128 	/* requested values */
129 	u_int r_objtotal;
130 	u_int r_objsize;
131 };
132 
133 #define NMA_LOCK_T		NM_MTX_T
134 #define NMA_LOCK_INIT(n)	NM_MTX_INIT((n)->nm_mtx)
135 #define NMA_LOCK_DESTROY(n)	NM_MTX_DESTROY((n)->nm_mtx)
136 #define NMA_LOCK(n)		NM_MTX_LOCK((n)->nm_mtx)
137 #define NMA_SPINLOCK(n)         NM_MTX_SPINLOCK((n)->nm_mtx)
138 #define NMA_UNLOCK(n)		NM_MTX_UNLOCK((n)->nm_mtx)
139 
140 struct netmap_mem_ops {
141 	int (*nmd_get_lut)(struct netmap_mem_d *, struct netmap_lut*);
142 	int  (*nmd_get_info)(struct netmap_mem_d *, uint64_t *size,
143 			u_int *memflags, uint16_t *id);
144 
145 	vm_paddr_t (*nmd_ofstophys)(struct netmap_mem_d *, vm_ooffset_t);
146 	int (*nmd_config)(struct netmap_mem_d *);
147 	int (*nmd_finalize)(struct netmap_mem_d *);
148 	void (*nmd_deref)(struct netmap_mem_d *);
149 	ssize_t  (*nmd_if_offset)(struct netmap_mem_d *, const void *vaddr);
150 	void (*nmd_delete)(struct netmap_mem_d *);
151 
152 	struct netmap_if * (*nmd_if_new)(struct netmap_adapter *,
153 					 struct netmap_priv_d *);
154 	void (*nmd_if_delete)(struct netmap_adapter *, struct netmap_if *);
155 	int  (*nmd_rings_create)(struct netmap_adapter *);
156 	void (*nmd_rings_delete)(struct netmap_adapter *);
157 };
158 
159 struct netmap_mem_d {
160 	NMA_LOCK_T nm_mtx;  /* protect the allocator */
161 	size_t nm_totalsize; /* shorthand */
162 
163 	u_int flags;
164 #define NETMAP_MEM_FINALIZED	0x1	/* preallocation done */
165 #define NETMAP_MEM_HIDDEN	0x8	/* being prepared */
166 	int lasterr;		/* last error for curr config */
167 	int active;		/* active users */
168 	int refcount;
169 	/* the three allocators */
170 	struct netmap_obj_pool pools[NETMAP_POOLS_NR];
171 
172 	nm_memid_t nm_id;	/* allocator identifier */
173 	int nm_grp;	/* iommu group id */
174 
175 	/* list of all existing allocators, sorted by nm_id */
176 	struct netmap_mem_d *prev, *next;
177 
178 	struct netmap_mem_ops *ops;
179 
180 	struct netmap_obj_params params[NETMAP_POOLS_NR];
181 
182 #define NM_MEM_NAMESZ	16
183 	char name[NM_MEM_NAMESZ];
184 };
185 
186 int
netmap_mem_get_lut(struct netmap_mem_d * nmd,struct netmap_lut * lut)187 netmap_mem_get_lut(struct netmap_mem_d *nmd, struct netmap_lut *lut)
188 {
189 	int rv;
190 
191 	NMA_LOCK(nmd);
192 	rv = nmd->ops->nmd_get_lut(nmd, lut);
193 	NMA_UNLOCK(nmd);
194 
195 	return rv;
196 }
197 
198 int
netmap_mem_get_info(struct netmap_mem_d * nmd,uint64_t * size,u_int * memflags,nm_memid_t * memid)199 netmap_mem_get_info(struct netmap_mem_d *nmd, uint64_t *size,
200 		u_int *memflags, nm_memid_t *memid)
201 {
202 	int rv;
203 
204 	NMA_LOCK(nmd);
205 	rv = nmd->ops->nmd_get_info(nmd, size, memflags, memid);
206 	NMA_UNLOCK(nmd);
207 
208 	return rv;
209 }
210 
211 vm_paddr_t
netmap_mem_ofstophys(struct netmap_mem_d * nmd,vm_ooffset_t off)212 netmap_mem_ofstophys(struct netmap_mem_d *nmd, vm_ooffset_t off)
213 {
214 	vm_paddr_t pa;
215 
216 #if defined(__FreeBSD__)
217 	/* This function is called by netmap_dev_pager_fault(), which holds a
218 	 * non-sleepable lock since FreeBSD 12. Since we cannot sleep, we
219 	 * spin on the trylock. */
220 	NMA_SPINLOCK(nmd);
221 #else
222 	NMA_LOCK(nmd);
223 #endif
224 	pa = nmd->ops->nmd_ofstophys(nmd, off);
225 	NMA_UNLOCK(nmd);
226 
227 	return pa;
228 }
229 
230 static int
netmap_mem_config(struct netmap_mem_d * nmd)231 netmap_mem_config(struct netmap_mem_d *nmd)
232 {
233 	if (nmd->active) {
234 		/* already in use. Not fatal, but we
235 		 * cannot change the configuration
236 		 */
237 		return 0;
238 	}
239 
240 	return nmd->ops->nmd_config(nmd);
241 }
242 
243 ssize_t
netmap_mem_if_offset(struct netmap_mem_d * nmd,const void * off)244 netmap_mem_if_offset(struct netmap_mem_d *nmd, const void *off)
245 {
246 	ssize_t rv;
247 
248 	NMA_LOCK(nmd);
249 	rv = nmd->ops->nmd_if_offset(nmd, off);
250 	NMA_UNLOCK(nmd);
251 
252 	return rv;
253 }
254 
255 static void
netmap_mem_delete(struct netmap_mem_d * nmd)256 netmap_mem_delete(struct netmap_mem_d *nmd)
257 {
258 	nmd->ops->nmd_delete(nmd);
259 }
260 
261 struct netmap_if *
netmap_mem_if_new(struct netmap_adapter * na,struct netmap_priv_d * priv)262 netmap_mem_if_new(struct netmap_adapter *na, struct netmap_priv_d *priv)
263 {
264 	struct netmap_if *nifp;
265 	struct netmap_mem_d *nmd = na->nm_mem;
266 
267 	NMA_LOCK(nmd);
268 	nifp = nmd->ops->nmd_if_new(na, priv);
269 	NMA_UNLOCK(nmd);
270 
271 	return nifp;
272 }
273 
274 void
netmap_mem_if_delete(struct netmap_adapter * na,struct netmap_if * nif)275 netmap_mem_if_delete(struct netmap_adapter *na, struct netmap_if *nif)
276 {
277 	struct netmap_mem_d *nmd = na->nm_mem;
278 
279 	NMA_LOCK(nmd);
280 	nmd->ops->nmd_if_delete(na, nif);
281 	NMA_UNLOCK(nmd);
282 }
283 
284 int
netmap_mem_rings_create(struct netmap_adapter * na)285 netmap_mem_rings_create(struct netmap_adapter *na)
286 {
287 	int rv;
288 	struct netmap_mem_d *nmd = na->nm_mem;
289 
290 	NMA_LOCK(nmd);
291 	rv = nmd->ops->nmd_rings_create(na);
292 	NMA_UNLOCK(nmd);
293 
294 	return rv;
295 }
296 
297 void
netmap_mem_rings_delete(struct netmap_adapter * na)298 netmap_mem_rings_delete(struct netmap_adapter *na)
299 {
300 	struct netmap_mem_d *nmd = na->nm_mem;
301 
302 	NMA_LOCK(nmd);
303 	nmd->ops->nmd_rings_delete(na);
304 	NMA_UNLOCK(nmd);
305 }
306 
307 static int netmap_mem_map(struct netmap_obj_pool *, struct netmap_adapter *);
308 static int netmap_mem_unmap(struct netmap_obj_pool *, struct netmap_adapter *);
309 static int nm_mem_assign_group(struct netmap_mem_d *, bus_dma_tag_t);
310 static void nm_mem_release_id(struct netmap_mem_d *);
311 
312 nm_memid_t
netmap_mem_get_id(struct netmap_mem_d * nmd)313 netmap_mem_get_id(struct netmap_mem_d *nmd)
314 {
315 	return nmd->nm_id;
316 }
317 
318 #ifdef NM_DEBUG_MEM_PUTGET
319 #define NM_DBG_REFC(nmd, func, line)	\
320 	nm_prinf("%d mem[%d] -> %d", line, (nmd)->nm_id, (nmd)->refcount);
321 #else
322 #define NM_DBG_REFC(nmd, func, line)
323 #endif
324 
325 /* circular list of all existing allocators */
326 static struct netmap_mem_d *netmap_last_mem_d = &nm_mem;
327 NM_MTX_T nm_mem_list_lock;
328 
329 struct netmap_mem_d *
__netmap_mem_get(struct netmap_mem_d * nmd,const char * func,int line)330 __netmap_mem_get(struct netmap_mem_d *nmd, const char *func, int line)
331 {
332 	NM_MTX_LOCK(nm_mem_list_lock);
333 	nmd->refcount++;
334 	NM_DBG_REFC(nmd, func, line);
335 	NM_MTX_UNLOCK(nm_mem_list_lock);
336 	return nmd;
337 }
338 
339 void
__netmap_mem_put(struct netmap_mem_d * nmd,const char * func,int line)340 __netmap_mem_put(struct netmap_mem_d *nmd, const char *func, int line)
341 {
342 	int last;
343 	NM_MTX_LOCK(nm_mem_list_lock);
344 	last = (--nmd->refcount == 0);
345 	if (last)
346 		nm_mem_release_id(nmd);
347 	NM_DBG_REFC(nmd, func, line);
348 	NM_MTX_UNLOCK(nm_mem_list_lock);
349 	if (last)
350 		netmap_mem_delete(nmd);
351 }
352 
353 int
netmap_mem_finalize(struct netmap_mem_d * nmd,struct netmap_adapter * na)354 netmap_mem_finalize(struct netmap_mem_d *nmd, struct netmap_adapter *na)
355 {
356 	int lasterr = 0;
357 	if (nm_mem_assign_group(nmd, na->pdev) < 0) {
358 		return ENOMEM;
359 	}
360 
361 	NMA_LOCK(nmd);
362 
363 	if (netmap_mem_config(nmd))
364 		goto out;
365 
366 	nmd->active++;
367 
368 	nmd->lasterr = nmd->ops->nmd_finalize(nmd);
369 
370 	if (!nmd->lasterr && na->pdev) {
371 		nmd->lasterr = netmap_mem_map(&nmd->pools[NETMAP_BUF_POOL], na);
372 	}
373 
374 out:
375 	lasterr = nmd->lasterr;
376 	NMA_UNLOCK(nmd);
377 
378 	if (lasterr)
379 		netmap_mem_deref(nmd, na);
380 
381 	return lasterr;
382 }
383 
384 static int
nm_isset(uint32_t * bitmap,u_int i)385 nm_isset(uint32_t *bitmap, u_int i)
386 {
387 	return bitmap[ (i>>5) ] & ( 1U << (i & 31U) );
388 }
389 
390 
391 static int
netmap_init_obj_allocator_bitmap(struct netmap_obj_pool * p)392 netmap_init_obj_allocator_bitmap(struct netmap_obj_pool *p)
393 {
394 	u_int n, j;
395 
396 	if (p->bitmap == NULL) {
397 		/* Allocate the bitmap */
398 		n = (p->objtotal + 31) / 32;
399 		p->bitmap = nm_os_malloc(sizeof(p->bitmap[0]) * n);
400 		if (p->bitmap == NULL) {
401 			nm_prerr("Unable to create bitmap (%d entries) for allocator '%s'", (int)n,
402 			    p->name);
403 			return ENOMEM;
404 		}
405 		p->bitmap_slots = n;
406 	} else {
407 		memset(p->bitmap, 0, p->bitmap_slots * sizeof(p->bitmap[0]));
408 	}
409 
410 	p->objfree = 0;
411 	/*
412 	 * Set all the bits in the bitmap that have
413 	 * corresponding buffers to 1 to indicate they are
414 	 * free.
415 	 */
416 	for (j = 0; j < p->objtotal; j++) {
417 		if (p->invalid_bitmap && nm_isset(p->invalid_bitmap, j)) {
418 			if (netmap_debug & NM_DEBUG_MEM)
419 				nm_prinf("skipping %s %d", p->name, j);
420 			continue;
421 		}
422 		p->bitmap[ (j>>5) ] |=  ( 1U << (j & 31U) );
423 		p->objfree++;
424 	}
425 
426 	if (netmap_verbose)
427 		nm_prinf("%s free %u", p->name, p->objfree);
428 	if (p->objfree == 0) {
429 		if (netmap_verbose)
430 			nm_prerr("%s: no objects available", p->name);
431 		return ENOMEM;
432 	}
433 
434 	return 0;
435 }
436 
437 static int
netmap_mem_init_bitmaps(struct netmap_mem_d * nmd)438 netmap_mem_init_bitmaps(struct netmap_mem_d *nmd)
439 {
440 	int i, error = 0;
441 
442 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
443 		struct netmap_obj_pool *p = &nmd->pools[i];
444 
445 		error = netmap_init_obj_allocator_bitmap(p);
446 		if (error)
447 			return error;
448 	}
449 
450 	/*
451 	 * buffers 0 and 1 are reserved
452 	 */
453 	if (nmd->pools[NETMAP_BUF_POOL].objfree < 2) {
454 		nm_prerr("%s: not enough buffers", nmd->pools[NETMAP_BUF_POOL].name);
455 		return ENOMEM;
456 	}
457 
458 	nmd->pools[NETMAP_BUF_POOL].objfree -= 2;
459 	if (nmd->pools[NETMAP_BUF_POOL].bitmap) {
460 		/* XXX This check is a workaround that prevents a
461 		 * NULL pointer crash which currently happens only
462 		 * with ptnetmap guests.
463 		 * Removed shared-info --> is the bug still there? */
464 		nmd->pools[NETMAP_BUF_POOL].bitmap[0] = ~3U;
465 	}
466 	return 0;
467 }
468 
469 int
netmap_mem_deref(struct netmap_mem_d * nmd,struct netmap_adapter * na)470 netmap_mem_deref(struct netmap_mem_d *nmd, struct netmap_adapter *na)
471 {
472 	int last_user = 0;
473 	NMA_LOCK(nmd);
474 	if (na->active_fds <= 0)
475 		netmap_mem_unmap(&nmd->pools[NETMAP_BUF_POOL], na);
476 	if (nmd->active == 1) {
477 		last_user = 1;
478 		/*
479 		 * Reset the allocator when it falls out of use so that any
480 		 * pool resources leaked by unclean application exits are
481 		 * reclaimed.
482 		 */
483 		netmap_mem_init_bitmaps(nmd);
484 	}
485 	nmd->ops->nmd_deref(nmd);
486 
487 	nmd->active--;
488 	if (last_user) {
489 		nmd->nm_grp = -1;
490 		nmd->lasterr = 0;
491 	}
492 
493 	NMA_UNLOCK(nmd);
494 	return last_user;
495 }
496 
497 
498 /* accessor functions */
499 static int
netmap_mem2_get_lut(struct netmap_mem_d * nmd,struct netmap_lut * lut)500 netmap_mem2_get_lut(struct netmap_mem_d *nmd, struct netmap_lut *lut)
501 {
502 	lut->lut = nmd->pools[NETMAP_BUF_POOL].lut;
503 #ifdef __FreeBSD__
504 	lut->plut = lut->lut;
505 #endif
506 	lut->objtotal = nmd->pools[NETMAP_BUF_POOL].objtotal;
507 	lut->objsize = nmd->pools[NETMAP_BUF_POOL]._objsize;
508 
509 	return 0;
510 }
511 
512 static struct netmap_obj_params netmap_min_priv_params[NETMAP_POOLS_NR] = {
513 	[NETMAP_IF_POOL] = {
514 		.size = 1024,
515 		.num  = 2,
516 	},
517 	[NETMAP_RING_POOL] = {
518 		.size = 5*PAGE_SIZE,
519 		.num  = 4,
520 	},
521 	[NETMAP_BUF_POOL] = {
522 		.size = 2048,
523 		.num  = 4098,
524 	},
525 };
526 
527 
528 /*
529  * nm_mem is the memory allocator used for all physical interfaces
530  * running in netmap mode.
531  * Virtual (VALE) ports will have each its own allocator.
532  */
533 extern struct netmap_mem_ops netmap_mem_global_ops; /* forward */
534 struct netmap_mem_d nm_mem = {	/* Our memory allocator. */
535 	.pools = {
536 		[NETMAP_IF_POOL] = {
537 			.name 	= "netmap_if",
538 			.objminsize = sizeof(struct netmap_if),
539 			.objmaxsize = 4096,
540 			.nummin     = 10,	/* don't be stingy */
541 			.nummax	    = 10000,	/* XXX very large */
542 		},
543 		[NETMAP_RING_POOL] = {
544 			.name 	= "netmap_ring",
545 			.objminsize = sizeof(struct netmap_ring),
546 			.objmaxsize = 32*PAGE_SIZE,
547 			.nummin     = 2,
548 			.nummax	    = 1024,
549 		},
550 		[NETMAP_BUF_POOL] = {
551 			.name	= "netmap_buf",
552 			.objminsize = 64,
553 			.objmaxsize = 65536,
554 			.nummin     = 4,
555 			.nummax	    = 1000000, /* one million! */
556 		},
557 	},
558 
559 	.params = {
560 		[NETMAP_IF_POOL] = {
561 			.size = 1024,
562 			.num  = 100,
563 		},
564 		[NETMAP_RING_POOL] = {
565 			.size = 9*PAGE_SIZE,
566 			.num  = 200,
567 		},
568 		[NETMAP_BUF_POOL] = {
569 			.size = 2048,
570 			.num  = NETMAP_BUF_MAX_NUM,
571 		},
572 	},
573 
574 	.nm_id = 1,
575 	.nm_grp = -1,
576 
577 	.prev = &nm_mem,
578 	.next = &nm_mem,
579 
580 	.ops = &netmap_mem_global_ops,
581 
582 	.name = "1"
583 };
584 
585 
586 /* blueprint for the private memory allocators */
587 /* XXX clang is not happy about using name as a print format */
588 static const struct netmap_mem_d nm_blueprint = {
589 	.pools = {
590 		[NETMAP_IF_POOL] = {
591 			.name 	= "%s_if",
592 			.objminsize = sizeof(struct netmap_if),
593 			.objmaxsize = 4096,
594 			.nummin     = 1,
595 			.nummax	    = 100,
596 		},
597 		[NETMAP_RING_POOL] = {
598 			.name 	= "%s_ring",
599 			.objminsize = sizeof(struct netmap_ring),
600 			.objmaxsize = 32*PAGE_SIZE,
601 			.nummin     = 2,
602 			.nummax	    = 1024,
603 		},
604 		[NETMAP_BUF_POOL] = {
605 			.name	= "%s_buf",
606 			.objminsize = 64,
607 			.objmaxsize = 65536,
608 			.nummin     = 4,
609 			.nummax	    = 1000000, /* one million! */
610 		},
611 	},
612 
613 	.nm_grp = -1,
614 
615 	.flags = NETMAP_MEM_PRIVATE,
616 
617 	.ops = &netmap_mem_global_ops,
618 };
619 
620 /* memory allocator related sysctls */
621 
622 #define STRINGIFY(x) #x
623 
624 
625 #define DECLARE_SYSCTLS(id, name) \
626 	SYSBEGIN(mem2_ ## name); \
627 	SYSCTL_INT(_dev_netmap, OID_AUTO, name##_size, \
628 	    CTLFLAG_RW, &nm_mem.params[id].size, 0, "Requested size of netmap " STRINGIFY(name) "s"); \
629 	SYSCTL_INT(_dev_netmap, OID_AUTO, name##_curr_size, \
630 	    CTLFLAG_RD, &nm_mem.pools[id]._objsize, 0, "Current size of netmap " STRINGIFY(name) "s"); \
631 	SYSCTL_INT(_dev_netmap, OID_AUTO, name##_num, \
632 	    CTLFLAG_RW, &nm_mem.params[id].num, 0, "Requested number of netmap " STRINGIFY(name) "s"); \
633 	SYSCTL_INT(_dev_netmap, OID_AUTO, name##_curr_num, \
634 	    CTLFLAG_RD, &nm_mem.pools[id].objtotal, 0, "Current number of netmap " STRINGIFY(name) "s"); \
635 	SYSCTL_INT(_dev_netmap, OID_AUTO, priv_##name##_size, \
636 	    CTLFLAG_RW, &netmap_min_priv_params[id].size, 0, \
637 	    "Default size of private netmap " STRINGIFY(name) "s"); \
638 	SYSCTL_INT(_dev_netmap, OID_AUTO, priv_##name##_num, \
639 	    CTLFLAG_RW, &netmap_min_priv_params[id].num, 0, \
640 	    "Default number of private netmap " STRINGIFY(name) "s");	\
641 	SYSEND
642 
643 SYSCTL_DECL(_dev_netmap);
644 DECLARE_SYSCTLS(NETMAP_IF_POOL, if);
645 DECLARE_SYSCTLS(NETMAP_RING_POOL, ring);
646 DECLARE_SYSCTLS(NETMAP_BUF_POOL, buf);
647 
648 /* call with nm_mem_list_lock held */
649 static int
nm_mem_assign_id_locked(struct netmap_mem_d * nmd)650 nm_mem_assign_id_locked(struct netmap_mem_d *nmd)
651 {
652 	nm_memid_t id;
653 	struct netmap_mem_d *scan = netmap_last_mem_d;
654 	int error = ENOMEM;
655 
656 	do {
657 		/* we rely on unsigned wrap around */
658 		id = scan->nm_id + 1;
659 		if (id == 0) /* reserve 0 as error value */
660 			id = 1;
661 		scan = scan->next;
662 		if (id != scan->nm_id) {
663 			nmd->nm_id = id;
664 			nmd->prev = scan->prev;
665 			nmd->next = scan;
666 			scan->prev->next = nmd;
667 			scan->prev = nmd;
668 			netmap_last_mem_d = nmd;
669 			nmd->refcount = 1;
670 			NM_DBG_REFC(nmd, __FUNCTION__, __LINE__);
671 			error = 0;
672 			break;
673 		}
674 	} while (scan != netmap_last_mem_d);
675 
676 	return error;
677 }
678 
679 /* call with nm_mem_list_lock *not* held */
680 static int
nm_mem_assign_id(struct netmap_mem_d * nmd)681 nm_mem_assign_id(struct netmap_mem_d *nmd)
682 {
683 	int ret;
684 
685 	NM_MTX_LOCK(nm_mem_list_lock);
686 	ret = nm_mem_assign_id_locked(nmd);
687 	NM_MTX_UNLOCK(nm_mem_list_lock);
688 
689 	return ret;
690 }
691 
692 /* call with nm_mem_list_lock held */
693 static void
nm_mem_release_id(struct netmap_mem_d * nmd)694 nm_mem_release_id(struct netmap_mem_d *nmd)
695 {
696 	nmd->prev->next = nmd->next;
697 	nmd->next->prev = nmd->prev;
698 
699 	if (netmap_last_mem_d == nmd)
700 		netmap_last_mem_d = nmd->prev;
701 
702 	nmd->prev = nmd->next = NULL;
703 }
704 
705 struct netmap_mem_d *
netmap_mem_find(nm_memid_t id)706 netmap_mem_find(nm_memid_t id)
707 {
708 	struct netmap_mem_d *nmd;
709 
710 	NM_MTX_LOCK(nm_mem_list_lock);
711 	nmd = netmap_last_mem_d;
712 	do {
713 		if (!(nmd->flags & NETMAP_MEM_HIDDEN) && nmd->nm_id == id) {
714 			nmd->refcount++;
715 			NM_DBG_REFC(nmd, __FUNCTION__, __LINE__);
716 			NM_MTX_UNLOCK(nm_mem_list_lock);
717 			return nmd;
718 		}
719 		nmd = nmd->next;
720 	} while (nmd != netmap_last_mem_d);
721 	NM_MTX_UNLOCK(nm_mem_list_lock);
722 	return NULL;
723 }
724 
725 static int
nm_mem_assign_group(struct netmap_mem_d * nmd,bus_dma_tag_t dev)726 nm_mem_assign_group(struct netmap_mem_d *nmd, bus_dma_tag_t dev)
727 {
728 	int err = 0, id;
729 	id = nm_iommu_group_id(dev);
730 	if (netmap_debug & NM_DEBUG_MEM)
731 		nm_prinf("iommu_group %d", id);
732 
733 	NMA_LOCK(nmd);
734 
735 	if (nmd->nm_grp < 0)
736 		nmd->nm_grp = id;
737 
738 	if (nmd->nm_grp != id) {
739 		if (netmap_verbose)
740 			nm_prerr("iommu group mismatch: %u vs %u",
741 					nmd->nm_grp, id);
742 		nmd->lasterr = err = ENOMEM;
743 	}
744 
745 	NMA_UNLOCK(nmd);
746 	return err;
747 }
748 
749 static struct lut_entry *
nm_alloc_lut(u_int nobj)750 nm_alloc_lut(u_int nobj)
751 {
752 	size_t n = sizeof(struct lut_entry) * nobj;
753 	struct lut_entry *lut;
754 #ifdef linux
755 	lut = vmalloc(n);
756 #else
757 	lut = nm_os_malloc(n);
758 #endif
759 	return lut;
760 }
761 
762 static void
nm_free_lut(struct lut_entry * lut,u_int objtotal)763 nm_free_lut(struct lut_entry *lut, u_int objtotal)
764 {
765 	bzero(lut, sizeof(struct lut_entry) * objtotal);
766 #ifdef linux
767 	vfree(lut);
768 #else
769 	nm_os_free(lut);
770 #endif
771 }
772 
773 #if defined(linux) || defined(_WIN32)
774 static struct plut_entry *
nm_alloc_plut(u_int nobj)775 nm_alloc_plut(u_int nobj)
776 {
777 	size_t n = sizeof(struct plut_entry) * nobj;
778 	struct plut_entry *lut;
779 	lut = vmalloc(n);
780 	return lut;
781 }
782 
783 static void
nm_free_plut(struct plut_entry * lut)784 nm_free_plut(struct plut_entry * lut)
785 {
786 	vfree(lut);
787 }
788 #endif /* linux or _WIN32 */
789 
790 
791 /*
792  * First, find the allocator that contains the requested offset,
793  * then locate the cluster through a lookup table.
794  */
795 static vm_paddr_t
netmap_mem2_ofstophys(struct netmap_mem_d * nmd,vm_ooffset_t offset)796 netmap_mem2_ofstophys(struct netmap_mem_d* nmd, vm_ooffset_t offset)
797 {
798 	int i;
799 	vm_ooffset_t o = offset;
800 	vm_paddr_t pa;
801 	struct netmap_obj_pool *p;
802 
803 	p = nmd->pools;
804 
805 	for (i = 0; i < NETMAP_POOLS_NR; offset -= p[i].memtotal, i++) {
806 		if (offset >= p[i].memtotal)
807 			continue;
808 		// now lookup the cluster's address
809 #ifndef _WIN32
810 		pa = vtophys(p[i].lut[offset / p[i]._objsize].vaddr) +
811 			offset % p[i]._objsize;
812 #else
813 		pa = vtophys(p[i].lut[offset / p[i]._objsize].vaddr);
814 		pa.QuadPart += offset % p[i]._objsize;
815 #endif
816 		return pa;
817 	}
818 	/* this is only in case of errors */
819 	nm_prerr("invalid ofs 0x%x out of 0x%zx 0x%zx 0x%zx", (u_int)o,
820 		p[NETMAP_IF_POOL].memtotal,
821 		p[NETMAP_IF_POOL].memtotal
822 			+ p[NETMAP_RING_POOL].memtotal,
823 		p[NETMAP_IF_POOL].memtotal
824 			+ p[NETMAP_RING_POOL].memtotal
825 			+ p[NETMAP_BUF_POOL].memtotal);
826 #ifndef _WIN32
827 	return 0; /* bad address */
828 #else
829 	vm_paddr_t res;
830 	res.QuadPart = 0;
831 	return res;
832 #endif
833 }
834 
835 #ifdef _WIN32
836 
837 /*
838  * win32_build_virtual_memory_for_userspace
839  *
840  * This function get all the object making part of the pools and maps
841  * a contiguous virtual memory space for the userspace
842  * It works this way
843  * 1 - allocate a Memory Descriptor List wide as the sum
844  *		of the memory needed for the pools
845  * 2 - cycle all the objects in every pool and for every object do
846  *
847  *		2a - cycle all the objects in every pool, get the list
848  *				of the physical address descriptors
849  *		2b - calculate the offset in the array of pages descriptor in the
850  *				main MDL
851  *		2c - copy the descriptors of the object in the main MDL
852  *
853  * 3 - return the resulting MDL that needs to be mapped in userland
854  *
855  * In this way we will have an MDL that describes all the memory for the
856  * objects in a single object
857 */
858 
859 PMDL
win32_build_user_vm_map(struct netmap_mem_d * nmd)860 win32_build_user_vm_map(struct netmap_mem_d* nmd)
861 {
862 	u_int memflags, ofs = 0;
863 	PMDL mainMdl, tempMdl;
864 	uint64_t memsize;
865 	int i, j;
866 
867 	if (netmap_mem_get_info(nmd, &memsize, &memflags, NULL)) {
868 		nm_prerr("memory not finalised yet");
869 		return NULL;
870 	}
871 
872 	mainMdl = IoAllocateMdl(NULL, memsize, FALSE, FALSE, NULL);
873 	if (mainMdl == NULL) {
874 		nm_prerr("failed to allocate mdl");
875 		return NULL;
876 	}
877 
878 	NMA_LOCK(nmd);
879 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
880 		struct netmap_obj_pool *p = &nmd->pools[i];
881 		int clsz = p->_clustsize;
882 		int clobjs = p->_clustentries; /* objects per cluster */
883 		int mdl_len = sizeof(PFN_NUMBER) * BYTES_TO_PAGES(clsz);
884 		PPFN_NUMBER pSrc, pDst;
885 
886 		/* each pool has a different cluster size so we need to reallocate */
887 		tempMdl = IoAllocateMdl(p->lut[0].vaddr, clsz, FALSE, FALSE, NULL);
888 		if (tempMdl == NULL) {
889 			NMA_UNLOCK(nmd);
890 			nm_prerr("fail to allocate tempMdl");
891 			IoFreeMdl(mainMdl);
892 			return NULL;
893 		}
894 		pSrc = MmGetMdlPfnArray(tempMdl);
895 		/* create one entry per cluster, the lut[] has one entry per object */
896 		for (j = 0; j < p->numclusters; j++, ofs += clsz) {
897 			pDst = &MmGetMdlPfnArray(mainMdl)[BYTES_TO_PAGES(ofs)];
898 			MmInitializeMdl(tempMdl, p->lut[j*clobjs].vaddr, clsz);
899 			MmBuildMdlForNonPagedPool(tempMdl); /* compute physical page addresses */
900 			RtlCopyMemory(pDst, pSrc, mdl_len); /* copy the page descriptors */
901 			mainMdl->MdlFlags = tempMdl->MdlFlags; /* XXX what is in here ? */
902 		}
903 		IoFreeMdl(tempMdl);
904 	}
905 	NMA_UNLOCK(nmd);
906 	return mainMdl;
907 }
908 
909 #endif /* _WIN32 */
910 
911 /*
912  * helper function for OS-specific mmap routines (currently only windows).
913  * Given an nmd and a pool index, returns the cluster size and number of clusters.
914  * Returns 0 if memory is finalised and the pool is valid, otherwise 1.
915  * It should be called under NMA_LOCK(nmd) otherwise the underlying info can change.
916  */
917 
918 int
netmap_mem2_get_pool_info(struct netmap_mem_d * nmd,u_int pool,u_int * clustsize,u_int * numclusters)919 netmap_mem2_get_pool_info(struct netmap_mem_d* nmd, u_int pool, u_int *clustsize, u_int *numclusters)
920 {
921 	if (!nmd || !clustsize || !numclusters || pool >= NETMAP_POOLS_NR)
922 		return 1; /* invalid arguments */
923 	// NMA_LOCK_ASSERT(nmd);
924 	if (!(nmd->flags & NETMAP_MEM_FINALIZED)) {
925 		*clustsize = *numclusters = 0;
926 		return 1; /* not ready yet */
927 	}
928 	*clustsize = nmd->pools[pool]._clustsize;
929 	*numclusters = nmd->pools[pool].numclusters;
930 	return 0; /* success */
931 }
932 
933 static int
netmap_mem2_get_info(struct netmap_mem_d * nmd,uint64_t * size,u_int * memflags,nm_memid_t * id)934 netmap_mem2_get_info(struct netmap_mem_d* nmd, uint64_t* size,
935 			u_int *memflags, nm_memid_t *id)
936 {
937 	int error = 0;
938 	error = netmap_mem_config(nmd);
939 	if (error)
940 		goto out;
941 	if (size) {
942 		if (nmd->flags & NETMAP_MEM_FINALIZED) {
943 			*size = nmd->nm_totalsize;
944 		} else {
945 			int i;
946 			*size = 0;
947 			for (i = 0; i < NETMAP_POOLS_NR; i++) {
948 				struct netmap_obj_pool *p = nmd->pools + i;
949 				*size += ((size_t)p->_numclusters * (size_t)p->_clustsize);
950 			}
951 		}
952 	}
953 	if (memflags)
954 		*memflags = nmd->flags;
955 	if (id)
956 		*id = nmd->nm_id;
957 out:
958 	return error;
959 }
960 
961 /*
962  * we store objects by kernel address, need to find the offset
963  * within the pool to export the value to userspace.
964  * Algorithm: scan until we find the cluster, then add the
965  * actual offset in the cluster
966  */
967 static ssize_t
netmap_obj_offset(struct netmap_obj_pool * p,const void * vaddr)968 netmap_obj_offset(struct netmap_obj_pool *p, const void *vaddr)
969 {
970 	int i, k = p->_clustentries, n = p->objtotal;
971 	ssize_t ofs = 0;
972 
973 	for (i = 0; i < n; i += k, ofs += p->_clustsize) {
974 		const char *base = p->lut[i].vaddr;
975 		ssize_t relofs = (const char *) vaddr - base;
976 
977 		if (relofs < 0 || relofs >= p->_clustsize)
978 			continue;
979 
980 		ofs = ofs + relofs;
981 		nm_prdis("%s: return offset %d (cluster %d) for pointer %p",
982 		    p->name, ofs, i, vaddr);
983 		return ofs;
984 	}
985 	nm_prerr("address %p is not contained inside any cluster (%s)",
986 	    vaddr, p->name);
987 	return 0; /* An error occurred */
988 }
989 
990 /* Helper functions which convert virtual addresses to offsets */
991 #define netmap_if_offset(n, v)					\
992 	netmap_obj_offset(&(n)->pools[NETMAP_IF_POOL], (v))
993 
994 #define netmap_ring_offset(n, v)				\
995     ((n)->pools[NETMAP_IF_POOL].memtotal + 			\
996 	netmap_obj_offset(&(n)->pools[NETMAP_RING_POOL], (v)))
997 
998 static ssize_t
netmap_mem2_if_offset(struct netmap_mem_d * nmd,const void * addr)999 netmap_mem2_if_offset(struct netmap_mem_d *nmd, const void *addr)
1000 {
1001 	return netmap_if_offset(nmd, addr);
1002 }
1003 
1004 /*
1005  * report the index, and use start position as a hint,
1006  * otherwise buffer allocation becomes terribly expensive.
1007  */
1008 static void *
netmap_obj_malloc(struct netmap_obj_pool * p,u_int len,uint32_t * start,uint32_t * index)1009 netmap_obj_malloc(struct netmap_obj_pool *p, u_int len, uint32_t *start, uint32_t *index)
1010 {
1011 	uint32_t i = 0;			/* index in the bitmap */
1012 	uint32_t mask, j = 0;		/* slot counter */
1013 	void *vaddr = NULL;
1014 
1015 	if (len > p->_objsize) {
1016 		nm_prerr("%s request size %d too large", p->name, len);
1017 		return NULL;
1018 	}
1019 
1020 	if (p->objfree == 0) {
1021 		nm_prerr("no more %s objects", p->name);
1022 		return NULL;
1023 	}
1024 	if (start)
1025 		i = *start;
1026 
1027 	/* termination is guaranteed by p->free, but better check bounds on i */
1028 	while (vaddr == NULL && i < p->bitmap_slots)  {
1029 		uint32_t cur = p->bitmap[i];
1030 		if (cur == 0) { /* bitmask is fully used */
1031 			i++;
1032 			continue;
1033 		}
1034 		/* locate a slot */
1035 		for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1)
1036 			;
1037 
1038 		p->bitmap[i] &= ~mask; /* mark object as in use */
1039 		p->objfree--;
1040 
1041 		vaddr = p->lut[i * 32 + j].vaddr;
1042 		if (index)
1043 			*index = i * 32 + j;
1044 	}
1045 	nm_prdis("%s allocator: allocated object @ [%d][%d]: vaddr %p",p->name, i, j, vaddr);
1046 
1047 	if (start)
1048 		*start = i;
1049 	return vaddr;
1050 }
1051 
1052 
1053 /*
1054  * free by index, not by address.
1055  * XXX should we also cleanup the content ?
1056  */
1057 static int
netmap_obj_free(struct netmap_obj_pool * p,uint32_t j)1058 netmap_obj_free(struct netmap_obj_pool *p, uint32_t j)
1059 {
1060 	uint32_t *ptr, mask;
1061 
1062 	if (j >= p->objtotal) {
1063 		nm_prerr("invalid index %u, max %u", j, p->objtotal);
1064 		return 1;
1065 	}
1066 	ptr = &p->bitmap[j / 32];
1067 	mask = (1 << (j % 32));
1068 	if (*ptr & mask) {
1069 		nm_prerr("ouch, double free on buffer %d", j);
1070 		return 1;
1071 	} else {
1072 		*ptr |= mask;
1073 		p->objfree++;
1074 		return 0;
1075 	}
1076 }
1077 
1078 /*
1079  * free by address. This is slow but is only used for a few
1080  * objects (rings, nifp)
1081  */
1082 static void
netmap_obj_free_va(struct netmap_obj_pool * p,void * vaddr)1083 netmap_obj_free_va(struct netmap_obj_pool *p, void *vaddr)
1084 {
1085 	u_int i, j, n = p->numclusters;
1086 
1087 	for (i = 0, j = 0; i < n; i++, j += p->_clustentries) {
1088 		void *base = p->lut[i * p->_clustentries].vaddr;
1089 		ssize_t relofs = (ssize_t) vaddr - (ssize_t) base;
1090 
1091 		/* Given address, is out of the scope of the current cluster.*/
1092 		if (base == NULL || vaddr < base || relofs >= p->_clustsize)
1093 			continue;
1094 
1095 		j = j + relofs / p->_objsize;
1096 		/* KASSERT(j != 0, ("Cannot free object 0")); */
1097 		netmap_obj_free(p, j);
1098 		return;
1099 	}
1100 	nm_prerr("address %p is not contained inside any cluster (%s)",
1101 	    vaddr, p->name);
1102 }
1103 
1104 unsigned
netmap_mem_bufsize(struct netmap_mem_d * nmd)1105 netmap_mem_bufsize(struct netmap_mem_d *nmd)
1106 {
1107 	return nmd->pools[NETMAP_BUF_POOL]._objsize;
1108 }
1109 
1110 #define netmap_if_malloc(n, len)	netmap_obj_malloc(&(n)->pools[NETMAP_IF_POOL], len, NULL, NULL)
1111 #define netmap_if_free(n, v)		netmap_obj_free_va(&(n)->pools[NETMAP_IF_POOL], (v))
1112 #define netmap_ring_malloc(n, len)	netmap_obj_malloc(&(n)->pools[NETMAP_RING_POOL], len, NULL, NULL)
1113 #define netmap_ring_free(n, v)		netmap_obj_free_va(&(n)->pools[NETMAP_RING_POOL], (v))
1114 #define netmap_buf_malloc(n, _pos, _index)			\
1115 	netmap_obj_malloc(&(n)->pools[NETMAP_BUF_POOL], netmap_mem_bufsize(n), _pos, _index)
1116 
1117 
1118 #if 0 /* currently unused */
1119 /* Return the index associated to the given packet buffer */
1120 #define netmap_buf_index(n, v)						\
1121     (netmap_obj_offset(&(n)->pools[NETMAP_BUF_POOL], (v)) / NETMAP_BDG_BUF_SIZE(n))
1122 #endif
1123 
1124 /*
1125  * allocate extra buffers in a linked list.
1126  * returns the actual number.
1127  */
1128 uint32_t
netmap_extra_alloc(struct netmap_adapter * na,uint32_t * head,uint32_t n)1129 netmap_extra_alloc(struct netmap_adapter *na, uint32_t *head, uint32_t n)
1130 {
1131 	struct netmap_mem_d *nmd = na->nm_mem;
1132 	uint32_t i, pos = 0; /* opaque, scan position in the bitmap */
1133 
1134 	NMA_LOCK(nmd);
1135 
1136 	*head = 0;	/* default, 'null' index ie empty list */
1137 	for (i = 0 ; i < n; i++) {
1138 		uint32_t cur = *head;	/* save current head */
1139 		uint32_t *p = netmap_buf_malloc(nmd, &pos, head);
1140 		if (p == NULL) {
1141 			nm_prerr("no more buffers after %d of %d", i, n);
1142 			*head = cur; /* restore */
1143 			break;
1144 		}
1145 		nm_prdis(5, "allocate buffer %d -> %d", *head, cur);
1146 		*p = cur; /* link to previous head */
1147 	}
1148 
1149 	NMA_UNLOCK(nmd);
1150 
1151 	return i;
1152 }
1153 
1154 static void
netmap_extra_free(struct netmap_adapter * na,uint32_t head)1155 netmap_extra_free(struct netmap_adapter *na, uint32_t head)
1156 {
1157 	struct lut_entry *lut = na->na_lut.lut;
1158 	struct netmap_mem_d *nmd = na->nm_mem;
1159 	struct netmap_obj_pool *p = &nmd->pools[NETMAP_BUF_POOL];
1160 	uint32_t i, cur, *buf;
1161 
1162 	nm_prdis("freeing the extra list");
1163 	for (i = 0; head >=2 && head < p->objtotal; i++) {
1164 		cur = head;
1165 		buf = lut[head].vaddr;
1166 		head = *buf;
1167 		*buf = 0;
1168 		if (netmap_obj_free(p, cur))
1169 			break;
1170 	}
1171 	if (head != 0)
1172 		nm_prerr("breaking with head %d", head);
1173 	if (netmap_debug & NM_DEBUG_MEM)
1174 		nm_prinf("freed %d buffers", i);
1175 }
1176 
1177 
1178 /* Return nonzero on error */
1179 static int
netmap_new_bufs(struct netmap_mem_d * nmd,struct netmap_slot * slot,u_int n)1180 netmap_new_bufs(struct netmap_mem_d *nmd, struct netmap_slot *slot, u_int n)
1181 {
1182 	struct netmap_obj_pool *p = &nmd->pools[NETMAP_BUF_POOL];
1183 	u_int i = 0;	/* slot counter */
1184 	uint32_t pos = 0;	/* slot in p->bitmap */
1185 	uint32_t index = 0;	/* buffer index */
1186 
1187 	for (i = 0; i < n; i++) {
1188 		void *vaddr = netmap_buf_malloc(nmd, &pos, &index);
1189 		if (vaddr == NULL) {
1190 			nm_prerr("no more buffers after %d of %d", i, n);
1191 			goto cleanup;
1192 		}
1193 		slot[i].buf_idx = index;
1194 		slot[i].len = p->_objsize;
1195 		slot[i].flags = 0;
1196 		slot[i].ptr = 0;
1197 	}
1198 
1199 	nm_prdis("%s: allocated %d buffers, %d available, first at %d", p->name, n, p->objfree, pos);
1200 	return (0);
1201 
1202 cleanup:
1203 	while (i > 0) {
1204 		i--;
1205 		netmap_obj_free(p, slot[i].buf_idx);
1206 	}
1207 	bzero(slot, n * sizeof(slot[0]));
1208 	return (ENOMEM);
1209 }
1210 
1211 static void
netmap_mem_set_ring(struct netmap_mem_d * nmd,struct netmap_slot * slot,u_int n,uint32_t index)1212 netmap_mem_set_ring(struct netmap_mem_d *nmd, struct netmap_slot *slot, u_int n, uint32_t index)
1213 {
1214 	struct netmap_obj_pool *p = &nmd->pools[NETMAP_BUF_POOL];
1215 	u_int i;
1216 
1217 	for (i = 0; i < n; i++) {
1218 		slot[i].buf_idx = index;
1219 		slot[i].len = p->_objsize;
1220 		slot[i].flags = 0;
1221 	}
1222 }
1223 
1224 
1225 static void
netmap_free_buf(struct netmap_mem_d * nmd,uint32_t i)1226 netmap_free_buf(struct netmap_mem_d *nmd, uint32_t i)
1227 {
1228 	struct netmap_obj_pool *p = &nmd->pools[NETMAP_BUF_POOL];
1229 
1230 	if (i < 2 || i >= p->objtotal) {
1231 		nm_prerr("Cannot free buf#%d: should be in [2, %d[", i, p->objtotal);
1232 		return;
1233 	}
1234 	netmap_obj_free(p, i);
1235 }
1236 
1237 
1238 static void
netmap_free_bufs(struct netmap_mem_d * nmd,struct netmap_slot * slot,u_int n)1239 netmap_free_bufs(struct netmap_mem_d *nmd, struct netmap_slot *slot, u_int n)
1240 {
1241 	u_int i;
1242 
1243 	for (i = 0; i < n; i++) {
1244 		if (slot[i].buf_idx > 1)
1245 			netmap_free_buf(nmd, slot[i].buf_idx);
1246 	}
1247 	nm_prdis("%s: released some buffers, available: %u",
1248 			p->name, p->objfree);
1249 }
1250 
1251 static void
netmap_reset_obj_allocator(struct netmap_obj_pool * p)1252 netmap_reset_obj_allocator(struct netmap_obj_pool *p)
1253 {
1254 
1255 	if (p == NULL)
1256 		return;
1257 	if (p->bitmap)
1258 		nm_os_free(p->bitmap);
1259 	p->bitmap = NULL;
1260 	if (p->invalid_bitmap)
1261 		nm_os_free(p->invalid_bitmap);
1262 	p->invalid_bitmap = NULL;
1263 	if (!p->alloc_done) {
1264 		/* allocation was done by somebody else.
1265 		 * Let them clean up after themselves.
1266 		 */
1267 		return;
1268 	}
1269 	if (p->lut) {
1270 		u_int i;
1271 
1272 		/*
1273 		 * Free each cluster allocated in
1274 		 * netmap_finalize_obj_allocator().  The cluster start
1275 		 * addresses are stored at multiples of p->_clusterentries
1276 		 * in the lut.
1277 		 */
1278 		for (i = 0; i < p->objtotal; i += p->_clustentries) {
1279 			contigfree(p->lut[i].vaddr, p->_clustsize, M_NETMAP);
1280 		}
1281 		nm_free_lut(p->lut, p->objtotal);
1282 	}
1283 	p->lut = NULL;
1284 	p->objtotal = 0;
1285 	p->memtotal = 0;
1286 	p->numclusters = 0;
1287 	p->objfree = 0;
1288 	p->alloc_done = 0;
1289 }
1290 
1291 /*
1292  * Free all resources related to an allocator.
1293  */
1294 static void
netmap_destroy_obj_allocator(struct netmap_obj_pool * p)1295 netmap_destroy_obj_allocator(struct netmap_obj_pool *p)
1296 {
1297 	if (p == NULL)
1298 		return;
1299 	netmap_reset_obj_allocator(p);
1300 }
1301 
1302 /*
1303  * We receive a request for objtotal objects, of size objsize each.
1304  * Internally we may round up both numbers, as we allocate objects
1305  * in small clusters multiple of the page size.
1306  * We need to keep track of objtotal and clustentries,
1307  * as they are needed when freeing memory.
1308  *
1309  * XXX note -- userspace needs the buffers to be contiguous,
1310  *	so we cannot afford gaps at the end of a cluster.
1311  */
1312 
1313 
1314 /* call with NMA_LOCK held */
1315 static int
netmap_config_obj_allocator(struct netmap_obj_pool * p,u_int objtotal,u_int objsize)1316 netmap_config_obj_allocator(struct netmap_obj_pool *p, u_int objtotal, u_int objsize)
1317 {
1318 	int i;
1319 	u_int clustsize;	/* the cluster size, multiple of page size */
1320 	u_int clustentries;	/* how many objects per entry */
1321 
1322 	/* we store the current request, so we can
1323 	 * detect configuration changes later */
1324 	p->r_objtotal = objtotal;
1325 	p->r_objsize = objsize;
1326 
1327 #define MAX_CLUSTSIZE	(1<<22)		// 4 MB
1328 #define LINE_ROUND	NM_CACHE_ALIGN	// 64
1329 	if (objsize >= MAX_CLUSTSIZE) {
1330 		/* we could do it but there is no point */
1331 		nm_prerr("unsupported allocation for %d bytes", objsize);
1332 		return EINVAL;
1333 	}
1334 	/* make sure objsize is a multiple of LINE_ROUND */
1335 	i = (objsize & (LINE_ROUND - 1));
1336 	if (i) {
1337 		nm_prinf("aligning object by %d bytes", LINE_ROUND - i);
1338 		objsize += LINE_ROUND - i;
1339 	}
1340 	if (objsize < p->objminsize || objsize > p->objmaxsize) {
1341 		nm_prerr("requested objsize %d out of range [%d, %d]",
1342 			objsize, p->objminsize, p->objmaxsize);
1343 		return EINVAL;
1344 	}
1345 	if (objtotal < p->nummin || objtotal > p->nummax) {
1346 		nm_prerr("requested objtotal %d out of range [%d, %d]",
1347 			objtotal, p->nummin, p->nummax);
1348 		return EINVAL;
1349 	}
1350 	/*
1351 	 * Compute number of objects using a brute-force approach:
1352 	 * given a max cluster size,
1353 	 * we try to fill it with objects keeping track of the
1354 	 * wasted space to the next page boundary.
1355 	 */
1356 	for (clustentries = 0, i = 1;; i++) {
1357 		u_int delta, used = i * objsize;
1358 		if (used > MAX_CLUSTSIZE)
1359 			break;
1360 		delta = used % PAGE_SIZE;
1361 		if (delta == 0) { // exact solution
1362 			clustentries = i;
1363 			break;
1364 		}
1365 	}
1366 	/* exact solution not found */
1367 	if (clustentries == 0) {
1368 		nm_prerr("unsupported allocation for %d bytes", objsize);
1369 		return EINVAL;
1370 	}
1371 	/* compute clustsize */
1372 	clustsize = clustentries * objsize;
1373 	if (netmap_debug & NM_DEBUG_MEM)
1374 		nm_prinf("objsize %d clustsize %d objects %d",
1375 			objsize, clustsize, clustentries);
1376 
1377 	/*
1378 	 * The number of clusters is n = ceil(objtotal/clustentries)
1379 	 * objtotal' = n * clustentries
1380 	 */
1381 	p->_clustentries = clustentries;
1382 	p->_clustsize = clustsize;
1383 	p->_numclusters = (objtotal + clustentries - 1) / clustentries;
1384 
1385 	/* actual values (may be larger than requested) */
1386 	p->_objsize = objsize;
1387 	p->_objtotal = p->_numclusters * clustentries;
1388 
1389 	return 0;
1390 }
1391 
1392 /* call with NMA_LOCK held */
1393 static int
netmap_finalize_obj_allocator(struct netmap_obj_pool * p)1394 netmap_finalize_obj_allocator(struct netmap_obj_pool *p)
1395 {
1396 	int i; /* must be signed */
1397 	size_t n;
1398 
1399 	if (p->lut) {
1400 		/* if the lut is already there we assume that also all the
1401 		 * clusters have already been allocated, possibly by somebody
1402 		 * else (e.g., extmem). In the latter case, the alloc_done flag
1403 		 * will remain at zero, so that we will not attempt to
1404 		 * deallocate the clusters by ourselves in
1405 		 * netmap_reset_obj_allocator.
1406 		 */
1407 		return 0;
1408 	}
1409 
1410 	/* optimistically assume we have enough memory */
1411 	p->numclusters = p->_numclusters;
1412 	p->objtotal = p->_objtotal;
1413 	p->alloc_done = 1;
1414 
1415 	p->lut = nm_alloc_lut(p->objtotal);
1416 	if (p->lut == NULL) {
1417 		nm_prerr("Unable to create lookup table for '%s'", p->name);
1418 		goto clean;
1419 	}
1420 
1421 	/*
1422 	 * Allocate clusters, init pointers
1423 	 */
1424 
1425 	n = p->_clustsize;
1426 	for (i = 0; i < (int)p->objtotal;) {
1427 		int lim = i + p->_clustentries;
1428 		char *clust;
1429 
1430 		/*
1431 		 * XXX Note, we only need contigmalloc() for buffers attached
1432 		 * to native interfaces. In all other cases (nifp, netmap rings
1433 		 * and even buffers for VALE ports or emulated interfaces) we
1434 		 * can live with standard malloc, because the hardware will not
1435 		 * access the pages directly.
1436 		 */
1437 		clust = contigmalloc(n, M_NETMAP, M_NOWAIT | M_ZERO,
1438 		    (size_t)0, -1UL, PAGE_SIZE, 0);
1439 		if (clust == NULL) {
1440 			/*
1441 			 * If we get here, there is a severe memory shortage,
1442 			 * so halve the allocated memory to reclaim some.
1443 			 */
1444 			nm_prerr("Unable to create cluster at %d for '%s' allocator",
1445 			    i, p->name);
1446 			if (i < 2) /* nothing to halve */
1447 				goto out;
1448 			lim = i / 2;
1449 			for (i--; i >= lim; i--) {
1450 				if (i % p->_clustentries == 0 && p->lut[i].vaddr)
1451 					contigfree(p->lut[i].vaddr,
1452 						n, M_NETMAP);
1453 				p->lut[i].vaddr = NULL;
1454 			}
1455 		out:
1456 			p->objtotal = i;
1457 			/* we may have stopped in the middle of a cluster */
1458 			p->numclusters = (i + p->_clustentries - 1) / p->_clustentries;
1459 			break;
1460 		}
1461 		/*
1462 		 * Set lut state for all buffers in the current cluster.
1463 		 *
1464 		 * [i, lim) is the set of buffer indexes that cover the
1465 		 * current cluster.
1466 		 *
1467 		 * 'clust' is really the address of the current buffer in
1468 		 * the current cluster as we index through it with a stride
1469 		 * of p->_objsize.
1470 		 */
1471 		for (; i < lim; i++, clust += p->_objsize) {
1472 			p->lut[i].vaddr = clust;
1473 #if !defined(linux) && !defined(_WIN32)
1474 			p->lut[i].paddr = vtophys(clust);
1475 #endif
1476 		}
1477 	}
1478 	p->memtotal = (size_t)p->numclusters * (size_t)p->_clustsize;
1479 	if (netmap_verbose)
1480 		nm_prinf("Pre-allocated %d clusters (%d/%zuKB) for '%s'",
1481 		    p->numclusters, p->_clustsize >> 10,
1482 		    p->memtotal >> 10, p->name);
1483 
1484 	return 0;
1485 
1486 clean:
1487 	netmap_reset_obj_allocator(p);
1488 	return ENOMEM;
1489 }
1490 
1491 /* call with lock held */
1492 static int
netmap_mem_params_changed(struct netmap_obj_params * p)1493 netmap_mem_params_changed(struct netmap_obj_params* p)
1494 {
1495 	int i, rv = 0;
1496 
1497 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1498 		if (p[i].last_size != p[i].size || p[i].last_num != p[i].num) {
1499 			p[i].last_size = p[i].size;
1500 			p[i].last_num = p[i].num;
1501 			rv = 1;
1502 		}
1503 	}
1504 	return rv;
1505 }
1506 
1507 static void
netmap_mem_reset_all(struct netmap_mem_d * nmd)1508 netmap_mem_reset_all(struct netmap_mem_d *nmd)
1509 {
1510 	int i;
1511 
1512 	if (netmap_debug & NM_DEBUG_MEM)
1513 		nm_prinf("resetting %p", nmd);
1514 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1515 		netmap_reset_obj_allocator(&nmd->pools[i]);
1516 	}
1517 	nmd->flags  &= ~NETMAP_MEM_FINALIZED;
1518 }
1519 
1520 static int
netmap_mem_unmap(struct netmap_obj_pool * p,struct netmap_adapter * na)1521 netmap_mem_unmap(struct netmap_obj_pool *p, struct netmap_adapter *na)
1522 {
1523 	int i, lim = p->objtotal;
1524 	struct netmap_lut *lut;
1525 
1526 	if (na == NULL || na->pdev == NULL)
1527 		return 0;
1528 
1529 	lut = &na->na_lut;
1530 #if defined(__FreeBSD__)
1531 	/* On FreeBSD mapping and unmapping is performed by the txsync
1532 	 * and rxsync routine, packet by packet. */
1533 	(void)i;
1534 	(void)lim;
1535 	(void)lut;
1536 #elif defined(_WIN32)
1537 	(void)i;
1538 	(void)lim;
1539 	(void)lut;
1540 	nm_prerr("unsupported on Windows");
1541 #else /* linux */
1542 	nm_prdis("unmapping and freeing plut for %s", na->name);
1543 	if (lut->plut == NULL)
1544 		return 0;
1545 	for (i = 0; i < lim; i += p->_clustentries) {
1546 		if (lut->plut[i].paddr)
1547 			netmap_unload_map(na, (bus_dma_tag_t) na->pdev, &lut->plut[i].paddr, p->_clustsize);
1548 	}
1549 	nm_free_plut(lut->plut);
1550 	lut->plut = NULL;
1551 #endif /* linux */
1552 
1553 	return 0;
1554 }
1555 
1556 static int
netmap_mem_map(struct netmap_obj_pool * p,struct netmap_adapter * na)1557 netmap_mem_map(struct netmap_obj_pool *p, struct netmap_adapter *na)
1558 {
1559 	int error = 0;
1560 	int i, lim = p->objtotal;
1561 	struct netmap_lut *lut = &na->na_lut;
1562 
1563 	if (na->pdev == NULL)
1564 		return 0;
1565 
1566 #if defined(__FreeBSD__)
1567 	/* On FreeBSD mapping and unmapping is performed by the txsync
1568 	 * and rxsync routine, packet by packet. */
1569 	(void)i;
1570 	(void)lim;
1571 	(void)lut;
1572 #elif defined(_WIN32)
1573 	(void)i;
1574 	(void)lim;
1575 	(void)lut;
1576 	nm_prerr("unsupported on Windows");
1577 #else /* linux */
1578 
1579 	if (lut->plut != NULL) {
1580 		nm_prdis("plut already allocated for %s", na->name);
1581 		return 0;
1582 	}
1583 
1584 	nm_prdis("allocating physical lut for %s", na->name);
1585 	lut->plut = nm_alloc_plut(lim);
1586 	if (lut->plut == NULL) {
1587 		nm_prerr("Failed to allocate physical lut for %s", na->name);
1588 		return ENOMEM;
1589 	}
1590 
1591 	for (i = 0; i < lim; i += p->_clustentries) {
1592 		lut->plut[i].paddr = 0;
1593 	}
1594 
1595 	for (i = 0; i < lim; i += p->_clustentries) {
1596 		int j;
1597 
1598 		if (p->lut[i].vaddr == NULL)
1599 			continue;
1600 
1601 		error = netmap_load_map(na, (bus_dma_tag_t) na->pdev, &lut->plut[i].paddr,
1602 				p->lut[i].vaddr, p->_clustsize);
1603 		if (error) {
1604 			nm_prerr("Failed to map cluster #%d from the %s pool", i, p->name);
1605 			break;
1606 		}
1607 
1608 		for (j = 1; j < p->_clustentries; j++) {
1609 			lut->plut[i + j].paddr = lut->plut[i + j - 1].paddr + p->_objsize;
1610 		}
1611 	}
1612 
1613 	if (error)
1614 		netmap_mem_unmap(p, na);
1615 
1616 #endif /* linux */
1617 
1618 	return error;
1619 }
1620 
1621 static int
netmap_mem_finalize_all(struct netmap_mem_d * nmd)1622 netmap_mem_finalize_all(struct netmap_mem_d *nmd)
1623 {
1624 	int i;
1625 	if (nmd->flags & NETMAP_MEM_FINALIZED)
1626 		return 0;
1627 	nmd->lasterr = 0;
1628 	nmd->nm_totalsize = 0;
1629 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1630 		nmd->lasterr = netmap_finalize_obj_allocator(&nmd->pools[i]);
1631 		if (nmd->lasterr)
1632 			goto error;
1633 		nmd->nm_totalsize += nmd->pools[i].memtotal;
1634 	}
1635 	nmd->lasterr = netmap_mem_init_bitmaps(nmd);
1636 	if (nmd->lasterr)
1637 		goto error;
1638 
1639 	nmd->flags |= NETMAP_MEM_FINALIZED;
1640 
1641 	if (netmap_verbose)
1642 		nm_prinf("interfaces %zd KB, rings %zd KB, buffers %zd MB",
1643 		    nmd->pools[NETMAP_IF_POOL].memtotal >> 10,
1644 		    nmd->pools[NETMAP_RING_POOL].memtotal >> 10,
1645 		    nmd->pools[NETMAP_BUF_POOL].memtotal >> 20);
1646 
1647 	if (netmap_verbose)
1648 		nm_prinf("Free buffers: %d", nmd->pools[NETMAP_BUF_POOL].objfree);
1649 
1650 
1651 	return 0;
1652 error:
1653 	netmap_mem_reset_all(nmd);
1654 	return nmd->lasterr;
1655 }
1656 
1657 /*
1658  * allocator for private memory
1659  */
1660 static void *
_netmap_mem_private_new(size_t size,struct netmap_obj_params * p,struct netmap_mem_ops * ops,int * perr)1661 _netmap_mem_private_new(size_t size, struct netmap_obj_params *p,
1662 		struct netmap_mem_ops *ops, int *perr)
1663 {
1664 	struct netmap_mem_d *d = NULL;
1665 	int i, err = 0;
1666 
1667 	d = nm_os_malloc(size);
1668 	if (d == NULL) {
1669 		err = ENOMEM;
1670 		goto error;
1671 	}
1672 
1673 	*d = nm_blueprint;
1674 	d->ops = ops;
1675 
1676 	err = nm_mem_assign_id(d);
1677 	if (err)
1678 		goto error_free;
1679 	snprintf(d->name, NM_MEM_NAMESZ, "%d", d->nm_id);
1680 
1681 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1682 		snprintf(d->pools[i].name, NETMAP_POOL_MAX_NAMSZ,
1683 				nm_blueprint.pools[i].name,
1684 				d->name);
1685 		d->params[i].num = p[i].num;
1686 		d->params[i].size = p[i].size;
1687 	}
1688 
1689 	NMA_LOCK_INIT(d);
1690 
1691 	err = netmap_mem_config(d);
1692 	if (err)
1693 		goto error_rel_id;
1694 
1695 	d->flags &= ~NETMAP_MEM_FINALIZED;
1696 
1697 	return d;
1698 
1699 error_rel_id:
1700 	NMA_LOCK_DESTROY(d);
1701 	nm_mem_release_id(d);
1702 error_free:
1703 	nm_os_free(d);
1704 error:
1705 	if (perr)
1706 		*perr = err;
1707 	return NULL;
1708 }
1709 
1710 struct netmap_mem_d *
netmap_mem_private_new(u_int txr,u_int txd,u_int rxr,u_int rxd,u_int extra_bufs,u_int npipes,int * perr)1711 netmap_mem_private_new(u_int txr, u_int txd, u_int rxr, u_int rxd,
1712 		u_int extra_bufs, u_int npipes, int *perr)
1713 {
1714 	struct netmap_mem_d *d = NULL;
1715 	struct netmap_obj_params p[NETMAP_POOLS_NR];
1716 	int i;
1717 	u_int v, maxd;
1718 	/* account for the fake host rings */
1719 	txr++;
1720 	rxr++;
1721 
1722 	/* copy the min values */
1723 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1724 		p[i] = netmap_min_priv_params[i];
1725 	}
1726 
1727 	/* possibly increase them to fit user request */
1728 	v = sizeof(struct netmap_if) + sizeof(ssize_t) * (txr + rxr);
1729 	if (p[NETMAP_IF_POOL].size < v)
1730 		p[NETMAP_IF_POOL].size = v;
1731 	v = 2 + 4 * npipes;
1732 	if (p[NETMAP_IF_POOL].num < v)
1733 		p[NETMAP_IF_POOL].num = v;
1734 	maxd = (txd > rxd) ? txd : rxd;
1735 	v = sizeof(struct netmap_ring) + sizeof(struct netmap_slot) * maxd;
1736 	if (p[NETMAP_RING_POOL].size < v)
1737 		p[NETMAP_RING_POOL].size = v;
1738 	/* each pipe endpoint needs two tx rings (1 normal + 1 host, fake)
1739 	 * and two rx rings (again, 1 normal and 1 fake host)
1740 	 */
1741 	v = txr + rxr + 8 * npipes;
1742 	if (p[NETMAP_RING_POOL].num < v)
1743 		p[NETMAP_RING_POOL].num = v;
1744 	/* for each pipe we only need the buffers for the 4 "real" rings.
1745 	 * On the other end, the pipe ring dimension may be different from
1746 	 * the parent port ring dimension. As a compromise, we allocate twice the
1747 	 * space actually needed if the pipe rings were the same size as the parent rings
1748 	 */
1749 	v = (4 * npipes + rxr) * rxd + (4 * npipes + txr) * txd + 2 + extra_bufs;
1750 		/* the +2 is for the tx and rx fake buffers (indices 0 and 1) */
1751 	if (p[NETMAP_BUF_POOL].num < v)
1752 		p[NETMAP_BUF_POOL].num = v;
1753 
1754 	if (netmap_verbose)
1755 		nm_prinf("req if %d*%d ring %d*%d buf %d*%d",
1756 			p[NETMAP_IF_POOL].num,
1757 			p[NETMAP_IF_POOL].size,
1758 			p[NETMAP_RING_POOL].num,
1759 			p[NETMAP_RING_POOL].size,
1760 			p[NETMAP_BUF_POOL].num,
1761 			p[NETMAP_BUF_POOL].size);
1762 
1763 	d = _netmap_mem_private_new(sizeof(*d), p, &netmap_mem_global_ops, perr);
1764 
1765 	return d;
1766 }
1767 
1768 
1769 /* call with lock held */
1770 static int
netmap_mem2_config(struct netmap_mem_d * nmd)1771 netmap_mem2_config(struct netmap_mem_d *nmd)
1772 {
1773 	int i;
1774 
1775 	if (!netmap_mem_params_changed(nmd->params))
1776 		goto out;
1777 
1778 	nm_prdis("reconfiguring");
1779 
1780 	if (nmd->flags & NETMAP_MEM_FINALIZED) {
1781 		/* reset previous allocation */
1782 		for (i = 0; i < NETMAP_POOLS_NR; i++) {
1783 			netmap_reset_obj_allocator(&nmd->pools[i]);
1784 		}
1785 		nmd->flags &= ~NETMAP_MEM_FINALIZED;
1786 	}
1787 
1788 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1789 		nmd->lasterr = netmap_config_obj_allocator(&nmd->pools[i],
1790 				nmd->params[i].num, nmd->params[i].size);
1791 		if (nmd->lasterr)
1792 			goto out;
1793 	}
1794 
1795 out:
1796 
1797 	return nmd->lasterr;
1798 }
1799 
1800 static int
netmap_mem2_finalize(struct netmap_mem_d * nmd)1801 netmap_mem2_finalize(struct netmap_mem_d *nmd)
1802 {
1803 	if (nmd->flags & NETMAP_MEM_FINALIZED)
1804 		goto out;
1805 
1806 	if (netmap_mem_finalize_all(nmd))
1807 		goto out;
1808 
1809 	nmd->lasterr = 0;
1810 
1811 out:
1812 	return nmd->lasterr;
1813 }
1814 
1815 static void
netmap_mem2_delete(struct netmap_mem_d * nmd)1816 netmap_mem2_delete(struct netmap_mem_d *nmd)
1817 {
1818 	int i;
1819 
1820 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
1821 	    netmap_destroy_obj_allocator(&nmd->pools[i]);
1822 	}
1823 
1824 	NMA_LOCK_DESTROY(nmd);
1825 	if (nmd != &nm_mem)
1826 		nm_os_free(nmd);
1827 }
1828 
1829 #ifdef WITH_EXTMEM
1830 /* doubly linekd list of all existing external allocators */
1831 static struct netmap_mem_ext *netmap_mem_ext_list = NULL;
1832 NM_MTX_T nm_mem_ext_list_lock;
1833 #endif /* WITH_EXTMEM */
1834 
1835 int
netmap_mem_init(void)1836 netmap_mem_init(void)
1837 {
1838 	NM_MTX_INIT(nm_mem_list_lock);
1839 	NMA_LOCK_INIT(&nm_mem);
1840 	netmap_mem_get(&nm_mem);
1841 #ifdef WITH_EXTMEM
1842 	NM_MTX_INIT(nm_mem_ext_list_lock);
1843 #endif /* WITH_EXTMEM */
1844 	return (0);
1845 }
1846 
1847 void
netmap_mem_fini(void)1848 netmap_mem_fini(void)
1849 {
1850 	netmap_mem_put(&nm_mem);
1851 }
1852 
1853 static void
netmap_free_rings(struct netmap_adapter * na)1854 netmap_free_rings(struct netmap_adapter *na)
1855 {
1856 	enum txrx t;
1857 
1858 	for_rx_tx(t) {
1859 		u_int i;
1860 		for (i = 0; i < netmap_all_rings(na, t); i++) {
1861 			struct netmap_kring *kring = NMR(na, t)[i];
1862 			struct netmap_ring *ring = kring->ring;
1863 
1864 			if (ring == NULL || kring->users > 0 || (kring->nr_kflags & NKR_NEEDRING)) {
1865 				if (netmap_debug & NM_DEBUG_MEM)
1866 					nm_prinf("NOT deleting ring %s (ring %p, users %d neekring %d)",
1867 						kring->name, ring, kring->users, kring->nr_kflags & NKR_NEEDRING);
1868 				continue;
1869 			}
1870 			if (netmap_debug & NM_DEBUG_MEM)
1871 				nm_prinf("deleting ring %s", kring->name);
1872 			if (!(kring->nr_kflags & NKR_FAKERING)) {
1873 				nm_prdis("freeing bufs for %s", kring->name);
1874 				netmap_free_bufs(na->nm_mem, ring->slot, kring->nkr_num_slots);
1875 			} else {
1876 				nm_prdis("NOT freeing bufs for %s", kring->name);
1877 			}
1878 			netmap_ring_free(na->nm_mem, ring);
1879 			kring->ring = NULL;
1880 		}
1881 	}
1882 }
1883 
1884 /* call with NMA_LOCK held *
1885  *
1886  * Allocate netmap rings and buffers for this card
1887  * The rings are contiguous, but have variable size.
1888  * The kring array must follow the layout described
1889  * in netmap_krings_create().
1890  */
1891 static int
netmap_mem2_rings_create(struct netmap_adapter * na)1892 netmap_mem2_rings_create(struct netmap_adapter *na)
1893 {
1894 	enum txrx t;
1895 
1896 	for_rx_tx(t) {
1897 		u_int i;
1898 
1899 		for (i = 0; i < netmap_all_rings(na, t); i++) {
1900 			struct netmap_kring *kring = NMR(na, t)[i];
1901 			struct netmap_ring *ring = kring->ring;
1902 			u_int len, ndesc;
1903 
1904 			if (ring || (!kring->users && !(kring->nr_kflags & NKR_NEEDRING))) {
1905 				/* unneeded, or already created by somebody else */
1906 				if (netmap_debug & NM_DEBUG_MEM)
1907 					nm_prinf("NOT creating ring %s (ring %p, users %d neekring %d)",
1908 						kring->name, ring, kring->users, kring->nr_kflags & NKR_NEEDRING);
1909 				continue;
1910 			}
1911 			if (netmap_debug & NM_DEBUG_MEM)
1912 				nm_prinf("creating %s", kring->name);
1913 			ndesc = kring->nkr_num_slots;
1914 			len = sizeof(struct netmap_ring) +
1915 				  ndesc * sizeof(struct netmap_slot);
1916 			ring = netmap_ring_malloc(na->nm_mem, len);
1917 			if (ring == NULL) {
1918 				nm_prerr("Cannot allocate %s_ring", nm_txrx2str(t));
1919 				goto cleanup;
1920 			}
1921 			nm_prdis("txring at %p", ring);
1922 			kring->ring = ring;
1923 			*(uint32_t *)(uintptr_t)&ring->num_slots = ndesc;
1924 			*(int64_t *)(uintptr_t)&ring->buf_ofs =
1925 			    (na->nm_mem->pools[NETMAP_IF_POOL].memtotal +
1926 				na->nm_mem->pools[NETMAP_RING_POOL].memtotal) -
1927 				netmap_ring_offset(na->nm_mem, ring);
1928 
1929 			/* copy values from kring */
1930 			ring->head = kring->rhead;
1931 			ring->cur = kring->rcur;
1932 			ring->tail = kring->rtail;
1933 			*(uint32_t *)(uintptr_t)&ring->nr_buf_size =
1934 				netmap_mem_bufsize(na->nm_mem);
1935 			nm_prdis("%s h %d c %d t %d", kring->name,
1936 				ring->head, ring->cur, ring->tail);
1937 			nm_prdis("initializing slots for %s_ring", nm_txrx2str(t));
1938 			if (!(kring->nr_kflags & NKR_FAKERING)) {
1939 				/* this is a real ring */
1940 				if (netmap_debug & NM_DEBUG_MEM)
1941 					nm_prinf("allocating buffers for %s", kring->name);
1942 				if (netmap_new_bufs(na->nm_mem, ring->slot, ndesc)) {
1943 					nm_prerr("Cannot allocate buffers for %s_ring", nm_txrx2str(t));
1944 					goto cleanup;
1945 				}
1946 			} else {
1947 				/* this is a fake ring, set all indices to 0 */
1948 				if (netmap_debug & NM_DEBUG_MEM)
1949 					nm_prinf("NOT allocating buffers for %s", kring->name);
1950 				netmap_mem_set_ring(na->nm_mem, ring->slot, ndesc, 0);
1951 			}
1952 		        /* ring info */
1953 		        *(uint16_t *)(uintptr_t)&ring->ringid = kring->ring_id;
1954 		        *(uint16_t *)(uintptr_t)&ring->dir = kring->tx;
1955 		}
1956 	}
1957 
1958 	return 0;
1959 
1960 cleanup:
1961 	/* we cannot actually cleanup here, since we don't own kring->users
1962 	 * and kring->nr_klags & NKR_NEEDRING. The caller must decrement
1963 	 * the first or zero-out the second, then call netmap_free_rings()
1964 	 * to do the cleanup
1965 	 */
1966 
1967 	return ENOMEM;
1968 }
1969 
1970 static void
netmap_mem2_rings_delete(struct netmap_adapter * na)1971 netmap_mem2_rings_delete(struct netmap_adapter *na)
1972 {
1973 	/* last instance, release bufs and rings */
1974 	netmap_free_rings(na);
1975 }
1976 
1977 
1978 /* call with NMA_LOCK held */
1979 /*
1980  * Allocate the per-fd structure netmap_if.
1981  *
1982  * We assume that the configuration stored in na
1983  * (number of tx/rx rings and descs) does not change while
1984  * the interface is in netmap mode.
1985  */
1986 static struct netmap_if *
netmap_mem2_if_new(struct netmap_adapter * na,struct netmap_priv_d * priv)1987 netmap_mem2_if_new(struct netmap_adapter *na, struct netmap_priv_d *priv)
1988 {
1989 	struct netmap_if *nifp;
1990 	ssize_t base; /* handy for relative offsets between rings and nifp */
1991 	u_int i, len, n[NR_TXRX], ntot;
1992 	enum txrx t;
1993 
1994 	ntot = 0;
1995 	for_rx_tx(t) {
1996 		/* account for the (eventually fake) host rings */
1997 		n[t] = netmap_all_rings(na, t);
1998 		ntot += n[t];
1999 	}
2000 	/*
2001 	 * the descriptor is followed inline by an array of offsets
2002 	 * to the tx and rx rings in the shared memory region.
2003 	 */
2004 
2005 	len = sizeof(struct netmap_if) + (ntot * sizeof(ssize_t));
2006 	nifp = netmap_if_malloc(na->nm_mem, len);
2007 	if (nifp == NULL) {
2008 		return NULL;
2009 	}
2010 
2011 	/* initialize base fields -- override const */
2012 	*(u_int *)(uintptr_t)&nifp->ni_tx_rings = na->num_tx_rings;
2013 	*(u_int *)(uintptr_t)&nifp->ni_rx_rings = na->num_rx_rings;
2014 	*(u_int *)(uintptr_t)&nifp->ni_host_tx_rings =
2015 		(na->num_host_tx_rings ? na->num_host_tx_rings : 1);
2016 	*(u_int *)(uintptr_t)&nifp->ni_host_rx_rings =
2017 		(na->num_host_rx_rings ? na->num_host_rx_rings : 1);
2018 	strlcpy(nifp->ni_name, na->name, sizeof(nifp->ni_name));
2019 
2020 	/*
2021 	 * fill the slots for the rx and tx rings. They contain the offset
2022 	 * between the ring and nifp, so the information is usable in
2023 	 * userspace to reach the ring from the nifp.
2024 	 */
2025 	base = netmap_if_offset(na->nm_mem, nifp);
2026 	for (i = 0; i < n[NR_TX]; i++) {
2027 		/* XXX instead of ofs == 0 maybe use the offset of an error
2028 		 * ring, like we do for buffers? */
2029 		ssize_t ofs = 0;
2030 
2031 		if (na->tx_rings[i]->ring != NULL && i >= priv->np_qfirst[NR_TX]
2032 				&& i < priv->np_qlast[NR_TX]) {
2033 			ofs = netmap_ring_offset(na->nm_mem,
2034 						 na->tx_rings[i]->ring) - base;
2035 		}
2036 		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] = ofs;
2037 	}
2038 	for (i = 0; i < n[NR_RX]; i++) {
2039 		/* XXX instead of ofs == 0 maybe use the offset of an error
2040 		 * ring, like we do for buffers? */
2041 		ssize_t ofs = 0;
2042 
2043 		if (na->rx_rings[i]->ring != NULL && i >= priv->np_qfirst[NR_RX]
2044 				&& i < priv->np_qlast[NR_RX]) {
2045 			ofs = netmap_ring_offset(na->nm_mem,
2046 						 na->rx_rings[i]->ring) - base;
2047 		}
2048 		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+n[NR_TX]] = ofs;
2049 	}
2050 
2051 	return (nifp);
2052 }
2053 
2054 static void
netmap_mem2_if_delete(struct netmap_adapter * na,struct netmap_if * nifp)2055 netmap_mem2_if_delete(struct netmap_adapter *na, struct netmap_if *nifp)
2056 {
2057 	if (nifp == NULL)
2058 		/* nothing to do */
2059 		return;
2060 	if (nifp->ni_bufs_head)
2061 		netmap_extra_free(na, nifp->ni_bufs_head);
2062 	netmap_if_free(na->nm_mem, nifp);
2063 }
2064 
2065 static void
netmap_mem2_deref(struct netmap_mem_d * nmd)2066 netmap_mem2_deref(struct netmap_mem_d *nmd)
2067 {
2068 
2069 	if (netmap_debug & NM_DEBUG_MEM)
2070 		nm_prinf("active = %d", nmd->active);
2071 
2072 }
2073 
2074 struct netmap_mem_ops netmap_mem_global_ops = {
2075 	.nmd_get_lut = netmap_mem2_get_lut,
2076 	.nmd_get_info = netmap_mem2_get_info,
2077 	.nmd_ofstophys = netmap_mem2_ofstophys,
2078 	.nmd_config = netmap_mem2_config,
2079 	.nmd_finalize = netmap_mem2_finalize,
2080 	.nmd_deref = netmap_mem2_deref,
2081 	.nmd_delete = netmap_mem2_delete,
2082 	.nmd_if_offset = netmap_mem2_if_offset,
2083 	.nmd_if_new = netmap_mem2_if_new,
2084 	.nmd_if_delete = netmap_mem2_if_delete,
2085 	.nmd_rings_create = netmap_mem2_rings_create,
2086 	.nmd_rings_delete = netmap_mem2_rings_delete
2087 };
2088 
2089 int
netmap_mem_pools_info_get(struct nmreq_pools_info * req,struct netmap_mem_d * nmd)2090 netmap_mem_pools_info_get(struct nmreq_pools_info *req,
2091 				struct netmap_mem_d *nmd)
2092 {
2093 	int ret;
2094 
2095 	ret = netmap_mem_get_info(nmd, &req->nr_memsize, NULL,
2096 					&req->nr_mem_id);
2097 	if (ret) {
2098 		return ret;
2099 	}
2100 
2101 	NMA_LOCK(nmd);
2102 	req->nr_if_pool_offset = 0;
2103 	req->nr_if_pool_objtotal = nmd->pools[NETMAP_IF_POOL].objtotal;
2104 	req->nr_if_pool_objsize = nmd->pools[NETMAP_IF_POOL]._objsize;
2105 
2106 	req->nr_ring_pool_offset = nmd->pools[NETMAP_IF_POOL].memtotal;
2107 	req->nr_ring_pool_objtotal = nmd->pools[NETMAP_RING_POOL].objtotal;
2108 	req->nr_ring_pool_objsize = nmd->pools[NETMAP_RING_POOL]._objsize;
2109 
2110 	req->nr_buf_pool_offset = nmd->pools[NETMAP_IF_POOL].memtotal +
2111 			     nmd->pools[NETMAP_RING_POOL].memtotal;
2112 	req->nr_buf_pool_objtotal = nmd->pools[NETMAP_BUF_POOL].objtotal;
2113 	req->nr_buf_pool_objsize = nmd->pools[NETMAP_BUF_POOL]._objsize;
2114 	NMA_UNLOCK(nmd);
2115 
2116 	return 0;
2117 }
2118 
2119 #ifdef WITH_EXTMEM
2120 struct netmap_mem_ext {
2121 	struct netmap_mem_d up;
2122 
2123 	struct nm_os_extmem *os;
2124 	struct netmap_mem_ext *next, *prev;
2125 };
2126 
2127 /* call with nm_mem_list_lock held */
2128 static void
netmap_mem_ext_register(struct netmap_mem_ext * e)2129 netmap_mem_ext_register(struct netmap_mem_ext *e)
2130 {
2131 	NM_MTX_LOCK(nm_mem_ext_list_lock);
2132 	if (netmap_mem_ext_list)
2133 		netmap_mem_ext_list->prev = e;
2134 	e->next = netmap_mem_ext_list;
2135 	netmap_mem_ext_list = e;
2136 	e->prev = NULL;
2137 	NM_MTX_UNLOCK(nm_mem_ext_list_lock);
2138 }
2139 
2140 /* call with nm_mem_list_lock held */
2141 static void
netmap_mem_ext_unregister(struct netmap_mem_ext * e)2142 netmap_mem_ext_unregister(struct netmap_mem_ext *e)
2143 {
2144 	if (e->prev)
2145 		e->prev->next = e->next;
2146 	else
2147 		netmap_mem_ext_list = e->next;
2148 	if (e->next)
2149 		e->next->prev = e->prev;
2150 	e->prev = e->next = NULL;
2151 }
2152 
2153 static struct netmap_mem_ext *
netmap_mem_ext_search(struct nm_os_extmem * os)2154 netmap_mem_ext_search(struct nm_os_extmem *os)
2155 {
2156 	struct netmap_mem_ext *e;
2157 
2158 	NM_MTX_LOCK(nm_mem_ext_list_lock);
2159 	for (e = netmap_mem_ext_list; e; e = e->next) {
2160 		if (nm_os_extmem_isequal(e->os, os)) {
2161 			netmap_mem_get(&e->up);
2162 			break;
2163 		}
2164 	}
2165 	NM_MTX_UNLOCK(nm_mem_ext_list_lock);
2166 	return e;
2167 }
2168 
2169 
2170 static void
netmap_mem_ext_delete(struct netmap_mem_d * d)2171 netmap_mem_ext_delete(struct netmap_mem_d *d)
2172 {
2173 	int i;
2174 	struct netmap_mem_ext *e =
2175 		(struct netmap_mem_ext *)d;
2176 
2177 	netmap_mem_ext_unregister(e);
2178 
2179 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
2180 		struct netmap_obj_pool *p = &d->pools[i];
2181 
2182 		if (p->lut) {
2183 			nm_free_lut(p->lut, p->objtotal);
2184 			p->lut = NULL;
2185 		}
2186 	}
2187 	if (e->os)
2188 		nm_os_extmem_delete(e->os);
2189 	netmap_mem2_delete(d);
2190 }
2191 
2192 static int
netmap_mem_ext_config(struct netmap_mem_d * nmd)2193 netmap_mem_ext_config(struct netmap_mem_d *nmd)
2194 {
2195 	return 0;
2196 }
2197 
2198 struct netmap_mem_ops netmap_mem_ext_ops = {
2199 	.nmd_get_lut = netmap_mem2_get_lut,
2200 	.nmd_get_info = netmap_mem2_get_info,
2201 	.nmd_ofstophys = netmap_mem2_ofstophys,
2202 	.nmd_config = netmap_mem_ext_config,
2203 	.nmd_finalize = netmap_mem2_finalize,
2204 	.nmd_deref = netmap_mem2_deref,
2205 	.nmd_delete = netmap_mem_ext_delete,
2206 	.nmd_if_offset = netmap_mem2_if_offset,
2207 	.nmd_if_new = netmap_mem2_if_new,
2208 	.nmd_if_delete = netmap_mem2_if_delete,
2209 	.nmd_rings_create = netmap_mem2_rings_create,
2210 	.nmd_rings_delete = netmap_mem2_rings_delete
2211 };
2212 
2213 struct netmap_mem_d *
netmap_mem_ext_create(uint64_t usrptr,struct nmreq_pools_info * pi,int * perror)2214 netmap_mem_ext_create(uint64_t usrptr, struct nmreq_pools_info *pi, int *perror)
2215 {
2216 	int error = 0;
2217 	int i, j;
2218 	struct netmap_mem_ext *nme;
2219 	char *clust;
2220 	size_t off;
2221 	struct nm_os_extmem *os = NULL;
2222 	int nr_pages;
2223 
2224 	// XXX sanity checks
2225 	if (pi->nr_if_pool_objtotal == 0)
2226 		pi->nr_if_pool_objtotal = netmap_min_priv_params[NETMAP_IF_POOL].num;
2227 	if (pi->nr_if_pool_objsize == 0)
2228 		pi->nr_if_pool_objsize = netmap_min_priv_params[NETMAP_IF_POOL].size;
2229 	if (pi->nr_ring_pool_objtotal == 0)
2230 		pi->nr_ring_pool_objtotal = netmap_min_priv_params[NETMAP_RING_POOL].num;
2231 	if (pi->nr_ring_pool_objsize == 0)
2232 		pi->nr_ring_pool_objsize = netmap_min_priv_params[NETMAP_RING_POOL].size;
2233 	if (pi->nr_buf_pool_objtotal == 0)
2234 		pi->nr_buf_pool_objtotal = netmap_min_priv_params[NETMAP_BUF_POOL].num;
2235 	if (pi->nr_buf_pool_objsize == 0)
2236 		pi->nr_buf_pool_objsize = netmap_min_priv_params[NETMAP_BUF_POOL].size;
2237 	if (netmap_verbose & NM_DEBUG_MEM)
2238 		nm_prinf("if %d %d ring %d %d buf %d %d",
2239 			pi->nr_if_pool_objtotal, pi->nr_if_pool_objsize,
2240 			pi->nr_ring_pool_objtotal, pi->nr_ring_pool_objsize,
2241 			pi->nr_buf_pool_objtotal, pi->nr_buf_pool_objsize);
2242 
2243 	os = nm_os_extmem_create(usrptr, pi, &error);
2244 	if (os == NULL) {
2245 		nm_prerr("os extmem creation failed");
2246 		goto out;
2247 	}
2248 
2249 	nme = netmap_mem_ext_search(os);
2250 	if (nme) {
2251 		nm_os_extmem_delete(os);
2252 		return &nme->up;
2253 	}
2254 	if (netmap_verbose & NM_DEBUG_MEM)
2255 		nm_prinf("not found, creating new");
2256 
2257 	nme = _netmap_mem_private_new(sizeof(*nme),
2258 			(struct netmap_obj_params[]){
2259 				{ pi->nr_if_pool_objsize, pi->nr_if_pool_objtotal },
2260 				{ pi->nr_ring_pool_objsize, pi->nr_ring_pool_objtotal },
2261 				{ pi->nr_buf_pool_objsize, pi->nr_buf_pool_objtotal }},
2262 			&netmap_mem_ext_ops,
2263 			&error);
2264 	if (nme == NULL)
2265 		goto out_unmap;
2266 
2267 	nr_pages = nm_os_extmem_nr_pages(os);
2268 
2269 	/* from now on pages will be released by nme destructor;
2270 	 * we let res = 0 to prevent release in out_unmap below
2271 	 */
2272 	nme->os = os;
2273 	os = NULL; /* pass ownership */
2274 
2275 	clust = nm_os_extmem_nextpage(nme->os);
2276 	off = 0;
2277 	for (i = 0; i < NETMAP_POOLS_NR; i++) {
2278 		struct netmap_obj_pool *p = &nme->up.pools[i];
2279 		struct netmap_obj_params *o = &nme->up.params[i];
2280 
2281 		p->_objsize = o->size;
2282 		p->_clustsize = o->size;
2283 		p->_clustentries = 1;
2284 
2285 		p->lut = nm_alloc_lut(o->num);
2286 		if (p->lut == NULL) {
2287 			error = ENOMEM;
2288 			goto out_delete;
2289 		}
2290 
2291 		p->bitmap_slots = (o->num + sizeof(uint32_t) - 1) / sizeof(uint32_t);
2292 		p->invalid_bitmap = nm_os_malloc(sizeof(uint32_t) * p->bitmap_slots);
2293 		if (p->invalid_bitmap == NULL) {
2294 			error = ENOMEM;
2295 			goto out_delete;
2296 		}
2297 
2298 		if (nr_pages == 0) {
2299 			p->objtotal = 0;
2300 			p->memtotal = 0;
2301 			p->objfree = 0;
2302 			continue;
2303 		}
2304 
2305 		for (j = 0; j < o->num && nr_pages > 0; j++) {
2306 			size_t noff;
2307 
2308 			p->lut[j].vaddr = clust + off;
2309 #if !defined(linux) && !defined(_WIN32)
2310 			p->lut[j].paddr = vtophys(p->lut[j].vaddr);
2311 #endif
2312 			nm_prdis("%s %d at %p", p->name, j, p->lut[j].vaddr);
2313 			noff = off + p->_objsize;
2314 			if (noff < PAGE_SIZE) {
2315 				off = noff;
2316 				continue;
2317 			}
2318 			nm_prdis("too big, recomputing offset...");
2319 			while (noff >= PAGE_SIZE) {
2320 				char *old_clust = clust;
2321 				noff -= PAGE_SIZE;
2322 				clust = nm_os_extmem_nextpage(nme->os);
2323 				nr_pages--;
2324 				nm_prdis("noff %zu page %p nr_pages %d", noff,
2325 						page_to_virt(*pages), nr_pages);
2326 				if (noff > 0 && !nm_isset(p->invalid_bitmap, j) &&
2327 					(nr_pages == 0 ||
2328 					 old_clust + PAGE_SIZE != clust))
2329 				{
2330 					/* out of space or non contiguous,
2331 					 * drop this object
2332 					 * */
2333 					p->invalid_bitmap[ (j>>5) ] |= 1U << (j & 31U);
2334 					nm_prdis("non contiguous at off %zu, drop", noff);
2335 				}
2336 				if (nr_pages == 0)
2337 					break;
2338 			}
2339 			off = noff;
2340 		}
2341 		p->objtotal = j;
2342 		p->numclusters = p->objtotal;
2343 		p->memtotal = j * (size_t)p->_objsize;
2344 		nm_prdis("%d memtotal %zu", j, p->memtotal);
2345 	}
2346 
2347 	netmap_mem_ext_register(nme);
2348 
2349 	return &nme->up;
2350 
2351 out_delete:
2352 	netmap_mem_put(&nme->up);
2353 out_unmap:
2354 	if (os)
2355 		nm_os_extmem_delete(os);
2356 out:
2357 	if (perror)
2358 		*perror = error;
2359 	return NULL;
2360 
2361 }
2362 #endif /* WITH_EXTMEM */
2363 
2364 
2365 #ifdef WITH_PTNETMAP
2366 struct mem_pt_if {
2367 	struct mem_pt_if *next;
2368 	struct ifnet *ifp;
2369 	unsigned int nifp_offset;
2370 };
2371 
2372 /* Netmap allocator for ptnetmap guests. */
2373 struct netmap_mem_ptg {
2374 	struct netmap_mem_d up;
2375 
2376 	vm_paddr_t nm_paddr;            /* physical address in the guest */
2377 	void *nm_addr;                  /* virtual address in the guest */
2378 	struct netmap_lut buf_lut;      /* lookup table for BUF pool in the guest */
2379 	nm_memid_t host_mem_id;         /* allocator identifier in the host */
2380 	struct ptnetmap_memdev *ptn_dev;/* ptnetmap memdev */
2381 	struct mem_pt_if *pt_ifs;	/* list of interfaces in passthrough */
2382 };
2383 
2384 /* Link a passthrough interface to a passthrough netmap allocator. */
2385 static int
netmap_mem_pt_guest_ifp_add(struct netmap_mem_d * nmd,struct ifnet * ifp,unsigned int nifp_offset)2386 netmap_mem_pt_guest_ifp_add(struct netmap_mem_d *nmd, struct ifnet *ifp,
2387 			    unsigned int nifp_offset)
2388 {
2389 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2390 	struct mem_pt_if *ptif = nm_os_malloc(sizeof(*ptif));
2391 
2392 	if (!ptif) {
2393 		return ENOMEM;
2394 	}
2395 
2396 	NMA_LOCK(nmd);
2397 
2398 	ptif->ifp = ifp;
2399 	ptif->nifp_offset = nifp_offset;
2400 
2401 	if (ptnmd->pt_ifs) {
2402 		ptif->next = ptnmd->pt_ifs;
2403 	}
2404 	ptnmd->pt_ifs = ptif;
2405 
2406 	NMA_UNLOCK(nmd);
2407 
2408 	nm_prinf("ifp=%s,nifp_offset=%u",
2409 		ptif->ifp->if_xname, ptif->nifp_offset);
2410 
2411 	return 0;
2412 }
2413 
2414 /* Called with NMA_LOCK(nmd) held. */
2415 static struct mem_pt_if *
netmap_mem_pt_guest_ifp_lookup(struct netmap_mem_d * nmd,struct ifnet * ifp)2416 netmap_mem_pt_guest_ifp_lookup(struct netmap_mem_d *nmd, struct ifnet *ifp)
2417 {
2418 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2419 	struct mem_pt_if *curr;
2420 
2421 	for (curr = ptnmd->pt_ifs; curr; curr = curr->next) {
2422 		if (curr->ifp == ifp) {
2423 			return curr;
2424 		}
2425 	}
2426 
2427 	return NULL;
2428 }
2429 
2430 /* Unlink a passthrough interface from a passthrough netmap allocator. */
2431 int
netmap_mem_pt_guest_ifp_del(struct netmap_mem_d * nmd,struct ifnet * ifp)2432 netmap_mem_pt_guest_ifp_del(struct netmap_mem_d *nmd, struct ifnet *ifp)
2433 {
2434 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2435 	struct mem_pt_if *prev = NULL;
2436 	struct mem_pt_if *curr;
2437 	int ret = -1;
2438 
2439 	NMA_LOCK(nmd);
2440 
2441 	for (curr = ptnmd->pt_ifs; curr; curr = curr->next) {
2442 		if (curr->ifp == ifp) {
2443 			if (prev) {
2444 				prev->next = curr->next;
2445 			} else {
2446 				ptnmd->pt_ifs = curr->next;
2447 			}
2448 			nm_prinf("removed (ifp=%s,nifp_offset=%u)",
2449 			  curr->ifp->if_xname, curr->nifp_offset);
2450 			nm_os_free(curr);
2451 			ret = 0;
2452 			break;
2453 		}
2454 		prev = curr;
2455 	}
2456 
2457 	NMA_UNLOCK(nmd);
2458 
2459 	return ret;
2460 }
2461 
2462 static int
netmap_mem_pt_guest_get_lut(struct netmap_mem_d * nmd,struct netmap_lut * lut)2463 netmap_mem_pt_guest_get_lut(struct netmap_mem_d *nmd, struct netmap_lut *lut)
2464 {
2465 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2466 
2467 	if (!(nmd->flags & NETMAP_MEM_FINALIZED)) {
2468 		return EINVAL;
2469 	}
2470 
2471 	*lut = ptnmd->buf_lut;
2472 	return 0;
2473 }
2474 
2475 static int
netmap_mem_pt_guest_get_info(struct netmap_mem_d * nmd,uint64_t * size,u_int * memflags,uint16_t * id)2476 netmap_mem_pt_guest_get_info(struct netmap_mem_d *nmd, uint64_t *size,
2477 			     u_int *memflags, uint16_t *id)
2478 {
2479 	int error = 0;
2480 
2481 	error = nmd->ops->nmd_config(nmd);
2482 	if (error)
2483 		goto out;
2484 
2485 	if (size)
2486 		*size = nmd->nm_totalsize;
2487 	if (memflags)
2488 		*memflags = nmd->flags;
2489 	if (id)
2490 		*id = nmd->nm_id;
2491 
2492 out:
2493 
2494 	return error;
2495 }
2496 
2497 static vm_paddr_t
netmap_mem_pt_guest_ofstophys(struct netmap_mem_d * nmd,vm_ooffset_t off)2498 netmap_mem_pt_guest_ofstophys(struct netmap_mem_d *nmd, vm_ooffset_t off)
2499 {
2500 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2501 	vm_paddr_t paddr;
2502 	/* if the offset is valid, just return csb->base_addr + off */
2503 	paddr = (vm_paddr_t)(ptnmd->nm_paddr + off);
2504 	nm_prdis("off %lx padr %lx", off, (unsigned long)paddr);
2505 	return paddr;
2506 }
2507 
2508 static int
netmap_mem_pt_guest_config(struct netmap_mem_d * nmd)2509 netmap_mem_pt_guest_config(struct netmap_mem_d *nmd)
2510 {
2511 	/* nothing to do, we are configured on creation
2512 	 * and configuration never changes thereafter
2513 	 */
2514 	return 0;
2515 }
2516 
2517 static int
netmap_mem_pt_guest_finalize(struct netmap_mem_d * nmd)2518 netmap_mem_pt_guest_finalize(struct netmap_mem_d *nmd)
2519 {
2520 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2521 	uint64_t mem_size;
2522 	uint32_t bufsize;
2523 	uint32_t nbuffers;
2524 	uint32_t poolofs;
2525 	vm_paddr_t paddr;
2526 	char *vaddr;
2527 	int i;
2528 	int error = 0;
2529 
2530 	if (nmd->flags & NETMAP_MEM_FINALIZED)
2531 		goto out;
2532 
2533 	if (ptnmd->ptn_dev == NULL) {
2534 		nm_prerr("ptnetmap memdev not attached");
2535 		error = ENOMEM;
2536 		goto out;
2537 	}
2538 	/* Map memory through ptnetmap-memdev BAR. */
2539 	error = nm_os_pt_memdev_iomap(ptnmd->ptn_dev, &ptnmd->nm_paddr,
2540 				      &ptnmd->nm_addr, &mem_size);
2541 	if (error)
2542 		goto out;
2543 
2544 	/* Initialize the lut using the information contained in the
2545 	 * ptnetmap memory device. */
2546 	bufsize = nm_os_pt_memdev_ioread(ptnmd->ptn_dev,
2547 					 PTNET_MDEV_IO_BUF_POOL_OBJSZ);
2548 	nbuffers = nm_os_pt_memdev_ioread(ptnmd->ptn_dev,
2549 					 PTNET_MDEV_IO_BUF_POOL_OBJNUM);
2550 
2551 	/* allocate the lut */
2552 	if (ptnmd->buf_lut.lut == NULL) {
2553 		nm_prinf("allocating lut");
2554 		ptnmd->buf_lut.lut = nm_alloc_lut(nbuffers);
2555 		if (ptnmd->buf_lut.lut == NULL) {
2556 			nm_prerr("lut allocation failed");
2557 			return ENOMEM;
2558 		}
2559 	}
2560 
2561 	/* we have physically contiguous memory mapped through PCI BAR */
2562 	poolofs = nm_os_pt_memdev_ioread(ptnmd->ptn_dev,
2563 					 PTNET_MDEV_IO_BUF_POOL_OFS);
2564 	vaddr = (char *)(ptnmd->nm_addr) + poolofs;
2565 	paddr = ptnmd->nm_paddr + poolofs;
2566 
2567 	for (i = 0; i < nbuffers; i++) {
2568 		ptnmd->buf_lut.lut[i].vaddr = vaddr;
2569 		vaddr += bufsize;
2570 		paddr += bufsize;
2571 	}
2572 
2573 	ptnmd->buf_lut.objtotal = nbuffers;
2574 	ptnmd->buf_lut.objsize = bufsize;
2575 	nmd->nm_totalsize = mem_size;
2576 
2577 	/* Initialize these fields as are needed by
2578 	 * netmap_mem_bufsize().
2579 	 * XXX please improve this, why do we need this
2580 	 * replication? maybe we nmd->pools[] should no be
2581 	 * there for the guest allocator? */
2582 	nmd->pools[NETMAP_BUF_POOL]._objsize = bufsize;
2583 	nmd->pools[NETMAP_BUF_POOL]._objtotal = nbuffers;
2584 
2585 	nmd->flags |= NETMAP_MEM_FINALIZED;
2586 out:
2587 	return error;
2588 }
2589 
2590 static void
netmap_mem_pt_guest_deref(struct netmap_mem_d * nmd)2591 netmap_mem_pt_guest_deref(struct netmap_mem_d *nmd)
2592 {
2593 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2594 
2595 	if (nmd->active == 1 &&
2596 		(nmd->flags & NETMAP_MEM_FINALIZED)) {
2597 	    nmd->flags  &= ~NETMAP_MEM_FINALIZED;
2598 	    /* unmap ptnetmap-memdev memory */
2599 	    if (ptnmd->ptn_dev) {
2600 		nm_os_pt_memdev_iounmap(ptnmd->ptn_dev);
2601 	    }
2602 	    ptnmd->nm_addr = NULL;
2603 	    ptnmd->nm_paddr = 0;
2604 	}
2605 }
2606 
2607 static ssize_t
netmap_mem_pt_guest_if_offset(struct netmap_mem_d * nmd,const void * vaddr)2608 netmap_mem_pt_guest_if_offset(struct netmap_mem_d *nmd, const void *vaddr)
2609 {
2610 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)nmd;
2611 
2612 	return (const char *)(vaddr) - (char *)(ptnmd->nm_addr);
2613 }
2614 
2615 static void
netmap_mem_pt_guest_delete(struct netmap_mem_d * nmd)2616 netmap_mem_pt_guest_delete(struct netmap_mem_d *nmd)
2617 {
2618 	if (nmd == NULL)
2619 		return;
2620 	if (netmap_verbose)
2621 		nm_prinf("deleting %p", nmd);
2622 	if (nmd->active > 0)
2623 		nm_prerr("bug: deleting mem allocator with active=%d!", nmd->active);
2624 	if (netmap_verbose)
2625 		nm_prinf("done deleting %p", nmd);
2626 	NMA_LOCK_DESTROY(nmd);
2627 	nm_os_free(nmd);
2628 }
2629 
2630 static struct netmap_if *
netmap_mem_pt_guest_if_new(struct netmap_adapter * na,struct netmap_priv_d * priv)2631 netmap_mem_pt_guest_if_new(struct netmap_adapter *na, struct netmap_priv_d *priv)
2632 {
2633 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)na->nm_mem;
2634 	struct mem_pt_if *ptif;
2635 	struct netmap_if *nifp = NULL;
2636 
2637 	ptif = netmap_mem_pt_guest_ifp_lookup(na->nm_mem, na->ifp);
2638 	if (ptif == NULL) {
2639 		nm_prerr("interface %s is not in passthrough", na->name);
2640 		goto out;
2641 	}
2642 
2643 	nifp = (struct netmap_if *)((char *)(ptnmd->nm_addr) +
2644 				    ptif->nifp_offset);
2645 out:
2646 	return nifp;
2647 }
2648 
2649 static void
netmap_mem_pt_guest_if_delete(struct netmap_adapter * na,struct netmap_if * nifp)2650 netmap_mem_pt_guest_if_delete(struct netmap_adapter *na, struct netmap_if *nifp)
2651 {
2652 	struct mem_pt_if *ptif;
2653 
2654 	ptif = netmap_mem_pt_guest_ifp_lookup(na->nm_mem, na->ifp);
2655 	if (ptif == NULL) {
2656 		nm_prerr("interface %s is not in passthrough", na->name);
2657 	}
2658 }
2659 
2660 static int
netmap_mem_pt_guest_rings_create(struct netmap_adapter * na)2661 netmap_mem_pt_guest_rings_create(struct netmap_adapter *na)
2662 {
2663 	struct netmap_mem_ptg *ptnmd = (struct netmap_mem_ptg *)na->nm_mem;
2664 	struct mem_pt_if *ptif;
2665 	struct netmap_if *nifp;
2666 	int i, error = -1;
2667 
2668 	ptif = netmap_mem_pt_guest_ifp_lookup(na->nm_mem, na->ifp);
2669 	if (ptif == NULL) {
2670 		nm_prerr("interface %s is not in passthrough", na->name);
2671 		goto out;
2672 	}
2673 
2674 
2675 	/* point each kring to the corresponding backend ring */
2676 	nifp = (struct netmap_if *)((char *)ptnmd->nm_addr + ptif->nifp_offset);
2677 	for (i = 0; i < netmap_all_rings(na, NR_TX); i++) {
2678 		struct netmap_kring *kring = na->tx_rings[i];
2679 		if (kring->ring)
2680 			continue;
2681 		kring->ring = (struct netmap_ring *)
2682 			((char *)nifp + nifp->ring_ofs[i]);
2683 	}
2684 	for (i = 0; i < netmap_all_rings(na, NR_RX); i++) {
2685 		struct netmap_kring *kring = na->rx_rings[i];
2686 		if (kring->ring)
2687 			continue;
2688 		kring->ring = (struct netmap_ring *)
2689 			((char *)nifp +
2690 			 nifp->ring_ofs[netmap_all_rings(na, NR_TX) + i]);
2691 	}
2692 
2693 	error = 0;
2694 out:
2695 	return error;
2696 }
2697 
2698 static void
netmap_mem_pt_guest_rings_delete(struct netmap_adapter * na)2699 netmap_mem_pt_guest_rings_delete(struct netmap_adapter *na)
2700 {
2701 #if 0
2702 	enum txrx t;
2703 
2704 	for_rx_tx(t) {
2705 		u_int i;
2706 		for (i = 0; i < nma_get_nrings(na, t) + 1; i++) {
2707 			struct netmap_kring *kring = &NMR(na, t)[i];
2708 
2709 			kring->ring = NULL;
2710 		}
2711 	}
2712 #endif
2713 }
2714 
2715 static struct netmap_mem_ops netmap_mem_pt_guest_ops = {
2716 	.nmd_get_lut = netmap_mem_pt_guest_get_lut,
2717 	.nmd_get_info = netmap_mem_pt_guest_get_info,
2718 	.nmd_ofstophys = netmap_mem_pt_guest_ofstophys,
2719 	.nmd_config = netmap_mem_pt_guest_config,
2720 	.nmd_finalize = netmap_mem_pt_guest_finalize,
2721 	.nmd_deref = netmap_mem_pt_guest_deref,
2722 	.nmd_if_offset = netmap_mem_pt_guest_if_offset,
2723 	.nmd_delete = netmap_mem_pt_guest_delete,
2724 	.nmd_if_new = netmap_mem_pt_guest_if_new,
2725 	.nmd_if_delete = netmap_mem_pt_guest_if_delete,
2726 	.nmd_rings_create = netmap_mem_pt_guest_rings_create,
2727 	.nmd_rings_delete = netmap_mem_pt_guest_rings_delete
2728 };
2729 
2730 /* Called with nm_mem_list_lock held. */
2731 static struct netmap_mem_d *
netmap_mem_pt_guest_find_memid(nm_memid_t mem_id)2732 netmap_mem_pt_guest_find_memid(nm_memid_t mem_id)
2733 {
2734 	struct netmap_mem_d *mem = NULL;
2735 	struct netmap_mem_d *scan = netmap_last_mem_d;
2736 
2737 	do {
2738 		/* find ptnetmap allocator through host ID */
2739 		if (scan->ops->nmd_deref == netmap_mem_pt_guest_deref &&
2740 			((struct netmap_mem_ptg *)(scan))->host_mem_id == mem_id) {
2741 			mem = scan;
2742 			mem->refcount++;
2743 			NM_DBG_REFC(mem, __FUNCTION__, __LINE__);
2744 			break;
2745 		}
2746 		scan = scan->next;
2747 	} while (scan != netmap_last_mem_d);
2748 
2749 	return mem;
2750 }
2751 
2752 /* Called with nm_mem_list_lock held. */
2753 static struct netmap_mem_d *
netmap_mem_pt_guest_create(nm_memid_t mem_id)2754 netmap_mem_pt_guest_create(nm_memid_t mem_id)
2755 {
2756 	struct netmap_mem_ptg *ptnmd;
2757 	int err = 0;
2758 
2759 	ptnmd = nm_os_malloc(sizeof(struct netmap_mem_ptg));
2760 	if (ptnmd == NULL) {
2761 		err = ENOMEM;
2762 		goto error;
2763 	}
2764 
2765 	ptnmd->up.ops = &netmap_mem_pt_guest_ops;
2766 	ptnmd->host_mem_id = mem_id;
2767 	ptnmd->pt_ifs = NULL;
2768 
2769 	/* Assign new id in the guest (We have the lock) */
2770 	err = nm_mem_assign_id_locked(&ptnmd->up);
2771 	if (err)
2772 		goto error;
2773 
2774 	ptnmd->up.flags &= ~NETMAP_MEM_FINALIZED;
2775 	ptnmd->up.flags |= NETMAP_MEM_IO;
2776 
2777 	NMA_LOCK_INIT(&ptnmd->up);
2778 
2779 	snprintf(ptnmd->up.name, NM_MEM_NAMESZ, "%d", ptnmd->up.nm_id);
2780 
2781 
2782 	return &ptnmd->up;
2783 error:
2784 	netmap_mem_pt_guest_delete(&ptnmd->up);
2785 	return NULL;
2786 }
2787 
2788 /*
2789  * find host id in guest allocators and create guest allocator
2790  * if it is not there
2791  */
2792 static struct netmap_mem_d *
netmap_mem_pt_guest_get(nm_memid_t mem_id)2793 netmap_mem_pt_guest_get(nm_memid_t mem_id)
2794 {
2795 	struct netmap_mem_d *nmd;
2796 
2797 	NM_MTX_LOCK(nm_mem_list_lock);
2798 	nmd = netmap_mem_pt_guest_find_memid(mem_id);
2799 	if (nmd == NULL) {
2800 		nmd = netmap_mem_pt_guest_create(mem_id);
2801 	}
2802 	NM_MTX_UNLOCK(nm_mem_list_lock);
2803 
2804 	return nmd;
2805 }
2806 
2807 /*
2808  * The guest allocator can be created by ptnetmap_memdev (during the device
2809  * attach) or by ptnetmap device (ptnet), during the netmap_attach.
2810  *
2811  * The order is not important (we have different order in LINUX and FreeBSD).
2812  * The first one, creates the device, and the second one simply attaches it.
2813  */
2814 
2815 /* Called when ptnetmap_memdev is attaching, to attach a new allocator in
2816  * the guest */
2817 struct netmap_mem_d *
netmap_mem_pt_guest_attach(struct ptnetmap_memdev * ptn_dev,nm_memid_t mem_id)2818 netmap_mem_pt_guest_attach(struct ptnetmap_memdev *ptn_dev, nm_memid_t mem_id)
2819 {
2820 	struct netmap_mem_d *nmd;
2821 	struct netmap_mem_ptg *ptnmd;
2822 
2823 	nmd = netmap_mem_pt_guest_get(mem_id);
2824 
2825 	/* assign this device to the guest allocator */
2826 	if (nmd) {
2827 		ptnmd = (struct netmap_mem_ptg *)nmd;
2828 		ptnmd->ptn_dev = ptn_dev;
2829 	}
2830 
2831 	return nmd;
2832 }
2833 
2834 /* Called when ptnet device is attaching */
2835 struct netmap_mem_d *
netmap_mem_pt_guest_new(struct ifnet * ifp,unsigned int nifp_offset,unsigned int memid)2836 netmap_mem_pt_guest_new(struct ifnet *ifp,
2837 			unsigned int nifp_offset,
2838 			unsigned int memid)
2839 {
2840 	struct netmap_mem_d *nmd;
2841 
2842 	if (ifp == NULL) {
2843 		return NULL;
2844 	}
2845 
2846 	nmd = netmap_mem_pt_guest_get((nm_memid_t)memid);
2847 
2848 	if (nmd) {
2849 		netmap_mem_pt_guest_ifp_add(nmd, ifp, nifp_offset);
2850 	}
2851 
2852 	return nmd;
2853 }
2854 
2855 #endif /* WITH_PTNETMAP */
2856