xref: /titanic_52/usr/src/uts/common/fs/sockfs/socksyscalls.c (revision 97322426b5359bb3ffd4527e1ad8b2c5f7dab832)
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 2009 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 (is_system_labeled()) {
1949 			mp = allocb_cred(iosize + extra, CRED(),
1950 			    curproc->p_pid);
1951 		} else {
1952 			mp = allocb(iosize + extra, BPRI_MED);
1953 		}
1954 		if (mp == NULL) {
1955 			error = EAGAIN;
1956 			break;
1957 		}
1958 
1959 		mp->b_rptr += wroff;
1960 
1961 		ret_size = soreadfile(fp, mp->b_rptr, fileoff, &error, iosize);
1962 
1963 		/* Error or Reached EOF ? */
1964 		if ((error != 0) || (ret_size == 0)) {
1965 			freeb(mp);
1966 			break;
1967 		}
1968 		mp->b_wptr = mp->b_rptr + ret_size;
1969 
1970 		snf_enque(sr, mp);
1971 		size -= ret_size;
1972 		fileoff += ret_size;
1973 	}
1974 	(void) VOP_IOCTL(fp->f_vnode, _FIODIRECTIO, DIRECTIO_OFF, 0,
1975 	    kcred, NULL, NULL);
1976 	mutex_enter(&sr->sr_lock);
1977 	sr->sr_read_error = error;
1978 	sr->sr_read_error |= SR_READ_DONE;
1979 	cv_signal(&sr->sr_cv);
1980 	mutex_exit(&sr->sr_lock);
1981 }
1982 
1983 void
1984 snf_async_thread(void)
1985 {
1986 	snf_req_t *sr;
1987 	callb_cpr_t cprinfo;
1988 	clock_t time_left = 1;
1989 
1990 	CALLB_CPR_INIT(&cprinfo, &snfq->snfq_lock, callb_generic_cpr, "snfq");
1991 
1992 	mutex_enter(&snfq->snfq_lock);
1993 	for (;;) {
1994 		/*
1995 		 * If we didn't find a entry, then block until woken up
1996 		 * again and then look through the queues again.
1997 		 */
1998 		while ((sr = snfq->snfq_req_head) == NULL) {
1999 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
2000 			if (time_left <= 0) {
2001 				snfq->snfq_svc_threads--;
2002 				CALLB_CPR_EXIT(&cprinfo);
2003 				thread_exit();
2004 				/* NOTREACHED */
2005 			}
2006 			snfq->snfq_idle_cnt++;
2007 
2008 			time_left = cv_reltimedwait(&snfq->snfq_cv,
2009 			    &snfq->snfq_lock, snfq_timeout, TR_CLOCK_TICK);
2010 			snfq->snfq_idle_cnt--;
2011 
2012 			CALLB_CPR_SAFE_END(&cprinfo, &snfq->snfq_lock);
2013 		}
2014 		snfq->snfq_req_head = sr->sr_next;
2015 		snfq->snfq_req_cnt--;
2016 		mutex_exit(&snfq->snfq_lock);
2017 		snf_async_read(sr);
2018 		mutex_enter(&snfq->snfq_lock);
2019 	}
2020 }
2021 
2022 
2023 snf_req_t *
2024 create_thread(int operation, struct vnode *vp, file_t *fp,
2025     u_offset_t fileoff, u_offset_t size)
2026 {
2027 	snf_req_t *sr;
2028 	stdata_t *stp;
2029 
2030 	sr = (snf_req_t *)kmem_zalloc(sizeof (snf_req_t), KM_SLEEP);
2031 
2032 	sr->sr_vp = vp;
2033 	sr->sr_fp = fp;
2034 	stp = vp->v_stream;
2035 
2036 	/*
2037 	 * store sd_qn_maxpsz into sr_maxpsz while we have stream head.
2038 	 * stream might be closed before thread returns from snf_async_read.
2039 	 */
2040 	if (stp != NULL && stp->sd_qn_maxpsz > 0) {
2041 		sr->sr_maxpsz = MIN(MAXBSIZE, stp->sd_qn_maxpsz);
2042 	} else {
2043 		sr->sr_maxpsz = MAXBSIZE;
2044 	}
2045 
2046 	sr->sr_operation = operation;
2047 	sr->sr_file_off = fileoff;
2048 	sr->sr_file_size = size;
2049 	sr->sr_hiwat = sendfile_req_hiwat;
2050 	sr->sr_lowat = sendfile_req_lowat;
2051 	mutex_init(&sr->sr_lock, NULL, MUTEX_DEFAULT, NULL);
2052 	cv_init(&sr->sr_cv, NULL, CV_DEFAULT, NULL);
2053 	/*
2054 	 * See whether we need another thread for servicing this
2055 	 * request. If there are already enough requests queued
2056 	 * for the threads, create one if not exceeding
2057 	 * snfq_max_threads.
2058 	 */
2059 	mutex_enter(&snfq->snfq_lock);
2060 	if (snfq->snfq_req_cnt >= snfq->snfq_idle_cnt &&
2061 	    snfq->snfq_svc_threads < snfq->snfq_max_threads) {
2062 		(void) thread_create(NULL, 0, &snf_async_thread, 0, 0, &p0,
2063 		    TS_RUN, minclsyspri);
2064 		snfq->snfq_svc_threads++;
2065 	}
2066 	if (snfq->snfq_req_head == NULL) {
2067 		snfq->snfq_req_head = snfq->snfq_req_tail = sr;
2068 		cv_signal(&snfq->snfq_cv);
2069 	} else {
2070 		snfq->snfq_req_tail->sr_next = sr;
2071 		snfq->snfq_req_tail = sr;
2072 	}
2073 	snfq->snfq_req_cnt++;
2074 	mutex_exit(&snfq->snfq_lock);
2075 	return (sr);
2076 }
2077 
2078 int
2079 snf_direct_io(file_t *fp, file_t *rfp, u_offset_t fileoff, u_offset_t size,
2080     ssize_t *count)
2081 {
2082 	snf_req_t *sr;
2083 	mblk_t *mp;
2084 	int iosize;
2085 	int error = 0;
2086 	short fflag;
2087 	struct vnode *vp;
2088 	int ksize;
2089 	struct nmsghdr msg;
2090 
2091 	ksize = 0;
2092 	*count = 0;
2093 	bzero(&msg, sizeof (msg));
2094 
2095 	vp = fp->f_vnode;
2096 	fflag = fp->f_flag;
2097 	if ((sr = create_thread(READ_OP, vp, rfp, fileoff, size)) == NULL)
2098 		return (EAGAIN);
2099 
2100 	/*
2101 	 * We check for read error in snf_deque. It has to check
2102 	 * for successful READ_DONE and return NULL, and we might
2103 	 * as well make an additional check there.
2104 	 */
2105 	while ((mp = snf_deque(sr)) != NULL) {
2106 
2107 		if (ISSIG(curthread, JUSTLOOKING)) {
2108 			freeb(mp);
2109 			error = EINTR;
2110 			break;
2111 		}
2112 		iosize = MBLKL(mp);
2113 
2114 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2115 
2116 		if (error != 0) {
2117 			if (mp != NULL)
2118 				freeb(mp);
2119 			break;
2120 		}
2121 		ksize += iosize;
2122 	}
2123 	*count = ksize;
2124 
2125 	mutex_enter(&sr->sr_lock);
2126 	sr->sr_write_error = error;
2127 	/* Look at the big comments on why we cv_signal here. */
2128 	cv_signal(&sr->sr_cv);
2129 
2130 	/* Wait for the reader to complete always. */
2131 	while (!(sr->sr_read_error & SR_READ_DONE)) {
2132 		cv_wait(&sr->sr_cv, &sr->sr_lock);
2133 	}
2134 	/* If there is no write error, check for read error. */
2135 	if (error == 0)
2136 		error = (sr->sr_read_error & ~SR_READ_DONE);
2137 
2138 	if (error != 0) {
2139 		mblk_t *next_mp;
2140 
2141 		mp = sr->sr_mp_head;
2142 		while (mp != NULL) {
2143 			next_mp = mp->b_next;
2144 			mp->b_next = NULL;
2145 			freeb(mp);
2146 			mp = next_mp;
2147 		}
2148 	}
2149 	mutex_exit(&sr->sr_lock);
2150 	kmem_free(sr, sizeof (snf_req_t));
2151 	return (error);
2152 }
2153 
2154 /* Maximum no.of pages allocated by vpm for sendfile at a time */
2155 #define	SNF_VPMMAXPGS	(VPMMAXPGS/2)
2156 
2157 /*
2158  * Maximum no.of elements in the list returned by vpm, including
2159  * NULL for the last entry
2160  */
2161 #define	SNF_MAXVMAPS	(SNF_VPMMAXPGS + 1)
2162 
2163 typedef struct {
2164 	unsigned int	snfv_ref;
2165 	frtn_t		snfv_frtn;
2166 	vnode_t		*snfv_vp;
2167 	struct vmap	snfv_vml[SNF_MAXVMAPS];
2168 } snf_vmap_desbinfo;
2169 
2170 typedef struct {
2171 	frtn_t		snfi_frtn;
2172 	caddr_t		snfi_base;
2173 	uint_t		snfi_mapoff;
2174 	size_t		snfi_len;
2175 	vnode_t		*snfi_vp;
2176 } snf_smap_desbinfo;
2177 
2178 /*
2179  * The callback function used for vpm mapped mblks called when the last ref of
2180  * the mblk is dropped which normally occurs when TCP receives the ack. But it
2181  * can be the driver too due to lazy reclaim.
2182  */
2183 void
2184 snf_vmap_desbfree(snf_vmap_desbinfo *snfv)
2185 {
2186 	ASSERT(snfv->snfv_ref != 0);
2187 	if (atomic_add_32_nv(&snfv->snfv_ref, -1) == 0) {
2188 		vpm_unmap_pages(snfv->snfv_vml, S_READ);
2189 		VN_RELE(snfv->snfv_vp);
2190 		kmem_free(snfv, sizeof (snf_vmap_desbinfo));
2191 	}
2192 }
2193 
2194 /*
2195  * The callback function used for segmap'ped mblks called when the last ref of
2196  * the mblk is dropped which normally occurs when TCP receives the ack. But it
2197  * can be the driver too due to lazy reclaim.
2198  */
2199 void
2200 snf_smap_desbfree(snf_smap_desbinfo *snfi)
2201 {
2202 	if (! IS_KPM_ADDR(snfi->snfi_base)) {
2203 		/*
2204 		 * We don't need to call segmap_fault(F_SOFTUNLOCK) for
2205 		 * segmap_kpm as long as the latter never falls back to
2206 		 * "use_segmap_range". (See segmap_getmapflt().)
2207 		 *
2208 		 * Using S_OTHER saves an redundant hat_setref() in
2209 		 * segmap_unlock()
2210 		 */
2211 		(void) segmap_fault(kas.a_hat, segkmap,
2212 		    (caddr_t)(uintptr_t)(((uintptr_t)snfi->snfi_base +
2213 		    snfi->snfi_mapoff) & PAGEMASK), snfi->snfi_len,
2214 		    F_SOFTUNLOCK, S_OTHER);
2215 	}
2216 	(void) segmap_release(segkmap, snfi->snfi_base, SM_DONTNEED);
2217 	VN_RELE(snfi->snfi_vp);
2218 	kmem_free(snfi, sizeof (*snfi));
2219 }
2220 
2221 /*
2222  * Use segmap or vpm instead of bcopy to send down a desballoca'ed, mblk.
2223  * When segmap is used, the mblk contains a segmap slot of no more
2224  * than MAXBSIZE.
2225  *
2226  * With vpm, a maximum of SNF_MAXVMAPS page-sized mappings can be obtained
2227  * in each iteration and sent by socket_sendmblk until an error occurs or
2228  * the requested size has been transferred. An mblk is esballoca'ed from
2229  * each mapped page and a chain of these mblk is sent to the transport layer.
2230  * vpm will be called to unmap the pages when all mblks have been freed by
2231  * free_func.
2232  *
2233  * At the end of the whole sendfile() operation, we wait till the data from
2234  * the last mblk is ack'ed by the transport before returning so that the
2235  * caller of sendfile() can safely modify the file content.
2236  */
2237 int
2238 snf_segmap(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t total_size,
2239     ssize_t *count, boolean_t nowait)
2240 {
2241 	caddr_t base;
2242 	int mapoff;
2243 	vnode_t *vp;
2244 	mblk_t *mp = NULL;
2245 	int chain_size;
2246 	int error;
2247 	short fflag;
2248 	int ksize;
2249 	struct vattr va;
2250 	boolean_t dowait = B_FALSE;
2251 	struct nmsghdr msg;
2252 
2253 	vp = fp->f_vnode;
2254 	fflag = fp->f_flag;
2255 	ksize = 0;
2256 	bzero(&msg, sizeof (msg));
2257 
2258 	for (;;) {
2259 		if (ISSIG(curthread, JUSTLOOKING)) {
2260 			error = EINTR;
2261 			break;
2262 		}
2263 
2264 		if (vpm_enable) {
2265 			snf_vmap_desbinfo *snfv;
2266 			mblk_t *nmp;
2267 			int mblk_size;
2268 			int maxsize;
2269 			int i;
2270 
2271 			mapoff = fileoff & PAGEOFFSET;
2272 			maxsize = MIN((SNF_VPMMAXPGS * PAGESIZE), total_size);
2273 
2274 			snfv = kmem_zalloc(sizeof (snf_vmap_desbinfo),
2275 			    KM_SLEEP);
2276 
2277 			/* Get vpm mappings for maxsize with read access */
2278 			if (vpm_map_pages(fvp, fileoff, (size_t)maxsize,
2279 			    (VPM_FETCHPAGE), snfv->snfv_vml, SNF_MAXVMAPS,
2280 			    NULL, S_READ) != 0) {
2281 				kmem_free(snfv, sizeof (snf_vmap_desbinfo));
2282 				error = EIO;
2283 				goto out;
2284 			}
2285 			snfv->snfv_frtn.free_func = snf_vmap_desbfree;
2286 			snfv->snfv_frtn.free_arg = (caddr_t)snfv;
2287 
2288 			/* Construct the mblk chain from the page mappings */
2289 			chain_size = 0;
2290 			for (i = 0; (snfv->snfv_vml[i].vs_addr != NULL) &&
2291 			    total_size > 0; i++) {
2292 				ASSERT(chain_size < maxsize);
2293 				mblk_size = MIN(snfv->snfv_vml[i].vs_len -
2294 				    mapoff, total_size);
2295 				nmp = esballoca(
2296 				    (uchar_t *)snfv->snfv_vml[i].vs_addr +
2297 				    mapoff, mblk_size, BPRI_HI,
2298 				    &snfv->snfv_frtn);
2299 
2300 				/*
2301 				 * We return EAGAIN after unmapping the pages
2302 				 * if we cannot allocate the the head of the
2303 				 * chain. Otherwise, we continue sending the
2304 				 * mblks constructed so far.
2305 				 */
2306 				if (nmp == NULL) {
2307 					if (i == 0) {
2308 						vpm_unmap_pages(snfv->snfv_vml,
2309 						    S_READ);
2310 						kmem_free(snfv,
2311 						    sizeof (snf_vmap_desbinfo));
2312 						error = EAGAIN;
2313 						goto out;
2314 					}
2315 					break;
2316 				}
2317 				/* Mark this dblk with the zero-copy flag */
2318 				nmp->b_datap->db_struioflag |= STRUIO_ZC;
2319 				nmp->b_wptr += mblk_size;
2320 				chain_size += mblk_size;
2321 				fileoff += mblk_size;
2322 				total_size -= mblk_size;
2323 				snfv->snfv_ref++;
2324 				mapoff = 0;
2325 				if (i > 0)
2326 					linkb(mp, nmp);
2327 				else
2328 					mp = nmp;
2329 			}
2330 			VN_HOLD(fvp);
2331 			snfv->snfv_vp = fvp;
2332 		} else {
2333 			/* vpm not supported. fallback to segmap */
2334 			snf_smap_desbinfo *snfi;
2335 
2336 			mapoff = fileoff & MAXBOFFSET;
2337 			chain_size = MAXBSIZE - mapoff;
2338 			if (chain_size > total_size)
2339 				chain_size = total_size;
2340 			/*
2341 			 * we don't forcefault because we'll call
2342 			 * segmap_fault(F_SOFTLOCK) next.
2343 			 *
2344 			 * S_READ will get the ref bit set (by either
2345 			 * segmap_getmapflt() or segmap_fault()) and page
2346 			 * shared locked.
2347 			 */
2348 			base = segmap_getmapflt(segkmap, fvp, fileoff,
2349 			    chain_size, segmap_kpm ? SM_FAULT : 0, S_READ);
2350 
2351 			snfi = kmem_alloc(sizeof (*snfi), KM_SLEEP);
2352 			snfi->snfi_len = (size_t)roundup(mapoff+chain_size,
2353 			    PAGESIZE)- (mapoff & PAGEMASK);
2354 			/*
2355 			 * We must call segmap_fault() even for segmap_kpm
2356 			 * because that's how error gets returned.
2357 			 * (segmap_getmapflt() never fails but segmap_fault()
2358 			 * does.)
2359 			 */
2360 			if (segmap_fault(kas.a_hat, segkmap,
2361 			    (caddr_t)(uintptr_t)(((uintptr_t)base + mapoff) &
2362 			    PAGEMASK), snfi->snfi_len,
2363 			    F_SOFTLOCK, S_READ) != 0) {
2364 				(void) segmap_release(segkmap, base, 0);
2365 				kmem_free(snfi, sizeof (*snfi));
2366 				error = EIO;
2367 				goto out;
2368 			}
2369 			snfi->snfi_frtn.free_func = snf_smap_desbfree;
2370 			snfi->snfi_frtn.free_arg = (caddr_t)snfi;
2371 			snfi->snfi_base = base;
2372 			snfi->snfi_mapoff = mapoff;
2373 			mp = esballoca((uchar_t *)base + mapoff, chain_size,
2374 			    BPRI_HI, &snfi->snfi_frtn);
2375 
2376 			if (mp == NULL) {
2377 				(void) segmap_fault(kas.a_hat, segkmap,
2378 				    (caddr_t)(uintptr_t)(((uintptr_t)base +
2379 				    mapoff) & PAGEMASK), snfi->snfi_len,
2380 				    F_SOFTUNLOCK, S_OTHER);
2381 				(void) segmap_release(segkmap, base, 0);
2382 				kmem_free(snfi, sizeof (*snfi));
2383 				freemsg(mp);
2384 				error = EAGAIN;
2385 				goto out;
2386 			}
2387 			VN_HOLD(fvp);
2388 			snfi->snfi_vp = fvp;
2389 			mp->b_wptr += chain_size;
2390 
2391 			/* Mark this dblk with the zero-copy flag */
2392 			mp->b_datap->db_struioflag |= STRUIO_ZC;
2393 			fileoff += chain_size;
2394 			total_size -= chain_size;
2395 		}
2396 
2397 		if (total_size == 0 && !nowait) {
2398 			ASSERT(!dowait);
2399 			dowait = B_TRUE;
2400 			mp->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
2401 		}
2402 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2403 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2404 		if (error != 0) {
2405 			/*
2406 			 * mp contains the mblks that were not sent by
2407 			 * socket_sendmblk. Use its size to update *count
2408 			 */
2409 			*count = ksize + (chain_size - msgdsize(mp));
2410 			if (mp != NULL)
2411 				freemsg(mp);
2412 			return (error);
2413 		}
2414 		ksize += chain_size;
2415 		if (total_size == 0)
2416 			goto done;
2417 
2418 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2419 		va.va_mask = AT_SIZE;
2420 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2421 		if (error)
2422 			break;
2423 		/* Read as much as possible. */
2424 		if (fileoff >= va.va_size)
2425 			break;
2426 		if (total_size + fileoff > va.va_size)
2427 			total_size = va.va_size - fileoff;
2428 	}
2429 out:
2430 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2431 done:
2432 	*count = ksize;
2433 	if (dowait) {
2434 		stdata_t *stp;
2435 
2436 		stp = vp->v_stream;
2437 		if (stp == NULL) {
2438 			struct sonode *so;
2439 			so = VTOSO(vp);
2440 			error = so_zcopy_wait(so);
2441 		} else {
2442 			mutex_enter(&stp->sd_lock);
2443 			while (!(stp->sd_flag & STZCNOTIFY)) {
2444 				if (cv_wait_sig(&stp->sd_zcopy_wait,
2445 				    &stp->sd_lock) == 0) {
2446 					error = EINTR;
2447 					break;
2448 				}
2449 			}
2450 			stp->sd_flag &= ~STZCNOTIFY;
2451 			mutex_exit(&stp->sd_lock);
2452 		}
2453 	}
2454 	return (error);
2455 }
2456 
2457 int
2458 snf_cache(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t size,
2459     uint_t maxpsz, ssize_t *count)
2460 {
2461 	struct vnode *vp;
2462 	mblk_t *mp;
2463 	int iosize;
2464 	int extra = 0;
2465 	int error;
2466 	short fflag;
2467 	int ksize;
2468 	int ioflag;
2469 	struct uio auio;
2470 	struct iovec aiov;
2471 	struct vattr va;
2472 	int maxblk = 0;
2473 	int wroff = 0;
2474 	struct sonode *so;
2475 	struct nmsghdr msg;
2476 
2477 	vp = fp->f_vnode;
2478 	if (vp->v_type == VSOCK) {
2479 		stdata_t *stp;
2480 
2481 		/*
2482 		 * Get the extra space to insert a header and a trailer.
2483 		 */
2484 		so = VTOSO(vp);
2485 		stp = vp->v_stream;
2486 		if (stp == NULL) {
2487 			wroff = so->so_proto_props.sopp_wroff;
2488 			maxblk = so->so_proto_props.sopp_maxblk;
2489 			extra = wroff + so->so_proto_props.sopp_tail;
2490 		} else {
2491 			wroff = (int)(stp->sd_wroff);
2492 			maxblk = (int)(stp->sd_maxblk);
2493 			extra = wroff + (int)(stp->sd_tail);
2494 		}
2495 	}
2496 	bzero(&msg, sizeof (msg));
2497 	fflag = fp->f_flag;
2498 	ksize = 0;
2499 	auio.uio_iov = &aiov;
2500 	auio.uio_iovcnt = 1;
2501 	auio.uio_segflg = UIO_SYSSPACE;
2502 	auio.uio_llimit = MAXOFFSET_T;
2503 	auio.uio_fmode = fflag;
2504 	auio.uio_extflg = UIO_COPY_CACHED;
2505 	ioflag = auio.uio_fmode & (FSYNC|FDSYNC|FRSYNC);
2506 	/* If read sync is not asked for, filter sync flags */
2507 	if ((ioflag & FRSYNC) == 0)
2508 		ioflag &= ~(FSYNC|FDSYNC);
2509 	for (;;) {
2510 		if (ISSIG(curthread, JUSTLOOKING)) {
2511 			error = EINTR;
2512 			break;
2513 		}
2514 		iosize = (int)MIN(maxpsz, size);
2515 
2516 		/*
2517 		 * For sockets acting as an SSL proxy, we
2518 		 * need to adjust the size to the maximum
2519 		 * SSL record size set in the stream head.
2520 		 */
2521 		if (vp->v_type == VSOCK && !SOCK_IS_NONSTR(so) &&
2522 		    SOTOTPI(so)->sti_kssl_ctx != NULL)
2523 			iosize = (int)MIN(iosize, maxblk);
2524 
2525 		if (is_system_labeled()) {
2526 			mp = allocb_cred(iosize + extra, CRED(),
2527 			    curproc->p_pid);
2528 		} else {
2529 			mp = allocb(iosize + extra, BPRI_MED);
2530 		}
2531 		if (mp == NULL) {
2532 			error = EAGAIN;
2533 			break;
2534 		}
2535 
2536 		mp->b_rptr += wroff;
2537 
2538 		aiov.iov_base = (caddr_t)mp->b_rptr;
2539 		aiov.iov_len = iosize;
2540 		auio.uio_loffset = fileoff;
2541 		auio.uio_resid = iosize;
2542 
2543 		error = VOP_READ(fvp, &auio, ioflag, fp->f_cred, NULL);
2544 		iosize -= auio.uio_resid;
2545 
2546 		if (error == EINTR && iosize != 0)
2547 			error = 0;
2548 
2549 		if (error != 0 || iosize == 0) {
2550 			freeb(mp);
2551 			break;
2552 		}
2553 		mp->b_wptr = mp->b_rptr + iosize;
2554 
2555 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2556 
2557 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2558 
2559 		if (error != 0) {
2560 			*count = ksize;
2561 			if (mp != NULL)
2562 				freeb(mp);
2563 			return (error);
2564 		}
2565 		ksize += iosize;
2566 		size -= iosize;
2567 		if (size == 0)
2568 			goto done;
2569 
2570 		fileoff += iosize;
2571 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2572 		va.va_mask = AT_SIZE;
2573 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2574 		if (error)
2575 			break;
2576 		/* Read as much as possible. */
2577 		if (fileoff >= va.va_size)
2578 			size = 0;
2579 		else if (size + fileoff > va.va_size)
2580 			size = va.va_size - fileoff;
2581 	}
2582 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2583 done:
2584 	*count = ksize;
2585 	return (error);
2586 }
2587 
2588 #if defined(_SYSCALL32_IMPL) || defined(_ILP32)
2589 /*
2590  * Largefile support for 32 bit applications only.
2591  */
2592 int
2593 sosendfile64(file_t *fp, file_t *rfp, const struct ksendfilevec64 *sfv,
2594     ssize32_t *count32)
2595 {
2596 	ssize32_t sfv_len;
2597 	u_offset_t sfv_off, va_size;
2598 	struct vnode *vp, *fvp, *realvp;
2599 	struct vattr va;
2600 	stdata_t *stp;
2601 	ssize_t count = 0;
2602 	int error = 0;
2603 	boolean_t dozcopy = B_FALSE;
2604 	uint_t maxpsz;
2605 
2606 	sfv_len = (ssize32_t)sfv->sfv_len;
2607 	if (sfv_len < 0) {
2608 		error = EINVAL;
2609 		goto out;
2610 	}
2611 
2612 	if (sfv_len == 0) goto out;
2613 
2614 	sfv_off = (u_offset_t)sfv->sfv_off;
2615 
2616 	/* Same checks as in pread */
2617 	if (sfv_off > MAXOFFSET_T) {
2618 		error = EINVAL;
2619 		goto out;
2620 	}
2621 	if (sfv_off + sfv_len > MAXOFFSET_T)
2622 		sfv_len = (ssize32_t)(MAXOFFSET_T - sfv_off);
2623 
2624 	/*
2625 	 * There are no more checks on sfv_len. So, we cast it to
2626 	 * u_offset_t and share the snf_direct_io/snf_cache code between
2627 	 * 32 bit and 64 bit.
2628 	 *
2629 	 * TODO: should do nbl_need_check() like read()?
2630 	 */
2631 	if (sfv_len > sendfile_max_size) {
2632 		sf_stats.ss_file_not_cached++;
2633 		error = snf_direct_io(fp, rfp, sfv_off, (u_offset_t)sfv_len,
2634 		    &count);
2635 		goto out;
2636 	}
2637 	fvp = rfp->f_vnode;
2638 	if (VOP_REALVP(fvp, &realvp, NULL) == 0)
2639 		fvp = realvp;
2640 	/*
2641 	 * Grab the lock as a reader to prevent the file size
2642 	 * from changing underneath.
2643 	 */
2644 	(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2645 	va.va_mask = AT_SIZE;
2646 	error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2647 	va_size = va.va_size;
2648 	if ((error != 0) || (va_size == 0) || (sfv_off >= va_size)) {
2649 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2650 		goto out;
2651 	}
2652 	/* Read as much as possible. */
2653 	if (sfv_off + sfv_len > va_size)
2654 		sfv_len = va_size - sfv_off;
2655 
2656 	vp = fp->f_vnode;
2657 	stp = vp->v_stream;
2658 	/*
2659 	 * When the NOWAIT flag is not set, we enable zero-copy only if the
2660 	 * transfer size is large enough. This prevents performance loss
2661 	 * when the caller sends the file piece by piece.
2662 	 */
2663 	if (sfv_len >= MAXBSIZE && (sfv_len >= (va_size >> 1) ||
2664 	    (sfv->sfv_flag & SFV_NOWAIT) || sfv_len >= 0x1000000) &&
2665 	    !vn_has_flocks(fvp) && !(fvp->v_flag & VNOMAP)) {
2666 		uint_t copyflag;
2667 		copyflag = stp != NULL ? stp->sd_copyflag :
2668 		    VTOSO(vp)->so_proto_props.sopp_zcopyflag;
2669 		if ((copyflag & (STZCVMSAFE|STZCVMUNSAFE)) == 0) {
2670 			int on = 1;
2671 
2672 			if (socket_setsockopt(VTOSO(vp), SOL_SOCKET,
2673 			    SO_SND_COPYAVOID, &on, sizeof (on), CRED()) == 0)
2674 				dozcopy = B_TRUE;
2675 		} else {
2676 			dozcopy = copyflag & STZCVMSAFE;
2677 		}
2678 	}
2679 	if (dozcopy) {
2680 		sf_stats.ss_file_segmap++;
2681 		error = snf_segmap(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2682 		    &count, ((sfv->sfv_flag & SFV_NOWAIT) != 0));
2683 	} else {
2684 		if (vp->v_type == VSOCK && stp == NULL) {
2685 			sonode_t *so = VTOSO(vp);
2686 			maxpsz = so->so_proto_props.sopp_maxpsz;
2687 		} else if (stp != NULL) {
2688 			maxpsz = stp->sd_qn_maxpsz;
2689 		} else {
2690 			maxpsz = maxphys;
2691 		}
2692 
2693 		if (maxpsz == INFPSZ)
2694 			maxpsz = maxphys;
2695 		else
2696 			maxpsz = roundup(maxpsz, MAXBSIZE);
2697 		sf_stats.ss_file_cached++;
2698 		error = snf_cache(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2699 		    maxpsz, &count);
2700 	}
2701 out:
2702 	releasef(sfv->sfv_fd);
2703 	*count32 = (ssize32_t)count;
2704 	return (error);
2705 }
2706 #endif
2707 
2708 #ifdef _SYSCALL32_IMPL
2709 /*
2710  * recv32(), recvfrom32(), send32(), sendto32(): intentionally return a
2711  * ssize_t rather than ssize32_t; see the comments above read32 for details.
2712  */
2713 
2714 ssize_t
2715 recv32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2716 {
2717 	return (recv(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2718 }
2719 
2720 ssize_t
2721 recvfrom32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2722 	caddr32_t name, caddr32_t namelenp)
2723 {
2724 	return (recvfrom(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2725 	    (void *)(uintptr_t)name, (void *)(uintptr_t)namelenp));
2726 }
2727 
2728 ssize_t
2729 send32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2730 {
2731 	return (send(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2732 }
2733 
2734 ssize_t
2735 sendto32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2736 	caddr32_t name, socklen_t namelen)
2737 {
2738 	return (sendto(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2739 	    (void *)(uintptr_t)name, namelen));
2740 }
2741 #endif	/* _SYSCALL32_IMPL */
2742 
2743 /*
2744  * Function wrappers (mostly around the sonode switch) for
2745  * backward compatibility.
2746  */
2747 
2748 int
2749 soaccept(struct sonode *so, int fflag, struct sonode **nsop)
2750 {
2751 	return (socket_accept(so, fflag, CRED(), nsop));
2752 }
2753 
2754 int
2755 sobind(struct sonode *so, struct sockaddr *name, socklen_t namelen,
2756     int backlog, int flags)
2757 {
2758 	int	error;
2759 
2760 	error = socket_bind(so, name, namelen, flags, CRED());
2761 	if (error == 0 && backlog != 0)
2762 		return (socket_listen(so, backlog, CRED()));
2763 
2764 	return (error);
2765 }
2766 
2767 int
2768 solisten(struct sonode *so, int backlog)
2769 {
2770 	return (socket_listen(so, backlog, CRED()));
2771 }
2772 
2773 int
2774 soconnect(struct sonode *so, const struct sockaddr *name, socklen_t namelen,
2775     int fflag, int flags)
2776 {
2777 	return (socket_connect(so, name, namelen, fflag, flags, CRED()));
2778 }
2779 
2780 int
2781 sorecvmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2782 {
2783 	return (socket_recvmsg(so, msg, uiop, CRED()));
2784 }
2785 
2786 int
2787 sosendmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2788 {
2789 	return (socket_sendmsg(so, msg, uiop, CRED()));
2790 }
2791 
2792 int
2793 soshutdown(struct sonode *so, int how)
2794 {
2795 	return (socket_shutdown(so, how, CRED()));
2796 }
2797 
2798 int
2799 sogetsockopt(struct sonode *so, int level, int option_name, void *optval,
2800     socklen_t *optlenp, int flags)
2801 {
2802 	return (socket_getsockopt(so, level, option_name, optval, optlenp,
2803 	    flags, CRED()));
2804 }
2805 
2806 int
2807 sosetsockopt(struct sonode *so, int level, int option_name, const void *optval,
2808     t_uscalar_t optlen)
2809 {
2810 	return (socket_setsockopt(so, level, option_name, optval, optlen,
2811 	    CRED()));
2812 }
2813 
2814 /*
2815  * Because this is backward compatibility interface it only needs to be
2816  * able to handle the creation of TPI sockfs sockets.
2817  */
2818 struct sonode *
2819 socreate(struct sockparams *sp, int family, int type, int protocol, int version,
2820     int *errorp)
2821 {
2822 	struct sonode *so;
2823 
2824 	ASSERT(sp != NULL);
2825 
2826 	so = sp->sp_smod_info->smod_sock_create_func(sp, family, type, protocol,
2827 	    version, SOCKET_SLEEP, errorp, CRED());
2828 	if (so == NULL) {
2829 		SOCKPARAMS_DEC_REF(sp);
2830 	} else {
2831 		if ((*errorp = SOP_INIT(so, NULL, CRED(), SOCKET_SLEEP)) == 0) {
2832 			/* Cannot fail, only bumps so_count */
2833 			(void) VOP_OPEN(&SOTOV(so), FREAD|FWRITE, CRED(), NULL);
2834 		} else {
2835 			socket_destroy(so);
2836 			so = NULL;
2837 		}
2838 	}
2839 	return (so);
2840 }
2841