xref: /illumos-gate/usr/src/uts/common/os/fio.c (revision 4de2612967d06c4fdbf524a62556a1e8118a006f)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	All Rights Reserved */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include <sys/types.h>
33 #include <sys/sysmacros.h>
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/errno.h>
37 #include <sys/signal.h>
38 #include <sys/cred.h>
39 #include <sys/user.h>
40 #include <sys/conf.h>
41 #include <sys/vfs.h>
42 #include <sys/vnode.h>
43 #include <sys/pathname.h>
44 #include <sys/file.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 
61 #include <c2/audit.h>
62 #include <sys/nbmlock.h>
63 
64 #ifdef DEBUG
65 
66 static uint32_t afd_maxfd;	/* # of entries in maximum allocated array */
67 static uint32_t afd_alloc;	/* count of kmem_alloc()s */
68 static uint32_t afd_free;	/* count of kmem_free()s */
69 static uint32_t afd_wait;	/* count of waits on non-zero ref count */
70 #define	MAXFD(x)	(afd_maxfd = ((afd_maxfd >= (x))? afd_maxfd : (x)))
71 #define	COUNT(x)	atomic_add_32(&x, 1)
72 
73 #else	/* DEBUG */
74 
75 #define	MAXFD(x)
76 #define	COUNT(x)
77 
78 #endif	/* DEBUG */
79 
80 kmem_cache_t *file_cache;
81 static int vpsetattr(vnode_t *, vattr_t *, int);
82 
83 static void port_close_fd(portfd_t *, int);
84 
85 /*
86  * File descriptor allocation.
87  *
88  * fd_find(fip, minfd) finds the first available descriptor >= minfd.
89  * The most common case is open(2), in which minfd = 0, but we must also
90  * support fcntl(fd, F_DUPFD, minfd).
91  *
92  * The algorithm is as follows: we keep all file descriptors in an infix
93  * binary tree in which each node records the number of descriptors
94  * allocated in its right subtree, including itself.  Starting at minfd,
95  * we ascend the tree until we find a non-fully allocated right subtree.
96  * We then descend that subtree in a binary search for the smallest fd.
97  * Finally, we ascend the tree again to increment the allocation count
98  * of every subtree containing the newly-allocated fd.  Freeing an fd
99  * requires only the last step: we ascend the tree to decrement allocation
100  * counts.  Each of these three steps (ascent to find non-full subtree,
101  * descent to find lowest fd, ascent to update allocation counts) is
102  * O(log n), thus the algorithm as a whole is O(log n).
103  *
104  * We don't implement the fd tree using the customary left/right/parent
105  * pointers, but instead take advantage of the glorious mathematics of
106  * full infix binary trees.  For reference, here's an illustration of the
107  * logical structure of such a tree, rooted at 4 (binary 100), covering
108  * the range 1-7 (binary 001-111).  Our canonical trees do not include
109  * fd 0; we'll deal with that later.
110  *
111  *	      100
112  *	     /	 \
113  *	    /	  \
114  *	  010	  110
115  *	  / \	  / \
116  *	001 011 101 111
117  *
118  * We make the following observations, all of which are easily proven by
119  * induction on the depth of the tree:
120  *
121  * (T1) The least-significant bit (LSB) of any node is equal to its level
122  *      in the tree.  In our example, nodes 001, 011, 101 and 111 are at
123  *      level 0; nodes 010 and 110 are at level 1; and node 100 is at level 2.
124  *
125  * (T2) The child size (CSIZE) of node N -- that is, the total number of
126  *	right-branch descendants in a child of node N, including itself -- is
127  *	given by clearing all but the least significant bit of N.  This
128  *	follows immediately from (T1).  Applying this rule to our example, we
129  *	see that CSIZE(100) = 100, CSIZE(x10) = 10, and CSIZE(xx1) = 1.
130  *
131  * (T3) The nearest left ancestor (LPARENT) of node N -- that is, the nearest
132  *	ancestor containing node N in its right child -- is given by clearing
133  *	the LSB of N.  For example, LPARENT(111) = 110 and LPARENT(110) = 100.
134  *	Clearing the LSB of nodes 001, 010 or 100 yields zero, reflecting
135  *	the fact that these are leftmost nodes.  Note that this algorithm
136  *	automatically skips generations as necessary.  For example, the parent
137  *      of node 101 is 110, which is a *right* ancestor (not what we want);
138  *      but its grandparent is 100, which is a left ancestor. Clearing the LSB
139  *      of 101 gets us to 100 directly, skipping right past the uninteresting
140  *      generation (110).
141  *
142  *      Note that since LPARENT clears the LSB, whereas CSIZE clears all *but*
143  *	the LSB, we can express LPARENT() nicely in terms of CSIZE():
144  *
145  *	LPARENT(N) = N - CSIZE(N)
146  *
147  * (T4) The nearest right ancestor (RPARENT) of node N is given by:
148  *
149  *	RPARENT(N) = N + CSIZE(N)
150  *
151  * (T5) For every interior node, the children differ from their parent by
152  *	CSIZE(parent) / 2.  In our example, CSIZE(100) / 2 = 2 = 10 binary,
153  *      and indeed, the children of 100 are 100 +/- 10 = 010 and 110.
154  *
155  * Next, we'll need a few two's-complement math tricks.  Suppose a number,
156  * N, has the following form:
157  *
158  *		N = xxxx10...0
159  *
160  * That is, the binary representation of N consists of some string of bits,
161  * then a 1, then all zeroes.  This amounts to nothing more than saying that
162  * N has a least-significant bit, which is true for any N != 0.  If we look
163  * at N and N - 1 together, we see that we can combine them in useful ways:
164  *
165  *		  N = xxxx10...0
166  *	      N - 1 = xxxx01...1
167  *	------------------------
168  *	N & (N - 1) = xxxx000000
169  *	N | (N - 1) = xxxx111111
170  *	N ^ (N - 1) =     111111
171  *
172  * In particular, this suggests several easy ways to clear all but the LSB,
173  * which by (T2) is exactly what we need to determine CSIZE(N) = 10...0.
174  * We'll opt for this formulation:
175  *
176  *	(C1) CSIZE(N) = (N - 1) ^ (N | (N - 1))
177  *
178  * Similarly, we have an easy way to determine LPARENT(N), which requires
179  * that we clear the LSB of N:
180  *
181  *	(L1) LPARENT(N) = N & (N - 1)
182  *
183  * We note in the above relations that (N | (N - 1)) - N = CSIZE(N) - 1.
184  * When combined with (T4), this yields an easy way to compute RPARENT(N):
185  *
186  *	(R1) RPARENT(N) = (N | (N - 1)) + 1
187  *
188  * Finally, to accommodate fd 0 we must adjust all of our results by +/-1 to
189  * move the fd range from [1, 2^n) to [0, 2^n - 1).  This is straightforward,
190  * so there's no need to belabor the algebra; the revised relations become:
191  *
192  *	(C1a) CSIZE(N) = N ^ (N | (N + 1))
193  *
194  *	(L1a) LPARENT(N) = (N & (N + 1)) - 1
195  *
196  *	(R1a) RPARENT(N) = N | (N + 1)
197  *
198  * This completes the mathematical framework.  We now have all the tools
199  * we need to implement fd_find() and fd_reserve().
200  *
201  * fd_find(fip, minfd) finds the smallest available file descriptor >= minfd.
202  * It does not actually allocate the descriptor; that's done by fd_reserve().
203  * fd_find() proceeds in two steps:
204  *
205  * (1) Find the leftmost subtree that contains a descriptor >= minfd.
206  *     We start at the right subtree rooted at minfd.  If this subtree is
207  *     not full -- if fip->fi_list[minfd].uf_alloc != CSIZE(minfd) -- then
208  *     step 1 is done.  Otherwise, we know that all fds in this subtree
209  *     are taken, so we ascend to RPARENT(minfd) using (R1a).  We repeat
210  *     this process until we either find a candidate subtree or exceed
211  *     fip->fi_nfiles.  We use (C1a) to compute CSIZE().
212  *
213  * (2) Find the smallest fd in the subtree discovered by step 1.
214  *     Starting at the root of this subtree, we descend to find the
215  *     smallest available fd.  Since the left children have the smaller
216  *     fds, we will descend rightward only when the left child is full.
217  *
218  *     We begin by comparing the number of allocated fds in the root
219  *     to the number of allocated fds in its right child; if they differ
220  *     by exactly CSIZE(child), we know the left subtree is full, so we
221  *     descend right; that is, the right child becomes the search root.
222  *     Otherwise we leave the root alone and start following the right
223  *     child's left children.  As fortune would have it, this is very
224  *     simple computationally: by (T5), the right child of fd is just
225  *     fd + size, where size = CSIZE(fd) / 2.  Applying (T5) again,
226  *     we find that the right child's left child is fd + size - (size / 2) =
227  *     fd + (size / 2); *its* left child is fd + (size / 2) - (size / 4) =
228  *     fd + (size / 4), and so on.  In general, fd's right child's
229  *     leftmost nth descendant is fd + (size >> n).  Thus, to follow
230  *     the right child's left descendants, we just halve the size in
231  *     each iteration of the search.
232  *
233  *     When we descend leftward, we must keep track of the number of fds
234  *     that were allocated in all the right subtrees we rejected, so we
235  *     know how many of the root fd's allocations are in the remaining
236  *     (as yet unexplored) leftmost part of its right subtree.  When we
237  *     encounter a fully-allocated left child -- that is, when we find
238  *     that fip->fi_list[fd].uf_alloc == ralloc + size -- we descend right
239  *     (as described earlier), resetting ralloc to zero.
240  *
241  * fd_reserve(fip, fd, incr) either allocates or frees fd, depending
242  * on whether incr is 1 or -1.  Starting at fd, fd_reserve() ascends
243  * the leftmost ancestors (see (T3)) and updates the allocation counts.
244  * At each step we use (L1a) to compute LPARENT(), the next left ancestor.
245  *
246  * flist_minsize() finds the minimal tree that still covers all
247  * used fds; as long as the allocation count of a root node is zero, we
248  * don't need that node or its right subtree.
249  *
250  * flist_nalloc() counts the number of allocated fds in the tree, by starting
251  * at the top of the tree and summing the right-subtree allocation counts as
252  * it descends leftwards.
253  *
254  * Note: we assume that flist_grow() will keep fip->fi_nfiles of the form
255  * 2^n - 1.  This ensures that the fd trees are always full, which saves
256  * quite a bit of boundary checking.
257  */
258 static int
259 fd_find(uf_info_t *fip, int minfd)
260 {
261 	int size, ralloc, fd;
262 
263 	ASSERT(MUTEX_HELD(&fip->fi_lock));
264 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
265 
266 	for (fd = minfd; (uint_t)fd < fip->fi_nfiles; fd |= fd + 1) {
267 		size = fd ^ (fd | (fd + 1));
268 		if (fip->fi_list[fd].uf_alloc == size)
269 			continue;
270 		for (ralloc = 0, size >>= 1; size != 0; size >>= 1) {
271 			ralloc += fip->fi_list[fd + size].uf_alloc;
272 			if (fip->fi_list[fd].uf_alloc == ralloc + size) {
273 				fd += size;
274 				ralloc = 0;
275 			}
276 		}
277 		return (fd);
278 	}
279 	return (-1);
280 }
281 
282 static void
283 fd_reserve(uf_info_t *fip, int fd, int incr)
284 {
285 	int pfd;
286 	uf_entry_t *ufp = &fip->fi_list[fd];
287 
288 	ASSERT((uint_t)fd < fip->fi_nfiles);
289 	ASSERT((ufp->uf_busy == 0 && incr == 1) ||
290 	    (ufp->uf_busy == 1 && incr == -1));
291 	ASSERT(MUTEX_HELD(&ufp->uf_lock));
292 	ASSERT(MUTEX_HELD(&fip->fi_lock));
293 
294 	for (pfd = fd; pfd >= 0; pfd = (pfd & (pfd + 1)) - 1)
295 		fip->fi_list[pfd].uf_alloc += incr;
296 
297 	ufp->uf_busy += incr;
298 }
299 
300 static int
301 flist_minsize(uf_info_t *fip)
302 {
303 	int fd;
304 
305 	/*
306 	 * We'd like to ASSERT(MUTEX_HELD(&fip->fi_lock)), but we're called
307 	 * by flist_fork(), which relies on other mechanisms for mutual
308 	 * exclusion.
309 	 */
310 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
311 
312 	for (fd = fip->fi_nfiles; fd != 0; fd >>= 1)
313 		if (fip->fi_list[fd >> 1].uf_alloc != 0)
314 			break;
315 
316 	return (fd);
317 }
318 
319 static int
320 flist_nalloc(uf_info_t *fip)
321 {
322 	int fd;
323 	int nalloc = 0;
324 
325 	ASSERT(MUTEX_HELD(&fip->fi_lock));
326 	ASSERT((fip->fi_nfiles & (fip->fi_nfiles + 1)) == 0);
327 
328 	for (fd = fip->fi_nfiles; fd != 0; fd >>= 1)
329 		nalloc += fip->fi_list[fd >> 1].uf_alloc;
330 
331 	return (nalloc);
332 }
333 
334 /*
335  * Increase size of the fi_list array to accommodate at least maxfd.
336  * We keep the size of the form 2^n - 1 for benefit of fd_find().
337  */
338 static void
339 flist_grow(int maxfd)
340 {
341 	uf_info_t *fip = P_FINFO(curproc);
342 	int newcnt, oldcnt;
343 	uf_entry_t *src, *dst, *newlist, *oldlist, *newend, *oldend;
344 	uf_rlist_t *urp;
345 
346 	for (newcnt = 1; newcnt <= maxfd; newcnt = (newcnt << 1) | 1)
347 		continue;
348 
349 	newlist = kmem_zalloc(newcnt * sizeof (uf_entry_t), KM_SLEEP);
350 
351 	mutex_enter(&fip->fi_lock);
352 	oldcnt = fip->fi_nfiles;
353 	if (newcnt <= oldcnt) {
354 		mutex_exit(&fip->fi_lock);
355 		kmem_free(newlist, newcnt * sizeof (uf_entry_t));
356 		return;
357 	}
358 	ASSERT((newcnt & (newcnt + 1)) == 0);
359 	oldlist = fip->fi_list;
360 	oldend = oldlist + oldcnt;
361 	newend = newlist + oldcnt;	/* no need to lock beyond old end */
362 
363 	/*
364 	 * fi_list and fi_nfiles cannot change while any uf_lock is held,
365 	 * so we must grab all the old locks *and* the new locks up to oldcnt.
366 	 * (Locks beyond the end of oldcnt aren't visible until we store
367 	 * the new fi_nfiles, which is the last thing we do before dropping
368 	 * all the locks, so there's no need to acquire these locks).
369 	 * Holding the new locks is necessary because when fi_list changes
370 	 * to point to the new list, fi_nfiles won't have been stored yet.
371 	 * If we *didn't* hold the new locks, someone doing a UF_ENTER()
372 	 * could see the new fi_list, grab the new uf_lock, and then see
373 	 * fi_nfiles change while the lock is held -- in violation of
374 	 * UF_ENTER() semantics.
375 	 */
376 	for (src = oldlist; src < oldend; src++)
377 		mutex_enter(&src->uf_lock);
378 
379 	for (dst = newlist; dst < newend; dst++)
380 		mutex_enter(&dst->uf_lock);
381 
382 	for (src = oldlist, dst = newlist; src < oldend; src++, dst++) {
383 		dst->uf_file = src->uf_file;
384 		dst->uf_fpollinfo = src->uf_fpollinfo;
385 		dst->uf_refcnt = src->uf_refcnt;
386 		dst->uf_alloc = src->uf_alloc;
387 		dst->uf_flag = src->uf_flag;
388 		dst->uf_busy = src->uf_busy;
389 		dst->uf_portfd = src->uf_portfd;
390 	}
391 
392 	/*
393 	 * As soon as we store the new flist, future locking operations
394 	 * will use it.  Therefore, we must ensure that all the state
395 	 * we've just established reaches global visibility before the
396 	 * new flist does.
397 	 */
398 	membar_producer();
399 	fip->fi_list = newlist;
400 
401 	/*
402 	 * Routines like getf() make an optimistic check on the validity
403 	 * of the supplied file descriptor: if it's less than the current
404 	 * value of fi_nfiles -- examined without any locks -- then it's
405 	 * safe to attempt a UF_ENTER() on that fd (which is a valid
406 	 * assumption because fi_nfiles only increases).  Therefore, it
407 	 * is critical that the new value of fi_nfiles not reach global
408 	 * visibility until after the new fi_list: if it happened the
409 	 * other way around, getf() could see the new fi_nfiles and attempt
410 	 * a UF_ENTER() on the old fi_list, which would write beyond its
411 	 * end if the fd exceeded the old fi_nfiles.
412 	 */
413 	membar_producer();
414 	fip->fi_nfiles = newcnt;
415 
416 	/*
417 	 * The new state is consistent now, so we can drop all the locks.
418 	 */
419 	for (dst = newlist; dst < newend; dst++)
420 		mutex_exit(&dst->uf_lock);
421 
422 	for (src = oldlist; src < oldend; src++) {
423 		/*
424 		 * If any threads are blocked on the old cvs, wake them.
425 		 * This will force them to wake up, discover that fi_list
426 		 * has changed, and go back to sleep on the new cvs.
427 		 */
428 		cv_broadcast(&src->uf_wanted_cv);
429 		cv_broadcast(&src->uf_closing_cv);
430 		mutex_exit(&src->uf_lock);
431 	}
432 
433 	mutex_exit(&fip->fi_lock);
434 
435 	/*
436 	 * Retire the old flist.  We can't actually kmem_free() it now
437 	 * because someone may still have a pointer to it.  Instead,
438 	 * we link it onto a list of retired flists.  The new flist
439 	 * is at least double the size of the previous flist, so the
440 	 * total size of all retired flists will be less than the size
441 	 * of the current one (to prove, consider the sum of a geometric
442 	 * series in powers of 2).  exit() frees the retired flists.
443 	 */
444 	urp = kmem_zalloc(sizeof (uf_rlist_t), KM_SLEEP);
445 	urp->ur_list = oldlist;
446 	urp->ur_nfiles = oldcnt;
447 
448 	mutex_enter(&fip->fi_lock);
449 	urp->ur_next = fip->fi_rlist;
450 	fip->fi_rlist = urp;
451 	mutex_exit(&fip->fi_lock);
452 }
453 
454 /*
455  * Utility functions for keeping track of the active file descriptors.
456  */
457 void
458 clear_stale_fd()		/* called from post_syscall() */
459 {
460 	afd_t *afd = &curthread->t_activefd;
461 	int i;
462 
463 	/* uninitialized is ok here, a_nfd is then zero */
464 	for (i = 0; i < afd->a_nfd; i++) {
465 		/* assert that this should not be necessary */
466 		ASSERT(afd->a_fd[i] == -1);
467 		afd->a_fd[i] = -1;
468 	}
469 	afd->a_stale = 0;
470 }
471 
472 void
473 free_afd(afd_t *afd)		/* called below and from thread_free() */
474 {
475 	int i;
476 
477 	/* free the buffer if it was kmem_alloc()ed */
478 	if (afd->a_nfd > sizeof (afd->a_buf) / sizeof (afd->a_buf[0])) {
479 		COUNT(afd_free);
480 		kmem_free(afd->a_fd, afd->a_nfd * sizeof (afd->a_fd[0]));
481 	}
482 
483 	/* (re)initialize the structure */
484 	afd->a_fd = &afd->a_buf[0];
485 	afd->a_nfd = sizeof (afd->a_buf) / sizeof (afd->a_buf[0]);
486 	afd->a_stale = 0;
487 	for (i = 0; i < afd->a_nfd; i++)
488 		afd->a_fd[i] = -1;
489 }
490 
491 static void
492 set_active_fd(int fd)
493 {
494 	afd_t *afd = &curthread->t_activefd;
495 	int i;
496 	int *old_fd;
497 	int old_nfd;
498 
499 	if (afd->a_nfd == 0)	/* first time initialization */
500 		free_afd(afd);
501 
502 	/* insert fd into vacant slot, if any */
503 	for (i = 0; i < afd->a_nfd; i++) {
504 		if (afd->a_fd[i] == -1) {
505 			afd->a_fd[i] = fd;
506 			return;
507 		}
508 	}
509 
510 	/*
511 	 * Reallocate the a_fd[] array to add one more slot.
512 	 */
513 	old_fd = afd->a_fd;
514 	old_nfd = afd->a_nfd;
515 	afd->a_nfd = old_nfd + 1;
516 	MAXFD(afd->a_nfd);
517 	COUNT(afd_alloc);
518 	afd->a_fd = kmem_alloc(afd->a_nfd * sizeof (afd->a_fd[0]), KM_SLEEP);
519 	for (i = 0; i < old_nfd; i++)
520 		afd->a_fd[i] = old_fd[i];
521 	afd->a_fd[i] = fd;
522 
523 	if (old_nfd > sizeof (afd->a_buf) / sizeof (afd->a_buf[0])) {
524 		COUNT(afd_free);
525 		kmem_free(old_fd, old_nfd * sizeof (afd->a_fd[0]));
526 	}
527 }
528 
529 void
530 clear_active_fd(int fd)		/* called below and from aio.c */
531 {
532 	afd_t *afd = &curthread->t_activefd;
533 	int i;
534 
535 	for (i = 0; i < afd->a_nfd; i++) {
536 		if (afd->a_fd[i] == fd) {
537 			afd->a_fd[i] = -1;
538 			break;
539 		}
540 	}
541 	ASSERT(i < afd->a_nfd);		/* not found is not ok */
542 }
543 
544 /*
545  * Does this thread have this fd active?
546  */
547 static int
548 is_active_fd(kthread_t *t, int fd)
549 {
550 	afd_t *afd = &t->t_activefd;
551 	int i;
552 
553 	/* uninitialized is ok here, a_nfd is then zero */
554 	for (i = 0; i < afd->a_nfd; i++) {
555 		if (afd->a_fd[i] == fd)
556 			return (1);
557 	}
558 	return (0);
559 }
560 
561 /*
562  * Convert a user supplied file descriptor into a pointer to a file
563  * structure.  Only task is to check range of the descriptor (soft
564  * resource limit was enforced at open time and shouldn't be checked
565  * here).
566  */
567 file_t *
568 getf(int fd)
569 {
570 	uf_info_t *fip = P_FINFO(curproc);
571 	uf_entry_t *ufp;
572 	file_t *fp;
573 
574 	if ((uint_t)fd >= fip->fi_nfiles)
575 		return (NULL);
576 
577 	UF_ENTER(ufp, fip, fd);
578 	if ((fp = ufp->uf_file) == NULL) {
579 		UF_EXIT(ufp);
580 		return (NULL);
581 	}
582 	ufp->uf_refcnt++;
583 
584 #ifdef C2_AUDIT
585 	/*
586 	 * archive per file audit data
587 	 */
588 	if (audit_active)
589 		(void) audit_getf(fd);
590 #endif
591 	UF_EXIT(ufp);
592 
593 	set_active_fd(fd);	/* record the active file descriptor */
594 
595 	return (fp);
596 }
597 
598 /*
599  * Close whatever file currently occupies the file descriptor slot
600  * and install the new file, usually NULL, in the file descriptor slot.
601  * The close must complete before we release the file descriptor slot.
602  * We return the error number from closef().
603  */
604 int
605 closeandsetf(int fd, file_t *newfp)
606 {
607 	proc_t *p = curproc;
608 	uf_info_t *fip = P_FINFO(p);
609 	uf_entry_t *ufp;
610 	file_t *fp;
611 	fpollinfo_t *fpip;
612 	portfd_t *pfd;
613 	int error;
614 
615 	if ((uint_t)fd >= fip->fi_nfiles) {
616 		if (newfp == NULL)
617 			return (EBADF);
618 		flist_grow(fd);
619 	}
620 
621 	if (newfp != NULL) {
622 		/*
623 		 * If ufp is reserved but has no file pointer, it's in the
624 		 * transition between ufalloc() and setf().  We must wait
625 		 * for this transition to complete before assigning the
626 		 * new non-NULL file pointer.
627 		 */
628 		mutex_enter(&fip->fi_lock);
629 		UF_ENTER(ufp, fip, fd);
630 		while (ufp->uf_busy && ufp->uf_file == NULL) {
631 			mutex_exit(&fip->fi_lock);
632 			cv_wait_stop(&ufp->uf_wanted_cv, &ufp->uf_lock, 250);
633 			UF_EXIT(ufp);
634 			mutex_enter(&fip->fi_lock);
635 			UF_ENTER(ufp, fip, fd);
636 		}
637 		if ((fp = ufp->uf_file) == NULL) {
638 			ASSERT(ufp->uf_fpollinfo == NULL);
639 			ASSERT(ufp->uf_flag == 0);
640 			fd_reserve(fip, fd, 1);
641 			ufp->uf_file = newfp;
642 			UF_EXIT(ufp);
643 			mutex_exit(&fip->fi_lock);
644 			return (0);
645 		}
646 		mutex_exit(&fip->fi_lock);
647 	} else {
648 		UF_ENTER(ufp, fip, fd);
649 		if ((fp = ufp->uf_file) == NULL) {
650 			UF_EXIT(ufp);
651 			return (EBADF);
652 		}
653 	}
654 
655 #ifdef C2_AUDIT
656 	/*
657 	 * archive per file audit data
658 	 */
659 	if (audit_active)
660 		(void) audit_getf(fd);
661 #endif
662 	ASSERT(ufp->uf_busy);
663 	ufp->uf_file = NULL;
664 	ufp->uf_flag = 0;
665 
666 	/*
667 	 * If the file descriptor reference count is non-zero, then
668 	 * some other lwp in the process is performing system call
669 	 * activity on the file.  To avoid blocking here for a long
670 	 * time (the other lwp might be in a long term sleep in its
671 	 * system call), we stop all other lwps in the process and
672 	 * scan them to find the ones with this fd as one of their
673 	 * active fds and set their a_stale flag so they will emerge
674 	 * from their system calls immediately.  post_syscall() will
675 	 * test the a_stale flag and set errno to EBADF.
676 	 */
677 	ASSERT(ufp->uf_refcnt == 0 || p->p_lwpcnt > 1);
678 	if (ufp->uf_refcnt > 0) {
679 		UF_EXIT(ufp);
680 		COUNT(afd_wait);
681 
682 		/*
683 		 * Make all other lwps hold in place, as if doing fork1().
684 		 * holdlwps(SHOLDFORK1) fails only if another lwp wants to
685 		 * perform a forkall() or the process is exiting.  In either
686 		 * case, all other lwps are either returning from their
687 		 * system calls (because of SHOLDFORK) or calling lwp_exit()
688 		 * (because of SEXITLWPS) so we don't need to scan them.
689 		 */
690 		if (holdlwps(SHOLDFORK1)) {
691 			kthread_t *t;
692 
693 			mutex_enter(&p->p_lock);
694 			for (t = curthread->t_forw; t != curthread;
695 			    t = t->t_forw) {
696 				if (is_active_fd(t, fd)) {
697 					t->t_activefd.a_stale = 1;
698 					t->t_post_sys = 1;
699 				}
700 			}
701 			continuelwps(p);
702 			mutex_exit(&p->p_lock);
703 		}
704 		UF_ENTER(ufp, fip, fd);
705 		ASSERT(ufp->uf_file == NULL);
706 	}
707 
708 	/*
709 	 * Wait for other lwps to stop using this file descriptor.
710 	 */
711 	while (ufp->uf_refcnt > 0) {
712 		cv_wait_stop(&ufp->uf_closing_cv, &ufp->uf_lock, 250);
713 		/*
714 		 * cv_wait_stop() drops ufp->uf_lock, so the file list
715 		 * can change.  Drop the lock on our (possibly) stale
716 		 * ufp and let UF_ENTER() find and lock the current ufp.
717 		 */
718 		UF_EXIT(ufp);
719 		UF_ENTER(ufp, fip, fd);
720 	}
721 
722 #ifdef DEBUG
723 	/*
724 	 * catch a watchfd on device's pollhead list but not on fpollinfo list
725 	 */
726 	if (ufp->uf_fpollinfo != NULL)
727 		checkwfdlist(fp->f_vnode, ufp->uf_fpollinfo);
728 #endif	/* DEBUG */
729 
730 	/*
731 	 * We may need to cleanup some cached poll states in t_pollstate
732 	 * before the fd can be reused. It is important that we don't
733 	 * access a stale thread structure. We will do the cleanup in two
734 	 * phases to avoid deadlock and holding uf_lock for too long.
735 	 * In phase 1, hold the uf_lock and call pollblockexit() to set
736 	 * state in t_pollstate struct so that a thread does not exit on
737 	 * us. In phase 2, we drop the uf_lock and call pollcacheclean().
738 	 */
739 	pfd = ufp->uf_portfd;
740 	ufp->uf_portfd = NULL;
741 	fpip = ufp->uf_fpollinfo;
742 	ufp->uf_fpollinfo = NULL;
743 	if (fpip != NULL)
744 		pollblockexit(fpip);
745 	UF_EXIT(ufp);
746 	if (fpip != NULL)
747 		pollcacheclean(fpip, fd);
748 	if (pfd)
749 		port_close_fd(pfd, fd);
750 
751 	/*
752 	 * Keep the file descriptor entry reserved across the closef().
753 	 */
754 	error = closef(fp);
755 
756 	setf(fd, newfp);
757 
758 	return (error);
759 }
760 
761 /*
762  * Decrement uf_refcnt; wakeup anyone waiting to close the file.
763  */
764 void
765 releasef(int fd)
766 {
767 	uf_info_t *fip = P_FINFO(curproc);
768 	uf_entry_t *ufp;
769 
770 	clear_active_fd(fd);	/* clear the active file descriptor */
771 
772 	UF_ENTER(ufp, fip, fd);
773 	ASSERT(ufp->uf_refcnt > 0);
774 	if (--ufp->uf_refcnt == 0)
775 		cv_broadcast(&ufp->uf_closing_cv);
776 	UF_EXIT(ufp);
777 }
778 
779 /*
780  * Identical to releasef() but can be called from another process.
781  */
782 void
783 areleasef(int fd, uf_info_t *fip)
784 {
785 	uf_entry_t *ufp;
786 
787 	UF_ENTER(ufp, fip, fd);
788 	ASSERT(ufp->uf_refcnt > 0);
789 	if (--ufp->uf_refcnt == 0)
790 		cv_broadcast(&ufp->uf_closing_cv);
791 	UF_EXIT(ufp);
792 }
793 
794 /*
795  * Duplicate all file descriptors across a fork.
796  */
797 void
798 flist_fork(uf_info_t *pfip, uf_info_t *cfip)
799 {
800 	int fd, nfiles;
801 	uf_entry_t *pufp, *cufp;
802 
803 	mutex_init(&cfip->fi_lock, NULL, MUTEX_DEFAULT, NULL);
804 	cfip->fi_rlist = NULL;
805 
806 	/*
807 	 * We don't need to hold fi_lock because all other lwp's in the
808 	 * parent have been held.
809 	 */
810 	cfip->fi_nfiles = nfiles = flist_minsize(pfip);
811 
812 	cfip->fi_list = kmem_zalloc(nfiles * sizeof (uf_entry_t), KM_SLEEP);
813 
814 	for (fd = 0, pufp = pfip->fi_list, cufp = cfip->fi_list; fd < nfiles;
815 	    fd++, pufp++, cufp++) {
816 		cufp->uf_file = pufp->uf_file;
817 		cufp->uf_alloc = pufp->uf_alloc;
818 		cufp->uf_flag = pufp->uf_flag;
819 		cufp->uf_busy = pufp->uf_busy;
820 		if (pufp->uf_file == NULL) {
821 			ASSERT(pufp->uf_flag == 0);
822 			if (pufp->uf_busy) {
823 				/*
824 				 * Grab locks to appease ASSERTs in fd_reserve
825 				 */
826 				mutex_enter(&cfip->fi_lock);
827 				mutex_enter(&cufp->uf_lock);
828 				fd_reserve(cfip, fd, -1);
829 				mutex_exit(&cufp->uf_lock);
830 				mutex_exit(&cfip->fi_lock);
831 			}
832 		}
833 	}
834 }
835 
836 /*
837  * Close all open file descriptors for the current process.
838  * This is only called from exit(), which is single-threaded,
839  * so we don't need any locking.
840  */
841 void
842 closeall(uf_info_t *fip)
843 {
844 	int fd;
845 	file_t *fp;
846 	uf_entry_t *ufp;
847 
848 	ufp = fip->fi_list;
849 	for (fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
850 		if ((fp = ufp->uf_file) != NULL) {
851 			ufp->uf_file = NULL;
852 			if (ufp->uf_portfd != NULL) {
853 				/* remove event port association */
854 				port_close_fd(ufp->uf_portfd, fd);
855 				ufp->uf_portfd = NULL;
856 			}
857 			ASSERT(ufp->uf_fpollinfo == NULL);
858 			(void) closef(fp);
859 		}
860 	}
861 
862 	kmem_free(fip->fi_list, fip->fi_nfiles * sizeof (uf_entry_t));
863 	fip->fi_list = NULL;
864 	fip->fi_nfiles = 0;
865 	while (fip->fi_rlist != NULL) {
866 		uf_rlist_t *urp = fip->fi_rlist;
867 		fip->fi_rlist = urp->ur_next;
868 		kmem_free(urp->ur_list, urp->ur_nfiles * sizeof (uf_entry_t));
869 		kmem_free(urp, sizeof (uf_rlist_t));
870 	}
871 }
872 
873 /*
874  * Internal form of close.  Decrement reference count on file
875  * structure.  Decrement reference count on the vnode following
876  * removal of the referencing file structure.
877  */
878 int
879 closef(file_t *fp)
880 {
881 	vnode_t *vp;
882 	int error;
883 	int count;
884 	int flag;
885 	offset_t offset;
886 
887 #ifdef C2_AUDIT
888 	/*
889 	 * audit close of file (may be exit)
890 	 */
891 	if (audit_active)
892 		audit_closef(fp);
893 #endif
894 	ASSERT(MUTEX_NOT_HELD(&P_FINFO(curproc)->fi_lock));
895 
896 	mutex_enter(&fp->f_tlock);
897 
898 	ASSERT(fp->f_count > 0);
899 
900 	count = fp->f_count--;
901 	flag = fp->f_flag;
902 	offset = fp->f_offset;
903 
904 	vp = fp->f_vnode;
905 
906 	error = VOP_CLOSE(vp, flag, count, offset, fp->f_cred);
907 
908 	if (count > 1) {
909 		mutex_exit(&fp->f_tlock);
910 		return (error);
911 	}
912 	ASSERT(fp->f_count == 0);
913 	mutex_exit(&fp->f_tlock);
914 
915 	VN_RELE(vp);
916 #ifdef C2_AUDIT
917 	/*
918 	 * deallocate resources to audit_data
919 	 */
920 	if (audit_active)
921 		audit_unfalloc(fp);
922 #endif
923 	crfree(fp->f_cred);
924 	kmem_cache_free(file_cache, fp);
925 	return (error);
926 }
927 
928 /*
929  * This is a combination of ufalloc() and setf().
930  */
931 int
932 ufalloc_file(int start, file_t *fp)
933 {
934 	proc_t *p = curproc;
935 	uf_info_t *fip = P_FINFO(p);
936 	int filelimit;
937 	uf_entry_t *ufp;
938 	int nfiles;
939 	int fd;
940 
941 	/*
942 	 * Assertion is to convince the correctness of the following
943 	 * assignment for filelimit after casting to int.
944 	 */
945 	ASSERT(p->p_fno_ctl <= INT_MAX);
946 	filelimit = (int)p->p_fno_ctl;
947 
948 	for (;;) {
949 		mutex_enter(&fip->fi_lock);
950 		fd = fd_find(fip, start);
951 		if ((uint_t)fd < filelimit)
952 			break;
953 		if (fd >= filelimit) {
954 			mutex_exit(&fip->fi_lock);
955 			mutex_enter(&p->p_lock);
956 			(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
957 			    p->p_rctls, p, RCA_SAFE);
958 			mutex_exit(&p->p_lock);
959 			return (-1);
960 		}
961 		/* fd_find() returned -1 */
962 		nfiles = fip->fi_nfiles;
963 		mutex_exit(&fip->fi_lock);
964 		flist_grow(MAX(start, nfiles));
965 	}
966 
967 	UF_ENTER(ufp, fip, fd);
968 	fd_reserve(fip, fd, 1);
969 	ASSERT(ufp->uf_file == NULL);
970 	ufp->uf_file = fp;
971 	UF_EXIT(ufp);
972 	mutex_exit(&fip->fi_lock);
973 	return (fd);
974 }
975 
976 /*
977  * Allocate a user file descriptor greater than or equal to "start".
978  */
979 int
980 ufalloc(int start)
981 {
982 	return (ufalloc_file(start, NULL));
983 }
984 
985 /*
986  * Check that a future allocation of count fds on proc p has a good
987  * chance of succeeding.  If not, do rctl processing as if we'd failed
988  * the allocation.
989  *
990  * Our caller must guarantee that p cannot disappear underneath us.
991  */
992 int
993 ufcanalloc(proc_t *p, uint_t count)
994 {
995 	uf_info_t *fip = P_FINFO(p);
996 	int filelimit;
997 	int current;
998 
999 	if (count == 0)
1000 		return (1);
1001 
1002 	ASSERT(p->p_fno_ctl <= INT_MAX);
1003 	filelimit = (int)p->p_fno_ctl;
1004 
1005 	mutex_enter(&fip->fi_lock);
1006 	current = flist_nalloc(fip);		/* # of in-use descriptors */
1007 	mutex_exit(&fip->fi_lock);
1008 
1009 	/*
1010 	 * If count is a positive integer, the worst that can happen is
1011 	 * an overflow to a negative value, which is caught by the >= 0 check.
1012 	 */
1013 	current += count;
1014 	if (count <= INT_MAX && current >= 0 && current <= filelimit)
1015 		return (1);
1016 
1017 	mutex_enter(&p->p_lock);
1018 	(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
1019 	    p->p_rctls, p, RCA_SAFE);
1020 	mutex_exit(&p->p_lock);
1021 	return (0);
1022 }
1023 
1024 /*
1025  * Allocate a user file descriptor and a file structure.
1026  * Initialize the descriptor to point at the file structure.
1027  * If fdp is NULL, the user file descriptor will not be allocated.
1028  */
1029 int
1030 falloc(vnode_t *vp, int flag, file_t **fpp, int *fdp)
1031 {
1032 	file_t *fp;
1033 	int fd;
1034 
1035 	if (fdp) {
1036 		if ((fd = ufalloc(0)) == -1)
1037 			return (EMFILE);
1038 	}
1039 	fp = kmem_cache_alloc(file_cache, KM_SLEEP);
1040 	/*
1041 	 * Note: falloc returns the fp locked
1042 	 */
1043 	mutex_enter(&fp->f_tlock);
1044 	fp->f_count = 1;
1045 	fp->f_flag = (ushort_t)flag;
1046 	fp->f_vnode = vp;
1047 	fp->f_offset = 0;
1048 	fp->f_audit_data = 0;
1049 	crhold(fp->f_cred = CRED());
1050 #ifdef C2_AUDIT
1051 	/*
1052 	 * allocate resources to audit_data
1053 	 */
1054 	if (audit_active)
1055 		audit_falloc(fp);
1056 #endif
1057 	*fpp = fp;
1058 	if (fdp)
1059 		*fdp = fd;
1060 	return (0);
1061 }
1062 
1063 /*ARGSUSED*/
1064 static int
1065 file_cache_constructor(void *buf, void *cdrarg, int kmflags)
1066 {
1067 	file_t *fp = buf;
1068 
1069 	mutex_init(&fp->f_tlock, NULL, MUTEX_DEFAULT, NULL);
1070 	return (0);
1071 }
1072 
1073 /*ARGSUSED*/
1074 static void
1075 file_cache_destructor(void *buf, void *cdrarg)
1076 {
1077 	file_t *fp = buf;
1078 
1079 	mutex_destroy(&fp->f_tlock);
1080 }
1081 
1082 void
1083 finit()
1084 {
1085 	file_cache = kmem_cache_create("file_cache", sizeof (file_t), 0,
1086 	    file_cache_constructor, file_cache_destructor, NULL, NULL, NULL, 0);
1087 }
1088 
1089 void
1090 unfalloc(file_t *fp)
1091 {
1092 	ASSERT(MUTEX_HELD(&fp->f_tlock));
1093 	if (--fp->f_count <= 0) {
1094 #ifdef C2_AUDIT
1095 		/*
1096 		 * deallocate resources to audit_data
1097 		 */
1098 		if (audit_active)
1099 			audit_unfalloc(fp);
1100 #endif
1101 		crfree(fp->f_cred);
1102 		mutex_exit(&fp->f_tlock);
1103 		kmem_cache_free(file_cache, fp);
1104 	} else
1105 		mutex_exit(&fp->f_tlock);
1106 }
1107 
1108 /*
1109  * Given a file descriptor, set the user's
1110  * file pointer to the given parameter.
1111  */
1112 void
1113 setf(int fd, file_t *fp)
1114 {
1115 	uf_info_t *fip = P_FINFO(curproc);
1116 	uf_entry_t *ufp;
1117 
1118 #ifdef C2_AUDIT
1119 	if (audit_active)
1120 		audit_setf(fp, fd);
1121 #endif /* C2_AUDIT */
1122 
1123 	if (fp == NULL) {
1124 		mutex_enter(&fip->fi_lock);
1125 		UF_ENTER(ufp, fip, fd);
1126 		fd_reserve(fip, fd, -1);
1127 		mutex_exit(&fip->fi_lock);
1128 	} else {
1129 		UF_ENTER(ufp, fip, fd);
1130 		ASSERT(ufp->uf_busy);
1131 	}
1132 	ASSERT(ufp->uf_fpollinfo == NULL);
1133 	ASSERT(ufp->uf_flag == 0);
1134 	ufp->uf_file = fp;
1135 	cv_broadcast(&ufp->uf_wanted_cv);
1136 	UF_EXIT(ufp);
1137 }
1138 
1139 /*
1140  * Given a file descriptor, return the file table flags, plus,
1141  * if this is a socket in asynchronous mode, the FASYNC flag.
1142  * getf() may or may not have been called before calling f_getfl().
1143  */
1144 int
1145 f_getfl(int fd, int *flagp)
1146 {
1147 	uf_info_t *fip = P_FINFO(curproc);
1148 	uf_entry_t *ufp;
1149 	file_t *fp;
1150 	int error;
1151 
1152 	if ((uint_t)fd >= fip->fi_nfiles)
1153 		error = EBADF;
1154 	else {
1155 		UF_ENTER(ufp, fip, fd);
1156 		if ((fp = ufp->uf_file) == NULL)
1157 			error = EBADF;
1158 		else {
1159 			vnode_t *vp = fp->f_vnode;
1160 			int flag = fp->f_flag;
1161 
1162 			/*
1163 			 * BSD fcntl() FASYNC compatibility.
1164 			 *
1165 			 * SCTP doesn't have an associated stream and thus
1166 			 * doesn't store flags on it.
1167 			 */
1168 			if ((vp->v_type == VSOCK) && (vp->v_stream != NULL))
1169 				flag |= sock_getfasync(vp);
1170 			*flagp = flag;
1171 			error = 0;
1172 		}
1173 		UF_EXIT(ufp);
1174 	}
1175 
1176 	return (error);
1177 }
1178 
1179 /*
1180  * Given a file descriptor, return the user's file flags.
1181  * Force the FD_CLOEXEC flag for writable self-open /proc files.
1182  * getf() may or may not have been called before calling f_getfd_error().
1183  */
1184 int
1185 f_getfd_error(int fd, int *flagp)
1186 {
1187 	uf_info_t *fip = P_FINFO(curproc);
1188 	uf_entry_t *ufp;
1189 	file_t *fp;
1190 	int flag;
1191 	int error;
1192 
1193 	if ((uint_t)fd >= fip->fi_nfiles)
1194 		error = EBADF;
1195 	else {
1196 		UF_ENTER(ufp, fip, fd);
1197 		if ((fp = ufp->uf_file) == NULL)
1198 			error = EBADF;
1199 		else {
1200 			flag = ufp->uf_flag;
1201 			if ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode))
1202 				flag |= FD_CLOEXEC;
1203 			*flagp = flag;
1204 			error = 0;
1205 		}
1206 		UF_EXIT(ufp);
1207 	}
1208 
1209 	return (error);
1210 }
1211 
1212 /*
1213  * getf() must have been called before calling f_getfd().
1214  */
1215 char
1216 f_getfd(int fd)
1217 {
1218 	int flag = 0;
1219 	(void) f_getfd_error(fd, &flag);
1220 	return ((char)flag);
1221 }
1222 
1223 /*
1224  * Given a file descriptor and file flags, set the user's file flags.
1225  * At present, the only valid flag is FD_CLOEXEC.
1226  * getf() may or may not have been called before calling f_setfd_error().
1227  */
1228 int
1229 f_setfd_error(int fd, int flags)
1230 {
1231 	uf_info_t *fip = P_FINFO(curproc);
1232 	uf_entry_t *ufp;
1233 	int error;
1234 
1235 	if ((uint_t)fd >= fip->fi_nfiles)
1236 		error = EBADF;
1237 	else {
1238 		UF_ENTER(ufp, fip, fd);
1239 		if (ufp->uf_file == NULL)
1240 			error = EBADF;
1241 		else {
1242 			ufp->uf_flag = flags & FD_CLOEXEC;
1243 			error = 0;
1244 		}
1245 		UF_EXIT(ufp);
1246 	}
1247 	return (error);
1248 }
1249 
1250 void
1251 f_setfd(int fd, char flags)
1252 {
1253 	(void) f_setfd_error(fd, flags);
1254 }
1255 
1256 /*
1257  * Allocate a file descriptor and assign it to the vnode "*vpp",
1258  * performing the usual open protocol upon it and returning the
1259  * file descriptor allocated.  It is the responsibility of the
1260  * caller to dispose of "*vpp" if any error occurs.
1261  */
1262 int
1263 fassign(vnode_t **vpp, int mode, int *fdp)
1264 {
1265 	file_t *fp;
1266 	int error;
1267 	int fd;
1268 
1269 	if (error = falloc((vnode_t *)NULL, mode, &fp, &fd))
1270 		return (error);
1271 	if (error = VOP_OPEN(vpp, mode, fp->f_cred)) {
1272 		setf(fd, NULL);
1273 		unfalloc(fp);
1274 		return (error);
1275 	}
1276 	fp->f_vnode = *vpp;
1277 	mutex_exit(&fp->f_tlock);
1278 	/*
1279 	 * Fill in the slot falloc reserved.
1280 	 */
1281 	setf(fd, fp);
1282 	*fdp = fd;
1283 	return (0);
1284 }
1285 
1286 /*
1287  * When a process forks it must increment the f_count of all file pointers
1288  * since there is a new process pointing at them.  fcnt_add(fip, 1) does this.
1289  * Since we are called when there is only 1 active lwp we don't need to
1290  * hold fi_lock or any uf_lock.  If the fork fails, fork_fail() calls
1291  * fcnt_add(fip, -1) to restore the counts.
1292  */
1293 void
1294 fcnt_add(uf_info_t *fip, int incr)
1295 {
1296 	int i;
1297 	uf_entry_t *ufp;
1298 	file_t *fp;
1299 
1300 	ufp = fip->fi_list;
1301 	for (i = 0; i < fip->fi_nfiles; i++, ufp++) {
1302 		if ((fp = ufp->uf_file) != NULL) {
1303 			mutex_enter(&fp->f_tlock);
1304 			ASSERT((incr == 1 && fp->f_count >= 1) ||
1305 			    (incr == -1 && fp->f_count >= 2));
1306 			fp->f_count += incr;
1307 			mutex_exit(&fp->f_tlock);
1308 		}
1309 	}
1310 }
1311 
1312 /*
1313  * This is called from exec to close all fd's that have the FD_CLOEXEC flag
1314  * set and also to close all self-open for write /proc file descriptors.
1315  */
1316 void
1317 close_exec(uf_info_t *fip)
1318 {
1319 	int fd;
1320 	file_t *fp;
1321 	fpollinfo_t *fpip;
1322 	uf_entry_t *ufp;
1323 	portfd_t *pfd;
1324 
1325 	ufp = fip->fi_list;
1326 	for (fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
1327 		if ((fp = ufp->uf_file) != NULL &&
1328 		    ((ufp->uf_flag & FD_CLOEXEC) ||
1329 		    ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode)))) {
1330 			fpip = ufp->uf_fpollinfo;
1331 			mutex_enter(&fip->fi_lock);
1332 			mutex_enter(&ufp->uf_lock);
1333 			fd_reserve(fip, fd, -1);
1334 			mutex_exit(&fip->fi_lock);
1335 			ufp->uf_file = NULL;
1336 			ufp->uf_fpollinfo = NULL;
1337 			ufp->uf_flag = 0;
1338 			/*
1339 			 * We may need to cleanup some cached poll states
1340 			 * in t_pollstate before the fd can be reused. It
1341 			 * is important that we don't access a stale thread
1342 			 * structure. We will do the cleanup in two
1343 			 * phases to avoid deadlock and holding uf_lock for
1344 			 * too long. In phase 1, hold the uf_lock and call
1345 			 * pollblockexit() to set state in t_pollstate struct
1346 			 * so that a thread does not exit on us. In phase 2,
1347 			 * we drop the uf_lock and call pollcacheclean().
1348 			 */
1349 			pfd = ufp->uf_portfd;
1350 			ufp->uf_portfd = NULL;
1351 			if (fpip != NULL)
1352 				pollblockexit(fpip);
1353 			mutex_exit(&ufp->uf_lock);
1354 			if (fpip != NULL)
1355 				pollcacheclean(fpip, fd);
1356 			if (pfd)
1357 				port_close_fd(pfd, fd);
1358 			(void) closef(fp);
1359 		}
1360 	}
1361 }
1362 
1363 /*
1364  * Common routine for modifying attributes of named files.
1365  */
1366 int
1367 namesetattr(char *fnamep, enum symfollow followlink, vattr_t *vap, int flags)
1368 {
1369 	vnode_t *vp;
1370 	int error = 0;
1371 
1372 	if (error = lookupname(fnamep, UIO_USERSPACE, followlink, NULLVPP, &vp))
1373 		return (set_errno(error));
1374 	if (error = vpsetattr(vp, vap, flags))
1375 		(void) set_errno(error);
1376 	VN_RELE(vp);
1377 	return (error);
1378 }
1379 
1380 /*
1381  * Common routine for modifying attributes of files referenced
1382  * by descriptor.
1383  */
1384 int
1385 fdsetattr(int fd, vattr_t *vap)
1386 {
1387 	file_t *fp;
1388 	vnode_t *vp;
1389 	int error = 0;
1390 
1391 	if ((fp = getf(fd)) != NULL) {
1392 		vp = fp->f_vnode;
1393 		if (error = vpsetattr(vp, vap, 0)) {
1394 			(void) set_errno(error);
1395 		}
1396 		releasef(fd);
1397 	} else
1398 		error = set_errno(EBADF);
1399 	return (error);
1400 }
1401 
1402 /*
1403  * Common routine to set the attributes for the given vnode.
1404  * If the vnode is a file and the filesize is being manipulated,
1405  * this makes sure that there are no conflicting non-blocking
1406  * mandatory locks in that region.
1407  */
1408 static int
1409 vpsetattr(vnode_t *vp, vattr_t *vap, int flags)
1410 {
1411 	int error = 0;
1412 	int in_crit = 0;
1413 	u_offset_t	begin;
1414 	vattr_t	vattr;
1415 	ssize_t	length;
1416 
1417 	if (vn_is_readonly(vp)) {
1418 		error = EROFS;
1419 	}
1420 	if (!error && (vap->va_mask & AT_SIZE) &&
1421 	    nbl_need_check(vp)) {
1422 		nbl_start_crit(vp, RW_READER);
1423 		in_crit = 1;
1424 		vattr.va_mask = AT_SIZE;
1425 		if (!(error = VOP_GETATTR(vp, &vattr, 0, CRED()))) {
1426 			begin = vap->va_size > vattr.va_size ?
1427 					vattr.va_size : vap->va_size;
1428 			length = vattr.va_size > vap->va_size ?
1429 					vattr.va_size - vap->va_size :
1430 					vap->va_size - vattr.va_size;
1431 
1432 			if (nbl_conflict(vp, NBL_WRITE, begin, length, 0)) {
1433 				error = EACCES;
1434 			}
1435 		}
1436 	}
1437 	if (!error)
1438 		error = VOP_SETATTR(vp, vap, flags, CRED(), NULL);
1439 
1440 	if (in_crit)
1441 		nbl_end_crit(vp);
1442 
1443 	return (error);
1444 }
1445 
1446 /*
1447  * Return true if the given vnode is referenced by any
1448  * entry in the current process's file descriptor table.
1449  */
1450 int
1451 fisopen(vnode_t *vp)
1452 {
1453 	int fd;
1454 	file_t *fp;
1455 	vnode_t *ovp;
1456 	uf_info_t *fip = P_FINFO(curproc);
1457 	uf_entry_t *ufp;
1458 
1459 	mutex_enter(&fip->fi_lock);
1460 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1461 		UF_ENTER(ufp, fip, fd);
1462 		if ((fp = ufp->uf_file) != NULL &&
1463 		    (ovp = fp->f_vnode) != NULL && VN_CMP(vp, ovp)) {
1464 			UF_EXIT(ufp);
1465 			mutex_exit(&fip->fi_lock);
1466 			return (1);
1467 		}
1468 		UF_EXIT(ufp);
1469 	}
1470 	mutex_exit(&fip->fi_lock);
1471 	return (0);
1472 }
1473 
1474 /*
1475  * Return zero if at least one file currently open (by curproc) shouldn't be
1476  * allowed to change zones.
1477  */
1478 int
1479 files_can_change_zones(void)
1480 {
1481 	int fd;
1482 	file_t *fp;
1483 	uf_info_t *fip = P_FINFO(curproc);
1484 	uf_entry_t *ufp;
1485 
1486 	mutex_enter(&fip->fi_lock);
1487 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1488 		UF_ENTER(ufp, fip, fd);
1489 		if ((fp = ufp->uf_file) != NULL &&
1490 		    !vn_can_change_zones(fp->f_vnode)) {
1491 			UF_EXIT(ufp);
1492 			mutex_exit(&fip->fi_lock);
1493 			return (0);
1494 		}
1495 		UF_EXIT(ufp);
1496 	}
1497 	mutex_exit(&fip->fi_lock);
1498 	return (1);
1499 }
1500 
1501 #ifdef DEBUG
1502 
1503 /*
1504  * The following functions are only used in ASSERT()s elsewhere.
1505  * They do not modify the state of the system.
1506  */
1507 
1508 /*
1509  * Return true (1) if the current thread is in the fpollinfo
1510  * list for this file descriptor, else false (0).
1511  */
1512 static int
1513 curthread_in_plist(uf_entry_t *ufp)
1514 {
1515 	fpollinfo_t *fpip;
1516 
1517 	ASSERT(MUTEX_HELD(&ufp->uf_lock));
1518 	for (fpip = ufp->uf_fpollinfo; fpip; fpip = fpip->fp_next)
1519 		if (fpip->fp_thread == curthread)
1520 			return (1);
1521 	return (0);
1522 }
1523 
1524 /*
1525  * Sanity check to make sure that after lwp_exit(),
1526  * curthread does not appear on any fd's fpollinfo list.
1527  */
1528 void
1529 checkfpollinfo(void)
1530 {
1531 	int fd;
1532 	uf_info_t *fip = P_FINFO(curproc);
1533 	uf_entry_t *ufp;
1534 
1535 	mutex_enter(&fip->fi_lock);
1536 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1537 		UF_ENTER(ufp, fip, fd);
1538 		ASSERT(!curthread_in_plist(ufp));
1539 		UF_EXIT(ufp);
1540 	}
1541 	mutex_exit(&fip->fi_lock);
1542 }
1543 
1544 /*
1545  * Return true (1) if the current thread is in the fpollinfo
1546  * list for this file descriptor, else false (0).
1547  * This is the same as curthread_in_plist(),
1548  * but is called w/o holding uf_lock.
1549  */
1550 int
1551 infpollinfo(int fd)
1552 {
1553 	uf_info_t *fip = P_FINFO(curproc);
1554 	uf_entry_t *ufp;
1555 	int rc;
1556 
1557 	UF_ENTER(ufp, fip, fd);
1558 	rc = curthread_in_plist(ufp);
1559 	UF_EXIT(ufp);
1560 	return (rc);
1561 }
1562 
1563 #endif	/* DEBUG */
1564 
1565 /*
1566  * Add the curthread to fpollinfo list, meaning this fd is currently in the
1567  * thread's poll cache. Each lwp polling this file descriptor should call
1568  * this routine once.
1569  */
1570 void
1571 addfpollinfo(int fd)
1572 {
1573 	struct uf_entry *ufp;
1574 	fpollinfo_t *fpip;
1575 	uf_info_t *fip = P_FINFO(curproc);
1576 
1577 	fpip = kmem_zalloc(sizeof (fpollinfo_t), KM_SLEEP);
1578 	fpip->fp_thread = curthread;
1579 	UF_ENTER(ufp, fip, fd);
1580 	/*
1581 	 * Assert we are not already on the list, that is, that
1582 	 * this lwp did not call addfpollinfo twice for the same fd.
1583 	 */
1584 	ASSERT(!curthread_in_plist(ufp));
1585 	/*
1586 	 * addfpollinfo is always done inside the getf/releasef pair.
1587 	 */
1588 	ASSERT(ufp->uf_refcnt >= 1);
1589 	fpip->fp_next = ufp->uf_fpollinfo;
1590 	ufp->uf_fpollinfo = fpip;
1591 	UF_EXIT(ufp);
1592 }
1593 
1594 /*
1595  * delete curthread from fpollinfo list.
1596  */
1597 /*ARGSUSED*/
1598 void
1599 delfpollinfo(int fd)
1600 {
1601 	struct uf_entry *ufp;
1602 	struct fpollinfo *fpip;
1603 	struct fpollinfo **fpipp;
1604 	uf_info_t *fip = P_FINFO(curproc);
1605 
1606 	UF_ENTER(ufp, fip, fd);
1607 	if (ufp->uf_fpollinfo == NULL) {
1608 		UF_EXIT(ufp);
1609 		return;
1610 	}
1611 	ASSERT(ufp->uf_busy);
1612 	/*
1613 	 * Find and delete curthread from the list.
1614 	 */
1615 	fpipp = &ufp->uf_fpollinfo;
1616 	while ((fpip = *fpipp)->fp_thread != curthread)
1617 		fpipp = &fpip->fp_next;
1618 	*fpipp = fpip->fp_next;
1619 	kmem_free(fpip, sizeof (fpollinfo_t));
1620 	/*
1621 	 * Assert that we are not still on the list, that is, that
1622 	 * this lwp did not call addfpollinfo twice for the same fd.
1623 	 */
1624 	ASSERT(!curthread_in_plist(ufp));
1625 	UF_EXIT(ufp);
1626 }
1627 
1628 /*
1629  * fd is associated with a port. pfd is a pointer to the fd entry in the
1630  * cache of the port.
1631  */
1632 
1633 void
1634 addfd_port(int fd, portfd_t *pfd)
1635 {
1636 	struct uf_entry *ufp;
1637 	uf_info_t *fip = P_FINFO(curproc);
1638 
1639 	UF_ENTER(ufp, fip, fd);
1640 	/*
1641 	 * addfd_port is always done inside the getf/releasef pair.
1642 	 */
1643 	ASSERT(ufp->uf_refcnt >= 1);
1644 	if (ufp->uf_portfd == NULL) {
1645 		/* first entry */
1646 		ufp->uf_portfd = pfd;
1647 		pfd->pfd_next = NULL;
1648 	} else {
1649 		pfd->pfd_next = ufp->uf_portfd;
1650 		ufp->uf_portfd = pfd;
1651 		pfd->pfd_next->pfd_prev = pfd;
1652 	}
1653 	UF_EXIT(ufp);
1654 }
1655 
1656 void
1657 delfd_port(int fd, portfd_t *pfd)
1658 {
1659 	struct uf_entry *ufp;
1660 	uf_info_t *fip = P_FINFO(curproc);
1661 
1662 	UF_ENTER(ufp, fip, fd);
1663 	/*
1664 	 * delfd_port is always done inside the getf/releasef pair.
1665 	 */
1666 	ASSERT(ufp->uf_refcnt >= 1);
1667 	if (ufp->uf_portfd == pfd) {
1668 		/* remove first entry */
1669 		ufp->uf_portfd = pfd->pfd_next;
1670 	} else {
1671 		pfd->pfd_prev->pfd_next = pfd->pfd_next;
1672 		if (pfd->pfd_next != NULL)
1673 			pfd->pfd_next->pfd_prev = pfd->pfd_prev;
1674 	}
1675 	UF_EXIT(ufp);
1676 }
1677 
1678 static void
1679 port_close_fd(portfd_t *pfd, int fd)
1680 {
1681 	portfd_t	*pfdn;
1682 	struct uf_entry *ufp;
1683 	uf_info_t *fip = P_FINFO(curproc);
1684 
1685 	UF_ENTER(ufp, fip, fd);
1686 	for (; pfd != NULL; pfd = pfdn) {
1687 		pfdn = pfd->pfd_next;
1688 		port_close_pfd(pfd);
1689 	}
1690 	UF_EXIT(ufp);
1691 }
1692