Home | History | Annotate | Line # | Download | only in npf
npf_portmap.c revision 1.2
      1 /*-
      2  * Copyright (c) 2019 Mindaugas Rasiukevicius <rmind at noxt eu>
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  *
     14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     24  * SUCH DAMAGE.
     25  */
     26 
     27 /*
     28  * NPF port map mechanism.
     29  *
     30  *	The port map is a bitmap used to track TCP/UDP ports used for
     31  *	translation.  Port maps are per IP addresses, therefore multiple
     32  *	NAT policies operating on the same IP address will share the
     33  *	same port map.
     34  */
     35 
     36 #ifdef _KERNEL
     37 #include <sys/cdefs.h>
     38 __KERNEL_RCSID(0, "$NetBSD: npf_portmap.c,v 1.2 2019/07/23 08:25:52 rmind Exp $");
     39 
     40 #include <sys/param.h>
     41 #include <sys/types.h>
     42 
     43 #include <sys/atomic.h>
     44 #include <sys/bitops.h>
     45 #include <sys/kmem.h>
     46 #include <sys/mutex.h>
     47 #include <sys/cprng.h>
     48 #include <sys/thmap.h>
     49 #endif
     50 
     51 #include "npf_impl.h"
     52 
     53 /*
     54  * Port map uses two-level bitmaps with compression to efficiently
     55  * represent the maximum of 65536 (2^16) values.
     56  *
     57  * Level 0: 64 chunks each representing 1048 bits in two modes:
     58  *
     59  *	a) If PORTMAP_L1_TAG, then up to 5 values are packed in the
     60  *	64-bit integer using 12 bits for each value, starting from the
     61  *	most significant bits.  The four 4 least significant bits are
     62  *	unused or reserved for pointer tagging.
     63  *
     64  *	b) If there are more than 5 values, then PORTMAP_L1_TAG is set
     65  *	and the value serves as a pointer to the second level bitmap.
     66  *
     67  * Level 1: 16 chunks each representing 64 bits in plain uint64_t.
     68  */
     69 
     70 #define	PORTMAP_MAX_BITS	(65536U)
     71 #define	PORTMAP_MASK		(PORTMAP_MAX_BITS - 1)
     72 
     73 #define	PORTMAP_L0_SHIFT	(10) // or 11
     74 #define	PORTMAP_L0_MASK		((1U << PORTMAP_L0_SHIFT) - 1)
     75 #define	PORTMAP_L0_WORDS	(PORTMAP_MAX_BITS >> PORTMAP_L0_SHIFT)
     76 
     77 #define	PORTMAP_L1_SHIFT	(6)
     78 #define	PORTMAP_L1_MASK		((1U << PORTMAP_L1_SHIFT) - 1)
     79 #define	PORTMAP_L1_WORDS	\
     80     ((PORTMAP_MAX_BITS / PORTMAP_L0_WORDS) >> PORTMAP_L1_SHIFT)
     81 
     82 #define	PORTMAP_L1_TAG		(UINT64_C(1)) // use level 1
     83 #define	PORTMAP_L1_GET(p)	((void *)((uintptr_t)(p) & ~(uintptr_t)3))
     84 
     85 CTASSERT(sizeof(uint64_t) >= sizeof(uintptr_t));
     86 
     87 typedef struct {
     88 	volatile uint64_t	bits1[PORTMAP_L1_WORDS];
     89 } bitmap_l1_t;
     90 
     91 typedef struct bitmap {
     92 	npf_addr_t		addr;
     93 	volatile uint64_t	bits0[PORTMAP_L0_WORDS];
     94 	LIST_ENTRY(bitmap)	entry;
     95 	unsigned		addr_len;
     96 } bitmap_t;
     97 
     98 struct npf_portmap {
     99 	thmap_t	*		addr_map;
    100 	LIST_HEAD(, bitmap)	bitmap_list;
    101 	kmutex_t		list_lock;
    102 };
    103 
    104 typedef struct {
    105 	int		min_port;
    106 	int		max_port;
    107 } npf_portmap_params_t;
    108 
    109 static kmutex_t			portmap_lock;
    110 
    111 void
    112 npf_portmap_init(npf_t *npf)
    113 {
    114 	npf_portmap_params_t *params = npf_param_allocgroup(npf,
    115 	    NPF_PARAMS_PORTMAP, sizeof(npf_portmap_params_t));
    116 	npf_param_t param_map[] = {
    117 		{
    118 			"portmap.min_port",
    119 			&params->min_port,
    120 			.default_val = 1024,
    121 			.min = 1024, .max = 65535
    122 		},
    123 		{
    124 			"portmap.max_port",
    125 			&params->max_port,
    126 			.default_val = 65535,
    127 			.min = 1024, .max = 65535
    128 		}
    129 	};
    130 	npf_param_register(npf, param_map, __arraycount(param_map));
    131 
    132 	npf->portmap = kmem_zalloc(sizeof(npf_portmap_t), KM_SLEEP);
    133 	mutex_init(&npf->portmap->list_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    134 	npf->portmap->addr_map = thmap_create(0, NULL, THMAP_NOCOPY);
    135 
    136 	mutex_init(&portmap_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    137 }
    138 
    139 void
    140 npf_portmap_fini(npf_t *npf)
    141 {
    142 	const size_t len = sizeof(npf_portmap_params_t);
    143 	npf_portmap_t *pm = npf->portmap;
    144 
    145 	npf_param_freegroup(npf, NPF_PARAMS_PORTMAP, len);
    146 
    147 	npf_portmap_flush(npf);
    148 	KASSERT(LIST_EMPTY(&pm->bitmap_list));
    149 
    150 	thmap_destroy(pm->addr_map);
    151 	mutex_destroy(&pm->list_lock);
    152 	kmem_free(pm, sizeof(npf_portmap_t));
    153 
    154 	mutex_destroy(&portmap_lock);
    155 }
    156 
    157 /////////////////////////////////////////////////////////////////////////
    158 
    159 #if defined(_LP64)
    160 #define	__npf_atomic_cas_64	atomic_cas_64
    161 #else
    162 static uint64_t
    163 __npf_atomic_cas_64(volatile uint64_t *ptr, uint64_t old, uint64_t new)
    164 {
    165 	uint64_t prev;
    166 
    167 	mutex_enter(&portmap_lock);
    168 	prev = *ptr;
    169 	if (prev == old) {
    170 		*ptr = new;
    171 	}
    172 	mutex_exit(&portmap_lock);
    173 
    174 	return prev;
    175 }
    176 #endif
    177 
    178 /*
    179  * bitmap_word_isset: test whether the bit value is in the packed array.
    180  *
    181  * => Return true if any value equals the bit number value.
    182  *
    183  * Packed array: 60 MSB bits, 5 values, 12 bits each.
    184  *
    185  * Reference: "Bit Twiddling Hacks" by S.E. Anderson, Stanford.
    186  * Based on the hasvalue() and haszero() ideas.  Since values are
    187  * represented by upper 60 bits, we shift right by 4.
    188  */
    189 static bool
    190 bitmap_word_isset(uint64_t x, unsigned bit)
    191 {
    192 	uint64_t m, r;
    193 
    194 	bit++;
    195 	KASSERT((x & PORTMAP_L1_TAG) == 0);
    196 	KASSERT(bit <= (PORTMAP_L0_MASK + 1));
    197 
    198 	m = (x >> 4) ^ (UINT64_C(0x1001001001001) * bit);
    199 	r = (m - UINT64_C(0x1001001001001)) & (~m & UINT64_C(0x800800800800800));
    200 	return r != 0;
    201 }
    202 
    203 /*
    204  * bitmap_word_cax: compare-and-xor on packed array elements.
    205  */
    206 static uint64_t
    207 bitmap_word_cax(uint64_t x, int exp, int bit)
    208 {
    209 	unsigned e = exp + 1;
    210 
    211 	/*
    212 	 * We need to distinguish "no value" from zero.  Just add one,
    213 	 * since we use 12 bits to represent 11 bit values.
    214 	 */
    215 	bit++;
    216 	KASSERT((unsigned)bit <= (PORTMAP_L0_MASK + 1));
    217 	KASSERT((x & PORTMAP_L1_TAG) == 0);
    218 
    219 	if (((x >> 52) & 0xfff) == e)
    220 		return x ^ ((uint64_t)bit << 52);
    221 	if (((x >> 40) & 0xfff) == e)
    222 		return x ^ ((uint64_t)bit << 40);
    223 	if (((x >> 28) & 0xfff) == e)
    224 		return x ^ ((uint64_t)bit << 28);
    225 	if (((x >> 16) & 0xfff) == e)
    226 		return x ^ ((uint64_t)bit << 16);
    227 	if (((x >>  4) & 0xfff) == e)
    228 		return x ^ ((uint64_t)bit << 4);
    229 	return 0;
    230 }
    231 
    232 static unsigned
    233 bitmap_word_unpack(uint64_t x, unsigned bitvals[static 5])
    234 {
    235 	unsigned n = 0;
    236 	uint64_t v;
    237 
    238 	KASSERT((x & PORTMAP_L1_TAG) == 0);
    239 
    240 	if ((v = ((x >> 52)) & 0xfff) != 0)
    241 		bitvals[n++] = v - 1;
    242 	if ((v = ((x >> 40)) & 0xfff) != 0)
    243 		bitvals[n++] = v - 1;
    244 	if ((v = ((x >> 28)) & 0xfff) != 0)
    245 		bitvals[n++] = v - 1;
    246 	if ((v = ((x >> 16)) & 0xfff) != 0)
    247 		bitvals[n++] = v - 1;
    248 	if ((v = ((x >>  4)) & 0xfff) != 0)
    249 		bitvals[n++] = v - 1;
    250 	return n;
    251 }
    252 
    253 #if 0
    254 static bool
    255 bitmap_isset(const bitmap_t *bm, unsigned bit)
    256 {
    257 	unsigned i, chunk_bit;
    258 	uint64_t bval, b;
    259 	bitmap_l1_t *bm1;
    260 
    261 	KASSERT(bit < PORTMAP_MAX_BITS);
    262 	i = bit >> PORTMAP_L0_SHIFT;
    263 	bval = bm->bits0[i];
    264 
    265 	/*
    266 	 * Empty check.  Note: we can test the whole word against zero,
    267 	 * since zero bit values in the packed array result in bits set.
    268 	 */
    269 	if (bval == 0)
    270 		return false;
    271 
    272 	/* Level 0 check. */
    273 	chunk_bit = bit & PORTMAP_L0_MASK;
    274 	if ((bval & PORTMAP_L1_TAG) == 0)
    275 		return bitmap_word_isset(bval, chunk_bit);
    276 
    277 	/* Level 1 check. */
    278 	bm1 = PORTMAP_L1_GET(bval);
    279 	KASSERT(bm1 != NULL);
    280 	i = chunk_bit >> PORTMAP_L1_SHIFT;
    281 	b = UINT64_C(1) << (chunk_bit & PORTMAP_L1_MASK);
    282 	return (bm1->bits1[i] & b) != 0;
    283 }
    284 #endif
    285 
    286 static bool
    287 bitmap_set(bitmap_t *bm, unsigned bit)
    288 {
    289 	unsigned i, chunk_bit;
    290 	uint64_t bval, b, oval, nval;
    291 	bitmap_l1_t *bm1;
    292 again:
    293 	KASSERT(bit < PORTMAP_MAX_BITS);
    294 	i = bit >> PORTMAP_L0_SHIFT;
    295 	chunk_bit = bit & PORTMAP_L0_MASK;
    296 	bval = bm->bits0[i]; // atomic fetch
    297 
    298 	if ((bval & PORTMAP_L1_TAG) == 0) {
    299 		unsigned n = 0, bitvals[5];
    300 		uint64_t bm1p;
    301 
    302 		if (bitmap_word_isset(bval, chunk_bit)) {
    303 			return false;
    304 		}
    305 
    306 		/*
    307 		 * Look for a zero-slot and put a value there.
    308 		 */
    309 		if ((nval = bitmap_word_cax(bval, -1, chunk_bit)) != 0) {
    310 			KASSERT((nval & PORTMAP_L1_TAG) == 0);
    311 			if (__npf_atomic_cas_64(&bm->bits0[i], bval, nval) != bval) {
    312 				goto again;
    313 			}
    314 			return true;
    315 		}
    316 
    317 		/*
    318 		 * Full: allocate L1 block and copy over the current
    319 		 * values into the level.
    320 		 */
    321 		bm1 = kmem_intr_zalloc(sizeof(bitmap_l1_t), KM_NOSLEEP);
    322 		if (bm1 == NULL) {
    323 			return false; // error
    324 		}
    325 		n = bitmap_word_unpack(bval, bitvals);
    326 		while (n--) {
    327 			const unsigned v = bitvals[n];
    328 			const unsigned off = v >> PORTMAP_L1_SHIFT;
    329 
    330 			KASSERT(v <= PORTMAP_L0_MASK);
    331 			KASSERT(off < (sizeof(uint64_t) * CHAR_BIT));
    332 			bm1->bits1[off] |= UINT64_C(1) << (v & PORTMAP_L1_MASK);
    333 		}
    334 
    335 		/*
    336 		 * Attempt to set the L1 structure.  Note: there is no
    337 		 * ABA problem since the we compare the actual values.
    338 		 * Note: CAS serves as a memory barrier.
    339 		 */
    340 		bm1p = (uintptr_t)bm1;
    341 		KASSERT((bm1p & PORTMAP_L1_TAG) == 0);
    342 		bm1p |= PORTMAP_L1_TAG;
    343 		if (__npf_atomic_cas_64(&bm->bits0[i], bval, bm1p) != bval) {
    344 			kmem_intr_free(bm1, sizeof(bitmap_l1_t));
    345 			goto again;
    346 		}
    347 		bval = bm1p;
    348 	}
    349 
    350 	bm1 = PORTMAP_L1_GET(bval);
    351 	KASSERT(bm1 != NULL);
    352 	i = chunk_bit >> PORTMAP_L1_SHIFT;
    353 	b = UINT64_C(1) << (chunk_bit & PORTMAP_L1_MASK);
    354 
    355 	oval = bm1->bits1[i]; // atomic fetch
    356 	if (oval & b) {
    357 		return false;
    358 	}
    359 	nval = oval | b;
    360 	if (__npf_atomic_cas_64(&bm1->bits1[i], oval, nval) != oval) {
    361 		goto again;
    362 	}
    363 	return true;
    364 }
    365 
    366 static bool
    367 bitmap_clr(bitmap_t *bm, unsigned bit)
    368 {
    369 	unsigned i, chunk_bit;
    370 	uint64_t bval, b, oval, nval;
    371 	bitmap_l1_t *bm1;
    372 again:
    373 	KASSERT(bit < PORTMAP_MAX_BITS);
    374 	i = bit >> PORTMAP_L0_SHIFT;
    375 	chunk_bit = bit & PORTMAP_L0_MASK;
    376 	bval = bm->bits0[i];
    377 
    378 	if ((bval & PORTMAP_L1_TAG) == 0) {
    379 		if (!bitmap_word_isset(bval, chunk_bit)) {
    380 			return false;
    381 		}
    382 		nval = bitmap_word_cax(bval, chunk_bit, chunk_bit);
    383 		KASSERT((nval & PORTMAP_L1_TAG) == 0);
    384 		if (__npf_atomic_cas_64(&bm->bits0[i], bval, nval) != bval) {
    385 			goto again;
    386 		}
    387 		return true;
    388 	}
    389 
    390 	bm1 = PORTMAP_L1_GET(bval);
    391 	KASSERT(bm1 != NULL);
    392 	i = chunk_bit >> PORTMAP_L1_SHIFT;
    393 	b = UINT64_C(1) << (chunk_bit & PORTMAP_L1_MASK);
    394 
    395 	oval = bm1->bits1[i]; // atomic fetch
    396 	if ((oval & b) == 0) {
    397 		return false;
    398 	}
    399 	nval = oval & ~b;
    400 	if (__npf_atomic_cas_64(&bm1->bits1[i], oval, nval) != oval) {
    401 		goto again;
    402 	}
    403 	return true;
    404 }
    405 
    406 /////////////////////////////////////////////////////////////////////////
    407 
    408 static bitmap_t *
    409 npf_portmap_autoget(npf_t *npf, unsigned alen, const npf_addr_t *addr)
    410 {
    411 	npf_portmap_t *pm = npf->portmap;
    412 	bitmap_t *bm;
    413 
    414 	KASSERT(pm && pm->addr_map);
    415 	KASSERT(alen && alen <= sizeof(npf_addr_t));
    416 
    417 	/* Lookup the port map for this address. */
    418 	bm = thmap_get(pm->addr_map, addr, alen);
    419 	if (bm == NULL) {
    420 		void *ret;
    421 
    422 		/*
    423 		 * Allocate a new port map for this address and
    424 		 * attempt to insert it.
    425 		 */
    426 		bm = kmem_intr_zalloc(sizeof(bitmap_t), KM_NOSLEEP);
    427 		if (bm == NULL) {
    428 			return NULL;
    429 		}
    430 		memcpy(&bm->addr, addr, alen);
    431 		bm->addr_len = alen;
    432 
    433 		int s = splsoftnet();
    434 		ret = thmap_put(pm->addr_map, &bm->addr, alen, bm);
    435 		splx(s);
    436 
    437 		if (ret == bm) {
    438 			/* Success: insert the bitmap into the list. */
    439 			mutex_enter(&pm->list_lock);
    440 			LIST_INSERT_HEAD(&pm->bitmap_list, bm, entry);
    441 			mutex_exit(&pm->list_lock);
    442 		} else {
    443 			/* Race: use an existing bitmap. */
    444 			kmem_free(bm, sizeof(bitmap_t));
    445 			bm = ret;
    446 		}
    447 	}
    448 	return bm;
    449 }
    450 
    451 
    452 /*
    453  * npf_portmap_flush: free all bitmaps and remove all addresses.
    454  *
    455  * => Concurrent calls to this routine are not allowed; therefore no
    456  * need to acquire locks.
    457  */
    458 void
    459 npf_portmap_flush(npf_t *npf)
    460 {
    461 	npf_portmap_t *pm = npf->portmap;
    462 	bitmap_t *bm;
    463 
    464 	KASSERT(npf_config_locked_p(npf));
    465 
    466 	while ((bm = LIST_FIRST(&pm->bitmap_list)) != NULL) {
    467 		for (unsigned i = 0; i < PORTMAP_L0_WORDS; i++) {
    468 			uintptr_t bm1 = bm->bits0[i];
    469 
    470 			if (bm1 & PORTMAP_L1_TAG) {
    471 				bitmap_l1_t *bm1p = PORTMAP_L1_GET(bm1);
    472 				kmem_intr_free(bm1p, sizeof(bitmap_l1_t));
    473 			}
    474 			bm->bits0[i] = UINT64_C(0);
    475 		}
    476 		LIST_REMOVE(bm, entry);
    477 		thmap_del(pm->addr_map, &bm->addr, bm->addr_len);
    478 		kmem_intr_free(bm, sizeof(bitmap_t));
    479 	}
    480 	/* Note: the caller ensures there are no active references. */
    481 	thmap_gc(pm->addr_map, thmap_stage_gc(pm->addr_map));
    482 }
    483 
    484 /*
    485  * npf_portmap_get: allocate and return a port from the given portmap.
    486  *
    487  * => Returns the port value in network byte-order.
    488  * => Zero indicates a failure.
    489  */
    490 in_port_t
    491 npf_portmap_get(npf_t *npf, int alen, const npf_addr_t *addr)
    492 {
    493 	const npf_portmap_params_t *params = npf->params[NPF_PARAMS_PORTMAP];
    494 	const unsigned port_delta = params->max_port - params->min_port;
    495 	unsigned bit, target;
    496 	bitmap_t *bm;
    497 
    498 	bm = npf_portmap_autoget(npf, alen, addr);
    499 	if (bm == NULL) {
    500 		/* No memory. */
    501 		return 0;
    502 	}
    503 
    504 	/* Randomly select a port. */
    505 	target = params->min_port + (cprng_fast32() % port_delta);
    506 	bit = target;
    507 next:
    508 	if (bitmap_set(bm, bit)) {
    509 		/* Success. */
    510 		return htons(bit);
    511 	}
    512 	bit = params->min_port + ((bit + 1) % port_delta);
    513 	if (target != bit) {
    514 		/* Next.. */
    515 		goto next;
    516 	}
    517 	/* No space. */
    518 	return 0;
    519 }
    520 
    521 /*
    522  * npf_portmap_take: allocate a specific port in the portmap.
    523  */
    524 bool
    525 npf_portmap_take(npf_t *npf, int alen, const npf_addr_t *addr, in_port_t port)
    526 {
    527 	const npf_portmap_params_t *params = npf->params[NPF_PARAMS_PORTMAP];
    528 	bitmap_t *bm = npf_portmap_autoget(npf, alen, addr);
    529 
    530 	port = ntohs(port);
    531 	if (!bm || port < params->min_port || port > params->max_port) {
    532 		/* Out of memory / invalid port. */
    533 		return false;
    534 	}
    535 	return bitmap_set(bm, port);
    536 }
    537 
    538 /*
    539  * npf_portmap_put: release the port, making it available in the portmap.
    540  *
    541  * => The port value should be in network byte-order.
    542  */
    543 void
    544 npf_portmap_put(npf_t *npf, int alen, const npf_addr_t *addr, in_port_t port)
    545 {
    546 	bitmap_t *bm;
    547 
    548 	bm = npf_portmap_autoget(npf, alen, addr);
    549 	if (bm) {
    550 		port = ntohs(port);
    551 		bitmap_clr(bm, port);
    552 	}
    553 }
    554