xref: /titanic_52/usr/src/uts/common/os/fio.c (revision 5763ba1e357fad1d57b5875c499307b7ea6e2cd4)
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 2007 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
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 *);
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 
581 		if (fd == fip->fi_badfd && fip->fi_action > 0)
582 			tsignal(curthread, fip->fi_action);
583 
584 		return (NULL);
585 	}
586 	ufp->uf_refcnt++;
587 
588 #ifdef C2_AUDIT
589 	/*
590 	 * archive per file audit data
591 	 */
592 	if (audit_active)
593 		(void) audit_getf(fd);
594 #endif
595 	UF_EXIT(ufp);
596 
597 	set_active_fd(fd);	/* record the active file descriptor */
598 
599 	return (fp);
600 }
601 
602 /*
603  * Close whatever file currently occupies the file descriptor slot
604  * and install the new file, usually NULL, in the file descriptor slot.
605  * The close must complete before we release the file descriptor slot.
606  * If newfp != NULL we only return an error if we can't allocate the
607  * slot so the caller knows that it needs to free the filep;
608  * in the other cases we return the error number from closef().
609  */
610 int
611 closeandsetf(int fd, file_t *newfp)
612 {
613 	proc_t *p = curproc;
614 	uf_info_t *fip = P_FINFO(p);
615 	uf_entry_t *ufp;
616 	file_t *fp;
617 	fpollinfo_t *fpip;
618 	portfd_t *pfd;
619 	int error;
620 
621 	if ((uint_t)fd >= fip->fi_nfiles) {
622 		if (newfp == NULL)
623 			return (EBADF);
624 		flist_grow(fd);
625 	}
626 
627 	if (newfp != NULL) {
628 		/*
629 		 * If ufp is reserved but has no file pointer, it's in the
630 		 * transition between ufalloc() and setf().  We must wait
631 		 * for this transition to complete before assigning the
632 		 * new non-NULL file pointer.
633 		 */
634 		mutex_enter(&fip->fi_lock);
635 		if (fd == fip->fi_badfd) {
636 			mutex_exit(&fip->fi_lock);
637 			if (fip->fi_action > 0)
638 				tsignal(curthread, fip->fi_action);
639 			return (EBADF);
640 		}
641 		UF_ENTER(ufp, fip, fd);
642 		while (ufp->uf_busy && ufp->uf_file == NULL) {
643 			mutex_exit(&fip->fi_lock);
644 			cv_wait_stop(&ufp->uf_wanted_cv, &ufp->uf_lock, 250);
645 			UF_EXIT(ufp);
646 			mutex_enter(&fip->fi_lock);
647 			UF_ENTER(ufp, fip, fd);
648 		}
649 		if ((fp = ufp->uf_file) == NULL) {
650 			ASSERT(ufp->uf_fpollinfo == NULL);
651 			ASSERT(ufp->uf_flag == 0);
652 			fd_reserve(fip, fd, 1);
653 			ufp->uf_file = newfp;
654 			UF_EXIT(ufp);
655 			mutex_exit(&fip->fi_lock);
656 			return (0);
657 		}
658 		mutex_exit(&fip->fi_lock);
659 	} else {
660 		UF_ENTER(ufp, fip, fd);
661 		if ((fp = ufp->uf_file) == NULL) {
662 			UF_EXIT(ufp);
663 			return (EBADF);
664 		}
665 	}
666 
667 #ifdef C2_AUDIT
668 	/*
669 	 * archive per file audit data
670 	 */
671 	if (audit_active)
672 		(void) audit_getf(fd);
673 #endif
674 	ASSERT(ufp->uf_busy);
675 	ufp->uf_file = NULL;
676 	ufp->uf_flag = 0;
677 
678 	/*
679 	 * If the file descriptor reference count is non-zero, then
680 	 * some other lwp in the process is performing system call
681 	 * activity on the file.  To avoid blocking here for a long
682 	 * time (the other lwp might be in a long term sleep in its
683 	 * system call), we stop all other lwps in the process and
684 	 * scan them to find the ones with this fd as one of their
685 	 * active fds and set their a_stale flag so they will emerge
686 	 * from their system calls immediately.  post_syscall() will
687 	 * test the a_stale flag and set errno to EBADF.
688 	 */
689 	ASSERT(ufp->uf_refcnt == 0 || p->p_lwpcnt > 1);
690 	if (ufp->uf_refcnt > 0) {
691 		UF_EXIT(ufp);
692 		COUNT(afd_wait);
693 
694 		/*
695 		 * Make all other lwps hold in place, as if doing fork1().
696 		 * holdlwps(SHOLDFORK1) fails only if another lwp wants to
697 		 * perform a forkall() or the process is exiting.  In either
698 		 * case, all other lwps are either returning from their
699 		 * system calls (because of SHOLDFORK) or calling lwp_exit()
700 		 * (because of SEXITLWPS) so we don't need to scan them.
701 		 */
702 		if (holdlwps(SHOLDFORK1)) {
703 			kthread_t *t;
704 
705 			mutex_enter(&p->p_lock);
706 			for (t = curthread->t_forw; t != curthread;
707 			    t = t->t_forw) {
708 				if (is_active_fd(t, fd)) {
709 					t->t_activefd.a_stale = 1;
710 					t->t_post_sys = 1;
711 				}
712 			}
713 			continuelwps(p);
714 			mutex_exit(&p->p_lock);
715 		}
716 		UF_ENTER(ufp, fip, fd);
717 		ASSERT(ufp->uf_file == NULL);
718 	}
719 
720 	/*
721 	 * Wait for other lwps to stop using this file descriptor.
722 	 */
723 	while (ufp->uf_refcnt > 0) {
724 		cv_wait_stop(&ufp->uf_closing_cv, &ufp->uf_lock, 250);
725 		/*
726 		 * cv_wait_stop() drops ufp->uf_lock, so the file list
727 		 * can change.  Drop the lock on our (possibly) stale
728 		 * ufp and let UF_ENTER() find and lock the current ufp.
729 		 */
730 		UF_EXIT(ufp);
731 		UF_ENTER(ufp, fip, fd);
732 	}
733 
734 #ifdef DEBUG
735 	/*
736 	 * catch a watchfd on device's pollhead list but not on fpollinfo list
737 	 */
738 	if (ufp->uf_fpollinfo != NULL)
739 		checkwfdlist(fp->f_vnode, ufp->uf_fpollinfo);
740 #endif	/* DEBUG */
741 
742 	/*
743 	 * We may need to cleanup some cached poll states in t_pollstate
744 	 * before the fd can be reused. It is important that we don't
745 	 * access a stale thread structure. We will do the cleanup in two
746 	 * phases to avoid deadlock and holding uf_lock for too long.
747 	 * In phase 1, hold the uf_lock and call pollblockexit() to set
748 	 * state in t_pollstate struct so that a thread does not exit on
749 	 * us. In phase 2, we drop the uf_lock and call pollcacheclean().
750 	 */
751 	pfd = ufp->uf_portfd;
752 	ufp->uf_portfd = NULL;
753 	fpip = ufp->uf_fpollinfo;
754 	ufp->uf_fpollinfo = NULL;
755 	if (fpip != NULL)
756 		pollblockexit(fpip);
757 	UF_EXIT(ufp);
758 	if (fpip != NULL)
759 		pollcacheclean(fpip, fd);
760 	if (pfd)
761 		port_close_fd(pfd);
762 
763 	/*
764 	 * Keep the file descriptor entry reserved across the closef().
765 	 */
766 	error = closef(fp);
767 
768 	setf(fd, newfp);
769 
770 	/* Only return closef() error when closing is all we do */
771 	return (newfp == NULL ? error : 0);
772 }
773 
774 /*
775  * Decrement uf_refcnt; wakeup anyone waiting to close the file.
776  */
777 void
778 releasef(int fd)
779 {
780 	uf_info_t *fip = P_FINFO(curproc);
781 	uf_entry_t *ufp;
782 
783 	clear_active_fd(fd);	/* clear the active file descriptor */
784 
785 	UF_ENTER(ufp, fip, fd);
786 	ASSERT(ufp->uf_refcnt > 0);
787 	if (--ufp->uf_refcnt == 0)
788 		cv_broadcast(&ufp->uf_closing_cv);
789 	UF_EXIT(ufp);
790 }
791 
792 /*
793  * Identical to releasef() but can be called from another process.
794  */
795 void
796 areleasef(int fd, uf_info_t *fip)
797 {
798 	uf_entry_t *ufp;
799 
800 	UF_ENTER(ufp, fip, fd);
801 	ASSERT(ufp->uf_refcnt > 0);
802 	if (--ufp->uf_refcnt == 0)
803 		cv_broadcast(&ufp->uf_closing_cv);
804 	UF_EXIT(ufp);
805 }
806 
807 /*
808  * Duplicate all file descriptors across a fork.
809  */
810 void
811 flist_fork(uf_info_t *pfip, uf_info_t *cfip)
812 {
813 	int fd, nfiles;
814 	uf_entry_t *pufp, *cufp;
815 
816 	mutex_init(&cfip->fi_lock, NULL, MUTEX_DEFAULT, NULL);
817 	cfip->fi_rlist = NULL;
818 
819 	/*
820 	 * We don't need to hold fi_lock because all other lwp's in the
821 	 * parent have been held.
822 	 */
823 	cfip->fi_nfiles = nfiles = flist_minsize(pfip);
824 
825 	cfip->fi_list = kmem_zalloc(nfiles * sizeof (uf_entry_t), KM_SLEEP);
826 
827 	for (fd = 0, pufp = pfip->fi_list, cufp = cfip->fi_list; fd < nfiles;
828 	    fd++, pufp++, cufp++) {
829 		cufp->uf_file = pufp->uf_file;
830 		cufp->uf_alloc = pufp->uf_alloc;
831 		cufp->uf_flag = pufp->uf_flag;
832 		cufp->uf_busy = pufp->uf_busy;
833 		if (pufp->uf_file == NULL) {
834 			ASSERT(pufp->uf_flag == 0);
835 			if (pufp->uf_busy) {
836 				/*
837 				 * Grab locks to appease ASSERTs in fd_reserve
838 				 */
839 				mutex_enter(&cfip->fi_lock);
840 				mutex_enter(&cufp->uf_lock);
841 				fd_reserve(cfip, fd, -1);
842 				mutex_exit(&cufp->uf_lock);
843 				mutex_exit(&cfip->fi_lock);
844 			}
845 		}
846 	}
847 }
848 
849 /*
850  * Close all open file descriptors for the current process.
851  * This is only called from exit(), which is single-threaded,
852  * so we don't need any locking.
853  */
854 void
855 closeall(uf_info_t *fip)
856 {
857 	int fd;
858 	file_t *fp;
859 	uf_entry_t *ufp;
860 
861 	ufp = fip->fi_list;
862 	for (fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
863 		if ((fp = ufp->uf_file) != NULL) {
864 			ufp->uf_file = NULL;
865 			if (ufp->uf_portfd != NULL) {
866 				portfd_t *pfd;
867 				/* remove event port association */
868 				pfd = ufp->uf_portfd;
869 				ufp->uf_portfd = NULL;
870 				port_close_fd(pfd);
871 			}
872 			ASSERT(ufp->uf_fpollinfo == NULL);
873 			(void) closef(fp);
874 		}
875 	}
876 
877 	kmem_free(fip->fi_list, fip->fi_nfiles * sizeof (uf_entry_t));
878 	fip->fi_list = NULL;
879 	fip->fi_nfiles = 0;
880 	while (fip->fi_rlist != NULL) {
881 		uf_rlist_t *urp = fip->fi_rlist;
882 		fip->fi_rlist = urp->ur_next;
883 		kmem_free(urp->ur_list, urp->ur_nfiles * sizeof (uf_entry_t));
884 		kmem_free(urp, sizeof (uf_rlist_t));
885 	}
886 }
887 
888 /*
889  * Internal form of close.  Decrement reference count on file
890  * structure.  Decrement reference count on the vnode following
891  * removal of the referencing file structure.
892  */
893 int
894 closef(file_t *fp)
895 {
896 	vnode_t *vp;
897 	int error;
898 	int count;
899 	int flag;
900 	offset_t offset;
901 
902 #ifdef C2_AUDIT
903 	/*
904 	 * audit close of file (may be exit)
905 	 */
906 	if (audit_active)
907 		audit_closef(fp);
908 #endif
909 	ASSERT(MUTEX_NOT_HELD(&P_FINFO(curproc)->fi_lock));
910 
911 	mutex_enter(&fp->f_tlock);
912 
913 	ASSERT(fp->f_count > 0);
914 
915 	count = fp->f_count--;
916 	flag = fp->f_flag;
917 	offset = fp->f_offset;
918 
919 	vp = fp->f_vnode;
920 
921 	error = VOP_CLOSE(vp, flag, count, offset, fp->f_cred, NULL);
922 
923 	if (count > 1) {
924 		mutex_exit(&fp->f_tlock);
925 		return (error);
926 	}
927 	ASSERT(fp->f_count == 0);
928 	mutex_exit(&fp->f_tlock);
929 
930 	VN_RELE(vp);
931 #ifdef C2_AUDIT
932 	/*
933 	 * deallocate resources to audit_data
934 	 */
935 	if (audit_active)
936 		audit_unfalloc(fp);
937 #endif
938 	crfree(fp->f_cred);
939 	kmem_cache_free(file_cache, fp);
940 	return (error);
941 }
942 
943 /*
944  * This is a combination of ufalloc() and setf().
945  */
946 int
947 ufalloc_file(int start, file_t *fp)
948 {
949 	proc_t *p = curproc;
950 	uf_info_t *fip = P_FINFO(p);
951 	int filelimit;
952 	uf_entry_t *ufp;
953 	int nfiles;
954 	int fd;
955 
956 	/*
957 	 * Assertion is to convince the correctness of the following
958 	 * assignment for filelimit after casting to int.
959 	 */
960 	ASSERT(p->p_fno_ctl <= INT_MAX);
961 	filelimit = (int)p->p_fno_ctl;
962 
963 	for (;;) {
964 		mutex_enter(&fip->fi_lock);
965 		fd = fd_find(fip, start);
966 		if (fd >= 0 && fd == fip->fi_badfd) {
967 			start = fd + 1;
968 			mutex_exit(&fip->fi_lock);
969 			continue;
970 		}
971 		if ((uint_t)fd < filelimit)
972 			break;
973 		if (fd >= filelimit) {
974 			mutex_exit(&fip->fi_lock);
975 			mutex_enter(&p->p_lock);
976 			(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
977 			    p->p_rctls, p, RCA_SAFE);
978 			mutex_exit(&p->p_lock);
979 			return (-1);
980 		}
981 		/* fd_find() returned -1 */
982 		nfiles = fip->fi_nfiles;
983 		mutex_exit(&fip->fi_lock);
984 		flist_grow(MAX(start, nfiles));
985 	}
986 
987 	UF_ENTER(ufp, fip, fd);
988 	fd_reserve(fip, fd, 1);
989 	ASSERT(ufp->uf_file == NULL);
990 	ufp->uf_file = fp;
991 	UF_EXIT(ufp);
992 	mutex_exit(&fip->fi_lock);
993 	return (fd);
994 }
995 
996 /*
997  * Allocate a user file descriptor greater than or equal to "start".
998  */
999 int
1000 ufalloc(int start)
1001 {
1002 	return (ufalloc_file(start, NULL));
1003 }
1004 
1005 /*
1006  * Check that a future allocation of count fds on proc p has a good
1007  * chance of succeeding.  If not, do rctl processing as if we'd failed
1008  * the allocation.
1009  *
1010  * Our caller must guarantee that p cannot disappear underneath us.
1011  */
1012 int
1013 ufcanalloc(proc_t *p, uint_t count)
1014 {
1015 	uf_info_t *fip = P_FINFO(p);
1016 	int filelimit;
1017 	int current;
1018 
1019 	if (count == 0)
1020 		return (1);
1021 
1022 	ASSERT(p->p_fno_ctl <= INT_MAX);
1023 	filelimit = (int)p->p_fno_ctl;
1024 
1025 	mutex_enter(&fip->fi_lock);
1026 	current = flist_nalloc(fip);		/* # of in-use descriptors */
1027 	mutex_exit(&fip->fi_lock);
1028 
1029 	/*
1030 	 * If count is a positive integer, the worst that can happen is
1031 	 * an overflow to a negative value, which is caught by the >= 0 check.
1032 	 */
1033 	current += count;
1034 	if (count <= INT_MAX && current >= 0 && current <= filelimit)
1035 		return (1);
1036 
1037 	mutex_enter(&p->p_lock);
1038 	(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
1039 	    p->p_rctls, p, RCA_SAFE);
1040 	mutex_exit(&p->p_lock);
1041 	return (0);
1042 }
1043 
1044 /*
1045  * Allocate a user file descriptor and a file structure.
1046  * Initialize the descriptor to point at the file structure.
1047  * If fdp is NULL, the user file descriptor will not be allocated.
1048  */
1049 int
1050 falloc(vnode_t *vp, int flag, file_t **fpp, int *fdp)
1051 {
1052 	file_t *fp;
1053 	int fd;
1054 
1055 	if (fdp) {
1056 		if ((fd = ufalloc(0)) == -1)
1057 			return (EMFILE);
1058 	}
1059 	fp = kmem_cache_alloc(file_cache, KM_SLEEP);
1060 	/*
1061 	 * Note: falloc returns the fp locked
1062 	 */
1063 	mutex_enter(&fp->f_tlock);
1064 	fp->f_count = 1;
1065 	fp->f_flag = (ushort_t)flag;
1066 	fp->f_vnode = vp;
1067 	fp->f_offset = 0;
1068 	fp->f_audit_data = 0;
1069 	crhold(fp->f_cred = CRED());
1070 #ifdef C2_AUDIT
1071 	/*
1072 	 * allocate resources to audit_data
1073 	 */
1074 	if (audit_active)
1075 		audit_falloc(fp);
1076 #endif
1077 	*fpp = fp;
1078 	if (fdp)
1079 		*fdp = fd;
1080 	return (0);
1081 }
1082 
1083 /*ARGSUSED*/
1084 static int
1085 file_cache_constructor(void *buf, void *cdrarg, int kmflags)
1086 {
1087 	file_t *fp = buf;
1088 
1089 	mutex_init(&fp->f_tlock, NULL, MUTEX_DEFAULT, NULL);
1090 	return (0);
1091 }
1092 
1093 /*ARGSUSED*/
1094 static void
1095 file_cache_destructor(void *buf, void *cdrarg)
1096 {
1097 	file_t *fp = buf;
1098 
1099 	mutex_destroy(&fp->f_tlock);
1100 }
1101 
1102 void
1103 finit()
1104 {
1105 	file_cache = kmem_cache_create("file_cache", sizeof (file_t), 0,
1106 	    file_cache_constructor, file_cache_destructor, NULL, NULL, NULL, 0);
1107 }
1108 
1109 void
1110 unfalloc(file_t *fp)
1111 {
1112 	ASSERT(MUTEX_HELD(&fp->f_tlock));
1113 	if (--fp->f_count <= 0) {
1114 #ifdef C2_AUDIT
1115 		/*
1116 		 * deallocate resources to audit_data
1117 		 */
1118 		if (audit_active)
1119 			audit_unfalloc(fp);
1120 #endif
1121 		crfree(fp->f_cred);
1122 		mutex_exit(&fp->f_tlock);
1123 		kmem_cache_free(file_cache, fp);
1124 	} else
1125 		mutex_exit(&fp->f_tlock);
1126 }
1127 
1128 /*
1129  * Given a file descriptor, set the user's
1130  * file pointer to the given parameter.
1131  */
1132 void
1133 setf(int fd, file_t *fp)
1134 {
1135 	uf_info_t *fip = P_FINFO(curproc);
1136 	uf_entry_t *ufp;
1137 
1138 #ifdef C2_AUDIT
1139 	if (audit_active)
1140 		audit_setf(fp, fd);
1141 #endif /* C2_AUDIT */
1142 
1143 	if (fp == NULL) {
1144 		mutex_enter(&fip->fi_lock);
1145 		UF_ENTER(ufp, fip, fd);
1146 		fd_reserve(fip, fd, -1);
1147 		mutex_exit(&fip->fi_lock);
1148 	} else {
1149 		UF_ENTER(ufp, fip, fd);
1150 		ASSERT(ufp->uf_busy);
1151 	}
1152 	ASSERT(ufp->uf_fpollinfo == NULL);
1153 	ASSERT(ufp->uf_flag == 0);
1154 	ufp->uf_file = fp;
1155 	cv_broadcast(&ufp->uf_wanted_cv);
1156 	UF_EXIT(ufp);
1157 }
1158 
1159 /*
1160  * Given a file descriptor, return the file table flags, plus,
1161  * if this is a socket in asynchronous mode, the FASYNC flag.
1162  * getf() may or may not have been called before calling f_getfl().
1163  */
1164 int
1165 f_getfl(int fd, int *flagp)
1166 {
1167 	uf_info_t *fip = P_FINFO(curproc);
1168 	uf_entry_t *ufp;
1169 	file_t *fp;
1170 	int error;
1171 
1172 	if ((uint_t)fd >= fip->fi_nfiles)
1173 		error = EBADF;
1174 	else {
1175 		UF_ENTER(ufp, fip, fd);
1176 		if ((fp = ufp->uf_file) == NULL)
1177 			error = EBADF;
1178 		else {
1179 			vnode_t *vp = fp->f_vnode;
1180 			int flag = fp->f_flag;
1181 
1182 			/*
1183 			 * BSD fcntl() FASYNC compatibility.
1184 			 *
1185 			 * SCTP doesn't have an associated stream and thus
1186 			 * doesn't store flags on it.
1187 			 */
1188 			if ((vp->v_type == VSOCK) && (vp->v_stream != NULL))
1189 				flag |= sock_getfasync(vp);
1190 			*flagp = flag;
1191 			error = 0;
1192 		}
1193 		UF_EXIT(ufp);
1194 	}
1195 
1196 	return (error);
1197 }
1198 
1199 /*
1200  * Given a file descriptor, return the user's file flags.
1201  * Force the FD_CLOEXEC flag for writable self-open /proc files.
1202  * getf() may or may not have been called before calling f_getfd_error().
1203  */
1204 int
1205 f_getfd_error(int fd, int *flagp)
1206 {
1207 	uf_info_t *fip = P_FINFO(curproc);
1208 	uf_entry_t *ufp;
1209 	file_t *fp;
1210 	int flag;
1211 	int error;
1212 
1213 	if ((uint_t)fd >= fip->fi_nfiles)
1214 		error = EBADF;
1215 	else {
1216 		UF_ENTER(ufp, fip, fd);
1217 		if ((fp = ufp->uf_file) == NULL)
1218 			error = EBADF;
1219 		else {
1220 			flag = ufp->uf_flag;
1221 			if ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode))
1222 				flag |= FD_CLOEXEC;
1223 			*flagp = flag;
1224 			error = 0;
1225 		}
1226 		UF_EXIT(ufp);
1227 	}
1228 
1229 	return (error);
1230 }
1231 
1232 /*
1233  * getf() must have been called before calling f_getfd().
1234  */
1235 char
1236 f_getfd(int fd)
1237 {
1238 	int flag = 0;
1239 	(void) f_getfd_error(fd, &flag);
1240 	return ((char)flag);
1241 }
1242 
1243 /*
1244  * Given a file descriptor and file flags, set the user's file flags.
1245  * At present, the only valid flag is FD_CLOEXEC.
1246  * getf() may or may not have been called before calling f_setfd_error().
1247  */
1248 int
1249 f_setfd_error(int fd, int flags)
1250 {
1251 	uf_info_t *fip = P_FINFO(curproc);
1252 	uf_entry_t *ufp;
1253 	int error;
1254 
1255 	if ((uint_t)fd >= fip->fi_nfiles)
1256 		error = EBADF;
1257 	else {
1258 		UF_ENTER(ufp, fip, fd);
1259 		if (ufp->uf_file == NULL)
1260 			error = EBADF;
1261 		else {
1262 			ufp->uf_flag = flags & FD_CLOEXEC;
1263 			error = 0;
1264 		}
1265 		UF_EXIT(ufp);
1266 	}
1267 	return (error);
1268 }
1269 
1270 void
1271 f_setfd(int fd, char flags)
1272 {
1273 	(void) f_setfd_error(fd, flags);
1274 }
1275 
1276 #define	BADFD_MIN	3
1277 #define	BADFD_MAX	255
1278 
1279 /*
1280  * Attempt to allocate a file descriptor which is bad and which
1281  * is "poison" to the application.  It cannot be closed (except
1282  * on exec), allocated for a different use, etc.
1283  */
1284 int
1285 f_badfd(int start, int *fdp, int action)
1286 {
1287 	int fdr;
1288 	int badfd;
1289 	uf_info_t *fip = P_FINFO(curproc);
1290 
1291 #ifdef _LP64
1292 	/* No restrictions on 64 bit _file */
1293 	if (get_udatamodel() != DATAMODEL_ILP32)
1294 		return (EINVAL);
1295 #endif
1296 
1297 	if (start > BADFD_MAX || start < BADFD_MIN)
1298 		return (EINVAL);
1299 
1300 	if (action >= NSIG || action < 0)
1301 		return (EINVAL);
1302 
1303 	mutex_enter(&fip->fi_lock);
1304 	badfd = fip->fi_badfd;
1305 	mutex_exit(&fip->fi_lock);
1306 
1307 	if (badfd != -1)
1308 		return (EAGAIN);
1309 
1310 	fdr = ufalloc(start);
1311 
1312 	if (fdr > BADFD_MAX) {
1313 		setf(fdr, NULL);
1314 		return (EMFILE);
1315 	}
1316 	if (fdr < 0)
1317 		return (EMFILE);
1318 
1319 	mutex_enter(&fip->fi_lock);
1320 	if (fip->fi_badfd != -1) {
1321 		/* Lost race */
1322 		mutex_exit(&fip->fi_lock);
1323 		setf(fdr, NULL);
1324 		return (EAGAIN);
1325 	}
1326 	fip->fi_action = action;
1327 	fip->fi_badfd = fdr;
1328 	mutex_exit(&fip->fi_lock);
1329 	setf(fdr, NULL);
1330 
1331 	*fdp = fdr;
1332 
1333 	return (0);
1334 }
1335 
1336 /*
1337  * Allocate a file descriptor and assign it to the vnode "*vpp",
1338  * performing the usual open protocol upon it and returning the
1339  * file descriptor allocated.  It is the responsibility of the
1340  * caller to dispose of "*vpp" if any error occurs.
1341  */
1342 int
1343 fassign(vnode_t **vpp, int mode, int *fdp)
1344 {
1345 	file_t *fp;
1346 	int error;
1347 	int fd;
1348 
1349 	if (error = falloc((vnode_t *)NULL, mode, &fp, &fd))
1350 		return (error);
1351 	if (error = VOP_OPEN(vpp, mode, fp->f_cred, NULL)) {
1352 		setf(fd, NULL);
1353 		unfalloc(fp);
1354 		return (error);
1355 	}
1356 	fp->f_vnode = *vpp;
1357 	mutex_exit(&fp->f_tlock);
1358 	/*
1359 	 * Fill in the slot falloc reserved.
1360 	 */
1361 	setf(fd, fp);
1362 	*fdp = fd;
1363 	return (0);
1364 }
1365 
1366 /*
1367  * When a process forks it must increment the f_count of all file pointers
1368  * since there is a new process pointing at them.  fcnt_add(fip, 1) does this.
1369  * Since we are called when there is only 1 active lwp we don't need to
1370  * hold fi_lock or any uf_lock.  If the fork fails, fork_fail() calls
1371  * fcnt_add(fip, -1) to restore the counts.
1372  */
1373 void
1374 fcnt_add(uf_info_t *fip, int incr)
1375 {
1376 	int i;
1377 	uf_entry_t *ufp;
1378 	file_t *fp;
1379 
1380 	ufp = fip->fi_list;
1381 	for (i = 0; i < fip->fi_nfiles; i++, ufp++) {
1382 		if ((fp = ufp->uf_file) != NULL) {
1383 			mutex_enter(&fp->f_tlock);
1384 			ASSERT((incr == 1 && fp->f_count >= 1) ||
1385 			    (incr == -1 && fp->f_count >= 2));
1386 			fp->f_count += incr;
1387 			mutex_exit(&fp->f_tlock);
1388 		}
1389 	}
1390 }
1391 
1392 /*
1393  * This is called from exec to close all fd's that have the FD_CLOEXEC flag
1394  * set and also to close all self-open for write /proc file descriptors.
1395  */
1396 void
1397 close_exec(uf_info_t *fip)
1398 {
1399 	int fd;
1400 	file_t *fp;
1401 	fpollinfo_t *fpip;
1402 	uf_entry_t *ufp;
1403 	portfd_t *pfd;
1404 
1405 	ufp = fip->fi_list;
1406 	for (fd = 0; fd < fip->fi_nfiles; fd++, ufp++) {
1407 		if ((fp = ufp->uf_file) != NULL &&
1408 		    ((ufp->uf_flag & FD_CLOEXEC) ||
1409 		    ((fp->f_flag & FWRITE) && pr_isself(fp->f_vnode)))) {
1410 			fpip = ufp->uf_fpollinfo;
1411 			mutex_enter(&fip->fi_lock);
1412 			mutex_enter(&ufp->uf_lock);
1413 			fd_reserve(fip, fd, -1);
1414 			mutex_exit(&fip->fi_lock);
1415 			ufp->uf_file = NULL;
1416 			ufp->uf_fpollinfo = NULL;
1417 			ufp->uf_flag = 0;
1418 			/*
1419 			 * We may need to cleanup some cached poll states
1420 			 * in t_pollstate before the fd can be reused. It
1421 			 * is important that we don't access a stale thread
1422 			 * structure. We will do the cleanup in two
1423 			 * phases to avoid deadlock and holding uf_lock for
1424 			 * too long. In phase 1, hold the uf_lock and call
1425 			 * pollblockexit() to set state in t_pollstate struct
1426 			 * so that a thread does not exit on us. In phase 2,
1427 			 * we drop the uf_lock and call pollcacheclean().
1428 			 */
1429 			pfd = ufp->uf_portfd;
1430 			ufp->uf_portfd = NULL;
1431 			if (fpip != NULL)
1432 				pollblockexit(fpip);
1433 			mutex_exit(&ufp->uf_lock);
1434 			if (fpip != NULL)
1435 				pollcacheclean(fpip, fd);
1436 			if (pfd)
1437 				port_close_fd(pfd);
1438 			(void) closef(fp);
1439 		}
1440 	}
1441 
1442 	/* Reset bad fd */
1443 	fip->fi_badfd = -1;
1444 	fip->fi_action = -1;
1445 }
1446 
1447 /*
1448  * Common routine for modifying attributes of named files.
1449  */
1450 int
1451 namesetattr(char *fnamep, enum symfollow followlink, vattr_t *vap, int flags)
1452 {
1453 	vnode_t *vp;
1454 	int error = 0;
1455 
1456 	if (error = lookupname(fnamep, UIO_USERSPACE, followlink, NULLVPP, &vp))
1457 		return (set_errno(error));
1458 	if (error = vpsetattr(vp, vap, flags))
1459 		(void) set_errno(error);
1460 	VN_RELE(vp);
1461 	return (error);
1462 }
1463 
1464 /*
1465  * Common routine for modifying attributes of files referenced
1466  * by descriptor.
1467  */
1468 int
1469 fdsetattr(int fd, vattr_t *vap)
1470 {
1471 	file_t *fp;
1472 	vnode_t *vp;
1473 	int error = 0;
1474 
1475 	if ((fp = getf(fd)) != NULL) {
1476 		vp = fp->f_vnode;
1477 		if (error = vpsetattr(vp, vap, 0)) {
1478 			(void) set_errno(error);
1479 		}
1480 		releasef(fd);
1481 	} else
1482 		error = set_errno(EBADF);
1483 	return (error);
1484 }
1485 
1486 /*
1487  * Common routine to set the attributes for the given vnode.
1488  * If the vnode is a file and the filesize is being manipulated,
1489  * this makes sure that there are no conflicting non-blocking
1490  * mandatory locks in that region.
1491  */
1492 static int
1493 vpsetattr(vnode_t *vp, vattr_t *vap, int flags)
1494 {
1495 	int error = 0;
1496 	int in_crit = 0;
1497 	u_offset_t	begin;
1498 	vattr_t	vattr;
1499 	ssize_t	length;
1500 
1501 	if (vn_is_readonly(vp)) {
1502 		error = EROFS;
1503 	}
1504 	if (!error && (vap->va_mask & AT_SIZE) &&
1505 	    nbl_need_check(vp)) {
1506 		nbl_start_crit(vp, RW_READER);
1507 		in_crit = 1;
1508 		vattr.va_mask = AT_SIZE;
1509 		if (!(error = VOP_GETATTR(vp, &vattr, 0, CRED(), NULL))) {
1510 			begin = vap->va_size > vattr.va_size ?
1511 					vattr.va_size : vap->va_size;
1512 			length = vattr.va_size > vap->va_size ?
1513 					vattr.va_size - vap->va_size :
1514 					vap->va_size - vattr.va_size;
1515 
1516 			if (nbl_conflict(vp, NBL_WRITE, begin, length, 0,
1517 			    NULL)) {
1518 				error = EACCES;
1519 			}
1520 		}
1521 	}
1522 	if (!error)
1523 		error = VOP_SETATTR(vp, vap, flags, CRED(), NULL);
1524 
1525 	if (in_crit)
1526 		nbl_end_crit(vp);
1527 
1528 	return (error);
1529 }
1530 
1531 /*
1532  * Return true if the given vnode is referenced by any
1533  * entry in the current process's file descriptor table.
1534  */
1535 int
1536 fisopen(vnode_t *vp)
1537 {
1538 	int fd;
1539 	file_t *fp;
1540 	vnode_t *ovp;
1541 	uf_info_t *fip = P_FINFO(curproc);
1542 	uf_entry_t *ufp;
1543 
1544 	mutex_enter(&fip->fi_lock);
1545 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1546 		UF_ENTER(ufp, fip, fd);
1547 		if ((fp = ufp->uf_file) != NULL &&
1548 		    (ovp = fp->f_vnode) != NULL && VN_CMP(vp, ovp)) {
1549 			UF_EXIT(ufp);
1550 			mutex_exit(&fip->fi_lock);
1551 			return (1);
1552 		}
1553 		UF_EXIT(ufp);
1554 	}
1555 	mutex_exit(&fip->fi_lock);
1556 	return (0);
1557 }
1558 
1559 /*
1560  * Return zero if at least one file currently open (by curproc) shouldn't be
1561  * allowed to change zones.
1562  */
1563 int
1564 files_can_change_zones(void)
1565 {
1566 	int fd;
1567 	file_t *fp;
1568 	uf_info_t *fip = P_FINFO(curproc);
1569 	uf_entry_t *ufp;
1570 
1571 	mutex_enter(&fip->fi_lock);
1572 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1573 		UF_ENTER(ufp, fip, fd);
1574 		if ((fp = ufp->uf_file) != NULL &&
1575 		    !vn_can_change_zones(fp->f_vnode)) {
1576 			UF_EXIT(ufp);
1577 			mutex_exit(&fip->fi_lock);
1578 			return (0);
1579 		}
1580 		UF_EXIT(ufp);
1581 	}
1582 	mutex_exit(&fip->fi_lock);
1583 	return (1);
1584 }
1585 
1586 #ifdef DEBUG
1587 
1588 /*
1589  * The following functions are only used in ASSERT()s elsewhere.
1590  * They do not modify the state of the system.
1591  */
1592 
1593 /*
1594  * Return true (1) if the current thread is in the fpollinfo
1595  * list for this file descriptor, else false (0).
1596  */
1597 static int
1598 curthread_in_plist(uf_entry_t *ufp)
1599 {
1600 	fpollinfo_t *fpip;
1601 
1602 	ASSERT(MUTEX_HELD(&ufp->uf_lock));
1603 	for (fpip = ufp->uf_fpollinfo; fpip; fpip = fpip->fp_next)
1604 		if (fpip->fp_thread == curthread)
1605 			return (1);
1606 	return (0);
1607 }
1608 
1609 /*
1610  * Sanity check to make sure that after lwp_exit(),
1611  * curthread does not appear on any fd's fpollinfo list.
1612  */
1613 void
1614 checkfpollinfo(void)
1615 {
1616 	int fd;
1617 	uf_info_t *fip = P_FINFO(curproc);
1618 	uf_entry_t *ufp;
1619 
1620 	mutex_enter(&fip->fi_lock);
1621 	for (fd = 0; fd < fip->fi_nfiles; fd++) {
1622 		UF_ENTER(ufp, fip, fd);
1623 		ASSERT(!curthread_in_plist(ufp));
1624 		UF_EXIT(ufp);
1625 	}
1626 	mutex_exit(&fip->fi_lock);
1627 }
1628 
1629 /*
1630  * Return true (1) if the current thread is in the fpollinfo
1631  * list for this file descriptor, else false (0).
1632  * This is the same as curthread_in_plist(),
1633  * but is called w/o holding uf_lock.
1634  */
1635 int
1636 infpollinfo(int fd)
1637 {
1638 	uf_info_t *fip = P_FINFO(curproc);
1639 	uf_entry_t *ufp;
1640 	int rc;
1641 
1642 	UF_ENTER(ufp, fip, fd);
1643 	rc = curthread_in_plist(ufp);
1644 	UF_EXIT(ufp);
1645 	return (rc);
1646 }
1647 
1648 #endif	/* DEBUG */
1649 
1650 /*
1651  * Add the curthread to fpollinfo list, meaning this fd is currently in the
1652  * thread's poll cache. Each lwp polling this file descriptor should call
1653  * this routine once.
1654  */
1655 void
1656 addfpollinfo(int fd)
1657 {
1658 	struct uf_entry *ufp;
1659 	fpollinfo_t *fpip;
1660 	uf_info_t *fip = P_FINFO(curproc);
1661 
1662 	fpip = kmem_zalloc(sizeof (fpollinfo_t), KM_SLEEP);
1663 	fpip->fp_thread = curthread;
1664 	UF_ENTER(ufp, fip, fd);
1665 	/*
1666 	 * Assert we are not already on the list, that is, that
1667 	 * this lwp did not call addfpollinfo twice for the same fd.
1668 	 */
1669 	ASSERT(!curthread_in_plist(ufp));
1670 	/*
1671 	 * addfpollinfo is always done inside the getf/releasef pair.
1672 	 */
1673 	ASSERT(ufp->uf_refcnt >= 1);
1674 	fpip->fp_next = ufp->uf_fpollinfo;
1675 	ufp->uf_fpollinfo = fpip;
1676 	UF_EXIT(ufp);
1677 }
1678 
1679 /*
1680  * delete curthread from fpollinfo list.
1681  */
1682 /*ARGSUSED*/
1683 void
1684 delfpollinfo(int fd)
1685 {
1686 	struct uf_entry *ufp;
1687 	struct fpollinfo *fpip;
1688 	struct fpollinfo **fpipp;
1689 	uf_info_t *fip = P_FINFO(curproc);
1690 
1691 	UF_ENTER(ufp, fip, fd);
1692 	if (ufp->uf_fpollinfo == NULL) {
1693 		UF_EXIT(ufp);
1694 		return;
1695 	}
1696 	ASSERT(ufp->uf_busy);
1697 	/*
1698 	 * Find and delete curthread from the list.
1699 	 */
1700 	fpipp = &ufp->uf_fpollinfo;
1701 	while ((fpip = *fpipp)->fp_thread != curthread)
1702 		fpipp = &fpip->fp_next;
1703 	*fpipp = fpip->fp_next;
1704 	kmem_free(fpip, sizeof (fpollinfo_t));
1705 	/*
1706 	 * Assert that we are not still on the list, that is, that
1707 	 * this lwp did not call addfpollinfo twice for the same fd.
1708 	 */
1709 	ASSERT(!curthread_in_plist(ufp));
1710 	UF_EXIT(ufp);
1711 }
1712 
1713 /*
1714  * fd is associated with a port. pfd is a pointer to the fd entry in the
1715  * cache of the port.
1716  */
1717 
1718 void
1719 addfd_port(int fd, portfd_t *pfd)
1720 {
1721 	struct uf_entry *ufp;
1722 	uf_info_t *fip = P_FINFO(curproc);
1723 
1724 	UF_ENTER(ufp, fip, fd);
1725 	/*
1726 	 * addfd_port is always done inside the getf/releasef pair.
1727 	 */
1728 	ASSERT(ufp->uf_refcnt >= 1);
1729 	if (ufp->uf_portfd == NULL) {
1730 		/* first entry */
1731 		ufp->uf_portfd = pfd;
1732 		pfd->pfd_next = NULL;
1733 	} else {
1734 		pfd->pfd_next = ufp->uf_portfd;
1735 		ufp->uf_portfd = pfd;
1736 		pfd->pfd_next->pfd_prev = pfd;
1737 	}
1738 	UF_EXIT(ufp);
1739 }
1740 
1741 void
1742 delfd_port(int fd, portfd_t *pfd)
1743 {
1744 	struct uf_entry *ufp;
1745 	uf_info_t *fip = P_FINFO(curproc);
1746 
1747 	UF_ENTER(ufp, fip, fd);
1748 	/*
1749 	 * delfd_port is always done inside the getf/releasef pair.
1750 	 */
1751 	ASSERT(ufp->uf_refcnt >= 1);
1752 	if (ufp->uf_portfd == pfd) {
1753 		/* remove first entry */
1754 		ufp->uf_portfd = pfd->pfd_next;
1755 	} else {
1756 		pfd->pfd_prev->pfd_next = pfd->pfd_next;
1757 		if (pfd->pfd_next != NULL)
1758 			pfd->pfd_next->pfd_prev = pfd->pfd_prev;
1759 	}
1760 	UF_EXIT(ufp);
1761 }
1762 
1763 static void
1764 port_close_fd(portfd_t *pfd)
1765 {
1766 	portfd_t	*pfdn;
1767 
1768 	/*
1769 	 * At this point, no other thread should access
1770 	 * the portfd_t list for this fd. The uf_file, uf_portfd
1771 	 * pointers in the uf_entry_t struct for this fd would
1772 	 * be set to NULL.
1773 	 */
1774 	for (; pfd != NULL; pfd = pfdn) {
1775 		pfdn = pfd->pfd_next;
1776 		port_close_pfd(pfd);
1777 	}
1778 }
1779