xref: /titanic_44/usr/src/uts/common/fs/sockfs/socksyscalls.c (revision 2d6b5ea734bb47d251c82670646fde46af15fd69)
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 #include <sys/types.h>
28 #include <sys/t_lock.h>
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/buf.h>
32 #include <sys/conf.h>
33 #include <sys/cred.h>
34 #include <sys/kmem.h>
35 #include <sys/sysmacros.h>
36 #include <sys/vfs.h>
37 #include <sys/vnode.h>
38 #include <sys/debug.h>
39 #include <sys/errno.h>
40 #include <sys/time.h>
41 #include <sys/file.h>
42 #include <sys/user.h>
43 #include <sys/stream.h>
44 #include <sys/strsubr.h>
45 #include <sys/strsun.h>
46 #include <sys/sunddi.h>
47 #include <sys/esunddi.h>
48 #include <sys/flock.h>
49 #include <sys/modctl.h>
50 #include <sys/cmn_err.h>
51 #include <sys/vmsystm.h>
52 #include <sys/policy.h>
53 
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 
57 #include <sys/isa_defs.h>
58 #include <sys/inttypes.h>
59 #include <sys/systm.h>
60 #include <sys/cpuvar.h>
61 #include <sys/filio.h>
62 #include <sys/sendfile.h>
63 #include <sys/ddi.h>
64 #include <vm/seg.h>
65 #include <vm/seg_map.h>
66 #include <vm/seg_kpm.h>
67 
68 #include <fs/sockfs/nl7c.h>
69 #include <fs/sockfs/sockcommon.h>
70 #include <fs/sockfs/socktpi.h>
71 
72 #ifdef SOCK_TEST
73 int do_useracc = 1;		/* Controlled by setting SO_DEBUG to 4 */
74 #else
75 #define	do_useracc	1
76 #endif /* SOCK_TEST */
77 
78 extern int xnet_truncate_print;
79 
80 /*
81  * Note: DEF_IOV_MAX is defined and used as it is in "fs/vncalls.c"
82  *	 as there isn't a formal definition of IOV_MAX ???
83  */
84 #define	MSG_MAXIOVLEN	16
85 
86 /*
87  * Kernel component of socket creation.
88  *
89  * The socket library determines which version number to use.
90  * First the library calls this with a NULL devpath. If this fails
91  * to find a transport (using solookup) the library will look in /etc/netconfig
92  * for the appropriate transport. If one is found it will pass in the
93  * devpath for the kernel to use.
94  */
95 int
96 so_socket(int family, int type, int protocol, char *devpath, int version)
97 {
98 	struct sonode *so;
99 	vnode_t *vp;
100 	struct file *fp;
101 	int fd;
102 	int error;
103 
104 	if (devpath != NULL) {
105 		char *buf;
106 		size_t kdevpathlen = 0;
107 
108 		buf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
109 		if ((error = copyinstr(devpath, buf,
110 		    MAXPATHLEN, &kdevpathlen)) != 0) {
111 			kmem_free(buf, MAXPATHLEN);
112 			return (set_errno(error));
113 		}
114 		so = socket_create(family, type, protocol, buf, NULL,
115 		    SOCKET_SLEEP, version, CRED(), &error);
116 		kmem_free(buf, MAXPATHLEN);
117 	} else {
118 		so = socket_create(family, type, protocol, NULL, NULL,
119 		    SOCKET_SLEEP, version, CRED(), &error);
120 	}
121 	if (so == NULL)
122 		return (set_errno(error));
123 
124 	/* Allocate a file descriptor for the socket */
125 	vp = SOTOV(so);
126 	if (error = falloc(vp, FWRITE|FREAD, &fp, &fd)) {
127 		(void) socket_close(so, 0, CRED());
128 		socket_destroy(so);
129 		return (set_errno(error));
130 	}
131 
132 	/*
133 	 * Now fill in the entries that falloc reserved
134 	 */
135 	mutex_exit(&fp->f_tlock);
136 	setf(fd, fp);
137 
138 	return (fd);
139 }
140 
141 /*
142  * Map from a file descriptor to a socket node.
143  * Returns with the file descriptor held i.e. the caller has to
144  * use releasef when done with the file descriptor.
145  */
146 struct sonode *
147 getsonode(int sock, int *errorp, file_t **fpp)
148 {
149 	file_t *fp;
150 	vnode_t *vp;
151 	struct sonode *so;
152 
153 	if ((fp = getf(sock)) == NULL) {
154 		*errorp = EBADF;
155 		eprintline(*errorp);
156 		return (NULL);
157 	}
158 	vp = fp->f_vnode;
159 	/* Check if it is a socket */
160 	if (vp->v_type != VSOCK) {
161 		releasef(sock);
162 		*errorp = ENOTSOCK;
163 		eprintline(*errorp);
164 		return (NULL);
165 	}
166 	/*
167 	 * Use the stream head to find the real socket vnode.
168 	 * This is needed when namefs sits above sockfs.
169 	 */
170 	if (vp->v_stream) {
171 		ASSERT(vp->v_stream->sd_vnode);
172 		vp = vp->v_stream->sd_vnode;
173 
174 		so = VTOSO(vp);
175 		if (so->so_version == SOV_STREAM) {
176 			releasef(sock);
177 			*errorp = ENOTSOCK;
178 			eprintsoline(so, *errorp);
179 			return (NULL);
180 		}
181 	} else {
182 		so = VTOSO(vp);
183 	}
184 	if (fpp)
185 		*fpp = fp;
186 	return (so);
187 }
188 
189 /*
190  * Allocate and copyin a sockaddr.
191  * Ensures NULL termination for AF_UNIX addresses by extending them
192  * with one NULL byte if need be. Verifies that the length is not
193  * excessive to prevent an application from consuming all of kernel
194  * memory. Returns NULL when an error occurred.
195  */
196 static struct sockaddr *
197 copyin_name(struct sonode *so, struct sockaddr *name, socklen_t *namelenp,
198 	    int *errorp)
199 {
200 	char	*faddr;
201 	size_t	namelen = (size_t)*namelenp;
202 
203 	ASSERT(namelen != 0);
204 	if (namelen > SO_MAXARGSIZE) {
205 		*errorp = EINVAL;
206 		eprintsoline(so, *errorp);
207 		return (NULL);
208 	}
209 
210 	faddr = (char *)kmem_alloc(namelen, KM_SLEEP);
211 	if (copyin(name, faddr, namelen)) {
212 		kmem_free(faddr, namelen);
213 		*errorp = EFAULT;
214 		eprintsoline(so, *errorp);
215 		return (NULL);
216 	}
217 
218 	/*
219 	 * Add space for NULL termination if needed.
220 	 * Do a quick check if the last byte is NUL.
221 	 */
222 	if (so->so_family == AF_UNIX && faddr[namelen - 1] != '\0') {
223 		/* Check if there is any NULL termination */
224 		size_t	i;
225 		int foundnull = 0;
226 
227 		for (i = sizeof (name->sa_family); i < namelen; i++) {
228 			if (faddr[i] == '\0') {
229 				foundnull = 1;
230 				break;
231 			}
232 		}
233 		if (!foundnull) {
234 			/* Add extra byte for NUL padding */
235 			char *nfaddr;
236 
237 			nfaddr = (char *)kmem_alloc(namelen + 1, KM_SLEEP);
238 			bcopy(faddr, nfaddr, namelen);
239 			kmem_free(faddr, namelen);
240 
241 			/* NUL terminate */
242 			nfaddr[namelen] = '\0';
243 			namelen++;
244 			ASSERT((socklen_t)namelen == namelen);
245 			*namelenp = (socklen_t)namelen;
246 			faddr = nfaddr;
247 		}
248 	}
249 	return ((struct sockaddr *)faddr);
250 }
251 
252 /*
253  * Copy from kaddr/klen to uaddr/ulen. Updates ulenp if non-NULL.
254  */
255 static int
256 copyout_arg(void *uaddr, socklen_t ulen, void *ulenp,
257 		void *kaddr, socklen_t klen)
258 {
259 	if (uaddr != NULL) {
260 		if (ulen > klen)
261 			ulen = klen;
262 
263 		if (ulen != 0) {
264 			if (copyout(kaddr, uaddr, ulen))
265 				return (EFAULT);
266 		}
267 	} else
268 		ulen = 0;
269 
270 	if (ulenp != NULL) {
271 		if (copyout(&ulen, ulenp, sizeof (ulen)))
272 			return (EFAULT);
273 	}
274 	return (0);
275 }
276 
277 /*
278  * Copy from kaddr/klen to uaddr/ulen. Updates ulenp if non-NULL.
279  * If klen is greater than ulen it still uses the non-truncated
280  * klen to update ulenp.
281  */
282 static int
283 copyout_name(void *uaddr, socklen_t ulen, void *ulenp,
284 		void *kaddr, socklen_t klen)
285 {
286 	if (uaddr != NULL) {
287 		if (ulen >= klen)
288 			ulen = klen;
289 		else if (ulen != 0 && xnet_truncate_print) {
290 			printf("sockfs: truncating copyout of address using "
291 			    "XNET semantics for pid = %d. Lengths %d, %d\n",
292 			    curproc->p_pid, klen, ulen);
293 		}
294 
295 		if (ulen != 0) {
296 			if (copyout(kaddr, uaddr, ulen))
297 				return (EFAULT);
298 		} else
299 			klen = 0;
300 	} else
301 		klen = 0;
302 
303 	if (ulenp != NULL) {
304 		if (copyout(&klen, ulenp, sizeof (klen)))
305 			return (EFAULT);
306 	}
307 	return (0);
308 }
309 
310 /*
311  * The socketpair() code in libsocket creates two sockets (using
312  * the /etc/netconfig fallback if needed) before calling this routine
313  * to connect the two sockets together.
314  *
315  * For a SOCK_STREAM socketpair a listener is needed - in that case this
316  * routine will create a new file descriptor as part of accepting the
317  * connection. The library socketpair() will check if svs[2] has changed
318  * in which case it will close the changed fd.
319  *
320  * Note that this code could use the TPI feature of accepting the connection
321  * on the listening endpoint. However, that would require significant changes
322  * to soaccept.
323  */
324 int
325 so_socketpair(int sv[2])
326 {
327 	int svs[2];
328 	struct sonode *so1, *so2;
329 	int error;
330 	struct sockaddr_ux *name;
331 	size_t namelen;
332 	sotpi_info_t *sti1;
333 	sotpi_info_t *sti2;
334 
335 	dprint(1, ("so_socketpair(%p)\n", (void *)sv));
336 
337 	error = useracc(sv, sizeof (svs), B_WRITE);
338 	if (error && do_useracc)
339 		return (set_errno(EFAULT));
340 
341 	if (copyin(sv, svs, sizeof (svs)))
342 		return (set_errno(EFAULT));
343 
344 	if ((so1 = getsonode(svs[0], &error, NULL)) == NULL)
345 		return (set_errno(error));
346 
347 	if ((so2 = getsonode(svs[1], &error, NULL)) == NULL) {
348 		releasef(svs[0]);
349 		return (set_errno(error));
350 	}
351 
352 	if (so1->so_family != AF_UNIX || so2->so_family != AF_UNIX) {
353 		error = EOPNOTSUPP;
354 		goto done;
355 	}
356 
357 	sti1 = SOTOTPI(so1);
358 	sti2 = SOTOTPI(so2);
359 
360 	/*
361 	 * The code below makes assumptions about the "sockfs" implementation.
362 	 * So make sure that the correct implementation is really used.
363 	 */
364 	ASSERT(so1->so_ops == &sotpi_sonodeops);
365 	ASSERT(so2->so_ops == &sotpi_sonodeops);
366 
367 	if (so1->so_type == SOCK_DGRAM) {
368 		/*
369 		 * Bind both sockets and connect them with each other.
370 		 * Need to allocate name/namelen for soconnect.
371 		 */
372 		error = socket_bind(so1, NULL, 0, _SOBIND_UNSPEC, CRED());
373 		if (error) {
374 			eprintsoline(so1, error);
375 			goto done;
376 		}
377 		error = socket_bind(so2, NULL, 0, _SOBIND_UNSPEC, CRED());
378 		if (error) {
379 			eprintsoline(so2, error);
380 			goto done;
381 		}
382 		namelen = sizeof (struct sockaddr_ux);
383 		name = kmem_alloc(namelen, KM_SLEEP);
384 		name->sou_family = AF_UNIX;
385 		name->sou_addr = sti2->sti_ux_laddr;
386 		error = socket_connect(so1,
387 		    (struct sockaddr *)name,
388 		    (socklen_t)namelen,
389 		    0, _SOCONNECT_NOXLATE, CRED());
390 		if (error) {
391 			kmem_free(name, namelen);
392 			eprintsoline(so1, error);
393 			goto done;
394 		}
395 		name->sou_addr = sti1->sti_ux_laddr;
396 		error = socket_connect(so2,
397 		    (struct sockaddr *)name,
398 		    (socklen_t)namelen,
399 		    0, _SOCONNECT_NOXLATE, CRED());
400 		kmem_free(name, namelen);
401 		if (error) {
402 			eprintsoline(so2, error);
403 			goto done;
404 		}
405 		releasef(svs[0]);
406 		releasef(svs[1]);
407 	} else {
408 		/*
409 		 * Bind both sockets, with so1 being a listener.
410 		 * Connect so2 to so1 - nonblocking to avoid waiting for
411 		 * soaccept to complete.
412 		 * Accept a connection on so1. Pass out the new fd as sv[0].
413 		 * The library will detect the changed fd and close
414 		 * the original one.
415 		 */
416 		struct sonode *nso;
417 		struct vnode *nvp;
418 		struct file *nfp;
419 		int nfd;
420 
421 		/*
422 		 * We could simply call socket_listen() here (which would do the
423 		 * binding automatically) if the code didn't rely on passing
424 		 * _SOBIND_NOXLATE to the TPI implementation of socket_bind().
425 		 */
426 		error = socket_bind(so1, NULL, 0, _SOBIND_UNSPEC|
427 		    _SOBIND_NOXLATE|_SOBIND_LISTEN|_SOBIND_SOCKETPAIR,
428 		    CRED());
429 		if (error) {
430 			eprintsoline(so1, error);
431 			goto done;
432 		}
433 		error = socket_bind(so2, NULL, 0, _SOBIND_UNSPEC, CRED());
434 		if (error) {
435 			eprintsoline(so2, error);
436 			goto done;
437 		}
438 
439 		namelen = sizeof (struct sockaddr_ux);
440 		name = kmem_alloc(namelen, KM_SLEEP);
441 		name->sou_family = AF_UNIX;
442 		name->sou_addr = sti1->sti_ux_laddr;
443 		error = socket_connect(so2,
444 		    (struct sockaddr *)name,
445 		    (socklen_t)namelen,
446 		    FNONBLOCK, _SOCONNECT_NOXLATE, CRED());
447 		kmem_free(name, namelen);
448 		if (error) {
449 			if (error != EINPROGRESS) {
450 				eprintsoline(so2, error); goto done;
451 			}
452 		}
453 
454 		error = socket_accept(so1, 0, CRED(), &nso);
455 		if (error) {
456 			eprintsoline(so1, error);
457 			goto done;
458 		}
459 
460 		/* wait for so2 being SS_CONNECTED ignoring signals */
461 		mutex_enter(&so2->so_lock);
462 		error = sowaitconnected(so2, 0, 1);
463 		mutex_exit(&so2->so_lock);
464 		if (error != 0) {
465 			(void) socket_close(nso, 0, CRED());
466 			socket_destroy(nso);
467 			eprintsoline(so2, error);
468 			goto done;
469 		}
470 
471 		nvp = SOTOV(nso);
472 		if (error = falloc(nvp, FWRITE|FREAD, &nfp, &nfd)) {
473 			(void) socket_close(nso, 0, CRED());
474 			socket_destroy(nso);
475 			eprintsoline(nso, error);
476 			goto done;
477 		}
478 		/*
479 		 * fill in the entries that falloc reserved
480 		 */
481 		mutex_exit(&nfp->f_tlock);
482 		setf(nfd, nfp);
483 
484 		releasef(svs[0]);
485 		releasef(svs[1]);
486 		svs[0] = nfd;
487 
488 		/*
489 		 * The socketpair library routine will close the original
490 		 * svs[0] when this code passes out a different file
491 		 * descriptor.
492 		 */
493 		if (copyout(svs, sv, sizeof (svs))) {
494 			(void) closeandsetf(nfd, NULL);
495 			eprintline(EFAULT);
496 			return (set_errno(EFAULT));
497 		}
498 	}
499 	return (0);
500 
501 done:
502 	releasef(svs[0]);
503 	releasef(svs[1]);
504 	return (set_errno(error));
505 }
506 
507 int
508 bind(int sock, struct sockaddr *name, socklen_t namelen, int version)
509 {
510 	struct sonode *so;
511 	int error;
512 
513 	dprint(1, ("bind(%d, %p, %d)\n",
514 	    sock, (void *)name, namelen));
515 
516 	if ((so = getsonode(sock, &error, NULL)) == NULL)
517 		return (set_errno(error));
518 
519 	/* Allocate and copyin name */
520 	/*
521 	 * X/Open test does not expect EFAULT with NULL name and non-zero
522 	 * namelen.
523 	 */
524 	if (name != NULL && namelen != 0) {
525 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
526 		name = copyin_name(so, name, &namelen, &error);
527 		if (name == NULL) {
528 			releasef(sock);
529 			return (set_errno(error));
530 		}
531 	} else {
532 		name = NULL;
533 		namelen = 0;
534 	}
535 
536 	switch (version) {
537 	default:
538 		error = socket_bind(so, name, namelen, 0, CRED());
539 		break;
540 	case SOV_XPG4_2:
541 		error = socket_bind(so, name, namelen, _SOBIND_XPG4_2, CRED());
542 		break;
543 	case SOV_SOCKBSD:
544 		error = socket_bind(so, name, namelen, _SOBIND_SOCKBSD, CRED());
545 		break;
546 	}
547 done:
548 	releasef(sock);
549 	if (name != NULL)
550 		kmem_free(name, (size_t)namelen);
551 
552 	if (error)
553 		return (set_errno(error));
554 	return (0);
555 }
556 
557 /* ARGSUSED2 */
558 int
559 listen(int sock, int backlog, int version)
560 {
561 	struct sonode *so;
562 	int error;
563 
564 	dprint(1, ("listen(%d, %d)\n",
565 	    sock, backlog));
566 
567 	if ((so = getsonode(sock, &error, NULL)) == NULL)
568 		return (set_errno(error));
569 
570 	error = socket_listen(so, backlog, CRED());
571 
572 	releasef(sock);
573 	if (error)
574 		return (set_errno(error));
575 	return (0);
576 }
577 
578 /*ARGSUSED3*/
579 int
580 accept(int sock, struct sockaddr *name, socklen_t *namelenp, int version)
581 {
582 	struct sonode *so;
583 	file_t *fp;
584 	int error;
585 	socklen_t namelen;
586 	struct sonode *nso;
587 	struct vnode *nvp;
588 	struct file *nfp;
589 	int nfd;
590 	struct sockaddr *addrp;
591 	socklen_t addrlen;
592 
593 	dprint(1, ("accept(%d, %p, %p)\n",
594 	    sock, (void *)name, (void *)namelenp));
595 
596 	if ((so = getsonode(sock, &error, &fp)) == NULL)
597 		return (set_errno(error));
598 
599 	if (name != NULL) {
600 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
601 		if (copyin(namelenp, &namelen, sizeof (namelen))) {
602 			releasef(sock);
603 			return (set_errno(EFAULT));
604 		}
605 		if (namelen != 0) {
606 			error = useracc(name, (size_t)namelen, B_WRITE);
607 			if (error && do_useracc) {
608 				releasef(sock);
609 				return (set_errno(EFAULT));
610 			}
611 		} else
612 			name = NULL;
613 	} else {
614 		namelen = 0;
615 	}
616 
617 	/*
618 	 * Allocate the user fd before socket_accept() in order to
619 	 * catch EMFILE errors before calling socket_accept().
620 	 */
621 	if ((nfd = ufalloc(0)) == -1) {
622 		eprintsoline(so, EMFILE);
623 		releasef(sock);
624 		return (set_errno(EMFILE));
625 	}
626 	error = socket_accept(so, fp->f_flag, CRED(), &nso);
627 	releasef(sock);
628 	if (error) {
629 		setf(nfd, NULL);
630 		return (set_errno(error));
631 	}
632 
633 	nvp = SOTOV(nso);
634 
635 	ASSERT(MUTEX_NOT_HELD(&nso->so_lock));
636 	if (namelen != 0) {
637 		addrlen = so->so_max_addr_len;
638 		addrp = (struct sockaddr *)kmem_alloc(addrlen, KM_SLEEP);
639 
640 		if ((error = socket_getpeername(nso, (struct sockaddr *)addrp,
641 		    &addrlen, B_TRUE, CRED())) == 0) {
642 			error = copyout_name(name, namelen, namelenp,
643 			    addrp, addrlen);
644 		} else {
645 			ASSERT(error == EINVAL || error == ENOTCONN);
646 			error = ECONNABORTED;
647 		}
648 		kmem_free(addrp, so->so_max_addr_len);
649 	}
650 
651 	if (error) {
652 		setf(nfd, NULL);
653 		(void) socket_close(nso, 0, CRED());
654 		socket_destroy(nso);
655 		return (set_errno(error));
656 	}
657 	if (error = falloc(NULL, FWRITE|FREAD, &nfp, NULL)) {
658 		setf(nfd, NULL);
659 		(void) socket_close(nso, 0, CRED());
660 		socket_destroy(nso);
661 		eprintsoline(so, error);
662 		return (set_errno(error));
663 	}
664 	/*
665 	 * fill in the entries that falloc reserved
666 	 */
667 	nfp->f_vnode = nvp;
668 	mutex_exit(&nfp->f_tlock);
669 	setf(nfd, nfp);
670 
671 	/*
672 	 * Copy FNDELAY and FNONBLOCK from listener to acceptor
673 	 */
674 	if (so->so_state & (SS_NDELAY|SS_NONBLOCK)) {
675 		uint_t oflag = nfp->f_flag;
676 		int arg = 0;
677 
678 		if (so->so_state & SS_NONBLOCK)
679 			arg |= FNONBLOCK;
680 		else if (so->so_state & SS_NDELAY)
681 			arg |= FNDELAY;
682 
683 		/*
684 		 * This code is a simplification of the F_SETFL code in fcntl()
685 		 * Ignore any errors from VOP_SETFL.
686 		 */
687 		if ((error = VOP_SETFL(nvp, oflag, arg, nfp->f_cred, NULL))
688 		    != 0) {
689 			eprintsoline(so, error);
690 			error = 0;
691 		} else {
692 			mutex_enter(&nfp->f_tlock);
693 			nfp->f_flag &= ~FMASK | (FREAD|FWRITE);
694 			nfp->f_flag |= arg;
695 			mutex_exit(&nfp->f_tlock);
696 		}
697 	}
698 	return (nfd);
699 }
700 
701 int
702 connect(int sock, struct sockaddr *name, socklen_t namelen, int version)
703 {
704 	struct sonode *so;
705 	file_t *fp;
706 	int error;
707 
708 	dprint(1, ("connect(%d, %p, %d)\n",
709 	    sock, (void *)name, namelen));
710 
711 	if ((so = getsonode(sock, &error, &fp)) == NULL)
712 		return (set_errno(error));
713 
714 	/* Allocate and copyin name */
715 	if (namelen != 0) {
716 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
717 		name = copyin_name(so, name, &namelen, &error);
718 		if (name == NULL) {
719 			releasef(sock);
720 			return (set_errno(error));
721 		}
722 	} else
723 		name = NULL;
724 
725 	error = socket_connect(so, name, namelen, fp->f_flag,
726 	    (version != SOV_XPG4_2) ? 0 : _SOCONNECT_XPG4_2, CRED());
727 	releasef(sock);
728 	if (name)
729 		kmem_free(name, (size_t)namelen);
730 	if (error)
731 		return (set_errno(error));
732 	return (0);
733 }
734 
735 /*ARGSUSED2*/
736 int
737 shutdown(int sock, int how, int version)
738 {
739 	struct sonode *so;
740 	int error;
741 
742 	dprint(1, ("shutdown(%d, %d)\n",
743 	    sock, how));
744 
745 	if ((so = getsonode(sock, &error, NULL)) == NULL)
746 		return (set_errno(error));
747 
748 	error = socket_shutdown(so, how, CRED());
749 
750 	releasef(sock);
751 	if (error)
752 		return (set_errno(error));
753 	return (0);
754 }
755 
756 /*
757  * Common receive routine.
758  */
759 static ssize_t
760 recvit(int sock,
761 	struct nmsghdr *msg,
762 	struct uio *uiop,
763 	int flags,
764 	socklen_t *namelenp,
765 	socklen_t *controllenp,
766 	int *flagsp)
767 {
768 	struct sonode *so;
769 	file_t *fp;
770 	void *name;
771 	socklen_t namelen;
772 	void *control;
773 	socklen_t controllen;
774 	ssize_t len;
775 	int error;
776 
777 	if ((so = getsonode(sock, &error, &fp)) == NULL)
778 		return (set_errno(error));
779 
780 	len = uiop->uio_resid;
781 	uiop->uio_fmode = fp->f_flag;
782 	uiop->uio_extflg = UIO_COPY_CACHED;
783 
784 	name = msg->msg_name;
785 	namelen = msg->msg_namelen;
786 	control = msg->msg_control;
787 	controllen = msg->msg_controllen;
788 
789 	msg->msg_flags = flags & (MSG_OOB | MSG_PEEK | MSG_WAITALL |
790 	    MSG_DONTWAIT | MSG_XPG4_2);
791 
792 	error = socket_recvmsg(so, msg, uiop, CRED());
793 	if (error) {
794 		releasef(sock);
795 		return (set_errno(error));
796 	}
797 	lwp_stat_update(LWP_STAT_MSGRCV, 1);
798 	releasef(sock);
799 
800 	error = copyout_name(name, namelen, namelenp,
801 	    msg->msg_name, msg->msg_namelen);
802 	if (error)
803 		goto err;
804 
805 	if (flagsp != NULL) {
806 		/*
807 		 * Clear internal flag.
808 		 */
809 		msg->msg_flags &= ~MSG_XPG4_2;
810 
811 		/*
812 		 * Determine MSG_CTRUNC. sorecvmsg sets MSG_CTRUNC only
813 		 * when controllen is zero and there is control data to
814 		 * copy out.
815 		 */
816 		if (controllen != 0 &&
817 		    (msg->msg_controllen > controllen || control == NULL)) {
818 			dprint(1, ("recvit: CTRUNC %d %d %p\n",
819 			    msg->msg_controllen, controllen, control));
820 
821 			msg->msg_flags |= MSG_CTRUNC;
822 		}
823 		if (copyout(&msg->msg_flags, flagsp,
824 		    sizeof (msg->msg_flags))) {
825 			error = EFAULT;
826 			goto err;
827 		}
828 	}
829 	/*
830 	 * Note: This MUST be done last. There can be no "goto err" after this
831 	 * point since it could make so_closefds run twice on some part
832 	 * of the file descriptor array.
833 	 */
834 	if (controllen != 0) {
835 		if (!(flags & MSG_XPG4_2)) {
836 			/*
837 			 * Good old msg_accrights can only return a multiple
838 			 * of 4 bytes.
839 			 */
840 			controllen &= ~((int)sizeof (uint32_t) - 1);
841 		}
842 		error = copyout_arg(control, controllen, controllenp,
843 		    msg->msg_control, msg->msg_controllen);
844 		if (error)
845 			goto err;
846 
847 		if (msg->msg_controllen > controllen || control == NULL) {
848 			if (control == NULL)
849 				controllen = 0;
850 			so_closefds(msg->msg_control, msg->msg_controllen,
851 			    !(flags & MSG_XPG4_2), controllen);
852 		}
853 	}
854 	if (msg->msg_namelen != 0)
855 		kmem_free(msg->msg_name, (size_t)msg->msg_namelen);
856 	if (msg->msg_controllen != 0)
857 		kmem_free(msg->msg_control, (size_t)msg->msg_controllen);
858 	return (len - uiop->uio_resid);
859 
860 err:
861 	/*
862 	 * If we fail and the control part contains file descriptors
863 	 * we have to close the fd's.
864 	 */
865 	if (msg->msg_controllen != 0)
866 		so_closefds(msg->msg_control, msg->msg_controllen,
867 		    !(flags & MSG_XPG4_2), 0);
868 	if (msg->msg_namelen != 0)
869 		kmem_free(msg->msg_name, (size_t)msg->msg_namelen);
870 	if (msg->msg_controllen != 0)
871 		kmem_free(msg->msg_control, (size_t)msg->msg_controllen);
872 	return (set_errno(error));
873 }
874 
875 /*
876  * Native system call
877  */
878 ssize_t
879 recv(int sock, void *buffer, size_t len, int flags)
880 {
881 	struct nmsghdr lmsg;
882 	struct uio auio;
883 	struct iovec aiov[1];
884 
885 	dprint(1, ("recv(%d, %p, %ld, %d)\n",
886 	    sock, buffer, len, flags));
887 
888 	if ((ssize_t)len < 0) {
889 		return (set_errno(EINVAL));
890 	}
891 
892 	aiov[0].iov_base = buffer;
893 	aiov[0].iov_len = len;
894 	auio.uio_loffset = 0;
895 	auio.uio_iov = aiov;
896 	auio.uio_iovcnt = 1;
897 	auio.uio_resid = len;
898 	auio.uio_segflg = UIO_USERSPACE;
899 	auio.uio_limit = 0;
900 
901 	lmsg.msg_namelen = 0;
902 	lmsg.msg_controllen = 0;
903 	lmsg.msg_flags = 0;
904 	return (recvit(sock, &lmsg, &auio, flags, NULL, NULL, NULL));
905 }
906 
907 ssize_t
908 recvfrom(int sock, void *buffer, size_t len, int flags,
909 	struct sockaddr *name, socklen_t *namelenp)
910 {
911 	struct nmsghdr lmsg;
912 	struct uio auio;
913 	struct iovec aiov[1];
914 
915 	dprint(1, ("recvfrom(%d, %p, %ld, %d, %p, %p)\n",
916 	    sock, buffer, len, flags, (void *)name, (void *)namelenp));
917 
918 	if ((ssize_t)len < 0) {
919 		return (set_errno(EINVAL));
920 	}
921 
922 	aiov[0].iov_base = buffer;
923 	aiov[0].iov_len = len;
924 	auio.uio_loffset = 0;
925 	auio.uio_iov = aiov;
926 	auio.uio_iovcnt = 1;
927 	auio.uio_resid = len;
928 	auio.uio_segflg = UIO_USERSPACE;
929 	auio.uio_limit = 0;
930 
931 	lmsg.msg_name = (char *)name;
932 	if (namelenp != NULL) {
933 		if (copyin(namelenp, &lmsg.msg_namelen,
934 		    sizeof (lmsg.msg_namelen)))
935 			return (set_errno(EFAULT));
936 	} else {
937 		lmsg.msg_namelen = 0;
938 	}
939 	lmsg.msg_controllen = 0;
940 	lmsg.msg_flags = 0;
941 
942 	return (recvit(sock, &lmsg, &auio, flags, namelenp, NULL, NULL));
943 }
944 
945 /*
946  * Uses the MSG_XPG4_2 flag to determine if the caller is using
947  * struct omsghdr or struct nmsghdr.
948  */
949 ssize_t
950 recvmsg(int sock, struct nmsghdr *msg, int flags)
951 {
952 	STRUCT_DECL(nmsghdr, u_lmsg);
953 	STRUCT_HANDLE(nmsghdr, umsgptr);
954 	struct nmsghdr lmsg;
955 	struct uio auio;
956 	struct iovec aiov[MSG_MAXIOVLEN];
957 	int iovcnt;
958 	ssize_t len;
959 	int i;
960 	int *flagsp;
961 	model_t	model;
962 
963 	dprint(1, ("recvmsg(%d, %p, %d)\n",
964 	    sock, (void *)msg, flags));
965 
966 	model = get_udatamodel();
967 	STRUCT_INIT(u_lmsg, model);
968 	STRUCT_SET_HANDLE(umsgptr, model, msg);
969 
970 	if (flags & MSG_XPG4_2) {
971 		if (copyin(msg, STRUCT_BUF(u_lmsg), STRUCT_SIZE(u_lmsg)))
972 			return (set_errno(EFAULT));
973 		flagsp = STRUCT_FADDR(umsgptr, msg_flags);
974 	} else {
975 		/*
976 		 * Assumes that nmsghdr and omsghdr are identically shaped
977 		 * except for the added msg_flags field.
978 		 */
979 		if (copyin(msg, STRUCT_BUF(u_lmsg),
980 		    SIZEOF_STRUCT(omsghdr, model)))
981 			return (set_errno(EFAULT));
982 		STRUCT_FSET(u_lmsg, msg_flags, 0);
983 		flagsp = NULL;
984 	}
985 
986 	/*
987 	 * Code below us will kmem_alloc memory and hang it
988 	 * off msg_control and msg_name fields. This forces
989 	 * us to copy the structure to its native form.
990 	 */
991 	lmsg.msg_name = STRUCT_FGETP(u_lmsg, msg_name);
992 	lmsg.msg_namelen = STRUCT_FGET(u_lmsg, msg_namelen);
993 	lmsg.msg_iov = STRUCT_FGETP(u_lmsg, msg_iov);
994 	lmsg.msg_iovlen = STRUCT_FGET(u_lmsg, msg_iovlen);
995 	lmsg.msg_control = STRUCT_FGETP(u_lmsg, msg_control);
996 	lmsg.msg_controllen = STRUCT_FGET(u_lmsg, msg_controllen);
997 	lmsg.msg_flags = STRUCT_FGET(u_lmsg, msg_flags);
998 
999 	iovcnt = lmsg.msg_iovlen;
1000 
1001 	if (iovcnt <= 0 || iovcnt > MSG_MAXIOVLEN) {
1002 		return (set_errno(EMSGSIZE));
1003 	}
1004 
1005 #ifdef _SYSCALL32_IMPL
1006 	/*
1007 	 * 32-bit callers need to have their iovec expanded, while ensuring
1008 	 * that they can't move more than 2Gbytes of data in a single call.
1009 	 */
1010 	if (model == DATAMODEL_ILP32) {
1011 		struct iovec32 aiov32[MSG_MAXIOVLEN];
1012 		ssize32_t count32;
1013 
1014 		if (copyin((struct iovec32 *)lmsg.msg_iov, aiov32,
1015 		    iovcnt * sizeof (struct iovec32)))
1016 			return (set_errno(EFAULT));
1017 
1018 		count32 = 0;
1019 		for (i = 0; i < iovcnt; i++) {
1020 			ssize32_t iovlen32;
1021 
1022 			iovlen32 = aiov32[i].iov_len;
1023 			count32 += iovlen32;
1024 			if (iovlen32 < 0 || count32 < 0)
1025 				return (set_errno(EINVAL));
1026 			aiov[i].iov_len = iovlen32;
1027 			aiov[i].iov_base =
1028 			    (caddr_t)(uintptr_t)aiov32[i].iov_base;
1029 		}
1030 	} else
1031 #endif /* _SYSCALL32_IMPL */
1032 	if (copyin(lmsg.msg_iov, aiov, iovcnt * sizeof (struct iovec))) {
1033 		return (set_errno(EFAULT));
1034 	}
1035 	len = 0;
1036 	for (i = 0; i < iovcnt; i++) {
1037 		ssize_t iovlen = aiov[i].iov_len;
1038 		len += iovlen;
1039 		if (iovlen < 0 || len < 0) {
1040 			return (set_errno(EINVAL));
1041 		}
1042 	}
1043 	auio.uio_loffset = 0;
1044 	auio.uio_iov = aiov;
1045 	auio.uio_iovcnt = iovcnt;
1046 	auio.uio_resid = len;
1047 	auio.uio_segflg = UIO_USERSPACE;
1048 	auio.uio_limit = 0;
1049 
1050 	if (lmsg.msg_control != NULL &&
1051 	    (do_useracc == 0 ||
1052 	    useracc(lmsg.msg_control, lmsg.msg_controllen,
1053 	    B_WRITE) != 0)) {
1054 		return (set_errno(EFAULT));
1055 	}
1056 
1057 	return (recvit(sock, &lmsg, &auio, flags,
1058 	    STRUCT_FADDR(umsgptr, msg_namelen),
1059 	    STRUCT_FADDR(umsgptr, msg_controllen), flagsp));
1060 }
1061 
1062 /*
1063  * Common send function.
1064  */
1065 static ssize_t
1066 sendit(int sock, struct nmsghdr *msg, struct uio *uiop, int flags)
1067 {
1068 	struct sonode *so;
1069 	file_t *fp;
1070 	void *name;
1071 	socklen_t namelen;
1072 	void *control;
1073 	socklen_t controllen;
1074 	ssize_t len;
1075 	int error;
1076 
1077 	if ((so = getsonode(sock, &error, &fp)) == NULL)
1078 		return (set_errno(error));
1079 
1080 	uiop->uio_fmode = fp->f_flag;
1081 
1082 	if (so->so_family == AF_UNIX)
1083 		uiop->uio_extflg = UIO_COPY_CACHED;
1084 	else
1085 		uiop->uio_extflg = UIO_COPY_DEFAULT;
1086 
1087 	/* Allocate and copyin name and control */
1088 	name = msg->msg_name;
1089 	namelen = msg->msg_namelen;
1090 	if (name != NULL && namelen != 0) {
1091 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1092 		name = copyin_name(so,
1093 		    (struct sockaddr *)name,
1094 		    &namelen, &error);
1095 		if (name == NULL)
1096 			goto done3;
1097 		/* copyin_name null terminates addresses for AF_UNIX */
1098 		msg->msg_namelen = namelen;
1099 		msg->msg_name = name;
1100 	} else {
1101 		msg->msg_name = name = NULL;
1102 		msg->msg_namelen = namelen = 0;
1103 	}
1104 
1105 	control = msg->msg_control;
1106 	controllen = msg->msg_controllen;
1107 	if ((control != NULL) && (controllen != 0)) {
1108 		/*
1109 		 * Verify that the length is not excessive to prevent
1110 		 * an application from consuming all of kernel memory.
1111 		 */
1112 		if (controllen > SO_MAXARGSIZE) {
1113 			error = EINVAL;
1114 			goto done2;
1115 		}
1116 		control = kmem_alloc(controllen, KM_SLEEP);
1117 
1118 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1119 		if (copyin(msg->msg_control, control, controllen)) {
1120 			error = EFAULT;
1121 			goto done1;
1122 		}
1123 		msg->msg_control = control;
1124 	} else {
1125 		msg->msg_control = control = NULL;
1126 		msg->msg_controllen = controllen = 0;
1127 	}
1128 
1129 	len = uiop->uio_resid;
1130 	msg->msg_flags = flags;
1131 
1132 	error = socket_sendmsg(so, msg, uiop, CRED());
1133 done1:
1134 	if (control != NULL)
1135 		kmem_free(control, controllen);
1136 done2:
1137 	if (name != NULL)
1138 		kmem_free(name, namelen);
1139 done3:
1140 	if (error != 0) {
1141 		releasef(sock);
1142 		return (set_errno(error));
1143 	}
1144 	lwp_stat_update(LWP_STAT_MSGSND, 1);
1145 	releasef(sock);
1146 	return (len - uiop->uio_resid);
1147 }
1148 
1149 /*
1150  * Native system call
1151  */
1152 ssize_t
1153 send(int sock, void *buffer, size_t len, int flags)
1154 {
1155 	struct nmsghdr lmsg;
1156 	struct uio auio;
1157 	struct iovec aiov[1];
1158 
1159 	dprint(1, ("send(%d, %p, %ld, %d)\n",
1160 	    sock, buffer, len, flags));
1161 
1162 	if ((ssize_t)len < 0) {
1163 		return (set_errno(EINVAL));
1164 	}
1165 
1166 	aiov[0].iov_base = buffer;
1167 	aiov[0].iov_len = len;
1168 	auio.uio_loffset = 0;
1169 	auio.uio_iov = aiov;
1170 	auio.uio_iovcnt = 1;
1171 	auio.uio_resid = len;
1172 	auio.uio_segflg = UIO_USERSPACE;
1173 	auio.uio_limit = 0;
1174 
1175 	lmsg.msg_name = NULL;
1176 	lmsg.msg_control = NULL;
1177 	if (!(flags & MSG_XPG4_2)) {
1178 		/*
1179 		 * In order to be compatible with the libsocket/sockmod
1180 		 * implementation we set EOR for all send* calls.
1181 		 */
1182 		flags |= MSG_EOR;
1183 	}
1184 	return (sendit(sock, &lmsg, &auio, flags));
1185 }
1186 
1187 /*
1188  * Uses the MSG_XPG4_2 flag to determine if the caller is using
1189  * struct omsghdr or struct nmsghdr.
1190  */
1191 ssize_t
1192 sendmsg(int sock, struct nmsghdr *msg, int flags)
1193 {
1194 	struct nmsghdr lmsg;
1195 	STRUCT_DECL(nmsghdr, u_lmsg);
1196 	struct uio auio;
1197 	struct iovec aiov[MSG_MAXIOVLEN];
1198 	int iovcnt;
1199 	ssize_t len;
1200 	int i;
1201 	model_t	model;
1202 
1203 	dprint(1, ("sendmsg(%d, %p, %d)\n", sock, (void *)msg, flags));
1204 
1205 	model = get_udatamodel();
1206 	STRUCT_INIT(u_lmsg, model);
1207 
1208 	if (flags & MSG_XPG4_2) {
1209 		if (copyin(msg, (char *)STRUCT_BUF(u_lmsg),
1210 		    STRUCT_SIZE(u_lmsg)))
1211 			return (set_errno(EFAULT));
1212 	} else {
1213 		/*
1214 		 * Assumes that nmsghdr and omsghdr are identically shaped
1215 		 * except for the added msg_flags field.
1216 		 */
1217 		if (copyin(msg, (char *)STRUCT_BUF(u_lmsg),
1218 		    SIZEOF_STRUCT(omsghdr, model)))
1219 			return (set_errno(EFAULT));
1220 		/*
1221 		 * In order to be compatible with the libsocket/sockmod
1222 		 * implementation we set EOR for all send* calls.
1223 		 */
1224 		flags |= MSG_EOR;
1225 	}
1226 
1227 	/*
1228 	 * Code below us will kmem_alloc memory and hang it
1229 	 * off msg_control and msg_name fields. This forces
1230 	 * us to copy the structure to its native form.
1231 	 */
1232 	lmsg.msg_name = STRUCT_FGETP(u_lmsg, msg_name);
1233 	lmsg.msg_namelen = STRUCT_FGET(u_lmsg, msg_namelen);
1234 	lmsg.msg_iov = STRUCT_FGETP(u_lmsg, msg_iov);
1235 	lmsg.msg_iovlen = STRUCT_FGET(u_lmsg, msg_iovlen);
1236 	lmsg.msg_control = STRUCT_FGETP(u_lmsg, msg_control);
1237 	lmsg.msg_controllen = STRUCT_FGET(u_lmsg, msg_controllen);
1238 	lmsg.msg_flags = STRUCT_FGET(u_lmsg, msg_flags);
1239 
1240 	iovcnt = lmsg.msg_iovlen;
1241 
1242 	if (iovcnt <= 0 || iovcnt > MSG_MAXIOVLEN) {
1243 		/*
1244 		 * Unless this is XPG 4.2 we allow iovcnt == 0 to
1245 		 * be compatible with SunOS 4.X and 4.4BSD.
1246 		 */
1247 		if (iovcnt != 0 || (flags & MSG_XPG4_2))
1248 			return (set_errno(EMSGSIZE));
1249 	}
1250 
1251 #ifdef _SYSCALL32_IMPL
1252 	/*
1253 	 * 32-bit callers need to have their iovec expanded, while ensuring
1254 	 * that they can't move more than 2Gbytes of data in a single call.
1255 	 */
1256 	if (model == DATAMODEL_ILP32) {
1257 		struct iovec32 aiov32[MSG_MAXIOVLEN];
1258 		ssize32_t count32;
1259 
1260 		if (iovcnt != 0 &&
1261 		    copyin((struct iovec32 *)lmsg.msg_iov, aiov32,
1262 		    iovcnt * sizeof (struct iovec32)))
1263 			return (set_errno(EFAULT));
1264 
1265 		count32 = 0;
1266 		for (i = 0; i < iovcnt; i++) {
1267 			ssize32_t iovlen32;
1268 
1269 			iovlen32 = aiov32[i].iov_len;
1270 			count32 += iovlen32;
1271 			if (iovlen32 < 0 || count32 < 0)
1272 				return (set_errno(EINVAL));
1273 			aiov[i].iov_len = iovlen32;
1274 			aiov[i].iov_base =
1275 			    (caddr_t)(uintptr_t)aiov32[i].iov_base;
1276 		}
1277 	} else
1278 #endif /* _SYSCALL32_IMPL */
1279 	if (iovcnt != 0 &&
1280 	    copyin(lmsg.msg_iov, aiov,
1281 	    (unsigned)iovcnt * sizeof (struct iovec))) {
1282 		return (set_errno(EFAULT));
1283 	}
1284 	len = 0;
1285 	for (i = 0; i < iovcnt; i++) {
1286 		ssize_t iovlen = aiov[i].iov_len;
1287 		len += iovlen;
1288 		if (iovlen < 0 || len < 0) {
1289 			return (set_errno(EINVAL));
1290 		}
1291 	}
1292 	auio.uio_loffset = 0;
1293 	auio.uio_iov = aiov;
1294 	auio.uio_iovcnt = iovcnt;
1295 	auio.uio_resid = len;
1296 	auio.uio_segflg = UIO_USERSPACE;
1297 	auio.uio_limit = 0;
1298 
1299 	return (sendit(sock, &lmsg, &auio, flags));
1300 }
1301 
1302 ssize_t
1303 sendto(int sock, void *buffer, size_t len, int flags,
1304     struct sockaddr *name, socklen_t namelen)
1305 {
1306 	struct nmsghdr lmsg;
1307 	struct uio auio;
1308 	struct iovec aiov[1];
1309 
1310 	dprint(1, ("sendto(%d, %p, %ld, %d, %p, %d)\n",
1311 	    sock, buffer, len, flags, (void *)name, namelen));
1312 
1313 	if ((ssize_t)len < 0) {
1314 		return (set_errno(EINVAL));
1315 	}
1316 
1317 	aiov[0].iov_base = buffer;
1318 	aiov[0].iov_len = len;
1319 	auio.uio_loffset = 0;
1320 	auio.uio_iov = aiov;
1321 	auio.uio_iovcnt = 1;
1322 	auio.uio_resid = len;
1323 	auio.uio_segflg = UIO_USERSPACE;
1324 	auio.uio_limit = 0;
1325 
1326 	lmsg.msg_name = (char *)name;
1327 	lmsg.msg_namelen = namelen;
1328 	lmsg.msg_control = NULL;
1329 	if (!(flags & MSG_XPG4_2)) {
1330 		/*
1331 		 * In order to be compatible with the libsocket/sockmod
1332 		 * implementation we set EOR for all send* calls.
1333 		 */
1334 		flags |= MSG_EOR;
1335 	}
1336 	return (sendit(sock, &lmsg, &auio, flags));
1337 }
1338 
1339 /*ARGSUSED3*/
1340 int
1341 getpeername(int sock, struct sockaddr *name, socklen_t *namelenp, int version)
1342 {
1343 	struct sonode *so;
1344 	int error;
1345 	socklen_t namelen;
1346 	socklen_t sock_addrlen;
1347 	struct sockaddr *sock_addrp;
1348 
1349 	dprint(1, ("getpeername(%d, %p, %p)\n",
1350 	    sock, (void *)name, (void *)namelenp));
1351 
1352 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1353 		goto bad;
1354 
1355 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1356 	if (copyin(namelenp, &namelen, sizeof (namelen)) ||
1357 	    (name == NULL && namelen != 0)) {
1358 		error = EFAULT;
1359 		goto rel_out;
1360 	}
1361 	sock_addrlen = so->so_max_addr_len;
1362 	sock_addrp = (struct sockaddr *)kmem_alloc(sock_addrlen, KM_SLEEP);
1363 
1364 	if ((error = socket_getpeername(so, sock_addrp, &sock_addrlen,
1365 	    B_FALSE, CRED())) == 0) {
1366 		ASSERT(sock_addrlen <= so->so_max_addr_len);
1367 		error = copyout_name(name, namelen, namelenp,
1368 		    (void *)sock_addrp, sock_addrlen);
1369 	}
1370 	kmem_free(sock_addrp, so->so_max_addr_len);
1371 rel_out:
1372 	releasef(sock);
1373 bad:	return (error != 0 ? set_errno(error) : 0);
1374 }
1375 
1376 /*ARGSUSED3*/
1377 int
1378 getsockname(int sock, struct sockaddr *name,
1379 		socklen_t *namelenp, int version)
1380 {
1381 	struct sonode *so;
1382 	int error;
1383 	socklen_t namelen, sock_addrlen;
1384 	struct sockaddr *sock_addrp;
1385 
1386 	dprint(1, ("getsockname(%d, %p, %p)\n",
1387 	    sock, (void *)name, (void *)namelenp));
1388 
1389 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1390 		goto bad;
1391 
1392 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1393 	if (copyin(namelenp, &namelen, sizeof (namelen)) ||
1394 	    (name == NULL && namelen != 0)) {
1395 		error = EFAULT;
1396 		goto rel_out;
1397 	}
1398 
1399 	sock_addrlen = so->so_max_addr_len;
1400 	sock_addrp = (struct sockaddr *)kmem_alloc(sock_addrlen, KM_SLEEP);
1401 	if ((error = socket_getsockname(so, sock_addrp, &sock_addrlen,
1402 	    CRED())) == 0) {
1403 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1404 		ASSERT(sock_addrlen <= so->so_max_addr_len);
1405 		error = copyout_name(name, namelen, namelenp,
1406 		    (void *)sock_addrp, sock_addrlen);
1407 	}
1408 	kmem_free(sock_addrp, so->so_max_addr_len);
1409 rel_out:
1410 	releasef(sock);
1411 bad:	return (error != 0 ? set_errno(error) : 0);
1412 }
1413 
1414 /*ARGSUSED5*/
1415 int
1416 getsockopt(int sock,
1417 	int level,
1418 	int option_name,
1419 	void *option_value,
1420 	socklen_t *option_lenp,
1421 	int version)
1422 {
1423 	struct sonode *so;
1424 	socklen_t optlen, optlen_res;
1425 	void *optval;
1426 	int error;
1427 
1428 	dprint(1, ("getsockopt(%d, %d, %d, %p, %p)\n",
1429 	    sock, level, option_name, option_value, (void *)option_lenp));
1430 
1431 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1432 		return (set_errno(error));
1433 
1434 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1435 	if (copyin(option_lenp, &optlen, sizeof (optlen))) {
1436 		releasef(sock);
1437 		return (set_errno(EFAULT));
1438 	}
1439 	/*
1440 	 * Verify that the length is not excessive to prevent
1441 	 * an application from consuming all of kernel memory.
1442 	 */
1443 	if (optlen > SO_MAXARGSIZE) {
1444 		error = EINVAL;
1445 		releasef(sock);
1446 		return (set_errno(error));
1447 	}
1448 	optval = kmem_alloc(optlen, KM_SLEEP);
1449 	optlen_res = optlen;
1450 	error = socket_getsockopt(so, level, option_name, optval,
1451 	    &optlen_res, (version != SOV_XPG4_2) ? 0 : _SOGETSOCKOPT_XPG4_2,
1452 	    CRED());
1453 	releasef(sock);
1454 	if (error) {
1455 		kmem_free(optval, optlen);
1456 		return (set_errno(error));
1457 	}
1458 	error = copyout_arg(option_value, optlen, option_lenp,
1459 	    optval, optlen_res);
1460 	kmem_free(optval, optlen);
1461 	if (error)
1462 		return (set_errno(error));
1463 	return (0);
1464 }
1465 
1466 /*ARGSUSED5*/
1467 int
1468 setsockopt(int sock,
1469 	int level,
1470 	int option_name,
1471 	void *option_value,
1472 	socklen_t option_len,
1473 	int version)
1474 {
1475 	struct sonode *so;
1476 	intptr_t buffer[2];
1477 	void *optval = NULL;
1478 	int error;
1479 
1480 	dprint(1, ("setsockopt(%d, %d, %d, %p, %d)\n",
1481 	    sock, level, option_name, option_value, option_len));
1482 
1483 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1484 		return (set_errno(error));
1485 
1486 	if (option_value != NULL) {
1487 		if (option_len != 0) {
1488 			/*
1489 			 * Verify that the length is not excessive to prevent
1490 			 * an application from consuming all of kernel memory.
1491 			 */
1492 			if (option_len > SO_MAXARGSIZE) {
1493 				error = EINVAL;
1494 				goto done2;
1495 			}
1496 			optval = option_len <= sizeof (buffer) ?
1497 			    &buffer : kmem_alloc((size_t)option_len, KM_SLEEP);
1498 			ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1499 			if (copyin(option_value, optval, (size_t)option_len)) {
1500 				error = EFAULT;
1501 				goto done1;
1502 			}
1503 		}
1504 	} else
1505 		option_len = 0;
1506 
1507 	error = socket_setsockopt(so, level, option_name, optval,
1508 	    (t_uscalar_t)option_len, CRED());
1509 done1:
1510 	if (optval != buffer)
1511 		kmem_free(optval, (size_t)option_len);
1512 done2:
1513 	releasef(sock);
1514 	if (error)
1515 		return (set_errno(error));
1516 	return (0);
1517 }
1518 
1519 /*
1520  * Add config info when name is non-NULL; delete info when name is NULL.
1521  * name could be a device name or a module name and are user address.
1522  */
1523 int
1524 sockconfig(int family, int type, int protocol, char *name)
1525 {
1526 	char *kdevpath = NULL;		/* Copied in devpath string */
1527 	char *kmodule = NULL;
1528 	size_t pathlen = 0;
1529 	int error = 0;
1530 
1531 	dprint(1, ("sockconfig(%d, %d, %d, %p)\n",
1532 	    family, type, protocol, (void *)name));
1533 
1534 	if (secpolicy_net_config(CRED(), B_FALSE) != 0)
1535 		return (set_errno(EPERM));
1536 
1537 	/*
1538 	 * By default set the kdevpath and kmodule to NULL to delete an entry.
1539 	 * Otherwise when name is not NULL, set the kdevpath or kmodule
1540 	 * value to add an entry.
1541 	 */
1542 	if (name != NULL) {
1543 		/*
1544 		 * Adding an entry.
1545 		 * Copyin the name.
1546 		 * This also makes it possible to check for too long pathnames.
1547 		 * Compress the space needed for the name before passing it
1548 		 * to soconfig - soconfig will store the string until
1549 		 * the configuration is removed.
1550 		 */
1551 		char *buf;
1552 		buf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1553 		if ((error = copyinstr(name, buf, MAXPATHLEN, &pathlen)) != 0) {
1554 			kmem_free(buf, MAXPATHLEN);
1555 			goto done;
1556 		}
1557 		if (strncmp(buf, "/dev", strlen("/dev")) == 0) {
1558 			/* For device */
1559 
1560 			/*
1561 			 * Special handling for NCA:
1562 			 *
1563 			 * DEV_NCA is never opened even if an application
1564 			 * requests for AF_NCA. The device opened is instead a
1565 			 * predefined AF_INET transport (NCA_INET_DEV).
1566 			 *
1567 			 * Prior to Volo (PSARC/2007/587) NCA would determine
1568 			 * the device using a lookup, which worked then because
1569 			 * all protocols were based on TPI. Since TPI is no
1570 			 * longer the default, we have to explicitly state
1571 			 * which device to use.
1572 			 */
1573 			if (strcmp(buf, NCA_DEV) == 0) {
1574 				/* only support entry <28, 2, 0> */
1575 				if (family != AF_NCA || type != SOCK_STREAM ||
1576 				    protocol != 0) {
1577 					kmem_free(buf, MAXPATHLEN);
1578 					error = EINVAL;
1579 					goto done;
1580 				}
1581 
1582 				pathlen = strlen(NCA_INET_DEV) + 1;
1583 				kdevpath = kmem_alloc(pathlen, KM_SLEEP);
1584 				bcopy(NCA_INET_DEV, kdevpath, pathlen);
1585 				kdevpath[pathlen - 1] = '\0';
1586 			} else {
1587 				kdevpath = kmem_alloc(pathlen, KM_SLEEP);
1588 				bcopy(buf, kdevpath, pathlen);
1589 				kdevpath[pathlen - 1] = '\0';
1590 			}
1591 		} else {
1592 			/* For socket module */
1593 			kmodule = kmem_alloc(pathlen, KM_SLEEP);
1594 			bcopy(buf, kmodule, pathlen);
1595 			kmodule[pathlen - 1] = '\0';
1596 
1597 			pathlen = 0;
1598 			if (strcmp(kmodule, "tcp") == 0) {
1599 				/* Get the tcp device name for fallback */
1600 				if (family == 2) {
1601 					pathlen = strlen("/dev/tcp") + 1;
1602 					kdevpath = kmem_alloc(pathlen,
1603 					    KM_SLEEP);
1604 					bcopy("/dev/tcp", kdevpath,
1605 					    pathlen);
1606 					kdevpath[pathlen - 1] = '\0';
1607 				} else {
1608 					ASSERT(family == 26);
1609 					pathlen = strlen("/dev/tcp6") + 1;
1610 					kdevpath = kmem_alloc(pathlen,
1611 					    KM_SLEEP);
1612 					bcopy("/dev/tcp6", kdevpath, pathlen);
1613 					kdevpath[pathlen - 1] = '\0';
1614 				}
1615 			} else if (strcmp(kmodule, "udp") == 0) {
1616 				/* Get the udp device name for fallback */
1617 				if (family == 2) {
1618 					pathlen = strlen("/dev/udp") + 1;
1619 					kdevpath = kmem_alloc(pathlen,
1620 					    KM_SLEEP);
1621 					bcopy("/dev/udp", kdevpath, pathlen);
1622 					kdevpath[pathlen - 1] = '\0';
1623 				} else {
1624 					ASSERT(family == 26);
1625 					pathlen = strlen("/dev/udp6") + 1;
1626 					kdevpath = kmem_alloc(pathlen,
1627 					    KM_SLEEP);
1628 					bcopy("/dev/udp6", kdevpath, pathlen);
1629 					kdevpath[pathlen - 1] = '\0';
1630 				}
1631 			} else if (strcmp(kmodule, "icmp") == 0) {
1632 				/* Get the icmp device name for fallback */
1633 				if (family == 2) {
1634 					pathlen = strlen("/dev/rawip") + 1;
1635 					kdevpath = kmem_alloc(pathlen,
1636 					    KM_SLEEP);
1637 					bcopy("/dev/rawip", kdevpath, pathlen);
1638 					kdevpath[pathlen - 1] = '\0';
1639 				} else {
1640 					ASSERT(family == 26);
1641 					pathlen = strlen("/dev/rawip6") + 1;
1642 					kdevpath = kmem_alloc(pathlen,
1643 					    KM_SLEEP);
1644 					bcopy("/dev/rawip6", kdevpath, pathlen);
1645 					kdevpath[pathlen - 1] = '\0';
1646 				}
1647 			}
1648 		}
1649 
1650 		kmem_free(buf, MAXPATHLEN);
1651 	}
1652 	error = soconfig(family, type, protocol, kdevpath, (int)pathlen,
1653 	    kmodule);
1654 done:
1655 	if (error) {
1656 		eprintline(error);
1657 		return (set_errno(error));
1658 	}
1659 	return (0);
1660 }
1661 
1662 
1663 /*
1664  * Sendfile is implemented through two schemes, direct I/O or by
1665  * caching in the filesystem page cache. We cache the input file by
1666  * default and use direct I/O only if sendfile_max_size is set
1667  * appropriately as explained below. Note that this logic is consistent
1668  * with other filesystems where caching is turned on by default
1669  * unless explicitly turned off by using the DIRECTIO ioctl.
1670  *
1671  * We choose a slightly different scheme here. One can turn off
1672  * caching by setting sendfile_max_size to 0. One can also enable
1673  * caching of files <= sendfile_max_size by setting sendfile_max_size
1674  * to an appropriate value. By default sendfile_max_size is set to the
1675  * maximum value so that all files are cached. In future, we may provide
1676  * better interfaces for caching the file.
1677  *
1678  * Sendfile through Direct I/O (Zero copy)
1679  * --------------------------------------
1680  *
1681  * As disks are normally slower than the network, we can't have a
1682  * single thread that reads the disk and writes to the network. We
1683  * need to have parallelism. This is done by having the sendfile
1684  * thread create another thread that reads from the filesystem
1685  * and queues it for network processing. In this scheme, the data
1686  * is never copied anywhere i.e it is zero copy unlike the other
1687  * scheme.
1688  *
1689  * We have a sendfile queue (snfq) where each sendfile
1690  * request (snf_req_t) is queued for processing by a thread. Number
1691  * of threads is dynamically allocated and they exit if they are idling
1692  * beyond a specified amount of time. When each request (snf_req_t) is
1693  * processed by a thread, it produces a number of mblk_t structures to
1694  * be consumed by the sendfile thread. snf_deque and snf_enque are
1695  * used for consuming and producing mblks. Size of the filesystem
1696  * read is determined by the tunable (sendfile_read_size). A single
1697  * mblk holds sendfile_read_size worth of data (except the last
1698  * read of the file) which is sent down as a whole to the network.
1699  * sendfile_read_size is set to 1 MB as this seems to be the optimal
1700  * value for the UFS filesystem backed by a striped storage array.
1701  *
1702  * Synchronisation between read (producer) and write (consumer) threads.
1703  * --------------------------------------------------------------------
1704  *
1705  * sr_lock protects sr_ib_head and sr_ib_tail. The lock is held while
1706  * adding and deleting items in this list. Error can happen anytime
1707  * during read or write. There could be unprocessed mblks in the
1708  * sr_ib_XXX list when a read or write error occurs. Whenever error
1709  * is encountered, we need two things to happen :
1710  *
1711  * a) One of the threads need to clean the mblks.
1712  * b) When one thread encounters an error, the other should stop.
1713  *
1714  * For (a), we don't want to penalize the reader thread as it could do
1715  * some useful work processing other requests. For (b), the error can
1716  * be detected by examining sr_read_error or sr_write_error.
1717  * sr_lock protects sr_read_error and sr_write_error. If both reader and
1718  * writer encounters error, we need to report the write error back to
1719  * the application as that's what would have happened if the operations
1720  * were done sequentially. With this in mind, following should work :
1721  *
1722  * 	- Check for errors before read or write.
1723  *	- If the reader encounters error, set the error in sr_read_error.
1724  *	  Check sr_write_error, if it is set, send cv_signal as it is
1725  *	  waiting for reader to complete. If it is not set, the writer
1726  *	  is either running sinking data to the network or blocked
1727  *        because of flow control. For handling the latter case, we
1728  *	  always send a signal. In any case, it will examine sr_read_error
1729  *	  and return. sr_read_error is marked with SR_READ_DONE to tell
1730  *	  the writer that the reader is done in all the cases.
1731  *	- If the writer encounters error, set the error in sr_write_error.
1732  *	  The reader thread is either blocked because of flow control or
1733  *	  running reading data from the disk. For the former, we need to
1734  *	  wakeup the thread. Again to keep it simple, we always wake up
1735  *	  the reader thread. Then, wait for the read thread to complete
1736  *	  if it is not done yet. Cleanup and return.
1737  *
1738  * High and low water marks for the read thread.
1739  * --------------------------------------------
1740  *
1741  * If sendfile() is used to send data over a slow network, we need to
1742  * make sure that the read thread does not produce data at a faster
1743  * rate than the network. This can happen if the disk is faster than
1744  * the network. In such a case, we don't want to build a very large queue.
1745  * But we would still like to get all of the network throughput possible.
1746  * This implies that network should never block waiting for data.
1747  * As there are lot of disk throughput/network throughput combinations
1748  * possible, it is difficult to come up with an accurate number.
1749  * A typical 10K RPM disk has a max seek latency 17ms and rotational
1750  * latency of 3ms for reading a disk block. Thus, the total latency to
1751  * initiate a new read, transfer data from the disk and queue for
1752  * transmission would take about a max of 25ms. Todays max transfer rate
1753  * for network is 100MB/sec. If the thread is blocked because of flow
1754  * control, it would take 25ms to get new data ready for transmission.
1755  * We have to make sure that network is not idling, while we are initiating
1756  * new transfers. So, at 100MB/sec, to keep network busy we would need
1757  * 2.5MB of data. Rounding off, we keep the low water mark to be 3MB of data.
1758  * We need to pick a high water mark so that the woken up thread would
1759  * do considerable work before blocking again to prevent thrashing. Currently,
1760  * we pick this to be 10 times that of the low water mark.
1761  *
1762  * Sendfile with segmap caching (One copy from page cache to mblks).
1763  * ----------------------------------------------------------------
1764  *
1765  * We use the segmap cache for caching the file, if the size of file
1766  * is <= sendfile_max_size. In this case we don't use threads as VM
1767  * is reasonably fast enough to keep up with the network. If the underlying
1768  * transport allows, we call segmap_getmapflt() to map MAXBSIZE (8K) worth
1769  * of data into segmap space, and use the virtual address from segmap
1770  * directly through desballoc() to avoid copy. Once the transport is done
1771  * with the data, the mapping will be released through segmap_release()
1772  * called by the call-back routine.
1773  *
1774  * If zero-copy is not allowed by the transport, we simply call VOP_READ()
1775  * to copy the data from the filesystem into our temporary network buffer.
1776  *
1777  * To disable caching, set sendfile_max_size to 0.
1778  */
1779 
1780 uint_t sendfile_read_size = 1024 * 1024;
1781 #define	SENDFILE_REQ_LOWAT	3 * 1024 * 1024
1782 uint_t sendfile_req_lowat = SENDFILE_REQ_LOWAT;
1783 uint_t sendfile_req_hiwat = 10 * SENDFILE_REQ_LOWAT;
1784 struct sendfile_stats sf_stats;
1785 struct sendfile_queue *snfq;
1786 clock_t snfq_timeout;
1787 off64_t sendfile_max_size;
1788 
1789 static void snf_enque(snf_req_t *, mblk_t *);
1790 static mblk_t *snf_deque(snf_req_t *);
1791 
1792 void
1793 sendfile_init(void)
1794 {
1795 	snfq = kmem_zalloc(sizeof (struct sendfile_queue), KM_SLEEP);
1796 
1797 	mutex_init(&snfq->snfq_lock, NULL, MUTEX_DEFAULT, NULL);
1798 	cv_init(&snfq->snfq_cv, NULL, CV_DEFAULT, NULL);
1799 	snfq->snfq_max_threads = max_ncpus;
1800 	snfq_timeout = SNFQ_TIMEOUT;
1801 	/* Cache all files by default. */
1802 	sendfile_max_size = MAXOFFSET_T;
1803 }
1804 
1805 /*
1806  * Queues a mblk_t for network processing.
1807  */
1808 static void
1809 snf_enque(snf_req_t *sr, mblk_t *mp)
1810 {
1811 	mp->b_next = NULL;
1812 	mutex_enter(&sr->sr_lock);
1813 	if (sr->sr_mp_head == NULL) {
1814 		sr->sr_mp_head = sr->sr_mp_tail = mp;
1815 		cv_signal(&sr->sr_cv);
1816 	} else {
1817 		sr->sr_mp_tail->b_next = mp;
1818 		sr->sr_mp_tail = mp;
1819 	}
1820 	sr->sr_qlen += MBLKL(mp);
1821 	while ((sr->sr_qlen > sr->sr_hiwat) &&
1822 	    (sr->sr_write_error == 0)) {
1823 		sf_stats.ss_full_waits++;
1824 		cv_wait(&sr->sr_cv, &sr->sr_lock);
1825 	}
1826 	mutex_exit(&sr->sr_lock);
1827 }
1828 
1829 /*
1830  * De-queues a mblk_t for network processing.
1831  */
1832 static mblk_t *
1833 snf_deque(snf_req_t *sr)
1834 {
1835 	mblk_t *mp;
1836 
1837 	mutex_enter(&sr->sr_lock);
1838 	/*
1839 	 * If we have encountered an error on read or read is
1840 	 * completed and no more mblks, return NULL.
1841 	 * We need to check for NULL sr_mp_head also as
1842 	 * the reads could have completed and there is
1843 	 * nothing more to come.
1844 	 */
1845 	if (((sr->sr_read_error & ~SR_READ_DONE) != 0) ||
1846 	    ((sr->sr_read_error & SR_READ_DONE) &&
1847 	    sr->sr_mp_head == NULL)) {
1848 		mutex_exit(&sr->sr_lock);
1849 		return (NULL);
1850 	}
1851 	/*
1852 	 * To start with neither SR_READ_DONE is marked nor
1853 	 * the error is set. When we wake up from cv_wait,
1854 	 * following are the possibilities :
1855 	 *
1856 	 *	a) sr_read_error is zero and mblks are queued.
1857 	 *	b) sr_read_error is set to SR_READ_DONE
1858 	 *	   and mblks are queued.
1859 	 *	c) sr_read_error is set to SR_READ_DONE
1860 	 *	   and no mblks.
1861 	 *	d) sr_read_error is set to some error other
1862 	 *	   than SR_READ_DONE.
1863 	 */
1864 
1865 	while ((sr->sr_read_error == 0) && (sr->sr_mp_head == NULL)) {
1866 		sf_stats.ss_empty_waits++;
1867 		cv_wait(&sr->sr_cv, &sr->sr_lock);
1868 	}
1869 	/* Handle (a) and (b) first  - the normal case. */
1870 	if (((sr->sr_read_error & ~SR_READ_DONE) == 0) &&
1871 	    (sr->sr_mp_head != NULL)) {
1872 		mp = sr->sr_mp_head;
1873 		sr->sr_mp_head = mp->b_next;
1874 		sr->sr_qlen -= MBLKL(mp);
1875 		if (sr->sr_qlen < sr->sr_lowat)
1876 			cv_signal(&sr->sr_cv);
1877 		mutex_exit(&sr->sr_lock);
1878 		mp->b_next = NULL;
1879 		return (mp);
1880 	}
1881 	/* Handle (c) and (d). */
1882 	mutex_exit(&sr->sr_lock);
1883 	return (NULL);
1884 }
1885 
1886 /*
1887  * Reads data from the filesystem and queues it for network processing.
1888  */
1889 void
1890 snf_async_read(snf_req_t *sr)
1891 {
1892 	size_t iosize;
1893 	u_offset_t fileoff;
1894 	u_offset_t size;
1895 	int ret_size;
1896 	int error;
1897 	file_t *fp;
1898 	mblk_t *mp;
1899 	struct vnode *vp;
1900 	int extra = 0;
1901 	int maxblk = 0;
1902 	int wroff = 0;
1903 	struct sonode *so;
1904 
1905 	fp = sr->sr_fp;
1906 	size = sr->sr_file_size;
1907 	fileoff = sr->sr_file_off;
1908 
1909 	/*
1910 	 * Ignore the error for filesystems that doesn't support DIRECTIO.
1911 	 */
1912 	(void) VOP_IOCTL(fp->f_vnode, _FIODIRECTIO, DIRECTIO_ON, 0,
1913 	    kcred, NULL, NULL);
1914 
1915 	vp = sr->sr_vp;
1916 	if (vp->v_type == VSOCK) {
1917 		stdata_t *stp;
1918 
1919 		/*
1920 		 * Get the extra space to insert a header and a trailer.
1921 		 */
1922 		so = VTOSO(vp);
1923 		stp = vp->v_stream;
1924 		if (stp == NULL) {
1925 			wroff = so->so_proto_props.sopp_wroff;
1926 			maxblk = so->so_proto_props.sopp_maxblk;
1927 			extra = wroff + so->so_proto_props.sopp_tail;
1928 		} else {
1929 			wroff = (int)(stp->sd_wroff);
1930 			maxblk = (int)(stp->sd_maxblk);
1931 			extra = wroff + (int)(stp->sd_tail);
1932 		}
1933 	}
1934 
1935 	while ((size != 0) && (sr->sr_write_error == 0)) {
1936 
1937 		iosize = (int)MIN(sr->sr_maxpsz, size);
1938 
1939 		/*
1940 		 * For sockets acting as an SSL proxy, we
1941 		 * need to adjust the size to the maximum
1942 		 * SSL record size set in the stream head.
1943 		 */
1944 		if (vp->v_type == VSOCK && !SOCK_IS_NONSTR(so) &&
1945 		    SOTOTPI(so)->sti_kssl_ctx != NULL)
1946 			iosize = (int)MIN(iosize, maxblk);
1947 
1948 		if ((mp = allocb(iosize + extra, BPRI_MED)) == NULL) {
1949 			error = EAGAIN;
1950 			break;
1951 		}
1952 
1953 		mp->b_rptr += wroff;
1954 
1955 		ret_size = soreadfile(fp, mp->b_rptr, fileoff, &error, iosize);
1956 
1957 		/* Error or Reached EOF ? */
1958 		if ((error != 0) || (ret_size == 0)) {
1959 			freeb(mp);
1960 			break;
1961 		}
1962 		mp->b_wptr = mp->b_rptr + ret_size;
1963 
1964 		snf_enque(sr, mp);
1965 		size -= ret_size;
1966 		fileoff += ret_size;
1967 	}
1968 	(void) VOP_IOCTL(fp->f_vnode, _FIODIRECTIO, DIRECTIO_OFF, 0,
1969 	    kcred, NULL, NULL);
1970 	mutex_enter(&sr->sr_lock);
1971 	sr->sr_read_error = error;
1972 	sr->sr_read_error |= SR_READ_DONE;
1973 	cv_signal(&sr->sr_cv);
1974 	mutex_exit(&sr->sr_lock);
1975 }
1976 
1977 void
1978 snf_async_thread(void)
1979 {
1980 	snf_req_t *sr;
1981 	callb_cpr_t cprinfo;
1982 	clock_t time_left = 1;
1983 	clock_t now;
1984 
1985 	CALLB_CPR_INIT(&cprinfo, &snfq->snfq_lock, callb_generic_cpr, "snfq");
1986 
1987 	mutex_enter(&snfq->snfq_lock);
1988 	for (;;) {
1989 		/*
1990 		 * If we didn't find a entry, then block until woken up
1991 		 * again and then look through the queues again.
1992 		 */
1993 		while ((sr = snfq->snfq_req_head) == NULL) {
1994 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
1995 			if (time_left <= 0) {
1996 				snfq->snfq_svc_threads--;
1997 				CALLB_CPR_EXIT(&cprinfo);
1998 				thread_exit();
1999 				/* NOTREACHED */
2000 			}
2001 			snfq->snfq_idle_cnt++;
2002 
2003 			time_to_wait(&now, snfq_timeout);
2004 			time_left = cv_timedwait(&snfq->snfq_cv,
2005 			    &snfq->snfq_lock, now);
2006 			snfq->snfq_idle_cnt--;
2007 
2008 			CALLB_CPR_SAFE_END(&cprinfo, &snfq->snfq_lock);
2009 		}
2010 		snfq->snfq_req_head = sr->sr_next;
2011 		snfq->snfq_req_cnt--;
2012 		mutex_exit(&snfq->snfq_lock);
2013 		snf_async_read(sr);
2014 		mutex_enter(&snfq->snfq_lock);
2015 	}
2016 }
2017 
2018 
2019 snf_req_t *
2020 create_thread(int operation, struct vnode *vp, file_t *fp,
2021     u_offset_t fileoff, u_offset_t size)
2022 {
2023 	snf_req_t *sr;
2024 	stdata_t *stp;
2025 
2026 	sr = (snf_req_t *)kmem_zalloc(sizeof (snf_req_t), KM_SLEEP);
2027 
2028 	sr->sr_vp = vp;
2029 	sr->sr_fp = fp;
2030 	stp = vp->v_stream;
2031 
2032 	/*
2033 	 * store sd_qn_maxpsz into sr_maxpsz while we have stream head.
2034 	 * stream might be closed before thread returns from snf_async_read.
2035 	 */
2036 	if (stp != NULL && stp->sd_qn_maxpsz > 0) {
2037 		sr->sr_maxpsz = MIN(MAXBSIZE, stp->sd_qn_maxpsz);
2038 	} else {
2039 		sr->sr_maxpsz = MAXBSIZE;
2040 	}
2041 
2042 	sr->sr_operation = operation;
2043 	sr->sr_file_off = fileoff;
2044 	sr->sr_file_size = size;
2045 	sr->sr_hiwat = sendfile_req_hiwat;
2046 	sr->sr_lowat = sendfile_req_lowat;
2047 	mutex_init(&sr->sr_lock, NULL, MUTEX_DEFAULT, NULL);
2048 	cv_init(&sr->sr_cv, NULL, CV_DEFAULT, NULL);
2049 	/*
2050 	 * See whether we need another thread for servicing this
2051 	 * request. If there are already enough requests queued
2052 	 * for the threads, create one if not exceeding
2053 	 * snfq_max_threads.
2054 	 */
2055 	mutex_enter(&snfq->snfq_lock);
2056 	if (snfq->snfq_req_cnt >= snfq->snfq_idle_cnt &&
2057 	    snfq->snfq_svc_threads < snfq->snfq_max_threads) {
2058 		(void) thread_create(NULL, 0, &snf_async_thread, 0, 0, &p0,
2059 		    TS_RUN, minclsyspri);
2060 		snfq->snfq_svc_threads++;
2061 	}
2062 	if (snfq->snfq_req_head == NULL) {
2063 		snfq->snfq_req_head = snfq->snfq_req_tail = sr;
2064 		cv_signal(&snfq->snfq_cv);
2065 	} else {
2066 		snfq->snfq_req_tail->sr_next = sr;
2067 		snfq->snfq_req_tail = sr;
2068 	}
2069 	snfq->snfq_req_cnt++;
2070 	mutex_exit(&snfq->snfq_lock);
2071 	return (sr);
2072 }
2073 
2074 int
2075 snf_direct_io(file_t *fp, file_t *rfp, u_offset_t fileoff, u_offset_t size,
2076     ssize_t *count)
2077 {
2078 	snf_req_t *sr;
2079 	mblk_t *mp;
2080 	int iosize;
2081 	int error = 0;
2082 	short fflag;
2083 	struct vnode *vp;
2084 	int ksize;
2085 	struct nmsghdr msg;
2086 
2087 	ksize = 0;
2088 	*count = 0;
2089 	bzero(&msg, sizeof (msg));
2090 
2091 	vp = fp->f_vnode;
2092 	fflag = fp->f_flag;
2093 	if ((sr = create_thread(READ_OP, vp, rfp, fileoff, size)) == NULL)
2094 		return (EAGAIN);
2095 
2096 	/*
2097 	 * We check for read error in snf_deque. It has to check
2098 	 * for successful READ_DONE and return NULL, and we might
2099 	 * as well make an additional check there.
2100 	 */
2101 	while ((mp = snf_deque(sr)) != NULL) {
2102 
2103 		if (ISSIG(curthread, JUSTLOOKING)) {
2104 			freeb(mp);
2105 			error = EINTR;
2106 			break;
2107 		}
2108 		iosize = MBLKL(mp);
2109 
2110 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2111 
2112 		if (error != 0) {
2113 			if (mp != NULL)
2114 				freeb(mp);
2115 			break;
2116 		}
2117 		ksize += iosize;
2118 	}
2119 	*count = ksize;
2120 
2121 	mutex_enter(&sr->sr_lock);
2122 	sr->sr_write_error = error;
2123 	/* Look at the big comments on why we cv_signal here. */
2124 	cv_signal(&sr->sr_cv);
2125 
2126 	/* Wait for the reader to complete always. */
2127 	while (!(sr->sr_read_error & SR_READ_DONE)) {
2128 		cv_wait(&sr->sr_cv, &sr->sr_lock);
2129 	}
2130 	/* If there is no write error, check for read error. */
2131 	if (error == 0)
2132 		error = (sr->sr_read_error & ~SR_READ_DONE);
2133 
2134 	if (error != 0) {
2135 		mblk_t *next_mp;
2136 
2137 		mp = sr->sr_mp_head;
2138 		while (mp != NULL) {
2139 			next_mp = mp->b_next;
2140 			mp->b_next = NULL;
2141 			freeb(mp);
2142 			mp = next_mp;
2143 		}
2144 	}
2145 	mutex_exit(&sr->sr_lock);
2146 	kmem_free(sr, sizeof (snf_req_t));
2147 	return (error);
2148 }
2149 
2150 typedef struct {
2151 	frtn_t		snfi_frtn;
2152 	caddr_t		snfi_base;
2153 	uint_t		snfi_mapoff;
2154 	size_t		snfi_len;
2155 	vnode_t		*snfi_vp;
2156 } snf_smap_desbinfo;
2157 
2158 /*
2159  * The callback function when the last ref of the mblk is dropped,
2160  * normally occurs when TCP receives the ack. But it can be the driver
2161  * too due to lazy reclaim.
2162  */
2163 void
2164 snf_smap_desbfree(snf_smap_desbinfo *snfi)
2165 {
2166 	if (! IS_KPM_ADDR(snfi->snfi_base)) {
2167 		/*
2168 		 * We don't need to call segmap_fault(F_SOFTUNLOCK) for
2169 		 * segmap_kpm as long as the latter never falls back to
2170 		 * "use_segmap_range". (See segmap_getmapflt().)
2171 		 *
2172 		 * Using S_OTHER saves an redundant hat_setref() in
2173 		 * segmap_unlock()
2174 		 */
2175 		(void) segmap_fault(kas.a_hat, segkmap,
2176 		    (caddr_t)(uintptr_t)(((uintptr_t)snfi->snfi_base +
2177 		    snfi->snfi_mapoff) & PAGEMASK), snfi->snfi_len,
2178 		    F_SOFTUNLOCK, S_OTHER);
2179 	}
2180 	(void) segmap_release(segkmap, snfi->snfi_base, SM_DONTNEED);
2181 	VN_RELE(snfi->snfi_vp);
2182 	kmem_free(snfi, sizeof (*snfi));
2183 }
2184 
2185 /*
2186  * Use segmap instead of bcopy to send down a desballoca'ed, mblk.  The mblk
2187  * contains a segmap slot of no more than MAXBSIZE.
2188  *
2189  * At the end of the whole sendfile() operation, we wait till the data from
2190  * the last mblk is ack'ed by the transport before returning so that the
2191  * caller of sendfile() can safely modify the file content.
2192  */
2193 int
2194 snf_segmap(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t size,
2195     ssize_t *count, boolean_t nowait)
2196 {
2197 	caddr_t base;
2198 	int mapoff;
2199 	vnode_t *vp;
2200 	mblk_t *mp;
2201 	int iosize;
2202 	int error;
2203 	short fflag;
2204 	int ksize;
2205 	snf_smap_desbinfo *snfi;
2206 	struct vattr va;
2207 	boolean_t dowait = B_FALSE;
2208 	struct nmsghdr msg;
2209 
2210 	vp = fp->f_vnode;
2211 	fflag = fp->f_flag;
2212 	ksize = 0;
2213 	bzero(&msg, sizeof (msg));
2214 
2215 	for (;;) {
2216 		if (ISSIG(curthread, JUSTLOOKING)) {
2217 			error = EINTR;
2218 			break;
2219 		}
2220 
2221 		mapoff = fileoff & MAXBOFFSET;
2222 		iosize = MAXBSIZE - mapoff;
2223 		if (iosize > size)
2224 			iosize = size;
2225 		/*
2226 		 * we don't forcefault because we'll call
2227 		 * segmap_fault(F_SOFTLOCK) next.
2228 		 *
2229 		 * S_READ will get the ref bit set (by either
2230 		 * segmap_getmapflt() or segmap_fault()) and page
2231 		 * shared locked.
2232 		 */
2233 		base = segmap_getmapflt(segkmap, fvp, fileoff, iosize,
2234 		    segmap_kpm ? SM_FAULT : 0, S_READ);
2235 
2236 		snfi = kmem_alloc(sizeof (*snfi), KM_SLEEP);
2237 		snfi->snfi_len = (size_t)roundup(mapoff+iosize,
2238 		    PAGESIZE)- (mapoff & PAGEMASK);
2239 		/*
2240 		 * We must call segmap_fault() even for segmap_kpm
2241 		 * because that's how error gets returned.
2242 		 * (segmap_getmapflt() never fails but segmap_fault()
2243 		 * does.)
2244 		 */
2245 		if (segmap_fault(kas.a_hat, segkmap,
2246 		    (caddr_t)(uintptr_t)(((uintptr_t)base + mapoff) & PAGEMASK),
2247 		    snfi->snfi_len, F_SOFTLOCK, S_READ) != 0) {
2248 			(void) segmap_release(segkmap, base, 0);
2249 			kmem_free(snfi, sizeof (*snfi));
2250 			error = EIO;
2251 			goto out;
2252 		}
2253 		snfi->snfi_frtn.free_func = snf_smap_desbfree;
2254 		snfi->snfi_frtn.free_arg = (caddr_t)snfi;
2255 		snfi->snfi_base = base;
2256 		snfi->snfi_mapoff = mapoff;
2257 		mp = esballoca((uchar_t *)base + mapoff, iosize, BPRI_HI,
2258 		    &snfi->snfi_frtn);
2259 
2260 		if (mp == NULL) {
2261 			(void) segmap_fault(kas.a_hat, segkmap,
2262 			    (caddr_t)(uintptr_t)(((uintptr_t)base + mapoff)
2263 			    & PAGEMASK), snfi->snfi_len, F_SOFTUNLOCK, S_OTHER);
2264 			(void) segmap_release(segkmap, base, 0);
2265 			kmem_free(snfi, sizeof (*snfi));
2266 			freemsg(mp);
2267 			error = EAGAIN;
2268 			goto out;
2269 		}
2270 		VN_HOLD(fvp);
2271 		snfi->snfi_vp = fvp;
2272 		mp->b_wptr += iosize;
2273 
2274 		/* Mark this dblk with the zero-copy flag */
2275 		mp->b_datap->db_struioflag |= STRUIO_ZC;
2276 		fileoff += iosize;
2277 		size -= iosize;
2278 
2279 		if (size == 0 && !nowait) {
2280 			ASSERT(!dowait);
2281 			dowait = B_TRUE;
2282 			mp->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
2283 		}
2284 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2285 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2286 		if (error != 0) {
2287 			*count = ksize;
2288 			if (mp != NULL)
2289 				freemsg(mp);
2290 			return (error);
2291 		}
2292 		ksize += iosize;
2293 		if (size == 0)
2294 			goto done;
2295 
2296 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2297 		va.va_mask = AT_SIZE;
2298 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2299 		if (error)
2300 			break;
2301 		/* Read as much as possible. */
2302 		if (fileoff >= va.va_size)
2303 			break;
2304 		if (size + fileoff > va.va_size)
2305 			size = va.va_size - fileoff;
2306 	}
2307 out:
2308 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2309 done:
2310 	*count = ksize;
2311 	if (dowait) {
2312 		stdata_t *stp;
2313 
2314 		stp = vp->v_stream;
2315 		if (stp == NULL) {
2316 			struct sonode *so;
2317 			so = VTOSO(vp);
2318 			error = so_zcopy_wait(so);
2319 		} else {
2320 			mutex_enter(&stp->sd_lock);
2321 			while (!(stp->sd_flag & STZCNOTIFY)) {
2322 				if (cv_wait_sig(&stp->sd_zcopy_wait,
2323 				    &stp->sd_lock) == 0) {
2324 					error = EINTR;
2325 					break;
2326 				}
2327 			}
2328 			stp->sd_flag &= ~STZCNOTIFY;
2329 			mutex_exit(&stp->sd_lock);
2330 		}
2331 	}
2332 	return (error);
2333 }
2334 
2335 int
2336 snf_cache(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t size,
2337     uint_t maxpsz, ssize_t *count)
2338 {
2339 	struct vnode *vp;
2340 	mblk_t *mp;
2341 	int iosize;
2342 	int extra = 0;
2343 	int error;
2344 	short fflag;
2345 	int ksize;
2346 	int ioflag;
2347 	struct uio auio;
2348 	struct iovec aiov;
2349 	struct vattr va;
2350 	int maxblk = 0;
2351 	int wroff = 0;
2352 	struct sonode *so;
2353 	struct nmsghdr msg;
2354 
2355 	vp = fp->f_vnode;
2356 	if (vp->v_type == VSOCK) {
2357 		stdata_t *stp;
2358 
2359 		/*
2360 		 * Get the extra space to insert a header and a trailer.
2361 		 */
2362 		so = VTOSO(vp);
2363 		stp = vp->v_stream;
2364 		if (stp == NULL) {
2365 			wroff = so->so_proto_props.sopp_wroff;
2366 			maxblk = so->so_proto_props.sopp_maxblk;
2367 			extra = wroff + so->so_proto_props.sopp_tail;
2368 		} else {
2369 			wroff = (int)(stp->sd_wroff);
2370 			maxblk = (int)(stp->sd_maxblk);
2371 			extra = wroff + (int)(stp->sd_tail);
2372 		}
2373 	}
2374 	bzero(&msg, sizeof (msg));
2375 	fflag = fp->f_flag;
2376 	ksize = 0;
2377 	auio.uio_iov = &aiov;
2378 	auio.uio_iovcnt = 1;
2379 	auio.uio_segflg = UIO_SYSSPACE;
2380 	auio.uio_llimit = MAXOFFSET_T;
2381 	auio.uio_fmode = fflag;
2382 	auio.uio_extflg = UIO_COPY_CACHED;
2383 	ioflag = auio.uio_fmode & (FSYNC|FDSYNC|FRSYNC);
2384 	/* If read sync is not asked for, filter sync flags */
2385 	if ((ioflag & FRSYNC) == 0)
2386 		ioflag &= ~(FSYNC|FDSYNC);
2387 	for (;;) {
2388 		if (ISSIG(curthread, JUSTLOOKING)) {
2389 			error = EINTR;
2390 			break;
2391 		}
2392 		iosize = (int)MIN(maxpsz, size);
2393 
2394 		/*
2395 		 * For sockets acting as an SSL proxy, we
2396 		 * need to adjust the size to the maximum
2397 		 * SSL record size set in the stream head.
2398 		 */
2399 		if (vp->v_type == VSOCK && !SOCK_IS_NONSTR(so) &&
2400 		    SOTOTPI(so)->sti_kssl_ctx != NULL)
2401 			iosize = (int)MIN(iosize, maxblk);
2402 
2403 		if ((mp = allocb(iosize + extra, BPRI_MED)) == NULL) {
2404 			error = EAGAIN;
2405 			break;
2406 		}
2407 
2408 		mp->b_rptr += wroff;
2409 
2410 		aiov.iov_base = (caddr_t)mp->b_rptr;
2411 		aiov.iov_len = iosize;
2412 		auio.uio_loffset = fileoff;
2413 		auio.uio_resid = iosize;
2414 
2415 		error = VOP_READ(fvp, &auio, ioflag, fp->f_cred, NULL);
2416 		iosize -= auio.uio_resid;
2417 
2418 		if (error == EINTR && iosize != 0)
2419 			error = 0;
2420 
2421 		if (error != 0 || iosize == 0) {
2422 			freeb(mp);
2423 			break;
2424 		}
2425 		mp->b_wptr = mp->b_rptr + iosize;
2426 
2427 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2428 
2429 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2430 
2431 		if (error != 0) {
2432 			*count = ksize;
2433 			if (mp != NULL)
2434 				freeb(mp);
2435 			return (error);
2436 		}
2437 		ksize += iosize;
2438 		size -= iosize;
2439 		if (size == 0)
2440 			goto done;
2441 
2442 		fileoff += iosize;
2443 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2444 		va.va_mask = AT_SIZE;
2445 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2446 		if (error)
2447 			break;
2448 		/* Read as much as possible. */
2449 		if (fileoff >= va.va_size)
2450 			size = 0;
2451 		else if (size + fileoff > va.va_size)
2452 			size = va.va_size - fileoff;
2453 	}
2454 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2455 done:
2456 	*count = ksize;
2457 	return (error);
2458 }
2459 
2460 #if defined(_SYSCALL32_IMPL) || defined(_ILP32)
2461 /*
2462  * Largefile support for 32 bit applications only.
2463  */
2464 int
2465 sosendfile64(file_t *fp, file_t *rfp, const struct ksendfilevec64 *sfv,
2466     ssize32_t *count32)
2467 {
2468 	ssize32_t sfv_len;
2469 	u_offset_t sfv_off, va_size;
2470 	struct vnode *vp, *fvp, *realvp;
2471 	struct vattr va;
2472 	stdata_t *stp;
2473 	ssize_t count = 0;
2474 	int error = 0;
2475 	boolean_t dozcopy = B_FALSE;
2476 	uint_t maxpsz;
2477 
2478 	sfv_len = (ssize32_t)sfv->sfv_len;
2479 	if (sfv_len < 0) {
2480 		error = EINVAL;
2481 		goto out;
2482 	}
2483 
2484 	if (sfv_len == 0) goto out;
2485 
2486 	sfv_off = (u_offset_t)sfv->sfv_off;
2487 
2488 	/* Same checks as in pread */
2489 	if (sfv_off > MAXOFFSET_T) {
2490 		error = EINVAL;
2491 		goto out;
2492 	}
2493 	if (sfv_off + sfv_len > MAXOFFSET_T)
2494 		sfv_len = (ssize32_t)(MAXOFFSET_T - sfv_off);
2495 
2496 	/*
2497 	 * There are no more checks on sfv_len. So, we cast it to
2498 	 * u_offset_t and share the snf_direct_io/snf_cache code between
2499 	 * 32 bit and 64 bit.
2500 	 *
2501 	 * TODO: should do nbl_need_check() like read()?
2502 	 */
2503 	if (sfv_len > sendfile_max_size) {
2504 		sf_stats.ss_file_not_cached++;
2505 		error = snf_direct_io(fp, rfp, sfv_off, (u_offset_t)sfv_len,
2506 		    &count);
2507 		goto out;
2508 	}
2509 	fvp = rfp->f_vnode;
2510 	if (VOP_REALVP(fvp, &realvp, NULL) == 0)
2511 		fvp = realvp;
2512 	/*
2513 	 * Grab the lock as a reader to prevent the file size
2514 	 * from changing underneath.
2515 	 */
2516 	(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2517 	va.va_mask = AT_SIZE;
2518 	error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2519 	va_size = va.va_size;
2520 	if ((error != 0) || (va_size == 0) || (sfv_off >= va_size)) {
2521 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2522 		goto out;
2523 	}
2524 	/* Read as much as possible. */
2525 	if (sfv_off + sfv_len > va_size)
2526 		sfv_len = va_size - sfv_off;
2527 
2528 	vp = fp->f_vnode;
2529 	stp = vp->v_stream;
2530 	/*
2531 	 * When the NOWAIT flag is not set, we enable zero-copy only if the
2532 	 * transfer size is large enough. This prevents performance loss
2533 	 * when the caller sends the file piece by piece.
2534 	 */
2535 	if (sfv_len >= MAXBSIZE && (sfv_len >= (va_size >> 1) ||
2536 	    (sfv->sfv_flag & SFV_NOWAIT) || sfv_len >= 0x1000000) &&
2537 	    !vn_has_flocks(fvp) && !(fvp->v_flag & VNOMAP)) {
2538 		uint_t copyflag;
2539 		copyflag = stp != NULL ? stp->sd_copyflag :
2540 		    VTOSO(vp)->so_proto_props.sopp_zcopyflag;
2541 		if ((copyflag & (STZCVMSAFE|STZCVMUNSAFE)) == 0) {
2542 			int on = 1;
2543 
2544 			if (socket_setsockopt(VTOSO(vp), SOL_SOCKET,
2545 			    SO_SND_COPYAVOID, &on, sizeof (on), CRED()) == 0)
2546 				dozcopy = B_TRUE;
2547 		} else {
2548 			dozcopy = copyflag & STZCVMSAFE;
2549 		}
2550 	}
2551 	if (dozcopy) {
2552 		sf_stats.ss_file_segmap++;
2553 		error = snf_segmap(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2554 		    &count, ((sfv->sfv_flag & SFV_NOWAIT) != 0));
2555 	} else {
2556 		if (vp->v_type == VSOCK && stp == NULL) {
2557 			sonode_t *so = VTOSO(vp);
2558 			maxpsz = so->so_proto_props.sopp_maxpsz;
2559 		} else if (stp != NULL) {
2560 			maxpsz = stp->sd_qn_maxpsz;
2561 		} else {
2562 			maxpsz = maxphys;
2563 		}
2564 
2565 		if (maxpsz == INFPSZ)
2566 			maxpsz = maxphys;
2567 		else
2568 			maxpsz = roundup(maxpsz, MAXBSIZE);
2569 		sf_stats.ss_file_cached++;
2570 		error = snf_cache(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2571 		    maxpsz, &count);
2572 	}
2573 out:
2574 	releasef(sfv->sfv_fd);
2575 	*count32 = (ssize32_t)count;
2576 	return (error);
2577 }
2578 #endif
2579 
2580 #ifdef _SYSCALL32_IMPL
2581 /*
2582  * recv32(), recvfrom32(), send32(), sendto32(): intentionally return a
2583  * ssize_t rather than ssize32_t; see the comments above read32 for details.
2584  */
2585 
2586 ssize_t
2587 recv32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2588 {
2589 	return (recv(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2590 }
2591 
2592 ssize_t
2593 recvfrom32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2594 	caddr32_t name, caddr32_t namelenp)
2595 {
2596 	return (recvfrom(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2597 	    (void *)(uintptr_t)name, (void *)(uintptr_t)namelenp));
2598 }
2599 
2600 ssize_t
2601 send32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2602 {
2603 	return (send(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2604 }
2605 
2606 ssize_t
2607 sendto32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2608 	caddr32_t name, socklen_t namelen)
2609 {
2610 	return (sendto(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2611 	    (void *)(uintptr_t)name, namelen));
2612 }
2613 #endif	/* _SYSCALL32_IMPL */
2614 
2615 /*
2616  * Function wrappers (mostly around the sonode switch) for
2617  * backward compatibility.
2618  */
2619 
2620 int
2621 soaccept(struct sonode *so, int fflag, struct sonode **nsop)
2622 {
2623 	return (socket_accept(so, fflag, CRED(), nsop));
2624 }
2625 
2626 int
2627 sobind(struct sonode *so, struct sockaddr *name, socklen_t namelen,
2628     int backlog, int flags)
2629 {
2630 	int	error;
2631 
2632 	error = socket_bind(so, name, namelen, flags, CRED());
2633 	if (error == 0 && backlog != 0)
2634 		return (socket_listen(so, backlog, CRED()));
2635 
2636 	return (error);
2637 }
2638 
2639 int
2640 solisten(struct sonode *so, int backlog)
2641 {
2642 	return (socket_listen(so, backlog, CRED()));
2643 }
2644 
2645 int
2646 soconnect(struct sonode *so, const struct sockaddr *name, socklen_t namelen,
2647     int fflag, int flags)
2648 {
2649 	return (socket_connect(so, name, namelen, fflag, flags, CRED()));
2650 }
2651 
2652 int
2653 sorecvmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2654 {
2655 	return (socket_recvmsg(so, msg, uiop, CRED()));
2656 }
2657 
2658 int
2659 sosendmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2660 {
2661 	return (socket_sendmsg(so, msg, uiop, CRED()));
2662 }
2663 
2664 int
2665 soshutdown(struct sonode *so, int how)
2666 {
2667 	return (socket_shutdown(so, how, CRED()));
2668 }
2669 
2670 int
2671 sogetsockopt(struct sonode *so, int level, int option_name, void *optval,
2672     socklen_t *optlenp, int flags)
2673 {
2674 	return (socket_getsockopt(so, level, option_name, optval, optlenp,
2675 	    flags, CRED()));
2676 }
2677 
2678 int
2679 sosetsockopt(struct sonode *so, int level, int option_name, const void *optval,
2680     t_uscalar_t optlen)
2681 {
2682 	return (socket_setsockopt(so, level, option_name, optval, optlen,
2683 	    CRED()));
2684 }
2685 
2686 /*
2687  * Because this is backward compatibility interface it only needs to be
2688  * able to handle the creation of TPI sockfs sockets.
2689  */
2690 struct sonode *
2691 socreate(struct sockparams *sp, int family, int type, int protocol, int version,
2692     int *errorp)
2693 {
2694 	struct sonode *so;
2695 
2696 	ASSERT(sp != NULL);
2697 
2698 	so = sp->sp_smod_info->smod_sock_create_func(sp, family, type, protocol,
2699 	    version, SOCKET_SLEEP, errorp, CRED());
2700 	if (so == NULL) {
2701 		SOCKPARAMS_DEC_REF(sp);
2702 	} else {
2703 		if ((*errorp = SOP_INIT(so, NULL, CRED(), SOCKET_SLEEP)) == 0) {
2704 			/* Cannot fail, only bumps so_count */
2705 			(void) VOP_OPEN(&SOTOV(so), FREAD|FWRITE, CRED(), NULL);
2706 		} else {
2707 			socket_destroy(so);
2708 			so = NULL;
2709 		}
2710 	}
2711 	return (so);
2712 }
2713