xref: /illumos-gate/usr/src/uts/common/fs/smbsrv/smb_ofile.c (revision 78801af7286cd73dbc996d470f789e75993cf15d)
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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2016 Syneto S.R.L. All rights reserved.
24  * Copyright (c) 2016 by Delphix. All rights reserved.
25  * Copyright 2019 Nexenta Systems, Inc.  All rights reserved.
26  */
27 
28 /*
29  * General Structures Layout
30  * -------------------------
31  *
32  * This is a simplified diagram showing the relationship between most of the
33  * main structures.
34  *
35  * +-------------------+
36  * |     SMB_INFO      |
37  * +-------------------+
38  *          |
39  *          |
40  *          v
41  * +-------------------+       +-------------------+      +-------------------+
42  * |     SESSION       |<----->|     SESSION       |......|      SESSION      |
43  * +-------------------+       +-------------------+      +-------------------+
44  *   |          |
45  *   |          |
46  *   |          v
47  *   |  +-------------------+     +-------------------+   +-------------------+
48  *   |  |       USER        |<--->|       USER        |...|       USER        |
49  *   |  +-------------------+     +-------------------+   +-------------------+
50  *   |
51  *   |
52  *   v
53  * +-------------------+       +-------------------+      +-------------------+
54  * |       TREE        |<----->|       TREE        |......|       TREE        |
55  * +-------------------+       +-------------------+      +-------------------+
56  *      |         |
57  *      |         |
58  *      |         v
59  *      |     +-------+       +-------+      +-------+
60  *      |     | OFILE |<----->| OFILE |......| OFILE |
61  *      |     +-------+       +-------+      +-------+
62  *      |
63  *      |
64  *      v
65  *  +-------+       +------+      +------+
66  *  | ODIR  |<----->| ODIR |......| ODIR |
67  *  +-------+       +------+      +------+
68  *
69  *
70  * Ofile State Machine
71  * ------------------
72  *
73  *    +-------------------------+	 T0
74  *    |  SMB_OFILE_STATE_OPEN   |<--+-------- Creation/Allocation
75  *    +-------------------------+   |
76  *	    |		|	    | T5
77  *	    |		|	+---------------------------+
78  *	    |		|	| SMB_OFILE_STATE_RECONNECT |
79  *	    |		|	+---------------------------+
80  *	    |		|	    ^
81  *	    |		v	    |
82  *	    |   +---------------+   |
83  *	    |   | STATE_SAVE_DH |   |
84  *	    |   | STATE_SAVING  |   |
85  *	    |   +---------------+   |
86  *	    |		|	    | T4
87  *	    | T1	| T3	+--------------------------+
88  *	    |		+------>| SMB_OFILE_STATE_ORPHANED |
89  *	    v			+--------------------------+
90  *    +-------------------------+   |		|
91  *    | SMB_OFILE_STATE_CLOSING |<--+ T6	| T7
92  *    +-------------------------+		|
93  *	    |		^			v
94  *	    | T2	| T8	+-------------------------+
95  *	    |		+-------| SMB_OFILE_STATE_EXPIRED |
96  *	    v			+-------------------------+
97  *    +-------------------------+
98  *    | SMB_OFILE_STATE_CLOSED  |----------> Deletion/Free
99  *    +-------------------------+    T9
100  *
101  * SMB_OFILE_STATE_OPEN
102  *
103  *    While in this state:
104  *      - The ofile is queued in the list of ofiles of its tree.
105  *      - References will be given out if the ofile is looked up.
106  *
107  * SMB_OFILE_STATE_SAVE_DH
108  *
109  *    Similar to state _CLOSING, but instead of deleting the ofile,
110  *    it leaves the ofile in state _ORPHANED (for later reclaim).
111  *    Will move to _SAVING after last ref, then _ORPHANED.
112  *
113  *    While in this state:
114  *	- The ofile has been marked for preservation during a
115  *	  walk of the tree ofile list to close multiple files.
116  *	- References will not be given out if the ofile is looked up,
117  *	  except for oplock break processing.
118  *	- Still affects Sharing Violation rules
119  *
120  * SMB_OFILE_STATE_SAVING
121  *
122  *    Transient state used to keep oplock break processing out
123  *    while the ofile moves to state _ORPHANED.
124  *
125  *    While in this state:
126  *	- References will not be given out if the ofile is looked up,
127  *	  except for oplock break processing.
128  *	- Still affects Sharing Violation rules
129  *
130  * SMB_OFILE_STATE_CLOSING
131  *
132  *    Close has been requested.  Stay in this state until the last
133  *    ref. is gone, then move to state _CLOSED
134  *
135  *    While in this state:
136  *      - The ofile is queued in the list of ofiles of its tree.
137  *      - References will not be given out if the ofile is looked up.
138  *      - The file is closed and the locks held are being released.
139  *      - The resources associated with the ofile remain.
140  *
141  * SMB_OFILE_STATE_CLOSED
142  *
143  *    While in this state:
144  *      - The ofile is queued in the list of ofiles of its tree.
145  *      - References will not be given out if the ofile is looked up.
146  *      - The resources associated with the ofile remain.
147  *
148  * SMB_OFILE_STATE_ORPHANED
149  *
150  *    While in this state:
151  *      - The ofile is queued in the list of ofiles of its tree.
152  *      - Can be reclaimed by the original owner
153  *      - References will not be given out if the ofile is looked up.
154  *      - All the tree, user, and session "up" pointers are NULL!
155  *      - Will eventually be "expired" if not reclaimed
156  *      - Can be closed if its oplock is broken
157  *      - Still affects Sharing Violation rules
158  *
159  * SMB_OFILE_STATE_EXPIRED
160  *
161  *    While in this state:
162  *      - The ofile is queued in the list of ofiles of its tree.
163  *      - References will not be given out if the ofile is looked up.
164  *      - The ofile has not been reclaimed and will soon be closed,
165  *        due to, for example, the durable handle timer expiring, or its
166  *        oplock being broken.
167  *      - Cannot be reclaimed at this point
168  *
169  * SMB_OFILE_STATE_RECONNECT
170  *
171  *    Transient state used to keep oplock break processing out
172  *    while the ofile moves from state _ORPHANED to _OPEN.
173  *
174  *    While in this state:
175  *      - The ofile is being reclaimed; do not touch it.
176  *      - References will not be given out if the ofile is looked up.
177  *      - Still affects Sharing Violation rules
178  *	- see smb2_dh_reconnect() for which members need to be avoided
179  *
180  * Transition T0
181  *
182  *    This transition occurs in smb_ofile_open(). A new ofile is created and
183  *    added to the list of ofiles of a tree.
184  *
185  * Transition T1
186  *
187  *    This transition occurs in smb_ofile_close(). Note that this only happens
188  *    when we determine that an ofile should be closed in spite of its durable
189  *    handle properties.
190  *
191  * Transition T2
192  *
193  *    This transition occurs in smb_ofile_release(). The resources associated
194  *    with the ofile are freed as well as the ofile structure. For the
195  *    transition to occur, the ofile must be in the SMB_OFILE_STATE_CLOSED
196  *    state and the reference count be zero.
197  *
198  * Transition T3
199  *
200  *    This transition occurs in smb_ofile_orphan_dh(). It happens during an
201  *    smb2 logoff, or during a session disconnect when certain conditions are
202  *    met. The ofile and structures above it will be kept around until the ofile
203  *    either gets reclaimed, expires after f_timeout_offset nanoseconds, or its
204  *    oplock is broken.
205  *
206  * Transition T4
207  *
208  *    This transition occurs in smb2_dh_reconnect(). An smb2 create request
209  *    with a DURABLE_HANDLE_RECONNECT(_V2) create context has been
210  *    recieved from the original owner. If leases are supported or it's
211  *    RECONNECT_V2, reconnect is subject to additional conditions. The ofile
212  *    will be unwired from the old, disconnected session, tree, and user,
213  *    and wired up to its new context.
214  *
215  * Transition T5
216  *
217  *    This transition occurs in smb2_dh_reconnect(). The ofile has been
218  *    successfully reclaimed.
219  *
220  * Transition T6
221  *
222  *    This transition occurs in smb_ofile_close(). The ofile has been orphaned
223  *    while some thread was blocked, and that thread closes the ofile. Can only
224  *    happen when the ofile is orphaned due to an SMB2 LOGOFF request.
225  *
226  * Transition T7
227  *
228  *    This transition occurs in smb_session_durable_timers() and
229  *    smb_oplock_send_brk(). The ofile will soon be closed.
230  *    In the former case, f_timeout_offset nanoseconds have passed since
231  *    the ofile was orphaned. In the latter, an oplock break occured
232  *    on the ofile while it was orphaned.
233  *
234  * Transition T8
235  *
236  *    This transition occurs in smb_ofile_close().
237  *
238  * Transition T9
239  *
240  *    This transition occurs in smb_ofile_delete().
241  *
242  * Comments
243  * --------
244  *
245  *    The state machine of the ofile structures is controlled by 3 elements:
246  *      - The list of ofiles of the tree it belongs to.
247  *      - The mutex embedded in the structure itself.
248  *      - The reference count.
249  *
250  *    There's a mutex embedded in the ofile structure used to protect its fields
251  *    and there's a lock embedded in the list of ofiles of a tree. To
252  *    increment or to decrement the reference count the mutex must be entered.
253  *    To insert the ofile into the list of ofiles of the tree and to remove
254  *    the ofile from it, the lock must be entered in RW_WRITER mode.
255  *
256  *    Rules of access to a ofile structure:
257  *
258  *    1) In order to avoid deadlocks, when both (mutex and lock of the ofile
259  *       list) have to be entered, the lock must be entered first. Additionally,
260  *       f_mutex must not be held when removing the ofile from sv_persistid_ht.
261  *
262  *    2) All actions applied to an ofile require a reference count.
263  *
264  *    3) There are 2 ways of getting a reference count. One is when the ofile
265  *       is opened. The other one when the ofile is looked up. This translates
266  *       into 2 functions: smb_ofile_open() and smb_ofile_lookup_by_fid().
267  *
268  *    It should be noted that the reference count of an ofile registers the
269  *    number of references to the ofile in other structures (such as an smb
270  *    request). The reference count is not incremented in these 2 instances:
271  *
272  *    1) The ofile is open. An ofile is anchored by its state. If there's
273  *       no activity involving an ofile currently open, the reference count
274  *       of that ofile is zero.
275  *
276  *    2) The ofile is queued in the list of ofiles of its tree. The fact of
277  *       being queued in that list is NOT registered by incrementing the
278  *       reference count.
279  */
280 #include <smbsrv/smb2_kproto.h>
281 #include <smbsrv/smb_fsops.h>
282 #include <sys/time.h>
283 #include <sys/random.h>
284 
285 static boolean_t smb_ofile_is_open_locked(smb_ofile_t *);
286 static void smb_ofile_delete(void *arg);
287 static void smb_ofile_save_dh(void *arg);
288 
289 static int smb_ofile_netinfo_encode(smb_ofile_t *, uint8_t *, size_t,
290     uint32_t *);
291 static int smb_ofile_netinfo_init(smb_ofile_t *, smb_netfileinfo_t *);
292 static void smb_ofile_netinfo_fini(smb_netfileinfo_t *);
293 
294 /*
295  * The uniq_fid is a CIFS-server-wide unique identifier for an ofile
296  * which is used to uniquely identify open instances for the
297  * VFS share reservation and POSIX locks.
298  */
299 static volatile uint32_t smb_fids = 0;
300 #define	SMB_UNIQ_FID()	atomic_inc_32_nv(&smb_fids)
301 
302 /*
303  * smb_ofile_alloc
304  * Allocate an ofile and fill in it's "up" pointers, but
305  * do NOT link it into the tree's list of ofiles or the
306  * node's list of ofiles.  An ofile in this state is a
307  * "proposed" open passed to the oplock break code.
308  *
309  * If we don't get as far as smb_ofile_open with this OF,
310  * call smb_ofile_free() to free this object.
311  *
312  * Note: The following sr members may be null during
313  * persistent handle import: session, uid_usr, tid_tree
314  */
315 smb_ofile_t *
316 smb_ofile_alloc(
317     smb_request_t	*sr,
318     smb_arg_open_t	*op,
319     smb_node_t		*node, /* optional (may be NULL) */
320     uint16_t		ftype,
321     uint16_t		tree_fid)
322 {
323 	smb_user_t	*user = sr->uid_user;	/* optional */
324 	smb_tree_t	*tree = sr->tid_tree;	/* optional */
325 	smb_ofile_t	*of;
326 
327 	of = kmem_cache_alloc(smb_cache_ofile, KM_SLEEP);
328 	bzero(of, sizeof (smb_ofile_t));
329 	of->f_magic = SMB_OFILE_MAGIC;
330 
331 	mutex_init(&of->f_mutex, NULL, MUTEX_DEFAULT, NULL);
332 	list_create(&of->f_notify.nc_waiters, sizeof (smb_request_t),
333 	    offsetof(smb_request_t, sr_waiters));
334 	mutex_init(&of->dh_nvlock, NULL, MUTEX_DEFAULT, NULL);
335 
336 	of->f_state = SMB_OFILE_STATE_ALLOC;
337 	of->f_refcnt = 1;
338 	of->f_ftype = ftype;
339 	of->f_fid = tree_fid;
340 	/* of->f_persistid see smb2_create */
341 	of->f_uniqid = SMB_UNIQ_FID();
342 	of->f_opened_by_pid = sr->smb_pid;
343 	of->f_granted_access = op->desired_access;
344 	of->f_share_access = op->share_access;
345 	of->f_create_options = op->create_options;
346 	if (user != NULL) {
347 		if ((op->create_options & FILE_OPEN_FOR_BACKUP_INTENT) != 0)
348 			of->f_cr = smb_user_getprivcred(user);
349 		else
350 			of->f_cr = user->u_cred;
351 		crhold(of->f_cr);
352 	}
353 	of->f_server = sr->sr_server;
354 	of->f_session = sr->session;	/* may be NULL */
355 
356 	(void) memset(of->f_lock_seq, -1, SMB_OFILE_LSEQ_MAX);
357 
358 	of->f_mode = smb_fsop_amask_to_omode(of->f_granted_access);
359 	if ((of->f_granted_access & FILE_DATA_ALL) == FILE_EXECUTE)
360 		of->f_flags |= SMB_OFLAGS_EXECONLY;
361 
362 	/*
363 	 * In case a lease is requested, copy the lease keys now so
364 	 * any oplock breaks during open don't break those on our
365 	 * other handles that might have the same lease.
366 	 */
367 	bcopy(op->lease_key, of->TargetOplockKey, SMB_LEASE_KEY_SZ);
368 	bcopy(op->parent_lease_key, of->ParentOplockKey, SMB_LEASE_KEY_SZ);
369 
370 	/*
371 	 * grab a ref for of->f_user and of->f_tree
372 	 * We know the user and tree must be "live" because
373 	 * this SR holds references to them.  The node ref. is
374 	 * held by our caller, until smb_ofile_open puts this
375 	 * ofile on the node ofile list with smb_node_add_ofile.
376 	 */
377 	if (user != NULL) {
378 		smb_user_hold_internal(user);
379 		of->f_user = user;
380 	}
381 	if (tree != NULL) {
382 		smb_tree_hold_internal(tree);
383 		of->f_tree = tree;
384 	}
385 	of->f_node = node;	/* may be NULL */
386 
387 	return (of);
388 }
389 
390 /*
391  * smb_ofile_open
392  *
393  * Complete an open on an ofile that was previously allocated by
394  * smb_ofile_alloc, by putting it on the tree ofile list and
395  * (if it's a file) the node ofile list.
396  */
397 void
398 smb_ofile_open(
399     smb_request_t	*sr,
400     smb_arg_open_t	*op,
401     smb_ofile_t		*of)
402 {
403 	smb_tree_t	*tree = sr->tid_tree;
404 	smb_node_t	*node = of->f_node;
405 
406 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
407 	of->f_state = SMB_OFILE_STATE_OPEN;
408 
409 	switch (of->f_ftype) {
410 	case SMB_FTYPE_BYTE_PIPE:
411 	case SMB_FTYPE_MESG_PIPE:
412 		/* See smb_opipe_open. */
413 		of->f_pipe = op->pipe;
414 		smb_server_inc_pipes(of->f_server);
415 		break;
416 	case SMB_FTYPE_DISK:
417 	case SMB_FTYPE_PRINTER:
418 		/* Regular file, not a pipe */
419 		ASSERT(node != NULL);
420 
421 		smb_node_inc_open_ofiles(node);
422 		smb_node_add_ofile(node, of);
423 		smb_node_ref(node);
424 		smb_server_inc_files(of->f_server);
425 		break;
426 	default:
427 		ASSERT(0);
428 	}
429 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
430 	smb_llist_insert_tail(&tree->t_ofile_list, of);
431 	smb_llist_exit(&tree->t_ofile_list);
432 	atomic_inc_32(&tree->t_open_files);
433 	atomic_inc_32(&of->f_session->s_file_cnt);
434 
435 }
436 
437 /*
438  * smb_ofile_close
439  *
440  * Incoming states: (where from)
441  *   SMB_OFILE_STATE_OPEN  protocol close, smb_ofile_drop
442  *   SMB_OFILE_STATE_EXPIRED  called via smb2_dh_expire
443  *   SMB_OFILE_STATE_ORPHANED  smb2_dh_shutdown
444  */
445 void
446 smb_ofile_close(smb_ofile_t *of, int32_t mtime_sec)
447 {
448 	smb_attr_t *pa;
449 	timestruc_t now;
450 
451 	SMB_OFILE_VALID(of);
452 
453 	mutex_enter(&of->f_mutex);
454 	ASSERT(of->f_refcnt);
455 
456 	switch (of->f_state) {
457 	case SMB_OFILE_STATE_OPEN:
458 	case SMB_OFILE_STATE_ORPHANED:
459 	case SMB_OFILE_STATE_EXPIRED:
460 		of->f_state = SMB_OFILE_STATE_CLOSING;
461 		mutex_exit(&of->f_mutex);
462 		break;
463 	default:
464 		mutex_exit(&of->f_mutex);
465 		return;
466 	}
467 
468 	/*
469 	 * Only one thread here (the one that that set f_state closing)
470 	 */
471 	switch (of->f_ftype) {
472 	case SMB_FTYPE_BYTE_PIPE:
473 	case SMB_FTYPE_MESG_PIPE:
474 		smb_opipe_close(of);
475 		smb_server_dec_pipes(of->f_server);
476 		break;
477 
478 	case SMB_FTYPE_DISK:
479 		if (of->dh_persist)
480 			smb2_dh_close_persistent(of);
481 		if (of->f_persistid != 0)
482 			smb_ofile_del_persistid(of);
483 		if (of->f_lease != NULL)
484 			smb2_lease_ofile_close(of);
485 		smb_oplock_break_CLOSE(of->f_node, of);
486 		/* FALLTHROUGH */
487 
488 	case SMB_FTYPE_PRINTER: /* or FTYPE_DISK */
489 		/*
490 		 * In here we make changes to of->f_pending_attr
491 		 * while not holding of->f_mutex.  This is OK
492 		 * because we've changed f_state to CLOSING,
493 		 * so no more threads will take this path.
494 		 */
495 		pa = &of->f_pending_attr;
496 		if (mtime_sec != 0) {
497 			pa->sa_vattr.va_mtime.tv_sec = mtime_sec;
498 			pa->sa_mask |= SMB_AT_MTIME;
499 		}
500 
501 		/*
502 		 * If we have ever modified data via this handle
503 		 * (write or truncate) and if the mtime was not
504 		 * set via this handle, update the mtime again
505 		 * during the close.  Windows expects this.
506 		 * [ MS-FSA 2.1.5.4 "Update Timestamps" ]
507 		 */
508 		if (of->f_written &&
509 		    (pa->sa_mask & SMB_AT_MTIME) == 0) {
510 			pa->sa_mask |= SMB_AT_MTIME;
511 			gethrestime(&now);
512 			pa->sa_vattr.va_mtime = now;
513 		}
514 
515 		if (of->f_flags & SMB_OFLAGS_SET_DELETE_ON_CLOSE) {
516 			/* We delete using the on-disk name. */
517 			uint32_t flags = SMB_CASE_SENSITIVE;
518 			(void) smb_node_set_delete_on_close(of->f_node,
519 			    of->f_cr, flags);
520 		}
521 		smb_fsop_unshrlock(of->f_cr, of->f_node, of->f_uniqid);
522 		smb_node_destroy_lock_by_ofile(of->f_node, of);
523 
524 		if (smb_node_is_file(of->f_node)) {
525 			(void) smb_fsop_close(of->f_node, of->f_mode,
526 			    of->f_cr);
527 		} else {
528 			/*
529 			 * If there was an odir, close it.
530 			 */
531 			if (of->f_odir != NULL)
532 				smb_odir_close(of->f_odir);
533 			/*
534 			 * Cancel any notify change requests that
535 			 * might be watching this open file (dir),
536 			 * and unsubscribe it from node events.
537 			 *
538 			 * Can't hold f_mutex when calling smb_notify_ofile.
539 			 * Don't really need it when unsubscribing, but
540 			 * harmless, and consistent with subscribing.
541 			 */
542 			if (of->f_notify.nc_subscribed)
543 				smb_notify_ofile(of,
544 				    FILE_ACTION_HANDLE_CLOSED, NULL);
545 			mutex_enter(&of->f_mutex);
546 			if (of->f_notify.nc_subscribed) {
547 				of->f_notify.nc_subscribed = B_FALSE;
548 				smb_node_fcn_unsubscribe(of->f_node);
549 				of->f_notify.nc_filter = 0;
550 			}
551 			mutex_exit(&of->f_mutex);
552 		}
553 		if (smb_node_dec_open_ofiles(of->f_node) == 0) {
554 			/*
555 			 * Last close.  If we're not deleting
556 			 * the file, apply any pending attrs.
557 			 * Leave allocsz zero when no open files,
558 			 * just to avoid confusion, because it's
559 			 * only updated when there are opens.
560 			 * XXX: Just do this on _every_ close.
561 			 */
562 			mutex_enter(&of->f_node->n_mutex);
563 			if (of->f_node->flags & NODE_FLAGS_DELETE_ON_CLOSE) {
564 				smb_node_delete_on_close(of->f_node);
565 				pa->sa_mask = 0;
566 			}
567 			of->f_node->n_allocsz = 0;
568 			mutex_exit(&of->f_node->n_mutex);
569 		}
570 		if (pa->sa_mask != 0) {
571 			/*
572 			 * Commit any pending attributes from
573 			 * the ofile we're closing.  Note that
574 			 * we pass NULL as the ofile to setattr
575 			 * so it will write to the file system
576 			 * and not keep anything on the ofile.
577 			 */
578 			(void) smb_node_setattr(NULL, of->f_node,
579 			    of->f_cr, NULL, pa);
580 		}
581 
582 		smb_server_dec_files(of->f_server);
583 		break;
584 	}
585 
586 	/*
587 	 * Keep f_state == SMB_OFILE_STATE_CLOSING
588 	 * until the last ref. is dropped, in
589 	 * smb_ofile_release()
590 	 */
591 }
592 
593 /*
594  * "Destructor" function for smb_ofile_close_all, and
595  * smb_ofile_close_all_by_pid, called after the llist lock
596  * for tree list has been exited.  Our job is to either
597  * close this ofile, or (if durable) set state _SAVE_DH.
598  *
599  * The next interesting thing happens when the last ref.
600  * on this ofile calls smb_ofile_release(), where we
601  * eihter delete the ofile, or (if durable) leave it
602  * in the persistid hash table for possible reclaim.
603  *
604  * This is run via smb_llist_post (after smb_llist_exit)
605  * because smb_ofile_close can block, and we'd rather not
606  * block while holding the ofile list as reader.
607  */
608 static void
609 smb_ofile_drop(void *arg)
610 {
611 	smb_ofile_t	*of = arg;
612 
613 	SMB_OFILE_VALID(of);
614 
615 	mutex_enter(&of->f_mutex);
616 	switch (of->f_state) {
617 	case SMB_OFILE_STATE_OPEN:
618 		/* DH checks under mutex. */
619 		if (of->f_ftype == SMB_FTYPE_DISK &&
620 		    of->dh_vers != SMB2_NOT_DURABLE &&
621 		    smb_dh_should_save(of)) {
622 			/*
623 			 * Tell smb_ofile_release() to
624 			 * make this an _ORPHANED DH.
625 			 */
626 			of->f_state = SMB_OFILE_STATE_SAVE_DH;
627 			mutex_exit(&of->f_mutex);
628 			break;
629 		}
630 		/* OK close it. */
631 		mutex_exit(&of->f_mutex);
632 		smb_ofile_close(of, 0);
633 		break;
634 
635 	default:
636 		/* Something else closed it already. */
637 		mutex_exit(&of->f_mutex);
638 		break;
639 	}
640 
641 	/*
642 	 * Release the ref acquired during the traversal loop.
643 	 * Note that on the last ref, this ofile will be
644 	 * removed from the tree list etc.
645 	 * See: smb_llist_post, smb_ofile_delete
646 	 */
647 	smb_ofile_release(of);
648 }
649 
650 /*
651  * smb_ofile_close_all
652  *
653  *
654  */
655 void
656 smb_ofile_close_all(
657     smb_tree_t		*tree,
658     uint32_t		pid)
659 {
660 	smb_ofile_t	*of;
661 	smb_llist_t	*ll;
662 
663 	ASSERT(tree);
664 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
665 
666 	ll = &tree->t_ofile_list;
667 
668 	smb_llist_enter(ll, RW_READER);
669 	for (of = smb_llist_head(ll);
670 	    of != NULL;
671 	    of = smb_llist_next(ll, of)) {
672 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
673 		ASSERT(of->f_tree == tree);
674 		if (pid != 0 && of->f_opened_by_pid != pid)
675 			continue;
676 		if (smb_ofile_hold(of)) {
677 			smb_llist_post(ll, of, smb_ofile_drop);
678 		}
679 	}
680 
681 	/*
682 	 * Drop the lock and process the llist dtor queue.
683 	 * Calls smb_ofile_drop on ofiles that were open.
684 	 */
685 	smb_llist_exit(ll);
686 }
687 
688 /*
689  * If the enumeration request is for ofile data, handle it here.
690  * Otherwise, return.
691  *
692  * This function should be called with a hold on the ofile.
693  */
694 int
695 smb_ofile_enum(smb_ofile_t *of, smb_svcenum_t *svcenum)
696 {
697 	uint8_t *pb;
698 	uint_t nbytes;
699 	int rc;
700 
701 	ASSERT(of);
702 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
703 	ASSERT(of->f_refcnt);
704 
705 	if (svcenum->se_type != SMB_SVCENUM_TYPE_FILE)
706 		return (0);
707 
708 	if (svcenum->se_nskip > 0) {
709 		svcenum->se_nskip--;
710 		return (0);
711 	}
712 
713 	if (svcenum->se_nitems >= svcenum->se_nlimit) {
714 		svcenum->se_nitems = svcenum->se_nlimit;
715 		return (0);
716 	}
717 
718 	pb = &svcenum->se_buf[svcenum->se_bused];
719 
720 	rc = smb_ofile_netinfo_encode(of, pb, svcenum->se_bavail,
721 	    &nbytes);
722 	if (rc == 0) {
723 		svcenum->se_bavail -= nbytes;
724 		svcenum->se_bused += nbytes;
725 		svcenum->se_nitems++;
726 	}
727 
728 	return (rc);
729 }
730 
731 /*
732  * Take a reference on an open file, in any of the states:
733  *   RECONNECT, SAVE_DH, OPEN, ORPHANED.
734  * Return TRUE if ref taken.  Used for oplock breaks.
735  *
736  * Note: When the oplock break code calls this, it holds the
737  * node ofile list lock and node oplock mutex.  When we see
738  * an ofile in states RECONNECT or SAVING, we know the ofile
739  * is gaining or losing it's tree, and that happens quickly,
740  * so we just wait for that work to finish.  However, the
741  * waiting for state transitions here means we have to be
742  * careful not to re-enter the node list lock or otherwise
743  * block on things that could cause a deadlock.  Waiting
744  * just on of->f_mutex here is OK.
745  */
746 boolean_t
747 smb_ofile_hold_olbrk(smb_ofile_t *of)
748 {
749 	boolean_t ret = B_FALSE;
750 
751 	ASSERT(of);
752 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
753 
754 	mutex_enter(&of->f_mutex);
755 
756 again:
757 	switch (of->f_state) {
758 	case SMB_OFILE_STATE_RECONNECT:
759 	case SMB_OFILE_STATE_SAVING:
760 		cv_wait(&of->f_cv, &of->f_mutex);
761 		goto again;
762 
763 	case SMB_OFILE_STATE_OPEN:
764 	case SMB_OFILE_STATE_ORPHANED:
765 	case SMB_OFILE_STATE_SAVE_DH:
766 		of->f_refcnt++;
767 		ret = B_TRUE;
768 		break;
769 
770 	default:
771 		break;
772 	}
773 	mutex_exit(&of->f_mutex);
774 
775 	return (ret);
776 }
777 
778 /*
779  * Take a reference on an open file.
780  */
781 boolean_t
782 smb_ofile_hold(smb_ofile_t *of)
783 {
784 	ASSERT(of);
785 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
786 
787 	mutex_enter(&of->f_mutex);
788 
789 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
790 		mutex_exit(&of->f_mutex);
791 		return (B_FALSE);
792 	}
793 	of->f_refcnt++;
794 
795 	mutex_exit(&of->f_mutex);
796 	return (B_TRUE);
797 }
798 
799 /*
800  * Release a reference on a file.  If the reference count falls to
801  * zero and the file has been closed, post the object for deletion.
802  * Object deletion is deferred to avoid modifying a list while an
803  * iteration may be in progress.
804  *
805  * We're careful to avoid dropping f_session etc. until the last
806  * reference goes away.  The oplock break code depends on that
807  * not changing while it holds a ref. on an ofile.
808  */
809 void
810 smb_ofile_release(smb_ofile_t *of)
811 {
812 	smb_tree_t *tree = of->f_tree;
813 	boolean_t delete = B_FALSE;
814 
815 	SMB_OFILE_VALID(of);
816 
817 	mutex_enter(&of->f_mutex);
818 	ASSERT(of->f_refcnt > 0);
819 	of->f_refcnt--;
820 
821 	switch (of->f_state) {
822 	case SMB_OFILE_STATE_OPEN:
823 	case SMB_OFILE_STATE_ORPHANED:
824 	case SMB_OFILE_STATE_EXPIRED:
825 		break;
826 
827 	case SMB_OFILE_STATE_SAVE_DH:
828 		ASSERT(tree != NULL);
829 		if (of->f_refcnt == 0) {
830 			of->f_state = SMB_OFILE_STATE_SAVING;
831 			smb_llist_post(&tree->t_ofile_list, of,
832 			    smb_ofile_save_dh);
833 		}
834 		break;
835 
836 	case SMB_OFILE_STATE_CLOSING:
837 		/* Note, tree == NULL on _ORPHANED */
838 		if (of->f_refcnt == 0) {
839 			of->f_state = SMB_OFILE_STATE_CLOSED;
840 			if (tree == NULL) {
841 				/* Skip smb_llist_post */
842 				delete = B_TRUE;
843 				break;
844 			}
845 			smb_llist_post(&tree->t_ofile_list, of,
846 			    smb_ofile_delete);
847 		}
848 		break;
849 
850 	default:
851 		ASSERT(0);
852 		break;
853 	}
854 	mutex_exit(&of->f_mutex);
855 
856 	/*
857 	 * When we drop the last ref. on an expired DH, it's no longer
858 	 * in any tree, so skip the smb_llist_post and just call
859 	 * smb_ofile_delete directly.
860 	 */
861 	if (delete) {
862 		smb_ofile_delete(of);
863 	}
864 }
865 
866 /*
867  * smb_ofile_lookup_by_fid
868  *
869  * Find the open file whose fid matches the one specified in the request.
870  * If we can't find the fid or the shares (trees) don't match, we have a
871  * bad fid.
872  */
873 smb_ofile_t *
874 smb_ofile_lookup_by_fid(
875     smb_request_t	*sr,
876     uint16_t		fid)
877 {
878 	smb_tree_t	*tree = sr->tid_tree;
879 	smb_llist_t	*of_list;
880 	smb_ofile_t	*of;
881 
882 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
883 
884 	of_list = &tree->t_ofile_list;
885 
886 	smb_llist_enter(of_list, RW_READER);
887 	of = smb_llist_head(of_list);
888 	while (of) {
889 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
890 		ASSERT(of->f_tree == tree);
891 		if (of->f_fid == fid)
892 			break;
893 		of = smb_llist_next(of_list, of);
894 	}
895 	if (of == NULL)
896 		goto out;
897 
898 	/*
899 	 * Only allow use of a given FID with the same UID that
900 	 * was used to open it.  MS-CIFS 3.3.5.14
901 	 */
902 	if (of->f_user != sr->uid_user) {
903 		of = NULL;
904 		goto out;
905 	}
906 
907 	/* inline smb_ofile_hold() */
908 	mutex_enter(&of->f_mutex);
909 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
910 		mutex_exit(&of->f_mutex);
911 		of = NULL;
912 		goto out;
913 	}
914 	of->f_refcnt++;
915 	mutex_exit(&of->f_mutex);
916 
917 out:
918 	smb_llist_exit(of_list);
919 	return (of);
920 }
921 
922 /*
923  * smb_ofile_lookup_by_uniqid
924  *
925  * Find the open file whose uniqid matches the one specified in the request.
926  */
927 smb_ofile_t *
928 smb_ofile_lookup_by_uniqid(smb_tree_t *tree, uint32_t uniqid)
929 {
930 	smb_llist_t	*of_list;
931 	smb_ofile_t	*of;
932 
933 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
934 
935 	of_list = &tree->t_ofile_list;
936 	smb_llist_enter(of_list, RW_READER);
937 	of = smb_llist_head(of_list);
938 
939 	while (of) {
940 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
941 		ASSERT(of->f_tree == tree);
942 
943 		if (of->f_uniqid == uniqid) {
944 			if (smb_ofile_hold(of)) {
945 				smb_llist_exit(of_list);
946 				return (of);
947 			}
948 		}
949 
950 		of = smb_llist_next(of_list, of);
951 	}
952 
953 	smb_llist_exit(of_list);
954 	return (NULL);
955 }
956 
957 /*
958  * Durable ID (or persistent ID)
959  */
960 
961 static smb_ofile_t *
962 smb_ofile_hold_cb(smb_ofile_t *of)
963 {
964 	smb_ofile_t *ret = of;
965 
966 	mutex_enter(&of->f_mutex);
967 	if (of->f_state == SMB_OFILE_STATE_ORPHANED)
968 		/* inline smb_ofile_hold() */
969 		of->f_refcnt++;
970 	else
971 		ret = NULL;
972 
973 	mutex_exit(&of->f_mutex);
974 	return (ret);
975 }
976 
977 /*
978  * Lookup an ofile by persistent ID, and return ONLY if in state ORPHANED
979  * This is used by SMB2 create "reclaim".
980  */
981 smb_ofile_t *
982 smb_ofile_lookup_by_persistid(smb_request_t *sr, uint64_t persistid)
983 {
984 	smb_hash_t *hash;
985 	smb_bucket_t *bucket;
986 	smb_llist_t *ll;
987 	smb_ofile_t *of;
988 	uint_t idx;
989 
990 	if (persistid == 0)
991 		return (NULL);
992 
993 	hash = sr->sr_server->sv_persistid_ht;
994 	idx = smb_hash_uint64(hash, persistid);
995 	bucket = &hash->buckets[idx];
996 	ll = &bucket->b_list;
997 
998 	smb_llist_enter(ll, RW_READER);
999 	of = smb_llist_head(ll);
1000 	while (of != NULL) {
1001 		if (of->f_persistid == persistid)
1002 			break;
1003 		of = smb_llist_next(ll, of);
1004 	}
1005 	if (of != NULL)
1006 		of = smb_ofile_hold_cb(of);
1007 	smb_llist_exit(ll);
1008 
1009 	return (of);
1010 }
1011 
1012 /*
1013  * Create a (unique) durable/persistent ID for a new ofile,
1014  * and add this ofile to the persistid hash table.  This ID
1015  * is referred to as the persistent ID in the protocol spec,
1016  * so that's what we call it too, though the persistence may
1017  * vary.  "Durable" handles are persistent across reconnects
1018  * but not server reboots.  Persistent handles are persistent
1019  * across server reboots too.
1020  *
1021  * Note that persistent IDs need to be unique for the lifetime of
1022  * any given ofile.  For normal (non-persistent) ofiles we can just
1023  * use a persistent ID derived from the ofile memory address, as
1024  * these don't ever live beyond the current OS boot lifetime.
1025  *
1026  * Persistent handles are re-imported after server restart, and
1027  * generally have a different memory address after import than
1028  * they had in the previous OS boot lifetime, so for these we
1029  * use a randomly assigned value that won't conflict with any
1030  * non-persistent (durable) handles.  Ensuring that a randomly
1031  * generated ID is unique requires a search of the ofiles in one
1032  * hash bucket, which we'd rather avoid for non-persistent opens.
1033  *
1034  * The solution used here is to divide the persistent ID space
1035  * in half (odd and even values) where durable opens use an ID
1036  * derived from the ofile address (which is always even), and
1037  * persistent opens use an ID generated randomly (always odd).
1038  *
1039  * smb_ofile_set_persistid_dh() sets a durable handle ID and
1040  * smb_ofile_set_persistid_ph() sets a persistent handle ID.
1041  */
1042 void
1043 smb_ofile_set_persistid_dh(smb_ofile_t *of)
1044 {
1045 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1046 	smb_bucket_t *bucket;
1047 	smb_llist_t *ll;
1048 	uint64_t persistid;
1049 	uint_t idx;
1050 
1051 	persistid = (uintptr_t)of;
1052 	/* Avoid showing object addresses */
1053 	persistid ^= ((uintptr_t)&smb_cache_ofile);
1054 	/* make sure it's even */
1055 	persistid &= ~((uint64_t)1);
1056 
1057 	idx = smb_hash_uint64(hash, persistid);
1058 	bucket = &hash->buckets[idx];
1059 	ll = &bucket->b_list;
1060 	smb_llist_enter(ll, RW_WRITER);
1061 	if (of->f_persistid == 0) {
1062 		of->f_persistid = persistid;
1063 		smb_llist_insert_tail(ll, of);
1064 	}
1065 	smb_llist_exit(ll);
1066 }
1067 
1068 void
1069 smb_ofile_set_persistid_ph(smb_ofile_t *of)
1070 {
1071 	uint64_t persistid;
1072 	int rc;
1073 
1074 top:
1075 	(void) random_get_pseudo_bytes((uint8_t *)&persistid,
1076 	    sizeof (persistid));
1077 	if (persistid == 0) {
1078 		cmn_err(CE_NOTE, "random gave all zeros!");
1079 		goto top;
1080 	}
1081 	/* make sure it's odd */
1082 	persistid |= (uint64_t)1;
1083 
1084 	/*
1085 	 * Try inserting with this persistent ID.
1086 	 */
1087 	rc = smb_ofile_insert_persistid(of, persistid);
1088 	if (rc == EEXIST)
1089 		goto top;
1090 	if (rc != 0) {
1091 		cmn_err(CE_NOTE, "set persistid rc=%d", rc);
1092 	}
1093 }
1094 
1095 /*
1096  * Insert an ofile into the persistid hash table.
1097  * If the persistent ID is in use, error.
1098  */
1099 int
1100 smb_ofile_insert_persistid(smb_ofile_t *new_of, uint64_t persistid)
1101 {
1102 	smb_hash_t *hash = new_of->f_server->sv_persistid_ht;
1103 	smb_bucket_t *bucket;
1104 	smb_llist_t *ll;
1105 	smb_ofile_t *of;
1106 	uint_t idx;
1107 
1108 	ASSERT(persistid != 0);
1109 
1110 	/*
1111 	 * Look to see if this key alreay exists.
1112 	 */
1113 	idx = smb_hash_uint64(hash, persistid);
1114 	bucket = &hash->buckets[idx];
1115 	ll = &bucket->b_list;
1116 
1117 	smb_llist_enter(ll, RW_WRITER);
1118 	of = smb_llist_head(ll);
1119 	while (of != NULL) {
1120 		if (of->f_persistid == persistid) {
1121 			/* already in use */
1122 			smb_llist_exit(ll);
1123 			return (EEXIST);
1124 		}
1125 		of = smb_llist_next(ll, of);
1126 	}
1127 
1128 	/* Not found, so OK to insert. */
1129 	if (new_of->f_persistid == 0) {
1130 		new_of->f_persistid = persistid;
1131 		smb_llist_insert_tail(ll, new_of);
1132 	}
1133 	smb_llist_exit(ll);
1134 
1135 	return (0);
1136 }
1137 
1138 void
1139 smb_ofile_del_persistid(smb_ofile_t *of)
1140 {
1141 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1142 	smb_bucket_t *bucket;
1143 	smb_llist_t *ll;
1144 	uint_t idx;
1145 
1146 	idx = smb_hash_uint64(hash, of->f_persistid);
1147 	bucket = &hash->buckets[idx];
1148 	ll = &bucket->b_list;
1149 	smb_llist_enter(ll, RW_WRITER);
1150 	if (of->f_persistid != 0) {
1151 		smb_llist_remove(ll, of);
1152 		of->f_persistid = 0;
1153 	}
1154 	smb_llist_exit(ll);
1155 }
1156 
1157 /*
1158  * Disallow NetFileClose on certain ofiles to avoid side-effects.
1159  * Closing a tree root is not allowed: use NetSessionDel or NetShareDel.
1160  * Closing SRVSVC connections is not allowed because this NetFileClose
1161  * request may depend on this ofile.
1162  */
1163 boolean_t
1164 smb_ofile_disallow_fclose(smb_ofile_t *of)
1165 {
1166 	ASSERT(of);
1167 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1168 	ASSERT(of->f_refcnt);
1169 
1170 	switch (of->f_ftype) {
1171 	case SMB_FTYPE_DISK:
1172 		ASSERT(of->f_tree);
1173 		return (of->f_node == of->f_tree->t_snode);
1174 
1175 	case SMB_FTYPE_MESG_PIPE:
1176 		ASSERT(of->f_pipe);
1177 		if (smb_strcasecmp(of->f_pipe->p_name, "SRVSVC", 0) == 0)
1178 			return (B_TRUE);
1179 		break;
1180 	default:
1181 		break;
1182 	}
1183 
1184 	return (B_FALSE);
1185 }
1186 
1187 /*
1188  * smb_ofile_set_flags
1189  *
1190  * Return value:
1191  *
1192  *	Current flags value
1193  *
1194  */
1195 void
1196 smb_ofile_set_flags(
1197     smb_ofile_t		*of,
1198     uint32_t		flags)
1199 {
1200 	ASSERT(of);
1201 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1202 	ASSERT(of->f_refcnt);
1203 
1204 	mutex_enter(&of->f_mutex);
1205 	of->f_flags |= flags;
1206 	mutex_exit(&of->f_mutex);
1207 }
1208 
1209 /*
1210  * smb_ofile_seek
1211  *
1212  * Return value:
1213  *
1214  *	0		Success
1215  *	EINVAL		Unknown mode
1216  *	EOVERFLOW	offset too big
1217  *
1218  */
1219 int
1220 smb_ofile_seek(
1221     smb_ofile_t		*of,
1222     ushort_t		mode,
1223     int32_t		off,
1224     uint32_t		*retoff)
1225 {
1226 	u_offset_t	newoff = 0;
1227 	int		rc = 0;
1228 	smb_attr_t	attr;
1229 
1230 	ASSERT(of);
1231 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1232 	ASSERT(of->f_refcnt);
1233 
1234 	mutex_enter(&of->f_mutex);
1235 	switch (mode) {
1236 	case SMB_SEEK_SET:
1237 		if (off < 0)
1238 			newoff = 0;
1239 		else
1240 			newoff = (u_offset_t)off;
1241 		break;
1242 
1243 	case SMB_SEEK_CUR:
1244 		if (off < 0 && (-off) > of->f_seek_pos)
1245 			newoff = 0;
1246 		else
1247 			newoff = of->f_seek_pos + (u_offset_t)off;
1248 		break;
1249 
1250 	case SMB_SEEK_END:
1251 		bzero(&attr, sizeof (smb_attr_t));
1252 		attr.sa_mask |= SMB_AT_SIZE;
1253 		rc = smb_fsop_getattr(NULL, zone_kcred(), of->f_node, &attr);
1254 		if (rc != 0) {
1255 			mutex_exit(&of->f_mutex);
1256 			return (rc);
1257 		}
1258 		if (off < 0 && (-off) > attr.sa_vattr.va_size)
1259 			newoff = 0;
1260 		else
1261 			newoff = attr.sa_vattr.va_size + (u_offset_t)off;
1262 		break;
1263 
1264 	default:
1265 		mutex_exit(&of->f_mutex);
1266 		return (EINVAL);
1267 	}
1268 
1269 	/*
1270 	 * See comments at the beginning of smb_seek.c.
1271 	 * If the offset is greater than UINT_MAX, we will return an error.
1272 	 */
1273 
1274 	if (newoff > UINT_MAX) {
1275 		rc = EOVERFLOW;
1276 	} else {
1277 		of->f_seek_pos = newoff;
1278 		*retoff = (uint32_t)newoff;
1279 	}
1280 	mutex_exit(&of->f_mutex);
1281 	return (rc);
1282 }
1283 
1284 /*
1285  * smb_ofile_flush
1286  *
1287  * If writes on this file are not synchronous, flush it using the NFSv3
1288  * commit interface.
1289  *
1290  * XXX - todo: Flush named pipe should drain writes.
1291  */
1292 void
1293 smb_ofile_flush(struct smb_request *sr, struct smb_ofile *of)
1294 {
1295 	switch (of->f_ftype) {
1296 	case SMB_FTYPE_DISK:
1297 		if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
1298 			(void) smb_fsop_commit(sr, of->f_cr, of->f_node);
1299 		break;
1300 	default:
1301 		break;
1302 	}
1303 }
1304 
1305 /*
1306  * smb_ofile_is_open
1307  */
1308 boolean_t
1309 smb_ofile_is_open(smb_ofile_t *of)
1310 {
1311 	boolean_t	rc;
1312 
1313 	SMB_OFILE_VALID(of);
1314 
1315 	mutex_enter(&of->f_mutex);
1316 	rc = smb_ofile_is_open_locked(of);
1317 	mutex_exit(&of->f_mutex);
1318 	return (rc);
1319 }
1320 
1321 /* *************************** Static Functions ***************************** */
1322 
1323 /*
1324  * Determine whether or not an ofile is open.
1325  * This function must be called with the mutex held.
1326  */
1327 static boolean_t
1328 smb_ofile_is_open_locked(smb_ofile_t *of)
1329 {
1330 	ASSERT(MUTEX_HELD(&of->f_mutex));
1331 
1332 	switch (of->f_state) {
1333 	case SMB_OFILE_STATE_OPEN:
1334 	case SMB_OFILE_STATE_SAVE_DH:
1335 	case SMB_OFILE_STATE_SAVING:
1336 	case SMB_OFILE_STATE_ORPHANED:
1337 	case SMB_OFILE_STATE_RECONNECT:
1338 		return (B_TRUE);
1339 
1340 	case SMB_OFILE_STATE_CLOSING:
1341 	case SMB_OFILE_STATE_CLOSED:
1342 	case SMB_OFILE_STATE_EXPIRED:
1343 		return (B_FALSE);
1344 
1345 	default:
1346 		ASSERT(0);
1347 		return (B_FALSE);
1348 	}
1349 }
1350 
1351 /*
1352  * smb_ofile_save_dh
1353  *
1354  * Called via smb_llist_post (after smb_llist_exit) when the last ref.
1355  * on this ofile has gone, and this ofile is a "durable handle" (DH)
1356  * that has state we've decided to save.
1357  *
1358  * This does parts of what smb_ofile_delete would do, including:
1359  * remove the ofile from the tree ofile list and related.
1360  *
1361  * We leave the ofile in state ORPHANED, ready for reconnect
1362  * or expiration via smb2_dh_expire (see smb_ofile_delete).
1363  */
1364 static void
1365 smb_ofile_save_dh(void *arg)
1366 {
1367 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1368 	smb_tree_t	*tree = of->f_tree;
1369 
1370 	SMB_OFILE_VALID(of);
1371 	ASSERT(of->f_refcnt == 0);
1372 	ASSERT(of->f_ftype == SMB_FTYPE_DISK);
1373 	ASSERT(of->f_state == SMB_OFILE_STATE_SAVING);
1374 
1375 	atomic_dec_32(&of->f_session->s_file_cnt);
1376 	atomic_dec_32(&of->f_tree->t_open_files);
1377 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1378 	smb_llist_remove(&tree->t_ofile_list, of);
1379 	smb_llist_exit(&tree->t_ofile_list);
1380 
1381 	/*
1382 	 * This ofile is no longer on t_ofile_list, however...
1383 	 *
1384 	 * This is called via smb_llist_post, which means it may run
1385 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1386 	 * flushes the delete queue before we do).  Synchronize.
1387 	 */
1388 	mutex_enter(&of->f_mutex);
1389 	DTRACE_PROBE1(ofile__exit, smb_ofile_t, of);
1390 	mutex_exit(&of->f_mutex);
1391 
1392 	/*
1393 	 * Keep f_notify state, lease, and
1394 	 * keep on node ofile list.
1395 	 * Keep of->f_cr until reclaim.
1396 	 */
1397 
1398 	ASSERT(of->f_fid != 0);
1399 	smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1400 	of->f_fid = 0;
1401 	smb_tree_release(of->f_tree);
1402 	of->f_tree = NULL;
1403 	smb_user_release(of->f_user);
1404 	of->f_user = NULL;
1405 	of->f_session = NULL;
1406 
1407 	/*
1408 	 * Make it "orphaned" so it can now be reclaimed.
1409 	 * Note that smb_ofile_hold_olbrk() may have blocked
1410 	 * for state SMB_OFILE_STATE_SAVING, so wake it.
1411 	 */
1412 	mutex_enter(&of->f_mutex);
1413 	of->dh_expire_time = gethrtime() + of->dh_timeout_offset;
1414 	of->f_state = SMB_OFILE_STATE_ORPHANED;
1415 	cv_broadcast(&of->f_cv);
1416 	mutex_exit(&of->f_mutex);
1417 }
1418 
1419 /*
1420  * Delete an ofile.
1421  *
1422  * Approximately the inverse of smb_ofile_alloc()
1423  * Called via smb_llist_post (after smb_llist_exit)
1424  * when the last ref. on this ofile has gone.
1425  *
1426  * Normally,this removes the ofile from the tree list and
1427  * then frees resources held on the ofile.  However, when
1428  * we're expiring an orphaned durable handle, the linkage
1429  * into the tree lists etc. have already been destroyed.
1430  * This case is distinguished by of->f_tree == NULL.
1431  */
1432 static void
1433 smb_ofile_delete(void *arg)
1434 {
1435 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1436 	smb_tree_t	*tree = of->f_tree;
1437 
1438 	SMB_OFILE_VALID(of);
1439 	ASSERT(of->f_refcnt == 0);
1440 	ASSERT(of->f_state == SMB_OFILE_STATE_CLOSED);
1441 
1442 	if (tree != NULL) {
1443 		ASSERT(of->f_user != NULL);
1444 		ASSERT(of->f_session != NULL);
1445 		atomic_dec_32(&of->f_session->s_file_cnt);
1446 		atomic_dec_32(&of->f_tree->t_open_files);
1447 		smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1448 		smb_llist_remove(&tree->t_ofile_list, of);
1449 		smb_llist_exit(&tree->t_ofile_list);
1450 	}
1451 
1452 	/*
1453 	 * Remove this ofile from the node's n_ofile_list so it
1454 	 * can't be found by list walkers like notify or oplock.
1455 	 * Keep the node ref. until later in this function so
1456 	 * of->f_node remains valid while we destroy the ofile.
1457 	 */
1458 	if (of->f_ftype == SMB_FTYPE_DISK ||
1459 	    of->f_ftype == SMB_FTYPE_PRINTER) {
1460 		ASSERT(of->f_node != NULL);
1461 		/*
1462 		 * Note smb_ofile_close did smb_node_dec_open_ofiles()
1463 		 */
1464 		smb_node_rem_ofile(of->f_node, of);
1465 	}
1466 
1467 	/*
1468 	 * This ofile is no longer on any lists, however...
1469 	 *
1470 	 * This is called via smb_llist_post, which means it may run
1471 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1472 	 * flushes the delete queue before we do).  Synchronize.
1473 	 */
1474 	mutex_enter(&of->f_mutex);
1475 	of->f_state = SMB_OFILE_STATE_ALLOC;
1476 	DTRACE_PROBE1(ofile__exit, smb_ofile_t, of);
1477 	mutex_exit(&of->f_mutex);
1478 
1479 	switch (of->f_ftype) {
1480 	case SMB_FTYPE_BYTE_PIPE:
1481 	case SMB_FTYPE_MESG_PIPE:
1482 		smb_opipe_dealloc(of->f_pipe);
1483 		of->f_pipe = NULL;
1484 		break;
1485 	case SMB_FTYPE_DISK:
1486 		ASSERT(of->f_notify.nc_subscribed == B_FALSE);
1487 		MBC_FLUSH(&of->f_notify.nc_buffer);
1488 		if (of->f_odir != NULL)
1489 			smb_odir_release(of->f_odir);
1490 		if (of->f_lease != NULL) {
1491 			smb2_lease_rele(of->f_lease);
1492 			of->f_lease = NULL;
1493 		}
1494 		/* FALLTHROUGH */
1495 	case SMB_FTYPE_PRINTER:
1496 		/*
1497 		 * Did smb_node_rem_ofile above.
1498 		 */
1499 		ASSERT(of->f_node != NULL);
1500 		smb_node_release(of->f_node);
1501 		break;
1502 	default:
1503 		ASSERT(!"f_ftype");
1504 		break;
1505 	}
1506 
1507 	smb_ofile_free(of);
1508 }
1509 
1510 void
1511 smb_ofile_free(smb_ofile_t *of)
1512 {
1513 	smb_tree_t	*tree = of->f_tree;
1514 
1515 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
1516 
1517 	/* Make sure it's not in the persistid hash. */
1518 	ASSERT(of->f_persistid == 0);
1519 
1520 	if (tree != NULL) {
1521 		if (of->f_fid != 0)
1522 			smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1523 		smb_tree_release(of->f_tree);
1524 		smb_user_release(of->f_user);
1525 	}
1526 
1527 	if (of->f_cr != NULL)
1528 		crfree(of->f_cr);
1529 
1530 	of->f_magic = (uint32_t)~SMB_OFILE_MAGIC;
1531 	list_destroy(&of->f_notify.nc_waiters);
1532 	mutex_destroy(&of->dh_nvlock);
1533 	mutex_destroy(&of->f_mutex);
1534 	kmem_cache_free(smb_cache_ofile, of);
1535 }
1536 
1537 /*
1538  * smb_ofile_access
1539  *
1540  * This function will check to see if the access requested is granted.
1541  * Returns NT status codes.
1542  */
1543 uint32_t
1544 smb_ofile_access(smb_ofile_t *of, cred_t *cr, uint32_t access)
1545 {
1546 
1547 	if ((of == NULL) || (cr == zone_kcred()))
1548 		return (NT_STATUS_SUCCESS);
1549 
1550 	/*
1551 	 * If the request is for something
1552 	 * I don't grant it is an error
1553 	 */
1554 	if (~(of->f_granted_access) & access) {
1555 		if (!(of->f_granted_access & ACCESS_SYSTEM_SECURITY) &&
1556 		    (access & ACCESS_SYSTEM_SECURITY)) {
1557 			return (NT_STATUS_PRIVILEGE_NOT_HELD);
1558 		}
1559 		return (NT_STATUS_ACCESS_DENIED);
1560 	}
1561 
1562 	return (NT_STATUS_SUCCESS);
1563 }
1564 
1565 /*
1566  * smb_ofile_share_check
1567  *
1568  * Check if ofile was opened with share access NONE (0).
1569  * Returns: B_TRUE  - share access non-zero
1570  *          B_FALSE - share access NONE
1571  */
1572 boolean_t
1573 smb_ofile_share_check(smb_ofile_t *of)
1574 {
1575 	return (!SMB_DENY_ALL(of->f_share_access));
1576 }
1577 
1578 /*
1579  * check file sharing rules for current open request
1580  * against existing open instances of the same file
1581  *
1582  * Returns NT_STATUS_SHARING_VIOLATION if there is any
1583  * sharing conflict, otherwise returns NT_STATUS_SUCCESS.
1584  */
1585 uint32_t
1586 smb_ofile_open_check(smb_ofile_t *of, uint32_t desired_access,
1587     uint32_t share_access)
1588 {
1589 	uint32_t ret;
1590 
1591 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1592 
1593 	mutex_enter(&of->f_mutex);
1594 
1595 	if (!smb_ofile_is_open_locked(of)) {
1596 		ret = NT_STATUS_INVALID_HANDLE;
1597 		goto out;
1598 	}
1599 
1600 	/* if it's just meta data */
1601 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1602 		ret = NT_STATUS_SUCCESS;
1603 		goto out;
1604 	}
1605 
1606 	/*
1607 	 * Check requested share access against the
1608 	 * open granted (desired) access
1609 	 */
1610 	if (SMB_DENY_DELETE(share_access) && (of->f_granted_access & DELETE)) {
1611 		ret = NT_STATUS_SHARING_VIOLATION;
1612 		goto out;
1613 	}
1614 
1615 	if (SMB_DENY_READ(share_access) &&
1616 	    (of->f_granted_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1617 		ret = NT_STATUS_SHARING_VIOLATION;
1618 		goto out;
1619 	}
1620 
1621 	if (SMB_DENY_WRITE(share_access) &&
1622 	    (of->f_granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1623 		ret = NT_STATUS_SHARING_VIOLATION;
1624 		goto out;
1625 	}
1626 
1627 	/* check requested desired access against the open share access */
1628 	if (SMB_DENY_DELETE(of->f_share_access) && (desired_access & DELETE)) {
1629 		ret = NT_STATUS_SHARING_VIOLATION;
1630 		goto out;
1631 	}
1632 
1633 	if (SMB_DENY_READ(of->f_share_access) &&
1634 	    (desired_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1635 		ret = NT_STATUS_SHARING_VIOLATION;
1636 		goto out;
1637 	}
1638 
1639 	if (SMB_DENY_WRITE(of->f_share_access) &&
1640 	    (desired_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1641 		ret = NT_STATUS_SHARING_VIOLATION;
1642 		goto out;
1643 	}
1644 
1645 	ret = NT_STATUS_SUCCESS;
1646 out:
1647 	mutex_exit(&of->f_mutex);
1648 	return (ret);
1649 }
1650 
1651 /*
1652  * smb_ofile_rename_check
1653  *
1654  * This does the work described in MS-FSA 2.1.5.1.2.2 (Algorithm
1655  * to Check Sharing Access to an Existing Stream or Directory),
1656  * where the "open in-progress" has DesiredAccess = DELETE and
1657  * SharingMode = SHARE_READ | SHARE_WRITE | SHARE_DELETE.
1658  */
1659 
1660 uint32_t
1661 smb_ofile_rename_check(smb_ofile_t *of)
1662 {
1663 	uint32_t ret;
1664 
1665 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1666 
1667 	mutex_enter(&of->f_mutex);
1668 
1669 	if (!smb_ofile_is_open_locked(of)) {
1670 		ret = NT_STATUS_INVALID_HANDLE;
1671 		goto out;
1672 	}
1673 
1674 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1675 		ret = NT_STATUS_SUCCESS;
1676 		goto out;
1677 	}
1678 
1679 	if ((of->f_share_access & FILE_SHARE_DELETE) == 0) {
1680 		ret = NT_STATUS_SHARING_VIOLATION;
1681 		goto out;
1682 	}
1683 
1684 	ret = NT_STATUS_SUCCESS;
1685 out:
1686 	mutex_exit(&of->f_mutex);
1687 	return (ret);
1688 }
1689 
1690 /*
1691  * smb_ofile_delete_check
1692  *
1693  * An open file can be deleted only if opened for
1694  * accessing meta data. Share modes aren't important
1695  * in this case.
1696  *
1697  * NOTE: there is another mechanism for deleting an
1698  * open file that NT clients usually use.
1699  * That's setting "Delete on close" flag for an open
1700  * file.  In this way the file will be deleted after
1701  * last close. This flag can be set by SmbTrans2SetFileInfo
1702  * with FILE_DISPOSITION_INFO information level.
1703  * For setting this flag, the file should be opened by
1704  * DELETE access in the FID that is passed in the Trans2
1705  * request.
1706  */
1707 
1708 uint32_t
1709 smb_ofile_delete_check(smb_ofile_t *of)
1710 {
1711 	uint32_t ret;
1712 
1713 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1714 
1715 	mutex_enter(&of->f_mutex);
1716 
1717 	if (!smb_ofile_is_open_locked(of)) {
1718 		ret = NT_STATUS_INVALID_HANDLE;
1719 		goto out;
1720 	}
1721 
1722 	if (of->f_granted_access &
1723 	    (FILE_READ_DATA | FILE_WRITE_DATA |
1724 	    FILE_APPEND_DATA | FILE_EXECUTE | DELETE)) {
1725 		ret = NT_STATUS_SHARING_VIOLATION;
1726 		goto out;
1727 	}
1728 
1729 	ret = NT_STATUS_SUCCESS;
1730 out:
1731 	mutex_exit(&of->f_mutex);
1732 	return (ret);
1733 }
1734 
1735 cred_t *
1736 smb_ofile_getcred(smb_ofile_t *of)
1737 {
1738 	return (of->f_cr);
1739 }
1740 
1741 /*
1742  * smb_ofile_set_delete_on_close
1743  *
1744  * Set the DeleteOnClose flag on the smb file. When the file is closed,
1745  * the flag will be transferred to the smb node, which will commit the
1746  * delete operation and inhibit subsequent open requests.
1747  *
1748  * When DeleteOnClose is set on an smb_node, the common open code will
1749  * reject subsequent open requests for the file. Observation of Windows
1750  * 2000 indicates that subsequent opens should be allowed (assuming
1751  * there would be no sharing violation) until the file is closed using
1752  * the fid on which the DeleteOnClose was requested.
1753  */
1754 void
1755 smb_ofile_set_delete_on_close(smb_request_t *sr, smb_ofile_t *of)
1756 {
1757 	uint32_t	status;
1758 
1759 	/*
1760 	 * Break any oplock handle caching.
1761 	 */
1762 	status = smb_oplock_break_SETINFO(of->f_node, of,
1763 	    FileDispositionInformation);
1764 	if (status == NT_STATUS_OPLOCK_BREAK_IN_PROGRESS) {
1765 		if (sr->session->dialect >= SMB_VERS_2_BASE)
1766 			(void) smb2sr_go_async(sr);
1767 		(void) smb_oplock_wait_break(of->f_node, 0);
1768 	}
1769 
1770 	mutex_enter(&of->f_mutex);
1771 	of->f_flags |= SMB_OFLAGS_SET_DELETE_ON_CLOSE;
1772 	mutex_exit(&of->f_mutex);
1773 }
1774 
1775 /*
1776  * Encode open file information into a buffer; needed in user space to
1777  * support RPC requests.
1778  */
1779 static int
1780 smb_ofile_netinfo_encode(smb_ofile_t *of, uint8_t *buf, size_t buflen,
1781     uint32_t *nbytes)
1782 {
1783 	smb_netfileinfo_t	fi;
1784 	int			rc;
1785 
1786 	rc = smb_ofile_netinfo_init(of, &fi);
1787 	if (rc == 0) {
1788 		rc = smb_netfileinfo_encode(&fi, buf, buflen, nbytes);
1789 		smb_ofile_netinfo_fini(&fi);
1790 	}
1791 
1792 	return (rc);
1793 }
1794 
1795 static int
1796 smb_ofile_netinfo_init(smb_ofile_t *of, smb_netfileinfo_t *fi)
1797 {
1798 	smb_user_t	*user;
1799 	smb_tree_t	*tree;
1800 	smb_node_t	*node;
1801 	char		*path;
1802 	char		*buf;
1803 	int		rc;
1804 
1805 	ASSERT(of);
1806 	user = of->f_user;
1807 	tree = of->f_tree;
1808 	ASSERT(user);
1809 	ASSERT(tree);
1810 
1811 	buf = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1812 
1813 	switch (of->f_ftype) {
1814 	case SMB_FTYPE_DISK:
1815 		node = of->f_node;
1816 		ASSERT(node);
1817 
1818 		fi->fi_permissions = of->f_granted_access;
1819 		fi->fi_numlocks = smb_lock_get_lock_count(node, of);
1820 
1821 		path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1822 
1823 		if (node != tree->t_snode) {
1824 			rc = smb_node_getshrpath(node, tree, path, MAXPATHLEN);
1825 			if (rc != 0)
1826 				(void) strlcpy(path, node->od_name, MAXPATHLEN);
1827 		}
1828 
1829 		(void) snprintf(buf, MAXPATHLEN, "%s:%s", tree->t_sharename,
1830 		    path);
1831 		kmem_free(path, MAXPATHLEN);
1832 		break;
1833 
1834 	case SMB_FTYPE_MESG_PIPE:
1835 		ASSERT(of->f_pipe);
1836 
1837 		fi->fi_permissions = FILE_READ_DATA | FILE_WRITE_DATA |
1838 		    FILE_EXECUTE;
1839 		fi->fi_numlocks = 0;
1840 		(void) snprintf(buf, MAXPATHLEN, "\\PIPE\\%s",
1841 		    of->f_pipe->p_name);
1842 		break;
1843 
1844 	default:
1845 		kmem_free(buf, MAXPATHLEN);
1846 		return (-1);
1847 	}
1848 
1849 	fi->fi_fid = of->f_fid;
1850 	fi->fi_uniqid = of->f_uniqid;
1851 	fi->fi_pathlen = strlen(buf) + 1;
1852 	fi->fi_path = smb_mem_strdup(buf);
1853 	kmem_free(buf, MAXPATHLEN);
1854 
1855 	fi->fi_namelen = user->u_domain_len + user->u_name_len + 2;
1856 	fi->fi_username = kmem_alloc(fi->fi_namelen, KM_SLEEP);
1857 	(void) snprintf(fi->fi_username, fi->fi_namelen, "%s\\%s",
1858 	    user->u_domain, user->u_name);
1859 	return (0);
1860 }
1861 
1862 static void
1863 smb_ofile_netinfo_fini(smb_netfileinfo_t *fi)
1864 {
1865 	if (fi == NULL)
1866 		return;
1867 
1868 	if (fi->fi_path)
1869 		smb_mem_free(fi->fi_path);
1870 	if (fi->fi_username)
1871 		kmem_free(fi->fi_username, fi->fi_namelen);
1872 
1873 	bzero(fi, sizeof (smb_netfileinfo_t));
1874 }
1875 
1876 /*
1877  * A query of user and group quotas may span multiple requests.
1878  * f_quota_resume is used to determine where the query should
1879  * be resumed, in a subsequent request. f_quota_resume contains
1880  * the SID of the last quota entry returned to the client.
1881  */
1882 void
1883 smb_ofile_set_quota_resume(smb_ofile_t *ofile, char *resume)
1884 {
1885 	ASSERT(ofile);
1886 	mutex_enter(&ofile->f_mutex);
1887 	if (resume == NULL)
1888 		bzero(ofile->f_quota_resume, SMB_SID_STRSZ);
1889 	else
1890 		(void) strlcpy(ofile->f_quota_resume, resume, SMB_SID_STRSZ);
1891 	mutex_exit(&ofile->f_mutex);
1892 }
1893 
1894 void
1895 smb_ofile_get_quota_resume(smb_ofile_t *ofile, char *buf, int bufsize)
1896 {
1897 	ASSERT(ofile);
1898 	mutex_enter(&ofile->f_mutex);
1899 	(void) strlcpy(buf, ofile->f_quota_resume, bufsize);
1900 	mutex_exit(&ofile->f_mutex);
1901 }
1902