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