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