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