xref: /illumos-gate/usr/src/uts/common/fs/smbsrv/smb_ofile.c (revision 28ab0ca48b3e331cbbb231b1c8325f9f24f9af95)
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  */
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 
450 	SMB_OFILE_VALID(of);
451 
452 	if (of->f_ftype == SMB_FTYPE_DISK) {
453 		smb_node_t *node = of->f_node;
454 
455 		smb_llist_enter(&node->n_ofile_list, RW_READER);
456 		mutex_enter(&node->n_oplock.ol_mutex);
457 
458 		if (of->f_lease != NULL)
459 			smb2_lease_ofile_close(of);
460 		smb_oplock_break_CLOSE(node, of);
461 
462 		mutex_exit(&node->n_oplock.ol_mutex);
463 		smb_llist_exit(&node->n_ofile_list);
464 	}
465 
466 	mutex_enter(&of->f_mutex);
467 	ASSERT(of->f_refcnt);
468 
469 	switch (of->f_state) {
470 	case SMB_OFILE_STATE_OPEN:
471 	case SMB_OFILE_STATE_ORPHANED:
472 	case SMB_OFILE_STATE_EXPIRED:
473 		of->f_state = SMB_OFILE_STATE_CLOSING;
474 		mutex_exit(&of->f_mutex);
475 		break;
476 	default:
477 		mutex_exit(&of->f_mutex);
478 		return;
479 	}
480 
481 	/*
482 	 * Only one thread here (the one that that set f_state closing)
483 	 */
484 	switch (of->f_ftype) {
485 	case SMB_FTYPE_BYTE_PIPE:
486 	case SMB_FTYPE_MESG_PIPE:
487 		smb_opipe_close(of);
488 		smb_server_dec_pipes(of->f_server);
489 		break;
490 
491 	case SMB_FTYPE_DISK:
492 		if (of->dh_persist)
493 			smb2_dh_close_persistent(of);
494 		if (of->f_persistid != 0)
495 			smb_ofile_del_persistid(of);
496 		/* FALLTHROUGH */
497 
498 	case SMB_FTYPE_PRINTER: /* or FTYPE_DISK */
499 		/*
500 		 * In here we make changes to of->f_pending_attr
501 		 * while not holding of->f_mutex.  This is OK
502 		 * because we've changed f_state to CLOSING,
503 		 * so no more threads will take this path.
504 		 */
505 		pa = &of->f_pending_attr;
506 		if (mtime_sec != 0) {
507 			pa->sa_vattr.va_mtime.tv_sec = mtime_sec;
508 			pa->sa_mask |= SMB_AT_MTIME;
509 		}
510 
511 		if (of->f_flags & SMB_OFLAGS_SET_DELETE_ON_CLOSE) {
512 			/* We delete using the on-disk name. */
513 			uint32_t flags = SMB_CASE_SENSITIVE;
514 			(void) smb_node_set_delete_on_close(of->f_node,
515 			    of->f_cr, flags);
516 		}
517 		smb_fsop_unshrlock(of->f_cr, of->f_node, of->f_uniqid);
518 		smb_node_destroy_lock_by_ofile(of->f_node, of);
519 
520 		if (smb_node_is_file(of->f_node)) {
521 			(void) smb_fsop_close(of->f_node, of->f_mode,
522 			    of->f_cr);
523 		} else {
524 			/*
525 			 * If there was an odir, close it.
526 			 */
527 			if (of->f_odir != NULL)
528 				smb_odir_close(of->f_odir);
529 			/*
530 			 * Cancel any notify change requests that
531 			 * might be watching this open file (dir),
532 			 * and unsubscribe it from node events.
533 			 *
534 			 * Can't hold f_mutex when calling smb_notify_ofile.
535 			 * Don't really need it when unsubscribing, but
536 			 * harmless, and consistent with subscribing.
537 			 */
538 			if (of->f_notify.nc_subscribed)
539 				smb_notify_ofile(of,
540 				    FILE_ACTION_HANDLE_CLOSED, NULL);
541 			mutex_enter(&of->f_mutex);
542 			if (of->f_notify.nc_subscribed) {
543 				of->f_notify.nc_subscribed = B_FALSE;
544 				smb_node_fcn_unsubscribe(of->f_node);
545 				of->f_notify.nc_filter = 0;
546 			}
547 			mutex_exit(&of->f_mutex);
548 		}
549 		if (smb_node_dec_open_ofiles(of->f_node) == 0) {
550 			/*
551 			 * Last close.  If we're not deleting
552 			 * the file, apply any pending attrs.
553 			 * Leave allocsz zero when no open files,
554 			 * just to avoid confusion, because it's
555 			 * only updated when there are opens.
556 			 * XXX: Just do this on _every_ close.
557 			 */
558 			mutex_enter(&of->f_node->n_mutex);
559 			if (of->f_node->flags & NODE_FLAGS_DELETE_ON_CLOSE) {
560 				smb_node_delete_on_close(of->f_node);
561 				pa->sa_mask = 0;
562 			}
563 			of->f_node->n_allocsz = 0;
564 			mutex_exit(&of->f_node->n_mutex);
565 		}
566 		if (pa->sa_mask != 0) {
567 			/*
568 			 * Commit any pending attributes from
569 			 * the ofile we're closing.  Note that
570 			 * we pass NULL as the ofile to setattr
571 			 * so it will write to the file system
572 			 * and not keep anything on the ofile.
573 			 */
574 			(void) smb_node_setattr(NULL, of->f_node,
575 			    of->f_cr, NULL, pa);
576 		}
577 
578 		smb_server_dec_files(of->f_server);
579 		break;
580 	}
581 
582 	/*
583 	 * Keep f_state == SMB_OFILE_STATE_CLOSING
584 	 * until the last ref. is dropped, in
585 	 * smb_ofile_release()
586 	 */
587 }
588 
589 /*
590  * "Destructor" function for smb_ofile_close_all, and
591  * smb_ofile_close_all_by_pid, called after the llist lock
592  * for tree list has been exited.  Our job is to either
593  * close this ofile, or (if durable) set state _SAVE_DH.
594  *
595  * The next interesting thing happens when the last ref.
596  * on this ofile calls smb_ofile_release(), where we
597  * eihter delete the ofile, or (if durable) leave it
598  * in the persistid hash table for possible reclaim.
599  *
600  * This is run via smb_llist_post (after smb_llist_exit)
601  * because smb_ofile_close can block, and we'd rather not
602  * block while holding the ofile list as reader.
603  */
604 static void
605 smb_ofile_drop(void *arg)
606 {
607 	smb_ofile_t	*of = arg;
608 
609 	SMB_OFILE_VALID(of);
610 
611 	mutex_enter(&of->f_mutex);
612 	switch (of->f_state) {
613 	case SMB_OFILE_STATE_OPEN:
614 		/* DH checks under mutex. */
615 		if (of->f_ftype == SMB_FTYPE_DISK &&
616 		    of->dh_vers != SMB2_NOT_DURABLE &&
617 		    smb_dh_should_save(of)) {
618 			/*
619 			 * Tell smb_ofile_release() to
620 			 * make this an _ORPHANED DH.
621 			 */
622 			of->f_state = SMB_OFILE_STATE_SAVE_DH;
623 			mutex_exit(&of->f_mutex);
624 			break;
625 		}
626 		/* OK close it. */
627 		mutex_exit(&of->f_mutex);
628 		smb_ofile_close(of, 0);
629 		break;
630 
631 	default:
632 		/* Something else closed it already. */
633 		mutex_exit(&of->f_mutex);
634 		break;
635 	}
636 
637 	/*
638 	 * Release the ref acquired during the traversal loop.
639 	 * Note that on the last ref, this ofile will be
640 	 * removed from the tree list etc.
641 	 * See: smb_llist_post, smb_ofile_delete
642 	 */
643 	smb_ofile_release(of);
644 }
645 
646 /*
647  * smb_ofile_close_all
648  *
649  *
650  */
651 void
652 smb_ofile_close_all(
653     smb_tree_t		*tree,
654     uint32_t		pid)
655 {
656 	smb_ofile_t	*of;
657 	smb_llist_t	*ll;
658 
659 	ASSERT(tree);
660 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
661 
662 	ll = &tree->t_ofile_list;
663 
664 	smb_llist_enter(ll, RW_READER);
665 	for (of = smb_llist_head(ll);
666 	    of != NULL;
667 	    of = smb_llist_next(ll, of)) {
668 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
669 		ASSERT(of->f_tree == tree);
670 		if (pid != 0 && of->f_opened_by_pid != pid)
671 			continue;
672 		if (smb_ofile_hold(of)) {
673 			smb_llist_post(ll, of, smb_ofile_drop);
674 		}
675 	}
676 
677 	/*
678 	 * Drop the lock and process the llist dtor queue.
679 	 * Calls smb_ofile_drop on ofiles that were open.
680 	 */
681 	smb_llist_exit(ll);
682 }
683 
684 /*
685  * If the enumeration request is for ofile data, handle it here.
686  * Otherwise, return.
687  *
688  * This function should be called with a hold on the ofile.
689  */
690 int
691 smb_ofile_enum(smb_ofile_t *of, smb_svcenum_t *svcenum)
692 {
693 	uint8_t *pb;
694 	uint_t nbytes;
695 	int rc;
696 
697 	ASSERT(of);
698 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
699 	ASSERT(of->f_refcnt);
700 
701 	if (svcenum->se_type != SMB_SVCENUM_TYPE_FILE)
702 		return (0);
703 
704 	if (svcenum->se_nskip > 0) {
705 		svcenum->se_nskip--;
706 		return (0);
707 	}
708 
709 	if (svcenum->se_nitems >= svcenum->se_nlimit) {
710 		svcenum->se_nitems = svcenum->se_nlimit;
711 		return (0);
712 	}
713 
714 	pb = &svcenum->se_buf[svcenum->se_bused];
715 
716 	rc = smb_ofile_netinfo_encode(of, pb, svcenum->se_bavail,
717 	    &nbytes);
718 	if (rc == 0) {
719 		svcenum->se_bavail -= nbytes;
720 		svcenum->se_bused += nbytes;
721 		svcenum->se_nitems++;
722 	}
723 
724 	return (rc);
725 }
726 
727 /*
728  * Take a reference on an open file, in any of the states:
729  *   RECONNECT, SAVE_DH, OPEN, ORPHANED.
730  * Return TRUE if ref taken.  Used for oplock breaks.
731  *
732  * Note: When the oplock break code calls this, it holds the
733  * node ofile list lock and node oplock mutex.  When we see
734  * an ofile in states RECONNECT or SAVING, we know the ofile
735  * is gaining or losing it's tree, and that happens quickly,
736  * so we just wait for that work to finish.  However, the
737  * waiting for state transitions here means we have to be
738  * careful not to re-enter the node list lock or otherwise
739  * block on things that could cause a deadlock.  Waiting
740  * just on of->f_mutex here is OK.
741  */
742 boolean_t
743 smb_ofile_hold_olbrk(smb_ofile_t *of)
744 {
745 	boolean_t ret = B_FALSE;
746 
747 	ASSERT(of);
748 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
749 
750 	mutex_enter(&of->f_mutex);
751 
752 again:
753 	switch (of->f_state) {
754 	case SMB_OFILE_STATE_RECONNECT:
755 	case SMB_OFILE_STATE_SAVING:
756 		cv_wait(&of->f_cv, &of->f_mutex);
757 		goto again;
758 
759 	case SMB_OFILE_STATE_OPEN:
760 	case SMB_OFILE_STATE_ORPHANED:
761 	case SMB_OFILE_STATE_SAVE_DH:
762 		of->f_refcnt++;
763 		ret = B_TRUE;
764 		break;
765 
766 	default:
767 		break;
768 	}
769 	mutex_exit(&of->f_mutex);
770 
771 	return (ret);
772 }
773 
774 /*
775  * Take a reference on an open file.
776  */
777 boolean_t
778 smb_ofile_hold(smb_ofile_t *of)
779 {
780 	ASSERT(of);
781 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
782 
783 	mutex_enter(&of->f_mutex);
784 
785 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
786 		mutex_exit(&of->f_mutex);
787 		return (B_FALSE);
788 	}
789 	of->f_refcnt++;
790 
791 	mutex_exit(&of->f_mutex);
792 	return (B_TRUE);
793 }
794 
795 /*
796  * Release a reference on a file.  If the reference count falls to
797  * zero and the file has been closed, post the object for deletion.
798  * Object deletion is deferred to avoid modifying a list while an
799  * iteration may be in progress.
800  *
801  * We're careful to avoid dropping f_session etc. until the last
802  * reference goes away.  The oplock break code depends on that
803  * not changing while it holds a ref. on an ofile.
804  */
805 void
806 smb_ofile_release(smb_ofile_t *of)
807 {
808 	smb_tree_t *tree = of->f_tree;
809 	boolean_t delete = B_FALSE;
810 
811 	SMB_OFILE_VALID(of);
812 
813 	mutex_enter(&of->f_mutex);
814 	ASSERT(of->f_refcnt > 0);
815 	of->f_refcnt--;
816 
817 	switch (of->f_state) {
818 	case SMB_OFILE_STATE_OPEN:
819 	case SMB_OFILE_STATE_ORPHANED:
820 	case SMB_OFILE_STATE_EXPIRED:
821 		break;
822 
823 	case SMB_OFILE_STATE_SAVE_DH:
824 		ASSERT(tree != NULL);
825 		if (of->f_refcnt == 0) {
826 			of->f_state = SMB_OFILE_STATE_SAVING;
827 			smb_llist_post(&tree->t_ofile_list, of,
828 			    smb_ofile_save_dh);
829 		}
830 		break;
831 
832 	case SMB_OFILE_STATE_CLOSING:
833 		/* Note, tree == NULL on _ORPHANED */
834 		if (of->f_refcnt == 0) {
835 			of->f_state = SMB_OFILE_STATE_CLOSED;
836 			if (tree == NULL) {
837 				/* Skip smb_llist_post */
838 				delete = B_TRUE;
839 				break;
840 			}
841 			smb_llist_post(&tree->t_ofile_list, of,
842 			    smb_ofile_delete);
843 		}
844 		break;
845 
846 	default:
847 		ASSERT(0);
848 		break;
849 	}
850 	mutex_exit(&of->f_mutex);
851 
852 	/*
853 	 * When we drop the last ref. on an expired DH, it's no longer
854 	 * in any tree, so skip the smb_llist_post and just call
855 	 * smb_ofile_delete directly.
856 	 */
857 	if (delete) {
858 		smb_ofile_delete(of);
859 	}
860 }
861 
862 /*
863  * smb_ofile_lookup_by_fid
864  *
865  * Find the open file whose fid matches the one specified in the request.
866  * If we can't find the fid or the shares (trees) don't match, we have a
867  * bad fid.
868  */
869 smb_ofile_t *
870 smb_ofile_lookup_by_fid(
871     smb_request_t	*sr,
872     uint16_t		fid)
873 {
874 	smb_tree_t	*tree = sr->tid_tree;
875 	smb_llist_t	*of_list;
876 	smb_ofile_t	*of;
877 
878 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
879 
880 	of_list = &tree->t_ofile_list;
881 
882 	smb_llist_enter(of_list, RW_READER);
883 	of = smb_llist_head(of_list);
884 	while (of) {
885 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
886 		ASSERT(of->f_tree == tree);
887 		if (of->f_fid == fid)
888 			break;
889 		of = smb_llist_next(of_list, of);
890 	}
891 	if (of == NULL)
892 		goto out;
893 
894 	/*
895 	 * Only allow use of a given FID with the same UID that
896 	 * was used to open it.  MS-CIFS 3.3.5.14
897 	 */
898 	if (of->f_user != sr->uid_user) {
899 		of = NULL;
900 		goto out;
901 	}
902 
903 	/* inline smb_ofile_hold() */
904 	mutex_enter(&of->f_mutex);
905 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
906 		mutex_exit(&of->f_mutex);
907 		of = NULL;
908 		goto out;
909 	}
910 	of->f_refcnt++;
911 	mutex_exit(&of->f_mutex);
912 
913 out:
914 	smb_llist_exit(of_list);
915 	return (of);
916 }
917 
918 /*
919  * smb_ofile_lookup_by_uniqid
920  *
921  * Find the open file whose uniqid matches the one specified in the request.
922  */
923 smb_ofile_t *
924 smb_ofile_lookup_by_uniqid(smb_tree_t *tree, uint32_t uniqid)
925 {
926 	smb_llist_t	*of_list;
927 	smb_ofile_t	*of;
928 
929 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
930 
931 	of_list = &tree->t_ofile_list;
932 	smb_llist_enter(of_list, RW_READER);
933 	of = smb_llist_head(of_list);
934 
935 	while (of) {
936 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
937 		ASSERT(of->f_tree == tree);
938 
939 		if (of->f_uniqid == uniqid) {
940 			if (smb_ofile_hold(of)) {
941 				smb_llist_exit(of_list);
942 				return (of);
943 			}
944 		}
945 
946 		of = smb_llist_next(of_list, of);
947 	}
948 
949 	smb_llist_exit(of_list);
950 	return (NULL);
951 }
952 
953 /*
954  * Durable ID (or persistent ID)
955  */
956 
957 static smb_ofile_t *
958 smb_ofile_hold_cb(smb_ofile_t *of)
959 {
960 	smb_ofile_t *ret = of;
961 
962 	mutex_enter(&of->f_mutex);
963 	if (of->f_state == SMB_OFILE_STATE_ORPHANED)
964 		/* inline smb_ofile_hold() */
965 		of->f_refcnt++;
966 	else
967 		ret = NULL;
968 
969 	mutex_exit(&of->f_mutex);
970 	return (ret);
971 }
972 
973 /*
974  * Lookup an ofile by persistent ID, and return ONLY if in state ORPHANED
975  * This is used by SMB2 create "reclaim".
976  */
977 smb_ofile_t *
978 smb_ofile_lookup_by_persistid(smb_request_t *sr, uint64_t persistid)
979 {
980 	smb_hash_t *hash;
981 	smb_bucket_t *bucket;
982 	smb_llist_t *ll;
983 	smb_ofile_t *of;
984 	uint_t idx;
985 
986 	if (persistid == 0)
987 		return (NULL);
988 
989 	hash = sr->sr_server->sv_persistid_ht;
990 	idx = smb_hash_uint64(hash, persistid);
991 	bucket = &hash->buckets[idx];
992 	ll = &bucket->b_list;
993 
994 	smb_llist_enter(ll, RW_READER);
995 	of = smb_llist_head(ll);
996 	while (of != NULL) {
997 		if (of->f_persistid == persistid)
998 			break;
999 		of = smb_llist_next(ll, of);
1000 	}
1001 	if (of != NULL)
1002 		of = smb_ofile_hold_cb(of);
1003 	smb_llist_exit(ll);
1004 
1005 	return (of);
1006 }
1007 
1008 /*
1009  * Create a (unique) durable/persistent ID for a new ofile,
1010  * and add this ofile to the persistid hash table.  This ID
1011  * is referred to as the persistent ID in the protocol spec,
1012  * so that's what we call it too, though the persistence may
1013  * vary.  "Durable" handles are persistent across reconnects
1014  * but not server reboots.  Persistent handles are persistent
1015  * across server reboots too.
1016  *
1017  * Note that persistent IDs need to be unique for the lifetime of
1018  * any given ofile.  For normal (non-persistent) ofiles we can just
1019  * use a persistent ID derived from the ofile memory address, as
1020  * these don't ever live beyond the current OS boot lifetime.
1021  *
1022  * Persistent handles are re-imported after server restart, and
1023  * generally have a different memory address after import than
1024  * they had in the previous OS boot lifetime, so for these we
1025  * use a randomly assigned value that won't conflict with any
1026  * non-persistent (durable) handles.  Ensuring that a randomly
1027  * generated ID is unique requires a search of the ofiles in one
1028  * hash bucket, which we'd rather avoid for non-persistent opens.
1029  *
1030  * The solution used here is to divide the persistent ID space
1031  * in half (odd and even values) where durable opens use an ID
1032  * derived from the ofile address (which is always even), and
1033  * persistent opens use an ID generated randomly (always odd).
1034  *
1035  * smb_ofile_set_persistid_dh() sets a durable handle ID and
1036  * smb_ofile_set_persistid_ph() sets a persistent handle ID.
1037  */
1038 void
1039 smb_ofile_set_persistid_dh(smb_ofile_t *of)
1040 {
1041 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1042 	smb_bucket_t *bucket;
1043 	smb_llist_t *ll;
1044 	uint64_t persistid;
1045 	uint_t idx;
1046 
1047 	persistid = (uintptr_t)of;
1048 	/* Avoid showing object addresses */
1049 	persistid ^= ((uintptr_t)&smb_cache_ofile);
1050 	/* make sure it's even */
1051 	persistid &= ~((uint64_t)1);
1052 
1053 	idx = smb_hash_uint64(hash, persistid);
1054 	bucket = &hash->buckets[idx];
1055 	ll = &bucket->b_list;
1056 	smb_llist_enter(ll, RW_WRITER);
1057 	if (of->f_persistid == 0) {
1058 		of->f_persistid = persistid;
1059 		smb_llist_insert_tail(ll, of);
1060 	}
1061 	smb_llist_exit(ll);
1062 }
1063 
1064 void
1065 smb_ofile_set_persistid_ph(smb_ofile_t *of)
1066 {
1067 	uint64_t persistid;
1068 	int rc;
1069 
1070 top:
1071 	(void) random_get_pseudo_bytes((uint8_t *)&persistid,
1072 	    sizeof (persistid));
1073 	if (persistid == 0) {
1074 		cmn_err(CE_NOTE, "random gave all zeros!");
1075 		goto top;
1076 	}
1077 	/* make sure it's odd */
1078 	persistid |= (uint64_t)1;
1079 
1080 	/*
1081 	 * Try inserting with this persistent ID.
1082 	 */
1083 	rc = smb_ofile_insert_persistid(of, persistid);
1084 	if (rc == EEXIST)
1085 		goto top;
1086 	if (rc != 0) {
1087 		cmn_err(CE_NOTE, "set persistid rc=%d", rc);
1088 	}
1089 }
1090 
1091 /*
1092  * Insert an ofile into the persistid hash table.
1093  * If the persistent ID is in use, error.
1094  */
1095 int
1096 smb_ofile_insert_persistid(smb_ofile_t *new_of, uint64_t persistid)
1097 {
1098 	smb_hash_t *hash = new_of->f_server->sv_persistid_ht;
1099 	smb_bucket_t *bucket;
1100 	smb_llist_t *ll;
1101 	smb_ofile_t *of;
1102 	uint_t idx;
1103 
1104 	ASSERT(persistid != 0);
1105 
1106 	/*
1107 	 * Look to see if this key alreay exists.
1108 	 */
1109 	idx = smb_hash_uint64(hash, persistid);
1110 	bucket = &hash->buckets[idx];
1111 	ll = &bucket->b_list;
1112 
1113 	smb_llist_enter(ll, RW_WRITER);
1114 	of = smb_llist_head(ll);
1115 	while (of != NULL) {
1116 		if (of->f_persistid == persistid) {
1117 			/* already in use */
1118 			smb_llist_exit(ll);
1119 			return (EEXIST);
1120 		}
1121 		of = smb_llist_next(ll, of);
1122 	}
1123 
1124 	/* Not found, so OK to insert. */
1125 	if (new_of->f_persistid == 0) {
1126 		new_of->f_persistid = persistid;
1127 		smb_llist_insert_tail(ll, new_of);
1128 	}
1129 	smb_llist_exit(ll);
1130 
1131 	return (0);
1132 }
1133 
1134 void
1135 smb_ofile_del_persistid(smb_ofile_t *of)
1136 {
1137 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1138 	smb_bucket_t *bucket;
1139 	smb_llist_t *ll;
1140 	uint_t idx;
1141 
1142 	idx = smb_hash_uint64(hash, of->f_persistid);
1143 	bucket = &hash->buckets[idx];
1144 	ll = &bucket->b_list;
1145 	smb_llist_enter(ll, RW_WRITER);
1146 	if (of->f_persistid != 0) {
1147 		smb_llist_remove(ll, of);
1148 		of->f_persistid = 0;
1149 	}
1150 	smb_llist_exit(ll);
1151 }
1152 
1153 /*
1154  * Disallow NetFileClose on certain ofiles to avoid side-effects.
1155  * Closing a tree root is not allowed: use NetSessionDel or NetShareDel.
1156  * Closing SRVSVC connections is not allowed because this NetFileClose
1157  * request may depend on this ofile.
1158  */
1159 boolean_t
1160 smb_ofile_disallow_fclose(smb_ofile_t *of)
1161 {
1162 	ASSERT(of);
1163 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1164 	ASSERT(of->f_refcnt);
1165 
1166 	switch (of->f_ftype) {
1167 	case SMB_FTYPE_DISK:
1168 		ASSERT(of->f_tree);
1169 		return (of->f_node == of->f_tree->t_snode);
1170 
1171 	case SMB_FTYPE_MESG_PIPE:
1172 		ASSERT(of->f_pipe);
1173 		if (smb_strcasecmp(of->f_pipe->p_name, "SRVSVC", 0) == 0)
1174 			return (B_TRUE);
1175 		break;
1176 	default:
1177 		break;
1178 	}
1179 
1180 	return (B_FALSE);
1181 }
1182 
1183 /*
1184  * smb_ofile_set_flags
1185  *
1186  * Return value:
1187  *
1188  *	Current flags value
1189  *
1190  */
1191 void
1192 smb_ofile_set_flags(
1193     smb_ofile_t		*of,
1194     uint32_t		flags)
1195 {
1196 	ASSERT(of);
1197 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1198 	ASSERT(of->f_refcnt);
1199 
1200 	mutex_enter(&of->f_mutex);
1201 	of->f_flags |= flags;
1202 	mutex_exit(&of->f_mutex);
1203 }
1204 
1205 /*
1206  * smb_ofile_seek
1207  *
1208  * Return value:
1209  *
1210  *	0		Success
1211  *	EINVAL		Unknown mode
1212  *	EOVERFLOW	offset too big
1213  *
1214  */
1215 int
1216 smb_ofile_seek(
1217     smb_ofile_t		*of,
1218     ushort_t		mode,
1219     int32_t		off,
1220     uint32_t		*retoff)
1221 {
1222 	u_offset_t	newoff = 0;
1223 	int		rc = 0;
1224 	smb_attr_t	attr;
1225 
1226 	ASSERT(of);
1227 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1228 	ASSERT(of->f_refcnt);
1229 
1230 	mutex_enter(&of->f_mutex);
1231 	switch (mode) {
1232 	case SMB_SEEK_SET:
1233 		if (off < 0)
1234 			newoff = 0;
1235 		else
1236 			newoff = (u_offset_t)off;
1237 		break;
1238 
1239 	case SMB_SEEK_CUR:
1240 		if (off < 0 && (-off) > of->f_seek_pos)
1241 			newoff = 0;
1242 		else
1243 			newoff = of->f_seek_pos + (u_offset_t)off;
1244 		break;
1245 
1246 	case SMB_SEEK_END:
1247 		bzero(&attr, sizeof (smb_attr_t));
1248 		attr.sa_mask |= SMB_AT_SIZE;
1249 		rc = smb_fsop_getattr(NULL, zone_kcred(), of->f_node, &attr);
1250 		if (rc != 0) {
1251 			mutex_exit(&of->f_mutex);
1252 			return (rc);
1253 		}
1254 		if (off < 0 && (-off) > attr.sa_vattr.va_size)
1255 			newoff = 0;
1256 		else
1257 			newoff = attr.sa_vattr.va_size + (u_offset_t)off;
1258 		break;
1259 
1260 	default:
1261 		mutex_exit(&of->f_mutex);
1262 		return (EINVAL);
1263 	}
1264 
1265 	/*
1266 	 * See comments at the beginning of smb_seek.c.
1267 	 * If the offset is greater than UINT_MAX, we will return an error.
1268 	 */
1269 
1270 	if (newoff > UINT_MAX) {
1271 		rc = EOVERFLOW;
1272 	} else {
1273 		of->f_seek_pos = newoff;
1274 		*retoff = (uint32_t)newoff;
1275 	}
1276 	mutex_exit(&of->f_mutex);
1277 	return (rc);
1278 }
1279 
1280 /*
1281  * smb_ofile_flush
1282  *
1283  * If writes on this file are not synchronous, flush it using the NFSv3
1284  * commit interface.
1285  *
1286  * XXX - todo: Flush named pipe should drain writes.
1287  */
1288 void
1289 smb_ofile_flush(struct smb_request *sr, struct smb_ofile *of)
1290 {
1291 	switch (of->f_ftype) {
1292 	case SMB_FTYPE_DISK:
1293 		if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
1294 			(void) smb_fsop_commit(sr, of->f_cr, of->f_node);
1295 		break;
1296 	default:
1297 		break;
1298 	}
1299 }
1300 
1301 /*
1302  * smb_ofile_is_open
1303  */
1304 boolean_t
1305 smb_ofile_is_open(smb_ofile_t *of)
1306 {
1307 	boolean_t	rc;
1308 
1309 	SMB_OFILE_VALID(of);
1310 
1311 	mutex_enter(&of->f_mutex);
1312 	rc = smb_ofile_is_open_locked(of);
1313 	mutex_exit(&of->f_mutex);
1314 	return (rc);
1315 }
1316 
1317 /* *************************** Static Functions ***************************** */
1318 
1319 /*
1320  * Determine whether or not an ofile is open.
1321  * This function must be called with the mutex held.
1322  */
1323 static boolean_t
1324 smb_ofile_is_open_locked(smb_ofile_t *of)
1325 {
1326 	ASSERT(MUTEX_HELD(&of->f_mutex));
1327 
1328 	switch (of->f_state) {
1329 	case SMB_OFILE_STATE_OPEN:
1330 	case SMB_OFILE_STATE_SAVE_DH:
1331 	case SMB_OFILE_STATE_SAVING:
1332 	case SMB_OFILE_STATE_ORPHANED:
1333 	case SMB_OFILE_STATE_RECONNECT:
1334 		return (B_TRUE);
1335 
1336 	case SMB_OFILE_STATE_CLOSING:
1337 	case SMB_OFILE_STATE_CLOSED:
1338 	case SMB_OFILE_STATE_EXPIRED:
1339 		return (B_FALSE);
1340 
1341 	default:
1342 		ASSERT(0);
1343 		return (B_FALSE);
1344 	}
1345 }
1346 
1347 /*
1348  * smb_ofile_save_dh
1349  *
1350  * Called via smb_llist_post (after smb_llist_exit) when the last ref.
1351  * on this ofile has gone, and this ofile is a "durable handle" (DH)
1352  * that has state we've decided to save.
1353  *
1354  * This does parts of what smb_ofile_delete would do, including:
1355  * remove the ofile from the tree ofile list and related.
1356  *
1357  * We leave the ofile in state ORPHANED, ready for reconnect
1358  * or expiration via smb2_dh_expire (see smb_ofile_delete).
1359  */
1360 static void
1361 smb_ofile_save_dh(void *arg)
1362 {
1363 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1364 	smb_tree_t	*tree = of->f_tree;
1365 
1366 	SMB_OFILE_VALID(of);
1367 	ASSERT(of->f_refcnt == 0);
1368 	ASSERT(of->f_ftype == SMB_FTYPE_DISK);
1369 	ASSERT(of->f_state == SMB_OFILE_STATE_SAVING);
1370 
1371 	atomic_dec_32(&of->f_session->s_file_cnt);
1372 	atomic_dec_32(&of->f_tree->t_open_files);
1373 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1374 	smb_llist_remove(&tree->t_ofile_list, of);
1375 	smb_llist_exit(&tree->t_ofile_list);
1376 
1377 	/*
1378 	 * This ofile is no longer on t_ofile_list, however...
1379 	 *
1380 	 * This is called via smb_llist_post, which means it may run
1381 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1382 	 * flushes the delete queue before we do).  Synchronize.
1383 	 */
1384 	mutex_enter(&of->f_mutex);
1385 	DTRACE_PROBE1(ofile__exit, smb_ofile_t, of);
1386 	mutex_exit(&of->f_mutex);
1387 
1388 	/*
1389 	 * Keep f_notify state, lease, and
1390 	 * keep on node ofile list.
1391 	 * Keep of->f_cr until reclaim.
1392 	 */
1393 
1394 	ASSERT(of->f_fid != 0);
1395 	smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1396 	of->f_fid = 0;
1397 	smb_tree_release(of->f_tree);
1398 	of->f_tree = NULL;
1399 	smb_user_release(of->f_user);
1400 	of->f_user = NULL;
1401 	of->f_session = NULL;
1402 
1403 	/*
1404 	 * Make it "orphaned" so it can now be reclaimed.
1405 	 * Note that smb_ofile_hold_olbrk() may have blocked
1406 	 * for state SMB_OFILE_STATE_SAVING, so wake it.
1407 	 */
1408 	mutex_enter(&of->f_mutex);
1409 	of->dh_expire_time = gethrtime() + of->dh_timeout_offset;
1410 	of->f_state = SMB_OFILE_STATE_ORPHANED;
1411 	cv_broadcast(&of->f_cv);
1412 	mutex_exit(&of->f_mutex);
1413 }
1414 
1415 /*
1416  * Delete an ofile.
1417  *
1418  * Approximately the inverse of smb_ofile_alloc()
1419  * Called via smb_llist_post (after smb_llist_exit)
1420  * when the last ref. on this ofile has gone.
1421  *
1422  * Normally,this removes the ofile from the tree list and
1423  * then frees resources held on the ofile.  However, when
1424  * we're expiring an orphaned durable handle, the linkage
1425  * into the tree lists etc. have already been destroyed.
1426  * This case is distinguished by of->f_tree == NULL.
1427  */
1428 static void
1429 smb_ofile_delete(void *arg)
1430 {
1431 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1432 	smb_tree_t	*tree = of->f_tree;
1433 
1434 	SMB_OFILE_VALID(of);
1435 	ASSERT(of->f_refcnt == 0);
1436 	ASSERT(of->f_state == SMB_OFILE_STATE_CLOSED);
1437 
1438 	if (tree != NULL) {
1439 		ASSERT(of->f_user != NULL);
1440 		ASSERT(of->f_session != NULL);
1441 		atomic_dec_32(&of->f_session->s_file_cnt);
1442 		atomic_dec_32(&of->f_tree->t_open_files);
1443 		smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1444 		smb_llist_remove(&tree->t_ofile_list, of);
1445 		smb_llist_exit(&tree->t_ofile_list);
1446 	}
1447 
1448 	/*
1449 	 * Remove this ofile from the node's n_ofile_list so it
1450 	 * can't be found by list walkers like notify or oplock.
1451 	 * Keep the node ref. until later in this function so
1452 	 * of->f_node remains valid while we destroy the ofile.
1453 	 */
1454 	if (of->f_ftype == SMB_FTYPE_DISK ||
1455 	    of->f_ftype == SMB_FTYPE_PRINTER) {
1456 		smb_node_t *node = of->f_node;
1457 
1458 		/*
1459 		 * Oplock cleanup should have made sure that
1460 		 * excl_open does not point to this ofile.
1461 		 */
1462 		VERIFY(node->n_oplock.excl_open != of);
1463 
1464 		/*
1465 		 * Note smb_ofile_close did smb_node_dec_open_ofiles()
1466 		 */
1467 		smb_node_rem_ofile(node, of);
1468 	}
1469 
1470 	/*
1471 	 * This ofile is no longer on any lists, however...
1472 	 *
1473 	 * This is called via smb_llist_post, which means it may run
1474 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1475 	 * flushes the delete queue before we do).  Synchronize.
1476 	 */
1477 	mutex_enter(&of->f_mutex);
1478 	of->f_state = SMB_OFILE_STATE_ALLOC;
1479 	DTRACE_PROBE1(ofile__exit, smb_ofile_t, of);
1480 	mutex_exit(&of->f_mutex);
1481 
1482 	switch (of->f_ftype) {
1483 	case SMB_FTYPE_BYTE_PIPE:
1484 	case SMB_FTYPE_MESG_PIPE:
1485 		smb_opipe_dealloc(of->f_pipe);
1486 		of->f_pipe = NULL;
1487 		break;
1488 	case SMB_FTYPE_DISK:
1489 		ASSERT(of->f_notify.nc_subscribed == B_FALSE);
1490 		MBC_FLUSH(&of->f_notify.nc_buffer);
1491 		if (of->f_odir != NULL)
1492 			smb_odir_release(of->f_odir);
1493 		if (of->f_lease != NULL) {
1494 			smb2_lease_rele(of->f_lease);
1495 			of->f_lease = NULL;
1496 		}
1497 		/* FALLTHROUGH */
1498 	case SMB_FTYPE_PRINTER:
1499 		/*
1500 		 * Did smb_node_rem_ofile above.
1501 		 */
1502 		ASSERT(of->f_node != NULL);
1503 		smb_node_release(of->f_node);
1504 		break;
1505 	default:
1506 		ASSERT(!"f_ftype");
1507 		break;
1508 	}
1509 
1510 	smb_ofile_free(of);
1511 }
1512 
1513 void
1514 smb_ofile_free(smb_ofile_t *of)
1515 {
1516 	smb_tree_t	*tree = of->f_tree;
1517 
1518 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
1519 
1520 	/* Make sure it's not in the persistid hash. */
1521 	ASSERT(of->f_persistid == 0);
1522 
1523 	if (tree != NULL) {
1524 		if (of->f_fid != 0)
1525 			smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1526 		smb_tree_release(of->f_tree);
1527 		smb_user_release(of->f_user);
1528 	}
1529 
1530 	if (of->f_cr != NULL)
1531 		crfree(of->f_cr);
1532 
1533 	of->f_magic = (uint32_t)~SMB_OFILE_MAGIC;
1534 	list_destroy(&of->f_notify.nc_waiters);
1535 	mutex_destroy(&of->dh_nvlock);
1536 	mutex_destroy(&of->f_mutex);
1537 	kmem_cache_free(smb_cache_ofile, of);
1538 }
1539 
1540 /*
1541  * smb_ofile_access
1542  *
1543  * This function will check to see if the access requested is granted.
1544  * Returns NT status codes.
1545  */
1546 uint32_t
1547 smb_ofile_access(smb_ofile_t *of, cred_t *cr, uint32_t access)
1548 {
1549 
1550 	if ((of == NULL) || (cr == zone_kcred()))
1551 		return (NT_STATUS_SUCCESS);
1552 
1553 	/*
1554 	 * If the request is for something
1555 	 * I don't grant it is an error
1556 	 */
1557 	if (~(of->f_granted_access) & access) {
1558 		if (!(of->f_granted_access & ACCESS_SYSTEM_SECURITY) &&
1559 		    (access & ACCESS_SYSTEM_SECURITY)) {
1560 			return (NT_STATUS_PRIVILEGE_NOT_HELD);
1561 		}
1562 		return (NT_STATUS_ACCESS_DENIED);
1563 	}
1564 
1565 	return (NT_STATUS_SUCCESS);
1566 }
1567 
1568 /*
1569  * smb_ofile_share_check
1570  *
1571  * Check if ofile was opened with share access NONE (0).
1572  * Returns: B_TRUE  - share access non-zero
1573  *          B_FALSE - share access NONE
1574  */
1575 boolean_t
1576 smb_ofile_share_check(smb_ofile_t *of)
1577 {
1578 	return (!SMB_DENY_ALL(of->f_share_access));
1579 }
1580 
1581 /*
1582  * check file sharing rules for current open request
1583  * against existing open instances of the same file
1584  *
1585  * Returns NT_STATUS_SHARING_VIOLATION if there is any
1586  * sharing conflict, otherwise returns NT_STATUS_SUCCESS.
1587  */
1588 uint32_t
1589 smb_ofile_open_check(smb_ofile_t *of, uint32_t desired_access,
1590     uint32_t share_access)
1591 {
1592 	uint32_t ret;
1593 
1594 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1595 
1596 	mutex_enter(&of->f_mutex);
1597 
1598 	if (!smb_ofile_is_open_locked(of)) {
1599 		ret = NT_STATUS_INVALID_HANDLE;
1600 		goto out;
1601 	}
1602 
1603 	/* if it's just meta data */
1604 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1605 		ret = NT_STATUS_SUCCESS;
1606 		goto out;
1607 	}
1608 
1609 	/*
1610 	 * Check requested share access against the
1611 	 * open granted (desired) access
1612 	 */
1613 	if (SMB_DENY_DELETE(share_access) && (of->f_granted_access & DELETE)) {
1614 		ret = NT_STATUS_SHARING_VIOLATION;
1615 		goto out;
1616 	}
1617 
1618 	if (SMB_DENY_READ(share_access) &&
1619 	    (of->f_granted_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1620 		ret = NT_STATUS_SHARING_VIOLATION;
1621 		goto out;
1622 	}
1623 
1624 	if (SMB_DENY_WRITE(share_access) &&
1625 	    (of->f_granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1626 		ret = NT_STATUS_SHARING_VIOLATION;
1627 		goto out;
1628 	}
1629 
1630 	/* check requested desired access against the open share access */
1631 	if (SMB_DENY_DELETE(of->f_share_access) && (desired_access & DELETE)) {
1632 		ret = NT_STATUS_SHARING_VIOLATION;
1633 		goto out;
1634 	}
1635 
1636 	if (SMB_DENY_READ(of->f_share_access) &&
1637 	    (desired_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1638 		ret = NT_STATUS_SHARING_VIOLATION;
1639 		goto out;
1640 	}
1641 
1642 	if (SMB_DENY_WRITE(of->f_share_access) &&
1643 	    (desired_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1644 		ret = NT_STATUS_SHARING_VIOLATION;
1645 		goto out;
1646 	}
1647 
1648 	ret = NT_STATUS_SUCCESS;
1649 out:
1650 	mutex_exit(&of->f_mutex);
1651 	return (ret);
1652 }
1653 
1654 /*
1655  * smb_ofile_rename_check
1656  *
1657  * This does the work described in MS-FSA 2.1.5.1.2.2 (Algorithm
1658  * to Check Sharing Access to an Existing Stream or Directory),
1659  * where the "open in-progress" has DesiredAccess = DELETE and
1660  * SharingMode = SHARE_READ | SHARE_WRITE | SHARE_DELETE.
1661  */
1662 
1663 uint32_t
1664 smb_ofile_rename_check(smb_ofile_t *of)
1665 {
1666 	uint32_t ret;
1667 
1668 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1669 
1670 	mutex_enter(&of->f_mutex);
1671 
1672 	if (!smb_ofile_is_open_locked(of)) {
1673 		ret = NT_STATUS_INVALID_HANDLE;
1674 		goto out;
1675 	}
1676 
1677 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1678 		ret = NT_STATUS_SUCCESS;
1679 		goto out;
1680 	}
1681 
1682 	if ((of->f_share_access & FILE_SHARE_DELETE) == 0) {
1683 		ret = NT_STATUS_SHARING_VIOLATION;
1684 		goto out;
1685 	}
1686 
1687 	ret = NT_STATUS_SUCCESS;
1688 out:
1689 	mutex_exit(&of->f_mutex);
1690 	return (ret);
1691 }
1692 
1693 /*
1694  * smb_ofile_delete_check
1695  *
1696  * An open file can be deleted only if opened for
1697  * accessing meta data. Share modes aren't important
1698  * in this case.
1699  *
1700  * NOTE: there is another mechanism for deleting an
1701  * open file that NT clients usually use.
1702  * That's setting "Delete on close" flag for an open
1703  * file.  In this way the file will be deleted after
1704  * last close. This flag can be set by SmbTrans2SetFileInfo
1705  * with FILE_DISPOSITION_INFO information level.
1706  * For setting this flag, the file should be opened by
1707  * DELETE access in the FID that is passed in the Trans2
1708  * request.
1709  */
1710 
1711 uint32_t
1712 smb_ofile_delete_check(smb_ofile_t *of)
1713 {
1714 	uint32_t ret;
1715 
1716 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1717 
1718 	mutex_enter(&of->f_mutex);
1719 
1720 	if (!smb_ofile_is_open_locked(of)) {
1721 		ret = NT_STATUS_INVALID_HANDLE;
1722 		goto out;
1723 	}
1724 
1725 	if (of->f_granted_access &
1726 	    (FILE_READ_DATA | FILE_WRITE_DATA |
1727 	    FILE_APPEND_DATA | FILE_EXECUTE | DELETE)) {
1728 		ret = NT_STATUS_SHARING_VIOLATION;
1729 		goto out;
1730 	}
1731 
1732 	ret = NT_STATUS_SUCCESS;
1733 out:
1734 	mutex_exit(&of->f_mutex);
1735 	return (ret);
1736 }
1737 
1738 cred_t *
1739 smb_ofile_getcred(smb_ofile_t *of)
1740 {
1741 	return (of->f_cr);
1742 }
1743 
1744 /*
1745  * smb_ofile_set_delete_on_close
1746  *
1747  * Set the DeleteOnClose flag on the smb file. When the file is closed,
1748  * the flag will be transferred to the smb node, which will commit the
1749  * delete operation and inhibit subsequent open requests.
1750  *
1751  * When DeleteOnClose is set on an smb_node, the common open code will
1752  * reject subsequent open requests for the file. Observation of Windows
1753  * 2000 indicates that subsequent opens should be allowed (assuming
1754  * there would be no sharing violation) until the file is closed using
1755  * the fid on which the DeleteOnClose was requested.
1756  */
1757 void
1758 smb_ofile_set_delete_on_close(smb_request_t *sr, smb_ofile_t *of)
1759 {
1760 	uint32_t	status;
1761 
1762 	/*
1763 	 * Break any oplock handle caching.
1764 	 */
1765 	status = smb_oplock_break_SETINFO(of->f_node, of,
1766 	    FileDispositionInformation);
1767 	if (status == NT_STATUS_OPLOCK_BREAK_IN_PROGRESS) {
1768 		if (sr->session->dialect >= SMB_VERS_2_BASE)
1769 			(void) smb2sr_go_async(sr);
1770 		(void) smb_oplock_wait_break(of->f_node, 0);
1771 	}
1772 
1773 	mutex_enter(&of->f_mutex);
1774 	of->f_flags |= SMB_OFLAGS_SET_DELETE_ON_CLOSE;
1775 	mutex_exit(&of->f_mutex);
1776 }
1777 
1778 /*
1779  * Encode open file information into a buffer; needed in user space to
1780  * support RPC requests.
1781  */
1782 static int
1783 smb_ofile_netinfo_encode(smb_ofile_t *of, uint8_t *buf, size_t buflen,
1784     uint32_t *nbytes)
1785 {
1786 	smb_netfileinfo_t	fi;
1787 	int			rc;
1788 
1789 	rc = smb_ofile_netinfo_init(of, &fi);
1790 	if (rc == 0) {
1791 		rc = smb_netfileinfo_encode(&fi, buf, buflen, nbytes);
1792 		smb_ofile_netinfo_fini(&fi);
1793 	}
1794 
1795 	return (rc);
1796 }
1797 
1798 static int
1799 smb_ofile_netinfo_init(smb_ofile_t *of, smb_netfileinfo_t *fi)
1800 {
1801 	smb_user_t	*user;
1802 	smb_tree_t	*tree;
1803 	smb_node_t	*node;
1804 	char		*path;
1805 	char		*buf;
1806 	int		rc;
1807 
1808 	ASSERT(of);
1809 	user = of->f_user;
1810 	tree = of->f_tree;
1811 	ASSERT(user);
1812 	ASSERT(tree);
1813 
1814 	buf = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1815 
1816 	switch (of->f_ftype) {
1817 	case SMB_FTYPE_DISK:
1818 		node = of->f_node;
1819 		ASSERT(node);
1820 
1821 		fi->fi_permissions = of->f_granted_access;
1822 		fi->fi_numlocks = smb_lock_get_lock_count(node, of);
1823 
1824 		path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1825 
1826 		if (node != tree->t_snode) {
1827 			rc = smb_node_getshrpath(node, tree, path, MAXPATHLEN);
1828 			if (rc != 0)
1829 				(void) strlcpy(path, node->od_name, MAXPATHLEN);
1830 		}
1831 
1832 		(void) snprintf(buf, MAXPATHLEN, "%s:%s", tree->t_sharename,
1833 		    path);
1834 		kmem_free(path, MAXPATHLEN);
1835 		break;
1836 
1837 	case SMB_FTYPE_MESG_PIPE:
1838 		ASSERT(of->f_pipe);
1839 
1840 		fi->fi_permissions = FILE_READ_DATA | FILE_WRITE_DATA |
1841 		    FILE_EXECUTE;
1842 		fi->fi_numlocks = 0;
1843 		(void) snprintf(buf, MAXPATHLEN, "\\PIPE\\%s",
1844 		    of->f_pipe->p_name);
1845 		break;
1846 
1847 	default:
1848 		kmem_free(buf, MAXPATHLEN);
1849 		return (-1);
1850 	}
1851 
1852 	fi->fi_fid = of->f_fid;
1853 	fi->fi_uniqid = of->f_uniqid;
1854 	fi->fi_pathlen = strlen(buf) + 1;
1855 	fi->fi_path = smb_mem_strdup(buf);
1856 	kmem_free(buf, MAXPATHLEN);
1857 
1858 	fi->fi_namelen = user->u_domain_len + user->u_name_len + 2;
1859 	fi->fi_username = kmem_alloc(fi->fi_namelen, KM_SLEEP);
1860 	(void) snprintf(fi->fi_username, fi->fi_namelen, "%s\\%s",
1861 	    user->u_domain, user->u_name);
1862 	return (0);
1863 }
1864 
1865 static void
1866 smb_ofile_netinfo_fini(smb_netfileinfo_t *fi)
1867 {
1868 	if (fi == NULL)
1869 		return;
1870 
1871 	if (fi->fi_path)
1872 		smb_mem_free(fi->fi_path);
1873 	if (fi->fi_username)
1874 		kmem_free(fi->fi_username, fi->fi_namelen);
1875 
1876 	bzero(fi, sizeof (smb_netfileinfo_t));
1877 }
1878 
1879 /*
1880  * A query of user and group quotas may span multiple requests.
1881  * f_quota_resume is used to determine where the query should
1882  * be resumed, in a subsequent request. f_quota_resume contains
1883  * the SID of the last quota entry returned to the client.
1884  */
1885 void
1886 smb_ofile_set_quota_resume(smb_ofile_t *ofile, char *resume)
1887 {
1888 	ASSERT(ofile);
1889 	mutex_enter(&ofile->f_mutex);
1890 	if (resume == NULL)
1891 		bzero(ofile->f_quota_resume, SMB_SID_STRSZ);
1892 	else
1893 		(void) strlcpy(ofile->f_quota_resume, resume, SMB_SID_STRSZ);
1894 	mutex_exit(&ofile->f_mutex);
1895 }
1896 
1897 void
1898 smb_ofile_get_quota_resume(smb_ofile_t *ofile, char *buf, int bufsize)
1899 {
1900 	ASSERT(ofile);
1901 	mutex_enter(&ofile->f_mutex);
1902 	(void) strlcpy(buf, ofile->f_quota_resume, bufsize);
1903 	mutex_exit(&ofile->f_mutex);
1904 }
1905