xref: /freebsd/sys/kern/uipc_syscalls.c (revision 255c1caae364c686a9f87d97a31c70728f9377f1)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * sendfile(2) and related extensions:
6  * Copyright (c) 1998, David Greenman. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)uipc_syscalls.c	8.4 (Berkeley) 2/21/94
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_capsicum.h"
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_sctp.h"
42 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/capability.h>
48 #include <sys/condvar.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/sysproto.h>
53 #include <sys/malloc.h>
54 #include <sys/filedesc.h>
55 #include <sys/event.h>
56 #include <sys/proc.h>
57 #include <sys/fcntl.h>
58 #include <sys/file.h>
59 #include <sys/filio.h>
60 #include <sys/jail.h>
61 #include <sys/mman.h>
62 #include <sys/mount.h>
63 #include <sys/mbuf.h>
64 #include <sys/protosw.h>
65 #include <sys/rwlock.h>
66 #include <sys/sf_buf.h>
67 #include <sys/sysent.h>
68 #include <sys/socket.h>
69 #include <sys/socketvar.h>
70 #include <sys/signalvar.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/sysctl.h>
73 #include <sys/uio.h>
74 #include <sys/vnode.h>
75 #ifdef KTRACE
76 #include <sys/ktrace.h>
77 #endif
78 #ifdef COMPAT_FREEBSD32
79 #include <compat/freebsd32/freebsd32_util.h>
80 #endif
81 
82 #include <net/vnet.h>
83 
84 #include <security/audit/audit.h>
85 #include <security/mac/mac_framework.h>
86 
87 #include <vm/vm.h>
88 #include <vm/vm_param.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_pager.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
94 
95 #if defined(INET) || defined(INET6)
96 #ifdef SCTP
97 #include <netinet/sctp.h>
98 #include <netinet/sctp_peeloff.h>
99 #endif /* SCTP */
100 #endif /* INET || INET6 */
101 
102 /*
103  * Flags for accept1() and kern_accept4(), in addition to SOCK_CLOEXEC
104  * and SOCK_NONBLOCK.
105  */
106 #define	ACCEPT4_INHERIT	0x1
107 #define	ACCEPT4_COMPAT	0x2
108 
109 static int sendit(struct thread *td, int s, struct msghdr *mp, int flags);
110 static int recvit(struct thread *td, int s, struct msghdr *mp, void *namelenp);
111 
112 static int accept1(struct thread *td, int s, struct sockaddr *uname,
113 		   socklen_t *anamelen, int flags);
114 static int do_sendfile(struct thread *td, struct sendfile_args *uap,
115 		   int compat);
116 static int getsockname1(struct thread *td, struct getsockname_args *uap,
117 			int compat);
118 static int getpeername1(struct thread *td, struct getpeername_args *uap,
119 			int compat);
120 
121 counter_u64_t sfstat[sizeof(struct sfstat) / sizeof(uint64_t)];
122 
123 /*
124  * sendfile(2)-related variables and associated sysctls
125  */
126 static SYSCTL_NODE(_kern_ipc, OID_AUTO, sendfile, CTLFLAG_RW, 0,
127     "sendfile(2) tunables");
128 static int sfreadahead = 1;
129 SYSCTL_INT(_kern_ipc_sendfile, OID_AUTO, readahead, CTLFLAG_RW,
130     &sfreadahead, 0, "Number of sendfile(2) read-ahead MAXBSIZE blocks");
131 
132 
133 static void
134 sfstat_init(const void *unused)
135 {
136 
137 	COUNTER_ARRAY_ALLOC(sfstat, sizeof(struct sfstat) / sizeof(uint64_t),
138 	    M_WAITOK);
139 }
140 SYSINIT(sfstat, SI_SUB_MBUF, SI_ORDER_FIRST, sfstat_init, NULL);
141 
142 static int
143 sfstat_sysctl(SYSCTL_HANDLER_ARGS)
144 {
145 	struct sfstat s;
146 
147 	COUNTER_ARRAY_COPY(sfstat, &s, sizeof(s) / sizeof(uint64_t));
148 	if (req->newptr)
149 		COUNTER_ARRAY_ZERO(sfstat, sizeof(s) / sizeof(uint64_t));
150 	return (SYSCTL_OUT(req, &s, sizeof(s)));
151 }
152 SYSCTL_PROC(_kern_ipc, OID_AUTO, sfstat, CTLTYPE_OPAQUE | CTLFLAG_RW,
153     NULL, 0, sfstat_sysctl, "I", "sendfile statistics");
154 
155 /*
156  * Convert a user file descriptor to a kernel file entry and check if required
157  * capability rights are present.
158  * A reference on the file entry is held upon returning.
159  */
160 static int
161 getsock_cap(struct filedesc *fdp, int fd, cap_rights_t *rightsp,
162     struct file **fpp, u_int *fflagp)
163 {
164 	struct file *fp;
165 	int error;
166 
167 	error = fget_unlocked(fdp, fd, rightsp, 0, &fp, NULL);
168 	if (error != 0)
169 		return (error);
170 	if (fp->f_type != DTYPE_SOCKET) {
171 		fdrop(fp, curthread);
172 		return (ENOTSOCK);
173 	}
174 	if (fflagp != NULL)
175 		*fflagp = fp->f_flag;
176 	*fpp = fp;
177 	return (0);
178 }
179 
180 /*
181  * System call interface to the socket abstraction.
182  */
183 #if defined(COMPAT_43)
184 #define COMPAT_OLDSOCK
185 #endif
186 
187 int
188 sys_socket(td, uap)
189 	struct thread *td;
190 	struct socket_args /* {
191 		int	domain;
192 		int	type;
193 		int	protocol;
194 	} */ *uap;
195 {
196 	struct socket *so;
197 	struct file *fp;
198 	int fd, error, type, oflag, fflag;
199 
200 	AUDIT_ARG_SOCKET(uap->domain, uap->type, uap->protocol);
201 
202 	type = uap->type;
203 	oflag = 0;
204 	fflag = 0;
205 	if ((type & SOCK_CLOEXEC) != 0) {
206 		type &= ~SOCK_CLOEXEC;
207 		oflag |= O_CLOEXEC;
208 	}
209 	if ((type & SOCK_NONBLOCK) != 0) {
210 		type &= ~SOCK_NONBLOCK;
211 		fflag |= FNONBLOCK;
212 	}
213 
214 #ifdef MAC
215 	error = mac_socket_check_create(td->td_ucred, uap->domain, type,
216 	    uap->protocol);
217 	if (error != 0)
218 		return (error);
219 #endif
220 	error = falloc(td, &fp, &fd, oflag);
221 	if (error != 0)
222 		return (error);
223 	/* An extra reference on `fp' has been held for us by falloc(). */
224 	error = socreate(uap->domain, &so, type, uap->protocol,
225 	    td->td_ucred, td);
226 	if (error != 0) {
227 		fdclose(td->td_proc->p_fd, fp, fd, td);
228 	} else {
229 		finit(fp, FREAD | FWRITE | fflag, DTYPE_SOCKET, so, &socketops);
230 		if ((fflag & FNONBLOCK) != 0)
231 			(void) fo_ioctl(fp, FIONBIO, &fflag, td->td_ucred, td);
232 		td->td_retval[0] = fd;
233 	}
234 	fdrop(fp, td);
235 	return (error);
236 }
237 
238 /* ARGSUSED */
239 int
240 sys_bind(td, uap)
241 	struct thread *td;
242 	struct bind_args /* {
243 		int	s;
244 		caddr_t	name;
245 		int	namelen;
246 	} */ *uap;
247 {
248 	struct sockaddr *sa;
249 	int error;
250 
251 	error = getsockaddr(&sa, uap->name, uap->namelen);
252 	if (error == 0) {
253 		error = kern_bind(td, uap->s, sa);
254 		free(sa, M_SONAME);
255 	}
256 	return (error);
257 }
258 
259 static int
260 kern_bindat(struct thread *td, int dirfd, int fd, struct sockaddr *sa)
261 {
262 	struct socket *so;
263 	struct file *fp;
264 	cap_rights_t rights;
265 	int error;
266 
267 	AUDIT_ARG_FD(fd);
268 	AUDIT_ARG_SOCKADDR(td, dirfd, sa);
269 	error = getsock_cap(td->td_proc->p_fd, fd,
270 	    cap_rights_init(&rights, CAP_BIND), &fp, NULL);
271 	if (error != 0)
272 		return (error);
273 	so = fp->f_data;
274 #ifdef KTRACE
275 	if (KTRPOINT(td, KTR_STRUCT))
276 		ktrsockaddr(sa);
277 #endif
278 #ifdef MAC
279 	error = mac_socket_check_bind(td->td_ucred, so, sa);
280 	if (error == 0) {
281 #endif
282 		if (dirfd == AT_FDCWD)
283 			error = sobind(so, sa, td);
284 		else
285 			error = sobindat(dirfd, so, sa, td);
286 #ifdef MAC
287 	}
288 #endif
289 	fdrop(fp, td);
290 	return (error);
291 }
292 
293 int
294 kern_bind(struct thread *td, int fd, struct sockaddr *sa)
295 {
296 
297 	return (kern_bindat(td, AT_FDCWD, fd, sa));
298 }
299 
300 /* ARGSUSED */
301 int
302 sys_bindat(td, uap)
303 	struct thread *td;
304 	struct bindat_args /* {
305 		int	fd;
306 		int	s;
307 		caddr_t	name;
308 		int	namelen;
309 	} */ *uap;
310 {
311 	struct sockaddr *sa;
312 	int error;
313 
314 	error = getsockaddr(&sa, uap->name, uap->namelen);
315 	if (error == 0) {
316 		error = kern_bindat(td, uap->fd, uap->s, sa);
317 		free(sa, M_SONAME);
318 	}
319 	return (error);
320 }
321 
322 /* ARGSUSED */
323 int
324 sys_listen(td, uap)
325 	struct thread *td;
326 	struct listen_args /* {
327 		int	s;
328 		int	backlog;
329 	} */ *uap;
330 {
331 	struct socket *so;
332 	struct file *fp;
333 	cap_rights_t rights;
334 	int error;
335 
336 	AUDIT_ARG_FD(uap->s);
337 	error = getsock_cap(td->td_proc->p_fd, uap->s,
338 	    cap_rights_init(&rights, CAP_LISTEN), &fp, NULL);
339 	if (error == 0) {
340 		so = fp->f_data;
341 #ifdef MAC
342 		error = mac_socket_check_listen(td->td_ucred, so);
343 		if (error == 0)
344 #endif
345 			error = solisten(so, uap->backlog, td);
346 		fdrop(fp, td);
347 	}
348 	return(error);
349 }
350 
351 /*
352  * accept1()
353  */
354 static int
355 accept1(td, s, uname, anamelen, flags)
356 	struct thread *td;
357 	int s;
358 	struct sockaddr *uname;
359 	socklen_t *anamelen;
360 	int flags;
361 {
362 	struct sockaddr *name;
363 	socklen_t namelen;
364 	struct file *fp;
365 	int error;
366 
367 	if (uname == NULL)
368 		return (kern_accept4(td, s, NULL, NULL, flags, NULL));
369 
370 	error = copyin(anamelen, &namelen, sizeof (namelen));
371 	if (error != 0)
372 		return (error);
373 
374 	error = kern_accept4(td, s, &name, &namelen, flags, &fp);
375 
376 	/*
377 	 * return a namelen of zero for older code which might
378 	 * ignore the return value from accept.
379 	 */
380 	if (error != 0) {
381 		(void) copyout(&namelen, anamelen, sizeof(*anamelen));
382 		return (error);
383 	}
384 
385 	if (error == 0 && uname != NULL) {
386 #ifdef COMPAT_OLDSOCK
387 		if (flags & ACCEPT4_COMPAT)
388 			((struct osockaddr *)name)->sa_family =
389 			    name->sa_family;
390 #endif
391 		error = copyout(name, uname, namelen);
392 	}
393 	if (error == 0)
394 		error = copyout(&namelen, anamelen,
395 		    sizeof(namelen));
396 	if (error != 0)
397 		fdclose(td->td_proc->p_fd, fp, td->td_retval[0], td);
398 	fdrop(fp, td);
399 	free(name, M_SONAME);
400 	return (error);
401 }
402 
403 int
404 kern_accept(struct thread *td, int s, struct sockaddr **name,
405     socklen_t *namelen, struct file **fp)
406 {
407 	return (kern_accept4(td, s, name, namelen, ACCEPT4_INHERIT, fp));
408 }
409 
410 int
411 kern_accept4(struct thread *td, int s, struct sockaddr **name,
412     socklen_t *namelen, int flags, struct file **fp)
413 {
414 	struct filedesc *fdp;
415 	struct file *headfp, *nfp = NULL;
416 	struct sockaddr *sa = NULL;
417 	struct socket *head, *so;
418 	cap_rights_t rights;
419 	u_int fflag;
420 	pid_t pgid;
421 	int error, fd, tmp;
422 
423 	if (name != NULL)
424 		*name = NULL;
425 
426 	AUDIT_ARG_FD(s);
427 	fdp = td->td_proc->p_fd;
428 	error = getsock_cap(fdp, s, cap_rights_init(&rights, CAP_ACCEPT),
429 	    &headfp, &fflag);
430 	if (error != 0)
431 		return (error);
432 	head = headfp->f_data;
433 	if ((head->so_options & SO_ACCEPTCONN) == 0) {
434 		error = EINVAL;
435 		goto done;
436 	}
437 #ifdef MAC
438 	error = mac_socket_check_accept(td->td_ucred, head);
439 	if (error != 0)
440 		goto done;
441 #endif
442 	error = falloc(td, &nfp, &fd, (flags & SOCK_CLOEXEC) ? O_CLOEXEC : 0);
443 	if (error != 0)
444 		goto done;
445 	ACCEPT_LOCK();
446 	if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->so_comp)) {
447 		ACCEPT_UNLOCK();
448 		error = EWOULDBLOCK;
449 		goto noconnection;
450 	}
451 	while (TAILQ_EMPTY(&head->so_comp) && head->so_error == 0) {
452 		if (head->so_rcv.sb_state & SBS_CANTRCVMORE) {
453 			head->so_error = ECONNABORTED;
454 			break;
455 		}
456 		error = msleep(&head->so_timeo, &accept_mtx, PSOCK | PCATCH,
457 		    "accept", 0);
458 		if (error != 0) {
459 			ACCEPT_UNLOCK();
460 			goto noconnection;
461 		}
462 	}
463 	if (head->so_error) {
464 		error = head->so_error;
465 		head->so_error = 0;
466 		ACCEPT_UNLOCK();
467 		goto noconnection;
468 	}
469 	so = TAILQ_FIRST(&head->so_comp);
470 	KASSERT(!(so->so_qstate & SQ_INCOMP), ("accept1: so SQ_INCOMP"));
471 	KASSERT(so->so_qstate & SQ_COMP, ("accept1: so not SQ_COMP"));
472 
473 	/*
474 	 * Before changing the flags on the socket, we have to bump the
475 	 * reference count.  Otherwise, if the protocol calls sofree(),
476 	 * the socket will be released due to a zero refcount.
477 	 */
478 	SOCK_LOCK(so);			/* soref() and so_state update */
479 	soref(so);			/* file descriptor reference */
480 
481 	TAILQ_REMOVE(&head->so_comp, so, so_list);
482 	head->so_qlen--;
483 	if (flags & ACCEPT4_INHERIT)
484 		so->so_state |= (head->so_state & SS_NBIO);
485 	else
486 		so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
487 	so->so_qstate &= ~SQ_COMP;
488 	so->so_head = NULL;
489 
490 	SOCK_UNLOCK(so);
491 	ACCEPT_UNLOCK();
492 
493 	/* An extra reference on `nfp' has been held for us by falloc(). */
494 	td->td_retval[0] = fd;
495 
496 	/* connection has been removed from the listen queue */
497 	KNOTE_UNLOCKED(&head->so_rcv.sb_sel.si_note, 0);
498 
499 	if (flags & ACCEPT4_INHERIT) {
500 		pgid = fgetown(&head->so_sigio);
501 		if (pgid != 0)
502 			fsetown(pgid, &so->so_sigio);
503 	} else {
504 		fflag &= ~(FNONBLOCK | FASYNC);
505 		if (flags & SOCK_NONBLOCK)
506 			fflag |= FNONBLOCK;
507 	}
508 
509 	finit(nfp, fflag, DTYPE_SOCKET, so, &socketops);
510 	/* Sync socket nonblocking/async state with file flags */
511 	tmp = fflag & FNONBLOCK;
512 	(void) fo_ioctl(nfp, FIONBIO, &tmp, td->td_ucred, td);
513 	tmp = fflag & FASYNC;
514 	(void) fo_ioctl(nfp, FIOASYNC, &tmp, td->td_ucred, td);
515 	sa = 0;
516 	error = soaccept(so, &sa);
517 	if (error != 0) {
518 		/*
519 		 * return a namelen of zero for older code which might
520 		 * ignore the return value from accept.
521 		 */
522 		if (name)
523 			*namelen = 0;
524 		goto noconnection;
525 	}
526 	if (sa == NULL) {
527 		if (name)
528 			*namelen = 0;
529 		goto done;
530 	}
531 	AUDIT_ARG_SOCKADDR(td, AT_FDCWD, sa);
532 	if (name) {
533 		/* check sa_len before it is destroyed */
534 		if (*namelen > sa->sa_len)
535 			*namelen = sa->sa_len;
536 #ifdef KTRACE
537 		if (KTRPOINT(td, KTR_STRUCT))
538 			ktrsockaddr(sa);
539 #endif
540 		*name = sa;
541 		sa = NULL;
542 	}
543 noconnection:
544 	free(sa, M_SONAME);
545 
546 	/*
547 	 * close the new descriptor, assuming someone hasn't ripped it
548 	 * out from under us.
549 	 */
550 	if (error != 0)
551 		fdclose(fdp, nfp, fd, td);
552 
553 	/*
554 	 * Release explicitly held references before returning.  We return
555 	 * a reference on nfp to the caller on success if they request it.
556 	 */
557 done:
558 	if (fp != NULL) {
559 		if (error == 0) {
560 			*fp = nfp;
561 			nfp = NULL;
562 		} else
563 			*fp = NULL;
564 	}
565 	if (nfp != NULL)
566 		fdrop(nfp, td);
567 	fdrop(headfp, td);
568 	return (error);
569 }
570 
571 int
572 sys_accept(td, uap)
573 	struct thread *td;
574 	struct accept_args *uap;
575 {
576 
577 	return (accept1(td, uap->s, uap->name, uap->anamelen, ACCEPT4_INHERIT));
578 }
579 
580 int
581 sys_accept4(td, uap)
582 	struct thread *td;
583 	struct accept4_args *uap;
584 {
585 
586 	if (uap->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
587 		return (EINVAL);
588 
589 	return (accept1(td, uap->s, uap->name, uap->anamelen, uap->flags));
590 }
591 
592 #ifdef COMPAT_OLDSOCK
593 int
594 oaccept(td, uap)
595 	struct thread *td;
596 	struct accept_args *uap;
597 {
598 
599 	return (accept1(td, uap->s, uap->name, uap->anamelen,
600 	    ACCEPT4_INHERIT | ACCEPT4_COMPAT));
601 }
602 #endif /* COMPAT_OLDSOCK */
603 
604 /* ARGSUSED */
605 int
606 sys_connect(td, uap)
607 	struct thread *td;
608 	struct connect_args /* {
609 		int	s;
610 		caddr_t	name;
611 		int	namelen;
612 	} */ *uap;
613 {
614 	struct sockaddr *sa;
615 	int error;
616 
617 	error = getsockaddr(&sa, uap->name, uap->namelen);
618 	if (error == 0) {
619 		error = kern_connect(td, uap->s, sa);
620 		free(sa, M_SONAME);
621 	}
622 	return (error);
623 }
624 
625 static int
626 kern_connectat(struct thread *td, int dirfd, int fd, struct sockaddr *sa)
627 {
628 	struct socket *so;
629 	struct file *fp;
630 	cap_rights_t rights;
631 	int error, interrupted = 0;
632 
633 	AUDIT_ARG_FD(fd);
634 	AUDIT_ARG_SOCKADDR(td, dirfd, sa);
635 	error = getsock_cap(td->td_proc->p_fd, fd,
636 	    cap_rights_init(&rights, CAP_CONNECT), &fp, NULL);
637 	if (error != 0)
638 		return (error);
639 	so = fp->f_data;
640 	if (so->so_state & SS_ISCONNECTING) {
641 		error = EALREADY;
642 		goto done1;
643 	}
644 #ifdef KTRACE
645 	if (KTRPOINT(td, KTR_STRUCT))
646 		ktrsockaddr(sa);
647 #endif
648 #ifdef MAC
649 	error = mac_socket_check_connect(td->td_ucred, so, sa);
650 	if (error != 0)
651 		goto bad;
652 #endif
653 	if (dirfd == AT_FDCWD)
654 		error = soconnect(so, sa, td);
655 	else
656 		error = soconnectat(dirfd, so, sa, td);
657 	if (error != 0)
658 		goto bad;
659 	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
660 		error = EINPROGRESS;
661 		goto done1;
662 	}
663 	SOCK_LOCK(so);
664 	while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
665 		error = msleep(&so->so_timeo, SOCK_MTX(so), PSOCK | PCATCH,
666 		    "connec", 0);
667 		if (error != 0) {
668 			if (error == EINTR || error == ERESTART)
669 				interrupted = 1;
670 			break;
671 		}
672 	}
673 	if (error == 0) {
674 		error = so->so_error;
675 		so->so_error = 0;
676 	}
677 	SOCK_UNLOCK(so);
678 bad:
679 	if (!interrupted)
680 		so->so_state &= ~SS_ISCONNECTING;
681 	if (error == ERESTART)
682 		error = EINTR;
683 done1:
684 	fdrop(fp, td);
685 	return (error);
686 }
687 
688 int
689 kern_connect(struct thread *td, int fd, struct sockaddr *sa)
690 {
691 
692 	return (kern_connectat(td, AT_FDCWD, fd, sa));
693 }
694 
695 /* ARGSUSED */
696 int
697 sys_connectat(td, uap)
698 	struct thread *td;
699 	struct connectat_args /* {
700 		int	fd;
701 		int	s;
702 		caddr_t	name;
703 		int	namelen;
704 	} */ *uap;
705 {
706 	struct sockaddr *sa;
707 	int error;
708 
709 	error = getsockaddr(&sa, uap->name, uap->namelen);
710 	if (error == 0) {
711 		error = kern_connectat(td, uap->fd, uap->s, sa);
712 		free(sa, M_SONAME);
713 	}
714 	return (error);
715 }
716 
717 int
718 kern_socketpair(struct thread *td, int domain, int type, int protocol,
719     int *rsv)
720 {
721 	struct filedesc *fdp = td->td_proc->p_fd;
722 	struct file *fp1, *fp2;
723 	struct socket *so1, *so2;
724 	int fd, error, oflag, fflag;
725 
726 	AUDIT_ARG_SOCKET(domain, type, protocol);
727 
728 	oflag = 0;
729 	fflag = 0;
730 	if ((type & SOCK_CLOEXEC) != 0) {
731 		type &= ~SOCK_CLOEXEC;
732 		oflag |= O_CLOEXEC;
733 	}
734 	if ((type & SOCK_NONBLOCK) != 0) {
735 		type &= ~SOCK_NONBLOCK;
736 		fflag |= FNONBLOCK;
737 	}
738 #ifdef MAC
739 	/* We might want to have a separate check for socket pairs. */
740 	error = mac_socket_check_create(td->td_ucred, domain, type,
741 	    protocol);
742 	if (error != 0)
743 		return (error);
744 #endif
745 	error = socreate(domain, &so1, type, protocol, td->td_ucred, td);
746 	if (error != 0)
747 		return (error);
748 	error = socreate(domain, &so2, type, protocol, td->td_ucred, td);
749 	if (error != 0)
750 		goto free1;
751 	/* On success extra reference to `fp1' and 'fp2' is set by falloc. */
752 	error = falloc(td, &fp1, &fd, oflag);
753 	if (error != 0)
754 		goto free2;
755 	rsv[0] = fd;
756 	fp1->f_data = so1;	/* so1 already has ref count */
757 	error = falloc(td, &fp2, &fd, oflag);
758 	if (error != 0)
759 		goto free3;
760 	fp2->f_data = so2;	/* so2 already has ref count */
761 	rsv[1] = fd;
762 	error = soconnect2(so1, so2);
763 	if (error != 0)
764 		goto free4;
765 	if (type == SOCK_DGRAM) {
766 		/*
767 		 * Datagram socket connection is asymmetric.
768 		 */
769 		 error = soconnect2(so2, so1);
770 		 if (error != 0)
771 			goto free4;
772 	}
773 	finit(fp1, FREAD | FWRITE | fflag, DTYPE_SOCKET, fp1->f_data,
774 	    &socketops);
775 	finit(fp2, FREAD | FWRITE | fflag, DTYPE_SOCKET, fp2->f_data,
776 	    &socketops);
777 	if ((fflag & FNONBLOCK) != 0) {
778 		(void) fo_ioctl(fp1, FIONBIO, &fflag, td->td_ucred, td);
779 		(void) fo_ioctl(fp2, FIONBIO, &fflag, td->td_ucred, td);
780 	}
781 	fdrop(fp1, td);
782 	fdrop(fp2, td);
783 	return (0);
784 free4:
785 	fdclose(fdp, fp2, rsv[1], td);
786 	fdrop(fp2, td);
787 free3:
788 	fdclose(fdp, fp1, rsv[0], td);
789 	fdrop(fp1, td);
790 free2:
791 	if (so2 != NULL)
792 		(void)soclose(so2);
793 free1:
794 	if (so1 != NULL)
795 		(void)soclose(so1);
796 	return (error);
797 }
798 
799 int
800 sys_socketpair(struct thread *td, struct socketpair_args *uap)
801 {
802 	int error, sv[2];
803 
804 	error = kern_socketpair(td, uap->domain, uap->type,
805 	    uap->protocol, sv);
806 	if (error != 0)
807 		return (error);
808 	error = copyout(sv, uap->rsv, 2 * sizeof(int));
809 	if (error != 0) {
810 		(void)kern_close(td, sv[0]);
811 		(void)kern_close(td, sv[1]);
812 	}
813 	return (error);
814 }
815 
816 static int
817 sendit(td, s, mp, flags)
818 	struct thread *td;
819 	int s;
820 	struct msghdr *mp;
821 	int flags;
822 {
823 	struct mbuf *control;
824 	struct sockaddr *to;
825 	int error;
826 
827 #ifdef CAPABILITY_MODE
828 	if (IN_CAPABILITY_MODE(td) && (mp->msg_name != NULL))
829 		return (ECAPMODE);
830 #endif
831 
832 	if (mp->msg_name != NULL) {
833 		error = getsockaddr(&to, mp->msg_name, mp->msg_namelen);
834 		if (error != 0) {
835 			to = NULL;
836 			goto bad;
837 		}
838 		mp->msg_name = to;
839 	} else {
840 		to = NULL;
841 	}
842 
843 	if (mp->msg_control) {
844 		if (mp->msg_controllen < sizeof(struct cmsghdr)
845 #ifdef COMPAT_OLDSOCK
846 		    && mp->msg_flags != MSG_COMPAT
847 #endif
848 		) {
849 			error = EINVAL;
850 			goto bad;
851 		}
852 		error = sockargs(&control, mp->msg_control,
853 		    mp->msg_controllen, MT_CONTROL);
854 		if (error != 0)
855 			goto bad;
856 #ifdef COMPAT_OLDSOCK
857 		if (mp->msg_flags == MSG_COMPAT) {
858 			struct cmsghdr *cm;
859 
860 			M_PREPEND(control, sizeof(*cm), M_WAITOK);
861 			cm = mtod(control, struct cmsghdr *);
862 			cm->cmsg_len = control->m_len;
863 			cm->cmsg_level = SOL_SOCKET;
864 			cm->cmsg_type = SCM_RIGHTS;
865 		}
866 #endif
867 	} else {
868 		control = NULL;
869 	}
870 
871 	error = kern_sendit(td, s, mp, flags, control, UIO_USERSPACE);
872 
873 bad:
874 	free(to, M_SONAME);
875 	return (error);
876 }
877 
878 int
879 kern_sendit(td, s, mp, flags, control, segflg)
880 	struct thread *td;
881 	int s;
882 	struct msghdr *mp;
883 	int flags;
884 	struct mbuf *control;
885 	enum uio_seg segflg;
886 {
887 	struct file *fp;
888 	struct uio auio;
889 	struct iovec *iov;
890 	struct socket *so;
891 	cap_rights_t rights;
892 #ifdef KTRACE
893 	struct uio *ktruio = NULL;
894 #endif
895 	ssize_t len;
896 	int i, error;
897 
898 	AUDIT_ARG_FD(s);
899 	cap_rights_init(&rights, CAP_SEND);
900 	if (mp->msg_name != NULL) {
901 		AUDIT_ARG_SOCKADDR(td, AT_FDCWD, mp->msg_name);
902 		cap_rights_set(&rights, CAP_CONNECT);
903 	}
904 	error = getsock_cap(td->td_proc->p_fd, s, &rights, &fp, NULL);
905 	if (error != 0)
906 		return (error);
907 	so = (struct socket *)fp->f_data;
908 
909 #ifdef KTRACE
910 	if (mp->msg_name != NULL && KTRPOINT(td, KTR_STRUCT))
911 		ktrsockaddr(mp->msg_name);
912 #endif
913 #ifdef MAC
914 	if (mp->msg_name != NULL) {
915 		error = mac_socket_check_connect(td->td_ucred, so,
916 		    mp->msg_name);
917 		if (error != 0)
918 			goto bad;
919 	}
920 	error = mac_socket_check_send(td->td_ucred, so);
921 	if (error != 0)
922 		goto bad;
923 #endif
924 
925 	auio.uio_iov = mp->msg_iov;
926 	auio.uio_iovcnt = mp->msg_iovlen;
927 	auio.uio_segflg = segflg;
928 	auio.uio_rw = UIO_WRITE;
929 	auio.uio_td = td;
930 	auio.uio_offset = 0;			/* XXX */
931 	auio.uio_resid = 0;
932 	iov = mp->msg_iov;
933 	for (i = 0; i < mp->msg_iovlen; i++, iov++) {
934 		if ((auio.uio_resid += iov->iov_len) < 0) {
935 			error = EINVAL;
936 			goto bad;
937 		}
938 	}
939 #ifdef KTRACE
940 	if (KTRPOINT(td, KTR_GENIO))
941 		ktruio = cloneuio(&auio);
942 #endif
943 	len = auio.uio_resid;
944 	error = sosend(so, mp->msg_name, &auio, 0, control, flags, td);
945 	if (error != 0) {
946 		if (auio.uio_resid != len && (error == ERESTART ||
947 		    error == EINTR || error == EWOULDBLOCK))
948 			error = 0;
949 		/* Generation of SIGPIPE can be controlled per socket */
950 		if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
951 		    !(flags & MSG_NOSIGNAL)) {
952 			PROC_LOCK(td->td_proc);
953 			tdsignal(td, SIGPIPE);
954 			PROC_UNLOCK(td->td_proc);
955 		}
956 	}
957 	if (error == 0)
958 		td->td_retval[0] = len - auio.uio_resid;
959 #ifdef KTRACE
960 	if (ktruio != NULL) {
961 		ktruio->uio_resid = td->td_retval[0];
962 		ktrgenio(s, UIO_WRITE, ktruio, error);
963 	}
964 #endif
965 bad:
966 	fdrop(fp, td);
967 	return (error);
968 }
969 
970 int
971 sys_sendto(td, uap)
972 	struct thread *td;
973 	struct sendto_args /* {
974 		int	s;
975 		caddr_t	buf;
976 		size_t	len;
977 		int	flags;
978 		caddr_t	to;
979 		int	tolen;
980 	} */ *uap;
981 {
982 	struct msghdr msg;
983 	struct iovec aiov;
984 
985 	msg.msg_name = uap->to;
986 	msg.msg_namelen = uap->tolen;
987 	msg.msg_iov = &aiov;
988 	msg.msg_iovlen = 1;
989 	msg.msg_control = 0;
990 #ifdef COMPAT_OLDSOCK
991 	msg.msg_flags = 0;
992 #endif
993 	aiov.iov_base = uap->buf;
994 	aiov.iov_len = uap->len;
995 	return (sendit(td, uap->s, &msg, uap->flags));
996 }
997 
998 #ifdef COMPAT_OLDSOCK
999 int
1000 osend(td, uap)
1001 	struct thread *td;
1002 	struct osend_args /* {
1003 		int	s;
1004 		caddr_t	buf;
1005 		int	len;
1006 		int	flags;
1007 	} */ *uap;
1008 {
1009 	struct msghdr msg;
1010 	struct iovec aiov;
1011 
1012 	msg.msg_name = 0;
1013 	msg.msg_namelen = 0;
1014 	msg.msg_iov = &aiov;
1015 	msg.msg_iovlen = 1;
1016 	aiov.iov_base = uap->buf;
1017 	aiov.iov_len = uap->len;
1018 	msg.msg_control = 0;
1019 	msg.msg_flags = 0;
1020 	return (sendit(td, uap->s, &msg, uap->flags));
1021 }
1022 
1023 int
1024 osendmsg(td, uap)
1025 	struct thread *td;
1026 	struct osendmsg_args /* {
1027 		int	s;
1028 		caddr_t	msg;
1029 		int	flags;
1030 	} */ *uap;
1031 {
1032 	struct msghdr msg;
1033 	struct iovec *iov;
1034 	int error;
1035 
1036 	error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
1037 	if (error != 0)
1038 		return (error);
1039 	error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1040 	if (error != 0)
1041 		return (error);
1042 	msg.msg_iov = iov;
1043 	msg.msg_flags = MSG_COMPAT;
1044 	error = sendit(td, uap->s, &msg, uap->flags);
1045 	free(iov, M_IOV);
1046 	return (error);
1047 }
1048 #endif
1049 
1050 int
1051 sys_sendmsg(td, uap)
1052 	struct thread *td;
1053 	struct sendmsg_args /* {
1054 		int	s;
1055 		caddr_t	msg;
1056 		int	flags;
1057 	} */ *uap;
1058 {
1059 	struct msghdr msg;
1060 	struct iovec *iov;
1061 	int error;
1062 
1063 	error = copyin(uap->msg, &msg, sizeof (msg));
1064 	if (error != 0)
1065 		return (error);
1066 	error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1067 	if (error != 0)
1068 		return (error);
1069 	msg.msg_iov = iov;
1070 #ifdef COMPAT_OLDSOCK
1071 	msg.msg_flags = 0;
1072 #endif
1073 	error = sendit(td, uap->s, &msg, uap->flags);
1074 	free(iov, M_IOV);
1075 	return (error);
1076 }
1077 
1078 int
1079 kern_recvit(td, s, mp, fromseg, controlp)
1080 	struct thread *td;
1081 	int s;
1082 	struct msghdr *mp;
1083 	enum uio_seg fromseg;
1084 	struct mbuf **controlp;
1085 {
1086 	struct uio auio;
1087 	struct iovec *iov;
1088 	struct mbuf *m, *control = NULL;
1089 	caddr_t ctlbuf;
1090 	struct file *fp;
1091 	struct socket *so;
1092 	struct sockaddr *fromsa = NULL;
1093 	cap_rights_t rights;
1094 #ifdef KTRACE
1095 	struct uio *ktruio = NULL;
1096 #endif
1097 	ssize_t len;
1098 	int error, i;
1099 
1100 	if (controlp != NULL)
1101 		*controlp = NULL;
1102 
1103 	AUDIT_ARG_FD(s);
1104 	error = getsock_cap(td->td_proc->p_fd, s,
1105 	    cap_rights_init(&rights, CAP_RECV), &fp, NULL);
1106 	if (error != 0)
1107 		return (error);
1108 	so = fp->f_data;
1109 
1110 #ifdef MAC
1111 	error = mac_socket_check_receive(td->td_ucred, so);
1112 	if (error != 0) {
1113 		fdrop(fp, td);
1114 		return (error);
1115 	}
1116 #endif
1117 
1118 	auio.uio_iov = mp->msg_iov;
1119 	auio.uio_iovcnt = mp->msg_iovlen;
1120 	auio.uio_segflg = UIO_USERSPACE;
1121 	auio.uio_rw = UIO_READ;
1122 	auio.uio_td = td;
1123 	auio.uio_offset = 0;			/* XXX */
1124 	auio.uio_resid = 0;
1125 	iov = mp->msg_iov;
1126 	for (i = 0; i < mp->msg_iovlen; i++, iov++) {
1127 		if ((auio.uio_resid += iov->iov_len) < 0) {
1128 			fdrop(fp, td);
1129 			return (EINVAL);
1130 		}
1131 	}
1132 #ifdef KTRACE
1133 	if (KTRPOINT(td, KTR_GENIO))
1134 		ktruio = cloneuio(&auio);
1135 #endif
1136 	len = auio.uio_resid;
1137 	error = soreceive(so, &fromsa, &auio, NULL,
1138 	    (mp->msg_control || controlp) ? &control : NULL,
1139 	    &mp->msg_flags);
1140 	if (error != 0) {
1141 		if (auio.uio_resid != len && (error == ERESTART ||
1142 		    error == EINTR || error == EWOULDBLOCK))
1143 			error = 0;
1144 	}
1145 	if (fromsa != NULL)
1146 		AUDIT_ARG_SOCKADDR(td, AT_FDCWD, fromsa);
1147 #ifdef KTRACE
1148 	if (ktruio != NULL) {
1149 		ktruio->uio_resid = len - auio.uio_resid;
1150 		ktrgenio(s, UIO_READ, ktruio, error);
1151 	}
1152 #endif
1153 	if (error != 0)
1154 		goto out;
1155 	td->td_retval[0] = len - auio.uio_resid;
1156 	if (mp->msg_name) {
1157 		len = mp->msg_namelen;
1158 		if (len <= 0 || fromsa == NULL)
1159 			len = 0;
1160 		else {
1161 			/* save sa_len before it is destroyed by MSG_COMPAT */
1162 			len = MIN(len, fromsa->sa_len);
1163 #ifdef COMPAT_OLDSOCK
1164 			if (mp->msg_flags & MSG_COMPAT)
1165 				((struct osockaddr *)fromsa)->sa_family =
1166 				    fromsa->sa_family;
1167 #endif
1168 			if (fromseg == UIO_USERSPACE) {
1169 				error = copyout(fromsa, mp->msg_name,
1170 				    (unsigned)len);
1171 				if (error != 0)
1172 					goto out;
1173 			} else
1174 				bcopy(fromsa, mp->msg_name, len);
1175 		}
1176 		mp->msg_namelen = len;
1177 	}
1178 	if (mp->msg_control && controlp == NULL) {
1179 #ifdef COMPAT_OLDSOCK
1180 		/*
1181 		 * We assume that old recvmsg calls won't receive access
1182 		 * rights and other control info, esp. as control info
1183 		 * is always optional and those options didn't exist in 4.3.
1184 		 * If we receive rights, trim the cmsghdr; anything else
1185 		 * is tossed.
1186 		 */
1187 		if (control && mp->msg_flags & MSG_COMPAT) {
1188 			if (mtod(control, struct cmsghdr *)->cmsg_level !=
1189 			    SOL_SOCKET ||
1190 			    mtod(control, struct cmsghdr *)->cmsg_type !=
1191 			    SCM_RIGHTS) {
1192 				mp->msg_controllen = 0;
1193 				goto out;
1194 			}
1195 			control->m_len -= sizeof (struct cmsghdr);
1196 			control->m_data += sizeof (struct cmsghdr);
1197 		}
1198 #endif
1199 		len = mp->msg_controllen;
1200 		m = control;
1201 		mp->msg_controllen = 0;
1202 		ctlbuf = mp->msg_control;
1203 
1204 		while (m && len > 0) {
1205 			unsigned int tocopy;
1206 
1207 			if (len >= m->m_len)
1208 				tocopy = m->m_len;
1209 			else {
1210 				mp->msg_flags |= MSG_CTRUNC;
1211 				tocopy = len;
1212 			}
1213 
1214 			if ((error = copyout(mtod(m, caddr_t),
1215 					ctlbuf, tocopy)) != 0)
1216 				goto out;
1217 
1218 			ctlbuf += tocopy;
1219 			len -= tocopy;
1220 			m = m->m_next;
1221 		}
1222 		mp->msg_controllen = ctlbuf - (caddr_t)mp->msg_control;
1223 	}
1224 out:
1225 	fdrop(fp, td);
1226 #ifdef KTRACE
1227 	if (fromsa && KTRPOINT(td, KTR_STRUCT))
1228 		ktrsockaddr(fromsa);
1229 #endif
1230 	free(fromsa, M_SONAME);
1231 
1232 	if (error == 0 && controlp != NULL)
1233 		*controlp = control;
1234 	else  if (control)
1235 		m_freem(control);
1236 
1237 	return (error);
1238 }
1239 
1240 static int
1241 recvit(td, s, mp, namelenp)
1242 	struct thread *td;
1243 	int s;
1244 	struct msghdr *mp;
1245 	void *namelenp;
1246 {
1247 	int error;
1248 
1249 	error = kern_recvit(td, s, mp, UIO_USERSPACE, NULL);
1250 	if (error != 0)
1251 		return (error);
1252 	if (namelenp != NULL) {
1253 		error = copyout(&mp->msg_namelen, namelenp, sizeof (socklen_t));
1254 #ifdef COMPAT_OLDSOCK
1255 		if (mp->msg_flags & MSG_COMPAT)
1256 			error = 0;	/* old recvfrom didn't check */
1257 #endif
1258 	}
1259 	return (error);
1260 }
1261 
1262 int
1263 sys_recvfrom(td, uap)
1264 	struct thread *td;
1265 	struct recvfrom_args /* {
1266 		int	s;
1267 		caddr_t	buf;
1268 		size_t	len;
1269 		int	flags;
1270 		struct sockaddr * __restrict	from;
1271 		socklen_t * __restrict fromlenaddr;
1272 	} */ *uap;
1273 {
1274 	struct msghdr msg;
1275 	struct iovec aiov;
1276 	int error;
1277 
1278 	if (uap->fromlenaddr) {
1279 		error = copyin(uap->fromlenaddr,
1280 		    &msg.msg_namelen, sizeof (msg.msg_namelen));
1281 		if (error != 0)
1282 			goto done2;
1283 	} else {
1284 		msg.msg_namelen = 0;
1285 	}
1286 	msg.msg_name = uap->from;
1287 	msg.msg_iov = &aiov;
1288 	msg.msg_iovlen = 1;
1289 	aiov.iov_base = uap->buf;
1290 	aiov.iov_len = uap->len;
1291 	msg.msg_control = 0;
1292 	msg.msg_flags = uap->flags;
1293 	error = recvit(td, uap->s, &msg, uap->fromlenaddr);
1294 done2:
1295 	return (error);
1296 }
1297 
1298 #ifdef COMPAT_OLDSOCK
1299 int
1300 orecvfrom(td, uap)
1301 	struct thread *td;
1302 	struct recvfrom_args *uap;
1303 {
1304 
1305 	uap->flags |= MSG_COMPAT;
1306 	return (sys_recvfrom(td, uap));
1307 }
1308 #endif
1309 
1310 #ifdef COMPAT_OLDSOCK
1311 int
1312 orecv(td, uap)
1313 	struct thread *td;
1314 	struct orecv_args /* {
1315 		int	s;
1316 		caddr_t	buf;
1317 		int	len;
1318 		int	flags;
1319 	} */ *uap;
1320 {
1321 	struct msghdr msg;
1322 	struct iovec aiov;
1323 
1324 	msg.msg_name = 0;
1325 	msg.msg_namelen = 0;
1326 	msg.msg_iov = &aiov;
1327 	msg.msg_iovlen = 1;
1328 	aiov.iov_base = uap->buf;
1329 	aiov.iov_len = uap->len;
1330 	msg.msg_control = 0;
1331 	msg.msg_flags = uap->flags;
1332 	return (recvit(td, uap->s, &msg, NULL));
1333 }
1334 
1335 /*
1336  * Old recvmsg.  This code takes advantage of the fact that the old msghdr
1337  * overlays the new one, missing only the flags, and with the (old) access
1338  * rights where the control fields are now.
1339  */
1340 int
1341 orecvmsg(td, uap)
1342 	struct thread *td;
1343 	struct orecvmsg_args /* {
1344 		int	s;
1345 		struct	omsghdr *msg;
1346 		int	flags;
1347 	} */ *uap;
1348 {
1349 	struct msghdr msg;
1350 	struct iovec *iov;
1351 	int error;
1352 
1353 	error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
1354 	if (error != 0)
1355 		return (error);
1356 	error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1357 	if (error != 0)
1358 		return (error);
1359 	msg.msg_flags = uap->flags | MSG_COMPAT;
1360 	msg.msg_iov = iov;
1361 	error = recvit(td, uap->s, &msg, &uap->msg->msg_namelen);
1362 	if (msg.msg_controllen && error == 0)
1363 		error = copyout(&msg.msg_controllen,
1364 		    &uap->msg->msg_accrightslen, sizeof (int));
1365 	free(iov, M_IOV);
1366 	return (error);
1367 }
1368 #endif
1369 
1370 int
1371 sys_recvmsg(td, uap)
1372 	struct thread *td;
1373 	struct recvmsg_args /* {
1374 		int	s;
1375 		struct	msghdr *msg;
1376 		int	flags;
1377 	} */ *uap;
1378 {
1379 	struct msghdr msg;
1380 	struct iovec *uiov, *iov;
1381 	int error;
1382 
1383 	error = copyin(uap->msg, &msg, sizeof (msg));
1384 	if (error != 0)
1385 		return (error);
1386 	error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1387 	if (error != 0)
1388 		return (error);
1389 	msg.msg_flags = uap->flags;
1390 #ifdef COMPAT_OLDSOCK
1391 	msg.msg_flags &= ~MSG_COMPAT;
1392 #endif
1393 	uiov = msg.msg_iov;
1394 	msg.msg_iov = iov;
1395 	error = recvit(td, uap->s, &msg, NULL);
1396 	if (error == 0) {
1397 		msg.msg_iov = uiov;
1398 		error = copyout(&msg, uap->msg, sizeof(msg));
1399 	}
1400 	free(iov, M_IOV);
1401 	return (error);
1402 }
1403 
1404 /* ARGSUSED */
1405 int
1406 sys_shutdown(td, uap)
1407 	struct thread *td;
1408 	struct shutdown_args /* {
1409 		int	s;
1410 		int	how;
1411 	} */ *uap;
1412 {
1413 	struct socket *so;
1414 	struct file *fp;
1415 	cap_rights_t rights;
1416 	int error;
1417 
1418 	AUDIT_ARG_FD(uap->s);
1419 	error = getsock_cap(td->td_proc->p_fd, uap->s,
1420 	    cap_rights_init(&rights, CAP_SHUTDOWN), &fp, NULL);
1421 	if (error == 0) {
1422 		so = fp->f_data;
1423 		error = soshutdown(so, uap->how);
1424 		fdrop(fp, td);
1425 	}
1426 	return (error);
1427 }
1428 
1429 /* ARGSUSED */
1430 int
1431 sys_setsockopt(td, uap)
1432 	struct thread *td;
1433 	struct setsockopt_args /* {
1434 		int	s;
1435 		int	level;
1436 		int	name;
1437 		caddr_t	val;
1438 		int	valsize;
1439 	} */ *uap;
1440 {
1441 
1442 	return (kern_setsockopt(td, uap->s, uap->level, uap->name,
1443 	    uap->val, UIO_USERSPACE, uap->valsize));
1444 }
1445 
1446 int
1447 kern_setsockopt(td, s, level, name, val, valseg, valsize)
1448 	struct thread *td;
1449 	int s;
1450 	int level;
1451 	int name;
1452 	void *val;
1453 	enum uio_seg valseg;
1454 	socklen_t valsize;
1455 {
1456 	struct socket *so;
1457 	struct file *fp;
1458 	struct sockopt sopt;
1459 	cap_rights_t rights;
1460 	int error;
1461 
1462 	if (val == NULL && valsize != 0)
1463 		return (EFAULT);
1464 	if ((int)valsize < 0)
1465 		return (EINVAL);
1466 
1467 	sopt.sopt_dir = SOPT_SET;
1468 	sopt.sopt_level = level;
1469 	sopt.sopt_name = name;
1470 	sopt.sopt_val = val;
1471 	sopt.sopt_valsize = valsize;
1472 	switch (valseg) {
1473 	case UIO_USERSPACE:
1474 		sopt.sopt_td = td;
1475 		break;
1476 	case UIO_SYSSPACE:
1477 		sopt.sopt_td = NULL;
1478 		break;
1479 	default:
1480 		panic("kern_setsockopt called with bad valseg");
1481 	}
1482 
1483 	AUDIT_ARG_FD(s);
1484 	error = getsock_cap(td->td_proc->p_fd, s,
1485 	    cap_rights_init(&rights, CAP_SETSOCKOPT), &fp, NULL);
1486 	if (error == 0) {
1487 		so = fp->f_data;
1488 		error = sosetopt(so, &sopt);
1489 		fdrop(fp, td);
1490 	}
1491 	return(error);
1492 }
1493 
1494 /* ARGSUSED */
1495 int
1496 sys_getsockopt(td, uap)
1497 	struct thread *td;
1498 	struct getsockopt_args /* {
1499 		int	s;
1500 		int	level;
1501 		int	name;
1502 		void * __restrict	val;
1503 		socklen_t * __restrict avalsize;
1504 	} */ *uap;
1505 {
1506 	socklen_t valsize;
1507 	int error;
1508 
1509 	if (uap->val) {
1510 		error = copyin(uap->avalsize, &valsize, sizeof (valsize));
1511 		if (error != 0)
1512 			return (error);
1513 	}
1514 
1515 	error = kern_getsockopt(td, uap->s, uap->level, uap->name,
1516 	    uap->val, UIO_USERSPACE, &valsize);
1517 
1518 	if (error == 0)
1519 		error = copyout(&valsize, uap->avalsize, sizeof (valsize));
1520 	return (error);
1521 }
1522 
1523 /*
1524  * Kernel version of getsockopt.
1525  * optval can be a userland or userspace. optlen is always a kernel pointer.
1526  */
1527 int
1528 kern_getsockopt(td, s, level, name, val, valseg, valsize)
1529 	struct thread *td;
1530 	int s;
1531 	int level;
1532 	int name;
1533 	void *val;
1534 	enum uio_seg valseg;
1535 	socklen_t *valsize;
1536 {
1537 	struct socket *so;
1538 	struct file *fp;
1539 	struct sockopt sopt;
1540 	cap_rights_t rights;
1541 	int error;
1542 
1543 	if (val == NULL)
1544 		*valsize = 0;
1545 	if ((int)*valsize < 0)
1546 		return (EINVAL);
1547 
1548 	sopt.sopt_dir = SOPT_GET;
1549 	sopt.sopt_level = level;
1550 	sopt.sopt_name = name;
1551 	sopt.sopt_val = val;
1552 	sopt.sopt_valsize = (size_t)*valsize; /* checked non-negative above */
1553 	switch (valseg) {
1554 	case UIO_USERSPACE:
1555 		sopt.sopt_td = td;
1556 		break;
1557 	case UIO_SYSSPACE:
1558 		sopt.sopt_td = NULL;
1559 		break;
1560 	default:
1561 		panic("kern_getsockopt called with bad valseg");
1562 	}
1563 
1564 	AUDIT_ARG_FD(s);
1565 	error = getsock_cap(td->td_proc->p_fd, s,
1566 	    cap_rights_init(&rights, CAP_GETSOCKOPT), &fp, NULL);
1567 	if (error == 0) {
1568 		so = fp->f_data;
1569 		error = sogetopt(so, &sopt);
1570 		*valsize = sopt.sopt_valsize;
1571 		fdrop(fp, td);
1572 	}
1573 	return (error);
1574 }
1575 
1576 /*
1577  * getsockname1() - Get socket name.
1578  */
1579 /* ARGSUSED */
1580 static int
1581 getsockname1(td, uap, compat)
1582 	struct thread *td;
1583 	struct getsockname_args /* {
1584 		int	fdes;
1585 		struct sockaddr * __restrict asa;
1586 		socklen_t * __restrict alen;
1587 	} */ *uap;
1588 	int compat;
1589 {
1590 	struct sockaddr *sa;
1591 	socklen_t len;
1592 	int error;
1593 
1594 	error = copyin(uap->alen, &len, sizeof(len));
1595 	if (error != 0)
1596 		return (error);
1597 
1598 	error = kern_getsockname(td, uap->fdes, &sa, &len);
1599 	if (error != 0)
1600 		return (error);
1601 
1602 	if (len != 0) {
1603 #ifdef COMPAT_OLDSOCK
1604 		if (compat)
1605 			((struct osockaddr *)sa)->sa_family = sa->sa_family;
1606 #endif
1607 		error = copyout(sa, uap->asa, (u_int)len);
1608 	}
1609 	free(sa, M_SONAME);
1610 	if (error == 0)
1611 		error = copyout(&len, uap->alen, sizeof(len));
1612 	return (error);
1613 }
1614 
1615 int
1616 kern_getsockname(struct thread *td, int fd, struct sockaddr **sa,
1617     socklen_t *alen)
1618 {
1619 	struct socket *so;
1620 	struct file *fp;
1621 	cap_rights_t rights;
1622 	socklen_t len;
1623 	int error;
1624 
1625 	AUDIT_ARG_FD(fd);
1626 	error = getsock_cap(td->td_proc->p_fd, fd,
1627 	    cap_rights_init(&rights, CAP_GETSOCKNAME), &fp, NULL);
1628 	if (error != 0)
1629 		return (error);
1630 	so = fp->f_data;
1631 	*sa = NULL;
1632 	CURVNET_SET(so->so_vnet);
1633 	error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, sa);
1634 	CURVNET_RESTORE();
1635 	if (error != 0)
1636 		goto bad;
1637 	if (*sa == NULL)
1638 		len = 0;
1639 	else
1640 		len = MIN(*alen, (*sa)->sa_len);
1641 	*alen = len;
1642 #ifdef KTRACE
1643 	if (KTRPOINT(td, KTR_STRUCT))
1644 		ktrsockaddr(*sa);
1645 #endif
1646 bad:
1647 	fdrop(fp, td);
1648 	if (error != 0 && *sa != NULL) {
1649 		free(*sa, M_SONAME);
1650 		*sa = NULL;
1651 	}
1652 	return (error);
1653 }
1654 
1655 int
1656 sys_getsockname(td, uap)
1657 	struct thread *td;
1658 	struct getsockname_args *uap;
1659 {
1660 
1661 	return (getsockname1(td, uap, 0));
1662 }
1663 
1664 #ifdef COMPAT_OLDSOCK
1665 int
1666 ogetsockname(td, uap)
1667 	struct thread *td;
1668 	struct getsockname_args *uap;
1669 {
1670 
1671 	return (getsockname1(td, uap, 1));
1672 }
1673 #endif /* COMPAT_OLDSOCK */
1674 
1675 /*
1676  * getpeername1() - Get name of peer for connected socket.
1677  */
1678 /* ARGSUSED */
1679 static int
1680 getpeername1(td, uap, compat)
1681 	struct thread *td;
1682 	struct getpeername_args /* {
1683 		int	fdes;
1684 		struct sockaddr * __restrict	asa;
1685 		socklen_t * __restrict	alen;
1686 	} */ *uap;
1687 	int compat;
1688 {
1689 	struct sockaddr *sa;
1690 	socklen_t len;
1691 	int error;
1692 
1693 	error = copyin(uap->alen, &len, sizeof (len));
1694 	if (error != 0)
1695 		return (error);
1696 
1697 	error = kern_getpeername(td, uap->fdes, &sa, &len);
1698 	if (error != 0)
1699 		return (error);
1700 
1701 	if (len != 0) {
1702 #ifdef COMPAT_OLDSOCK
1703 		if (compat)
1704 			((struct osockaddr *)sa)->sa_family = sa->sa_family;
1705 #endif
1706 		error = copyout(sa, uap->asa, (u_int)len);
1707 	}
1708 	free(sa, M_SONAME);
1709 	if (error == 0)
1710 		error = copyout(&len, uap->alen, sizeof(len));
1711 	return (error);
1712 }
1713 
1714 int
1715 kern_getpeername(struct thread *td, int fd, struct sockaddr **sa,
1716     socklen_t *alen)
1717 {
1718 	struct socket *so;
1719 	struct file *fp;
1720 	cap_rights_t rights;
1721 	socklen_t len;
1722 	int error;
1723 
1724 	AUDIT_ARG_FD(fd);
1725 	error = getsock_cap(td->td_proc->p_fd, fd,
1726 	    cap_rights_init(&rights, CAP_GETPEERNAME), &fp, NULL);
1727 	if (error != 0)
1728 		return (error);
1729 	so = fp->f_data;
1730 	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1731 		error = ENOTCONN;
1732 		goto done;
1733 	}
1734 	*sa = NULL;
1735 	CURVNET_SET(so->so_vnet);
1736 	error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, sa);
1737 	CURVNET_RESTORE();
1738 	if (error != 0)
1739 		goto bad;
1740 	if (*sa == NULL)
1741 		len = 0;
1742 	else
1743 		len = MIN(*alen, (*sa)->sa_len);
1744 	*alen = len;
1745 #ifdef KTRACE
1746 	if (KTRPOINT(td, KTR_STRUCT))
1747 		ktrsockaddr(*sa);
1748 #endif
1749 bad:
1750 	if (error != 0 && *sa != NULL) {
1751 		free(*sa, M_SONAME);
1752 		*sa = NULL;
1753 	}
1754 done:
1755 	fdrop(fp, td);
1756 	return (error);
1757 }
1758 
1759 int
1760 sys_getpeername(td, uap)
1761 	struct thread *td;
1762 	struct getpeername_args *uap;
1763 {
1764 
1765 	return (getpeername1(td, uap, 0));
1766 }
1767 
1768 #ifdef COMPAT_OLDSOCK
1769 int
1770 ogetpeername(td, uap)
1771 	struct thread *td;
1772 	struct ogetpeername_args *uap;
1773 {
1774 
1775 	/* XXX uap should have type `getpeername_args *' to begin with. */
1776 	return (getpeername1(td, (struct getpeername_args *)uap, 1));
1777 }
1778 #endif /* COMPAT_OLDSOCK */
1779 
1780 int
1781 sockargs(mp, buf, buflen, type)
1782 	struct mbuf **mp;
1783 	caddr_t buf;
1784 	int buflen, type;
1785 {
1786 	struct sockaddr *sa;
1787 	struct mbuf *m;
1788 	int error;
1789 
1790 	if (buflen > MLEN) {
1791 #ifdef COMPAT_OLDSOCK
1792 		if (type == MT_SONAME && buflen <= 112)
1793 			buflen = MLEN;		/* unix domain compat. hack */
1794 		else
1795 #endif
1796 			if (buflen > MCLBYTES)
1797 				return (EINVAL);
1798 	}
1799 	m = m_get2(buflen, M_WAITOK, type, 0);
1800 	m->m_len = buflen;
1801 	error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1802 	if (error != 0)
1803 		(void) m_free(m);
1804 	else {
1805 		*mp = m;
1806 		if (type == MT_SONAME) {
1807 			sa = mtod(m, struct sockaddr *);
1808 
1809 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1810 			if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1811 				sa->sa_family = sa->sa_len;
1812 #endif
1813 			sa->sa_len = buflen;
1814 		}
1815 	}
1816 	return (error);
1817 }
1818 
1819 int
1820 getsockaddr(namp, uaddr, len)
1821 	struct sockaddr **namp;
1822 	caddr_t uaddr;
1823 	size_t len;
1824 {
1825 	struct sockaddr *sa;
1826 	int error;
1827 
1828 	if (len > SOCK_MAXADDRLEN)
1829 		return (ENAMETOOLONG);
1830 	if (len < offsetof(struct sockaddr, sa_data[0]))
1831 		return (EINVAL);
1832 	sa = malloc(len, M_SONAME, M_WAITOK);
1833 	error = copyin(uaddr, sa, len);
1834 	if (error != 0) {
1835 		free(sa, M_SONAME);
1836 	} else {
1837 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1838 		if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1839 			sa->sa_family = sa->sa_len;
1840 #endif
1841 		sa->sa_len = len;
1842 		*namp = sa;
1843 	}
1844 	return (error);
1845 }
1846 
1847 struct sendfile_sync {
1848 	struct mtx	mtx;
1849 	struct cv	cv;
1850 	unsigned	count;
1851 };
1852 
1853 /*
1854  * Detach mapped page and release resources back to the system.
1855  */
1856 int
1857 sf_buf_mext(struct mbuf *mb, void *addr, void *args)
1858 {
1859 	vm_page_t m;
1860 	struct sendfile_sync *sfs;
1861 
1862 	m = sf_buf_page(args);
1863 	sf_buf_free(args);
1864 	vm_page_lock(m);
1865 	vm_page_unwire(m, 0);
1866 	/*
1867 	 * Check for the object going away on us. This can
1868 	 * happen since we don't hold a reference to it.
1869 	 * If so, we're responsible for freeing the page.
1870 	 */
1871 	if (m->wire_count == 0 && m->object == NULL)
1872 		vm_page_free(m);
1873 	vm_page_unlock(m);
1874 	if (addr == NULL)
1875 		return (EXT_FREE_OK);
1876 	sfs = addr;
1877 	mtx_lock(&sfs->mtx);
1878 	KASSERT(sfs->count> 0, ("Sendfile sync botchup count == 0"));
1879 	if (--sfs->count == 0)
1880 		cv_signal(&sfs->cv);
1881 	mtx_unlock(&sfs->mtx);
1882 	return (EXT_FREE_OK);
1883 }
1884 
1885 /*
1886  * sendfile(2)
1887  *
1888  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1889  *	 struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1890  *
1891  * Send a file specified by 'fd' and starting at 'offset' to a socket
1892  * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1893  * 0.  Optionally add a header and/or trailer to the socket output.  If
1894  * specified, write the total number of bytes sent into *sbytes.
1895  */
1896 int
1897 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1898 {
1899 
1900 	return (do_sendfile(td, uap, 0));
1901 }
1902 
1903 static int
1904 do_sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1905 {
1906 	struct sf_hdtr hdtr;
1907 	struct uio *hdr_uio, *trl_uio;
1908 	struct file *fp;
1909 	cap_rights_t rights;
1910 	int error;
1911 
1912 	/*
1913 	 * File offset must be positive.  If it goes beyond EOF
1914 	 * we send only the header/trailer and no payload data.
1915 	 */
1916 	if (uap->offset < 0)
1917 		return (EINVAL);
1918 
1919 	hdr_uio = trl_uio = NULL;
1920 
1921 	if (uap->hdtr != NULL) {
1922 		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1923 		if (error != 0)
1924 			goto out;
1925 		if (hdtr.headers != NULL) {
1926 			error = copyinuio(hdtr.headers, hdtr.hdr_cnt, &hdr_uio);
1927 			if (error != 0)
1928 				goto out;
1929 		}
1930 		if (hdtr.trailers != NULL) {
1931 			error = copyinuio(hdtr.trailers, hdtr.trl_cnt, &trl_uio);
1932 			if (error != 0)
1933 				goto out;
1934 
1935 		}
1936 	}
1937 
1938 	AUDIT_ARG_FD(uap->fd);
1939 
1940 	/*
1941 	 * sendfile(2) can start at any offset within a file so we require
1942 	 * CAP_READ+CAP_SEEK = CAP_PREAD.
1943 	 */
1944 	if ((error = fget_read(td, uap->fd,
1945 	    cap_rights_init(&rights, CAP_PREAD), &fp)) != 0) {
1946 		goto out;
1947 	}
1948 
1949 	error = fo_sendfile(fp, uap->s, hdr_uio, trl_uio, uap->offset,
1950 	    uap->nbytes, uap->sbytes, uap->flags, compat ? SFK_COMPAT : 0, td);
1951 	fdrop(fp, td);
1952 
1953 out:
1954 	free(hdr_uio, M_IOV);
1955 	free(trl_uio, M_IOV);
1956 	return (error);
1957 }
1958 
1959 #ifdef COMPAT_FREEBSD4
1960 int
1961 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1962 {
1963 	struct sendfile_args args;
1964 
1965 	args.fd = uap->fd;
1966 	args.s = uap->s;
1967 	args.offset = uap->offset;
1968 	args.nbytes = uap->nbytes;
1969 	args.hdtr = uap->hdtr;
1970 	args.sbytes = uap->sbytes;
1971 	args.flags = uap->flags;
1972 
1973 	return (do_sendfile(td, &args, 1));
1974 }
1975 #endif /* COMPAT_FREEBSD4 */
1976 
1977 static int
1978 sendfile_readpage(vm_object_t obj, struct vnode *vp, int nd,
1979     off_t off, int xfsize, int bsize, struct thread *td, vm_page_t *res)
1980 {
1981 	vm_page_t m;
1982 	vm_pindex_t pindex;
1983 	ssize_t resid;
1984 	int error, readahead, rv;
1985 
1986 	pindex = OFF_TO_IDX(off);
1987 	VM_OBJECT_WLOCK(obj);
1988 	m = vm_page_grab(obj, pindex, (vp != NULL ? VM_ALLOC_NOBUSY |
1989 	    VM_ALLOC_IGN_SBUSY : 0) | VM_ALLOC_WIRED | VM_ALLOC_NORMAL);
1990 
1991 	/*
1992 	 * Check if page is valid for what we need, otherwise initiate I/O.
1993 	 *
1994 	 * The non-zero nd argument prevents disk I/O, instead we
1995 	 * return the caller what he specified in nd.  In particular,
1996 	 * if we already turned some pages into mbufs, nd == EAGAIN
1997 	 * and the main function send them the pages before we come
1998 	 * here again and block.
1999 	 */
2000 	if (m->valid != 0 && vm_page_is_valid(m, off & PAGE_MASK, xfsize)) {
2001 		if (vp == NULL)
2002 			vm_page_xunbusy(m);
2003 		VM_OBJECT_WUNLOCK(obj);
2004 		*res = m;
2005 		return (0);
2006 	} else if (nd != 0) {
2007 		if (vp == NULL)
2008 			vm_page_xunbusy(m);
2009 		error = nd;
2010 		goto free_page;
2011 	}
2012 
2013 	/*
2014 	 * Get the page from backing store.
2015 	 */
2016 	error = 0;
2017 	if (vp != NULL) {
2018 		VM_OBJECT_WUNLOCK(obj);
2019 		readahead = sfreadahead * MAXBSIZE;
2020 
2021 		/*
2022 		 * Use vn_rdwr() instead of the pager interface for
2023 		 * the vnode, to allow the read-ahead.
2024 		 *
2025 		 * XXXMAC: Because we don't have fp->f_cred here, we
2026 		 * pass in NOCRED.  This is probably wrong, but is
2027 		 * consistent with our original implementation.
2028 		 */
2029 		error = vn_rdwr(UIO_READ, vp, NULL, readahead, trunc_page(off),
2030 		    UIO_NOCOPY, IO_NODELOCKED | IO_VMIO | ((readahead /
2031 		    bsize) << IO_SEQSHIFT), td->td_ucred, NOCRED, &resid, td);
2032 		SFSTAT_INC(sf_iocnt);
2033 		VM_OBJECT_WLOCK(obj);
2034 	} else {
2035 		if (vm_pager_has_page(obj, pindex, NULL, NULL)) {
2036 			rv = vm_pager_get_pages(obj, &m, 1, 0);
2037 			SFSTAT_INC(sf_iocnt);
2038 			m = vm_page_lookup(obj, pindex);
2039 			if (m == NULL)
2040 				error = EIO;
2041 			else if (rv != VM_PAGER_OK) {
2042 				vm_page_lock(m);
2043 				vm_page_free(m);
2044 				vm_page_unlock(m);
2045 				m = NULL;
2046 				error = EIO;
2047 			}
2048 		} else {
2049 			pmap_zero_page(m);
2050 			m->valid = VM_PAGE_BITS_ALL;
2051 			m->dirty = 0;
2052 		}
2053 		if (m != NULL)
2054 			vm_page_xunbusy(m);
2055 	}
2056 	if (error == 0) {
2057 		*res = m;
2058 	} else if (m != NULL) {
2059 free_page:
2060 		vm_page_lock(m);
2061 		vm_page_unwire(m, 0);
2062 
2063 		/*
2064 		 * See if anyone else might know about this page.  If
2065 		 * not and it is not valid, then free it.
2066 		 */
2067 		if (m->wire_count == 0 && m->valid == 0 && !vm_page_busied(m))
2068 			vm_page_free(m);
2069 		vm_page_unlock(m);
2070 	}
2071 	KASSERT(error != 0 || (m->wire_count > 0 &&
2072 	    vm_page_is_valid(m, off & PAGE_MASK, xfsize)),
2073 	    ("wrong page state m %p", m));
2074 	VM_OBJECT_WUNLOCK(obj);
2075 	return (error);
2076 }
2077 
2078 static int
2079 sendfile_getobj(struct thread *td, struct file *fp, vm_object_t *obj_res,
2080     struct vnode **vp_res, struct shmfd **shmfd_res, off_t *obj_size,
2081     int *bsize)
2082 {
2083 	struct vattr va;
2084 	vm_object_t obj;
2085 	struct vnode *vp;
2086 	struct shmfd *shmfd;
2087 	int error;
2088 
2089 	vp = *vp_res = NULL;
2090 	obj = NULL;
2091 	shmfd = *shmfd_res = NULL;
2092 	*bsize = 0;
2093 
2094 	/*
2095 	 * The file descriptor must be a regular file and have a
2096 	 * backing VM object.
2097 	 */
2098 	if (fp->f_type == DTYPE_VNODE) {
2099 		vp = fp->f_vnode;
2100 		vn_lock(vp, LK_SHARED | LK_RETRY);
2101 		if (vp->v_type != VREG) {
2102 			error = EINVAL;
2103 			goto out;
2104 		}
2105 		*bsize = vp->v_mount->mnt_stat.f_iosize;
2106 		error = VOP_GETATTR(vp, &va, td->td_ucred);
2107 		if (error != 0)
2108 			goto out;
2109 		*obj_size = va.va_size;
2110 		obj = vp->v_object;
2111 		if (obj == NULL) {
2112 			error = EINVAL;
2113 			goto out;
2114 		}
2115 	} else if (fp->f_type == DTYPE_SHM) {
2116 		shmfd = fp->f_data;
2117 		obj = shmfd->shm_object;
2118 		*obj_size = shmfd->shm_size;
2119 	} else {
2120 		error = EINVAL;
2121 		goto out;
2122 	}
2123 
2124 	VM_OBJECT_WLOCK(obj);
2125 	if ((obj->flags & OBJ_DEAD) != 0) {
2126 		VM_OBJECT_WUNLOCK(obj);
2127 		error = EBADF;
2128 		goto out;
2129 	}
2130 
2131 	/*
2132 	 * Temporarily increase the backing VM object's reference
2133 	 * count so that a forced reclamation of its vnode does not
2134 	 * immediately destroy it.
2135 	 */
2136 	vm_object_reference_locked(obj);
2137 	VM_OBJECT_WUNLOCK(obj);
2138 	*obj_res = obj;
2139 	*vp_res = vp;
2140 	*shmfd_res = shmfd;
2141 
2142 out:
2143 	if (vp != NULL)
2144 		VOP_UNLOCK(vp, 0);
2145 	return (error);
2146 }
2147 
2148 static int
2149 kern_sendfile_getsock(struct thread *td, int s, struct file **sock_fp,
2150     struct socket **so)
2151 {
2152 	cap_rights_t rights;
2153 	int error;
2154 
2155 	*sock_fp = NULL;
2156 	*so = NULL;
2157 
2158 	/*
2159 	 * The socket must be a stream socket and connected.
2160 	 */
2161 	error = getsock_cap(td->td_proc->p_fd, s, cap_rights_init(&rights,
2162 	    CAP_SEND), sock_fp, NULL);
2163 	if (error != 0)
2164 		return (error);
2165 	*so = (*sock_fp)->f_data;
2166 	if ((*so)->so_type != SOCK_STREAM)
2167 		return (EINVAL);
2168 	if (((*so)->so_state & SS_ISCONNECTED) == 0)
2169 		return (ENOTCONN);
2170 	return (0);
2171 }
2172 
2173 int
2174 vn_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
2175     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
2176     int kflags, struct thread *td)
2177 {
2178 	struct file *sock_fp;
2179 	struct vnode *vp;
2180 	struct vm_object *obj;
2181 	struct socket *so;
2182 	struct mbuf *m;
2183 	struct sf_buf *sf;
2184 	struct vm_page *pg;
2185 	struct shmfd *shmfd;
2186 	struct sendfile_sync *sfs;
2187 	struct vattr va;
2188 	off_t off, xfsize, fsbytes, sbytes, rem, obj_size;
2189 	int error, bsize, nd, hdrlen, mnw;
2190 	bool inflight_called;
2191 
2192 	pg = NULL;
2193 	obj = NULL;
2194 	so = NULL;
2195 	m = NULL;
2196 	sfs = NULL;
2197 	fsbytes = sbytes = 0;
2198 	hdrlen = mnw = 0;
2199 	rem = nbytes;
2200 	obj_size = 0;
2201 	inflight_called = false;
2202 
2203 	error = sendfile_getobj(td, fp, &obj, &vp, &shmfd, &obj_size, &bsize);
2204 	if (error != 0)
2205 		return (error);
2206 	if (rem == 0)
2207 		rem = obj_size;
2208 
2209 	error = kern_sendfile_getsock(td, sockfd, &sock_fp, &so);
2210 	if (error != 0)
2211 		goto out;
2212 
2213 	/*
2214 	 * Do not wait on memory allocations but return ENOMEM for
2215 	 * caller to retry later.
2216 	 * XXX: Experimental.
2217 	 */
2218 	if (flags & SF_MNOWAIT)
2219 		mnw = 1;
2220 
2221 	if (flags & SF_SYNC) {
2222 		sfs = malloc(sizeof *sfs, M_TEMP, M_WAITOK | M_ZERO);
2223 		mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
2224 		cv_init(&sfs->cv, "sendfile");
2225 	}
2226 
2227 #ifdef MAC
2228 	error = mac_socket_check_send(td->td_ucred, so);
2229 	if (error != 0)
2230 		goto out;
2231 #endif
2232 
2233 	/* If headers are specified copy them into mbufs. */
2234 	if (hdr_uio != NULL) {
2235 		hdr_uio->uio_td = td;
2236 		hdr_uio->uio_rw = UIO_WRITE;
2237 		if (hdr_uio->uio_resid > 0) {
2238 			/*
2239 			 * In FBSD < 5.0 the nbytes to send also included
2240 			 * the header.  If compat is specified subtract the
2241 			 * header size from nbytes.
2242 			 */
2243 			if (kflags & SFK_COMPAT) {
2244 				if (nbytes > hdr_uio->uio_resid)
2245 					nbytes -= hdr_uio->uio_resid;
2246 				else
2247 					nbytes = 0;
2248 			}
2249 			m = m_uiotombuf(hdr_uio, (mnw ? M_NOWAIT : M_WAITOK),
2250 			    0, 0, 0);
2251 			if (m == NULL) {
2252 				error = mnw ? EAGAIN : ENOBUFS;
2253 				goto out;
2254 			}
2255 			hdrlen = m_length(m, NULL);
2256 		}
2257 	}
2258 
2259 	/*
2260 	 * Protect against multiple writers to the socket.
2261 	 *
2262 	 * XXXRW: Historically this has assumed non-interruptibility, so now
2263 	 * we implement that, but possibly shouldn't.
2264 	 */
2265 	(void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
2266 
2267 	/*
2268 	 * Loop through the pages of the file, starting with the requested
2269 	 * offset. Get a file page (do I/O if necessary), map the file page
2270 	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
2271 	 * it on the socket.
2272 	 * This is done in two loops.  The inner loop turns as many pages
2273 	 * as it can, up to available socket buffer space, without blocking
2274 	 * into mbufs to have it bulk delivered into the socket send buffer.
2275 	 * The outer loop checks the state and available space of the socket
2276 	 * and takes care of the overall progress.
2277 	 */
2278 	for (off = offset; ; ) {
2279 		struct mbuf *mtail;
2280 		int loopbytes;
2281 		int space;
2282 		int done;
2283 
2284 		if ((nbytes != 0 && nbytes == fsbytes) ||
2285 		    (nbytes == 0 && obj_size == fsbytes))
2286 			break;
2287 
2288 		mtail = NULL;
2289 		loopbytes = 0;
2290 		space = 0;
2291 		done = 0;
2292 
2293 		/*
2294 		 * Check the socket state for ongoing connection,
2295 		 * no errors and space in socket buffer.
2296 		 * If space is low allow for the remainder of the
2297 		 * file to be processed if it fits the socket buffer.
2298 		 * Otherwise block in waiting for sufficient space
2299 		 * to proceed, or if the socket is nonblocking, return
2300 		 * to userland with EAGAIN while reporting how far
2301 		 * we've come.
2302 		 * We wait until the socket buffer has significant free
2303 		 * space to do bulk sends.  This makes good use of file
2304 		 * system read ahead and allows packet segmentation
2305 		 * offloading hardware to take over lots of work.  If
2306 		 * we were not careful here we would send off only one
2307 		 * sfbuf at a time.
2308 		 */
2309 		SOCKBUF_LOCK(&so->so_snd);
2310 		if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
2311 			so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
2312 retry_space:
2313 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2314 			error = EPIPE;
2315 			SOCKBUF_UNLOCK(&so->so_snd);
2316 			goto done;
2317 		} else if (so->so_error) {
2318 			error = so->so_error;
2319 			so->so_error = 0;
2320 			SOCKBUF_UNLOCK(&so->so_snd);
2321 			goto done;
2322 		}
2323 		space = sbspace(&so->so_snd);
2324 		if (space < rem &&
2325 		    (space <= 0 ||
2326 		     space < so->so_snd.sb_lowat)) {
2327 			if (so->so_state & SS_NBIO) {
2328 				SOCKBUF_UNLOCK(&so->so_snd);
2329 				error = EAGAIN;
2330 				goto done;
2331 			}
2332 			/*
2333 			 * sbwait drops the lock while sleeping.
2334 			 * When we loop back to retry_space the
2335 			 * state may have changed and we retest
2336 			 * for it.
2337 			 */
2338 			error = sbwait(&so->so_snd);
2339 			/*
2340 			 * An error from sbwait usually indicates that we've
2341 			 * been interrupted by a signal. If we've sent anything
2342 			 * then return bytes sent, otherwise return the error.
2343 			 */
2344 			if (error != 0) {
2345 				SOCKBUF_UNLOCK(&so->so_snd);
2346 				goto done;
2347 			}
2348 			goto retry_space;
2349 		}
2350 		SOCKBUF_UNLOCK(&so->so_snd);
2351 
2352 		/*
2353 		 * Reduce space in the socket buffer by the size of
2354 		 * the header mbuf chain.
2355 		 * hdrlen is set to 0 after the first loop.
2356 		 */
2357 		space -= hdrlen;
2358 
2359 		if (vp != NULL) {
2360 			error = vn_lock(vp, LK_SHARED);
2361 			if (error != 0)
2362 				goto done;
2363 			error = VOP_GETATTR(vp, &va, td->td_ucred);
2364 			if (error != 0 || off >= va.va_size) {
2365 				VOP_UNLOCK(vp, 0);
2366 				goto done;
2367 			}
2368 			obj_size = va.va_size;
2369 		}
2370 
2371 		/*
2372 		 * Loop and construct maximum sized mbuf chain to be bulk
2373 		 * dumped into socket buffer.
2374 		 */
2375 		while (space > loopbytes) {
2376 			vm_offset_t pgoff;
2377 			struct mbuf *m0;
2378 
2379 			/*
2380 			 * Calculate the amount to transfer.
2381 			 * Not to exceed a page, the EOF,
2382 			 * or the passed in nbytes.
2383 			 */
2384 			pgoff = (vm_offset_t)(off & PAGE_MASK);
2385 			rem = obj_size - offset;
2386 			if (nbytes != 0)
2387 				rem = omin(rem, nbytes);
2388 			rem -= fsbytes + loopbytes;
2389 			xfsize = omin(PAGE_SIZE - pgoff, rem);
2390 			xfsize = omin(space - loopbytes, xfsize);
2391 			if (xfsize <= 0) {
2392 				done = 1;		/* all data sent */
2393 				break;
2394 			}
2395 
2396 			/*
2397 			 * Attempt to look up the page.  Allocate
2398 			 * if not found or wait and loop if busy.
2399 			 */
2400 			if (m != NULL)
2401 				nd = EAGAIN; /* send what we already got */
2402 			else if ((flags & SF_NODISKIO) != 0)
2403 				nd = EBUSY;
2404 			else
2405 				nd = 0;
2406 			error = sendfile_readpage(obj, vp, nd, off,
2407 			    xfsize, bsize, td, &pg);
2408 			if (error != 0) {
2409 				if (error == EAGAIN)
2410 					error = 0;	/* not a real error */
2411 				break;
2412 			}
2413 
2414 			/*
2415 			 * Get a sendfile buf.  When allocating the
2416 			 * first buffer for mbuf chain, we usually
2417 			 * wait as long as necessary, but this wait
2418 			 * can be interrupted.  For consequent
2419 			 * buffers, do not sleep, since several
2420 			 * threads might exhaust the buffers and then
2421 			 * deadlock.
2422 			 */
2423 			sf = sf_buf_alloc(pg, (mnw || m != NULL) ? SFB_NOWAIT :
2424 			    SFB_CATCH);
2425 			if (sf == NULL) {
2426 				SFSTAT_INC(sf_allocfail);
2427 				vm_page_lock(pg);
2428 				vm_page_unwire(pg, 0);
2429 				KASSERT(pg->object != NULL,
2430 				    ("%s: object disappeared", __func__));
2431 				vm_page_unlock(pg);
2432 				if (m == NULL)
2433 					error = (mnw ? EAGAIN : EINTR);
2434 				break;
2435 			}
2436 
2437 			/*
2438 			 * Get an mbuf and set it up as having
2439 			 * external storage.
2440 			 */
2441 			m0 = m_get((mnw ? M_NOWAIT : M_WAITOK), MT_DATA);
2442 			if (m0 == NULL) {
2443 				error = (mnw ? EAGAIN : ENOBUFS);
2444 				(void)sf_buf_mext(NULL, NULL, sf);
2445 				break;
2446 			}
2447 			if (m_extadd(m0, (caddr_t )sf_buf_kva(sf), PAGE_SIZE,
2448 			    sf_buf_mext, sfs, sf, M_RDONLY, EXT_SFBUF,
2449 			    (mnw ? M_NOWAIT : M_WAITOK)) != 0) {
2450 				error = (mnw ? EAGAIN : ENOBUFS);
2451 				(void)sf_buf_mext(NULL, NULL, sf);
2452 				m_freem(m0);
2453 				break;
2454 			}
2455 			m0->m_data = (char *)sf_buf_kva(sf) + pgoff;
2456 			m0->m_len = xfsize;
2457 
2458 			/* Append to mbuf chain. */
2459 			if (mtail != NULL)
2460 				mtail->m_next = m0;
2461 			else if (m != NULL)
2462 				m_last(m)->m_next = m0;
2463 			else
2464 				m = m0;
2465 			mtail = m0;
2466 
2467 			/* Keep track of bits processed. */
2468 			loopbytes += xfsize;
2469 			off += xfsize;
2470 
2471 			if (sfs != NULL) {
2472 				mtx_lock(&sfs->mtx);
2473 				sfs->count++;
2474 				mtx_unlock(&sfs->mtx);
2475 			}
2476 		}
2477 
2478 		if (vp != NULL)
2479 			VOP_UNLOCK(vp, 0);
2480 
2481 		/* Add the buffer chain to the socket buffer. */
2482 		if (m != NULL) {
2483 			int mlen, err;
2484 
2485 			mlen = m_length(m, NULL);
2486 			SOCKBUF_LOCK(&so->so_snd);
2487 			if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2488 				error = EPIPE;
2489 				SOCKBUF_UNLOCK(&so->so_snd);
2490 				goto done;
2491 			}
2492 			SOCKBUF_UNLOCK(&so->so_snd);
2493 			CURVNET_SET(so->so_vnet);
2494 			/* Avoid error aliasing. */
2495 			err = (*so->so_proto->pr_usrreqs->pru_send)
2496 				    (so, 0, m, NULL, NULL, td);
2497 			CURVNET_RESTORE();
2498 			if (err == 0) {
2499 				/*
2500 				 * We need two counters to get the
2501 				 * file offset and nbytes to send
2502 				 * right:
2503 				 * - sbytes contains the total amount
2504 				 *   of bytes sent, including headers.
2505 				 * - fsbytes contains the total amount
2506 				 *   of bytes sent from the file.
2507 				 */
2508 				sbytes += mlen;
2509 				fsbytes += mlen;
2510 				if (hdrlen) {
2511 					fsbytes -= hdrlen;
2512 					hdrlen = 0;
2513 				}
2514 			} else if (error == 0)
2515 				error = err;
2516 			m = NULL;	/* pru_send always consumes */
2517 		}
2518 
2519 		/* Quit outer loop on error or when we're done. */
2520 		if (done)
2521 			break;
2522 		if (error != 0)
2523 			goto done;
2524 	}
2525 
2526 	/*
2527 	 * Send trailers. Wimp out and use writev(2).
2528 	 */
2529 	if (trl_uio != NULL) {
2530 		sbunlock(&so->so_snd);
2531 		error = kern_writev(td, sockfd, trl_uio);
2532 		if (error == 0)
2533 			sbytes += td->td_retval[0];
2534 		goto out;
2535 	}
2536 
2537 done:
2538 	sbunlock(&so->so_snd);
2539 out:
2540 	/*
2541 	 * If there was no error we have to clear td->td_retval[0]
2542 	 * because it may have been set by writev.
2543 	 */
2544 	if (error == 0) {
2545 		td->td_retval[0] = 0;
2546 	}
2547 	if (sent != NULL) {
2548 		copyout(&sbytes, sent, sizeof(off_t));
2549 	}
2550 	if (obj != NULL)
2551 		vm_object_deallocate(obj);
2552 	if (so)
2553 		fdrop(sock_fp, td);
2554 	if (m)
2555 		m_freem(m);
2556 
2557 	if (sfs != NULL) {
2558 		mtx_lock(&sfs->mtx);
2559 		if (sfs->count != 0)
2560 			cv_wait(&sfs->cv, &sfs->mtx);
2561 		KASSERT(sfs->count == 0, ("sendfile sync still busy"));
2562 		cv_destroy(&sfs->cv);
2563 		mtx_destroy(&sfs->mtx);
2564 		free(sfs, M_TEMP);
2565 	}
2566 
2567 	if (error == ERESTART)
2568 		error = EINTR;
2569 
2570 	return (error);
2571 }
2572 
2573 /*
2574  * SCTP syscalls.
2575  * Functionality only compiled in if SCTP is defined in the kernel Makefile,
2576  * otherwise all return EOPNOTSUPP.
2577  * XXX: We should make this loadable one day.
2578  */
2579 int
2580 sys_sctp_peeloff(td, uap)
2581 	struct thread *td;
2582 	struct sctp_peeloff_args /* {
2583 		int	sd;
2584 		caddr_t	name;
2585 	} */ *uap;
2586 {
2587 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2588 	struct file *nfp = NULL;
2589 	struct socket *head, *so;
2590 	cap_rights_t rights;
2591 	u_int fflag;
2592 	int error, fd;
2593 
2594 	AUDIT_ARG_FD(uap->sd);
2595 	error = fgetsock(td, uap->sd, cap_rights_init(&rights, CAP_PEELOFF),
2596 	    &head, &fflag);
2597 	if (error != 0)
2598 		goto done2;
2599 	if (head->so_proto->pr_protocol != IPPROTO_SCTP) {
2600 		error = EOPNOTSUPP;
2601 		goto done;
2602 	}
2603 	error = sctp_can_peel_off(head, (sctp_assoc_t)uap->name);
2604 	if (error != 0)
2605 		goto done;
2606 	/*
2607 	 * At this point we know we do have a assoc to pull
2608 	 * we proceed to get the fd setup. This may block
2609 	 * but that is ok.
2610 	 */
2611 
2612 	error = falloc(td, &nfp, &fd, 0);
2613 	if (error != 0)
2614 		goto done;
2615 	td->td_retval[0] = fd;
2616 
2617 	CURVNET_SET(head->so_vnet);
2618 	so = sonewconn(head, SS_ISCONNECTED);
2619 	if (so == NULL) {
2620 		error = ENOMEM;
2621 		goto noconnection;
2622 	}
2623 	/*
2624 	 * Before changing the flags on the socket, we have to bump the
2625 	 * reference count.  Otherwise, if the protocol calls sofree(),
2626 	 * the socket will be released due to a zero refcount.
2627 	 */
2628         SOCK_LOCK(so);
2629         soref(so);                      /* file descriptor reference */
2630         SOCK_UNLOCK(so);
2631 
2632 	ACCEPT_LOCK();
2633 
2634 	TAILQ_REMOVE(&head->so_comp, so, so_list);
2635 	head->so_qlen--;
2636 	so->so_state |= (head->so_state & SS_NBIO);
2637 	so->so_state &= ~SS_NOFDREF;
2638 	so->so_qstate &= ~SQ_COMP;
2639 	so->so_head = NULL;
2640 	ACCEPT_UNLOCK();
2641 	finit(nfp, fflag, DTYPE_SOCKET, so, &socketops);
2642 	error = sctp_do_peeloff(head, so, (sctp_assoc_t)uap->name);
2643 	if (error != 0)
2644 		goto noconnection;
2645 	if (head->so_sigio != NULL)
2646 		fsetown(fgetown(&head->so_sigio), &so->so_sigio);
2647 
2648 noconnection:
2649 	/*
2650 	 * close the new descriptor, assuming someone hasn't ripped it
2651 	 * out from under us.
2652 	 */
2653 	if (error != 0)
2654 		fdclose(td->td_proc->p_fd, nfp, fd, td);
2655 
2656 	/*
2657 	 * Release explicitly held references before returning.
2658 	 */
2659 	CURVNET_RESTORE();
2660 done:
2661 	if (nfp != NULL)
2662 		fdrop(nfp, td);
2663 	fputsock(head);
2664 done2:
2665 	return (error);
2666 #else  /* SCTP */
2667 	return (EOPNOTSUPP);
2668 #endif /* SCTP */
2669 }
2670 
2671 int
2672 sys_sctp_generic_sendmsg (td, uap)
2673 	struct thread *td;
2674 	struct sctp_generic_sendmsg_args /* {
2675 		int sd,
2676 		caddr_t msg,
2677 		int mlen,
2678 		caddr_t to,
2679 		__socklen_t tolen,
2680 		struct sctp_sndrcvinfo *sinfo,
2681 		int flags
2682 	} */ *uap;
2683 {
2684 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2685 	struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2686 	struct socket *so;
2687 	struct file *fp = NULL;
2688 	struct sockaddr *to = NULL;
2689 #ifdef KTRACE
2690 	struct uio *ktruio = NULL;
2691 #endif
2692 	struct uio auio;
2693 	struct iovec iov[1];
2694 	cap_rights_t rights;
2695 	int error = 0, len;
2696 
2697 	if (uap->sinfo != NULL) {
2698 		error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2699 		if (error != 0)
2700 			return (error);
2701 		u_sinfo = &sinfo;
2702 	}
2703 
2704 	cap_rights_init(&rights, CAP_SEND);
2705 	if (uap->tolen != 0) {
2706 		error = getsockaddr(&to, uap->to, uap->tolen);
2707 		if (error != 0) {
2708 			to = NULL;
2709 			goto sctp_bad2;
2710 		}
2711 		cap_rights_set(&rights, CAP_CONNECT);
2712 	}
2713 
2714 	AUDIT_ARG_FD(uap->sd);
2715 	error = getsock_cap(td->td_proc->p_fd, uap->sd, &rights, &fp, NULL);
2716 	if (error != 0)
2717 		goto sctp_bad;
2718 #ifdef KTRACE
2719 	if (to && (KTRPOINT(td, KTR_STRUCT)))
2720 		ktrsockaddr(to);
2721 #endif
2722 
2723 	iov[0].iov_base = uap->msg;
2724 	iov[0].iov_len = uap->mlen;
2725 
2726 	so = (struct socket *)fp->f_data;
2727 	if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2728 		error = EOPNOTSUPP;
2729 		goto sctp_bad;
2730 	}
2731 #ifdef MAC
2732 	error = mac_socket_check_send(td->td_ucred, so);
2733 	if (error != 0)
2734 		goto sctp_bad;
2735 #endif /* MAC */
2736 
2737 	auio.uio_iov =  iov;
2738 	auio.uio_iovcnt = 1;
2739 	auio.uio_segflg = UIO_USERSPACE;
2740 	auio.uio_rw = UIO_WRITE;
2741 	auio.uio_td = td;
2742 	auio.uio_offset = 0;			/* XXX */
2743 	auio.uio_resid = 0;
2744 	len = auio.uio_resid = uap->mlen;
2745 	CURVNET_SET(so->so_vnet);
2746 	error = sctp_lower_sosend(so, to, &auio, (struct mbuf *)NULL,
2747 	    (struct mbuf *)NULL, uap->flags, u_sinfo, td);
2748 	CURVNET_RESTORE();
2749 	if (error != 0) {
2750 		if (auio.uio_resid != len && (error == ERESTART ||
2751 		    error == EINTR || error == EWOULDBLOCK))
2752 			error = 0;
2753 		/* Generation of SIGPIPE can be controlled per socket. */
2754 		if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2755 		    !(uap->flags & MSG_NOSIGNAL)) {
2756 			PROC_LOCK(td->td_proc);
2757 			tdsignal(td, SIGPIPE);
2758 			PROC_UNLOCK(td->td_proc);
2759 		}
2760 	}
2761 	if (error == 0)
2762 		td->td_retval[0] = len - auio.uio_resid;
2763 #ifdef KTRACE
2764 	if (ktruio != NULL) {
2765 		ktruio->uio_resid = td->td_retval[0];
2766 		ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2767 	}
2768 #endif /* KTRACE */
2769 sctp_bad:
2770 	if (fp != NULL)
2771 		fdrop(fp, td);
2772 sctp_bad2:
2773 	free(to, M_SONAME);
2774 	return (error);
2775 #else  /* SCTP */
2776 	return (EOPNOTSUPP);
2777 #endif /* SCTP */
2778 }
2779 
2780 int
2781 sys_sctp_generic_sendmsg_iov(td, uap)
2782 	struct thread *td;
2783 	struct sctp_generic_sendmsg_iov_args /* {
2784 		int sd,
2785 		struct iovec *iov,
2786 		int iovlen,
2787 		caddr_t to,
2788 		__socklen_t tolen,
2789 		struct sctp_sndrcvinfo *sinfo,
2790 		int flags
2791 	} */ *uap;
2792 {
2793 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2794 	struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2795 	struct socket *so;
2796 	struct file *fp = NULL;
2797 	struct sockaddr *to = NULL;
2798 #ifdef KTRACE
2799 	struct uio *ktruio = NULL;
2800 #endif
2801 	struct uio auio;
2802 	struct iovec *iov, *tiov;
2803 	cap_rights_t rights;
2804 	ssize_t len;
2805 	int error, i;
2806 
2807 	if (uap->sinfo != NULL) {
2808 		error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2809 		if (error != 0)
2810 			return (error);
2811 		u_sinfo = &sinfo;
2812 	}
2813 	cap_rights_init(&rights, CAP_SEND);
2814 	if (uap->tolen != 0) {
2815 		error = getsockaddr(&to, uap->to, uap->tolen);
2816 		if (error != 0) {
2817 			to = NULL;
2818 			goto sctp_bad2;
2819 		}
2820 		cap_rights_set(&rights, CAP_CONNECT);
2821 	}
2822 
2823 	AUDIT_ARG_FD(uap->sd);
2824 	error = getsock_cap(td->td_proc->p_fd, uap->sd, &rights, &fp, NULL);
2825 	if (error != 0)
2826 		goto sctp_bad1;
2827 
2828 #ifdef COMPAT_FREEBSD32
2829 	if (SV_CURPROC_FLAG(SV_ILP32))
2830 		error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2831 		    uap->iovlen, &iov, EMSGSIZE);
2832 	else
2833 #endif
2834 		error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2835 	if (error != 0)
2836 		goto sctp_bad1;
2837 #ifdef KTRACE
2838 	if (to && (KTRPOINT(td, KTR_STRUCT)))
2839 		ktrsockaddr(to);
2840 #endif
2841 
2842 	so = (struct socket *)fp->f_data;
2843 	if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2844 		error = EOPNOTSUPP;
2845 		goto sctp_bad;
2846 	}
2847 #ifdef MAC
2848 	error = mac_socket_check_send(td->td_ucred, so);
2849 	if (error != 0)
2850 		goto sctp_bad;
2851 #endif /* MAC */
2852 
2853 	auio.uio_iov = iov;
2854 	auio.uio_iovcnt = uap->iovlen;
2855 	auio.uio_segflg = UIO_USERSPACE;
2856 	auio.uio_rw = UIO_WRITE;
2857 	auio.uio_td = td;
2858 	auio.uio_offset = 0;			/* XXX */
2859 	auio.uio_resid = 0;
2860 	tiov = iov;
2861 	for (i = 0; i <uap->iovlen; i++, tiov++) {
2862 		if ((auio.uio_resid += tiov->iov_len) < 0) {
2863 			error = EINVAL;
2864 			goto sctp_bad;
2865 		}
2866 	}
2867 	len = auio.uio_resid;
2868 	CURVNET_SET(so->so_vnet);
2869 	error = sctp_lower_sosend(so, to, &auio,
2870 		    (struct mbuf *)NULL, (struct mbuf *)NULL,
2871 		    uap->flags, u_sinfo, td);
2872 	CURVNET_RESTORE();
2873 	if (error != 0) {
2874 		if (auio.uio_resid != len && (error == ERESTART ||
2875 		    error == EINTR || error == EWOULDBLOCK))
2876 			error = 0;
2877 		/* Generation of SIGPIPE can be controlled per socket */
2878 		if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2879 		    !(uap->flags & MSG_NOSIGNAL)) {
2880 			PROC_LOCK(td->td_proc);
2881 			tdsignal(td, SIGPIPE);
2882 			PROC_UNLOCK(td->td_proc);
2883 		}
2884 	}
2885 	if (error == 0)
2886 		td->td_retval[0] = len - auio.uio_resid;
2887 #ifdef KTRACE
2888 	if (ktruio != NULL) {
2889 		ktruio->uio_resid = td->td_retval[0];
2890 		ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2891 	}
2892 #endif /* KTRACE */
2893 sctp_bad:
2894 	free(iov, M_IOV);
2895 sctp_bad1:
2896 	if (fp != NULL)
2897 		fdrop(fp, td);
2898 sctp_bad2:
2899 	free(to, M_SONAME);
2900 	return (error);
2901 #else  /* SCTP */
2902 	return (EOPNOTSUPP);
2903 #endif /* SCTP */
2904 }
2905 
2906 int
2907 sys_sctp_generic_recvmsg(td, uap)
2908 	struct thread *td;
2909 	struct sctp_generic_recvmsg_args /* {
2910 		int sd,
2911 		struct iovec *iov,
2912 		int iovlen,
2913 		struct sockaddr *from,
2914 		__socklen_t *fromlenaddr,
2915 		struct sctp_sndrcvinfo *sinfo,
2916 		int *msg_flags
2917 	} */ *uap;
2918 {
2919 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2920 	uint8_t sockbufstore[256];
2921 	struct uio auio;
2922 	struct iovec *iov, *tiov;
2923 	struct sctp_sndrcvinfo sinfo;
2924 	struct socket *so;
2925 	struct file *fp = NULL;
2926 	struct sockaddr *fromsa;
2927 	cap_rights_t rights;
2928 #ifdef KTRACE
2929 	struct uio *ktruio = NULL;
2930 #endif
2931 	ssize_t len;
2932 	int error, fromlen, i, msg_flags;
2933 
2934 	AUDIT_ARG_FD(uap->sd);
2935 	error = getsock_cap(td->td_proc->p_fd, uap->sd,
2936 	    cap_rights_init(&rights, CAP_RECV), &fp, NULL);
2937 	if (error != 0)
2938 		return (error);
2939 #ifdef COMPAT_FREEBSD32
2940 	if (SV_CURPROC_FLAG(SV_ILP32))
2941 		error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2942 		    uap->iovlen, &iov, EMSGSIZE);
2943 	else
2944 #endif
2945 		error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2946 	if (error != 0)
2947 		goto out1;
2948 
2949 	so = fp->f_data;
2950 	if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2951 		error = EOPNOTSUPP;
2952 		goto out;
2953 	}
2954 #ifdef MAC
2955 	error = mac_socket_check_receive(td->td_ucred, so);
2956 	if (error != 0)
2957 		goto out;
2958 #endif /* MAC */
2959 
2960 	if (uap->fromlenaddr != NULL) {
2961 		error = copyin(uap->fromlenaddr, &fromlen, sizeof (fromlen));
2962 		if (error != 0)
2963 			goto out;
2964 	} else {
2965 		fromlen = 0;
2966 	}
2967 	if (uap->msg_flags) {
2968 		error = copyin(uap->msg_flags, &msg_flags, sizeof (int));
2969 		if (error != 0)
2970 			goto out;
2971 	} else {
2972 		msg_flags = 0;
2973 	}
2974 	auio.uio_iov = iov;
2975 	auio.uio_iovcnt = uap->iovlen;
2976 	auio.uio_segflg = UIO_USERSPACE;
2977 	auio.uio_rw = UIO_READ;
2978 	auio.uio_td = td;
2979 	auio.uio_offset = 0;			/* XXX */
2980 	auio.uio_resid = 0;
2981 	tiov = iov;
2982 	for (i = 0; i <uap->iovlen; i++, tiov++) {
2983 		if ((auio.uio_resid += tiov->iov_len) < 0) {
2984 			error = EINVAL;
2985 			goto out;
2986 		}
2987 	}
2988 	len = auio.uio_resid;
2989 	fromsa = (struct sockaddr *)sockbufstore;
2990 
2991 #ifdef KTRACE
2992 	if (KTRPOINT(td, KTR_GENIO))
2993 		ktruio = cloneuio(&auio);
2994 #endif /* KTRACE */
2995 	memset(&sinfo, 0, sizeof(struct sctp_sndrcvinfo));
2996 	CURVNET_SET(so->so_vnet);
2997 	error = sctp_sorecvmsg(so, &auio, (struct mbuf **)NULL,
2998 		    fromsa, fromlen, &msg_flags,
2999 		    (struct sctp_sndrcvinfo *)&sinfo, 1);
3000 	CURVNET_RESTORE();
3001 	if (error != 0) {
3002 		if (auio.uio_resid != len && (error == ERESTART ||
3003 		    error == EINTR || error == EWOULDBLOCK))
3004 			error = 0;
3005 	} else {
3006 		if (uap->sinfo)
3007 			error = copyout(&sinfo, uap->sinfo, sizeof (sinfo));
3008 	}
3009 #ifdef KTRACE
3010 	if (ktruio != NULL) {
3011 		ktruio->uio_resid = len - auio.uio_resid;
3012 		ktrgenio(uap->sd, UIO_READ, ktruio, error);
3013 	}
3014 #endif /* KTRACE */
3015 	if (error != 0)
3016 		goto out;
3017 	td->td_retval[0] = len - auio.uio_resid;
3018 
3019 	if (fromlen && uap->from) {
3020 		len = fromlen;
3021 		if (len <= 0 || fromsa == 0)
3022 			len = 0;
3023 		else {
3024 			len = MIN(len, fromsa->sa_len);
3025 			error = copyout(fromsa, uap->from, (size_t)len);
3026 			if (error != 0)
3027 				goto out;
3028 		}
3029 		error = copyout(&len, uap->fromlenaddr, sizeof (socklen_t));
3030 		if (error != 0)
3031 			goto out;
3032 	}
3033 #ifdef KTRACE
3034 	if (KTRPOINT(td, KTR_STRUCT))
3035 		ktrsockaddr(fromsa);
3036 #endif
3037 	if (uap->msg_flags) {
3038 		error = copyout(&msg_flags, uap->msg_flags, sizeof (int));
3039 		if (error != 0)
3040 			goto out;
3041 	}
3042 out:
3043 	free(iov, M_IOV);
3044 out1:
3045 	if (fp != NULL)
3046 		fdrop(fp, td);
3047 
3048 	return (error);
3049 #else  /* SCTP */
3050 	return (EOPNOTSUPP);
3051 #endif /* SCTP */
3052 }
3053