xref: /freebsd/sys/netpfil/ipfw/nat64/nat64lsn.c (revision f8b865d1d62d17626ab993212963277c06cc25b8)
1 /*-
2  * Copyright (c) 2015-2016 Yandex LLC
3  * Copyright (c) 2015 Alexander V. Chernikov <melifaro@FreeBSD.org>
4  * Copyright (c) 2016 Andrey V. Elsukov <ae@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/counter.h>
35 #include <sys/errno.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/module.h>
41 #include <sys/rmlock.h>
42 #include <sys/rwlock.h>
43 #include <sys/socket.h>
44 #include <sys/queue.h>
45 #include <sys/syslog.h>
46 #include <sys/sysctl.h>
47 
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_pflog.h>
51 #include <net/pfil.h>
52 
53 #include <netinet/in.h>
54 #include <netinet/ip.h>
55 #include <netinet/ip_var.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/ip6.h>
58 #include <netinet/icmp6.h>
59 #include <netinet/ip_icmp.h>
60 #include <netinet/tcp.h>
61 #include <netinet/udp.h>
62 #include <netinet6/in6_var.h>
63 #include <netinet6/ip6_var.h>
64 #include <netinet6/ip_fw_nat64.h>
65 
66 #include <netpfil/ipfw/ip_fw_private.h>
67 #include <netpfil/ipfw/nat64/ip_fw_nat64.h>
68 #include <netpfil/ipfw/nat64/nat64lsn.h>
69 #include <netpfil/ipfw/nat64/nat64_translate.h>
70 #include <netpfil/pf/pf.h>
71 
72 MALLOC_DEFINE(M_NAT64LSN, "NAT64LSN", "NAT64LSN");
73 
74 static void nat64lsn_periodic(void *data);
75 #define	PERIODIC_DELAY	4
76 static uint8_t nat64lsn_proto_map[256];
77 uint8_t nat64lsn_rproto_map[NAT_MAX_PROTO];
78 
79 #define	NAT64_FLAG_FIN		0x01	/* FIN was seen */
80 #define	NAT64_FLAG_SYN		0x02	/* First syn in->out */
81 #define	NAT64_FLAG_ESTAB	0x04	/* Packet with Ack */
82 #define	NAT64_FLAGS_TCP	(NAT64_FLAG_SYN|NAT64_FLAG_ESTAB|NAT64_FLAG_FIN)
83 
84 #define	NAT64_FLAG_RDR		0x80	/* Port redirect */
85 #define	NAT64_LOOKUP(chain, cmd)	\
86 	(struct nat64lsn_cfg *)SRV_OBJECT((chain), (cmd)->arg1)
87 /*
88  * Delayed job queue, used to create new hosts
89  * and new portgroups
90  */
91 enum nat64lsn_jtype {
92 	JTYPE_NEWHOST = 1,
93 	JTYPE_NEWPORTGROUP,
94 	JTYPE_DELPORTGROUP,
95 };
96 
97 struct nat64lsn_job_item {
98 	TAILQ_ENTRY(nat64lsn_job_item)	next;
99 	enum nat64lsn_jtype	jtype;
100 	struct nat64lsn_host	*nh;
101 	struct nat64lsn_portgroup	*pg;
102 	void			*spare_idx;
103 	struct in6_addr		haddr;
104 	uint8_t			nat_proto;
105 	uint8_t			done;
106 	int			needs_idx;
107 	int			delcount;
108 	unsigned int		fhash;	/* Flow hash */
109 	uint32_t		aaddr;	/* Last used address (net) */
110 	struct mbuf		*m;
111 	struct ipfw_flow_id	f_id;
112 	uint64_t		delmask[NAT64LSN_PGPTRNMASK];
113 };
114 
115 static struct mtx jmtx;
116 #define	JQUEUE_LOCK_INIT()	mtx_init(&jmtx, "qlock", NULL, MTX_DEF)
117 #define	JQUEUE_LOCK_DESTROY()	mtx_destroy(&jmtx)
118 #define	JQUEUE_LOCK()		mtx_lock(&jmtx)
119 #define	JQUEUE_UNLOCK()		mtx_unlock(&jmtx)
120 
121 static void nat64lsn_enqueue_job(struct nat64lsn_cfg *cfg,
122     struct nat64lsn_job_item *ji);
123 static void nat64lsn_enqueue_jobs(struct nat64lsn_cfg *cfg,
124     struct nat64lsn_job_head *jhead, int jlen);
125 
126 static struct nat64lsn_job_item *nat64lsn_create_job(struct nat64lsn_cfg *cfg,
127     const struct ipfw_flow_id *f_id, int jtype);
128 static int nat64lsn_request_portgroup(struct nat64lsn_cfg *cfg,
129     const struct ipfw_flow_id *f_id, struct mbuf **pm, uint32_t aaddr,
130     int needs_idx);
131 static int nat64lsn_request_host(struct nat64lsn_cfg *cfg,
132     const struct ipfw_flow_id *f_id, struct mbuf **pm);
133 static int nat64lsn_translate4(struct nat64lsn_cfg *cfg,
134     const struct ipfw_flow_id *f_id, struct mbuf **pm);
135 static int nat64lsn_translate6(struct nat64lsn_cfg *cfg,
136     struct ipfw_flow_id *f_id, struct mbuf **pm);
137 
138 static int alloc_portgroup(struct nat64lsn_job_item *ji);
139 static void destroy_portgroup(struct nat64lsn_portgroup *pg);
140 static void destroy_host6(struct nat64lsn_host *nh);
141 static int alloc_host6(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji);
142 
143 static int attach_portgroup(struct nat64lsn_cfg *cfg,
144     struct nat64lsn_job_item *ji);
145 static int attach_host6(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji);
146 
147 
148 /* XXX tmp */
149 static uma_zone_t nat64lsn_host_zone;
150 static uma_zone_t nat64lsn_pg_zone;
151 static uma_zone_t nat64lsn_pgidx_zone;
152 
153 static unsigned int nat64lsn_periodic_chkstates(struct nat64lsn_cfg *cfg,
154     struct nat64lsn_host *nh);
155 
156 #define	I6_hash(x)		(djb_hash((const unsigned char *)(x), 16))
157 #define	I6_first(_ph, h)	(_ph)[h]
158 #define	I6_next(x)		(x)->next
159 #define	I6_val(x)		(&(x)->addr)
160 #define	I6_cmp(a, b)		IN6_ARE_ADDR_EQUAL(a, b)
161 #define	I6_lock(a, b)
162 #define	I6_unlock(a, b)
163 
164 #define	I6HASH_FIND(_cfg, _res, _a) \
165 	CHT_FIND(_cfg->ih, _cfg->ihsize, I6_, _res, _a)
166 #define	I6HASH_INSERT(_cfg, _i)	\
167 	CHT_INSERT_HEAD(_cfg->ih, _cfg->ihsize, I6_, _i)
168 #define	I6HASH_REMOVE(_cfg, _res, _tmp, _a)	\
169 	CHT_REMOVE(_cfg->ih, _cfg->ihsize, I6_, _res, _tmp, _a)
170 
171 #define	I6HASH_FOREACH_SAFE(_cfg, _x, _tmp, _cb, _arg)	\
172 	CHT_FOREACH_SAFE(_cfg->ih, _cfg->ihsize, I6_, _x, _tmp, _cb, _arg)
173 
174 #define	HASH_IN4(x)	djb_hash((const unsigned char *)(x), 8)
175 
176 static unsigned
177 djb_hash(const unsigned char *h, const int len)
178 {
179 	unsigned int result = 0;
180 	int i;
181 
182 	for (i = 0; i < len; i++)
183 		result = 33 * result ^ h[i];
184 
185 	return (result);
186 }
187 
188 /*
189 static size_t
190 bitmask_size(size_t num, int *level)
191 {
192 	size_t x;
193 	int c;
194 
195 	for (c = 0, x = num; num > 1; num /= 64, c++)
196 		;
197 
198 	return (x);
199 }
200 
201 static void
202 bitmask_prepare(uint64_t *pmask, size_t bufsize, int level)
203 {
204 	size_t x, z;
205 
206 	memset(pmask, 0xFF, bufsize);
207 	for (x = 0, z = 1; level > 1; x += z, z *= 64, level--)
208 		;
209 	pmask[x] ~= 0x01;
210 }
211 */
212 
213 static void
214 nat64lsn_log(struct pfloghdr *plog, struct mbuf *m, sa_family_t family,
215     uint32_t n, uint32_t sn)
216 {
217 
218 	memset(plog, 0, sizeof(*plog));
219 	plog->length = PFLOG_REAL_HDRLEN;
220 	plog->af = family;
221 	plog->action = PF_NAT;
222 	plog->dir = PF_IN;
223 	plog->rulenr = htonl(n);
224 	plog->subrulenr = htonl(sn);
225 	plog->ruleset[0] = '\0';
226 	strlcpy(plog->ifname, "NAT64LSN", sizeof(plog->ifname));
227 	ipfw_bpf_mtap2(plog, PFLOG_HDRLEN, m);
228 }
229 /*
230  * Inspects icmp packets to see if the message contains different
231  * packet header so we need to alter @addr and @port.
232  */
233 static int
234 inspect_icmp_mbuf(struct mbuf **m, uint8_t *nat_proto, uint32_t *addr,
235     uint16_t *port)
236 {
237 	struct ip *ip;
238 	struct tcphdr *tcp;
239 	struct udphdr *udp;
240 	struct icmphdr *icmp;
241 	int off;
242 	uint8_t proto;
243 
244 	ip = mtod(*m, struct ip *); /* Outer IP header */
245 	off = (ip->ip_hl << 2) + ICMP_MINLEN;
246 	if ((*m)->m_len < off)
247 		*m = m_pullup(*m, off);
248 	if (*m == NULL)
249 		return (ENOMEM);
250 
251 	ip = mtod(*m, struct ip *); /* Outer IP header */
252 	icmp = L3HDR(ip, struct icmphdr *);
253 	switch (icmp->icmp_type) {
254 	case ICMP_ECHO:
255 	case ICMP_ECHOREPLY:
256 		/* Use icmp ID as distinguisher */
257 		*port = ntohs(*((uint16_t *)(icmp + 1)));
258 		return (0);
259 	case ICMP_UNREACH:
260 	case ICMP_TIMXCEED:
261 		break;
262 	default:
263 		return (EOPNOTSUPP);
264 	}
265 	/*
266 	 * ICMP_UNREACH and ICMP_TIMXCEED contains IP header + 64 bits
267 	 * of ULP header.
268 	 */
269 	if ((*m)->m_pkthdr.len < off + sizeof(struct ip) + ICMP_MINLEN)
270 		return (EINVAL);
271 	if ((*m)->m_len < off + sizeof(struct ip) + ICMP_MINLEN)
272 		*m = m_pullup(*m, off + sizeof(struct ip) + ICMP_MINLEN);
273 	if (*m == NULL)
274 		return (ENOMEM);
275 	ip = mtodo(*m, off); /* Inner IP header */
276 	proto = ip->ip_p;
277 	off += ip->ip_hl << 2; /* Skip inner IP header */
278 	*addr = ntohl(ip->ip_src.s_addr);
279 	if ((*m)->m_len < off + ICMP_MINLEN)
280 		*m = m_pullup(*m, off + ICMP_MINLEN);
281 	if (*m == NULL)
282 		return (ENOMEM);
283 	switch (proto) {
284 	case IPPROTO_TCP:
285 		tcp = mtodo(*m, off);
286 		*nat_proto = NAT_PROTO_TCP;
287 		*port = ntohs(tcp->th_sport);
288 		return (0);
289 	case IPPROTO_UDP:
290 		udp = mtodo(*m, off);
291 		*nat_proto = NAT_PROTO_UDP;
292 		*port = ntohs(udp->uh_sport);
293 		return (0);
294 	case IPPROTO_ICMP:
295 		/*
296 		 * We will translate only ICMP errors for our ICMP
297 		 * echo requests.
298 		 */
299 		icmp = mtodo(*m, off);
300 		if (icmp->icmp_type != ICMP_ECHO)
301 			return (EOPNOTSUPP);
302 		*port = ntohs(*((uint16_t *)(icmp + 1)));
303 		return (0);
304 	};
305 	return (EOPNOTSUPP);
306 }
307 
308 static inline uint8_t
309 convert_tcp_flags(uint8_t flags)
310 {
311 	uint8_t result;
312 
313 	result = flags & (TH_FIN|TH_SYN);
314 	result |= (flags & TH_RST) >> 2; /* Treat RST as FIN */
315 	result |= (flags & TH_ACK) >> 2; /* Treat ACK as estab */
316 
317 	return (result);
318 }
319 
320 static NAT64NOINLINE int
321 nat64lsn_translate4(struct nat64lsn_cfg *cfg, const struct ipfw_flow_id *f_id,
322     struct mbuf **pm)
323 {
324 	struct pfloghdr loghdr, *logdata;
325 	struct in6_addr src6;
326 	struct nat64lsn_portgroup *pg;
327 	struct nat64lsn_host *nh;
328 	struct nat64lsn_state *st;
329 	struct ip *ip;
330 	uint32_t addr;
331 	uint16_t state_flags, state_ts;
332 	uint16_t port, lport;
333 	uint8_t nat_proto;
334 	int ret;
335 
336 	addr = f_id->dst_ip;
337 	port = f_id->dst_port;
338 	if (addr < cfg->prefix4 || addr > cfg->pmask4) {
339 		NAT64STAT_INC(&cfg->stats, nomatch4);
340 		return (cfg->nomatch_verdict);
341 	}
342 
343 	/* Check if protocol is supported and get its short id */
344 	nat_proto = nat64lsn_proto_map[f_id->proto];
345 	if (nat_proto == 0) {
346 		NAT64STAT_INC(&cfg->stats, noproto);
347 		return (cfg->nomatch_verdict);
348 	}
349 
350 	/* We might need to handle icmp differently */
351 	if (nat_proto == NAT_PROTO_ICMP) {
352 		ret = inspect_icmp_mbuf(pm, &nat_proto, &addr, &port);
353 		if (ret != 0) {
354 			if (ret == ENOMEM) {
355 				NAT64STAT_INC(&cfg->stats, nomem);
356 				return (IP_FW_DENY);
357 			}
358 			NAT64STAT_INC(&cfg->stats, noproto);
359 			return (cfg->nomatch_verdict);
360 		}
361 		/* XXX: Check addr for validity */
362 		if (addr < cfg->prefix4 || addr > cfg->pmask4) {
363 			NAT64STAT_INC(&cfg->stats, nomatch4);
364 			return (cfg->nomatch_verdict);
365 		}
366 	}
367 
368 	/* Calc portgroup offset w.r.t protocol */
369 	pg = GET_PORTGROUP(cfg, addr, nat_proto, port);
370 
371 	/* Check if this port is occupied by any portgroup */
372 	if (pg == NULL) {
373 		NAT64STAT_INC(&cfg->stats, nomatch4);
374 #if 0
375 		DPRINTF(DP_STATE, "NOMATCH %u %d %d (%d)", addr, nat_proto, port,
376 		    _GET_PORTGROUP_IDX(cfg, addr, nat_proto, port));
377 #endif
378 		return (cfg->nomatch_verdict);
379 	}
380 
381 	/* TODO: Check flags to see if we need to do some static mapping */
382 	nh = pg->host;
383 
384 	/* Prepare some fields we might need to update */
385 	SET_AGE(state_ts);
386 	ip = mtod(*pm, struct ip *);
387 	if (ip->ip_p == IPPROTO_TCP)
388 		state_flags = convert_tcp_flags(
389 		    L3HDR(ip, struct tcphdr *)->th_flags);
390 	else
391 		state_flags = 0;
392 
393 	/* Lock host and get port mapping */
394 	NAT64_LOCK(nh);
395 
396 	st = &pg->states[port & (NAT64_CHUNK_SIZE - 1)];
397 	if (st->timestamp != state_ts)
398 		st->timestamp = state_ts;
399 	if ((st->flags & state_flags) != state_flags)
400 		st->flags |= state_flags;
401 	lport = htons(st->u.s.lport);
402 
403 	NAT64_UNLOCK(nh);
404 
405 	if (cfg->flags & NAT64_LOG) {
406 		logdata = &loghdr;
407 		nat64lsn_log(logdata, *pm, AF_INET, pg->idx, st->cur.off);
408 	} else
409 		logdata = NULL;
410 
411 	src6.s6_addr32[0] = cfg->prefix6.s6_addr32[0];
412 	src6.s6_addr32[1] = cfg->prefix6.s6_addr32[1];
413 	src6.s6_addr32[2] = cfg->prefix6.s6_addr32[2];
414 	src6.s6_addr32[3] = htonl(f_id->src_ip);
415 
416 	ret = nat64_do_handle_ip4(*pm, &src6, &nh->addr, lport,
417 	    &cfg->stats, logdata);
418 
419 	if (ret == NAT64SKIP)
420 		return (cfg->nomatch_verdict);
421 	if (ret == NAT64MFREE)
422 		m_freem(*pm);
423 	*pm = NULL;
424 
425 	return (IP_FW_DENY);
426 }
427 
428 void
429 nat64lsn_dump_state(const struct nat64lsn_cfg *cfg,
430    const struct nat64lsn_portgroup *pg, const struct nat64lsn_state *st,
431    const char *px, int off)
432 {
433 	char s[INET6_ADDRSTRLEN], a[INET_ADDRSTRLEN], d[INET_ADDRSTRLEN];
434 
435 	if ((nat64_debug & DP_STATE) == 0)
436 		return;
437 	inet_ntop(AF_INET6, &pg->host->addr, s, sizeof(s));
438 	inet_ntop(AF_INET, &pg->aaddr, a, sizeof(a));
439 	inet_ntop(AF_INET, &st->u.s.faddr, d, sizeof(d));
440 
441 	DPRINTF(DP_STATE, "%s: PG %d ST [%p|%d]: %s:%d/%d <%s:%d> "
442 	    "%s:%d AGE %d", px, pg->idx, st, off,
443 	    s, st->u.s.lport, pg->nat_proto, a, pg->aport + off,
444 	    d, st->u.s.fport, GET_AGE(st->timestamp));
445 }
446 
447 /*
448  * Check if particular TCP state is stale and should be deleted.
449  * Return 1 if true, 0 otherwise.
450  */
451 static int
452 nat64lsn_periodic_check_tcp(const struct nat64lsn_cfg *cfg,
453     const struct nat64lsn_state *st, int age)
454 {
455 	int ttl;
456 
457 	if (st->flags & NAT64_FLAG_FIN)
458 		ttl = cfg->st_close_ttl;
459 	else if (st->flags & NAT64_FLAG_ESTAB)
460 		ttl = cfg->st_estab_ttl;
461 	else if (st->flags & NAT64_FLAG_SYN)
462 		ttl = cfg->st_syn_ttl;
463 	else
464 		ttl = cfg->st_syn_ttl;
465 
466 	if (age > ttl)
467 		return (1);
468 	return (0);
469 }
470 
471 /*
472  * Check if nat state @st is stale and should be deleted.
473  * Return 1 if true, 0 otherwise.
474  */
475 static NAT64NOINLINE int
476 nat64lsn_periodic_chkstate(const struct nat64lsn_cfg *cfg,
477     const struct nat64lsn_portgroup *pg, const struct nat64lsn_state *st)
478 {
479 	int age, delete;
480 
481 	age = GET_AGE(st->timestamp);
482 	delete = 0;
483 
484 	/* Skip immutable records */
485 	if (st->flags & NAT64_FLAG_RDR)
486 		return (0);
487 
488 	switch (pg->nat_proto) {
489 		case NAT_PROTO_TCP:
490 			delete = nat64lsn_periodic_check_tcp(cfg, st, age);
491 			break;
492 		case NAT_PROTO_UDP:
493 			if (age > cfg->st_udp_ttl)
494 				delete = 1;
495 			break;
496 		case NAT_PROTO_ICMP:
497 			if (age > cfg->st_icmp_ttl)
498 				delete = 1;
499 			break;
500 	}
501 
502 	return (delete);
503 }
504 
505 
506 /*
507  * The following structures and functions
508  * are used to perform SLIST_FOREACH_SAFE()
509  * analog for states identified by struct st_ptr.
510  */
511 
512 struct st_idx {
513 	struct nat64lsn_portgroup *pg;
514 	struct nat64lsn_state *st;
515 	struct st_ptr sidx_next;
516 };
517 
518 static struct st_idx *
519 st_first(const struct nat64lsn_cfg *cfg, const struct nat64lsn_host *nh,
520     struct st_ptr *sidx, struct st_idx *si)
521 {
522 	struct nat64lsn_portgroup *pg;
523 	struct nat64lsn_state *st;
524 
525 	if (sidx->idx == 0) {
526 		memset(si, 0, sizeof(*si));
527 		return (si);
528 	}
529 
530 	pg = PORTGROUP_BYSIDX(cfg, nh, sidx->idx);
531 	st = &pg->states[sidx->off];
532 
533 	si->pg = pg;
534 	si->st = st;
535 	si->sidx_next = st->next;
536 
537 	return (si);
538 }
539 
540 static struct st_idx *
541 st_next(const struct nat64lsn_cfg *cfg, const struct nat64lsn_host *nh,
542     struct st_idx *si)
543 {
544 	struct st_ptr sidx;
545 	struct nat64lsn_portgroup *pg;
546 	struct nat64lsn_state *st;
547 
548 	sidx = si->sidx_next;
549 	if (sidx.idx == 0) {
550 		memset(si, 0, sizeof(*si));
551 		si->st = NULL;
552 		si->pg = NULL;
553 		return (si);
554 	}
555 
556 	pg = PORTGROUP_BYSIDX(cfg, nh, sidx.idx);
557 	st = &pg->states[sidx.off];
558 
559 	si->pg = pg;
560 	si->st = st;
561 	si->sidx_next = st->next;
562 
563 	return (si);
564 }
565 
566 static struct st_idx *
567 st_save_cond(struct st_idx *si_dst, struct st_idx *si)
568 {
569 	if (si->st != NULL)
570 		*si_dst = *si;
571 
572 	return (si_dst);
573 }
574 
575 unsigned int
576 nat64lsn_periodic_chkstates(struct nat64lsn_cfg *cfg, struct nat64lsn_host *nh)
577 {
578 	struct st_idx si, si_prev;
579 	int i;
580 	unsigned int delcount;
581 
582 	delcount = 0;
583 	for (i = 0; i < nh->hsize; i++) {
584 		memset(&si_prev, 0, sizeof(si_prev));
585 		for (st_first(cfg, nh, &nh->phash[i], &si);
586 		    si.st != NULL;
587 		    st_save_cond(&si_prev, &si), st_next(cfg, nh, &si)) {
588 			if (nat64lsn_periodic_chkstate(cfg, si.pg, si.st) == 0)
589 				continue;
590 			nat64lsn_dump_state(cfg, si.pg, si.st, "DELETE STATE",
591 			    si.st->cur.off);
592 			/* Unlink from hash */
593 			if (si_prev.st != NULL)
594 				si_prev.st->next = si.st->next;
595 			else
596 				nh->phash[i] = si.st->next;
597 			/* Delete state and free its data */
598 			PG_MARK_FREE_IDX(si.pg, si.st->cur.off);
599 			memset(si.st, 0, sizeof(struct nat64lsn_state));
600 			si.st = NULL;
601 			delcount++;
602 
603 			/* Update portgroup timestamp */
604 			SET_AGE(si.pg->timestamp);
605 		}
606 	}
607 	NAT64STAT_ADD(&cfg->stats, sdeleted, delcount);
608 	return (delcount);
609 }
610 
611 /*
612  * Checks if portgroup is not used and can be deleted,
613  * Returns 1 if stale, 0 otherwise
614  */
615 static int
616 stale_pg(const struct nat64lsn_cfg *cfg, const struct nat64lsn_portgroup *pg)
617 {
618 
619 	if (!PG_IS_EMPTY(pg))
620 		return (0);
621 	if (GET_AGE(pg->timestamp) < cfg->pg_delete_delay)
622 		return (0);
623 	return (1);
624 }
625 
626 /*
627  * Checks if host record is not used and can be deleted,
628  * Returns 1 if stale, 0 otherwise
629  */
630 static int
631 stale_nh(const struct nat64lsn_cfg *cfg, const struct nat64lsn_host *nh)
632 {
633 
634 	if (nh->pg_used != 0)
635 		return (0);
636 	if (GET_AGE(nh->timestamp) < cfg->nh_delete_delay)
637 		return (0);
638 	return (1);
639 }
640 
641 struct nat64lsn_periodic_data {
642 	struct nat64lsn_cfg *cfg;
643 	struct nat64lsn_job_head jhead;
644 	int jlen;
645 };
646 
647 static NAT64NOINLINE int
648 nat64lsn_periodic_chkhost(struct nat64lsn_host *nh,
649     struct nat64lsn_periodic_data *d)
650 {
651 	char a[INET6_ADDRSTRLEN];
652 	struct nat64lsn_portgroup *pg;
653 	struct nat64lsn_job_item *ji;
654 	uint64_t delmask[NAT64LSN_PGPTRNMASK];
655 	int delcount, i;
656 
657 	delcount = 0;
658 	memset(delmask, 0, sizeof(delmask));
659 
660 	inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
661 	DPRINTF(DP_JQUEUE, "Checking %s host %s on cpu %d",
662 	    stale_nh(d->cfg, nh) ? "stale" : "non-stale", a, curcpu);
663 	if (!stale_nh(d->cfg, nh)) {
664 		/* Non-stale host. Inspect internals */
665 		NAT64_LOCK(nh);
666 
667 		/* Stage 1: Check&expire states */
668 		if (nat64lsn_periodic_chkstates(d->cfg, nh) != 0)
669 			SET_AGE(nh->timestamp);
670 
671 		/* Stage 2: Check if we need to expire */
672 		for (i = 0; i < nh->pg_used; i++) {
673 			pg = PORTGROUP_BYSIDX(d->cfg, nh, i + 1);
674 			if (pg == NULL)
675 				continue;
676 
677 			/* Check if we can delete portgroup */
678 			if (stale_pg(d->cfg, pg) == 0)
679 				continue;
680 
681 			DPRINTF(DP_JQUEUE, "Check PG %d", i);
682 			delmask[i / 64] |= ((uint64_t)1 << (i % 64));
683 			delcount++;
684 		}
685 
686 		NAT64_UNLOCK(nh);
687 		if (delcount == 0)
688 			return (0);
689 	}
690 
691 	DPRINTF(DP_JQUEUE, "Queueing %d portgroups for deleting", delcount);
692 	/* We have something to delete - add it to queue */
693 	ji = nat64lsn_create_job(d->cfg, NULL, JTYPE_DELPORTGROUP);
694 	if (ji == NULL)
695 		return (0);
696 
697 	ji->haddr = nh->addr;
698 	ji->delcount = delcount;
699 	memcpy(ji->delmask, delmask, sizeof(ji->delmask));
700 
701 	TAILQ_INSERT_TAIL(&d->jhead, ji, next);
702 	d->jlen++;
703 	return (0);
704 }
705 
706 /*
707  * This procedure is used to perform various maintance
708  * on dynamic hash list. Currently it is called every second.
709  */
710 static void
711 nat64lsn_periodic(void *data)
712 {
713 	struct ip_fw_chain *ch;
714 	IPFW_RLOCK_TRACKER;
715 	struct nat64lsn_cfg *cfg;
716 	struct nat64lsn_periodic_data d;
717 	struct nat64lsn_host *nh, *tmp;
718 
719 	cfg = (struct nat64lsn_cfg *) data;
720 	ch = cfg->ch;
721 	CURVNET_SET(cfg->vp);
722 
723 	memset(&d, 0, sizeof(d));
724 	d.cfg = cfg;
725 	TAILQ_INIT(&d.jhead);
726 
727 	IPFW_RLOCK(ch);
728 
729 	/* Stage 1: foreach host, check all its portgroups */
730 	I6HASH_FOREACH_SAFE(cfg, nh, tmp, nat64lsn_periodic_chkhost, &d);
731 
732 	/* Enqueue everything we have requested */
733 	nat64lsn_enqueue_jobs(cfg, &d.jhead, d.jlen);
734 
735 	callout_schedule(&cfg->periodic, hz * PERIODIC_DELAY);
736 
737 	IPFW_RUNLOCK(ch);
738 
739 	CURVNET_RESTORE();
740 }
741 
742 static NAT64NOINLINE void
743 reinject_mbuf(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
744 {
745 
746 	if (ji->m == NULL)
747 		return;
748 
749 	/* Request has failed or packet type is wrong */
750 	if (ji->f_id.addr_type != 6 || ji->done == 0) {
751 		m_freem(ji->m);
752 		ji->m = NULL;
753 		NAT64STAT_INC(&cfg->stats, dropped);
754 		DPRINTF(DP_DROPS, "mbuf dropped: type %d, done %d",
755 		    ji->jtype, ji->done);
756 		return;
757 	}
758 
759 	/*
760 	 * XXX: Limit recursion level
761 	 */
762 
763 	NAT64STAT_INC(&cfg->stats, jreinjected);
764 	DPRINTF(DP_JQUEUE, "Reinject mbuf");
765 	nat64lsn_translate6(cfg, &ji->f_id, &ji->m);
766 }
767 
768 static void
769 destroy_portgroup(struct nat64lsn_portgroup *pg)
770 {
771 
772 	DPRINTF(DP_OBJ, "DESTROY PORTGROUP %d %p", pg->idx, pg);
773 	uma_zfree(nat64lsn_pg_zone, pg);
774 }
775 
776 static NAT64NOINLINE int
777 alloc_portgroup(struct nat64lsn_job_item *ji)
778 {
779 	struct nat64lsn_portgroup *pg;
780 
781 	pg = uma_zalloc(nat64lsn_pg_zone, M_NOWAIT);
782 	if (pg == NULL)
783 		return (1);
784 
785 	if (ji->needs_idx != 0) {
786 		ji->spare_idx = uma_zalloc(nat64lsn_pgidx_zone, M_NOWAIT);
787 		/* Failed alloc isn't always fatal, so don't check */
788 	}
789 	memset(&pg->freemask, 0xFF, sizeof(pg->freemask));
790 	pg->nat_proto = ji->nat_proto;
791 	ji->pg = pg;
792 	return (0);
793 
794 }
795 
796 static void
797 destroy_host6(struct nat64lsn_host *nh)
798 {
799 	char a[INET6_ADDRSTRLEN];
800 	int i;
801 
802 	inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
803 	DPRINTF(DP_OBJ, "DESTROY HOST %s %p (pg used %d)", a, nh,
804 	    nh->pg_used);
805 	NAT64_LOCK_DESTROY(nh);
806 	for (i = 0; i < nh->pg_allocated / NAT64LSN_PGIDX_CHUNK; i++)
807 		uma_zfree(nat64lsn_pgidx_zone, PORTGROUP_CHUNK(nh, i));
808 	uma_zfree(nat64lsn_host_zone, nh);
809 }
810 
811 static NAT64NOINLINE int
812 alloc_host6(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
813 {
814 	struct nat64lsn_host *nh;
815 	char a[INET6_ADDRSTRLEN];
816 
817 	nh = uma_zalloc(nat64lsn_host_zone, M_NOWAIT);
818 	if (nh == NULL)
819 		return (1);
820 	PORTGROUP_CHUNK(nh, 0) = uma_zalloc(nat64lsn_pgidx_zone, M_NOWAIT);
821 	if (PORTGROUP_CHUNK(nh, 0) == NULL) {
822 		uma_zfree(nat64lsn_host_zone, nh);
823 		return (2);
824 	}
825 	if (alloc_portgroup(ji) != 0) {
826 		NAT64STAT_INC(&cfg->stats, jportfails);
827 		uma_zfree(nat64lsn_pgidx_zone, PORTGROUP_CHUNK(nh, 0));
828 		uma_zfree(nat64lsn_host_zone, nh);
829 		return (3);
830 	}
831 
832 	NAT64_LOCK_INIT(nh);
833 	nh->addr = ji->haddr;
834 	nh->hsize = NAT64LSN_HSIZE; /* XXX: hardcoded size */
835 	nh->pg_allocated = NAT64LSN_PGIDX_CHUNK;
836 	nh->pg_used = 0;
837 	ji->nh = nh;
838 
839 	inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
840 	DPRINTF(DP_OBJ, "ALLOC HOST %s %p", a, ji->nh);
841 	return (0);
842 }
843 
844 /*
845  * Finds free @pg index inside @nh
846  */
847 static NAT64NOINLINE int
848 find_nh_pg_idx(struct nat64lsn_cfg *cfg, struct nat64lsn_host *nh, int *idx)
849 {
850 	int i;
851 
852 	for (i = 0; i < nh->pg_allocated; i++) {
853 		if (PORTGROUP_BYSIDX(cfg, nh, i + 1) == NULL) {
854 			*idx = i;
855 			return (0);
856 		}
857 	}
858 	return (1);
859 }
860 
861 static NAT64NOINLINE int
862 attach_host6(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
863 {
864 	char a[INET6_ADDRSTRLEN];
865 	struct nat64lsn_host *nh;
866 
867 	I6HASH_FIND(cfg, nh, &ji->haddr);
868 	if (nh == NULL) {
869 		/* Add new host to list */
870 		nh = ji->nh;
871 		I6HASH_INSERT(cfg, nh);
872 		cfg->ihcount++;
873 		ji->nh = NULL;
874 
875 		inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
876 		DPRINTF(DP_OBJ, "ATTACH HOST %s %p", a, nh);
877 		/*
878 		 * Try to add portgroup.
879 		 * Note it will automatically set
880 		 * 'done' on ji if successful.
881 		 */
882 		if (attach_portgroup(cfg, ji) != 0) {
883 			DPRINTF(DP_DROPS, "%s %p failed to attach PG",
884 			    a, nh);
885 			NAT64STAT_INC(&cfg->stats, jportfails);
886 			return (1);
887 		}
888 		return (0);
889 	}
890 
891 	/*
892 	 * nh isn't NULL. This probably means we had several simultaneous
893 	 * host requests. The previous one request has already attached
894 	 * this host. Requeue attached mbuf and mark job as done, but
895 	 * leave nh and pg pointers not changed, so nat64lsn_do_request()
896 	 * will release all allocated resources.
897 	 */
898 	inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
899 	DPRINTF(DP_OBJ, "%s %p is already attached as %p",
900 	    a, ji->nh, nh);
901 	ji->done = 1;
902 	return (0);
903 }
904 
905 static NAT64NOINLINE int
906 find_pg_place_addr(const struct nat64lsn_cfg *cfg, int addr_off,
907     int nat_proto, uint16_t *aport, int *ppg_idx)
908 {
909 	int j, pg_idx;
910 
911 	pg_idx = addr_off * _ADDR_PG_COUNT +
912 	    (nat_proto - 1) * _ADDR_PG_PROTO_COUNT;
913 
914 	for (j = NAT64_MIN_CHUNK; j < _ADDR_PG_PROTO_COUNT; j++) {
915 		if (cfg->pg[pg_idx + j] != NULL)
916 			continue;
917 
918 		*aport = j * NAT64_CHUNK_SIZE;
919 		*ppg_idx = pg_idx + j;
920 		return (1);
921 	}
922 
923 	return (0);
924 }
925 
926 /*
927  * XXX: This function needs to be rewritten to
928  * use free bitmask for faster pg finding,
929  * additionally, it should take into consideration
930  * a) randomization and
931  * b) previous addresses allocated to given nat instance
932  *
933  */
934 static NAT64NOINLINE int
935 find_portgroup_place(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji,
936     uint32_t *aaddr, uint16_t *aport, int *ppg_idx)
937 {
938 	int i, nat_proto;
939 
940 	/*
941 	 * XXX: Use bitmask index to be able to find/check if IP address
942 	 * has some spare pg's
943 	 */
944 	nat_proto = ji->nat_proto;
945 
946 	/* First, try to use same address */
947 	if (ji->aaddr != 0) {
948 		i = ntohl(ji->aaddr) - cfg->prefix4;
949 		if (find_pg_place_addr(cfg, i, nat_proto, aport,
950 		    ppg_idx) != 0){
951 			/* Found! */
952 			*aaddr = htonl(cfg->prefix4 + i);
953 			return (0);
954 		}
955 	}
956 
957 	/* Next, try to use random address based on flow hash */
958 	i = ji->fhash % (1 << (32 - cfg->plen4));
959 	if (find_pg_place_addr(cfg, i, nat_proto, aport, ppg_idx) != 0) {
960 		/* Found! */
961 		*aaddr = htonl(cfg->prefix4 + i);
962 		return (0);
963 	}
964 
965 
966 	/* Last one: simply find ANY available */
967 	for (i = 0; i < (1 << (32 - cfg->plen4)); i++) {
968 		if (find_pg_place_addr(cfg, i, nat_proto, aport,
969 		    ppg_idx) != 0){
970 			/* Found! */
971 			*aaddr = htonl(cfg->prefix4 + i);
972 			return (0);
973 		}
974 	}
975 
976 	return (1);
977 }
978 
979 static NAT64NOINLINE int
980 attach_portgroup(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
981 {
982 	char a[INET6_ADDRSTRLEN];
983 	struct nat64lsn_portgroup *pg;
984 	struct nat64lsn_host *nh;
985 	uint32_t aaddr;
986 	uint16_t aport;
987 	int nh_pg_idx, pg_idx;
988 
989 	pg = ji->pg;
990 
991 	/*
992 	 * Find source host and bind: we can't rely on
993 	 * pg->host
994 	 */
995 	I6HASH_FIND(cfg, nh, &ji->haddr);
996 	if (nh == NULL)
997 		return (1);
998 
999 	/* Find spare port chunk */
1000 	if (find_portgroup_place(cfg, ji, &aaddr, &aport, &pg_idx) != 0) {
1001 		inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
1002 		DPRINTF(DP_OBJ | DP_DROPS, "empty PG not found for %s", a);
1003 		return (2);
1004 	}
1005 
1006 	/* Expand PG indexes if needed */
1007 	if (nh->pg_allocated < cfg->max_chunks && ji->spare_idx != NULL) {
1008 		PORTGROUP_CHUNK(nh, nh->pg_allocated / NAT64LSN_PGIDX_CHUNK) =
1009 		    ji->spare_idx;
1010 		nh->pg_allocated += NAT64LSN_PGIDX_CHUNK;
1011 		ji->spare_idx = NULL;
1012 	}
1013 
1014 	/* Find empty index to store PG in the @nh */
1015 	if (find_nh_pg_idx(cfg, nh, &nh_pg_idx) != 0) {
1016 		inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
1017 		DPRINTF(DP_OBJ | DP_DROPS, "free PG index not found for %s",
1018 		    a);
1019 		return (3);
1020 	}
1021 
1022 	cfg->pg[pg_idx] = pg;
1023 	cfg->protochunks[pg->nat_proto]++;
1024 	NAT64STAT_INC(&cfg->stats, spgcreated);
1025 
1026 	pg->aaddr = aaddr;
1027 	pg->aport = aport;
1028 	pg->host = nh;
1029 	pg->idx = pg_idx;
1030 	SET_AGE(pg->timestamp);
1031 
1032 	PORTGROUP_BYSIDX(cfg, nh, nh_pg_idx + 1) = pg;
1033 	if (nh->pg_used == nh_pg_idx)
1034 		nh->pg_used++;
1035 	SET_AGE(nh->timestamp);
1036 
1037 	ji->pg = NULL;
1038 	ji->done = 1;
1039 
1040 	return (0);
1041 }
1042 
1043 static NAT64NOINLINE void
1044 consider_del_portgroup(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
1045 {
1046 	struct nat64lsn_host *nh, *nh_tmp;
1047 	struct nat64lsn_portgroup *pg, *pg_list[256];
1048 	int i, pg_lidx, idx;
1049 
1050 	/* Find source host */
1051 	I6HASH_FIND(cfg, nh, &ji->haddr);
1052 	if (nh == NULL || nh->pg_used == 0)
1053 		return;
1054 
1055 	memset(pg_list, 0, sizeof(pg_list));
1056 	pg_lidx = 0;
1057 
1058 	NAT64_LOCK(nh);
1059 
1060 	for (i = nh->pg_used - 1; i >= 0; i--) {
1061 		if ((ji->delmask[i / 64] & ((uint64_t)1 << (i % 64))) == 0)
1062 			continue;
1063 		pg = PORTGROUP_BYSIDX(cfg, nh, i + 1);
1064 
1065 		/* Check that PG isn't busy. */
1066 		if (stale_pg(cfg, pg) == 0)
1067 			continue;
1068 
1069 		/* DO delete */
1070 		pg_list[pg_lidx++] = pg;
1071 		PORTGROUP_BYSIDX(cfg, nh, i + 1) = NULL;
1072 
1073 		idx = _GET_PORTGROUP_IDX(cfg, ntohl(pg->aaddr), pg->nat_proto,
1074 		    pg->aport);
1075 		KASSERT(cfg->pg[idx] == pg, ("Non matched pg"));
1076 		cfg->pg[idx] = NULL;
1077 		cfg->protochunks[pg->nat_proto]--;
1078 		NAT64STAT_INC(&cfg->stats, spgdeleted);
1079 
1080 		/* Decrease pg_used */
1081 		while (nh->pg_used > 0 &&
1082 		    PORTGROUP_BYSIDX(cfg, nh, nh->pg_used) == NULL)
1083 			nh->pg_used--;
1084 
1085 		/* Check if on-stack buffer has ended */
1086 		if (pg_lidx == nitems(pg_list))
1087 			break;
1088 	}
1089 
1090 	NAT64_UNLOCK(nh);
1091 
1092 	if (stale_nh(cfg, nh)) {
1093 		I6HASH_REMOVE(cfg, nh, nh_tmp, &ji->haddr);
1094 		KASSERT(nh != NULL, ("Unable to find address"));
1095 		cfg->ihcount--;
1096 		ji->nh = nh;
1097 		I6HASH_FIND(cfg, nh, &ji->haddr);
1098 		KASSERT(nh == NULL, ("Failed to delete address"));
1099 	}
1100 
1101 	/* TODO: Delay freeing portgroups */
1102 	while (pg_lidx > 0) {
1103 		pg_lidx--;
1104 		NAT64STAT_INC(&cfg->stats, spgdeleted);
1105 		destroy_portgroup(pg_list[pg_lidx]);
1106 	}
1107 }
1108 
1109 /*
1110  * Main request handler.
1111  * Responsible for handling jqueue, e.g.
1112  * creating new hosts, addind/deleting portgroups.
1113  */
1114 static NAT64NOINLINE void
1115 nat64lsn_do_request(void *data)
1116 {
1117 	IPFW_RLOCK_TRACKER;
1118 	struct nat64lsn_job_head jhead;
1119 	struct nat64lsn_job_item *ji;
1120 	int jcount, nhsize;
1121 	struct nat64lsn_cfg *cfg = (struct nat64lsn_cfg *) data;
1122 	struct ip_fw_chain *ch;
1123 	int delcount;
1124 
1125 	CURVNET_SET(cfg->vp);
1126 
1127 	TAILQ_INIT(&jhead);
1128 
1129 	/* XXX: We're running unlocked here */
1130 
1131 	ch = cfg->ch;
1132 	delcount = 0;
1133 	IPFW_RLOCK(ch);
1134 
1135 	/* Grab queue */
1136 	JQUEUE_LOCK();
1137 	TAILQ_SWAP(&jhead, &cfg->jhead, nat64lsn_job_item, next);
1138 	jcount = cfg->jlen;
1139 	cfg->jlen = 0;
1140 	JQUEUE_UNLOCK();
1141 
1142 	/* check if we need to resize hash */
1143 	nhsize = 0;
1144 	if (cfg->ihcount > cfg->ihsize && cfg->ihsize < 65536) {
1145 		nhsize = cfg->ihsize;
1146 		for ( ; cfg->ihcount > nhsize && nhsize < 65536; nhsize *= 2)
1147 			;
1148 	} else if (cfg->ihcount < cfg->ihsize * 4) {
1149 		nhsize = cfg->ihsize;
1150 		for ( ; cfg->ihcount < nhsize * 4 && nhsize > 32; nhsize /= 2)
1151 			;
1152 	}
1153 
1154 	IPFW_RUNLOCK(ch);
1155 
1156 	if (TAILQ_EMPTY(&jhead)) {
1157 		CURVNET_RESTORE();
1158 		return;
1159 	}
1160 
1161 	NAT64STAT_INC(&cfg->stats, jcalls);
1162 	DPRINTF(DP_JQUEUE, "count=%d", jcount);
1163 
1164 	/*
1165 	 * TODO:
1166 	 * What we should do here is to build a hash
1167 	 * to ensure we don't have lots of duplicate requests.
1168 	 * Skip this for now.
1169 	 *
1170 	 * TODO: Limit per-call number of items
1171 	 */
1172 
1173 	/* Pre-allocate everything for entire chain */
1174 	TAILQ_FOREACH(ji, &jhead,  next) {
1175 		switch (ji->jtype) {
1176 			case JTYPE_NEWHOST:
1177 				if (alloc_host6(cfg, ji) != 0)
1178 					NAT64STAT_INC(&cfg->stats, jhostfails);
1179 				break;
1180 			case JTYPE_NEWPORTGROUP:
1181 				if (alloc_portgroup(ji) != 0)
1182 					NAT64STAT_INC(&cfg->stats, jportfails);
1183 				break;
1184 			case JTYPE_DELPORTGROUP:
1185 				delcount += ji->delcount;
1186 				break;
1187 			default:
1188 				break;
1189 		}
1190 	}
1191 
1192 	/*
1193 	 * TODO: Alloc hew hash
1194 	 */
1195 	nhsize = 0;
1196 	if (nhsize > 0) {
1197 		/* XXX: */
1198 	}
1199 
1200 	/* Apply all changes in batch */
1201 	IPFW_UH_WLOCK(ch);
1202 	IPFW_WLOCK(ch);
1203 
1204 	TAILQ_FOREACH(ji, &jhead,  next) {
1205 		switch (ji->jtype) {
1206 			case JTYPE_NEWHOST:
1207 				if (ji->nh != NULL)
1208 					attach_host6(cfg, ji);
1209 				break;
1210 			case JTYPE_NEWPORTGROUP:
1211 				if (ji->pg != NULL &&
1212 				    attach_portgroup(cfg, ji) != 0)
1213 					NAT64STAT_INC(&cfg->stats, jportfails);
1214 				break;
1215 			case JTYPE_DELPORTGROUP:
1216 				consider_del_portgroup(cfg, ji);
1217 				break;
1218 		}
1219 	}
1220 
1221 	if (nhsize > 0) {
1222 		/* XXX: Move everything to new hash */
1223 	}
1224 
1225 	IPFW_WUNLOCK(ch);
1226 	IPFW_UH_WUNLOCK(ch);
1227 
1228 	/* Flush unused entries */
1229 	while (!TAILQ_EMPTY(&jhead)) {
1230 		ji = TAILQ_FIRST(&jhead);
1231 		TAILQ_REMOVE(&jhead, ji, next);
1232 		if (ji->nh != NULL)
1233 			destroy_host6(ji->nh);
1234 		if (ji->pg != NULL)
1235 			destroy_portgroup(ji->pg);
1236 		if (ji->m != NULL)
1237 			reinject_mbuf(cfg, ji);
1238 		if (ji->spare_idx != NULL)
1239 			uma_zfree(nat64lsn_pgidx_zone, ji->spare_idx);
1240 		free(ji, M_IPFW);
1241 	}
1242 	CURVNET_RESTORE();
1243 }
1244 
1245 static NAT64NOINLINE struct nat64lsn_job_item *
1246 nat64lsn_create_job(struct nat64lsn_cfg *cfg, const struct ipfw_flow_id *f_id,
1247     int jtype)
1248 {
1249 	struct nat64lsn_job_item *ji;
1250 	struct in6_addr haddr;
1251 	uint8_t nat_proto;
1252 
1253 	/*
1254 	 * Do not try to lock possibly contested mutex if we're near the limit.
1255 	 * Drop packet instead.
1256 	 */
1257 	if (cfg->jlen >= cfg->jmaxlen) {
1258 		NAT64STAT_INC(&cfg->stats, jmaxlen);
1259 		return (NULL);
1260 	}
1261 
1262 	memset(&haddr, 0, sizeof(haddr));
1263 	nat_proto = 0;
1264 	if (f_id != NULL) {
1265 		haddr = f_id->src_ip6;
1266 		nat_proto = nat64lsn_proto_map[f_id->proto];
1267 
1268 		DPRINTF(DP_JQUEUE, "REQUEST pg nat_proto %d on proto %d",
1269 		    nat_proto, f_id->proto);
1270 
1271 		if (nat_proto == 0)
1272 			return (NULL);
1273 	}
1274 
1275 	ji = malloc(sizeof(struct nat64lsn_job_item), M_IPFW,
1276 	    M_NOWAIT | M_ZERO);
1277 
1278 	if (ji == NULL) {
1279 		NAT64STAT_INC(&cfg->stats, jnomem);
1280 		return (NULL);
1281 	}
1282 
1283 	ji->jtype = jtype;
1284 
1285 	if (f_id != NULL) {
1286 		ji->f_id = *f_id;
1287 		ji->haddr = haddr;
1288 		ji->nat_proto = nat_proto;
1289 	}
1290 
1291 	return (ji);
1292 }
1293 
1294 static NAT64NOINLINE void
1295 nat64lsn_enqueue_job(struct nat64lsn_cfg *cfg, struct nat64lsn_job_item *ji)
1296 {
1297 
1298 	if (ji == NULL)
1299 		return;
1300 
1301 	JQUEUE_LOCK();
1302 	TAILQ_INSERT_TAIL(&cfg->jhead, ji, next);
1303 	cfg->jlen++;
1304 	NAT64STAT_INC(&cfg->stats, jrequests);
1305 
1306 	if (callout_pending(&cfg->jcallout) == 0)
1307 		callout_reset(&cfg->jcallout, 1, nat64lsn_do_request, cfg);
1308 	JQUEUE_UNLOCK();
1309 }
1310 
1311 static NAT64NOINLINE void
1312 nat64lsn_enqueue_jobs(struct nat64lsn_cfg *cfg,
1313     struct nat64lsn_job_head *jhead, int jlen)
1314 {
1315 
1316 	if (TAILQ_EMPTY(jhead))
1317 		return;
1318 
1319 	/* Attach current queue to execution one */
1320 	JQUEUE_LOCK();
1321 	TAILQ_CONCAT(&cfg->jhead, jhead, next);
1322 	cfg->jlen += jlen;
1323 	NAT64STAT_ADD(&cfg->stats, jrequests, jlen);
1324 
1325 	if (callout_pending(&cfg->jcallout) == 0)
1326 		callout_reset(&cfg->jcallout, 1, nat64lsn_do_request, cfg);
1327 	JQUEUE_UNLOCK();
1328 }
1329 
1330 static unsigned int
1331 flow6_hash(const struct ipfw_flow_id *f_id)
1332 {
1333 	unsigned char hbuf[36];
1334 
1335 	memcpy(hbuf, &f_id->dst_ip6, 16);
1336 	memcpy(&hbuf[16], &f_id->src_ip6, 16);
1337 	memcpy(&hbuf[32], &f_id->dst_port, 2);
1338 	memcpy(&hbuf[32], &f_id->src_port, 2);
1339 
1340 	return (djb_hash(hbuf, sizeof(hbuf)));
1341 }
1342 
1343 static NAT64NOINLINE int
1344 nat64lsn_request_host(struct nat64lsn_cfg *cfg,
1345     const struct ipfw_flow_id *f_id, struct mbuf **pm)
1346 {
1347 	struct nat64lsn_job_item *ji;
1348 	struct mbuf *m;
1349 
1350 	m = *pm;
1351 	*pm = NULL;
1352 
1353 	ji = nat64lsn_create_job(cfg, f_id, JTYPE_NEWHOST);
1354 	if (ji == NULL) {
1355 		m_freem(m);
1356 		NAT64STAT_INC(&cfg->stats, dropped);
1357 		DPRINTF(DP_DROPS, "failed to create job");
1358 	} else {
1359 		ji->m = m;
1360 		/* Provide pseudo-random value based on flow */
1361 		ji->fhash = flow6_hash(f_id);
1362 		nat64lsn_enqueue_job(cfg, ji);
1363 		NAT64STAT_INC(&cfg->stats, jhostsreq);
1364 	}
1365 
1366 	return (IP_FW_DENY);
1367 }
1368 
1369 static NAT64NOINLINE int
1370 nat64lsn_request_portgroup(struct nat64lsn_cfg *cfg,
1371     const struct ipfw_flow_id *f_id, struct mbuf **pm, uint32_t aaddr,
1372     int needs_idx)
1373 {
1374 	struct nat64lsn_job_item *ji;
1375 	struct mbuf *m;
1376 
1377 	m = *pm;
1378 	*pm = NULL;
1379 
1380 	ji = nat64lsn_create_job(cfg, f_id, JTYPE_NEWPORTGROUP);
1381 	if (ji == NULL) {
1382 		m_freem(m);
1383 		NAT64STAT_INC(&cfg->stats, dropped);
1384 		DPRINTF(DP_DROPS, "failed to create job");
1385 	} else {
1386 		ji->m = m;
1387 		/* Provide pseudo-random value based on flow */
1388 		ji->fhash = flow6_hash(f_id);
1389 		ji->aaddr = aaddr;
1390 		ji->needs_idx = needs_idx;
1391 		nat64lsn_enqueue_job(cfg, ji);
1392 		NAT64STAT_INC(&cfg->stats, jportreq);
1393 	}
1394 
1395 	return (IP_FW_DENY);
1396 }
1397 
1398 static NAT64NOINLINE struct nat64lsn_state *
1399 nat64lsn_create_state(struct nat64lsn_cfg *cfg, struct nat64lsn_host *nh,
1400     int nat_proto, struct nat64lsn_state *kst, uint32_t *aaddr)
1401 {
1402 	struct nat64lsn_portgroup *pg;
1403 	struct nat64lsn_state *st;
1404 	int i, hval, off;
1405 
1406 	/* XXX: create additional bitmask for selecting proper portgroup */
1407 	for (i = 0; i < nh->pg_used; i++) {
1408 		pg = PORTGROUP_BYSIDX(cfg, nh, i + 1);
1409 		if (pg == NULL)
1410 			continue;
1411 		if (*aaddr == 0)
1412 			*aaddr = pg->aaddr;
1413 		if (pg->nat_proto != nat_proto)
1414 			continue;
1415 
1416 		off = PG_GET_FREE_IDX(pg);
1417 		if (off != 0) {
1418 			/* We have found spare state. Use it */
1419 			off--;
1420 			PG_MARK_BUSY_IDX(pg, off);
1421 			st = &pg->states[off];
1422 
1423 			/*
1424 			 * Fill in new info. Assume state was zeroed.
1425 			 * Timestamp and flags will be filled by caller.
1426 			 */
1427 			st->u.s = kst->u.s;
1428 			st->cur.idx = i + 1;
1429 			st->cur.off = off;
1430 
1431 			/* Insert into host hash table */
1432 			hval = HASH_IN4(&st->u.hkey) & (nh->hsize - 1);
1433 			st->next = nh->phash[hval];
1434 			nh->phash[hval] = st->cur;
1435 
1436 			nat64lsn_dump_state(cfg, pg, st, "ALLOC STATE", off);
1437 
1438 			NAT64STAT_INC(&cfg->stats, screated);
1439 
1440 			return (st);
1441 		}
1442 		/* Saev last used alias affress */
1443 		*aaddr = pg->aaddr;
1444 	}
1445 
1446 	return (NULL);
1447 }
1448 
1449 static NAT64NOINLINE int
1450 nat64lsn_translate6(struct nat64lsn_cfg *cfg, struct ipfw_flow_id *f_id,
1451     struct mbuf **pm)
1452 {
1453 	struct pfloghdr loghdr, *logdata;
1454 	char a[INET6_ADDRSTRLEN];
1455 	struct nat64lsn_host *nh;
1456 	struct st_ptr sidx;
1457 	struct nat64lsn_state *st, kst;
1458 	struct nat64lsn_portgroup *pg;
1459 	struct icmp6_hdr *icmp6;
1460 	uint32_t aaddr;
1461 	int action, hval, nat_proto, proto;
1462 	uint16_t aport, state_ts, state_flags;
1463 
1464 	/* Check if af/protocol is supported and get it short id */
1465 	nat_proto = nat64lsn_proto_map[f_id->proto];
1466 	if (nat_proto == 0) {
1467 		/*
1468 		 * Since we can be called from jobs handler, we need
1469 		 * to free mbuf by self, do not leave this task to
1470 		 * ipfw_check_packet().
1471 		 */
1472 		NAT64STAT_INC(&cfg->stats, noproto);
1473 		m_freem(*pm);
1474 		*pm = NULL;
1475 		return (IP_FW_DENY);
1476 	}
1477 
1478 	/* Try to find host first */
1479 	I6HASH_FIND(cfg, nh, &f_id->src_ip6);
1480 
1481 	if (nh == NULL)
1482 		return (nat64lsn_request_host(cfg, f_id, pm));
1483 
1484 	/* Fill-in on-stack state structure */
1485 	kst.u.s.faddr = f_id->dst_ip6.s6_addr32[3];
1486 	kst.u.s.fport = f_id->dst_port;
1487 	kst.u.s.lport = f_id->src_port;
1488 
1489 	/* Prepare some fields we might need to update */
1490 	hval = 0;
1491 	proto = nat64_getlasthdr(*pm, &hval);
1492 	if (proto < 0) {
1493 		NAT64STAT_INC(&cfg->stats, dropped);
1494 		DPRINTF(DP_DROPS, "dropped due to mbuf isn't contigious");
1495 		m_freem(*pm);
1496 		*pm = NULL;
1497 		return (IP_FW_DENY);
1498 	}
1499 
1500 	SET_AGE(state_ts);
1501 	if (proto == IPPROTO_TCP)
1502 		state_flags = convert_tcp_flags(
1503 		    TCP(mtodo(*pm, hval))->th_flags);
1504 	else
1505 		state_flags = 0;
1506 	if (proto == IPPROTO_ICMPV6) {
1507 		/* Alter local port data */
1508 		icmp6 = mtodo(*pm, hval);
1509 		if (icmp6->icmp6_type == ICMP6_ECHO_REQUEST ||
1510 		    icmp6->icmp6_type == ICMP6_ECHO_REPLY)
1511 			kst.u.s.lport = ntohs(icmp6->icmp6_id);
1512 	}
1513 
1514 	hval = HASH_IN4(&kst.u.hkey) & (nh->hsize - 1);
1515 	pg = NULL;
1516 	st = NULL;
1517 
1518 	/* OK, let's find state in host hash */
1519 	NAT64_LOCK(nh);
1520 	sidx = nh->phash[hval];
1521 	int k = 0;
1522 	while (sidx.idx != 0) {
1523 		pg = PORTGROUP_BYSIDX(cfg, nh, sidx.idx);
1524 		st = &pg->states[sidx.off];
1525 		//DPRINTF("SISX: %d/%d next: %d/%d", sidx.idx, sidx.off,
1526 		//st->next.idx, st->next.off);
1527 		if (st->u.hkey == kst.u.hkey && pg->nat_proto == nat_proto)
1528 			break;
1529 		if (k++ > 1000) {
1530 			DPRINTF(DP_ALL, "XXX: too long %d/%d %d/%d\n",
1531 			    sidx.idx, sidx.off, st->next.idx, st->next.off);
1532 			inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
1533 			DPRINTF(DP_GENERIC, "TR host %s %p on cpu %d",
1534 			    a, nh, curcpu);
1535 			k = 0;
1536 		}
1537 		sidx = st->next;
1538 	}
1539 
1540 	if (sidx.idx == 0) {
1541 		aaddr = 0;
1542 		st = nat64lsn_create_state(cfg, nh, nat_proto, &kst, &aaddr);
1543 		if (st == NULL) {
1544 			/* No free states. Request more if we can */
1545 			if (nh->pg_used >= cfg->max_chunks) {
1546 				/* Limit reached */
1547 				NAT64STAT_INC(&cfg->stats, dropped);
1548 				inet_ntop(AF_INET6, &nh->addr, a, sizeof(a));
1549 				DPRINTF(DP_DROPS, "PG limit reached "
1550 				    " for host %s (used %u, allocated %u, "
1551 				    "limit %u)", a,
1552 				    nh->pg_used * NAT64_CHUNK_SIZE,
1553 				    nh->pg_allocated * NAT64_CHUNK_SIZE,
1554 				    cfg->max_chunks * NAT64_CHUNK_SIZE);
1555 				m_freem(*pm);
1556 				*pm = NULL;
1557 				NAT64_UNLOCK(nh);
1558 				return (IP_FW_DENY);
1559 			}
1560 			if ((nh->pg_allocated <=
1561 			    nh->pg_used + NAT64LSN_REMAININGPG) &&
1562 			    nh->pg_allocated < cfg->max_chunks)
1563 				action = 1; /* Request new indexes */
1564 			else
1565 				action = 0;
1566 			NAT64_UNLOCK(nh);
1567 			//DPRINTF("No state, unlock for %p", nh);
1568 			return (nat64lsn_request_portgroup(cfg, f_id,
1569 			    pm, aaddr, action));
1570 		}
1571 
1572 		/* We've got new state. */
1573 		sidx = st->cur;
1574 		pg = PORTGROUP_BYSIDX(cfg, nh, sidx.idx);
1575 	}
1576 
1577 	/* Okay, state found */
1578 
1579 	/* Update necessary fileds */
1580 	if (st->timestamp != state_ts)
1581 		st->timestamp = state_ts;
1582 	if ((st->flags & state_flags) != 0)
1583 		st->flags |= state_flags;
1584 
1585 	/* Copy needed state data */
1586 	aaddr = pg->aaddr;
1587 	aport = htons(pg->aport + sidx.off);
1588 
1589 	NAT64_UNLOCK(nh);
1590 
1591 	if (cfg->flags & NAT64_LOG) {
1592 		logdata = &loghdr;
1593 		nat64lsn_log(logdata, *pm, AF_INET6, pg->idx, st->cur.off);
1594 	} else
1595 		logdata = NULL;
1596 
1597 	action = nat64_do_handle_ip6(*pm, aaddr, aport, &cfg->stats, logdata);
1598 	if (action == NAT64SKIP)
1599 		return (cfg->nomatch_verdict);
1600 	if (action == NAT64MFREE)
1601 		m_freem(*pm);
1602 	*pm = NULL;	/* mark mbuf as consumed */
1603 	return (IP_FW_DENY);
1604 }
1605 
1606 /*
1607  * Main dataplane entry point.
1608  */
1609 int
1610 ipfw_nat64lsn(struct ip_fw_chain *ch, struct ip_fw_args *args,
1611     ipfw_insn *cmd, int *done)
1612 {
1613 	ipfw_insn *icmd;
1614 	struct nat64lsn_cfg *cfg;
1615 	int ret;
1616 
1617 	IPFW_RLOCK_ASSERT(ch);
1618 
1619 	*done = 1; /* terminate the search */
1620 	icmd = cmd + 1;
1621 	if (cmd->opcode != O_EXTERNAL_ACTION ||
1622 	    cmd->arg1 != V_nat64lsn_eid ||
1623 	    icmd->opcode != O_EXTERNAL_INSTANCE ||
1624 	    (cfg = NAT64_LOOKUP(ch, icmd)) == NULL)
1625 		return (0);
1626 
1627 	switch (args->f_id.addr_type) {
1628 	case 4:
1629 		ret = nat64lsn_translate4(cfg, &args->f_id, &args->m);
1630 		break;
1631 	case 6:
1632 		ret = nat64lsn_translate6(cfg, &args->f_id, &args->m);
1633 		break;
1634 	default:
1635 		return (cfg->nomatch_verdict);
1636 	}
1637 	return (ret);
1638 }
1639 
1640 static int
1641 nat64lsn_ctor_host(void *mem, int size, void *arg, int flags)
1642 {
1643 	struct nat64lsn_host *nh;
1644 
1645 	nh = (struct nat64lsn_host *)mem;
1646 	memset(nh->pg_ptr, 0, sizeof(nh->pg_ptr));
1647 	memset(nh->phash, 0, sizeof(nh->phash));
1648 	return (0);
1649 }
1650 
1651 static int
1652 nat64lsn_ctor_pgidx(void *mem, int size, void *arg, int flags)
1653 {
1654 
1655 	memset(mem, 0, size);
1656 	return (0);
1657 }
1658 
1659 void
1660 nat64lsn_init_internal(void)
1661 {
1662 
1663 	memset(nat64lsn_proto_map, 0, sizeof(nat64lsn_proto_map));
1664 	/* Set up supported protocol map */
1665 	nat64lsn_proto_map[IPPROTO_TCP] = NAT_PROTO_TCP;
1666 	nat64lsn_proto_map[IPPROTO_UDP] = NAT_PROTO_UDP;
1667 	nat64lsn_proto_map[IPPROTO_ICMP] = NAT_PROTO_ICMP;
1668 	nat64lsn_proto_map[IPPROTO_ICMPV6] = NAT_PROTO_ICMP;
1669 	/* Fill in reverse proto map */
1670 	memset(nat64lsn_rproto_map, 0, sizeof(nat64lsn_rproto_map));
1671 	nat64lsn_rproto_map[NAT_PROTO_TCP] = IPPROTO_TCP;
1672 	nat64lsn_rproto_map[NAT_PROTO_UDP] = IPPROTO_UDP;
1673 	nat64lsn_rproto_map[NAT_PROTO_ICMP] = IPPROTO_ICMPV6;
1674 
1675 	JQUEUE_LOCK_INIT();
1676 	nat64lsn_host_zone = uma_zcreate("NAT64 hosts zone",
1677 	    sizeof(struct nat64lsn_host), nat64lsn_ctor_host, NULL,
1678 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1679 	nat64lsn_pg_zone = uma_zcreate("NAT64 portgroups zone",
1680 	    sizeof(struct nat64lsn_portgroup), NULL, NULL, NULL, NULL,
1681 	    UMA_ALIGN_PTR, 0);
1682 	nat64lsn_pgidx_zone = uma_zcreate("NAT64 portgroup indexes zone",
1683 	    sizeof(struct nat64lsn_portgroup *) * NAT64LSN_PGIDX_CHUNK,
1684 	    nat64lsn_ctor_pgidx, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1685 }
1686 
1687 void
1688 nat64lsn_uninit_internal(void)
1689 {
1690 
1691 	JQUEUE_LOCK_DESTROY();
1692 	uma_zdestroy(nat64lsn_host_zone);
1693 	uma_zdestroy(nat64lsn_pg_zone);
1694 	uma_zdestroy(nat64lsn_pgidx_zone);
1695 }
1696 
1697 void
1698 nat64lsn_start_instance(struct nat64lsn_cfg *cfg)
1699 {
1700 
1701 	callout_reset(&cfg->periodic, hz * PERIODIC_DELAY,
1702 	    nat64lsn_periodic, cfg);
1703 }
1704 
1705 struct nat64lsn_cfg *
1706 nat64lsn_init_instance(struct ip_fw_chain *ch, size_t numaddr)
1707 {
1708 	struct nat64lsn_cfg *cfg;
1709 
1710 	cfg = malloc(sizeof(struct nat64lsn_cfg), M_IPFW, M_WAITOK | M_ZERO);
1711 	TAILQ_INIT(&cfg->jhead);
1712 	cfg->vp = curvnet;
1713 	cfg->ch = ch;
1714 	COUNTER_ARRAY_ALLOC(cfg->stats.stats, NAT64STATS, M_WAITOK);
1715 
1716 	cfg->ihsize = NAT64LSN_HSIZE;
1717 	cfg->ih = malloc(sizeof(void *) * cfg->ihsize, M_IPFW,
1718 	    M_WAITOK | M_ZERO);
1719 
1720 	cfg->pg = malloc(sizeof(void *) * numaddr * _ADDR_PG_COUNT, M_IPFW,
1721 	    M_WAITOK | M_ZERO);
1722 
1723         callout_init(&cfg->periodic, CALLOUT_MPSAFE);
1724         callout_init(&cfg->jcallout, CALLOUT_MPSAFE);
1725 
1726 	return (cfg);
1727 }
1728 
1729 /*
1730  * Destroy all hosts callback.
1731  * Called on module unload when all activity already finished, so
1732  * can work without any locks.
1733  */
1734 static NAT64NOINLINE int
1735 nat64lsn_destroy_host(struct nat64lsn_host *nh, struct nat64lsn_cfg *cfg)
1736 {
1737 	struct nat64lsn_portgroup *pg;
1738 	int i;
1739 
1740 	for (i = nh->pg_used; i > 0; i--) {
1741 		pg = PORTGROUP_BYSIDX(cfg, nh, i);
1742 		if (pg == NULL)
1743 			continue;
1744 		cfg->pg[pg->idx] = NULL;
1745 		destroy_portgroup(pg);
1746 		nh->pg_used--;
1747 	}
1748 	destroy_host6(nh);
1749 	cfg->ihcount--;
1750 	return (0);
1751 }
1752 
1753 void
1754 nat64lsn_destroy_instance(struct nat64lsn_cfg *cfg)
1755 {
1756 	struct nat64lsn_host *nh, *tmp;
1757 
1758 	callout_drain(&cfg->jcallout);
1759 	callout_drain(&cfg->periodic);
1760 	I6HASH_FOREACH_SAFE(cfg, nh, tmp, nat64lsn_destroy_host, cfg);
1761 	DPRINTF(DP_OBJ, "instance %s: hosts %d", cfg->name, cfg->ihcount);
1762 
1763 	COUNTER_ARRAY_FREE(cfg->stats.stats, NAT64STATS);
1764 	free(cfg->ih, M_IPFW);
1765 	free(cfg->pg, M_IPFW);
1766 	free(cfg, M_IPFW);
1767 }
1768 
1769