xref: /illumos-gate/usr/src/uts/common/os/fio.c (revision ac2250cb76bb32944fd2c8a3ba2cd3f79747748d)
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 (c) 1989, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2015, Joyent Inc.
25  * Copyright 2026 Oxide Computer Company
26  */
27 
28 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
29 /*	All Rights Reserved */
30 
31 #include <sys/types.h>
32 #include <sys/sysmacros.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/errno.h>
36 #include <sys/signal.h>
37 #include <sys/cred.h>
38 #include <sys/user.h>
39 #include <sys/conf.h>
40 #include <sys/vfs.h>
41 #include <sys/vnode.h>
42 #include <sys/pathname.h>
43 #include <sys/file.h>
44 #include <sys/flock.h>
45 #include <sys/proc.h>
46 #include <sys/var.h>
47 #include <sys/cpuvar.h>
48 #include <sys/open.h>
49 #include <sys/cmn_err.h>
50 #include <sys/priocntl.h>
51 #include <sys/procset.h>
52 #include <sys/prsystm.h>
53 #include <sys/debug.h>
54 #include <sys/kmem.h>
55 #include <sys/atomic.h>
56 #include <sys/fcntl.h>
57 #include <sys/poll.h>
58 #include <sys/rctl.h>
59 #include <sys/port_impl.h>
60 #include <sys/dtrace.h>
61 #include <sys/stdbool.h>
62 #include <sys/stdbit.h>
63 #include <sys/spawn_impl.h>
64 
65 #include <c2/audit.h>
66 #include <sys/nbmlock.h>
67 
68 #ifdef DEBUG
69 
70 static uint32_t afd_maxfd;	/* # of entries in maximum allocated array */
71 static uint32_t afd_alloc;	/* count of kmem_alloc()s */
72 static uint32_t afd_free;	/* count of kmem_free()s */
73 static uint32_t afd_wait;	/* count of waits on non-zero ref count */
74 #define	MAXFD(x)	(afd_maxfd = ((afd_maxfd >= (x))? afd_maxfd : (x)))
75 #define	COUNT(x)	atomic_inc_32(&x)
76 
77 #else	/* DEBUG */
78 
79 #define	MAXFD(x)
80 #define	COUNT(x)
81 
82 #endif	/* DEBUG */
83 
84 kmem_cache_t *file_cache;
85 
86 static void port_close_fd(portfd_t *);
87 
88 /*
89  * File descriptor allocation.
90  *
91  * fd_find(fip, minfd) finds the first available descriptor >= minfd.
92  * The most common case is open(2), in which minfd = 0, but we must also
93  * support fcntl(fd, F_DUPFD, minfd).
94  *
95  * The algorithm is as follows: we keep all file descriptors in an infix
96  * binary tree in which each node records the number of descriptors
97  * allocated in its right subtree, including itself.  Starting at minfd,
98  * we ascend the tree until we find a non-fully allocated right subtree.
99  * We then descend that subtree in a binary search for the smallest fd.
100  * Finally, we ascend the tree again to increment the allocation count
101  * of every subtree containing the newly-allocated fd.  Freeing an fd
102  * requires only the last step: we ascend the tree to decrement allocation
103  * counts.  Each of these three steps (ascent to find non-full subtree,
104  * descent to find lowest fd, ascent to update allocation counts) is
105  * O(log n), thus the algorithm as a whole is O(log n).
106  *
107  * We don't implement the fd tree using the customary left/right/parent
108  * pointers, but instead take advantage of the glorious mathematics of
109  * full infix binary trees.  For reference, here's an illustration of the
110  * logical structure of such a tree, rooted at 4 (binary 100), covering
111  * the range 1-7 (binary 001-111).  Our canonical trees do not include
112  * fd 0; we'll deal with that later.
113  *
114  *	      100
115  *	     /	 \
116  *	    /	  \
117  *	  010	  110
118  *	  / \	  / \
119  *	001 011 101 111
120  *
121  * We make the following observations, all of which are easily proven by
122  * induction on the depth of the tree:
123  *
124  * (T1) The least-significant bit (LSB) of any node is equal to its level
125  *      in the tree.  In our example, nodes 001, 011, 101 and 111 are at
126  *      level 0; nodes 010 and 110 are at level 1; and node 100 is at level 2.
127  *
128  * (T2) The child size (CSIZE) of node N -- that is, the total number of
129  *	right-branch descendants in a child of node N, including itself -- is
130  *	given by clearing all but the least significant bit of N.  This
131  *	follows immediately from (T1).  Applying this rule to our example, we
132  *	see that CSIZE(100) = 100, CSIZE(x10) = 10, and CSIZE(xx1) = 1.
133  *
134  * (T3) The nearest left ancestor (LPARENT) of node N -- that is, the nearest
135  *	ancestor containing node N in its right child -- is given by clearing
136  *	the LSB of N.  For example, LPARENT(111) = 110 and LPARENT(110) = 100.
137  *	Clearing the LSB of nodes 001, 010 or 100 yields zero, reflecting
138  *	the fact that these are leftmost nodes.  Note that this algorithm
139  *	automatically skips generations as necessary.  For example, the parent
140  *      of node 101 is 110, which is a *right* ancestor (not what we want);
141  *      but its grandparent is 100, which is a left ancestor. Clearing the LSB
142  *      of 101 gets us to 100 directly, skipping right past the uninteresting
143  *      generation (110).
144  *
145  *      Note that since LPARENT clears the LSB, whereas CSIZE clears all *but*
146  *	the LSB, we can express LPARENT() nicely in terms of CSIZE():
147  *
148  *	LPARENT(N) = N - CSIZE(N)
149  *
150  * (T4) The nearest right ancestor (RPARENT) of node N is given by:
151  *
152  *	RPARENT(N) = N + CSIZE(N)
153  *
154  * (T5) For every interior node, the children differ from their parent by
155  *	CSIZE(parent) / 2.  In our example, CSIZE(100) / 2 = 2 = 10 binary,
156  *      and indeed, the children of 100 are 100 +/- 10 = 010 and 110.
157  *
158  * Next, we'll need a few two's-complement math tricks.  Suppose a number,
159  * N, has the following form:
160  *
161  *		N = xxxx10...0
162  *
163  * That is, the binary representation of N consists of some string of bits,
164  * then a 1, then all zeroes.  This amounts to nothing more than saying that
165  * N has a least-significant bit, which is true for any N != 0.  If we look
166  * at N and N - 1 together, we see that we can combine them in useful ways:
167  *
168  *		  N = xxxx10...0
169  *	      N - 1 = xxxx01...1
170  *	------------------------
171  *	N & (N - 1) = xxxx000000
172  *	N | (N - 1) = xxxx111111
173  *	N ^ (N - 1) =     111111
174  *
175  * In particular, this suggests several easy ways to clear all but the LSB,
176  * which by (T2) is exactly what we need to determine CSIZE(N) = 10...0.
177  * We'll opt for this formulation:
178  *
179  *	(C1) CSIZE(N) = (N - 1) ^ (N | (N - 1))
180  *
181  * Similarly, we have an easy way to determine LPARENT(N), which requires
182  * that we clear the LSB of N:
183  *
184  *	(L1) LPARENT(N) = N & (N - 1)
185  *
186  * We note in the above relations that (N | (N - 1)) - N = CSIZE(N) - 1.
187  * When combined with (T4), this yields an easy way to compute RPARENT(N):
188  *
189  *	(R1) RPARENT(N) = (N | (N - 1)) + 1
190  *
191  * Finally, to accommodate fd 0 we must adjust all of our results by +/-1 to
192  * move the fd range from [1, 2^n) to [0, 2^n - 1).  This is straightforward,
193  * so there's no need to belabor the algebra; the revised relations become:
194  *
195  *	(C1a) CSIZE(N) = N ^ (N | (N + 1))
196  *
197  *	(L1a) LPARENT(N) = (N & (N + 1)) - 1
198  *
199  *	(R1a) RPARENT(N) = N | (N + 1)
200  *
201  * This completes the mathematical framework.  We now have all the tools
202  * we need to implement fd_find() and fd_reserve().
203  *
204  * fd_find(fip, minfd) finds the smallest available file descriptor >= minfd.
205  * It does not actually allocate the descriptor; that's done by fd_reserve().
206  * fd_find() proceeds in two steps:
207  *
208  * (1) Find the leftmost subtree that contains a descriptor >= minfd.
209  *     We start at the right subtree rooted at minfd.  If this subtree is
210  *     not full -- if fip->fi_list[minfd].uf_alloc != CSIZE(minfd) -- then
211  *     step 1 is done.  Otherwise, we know that all fds in this subtree
212  *     are taken, so we ascend to RPARENT(minfd) using (R1a).  We repeat
213  *     this process until we either find a candidate subtree or exceed
214  *     fip->fi_nfiles.  We use (C1a) to compute CSIZE().
215  *
216  * (2) Find the smallest fd in the subtree discovered by step 1.
217  *     Starting at the root of this subtree, we descend to find the
218  *     smallest available fd.  Since the left children have the smaller
219  *     fds, we will descend rightward only when the left child is full.
220  *
221  *     We begin by comparing the number of allocated fds in the root
222  *     to the number of allocated fds in its right child; if they differ
223  *     by exactly CSIZE(child), we know the left subtree is full, so we
224  *     descend right; that is, the right child becomes the search root.
225  *     Otherwise we leave the root alone and start following the right
226  *     child's left children.  As fortune would have it, this is very
227  *     simple computationally: by (T5), the right child of fd is just
228  *     fd + size, where size = CSIZE(fd) / 2.  Applying (T5) again,
229  *     we find that the right child's left child is fd + size - (size / 2) =
230  *     fd + (size / 2); *its* left child is fd + (size / 2) - (size / 4) =
231  *     fd + (size / 4), and so on.  In general, fd's right child's
232  *     leftmost nth descendant is fd + (size >> n).  Thus, to follow
233  *     the right child's left descendants, we just halve the size in
234  *     each iteration of the search.
235  *
236  *     When we descend leftward, we must keep track of the number of fds
237  *     that were allocated in all the right subtrees we rejected, so we
238  *     know how many of the root fd's allocations are in the remaining
239  *     (as yet unexplored) leftmost part of its right subtree.  When we
240  *     encounter a fully-allocated left child -- that is, when we find
241  *     that fip->fi_list[fd].uf_alloc == ralloc + size -- we descend right
242  *     (as described earlier), resetting ralloc to zero.
243  *
244  * fd_reserve(fip, fd, incr) either allocates or frees fd, depending
245  * on whether incr is 1 or -1.  Starting at fd, fd_reserve() ascends
246  * the leftmost ancestors (see (T3)) and updates the allocation counts.
247  * At each step we use (L1a) to compute LPARENT(), the next left ancestor.
248  *
249  * flist_minsize() finds the minimal tree that still covers all
250  * used fds; as long as the allocation count of a root node is zero, we
251  * don't need that node or its right subtree.
252  *
253  * flist_nalloc() counts the number of allocated fds in the tree, by starting
254  * at the top of the tree and summing the right-subtree allocation counts as
255  * it descends leftwards.
256  *
257  * Note: we assume that flist_grow() will keep fip->fi_nfiles of the form
258  * 2^n - 1.  This ensures that the fd trees are always full, which saves
259  * quite a bit of boundary checking.
260  */
261 static int
262 fd_find(uf_info_t *fip, int minfd)
263 {
264 	int size, ralloc, fd;
265 
266 	ASSERT(MUTEX_HELD(&fip->fi_lock));
267 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
268 
269 	for (fd = minfd; (uint_t)fd < fip->fi_nfiles; fd |= fd + 1) {
270 		size = fd ^ (fd | (fd + 1));
271 		if (fip->fi_list[fd].uf_alloc == size)
272 			continue;
273 		for (ralloc = 0, size >>= 1; size != 0; size >>= 1) {
274 			ralloc += fip->fi_list[fd + size].uf_alloc;
275 			if (fip->fi_list[fd].uf_alloc == ralloc + size) {
276 				fd += size;
277 				ralloc = 0;
278 			}
279 		}
280 		return (fd);
281 	}
282 	return (-1);
283 }
284 
285 static void
286 fd_reserve(uf_info_t *fip, int fd, int incr)
287 {
288 	int pfd;
289 	uf_entry_t *ufp = &fip->fi_list[fd];
290 
291 	ASSERT((uint_t)fd < fip->fi_nfiles);
292 	ASSERT((ufp->uf_busy == 0 && incr == 1) ||
293 	    (ufp->uf_busy == 1 && incr == -1));
294 	ASSERT(MUTEX_HELD(&ufp->uf_lock));
295 	ASSERT(MUTEX_HELD(&fip->fi_lock));
296 
297 	for (pfd = fd; pfd >= 0; pfd = (pfd & (pfd + 1)) - 1)
298 		fip->fi_list[pfd].uf_alloc += incr;
299 
300 	ufp->uf_busy += incr;
301 }
302 
303 static int
304 flist_minsize(uf_info_t *fip)
305 {
306 	int fd;
307 
308 	/*
309 	 * We'd like to ASSERT(MUTEX_HELD(&fip->fi_lock)), but we're called
310 	 * by flist_fork(), which relies on other mechanisms for mutual
311 	 * exclusion.
312 	 */
313 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
314 
315 	for (fd = fip->fi_nfiles; fd != 0; fd >>= 1)
316 		if (fip->fi_list[fd >> 1].uf_alloc != 0)
317 			break;
318 
319 	return (fd);
320 }
321 
322 static int
323 flist_nalloc(uf_info_t *fip)
324 {
325 	int fd;
326 	int nalloc = 0;
327 
328 	ASSERT(MUTEX_HELD(&fip->fi_lock));
329 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
330 
331 	for (fd = fip->fi_nfiles; fd != 0; fd >>= 1)
332 		nalloc += fip->fi_list[fd >> 1].uf_alloc;
333 
334 	return (nalloc);
335 }
336 
337 /*
338  * Increase size of the fi_list array to accommodate at least maxfd.
339  * We keep the size of the form 2^n - 1 for benefit of fd_find().
340  */
341 static void
342 flist_grow(int maxfd)
343 {
344 	uf_info_t *fip = P_FINFO(curproc);
345 	int newcnt, oldcnt;
346 	uf_entry_t *src, *dst, *newlist, *oldlist, *newend, *oldend;
347 	uf_rlist_t *urp;
348 
349 	newcnt = (1U << stdc_bit_width_ui(maxfd + 1)) - 1;
350 	newlist = kmem_zalloc(newcnt * sizeof (uf_entry_t), KM_SLEEP);
351 
352 	mutex_enter(&fip->fi_lock);
353 	oldcnt = fip->fi_nfiles;
354 	if (newcnt <= oldcnt) {
355 		mutex_exit(&fip->fi_lock);
356 		kmem_free(newlist, newcnt * sizeof (uf_entry_t));
357 		return;
358 	}
359 	ASSERT((newcnt & (newcnt + 1)) == 0);
360 	oldlist = fip->fi_list;
361 	oldend = oldlist + oldcnt;
362 	newend = newlist + oldcnt;	/* no need to lock beyond old end */
363 
364 	/*
365 	 * fi_list and fi_nfiles cannot change while any uf_lock is held,
366 	 * so we must grab all the old locks *and* the new locks up to oldcnt.
367 	 * (Locks beyond the end of oldcnt aren't visible until we store
368 	 * the new fi_nfiles, which is the last thing we do before dropping
369 	 * all the locks, so there's no need to acquire these locks).
370 	 * Holding the new locks is necessary because when fi_list changes
371 	 * to point to the new list, fi_nfiles won't have been stored yet.
372 	 * If we *didn't* hold the new locks, someone doing a UF_ENTER()
373 	 * could see the new fi_list, grab the new uf_lock, and then see
374 	 * fi_nfiles change while the lock is held -- in violation of
375 	 * UF_ENTER() semantics.
376 	 */
377 	for (src = oldlist; src < oldend; src++)
378 		mutex_enter(&src->uf_lock);
379 
380 	for (dst = newlist; dst < newend; dst++)
381 		mutex_enter(&dst->uf_lock);
382 
383 	for (src = oldlist, dst = newlist; src < oldend; src++, dst++) {
384 		dst->uf_file = src->uf_file;
385 		dst->uf_fpollinfo = src->uf_fpollinfo;
386 		dst->uf_refcnt = src->uf_refcnt;
387 		dst->uf_alloc = src->uf_alloc;
388 		dst->uf_flag = src->uf_flag;
389 		dst->uf_busy = src->uf_busy;
390 		dst->uf_portfd = src->uf_portfd;
391 		dst->uf_gen = src->uf_gen;
392 	}
393 
394 	/*
395 	 * As soon as we store the new flist, future locking operations
396 	 * will use it.  Therefore, we must ensure that all the state
397 	 * we've just established reaches global visibility before the
398 	 * new flist does.
399 	 */
400 	membar_producer();
401 	fip->fi_list = newlist;
402 
403 	/*
404 	 * Routines like getf() make an optimistic check on the validity
405 	 * of the supplied file descriptor: if it's less than the current
406 	 * value of fi_nfiles -- examined without any locks -- then it's
407 	 * safe to attempt a UF_ENTER() on that fd (which is a valid
408 	 * assumption because fi_nfiles only increases).  Therefore, it
409 	 * is critical that the new value of fi_nfiles not reach global
410 	 * visibility until after the new fi_list: if it happened the
411 	 * other way around, getf() could see the new fi_nfiles and attempt
412 	 * a UF_ENTER() on the old fi_list, which would write beyond its
413 	 * end if the fd exceeded the old fi_nfiles.
414 	 */
415 	membar_producer();
416 	fip->fi_nfiles = newcnt;
417 
418 	/*
419 	 * The new state is consistent now, so we can drop all the locks.
420 	 */
421 	for (dst = newlist; dst < newend; dst++)
422 		mutex_exit(&dst->uf_lock);
423 
424 	for (src = oldlist; src < oldend; src++) {
425 		/*
426 		 * If any threads are blocked on the old cvs, wake them.
427 		 * This will force them to wake up, discover that fi_list
428 		 * has changed, and go back to sleep on the new cvs.
429 		 */
430 		cv_broadcast(&src->uf_wanted_cv);
431 		cv_broadcast(&src->uf_closing_cv);
432 		mutex_exit(&src->uf_lock);
433 	}
434 
435 	mutex_exit(&fip->fi_lock);
436 
437 	/*
438 	 * Retire the old flist.  We can't actually kmem_free() it now
439 	 * because someone may still have a pointer to it.  Instead,
440 	 * we link it onto a list of retired flists.  The new flist
441 	 * is at least double the size of the previous flist, so the
442 	 * total size of all retired flists will be less than the size
443 	 * of the current one (to prove, consider the sum of a geometric
444 	 * series in powers of 2).  exit() frees the retired flists.
445 	 */
446 	urp = kmem_zalloc(sizeof (uf_rlist_t), KM_SLEEP);
447 	urp->ur_list = oldlist;
448 	urp->ur_nfiles = oldcnt;
449 
450 	mutex_enter(&fip->fi_lock);
451 	urp->ur_next = fip->fi_rlist;
452 	fip->fi_rlist = urp;
453 	mutex_exit(&fip->fi_lock);
454 }
455 
456 /*
457  * Utility functions for keeping track of the active file descriptors.
458  */
459 void
460 clear_stale_fd()		/* called from post_syscall() */
461 {
462 	afd_t *afd = &curthread->t_activefd;
463 	int i;
464 
465 	/* uninitialized is ok here, a_nfd is then zero */
466 	for (i = 0; i < afd->a_nfd; i++) {
467 		/* assert that this should not be necessary */
468 		ASSERT(afd->a_fd[i] == -1);
469 		afd->a_fd[i] = -1;
470 	}
471 	afd->a_stale = 0;
472 }
473 
474 void
475 free_afd(afd_t *afd)		/* called below and from thread_free() */
476 {
477 	int i;
478 
479 	/* free the buffer if it was kmem_alloc()ed */
480 	if (afd->a_nfd > sizeof (afd->a_buf) / sizeof (afd->a_buf[0])) {
481 		COUNT(afd_free);
482 		kmem_free(afd->a_fd, afd->a_nfd * sizeof (afd->a_fd[0]));
483 	}
484 
485 	/* (re)initialize the structure */
486 	afd->a_fd = &afd->a_buf[0];
487 	afd->a_nfd = sizeof (afd->a_buf) / sizeof (afd->a_buf[0]);
488 	afd->a_stale = 0;
489 	for (i = 0; i < afd->a_nfd; i++)
490 		afd->a_fd[i] = -1;
491 }
492 
493 static void
494 set_active_fd(int fd)
495 {
496 	afd_t *afd = &curthread->t_activefd;
497 	int i;
498 	int *old_fd;
499 	int old_nfd;
500 	int *new_fd;
501 	int new_nfd;
502 
503 	if (afd->a_nfd == 0) {	/* first time initialization */
504 		ASSERT(fd == -1);
505 		mutex_enter(&afd->a_fdlock);
506 		free_afd(afd);
507 		mutex_exit(&afd->a_fdlock);
508 	}
509 
510 	/* insert fd into vacant slot, if any */
511 	for (i = 0; i < afd->a_nfd; i++) {
512 		if (afd->a_fd[i] == -1) {
513 			afd->a_fd[i] = fd;
514 			return;
515 		}
516 	}
517 
518 	/*
519 	 * Reallocate the a_fd[] array to add one more slot.
520 	 */
521 	ASSERT(fd == -1);
522 	old_nfd = afd->a_nfd;
523 	old_fd = afd->a_fd;
524 	new_nfd = old_nfd + 1;
525 	new_fd = kmem_alloc(new_nfd * sizeof (afd->a_fd[0]), KM_SLEEP);
526 	MAXFD(new_nfd);
527 	COUNT(afd_alloc);
528 
529 	mutex_enter(&afd->a_fdlock);
530 	afd->a_fd = new_fd;
531 	afd->a_nfd = new_nfd;
532 	for (i = 0; i < old_nfd; i++)
533 		afd->a_fd[i] = old_fd[i];
534 	afd->a_fd[i] = fd;
535 	mutex_exit(&afd->a_fdlock);
536 
537 	if (old_nfd > sizeof (afd->a_buf) / sizeof (afd->a_buf[0])) {
538 		COUNT(afd_free);
539 		kmem_free(old_fd, old_nfd * sizeof (afd->a_fd[0]));
540 	}
541 }
542 
543 void
544 clear_active_fd(int fd)		/* called below and from aio.c */
545 {
546 	afd_t *afd = &curthread->t_activefd;
547 	int i;
548 
549 	for (i = 0; i < afd->a_nfd; i++) {
550 		if (afd->a_fd[i] == fd) {
551 			afd->a_fd[i] = -1;
552 			break;
553 		}
554 	}
555 	ASSERT(i < afd->a_nfd);		/* not found is not ok */
556 }
557 
558 /*
559  * Does this thread have this fd active?
560  */
561 static int
562 is_active_fd(kthread_t *t, int fd)
563 {
564 	afd_t *afd = &t->t_activefd;
565 	int i;
566 
567 	ASSERT(t != curthread);
568 	mutex_enter(&afd->a_fdlock);
569 	/* uninitialized is ok here, a_nfd is then zero */
570 	for (i = 0; i < afd->a_nfd; i++) {
571 		if (afd->a_fd[i] == fd) {
572 			mutex_exit(&afd->a_fdlock);
573 			return (1);
574 		}
575 	}
576 	mutex_exit(&afd->a_fdlock);
577 	return (0);
578 }
579 
580 /*
581  * Convert a user supplied file descriptor into a pointer to a file structure.
582  * Only task is to check range of the descriptor (soft resource limit was
583  * enforced at open time and shouldn't be checked here).
584  */
585 file_t *
586 getf_gen(int fd, uf_entry_gen_t *genp)
587 {
588 	uf_info_t *fip = P_FINFO(curproc);
589 	uf_entry_t *ufp;
590 	file_t *fp;
591 
592 	if ((uint_t)fd >= fip->fi_nfiles)
593 		return (NULL);
594 
595 	/*
596 	 * Reserve a slot in the active fd array now so we can call
597 	 * set_active_fd(fd) for real below, while still inside UF_ENTER().
598 	 */
599 	set_active_fd(-1);
600 
601 	UF_ENTER(ufp, fip, fd);
602 
603 	if ((fp = ufp->uf_file) == NULL) {
604 		UF_EXIT(ufp);
605 
606 		if (fd == fip->fi_badfd && fip->fi_action > 0)
607 			tsignal(curthread, fip->fi_action);
608 
609 		return (NULL);
610 	}
611 	ufp->uf_refcnt++;
612 	if (genp != NULL) {
613 		*genp = ufp->uf_gen;
614 	}
615 
616 	set_active_fd(fd);	/* record the active file descriptor */
617 
618 	UF_EXIT(ufp);
619 
620 	return (fp);
621 }
622 
623 file_t *
624 getf(int fd)
625 {
626 	return (getf_gen(fd, NULL));
627 }
628 
629 /*
630  * Close whatever file currently occupies the file descriptor slot
631  * and install the new file, usually NULL, in the file descriptor slot.
632  * The close must complete before we release the file descriptor slot.
633  * If newfp != NULL we only return an error if we can't allocate the
634  * slot so the caller knows that it needs to free the filep;
635  * in the other cases we return the error number from closef().
636  */
637 int
638 closeandsetf(int fd, file_t *newfp)
639 {
640 	proc_t *p = curproc;
641 	uf_info_t *fip = P_FINFO(p);
642 	uf_entry_t *ufp;
643 	file_t *fp;
644 	fpollinfo_t *fpip;
645 	portfd_t *pfd;
646 	int error;
647 
648 	if ((uint_t)fd >= fip->fi_nfiles) {
649 		if (newfp == NULL)
650 			return (EBADF);
651 		flist_grow(fd);
652 	}
653 
654 	if (newfp != NULL) {
655 		/*
656 		 * If ufp is reserved but has no file pointer, it's in the
657 		 * transition between ufalloc() and setf().  We must wait
658 		 * for this transition to complete before assigning the
659 		 * new non-NULL file pointer.
660 		 */
661 		mutex_enter(&fip->fi_lock);
662 		if (fd == fip->fi_badfd) {
663 			mutex_exit(&fip->fi_lock);
664 			if (fip->fi_action > 0)
665 				tsignal(curthread, fip->fi_action);
666 			return (EBADF);
667 		}
668 		UF_ENTER(ufp, fip, fd);
669 		while (ufp->uf_busy && ufp->uf_file == NULL) {
670 			mutex_exit(&fip->fi_lock);
671 			cv_wait_stop(&ufp->uf_wanted_cv, &ufp->uf_lock, 250);
672 			UF_EXIT(ufp);
673 			mutex_enter(&fip->fi_lock);
674 			UF_ENTER(ufp, fip, fd);
675 		}
676 		if ((fp = ufp->uf_file) == NULL) {
677 			ASSERT(ufp->uf_fpollinfo == NULL);
678 			ASSERT(ufp->uf_flag == 0);
679 			fd_reserve(fip, fd, 1);
680 			ufp->uf_file = newfp;
681 			ufp->uf_gen++;
682 			UF_EXIT(ufp);
683 			mutex_exit(&fip->fi_lock);
684 			return (0);
685 		}
686 		mutex_exit(&fip->fi_lock);
687 	} else {
688 		UF_ENTER(ufp, fip, fd);
689 		if ((fp = ufp->uf_file) == NULL) {
690 			UF_EXIT(ufp);
691 			return (EBADF);
692 		}
693 	}
694 
695 	ASSERT(ufp->uf_busy);
696 	ufp->uf_file = NULL;
697 	ufp->uf_flag = 0;
698 
699 	/*
700 	 * If the file descriptor reference count is non-zero, then
701 	 * some other lwp in the process is performing system call
702 	 * activity on the file.  To avoid blocking here for a long
703 	 * time (the other lwp might be in a long term sleep in its
704 	 * system call), we scan all other lwps in the process to
705 	 * find the ones with this fd as one of their active fds,
706 	 * set their a_stale flag, and set them running if they
707 	 * are in an interruptible sleep so they will emerge from
708 	 * their system calls immediately.  post_syscall() will
709 	 * test the a_stale flag and set errno to EBADF.
710 	 */
711 	ASSERT(ufp->uf_refcnt == 0 || p->p_lwpcnt > 1);
712 	if (ufp->uf_refcnt > 0) {
713 		kthread_t *t;
714 
715 		/*
716 		 * We call sprlock_proc(p) to ensure that the thread
717 		 * list will not change while we are scanning it.
718 		 * To do this, we must drop ufp->uf_lock and then
719 		 * reacquire it (so we are not holding both p->p_lock
720 		 * and ufp->uf_lock at the same time).  ufp->uf_lock
721 		 * must be held for is_active_fd() to be correct
722 		 * (set_active_fd() is called while holding ufp->uf_lock).
723 		 *
724 		 * This is a convoluted dance, but it is better than
725 		 * the old brute-force method of stopping every thread
726 		 * in the process by calling holdlwps(SHOLDFORK1).
727 		 */
728 
729 		UF_EXIT(ufp);
730 		COUNT(afd_wait);
731 
732 		mutex_enter(&p->p_lock);
733 		sprlock_proc(p);
734 		mutex_exit(&p->p_lock);
735 
736 		UF_ENTER(ufp, fip, fd);
737 		ASSERT(ufp->uf_file == NULL);
738 
739 		if (ufp->uf_refcnt > 0) {
740 			for (t = curthread->t_forw;
741 			    t != curthread;
742 			    t = t->t_forw) {
743 				if (is_active_fd(t, fd)) {
744 					thread_lock(t);
745 					t->t_activefd.a_stale = 1;
746 					t->t_post_sys = 1;
747 					if (ISWAKEABLE(t))
748 						setrun_locked(t);
749 					thread_unlock(t);
750 				}
751 			}
752 		}
753 
754 		UF_EXIT(ufp);
755 
756 		mutex_enter(&p->p_lock);
757 		sprunlock(p);
758 
759 		UF_ENTER(ufp, fip, fd);
760 		ASSERT(ufp->uf_file == NULL);
761 	}
762 
763 	/*
764 	 * Wait for other lwps to stop using this file descriptor.
765 	 */
766 	while (ufp->uf_refcnt > 0) {
767 		cv_wait_stop(&ufp->uf_closing_cv, &ufp->uf_lock, 250);
768 		/*
769 		 * cv_wait_stop() drops ufp->uf_lock, so the file list
770 		 * can change.  Drop the lock on our (possibly) stale
771 		 * ufp and let UF_ENTER() find and lock the current ufp.
772 		 */
773 		UF_EXIT(ufp);
774 		UF_ENTER(ufp, fip, fd);
775 	}
776 
777 #ifdef DEBUG
778 	/*
779 	 * catch a watchfd on device's pollhead list but not on fpollinfo list
780 	 */
781 	if (ufp->uf_fpollinfo != NULL)
782 		checkwfdlist(fp->f_vnode, ufp->uf_fpollinfo);
783 #endif	/* DEBUG */
784 
785 	/*
786 	 * We may need to cleanup some cached poll states in t_pollstate
787 	 * before the fd can be reused. It is important that we don't
788 	 * access a stale thread structure. We will do the cleanup in two
789 	 * phases to avoid deadlock and holding uf_lock for too long.
790 	 * In phase 1, hold the uf_lock and call pollblockexit() to set
791 	 * state in t_pollstate struct so that a thread does not exit on
792 	 * us. In phase 2, we drop the uf_lock and call pollcacheclean().
793 	 */
794 	pfd = ufp->uf_portfd;
795 	ufp->uf_portfd = NULL;
796 	fpip = ufp->uf_fpollinfo;
797 	ufp->uf_fpollinfo = NULL;
798 	if (fpip != NULL)
799 		pollblockexit(fpip);
800 	UF_EXIT(ufp);
801 	if (fpip != NULL)
802 		pollcacheclean(fpip, fd);
803 	if (pfd)
804 		port_close_fd(pfd);
805 
806 	/*
807 	 * Keep the file descriptor entry reserved across the closef().
808 	 */
809 	error = closef(fp);
810 
811 	setf(fd, newfp);
812 
813 	/* Only return closef() error when closing is all we do */
814 	return (newfp == NULL ? error : 0);
815 }
816 
817 /*
818  * Decrement uf_refcnt; wakeup anyone waiting to close the file.
819  */
820 void
821 releasef(int fd)
822 {
823 	uf_info_t *fip = P_FINFO(curproc);
824 	uf_entry_t *ufp;
825 
826 	UF_ENTER(ufp, fip, fd);
827 	ASSERT(ufp->uf_refcnt > 0);
828 	clear_active_fd(fd);	/* clear the active file descriptor */
829 	if (--ufp->uf_refcnt == 0)
830 		cv_broadcast(&ufp->uf_closing_cv);
831 	UF_EXIT(ufp);
832 }
833 
834 /*
835  * Identical to releasef() but can be called from another process.
836  */
837 void
838 areleasef(int fd, uf_info_t *fip)
839 {
840 	uf_entry_t *ufp;
841 
842 	UF_ENTER(ufp, fip, fd);
843 	ASSERT(ufp->uf_refcnt > 0);
844 	if (--ufp->uf_refcnt == 0)
845 		cv_broadcast(&ufp->uf_closing_cv);
846 	UF_EXIT(ufp);
847 }
848 
849 /*
850  * Duplicate all file descriptors across a fork.
851  */
852 void
853 flist_fork(uf_info_t *pfip, uf_info_t *cfip)
854 {
855 	int fd, nfiles;
856 	uf_entry_t *pufp, *cufp;
857 
858 	mutex_init(&cfip->fi_lock, NULL, MUTEX_DEFAULT, NULL);
859 	cfip->fi_rlist = NULL;
860 
861 	/*
862 	 * We don't need to hold fi_lock because all other lwp's in the
863 	 * parent have been held.
864 	 */
865 	cfip->fi_nfiles = nfiles = flist_minsize(pfip);
866 
867 	cfip->fi_list = nfiles == 0 ? NULL :
868 	    kmem_zalloc(nfiles * sizeof (uf_entry_t), KM_SLEEP);
869 
870 	for (fd = 0, pufp = pfip->fi_list, cufp = cfip->fi_list; fd < nfiles;
871 	    fd++, pufp++, cufp++) {
872 		boolean_t unreserve = B_FALSE;
873 
874 		/*
875 		 * Check to see if FD_CLOFORK is set. In this case we 'close'
876 		 * the file descriptor by simply not duplicating it and leaving
877 		 * this entry as an empty descriptor. While we don't need to
878 		 * close the underlying file_t, we do need to make sure we take
879 		 * care of cleaning up our reservation. We do not reset the
880 		 * generation either, simulating a setf here.
881 		 */
882 		if ((pufp->uf_flag & FD_CLOFORK) == 0) {
883 			cufp->uf_file = pufp->uf_file;
884 			cufp->uf_flag = pufp->uf_flag;
885 		}
886 		cufp->uf_busy = pufp->uf_busy;
887 		cufp->uf_alloc = pufp->uf_alloc;
888 		cufp->uf_gen = pufp->uf_gen;
889 
890 		/*
891 		 * We may have to clean up our allocation tracking. This happens
892 		 * either because we have no file due to the fact that we're
893 		 * busy or because we had a file and FD_CLOFORK is set. If there
894 		 * is no file and we're not busy, then the unreserve was already
895 		 * taken care of.
896 		 */
897 		if (pufp->uf_file == NULL) {
898 			ASSERT3U(pufp->uf_flag, ==, 0);
899 			if (pufp->uf_busy) {
900 				unreserve = B_TRUE;
901 			}
902 		} else if ((pufp->uf_flag & FD_CLOFORK) != 0) {
903 			ASSERT3P(pufp->uf_file, !=, NULL);
904 			unreserve = B_TRUE;
905 		}
906 
907 		if (unreserve) {
908 			/*
909 			 * Grab locks to appease ASSERTs in fd_reserve
910 			 */
911 			mutex_enter(&cfip->fi_lock);
912 			mutex_enter(&cufp->uf_lock);
913 			fd_reserve(cfip, fd, -1);
914 			mutex_exit(&cufp->uf_lock);
915 			mutex_exit(&cfip->fi_lock);
916 		}
917 	}
918 }
919 
920 /*
921  * Determine whether a spawned child needs a copy of one of its parent's file
922  * descriptors. Called with the entry's uf_lock held.
923  */
924 static bool
925 spawn_fd_keep(const uf_entry_t *ufp, int fd, const kspawn_param_t *ksp)
926 {
927 	if (ufp->uf_file == NULL)
928 		return (false);
929 
930 	/*
931 	 * Spawn is fork followed by exec, so a descriptor marked FD_CLOFORK
932 	 * is never inherited, just as for fork.
933 	 */
934 	if ((ufp->uf_flag & FD_CLOFORK) != 0)
935 		return (false);
936 
937 	/*
938 	 * A descriptor survives into the exec'd image if it is not marked
939 	 * close-on-exec and lies below any closefrom() bound.
940 	 */
941 	if ((ufp->uf_flag & FD_CLOEXEC) == 0 && fd < ksp->ksp_closefrom)
942 		return (true);
943 
944 	/*
945 	 * Anything else would not survive the file actions and exec but it
946 	 * must still be copied if any action consumes it as a source.
947 	 */
948 	for (uint_t i = 0; i < ksp->ksp_nreffds; i++) {
949 		if (ksp->ksp_reffds[i] == fd)
950 			return (true);
951 	}
952 
953 	return (false);
954 }
955 
956 /*
957  * Duplicate file descriptors for a spawn(2) child.
958  *
959  * Unlike flist_fork(), the parent's other threads continue to run while the
960  * child is created, so each entry must be locked as it is examined and copied.
961  * Since the child will exec immediately after applying the file actions,
962  * descriptors that can play no part in the final picture are not copied at all
963  * as an optimisation.
964  *
965  * The child's table is also sized to cover only the descriptors being
966  * copied, so a sparse high-numbered descriptor in the parent does not cause
967  * every spawned child to create an enormous table.
968  */
969 void
970 flist_spawn(uf_info_t *pfip, uf_info_t *cfip, const kspawn_param_t *ksp)
971 {
972 	int fd, pnfiles, cnfiles, maxkept;
973 	uf_entry_t *pufp, *cufp;
974 
975 	mutex_init(&cfip->fi_lock, NULL, MUTEX_DEFAULT, NULL);
976 	cfip->fi_rlist = NULL;
977 
978 	mutex_enter(&pfip->fi_lock);
979 	pnfiles = flist_minsize(pfip);
980 	mutex_exit(&pfip->fi_lock);
981 
982 	/*
983 	 * Find the highest descriptor that the child needs, so that we can
984 	 * size its table. The decision for each descriptor is re-evaluated
985 	 * under the lock in the second pass and an entry that changes in the
986 	 * meantime is treated as if the change had happened before the spawn
987 	 * and not copied.
988 	 */
989 	maxkept = -1;
990 	for (fd = 0; fd < pnfiles; fd++) {
991 		UF_ENTER(pufp, pfip, fd);
992 		if (spawn_fd_keep(pufp, fd, ksp))
993 			maxkept = fd;
994 		UF_EXIT(pufp);
995 	}
996 
997 	if (maxkept == -1) {
998 		cfip->fi_nfiles = 0;
999 		cfip->fi_list = NULL;
1000 		return;
1001 	}
1002 
1003 	/* The table size is kept of the form 2^n - 1 for fd_find(). */
1004 	cnfiles = (1U << stdc_bit_width_ui(maxkept + 1)) - 1;
1005 
1006 	cfip->fi_nfiles = cnfiles;
1007 	cfip->fi_list = kmem_zalloc(cnfiles * sizeof (uf_entry_t), KM_SLEEP);
1008 
1009 	/*
1010 	 * Copy the chosen descriptors, taking a hold on each underlying file.
1011 	 * The hold must be taken while the parent's entry is locked so that
1012 	 * none of the parent's threads could close the descriptor and
1013 	 * release the final reference while we work.
1014 	 */
1015 	for (fd = 0, cufp = cfip->fi_list; fd <= maxkept; fd++, cufp++) {
1016 		file_t *fp;
1017 
1018 		UF_ENTER(pufp, pfip, fd);
1019 		cufp->uf_gen = pufp->uf_gen;
1020 		if (spawn_fd_keep(pufp, fd, ksp)) {
1021 			fp = pufp->uf_file;
1022 			mutex_enter(&fp->f_tlock);
1023 			fp->f_count++;
1024 			mutex_exit(&fp->f_tlock);
1025 
1026 			cufp->uf_file = fp;
1027 			cufp->uf_flag = pufp->uf_flag;
1028 
1029 			mutex_enter(&cfip->fi_lock);
1030 			mutex_enter(&cufp->uf_lock);
1031 			fd_reserve(cfip, fd, 1);
1032 			mutex_exit(&cufp->uf_lock);
1033 			mutex_exit(&cfip->fi_lock);
1034 		}
1035 		UF_EXIT(pufp);
1036 	}
1037 }
1038 
1039 /*
1040  * Trigger the resource control warning for a process that has tried to
1041  * exceed its file descriptor limit.
1042  */
1043 void
1044 fd_too_big(proc_t *p)
1045 {
1046 	mutex_enter(&p->p_lock);
1047 	(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
1048 	    p->p_rctls, p, RCA_SAFE);
1049 	mutex_exit(&p->p_lock);
1050 }
1051 
1052 /*
1053  * Duplicate the open descriptor ofd onto nfd, as fcntl(ofd, F_DUP2FD, nfd)
1054  * does. This is the shared implementation for the F_DUP2FD family of
1055  * fcntl(2) commands and for spawn(2) FA_DUP2 file actions.
1056  */
1057 int
1058 fdup2(int ofd, int nfd)
1059 {
1060 	proc_t *p = curproc;
1061 	file_t *fp;
1062 	int error;
1063 
1064 	if ((fp = getf(ofd)) == NULL)
1065 		return (EBADF);
1066 
1067 	if (ofd == nfd) {
1068 		uf_entry_t *ufp;
1069 
1070 		/*
1071 		 * This is only reached with equal descriptors from a spawn(2)
1072 		 * FA_DUP2 file action. posix_spawn_file_actions_adddup2()
1073 		 * requires FD_CLOEXEC and FD_CLOFORK to be cleared so the
1074 		 * descriptor survives the exec. The fcntl(2)/dup2() path never
1075 		 * arrives here with ofd == nfd since dup2() must leave those
1076 		 * flags unchanged.
1077 		 */
1078 		UF_ENTER(ufp, P_FINFO(p), ofd);
1079 		ufp->uf_flag &= ~(FD_CLOEXEC | FD_CLOFORK);
1080 		UF_EXIT(ufp);
1081 		releasef(ofd);
1082 		return (0);
1083 	}
1084 
1085 	if ((uint_t)nfd >= p->p_fno_ctl) {
1086 		releasef(ofd);
1087 		if (nfd >= 0)
1088 			fd_too_big(p);
1089 		return (EBADF);
1090 	}
1091 
1092 	/*
1093 	 * We can't hold our getf(ofd) across the call to closeandsetf()
1094 	 * because it creates a window for deadlock. If one thread is doing
1095 	 * dup2(a, b) while another is doing dup2(b, a), each one will block
1096 	 * waiting for the other to call releasef().
1097 	 */
1098 	mutex_enter(&fp->f_tlock);
1099 	fp->f_count++;
1100 	mutex_exit(&fp->f_tlock);
1101 	releasef(ofd);
1102 
1103 	if ((error = closeandsetf(nfd, fp)) != 0) {
1104 		mutex_enter(&fp->f_tlock);
1105 		if (fp->f_count > 1) {
1106 			fp->f_count--;
1107 			mutex_exit(&fp->f_tlock);
1108 		} else {
1109 			mutex_exit(&fp->f_tlock);
1110 			(void) closef(fp);
1111 		}
1112 	}
1113 
1114 	return (error);
1115 }
1116 
1117 /*
1118  * Close all open file descriptors at or above lowfd. This is used to apply
1119  * spawn(2) closefrom file actions in a spawned child which is still
1120  * single-threaded.
1121  */
1122 void
1123 closefrom_all(int lowfd)
1124 {
1125 	uf_info_t *fip = P_FINFO(curproc);
1126 	int fd, nfiles;
1127 
1128 	if (lowfd < 0)
1129 		lowfd = 0;
1130 
1131 	mutex_enter(&fip->fi_lock);
1132 	nfiles = fip->fi_nfiles;
1133 	mutex_exit(&fip->fi_lock);
1134 
1135 	for (fd = lowfd; fd < nfiles; fd++) {
1136 		uf_entry_t *ufp;
1137 		bool isopen;
1138 
1139 		UF_ENTER(ufp, fip, fd);
1140 		isopen = ufp->uf_file != NULL;
1141 		UF_EXIT(ufp);
1142 
1143 		if (isopen)
1144 			(void) closeandsetf(fd, NULL);
1145 	}
1146 }
1147 
1148 /*
1149  * Close all open file descriptors for the current process.
1150  * This is only called from exit(), which is single-threaded,
1151  * so we don't need any locking.
1152  */
1153 void
1154 closeall(uf_info_t *fip)
1155 {
1156 	int fd;
1157 	file_t *fp;
1158 	uf_entry_t *ufp;
1159 
1160 	ufp = fip->fi_list;
1161 	for (fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
1162 		if ((fp = ufp->uf_file) != NULL) {
1163 			ufp->uf_file = NULL;
1164 			if (ufp->uf_portfd != NULL) {
1165 				portfd_t *pfd;
1166 				/* remove event port association */
1167 				pfd = ufp->uf_portfd;
1168 				ufp->uf_portfd = NULL;
1169 				port_close_fd(pfd);
1170 			}
1171 			ASSERT(ufp->uf_fpollinfo == NULL);
1172 			(void) closef(fp);
1173 		}
1174 	}
1175 
1176 	kmem_free(fip->fi_list, fip->fi_nfiles * sizeof (uf_entry_t));
1177 	fip->fi_list = NULL;
1178 	fip->fi_nfiles = 0;
1179 	while (fip->fi_rlist != NULL) {
1180 		uf_rlist_t *urp = fip->fi_rlist;
1181 		fip->fi_rlist = urp->ur_next;
1182 		kmem_free(urp->ur_list, urp->ur_nfiles * sizeof (uf_entry_t));
1183 		kmem_free(urp, sizeof (uf_rlist_t));
1184 	}
1185 }
1186 
1187 /*
1188  * Internal form of close.  Decrement reference count on file
1189  * structure.  Decrement reference count on the vnode following
1190  * removal of the referencing file structure.
1191  */
1192 int
1193 closef(file_t *fp)
1194 {
1195 	vnode_t *vp;
1196 	int error;
1197 	int count;
1198 	int flag;
1199 	offset_t offset;
1200 
1201 	/*
1202 	 * audit close of file (may be exit)
1203 	 */
1204 	if (AU_AUDITING())
1205 		audit_closef(fp);
1206 	ASSERT(MUTEX_NOT_HELD(&P_FINFO(curproc)->fi_lock));
1207 
1208 	mutex_enter(&fp->f_tlock);
1209 
1210 	ASSERT(fp->f_count > 0);
1211 
1212 	count = fp->f_count--;
1213 	flag = fp->f_flag;
1214 	offset = fp->f_offset;
1215 
1216 	vp = fp->f_vnode;
1217 
1218 	error = VOP_CLOSE(vp, flag, count, offset, fp->f_cred, NULL);
1219 
1220 	if (count > 1) {
1221 		mutex_exit(&fp->f_tlock);
1222 		return (error);
1223 	}
1224 	ASSERT(fp->f_count == 0);
1225 	/* Last reference, remove any OFD style lock for the file_t */
1226 	ofdcleanlock(fp);
1227 	mutex_exit(&fp->f_tlock);
1228 
1229 	/*
1230 	 * If DTrace has getf() subroutines active, it will set dtrace_closef
1231 	 * to point to code that implements a barrier with respect to probe
1232 	 * context.  This must be called before the file_t is freed (and the
1233 	 * vnode that it refers to is released) -- but it must be after the
1234 	 * file_t has been removed from the uf_entry_t.  That is, there must
1235 	 * be no way for a racing getf() in probe context to yield the fp that
1236 	 * we're operating upon.
1237 	 */
1238 	if (dtrace_closef != NULL)
1239 		(*dtrace_closef)();
1240 
1241 	VN_RELE(vp);
1242 	/*
1243 	 * deallocate resources to audit_data
1244 	 */
1245 	if (audit_active)
1246 		audit_unfalloc(fp);
1247 	crfree(fp->f_cred);
1248 	kmem_cache_free(file_cache, fp);
1249 	return (error);
1250 }
1251 
1252 /*
1253  * This is a combination of ufalloc() and setf().
1254  */
1255 int
1256 ufalloc_file(int start, file_t *fp)
1257 {
1258 	proc_t *p = curproc;
1259 	uf_info_t *fip = P_FINFO(p);
1260 	int filelimit;
1261 	uf_entry_t *ufp;
1262 	int nfiles;
1263 	int fd;
1264 
1265 	/*
1266 	 * Assertion is to convince the correctness of the following
1267 	 * assignment for filelimit after casting to int.
1268 	 */
1269 	ASSERT(p->p_fno_ctl <= INT_MAX);
1270 	filelimit = (int)p->p_fno_ctl;
1271 
1272 	for (;;) {
1273 		mutex_enter(&fip->fi_lock);
1274 		fd = fd_find(fip, start);
1275 		if (fd >= 0 && fd == fip->fi_badfd) {
1276 			start = fd + 1;
1277 			mutex_exit(&fip->fi_lock);
1278 			continue;
1279 		}
1280 		if ((uint_t)fd < filelimit)
1281 			break;
1282 		if (fd >= filelimit) {
1283 			mutex_exit(&fip->fi_lock);
1284 			mutex_enter(&p->p_lock);
1285 			(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
1286 			    p->p_rctls, p, RCA_SAFE);
1287 			mutex_exit(&p->p_lock);
1288 			return (-1);
1289 		}
1290 		/* fd_find() returned -1 */
1291 		nfiles = fip->fi_nfiles;
1292 		mutex_exit(&fip->fi_lock);
1293 		flist_grow(MAX(start, nfiles));
1294 	}
1295 
1296 	UF_ENTER(ufp, fip, fd);
1297 	fd_reserve(fip, fd, 1);
1298 	ASSERT(ufp->uf_file == NULL);
1299 	ufp->uf_file = fp;
1300 	if (fp != NULL) {
1301 		ufp->uf_gen++;
1302 	}
1303 	UF_EXIT(ufp);
1304 	mutex_exit(&fip->fi_lock);
1305 	return (fd);
1306 }
1307 
1308 /*
1309  * Allocate a user file descriptor greater than or equal to "start".
1310  */
1311 int
1312 ufalloc(int start)
1313 {
1314 	return (ufalloc_file(start, NULL));
1315 }
1316 
1317 /*
1318  * Check that a future allocation of count fds on proc p has a good
1319  * chance of succeeding.  If not, do rctl processing as if we'd failed
1320  * the allocation.
1321  *
1322  * Our caller must guarantee that p cannot disappear underneath us.
1323  */
1324 int
1325 ufcanalloc(proc_t *p, uint_t count)
1326 {
1327 	uf_info_t *fip = P_FINFO(p);
1328 	int filelimit;
1329 	int current;
1330 
1331 	if (count == 0)
1332 		return (1);
1333 
1334 	ASSERT(p->p_fno_ctl <= INT_MAX);
1335 	filelimit = (int)p->p_fno_ctl;
1336 
1337 	mutex_enter(&fip->fi_lock);
1338 	current = flist_nalloc(fip);		/* # of in-use descriptors */
1339 	mutex_exit(&fip->fi_lock);
1340 
1341 	/*
1342 	 * If count is a positive integer, the worst that can happen is
1343 	 * an overflow to a negative value, which is caught by the >= 0 check.
1344 	 */
1345 	current += count;
1346 	if (count <= INT_MAX && current >= 0 && current <= filelimit)
1347 		return (1);
1348 
1349 	mutex_enter(&p->p_lock);
1350 	(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
1351 	    p->p_rctls, p, RCA_SAFE);
1352 	mutex_exit(&p->p_lock);
1353 	return (0);
1354 }
1355 
1356 /*
1357  * Allocate a user file descriptor and a file structure.
1358  * Initialize the descriptor to point at the file structure.
1359  * If fdp is NULL, the user file descriptor will not be allocated.
1360  */
1361 int
1362 falloc(vnode_t *vp, int flag, file_t **fpp, int *fdp)
1363 {
1364 	file_t *fp;
1365 	int fd;
1366 
1367 	if (fdp) {
1368 		if ((fd = ufalloc(0)) == -1)
1369 			return (EMFILE);
1370 	}
1371 	fp = kmem_cache_alloc(file_cache, KM_SLEEP);
1372 	/*
1373 	 * Note: falloc returns the fp locked
1374 	 */
1375 	mutex_enter(&fp->f_tlock);
1376 	fp->f_count = 1;
1377 	fp->f_flag = (ushort_t)flag;
1378 	fp->f_flag2 = (flag & (FSEARCH|FEXEC)) >> 16;
1379 	fp->f_vnode = vp;
1380 	fp->f_offset = 0;
1381 	fp->f_audit_data = 0;
1382 	crhold(fp->f_cred = CRED());
1383 	/*
1384 	 * allocate resources to audit_data
1385 	 */
1386 	if (audit_active)
1387 		audit_falloc(fp);
1388 	*fpp = fp;
1389 	if (fdp)
1390 		*fdp = fd;
1391 	return (0);
1392 }
1393 
1394 /*ARGSUSED*/
1395 static int
1396 file_cache_constructor(void *buf, void *cdrarg, int kmflags)
1397 {
1398 	file_t *fp = buf;
1399 
1400 	mutex_init(&fp->f_tlock, NULL, MUTEX_DEFAULT, NULL);
1401 	return (0);
1402 }
1403 
1404 /*ARGSUSED*/
1405 static void
1406 file_cache_destructor(void *buf, void *cdrarg)
1407 {
1408 	file_t *fp = buf;
1409 
1410 	mutex_destroy(&fp->f_tlock);
1411 }
1412 
1413 void
1414 finit()
1415 {
1416 	file_cache = kmem_cache_create("file_cache", sizeof (file_t), 0,
1417 	    file_cache_constructor, file_cache_destructor, NULL, NULL, NULL, 0);
1418 }
1419 
1420 void
1421 unfalloc(file_t *fp)
1422 {
1423 	ASSERT(MUTEX_HELD(&fp->f_tlock));
1424 	if (--fp->f_count <= 0) {
1425 		/*
1426 		 * deallocate resources to audit_data
1427 		 */
1428 		if (audit_active)
1429 			audit_unfalloc(fp);
1430 		crfree(fp->f_cred);
1431 		mutex_exit(&fp->f_tlock);
1432 		kmem_cache_free(file_cache, fp);
1433 	} else
1434 		mutex_exit(&fp->f_tlock);
1435 }
1436 
1437 /*
1438  * Given a file descriptor, set the user's
1439  * file pointer to the given parameter.
1440  */
1441 void
1442 setf(int fd, file_t *fp)
1443 {
1444 	uf_info_t *fip = P_FINFO(curproc);
1445 	uf_entry_t *ufp;
1446 
1447 	if (AU_AUDITING())
1448 		audit_setf(fp, fd);
1449 
1450 	if (fp == NULL) {
1451 		mutex_enter(&fip->fi_lock);
1452 		UF_ENTER(ufp, fip, fd);
1453 		fd_reserve(fip, fd, -1);
1454 		mutex_exit(&fip->fi_lock);
1455 	} else {
1456 		UF_ENTER(ufp, fip, fd);
1457 		ASSERT(ufp->uf_busy);
1458 		ufp->uf_gen++;
1459 	}
1460 	ASSERT(ufp->uf_fpollinfo == NULL);
1461 	ASSERT(ufp->uf_flag == 0);
1462 	ufp->uf_file = fp;
1463 	cv_broadcast(&ufp->uf_wanted_cv);
1464 	UF_EXIT(ufp);
1465 }
1466 
1467 /*
1468  * Given a file descriptor, return the file table flags, plus,
1469  * if this is a socket in asynchronous mode, the FASYNC flag.
1470  * getf() may or may not have been called before calling f_getfl().
1471  */
1472 int
1473 f_getfl(int fd, int *flagp)
1474 {
1475 	uf_info_t *fip = P_FINFO(curproc);
1476 	uf_entry_t *ufp;
1477 	file_t *fp;
1478 	int error;
1479 
1480 	if ((uint_t)fd >= fip->fi_nfiles)
1481 		error = EBADF;
1482 	else {
1483 		UF_ENTER(ufp, fip, fd);
1484 		if ((fp = ufp->uf_file) == NULL)
1485 			error = EBADF;
1486 		else {
1487 			vnode_t *vp = fp->f_vnode;
1488 			int flag = fp->f_flag | (fp->f_flag2 << 16);
1489 
1490 			/*
1491 			 * BSD fcntl() FASYNC compatibility.
1492 			 */
1493 			if (vp->v_type == VSOCK)
1494 				flag |= sock_getfasync(vp);
1495 			*flagp = flag;
1496 			error = 0;
1497 		}
1498 		UF_EXIT(ufp);
1499 	}
1500 
1501 	return (error);
1502 }
1503 
1504 /*
1505  * Given a file descriptor, return the user's file flags.
1506  * Force the FD_CLOEXEC flag for writable self-open /proc files.
1507  * getf() may or may not have been called before calling f_getfd_error().
1508  */
1509 int
1510 f_getfd_error(int fd, int *flagp)
1511 {
1512 	uf_info_t *fip = P_FINFO(curproc);
1513 	uf_entry_t *ufp;
1514 	file_t *fp;
1515 	int flag;
1516 	int error;
1517 
1518 	if ((uint_t)fd >= fip->fi_nfiles)
1519 		error = EBADF;
1520 	else {
1521 		UF_ENTER(ufp, fip, fd);
1522 		if ((fp = ufp->uf_file) == NULL) {
1523 			error = EBADF;
1524 		} else {
1525 			flag = ufp->uf_flag;
1526 			if ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode))
1527 				flag |= FD_CLOEXEC;
1528 			*flagp = flag;
1529 			error = 0;
1530 		}
1531 		UF_EXIT(ufp);
1532 	}
1533 
1534 	return (error);
1535 }
1536 
1537 /*
1538  * getf() must have been called before calling f_getfd().
1539  */
1540 char
1541 f_getfd(int fd)
1542 {
1543 	int flag = 0;
1544 	(void) f_getfd_error(fd, &flag);
1545 	return ((char)flag);
1546 }
1547 
1548 /*
1549  * Given a file descriptor and file flags, set the user's file flags.
1550  * At present, the only valid flags are FD_CLOEXEC and FD_CLOFORK.
1551  * getf() may or may not have been called before calling f_setfd_error().
1552  */
1553 static int
1554 f_setfd_int(int fd, int flags, bool or)
1555 {
1556 	uf_info_t *fip = P_FINFO(curproc);
1557 	uf_entry_t *ufp;
1558 	int error;
1559 
1560 	if ((uint_t)fd >= fip->fi_nfiles) {
1561 		error = EBADF;
1562 	} else {
1563 		UF_ENTER(ufp, fip, fd);
1564 		if (ufp->uf_file == NULL) {
1565 			error = EBADF;
1566 		} else {
1567 			flags &= (FD_CLOEXEC | FD_CLOFORK);
1568 			if (or) {
1569 				ufp->uf_flag |= flags;
1570 			} else {
1571 				ufp->uf_flag = flags;
1572 			}
1573 			error = 0;
1574 		}
1575 		UF_EXIT(ufp);
1576 	}
1577 	return (error);
1578 }
1579 
1580 int
1581 f_setfd_error(int fd, int flags)
1582 {
1583 	return (f_setfd_int(fd, flags, false));
1584 }
1585 
1586 void
1587 f_setfd_or(int fd, short flags)
1588 {
1589 	(void) f_setfd_int(fd, flags, true);
1590 }
1591 
1592 #define	BADFD_MIN	3
1593 #define	BADFD_MAX	255
1594 
1595 /*
1596  * Attempt to allocate a file descriptor which is bad and which
1597  * is "poison" to the application.  It cannot be closed (except
1598  * on exec), allocated for a different use, etc.
1599  */
1600 int
1601 f_badfd(int start, int *fdp, int action)
1602 {
1603 	int fdr;
1604 	int badfd;
1605 	uf_info_t *fip = P_FINFO(curproc);
1606 
1607 #ifdef _LP64
1608 	/* No restrictions on 64 bit _file */
1609 	if (get_udatamodel() != DATAMODEL_ILP32)
1610 		return (EINVAL);
1611 #endif
1612 
1613 	if (start > BADFD_MAX || start < BADFD_MIN)
1614 		return (EINVAL);
1615 
1616 	if (action >= NSIG || action < 0)
1617 		return (EINVAL);
1618 
1619 	mutex_enter(&fip->fi_lock);
1620 	badfd = fip->fi_badfd;
1621 	mutex_exit(&fip->fi_lock);
1622 
1623 	if (badfd != -1)
1624 		return (EAGAIN);
1625 
1626 	fdr = ufalloc(start);
1627 
1628 	if (fdr > BADFD_MAX) {
1629 		setf(fdr, NULL);
1630 		return (EMFILE);
1631 	}
1632 	if (fdr < 0)
1633 		return (EMFILE);
1634 
1635 	mutex_enter(&fip->fi_lock);
1636 	if (fip->fi_badfd != -1) {
1637 		/* Lost race */
1638 		mutex_exit(&fip->fi_lock);
1639 		setf(fdr, NULL);
1640 		return (EAGAIN);
1641 	}
1642 	fip->fi_action = action;
1643 	fip->fi_badfd = fdr;
1644 	mutex_exit(&fip->fi_lock);
1645 	setf(fdr, NULL);
1646 
1647 	*fdp = fdr;
1648 
1649 	return (0);
1650 }
1651 
1652 /*
1653  * Allocate a file descriptor and assign it to the vnode "*vpp",
1654  * performing the usual open protocol upon it and returning the
1655  * file descriptor allocated.  It is the responsibility of the
1656  * caller to dispose of "*vpp" if any error occurs.
1657  */
1658 int
1659 fassign(vnode_t **vpp, int mode, int *fdp)
1660 {
1661 	file_t *fp;
1662 	int error;
1663 	int fd;
1664 
1665 	if (error = falloc((vnode_t *)NULL, mode, &fp, &fd))
1666 		return (error);
1667 	if (error = VOP_OPEN(vpp, mode, fp->f_cred, NULL)) {
1668 		setf(fd, NULL);
1669 		unfalloc(fp);
1670 		return (error);
1671 	}
1672 	fp->f_vnode = *vpp;
1673 	mutex_exit(&fp->f_tlock);
1674 	/*
1675 	 * Fill in the slot falloc reserved.
1676 	 */
1677 	setf(fd, fp);
1678 	*fdp = fd;
1679 	return (0);
1680 }
1681 
1682 /*
1683  * When a process forks it must increment the f_count of all file pointers
1684  * since there is a new process pointing at them.  fcnt_add(fip, 1) does this.
1685  * Since we are called when there is only 1 active lwp we don't need to
1686  * hold fi_lock or any uf_lock.  If the fork fails, fork_fail() calls
1687  * fcnt_add(fip, -1) to restore the counts.
1688  */
1689 void
1690 fcnt_add(uf_info_t *fip, int incr)
1691 {
1692 	int i;
1693 	uf_entry_t *ufp;
1694 	file_t *fp;
1695 
1696 	ufp = fip->fi_list;
1697 	for (i = 0; i < fip->fi_nfiles; i++, ufp++) {
1698 		if ((fp = ufp->uf_file) != NULL) {
1699 			mutex_enter(&fp->f_tlock);
1700 			ASSERT((incr == 1 && fp->f_count >= 1) ||
1701 			    (incr == -1 && fp->f_count >= 2));
1702 			fp->f_count += incr;
1703 			mutex_exit(&fp->f_tlock);
1704 		}
1705 	}
1706 }
1707 
1708 /*
1709  * This is called from exec to close all fd's that have the FD_CLOEXEC flag
1710  * set and also to close all self-open for write /proc file descriptors. In
1711  * addition, we clear the close-on-fork flag from any file descriptors that have
1712  * it present.
1713  */
1714 void
1715 close_exec(uf_info_t *fip)
1716 {
1717 	uf_entry_t *ufp = fip->fi_list;
1718 
1719 	for (int fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
1720 		file_t *fp;
1721 
1722 		/*
1723 		 * If this is a hole in the file descriptor space we can simply
1724 		 * skip it.
1725 		 */
1726 		if ((fp = ufp->uf_file) == NULL)
1727 			continue;
1728 
1729 		if ((ufp->uf_flag & FD_CLOEXEC) ||
1730 		    ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode))) {
1731 			portfd_t *pfd;
1732 			fpollinfo_t *fpip = ufp->uf_fpollinfo;
1733 
1734 			mutex_enter(&fip->fi_lock);
1735 			mutex_enter(&ufp->uf_lock);
1736 			fd_reserve(fip, fd, -1);
1737 			mutex_exit(&fip->fi_lock);
1738 			ufp->uf_file = NULL;
1739 			ufp->uf_fpollinfo = NULL;
1740 			ufp->uf_flag = 0;
1741 			/*
1742 			 * We may need to cleanup some cached poll states
1743 			 * in t_pollstate before the fd can be reused. It
1744 			 * is important that we don't access a stale thread
1745 			 * structure. We will do the cleanup in two
1746 			 * phases to avoid deadlock and holding uf_lock for
1747 			 * too long. In phase 1, hold the uf_lock and call
1748 			 * pollblockexit() to set state in t_pollstate struct
1749 			 * so that a thread does not exit on us. In phase 2,
1750 			 * we drop the uf_lock and call pollcacheclean().
1751 			 */
1752 			pfd = ufp->uf_portfd;
1753 			ufp->uf_portfd = NULL;
1754 			if (fpip != NULL)
1755 				pollblockexit(fpip);
1756 			mutex_exit(&ufp->uf_lock);
1757 			if (fpip != NULL)
1758 				pollcacheclean(fpip, fd);
1759 			if (pfd)
1760 				port_close_fd(pfd);
1761 			(void) closef(fp);
1762 		} else if ((ufp->uf_flag & FD_CLOFORK) != 0) {
1763 			/*
1764 			 * We are in the case where a file descriptor has
1765 			 * FD_CLOFORK set and must clear it. This has a bit of a
1766 			 * history. In the original POSIX 2024 specification
1767 			 * FD_CLOFORK is noted to be preserved across an exec(2)
1768 			 * call. A process that has inherited this flag and
1769 			 * didn't put it there itself could be quite surprised
1770 			 * when a file descriptor disappears especially if this
1771 			 * refers to stdout, stdin, or stderr.
1772 			 *
1773 			 * Originally we implemented the POSIX version of this.
1774 			 * As other folks evaluated this, this issue was raised
1775 			 * and in general most implementations have agreed to
1776 			 * clear this on exec despite the original standard
1777 			 * wording.
1778 			 */
1779 			mutex_enter(&ufp->uf_lock);
1780 			ufp->uf_flag &= ~FD_CLOFORK;
1781 			mutex_exit(&ufp->uf_lock);
1782 		}
1783 	}
1784 
1785 	/* Reset bad fd */
1786 	fip->fi_badfd = -1;
1787 	fip->fi_action = -1;
1788 }
1789 
1790 /*
1791  * Utility function called by most of the *at() system call interfaces.
1792  *
1793  * Generate a starting vnode pointer for an (fd, path) pair where 'fd'
1794  * is an open file descriptor for a directory to be used as the starting
1795  * point for the lookup of the relative pathname 'path' (or, if path is
1796  * NULL, generate a vnode pointer for the direct target of the operation).
1797  *
1798  * If we successfully return a non-NULL startvp, it has been the target
1799  * of VN_HOLD() and the caller must call VN_RELE() on it.
1800  */
1801 int
1802 fgetstartvp(int fd, char *path, vnode_t **startvpp)
1803 {
1804 	vnode_t		*startvp;
1805 	file_t		*startfp;
1806 	char		startchar;
1807 
1808 	if (fd == AT_FDCWD && path == NULL)
1809 		return (EFAULT);
1810 
1811 	if (fd == AT_FDCWD) {
1812 		/*
1813 		 * Start from the current working directory.
1814 		 */
1815 		startvp = NULL;
1816 	} else {
1817 		if (path == NULL)
1818 			startchar = '\0';
1819 		else if (copyin(path, &startchar, sizeof (char)))
1820 			return (EFAULT);
1821 
1822 		if (startchar == '/') {
1823 			/*
1824 			 * 'path' is an absolute pathname.
1825 			 */
1826 			startvp = NULL;
1827 		} else {
1828 			/*
1829 			 * 'path' is a relative pathname or we will
1830 			 * be applying the operation to 'fd' itself.
1831 			 */
1832 			if ((startfp = getf(fd)) == NULL)
1833 				return (EBADF);
1834 			startvp = startfp->f_vnode;
1835 			VN_HOLD(startvp);
1836 			releasef(fd);
1837 		}
1838 	}
1839 	*startvpp = startvp;
1840 	return (0);
1841 }
1842 
1843 /*
1844  * Called from fchownat() and fchmodat() to set ownership and mode.
1845  * The contents of *vap must be set before calling here.
1846  */
1847 int
1848 fsetattrat(int fd, char *path, int flags, struct vattr *vap)
1849 {
1850 	vnode_t		*startvp;
1851 	vnode_t		*vp;
1852 	int		error;
1853 
1854 	/*
1855 	 * Since we are never called to set the size of a file, we don't
1856 	 * need to check for non-blocking locks (via nbl_need_check(vp)).
1857 	 */
1858 	ASSERT(!(vap->va_mask & AT_SIZE));
1859 
1860 	if ((error = fgetstartvp(fd, path, &startvp)) != 0)
1861 		return (error);
1862 	if (AU_AUDITING() && startvp != NULL)
1863 		audit_setfsat_path(1);
1864 
1865 	/*
1866 	 * Do lookup for fchownat/fchmodat when path not NULL
1867 	 */
1868 	if (path != NULL) {
1869 		if (error = lookupnameat(path, UIO_USERSPACE,
1870 		    (flags == AT_SYMLINK_NOFOLLOW) ?
1871 		    NO_FOLLOW : FOLLOW,
1872 		    NULLVPP, &vp, startvp)) {
1873 			if (startvp != NULL)
1874 				VN_RELE(startvp);
1875 			return (error);
1876 		}
1877 	} else {
1878 		vp = startvp;
1879 		ASSERT(vp);
1880 		VN_HOLD(vp);
1881 	}
1882 
1883 	if (vp->v_type == VLNK && (vap->va_mask & AT_MODE) != 0) {
1884 		error = EOPNOTSUPP;
1885 	} else if (vn_is_readonly(vp)) {
1886 		error = EROFS;
1887 	} else {
1888 		error = VOP_SETATTR(vp, vap, 0, CRED(), NULL);
1889 	}
1890 
1891 	if (startvp != NULL)
1892 		VN_RELE(startvp);
1893 	VN_RELE(vp);
1894 
1895 	return (error);
1896 }
1897 
1898 /*
1899  * Return true if the given vnode is referenced by any
1900  * entry in the current process's file descriptor table.
1901  */
1902 int
1903 fisopen(vnode_t *vp)
1904 {
1905 	int fd;
1906 	file_t *fp;
1907 	vnode_t *ovp;
1908 	uf_info_t *fip = P_FINFO(curproc);
1909 	uf_entry_t *ufp;
1910 
1911 	mutex_enter(&fip->fi_lock);
1912 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1913 		UF_ENTER(ufp, fip, fd);
1914 		if ((fp = ufp->uf_file) != NULL &&
1915 		    (ovp = fp->f_vnode) != NULL && VN_CMP(vp, ovp)) {
1916 			UF_EXIT(ufp);
1917 			mutex_exit(&fip->fi_lock);
1918 			return (1);
1919 		}
1920 		UF_EXIT(ufp);
1921 	}
1922 	mutex_exit(&fip->fi_lock);
1923 	return (0);
1924 }
1925 
1926 /*
1927  * Return zero if at least one file currently open (by curproc) shouldn't be
1928  * allowed to change zones.
1929  */
1930 int
1931 files_can_change_zones(void)
1932 {
1933 	int fd;
1934 	file_t *fp;
1935 	uf_info_t *fip = P_FINFO(curproc);
1936 	uf_entry_t *ufp;
1937 
1938 	mutex_enter(&fip->fi_lock);
1939 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1940 		UF_ENTER(ufp, fip, fd);
1941 		if ((fp = ufp->uf_file) != NULL &&
1942 		    !vn_can_change_zones(fp->f_vnode)) {
1943 			UF_EXIT(ufp);
1944 			mutex_exit(&fip->fi_lock);
1945 			return (0);
1946 		}
1947 		UF_EXIT(ufp);
1948 	}
1949 	mutex_exit(&fip->fi_lock);
1950 	return (1);
1951 }
1952 
1953 #ifdef DEBUG
1954 
1955 /*
1956  * The following functions are only used in ASSERT()s elsewhere.
1957  * They do not modify the state of the system.
1958  */
1959 
1960 /*
1961  * Return true (1) if the current thread is in the fpollinfo
1962  * list for this file descriptor, else false (0).
1963  */
1964 static int
1965 curthread_in_plist(uf_entry_t *ufp)
1966 {
1967 	fpollinfo_t *fpip;
1968 
1969 	ASSERT(MUTEX_HELD(&ufp->uf_lock));
1970 	for (fpip = ufp->uf_fpollinfo; fpip; fpip = fpip->fp_next)
1971 		if (fpip->fp_thread == curthread)
1972 			return (1);
1973 	return (0);
1974 }
1975 
1976 /*
1977  * Sanity check to make sure that after lwp_exit(),
1978  * curthread does not appear on any fd's fpollinfo list.
1979  */
1980 void
1981 checkfpollinfo(void)
1982 {
1983 	int fd;
1984 	uf_info_t *fip = P_FINFO(curproc);
1985 	uf_entry_t *ufp;
1986 
1987 	mutex_enter(&fip->fi_lock);
1988 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1989 		UF_ENTER(ufp, fip, fd);
1990 		ASSERT(!curthread_in_plist(ufp));
1991 		UF_EXIT(ufp);
1992 	}
1993 	mutex_exit(&fip->fi_lock);
1994 }
1995 
1996 /*
1997  * Return true (1) if the current thread is in the fpollinfo
1998  * list for this file descriptor, else false (0).
1999  * This is the same as curthread_in_plist(),
2000  * but is called w/o holding uf_lock.
2001  */
2002 int
2003 infpollinfo(int fd)
2004 {
2005 	uf_info_t *fip = P_FINFO(curproc);
2006 	uf_entry_t *ufp;
2007 	int rc;
2008 
2009 	UF_ENTER(ufp, fip, fd);
2010 	rc = curthread_in_plist(ufp);
2011 	UF_EXIT(ufp);
2012 	return (rc);
2013 }
2014 
2015 #endif	/* DEBUG */
2016 
2017 /*
2018  * Add the curthread to fpollinfo list, meaning this fd is currently in the
2019  * thread's poll cache. Each lwp polling this file descriptor should call
2020  * this routine once.
2021  */
2022 void
2023 addfpollinfo(int fd)
2024 {
2025 	struct uf_entry *ufp;
2026 	fpollinfo_t *fpip;
2027 	uf_info_t *fip = P_FINFO(curproc);
2028 
2029 	fpip = kmem_zalloc(sizeof (fpollinfo_t), KM_SLEEP);
2030 	fpip->fp_thread = curthread;
2031 	UF_ENTER(ufp, fip, fd);
2032 	/*
2033 	 * Assert we are not already on the list, that is, that
2034 	 * this lwp did not call addfpollinfo twice for the same fd.
2035 	 */
2036 	ASSERT(!curthread_in_plist(ufp));
2037 	/*
2038 	 * addfpollinfo is always done inside the getf/releasef pair.
2039 	 */
2040 	ASSERT(ufp->uf_refcnt >= 1);
2041 	fpip->fp_next = ufp->uf_fpollinfo;
2042 	ufp->uf_fpollinfo = fpip;
2043 	UF_EXIT(ufp);
2044 }
2045 
2046 /*
2047  * Delete curthread from fpollinfo list if it is there.
2048  */
2049 void
2050 delfpollinfo(int fd)
2051 {
2052 	struct uf_entry *ufp;
2053 	struct fpollinfo *fpip;
2054 	struct fpollinfo **fpipp;
2055 	uf_info_t *fip = P_FINFO(curproc);
2056 
2057 	UF_ENTER(ufp, fip, fd);
2058 	for (fpipp = &ufp->uf_fpollinfo;
2059 	    (fpip = *fpipp) != NULL;
2060 	    fpipp = &fpip->fp_next) {
2061 		if (fpip->fp_thread == curthread) {
2062 			*fpipp = fpip->fp_next;
2063 			kmem_free(fpip, sizeof (fpollinfo_t));
2064 			break;
2065 		}
2066 	}
2067 	/*
2068 	 * Assert that we are not still on the list, that is, that
2069 	 * this lwp did not call addfpollinfo twice for the same fd.
2070 	 */
2071 	ASSERT(!curthread_in_plist(ufp));
2072 	UF_EXIT(ufp);
2073 }
2074 
2075 /*
2076  * fd is associated with a port. pfd is a pointer to the fd entry in the
2077  * cache of the port.
2078  */
2079 
2080 void
2081 addfd_port(int fd, portfd_t *pfd)
2082 {
2083 	struct uf_entry *ufp;
2084 	uf_info_t *fip = P_FINFO(curproc);
2085 
2086 	UF_ENTER(ufp, fip, fd);
2087 	/*
2088 	 * addfd_port is always done inside the getf/releasef pair.
2089 	 */
2090 	ASSERT(ufp->uf_refcnt >= 1);
2091 	if (ufp->uf_portfd == NULL) {
2092 		/* first entry */
2093 		ufp->uf_portfd = pfd;
2094 		pfd->pfd_next = NULL;
2095 	} else {
2096 		pfd->pfd_next = ufp->uf_portfd;
2097 		ufp->uf_portfd = pfd;
2098 		pfd->pfd_next->pfd_prev = pfd;
2099 	}
2100 	UF_EXIT(ufp);
2101 }
2102 
2103 void
2104 delfd_port(int fd, portfd_t *pfd)
2105 {
2106 	struct uf_entry *ufp;
2107 	uf_info_t *fip = P_FINFO(curproc);
2108 
2109 	UF_ENTER(ufp, fip, fd);
2110 	/*
2111 	 * delfd_port is always done inside the getf/releasef pair.
2112 	 */
2113 	ASSERT(ufp->uf_refcnt >= 1);
2114 	if (ufp->uf_portfd == pfd) {
2115 		/* remove first entry */
2116 		ufp->uf_portfd = pfd->pfd_next;
2117 	} else {
2118 		pfd->pfd_prev->pfd_next = pfd->pfd_next;
2119 		if (pfd->pfd_next != NULL)
2120 			pfd->pfd_next->pfd_prev = pfd->pfd_prev;
2121 	}
2122 	UF_EXIT(ufp);
2123 }
2124 
2125 static void
2126 port_close_fd(portfd_t *pfd)
2127 {
2128 	portfd_t	*pfdn;
2129 
2130 	/*
2131 	 * At this point, no other thread should access
2132 	 * the portfd_t list for this fd. The uf_file, uf_portfd
2133 	 * pointers in the uf_entry_t struct for this fd would
2134 	 * be set to NULL.
2135 	 */
2136 	for (; pfd != NULL; pfd = pfdn) {
2137 		pfdn = pfd->pfd_next;
2138 		port_close_pfd(pfd);
2139 	}
2140 }
2141