xref: /titanic_51/usr/src/uts/common/fs/sockfs/socksubr.c (revision 17169044f903cb92234f23d0ba0ce43449614a4d)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/t_lock.h>
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/cred.h>
36 #include <sys/kmem.h>
37 #include <sys/sysmacros.h>
38 #include <sys/vfs.h>
39 #include <sys/vfs_opreg.h>
40 #include <sys/vnode.h>
41 #include <sys/debug.h>
42 #include <sys/errno.h>
43 #include <sys/time.h>
44 #include <sys/file.h>
45 #include <sys/open.h>
46 #include <sys/user.h>
47 #include <sys/uio.h>
48 #include <sys/termios.h>
49 #include <sys/stream.h>
50 #include <sys/strsubr.h>
51 #include <sys/strsun.h>
52 #include <sys/esunddi.h>
53 #include <sys/flock.h>
54 #include <sys/modctl.h>
55 #include <sys/cmn_err.h>
56 #include <sys/mkdev.h>
57 #include <sys/pathname.h>
58 #include <sys/ddi.h>
59 #include <sys/stat.h>
60 #include <sys/fs/snode.h>
61 #include <sys/fs/dv_node.h>
62 #include <sys/zone.h>
63 
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <netinet/in.h>
67 #include <sys/un.h>
68 
69 #include <sys/ucred.h>
70 
71 #include <sys/tiuser.h>
72 #define	_SUN_TPI_VERSION	2
73 #include <sys/tihdr.h>
74 
75 #include <c2/audit.h>
76 
77 #include <fs/sockfs/nl7c.h>
78 
79 /*
80  * Macros that operate on struct cmsghdr.
81  * The CMSG_VALID macro does not assume that the last option buffer is padded.
82  */
83 #define	CMSG_CONTENT(cmsg)	(&((cmsg)[1]))
84 #define	CMSG_CONTENTLEN(cmsg)	((cmsg)->cmsg_len - sizeof (struct cmsghdr))
85 #define	CMSG_VALID(cmsg, start, end)					\
86 	(ISALIGNED_cmsghdr(cmsg) &&					\
87 	((uintptr_t)(cmsg) >= (uintptr_t)(start)) &&			\
88 	((uintptr_t)(cmsg) < (uintptr_t)(end)) &&			\
89 	((ssize_t)(cmsg)->cmsg_len >= sizeof (struct cmsghdr)) &&	\
90 	((uintptr_t)(cmsg) + (cmsg)->cmsg_len <= (uintptr_t)(end)))
91 #define	SO_LOCK_WAKEUP_TIME	3000	/* Wakeup time in milliseconds */
92 
93 static struct kmem_cache *socktpi_cache, *socktpi_unix_cache;
94 struct kmem_cache *socktpi_sod_cache;
95 
96 dev_t sockdev;	/* For fsid in getattr */
97 
98 struct sockparams *sphead;
99 krwlock_t splist_lock;
100 
101 struct socklist socklist;
102 
103 static int sockfs_update(kstat_t *, int);
104 static int sockfs_snapshot(kstat_t *, void *, int);
105 
106 extern void sendfile_init();
107 
108 extern void nl7c_init(void);
109 
110 extern int sostr_init();
111 
112 #define	ADRSTRLEN (2 * sizeof (void *) + 1)
113 /*
114  * kernel structure for passing the sockinfo data back up to the user.
115  * the strings array allows us to convert AF_UNIX addresses into strings
116  * with a common method regardless of which n-bit kernel we're running.
117  */
118 struct k_sockinfo {
119 	struct sockinfo	ks_si;
120 	char		ks_straddr[3][ADRSTRLEN];
121 };
122 
123 /*
124  * Translate from a device pathname (e.g. "/dev/tcp") to a vnode.
125  * Returns with the vnode held.
126  */
127 static int
128 sogetvp(char *devpath, vnode_t **vpp, int uioflag)
129 {
130 	struct snode *csp;
131 	vnode_t *vp, *dvp;
132 	major_t maj;
133 	int error;
134 
135 	ASSERT(uioflag == UIO_SYSSPACE || uioflag == UIO_USERSPACE);
136 	/*
137 	 * Lookup the underlying filesystem vnode.
138 	 */
139 	error = lookupname(devpath, uioflag, FOLLOW, NULLVPP, &vp);
140 	if (error)
141 		return (error);
142 
143 	/* Check that it is the correct vnode */
144 	if (vp->v_type != VCHR) {
145 		VN_RELE(vp);
146 		return (ENOTSOCK);
147 	}
148 
149 	/*
150 	 * If devpath went through devfs, the device should already
151 	 * be configured. If devpath is a mknod file, however, we
152 	 * need to make sure the device is properly configured.
153 	 * To do this, we do something similar to spec_open()
154 	 * except that we resolve to the minor/leaf level since
155 	 * we need to return a vnode.
156 	 */
157 	csp = VTOS(VTOS(vp)->s_commonvp);
158 	if (!(csp->s_flag & SDIPSET)) {
159 		char *pathname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
160 		error = ddi_dev_pathname(vp->v_rdev, S_IFCHR, pathname);
161 		if (error == 0)
162 			error = devfs_lookupname(pathname, NULLVPP, &dvp);
163 		VN_RELE(vp);
164 		kmem_free(pathname, MAXPATHLEN);
165 		if (error != 0)
166 			return (ENXIO);
167 		vp = dvp;	/* use the devfs vp */
168 	}
169 
170 	/* device is configured at this point */
171 	maj = getmajor(vp->v_rdev);
172 	if (!STREAMSTAB(maj)) {
173 		VN_RELE(vp);
174 		return (ENOSTR);
175 	}
176 
177 	*vpp = vp;
178 	return (0);
179 }
180 
181 /*
182  * Add or delete (latter if devpath is NULL) an enter to the sockparams
183  * table. If devpathlen is zero the devpath with not be kmem_freed. Otherwise
184  * this routine assumes that the caller has kmem_alloced devpath/devpathlen
185  * for this routine to consume.
186  * The zero devpathlen could be used if the kernel wants to create entries
187  * itself by calling sockconfig(1,2,3, "/dev/tcp", 0);
188  */
189 int
190 soconfig(int domain, int type, int protocol,
191     char *devpath, int devpathlen)
192 {
193 	struct sockparams **spp;
194 	struct sockparams *sp;
195 	int error = 0;
196 
197 	dprint(0, ("soconfig(%d,%d,%d,%s,%d)\n",
198 	    domain, type, protocol, devpath, devpathlen));
199 
200 	/*
201 	 * Look for an existing match.
202 	 */
203 	rw_enter(&splist_lock, RW_WRITER);
204 	for (spp = &sphead; (sp = *spp) != NULL; spp = &sp->sp_next) {
205 		if (sp->sp_domain == domain &&
206 		    sp->sp_type == type &&
207 		    sp->sp_protocol == protocol) {
208 			break;
209 		}
210 	}
211 	if (devpath == NULL) {
212 		ASSERT(devpathlen == 0);
213 
214 		/* Delete existing entry */
215 		if (sp == NULL) {
216 			error = ENXIO;
217 			goto done;
218 		}
219 		/* Unlink and free existing entry */
220 		*spp = sp->sp_next;
221 		ASSERT(sp->sp_vnode);
222 		VN_RELE(sp->sp_vnode);
223 		if (sp->sp_devpathlen != 0)
224 			kmem_free(sp->sp_devpath, sp->sp_devpathlen);
225 		kmem_free(sp, sizeof (*sp));
226 	} else {
227 		vnode_t *vp;
228 
229 		/* Add new entry */
230 		if (sp != NULL) {
231 			error = EEXIST;
232 			goto done;
233 		}
234 
235 		error = sogetvp(devpath, &vp, UIO_SYSSPACE);
236 		if (error) {
237 			dprint(0, ("soconfig: vp %s failed with %d\n",
238 			    devpath, error));
239 			goto done;
240 		}
241 
242 		dprint(0, ("soconfig: %s => vp %p, dev 0x%lx\n",
243 		    devpath, vp, vp->v_rdev));
244 
245 		sp = kmem_alloc(sizeof (*sp), KM_SLEEP);
246 		sp->sp_domain = domain;
247 		sp->sp_type = type;
248 		sp->sp_protocol = protocol;
249 		sp->sp_devpath = devpath;
250 		sp->sp_devpathlen = devpathlen;
251 		sp->sp_vnode = vp;
252 		sp->sp_next = NULL;
253 		*spp = sp;
254 	}
255 done:
256 	rw_exit(&splist_lock);
257 	if (error) {
258 		if (devpath != NULL)
259 			kmem_free(devpath, devpathlen);
260 #ifdef SOCK_DEBUG
261 		eprintline(error);
262 #endif /* SOCK_DEBUG */
263 	}
264 	return (error);
265 }
266 
267 /*
268  * Lookup an entry in the sockparams list based on the triple.
269  * If no entry is found and devpath is not NULL translate devpath to a
270  * vnode. Note that devpath is a pointer to a user address!
271  * Returns with the vnode held.
272  *
273  * When this routine uses devpath it does not create an entry in the sockparams
274  * list since this routine can run on behalf of any user and one user
275  * should not be able to effect the transport used by another user.
276  *
277  * In order to return the correct error this routine has to do wildcard scans
278  * of the list. The errors are (in decreasing precedence):
279  *	EAFNOSUPPORT - address family not in list
280  *	EPROTONOSUPPORT - address family supported but not protocol.
281  *	EPROTOTYPE - address family and protocol supported but not socket type.
282  */
283 vnode_t *
284 solookup(int domain, int type, int protocol, char *devpath, int *errorp)
285 {
286 	struct sockparams *sp;
287 	int error;
288 	vnode_t *vp;
289 
290 	rw_enter(&splist_lock, RW_READER);
291 	for (sp = sphead; sp != NULL; sp = sp->sp_next) {
292 		if (sp->sp_domain == domain &&
293 		    sp->sp_type == type &&
294 		    sp->sp_protocol == protocol) {
295 			break;
296 		}
297 	}
298 	if (sp == NULL) {
299 		dprint(0, ("solookup(%d,%d,%d) not found\n",
300 		    domain, type, protocol));
301 		if (devpath == NULL) {
302 			/* Determine correct error code */
303 			int found = 0;
304 
305 			for (sp = sphead; sp != NULL; sp = sp->sp_next) {
306 				if (sp->sp_domain == domain && found < 1)
307 					found = 1;
308 				if (sp->sp_domain == domain &&
309 				    sp->sp_protocol == protocol && found < 2)
310 					found = 2;
311 			}
312 			rw_exit(&splist_lock);
313 			switch (found) {
314 			case 0:
315 				*errorp = EAFNOSUPPORT;
316 				break;
317 			case 1:
318 				*errorp = EPROTONOSUPPORT;
319 				break;
320 			case 2:
321 				*errorp = EPROTOTYPE;
322 				break;
323 			}
324 			return (NULL);
325 		}
326 		rw_exit(&splist_lock);
327 
328 		/*
329 		 * Return vp based on devpath.
330 		 * Do not enter into table to avoid random users
331 		 * modifying the sockparams list.
332 		 */
333 		error = sogetvp(devpath, &vp, UIO_USERSPACE);
334 		if (error) {
335 			dprint(0, ("solookup: vp %p failed with %d\n",
336 			    devpath, error));
337 			*errorp = EPROTONOSUPPORT;
338 			return (NULL);
339 		}
340 		dprint(0, ("solookup: %p => vp %p, dev 0x%lx\n",
341 		    devpath, vp, vp->v_rdev));
342 
343 		return (vp);
344 	}
345 	dprint(0, ("solookup(%d,%d,%d) vp %p devpath %s\n",
346 	    domain, type, protocol, sp->sp_vnode, sp->sp_devpath));
347 
348 	vp = sp->sp_vnode;
349 	VN_HOLD(vp);
350 	rw_exit(&splist_lock);
351 	return (vp);
352 }
353 
354 /*
355  * Return a socket vnode.
356  *
357  * Assumes that the caller is "passing" an VN_HOLD for accessvp i.e.
358  * when the socket is freed a VN_RELE will take place.
359  *
360  * Note that sockets assume that the driver will clone (either itself
361  * or by using the clone driver) i.e. a socket() call will always
362  * result in a new vnode being created.
363  */
364 struct vnode *
365 makesockvp(struct vnode *accessvp, int domain, int type, int protocol)
366 {
367 	kmem_cache_t *cp;
368 	struct sonode *so;
369 	struct vnode *vp;
370 	time_t now;
371 	dev_t dev;
372 
373 	cp = (domain == AF_UNIX) ? socktpi_unix_cache : socktpi_cache;
374 	so = kmem_cache_alloc(cp, KM_SLEEP);
375 	so->so_cache = cp;
376 	so->so_obj = so;
377 	vp = SOTOV(so);
378 	now = gethrestime_sec();
379 
380 	so->so_flag	= 0;
381 	ASSERT(so->so_accessvp == NULL);
382 	so->so_accessvp	= accessvp;
383 	dev = accessvp->v_rdev;
384 
385 	/*
386 	 * Record in so_flag that it is a clone.
387 	 */
388 	if (getmajor(dev) == clone_major) {
389 		so->so_flag |= SOCLONE;
390 	}
391 	so->so_dev = dev;
392 
393 	so->so_state	= 0;
394 	so->so_mode	= 0;
395 
396 	so->so_fsid	= sockdev;
397 	so->so_atime	= now;
398 	so->so_mtime	= now;
399 	so->so_ctime	= now;		/* Never modified */
400 	so->so_count	= 0;
401 
402 	so->so_family	= (short)domain;
403 	so->so_type	= (short)type;
404 	so->so_protocol	= (short)protocol;
405 	so->so_pushcnt	= 0;
406 
407 	so->so_options	= 0;
408 	so->so_linger.l_onoff	= 0;
409 	so->so_linger.l_linger = 0;
410 	so->so_sndbuf	= 0;
411 	so->so_rcvbuf	= 0;
412 	so->so_sndlowat	= 0;
413 	so->so_rcvlowat	= 0;
414 #ifdef notyet
415 	so->so_sndtimeo	= 0;
416 	so->so_rcvtimeo	= 0;
417 #endif /* notyet */
418 	so->so_error	= 0;
419 	so->so_delayed_error = 0;
420 
421 	ASSERT(so->so_oobmsg == NULL);
422 	so->so_oobcnt	= 0;
423 	so->so_oobsigcnt = 0;
424 	so->so_pgrp	= 0;
425 	so->so_provinfo = NULL;
426 
427 	ASSERT(so->so_laddr_sa == NULL && so->so_faddr_sa == NULL);
428 	so->so_laddr_len = so->so_faddr_len = 0;
429 	so->so_laddr_maxlen = so->so_faddr_maxlen = 0;
430 	so->so_eaddr_mp = NULL;
431 	so->so_priv = NULL;
432 
433 	so->so_peercred = NULL;
434 
435 	ASSERT(so->so_ack_mp == NULL);
436 	ASSERT(so->so_conn_ind_head == NULL);
437 	ASSERT(so->so_conn_ind_tail == NULL);
438 	ASSERT(so->so_ux_bound_vp == NULL);
439 	ASSERT(so->so_unbind_mp == NULL);
440 
441 	vn_reinit(vp);
442 	vp->v_vfsp	= rootvfs;
443 	vp->v_type	= VSOCK;
444 	vp->v_rdev	= so->so_dev;
445 	vn_exists(vp);
446 
447 	return (vp);
448 }
449 
450 void
451 sockfree(struct sonode *so)
452 {
453 	mblk_t *mp;
454 	vnode_t *vp;
455 
456 	ASSERT(so->so_count == 0);
457 	ASSERT(so->so_accessvp);
458 	ASSERT(so->so_discon_ind_mp == NULL);
459 
460 	vp = so->so_accessvp;
461 	VN_RELE(vp);
462 
463 	/*
464 	 * Protect so->so_[lf]addr_sa so that sockfs_snapshot() can safely
465 	 * indirect them.  It also uses so_accessvp as a validity test.
466 	 */
467 	mutex_enter(&so->so_lock);
468 
469 	so->so_accessvp = NULL;
470 
471 	if (so->so_laddr_sa) {
472 		ASSERT((caddr_t)so->so_faddr_sa ==
473 		    (caddr_t)so->so_laddr_sa + so->so_laddr_maxlen);
474 		ASSERT(so->so_faddr_maxlen == so->so_laddr_maxlen);
475 		so->so_state &= ~(SS_LADDR_VALID | SS_FADDR_VALID);
476 		kmem_free(so->so_laddr_sa, so->so_laddr_maxlen * 2);
477 		so->so_laddr_sa = NULL;
478 		so->so_laddr_len = so->so_laddr_maxlen = 0;
479 		so->so_faddr_sa = NULL;
480 		so->so_faddr_len = so->so_faddr_maxlen = 0;
481 	}
482 
483 	mutex_exit(&so->so_lock);
484 
485 	if ((mp = so->so_eaddr_mp) != NULL) {
486 		freemsg(mp);
487 		so->so_eaddr_mp = NULL;
488 		so->so_delayed_error = 0;
489 	}
490 	if ((mp = so->so_ack_mp) != NULL) {
491 		freemsg(mp);
492 		so->so_ack_mp = NULL;
493 	}
494 	if ((mp = so->so_conn_ind_head) != NULL) {
495 		mblk_t *mp1;
496 
497 		while (mp) {
498 			mp1 = mp->b_next;
499 			mp->b_next = NULL;
500 			freemsg(mp);
501 			mp = mp1;
502 		}
503 		so->so_conn_ind_head = so->so_conn_ind_tail = NULL;
504 		so->so_state &= ~SS_HASCONNIND;
505 	}
506 #ifdef DEBUG
507 	mutex_enter(&so->so_lock);
508 	ASSERT(so_verify_oobstate(so));
509 	mutex_exit(&so->so_lock);
510 #endif /* DEBUG */
511 	if ((mp = so->so_oobmsg) != NULL) {
512 		freemsg(mp);
513 		so->so_oobmsg = NULL;
514 		so->so_state &= ~(SS_OOBPEND|SS_HAVEOOBDATA|SS_HADOOBDATA);
515 	}
516 
517 	if ((mp = so->so_nl7c_rcv_mp) != NULL) {
518 		so->so_nl7c_rcv_mp = NULL;
519 		freemsg(mp);
520 	}
521 	so->so_nl7c_rcv_rval = 0;
522 	if (so->so_nl7c_uri != NULL) {
523 		nl7c_urifree(so);
524 		/* urifree() cleared nl7c_uri */
525 	}
526 	if (so->so_nl7c_flags) {
527 		so->so_nl7c_flags = 0;
528 	}
529 
530 	if (so->so_direct != NULL) {
531 		sodirect_t *sodp = so->so_direct;
532 
533 		ASSERT(sodp->sod_uioafh == NULL);
534 
535 		so->so_direct = NULL;
536 		kmem_cache_free(socktpi_sod_cache, sodp);
537 	}
538 
539 	ASSERT(so->so_ux_bound_vp == NULL);
540 	if ((mp = so->so_unbind_mp) != NULL) {
541 		freemsg(mp);
542 		so->so_unbind_mp = NULL;
543 	}
544 	vn_invalid(SOTOV(so));
545 
546 	if (so->so_peercred != NULL)
547 		crfree(so->so_peercred);
548 
549 	kmem_cache_free(so->so_cache, so->so_obj);
550 }
551 
552 /*
553  * Update the accessed, updated, or changed times in an sonode
554  * with the current time.
555  *
556  * Note that both SunOS 4.X and 4.4BSD sockets do not present reasonable
557  * attributes in a fstat call. (They return the current time and 0 for
558  * all timestamps, respectively.) We maintain the current timestamps
559  * here primarily so that should sockmod be popped the resulting
560  * file descriptor will behave like a stream w.r.t. the timestamps.
561  */
562 void
563 so_update_attrs(struct sonode *so, int flag)
564 {
565 	time_t now = gethrestime_sec();
566 
567 	mutex_enter(&so->so_lock);
568 	so->so_flag |= flag;
569 	if (flag & SOACC)
570 		so->so_atime = now;
571 	if (flag & SOMOD)
572 		so->so_mtime = now;
573 	mutex_exit(&so->so_lock);
574 }
575 
576 /*ARGSUSED*/
577 static int
578 socktpi_constructor(void *buf, void *cdrarg, int kmflags)
579 {
580 	struct sonode *so = buf;
581 	struct vnode *vp;
582 
583 	so->so_direct		= NULL;
584 
585 	so->so_nl7c_flags	= 0;
586 	so->so_nl7c_uri		= NULL;
587 	so->so_nl7c_rcv_mp	= NULL;
588 
589 	so->so_oobmsg		= NULL;
590 	so->so_ack_mp		= NULL;
591 	so->so_conn_ind_head	= NULL;
592 	so->so_conn_ind_tail	= NULL;
593 	so->so_discon_ind_mp	= NULL;
594 	so->so_ux_bound_vp	= NULL;
595 	so->so_unbind_mp	= NULL;
596 	so->so_accessvp		= NULL;
597 	so->so_laddr_sa		= NULL;
598 	so->so_faddr_sa		= NULL;
599 	so->so_ops		= &sotpi_sonodeops;
600 
601 	vp = vn_alloc(KM_SLEEP);
602 	so->so_vnode = vp;
603 
604 	vn_setops(vp, socktpi_vnodeops);
605 	vp->v_data = (caddr_t)so;
606 
607 	mutex_init(&so->so_lock, NULL, MUTEX_DEFAULT, NULL);
608 	mutex_init(&so->so_plumb_lock, NULL, MUTEX_DEFAULT, NULL);
609 	cv_init(&so->so_state_cv, NULL, CV_DEFAULT, NULL);
610 	cv_init(&so->so_ack_cv, NULL, CV_DEFAULT, NULL);
611 	cv_init(&so->so_connind_cv, NULL, CV_DEFAULT, NULL);
612 	cv_init(&so->so_want_cv, NULL, CV_DEFAULT, NULL);
613 
614 	return (0);
615 }
616 
617 /*ARGSUSED1*/
618 static void
619 socktpi_destructor(void *buf, void *cdrarg)
620 {
621 	struct sonode *so = buf;
622 	struct vnode *vp = SOTOV(so);
623 
624 	ASSERT(so->so_direct == NULL);
625 
626 	ASSERT(so->so_nl7c_flags == 0);
627 	ASSERT(so->so_nl7c_uri == NULL);
628 	ASSERT(so->so_nl7c_rcv_mp == NULL);
629 
630 	ASSERT(so->so_oobmsg == NULL);
631 	ASSERT(so->so_ack_mp == NULL);
632 	ASSERT(so->so_conn_ind_head == NULL);
633 	ASSERT(so->so_conn_ind_tail == NULL);
634 	ASSERT(so->so_discon_ind_mp == NULL);
635 	ASSERT(so->so_ux_bound_vp == NULL);
636 	ASSERT(so->so_unbind_mp == NULL);
637 	ASSERT(so->so_ops == &sotpi_sonodeops);
638 
639 	ASSERT(vn_matchops(vp, socktpi_vnodeops));
640 	ASSERT(vp->v_data == (caddr_t)so);
641 
642 	vn_free(vp);
643 
644 	mutex_destroy(&so->so_lock);
645 	mutex_destroy(&so->so_plumb_lock);
646 	cv_destroy(&so->so_state_cv);
647 	cv_destroy(&so->so_ack_cv);
648 	cv_destroy(&so->so_connind_cv);
649 	cv_destroy(&so->so_want_cv);
650 }
651 
652 static int
653 socktpi_unix_constructor(void *buf, void *cdrarg, int kmflags)
654 {
655 	int retval;
656 
657 	if ((retval = socktpi_constructor(buf, cdrarg, kmflags)) == 0) {
658 		struct sonode *so = (struct sonode *)buf;
659 
660 		mutex_enter(&socklist.sl_lock);
661 
662 		so->so_next = socklist.sl_list;
663 		so->so_prev = NULL;
664 		if (so->so_next != NULL)
665 			so->so_next->so_prev = so;
666 		socklist.sl_list = so;
667 
668 		mutex_exit(&socklist.sl_lock);
669 
670 	}
671 	return (retval);
672 }
673 
674 static void
675 socktpi_unix_destructor(void *buf, void *cdrarg)
676 {
677 	struct sonode	*so	= (struct sonode *)buf;
678 
679 	mutex_enter(&socklist.sl_lock);
680 
681 	if (so->so_next != NULL)
682 		so->so_next->so_prev = so->so_prev;
683 	if (so->so_prev != NULL)
684 		so->so_prev->so_next = so->so_next;
685 	else
686 		socklist.sl_list = so->so_next;
687 
688 	mutex_exit(&socklist.sl_lock);
689 
690 	socktpi_destructor(buf, cdrarg);
691 }
692 
693 /*
694  * Init function called when sockfs is loaded.
695  */
696 int
697 sockinit(int fstype, char *name)
698 {
699 	static const fs_operation_def_t sock_vfsops_template[] = {
700 		NULL, NULL
701 	};
702 	int error;
703 	major_t dev;
704 	char *err_str;
705 
706 	error = vfs_setfsops(fstype, sock_vfsops_template, NULL);
707 	if (error != 0) {
708 		zcmn_err(GLOBAL_ZONEID, CE_WARN,
709 		    "sockinit: bad vfs ops template");
710 		return (error);
711 	}
712 
713 	error = vn_make_ops(name, socktpi_vnodeops_template, &socktpi_vnodeops);
714 	if (error != 0) {
715 		err_str = "sockinit: bad sock vnode ops template";
716 		/* vn_make_ops() does not reset socktpi_vnodeops on failure. */
717 		socktpi_vnodeops = NULL;
718 		goto failure;
719 	}
720 
721 	error = sosctp_init();
722 	if (error != 0) {
723 		err_str = NULL;
724 		goto failure;
725 	}
726 
727 	error = sosdp_init();
728 	if (error != 0) {
729 		err_str = NULL;
730 		goto failure;
731 	}
732 
733 	error = sostr_init();
734 	if (error != 0) {
735 		err_str = NULL;
736 		goto failure;
737 	}
738 
739 	/*
740 	 * Create sonode caches.  We create a special one for AF_UNIX so
741 	 * that we can track them for netstat(1m).
742 	 */
743 	socktpi_cache = kmem_cache_create("socktpi_cache",
744 	    sizeof (struct sonode), 0, socktpi_constructor,
745 	    socktpi_destructor, NULL, NULL, NULL, 0);
746 
747 	socktpi_unix_cache = kmem_cache_create("socktpi_unix_cache",
748 	    sizeof (struct sonode), 0, socktpi_unix_constructor,
749 	    socktpi_unix_destructor, NULL, NULL, NULL, 0);
750 
751 	/*
752 	 * Build initial list mapping socket parameters to vnode.
753 	 */
754 	rw_init(&splist_lock, NULL, RW_DEFAULT, NULL);
755 
756 	/*
757 	 * If sockets are needed before init runs /sbin/soconfig
758 	 * it is possible to preload the sockparams list here using
759 	 * calls like:
760 	 *	sockconfig(1,2,3, "/dev/tcp", 0);
761 	 */
762 
763 	/*
764 	 * Create a unique dev_t for use in so_fsid.
765 	 */
766 
767 	if ((dev = getudev()) == (major_t)-1)
768 		dev = 0;
769 	sockdev = makedevice(dev, 0);
770 
771 	mutex_init(&socklist.sl_lock, NULL, MUTEX_DEFAULT, NULL);
772 	sendfile_init();
773 	nl7c_init();
774 
775 	return (0);
776 
777 failure:
778 	(void) vfs_freevfsops_by_type(fstype);
779 	if (socktpi_vnodeops != NULL)
780 		vn_freevnodeops(socktpi_vnodeops);
781 	if (err_str != NULL)
782 		zcmn_err(GLOBAL_ZONEID, CE_WARN, err_str);
783 	return (error);
784 }
785 
786 /*
787  * Caller must hold the mutex. Used to set SOLOCKED.
788  */
789 void
790 so_lock_single(struct sonode *so)
791 {
792 	ASSERT(MUTEX_HELD(&so->so_lock));
793 
794 	while (so->so_flag & (SOLOCKED | SOASYNC_UNBIND)) {
795 		so->so_flag |= SOWANT;
796 		cv_wait_stop(&so->so_want_cv, &so->so_lock,
797 		    SO_LOCK_WAKEUP_TIME);
798 	}
799 	so->so_flag |= SOLOCKED;
800 }
801 
802 /*
803  * Caller must hold the mutex and pass in SOLOCKED or SOASYNC_UNBIND.
804  * Used to clear SOLOCKED or SOASYNC_UNBIND.
805  */
806 void
807 so_unlock_single(struct sonode *so, int flag)
808 {
809 	ASSERT(MUTEX_HELD(&so->so_lock));
810 	ASSERT(flag & (SOLOCKED|SOASYNC_UNBIND));
811 	ASSERT((flag & ~(SOLOCKED|SOASYNC_UNBIND)) == 0);
812 	ASSERT(so->so_flag & flag);
813 
814 	/*
815 	 * Process the T_DISCON_IND on so_discon_ind_mp.
816 	 *
817 	 * Call to so_drain_discon_ind will result in so_lock
818 	 * being dropped and re-acquired later.
819 	 */
820 	if (so->so_discon_ind_mp != NULL)
821 		so_drain_discon_ind(so);
822 
823 	if (so->so_flag & SOWANT)
824 		cv_broadcast(&so->so_want_cv);
825 	so->so_flag &= ~(SOWANT|flag);
826 }
827 
828 /*
829  * Caller must hold the mutex. Used to set SOREADLOCKED.
830  * If the caller wants nonblocking behavior it should set fmode.
831  */
832 int
833 so_lock_read(struct sonode *so, int fmode)
834 {
835 	ASSERT(MUTEX_HELD(&so->so_lock));
836 
837 	while (so->so_flag & SOREADLOCKED) {
838 		if (fmode & (FNDELAY|FNONBLOCK))
839 			return (EWOULDBLOCK);
840 		so->so_flag |= SOWANT;
841 		cv_wait_stop(&so->so_want_cv, &so->so_lock,
842 		    SO_LOCK_WAKEUP_TIME);
843 	}
844 	so->so_flag |= SOREADLOCKED;
845 	return (0);
846 }
847 
848 /*
849  * Like so_lock_read above but allows signals.
850  */
851 int
852 so_lock_read_intr(struct sonode *so, int fmode)
853 {
854 	ASSERT(MUTEX_HELD(&so->so_lock));
855 
856 	while (so->so_flag & SOREADLOCKED) {
857 		if (fmode & (FNDELAY|FNONBLOCK))
858 			return (EWOULDBLOCK);
859 		so->so_flag |= SOWANT;
860 		if (!cv_wait_sig(&so->so_want_cv, &so->so_lock))
861 			return (EINTR);
862 	}
863 	so->so_flag |= SOREADLOCKED;
864 	return (0);
865 }
866 
867 /*
868  * Caller must hold the mutex. Used to clear SOREADLOCKED,
869  * set in so_lock_read() or so_lock_read_intr().
870  */
871 void
872 so_unlock_read(struct sonode *so)
873 {
874 	ASSERT(MUTEX_HELD(&so->so_lock));
875 	ASSERT(so->so_flag & SOREADLOCKED);
876 
877 	if (so->so_flag & SOWANT)
878 		cv_broadcast(&so->so_want_cv);
879 	so->so_flag &= ~(SOWANT|SOREADLOCKED);
880 }
881 
882 /*
883  * Verify that the specified offset falls within the mblk and
884  * that the resulting pointer is aligned.
885  * Returns NULL if not.
886  */
887 void *
888 sogetoff(mblk_t *mp, t_uscalar_t offset,
889     t_uscalar_t length, uint_t align_size)
890 {
891 	uintptr_t ptr1, ptr2;
892 
893 	ASSERT(mp && mp->b_wptr >= mp->b_rptr);
894 	ptr1 = (uintptr_t)mp->b_rptr + offset;
895 	ptr2 = (uintptr_t)ptr1 + length;
896 	if (ptr1 < (uintptr_t)mp->b_rptr || ptr2 > (uintptr_t)mp->b_wptr) {
897 		eprintline(0);
898 		return (NULL);
899 	}
900 	if ((ptr1 & (align_size - 1)) != 0) {
901 		eprintline(0);
902 		return (NULL);
903 	}
904 	return ((void *)ptr1);
905 }
906 
907 /*
908  * Return the AF_UNIX underlying filesystem vnode matching a given name.
909  * Makes sure the sending and the destination sonodes are compatible.
910  * The vnode is returned held.
911  *
912  * The underlying filesystem VSOCK vnode has a v_stream pointer that
913  * references the actual stream head (hence indirectly the actual sonode).
914  */
915 static int
916 so_ux_lookup(struct sonode *so, struct sockaddr_un *soun, int checkaccess,
917 		vnode_t **vpp)
918 {
919 	vnode_t		*vp;	/* Underlying filesystem vnode */
920 	vnode_t		*svp;	/* sockfs vnode */
921 	struct sonode	*so2;
922 	int		error;
923 
924 	dprintso(so, 1, ("so_ux_lookup(%p) name <%s>\n",
925 	    so, soun->sun_path));
926 
927 	error = lookupname(soun->sun_path, UIO_SYSSPACE, FOLLOW, NULLVPP, &vp);
928 	if (error) {
929 		eprintsoline(so, error);
930 		return (error);
931 	}
932 	if (vp->v_type != VSOCK) {
933 		error = ENOTSOCK;
934 		eprintsoline(so, error);
935 		goto done2;
936 	}
937 
938 	if (checkaccess) {
939 		/*
940 		 * Check that we have permissions to access the destination
941 		 * vnode. This check is not done in BSD but it is required
942 		 * by X/Open.
943 		 */
944 		if (error = VOP_ACCESS(vp, VREAD|VWRITE, 0, CRED(), NULL)) {
945 			eprintsoline(so, error);
946 			goto done2;
947 		}
948 	}
949 
950 	/*
951 	 * Check if the remote socket has been closed.
952 	 *
953 	 * Synchronize with vn_rele_stream by holding v_lock while traversing
954 	 * v_stream->sd_vnode.
955 	 */
956 	mutex_enter(&vp->v_lock);
957 	if (vp->v_stream == NULL) {
958 		mutex_exit(&vp->v_lock);
959 		if (so->so_type == SOCK_DGRAM)
960 			error = EDESTADDRREQ;
961 		else
962 			error = ECONNREFUSED;
963 
964 		eprintsoline(so, error);
965 		goto done2;
966 	}
967 	ASSERT(vp->v_stream->sd_vnode);
968 	svp = vp->v_stream->sd_vnode;
969 	/*
970 	 * holding v_lock on underlying filesystem vnode and acquiring
971 	 * it on sockfs vnode. Assumes that no code ever attempts to
972 	 * acquire these locks in the reverse order.
973 	 */
974 	VN_HOLD(svp);
975 	mutex_exit(&vp->v_lock);
976 
977 	if (svp->v_type != VSOCK) {
978 		error = ENOTSOCK;
979 		eprintsoline(so, error);
980 		goto done;
981 	}
982 
983 	so2 = VTOSO(svp);
984 
985 	if (so->so_type != so2->so_type) {
986 		error = EPROTOTYPE;
987 		eprintsoline(so, error);
988 		goto done;
989 	}
990 
991 	VN_RELE(svp);
992 	*vpp = vp;
993 	return (0);
994 
995 done:
996 	VN_RELE(svp);
997 done2:
998 	VN_RELE(vp);
999 	return (error);
1000 }
1001 
1002 /*
1003  * Verify peer address for connect and sendto/sendmsg.
1004  * Since sendto/sendmsg would not get synchronous errors from the transport
1005  * provider we have to do these ugly checks in the socket layer to
1006  * preserve compatibility with SunOS 4.X.
1007  */
1008 int
1009 so_addr_verify(struct sonode *so, const struct sockaddr *name,
1010     socklen_t namelen)
1011 {
1012 	int		family;
1013 
1014 	dprintso(so, 1, ("so_addr_verify(%p, %p, %d)\n", so, name, namelen));
1015 
1016 	ASSERT(name != NULL);
1017 
1018 	family = so->so_family;
1019 	switch (family) {
1020 	case AF_INET:
1021 		if (name->sa_family != family) {
1022 			eprintsoline(so, EAFNOSUPPORT);
1023 			return (EAFNOSUPPORT);
1024 		}
1025 		if (namelen != (socklen_t)sizeof (struct sockaddr_in)) {
1026 			eprintsoline(so, EINVAL);
1027 			return (EINVAL);
1028 		}
1029 		break;
1030 	case AF_INET6: {
1031 #ifdef DEBUG
1032 		struct sockaddr_in6 *sin6;
1033 #endif /* DEBUG */
1034 
1035 		if (name->sa_family != family) {
1036 			eprintsoline(so, EAFNOSUPPORT);
1037 			return (EAFNOSUPPORT);
1038 		}
1039 		if (namelen != (socklen_t)sizeof (struct sockaddr_in6)) {
1040 			eprintsoline(so, EINVAL);
1041 			return (EINVAL);
1042 		}
1043 #ifdef DEBUG
1044 		/* Verify that apps don't forget to clear sin6_scope_id etc */
1045 		sin6 = (struct sockaddr_in6 *)name;
1046 		if (sin6->sin6_scope_id != 0 &&
1047 		    !IN6_IS_ADDR_LINKSCOPE(&sin6->sin6_addr)) {
1048 			zcmn_err(getzoneid(), CE_WARN,
1049 			    "connect/send* with uninitialized sin6_scope_id "
1050 			    "(%d) on socket. Pid = %d\n",
1051 			    (int)sin6->sin6_scope_id, (int)curproc->p_pid);
1052 		}
1053 #endif /* DEBUG */
1054 		break;
1055 	}
1056 	case AF_UNIX:
1057 		if (so->so_state & SS_FADDR_NOXLATE) {
1058 			return (0);
1059 		}
1060 		if (namelen < (socklen_t)sizeof (short)) {
1061 			eprintsoline(so, ENOENT);
1062 			return (ENOENT);
1063 		}
1064 		if (name->sa_family != family) {
1065 			eprintsoline(so, EAFNOSUPPORT);
1066 			return (EAFNOSUPPORT);
1067 		}
1068 		/* MAXPATHLEN + soun_family + nul termination */
1069 		if (namelen > (socklen_t)(MAXPATHLEN + sizeof (short) + 1)) {
1070 			eprintsoline(so, ENAMETOOLONG);
1071 			return (ENAMETOOLONG);
1072 		}
1073 
1074 		break;
1075 
1076 	default:
1077 		/*
1078 		 * Default is don't do any length or sa_family check
1079 		 * to allow non-sockaddr style addresses.
1080 		 */
1081 		break;
1082 	}
1083 
1084 	return (0);
1085 }
1086 
1087 
1088 /*
1089  * Translate an AF_UNIX sockaddr_un to the transport internal name.
1090  * Assumes caller has called so_addr_verify first.
1091  */
1092 /*ARGSUSED*/
1093 int
1094 so_ux_addr_xlate(struct sonode *so, struct sockaddr *name,
1095     socklen_t namelen, int checkaccess,
1096     void **addrp, socklen_t *addrlenp)
1097 {
1098 	int			error;
1099 	struct sockaddr_un	*soun;
1100 	vnode_t			*vp;
1101 	void			*addr;
1102 	socklen_t		addrlen;
1103 
1104 	dprintso(so, 1, ("so_ux_addr_xlate(%p, %p, %d, %d)\n",
1105 	    so, name, namelen, checkaccess));
1106 
1107 	ASSERT(name != NULL);
1108 	ASSERT(so->so_family == AF_UNIX);
1109 	ASSERT(!(so->so_state & SS_FADDR_NOXLATE));
1110 	ASSERT(namelen >= (socklen_t)sizeof (short));
1111 	ASSERT(name->sa_family == AF_UNIX);
1112 	soun = (struct sockaddr_un *)name;
1113 	/*
1114 	 * Lookup vnode for the specified path name and verify that
1115 	 * it is a socket.
1116 	 */
1117 	error = so_ux_lookup(so, soun, checkaccess, &vp);
1118 	if (error) {
1119 		eprintsoline(so, error);
1120 		return (error);
1121 	}
1122 	/*
1123 	 * Use the address of the peer vnode as the address to send
1124 	 * to. We release the peer vnode here. In case it has been
1125 	 * closed by the time the T_CONN_REQ or T_UNIDATA_REQ reaches the
1126 	 * transport the message will get an error or be dropped.
1127 	 */
1128 	so->so_ux_faddr.soua_vp = vp;
1129 	so->so_ux_faddr.soua_magic = SOU_MAGIC_EXPLICIT;
1130 	addr = &so->so_ux_faddr;
1131 	addrlen = (socklen_t)sizeof (so->so_ux_faddr);
1132 	dprintso(so, 1, ("ux_xlate UNIX: addrlen %d, vp %p\n",
1133 	    addrlen, vp));
1134 	VN_RELE(vp);
1135 	*addrp = addr;
1136 	*addrlenp = (socklen_t)addrlen;
1137 	return (0);
1138 }
1139 
1140 /*
1141  * Esballoc free function for messages that contain SO_FILEP option.
1142  * Decrement the reference count on the file pointers using closef.
1143  */
1144 void
1145 fdbuf_free(struct fdbuf *fdbuf)
1146 {
1147 	int	i;
1148 	struct file *fp;
1149 
1150 	dprint(1, ("fdbuf_free: %d fds\n", fdbuf->fd_numfd));
1151 	for (i = 0; i < fdbuf->fd_numfd; i++) {
1152 		/*
1153 		 * We need pointer size alignment for fd_fds. On a LP64
1154 		 * kernel, the required alignment is 8 bytes while
1155 		 * the option headers and values are only 4 bytes
1156 		 * aligned. So its safer to do a bcopy compared to
1157 		 * assigning fdbuf->fd_fds[i] to fp.
1158 		 */
1159 		bcopy((char *)&fdbuf->fd_fds[i], (char *)&fp, sizeof (fp));
1160 		dprint(1, ("fdbuf_free: [%d] = %p\n", i, fp));
1161 		(void) closef(fp);
1162 	}
1163 	if (fdbuf->fd_ebuf != NULL)
1164 		kmem_free(fdbuf->fd_ebuf, fdbuf->fd_ebuflen);
1165 	kmem_free(fdbuf, fdbuf->fd_size);
1166 }
1167 
1168 /*
1169  * Allocate an esballoc'ed message for AF_UNIX file descriptor passing.
1170  * Waits if memory is not available.
1171  */
1172 mblk_t *
1173 fdbuf_allocmsg(int size, struct fdbuf *fdbuf)
1174 {
1175 	uchar_t	*buf;
1176 	mblk_t	*mp;
1177 
1178 	dprint(1, ("fdbuf_allocmsg: size %d, %d fds\n", size, fdbuf->fd_numfd));
1179 	buf = kmem_alloc(size, KM_SLEEP);
1180 	fdbuf->fd_ebuf = (caddr_t)buf;
1181 	fdbuf->fd_ebuflen = size;
1182 	fdbuf->fd_frtn.free_func = fdbuf_free;
1183 	fdbuf->fd_frtn.free_arg = (caddr_t)fdbuf;
1184 
1185 	mp = esballoc_wait(buf, size, BPRI_MED, &fdbuf->fd_frtn);
1186 	mp->b_datap->db_type = M_PROTO;
1187 	return (mp);
1188 }
1189 
1190 /*
1191  * Extract file descriptors from a fdbuf.
1192  * Return list in rights/rightslen.
1193  */
1194 /*ARGSUSED*/
1195 static int
1196 fdbuf_extract(struct fdbuf *fdbuf, void *rights, int rightslen)
1197 {
1198 	int	i, fd;
1199 	int	*rp;
1200 	struct file *fp;
1201 	int	numfd;
1202 
1203 	dprint(1, ("fdbuf_extract: %d fds, len %d\n",
1204 	    fdbuf->fd_numfd, rightslen));
1205 
1206 	numfd = fdbuf->fd_numfd;
1207 	ASSERT(rightslen == numfd * (int)sizeof (int));
1208 
1209 	/*
1210 	 * Allocate a file descriptor and increment the f_count.
1211 	 * The latter is needed since we always call fdbuf_free
1212 	 * which performs a closef.
1213 	 */
1214 	rp = (int *)rights;
1215 	for (i = 0; i < numfd; i++) {
1216 		if ((fd = ufalloc(0)) == -1)
1217 			goto cleanup;
1218 		/*
1219 		 * We need pointer size alignment for fd_fds. On a LP64
1220 		 * kernel, the required alignment is 8 bytes while
1221 		 * the option headers and values are only 4 bytes
1222 		 * aligned. So its safer to do a bcopy compared to
1223 		 * assigning fdbuf->fd_fds[i] to fp.
1224 		 */
1225 		bcopy((char *)&fdbuf->fd_fds[i], (char *)&fp, sizeof (fp));
1226 		mutex_enter(&fp->f_tlock);
1227 		fp->f_count++;
1228 		mutex_exit(&fp->f_tlock);
1229 		setf(fd, fp);
1230 		*rp++ = fd;
1231 		if (audit_active)
1232 			audit_fdrecv(fd, fp);
1233 		dprint(1, ("fdbuf_extract: [%d] = %d, %p refcnt %d\n",
1234 		    i, fd, fp, fp->f_count));
1235 	}
1236 	return (0);
1237 
1238 cleanup:
1239 	/*
1240 	 * Undo whatever partial work the loop above has done.
1241 	 */
1242 	{
1243 		int j;
1244 
1245 		rp = (int *)rights;
1246 		for (j = 0; j < i; j++) {
1247 			dprint(0,
1248 			    ("fdbuf_extract: cleanup[%d] = %d\n", j, *rp));
1249 			(void) closeandsetf(*rp++, NULL);
1250 		}
1251 	}
1252 
1253 	return (EMFILE);
1254 }
1255 
1256 /*
1257  * Insert file descriptors into an fdbuf.
1258  * Returns a kmem_alloc'ed fdbuf. The fdbuf should be freed
1259  * by calling fdbuf_free().
1260  */
1261 int
1262 fdbuf_create(void *rights, int rightslen, struct fdbuf **fdbufp)
1263 {
1264 	int		numfd, i;
1265 	int		*fds;
1266 	struct file	*fp;
1267 	struct fdbuf	*fdbuf;
1268 	int		fdbufsize;
1269 
1270 	dprint(1, ("fdbuf_create: len %d\n", rightslen));
1271 
1272 	numfd = rightslen / (int)sizeof (int);
1273 
1274 	fdbufsize = (int)FDBUF_HDRSIZE + (numfd * (int)sizeof (struct file *));
1275 	fdbuf = kmem_alloc(fdbufsize, KM_SLEEP);
1276 	fdbuf->fd_size = fdbufsize;
1277 	fdbuf->fd_numfd = 0;
1278 	fdbuf->fd_ebuf = NULL;
1279 	fdbuf->fd_ebuflen = 0;
1280 	fds = (int *)rights;
1281 	for (i = 0; i < numfd; i++) {
1282 		if ((fp = getf(fds[i])) == NULL) {
1283 			fdbuf_free(fdbuf);
1284 			return (EBADF);
1285 		}
1286 		dprint(1, ("fdbuf_create: [%d] = %d, %p refcnt %d\n",
1287 		    i, fds[i], fp, fp->f_count));
1288 		mutex_enter(&fp->f_tlock);
1289 		fp->f_count++;
1290 		mutex_exit(&fp->f_tlock);
1291 		/*
1292 		 * The maximum alignment for fdbuf (or any option header
1293 		 * and its value) it 4 bytes. On a LP64 kernel, the alignment
1294 		 * is not sufficient for pointers (fd_fds in this case). Since
1295 		 * we just did a kmem_alloc (we get a double word alignment),
1296 		 * we don't need to do anything on the send side (we loose
1297 		 * the double word alignment because fdbuf goes after an
1298 		 * option header (eg T_unitdata_req) which is only 4 byte
1299 		 * aligned). We take care of this when we extract the file
1300 		 * descriptor in fdbuf_extract or fdbuf_free.
1301 		 */
1302 		fdbuf->fd_fds[i] = fp;
1303 		fdbuf->fd_numfd++;
1304 		releasef(fds[i]);
1305 		if (audit_active)
1306 			audit_fdsend(fds[i], fp, 0);
1307 	}
1308 	*fdbufp = fdbuf;
1309 	return (0);
1310 }
1311 
1312 static int
1313 fdbuf_optlen(int rightslen)
1314 {
1315 	int numfd;
1316 
1317 	numfd = rightslen / (int)sizeof (int);
1318 
1319 	return ((int)FDBUF_HDRSIZE + (numfd * (int)sizeof (struct file *)));
1320 }
1321 
1322 static t_uscalar_t
1323 fdbuf_cmsglen(int fdbuflen)
1324 {
1325 	return (t_uscalar_t)((fdbuflen - FDBUF_HDRSIZE) /
1326 	    (int)sizeof (struct file *) * (int)sizeof (int));
1327 }
1328 
1329 
1330 /*
1331  * Return non-zero if the mblk and fdbuf are consistent.
1332  */
1333 static int
1334 fdbuf_verify(mblk_t *mp, struct fdbuf *fdbuf, int fdbuflen)
1335 {
1336 	if (fdbuflen >= FDBUF_HDRSIZE &&
1337 	    fdbuflen == fdbuf->fd_size) {
1338 		frtn_t *frp = mp->b_datap->db_frtnp;
1339 		/*
1340 		 * Check that the SO_FILEP portion of the
1341 		 * message has not been modified by
1342 		 * the loopback transport. The sending sockfs generates
1343 		 * a message that is esballoc'ed with the free function
1344 		 * being fdbuf_free() and where free_arg contains the
1345 		 * identical information as the SO_FILEP content.
1346 		 *
1347 		 * If any of these constraints are not satisfied we
1348 		 * silently ignore the option.
1349 		 */
1350 		ASSERT(mp);
1351 		if (frp != NULL &&
1352 		    frp->free_func == fdbuf_free &&
1353 		    frp->free_arg != NULL &&
1354 		    bcmp(frp->free_arg, fdbuf, fdbuflen) == 0) {
1355 			dprint(1, ("fdbuf_verify: fdbuf %p len %d\n",
1356 			    fdbuf, fdbuflen));
1357 			return (1);
1358 		} else {
1359 			zcmn_err(getzoneid(), CE_WARN,
1360 			    "sockfs: mismatched fdbuf content (%p)",
1361 			    (void *)mp);
1362 			return (0);
1363 		}
1364 	} else {
1365 		zcmn_err(getzoneid(), CE_WARN,
1366 		    "sockfs: mismatched fdbuf len %d, %d\n",
1367 		    fdbuflen, fdbuf->fd_size);
1368 		return (0);
1369 	}
1370 }
1371 
1372 /*
1373  * When the file descriptors returned by sorecvmsg can not be passed
1374  * to the application this routine will cleanup the references on
1375  * the files. Start at startoff bytes into the buffer.
1376  */
1377 static void
1378 close_fds(void *fdbuf, int fdbuflen, int startoff)
1379 {
1380 	int *fds = (int *)fdbuf;
1381 	int numfd = fdbuflen / (int)sizeof (int);
1382 	int i;
1383 
1384 	dprint(1, ("close_fds(%p, %d, %d)\n", fdbuf, fdbuflen, startoff));
1385 
1386 	for (i = 0; i < numfd; i++) {
1387 		if (startoff < 0)
1388 			startoff = 0;
1389 		if (startoff < (int)sizeof (int)) {
1390 			/*
1391 			 * This file descriptor is partially or fully after
1392 			 * the offset
1393 			 */
1394 			dprint(0,
1395 			    ("close_fds: cleanup[%d] = %d\n", i, fds[i]));
1396 			(void) closeandsetf(fds[i], NULL);
1397 		}
1398 		startoff -= (int)sizeof (int);
1399 	}
1400 }
1401 
1402 /*
1403  * Close all file descriptors contained in the control part starting at
1404  * the startoffset.
1405  */
1406 void
1407 so_closefds(void *control, t_uscalar_t controllen, int oldflg,
1408     int startoff)
1409 {
1410 	struct cmsghdr *cmsg;
1411 
1412 	if (control == NULL)
1413 		return;
1414 
1415 	if (oldflg) {
1416 		close_fds(control, controllen, startoff);
1417 		return;
1418 	}
1419 	/* Scan control part for file descriptors. */
1420 	for (cmsg = (struct cmsghdr *)control;
1421 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1422 	    cmsg = CMSG_NEXT(cmsg)) {
1423 		if (cmsg->cmsg_level == SOL_SOCKET &&
1424 		    cmsg->cmsg_type == SCM_RIGHTS) {
1425 			close_fds(CMSG_CONTENT(cmsg),
1426 			    (int)CMSG_CONTENTLEN(cmsg),
1427 			    startoff - (int)sizeof (struct cmsghdr));
1428 		}
1429 		startoff -= cmsg->cmsg_len;
1430 	}
1431 }
1432 
1433 /*
1434  * Returns a pointer/length for the file descriptors contained
1435  * in the control buffer. Returns with *fdlenp == -1 if there are no
1436  * file descriptor options present. This is different than there being
1437  * a zero-length file descriptor option.
1438  * Fail if there are multiple SCM_RIGHT cmsgs.
1439  */
1440 int
1441 so_getfdopt(void *control, t_uscalar_t controllen, int oldflg,
1442     void **fdsp, int *fdlenp)
1443 {
1444 	struct cmsghdr *cmsg;
1445 	void *fds;
1446 	int fdlen;
1447 
1448 	if (control == NULL) {
1449 		*fdsp = NULL;
1450 		*fdlenp = -1;
1451 		return (0);
1452 	}
1453 
1454 	if (oldflg) {
1455 		*fdsp = control;
1456 		if (controllen == 0)
1457 			*fdlenp = -1;
1458 		else
1459 			*fdlenp = controllen;
1460 		dprint(1, ("so_getfdopt: old %d\n", *fdlenp));
1461 		return (0);
1462 	}
1463 
1464 	fds = NULL;
1465 	fdlen = 0;
1466 
1467 	for (cmsg = (struct cmsghdr *)control;
1468 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1469 	    cmsg = CMSG_NEXT(cmsg)) {
1470 		if (cmsg->cmsg_level == SOL_SOCKET &&
1471 		    cmsg->cmsg_type == SCM_RIGHTS) {
1472 			if (fds != NULL)
1473 				return (EINVAL);
1474 			fds = CMSG_CONTENT(cmsg);
1475 			fdlen = (int)CMSG_CONTENTLEN(cmsg);
1476 			dprint(1, ("so_getfdopt: new %lu\n",
1477 			    (size_t)CMSG_CONTENTLEN(cmsg)));
1478 		}
1479 	}
1480 	if (fds == NULL) {
1481 		dprint(1, ("so_getfdopt: NONE\n"));
1482 		*fdlenp = -1;
1483 	} else
1484 		*fdlenp = fdlen;
1485 	*fdsp = fds;
1486 	return (0);
1487 }
1488 
1489 /*
1490  * Return the length of the options including any file descriptor options.
1491  */
1492 t_uscalar_t
1493 so_optlen(void *control, t_uscalar_t controllen, int oldflg)
1494 {
1495 	struct cmsghdr *cmsg;
1496 	t_uscalar_t optlen = 0;
1497 	t_uscalar_t len;
1498 
1499 	if (control == NULL)
1500 		return (0);
1501 
1502 	if (oldflg)
1503 		return ((t_uscalar_t)(sizeof (struct T_opthdr) +
1504 		    fdbuf_optlen(controllen)));
1505 
1506 	for (cmsg = (struct cmsghdr *)control;
1507 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1508 	    cmsg = CMSG_NEXT(cmsg)) {
1509 		if (cmsg->cmsg_level == SOL_SOCKET &&
1510 		    cmsg->cmsg_type == SCM_RIGHTS) {
1511 			len = fdbuf_optlen((int)CMSG_CONTENTLEN(cmsg));
1512 		} else {
1513 			len = (t_uscalar_t)CMSG_CONTENTLEN(cmsg);
1514 		}
1515 		optlen += (t_uscalar_t)(_TPI_ALIGN_TOPT(len) +
1516 		    sizeof (struct T_opthdr));
1517 	}
1518 	dprint(1, ("so_optlen: controllen %d, flg %d -> optlen %d\n",
1519 	    controllen, oldflg, optlen));
1520 	return (optlen);
1521 }
1522 
1523 /*
1524  * Copy options from control to the mblk. Skip any file descriptor options.
1525  */
1526 void
1527 so_cmsg2opt(void *control, t_uscalar_t controllen, int oldflg, mblk_t *mp)
1528 {
1529 	struct T_opthdr toh;
1530 	struct cmsghdr *cmsg;
1531 
1532 	if (control == NULL)
1533 		return;
1534 
1535 	if (oldflg) {
1536 		/* No real options - caller has handled file descriptors */
1537 		return;
1538 	}
1539 	for (cmsg = (struct cmsghdr *)control;
1540 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1541 	    cmsg = CMSG_NEXT(cmsg)) {
1542 		/*
1543 		 * Note: The caller handles file descriptors prior
1544 		 * to calling this function.
1545 		 */
1546 		t_uscalar_t len;
1547 
1548 		if (cmsg->cmsg_level == SOL_SOCKET &&
1549 		    cmsg->cmsg_type == SCM_RIGHTS)
1550 			continue;
1551 
1552 		len = (t_uscalar_t)CMSG_CONTENTLEN(cmsg);
1553 		toh.level = cmsg->cmsg_level;
1554 		toh.name = cmsg->cmsg_type;
1555 		toh.len = len + (t_uscalar_t)sizeof (struct T_opthdr);
1556 		toh.status = 0;
1557 
1558 		soappendmsg(mp, &toh, sizeof (toh));
1559 		soappendmsg(mp, CMSG_CONTENT(cmsg), len);
1560 		mp->b_wptr += _TPI_ALIGN_TOPT(len) - len;
1561 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
1562 	}
1563 }
1564 
1565 /*
1566  * Return the length of the control message derived from the options.
1567  * Exclude SO_SRCADDR and SO_UNIX_CLOSE options. Include SO_FILEP.
1568  * When oldflg is set only include SO_FILEP.
1569  * so_opt2cmsg and so_cmsglen are inter-related since so_cmsglen
1570  * allocates the space that so_opt2cmsg fills. If one changes, the other should
1571  * also be checked for any possible impacts.
1572  */
1573 t_uscalar_t
1574 so_cmsglen(mblk_t *mp, void *opt, t_uscalar_t optlen, int oldflg)
1575 {
1576 	t_uscalar_t cmsglen = 0;
1577 	struct T_opthdr *tohp;
1578 	t_uscalar_t len;
1579 	t_uscalar_t last_roundup = 0;
1580 
1581 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1582 
1583 	for (tohp = (struct T_opthdr *)opt;
1584 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1585 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1586 		dprint(1, ("so_cmsglen: level 0x%x, name %d, len %d\n",
1587 		    tohp->level, tohp->name, tohp->len));
1588 		if (tohp->level == SOL_SOCKET &&
1589 		    (tohp->name == SO_SRCADDR ||
1590 		    tohp->name == SO_UNIX_CLOSE)) {
1591 			continue;
1592 		}
1593 		if (tohp->level == SOL_SOCKET && tohp->name == SO_FILEP) {
1594 			struct fdbuf *fdbuf;
1595 			int fdbuflen;
1596 
1597 			fdbuf = (struct fdbuf *)_TPI_TOPT_DATA(tohp);
1598 			fdbuflen = (int)_TPI_TOPT_DATALEN(tohp);
1599 
1600 			if (!fdbuf_verify(mp, fdbuf, fdbuflen))
1601 				continue;
1602 			if (oldflg) {
1603 				cmsglen += fdbuf_cmsglen(fdbuflen);
1604 				continue;
1605 			}
1606 			len = fdbuf_cmsglen(fdbuflen);
1607 		} else if (tohp->level == SOL_SOCKET &&
1608 		    tohp->name == SCM_TIMESTAMP) {
1609 			if (oldflg)
1610 				continue;
1611 
1612 			if (get_udatamodel() == DATAMODEL_NATIVE) {
1613 				len = sizeof (struct timeval);
1614 			} else {
1615 				len = sizeof (struct timeval32);
1616 			}
1617 		} else {
1618 			if (oldflg)
1619 				continue;
1620 			len = (t_uscalar_t)_TPI_TOPT_DATALEN(tohp);
1621 		}
1622 		/*
1623 		 * Exclude roundup for last option to not set
1624 		 * MSG_CTRUNC when the cmsg fits but the padding doesn't fit.
1625 		 */
1626 		last_roundup = (t_uscalar_t)
1627 		    (ROUNDUP_cmsglen(len + (int)sizeof (struct cmsghdr)) -
1628 		    (len + (int)sizeof (struct cmsghdr)));
1629 		cmsglen += (t_uscalar_t)(len + (int)sizeof (struct cmsghdr)) +
1630 		    last_roundup;
1631 	}
1632 	cmsglen -= last_roundup;
1633 	dprint(1, ("so_cmsglen: optlen %d, flg %d -> cmsglen %d\n",
1634 	    optlen, oldflg, cmsglen));
1635 	return (cmsglen);
1636 }
1637 
1638 /*
1639  * Copy options from options to the control. Convert SO_FILEP to
1640  * file descriptors.
1641  * Returns errno or zero.
1642  * so_opt2cmsg and so_cmsglen are inter-related since so_cmsglen
1643  * allocates the space that so_opt2cmsg fills. If one changes, the other should
1644  * also be checked for any possible impacts.
1645  */
1646 int
1647 so_opt2cmsg(mblk_t *mp, void *opt, t_uscalar_t optlen, int oldflg,
1648     void *control, t_uscalar_t controllen)
1649 {
1650 	struct T_opthdr *tohp;
1651 	struct cmsghdr *cmsg;
1652 	struct fdbuf *fdbuf;
1653 	int fdbuflen;
1654 	int error;
1655 #if defined(DEBUG) || defined(__lint)
1656 	struct cmsghdr *cend = (struct cmsghdr *)
1657 	    (((uint8_t *)control) + ROUNDUP_cmsglen(controllen));
1658 #endif
1659 	cmsg = (struct cmsghdr *)control;
1660 
1661 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1662 
1663 	for (tohp = (struct T_opthdr *)opt;
1664 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1665 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1666 		dprint(1, ("so_opt2cmsg: level 0x%x, name %d, len %d\n",
1667 		    tohp->level, tohp->name, tohp->len));
1668 
1669 		if (tohp->level == SOL_SOCKET &&
1670 		    (tohp->name == SO_SRCADDR ||
1671 		    tohp->name == SO_UNIX_CLOSE)) {
1672 			continue;
1673 		}
1674 		ASSERT((uintptr_t)cmsg <= (uintptr_t)control + controllen);
1675 		if (tohp->level == SOL_SOCKET && tohp->name == SO_FILEP) {
1676 			fdbuf = (struct fdbuf *)_TPI_TOPT_DATA(tohp);
1677 			fdbuflen = (int)_TPI_TOPT_DATALEN(tohp);
1678 
1679 			if (!fdbuf_verify(mp, fdbuf, fdbuflen))
1680 				return (EPROTO);
1681 			if (oldflg) {
1682 				error = fdbuf_extract(fdbuf, control,
1683 				    (int)controllen);
1684 				if (error != 0)
1685 					return (error);
1686 				continue;
1687 			} else {
1688 				int fdlen;
1689 
1690 				fdlen = (int)fdbuf_cmsglen(
1691 				    (int)_TPI_TOPT_DATALEN(tohp));
1692 
1693 				cmsg->cmsg_level = tohp->level;
1694 				cmsg->cmsg_type = SCM_RIGHTS;
1695 				cmsg->cmsg_len = (socklen_t)(fdlen +
1696 				    sizeof (struct cmsghdr));
1697 
1698 				error = fdbuf_extract(fdbuf,
1699 				    CMSG_CONTENT(cmsg), fdlen);
1700 				if (error != 0)
1701 					return (error);
1702 			}
1703 		} else if (tohp->level == SOL_SOCKET &&
1704 		    tohp->name == SCM_TIMESTAMP) {
1705 			timestruc_t *timestamp;
1706 
1707 			if (oldflg)
1708 				continue;
1709 
1710 			cmsg->cmsg_level = tohp->level;
1711 			cmsg->cmsg_type = tohp->name;
1712 
1713 			timestamp =
1714 			    (timestruc_t *)P2ROUNDUP((intptr_t)&tohp[1],
1715 			    sizeof (intptr_t));
1716 
1717 			if (get_udatamodel() == DATAMODEL_NATIVE) {
1718 				struct timeval tv;
1719 
1720 				cmsg->cmsg_len = sizeof (struct timeval) +
1721 				    sizeof (struct cmsghdr);
1722 				tv.tv_sec = timestamp->tv_sec;
1723 				tv.tv_usec = timestamp->tv_nsec /
1724 				    (NANOSEC / MICROSEC);
1725 				/*
1726 				 * on LP64 systems, the struct timeval in
1727 				 * the destination will not be 8-byte aligned,
1728 				 * so use bcopy to avoid alignment trouble
1729 				 */
1730 				bcopy(&tv, CMSG_CONTENT(cmsg), sizeof (tv));
1731 			} else {
1732 				struct timeval32 *time32;
1733 
1734 				cmsg->cmsg_len = sizeof (struct timeval32) +
1735 				    sizeof (struct cmsghdr);
1736 				time32 = (struct timeval32 *)CMSG_CONTENT(cmsg);
1737 				time32->tv_sec = (time32_t)timestamp->tv_sec;
1738 				time32->tv_usec =
1739 				    (int32_t)(timestamp->tv_nsec /
1740 				    (NANOSEC / MICROSEC));
1741 			}
1742 
1743 		} else {
1744 			if (oldflg)
1745 				continue;
1746 
1747 			cmsg->cmsg_level = tohp->level;
1748 			cmsg->cmsg_type = tohp->name;
1749 			cmsg->cmsg_len = (socklen_t)(_TPI_TOPT_DATALEN(tohp) +
1750 			    sizeof (struct cmsghdr));
1751 
1752 			/* copy content to control data part */
1753 			bcopy(&tohp[1], CMSG_CONTENT(cmsg),
1754 			    CMSG_CONTENTLEN(cmsg));
1755 		}
1756 		/* move to next CMSG structure! */
1757 		cmsg = CMSG_NEXT(cmsg);
1758 	}
1759 	dprint(1, ("so_opt2cmsg: buf %p len %d; cend %p; final cmsg %p\n",
1760 	    control, controllen, cend, cmsg));
1761 	ASSERT(cmsg <= cend);
1762 	return (0);
1763 }
1764 
1765 /*
1766  * Extract the SO_SRCADDR option value if present.
1767  */
1768 void
1769 so_getopt_srcaddr(void *opt, t_uscalar_t optlen, void **srcp,
1770     t_uscalar_t *srclenp)
1771 {
1772 	struct T_opthdr		*tohp;
1773 
1774 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1775 
1776 	ASSERT(srcp != NULL && srclenp != NULL);
1777 	*srcp = NULL;
1778 	*srclenp = 0;
1779 
1780 	for (tohp = (struct T_opthdr *)opt;
1781 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1782 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1783 		dprint(1, ("so_getopt_srcaddr: level 0x%x, name %d, len %d\n",
1784 		    tohp->level, tohp->name, tohp->len));
1785 		if (tohp->level == SOL_SOCKET &&
1786 		    tohp->name == SO_SRCADDR) {
1787 			*srcp = _TPI_TOPT_DATA(tohp);
1788 			*srclenp = (t_uscalar_t)_TPI_TOPT_DATALEN(tohp);
1789 		}
1790 	}
1791 }
1792 
1793 /*
1794  * Verify if the SO_UNIX_CLOSE option is present.
1795  */
1796 int
1797 so_getopt_unix_close(void *opt, t_uscalar_t optlen)
1798 {
1799 	struct T_opthdr		*tohp;
1800 
1801 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1802 
1803 	for (tohp = (struct T_opthdr *)opt;
1804 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1805 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1806 		dprint(1,
1807 		    ("so_getopt_unix_close: level 0x%x, name %d, len %d\n",
1808 		    tohp->level, tohp->name, tohp->len));
1809 		if (tohp->level == SOL_SOCKET &&
1810 		    tohp->name == SO_UNIX_CLOSE)
1811 			return (1);
1812 	}
1813 	return (0);
1814 }
1815 
1816 /*
1817  * Allocate an M_PROTO message.
1818  *
1819  * If allocation fails the behavior depends on sleepflg:
1820  *	_ALLOC_NOSLEEP	fail immediately
1821  *	_ALLOC_INTR	sleep for memory until a signal is caught
1822  *	_ALLOC_SLEEP	sleep forever. Don't return NULL.
1823  */
1824 mblk_t *
1825 soallocproto(size_t size, int sleepflg)
1826 {
1827 	mblk_t	*mp;
1828 
1829 	/* Round up size for reuse */
1830 	size = MAX(size, 64);
1831 	mp = allocb(size, BPRI_MED);
1832 	if (mp == NULL) {
1833 		int error;	/* Dummy - error not returned to caller */
1834 
1835 		switch (sleepflg) {
1836 		case _ALLOC_SLEEP:
1837 			mp = allocb_wait(size, BPRI_MED, STR_NOSIG, &error);
1838 			ASSERT(mp);
1839 			break;
1840 		case _ALLOC_INTR:
1841 			mp = allocb_wait(size, BPRI_MED, 0, &error);
1842 			if (mp == NULL) {
1843 				/* Caught signal while sleeping for memory */
1844 				eprintline(ENOBUFS);
1845 				return (NULL);
1846 			}
1847 			break;
1848 		case _ALLOC_NOSLEEP:
1849 		default:
1850 			eprintline(ENOBUFS);
1851 			return (NULL);
1852 		}
1853 	}
1854 	DB_TYPE(mp) = M_PROTO;
1855 	return (mp);
1856 }
1857 
1858 /*
1859  * Allocate an M_PROTO message with a single component.
1860  * len is the length of buf. size is the amount to allocate.
1861  *
1862  * buf can be NULL with a non-zero len.
1863  * This results in a bzero'ed chunk being placed the message.
1864  */
1865 mblk_t *
1866 soallocproto1(const void *buf, ssize_t len, ssize_t size, int sleepflg)
1867 {
1868 	mblk_t	*mp;
1869 
1870 	if (size == 0)
1871 		size = len;
1872 
1873 	ASSERT(size >= len);
1874 	/* Round up size for reuse */
1875 	size = MAX(size, 64);
1876 	mp = soallocproto(size, sleepflg);
1877 	if (mp == NULL)
1878 		return (NULL);
1879 	mp->b_datap->db_type = M_PROTO;
1880 	if (len != 0) {
1881 		if (buf != NULL)
1882 			bcopy(buf, mp->b_wptr, len);
1883 		else
1884 			bzero(mp->b_wptr, len);
1885 		mp->b_wptr += len;
1886 	}
1887 	return (mp);
1888 }
1889 
1890 /*
1891  * Append buf/len to mp.
1892  * The caller has to ensure that there is enough room in the mblk.
1893  *
1894  * buf can be NULL with a non-zero len.
1895  * This results in a bzero'ed chunk being placed the message.
1896  */
1897 void
1898 soappendmsg(mblk_t *mp, const void *buf, ssize_t len)
1899 {
1900 	ASSERT(mp);
1901 
1902 	if (len != 0) {
1903 		/* Assert for room left */
1904 		ASSERT(mp->b_datap->db_lim - mp->b_wptr >= len);
1905 		if (buf != NULL)
1906 			bcopy(buf, mp->b_wptr, len);
1907 		else
1908 			bzero(mp->b_wptr, len);
1909 	}
1910 	mp->b_wptr += len;
1911 }
1912 
1913 /*
1914  * Create a message using two kernel buffers.
1915  * If size is set that will determine the allocation size (e.g. for future
1916  * soappendmsg calls). If size is zero it is derived from the buffer
1917  * lengths.
1918  */
1919 mblk_t *
1920 soallocproto2(const void *buf1, ssize_t len1, const void *buf2, ssize_t len2,
1921     ssize_t size, int sleepflg)
1922 {
1923 	mblk_t *mp;
1924 
1925 	if (size == 0)
1926 		size = len1 + len2;
1927 	ASSERT(size >= len1 + len2);
1928 
1929 	mp = soallocproto1(buf1, len1, size, sleepflg);
1930 	if (mp)
1931 		soappendmsg(mp, buf2, len2);
1932 	return (mp);
1933 }
1934 
1935 /*
1936  * Create a message using three kernel buffers.
1937  * If size is set that will determine the allocation size (for future
1938  * soappendmsg calls). If size is zero it is derived from the buffer
1939  * lengths.
1940  */
1941 mblk_t *
1942 soallocproto3(const void *buf1, ssize_t len1, const void *buf2, ssize_t len2,
1943     const void *buf3, ssize_t len3, ssize_t size, int sleepflg)
1944 {
1945 	mblk_t *mp;
1946 
1947 	if (size == 0)
1948 		size = len1 + len2 +len3;
1949 	ASSERT(size >= len1 + len2 + len3);
1950 
1951 	mp = soallocproto1(buf1, len1, size, sleepflg);
1952 	if (mp != NULL) {
1953 		soappendmsg(mp, buf2, len2);
1954 		soappendmsg(mp, buf3, len3);
1955 	}
1956 	return (mp);
1957 }
1958 
1959 #ifdef DEBUG
1960 char *
1961 pr_state(uint_t state, uint_t mode)
1962 {
1963 	static char buf[1024];
1964 
1965 	buf[0] = 0;
1966 	if (state & SS_ISCONNECTED)
1967 		strcat(buf, "ISCONNECTED ");
1968 	if (state & SS_ISCONNECTING)
1969 		strcat(buf, "ISCONNECTING ");
1970 	if (state & SS_ISDISCONNECTING)
1971 		strcat(buf, "ISDISCONNECTING ");
1972 	if (state & SS_CANTSENDMORE)
1973 		strcat(buf, "CANTSENDMORE ");
1974 
1975 	if (state & SS_CANTRCVMORE)
1976 		strcat(buf, "CANTRCVMORE ");
1977 	if (state & SS_ISBOUND)
1978 		strcat(buf, "ISBOUND ");
1979 	if (state & SS_NDELAY)
1980 		strcat(buf, "NDELAY ");
1981 	if (state & SS_NONBLOCK)
1982 		strcat(buf, "NONBLOCK ");
1983 
1984 	if (state & SS_ASYNC)
1985 		strcat(buf, "ASYNC ");
1986 	if (state & SS_ACCEPTCONN)
1987 		strcat(buf, "ACCEPTCONN ");
1988 	if (state & SS_HASCONNIND)
1989 		strcat(buf, "HASCONNIND ");
1990 	if (state & SS_SAVEDEOR)
1991 		strcat(buf, "SAVEDEOR ");
1992 
1993 	if (state & SS_RCVATMARK)
1994 		strcat(buf, "RCVATMARK ");
1995 	if (state & SS_OOBPEND)
1996 		strcat(buf, "OOBPEND ");
1997 	if (state & SS_HAVEOOBDATA)
1998 		strcat(buf, "HAVEOOBDATA ");
1999 	if (state & SS_HADOOBDATA)
2000 		strcat(buf, "HADOOBDATA ");
2001 
2002 	if (state & SS_FADDR_NOXLATE)
2003 		strcat(buf, "FADDR_NOXLATE ");
2004 
2005 	if (mode & SM_PRIV)
2006 		strcat(buf, "PRIV ");
2007 	if (mode & SM_ATOMIC)
2008 		strcat(buf, "ATOMIC ");
2009 	if (mode & SM_ADDR)
2010 		strcat(buf, "ADDR ");
2011 	if (mode & SM_CONNREQUIRED)
2012 		strcat(buf, "CONNREQUIRED ");
2013 
2014 	if (mode & SM_FDPASSING)
2015 		strcat(buf, "FDPASSING ");
2016 	if (mode & SM_EXDATA)
2017 		strcat(buf, "EXDATA ");
2018 	if (mode & SM_OPTDATA)
2019 		strcat(buf, "OPTDATA ");
2020 	if (mode & SM_BYTESTREAM)
2021 		strcat(buf, "BYTESTREAM ");
2022 	return (buf);
2023 }
2024 
2025 char *
2026 pr_addr(int family, struct sockaddr *addr, t_uscalar_t addrlen)
2027 {
2028 	static char buf[1024];
2029 
2030 	if (addr == NULL || addrlen == 0) {
2031 		sprintf(buf, "(len %d) %p", addrlen, addr);
2032 		return (buf);
2033 	}
2034 	switch (family) {
2035 	case AF_INET: {
2036 		struct sockaddr_in sin;
2037 
2038 		bcopy(addr, &sin, sizeof (sin));
2039 
2040 		(void) sprintf(buf, "(len %d) %x/%d",
2041 		    addrlen, ntohl(sin.sin_addr.s_addr),
2042 		    ntohs(sin.sin_port));
2043 		break;
2044 	}
2045 	case AF_INET6: {
2046 		struct sockaddr_in6 sin6;
2047 		uint16_t *piece = (uint16_t *)&sin6.sin6_addr;
2048 
2049 		bcopy((char *)addr, (char *)&sin6, sizeof (sin6));
2050 		sprintf(buf, "(len %d) %x:%x:%x:%x:%x:%x:%x:%x/%d",
2051 		    addrlen,
2052 		    ntohs(piece[0]), ntohs(piece[1]),
2053 		    ntohs(piece[2]), ntohs(piece[3]),
2054 		    ntohs(piece[4]), ntohs(piece[5]),
2055 		    ntohs(piece[6]), ntohs(piece[7]),
2056 		    ntohs(sin6.sin6_port));
2057 		break;
2058 	}
2059 	case AF_UNIX: {
2060 		struct sockaddr_un *soun = (struct sockaddr_un *)addr;
2061 
2062 		(void) sprintf(buf, "(len %d) %s",
2063 		    addrlen,
2064 		    (soun == NULL) ? "(none)" : soun->sun_path);
2065 		break;
2066 	}
2067 	default:
2068 		(void) sprintf(buf, "(unknown af %d)", family);
2069 		break;
2070 	}
2071 	return (buf);
2072 }
2073 
2074 /* The logical equivalence operator (a if-and-only-if b) */
2075 #define	EQUIV(a, b)	(((a) && (b)) || (!(a) && (!(b))))
2076 
2077 /*
2078  * Verify limitations and invariants on oob state.
2079  * Return 1 if OK, otherwise 0 so that it can be used as
2080  *	ASSERT(verify_oobstate(so));
2081  */
2082 int
2083 so_verify_oobstate(struct sonode *so)
2084 {
2085 	ASSERT(MUTEX_HELD(&so->so_lock));
2086 
2087 	/*
2088 	 * The possible state combinations are:
2089 	 *	0
2090 	 *	SS_OOBPEND
2091 	 *	SS_OOBPEND|SS_HAVEOOBDATA
2092 	 *	SS_OOBPEND|SS_HADOOBDATA
2093 	 *	SS_HADOOBDATA
2094 	 */
2095 	switch (so->so_state & (SS_OOBPEND|SS_HAVEOOBDATA|SS_HADOOBDATA)) {
2096 	case 0:
2097 	case SS_OOBPEND:
2098 	case SS_OOBPEND|SS_HAVEOOBDATA:
2099 	case SS_OOBPEND|SS_HADOOBDATA:
2100 	case SS_HADOOBDATA:
2101 		break;
2102 	default:
2103 		printf("Bad oob state 1 (%p): counts %d/%d state %s\n",
2104 		    so, so->so_oobsigcnt,
2105 		    so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2106 		return (0);
2107 	}
2108 
2109 	/* SS_RCVATMARK should only be set when SS_OOBPEND is set */
2110 	if ((so->so_state & (SS_RCVATMARK|SS_OOBPEND)) == SS_RCVATMARK) {
2111 		printf("Bad oob state 2 (%p): counts %d/%d state %s\n",
2112 		    so, so->so_oobsigcnt,
2113 		    so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2114 		return (0);
2115 	}
2116 
2117 	/*
2118 	 * (so_oobsigcnt != 0 or SS_RCVATMARK) iff SS_OOBPEND
2119 	 */
2120 	if (!EQUIV((so->so_oobsigcnt != 0) || (so->so_state & SS_RCVATMARK),
2121 	    so->so_state & SS_OOBPEND)) {
2122 		printf("Bad oob state 3 (%p): counts %d/%d state %s\n",
2123 		    so, so->so_oobsigcnt,
2124 		    so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2125 		return (0);
2126 	}
2127 
2128 	/*
2129 	 * Unless SO_OOBINLINE we have so_oobmsg != NULL iff SS_HAVEOOBDATA
2130 	 */
2131 	if (!(so->so_options & SO_OOBINLINE) &&
2132 	    !EQUIV(so->so_oobmsg != NULL, so->so_state & SS_HAVEOOBDATA)) {
2133 		printf("Bad oob state 4 (%p): counts %d/%d state %s\n",
2134 		    so, so->so_oobsigcnt,
2135 		    so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2136 		return (0);
2137 	}
2138 	if (so->so_oobsigcnt < so->so_oobcnt) {
2139 		printf("Bad oob state 5 (%p): counts %d/%d state %s\n",
2140 		    so, so->so_oobsigcnt,
2141 		    so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2142 		return (0);
2143 	}
2144 	return (1);
2145 }
2146 #undef	EQUIV
2147 
2148 #endif /* DEBUG */
2149 
2150 /* initialize sockfs zone specific kstat related items			*/
2151 void *
2152 sock_kstat_init(zoneid_t zoneid)
2153 {
2154 	kstat_t	*ksp;
2155 
2156 	ksp = kstat_create_zone("sockfs", 0, "sock_unix_list", "misc",
2157 	    KSTAT_TYPE_RAW, 0, KSTAT_FLAG_VAR_SIZE|KSTAT_FLAG_VIRTUAL, zoneid);
2158 
2159 	if (ksp != NULL) {
2160 		ksp->ks_update = sockfs_update;
2161 		ksp->ks_snapshot = sockfs_snapshot;
2162 		ksp->ks_lock = &socklist.sl_lock;
2163 		ksp->ks_private = (void *)(uintptr_t)zoneid;
2164 		kstat_install(ksp);
2165 	}
2166 
2167 	return (ksp);
2168 }
2169 
2170 /* tear down sockfs zone specific kstat related items			*/
2171 /*ARGSUSED*/
2172 void
2173 sock_kstat_fini(zoneid_t zoneid, void *arg)
2174 {
2175 	kstat_t *ksp = (kstat_t *)arg;
2176 
2177 	if (ksp != NULL) {
2178 		ASSERT(zoneid == (zoneid_t)(uintptr_t)ksp->ks_private);
2179 		kstat_delete(ksp);
2180 	}
2181 }
2182 
2183 /*
2184  * Zones:
2185  * Note that nactive is going to be different for each zone.
2186  * This means we require kstat to call sockfs_update and then sockfs_snapshot
2187  * for the same zone, or sockfs_snapshot will be taken into the wrong size
2188  * buffer. This is safe, but if the buffer is too small, user will not be
2189  * given details of all sockets. However, as this kstat has a ks_lock, kstat
2190  * driver will keep it locked between the update and the snapshot, so no
2191  * other process (zone) can currently get inbetween resulting in a wrong size
2192  * buffer allocation.
2193  */
2194 static int
2195 sockfs_update(kstat_t *ksp, int rw)
2196 {
2197 	uint_t	nactive = 0;		/* # of active AF_UNIX sockets	*/
2198 	struct sonode	*so;		/* current sonode on socklist	*/
2199 	zoneid_t	myzoneid = (zoneid_t)(uintptr_t)ksp->ks_private;
2200 
2201 	ASSERT((zoneid_t)(uintptr_t)ksp->ks_private == getzoneid());
2202 
2203 	if (rw == KSTAT_WRITE) {	/* bounce all writes		*/
2204 		return (EACCES);
2205 	}
2206 
2207 	for (so = socklist.sl_list; so != NULL; so = so->so_next) {
2208 		if (so->so_accessvp != NULL && so->so_zoneid == myzoneid) {
2209 			nactive++;
2210 		}
2211 	}
2212 	ksp->ks_ndata = nactive;
2213 	ksp->ks_data_size = nactive * sizeof (struct k_sockinfo);
2214 
2215 	return (0);
2216 }
2217 
2218 static int
2219 sockfs_snapshot(kstat_t *ksp, void *buf, int rw)
2220 {
2221 	int			ns;	/* # of sonodes we've copied	*/
2222 	struct sonode		*so;	/* current sonode on socklist	*/
2223 	struct k_sockinfo	*pksi;	/* where we put sockinfo data	*/
2224 	t_uscalar_t		sn_len;	/* soa_len			*/
2225 	zoneid_t		myzoneid = (zoneid_t)(uintptr_t)ksp->ks_private;
2226 
2227 	ASSERT((zoneid_t)(uintptr_t)ksp->ks_private == getzoneid());
2228 
2229 	ksp->ks_snaptime = gethrtime();
2230 
2231 	if (rw == KSTAT_WRITE) {	/* bounce all writes		*/
2232 		return (EACCES);
2233 	}
2234 
2235 	/*
2236 	 * for each sonode on the socklist, we massage the important
2237 	 * info into buf, in k_sockinfo format.
2238 	 */
2239 	pksi = (struct k_sockinfo *)buf;
2240 	for (ns = 0, so = socklist.sl_list; so != NULL; so = so->so_next) {
2241 		/* only stuff active sonodes and the same zone:		*/
2242 		if (so->so_accessvp == NULL || so->so_zoneid != myzoneid) {
2243 			continue;
2244 		}
2245 
2246 		/*
2247 		 * If the sonode was activated between the update and the
2248 		 * snapshot, we're done - as this is only a snapshot.
2249 		 */
2250 		if ((caddr_t)(pksi) >= (caddr_t)buf + ksp->ks_data_size) {
2251 			break;
2252 		}
2253 
2254 		/* copy important info into buf:			*/
2255 		pksi->ks_si.si_size = sizeof (struct k_sockinfo);
2256 		pksi->ks_si.si_family = so->so_family;
2257 		pksi->ks_si.si_type = so->so_type;
2258 		pksi->ks_si.si_flag = so->so_flag;
2259 		pksi->ks_si.si_state = so->so_state;
2260 		pksi->ks_si.si_serv_type = so->so_serv_type;
2261 		pksi->ks_si.si_ux_laddr_sou_magic = so->so_ux_laddr.soua_magic;
2262 		pksi->ks_si.si_ux_faddr_sou_magic = so->so_ux_faddr.soua_magic;
2263 		pksi->ks_si.si_laddr_soa_len = so->so_laddr.soa_len;
2264 		pksi->ks_si.si_faddr_soa_len = so->so_faddr.soa_len;
2265 		pksi->ks_si.si_szoneid = so->so_zoneid;
2266 
2267 		mutex_enter(&so->so_lock);
2268 
2269 		if (so->so_laddr_sa != NULL) {
2270 			ASSERT(so->so_laddr_sa->sa_data != NULL);
2271 			sn_len = so->so_laddr_len;
2272 			ASSERT(sn_len <= sizeof (short) +
2273 			    sizeof (pksi->ks_si.si_laddr_sun_path));
2274 
2275 			pksi->ks_si.si_laddr_family =
2276 			    so->so_laddr_sa->sa_family;
2277 			if (sn_len != 0) {
2278 				/* AF_UNIX socket names are NULL terminated */
2279 				(void) strncpy(pksi->ks_si.si_laddr_sun_path,
2280 				    so->so_laddr_sa->sa_data,
2281 				    sizeof (pksi->ks_si.si_laddr_sun_path));
2282 				sn_len = strlen(pksi->ks_si.si_laddr_sun_path);
2283 			}
2284 			pksi->ks_si.si_laddr_sun_path[sn_len] = 0;
2285 		}
2286 
2287 		if (so->so_faddr_sa != NULL) {
2288 			ASSERT(so->so_faddr_sa->sa_data != NULL);
2289 			sn_len = so->so_faddr_len;
2290 			ASSERT(sn_len <= sizeof (short) +
2291 			    sizeof (pksi->ks_si.si_faddr_sun_path));
2292 
2293 			pksi->ks_si.si_faddr_family =
2294 			    so->so_faddr_sa->sa_family;
2295 			if (sn_len != 0) {
2296 				(void) strncpy(pksi->ks_si.si_faddr_sun_path,
2297 				    so->so_faddr_sa->sa_data,
2298 				    sizeof (pksi->ks_si.si_faddr_sun_path));
2299 				sn_len = strlen(pksi->ks_si.si_faddr_sun_path);
2300 			}
2301 			pksi->ks_si.si_faddr_sun_path[sn_len] = 0;
2302 		}
2303 
2304 		mutex_exit(&so->so_lock);
2305 
2306 		(void) sprintf(pksi->ks_straddr[0], "%p", (void *)so);
2307 		(void) sprintf(pksi->ks_straddr[1], "%p",
2308 		    (void *)so->so_ux_laddr.soua_vp);
2309 		(void) sprintf(pksi->ks_straddr[2], "%p",
2310 		    (void *)so->so_ux_faddr.soua_vp);
2311 
2312 		ns++;
2313 		pksi++;
2314 	}
2315 
2316 	ksp->ks_ndata = ns;
2317 	return (0);
2318 }
2319 
2320 ssize_t
2321 soreadfile(file_t *fp, uchar_t *buf, u_offset_t fileoff, int *err, size_t size)
2322 {
2323 	struct uio auio;
2324 	struct iovec aiov[MSG_MAXIOVLEN];
2325 	register vnode_t *vp;
2326 	int ioflag, rwflag;
2327 	ssize_t cnt;
2328 	int error = 0;
2329 	int iovcnt = 0;
2330 	short fflag;
2331 
2332 	vp = fp->f_vnode;
2333 	fflag = fp->f_flag;
2334 
2335 	rwflag = 0;
2336 	aiov[0].iov_base = (caddr_t)buf;
2337 	aiov[0].iov_len = size;
2338 	iovcnt = 1;
2339 	cnt = (ssize_t)size;
2340 	(void) VOP_RWLOCK(vp, rwflag, NULL);
2341 
2342 	auio.uio_loffset = fileoff;
2343 	auio.uio_iov = aiov;
2344 	auio.uio_iovcnt = iovcnt;
2345 	auio.uio_resid = cnt;
2346 	auio.uio_segflg = UIO_SYSSPACE;
2347 	auio.uio_llimit = MAXOFFSET_T;
2348 	auio.uio_fmode = fflag;
2349 	auio.uio_extflg = UIO_COPY_CACHED;
2350 
2351 	ioflag = auio.uio_fmode & (FAPPEND|FSYNC|FDSYNC|FRSYNC);
2352 
2353 	/* If read sync is not asked for, filter sync flags */
2354 	if ((ioflag & FRSYNC) == 0)
2355 		ioflag &= ~(FSYNC|FDSYNC);
2356 	error = VOP_READ(vp, &auio, ioflag, fp->f_cred, NULL);
2357 	cnt -= auio.uio_resid;
2358 
2359 	VOP_RWUNLOCK(vp, rwflag, NULL);
2360 
2361 	if (error == EINTR && cnt != 0)
2362 		error = 0;
2363 out:
2364 	if (error != 0) {
2365 		*err = error;
2366 		return (0);
2367 	} else {
2368 		*err = 0;
2369 		return (cnt);
2370 	}
2371 }
2372