xref: /titanic_44/usr/src/uts/common/fs/sockfs/socksyscalls.c (revision 525b892b4871655735786931d81ffcced2641b0d)
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 2010 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 	if (error) {
628 		setf(nfd, NULL);
629 		releasef(sock);
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 		releasef(sock);
656 		return (set_errno(error));
657 	}
658 	if (error = falloc(NULL, FWRITE|FREAD, &nfp, NULL)) {
659 		setf(nfd, NULL);
660 		(void) socket_close(nso, 0, CRED());
661 		socket_destroy(nso);
662 		eprintsoline(so, error);
663 		releasef(sock);
664 		return (set_errno(error));
665 	}
666 	/*
667 	 * fill in the entries that falloc reserved
668 	 */
669 	nfp->f_vnode = nvp;
670 	mutex_exit(&nfp->f_tlock);
671 	setf(nfd, nfp);
672 
673 	/*
674 	 * Copy FNDELAY and FNONBLOCK from listener to acceptor
675 	 */
676 	if (so->so_state & (SS_NDELAY|SS_NONBLOCK)) {
677 		uint_t oflag = nfp->f_flag;
678 		int arg = 0;
679 
680 		if (so->so_state & SS_NONBLOCK)
681 			arg |= FNONBLOCK;
682 		else if (so->so_state & SS_NDELAY)
683 			arg |= FNDELAY;
684 
685 		/*
686 		 * This code is a simplification of the F_SETFL code in fcntl()
687 		 * Ignore any errors from VOP_SETFL.
688 		 */
689 		if ((error = VOP_SETFL(nvp, oflag, arg, nfp->f_cred, NULL))
690 		    != 0) {
691 			eprintsoline(so, error);
692 			error = 0;
693 		} else {
694 			mutex_enter(&nfp->f_tlock);
695 			nfp->f_flag &= ~FMASK | (FREAD|FWRITE);
696 			nfp->f_flag |= arg;
697 			mutex_exit(&nfp->f_tlock);
698 		}
699 	}
700 	releasef(sock);
701 	return (nfd);
702 }
703 
704 int
705 connect(int sock, struct sockaddr *name, socklen_t namelen, int version)
706 {
707 	struct sonode *so;
708 	file_t *fp;
709 	int error;
710 
711 	dprint(1, ("connect(%d, %p, %d)\n",
712 	    sock, (void *)name, namelen));
713 
714 	if ((so = getsonode(sock, &error, &fp)) == NULL)
715 		return (set_errno(error));
716 
717 	/* Allocate and copyin name */
718 	if (namelen != 0) {
719 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
720 		name = copyin_name(so, name, &namelen, &error);
721 		if (name == NULL) {
722 			releasef(sock);
723 			return (set_errno(error));
724 		}
725 	} else
726 		name = NULL;
727 
728 	error = socket_connect(so, name, namelen, fp->f_flag,
729 	    (version != SOV_XPG4_2) ? 0 : _SOCONNECT_XPG4_2, CRED());
730 	releasef(sock);
731 	if (name)
732 		kmem_free(name, (size_t)namelen);
733 	if (error)
734 		return (set_errno(error));
735 	return (0);
736 }
737 
738 /*ARGSUSED2*/
739 int
740 shutdown(int sock, int how, int version)
741 {
742 	struct sonode *so;
743 	int error;
744 
745 	dprint(1, ("shutdown(%d, %d)\n",
746 	    sock, how));
747 
748 	if ((so = getsonode(sock, &error, NULL)) == NULL)
749 		return (set_errno(error));
750 
751 	error = socket_shutdown(so, how, CRED());
752 
753 	releasef(sock);
754 	if (error)
755 		return (set_errno(error));
756 	return (0);
757 }
758 
759 /*
760  * Common receive routine.
761  */
762 static ssize_t
763 recvit(int sock,
764 	struct nmsghdr *msg,
765 	struct uio *uiop,
766 	int flags,
767 	socklen_t *namelenp,
768 	socklen_t *controllenp,
769 	int *flagsp)
770 {
771 	struct sonode *so;
772 	file_t *fp;
773 	void *name;
774 	socklen_t namelen;
775 	void *control;
776 	socklen_t controllen;
777 	ssize_t len;
778 	int error;
779 
780 	if ((so = getsonode(sock, &error, &fp)) == NULL)
781 		return (set_errno(error));
782 
783 	len = uiop->uio_resid;
784 	uiop->uio_fmode = fp->f_flag;
785 	uiop->uio_extflg = UIO_COPY_CACHED;
786 
787 	name = msg->msg_name;
788 	namelen = msg->msg_namelen;
789 	control = msg->msg_control;
790 	controllen = msg->msg_controllen;
791 
792 	msg->msg_flags = flags & (MSG_OOB | MSG_PEEK | MSG_WAITALL |
793 	    MSG_DONTWAIT | MSG_XPG4_2);
794 
795 	error = socket_recvmsg(so, msg, uiop, CRED());
796 	if (error) {
797 		releasef(sock);
798 		return (set_errno(error));
799 	}
800 	lwp_stat_update(LWP_STAT_MSGRCV, 1);
801 	releasef(sock);
802 
803 	error = copyout_name(name, namelen, namelenp,
804 	    msg->msg_name, msg->msg_namelen);
805 	if (error)
806 		goto err;
807 
808 	if (flagsp != NULL) {
809 		/*
810 		 * Clear internal flag.
811 		 */
812 		msg->msg_flags &= ~MSG_XPG4_2;
813 
814 		/*
815 		 * Determine MSG_CTRUNC. sorecvmsg sets MSG_CTRUNC only
816 		 * when controllen is zero and there is control data to
817 		 * copy out.
818 		 */
819 		if (controllen != 0 &&
820 		    (msg->msg_controllen > controllen || control == NULL)) {
821 			dprint(1, ("recvit: CTRUNC %d %d %p\n",
822 			    msg->msg_controllen, controllen, control));
823 
824 			msg->msg_flags |= MSG_CTRUNC;
825 		}
826 		if (copyout(&msg->msg_flags, flagsp,
827 		    sizeof (msg->msg_flags))) {
828 			error = EFAULT;
829 			goto err;
830 		}
831 	}
832 	/*
833 	 * Note: This MUST be done last. There can be no "goto err" after this
834 	 * point since it could make so_closefds run twice on some part
835 	 * of the file descriptor array.
836 	 */
837 	if (controllen != 0) {
838 		if (!(flags & MSG_XPG4_2)) {
839 			/*
840 			 * Good old msg_accrights can only return a multiple
841 			 * of 4 bytes.
842 			 */
843 			controllen &= ~((int)sizeof (uint32_t) - 1);
844 		}
845 		error = copyout_arg(control, controllen, controllenp,
846 		    msg->msg_control, msg->msg_controllen);
847 		if (error)
848 			goto err;
849 
850 		if (msg->msg_controllen > controllen || control == NULL) {
851 			if (control == NULL)
852 				controllen = 0;
853 			so_closefds(msg->msg_control, msg->msg_controllen,
854 			    !(flags & MSG_XPG4_2), controllen);
855 		}
856 	}
857 	if (msg->msg_namelen != 0)
858 		kmem_free(msg->msg_name, (size_t)msg->msg_namelen);
859 	if (msg->msg_controllen != 0)
860 		kmem_free(msg->msg_control, (size_t)msg->msg_controllen);
861 	return (len - uiop->uio_resid);
862 
863 err:
864 	/*
865 	 * If we fail and the control part contains file descriptors
866 	 * we have to close the fd's.
867 	 */
868 	if (msg->msg_controllen != 0)
869 		so_closefds(msg->msg_control, msg->msg_controllen,
870 		    !(flags & MSG_XPG4_2), 0);
871 	if (msg->msg_namelen != 0)
872 		kmem_free(msg->msg_name, (size_t)msg->msg_namelen);
873 	if (msg->msg_controllen != 0)
874 		kmem_free(msg->msg_control, (size_t)msg->msg_controllen);
875 	return (set_errno(error));
876 }
877 
878 /*
879  * Native system call
880  */
881 ssize_t
882 recv(int sock, void *buffer, size_t len, int flags)
883 {
884 	struct nmsghdr lmsg;
885 	struct uio auio;
886 	struct iovec aiov[1];
887 
888 	dprint(1, ("recv(%d, %p, %ld, %d)\n",
889 	    sock, buffer, len, flags));
890 
891 	if ((ssize_t)len < 0) {
892 		return (set_errno(EINVAL));
893 	}
894 
895 	aiov[0].iov_base = buffer;
896 	aiov[0].iov_len = len;
897 	auio.uio_loffset = 0;
898 	auio.uio_iov = aiov;
899 	auio.uio_iovcnt = 1;
900 	auio.uio_resid = len;
901 	auio.uio_segflg = UIO_USERSPACE;
902 	auio.uio_limit = 0;
903 
904 	lmsg.msg_namelen = 0;
905 	lmsg.msg_controllen = 0;
906 	lmsg.msg_flags = 0;
907 	return (recvit(sock, &lmsg, &auio, flags, NULL, NULL, NULL));
908 }
909 
910 ssize_t
911 recvfrom(int sock, void *buffer, size_t len, int flags,
912 	struct sockaddr *name, socklen_t *namelenp)
913 {
914 	struct nmsghdr lmsg;
915 	struct uio auio;
916 	struct iovec aiov[1];
917 
918 	dprint(1, ("recvfrom(%d, %p, %ld, %d, %p, %p)\n",
919 	    sock, buffer, len, flags, (void *)name, (void *)namelenp));
920 
921 	if ((ssize_t)len < 0) {
922 		return (set_errno(EINVAL));
923 	}
924 
925 	aiov[0].iov_base = buffer;
926 	aiov[0].iov_len = len;
927 	auio.uio_loffset = 0;
928 	auio.uio_iov = aiov;
929 	auio.uio_iovcnt = 1;
930 	auio.uio_resid = len;
931 	auio.uio_segflg = UIO_USERSPACE;
932 	auio.uio_limit = 0;
933 
934 	lmsg.msg_name = (char *)name;
935 	if (namelenp != NULL) {
936 		if (copyin(namelenp, &lmsg.msg_namelen,
937 		    sizeof (lmsg.msg_namelen)))
938 			return (set_errno(EFAULT));
939 	} else {
940 		lmsg.msg_namelen = 0;
941 	}
942 	lmsg.msg_controllen = 0;
943 	lmsg.msg_flags = 0;
944 
945 	return (recvit(sock, &lmsg, &auio, flags, namelenp, NULL, NULL));
946 }
947 
948 /*
949  * Uses the MSG_XPG4_2 flag to determine if the caller is using
950  * struct omsghdr or struct nmsghdr.
951  */
952 ssize_t
953 recvmsg(int sock, struct nmsghdr *msg, int flags)
954 {
955 	STRUCT_DECL(nmsghdr, u_lmsg);
956 	STRUCT_HANDLE(nmsghdr, umsgptr);
957 	struct nmsghdr lmsg;
958 	struct uio auio;
959 	struct iovec aiov[MSG_MAXIOVLEN];
960 	int iovcnt;
961 	ssize_t len;
962 	int i;
963 	int *flagsp;
964 	model_t	model;
965 
966 	dprint(1, ("recvmsg(%d, %p, %d)\n",
967 	    sock, (void *)msg, flags));
968 
969 	model = get_udatamodel();
970 	STRUCT_INIT(u_lmsg, model);
971 	STRUCT_SET_HANDLE(umsgptr, model, msg);
972 
973 	if (flags & MSG_XPG4_2) {
974 		if (copyin(msg, STRUCT_BUF(u_lmsg), STRUCT_SIZE(u_lmsg)))
975 			return (set_errno(EFAULT));
976 		flagsp = STRUCT_FADDR(umsgptr, msg_flags);
977 	} else {
978 		/*
979 		 * Assumes that nmsghdr and omsghdr are identically shaped
980 		 * except for the added msg_flags field.
981 		 */
982 		if (copyin(msg, STRUCT_BUF(u_lmsg),
983 		    SIZEOF_STRUCT(omsghdr, model)))
984 			return (set_errno(EFAULT));
985 		STRUCT_FSET(u_lmsg, msg_flags, 0);
986 		flagsp = NULL;
987 	}
988 
989 	/*
990 	 * Code below us will kmem_alloc memory and hang it
991 	 * off msg_control and msg_name fields. This forces
992 	 * us to copy the structure to its native form.
993 	 */
994 	lmsg.msg_name = STRUCT_FGETP(u_lmsg, msg_name);
995 	lmsg.msg_namelen = STRUCT_FGET(u_lmsg, msg_namelen);
996 	lmsg.msg_iov = STRUCT_FGETP(u_lmsg, msg_iov);
997 	lmsg.msg_iovlen = STRUCT_FGET(u_lmsg, msg_iovlen);
998 	lmsg.msg_control = STRUCT_FGETP(u_lmsg, msg_control);
999 	lmsg.msg_controllen = STRUCT_FGET(u_lmsg, msg_controllen);
1000 	lmsg.msg_flags = STRUCT_FGET(u_lmsg, msg_flags);
1001 
1002 	iovcnt = lmsg.msg_iovlen;
1003 
1004 	if (iovcnt <= 0 || iovcnt > MSG_MAXIOVLEN) {
1005 		return (set_errno(EMSGSIZE));
1006 	}
1007 
1008 #ifdef _SYSCALL32_IMPL
1009 	/*
1010 	 * 32-bit callers need to have their iovec expanded, while ensuring
1011 	 * that they can't move more than 2Gbytes of data in a single call.
1012 	 */
1013 	if (model == DATAMODEL_ILP32) {
1014 		struct iovec32 aiov32[MSG_MAXIOVLEN];
1015 		ssize32_t count32;
1016 
1017 		if (copyin((struct iovec32 *)lmsg.msg_iov, aiov32,
1018 		    iovcnt * sizeof (struct iovec32)))
1019 			return (set_errno(EFAULT));
1020 
1021 		count32 = 0;
1022 		for (i = 0; i < iovcnt; i++) {
1023 			ssize32_t iovlen32;
1024 
1025 			iovlen32 = aiov32[i].iov_len;
1026 			count32 += iovlen32;
1027 			if (iovlen32 < 0 || count32 < 0)
1028 				return (set_errno(EINVAL));
1029 			aiov[i].iov_len = iovlen32;
1030 			aiov[i].iov_base =
1031 			    (caddr_t)(uintptr_t)aiov32[i].iov_base;
1032 		}
1033 	} else
1034 #endif /* _SYSCALL32_IMPL */
1035 	if (copyin(lmsg.msg_iov, aiov, iovcnt * sizeof (struct iovec))) {
1036 		return (set_errno(EFAULT));
1037 	}
1038 	len = 0;
1039 	for (i = 0; i < iovcnt; i++) {
1040 		ssize_t iovlen = aiov[i].iov_len;
1041 		len += iovlen;
1042 		if (iovlen < 0 || len < 0) {
1043 			return (set_errno(EINVAL));
1044 		}
1045 	}
1046 	auio.uio_loffset = 0;
1047 	auio.uio_iov = aiov;
1048 	auio.uio_iovcnt = iovcnt;
1049 	auio.uio_resid = len;
1050 	auio.uio_segflg = UIO_USERSPACE;
1051 	auio.uio_limit = 0;
1052 
1053 	if (lmsg.msg_control != NULL &&
1054 	    (do_useracc == 0 ||
1055 	    useracc(lmsg.msg_control, lmsg.msg_controllen,
1056 	    B_WRITE) != 0)) {
1057 		return (set_errno(EFAULT));
1058 	}
1059 
1060 	return (recvit(sock, &lmsg, &auio, flags,
1061 	    STRUCT_FADDR(umsgptr, msg_namelen),
1062 	    STRUCT_FADDR(umsgptr, msg_controllen), flagsp));
1063 }
1064 
1065 /*
1066  * Common send function.
1067  */
1068 static ssize_t
1069 sendit(int sock, struct nmsghdr *msg, struct uio *uiop, int flags)
1070 {
1071 	struct sonode *so;
1072 	file_t *fp;
1073 	void *name;
1074 	socklen_t namelen;
1075 	void *control;
1076 	socklen_t controllen;
1077 	ssize_t len;
1078 	int error;
1079 
1080 	if ((so = getsonode(sock, &error, &fp)) == NULL)
1081 		return (set_errno(error));
1082 
1083 	uiop->uio_fmode = fp->f_flag;
1084 
1085 	if (so->so_family == AF_UNIX)
1086 		uiop->uio_extflg = UIO_COPY_CACHED;
1087 	else
1088 		uiop->uio_extflg = UIO_COPY_DEFAULT;
1089 
1090 	/* Allocate and copyin name and control */
1091 	name = msg->msg_name;
1092 	namelen = msg->msg_namelen;
1093 	if (name != NULL && namelen != 0) {
1094 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1095 		name = copyin_name(so,
1096 		    (struct sockaddr *)name,
1097 		    &namelen, &error);
1098 		if (name == NULL)
1099 			goto done3;
1100 		/* copyin_name null terminates addresses for AF_UNIX */
1101 		msg->msg_namelen = namelen;
1102 		msg->msg_name = name;
1103 	} else {
1104 		msg->msg_name = name = NULL;
1105 		msg->msg_namelen = namelen = 0;
1106 	}
1107 
1108 	control = msg->msg_control;
1109 	controllen = msg->msg_controllen;
1110 	if ((control != NULL) && (controllen != 0)) {
1111 		/*
1112 		 * Verify that the length is not excessive to prevent
1113 		 * an application from consuming all of kernel memory.
1114 		 */
1115 		if (controllen > SO_MAXARGSIZE) {
1116 			error = EINVAL;
1117 			goto done2;
1118 		}
1119 		control = kmem_alloc(controllen, KM_SLEEP);
1120 
1121 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1122 		if (copyin(msg->msg_control, control, controllen)) {
1123 			error = EFAULT;
1124 			goto done1;
1125 		}
1126 		msg->msg_control = control;
1127 	} else {
1128 		msg->msg_control = control = NULL;
1129 		msg->msg_controllen = controllen = 0;
1130 	}
1131 
1132 	len = uiop->uio_resid;
1133 	msg->msg_flags = flags;
1134 
1135 	error = socket_sendmsg(so, msg, uiop, CRED());
1136 done1:
1137 	if (control != NULL)
1138 		kmem_free(control, controllen);
1139 done2:
1140 	if (name != NULL)
1141 		kmem_free(name, namelen);
1142 done3:
1143 	if (error != 0) {
1144 		releasef(sock);
1145 		return (set_errno(error));
1146 	}
1147 	lwp_stat_update(LWP_STAT_MSGSND, 1);
1148 	releasef(sock);
1149 	return (len - uiop->uio_resid);
1150 }
1151 
1152 /*
1153  * Native system call
1154  */
1155 ssize_t
1156 send(int sock, void *buffer, size_t len, int flags)
1157 {
1158 	struct nmsghdr lmsg;
1159 	struct uio auio;
1160 	struct iovec aiov[1];
1161 
1162 	dprint(1, ("send(%d, %p, %ld, %d)\n",
1163 	    sock, buffer, len, flags));
1164 
1165 	if ((ssize_t)len < 0) {
1166 		return (set_errno(EINVAL));
1167 	}
1168 
1169 	aiov[0].iov_base = buffer;
1170 	aiov[0].iov_len = len;
1171 	auio.uio_loffset = 0;
1172 	auio.uio_iov = aiov;
1173 	auio.uio_iovcnt = 1;
1174 	auio.uio_resid = len;
1175 	auio.uio_segflg = UIO_USERSPACE;
1176 	auio.uio_limit = 0;
1177 
1178 	lmsg.msg_name = NULL;
1179 	lmsg.msg_control = NULL;
1180 	if (!(flags & MSG_XPG4_2)) {
1181 		/*
1182 		 * In order to be compatible with the libsocket/sockmod
1183 		 * implementation we set EOR for all send* calls.
1184 		 */
1185 		flags |= MSG_EOR;
1186 	}
1187 	return (sendit(sock, &lmsg, &auio, flags));
1188 }
1189 
1190 /*
1191  * Uses the MSG_XPG4_2 flag to determine if the caller is using
1192  * struct omsghdr or struct nmsghdr.
1193  */
1194 ssize_t
1195 sendmsg(int sock, struct nmsghdr *msg, int flags)
1196 {
1197 	struct nmsghdr lmsg;
1198 	STRUCT_DECL(nmsghdr, u_lmsg);
1199 	struct uio auio;
1200 	struct iovec aiov[MSG_MAXIOVLEN];
1201 	int iovcnt;
1202 	ssize_t len;
1203 	int i;
1204 	model_t	model;
1205 
1206 	dprint(1, ("sendmsg(%d, %p, %d)\n", sock, (void *)msg, flags));
1207 
1208 	model = get_udatamodel();
1209 	STRUCT_INIT(u_lmsg, model);
1210 
1211 	if (flags & MSG_XPG4_2) {
1212 		if (copyin(msg, (char *)STRUCT_BUF(u_lmsg),
1213 		    STRUCT_SIZE(u_lmsg)))
1214 			return (set_errno(EFAULT));
1215 	} else {
1216 		/*
1217 		 * Assumes that nmsghdr and omsghdr are identically shaped
1218 		 * except for the added msg_flags field.
1219 		 */
1220 		if (copyin(msg, (char *)STRUCT_BUF(u_lmsg),
1221 		    SIZEOF_STRUCT(omsghdr, model)))
1222 			return (set_errno(EFAULT));
1223 		/*
1224 		 * In order to be compatible with the libsocket/sockmod
1225 		 * implementation we set EOR for all send* calls.
1226 		 */
1227 		flags |= MSG_EOR;
1228 	}
1229 
1230 	/*
1231 	 * Code below us will kmem_alloc memory and hang it
1232 	 * off msg_control and msg_name fields. This forces
1233 	 * us to copy the structure to its native form.
1234 	 */
1235 	lmsg.msg_name = STRUCT_FGETP(u_lmsg, msg_name);
1236 	lmsg.msg_namelen = STRUCT_FGET(u_lmsg, msg_namelen);
1237 	lmsg.msg_iov = STRUCT_FGETP(u_lmsg, msg_iov);
1238 	lmsg.msg_iovlen = STRUCT_FGET(u_lmsg, msg_iovlen);
1239 	lmsg.msg_control = STRUCT_FGETP(u_lmsg, msg_control);
1240 	lmsg.msg_controllen = STRUCT_FGET(u_lmsg, msg_controllen);
1241 	lmsg.msg_flags = STRUCT_FGET(u_lmsg, msg_flags);
1242 
1243 	iovcnt = lmsg.msg_iovlen;
1244 
1245 	if (iovcnt <= 0 || iovcnt > MSG_MAXIOVLEN) {
1246 		/*
1247 		 * Unless this is XPG 4.2 we allow iovcnt == 0 to
1248 		 * be compatible with SunOS 4.X and 4.4BSD.
1249 		 */
1250 		if (iovcnt != 0 || (flags & MSG_XPG4_2))
1251 			return (set_errno(EMSGSIZE));
1252 	}
1253 
1254 #ifdef _SYSCALL32_IMPL
1255 	/*
1256 	 * 32-bit callers need to have their iovec expanded, while ensuring
1257 	 * that they can't move more than 2Gbytes of data in a single call.
1258 	 */
1259 	if (model == DATAMODEL_ILP32) {
1260 		struct iovec32 aiov32[MSG_MAXIOVLEN];
1261 		ssize32_t count32;
1262 
1263 		if (iovcnt != 0 &&
1264 		    copyin((struct iovec32 *)lmsg.msg_iov, aiov32,
1265 		    iovcnt * sizeof (struct iovec32)))
1266 			return (set_errno(EFAULT));
1267 
1268 		count32 = 0;
1269 		for (i = 0; i < iovcnt; i++) {
1270 			ssize32_t iovlen32;
1271 
1272 			iovlen32 = aiov32[i].iov_len;
1273 			count32 += iovlen32;
1274 			if (iovlen32 < 0 || count32 < 0)
1275 				return (set_errno(EINVAL));
1276 			aiov[i].iov_len = iovlen32;
1277 			aiov[i].iov_base =
1278 			    (caddr_t)(uintptr_t)aiov32[i].iov_base;
1279 		}
1280 	} else
1281 #endif /* _SYSCALL32_IMPL */
1282 	if (iovcnt != 0 &&
1283 	    copyin(lmsg.msg_iov, aiov,
1284 	    (unsigned)iovcnt * sizeof (struct iovec))) {
1285 		return (set_errno(EFAULT));
1286 	}
1287 	len = 0;
1288 	for (i = 0; i < iovcnt; i++) {
1289 		ssize_t iovlen = aiov[i].iov_len;
1290 		len += iovlen;
1291 		if (iovlen < 0 || len < 0) {
1292 			return (set_errno(EINVAL));
1293 		}
1294 	}
1295 	auio.uio_loffset = 0;
1296 	auio.uio_iov = aiov;
1297 	auio.uio_iovcnt = iovcnt;
1298 	auio.uio_resid = len;
1299 	auio.uio_segflg = UIO_USERSPACE;
1300 	auio.uio_limit = 0;
1301 
1302 	return (sendit(sock, &lmsg, &auio, flags));
1303 }
1304 
1305 ssize_t
1306 sendto(int sock, void *buffer, size_t len, int flags,
1307     struct sockaddr *name, socklen_t namelen)
1308 {
1309 	struct nmsghdr lmsg;
1310 	struct uio auio;
1311 	struct iovec aiov[1];
1312 
1313 	dprint(1, ("sendto(%d, %p, %ld, %d, %p, %d)\n",
1314 	    sock, buffer, len, flags, (void *)name, namelen));
1315 
1316 	if ((ssize_t)len < 0) {
1317 		return (set_errno(EINVAL));
1318 	}
1319 
1320 	aiov[0].iov_base = buffer;
1321 	aiov[0].iov_len = len;
1322 	auio.uio_loffset = 0;
1323 	auio.uio_iov = aiov;
1324 	auio.uio_iovcnt = 1;
1325 	auio.uio_resid = len;
1326 	auio.uio_segflg = UIO_USERSPACE;
1327 	auio.uio_limit = 0;
1328 
1329 	lmsg.msg_name = (char *)name;
1330 	lmsg.msg_namelen = namelen;
1331 	lmsg.msg_control = NULL;
1332 	if (!(flags & MSG_XPG4_2)) {
1333 		/*
1334 		 * In order to be compatible with the libsocket/sockmod
1335 		 * implementation we set EOR for all send* calls.
1336 		 */
1337 		flags |= MSG_EOR;
1338 	}
1339 	return (sendit(sock, &lmsg, &auio, flags));
1340 }
1341 
1342 /*ARGSUSED3*/
1343 int
1344 getpeername(int sock, struct sockaddr *name, socklen_t *namelenp, int version)
1345 {
1346 	struct sonode *so;
1347 	int error;
1348 	socklen_t namelen;
1349 	socklen_t sock_addrlen;
1350 	struct sockaddr *sock_addrp;
1351 
1352 	dprint(1, ("getpeername(%d, %p, %p)\n",
1353 	    sock, (void *)name, (void *)namelenp));
1354 
1355 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1356 		goto bad;
1357 
1358 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1359 	if (copyin(namelenp, &namelen, sizeof (namelen)) ||
1360 	    (name == NULL && namelen != 0)) {
1361 		error = EFAULT;
1362 		goto rel_out;
1363 	}
1364 	sock_addrlen = so->so_max_addr_len;
1365 	sock_addrp = (struct sockaddr *)kmem_alloc(sock_addrlen, KM_SLEEP);
1366 
1367 	if ((error = socket_getpeername(so, sock_addrp, &sock_addrlen,
1368 	    B_FALSE, CRED())) == 0) {
1369 		ASSERT(sock_addrlen <= so->so_max_addr_len);
1370 		error = copyout_name(name, namelen, namelenp,
1371 		    (void *)sock_addrp, sock_addrlen);
1372 	}
1373 	kmem_free(sock_addrp, so->so_max_addr_len);
1374 rel_out:
1375 	releasef(sock);
1376 bad:	return (error != 0 ? set_errno(error) : 0);
1377 }
1378 
1379 /*ARGSUSED3*/
1380 int
1381 getsockname(int sock, struct sockaddr *name,
1382 		socklen_t *namelenp, int version)
1383 {
1384 	struct sonode *so;
1385 	int error;
1386 	socklen_t namelen, sock_addrlen;
1387 	struct sockaddr *sock_addrp;
1388 
1389 	dprint(1, ("getsockname(%d, %p, %p)\n",
1390 	    sock, (void *)name, (void *)namelenp));
1391 
1392 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1393 		goto bad;
1394 
1395 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1396 	if (copyin(namelenp, &namelen, sizeof (namelen)) ||
1397 	    (name == NULL && namelen != 0)) {
1398 		error = EFAULT;
1399 		goto rel_out;
1400 	}
1401 
1402 	sock_addrlen = so->so_max_addr_len;
1403 	sock_addrp = (struct sockaddr *)kmem_alloc(sock_addrlen, KM_SLEEP);
1404 	if ((error = socket_getsockname(so, sock_addrp, &sock_addrlen,
1405 	    CRED())) == 0) {
1406 		ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1407 		ASSERT(sock_addrlen <= so->so_max_addr_len);
1408 		error = copyout_name(name, namelen, namelenp,
1409 		    (void *)sock_addrp, sock_addrlen);
1410 	}
1411 	kmem_free(sock_addrp, so->so_max_addr_len);
1412 rel_out:
1413 	releasef(sock);
1414 bad:	return (error != 0 ? set_errno(error) : 0);
1415 }
1416 
1417 /*ARGSUSED5*/
1418 int
1419 getsockopt(int sock,
1420 	int level,
1421 	int option_name,
1422 	void *option_value,
1423 	socklen_t *option_lenp,
1424 	int version)
1425 {
1426 	struct sonode *so;
1427 	socklen_t optlen, optlen_res;
1428 	void *optval;
1429 	int error;
1430 
1431 	dprint(1, ("getsockopt(%d, %d, %d, %p, %p)\n",
1432 	    sock, level, option_name, option_value, (void *)option_lenp));
1433 
1434 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1435 		return (set_errno(error));
1436 
1437 	ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1438 	if (copyin(option_lenp, &optlen, sizeof (optlen))) {
1439 		releasef(sock);
1440 		return (set_errno(EFAULT));
1441 	}
1442 	/*
1443 	 * Verify that the length is not excessive to prevent
1444 	 * an application from consuming all of kernel memory.
1445 	 */
1446 	if (optlen > SO_MAXARGSIZE) {
1447 		error = EINVAL;
1448 		releasef(sock);
1449 		return (set_errno(error));
1450 	}
1451 	optval = kmem_alloc(optlen, KM_SLEEP);
1452 	optlen_res = optlen;
1453 	error = socket_getsockopt(so, level, option_name, optval,
1454 	    &optlen_res, (version != SOV_XPG4_2) ? 0 : _SOGETSOCKOPT_XPG4_2,
1455 	    CRED());
1456 	releasef(sock);
1457 	if (error) {
1458 		kmem_free(optval, optlen);
1459 		return (set_errno(error));
1460 	}
1461 	error = copyout_arg(option_value, optlen, option_lenp,
1462 	    optval, optlen_res);
1463 	kmem_free(optval, optlen);
1464 	if (error)
1465 		return (set_errno(error));
1466 	return (0);
1467 }
1468 
1469 /*ARGSUSED5*/
1470 int
1471 setsockopt(int sock,
1472 	int level,
1473 	int option_name,
1474 	void *option_value,
1475 	socklen_t option_len,
1476 	int version)
1477 {
1478 	struct sonode *so;
1479 	intptr_t buffer[2];
1480 	void *optval = NULL;
1481 	int error;
1482 
1483 	dprint(1, ("setsockopt(%d, %d, %d, %p, %d)\n",
1484 	    sock, level, option_name, option_value, option_len));
1485 
1486 	if ((so = getsonode(sock, &error, NULL)) == NULL)
1487 		return (set_errno(error));
1488 
1489 	if (option_value != NULL) {
1490 		if (option_len != 0) {
1491 			/*
1492 			 * Verify that the length is not excessive to prevent
1493 			 * an application from consuming all of kernel memory.
1494 			 */
1495 			if (option_len > SO_MAXARGSIZE) {
1496 				error = EINVAL;
1497 				goto done2;
1498 			}
1499 			optval = option_len <= sizeof (buffer) ?
1500 			    &buffer : kmem_alloc((size_t)option_len, KM_SLEEP);
1501 			ASSERT(MUTEX_NOT_HELD(&so->so_lock));
1502 			if (copyin(option_value, optval, (size_t)option_len)) {
1503 				error = EFAULT;
1504 				goto done1;
1505 			}
1506 		}
1507 	} else
1508 		option_len = 0;
1509 
1510 	error = socket_setsockopt(so, level, option_name, optval,
1511 	    (t_uscalar_t)option_len, CRED());
1512 done1:
1513 	if (optval != buffer)
1514 		kmem_free(optval, (size_t)option_len);
1515 done2:
1516 	releasef(sock);
1517 	if (error)
1518 		return (set_errno(error));
1519 	return (0);
1520 }
1521 
1522 /*
1523  * Add config info when name is non-NULL; delete info when name is NULL.
1524  * name could be a device name or a module name and are user address.
1525  */
1526 int
1527 sockconfig(int family, int type, int protocol, char *name)
1528 {
1529 	char *kdevpath = NULL;		/* Copied in devpath string */
1530 	char *kmodule = NULL;
1531 	size_t pathlen = 0;
1532 	int error = 0;
1533 
1534 	dprint(1, ("sockconfig(%d, %d, %d, %p)\n",
1535 	    family, type, protocol, (void *)name));
1536 
1537 	if (secpolicy_net_config(CRED(), B_FALSE) != 0)
1538 		return (set_errno(EPERM));
1539 
1540 	/*
1541 	 * By default set the kdevpath and kmodule to NULL to delete an entry.
1542 	 * Otherwise when name is not NULL, set the kdevpath or kmodule
1543 	 * value to add an entry.
1544 	 */
1545 	if (name != NULL) {
1546 		/*
1547 		 * Adding an entry.
1548 		 * Copyin the name.
1549 		 * This also makes it possible to check for too long pathnames.
1550 		 * Compress the space needed for the name before passing it
1551 		 * to soconfig - soconfig will store the string until
1552 		 * the configuration is removed.
1553 		 */
1554 		char *buf;
1555 		buf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1556 		if ((error = copyinstr(name, buf, MAXPATHLEN, &pathlen)) != 0) {
1557 			kmem_free(buf, MAXPATHLEN);
1558 			goto done;
1559 		}
1560 		if (strncmp(buf, "/dev", strlen("/dev")) == 0) {
1561 			/* For device */
1562 
1563 			/*
1564 			 * Special handling for NCA:
1565 			 *
1566 			 * DEV_NCA is never opened even if an application
1567 			 * requests for AF_NCA. The device opened is instead a
1568 			 * predefined AF_INET transport (NCA_INET_DEV).
1569 			 *
1570 			 * Prior to Volo (PSARC/2007/587) NCA would determine
1571 			 * the device using a lookup, which worked then because
1572 			 * all protocols were based on TPI. Since TPI is no
1573 			 * longer the default, we have to explicitly state
1574 			 * which device to use.
1575 			 */
1576 			if (strcmp(buf, NCA_DEV) == 0) {
1577 				/* only support entry <28, 2, 0> */
1578 				if (family != AF_NCA || type != SOCK_STREAM ||
1579 				    protocol != 0) {
1580 					kmem_free(buf, MAXPATHLEN);
1581 					error = EINVAL;
1582 					goto done;
1583 				}
1584 
1585 				pathlen = strlen(NCA_INET_DEV) + 1;
1586 				kdevpath = kmem_alloc(pathlen, KM_SLEEP);
1587 				bcopy(NCA_INET_DEV, kdevpath, pathlen);
1588 				kdevpath[pathlen - 1] = '\0';
1589 			} else {
1590 				kdevpath = kmem_alloc(pathlen, KM_SLEEP);
1591 				bcopy(buf, kdevpath, pathlen);
1592 				kdevpath[pathlen - 1] = '\0';
1593 			}
1594 		} else {
1595 			/* For socket module */
1596 			kmodule = kmem_alloc(pathlen, KM_SLEEP);
1597 			bcopy(buf, kmodule, pathlen);
1598 			kmodule[pathlen - 1] = '\0';
1599 
1600 			pathlen = 0;
1601 			if (strcmp(kmodule, "tcp") == 0) {
1602 				/* Get the tcp device name for fallback */
1603 				if (family == 2) {
1604 					pathlen = strlen("/dev/tcp") + 1;
1605 					kdevpath = kmem_alloc(pathlen,
1606 					    KM_SLEEP);
1607 					bcopy("/dev/tcp", kdevpath,
1608 					    pathlen);
1609 					kdevpath[pathlen - 1] = '\0';
1610 				} else {
1611 					ASSERT(family == 26);
1612 					pathlen = strlen("/dev/tcp6") + 1;
1613 					kdevpath = kmem_alloc(pathlen,
1614 					    KM_SLEEP);
1615 					bcopy("/dev/tcp6", kdevpath, pathlen);
1616 					kdevpath[pathlen - 1] = '\0';
1617 				}
1618 			} else if (strcmp(kmodule, "udp") == 0) {
1619 				/* Get the udp device name for fallback */
1620 				if (family == 2) {
1621 					pathlen = strlen("/dev/udp") + 1;
1622 					kdevpath = kmem_alloc(pathlen,
1623 					    KM_SLEEP);
1624 					bcopy("/dev/udp", kdevpath, pathlen);
1625 					kdevpath[pathlen - 1] = '\0';
1626 				} else {
1627 					ASSERT(family == 26);
1628 					pathlen = strlen("/dev/udp6") + 1;
1629 					kdevpath = kmem_alloc(pathlen,
1630 					    KM_SLEEP);
1631 					bcopy("/dev/udp6", kdevpath, pathlen);
1632 					kdevpath[pathlen - 1] = '\0';
1633 				}
1634 			} else if (strcmp(kmodule, "icmp") == 0) {
1635 				/* Get the icmp device name for fallback */
1636 				if (family == 2) {
1637 					pathlen = strlen("/dev/rawip") + 1;
1638 					kdevpath = kmem_alloc(pathlen,
1639 					    KM_SLEEP);
1640 					bcopy("/dev/rawip", kdevpath, pathlen);
1641 					kdevpath[pathlen - 1] = '\0';
1642 				} else {
1643 					ASSERT(family == 26);
1644 					pathlen = strlen("/dev/rawip6") + 1;
1645 					kdevpath = kmem_alloc(pathlen,
1646 					    KM_SLEEP);
1647 					bcopy("/dev/rawip6", kdevpath, pathlen);
1648 					kdevpath[pathlen - 1] = '\0';
1649 				}
1650 			}
1651 		}
1652 
1653 		kmem_free(buf, MAXPATHLEN);
1654 	}
1655 	error = soconfig(family, type, protocol, kdevpath, (int)pathlen,
1656 	    kmodule);
1657 done:
1658 	if (error) {
1659 		eprintline(error);
1660 		return (set_errno(error));
1661 	}
1662 	return (0);
1663 }
1664 
1665 
1666 /*
1667  * Sendfile is implemented through two schemes, direct I/O or by
1668  * caching in the filesystem page cache. We cache the input file by
1669  * default and use direct I/O only if sendfile_max_size is set
1670  * appropriately as explained below. Note that this logic is consistent
1671  * with other filesystems where caching is turned on by default
1672  * unless explicitly turned off by using the DIRECTIO ioctl.
1673  *
1674  * We choose a slightly different scheme here. One can turn off
1675  * caching by setting sendfile_max_size to 0. One can also enable
1676  * caching of files <= sendfile_max_size by setting sendfile_max_size
1677  * to an appropriate value. By default sendfile_max_size is set to the
1678  * maximum value so that all files are cached. In future, we may provide
1679  * better interfaces for caching the file.
1680  *
1681  * Sendfile through Direct I/O (Zero copy)
1682  * --------------------------------------
1683  *
1684  * As disks are normally slower than the network, we can't have a
1685  * single thread that reads the disk and writes to the network. We
1686  * need to have parallelism. This is done by having the sendfile
1687  * thread create another thread that reads from the filesystem
1688  * and queues it for network processing. In this scheme, the data
1689  * is never copied anywhere i.e it is zero copy unlike the other
1690  * scheme.
1691  *
1692  * We have a sendfile queue (snfq) where each sendfile
1693  * request (snf_req_t) is queued for processing by a thread. Number
1694  * of threads is dynamically allocated and they exit if they are idling
1695  * beyond a specified amount of time. When each request (snf_req_t) is
1696  * processed by a thread, it produces a number of mblk_t structures to
1697  * be consumed by the sendfile thread. snf_deque and snf_enque are
1698  * used for consuming and producing mblks. Size of the filesystem
1699  * read is determined by the tunable (sendfile_read_size). A single
1700  * mblk holds sendfile_read_size worth of data (except the last
1701  * read of the file) which is sent down as a whole to the network.
1702  * sendfile_read_size is set to 1 MB as this seems to be the optimal
1703  * value for the UFS filesystem backed by a striped storage array.
1704  *
1705  * Synchronisation between read (producer) and write (consumer) threads.
1706  * --------------------------------------------------------------------
1707  *
1708  * sr_lock protects sr_ib_head and sr_ib_tail. The lock is held while
1709  * adding and deleting items in this list. Error can happen anytime
1710  * during read or write. There could be unprocessed mblks in the
1711  * sr_ib_XXX list when a read or write error occurs. Whenever error
1712  * is encountered, we need two things to happen :
1713  *
1714  * a) One of the threads need to clean the mblks.
1715  * b) When one thread encounters an error, the other should stop.
1716  *
1717  * For (a), we don't want to penalize the reader thread as it could do
1718  * some useful work processing other requests. For (b), the error can
1719  * be detected by examining sr_read_error or sr_write_error.
1720  * sr_lock protects sr_read_error and sr_write_error. If both reader and
1721  * writer encounters error, we need to report the write error back to
1722  * the application as that's what would have happened if the operations
1723  * were done sequentially. With this in mind, following should work :
1724  *
1725  * 	- Check for errors before read or write.
1726  *	- If the reader encounters error, set the error in sr_read_error.
1727  *	  Check sr_write_error, if it is set, send cv_signal as it is
1728  *	  waiting for reader to complete. If it is not set, the writer
1729  *	  is either running sinking data to the network or blocked
1730  *        because of flow control. For handling the latter case, we
1731  *	  always send a signal. In any case, it will examine sr_read_error
1732  *	  and return. sr_read_error is marked with SR_READ_DONE to tell
1733  *	  the writer that the reader is done in all the cases.
1734  *	- If the writer encounters error, set the error in sr_write_error.
1735  *	  The reader thread is either blocked because of flow control or
1736  *	  running reading data from the disk. For the former, we need to
1737  *	  wakeup the thread. Again to keep it simple, we always wake up
1738  *	  the reader thread. Then, wait for the read thread to complete
1739  *	  if it is not done yet. Cleanup and return.
1740  *
1741  * High and low water marks for the read thread.
1742  * --------------------------------------------
1743  *
1744  * If sendfile() is used to send data over a slow network, we need to
1745  * make sure that the read thread does not produce data at a faster
1746  * rate than the network. This can happen if the disk is faster than
1747  * the network. In such a case, we don't want to build a very large queue.
1748  * But we would still like to get all of the network throughput possible.
1749  * This implies that network should never block waiting for data.
1750  * As there are lot of disk throughput/network throughput combinations
1751  * possible, it is difficult to come up with an accurate number.
1752  * A typical 10K RPM disk has a max seek latency 17ms and rotational
1753  * latency of 3ms for reading a disk block. Thus, the total latency to
1754  * initiate a new read, transfer data from the disk and queue for
1755  * transmission would take about a max of 25ms. Todays max transfer rate
1756  * for network is 100MB/sec. If the thread is blocked because of flow
1757  * control, it would take 25ms to get new data ready for transmission.
1758  * We have to make sure that network is not idling, while we are initiating
1759  * new transfers. So, at 100MB/sec, to keep network busy we would need
1760  * 2.5MB of data. Rounding off, we keep the low water mark to be 3MB of data.
1761  * We need to pick a high water mark so that the woken up thread would
1762  * do considerable work before blocking again to prevent thrashing. Currently,
1763  * we pick this to be 10 times that of the low water mark.
1764  *
1765  * Sendfile with segmap caching (One copy from page cache to mblks).
1766  * ----------------------------------------------------------------
1767  *
1768  * We use the segmap cache for caching the file, if the size of file
1769  * is <= sendfile_max_size. In this case we don't use threads as VM
1770  * is reasonably fast enough to keep up with the network. If the underlying
1771  * transport allows, we call segmap_getmapflt() to map MAXBSIZE (8K) worth
1772  * of data into segmap space, and use the virtual address from segmap
1773  * directly through desballoc() to avoid copy. Once the transport is done
1774  * with the data, the mapping will be released through segmap_release()
1775  * called by the call-back routine.
1776  *
1777  * If zero-copy is not allowed by the transport, we simply call VOP_READ()
1778  * to copy the data from the filesystem into our temporary network buffer.
1779  *
1780  * To disable caching, set sendfile_max_size to 0.
1781  */
1782 
1783 uint_t sendfile_read_size = 1024 * 1024;
1784 #define	SENDFILE_REQ_LOWAT	3 * 1024 * 1024
1785 uint_t sendfile_req_lowat = SENDFILE_REQ_LOWAT;
1786 uint_t sendfile_req_hiwat = 10 * SENDFILE_REQ_LOWAT;
1787 struct sendfile_stats sf_stats;
1788 struct sendfile_queue *snfq;
1789 clock_t snfq_timeout;
1790 off64_t sendfile_max_size;
1791 
1792 static void snf_enque(snf_req_t *, mblk_t *);
1793 static mblk_t *snf_deque(snf_req_t *);
1794 
1795 void
1796 sendfile_init(void)
1797 {
1798 	snfq = kmem_zalloc(sizeof (struct sendfile_queue), KM_SLEEP);
1799 
1800 	mutex_init(&snfq->snfq_lock, NULL, MUTEX_DEFAULT, NULL);
1801 	cv_init(&snfq->snfq_cv, NULL, CV_DEFAULT, NULL);
1802 	snfq->snfq_max_threads = max_ncpus;
1803 	snfq_timeout = SNFQ_TIMEOUT;
1804 	/* Cache all files by default. */
1805 	sendfile_max_size = MAXOFFSET_T;
1806 }
1807 
1808 /*
1809  * Queues a mblk_t for network processing.
1810  */
1811 static void
1812 snf_enque(snf_req_t *sr, mblk_t *mp)
1813 {
1814 	mp->b_next = NULL;
1815 	mutex_enter(&sr->sr_lock);
1816 	if (sr->sr_mp_head == NULL) {
1817 		sr->sr_mp_head = sr->sr_mp_tail = mp;
1818 		cv_signal(&sr->sr_cv);
1819 	} else {
1820 		sr->sr_mp_tail->b_next = mp;
1821 		sr->sr_mp_tail = mp;
1822 	}
1823 	sr->sr_qlen += MBLKL(mp);
1824 	while ((sr->sr_qlen > sr->sr_hiwat) &&
1825 	    (sr->sr_write_error == 0)) {
1826 		sf_stats.ss_full_waits++;
1827 		cv_wait(&sr->sr_cv, &sr->sr_lock);
1828 	}
1829 	mutex_exit(&sr->sr_lock);
1830 }
1831 
1832 /*
1833  * De-queues a mblk_t for network processing.
1834  */
1835 static mblk_t *
1836 snf_deque(snf_req_t *sr)
1837 {
1838 	mblk_t *mp;
1839 
1840 	mutex_enter(&sr->sr_lock);
1841 	/*
1842 	 * If we have encountered an error on read or read is
1843 	 * completed and no more mblks, return NULL.
1844 	 * We need to check for NULL sr_mp_head also as
1845 	 * the reads could have completed and there is
1846 	 * nothing more to come.
1847 	 */
1848 	if (((sr->sr_read_error & ~SR_READ_DONE) != 0) ||
1849 	    ((sr->sr_read_error & SR_READ_DONE) &&
1850 	    sr->sr_mp_head == NULL)) {
1851 		mutex_exit(&sr->sr_lock);
1852 		return (NULL);
1853 	}
1854 	/*
1855 	 * To start with neither SR_READ_DONE is marked nor
1856 	 * the error is set. When we wake up from cv_wait,
1857 	 * following are the possibilities :
1858 	 *
1859 	 *	a) sr_read_error is zero and mblks are queued.
1860 	 *	b) sr_read_error is set to SR_READ_DONE
1861 	 *	   and mblks are queued.
1862 	 *	c) sr_read_error is set to SR_READ_DONE
1863 	 *	   and no mblks.
1864 	 *	d) sr_read_error is set to some error other
1865 	 *	   than SR_READ_DONE.
1866 	 */
1867 
1868 	while ((sr->sr_read_error == 0) && (sr->sr_mp_head == NULL)) {
1869 		sf_stats.ss_empty_waits++;
1870 		cv_wait(&sr->sr_cv, &sr->sr_lock);
1871 	}
1872 	/* Handle (a) and (b) first  - the normal case. */
1873 	if (((sr->sr_read_error & ~SR_READ_DONE) == 0) &&
1874 	    (sr->sr_mp_head != NULL)) {
1875 		mp = sr->sr_mp_head;
1876 		sr->sr_mp_head = mp->b_next;
1877 		sr->sr_qlen -= MBLKL(mp);
1878 		if (sr->sr_qlen < sr->sr_lowat)
1879 			cv_signal(&sr->sr_cv);
1880 		mutex_exit(&sr->sr_lock);
1881 		mp->b_next = NULL;
1882 		return (mp);
1883 	}
1884 	/* Handle (c) and (d). */
1885 	mutex_exit(&sr->sr_lock);
1886 	return (NULL);
1887 }
1888 
1889 /*
1890  * Reads data from the filesystem and queues it for network processing.
1891  */
1892 void
1893 snf_async_read(snf_req_t *sr)
1894 {
1895 	size_t iosize;
1896 	u_offset_t fileoff;
1897 	u_offset_t size;
1898 	int ret_size;
1899 	int error;
1900 	file_t *fp;
1901 	mblk_t *mp;
1902 	struct vnode *vp;
1903 	int extra = 0;
1904 	int maxblk = 0;
1905 	int wroff = 0;
1906 	struct sonode *so;
1907 
1908 	fp = sr->sr_fp;
1909 	size = sr->sr_file_size;
1910 	fileoff = sr->sr_file_off;
1911 
1912 	/*
1913 	 * Ignore the error for filesystems that doesn't support DIRECTIO.
1914 	 */
1915 	(void) VOP_IOCTL(fp->f_vnode, _FIODIRECTIO, DIRECTIO_ON, 0,
1916 	    kcred, NULL, NULL);
1917 
1918 	vp = sr->sr_vp;
1919 	if (vp->v_type == VSOCK) {
1920 		stdata_t *stp;
1921 
1922 		/*
1923 		 * Get the extra space to insert a header and a trailer.
1924 		 */
1925 		so = VTOSO(vp);
1926 		stp = vp->v_stream;
1927 		if (stp == NULL) {
1928 			wroff = so->so_proto_props.sopp_wroff;
1929 			maxblk = so->so_proto_props.sopp_maxblk;
1930 			extra = wroff + so->so_proto_props.sopp_tail;
1931 		} else {
1932 			wroff = (int)(stp->sd_wroff);
1933 			maxblk = (int)(stp->sd_maxblk);
1934 			extra = wroff + (int)(stp->sd_tail);
1935 		}
1936 	}
1937 
1938 	while ((size != 0) && (sr->sr_write_error == 0)) {
1939 
1940 		iosize = (int)MIN(sr->sr_maxpsz, size);
1941 
1942 		/*
1943 		 * For sockets acting as an SSL proxy, we
1944 		 * need to adjust the size to the maximum
1945 		 * SSL record size set in the stream head.
1946 		 */
1947 		if (vp->v_type == VSOCK && !SOCK_IS_NONSTR(so) &&
1948 		    SOTOTPI(so)->sti_kssl_ctx != NULL)
1949 			iosize = (int)MIN(iosize, maxblk);
1950 
1951 		if (is_system_labeled()) {
1952 			mp = allocb_cred(iosize + extra, CRED(),
1953 			    curproc->p_pid);
1954 		} else {
1955 			mp = allocb(iosize + extra, BPRI_MED);
1956 		}
1957 		if (mp == NULL) {
1958 			error = EAGAIN;
1959 			break;
1960 		}
1961 
1962 		mp->b_rptr += wroff;
1963 
1964 		ret_size = soreadfile(fp, mp->b_rptr, fileoff, &error, iosize);
1965 
1966 		/* Error or Reached EOF ? */
1967 		if ((error != 0) || (ret_size == 0)) {
1968 			freeb(mp);
1969 			break;
1970 		}
1971 		mp->b_wptr = mp->b_rptr + ret_size;
1972 
1973 		snf_enque(sr, mp);
1974 		size -= ret_size;
1975 		fileoff += ret_size;
1976 	}
1977 	(void) VOP_IOCTL(fp->f_vnode, _FIODIRECTIO, DIRECTIO_OFF, 0,
1978 	    kcred, NULL, NULL);
1979 	mutex_enter(&sr->sr_lock);
1980 	sr->sr_read_error = error;
1981 	sr->sr_read_error |= SR_READ_DONE;
1982 	cv_signal(&sr->sr_cv);
1983 	mutex_exit(&sr->sr_lock);
1984 }
1985 
1986 void
1987 snf_async_thread(void)
1988 {
1989 	snf_req_t *sr;
1990 	callb_cpr_t cprinfo;
1991 	clock_t time_left = 1;
1992 
1993 	CALLB_CPR_INIT(&cprinfo, &snfq->snfq_lock, callb_generic_cpr, "snfq");
1994 
1995 	mutex_enter(&snfq->snfq_lock);
1996 	for (;;) {
1997 		/*
1998 		 * If we didn't find a entry, then block until woken up
1999 		 * again and then look through the queues again.
2000 		 */
2001 		while ((sr = snfq->snfq_req_head) == NULL) {
2002 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
2003 			if (time_left <= 0) {
2004 				snfq->snfq_svc_threads--;
2005 				CALLB_CPR_EXIT(&cprinfo);
2006 				thread_exit();
2007 				/* NOTREACHED */
2008 			}
2009 			snfq->snfq_idle_cnt++;
2010 
2011 			time_left = cv_reltimedwait(&snfq->snfq_cv,
2012 			    &snfq->snfq_lock, snfq_timeout, TR_CLOCK_TICK);
2013 			snfq->snfq_idle_cnt--;
2014 
2015 			CALLB_CPR_SAFE_END(&cprinfo, &snfq->snfq_lock);
2016 		}
2017 		snfq->snfq_req_head = sr->sr_next;
2018 		snfq->snfq_req_cnt--;
2019 		mutex_exit(&snfq->snfq_lock);
2020 		snf_async_read(sr);
2021 		mutex_enter(&snfq->snfq_lock);
2022 	}
2023 }
2024 
2025 
2026 snf_req_t *
2027 create_thread(int operation, struct vnode *vp, file_t *fp,
2028     u_offset_t fileoff, u_offset_t size)
2029 {
2030 	snf_req_t *sr;
2031 	stdata_t *stp;
2032 
2033 	sr = (snf_req_t *)kmem_zalloc(sizeof (snf_req_t), KM_SLEEP);
2034 
2035 	sr->sr_vp = vp;
2036 	sr->sr_fp = fp;
2037 	stp = vp->v_stream;
2038 
2039 	/*
2040 	 * store sd_qn_maxpsz into sr_maxpsz while we have stream head.
2041 	 * stream might be closed before thread returns from snf_async_read.
2042 	 */
2043 	if (stp != NULL && stp->sd_qn_maxpsz > 0) {
2044 		sr->sr_maxpsz = MIN(MAXBSIZE, stp->sd_qn_maxpsz);
2045 	} else {
2046 		sr->sr_maxpsz = MAXBSIZE;
2047 	}
2048 
2049 	sr->sr_operation = operation;
2050 	sr->sr_file_off = fileoff;
2051 	sr->sr_file_size = size;
2052 	sr->sr_hiwat = sendfile_req_hiwat;
2053 	sr->sr_lowat = sendfile_req_lowat;
2054 	mutex_init(&sr->sr_lock, NULL, MUTEX_DEFAULT, NULL);
2055 	cv_init(&sr->sr_cv, NULL, CV_DEFAULT, NULL);
2056 	/*
2057 	 * See whether we need another thread for servicing this
2058 	 * request. If there are already enough requests queued
2059 	 * for the threads, create one if not exceeding
2060 	 * snfq_max_threads.
2061 	 */
2062 	mutex_enter(&snfq->snfq_lock);
2063 	if (snfq->snfq_req_cnt >= snfq->snfq_idle_cnt &&
2064 	    snfq->snfq_svc_threads < snfq->snfq_max_threads) {
2065 		(void) thread_create(NULL, 0, &snf_async_thread, 0, 0, &p0,
2066 		    TS_RUN, minclsyspri);
2067 		snfq->snfq_svc_threads++;
2068 	}
2069 	if (snfq->snfq_req_head == NULL) {
2070 		snfq->snfq_req_head = snfq->snfq_req_tail = sr;
2071 		cv_signal(&snfq->snfq_cv);
2072 	} else {
2073 		snfq->snfq_req_tail->sr_next = sr;
2074 		snfq->snfq_req_tail = sr;
2075 	}
2076 	snfq->snfq_req_cnt++;
2077 	mutex_exit(&snfq->snfq_lock);
2078 	return (sr);
2079 }
2080 
2081 int
2082 snf_direct_io(file_t *fp, file_t *rfp, u_offset_t fileoff, u_offset_t size,
2083     ssize_t *count)
2084 {
2085 	snf_req_t *sr;
2086 	mblk_t *mp;
2087 	int iosize;
2088 	int error = 0;
2089 	short fflag;
2090 	struct vnode *vp;
2091 	int ksize;
2092 	struct nmsghdr msg;
2093 
2094 	ksize = 0;
2095 	*count = 0;
2096 	bzero(&msg, sizeof (msg));
2097 
2098 	vp = fp->f_vnode;
2099 	fflag = fp->f_flag;
2100 	if ((sr = create_thread(READ_OP, vp, rfp, fileoff, size)) == NULL)
2101 		return (EAGAIN);
2102 
2103 	/*
2104 	 * We check for read error in snf_deque. It has to check
2105 	 * for successful READ_DONE and return NULL, and we might
2106 	 * as well make an additional check there.
2107 	 */
2108 	while ((mp = snf_deque(sr)) != NULL) {
2109 
2110 		if (ISSIG(curthread, JUSTLOOKING)) {
2111 			freeb(mp);
2112 			error = EINTR;
2113 			break;
2114 		}
2115 		iosize = MBLKL(mp);
2116 
2117 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2118 
2119 		if (error != 0) {
2120 			if (mp != NULL)
2121 				freeb(mp);
2122 			break;
2123 		}
2124 		ksize += iosize;
2125 	}
2126 	*count = ksize;
2127 
2128 	mutex_enter(&sr->sr_lock);
2129 	sr->sr_write_error = error;
2130 	/* Look at the big comments on why we cv_signal here. */
2131 	cv_signal(&sr->sr_cv);
2132 
2133 	/* Wait for the reader to complete always. */
2134 	while (!(sr->sr_read_error & SR_READ_DONE)) {
2135 		cv_wait(&sr->sr_cv, &sr->sr_lock);
2136 	}
2137 	/* If there is no write error, check for read error. */
2138 	if (error == 0)
2139 		error = (sr->sr_read_error & ~SR_READ_DONE);
2140 
2141 	if (error != 0) {
2142 		mblk_t *next_mp;
2143 
2144 		mp = sr->sr_mp_head;
2145 		while (mp != NULL) {
2146 			next_mp = mp->b_next;
2147 			mp->b_next = NULL;
2148 			freeb(mp);
2149 			mp = next_mp;
2150 		}
2151 	}
2152 	mutex_exit(&sr->sr_lock);
2153 	kmem_free(sr, sizeof (snf_req_t));
2154 	return (error);
2155 }
2156 
2157 /* Maximum no.of pages allocated by vpm for sendfile at a time */
2158 #define	SNF_VPMMAXPGS	(VPMMAXPGS/2)
2159 
2160 /*
2161  * Maximum no.of elements in the list returned by vpm, including
2162  * NULL for the last entry
2163  */
2164 #define	SNF_MAXVMAPS	(SNF_VPMMAXPGS + 1)
2165 
2166 typedef struct {
2167 	unsigned int	snfv_ref;
2168 	frtn_t		snfv_frtn;
2169 	vnode_t		*snfv_vp;
2170 	struct vmap	snfv_vml[SNF_MAXVMAPS];
2171 } snf_vmap_desbinfo;
2172 
2173 typedef struct {
2174 	frtn_t		snfi_frtn;
2175 	caddr_t		snfi_base;
2176 	uint_t		snfi_mapoff;
2177 	size_t		snfi_len;
2178 	vnode_t		*snfi_vp;
2179 } snf_smap_desbinfo;
2180 
2181 /*
2182  * The callback function used for vpm mapped mblks called when the last ref of
2183  * the mblk is dropped which normally occurs when TCP receives the ack. But it
2184  * can be the driver too due to lazy reclaim.
2185  */
2186 void
2187 snf_vmap_desbfree(snf_vmap_desbinfo *snfv)
2188 {
2189 	ASSERT(snfv->snfv_ref != 0);
2190 	if (atomic_add_32_nv(&snfv->snfv_ref, -1) == 0) {
2191 		vpm_unmap_pages(snfv->snfv_vml, S_READ);
2192 		VN_RELE(snfv->snfv_vp);
2193 		kmem_free(snfv, sizeof (snf_vmap_desbinfo));
2194 	}
2195 }
2196 
2197 /*
2198  * The callback function used for segmap'ped mblks called when the last ref of
2199  * the mblk is dropped which normally occurs when TCP receives the ack. But it
2200  * can be the driver too due to lazy reclaim.
2201  */
2202 void
2203 snf_smap_desbfree(snf_smap_desbinfo *snfi)
2204 {
2205 	if (! IS_KPM_ADDR(snfi->snfi_base)) {
2206 		/*
2207 		 * We don't need to call segmap_fault(F_SOFTUNLOCK) for
2208 		 * segmap_kpm as long as the latter never falls back to
2209 		 * "use_segmap_range". (See segmap_getmapflt().)
2210 		 *
2211 		 * Using S_OTHER saves an redundant hat_setref() in
2212 		 * segmap_unlock()
2213 		 */
2214 		(void) segmap_fault(kas.a_hat, segkmap,
2215 		    (caddr_t)(uintptr_t)(((uintptr_t)snfi->snfi_base +
2216 		    snfi->snfi_mapoff) & PAGEMASK), snfi->snfi_len,
2217 		    F_SOFTUNLOCK, S_OTHER);
2218 	}
2219 	(void) segmap_release(segkmap, snfi->snfi_base, SM_DONTNEED);
2220 	VN_RELE(snfi->snfi_vp);
2221 	kmem_free(snfi, sizeof (*snfi));
2222 }
2223 
2224 /*
2225  * Use segmap or vpm instead of bcopy to send down a desballoca'ed, mblk.
2226  * When segmap is used, the mblk contains a segmap slot of no more
2227  * than MAXBSIZE.
2228  *
2229  * With vpm, a maximum of SNF_MAXVMAPS page-sized mappings can be obtained
2230  * in each iteration and sent by socket_sendmblk until an error occurs or
2231  * the requested size has been transferred. An mblk is esballoca'ed from
2232  * each mapped page and a chain of these mblk is sent to the transport layer.
2233  * vpm will be called to unmap the pages when all mblks have been freed by
2234  * free_func.
2235  *
2236  * At the end of the whole sendfile() operation, we wait till the data from
2237  * the last mblk is ack'ed by the transport before returning so that the
2238  * caller of sendfile() can safely modify the file content.
2239  */
2240 int
2241 snf_segmap(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t total_size,
2242     ssize_t *count, boolean_t nowait)
2243 {
2244 	caddr_t base;
2245 	int mapoff;
2246 	vnode_t *vp;
2247 	mblk_t *mp = NULL;
2248 	int chain_size;
2249 	int error;
2250 	short fflag;
2251 	int ksize;
2252 	struct vattr va;
2253 	boolean_t dowait = B_FALSE;
2254 	struct nmsghdr msg;
2255 
2256 	vp = fp->f_vnode;
2257 	fflag = fp->f_flag;
2258 	ksize = 0;
2259 	bzero(&msg, sizeof (msg));
2260 
2261 	for (;;) {
2262 		if (ISSIG(curthread, JUSTLOOKING)) {
2263 			error = EINTR;
2264 			break;
2265 		}
2266 
2267 		if (vpm_enable) {
2268 			snf_vmap_desbinfo *snfv;
2269 			mblk_t *nmp;
2270 			int mblk_size;
2271 			int maxsize;
2272 			int i;
2273 
2274 			mapoff = fileoff & PAGEOFFSET;
2275 			maxsize = MIN((SNF_VPMMAXPGS * PAGESIZE), total_size);
2276 
2277 			snfv = kmem_zalloc(sizeof (snf_vmap_desbinfo),
2278 			    KM_SLEEP);
2279 
2280 			/* Get vpm mappings for maxsize with read access */
2281 			if (vpm_map_pages(fvp, fileoff, (size_t)maxsize,
2282 			    (VPM_FETCHPAGE), snfv->snfv_vml, SNF_MAXVMAPS,
2283 			    NULL, S_READ) != 0) {
2284 				kmem_free(snfv, sizeof (snf_vmap_desbinfo));
2285 				error = EIO;
2286 				goto out;
2287 			}
2288 			snfv->snfv_frtn.free_func = snf_vmap_desbfree;
2289 			snfv->snfv_frtn.free_arg = (caddr_t)snfv;
2290 
2291 			/* Construct the mblk chain from the page mappings */
2292 			chain_size = 0;
2293 			for (i = 0; (snfv->snfv_vml[i].vs_addr != NULL) &&
2294 			    total_size > 0; i++) {
2295 				ASSERT(chain_size < maxsize);
2296 				mblk_size = MIN(snfv->snfv_vml[i].vs_len -
2297 				    mapoff, total_size);
2298 				nmp = esballoca(
2299 				    (uchar_t *)snfv->snfv_vml[i].vs_addr +
2300 				    mapoff, mblk_size, BPRI_HI,
2301 				    &snfv->snfv_frtn);
2302 
2303 				/*
2304 				 * We return EAGAIN after unmapping the pages
2305 				 * if we cannot allocate the the head of the
2306 				 * chain. Otherwise, we continue sending the
2307 				 * mblks constructed so far.
2308 				 */
2309 				if (nmp == NULL) {
2310 					if (i == 0) {
2311 						vpm_unmap_pages(snfv->snfv_vml,
2312 						    S_READ);
2313 						kmem_free(snfv,
2314 						    sizeof (snf_vmap_desbinfo));
2315 						error = EAGAIN;
2316 						goto out;
2317 					}
2318 					break;
2319 				}
2320 				/* Mark this dblk with the zero-copy flag */
2321 				nmp->b_datap->db_struioflag |= STRUIO_ZC;
2322 				nmp->b_wptr += mblk_size;
2323 				chain_size += mblk_size;
2324 				fileoff += mblk_size;
2325 				total_size -= mblk_size;
2326 				snfv->snfv_ref++;
2327 				mapoff = 0;
2328 				if (i > 0)
2329 					linkb(mp, nmp);
2330 				else
2331 					mp = nmp;
2332 			}
2333 			VN_HOLD(fvp);
2334 			snfv->snfv_vp = fvp;
2335 		} else {
2336 			/* vpm not supported. fallback to segmap */
2337 			snf_smap_desbinfo *snfi;
2338 
2339 			mapoff = fileoff & MAXBOFFSET;
2340 			chain_size = MAXBSIZE - mapoff;
2341 			if (chain_size > total_size)
2342 				chain_size = total_size;
2343 			/*
2344 			 * we don't forcefault because we'll call
2345 			 * segmap_fault(F_SOFTLOCK) next.
2346 			 *
2347 			 * S_READ will get the ref bit set (by either
2348 			 * segmap_getmapflt() or segmap_fault()) and page
2349 			 * shared locked.
2350 			 */
2351 			base = segmap_getmapflt(segkmap, fvp, fileoff,
2352 			    chain_size, segmap_kpm ? SM_FAULT : 0, S_READ);
2353 
2354 			snfi = kmem_alloc(sizeof (*snfi), KM_SLEEP);
2355 			snfi->snfi_len = (size_t)roundup(mapoff+chain_size,
2356 			    PAGESIZE)- (mapoff & PAGEMASK);
2357 			/*
2358 			 * We must call segmap_fault() even for segmap_kpm
2359 			 * because that's how error gets returned.
2360 			 * (segmap_getmapflt() never fails but segmap_fault()
2361 			 * does.)
2362 			 */
2363 			if (segmap_fault(kas.a_hat, segkmap,
2364 			    (caddr_t)(uintptr_t)(((uintptr_t)base + mapoff) &
2365 			    PAGEMASK), snfi->snfi_len,
2366 			    F_SOFTLOCK, S_READ) != 0) {
2367 				(void) segmap_release(segkmap, base, 0);
2368 				kmem_free(snfi, sizeof (*snfi));
2369 				error = EIO;
2370 				goto out;
2371 			}
2372 			snfi->snfi_frtn.free_func = snf_smap_desbfree;
2373 			snfi->snfi_frtn.free_arg = (caddr_t)snfi;
2374 			snfi->snfi_base = base;
2375 			snfi->snfi_mapoff = mapoff;
2376 			mp = esballoca((uchar_t *)base + mapoff, chain_size,
2377 			    BPRI_HI, &snfi->snfi_frtn);
2378 
2379 			if (mp == NULL) {
2380 				(void) segmap_fault(kas.a_hat, segkmap,
2381 				    (caddr_t)(uintptr_t)(((uintptr_t)base +
2382 				    mapoff) & PAGEMASK), snfi->snfi_len,
2383 				    F_SOFTUNLOCK, S_OTHER);
2384 				(void) segmap_release(segkmap, base, 0);
2385 				kmem_free(snfi, sizeof (*snfi));
2386 				freemsg(mp);
2387 				error = EAGAIN;
2388 				goto out;
2389 			}
2390 			VN_HOLD(fvp);
2391 			snfi->snfi_vp = fvp;
2392 			mp->b_wptr += chain_size;
2393 
2394 			/* Mark this dblk with the zero-copy flag */
2395 			mp->b_datap->db_struioflag |= STRUIO_ZC;
2396 			fileoff += chain_size;
2397 			total_size -= chain_size;
2398 		}
2399 
2400 		if (total_size == 0 && !nowait) {
2401 			ASSERT(!dowait);
2402 			dowait = B_TRUE;
2403 			mp->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
2404 		}
2405 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2406 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2407 		if (error != 0) {
2408 			/*
2409 			 * mp contains the mblks that were not sent by
2410 			 * socket_sendmblk. Use its size to update *count
2411 			 */
2412 			*count = ksize + (chain_size - msgdsize(mp));
2413 			if (mp != NULL)
2414 				freemsg(mp);
2415 			return (error);
2416 		}
2417 		ksize += chain_size;
2418 		if (total_size == 0)
2419 			goto done;
2420 
2421 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2422 		va.va_mask = AT_SIZE;
2423 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2424 		if (error)
2425 			break;
2426 		/* Read as much as possible. */
2427 		if (fileoff >= va.va_size)
2428 			break;
2429 		if (total_size + fileoff > va.va_size)
2430 			total_size = va.va_size - fileoff;
2431 	}
2432 out:
2433 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2434 done:
2435 	*count = ksize;
2436 	if (dowait) {
2437 		stdata_t *stp;
2438 
2439 		stp = vp->v_stream;
2440 		if (stp == NULL) {
2441 			struct sonode *so;
2442 			so = VTOSO(vp);
2443 			error = so_zcopy_wait(so);
2444 		} else {
2445 			mutex_enter(&stp->sd_lock);
2446 			while (!(stp->sd_flag & STZCNOTIFY)) {
2447 				if (cv_wait_sig(&stp->sd_zcopy_wait,
2448 				    &stp->sd_lock) == 0) {
2449 					error = EINTR;
2450 					break;
2451 				}
2452 			}
2453 			stp->sd_flag &= ~STZCNOTIFY;
2454 			mutex_exit(&stp->sd_lock);
2455 		}
2456 	}
2457 	return (error);
2458 }
2459 
2460 int
2461 snf_cache(file_t *fp, vnode_t *fvp, u_offset_t fileoff, u_offset_t size,
2462     uint_t maxpsz, ssize_t *count)
2463 {
2464 	struct vnode *vp;
2465 	mblk_t *mp;
2466 	int iosize;
2467 	int extra = 0;
2468 	int error;
2469 	short fflag;
2470 	int ksize;
2471 	int ioflag;
2472 	struct uio auio;
2473 	struct iovec aiov;
2474 	struct vattr va;
2475 	int maxblk = 0;
2476 	int wroff = 0;
2477 	struct sonode *so;
2478 	struct nmsghdr msg;
2479 
2480 	vp = fp->f_vnode;
2481 	if (vp->v_type == VSOCK) {
2482 		stdata_t *stp;
2483 
2484 		/*
2485 		 * Get the extra space to insert a header and a trailer.
2486 		 */
2487 		so = VTOSO(vp);
2488 		stp = vp->v_stream;
2489 		if (stp == NULL) {
2490 			wroff = so->so_proto_props.sopp_wroff;
2491 			maxblk = so->so_proto_props.sopp_maxblk;
2492 			extra = wroff + so->so_proto_props.sopp_tail;
2493 		} else {
2494 			wroff = (int)(stp->sd_wroff);
2495 			maxblk = (int)(stp->sd_maxblk);
2496 			extra = wroff + (int)(stp->sd_tail);
2497 		}
2498 	}
2499 	bzero(&msg, sizeof (msg));
2500 	fflag = fp->f_flag;
2501 	ksize = 0;
2502 	auio.uio_iov = &aiov;
2503 	auio.uio_iovcnt = 1;
2504 	auio.uio_segflg = UIO_SYSSPACE;
2505 	auio.uio_llimit = MAXOFFSET_T;
2506 	auio.uio_fmode = fflag;
2507 	auio.uio_extflg = UIO_COPY_CACHED;
2508 	ioflag = auio.uio_fmode & (FSYNC|FDSYNC|FRSYNC);
2509 	/* If read sync is not asked for, filter sync flags */
2510 	if ((ioflag & FRSYNC) == 0)
2511 		ioflag &= ~(FSYNC|FDSYNC);
2512 	for (;;) {
2513 		if (ISSIG(curthread, JUSTLOOKING)) {
2514 			error = EINTR;
2515 			break;
2516 		}
2517 		iosize = (int)MIN(maxpsz, size);
2518 
2519 		/*
2520 		 * For sockets acting as an SSL proxy, we
2521 		 * need to adjust the size to the maximum
2522 		 * SSL record size set in the stream head.
2523 		 */
2524 		if (vp->v_type == VSOCK && !SOCK_IS_NONSTR(so) &&
2525 		    SOTOTPI(so)->sti_kssl_ctx != NULL)
2526 			iosize = (int)MIN(iosize, maxblk);
2527 
2528 		if (is_system_labeled()) {
2529 			mp = allocb_cred(iosize + extra, CRED(),
2530 			    curproc->p_pid);
2531 		} else {
2532 			mp = allocb(iosize + extra, BPRI_MED);
2533 		}
2534 		if (mp == NULL) {
2535 			error = EAGAIN;
2536 			break;
2537 		}
2538 
2539 		mp->b_rptr += wroff;
2540 
2541 		aiov.iov_base = (caddr_t)mp->b_rptr;
2542 		aiov.iov_len = iosize;
2543 		auio.uio_loffset = fileoff;
2544 		auio.uio_resid = iosize;
2545 
2546 		error = VOP_READ(fvp, &auio, ioflag, fp->f_cred, NULL);
2547 		iosize -= auio.uio_resid;
2548 
2549 		if (error == EINTR && iosize != 0)
2550 			error = 0;
2551 
2552 		if (error != 0 || iosize == 0) {
2553 			freeb(mp);
2554 			break;
2555 		}
2556 		mp->b_wptr = mp->b_rptr + iosize;
2557 
2558 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2559 
2560 		error = socket_sendmblk(VTOSO(vp), &msg, fflag, CRED(), &mp);
2561 
2562 		if (error != 0) {
2563 			*count = ksize;
2564 			if (mp != NULL)
2565 				freeb(mp);
2566 			return (error);
2567 		}
2568 		ksize += iosize;
2569 		size -= iosize;
2570 		if (size == 0)
2571 			goto done;
2572 
2573 		fileoff += iosize;
2574 		(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2575 		va.va_mask = AT_SIZE;
2576 		error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2577 		if (error)
2578 			break;
2579 		/* Read as much as possible. */
2580 		if (fileoff >= va.va_size)
2581 			size = 0;
2582 		else if (size + fileoff > va.va_size)
2583 			size = va.va_size - fileoff;
2584 	}
2585 	VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2586 done:
2587 	*count = ksize;
2588 	return (error);
2589 }
2590 
2591 #if defined(_SYSCALL32_IMPL) || defined(_ILP32)
2592 /*
2593  * Largefile support for 32 bit applications only.
2594  */
2595 int
2596 sosendfile64(file_t *fp, file_t *rfp, const struct ksendfilevec64 *sfv,
2597     ssize32_t *count32)
2598 {
2599 	ssize32_t sfv_len;
2600 	u_offset_t sfv_off, va_size;
2601 	struct vnode *vp, *fvp, *realvp;
2602 	struct vattr va;
2603 	stdata_t *stp;
2604 	ssize_t count = 0;
2605 	int error = 0;
2606 	boolean_t dozcopy = B_FALSE;
2607 	uint_t maxpsz;
2608 
2609 	sfv_len = (ssize32_t)sfv->sfv_len;
2610 	if (sfv_len < 0) {
2611 		error = EINVAL;
2612 		goto out;
2613 	}
2614 
2615 	if (sfv_len == 0) goto out;
2616 
2617 	sfv_off = (u_offset_t)sfv->sfv_off;
2618 
2619 	/* Same checks as in pread */
2620 	if (sfv_off > MAXOFFSET_T) {
2621 		error = EINVAL;
2622 		goto out;
2623 	}
2624 	if (sfv_off + sfv_len > MAXOFFSET_T)
2625 		sfv_len = (ssize32_t)(MAXOFFSET_T - sfv_off);
2626 
2627 	/*
2628 	 * There are no more checks on sfv_len. So, we cast it to
2629 	 * u_offset_t and share the snf_direct_io/snf_cache code between
2630 	 * 32 bit and 64 bit.
2631 	 *
2632 	 * TODO: should do nbl_need_check() like read()?
2633 	 */
2634 	if (sfv_len > sendfile_max_size) {
2635 		sf_stats.ss_file_not_cached++;
2636 		error = snf_direct_io(fp, rfp, sfv_off, (u_offset_t)sfv_len,
2637 		    &count);
2638 		goto out;
2639 	}
2640 	fvp = rfp->f_vnode;
2641 	if (VOP_REALVP(fvp, &realvp, NULL) == 0)
2642 		fvp = realvp;
2643 	/*
2644 	 * Grab the lock as a reader to prevent the file size
2645 	 * from changing underneath.
2646 	 */
2647 	(void) VOP_RWLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2648 	va.va_mask = AT_SIZE;
2649 	error = VOP_GETATTR(fvp, &va, 0, kcred, NULL);
2650 	va_size = va.va_size;
2651 	if ((error != 0) || (va_size == 0) || (sfv_off >= va_size)) {
2652 		VOP_RWUNLOCK(fvp, V_WRITELOCK_FALSE, NULL);
2653 		goto out;
2654 	}
2655 	/* Read as much as possible. */
2656 	if (sfv_off + sfv_len > va_size)
2657 		sfv_len = va_size - sfv_off;
2658 
2659 	vp = fp->f_vnode;
2660 	stp = vp->v_stream;
2661 	/*
2662 	 * When the NOWAIT flag is not set, we enable zero-copy only if the
2663 	 * transfer size is large enough. This prevents performance loss
2664 	 * when the caller sends the file piece by piece.
2665 	 */
2666 	if (sfv_len >= MAXBSIZE && (sfv_len >= (va_size >> 1) ||
2667 	    (sfv->sfv_flag & SFV_NOWAIT) || sfv_len >= 0x1000000) &&
2668 	    !vn_has_flocks(fvp) && !(fvp->v_flag & VNOMAP)) {
2669 		uint_t copyflag;
2670 		copyflag = stp != NULL ? stp->sd_copyflag :
2671 		    VTOSO(vp)->so_proto_props.sopp_zcopyflag;
2672 		if ((copyflag & (STZCVMSAFE|STZCVMUNSAFE)) == 0) {
2673 			int on = 1;
2674 
2675 			if (socket_setsockopt(VTOSO(vp), SOL_SOCKET,
2676 			    SO_SND_COPYAVOID, &on, sizeof (on), CRED()) == 0)
2677 				dozcopy = B_TRUE;
2678 		} else {
2679 			dozcopy = copyflag & STZCVMSAFE;
2680 		}
2681 	}
2682 	if (dozcopy) {
2683 		sf_stats.ss_file_segmap++;
2684 		error = snf_segmap(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2685 		    &count, ((sfv->sfv_flag & SFV_NOWAIT) != 0));
2686 	} else {
2687 		if (vp->v_type == VSOCK && stp == NULL) {
2688 			sonode_t *so = VTOSO(vp);
2689 			maxpsz = so->so_proto_props.sopp_maxpsz;
2690 		} else if (stp != NULL) {
2691 			maxpsz = stp->sd_qn_maxpsz;
2692 		} else {
2693 			maxpsz = maxphys;
2694 		}
2695 
2696 		if (maxpsz == INFPSZ)
2697 			maxpsz = maxphys;
2698 		else
2699 			maxpsz = roundup(maxpsz, MAXBSIZE);
2700 		sf_stats.ss_file_cached++;
2701 		error = snf_cache(fp, fvp, sfv_off, (u_offset_t)sfv_len,
2702 		    maxpsz, &count);
2703 	}
2704 out:
2705 	releasef(sfv->sfv_fd);
2706 	*count32 = (ssize32_t)count;
2707 	return (error);
2708 }
2709 #endif
2710 
2711 #ifdef _SYSCALL32_IMPL
2712 /*
2713  * recv32(), recvfrom32(), send32(), sendto32(): intentionally return a
2714  * ssize_t rather than ssize32_t; see the comments above read32 for details.
2715  */
2716 
2717 ssize_t
2718 recv32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2719 {
2720 	return (recv(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2721 }
2722 
2723 ssize_t
2724 recvfrom32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2725 	caddr32_t name, caddr32_t namelenp)
2726 {
2727 	return (recvfrom(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2728 	    (void *)(uintptr_t)name, (void *)(uintptr_t)namelenp));
2729 }
2730 
2731 ssize_t
2732 send32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags)
2733 {
2734 	return (send(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags));
2735 }
2736 
2737 ssize_t
2738 sendto32(int32_t sock, caddr32_t buffer, size32_t len, int32_t flags,
2739 	caddr32_t name, socklen_t namelen)
2740 {
2741 	return (sendto(sock, (void *)(uintptr_t)buffer, (ssize32_t)len, flags,
2742 	    (void *)(uintptr_t)name, namelen));
2743 }
2744 #endif	/* _SYSCALL32_IMPL */
2745 
2746 /*
2747  * Function wrappers (mostly around the sonode switch) for
2748  * backward compatibility.
2749  */
2750 
2751 int
2752 soaccept(struct sonode *so, int fflag, struct sonode **nsop)
2753 {
2754 	return (socket_accept(so, fflag, CRED(), nsop));
2755 }
2756 
2757 int
2758 sobind(struct sonode *so, struct sockaddr *name, socklen_t namelen,
2759     int backlog, int flags)
2760 {
2761 	int	error;
2762 
2763 	error = socket_bind(so, name, namelen, flags, CRED());
2764 	if (error == 0 && backlog != 0)
2765 		return (socket_listen(so, backlog, CRED()));
2766 
2767 	return (error);
2768 }
2769 
2770 int
2771 solisten(struct sonode *so, int backlog)
2772 {
2773 	return (socket_listen(so, backlog, CRED()));
2774 }
2775 
2776 int
2777 soconnect(struct sonode *so, const struct sockaddr *name, socklen_t namelen,
2778     int fflag, int flags)
2779 {
2780 	return (socket_connect(so, name, namelen, fflag, flags, CRED()));
2781 }
2782 
2783 int
2784 sorecvmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2785 {
2786 	return (socket_recvmsg(so, msg, uiop, CRED()));
2787 }
2788 
2789 int
2790 sosendmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2791 {
2792 	return (socket_sendmsg(so, msg, uiop, CRED()));
2793 }
2794 
2795 int
2796 soshutdown(struct sonode *so, int how)
2797 {
2798 	return (socket_shutdown(so, how, CRED()));
2799 }
2800 
2801 int
2802 sogetsockopt(struct sonode *so, int level, int option_name, void *optval,
2803     socklen_t *optlenp, int flags)
2804 {
2805 	return (socket_getsockopt(so, level, option_name, optval, optlenp,
2806 	    flags, CRED()));
2807 }
2808 
2809 int
2810 sosetsockopt(struct sonode *so, int level, int option_name, const void *optval,
2811     t_uscalar_t optlen)
2812 {
2813 	return (socket_setsockopt(so, level, option_name, optval, optlen,
2814 	    CRED()));
2815 }
2816 
2817 /*
2818  * Because this is backward compatibility interface it only needs to be
2819  * able to handle the creation of TPI sockfs sockets.
2820  */
2821 struct sonode *
2822 socreate(struct sockparams *sp, int family, int type, int protocol, int version,
2823     int *errorp)
2824 {
2825 	struct sonode *so;
2826 
2827 	ASSERT(sp != NULL);
2828 
2829 	so = sp->sp_smod_info->smod_sock_create_func(sp, family, type, protocol,
2830 	    version, SOCKET_SLEEP, errorp, CRED());
2831 	if (so == NULL) {
2832 		SOCKPARAMS_DEC_REF(sp);
2833 	} else {
2834 		if ((*errorp = SOP_INIT(so, NULL, CRED(), SOCKET_SLEEP)) == 0) {
2835 			/* Cannot fail, only bumps so_count */
2836 			(void) VOP_OPEN(&SOTOV(so), FREAD|FWRITE, CRED(), NULL);
2837 		} else {
2838 			socket_destroy(so);
2839 			so = NULL;
2840 		}
2841 	}
2842 	return (so);
2843 }
2844