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