xref: /titanic_51/usr/src/uts/common/inet/ip/keysock.c (revision 9c2c14ab194d42014417b385d6bf226ba1a37995)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/param.h>
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/strsubr.h>
30 #include <sys/strsun.h>
31 #include <sys/stropts.h>
32 #include <sys/vnode.h>
33 #include <sys/zone.h>
34 #include <sys/strlog.h>
35 #include <sys/sysmacros.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/timod.h>
39 #include <sys/tiuser.h>
40 #include <sys/ddi.h>
41 #include <sys/sunddi.h>
42 #include <sys/sunldi.h>
43 #include <sys/file.h>
44 #include <sys/modctl.h>
45 #include <sys/debug.h>
46 #include <sys/kmem.h>
47 #include <sys/cmn_err.h>
48 #include <sys/proc.h>
49 #include <sys/suntpi.h>
50 #include <sys/atomic.h>
51 #include <sys/mkdev.h>
52 #include <sys/policy.h>
53 #include <sys/disp.h>
54 
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <net/pfkeyv2.h>
58 
59 #include <inet/common.h>
60 #include <netinet/ip6.h>
61 #include <inet/ip.h>
62 #include <inet/mi.h>
63 #include <inet/nd.h>
64 #include <inet/optcom.h>
65 #include <inet/ipsec_info.h>
66 #include <inet/ipsec_impl.h>
67 #include <inet/keysock.h>
68 
69 #include <sys/isa_defs.h>
70 
71 /*
72  * This is a transport provider for the PF_KEY key mangement socket.
73  * (See RFC 2367 for details.)
74  * Downstream messages are wrapped in a keysock consumer interface KEYSOCK_IN
75  * messages (see ipsec_info.h), and passed to the appropriate consumer.
76  * Upstream messages are generated for all open PF_KEY sockets, when
77  * appropriate, as well as the sender (as long as SO_USELOOPBACK is enabled)
78  * in reply to downstream messages.
79  *
80  * Upstream messages must be created asynchronously for the following
81  * situations:
82  *
83  *	1.) A keysock consumer requires an SA, and there is currently none.
84  *	2.) An SA expires, either hard or soft lifetime.
85  *	3.) Other events a consumer deems fit.
86  *
87  * The MT model of this is PERMOD, with shared put procedures.  Two types of
88  * messages, SADB_FLUSH and SADB_DUMP, need to lock down the perimeter to send
89  * down the *multiple* messages they create.
90  */
91 
92 static vmem_t *keysock_vmem;		/* for minor numbers. */
93 
94 #define	KEYSOCK_MAX_CONSUMERS 256
95 
96 /* Default structure copied into T_INFO_ACK messages (from rts.c...) */
97 static struct T_info_ack keysock_g_t_info_ack = {
98 	T_INFO_ACK,
99 	T_INFINITE,	/* TSDU_size. Maximum size messages. */
100 	T_INVALID,	/* ETSDU_size. No expedited data. */
101 	T_INVALID,	/* CDATA_size. No connect data. */
102 	T_INVALID,	/* DDATA_size. No disconnect data. */
103 	0,		/* ADDR_size. */
104 	0,		/* OPT_size. No user-settable options */
105 	64 * 1024,	/* TIDU_size. keysock allows maximum size messages. */
106 	T_COTS,		/* SERV_type. keysock supports connection oriented. */
107 	TS_UNBND,	/* CURRENT_state. This is set from keysock_state. */
108 	(XPG4_1)	/* Provider flags */
109 };
110 
111 /* Named Dispatch Parameter Management Structure */
112 typedef struct keysockparam_s {
113 	uint_t	keysock_param_min;
114 	uint_t	keysock_param_max;
115 	uint_t	keysock_param_value;
116 	char	*keysock_param_name;
117 } keysockparam_t;
118 
119 /*
120  * Table of NDD variables supported by keysock. These are loaded into
121  * keysock_g_nd in keysock_init_nd.
122  * All of these are alterable, within the min/max values given, at run time.
123  */
124 static	keysockparam_t	lcl_param_arr[] = {
125 	/* min	max	value	name */
126 	{ 4096, 65536,	8192,	"keysock_xmit_hiwat"},
127 	{ 0,	65536,	1024,	"keysock_xmit_lowat"},
128 	{ 4096, 65536,	8192,	"keysock_recv_hiwat"},
129 	{ 65536, 1024*1024*1024, 256*1024,	"keysock_max_buf"},
130 	{ 0,	3,	0,	"keysock_debug"},
131 };
132 #define	keystack_xmit_hiwat	keystack_params[0].keysock_param_value
133 #define	keystack_xmit_lowat	keystack_params[1].keysock_param_value
134 #define	keystack_recv_hiwat	keystack_params[2].keysock_param_value
135 #define	keystack_max_buf	keystack_params[3].keysock_param_value
136 #define	keystack_debug	keystack_params[4].keysock_param_value
137 
138 #define	ks0dbg(a)	printf a
139 /* NOTE:  != 0 instead of > 0 so lint doesn't complain. */
140 #define	ks1dbg(keystack, a)	if (keystack->keystack_debug != 0) printf a
141 #define	ks2dbg(keystack, a)	if (keystack->keystack_debug > 1) printf a
142 #define	ks3dbg(keystack, a)	if (keystack->keystack_debug > 2) printf a
143 
144 static int keysock_close(queue_t *);
145 static int keysock_open(queue_t *, dev_t *, int, int, cred_t *);
146 static void keysock_wput(queue_t *, mblk_t *);
147 static void keysock_rput(queue_t *, mblk_t *);
148 static void keysock_rsrv(queue_t *);
149 static void keysock_passup(mblk_t *, sadb_msg_t *, minor_t,
150     keysock_consumer_t *, boolean_t, keysock_stack_t *);
151 static void *keysock_stack_init(netstackid_t stackid, netstack_t *ns);
152 static void keysock_stack_fini(netstackid_t stackid, void *arg);
153 
154 static struct module_info info = {
155 	5138, "keysock", 1, INFPSZ, 512, 128
156 };
157 
158 static struct qinit rinit = {
159 	(pfi_t)keysock_rput, (pfi_t)keysock_rsrv, keysock_open, keysock_close,
160 	NULL, &info
161 };
162 
163 static struct qinit winit = {
164 	(pfi_t)keysock_wput, NULL, NULL, NULL, NULL, &info
165 };
166 
167 struct streamtab keysockinfo = {
168 	&rinit, &winit
169 };
170 
171 extern struct modlinkage *keysock_modlp;
172 
173 /*
174  * Plumb IPsec.
175  *
176  * NOTE:  New "default" modules will need to be loaded here if needed before
177  *	  boot time.
178  */
179 
180 /* Keep these in global space to keep the lint from complaining. */
181 static char *IPSECESP = "ipsecesp";
182 static char *IPSECESPDEV = "/devices/pseudo/ipsecesp@0:ipsecesp";
183 static char *IPSECAH = "ipsecah";
184 static char *IPSECAHDEV = "/devices/pseudo/ipsecah@0:ipsecah";
185 static char *IP6DEV = "/devices/pseudo/ip6@0:ip6";
186 static char *KEYSOCK = "keysock";
187 static char *STRMOD = "strmod";
188 
189 /*
190  * Load the other ipsec modules and plumb them together.
191  */
192 int
193 keysock_plumb_ipsec(netstack_t *ns)
194 {
195 	ldi_handle_t	lh, ip6_lh = NULL;
196 	ldi_ident_t	li = NULL;
197 	int		err = 0;
198 	int		muxid, rval;
199 	boolean_t	esp_present = B_TRUE;
200 	cred_t		*cr;
201 	keysock_stack_t *keystack = ns->netstack_keysock;
202 
203 #ifdef NS_DEBUG
204 	(void) printf("keysock_plumb_ipsec(%d)\n",
205 	    ns->netstack_stackid);
206 #endif
207 
208 	keystack->keystack_plumbed = 0;	/* we're trying again.. */
209 
210 	cr = zone_get_kcred(netstackid_to_zoneid(
211 	    keystack->keystack_netstack->netstack_stackid));
212 	ASSERT(cr != NULL);
213 	/*
214 	 * Load up the drivers (AH/ESP).
215 	 *
216 	 * I do this separately from the actual plumbing in case this function
217 	 * ever gets called from a diskless boot before the root filesystem is
218 	 * up.  I don't have to worry about "keysock" because, well, if I'm
219 	 * here, keysock must've loaded successfully.
220 	 */
221 	if (i_ddi_attach_pseudo_node(IPSECAH) == NULL) {
222 		ks0dbg(("IPsec:  AH failed to attach.\n"));
223 		goto bail;
224 	}
225 	if (i_ddi_attach_pseudo_node(IPSECESP) == NULL) {
226 		ks0dbg(("IPsec:  ESP failed to attach.\n"));
227 		esp_present = B_FALSE;
228 	}
229 
230 	/*
231 	 * Set up the IP streams for AH and ESP, as well as tacking keysock
232 	 * on top of them.  Assume keysock has set the autopushes up already.
233 	 */
234 
235 	/* Open IP. */
236 	err = ldi_ident_from_mod(keysock_modlp, &li);
237 	if (err) {
238 		ks0dbg(("IPsec:  lid_ident_from_mod failed (err %d).\n",
239 		    err));
240 		goto bail;
241 	}
242 
243 	err = ldi_open_by_name(IP6DEV, FREAD|FWRITE, cr, &ip6_lh, li);
244 	if (err) {
245 		ks0dbg(("IPsec:  Open of IP6 failed (err %d).\n", err));
246 		goto bail;
247 	}
248 
249 	/* PLINK KEYSOCK/AH */
250 	err = ldi_open_by_name(IPSECAHDEV, FREAD|FWRITE, cr, &lh, li);
251 	if (err) {
252 		ks0dbg(("IPsec:  Open of AH failed (err %d).\n", err));
253 		goto bail;
254 	}
255 	err = ldi_ioctl(lh,
256 	    I_PUSH, (intptr_t)KEYSOCK, FKIOCTL, cr, &rval);
257 	if (err) {
258 		ks0dbg(("IPsec:  Push of KEYSOCK onto AH failed (err %d).\n",
259 		    err));
260 		(void) ldi_close(lh, FREAD|FWRITE, cr);
261 		goto bail;
262 	}
263 	err = ldi_ioctl(ip6_lh, I_PLINK, (intptr_t)lh,
264 	    FREAD+FWRITE+FNOCTTY+FKIOCTL, cr, &muxid);
265 	if (err) {
266 		ks0dbg(("IPsec:  PLINK of KEYSOCK/AH failed (err %d).\n", err));
267 		(void) ldi_close(lh, FREAD|FWRITE, cr);
268 		goto bail;
269 	}
270 	(void) ldi_close(lh, FREAD|FWRITE, cr);
271 
272 	/* PLINK KEYSOCK/ESP */
273 	if (esp_present) {
274 		err = ldi_open_by_name(IPSECESPDEV,
275 		    FREAD|FWRITE, cr, &lh, li);
276 		if (err) {
277 			ks0dbg(("IPsec:  Open of ESP failed (err %d).\n", err));
278 			goto bail;
279 		}
280 		err = ldi_ioctl(lh,
281 		    I_PUSH, (intptr_t)KEYSOCK, FKIOCTL, cr, &rval);
282 		if (err) {
283 			ks0dbg(("IPsec:  "
284 			    "Push of KEYSOCK onto ESP failed (err %d).\n",
285 			    err));
286 			(void) ldi_close(lh, FREAD|FWRITE, cr);
287 			goto bail;
288 		}
289 		err = ldi_ioctl(ip6_lh, I_PLINK, (intptr_t)lh,
290 		    FREAD+FWRITE+FNOCTTY+FKIOCTL, cr, &muxid);
291 		if (err) {
292 			ks0dbg(("IPsec:  "
293 			    "PLINK of KEYSOCK/ESP failed (err %d).\n", err));
294 			(void) ldi_close(lh, FREAD|FWRITE, cr);
295 			goto bail;
296 		}
297 		(void) ldi_close(lh, FREAD|FWRITE, cr);
298 	}
299 
300 bail:
301 	keystack->keystack_plumbed = (err == 0) ? 1 : -1;
302 	if (ip6_lh != NULL) {
303 		(void) ldi_close(ip6_lh, FREAD|FWRITE, cr);
304 	}
305 	if (li != NULL)
306 		ldi_ident_release(li);
307 #ifdef NS_DEBUG
308 	(void) printf("keysock_plumb_ipsec -> %d\n",
309 	    keystack->keystack_plumbed);
310 #endif
311 	crfree(cr);
312 	return (err);
313 }
314 
315 /* ARGSUSED */
316 static int
317 keysock_param_get(q, mp, cp, cr)
318 	queue_t	*q;
319 	mblk_t	*mp;
320 	caddr_t	cp;
321 	cred_t *cr;
322 {
323 	keysockparam_t	*keysockpa = (keysockparam_t *)cp;
324 	uint_t value;
325 	keysock_t *ks = (keysock_t *)q->q_ptr;
326 	keysock_stack_t	*keystack = ks->keysock_keystack;
327 
328 	mutex_enter(&keystack->keystack_param_lock);
329 	value = keysockpa->keysock_param_value;
330 	mutex_exit(&keystack->keystack_param_lock);
331 
332 	(void) mi_mpprintf(mp, "%u", value);
333 	return (0);
334 }
335 
336 /* This routine sets an NDD variable in a keysockparam_t structure. */
337 /* ARGSUSED */
338 static int
339 keysock_param_set(q, mp, value, cp, cr)
340 	queue_t	*q;
341 	mblk_t	*mp;
342 	char	*value;
343 	caddr_t	cp;
344 	cred_t *cr;
345 {
346 	ulong_t	new_value;
347 	keysockparam_t	*keysockpa = (keysockparam_t *)cp;
348 	keysock_t *ks = (keysock_t *)q->q_ptr;
349 	keysock_stack_t	*keystack = ks->keysock_keystack;
350 
351 	/* Convert the value from a string into a long integer. */
352 	if (ddi_strtoul(value, NULL, 10, &new_value) != 0)
353 		return (EINVAL);
354 
355 	mutex_enter(&keystack->keystack_param_lock);
356 	/*
357 	 * Fail the request if the new value does not lie within the
358 	 * required bounds.
359 	 */
360 	if (new_value < keysockpa->keysock_param_min ||
361 	    new_value > keysockpa->keysock_param_max) {
362 		mutex_exit(&keystack->keystack_param_lock);
363 		return (EINVAL);
364 	}
365 
366 	/* Set the new value */
367 	keysockpa->keysock_param_value = new_value;
368 	mutex_exit(&keystack->keystack_param_lock);
369 
370 	return (0);
371 }
372 
373 /*
374  * Initialize keysock at module load time
375  */
376 boolean_t
377 keysock_ddi_init(void)
378 {
379 	keysock_max_optsize = optcom_max_optsize(
380 	    keysock_opt_obj.odb_opt_des_arr, keysock_opt_obj.odb_opt_arr_cnt);
381 
382 	keysock_vmem = vmem_create("keysock", (void *)1, MAXMIN, 1,
383 	    NULL, NULL, NULL, 1, VM_SLEEP | VMC_IDENTIFIER);
384 
385 	/*
386 	 * We want to be informed each time a stack is created or
387 	 * destroyed in the kernel, so we can maintain the
388 	 * set of keysock_stack_t's.
389 	 */
390 	netstack_register(NS_KEYSOCK, keysock_stack_init, NULL,
391 	    keysock_stack_fini);
392 
393 	return (B_TRUE);
394 }
395 
396 /*
397  * Walk through the param array specified registering each element with the
398  * named dispatch handler.
399  */
400 static boolean_t
401 keysock_param_register(IDP *ndp, keysockparam_t *ksp, int cnt)
402 {
403 	for (; cnt-- > 0; ksp++) {
404 		if (ksp->keysock_param_name != NULL &&
405 		    ksp->keysock_param_name[0]) {
406 			if (!nd_load(ndp,
407 			    ksp->keysock_param_name,
408 			    keysock_param_get, keysock_param_set,
409 			    (caddr_t)ksp)) {
410 				nd_free(ndp);
411 				return (B_FALSE);
412 			}
413 		}
414 	}
415 	return (B_TRUE);
416 }
417 
418 /*
419  * Initialize keysock for one stack instance
420  */
421 /* ARGSUSED */
422 static void *
423 keysock_stack_init(netstackid_t stackid, netstack_t *ns)
424 {
425 	keysock_stack_t	*keystack;
426 	keysockparam_t *ksp;
427 
428 	keystack = (keysock_stack_t *)kmem_zalloc(sizeof (*keystack), KM_SLEEP);
429 	keystack->keystack_netstack = ns;
430 
431 	keystack->keystack_acquire_seq = 0xffffffff;
432 
433 	ksp = (keysockparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
434 	keystack->keystack_params = ksp;
435 	bcopy(lcl_param_arr, ksp, sizeof (lcl_param_arr));
436 
437 	(void) keysock_param_register(&keystack->keystack_g_nd, ksp,
438 	    A_CNT(lcl_param_arr));
439 
440 	mutex_init(&keystack->keystack_list_lock, NULL, MUTEX_DEFAULT, NULL);
441 	mutex_init(&keystack->keystack_consumers_lock,
442 	    NULL, MUTEX_DEFAULT, NULL);
443 	mutex_init(&keystack->keystack_param_lock, NULL, MUTEX_DEFAULT, NULL);
444 	return (keystack);
445 }
446 
447 /*
448  * Free NDD variable space, and other destructors, for keysock.
449  */
450 void
451 keysock_ddi_destroy(void)
452 {
453 	netstack_unregister(NS_KEYSOCK);
454 	vmem_destroy(keysock_vmem);
455 }
456 
457 /*
458  * Remove one stack instance from keysock
459  */
460 /* ARGSUSED */
461 static void
462 keysock_stack_fini(netstackid_t stackid, void *arg)
463 {
464 	keysock_stack_t *keystack = (keysock_stack_t *)arg;
465 
466 	nd_free(&keystack->keystack_g_nd);
467 	kmem_free(keystack->keystack_params, sizeof (lcl_param_arr));
468 	keystack->keystack_params = NULL;
469 
470 	mutex_destroy(&keystack->keystack_list_lock);
471 	mutex_destroy(&keystack->keystack_consumers_lock);
472 	mutex_destroy(&keystack->keystack_param_lock);
473 
474 	kmem_free(keystack, sizeof (*keystack));
475 }
476 
477 /*
478  * Close routine for keysock.
479  */
480 static int
481 keysock_close(queue_t *q)
482 {
483 	keysock_t *ks;
484 	keysock_consumer_t *kc;
485 	void *ptr = q->q_ptr;
486 	int size;
487 	keysock_stack_t	*keystack;
488 
489 
490 	qprocsoff(q);
491 
492 	/* Safe assumption. */
493 	ASSERT(ptr != NULL);
494 
495 	if (WR(q)->q_next) {
496 		kc = (keysock_consumer_t *)ptr;
497 		keystack = kc->kc_keystack;
498 
499 		ks1dbg(keystack, ("Module close, removing a consumer (%d).\n",
500 		    kc->kc_sa_type));
501 		/*
502 		 * Because of PERMOD open/close exclusive perimeter, I
503 		 * can inspect KC_FLUSHING w/o locking down kc->kc_lock.
504 		 */
505 		if (kc->kc_flags & KC_FLUSHING) {
506 			/*
507 			 * If this decrement was the last one, send
508 			 * down the next pending one, if any.
509 			 *
510 			 * With a PERMOD perimeter, the mutexes ops aren't
511 			 * really necessary, but if we ever loosen up, we will
512 			 * have this bit covered already.
513 			 */
514 			keystack->keystack_flushdump--;
515 			if (keystack->keystack_flushdump == 0) {
516 				/*
517 				 * The flush/dump terminated by having a
518 				 * consumer go away.  I need to send up to the
519 				 * appropriate keysock all of the relevant
520 				 * information.  Unfortunately, I don't
521 				 * have that handy.
522 				 */
523 				ks0dbg(("Consumer went away while flushing or"
524 				    " dumping.\n"));
525 			}
526 		}
527 		size = sizeof (keysock_consumer_t);
528 		mutex_enter(&keystack->keystack_consumers_lock);
529 		keystack->keystack_consumers[kc->kc_sa_type] = NULL;
530 		mutex_exit(&keystack->keystack_consumers_lock);
531 		mutex_destroy(&kc->kc_lock);
532 		netstack_rele(kc->kc_keystack->keystack_netstack);
533 	} else {
534 		ks = (keysock_t *)ptr;
535 		keystack = ks->keysock_keystack;
536 
537 		ks3dbg(keystack,
538 		    ("Driver close, PF_KEY socket is going away.\n"));
539 		if ((ks->keysock_flags & KEYSOCK_EXTENDED) != 0)
540 			atomic_add_32(&keystack->keystack_num_extended, -1);
541 		size = sizeof (keysock_t);
542 		mutex_enter(&keystack->keystack_list_lock);
543 		*(ks->keysock_ptpn) = ks->keysock_next;
544 		if (ks->keysock_next != NULL)
545 			ks->keysock_next->keysock_ptpn = ks->keysock_ptpn;
546 		mutex_exit(&keystack->keystack_list_lock);
547 		mutex_destroy(&ks->keysock_lock);
548 		vmem_free(keysock_vmem, (void *)(uintptr_t)ks->keysock_serial,
549 		    1);
550 		netstack_rele(ks->keysock_keystack->keystack_netstack);
551 	}
552 
553 	/* Now I'm free. */
554 	kmem_free(ptr, size);
555 	return (0);
556 }
557 /*
558  * Open routine for keysock.
559  */
560 /* ARGSUSED */
561 static int
562 keysock_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
563 {
564 	keysock_t *ks;
565 	keysock_consumer_t *kc;
566 	mblk_t *mp;
567 	ipsec_info_t *ii;
568 	netstack_t *ns;
569 	keysock_stack_t *keystack;
570 
571 	if (secpolicy_ip_config(credp, B_FALSE) != 0) {
572 		/* Privilege debugging will log the error */
573 		return (EPERM);
574 	}
575 
576 	if (q->q_ptr != NULL)
577 		return (0);  /* Re-open of an already open instance. */
578 
579 	ns = netstack_find_by_cred(credp);
580 	ASSERT(ns != NULL);
581 	keystack = ns->netstack_keysock;
582 	ASSERT(keystack != NULL);
583 
584 	ks3dbg(keystack, ("Entering keysock open.\n"));
585 
586 	if (keystack->keystack_plumbed < 1) {
587 		netstack_t *ns = keystack->keystack_netstack;
588 
589 		keystack->keystack_plumbed = 0;
590 #ifdef NS_DEBUG
591 		printf("keysock_open(%d) - plumb\n",
592 		    keystack->keystack_netstack->netstack_stackid);
593 #endif
594 		/*
595 		 * Don't worry about ipsec_failure being true here.
596 		 * (See ip.c).  An open of keysock should try and force
597 		 * the issue.  Maybe it was a transient failure.
598 		 */
599 		ipsec_loader_loadnow(ns->netstack_ipsec);
600 	}
601 
602 	if (sflag & MODOPEN) {
603 		/* Initialize keysock_consumer state here. */
604 		kc = kmem_zalloc(sizeof (keysock_consumer_t), KM_NOSLEEP);
605 		if (kc == NULL) {
606 			netstack_rele(keystack->keystack_netstack);
607 			return (ENOMEM);
608 		}
609 		mutex_init(&kc->kc_lock, NULL, MUTEX_DEFAULT, 0);
610 		kc->kc_rq = q;
611 		kc->kc_wq = WR(q);
612 
613 		q->q_ptr = kc;
614 		WR(q)->q_ptr = kc;
615 
616 		kc->kc_keystack = keystack;
617 		qprocson(q);
618 
619 		/*
620 		 * Send down initial message to whatever I was pushed on top
621 		 * of asking for its consumer type.  The reply will set it.
622 		 */
623 
624 		/* Allocate it. */
625 		mp = allocb(sizeof (ipsec_info_t), BPRI_HI);
626 		if (mp == NULL) {
627 			ks1dbg(keystack, (
628 			    "keysock_open:  Cannot allocate KEYSOCK_HELLO.\n"));
629 			/* Do I need to set these to null? */
630 			q->q_ptr = NULL;
631 			WR(q)->q_ptr = NULL;
632 			mutex_destroy(&kc->kc_lock);
633 			kmem_free(kc, sizeof (*kc));
634 			netstack_rele(keystack->keystack_netstack);
635 			return (ENOMEM);
636 		}
637 
638 		/* If I allocated okay, putnext to what I was pushed atop. */
639 		mp->b_wptr += sizeof (ipsec_info_t);
640 		mp->b_datap->db_type = M_CTL;
641 		ii = (ipsec_info_t *)mp->b_rptr;
642 		ii->ipsec_info_type = KEYSOCK_HELLO;
643 		/* Length only of type/len. */
644 		ii->ipsec_info_len = sizeof (ii->ipsec_allu);
645 		ks2dbg(keystack, ("Ready to putnext KEYSOCK_HELLO.\n"));
646 		putnext(kc->kc_wq, mp);
647 	} else {
648 		minor_t ksminor;
649 
650 		/* Initialize keysock state. */
651 
652 		ks2dbg(keystack, ("Made it into PF_KEY socket open.\n"));
653 
654 		ksminor = (minor_t)(uintptr_t)
655 		    vmem_alloc(keysock_vmem, 1, VM_NOSLEEP);
656 		if (ksminor == 0) {
657 			netstack_rele(keystack->keystack_netstack);
658 			return (ENOMEM);
659 		}
660 		ks = kmem_zalloc(sizeof (keysock_t), KM_NOSLEEP);
661 		if (ks == NULL) {
662 			vmem_free(keysock_vmem, (void *)(uintptr_t)ksminor, 1);
663 			netstack_rele(keystack->keystack_netstack);
664 			return (ENOMEM);
665 		}
666 
667 		mutex_init(&ks->keysock_lock, NULL, MUTEX_DEFAULT, 0);
668 		ks->keysock_rq = q;
669 		ks->keysock_wq = WR(q);
670 		ks->keysock_state = TS_UNBND;
671 		ks->keysock_serial = ksminor;
672 
673 		q->q_ptr = ks;
674 		WR(q)->q_ptr = ks;
675 		ks->keysock_keystack = keystack;
676 
677 		/*
678 		 * The receive hiwat is only looked at on the stream head
679 		 * queue.  Store in q_hiwat in order to return on SO_RCVBUF
680 		 * getsockopts.
681 		 */
682 
683 		q->q_hiwat = keystack->keystack_recv_hiwat;
684 
685 		/*
686 		 * The transmit hiwat/lowat is only looked at on IP's queue.
687 		 * Store in q_hiwat/q_lowat in order to return on
688 		 * SO_SNDBUF/SO_SNDLOWAT getsockopts.
689 		 */
690 
691 		WR(q)->q_hiwat = keystack->keystack_xmit_hiwat;
692 		WR(q)->q_lowat = keystack->keystack_xmit_lowat;
693 
694 		*devp = makedevice(getmajor(*devp), ksminor);
695 
696 		/*
697 		 * Thread keysock into the global keysock list.
698 		 */
699 		mutex_enter(&keystack->keystack_list_lock);
700 		ks->keysock_next = keystack->keystack_list;
701 		ks->keysock_ptpn = &keystack->keystack_list;
702 		if (keystack->keystack_list != NULL) {
703 			keystack->keystack_list->keysock_ptpn =
704 			    &ks->keysock_next;
705 		}
706 		keystack->keystack_list = ks;
707 		mutex_exit(&keystack->keystack_list_lock);
708 
709 		qprocson(q);
710 		(void) mi_set_sth_hiwat(q, keystack->keystack_recv_hiwat);
711 		/*
712 		 * Wait outside the keysock module perimeter for IPsec
713 		 * plumbing to be completed.  If it fails, keysock_close()
714 		 * undoes everything we just did.
715 		 */
716 		if (!ipsec_loader_wait(q,
717 		    keystack->keystack_netstack->netstack_ipsec)) {
718 			(void) keysock_close(q);
719 			return (EPFNOSUPPORT);
720 		}
721 	}
722 
723 	return (0);
724 }
725 
726 /* BELOW THIS LINE ARE ROUTINES INCLUDING AND RELATED TO keysock_wput(). */
727 
728 /*
729  * Copy relevant state bits.
730  */
731 static void
732 keysock_copy_info(struct T_info_ack *tap, keysock_t *ks)
733 {
734 	*tap = keysock_g_t_info_ack;
735 	tap->CURRENT_state = ks->keysock_state;
736 	tap->OPT_size = keysock_max_optsize;
737 }
738 
739 /*
740  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
741  * keysock_wput.  Much of the T_CAPABILITY_ACK information is copied from
742  * keysock_g_t_info_ack.  The current state of the stream is copied from
743  * keysock_state.
744  */
745 static void
746 keysock_capability_req(queue_t *q, mblk_t *mp)
747 {
748 	keysock_t *ks = (keysock_t *)q->q_ptr;
749 	t_uscalar_t cap_bits1;
750 	struct T_capability_ack	*tcap;
751 
752 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
753 
754 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
755 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
756 	if (mp == NULL)
757 		return;
758 
759 	tcap = (struct T_capability_ack *)mp->b_rptr;
760 	tcap->CAP_bits1 = 0;
761 
762 	if (cap_bits1 & TC1_INFO) {
763 		keysock_copy_info(&tcap->INFO_ack, ks);
764 		tcap->CAP_bits1 |= TC1_INFO;
765 	}
766 
767 	qreply(q, mp);
768 }
769 
770 /*
771  * This routine responds to T_INFO_REQ messages. It is called by
772  * keysock_wput_other.
773  * Most of the T_INFO_ACK information is copied from keysock_g_t_info_ack.
774  * The current state of the stream is copied from keysock_state.
775  */
776 static void
777 keysock_info_req(q, mp)
778 	queue_t	*q;
779 	mblk_t	*mp;
780 {
781 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
782 	    T_INFO_ACK);
783 	if (mp == NULL)
784 		return;
785 	keysock_copy_info((struct T_info_ack *)mp->b_rptr,
786 	    (keysock_t *)q->q_ptr);
787 	qreply(q, mp);
788 }
789 
790 /*
791  * keysock_err_ack. This routine creates a
792  * T_ERROR_ACK message and passes it
793  * upstream.
794  */
795 static void
796 keysock_err_ack(q, mp, t_error, sys_error)
797 	queue_t	*q;
798 	mblk_t	*mp;
799 	int	t_error;
800 	int	sys_error;
801 {
802 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
803 		qreply(q, mp);
804 }
805 
806 /*
807  * This routine retrieves the current status of socket options.
808  * It returns the size of the option retrieved.
809  */
810 /* ARGSUSED */
811 int
812 keysock_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
813 {
814 	int *i1 = (int *)ptr;
815 	keysock_t *ks = (keysock_t *)q->q_ptr;
816 
817 	switch (level) {
818 	case SOL_SOCKET:
819 		mutex_enter(&ks->keysock_lock);
820 		switch (name) {
821 		case SO_TYPE:
822 			*i1 = SOCK_RAW;
823 			break;
824 		case SO_USELOOPBACK:
825 			*i1 = (int)(!((ks->keysock_flags & KEYSOCK_NOLOOP) ==
826 			    KEYSOCK_NOLOOP));
827 			break;
828 		/*
829 		 * The following two items can be manipulated,
830 		 * but changing them should do nothing.
831 		 */
832 		case SO_SNDBUF:
833 			*i1 = (int)q->q_hiwat;
834 			break;
835 		case SO_RCVBUF:
836 			*i1 = (int)(RD(q)->q_hiwat);
837 			break;
838 		}
839 		mutex_exit(&ks->keysock_lock);
840 		break;
841 	default:
842 		return (0);
843 	}
844 	return (sizeof (int));
845 }
846 
847 /*
848  * This routine sets socket options.
849  */
850 /* ARGSUSED */
851 int
852 keysock_opt_set(queue_t *q, uint_t mgmt_flags, int level,
853     int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
854     uchar_t *outvalp, void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
855 {
856 	int *i1 = (int *)invalp;
857 	keysock_t *ks = (keysock_t *)q->q_ptr;
858 	keysock_stack_t	*keystack = ks->keysock_keystack;
859 
860 	switch (level) {
861 	case SOL_SOCKET:
862 		mutex_enter(&ks->keysock_lock);
863 		switch (name) {
864 		case SO_USELOOPBACK:
865 			if (!(*i1))
866 				ks->keysock_flags |= KEYSOCK_NOLOOP;
867 			else ks->keysock_flags &= ~KEYSOCK_NOLOOP;
868 			break;
869 		case SO_SNDBUF:
870 			if (*i1 > keystack->keystack_max_buf)
871 				return (ENOBUFS);
872 			q->q_hiwat = *i1;
873 			break;
874 		case SO_RCVBUF:
875 			if (*i1 > keystack->keystack_max_buf)
876 				return (ENOBUFS);
877 			RD(q)->q_hiwat = *i1;
878 			(void) mi_set_sth_hiwat(RD(q), *i1);
879 			break;
880 		}
881 		mutex_exit(&ks->keysock_lock);
882 		break;
883 	}
884 	return (0);
885 }
886 
887 /*
888  * Handle STREAMS messages.
889  */
890 static void
891 keysock_wput_other(queue_t *q, mblk_t *mp)
892 {
893 	struct iocblk *iocp;
894 	int error;
895 	keysock_t *ks = (keysock_t *)q->q_ptr;
896 	keysock_stack_t	*keystack = ks->keysock_keystack;
897 	cred_t		*cr;
898 
899 	switch (mp->b_datap->db_type) {
900 	case M_PROTO:
901 	case M_PCPROTO:
902 		if ((mp->b_wptr - mp->b_rptr) < sizeof (long)) {
903 			ks3dbg(keystack, (
904 			    "keysock_wput_other: Not big enough M_PROTO\n"));
905 			freemsg(mp);
906 			return;
907 		}
908 		cr = zone_get_kcred(netstackid_to_zoneid(
909 		    keystack->keystack_netstack->netstack_stackid));
910 		ASSERT(cr != NULL);
911 
912 		switch (((union T_primitives *)mp->b_rptr)->type) {
913 		case T_CAPABILITY_REQ:
914 			keysock_capability_req(q, mp);
915 			break;
916 		case T_INFO_REQ:
917 			keysock_info_req(q, mp);
918 			break;
919 		case T_SVR4_OPTMGMT_REQ:
920 			(void) svr4_optcom_req(q, mp, DB_CREDDEF(mp, cr),
921 			    &keysock_opt_obj, B_FALSE);
922 			break;
923 		case T_OPTMGMT_REQ:
924 			(void) tpi_optcom_req(q, mp, DB_CREDDEF(mp, cr),
925 			    &keysock_opt_obj, B_FALSE);
926 			break;
927 		case T_DATA_REQ:
928 		case T_EXDATA_REQ:
929 		case T_ORDREL_REQ:
930 			/* Illegal for keysock. */
931 			freemsg(mp);
932 			(void) putnextctl1(RD(q), M_ERROR, EPROTO);
933 			break;
934 		default:
935 			/* Not supported by keysock. */
936 			keysock_err_ack(q, mp, TNOTSUPPORT, 0);
937 			break;
938 		}
939 		crfree(cr);
940 		return;
941 	case M_IOCTL:
942 		iocp = (struct iocblk *)mp->b_rptr;
943 		error = EINVAL;
944 
945 		switch (iocp->ioc_cmd) {
946 		case ND_SET:
947 		case ND_GET:
948 			if (nd_getset(q, keystack->keystack_g_nd, mp)) {
949 				qreply(q, mp);
950 				return;
951 			} else
952 				error = ENOENT;
953 			/* FALLTHRU */
954 		default:
955 			miocnak(q, mp, 0, error);
956 			return;
957 		}
958 	case M_FLUSH:
959 		if (*mp->b_rptr & FLUSHW) {
960 			flushq(q, FLUSHALL);
961 			*mp->b_rptr &= ~FLUSHW;
962 		}
963 		if (*mp->b_rptr & FLUSHR) {
964 			qreply(q, mp);
965 			return;
966 		}
967 		/* Else FALLTHRU */
968 	}
969 
970 	/* If fell through, just black-hole the message. */
971 	freemsg(mp);
972 }
973 
974 /*
975  * Transmit a PF_KEY error message to the instance either pointed to
976  * by ks, the instance with serial number serial, or more, depending.
977  *
978  * The faulty message (or a reasonable facsimile thereof) is in mp.
979  * This function will free mp or recycle it for delivery, thereby causing
980  * the stream head to free it.
981  */
982 static void
983 keysock_error(keysock_t *ks, mblk_t *mp, int error, int diagnostic)
984 {
985 	sadb_msg_t *samsg = (sadb_msg_t *)mp->b_rptr;
986 	keysock_stack_t	*keystack = ks->keysock_keystack;
987 
988 	ASSERT(mp->b_datap->db_type == M_DATA);
989 
990 	if (samsg->sadb_msg_type < SADB_GETSPI ||
991 	    samsg->sadb_msg_type > SADB_MAX)
992 		samsg->sadb_msg_type = SADB_RESERVED;
993 
994 	/*
995 	 * Strip out extension headers.
996 	 */
997 	ASSERT(mp->b_rptr + sizeof (*samsg) <= mp->b_datap->db_lim);
998 	mp->b_wptr = mp->b_rptr + sizeof (*samsg);
999 	samsg->sadb_msg_len = SADB_8TO64(sizeof (sadb_msg_t));
1000 	samsg->sadb_msg_errno = (uint8_t)error;
1001 	samsg->sadb_x_msg_diagnostic = (uint16_t)diagnostic;
1002 
1003 	keysock_passup(mp, samsg, ks->keysock_serial, NULL, B_FALSE, keystack);
1004 }
1005 
1006 /*
1007  * Pass down a message to a consumer.  Wrap it in KEYSOCK_IN, and copy
1008  * in the extv if passed in.
1009  */
1010 static void
1011 keysock_passdown(keysock_t *ks, mblk_t *mp, uint8_t satype, sadb_ext_t *extv[],
1012     boolean_t flushmsg)
1013 {
1014 	keysock_consumer_t *kc;
1015 	mblk_t *wrapper;
1016 	keysock_in_t *ksi;
1017 	int i;
1018 	keysock_stack_t	*keystack = ks->keysock_keystack;
1019 
1020 	wrapper = allocb(sizeof (ipsec_info_t), BPRI_HI);
1021 	if (wrapper == NULL) {
1022 		ks3dbg(keystack, ("keysock_passdown: allocb failed.\n"));
1023 		if (extv[SADB_EXT_KEY_ENCRYPT] != NULL)
1024 			bzero(extv[SADB_EXT_KEY_ENCRYPT],
1025 			    SADB_64TO8(
1026 			    extv[SADB_EXT_KEY_ENCRYPT]->sadb_ext_len));
1027 		if (extv[SADB_EXT_KEY_AUTH] != NULL)
1028 			bzero(extv[SADB_EXT_KEY_AUTH],
1029 			    SADB_64TO8(
1030 			    extv[SADB_EXT_KEY_AUTH]->sadb_ext_len));
1031 		if (flushmsg) {
1032 			ks0dbg((
1033 			    "keysock: Downwards flush/dump message failed!\n"));
1034 			/* If this is true, I hold the perimeter. */
1035 			keystack->keystack_flushdump--;
1036 		}
1037 		freemsg(mp);
1038 		return;
1039 	}
1040 
1041 	wrapper->b_datap->db_type = M_CTL;
1042 	ksi = (keysock_in_t *)wrapper->b_rptr;
1043 	ksi->ks_in_type = KEYSOCK_IN;
1044 	ksi->ks_in_len = sizeof (keysock_in_t);
1045 	if (extv[SADB_EXT_ADDRESS_SRC] != NULL)
1046 		ksi->ks_in_srctype = KS_IN_ADDR_UNKNOWN;
1047 	else ksi->ks_in_srctype = KS_IN_ADDR_NOTTHERE;
1048 	if (extv[SADB_EXT_ADDRESS_DST] != NULL)
1049 		ksi->ks_in_dsttype = KS_IN_ADDR_UNKNOWN;
1050 	else ksi->ks_in_dsttype = KS_IN_ADDR_NOTTHERE;
1051 	for (i = 0; i <= SADB_EXT_MAX; i++)
1052 		ksi->ks_in_extv[i] = extv[i];
1053 	ksi->ks_in_serial = ks->keysock_serial;
1054 	wrapper->b_wptr += sizeof (ipsec_info_t);
1055 	wrapper->b_cont = mp;
1056 
1057 	/*
1058 	 * Find the appropriate consumer where the message is passed down.
1059 	 */
1060 	kc = keystack->keystack_consumers[satype];
1061 	if (kc == NULL) {
1062 		freeb(wrapper);
1063 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE);
1064 		if (flushmsg) {
1065 			ks0dbg((
1066 			    "keysock: Downwards flush/dump message failed!\n"));
1067 			/* If this is true, I hold the perimeter. */
1068 			keystack->keystack_flushdump--;
1069 		}
1070 		return;
1071 	}
1072 
1073 	/*
1074 	 * NOTE: There used to be code in here to spin while a flush or
1075 	 *	 dump finished.  Keysock now assumes that consumers have enough
1076 	 *	 MT-savviness to deal with that.
1077 	 */
1078 
1079 	/*
1080 	 * Current consumers (AH and ESP) are guaranteed to return a
1081 	 * FLUSH or DUMP message back, so when we reach here, we don't
1082 	 * have to worry about keysock_flushdumps.
1083 	 */
1084 
1085 	putnext(kc->kc_wq, wrapper);
1086 }
1087 
1088 /*
1089  * High-level reality checking of extensions.
1090  */
1091 static boolean_t
1092 ext_check(sadb_ext_t *ext, keysock_stack_t *keystack)
1093 {
1094 	int i;
1095 	uint64_t *lp;
1096 	sadb_ident_t *id;
1097 	char *idstr;
1098 
1099 	switch (ext->sadb_ext_type) {
1100 	case SADB_EXT_ADDRESS_SRC:
1101 	case SADB_EXT_ADDRESS_DST:
1102 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1103 	case SADB_X_EXT_ADDRESS_INNER_DST:
1104 		/* Check for at least enough addtl length for a sockaddr. */
1105 		if (ext->sadb_ext_len <= SADB_8TO64(sizeof (sadb_address_t)))
1106 			return (B_FALSE);
1107 		break;
1108 	case SADB_EXT_LIFETIME_HARD:
1109 	case SADB_EXT_LIFETIME_SOFT:
1110 	case SADB_EXT_LIFETIME_CURRENT:
1111 		if (ext->sadb_ext_len != SADB_8TO64(sizeof (sadb_lifetime_t)))
1112 			return (B_FALSE);
1113 		break;
1114 	case SADB_EXT_SPIRANGE:
1115 		/* See if the SPI range is legit. */
1116 		if (htonl(((sadb_spirange_t *)ext)->sadb_spirange_min) >
1117 		    htonl(((sadb_spirange_t *)ext)->sadb_spirange_max))
1118 			return (B_FALSE);
1119 		break;
1120 	case SADB_EXT_KEY_AUTH:
1121 	case SADB_EXT_KEY_ENCRYPT:
1122 		/* Key length check. */
1123 		if (((sadb_key_t *)ext)->sadb_key_bits == 0)
1124 			return (B_FALSE);
1125 		/*
1126 		 * Check to see if the key length (in bits) is less than the
1127 		 * extension length (in 8-bits words).
1128 		 */
1129 		if ((roundup(SADB_1TO8(((sadb_key_t *)ext)->sadb_key_bits), 8) +
1130 		    sizeof (sadb_key_t)) != SADB_64TO8(ext->sadb_ext_len)) {
1131 			ks1dbg(keystack, (
1132 			    "ext_check:  Key bits/length inconsistent.\n"));
1133 			ks1dbg(keystack, ("%d bits, len is %d bytes.\n",
1134 			    ((sadb_key_t *)ext)->sadb_key_bits,
1135 			    SADB_64TO8(ext->sadb_ext_len)));
1136 			return (B_FALSE);
1137 		}
1138 
1139 		/* All-zeroes key check. */
1140 		lp = (uint64_t *)(((char *)ext) + sizeof (sadb_key_t));
1141 		for (i = 0;
1142 		    i < (ext->sadb_ext_len - SADB_8TO64(sizeof (sadb_key_t)));
1143 		    i++)
1144 			if (lp[i] != 0)
1145 				break;	/* Out of for loop. */
1146 		/* If finished the loop naturally, it's an all zero key. */
1147 		if (lp[i] == 0)
1148 			return (B_FALSE);
1149 		break;
1150 	case SADB_EXT_IDENTITY_SRC:
1151 	case SADB_EXT_IDENTITY_DST:
1152 		/*
1153 		 * Make sure the strings in these identities are
1154 		 * null-terminated.  RFC 2367 underspecified how to handle
1155 		 * such a case.  I "proactively" null-terminate the string
1156 		 * at the last byte if it's not terminated sooner.
1157 		 */
1158 		id = (sadb_ident_t *)ext;
1159 		i = SADB_64TO8(id->sadb_ident_len);
1160 		i -= sizeof (sadb_ident_t);
1161 		idstr = (char *)(id + 1);
1162 		while (*idstr != '\0' && i > 0) {
1163 			i--;
1164 			idstr++;
1165 		}
1166 		if (i == 0) {
1167 			/*
1168 			 * I.e., if the bozo user didn't NULL-terminate the
1169 			 * string...
1170 			 */
1171 			idstr--;
1172 			*idstr = '\0';
1173 		}
1174 		break;
1175 	}
1176 	return (B_TRUE);	/* For now... */
1177 }
1178 
1179 /* Return values for keysock_get_ext(). */
1180 #define	KGE_OK	0
1181 #define	KGE_DUP	1
1182 #define	KGE_UNK	2
1183 #define	KGE_LEN	3
1184 #define	KGE_CHK	4
1185 
1186 /*
1187  * Parse basic extension headers and return in the passed-in pointer vector.
1188  * Return values include:
1189  *
1190  *	KGE_OK	Everything's nice and parsed out.
1191  *		If there are no extensions, place NULL in extv[0].
1192  *	KGE_DUP	There is a duplicate extension.
1193  *		First instance in appropriate bin.  First duplicate in
1194  *		extv[0].
1195  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
1196  *		unknown header.
1197  *	KGE_LEN	Extension length error.
1198  *	KGE_CHK	High-level reality check failed on specific extension.
1199  *
1200  * My apologies for some of the pointer arithmetic in here.  I'm thinking
1201  * like an assembly programmer, yet trying to make the compiler happy.
1202  */
1203 static int
1204 keysock_get_ext(sadb_ext_t *extv[], sadb_msg_t *basehdr, uint_t msgsize,
1205     keysock_stack_t *keystack)
1206 {
1207 	bzero(extv, sizeof (sadb_ext_t *) * (SADB_EXT_MAX + 1));
1208 
1209 	/* Use extv[0] as the "current working pointer". */
1210 
1211 	extv[0] = (sadb_ext_t *)(basehdr + 1);
1212 
1213 	while (extv[0] < (sadb_ext_t *)(((uint8_t *)basehdr) + msgsize)) {
1214 		/* Check for unknown headers. */
1215 		if (extv[0]->sadb_ext_type == 0 ||
1216 		    extv[0]->sadb_ext_type > SADB_EXT_MAX)
1217 			return (KGE_UNK);
1218 
1219 		/*
1220 		 * Check length.  Use uint64_t because extlen is in units
1221 		 * of 64-bit words.  If length goes beyond the msgsize,
1222 		 * return an error.  (Zero length also qualifies here.)
1223 		 */
1224 		if (extv[0]->sadb_ext_len == 0 ||
1225 		    (void *)((uint64_t *)extv[0] + extv[0]->sadb_ext_len) >
1226 		    (void *)((uint8_t *)basehdr + msgsize))
1227 			return (KGE_LEN);
1228 
1229 		/* Check for redundant headers. */
1230 		if (extv[extv[0]->sadb_ext_type] != NULL)
1231 			return (KGE_DUP);
1232 
1233 		/*
1234 		 * Reality check the extension if possible at the keysock
1235 		 * level.
1236 		 */
1237 		if (!ext_check(extv[0], keystack))
1238 			return (KGE_CHK);
1239 
1240 		/* If I make it here, assign the appropriate bin. */
1241 		extv[extv[0]->sadb_ext_type] = extv[0];
1242 
1243 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
1244 		extv[0] = (sadb_ext_t *)
1245 		    ((uint64_t *)extv[0] + extv[0]->sadb_ext_len);
1246 	}
1247 
1248 	/* Everything's cool. */
1249 
1250 	/*
1251 	 * If extv[0] == NULL, then there are no extension headers in this
1252 	 * message.  Ensure that this is the case.
1253 	 */
1254 	if (extv[0] == (sadb_ext_t *)(basehdr + 1))
1255 		extv[0] = NULL;
1256 
1257 	return (KGE_OK);
1258 }
1259 
1260 /*
1261  * qwriter() callback to handle flushes and dumps.  This routine will hold
1262  * the inner perimeter.
1263  */
1264 void
1265 keysock_do_flushdump(queue_t *q, mblk_t *mp)
1266 {
1267 	int i, start, finish;
1268 	mblk_t *mp1 = NULL;
1269 	keysock_t *ks = (keysock_t *)q->q_ptr;
1270 	sadb_ext_t *extv[SADB_EXT_MAX + 1];
1271 	sadb_msg_t *samsg = (sadb_msg_t *)mp->b_rptr;
1272 	keysock_stack_t	*keystack = ks->keysock_keystack;
1273 
1274 	/*
1275 	 * I am guaranteed this will work.  I did the work in keysock_parse()
1276 	 * already.
1277 	 */
1278 	(void) keysock_get_ext(extv, samsg, SADB_64TO8(samsg->sadb_msg_len),
1279 	    keystack);
1280 
1281 	/*
1282 	 * I hold the perimeter, therefore I don't need to use atomic ops.
1283 	 */
1284 	if (keystack->keystack_flushdump != 0) {
1285 		/* XXX Should I instead use EBUSY? */
1286 		/* XXX Or is there a way to queue these up? */
1287 		keysock_error(ks, mp, ENOMEM, SADB_X_DIAGNOSTIC_NONE);
1288 		return;
1289 	}
1290 
1291 	if (samsg->sadb_msg_satype == SADB_SATYPE_UNSPEC) {
1292 		start = 0;
1293 		finish = KEYSOCK_MAX_CONSUMERS - 1;
1294 	} else {
1295 		start = samsg->sadb_msg_satype;
1296 		finish = samsg->sadb_msg_satype;
1297 	}
1298 
1299 	/*
1300 	 * Fill up keysock_flushdump with the number of outstanding dumps
1301 	 * and/or flushes.
1302 	 */
1303 
1304 	keystack->keystack_flushdump_errno = 0;
1305 
1306 	/*
1307 	 * Okay, I hold the perimeter.  Eventually keysock_flushdump will
1308 	 * contain the number of consumers with outstanding flush operations.
1309 	 *
1310 	 * SO, here's the plan:
1311 	 *	* For each relevant consumer (Might be one, might be all)
1312 	 *		* Twiddle on the FLUSHING flag.
1313 	 *		* Pass down the FLUSH/DUMP message.
1314 	 *
1315 	 * When I see upbound FLUSH/DUMP messages, I will decrement the
1316 	 * keysock_flushdump.  When I decrement it to 0, I will pass the
1317 	 * FLUSH/DUMP message back up to the PF_KEY sockets.  Because I will
1318 	 * pass down the right SA type to the consumer (either its own, or
1319 	 * that of UNSPEC), the right one will be reflected from each consumer,
1320 	 * and accordingly back to the socket.
1321 	 */
1322 
1323 	mutex_enter(&keystack->keystack_consumers_lock);
1324 	for (i = start; i <= finish; i++) {
1325 		if (keystack->keystack_consumers[i] != NULL) {
1326 			mp1 = copymsg(mp);
1327 			if (mp1 == NULL) {
1328 				ks0dbg(("SADB_FLUSH copymsg() failed.\n"));
1329 				/*
1330 				 * Error?  And what about outstanding
1331 				 * flushes?  Oh, yeah, they get sucked up and
1332 				 * the counter is decremented.  Consumers
1333 				 * (see keysock_passdown()) are guaranteed
1334 				 * to deliver back a flush request, even if
1335 				 * it's an error.
1336 				 */
1337 				keysock_error(ks, mp, ENOMEM,
1338 				    SADB_X_DIAGNOSTIC_NONE);
1339 				return;
1340 			}
1341 			/*
1342 			 * Because my entry conditions are met above, the
1343 			 * following assertion should hold true.
1344 			 */
1345 			mutex_enter(&keystack->keystack_consumers[i]->kc_lock);
1346 			ASSERT((keystack->keystack_consumers[i]->kc_flags &
1347 			    KC_FLUSHING) == 0);
1348 			keystack->keystack_consumers[i]->kc_flags |=
1349 			    KC_FLUSHING;
1350 			mutex_exit(&(keystack->keystack_consumers[i]->kc_lock));
1351 			/* Always increment the number of flushes... */
1352 			keystack->keystack_flushdump++;
1353 			/* Guaranteed to return a message. */
1354 			keysock_passdown(ks, mp1, i, extv, B_TRUE);
1355 		} else if (start == finish) {
1356 			/*
1357 			 * In case where start == finish, and there's no
1358 			 * consumer, should we force an error?  Yes.
1359 			 */
1360 			mutex_exit(&keystack->keystack_consumers_lock);
1361 			keysock_error(ks, mp, EINVAL,
1362 			    SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE);
1363 			return;
1364 		}
1365 	}
1366 	mutex_exit(&keystack->keystack_consumers_lock);
1367 
1368 	if (keystack->keystack_flushdump == 0) {
1369 		/*
1370 		 * There were no consumers at all for this message.
1371 		 * XXX For now return ESRCH.
1372 		 */
1373 		keysock_error(ks, mp, ESRCH, SADB_X_DIAGNOSTIC_NO_SADBS);
1374 	} else {
1375 		/* Otherwise, free the original message. */
1376 		freemsg(mp);
1377 	}
1378 }
1379 
1380 /*
1381  * Get the right diagnostic for a duplicate.  Should probably use a static
1382  * table lookup.
1383  */
1384 int
1385 keysock_duplicate(int ext_type)
1386 {
1387 	int rc = 0;
1388 
1389 	switch (ext_type) {
1390 	case SADB_EXT_ADDRESS_SRC:
1391 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_SRC;
1392 		break;
1393 	case SADB_EXT_ADDRESS_DST:
1394 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_DST;
1395 		break;
1396 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1397 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_INNER_SRC;
1398 		break;
1399 	case SADB_X_EXT_ADDRESS_INNER_DST:
1400 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_INNER_DST;
1401 		break;
1402 	case SADB_EXT_SA:
1403 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_SA;
1404 		break;
1405 	case SADB_EXT_SPIRANGE:
1406 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_RANGE;
1407 		break;
1408 	case SADB_EXT_KEY_AUTH:
1409 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_AKEY;
1410 		break;
1411 	case SADB_EXT_KEY_ENCRYPT:
1412 		rc = SADB_X_DIAGNOSTIC_DUPLICATE_EKEY;
1413 		break;
1414 	}
1415 	return (rc);
1416 }
1417 
1418 /*
1419  * Get the right diagnostic for a reality check failure.  Should probably use
1420  * a static table lookup.
1421  */
1422 int
1423 keysock_malformed(int ext_type)
1424 {
1425 	int rc = 0;
1426 
1427 	switch (ext_type) {
1428 	case SADB_EXT_ADDRESS_SRC:
1429 		rc = SADB_X_DIAGNOSTIC_MALFORMED_SRC;
1430 		break;
1431 	case SADB_EXT_ADDRESS_DST:
1432 		rc = SADB_X_DIAGNOSTIC_MALFORMED_DST;
1433 		break;
1434 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1435 		rc = SADB_X_DIAGNOSTIC_MALFORMED_INNER_SRC;
1436 		break;
1437 	case SADB_X_EXT_ADDRESS_INNER_DST:
1438 		rc = SADB_X_DIAGNOSTIC_MALFORMED_INNER_DST;
1439 		break;
1440 	case SADB_EXT_SA:
1441 		rc = SADB_X_DIAGNOSTIC_MALFORMED_SA;
1442 		break;
1443 	case SADB_EXT_SPIRANGE:
1444 		rc = SADB_X_DIAGNOSTIC_MALFORMED_RANGE;
1445 		break;
1446 	case SADB_EXT_KEY_AUTH:
1447 		rc = SADB_X_DIAGNOSTIC_MALFORMED_AKEY;
1448 		break;
1449 	case SADB_EXT_KEY_ENCRYPT:
1450 		rc = SADB_X_DIAGNOSTIC_MALFORMED_EKEY;
1451 		break;
1452 	}
1453 	return (rc);
1454 }
1455 
1456 /*
1457  * Keysock massaging of an inverse ACQUIRE.  Consult policy,
1458  * and construct an appropriate response.
1459  */
1460 static void
1461 keysock_inverse_acquire(mblk_t *mp, sadb_msg_t *samsg, sadb_ext_t *extv[],
1462     keysock_t *ks)
1463 {
1464 	mblk_t *reply_mp;
1465 	keysock_stack_t	*keystack = ks->keysock_keystack;
1466 
1467 	/*
1468 	 * Reality check things...
1469 	 */
1470 	if (extv[SADB_EXT_ADDRESS_SRC] == NULL) {
1471 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_MISSING_SRC);
1472 		return;
1473 	}
1474 	if (extv[SADB_EXT_ADDRESS_DST] == NULL) {
1475 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_MISSING_DST);
1476 		return;
1477 	}
1478 
1479 	if (extv[SADB_X_EXT_ADDRESS_INNER_SRC] != NULL &&
1480 	    extv[SADB_X_EXT_ADDRESS_INNER_DST] == NULL) {
1481 		keysock_error(ks, mp, EINVAL,
1482 		    SADB_X_DIAGNOSTIC_MISSING_INNER_DST);
1483 		return;
1484 	}
1485 
1486 	if (extv[SADB_X_EXT_ADDRESS_INNER_SRC] == NULL &&
1487 	    extv[SADB_X_EXT_ADDRESS_INNER_DST] != NULL) {
1488 		keysock_error(ks, mp, EINVAL,
1489 		    SADB_X_DIAGNOSTIC_MISSING_INNER_SRC);
1490 		return;
1491 	}
1492 
1493 	reply_mp = ipsec_construct_inverse_acquire(samsg, extv,
1494 	    keystack->keystack_netstack);
1495 
1496 	if (reply_mp != NULL) {
1497 		freemsg(mp);
1498 		keysock_passup(reply_mp, (sadb_msg_t *)reply_mp->b_rptr,
1499 		    ks->keysock_serial, NULL, B_FALSE, keystack);
1500 	} else {
1501 		keysock_error(ks, mp, samsg->sadb_msg_errno,
1502 		    samsg->sadb_x_msg_diagnostic);
1503 	}
1504 }
1505 
1506 /*
1507  * Spew an extended REGISTER down to the relevant consumers.
1508  */
1509 static void
1510 keysock_extended_register(keysock_t *ks, mblk_t *mp, sadb_ext_t *extv[])
1511 {
1512 	sadb_x_ereg_t *ereg = (sadb_x_ereg_t *)extv[SADB_X_EXT_EREG];
1513 	uint8_t *satypes, *fencepost;
1514 	mblk_t *downmp;
1515 	sadb_ext_t *downextv[SADB_EXT_MAX + 1];
1516 	keysock_stack_t	*keystack = ks->keysock_keystack;
1517 
1518 	if (ks->keysock_registered[0] != 0 || ks->keysock_registered[1] != 0 ||
1519 	    ks->keysock_registered[2] != 0 || ks->keysock_registered[3] != 0) {
1520 		keysock_error(ks, mp, EBUSY, 0);
1521 	}
1522 
1523 	ks->keysock_flags |= KEYSOCK_EXTENDED;
1524 	if (ereg == NULL) {
1525 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_SATYPE_NEEDED);
1526 	} else {
1527 		ASSERT(mp->b_rptr + msgdsize(mp) == mp->b_wptr);
1528 		fencepost = (uint8_t *)mp->b_wptr;
1529 		satypes = ereg->sadb_x_ereg_satypes;
1530 		while (*satypes != SADB_SATYPE_UNSPEC && satypes != fencepost) {
1531 			downmp = copymsg(mp);
1532 			if (downmp == NULL) {
1533 				keysock_error(ks, mp, ENOMEM, 0);
1534 				return;
1535 			}
1536 			/*
1537 			 * Since we've made it here, keysock_get_ext will work!
1538 			 */
1539 			(void) keysock_get_ext(downextv,
1540 			    (sadb_msg_t *)downmp->b_rptr, msgdsize(downmp),
1541 			    keystack);
1542 			keysock_passdown(ks, downmp, *satypes, downextv,
1543 			    B_FALSE);
1544 			++satypes;
1545 		}
1546 		freemsg(mp);
1547 	}
1548 
1549 	/*
1550 	 * Set global to indicate we prefer an extended ACQUIRE.
1551 	 */
1552 	atomic_add_32(&keystack->keystack_num_extended, 1);
1553 }
1554 
1555 static void
1556 keysock_delpair_all(keysock_t *ks, mblk_t *mp, sadb_ext_t *extv[])
1557 {
1558 	int i, start, finish;
1559 	mblk_t *mp1 = NULL;
1560 	keysock_stack_t *keystack = ks->keysock_keystack;
1561 
1562 	start = 0;
1563 	finish = KEYSOCK_MAX_CONSUMERS - 1;
1564 
1565 	for (i = start; i <= finish; i++) {
1566 		if (keystack->keystack_consumers[i] != NULL) {
1567 			mp1 = copymsg(mp);
1568 			if (mp1 == NULL) {
1569 				keysock_error(ks, mp, ENOMEM,
1570 				    SADB_X_DIAGNOSTIC_NONE);
1571 				return;
1572 			}
1573 			keysock_passdown(ks, mp1, i, extv, B_FALSE);
1574 		}
1575 	}
1576 }
1577 
1578 /*
1579  * Handle PF_KEY messages.
1580  */
1581 static void
1582 keysock_parse(queue_t *q, mblk_t *mp)
1583 {
1584 	sadb_msg_t *samsg;
1585 	sadb_ext_t *extv[SADB_EXT_MAX + 1];
1586 	keysock_t *ks = (keysock_t *)q->q_ptr;
1587 	uint_t msgsize;
1588 	uint8_t satype;
1589 	keysock_stack_t	*keystack = ks->keysock_keystack;
1590 
1591 	/* Make sure I'm a PF_KEY socket.  (i.e. nothing's below me) */
1592 	ASSERT(WR(q)->q_next == NULL);
1593 
1594 	samsg = (sadb_msg_t *)mp->b_rptr;
1595 	ks2dbg(keystack, ("Received possible PF_KEY message, type %d.\n",
1596 	    samsg->sadb_msg_type));
1597 
1598 	msgsize = SADB_64TO8(samsg->sadb_msg_len);
1599 
1600 	if (msgdsize(mp) != msgsize) {
1601 		/*
1602 		 * Message len incorrect w.r.t. actual size.  Send an error
1603 		 * (EMSGSIZE).	It may be necessary to massage things a
1604 		 * bit.	 For example, if the sadb_msg_type is hosed,
1605 		 * I need to set it to SADB_RESERVED to get delivery to
1606 		 * do the right thing.	Then again, maybe just letting
1607 		 * the error delivery do the right thing.
1608 		 */
1609 		ks2dbg(keystack,
1610 		    ("mblk (%lu) and base (%d) message sizes don't jibe.\n",
1611 		    msgdsize(mp), msgsize));
1612 		keysock_error(ks, mp, EMSGSIZE, SADB_X_DIAGNOSTIC_NONE);
1613 		return;
1614 	}
1615 
1616 	if (msgsize > (uint_t)(mp->b_wptr - mp->b_rptr)) {
1617 		/* Get all message into one mblk. */
1618 		if (pullupmsg(mp, -1) == 0) {
1619 			/*
1620 			 * Something screwy happened.
1621 			 */
1622 			ks3dbg(keystack,
1623 			    ("keysock_parse: pullupmsg() failed.\n"));
1624 			return;
1625 		} else {
1626 			samsg = (sadb_msg_t *)mp->b_rptr;
1627 		}
1628 	}
1629 
1630 	switch (keysock_get_ext(extv, samsg, msgsize, keystack)) {
1631 	case KGE_DUP:
1632 		/* Handle duplicate extension. */
1633 		ks1dbg(keystack, ("Got duplicate extension of type %d.\n",
1634 		    extv[0]->sadb_ext_type));
1635 		keysock_error(ks, mp, EINVAL,
1636 		    keysock_duplicate(extv[0]->sadb_ext_type));
1637 		return;
1638 	case KGE_UNK:
1639 		/* Handle unknown extension. */
1640 		ks1dbg(keystack, ("Got unknown extension of type %d.\n",
1641 		    extv[0]->sadb_ext_type));
1642 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_UNKNOWN_EXT);
1643 		return;
1644 	case KGE_LEN:
1645 		/* Length error. */
1646 		ks1dbg(keystack,
1647 		    ("Length %d on extension type %d overrun or 0.\n",
1648 		    extv[0]->sadb_ext_len, extv[0]->sadb_ext_type));
1649 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_BAD_EXTLEN);
1650 		return;
1651 	case KGE_CHK:
1652 		/* Reality check failed. */
1653 		ks1dbg(keystack,
1654 		    ("Reality check failed on extension type %d.\n",
1655 		    extv[0]->sadb_ext_type));
1656 		keysock_error(ks, mp, EINVAL,
1657 		    keysock_malformed(extv[0]->sadb_ext_type));
1658 		return;
1659 	default:
1660 		/* Default case is no errors. */
1661 		break;
1662 	}
1663 
1664 	switch (samsg->sadb_msg_type) {
1665 	case SADB_REGISTER:
1666 		/*
1667 		 * There's a semantic weirdness in that a message OTHER than
1668 		 * the return REGISTER message may be passed up if I set the
1669 		 * registered bit BEFORE I pass it down.
1670 		 *
1671 		 * SOOOO, I'll not twiddle any registered bits until I see
1672 		 * the upbound REGISTER (with a serial number in it).
1673 		 */
1674 		if (samsg->sadb_msg_satype == SADB_SATYPE_UNSPEC) {
1675 			/* Handle extended register here. */
1676 			keysock_extended_register(ks, mp, extv);
1677 			return;
1678 		} else if (ks->keysock_flags & KEYSOCK_EXTENDED) {
1679 			keysock_error(ks, mp, EBUSY, 0);
1680 			return;
1681 		}
1682 		/* FALLTHRU */
1683 	case SADB_GETSPI:
1684 	case SADB_ADD:
1685 	case SADB_UPDATE:
1686 	case SADB_X_UPDATEPAIR:
1687 	case SADB_DELETE:
1688 	case SADB_X_DELPAIR:
1689 	case SADB_GET:
1690 		/*
1691 		 * Pass down to appropriate consumer.
1692 		 */
1693 		if (samsg->sadb_msg_satype != SADB_SATYPE_UNSPEC)
1694 			keysock_passdown(ks, mp, samsg->sadb_msg_satype, extv,
1695 			    B_FALSE);
1696 		else keysock_error(ks, mp, EINVAL,
1697 		    SADB_X_DIAGNOSTIC_SATYPE_NEEDED);
1698 		return;
1699 	case SADB_X_DELPAIR_STATE:
1700 		if (samsg->sadb_msg_satype == SADB_SATYPE_UNSPEC) {
1701 			keysock_delpair_all(ks, mp, extv);
1702 		} else {
1703 			keysock_passdown(ks, mp, samsg->sadb_msg_satype, extv,
1704 			    B_FALSE);
1705 		}
1706 		return;
1707 	case SADB_ACQUIRE:
1708 		/*
1709 		 * If I _receive_ an acquire, this means I should spread it
1710 		 * out to registered sockets.  Unless there's an errno...
1711 		 *
1712 		 * Need ADDRESS, may have ID, SENS, and PROP, unless errno,
1713 		 * in which case there should be NO extensions.
1714 		 *
1715 		 * Return to registered.
1716 		 */
1717 		if (samsg->sadb_msg_errno != 0) {
1718 			satype = samsg->sadb_msg_satype;
1719 			if (satype == SADB_SATYPE_UNSPEC) {
1720 				if (!(ks->keysock_flags & KEYSOCK_EXTENDED)) {
1721 					keysock_error(ks, mp, EINVAL,
1722 					    SADB_X_DIAGNOSTIC_SATYPE_NEEDED);
1723 					return;
1724 				}
1725 				/*
1726 				 * Reassign satype based on the first
1727 				 * flags that KEYSOCK_SETREG says.
1728 				 */
1729 				while (satype <= SADB_SATYPE_MAX) {
1730 					if (KEYSOCK_ISREG(ks, satype))
1731 						break;
1732 					satype++;
1733 				}
1734 				if (satype > SADB_SATYPE_MAX) {
1735 					keysock_error(ks, mp, EBUSY, 0);
1736 					return;
1737 				}
1738 			}
1739 			keysock_passdown(ks, mp, satype, extv, B_FALSE);
1740 		} else {
1741 			if (samsg->sadb_msg_satype == SADB_SATYPE_UNSPEC) {
1742 				keysock_error(ks, mp, EINVAL,
1743 				    SADB_X_DIAGNOSTIC_SATYPE_NEEDED);
1744 			} else {
1745 				keysock_passup(mp, samsg, 0, NULL, B_FALSE,
1746 				    keystack);
1747 			}
1748 		}
1749 		return;
1750 	case SADB_EXPIRE:
1751 		/*
1752 		 * If someone sends this in, then send out to all senders.
1753 		 * (Save maybe ESP or AH, I have to be careful here.)
1754 		 *
1755 		 * Need ADDRESS, may have ID and SENS.
1756 		 *
1757 		 * XXX for now this is unsupported.
1758 		 */
1759 		break;
1760 	case SADB_FLUSH:
1761 		/*
1762 		 * Nuke all SAs.
1763 		 *
1764 		 * No extensions at all.  Return to all listeners.
1765 		 *
1766 		 * Question:	Should I hold a lock here to prevent
1767 		 *		additions/deletions while flushing?
1768 		 * Answer:	No.  (See keysock_passdown() for details.)
1769 		 */
1770 		if (extv[0] != NULL) {
1771 			/*
1772 			 * FLUSH messages shouldn't have extensions.
1773 			 * Return EINVAL.
1774 			 */
1775 			ks2dbg(keystack, ("FLUSH message with extension.\n"));
1776 			keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_NO_EXT);
1777 			return;
1778 		}
1779 
1780 		/* Passing down of DUMP/FLUSH messages are special. */
1781 		qwriter(q, mp, keysock_do_flushdump, PERIM_INNER);
1782 		return;
1783 	case SADB_DUMP:	 /* not used by normal applications */
1784 		if ((extv[0] != NULL) &&
1785 		    ((msgsize >
1786 		    (sizeof (sadb_msg_t) + sizeof (sadb_x_edump_t))) ||
1787 		    (extv[SADB_X_EXT_EDUMP] == NULL))) {
1788 				keysock_error(ks, mp, EINVAL,
1789 				    SADB_X_DIAGNOSTIC_NO_EXT);
1790 				return;
1791 		}
1792 		qwriter(q, mp, keysock_do_flushdump, PERIM_INNER);
1793 		return;
1794 	case SADB_X_PROMISC:
1795 		/*
1796 		 * Promiscuous processing message.
1797 		 */
1798 		if (samsg->sadb_msg_satype == 0)
1799 			ks->keysock_flags &= ~KEYSOCK_PROMISC;
1800 		else
1801 			ks->keysock_flags |= KEYSOCK_PROMISC;
1802 		keysock_passup(mp, samsg, ks->keysock_serial, NULL, B_FALSE,
1803 		    keystack);
1804 		return;
1805 	case SADB_X_INVERSE_ACQUIRE:
1806 		keysock_inverse_acquire(mp, samsg, extv, ks);
1807 		return;
1808 	default:
1809 		ks2dbg(keystack, ("Got unknown message type %d.\n",
1810 		    samsg->sadb_msg_type));
1811 		keysock_error(ks, mp, EINVAL, SADB_X_DIAGNOSTIC_UNKNOWN_MSG);
1812 		return;
1813 	}
1814 
1815 	/* As a placeholder... */
1816 	ks0dbg(("keysock_parse():  Hit EOPNOTSUPP\n"));
1817 	keysock_error(ks, mp, EOPNOTSUPP, SADB_X_DIAGNOSTIC_NONE);
1818 }
1819 
1820 /*
1821  * wput routing for PF_KEY/keysock/whatever.  Unlike the routing socket,
1822  * I don't convert to ioctl()'s for IP.  I am the end-all driver as far
1823  * as PF_KEY sockets are concerned.  I do some conversion, but not as much
1824  * as IP/rts does.
1825  */
1826 static void
1827 keysock_wput(queue_t *q, mblk_t *mp)
1828 {
1829 	uchar_t *rptr = mp->b_rptr;
1830 	mblk_t *mp1;
1831 	keysock_t *ks;
1832 	keysock_stack_t	*keystack;
1833 
1834 	if (WR(q)->q_next) {
1835 		keysock_consumer_t *kc = (keysock_consumer_t *)q->q_ptr;
1836 		keystack = kc->kc_keystack;
1837 
1838 		ks3dbg(keystack, ("In keysock_wput\n"));
1839 
1840 		/*
1841 		 * We shouldn't get writes on a consumer instance.
1842 		 * But for now, just passthru.
1843 		 */
1844 		ks1dbg(keystack, ("Huh?  wput for an consumer instance (%d)?\n",
1845 		    kc->kc_sa_type));
1846 		putnext(q, mp);
1847 		return;
1848 	}
1849 	ks = (keysock_t *)q->q_ptr;
1850 	keystack = ks->keysock_keystack;
1851 
1852 	ks3dbg(keystack, ("In keysock_wput\n"));
1853 
1854 	switch (mp->b_datap->db_type) {
1855 	case M_DATA:
1856 		/*
1857 		 * Silently discard.
1858 		 */
1859 		ks2dbg(keystack, ("raw M_DATA in keysock.\n"));
1860 		freemsg(mp);
1861 		return;
1862 	case M_PROTO:
1863 	case M_PCPROTO:
1864 		if ((mp->b_wptr - rptr) >= sizeof (struct T_data_req)) {
1865 			if (((union T_primitives *)rptr)->type == T_DATA_REQ) {
1866 				if ((mp1 = mp->b_cont) == NULL) {
1867 					/* No data after T_DATA_REQ. */
1868 					ks2dbg(keystack,
1869 					    ("No data after DATA_REQ.\n"));
1870 					freemsg(mp);
1871 					return;
1872 				}
1873 				freeb(mp);
1874 				mp = mp1;
1875 				ks2dbg(keystack, ("T_DATA_REQ\n"));
1876 				break;	/* Out of switch. */
1877 			}
1878 		}
1879 		/* FALLTHRU */
1880 	default:
1881 		ks3dbg(keystack, ("In default wput case (%d %d).\n",
1882 		    mp->b_datap->db_type, ((union T_primitives *)rptr)->type));
1883 		keysock_wput_other(q, mp);
1884 		return;
1885 	}
1886 
1887 	/* I now have a PF_KEY message in an M_DATA block, pointed to by mp. */
1888 	keysock_parse(q, mp);
1889 }
1890 
1891 /* BELOW THIS LINE ARE ROUTINES INCLUDING AND RELATED TO keysock_rput(). */
1892 
1893 /*
1894  * Called upon receipt of a KEYSOCK_HELLO_ACK to set up the appropriate
1895  * state vectors.
1896  */
1897 static void
1898 keysock_link_consumer(uint8_t satype, keysock_consumer_t *kc)
1899 {
1900 	keysock_t *ks;
1901 	keysock_stack_t	*keystack = kc->kc_keystack;
1902 
1903 	mutex_enter(&keystack->keystack_consumers_lock);
1904 	mutex_enter(&kc->kc_lock);
1905 	if (keystack->keystack_consumers[satype] != NULL) {
1906 		ks0dbg((
1907 		    "Hmmmm, someone closed %d before the HELLO_ACK happened.\n",
1908 		    satype));
1909 		/*
1910 		 * Perhaps updating the new below-me consumer with what I have
1911 		 * so far would work too?
1912 		 */
1913 		mutex_exit(&kc->kc_lock);
1914 		mutex_exit(&keystack->keystack_consumers_lock);
1915 	} else {
1916 		/* Add new below-me consumer. */
1917 		keystack->keystack_consumers[satype] = kc;
1918 
1919 		kc->kc_flags = 0;
1920 		kc->kc_sa_type = satype;
1921 		mutex_exit(&kc->kc_lock);
1922 		mutex_exit(&keystack->keystack_consumers_lock);
1923 
1924 		/* Scan the keysock list. */
1925 		mutex_enter(&keystack->keystack_list_lock);
1926 		for (ks = keystack->keystack_list; ks != NULL;
1927 		    ks = ks->keysock_next) {
1928 			if (KEYSOCK_ISREG(ks, satype)) {
1929 				/*
1930 				 * XXX Perhaps send an SADB_REGISTER down on
1931 				 * the socket's behalf.
1932 				 */
1933 				ks1dbg(keystack,
1934 				    ("Socket %u registered already for "
1935 				    "new consumer.\n", ks->keysock_serial));
1936 			}
1937 		}
1938 		mutex_exit(&keystack->keystack_list_lock);
1939 	}
1940 }
1941 
1942 /*
1943  * Generate a KEYSOCK_OUT_ERR message for my consumer.
1944  */
1945 static void
1946 keysock_out_err(keysock_consumer_t *kc, int ks_errno, mblk_t *mp)
1947 {
1948 	keysock_out_err_t *kse;
1949 	mblk_t *imp;
1950 	keysock_stack_t	*keystack = kc->kc_keystack;
1951 
1952 	imp = allocb(sizeof (ipsec_info_t), BPRI_HI);
1953 	if (imp == NULL) {
1954 		ks1dbg(keystack, ("keysock_out_err:  Can't alloc message.\n"));
1955 		return;
1956 	}
1957 
1958 	imp->b_datap->db_type = M_CTL;
1959 	imp->b_wptr += sizeof (ipsec_info_t);
1960 
1961 	kse = (keysock_out_err_t *)imp->b_rptr;
1962 	imp->b_cont = mp;
1963 	kse->ks_err_type = KEYSOCK_OUT_ERR;
1964 	kse->ks_err_len = sizeof (*kse);
1965 	/* Is serial necessary? */
1966 	kse->ks_err_serial = 0;
1967 	kse->ks_err_errno = ks_errno;
1968 
1969 	/*
1970 	 * XXX What else do I need to do here w.r.t. information
1971 	 * to tell the consumer what caused this error?
1972 	 *
1973 	 * I believe the answer is the PF_KEY ACQUIRE (or other) message
1974 	 * attached in mp, which is appended at the end.  I believe the
1975 	 * db_ref won't matter here, because the PF_KEY message is only read
1976 	 * for KEYSOCK_OUT_ERR.
1977 	 */
1978 
1979 	putnext(kc->kc_wq, imp);
1980 }
1981 
1982 /* XXX this is a hack errno. */
1983 #define	EIPSECNOSA 255
1984 
1985 /*
1986  * Route message (pointed by mp, header in samsg) toward appropriate
1987  * sockets.  Assume the message's creator did its job correctly.
1988  *
1989  * This should be a function that is followed by a return in its caller.
1990  * The compiler _should_ be able to use tail-call optimizations to make the
1991  * large ## of parameters not a huge deal.
1992  */
1993 static void
1994 keysock_passup(mblk_t *mp, sadb_msg_t *samsg, minor_t serial,
1995     keysock_consumer_t *kc, boolean_t persistent, keysock_stack_t *keystack)
1996 {
1997 	keysock_t *ks;
1998 	uint8_t satype = samsg->sadb_msg_satype;
1999 	boolean_t toall = B_FALSE, allreg = B_FALSE, allereg = B_FALSE,
2000 	    setalg = B_FALSE;
2001 	mblk_t *mp1;
2002 	int err = EIPSECNOSA;
2003 
2004 	/* Convert mp, which is M_DATA, into an M_PROTO of type T_DATA_IND */
2005 	mp1 = allocb(sizeof (struct T_data_req), BPRI_HI);
2006 	if (mp1 == NULL) {
2007 		err = ENOMEM;
2008 		goto error;
2009 	}
2010 	mp1->b_wptr += sizeof (struct T_data_req);
2011 	((struct T_data_ind *)mp1->b_rptr)->PRIM_type = T_DATA_IND;
2012 	((struct T_data_ind *)mp1->b_rptr)->MORE_flag = 0;
2013 	mp1->b_datap->db_type = M_PROTO;
2014 	mp1->b_cont = mp;
2015 	mp = mp1;
2016 
2017 	switch (samsg->sadb_msg_type) {
2018 	case SADB_FLUSH:
2019 	case SADB_GETSPI:
2020 	case SADB_UPDATE:
2021 	case SADB_X_UPDATEPAIR:
2022 	case SADB_ADD:
2023 	case SADB_DELETE:
2024 	case SADB_X_DELPAIR:
2025 	case SADB_EXPIRE:
2026 		/*
2027 		 * These are most likely replies.  Don't worry about
2028 		 * KEYSOCK_OUT_ERR handling.  Deliver to all sockets.
2029 		 */
2030 		ks3dbg(keystack,
2031 		    ("Delivering normal message (%d) to all sockets.\n",
2032 		    samsg->sadb_msg_type));
2033 		toall = B_TRUE;
2034 		break;
2035 	case SADB_REGISTER:
2036 		/*
2037 		 * REGISTERs come up for one of three reasons:
2038 		 *
2039 		 *	1.) In response to a normal SADB_REGISTER
2040 		 *		(samsg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
2041 		 *		    serial != 0)
2042 		 *		Deliver to normal SADB_REGISTERed sockets.
2043 		 *	2.) In response to an extended REGISTER
2044 		 *		(samsg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
2045 		 *		Deliver to extended REGISTERed socket.
2046 		 *	3.) Spontaneous algorithm changes
2047 		 *		(samsg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
2048 		 *		    serial == 0)
2049 		 *		Deliver to REGISTERed sockets of all sorts.
2050 		 */
2051 		if (kc == NULL) {
2052 			/* Here because of keysock_error() call. */
2053 			ASSERT(samsg->sadb_msg_errno != 0);
2054 			break;	/* Out of switch. */
2055 		}
2056 		ks3dbg(keystack, ("Delivering REGISTER.\n"));
2057 		if (satype == SADB_SATYPE_UNSPEC) {
2058 			/* REGISTER Reason #2 */
2059 			allereg = B_TRUE;
2060 			/*
2061 			 * Rewhack SA type so PF_KEY socket holder knows what
2062 			 * consumer generated this algorithm list.
2063 			 */
2064 			satype = kc->kc_sa_type;
2065 			samsg->sadb_msg_satype = satype;
2066 			setalg = B_TRUE;
2067 		} else if (serial == 0) {
2068 			/* REGISTER Reason #3 */
2069 			allreg = B_TRUE;
2070 			allereg = B_TRUE;
2071 		} else {
2072 			/* REGISTER Reason #1 */
2073 			allreg = B_TRUE;
2074 			setalg = B_TRUE;
2075 		}
2076 		break;
2077 	case SADB_ACQUIRE:
2078 		/*
2079 		 * ACQUIREs are either extended (sadb_msg_satype == 0) or
2080 		 * regular (sadb_msg_satype != 0).  And we're guaranteed
2081 		 * that serial == 0 for an ACQUIRE.
2082 		 */
2083 		ks3dbg(keystack, ("Delivering ACQUIRE.\n"));
2084 		allereg = (satype == SADB_SATYPE_UNSPEC);
2085 		allreg = !allereg;
2086 		/*
2087 		 * Corner case - if we send a regular ACQUIRE and there's
2088 		 * extended ones registered, don't send an error down to
2089 		 * consumers if nobody's listening and prematurely destroy
2090 		 * their ACQUIRE record.  This might be too hackish of a
2091 		 * solution.
2092 		 */
2093 		if (allreg && keystack->keystack_num_extended > 0)
2094 			err = 0;
2095 		break;
2096 	case SADB_X_PROMISC:
2097 	case SADB_X_INVERSE_ACQUIRE:
2098 	case SADB_DUMP:
2099 	case SADB_GET:
2100 	default:
2101 		/*
2102 		 * Deliver to the sender and promiscuous only.
2103 		 */
2104 		ks3dbg(keystack, ("Delivering sender/promisc only (%d).\n",
2105 		    samsg->sadb_msg_type));
2106 		break;
2107 	}
2108 
2109 	mutex_enter(&keystack->keystack_list_lock);
2110 	for (ks = keystack->keystack_list; ks != NULL; ks = ks->keysock_next) {
2111 		/* Delivery loop. */
2112 
2113 		/*
2114 		 * Check special keysock-setting cases (REGISTER replies)
2115 		 * here.
2116 		 */
2117 		if (setalg && serial == ks->keysock_serial) {
2118 			ASSERT(kc != NULL);
2119 			ASSERT(kc->kc_sa_type == satype);
2120 			KEYSOCK_SETREG(ks, satype);
2121 		}
2122 
2123 		/*
2124 		 * NOLOOP takes precedence over PROMISC.  So if you've set
2125 		 * !SO_USELOOPBACK, don't expect to see any data...
2126 		 */
2127 		if (ks->keysock_flags & KEYSOCK_NOLOOP)
2128 			continue;
2129 
2130 		/*
2131 		 * Messages to all, or promiscuous sockets just GET the
2132 		 * message.  Perform rules-type checking iff it's not for all
2133 		 * listeners or the socket is in promiscuous mode.
2134 		 *
2135 		 * NOTE:Because of the (kc != NULL && ISREG()), make sure
2136 		 *	extended ACQUIREs arrive off a consumer that is
2137 		 *	part of the extended REGISTER set of consumers.
2138 		 */
2139 		if (serial != ks->keysock_serial &&
2140 		    !toall &&
2141 		    !(ks->keysock_flags & KEYSOCK_PROMISC) &&
2142 		    !((ks->keysock_flags & KEYSOCK_EXTENDED) ?
2143 		    allereg : allreg && kc != NULL &&
2144 		    KEYSOCK_ISREG(ks, kc->kc_sa_type)))
2145 			continue;
2146 
2147 		mp1 = dupmsg(mp);
2148 		if (mp1 == NULL) {
2149 			ks2dbg(keystack, (
2150 			    "keysock_passup():  dupmsg() failed.\n"));
2151 			mp1 = mp;
2152 			mp = NULL;
2153 			err = ENOMEM;
2154 		}
2155 
2156 		/*
2157 		 * At this point, we can deliver or attempt to deliver
2158 		 * this message.  We're free of obligation to report
2159 		 * no listening PF_KEY sockets.  So set err to 0.
2160 		 */
2161 		err = 0;
2162 
2163 		/*
2164 		 * See if we canputnext(), as well as see if the message
2165 		 * needs to be queued if we can't.
2166 		 */
2167 		if (!canputnext(ks->keysock_rq)) {
2168 			if (persistent) {
2169 				if (putq(ks->keysock_rq, mp1) == 0) {
2170 					ks1dbg(keystack, (
2171 					    "keysock_passup: putq failed.\n"));
2172 				} else {
2173 					continue;
2174 				}
2175 			}
2176 			freemsg(mp1);
2177 			continue;
2178 		}
2179 
2180 		ks3dbg(keystack,
2181 		    ("Putting to serial %d.\n", ks->keysock_serial));
2182 		/*
2183 		 * Unlike the specific keysock instance case, this
2184 		 * will only hit for listeners, so we will only
2185 		 * putnext() if we can.
2186 		 */
2187 		putnext(ks->keysock_rq, mp1);
2188 		if (mp == NULL)
2189 			break;	/* out of for loop. */
2190 	}
2191 	mutex_exit(&keystack->keystack_list_lock);
2192 
2193 error:
2194 	if ((err != 0) && (kc != NULL)) {
2195 		/*
2196 		 * Generate KEYSOCK_OUT_ERR for consumer.
2197 		 * Basically, I send this back if I have not been able to
2198 		 * transmit (for whatever reason)
2199 		 */
2200 		ks1dbg(keystack,
2201 		    ("keysock_passup():  No registered of type %d.\n",
2202 		    satype));
2203 		if (mp != NULL) {
2204 			if (mp->b_datap->db_type == M_PROTO) {
2205 				mp1 = mp;
2206 				mp = mp->b_cont;
2207 				freeb(mp1);
2208 			}
2209 			/*
2210 			 * Do a copymsg() because people who get
2211 			 * KEYSOCK_OUT_ERR may alter the message contents.
2212 			 */
2213 			mp1 = copymsg(mp);
2214 			if (mp1 == NULL) {
2215 				ks2dbg(keystack,
2216 				    ("keysock_passup: copymsg() failed.\n"));
2217 				mp1 = mp;
2218 				mp = NULL;
2219 			}
2220 			keysock_out_err(kc, err, mp1);
2221 		}
2222 	}
2223 
2224 	/*
2225 	 * XXX Blank the message somehow.  This is difficult because we don't
2226 	 * know at this point if the message has db_ref > 1, etc.
2227 	 *
2228 	 * Optimally, keysock messages containing actual keying material would
2229 	 * be allocated with esballoc(), with a zeroing free function.
2230 	 */
2231 	if (mp != NULL)
2232 		freemsg(mp);
2233 }
2234 
2235 /*
2236  * Keysock's read service procedure is there only for PF_KEY reply
2237  * messages that really need to reach the top.
2238  */
2239 static void
2240 keysock_rsrv(queue_t *q)
2241 {
2242 	mblk_t *mp;
2243 
2244 	while ((mp = getq(q)) != NULL) {
2245 		if (canputnext(q)) {
2246 			putnext(q, mp);
2247 		} else {
2248 			(void) putbq(q, mp);
2249 			return;
2250 		}
2251 	}
2252 }
2253 
2254 /*
2255  * The read procedure should only be invoked by a keysock consumer, like
2256  * ESP, AH, etc.  I should only see KEYSOCK_OUT and KEYSOCK_HELLO_ACK
2257  * messages on my read queues.
2258  */
2259 static void
2260 keysock_rput(queue_t *q, mblk_t *mp)
2261 {
2262 	keysock_consumer_t *kc = (keysock_consumer_t *)q->q_ptr;
2263 	ipsec_info_t *ii;
2264 	keysock_hello_ack_t *ksa;
2265 	minor_t serial;
2266 	mblk_t *mp1;
2267 	sadb_msg_t *samsg;
2268 	keysock_stack_t	*keystack = kc->kc_keystack;
2269 
2270 	/* Make sure I'm a consumer instance.  (i.e. something's below me) */
2271 	ASSERT(WR(q)->q_next != NULL);
2272 
2273 	if (mp->b_datap->db_type != M_CTL) {
2274 		/*
2275 		 * Keysock should only see keysock consumer interface
2276 		 * messages (see ipsec_info.h) on its read procedure.
2277 		 * To be robust, however, putnext() up so the STREAM head can
2278 		 * deal with it appropriately.
2279 		 */
2280 		ks1dbg(keystack,
2281 		    ("Hmmm, a non M_CTL (%d, 0x%x) on keysock_rput.\n",
2282 		    mp->b_datap->db_type, mp->b_datap->db_type));
2283 		putnext(q, mp);
2284 		return;
2285 	}
2286 
2287 	ii = (ipsec_info_t *)mp->b_rptr;
2288 
2289 	switch (ii->ipsec_info_type) {
2290 	case KEYSOCK_OUT:
2291 		/*
2292 		 * A consumer needs to pass a response message or an ACQUIRE
2293 		 * UP.  I assume that the consumer has done the right
2294 		 * thing w.r.t. message creation, etc.
2295 		 */
2296 		serial = ((keysock_out_t *)mp->b_rptr)->ks_out_serial;
2297 		mp1 = mp->b_cont;	/* Get M_DATA portion. */
2298 		freeb(mp);
2299 		samsg = (sadb_msg_t *)mp1->b_rptr;
2300 		if (samsg->sadb_msg_type == SADB_FLUSH ||
2301 		    (samsg->sadb_msg_type == SADB_DUMP &&
2302 		    samsg->sadb_msg_len == SADB_8TO64(sizeof (*samsg)))) {
2303 			/*
2304 			 * If I'm an end-of-FLUSH or an end-of-DUMP marker...
2305 			 */
2306 			ASSERT(keystack->keystack_flushdump != 0);
2307 						/* Am I flushing? */
2308 
2309 			mutex_enter(&kc->kc_lock);
2310 			kc->kc_flags &= ~KC_FLUSHING;
2311 			mutex_exit(&kc->kc_lock);
2312 
2313 			if (samsg->sadb_msg_errno != 0)
2314 				keystack->keystack_flushdump_errno =
2315 				    samsg->sadb_msg_errno;
2316 
2317 			/*
2318 			 * Lower the atomic "flushing" count.  If it's
2319 			 * the last one, send up the end-of-{FLUSH,DUMP} to
2320 			 * the appropriate PF_KEY socket.
2321 			 */
2322 			if (atomic_add_32_nv(&keystack->keystack_flushdump,
2323 			    -1) != 0) {
2324 				ks1dbg(keystack,
2325 				    ("One flush/dump message back from %d,"
2326 				    " more to go.\n", samsg->sadb_msg_satype));
2327 				freemsg(mp1);
2328 				return;
2329 			}
2330 
2331 			samsg->sadb_msg_errno =
2332 			    (uint8_t)keystack->keystack_flushdump_errno;
2333 			if (samsg->sadb_msg_type == SADB_DUMP) {
2334 				samsg->sadb_msg_seq = 0;
2335 			}
2336 		}
2337 		keysock_passup(mp1, samsg, serial, kc,
2338 		    (samsg->sadb_msg_type == SADB_DUMP), keystack);
2339 		return;
2340 	case KEYSOCK_HELLO_ACK:
2341 		/* Aha, now we can link in the consumer! */
2342 		ksa = (keysock_hello_ack_t *)ii;
2343 		keysock_link_consumer(ksa->ks_hello_satype, kc);
2344 		freemsg(mp);
2345 		return;
2346 	default:
2347 		ks1dbg(keystack, ("Hmmm, an IPsec info I'm not used to, 0x%x\n",
2348 		    ii->ipsec_info_type));
2349 		putnext(q, mp);
2350 	}
2351 }
2352 
2353 /*
2354  * So we can avoid external linking problems....
2355  */
2356 boolean_t
2357 keysock_extended_reg(netstack_t *ns)
2358 {
2359 	keysock_stack_t	*keystack = ns->netstack_keysock;
2360 
2361 	return (keystack->keystack_num_extended != 0);
2362 }
2363 
2364 uint32_t
2365 keysock_next_seq(netstack_t *ns)
2366 {
2367 	keysock_stack_t	*keystack = ns->netstack_keysock;
2368 
2369 	return (atomic_add_32_nv(&keystack->keystack_acquire_seq, -1));
2370 }
2371