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 2018 Nexenta Systems, Inc.  All rights reserved.
26  */
27 
28 /*
29  * General Structures Layout
30  * -------------------------
31  *
32  * This is a simplified diagram showing the relationship between most of the
33  * main structures.
34  *
35  * +-------------------+
36  * |     SMB_INFO      |
37  * +-------------------+
38  *          |
39  *          |
40  *          v
41  * +-------------------+       +-------------------+      +-------------------+
42  * |     SESSION       |<----->|     SESSION       |......|      SESSION      |
43  * +-------------------+       +-------------------+      +-------------------+
44  *   |          |
45  *   |          |
46  *   |          v
47  *   |  +-------------------+     +-------------------+   +-------------------+
48  *   |  |       USER        |<--->|       USER        |...|       USER        |
49  *   |  +-------------------+     +-------------------+   +-------------------+
50  *   |
51  *   |
52  *   v
53  * +-------------------+       +-------------------+      +-------------------+
54  * |       TREE        |<----->|       TREE        |......|       TREE        |
55  * +-------------------+       +-------------------+      +-------------------+
56  *      |         |
57  *      |         |
58  *      |         v
59  *      |     +-------+       +-------+      +-------+
60  *      |     | OFILE |<----->| OFILE |......| OFILE |
61  *      |     +-------+       +-------+      +-------+
62  *      |
63  *      |
64  *      v
65  *  +-------+       +------+      +------+
66  *  | ODIR  |<----->| ODIR |......| ODIR |
67  *  +-------+       +------+      +------+
68  *
69  *
70  * Ofile State Machine
71  * ------------------
72  *
73  *    +-------------------------+	 T0
74  *    |  SMB_OFILE_STATE_OPEN   |<--+-------- Creation/Allocation
75  *    +-------------------------+   |
76  *	    |		|	    | T5
77  *	    |		|	+---------------------------+
78  *	    |		|	| SMB_OFILE_STATE_RECONNECT |
79  *	    |		|	+---------------------------+
80  *	    |		|	    ^
81  *	    |		v	    |
82  *	    |   +---------------+   |
83  *	    |   | STATE_SAVE_DH |   |
84  *	    |   | STATE_SAVING  |   |
85  *	    |   +---------------+   |
86  *	    |		|	    | T4
87  *	    | T1	| T3	+--------------------------+
88  *	    |		+------>| SMB_OFILE_STATE_ORPHANED |
89  *	    v			+--------------------------+
90  *    +-------------------------+   |		|
91  *    | SMB_OFILE_STATE_CLOSING |<--+ T6	| T7
92  *    +-------------------------+		|
93  *	    |		^			v
94  *	    | T2	| T8	+-------------------------+
95  *	    |		+-------| SMB_OFILE_STATE_EXPIRED |
96  *	    v			+-------------------------+
97  *    +-------------------------+
98  *    | SMB_OFILE_STATE_CLOSED  |----------> Deletion/Free
99  *    +-------------------------+    T9
100  *
101  * SMB_OFILE_STATE_OPEN
102  *
103  *    While in this state:
104  *      - The ofile is queued in the list of ofiles of its tree.
105  *      - References will be given out if the ofile is looked up.
106  *
107  * SMB_OFILE_STATE_SAVE_DH
108  *
109  *    Similar to state _CLOSING, but instead of deleting the ofile,
110  *    it leaves the ofile in state _ORPHANED (for later reclaim).
111  *    Will move to _SAVING after last ref, then _ORPHANED.
112  *
113  *    While in this state:
114  *	- The ofile has been marked for preservation during a
115  *	  walk of the tree ofile list to close multiple files.
116  *	- References will not be given out if the ofile is looked up,
117  *	  except for oplock break processing.
118  *	- Still affects Sharing Violation rules
119  *
120  * SMB_OFILE_STATE_SAVING
121  *
122  *    Transient state used to keep oplock break processing out
123  *    while the ofile moves to state _ORPHANED.
124  *
125  *    While in this state:
126  *	- References will not be given out if the ofile is looked up,
127  *	  except for oplock break processing.
128  *	- Still affects Sharing Violation rules
129  *
130  * SMB_OFILE_STATE_CLOSING
131  *
132  *    Close has been requested.  Stay in this state until the last
133  *    ref. is gone, then move to state _CLOSED
134  *
135  *    While in this state:
136  *      - The ofile is queued in the list of ofiles of its tree.
137  *      - References will not be given out if the ofile is looked up.
138  *      - The file is closed and the locks held are being released.
139  *      - The resources associated with the ofile remain.
140  *
141  * SMB_OFILE_STATE_CLOSED
142  *
143  *    While in this state:
144  *      - The ofile is queued in the list of ofiles of its tree.
145  *      - References will not be given out if the ofile is looked up.
146  *      - The resources associated with the ofile remain.
147  *
148  * SMB_OFILE_STATE_ORPHANED
149  *
150  *    While in this state:
151  *      - The ofile is queued in the list of ofiles of its tree.
152  *      - Can be reclaimed by the original owner
153  *      - References will not be given out if the ofile is looked up.
154  *      - All the tree, user, and session "up" pointers are NULL!
155  *      - Will eventually be "expired" if not reclaimed
156  *      - Can be closed if its oplock is broken
157  *      - Still affects Sharing Violation rules
158  *
159  * SMB_OFILE_STATE_EXPIRED
160  *
161  *    While in this state:
162  *      - The ofile is queued in the list of ofiles of its tree.
163  *      - References will not be given out if the ofile is looked up.
164  *      - The ofile has not been reclaimed and will soon be closed,
165  *        due to, for example, the durable handle timer expiring, or its
166  *        oplock being broken.
167  *      - Cannot be reclaimed at this point
168  *
169  * SMB_OFILE_STATE_RECONNECT
170  *
171  *    Transient state used to keep oplock break processing out
172  *    while the ofile moves from state _ORPHANED to _OPEN.
173  *
174  *    While in this state:
175  *      - The ofile is being reclaimed; do not touch it.
176  *      - References will not be given out if the ofile is looked up.
177  *      - Still affects Sharing Violation rules
178  *	- see smb2_dh_reconnect() for which members need to be avoided
179  *
180  * Transition T0
181  *
182  *    This transition occurs in smb_ofile_open(). A new ofile is created and
183  *    added to the list of ofiles of a tree.
184  *
185  * Transition T1
186  *
187  *    This transition occurs in smb_ofile_close(). Note that this only happens
188  *    when we determine that an ofile should be closed in spite of its durable
189  *    handle properties.
190  *
191  * Transition T2
192  *
193  *    This transition occurs in smb_ofile_release(). The resources associated
194  *    with the ofile are freed as well as the ofile structure. For the
195  *    transition to occur, the ofile must be in the SMB_OFILE_STATE_CLOSED
196  *    state and the reference count be zero.
197  *
198  * Transition T3
199  *
200  *    This transition occurs in smb_ofile_orphan_dh(). It happens during an
201  *    smb2 logoff, or during a session disconnect when certain conditions are
202  *    met. The ofile and structures above it will be kept around until the ofile
203  *    either gets reclaimed, expires after f_timeout_offset nanoseconds, or its
204  *    oplock is broken.
205  *
206  * Transition T4
207  *
208  *    This transition occurs in smb2_dh_reconnect(). An smb2 create request
209  *    with a DURABLE_HANDLE_RECONNECT(_V2) create context has been
210  *    recieved from the original owner. If leases are supported or it's
211  *    RECONNECT_V2, reconnect is subject to additional conditions. The ofile
212  *    will be unwired from the old, disconnected session, tree, and user,
213  *    and wired up to its new context.
214  *
215  * Transition T5
216  *
217  *    This transition occurs in smb2_dh_reconnect(). The ofile has been
218  *    successfully reclaimed.
219  *
220  * Transition T6
221  *
222  *    This transition occurs in smb_ofile_close(). The ofile has been orphaned
223  *    while some thread was blocked, and that thread closes the ofile. Can only
224  *    happen when the ofile is orphaned due to an SMB2 LOGOFF request.
225  *
226  * Transition T7
227  *
228  *    This transition occurs in smb_session_durable_timers() and
229  *    smb_oplock_send_brk(). The ofile will soon be closed.
230  *    In the former case, f_timeout_offset nanoseconds have passed since
231  *    the ofile was orphaned. In the latter, an oplock break occured
232  *    on the ofile while it was orphaned.
233  *
234  * Transition T8
235  *
236  *    This transition occurs in smb_ofile_close().
237  *
238  * Transition T9
239  *
240  *    This transition occurs in smb_ofile_delete().
241  *
242  * Comments
243  * --------
244  *
245  *    The state machine of the ofile structures is controlled by 3 elements:
246  *      - The list of ofiles of the tree it belongs to.
247  *      - The mutex embedded in the structure itself.
248  *      - The reference count.
249  *
250  *    There's a mutex embedded in the ofile structure used to protect its fields
251  *    and there's a lock embedded in the list of ofiles of a tree. To
252  *    increment or to decrement the reference count the mutex must be entered.
253  *    To insert the ofile into the list of ofiles of the tree and to remove
254  *    the ofile from it, the lock must be entered in RW_WRITER mode.
255  *
256  *    Rules of access to a ofile structure:
257  *
258  *    1) In order to avoid deadlocks, when both (mutex and lock of the ofile
259  *       list) have to be entered, the lock must be entered first. Additionally,
260  *       f_mutex must not be held when removing the ofile from sv_persistid_ht.
261  *
262  *    2) All actions applied to an ofile require a reference count.
263  *
264  *    3) There are 2 ways of getting a reference count. One is when the ofile
265  *       is opened. The other one when the ofile is looked up. This translates
266  *       into 2 functions: smb_ofile_open() and smb_ofile_lookup_by_fid().
267  *
268  *    It should be noted that the reference count of an ofile registers the
269  *    number of references to the ofile in other structures (such as an smb
270  *    request). The reference count is not incremented in these 2 instances:
271  *
272  *    1) The ofile is open. An ofile is anchored by its state. If there's
273  *       no activity involving an ofile currently open, the reference count
274  *       of that ofile is zero.
275  *
276  *    2) The ofile is queued in the list of ofiles of its tree. The fact of
277  *       being queued in that list is NOT registered by incrementing the
278  *       reference count.
279  */
280 #include <smbsrv/smb2_kproto.h>
281 #include <smbsrv/smb_fsops.h>
282 #include <sys/time.h>
283 #include <sys/random.h>
284 
285 static boolean_t smb_ofile_is_open_locked(smb_ofile_t *);
286 static void smb_ofile_delete(void *arg);
287 static void smb_ofile_save_dh(void *arg);
288 
289 static int smb_ofile_netinfo_encode(smb_ofile_t *, uint8_t *, size_t,
290     uint32_t *);
291 static int smb_ofile_netinfo_init(smb_ofile_t *, smb_netfileinfo_t *);
292 static void smb_ofile_netinfo_fini(smb_netfileinfo_t *);
293 
294 /*
295  * The uniq_fid is a CIFS-server-wide unique identifier for an ofile
296  * which is used to uniquely identify open instances for the
297  * VFS share reservation and POSIX locks.
298  */
299 static volatile uint32_t smb_fids = 0;
300 #define	SMB_UNIQ_FID()	atomic_inc_32_nv(&smb_fids)
301 
302 /*
303  * smb_ofile_alloc
304  * Allocate an ofile and fill in it's "up" pointers, but
305  * do NOT link it into the tree's list of ofiles or the
306  * node's list of ofiles.  An ofile in this state is a
307  * "proposed" open passed to the oplock break code.
308  *
309  * If we don't get as far as smb_ofile_open with this OF,
310  * call smb_ofile_free() to free this object.
311  *
312  * Note: The following sr members may be null during
313  * persistent handle import: session, uid_usr, tid_tree
314  */
315 smb_ofile_t *
316 smb_ofile_alloc(
317     smb_request_t	*sr,
318     smb_arg_open_t	*op,
319     smb_node_t		*node, /* optional (may be NULL) */
320     uint16_t		ftype,
321     uint16_t		tree_fid)
322 {
323 	smb_user_t	*user = sr->uid_user;	/* optional */
324 	smb_tree_t	*tree = sr->tid_tree;	/* optional */
325 	smb_ofile_t	*of;
326 
327 	of = kmem_cache_alloc(smb_cache_ofile, KM_SLEEP);
328 	bzero(of, sizeof (smb_ofile_t));
329 	of->f_magic = SMB_OFILE_MAGIC;
330 
331 	mutex_init(&of->f_mutex, NULL, MUTEX_DEFAULT, NULL);
332 	list_create(&of->f_notify.nc_waiters, sizeof (smb_request_t),
333 	    offsetof(smb_request_t, sr_waiters));
334 	mutex_init(&of->dh_nvlock, NULL, MUTEX_DEFAULT, NULL);
335 
336 	of->f_state = SMB_OFILE_STATE_ALLOC;
337 	of->f_refcnt = 1;
338 	of->f_ftype = ftype;
339 	of->f_fid = tree_fid;
340 	/* of->f_persistid see smb2_create */
341 	of->f_uniqid = SMB_UNIQ_FID();
342 	of->f_opened_by_pid = sr->smb_pid;
343 	of->f_granted_access = op->desired_access;
344 	of->f_share_access = op->share_access;
345 	of->f_create_options = op->create_options;
346 	if (user != NULL) {
347 		if ((op->create_options & FILE_OPEN_FOR_BACKUP_INTENT) != 0)
348 			of->f_cr = smb_user_getprivcred(user);
349 		else
350 			of->f_cr = user->u_cred;
351 		crhold(of->f_cr);
352 	}
353 	of->f_server = sr->sr_server;
354 	of->f_session = sr->session;	/* may be NULL */
355 
356 	(void) memset(of->f_lock_seq, -1, SMB_OFILE_LSEQ_MAX);
357 
358 	of->f_mode = smb_fsop_amask_to_omode(of->f_granted_access);
359 	if ((of->f_granted_access & FILE_DATA_ALL) == FILE_EXECUTE)
360 		of->f_flags |= SMB_OFLAGS_EXECONLY;
361 
362 	/*
363 	 * In case a lease is requested, copy the lease keys now so
364 	 * any oplock breaks during open don't break those on our
365 	 * other handles that might have the same lease.
366 	 */
367 	bcopy(op->lease_key, of->TargetOplockKey, SMB_LEASE_KEY_SZ);
368 	bcopy(op->parent_lease_key, of->ParentOplockKey, SMB_LEASE_KEY_SZ);
369 
370 	/*
371 	 * grab a ref for of->f_user and of->f_tree
372 	 * We know the user and tree must be "live" because
373 	 * this SR holds references to them.  The node ref. is
374 	 * held by our caller, until smb_ofile_open puts this
375 	 * ofile on the node ofile list with smb_node_add_ofile.
376 	 */
377 	if (user != NULL) {
378 		smb_user_hold_internal(user);
379 		of->f_user = user;
380 	}
381 	if (tree != NULL) {
382 		smb_tree_hold_internal(tree);
383 		of->f_tree = tree;
384 	}
385 	of->f_node = node;	/* may be NULL */
386 
387 	return (of);
388 }
389 
390 /*
391  * smb_ofile_open
392  *
393  * Complete an open on an ofile that was previously allocated by
394  * smb_ofile_alloc, by putting it on the tree ofile list and
395  * (if it's a file) the node ofile list.
396  */
397 void
398 smb_ofile_open(
399     smb_request_t	*sr,
400     smb_arg_open_t	*op,
401     smb_ofile_t		*of)
402 {
403 	smb_tree_t	*tree = sr->tid_tree;
404 	smb_node_t	*node = of->f_node;
405 
406 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
407 	of->f_state = SMB_OFILE_STATE_OPEN;
408 
409 	switch (of->f_ftype) {
410 	case SMB_FTYPE_BYTE_PIPE:
411 	case SMB_FTYPE_MESG_PIPE:
412 		/* See smb_opipe_open. */
413 		of->f_pipe = op->pipe;
414 		smb_server_inc_pipes(of->f_server);
415 		break;
416 	case SMB_FTYPE_DISK:
417 	case SMB_FTYPE_PRINTER:
418 		/* Regular file, not a pipe */
419 		ASSERT(node != NULL);
420 
421 		smb_node_inc_open_ofiles(node);
422 		smb_node_add_ofile(node, of);
423 		smb_node_ref(node);
424 		smb_server_inc_files(of->f_server);
425 		break;
426 	default:
427 		ASSERT(0);
428 	}
429 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
430 	smb_llist_insert_tail(&tree->t_ofile_list, of);
431 	smb_llist_exit(&tree->t_ofile_list);
432 	atomic_inc_32(&tree->t_open_files);
433 	atomic_inc_32(&of->f_session->s_file_cnt);
434 
435 }
436 
437 /*
438  * smb_ofile_close
439  *
440  * Incoming states: (where from)
441  *   SMB_OFILE_STATE_OPEN  protocol close, smb_ofile_drop
442  *   SMB_OFILE_STATE_EXPIRED  called via smb2_dh_expire
443  *   SMB_OFILE_STATE_ORPHANED  smb2_dh_shutdown
444  */
445 void
446 smb_ofile_close(smb_ofile_t *of, int32_t mtime_sec)
447 {
448 	smb_attr_t *pa;
449 	timestruc_t now;
450 
451 	SMB_OFILE_VALID(of);
452 
453 	mutex_enter(&of->f_mutex);
454 	ASSERT(of->f_refcnt);
455 
456 	switch (of->f_state) {
457 	case SMB_OFILE_STATE_OPEN:
458 	case SMB_OFILE_STATE_ORPHANED:
459 	case SMB_OFILE_STATE_EXPIRED:
460 		of->f_state = SMB_OFILE_STATE_CLOSING;
461 		mutex_exit(&of->f_mutex);
462 		break;
463 	default:
464 		mutex_exit(&of->f_mutex);
465 		return;
466 	}
467 
468 	/*
469 	 * Only one thread here (the one that that set f_state closing)
470 	 */
471 	switch (of->f_ftype) {
472 	case SMB_FTYPE_BYTE_PIPE:
473 	case SMB_FTYPE_MESG_PIPE:
474 		smb_opipe_close(of);
475 		smb_server_dec_pipes(of->f_server);
476 		break;
477 
478 	case SMB_FTYPE_DISK:
479 		if (of->dh_persist)
480 			smb2_dh_close_persistent(of);
481 		if (of->f_persistid != 0)
482 			smb_ofile_del_persistid(of);
483 		if (of->f_lease != NULL)
484 			smb2_lease_ofile_close(of);
485 		smb_oplock_break_CLOSE(of->f_node, of);
486 		/* FALLTHROUGH */
487 
488 	case SMB_FTYPE_PRINTER: /* or FTYPE_DISK */
489 		/*
490 		 * In here we make changes to of->f_pending_attr
491 		 * while not holding of->f_mutex.  This is OK
492 		 * because we've changed f_state to CLOSING,
493 		 * so no more threads will take this path.
494 		 */
495 		pa = &of->f_pending_attr;
496 		if (mtime_sec != 0) {
497 			pa->sa_vattr.va_mtime.tv_sec = mtime_sec;
498 			pa->sa_mask |= SMB_AT_MTIME;
499 		}
500 
501 		/*
502 		 * If we have ever modified data via this handle
503 		 * (write or truncate) and if the mtime was not
504 		 * set via this handle, update the mtime again
505 		 * during the close.  Windows expects this.
506 		 * [ MS-FSA 2.1.5.4 "Update Timestamps" ]
507 		 */
508 		if (of->f_written &&
509 		    (pa->sa_mask & SMB_AT_MTIME) == 0) {
510 			pa->sa_mask |= SMB_AT_MTIME;
511 			gethrestime(&now);
512 			pa->sa_vattr.va_mtime = now;
513 		}
514 
515 		if (of->f_flags & SMB_OFLAGS_SET_DELETE_ON_CLOSE) {
516 			/* We delete using the on-disk name. */
517 			uint32_t flags = SMB_CASE_SENSITIVE;
518 			(void) smb_node_set_delete_on_close(of->f_node,
519 			    of->f_cr, flags);
520 		}
521 		smb_fsop_unshrlock(of->f_cr, of->f_node, of->f_uniqid);
522 		smb_node_destroy_lock_by_ofile(of->f_node, of);
523 
524 		if (smb_node_is_file(of->f_node)) {
525 			(void) smb_fsop_close(of->f_node, of->f_mode,
526 			    of->f_cr);
527 		} else {
528 			/*
529 			 * If there was an odir, close it.
530 			 */
531 			if (of->f_odir != NULL)
532 				smb_odir_close(of->f_odir);
533 			/*
534 			 * Cancel any notify change requests that
535 			 * might be watching this open file (dir),
536 			 * and unsubscribe it from node events.
537 			 *
538 			 * Can't hold f_mutex when calling smb_notify_ofile.
539 			 * Don't really need it when unsubscribing, but
540 			 * harmless, and consistent with subscribing.
541 			 */
542 			if (of->f_notify.nc_subscribed)
543 				smb_notify_ofile(of,
544 				    FILE_ACTION_HANDLE_CLOSED, NULL);
545 			mutex_enter(&of->f_mutex);
546 			if (of->f_notify.nc_subscribed) {
547 				of->f_notify.nc_subscribed = B_FALSE;
548 				smb_node_fcn_unsubscribe(of->f_node);
549 				of->f_notify.nc_filter = 0;
550 			}
551 			mutex_exit(&of->f_mutex);
552 		}
553 		if (smb_node_dec_open_ofiles(of->f_node) == 0) {
554 			/*
555 			 * Last close.  If we're not deleting
556 			 * the file, apply any pending attrs.
557 			 * Leave allocsz zero when no open files,
558 			 * just to avoid confusion, because it's
559 			 * only updated when there are opens.
560 			 * XXX: Just do this on _every_ close.
561 			 */
562 			mutex_enter(&of->f_node->n_mutex);
563 			if (of->f_node->flags & NODE_FLAGS_DELETE_ON_CLOSE) {
564 				smb_node_delete_on_close(of->f_node);
565 				pa->sa_mask = 0;
566 			}
567 			of->f_node->n_allocsz = 0;
568 			mutex_exit(&of->f_node->n_mutex);
569 		}
570 		if (pa->sa_mask != 0) {
571 			/*
572 			 * Commit any pending attributes from
573 			 * the ofile we're closing.  Note that
574 			 * we pass NULL as the ofile to setattr
575 			 * so it will write to the file system
576 			 * and not keep anything on the ofile.
577 			 */
578 			(void) smb_node_setattr(NULL, of->f_node,
579 			    of->f_cr, NULL, pa);
580 		}
581 
582 		smb_server_dec_files(of->f_server);
583 		break;
584 	}
585 
586 	/*
587 	 * Keep f_state == SMB_OFILE_STATE_CLOSING
588 	 * until the last ref. is dropped, in
589 	 * smb_ofile_release()
590 	 */
591 }
592 
593 /*
594  * "Destructor" function for smb_ofile_close_all, and
595  * smb_ofile_close_all_by_pid, called after the llist lock
596  * for tree list has been exited.  Our job is to either
597  * close this ofile, or (if durable) set state _SAVE_DH.
598  *
599  * The next interesting thing happens when the last ref.
600  * on this ofile calls smb_ofile_release(), where we
601  * eihter delete the ofile, or (if durable) leave it
602  * in the persistid hash table for possible reclaim.
603  *
604  * This is run via smb_llist_post (after smb_llist_exit)
605  * because smb_ofile_close can block, and we'd rather not
606  * block while holding the ofile list as reader.
607  */
608 static void
609 smb_ofile_drop(void *arg)
610 {
611 	smb_ofile_t	*of = arg;
612 
613 	SMB_OFILE_VALID(of);
614 
615 	mutex_enter(&of->f_mutex);
616 	switch (of->f_state) {
617 	case SMB_OFILE_STATE_OPEN:
618 		/* DH checks under mutex. */
619 		if (of->f_ftype == SMB_FTYPE_DISK &&
620 		    of->dh_vers != SMB2_NOT_DURABLE &&
621 		    smb_dh_should_save(of)) {
622 			/*
623 			 * Tell smb_ofile_release() to
624 			 * make this an _ORPHANED DH.
625 			 */
626 			of->f_state = SMB_OFILE_STATE_SAVE_DH;
627 			mutex_exit(&of->f_mutex);
628 			break;
629 		}
630 		/* OK close it. */
631 		mutex_exit(&of->f_mutex);
632 		smb_ofile_close(of, 0);
633 		break;
634 
635 	default:
636 		/* Something else closed it already. */
637 		mutex_exit(&of->f_mutex);
638 		break;
639 	}
640 
641 	/*
642 	 * Release the ref acquired during the traversal loop.
643 	 * Note that on the last ref, this ofile will be
644 	 * removed from the tree list etc.
645 	 * See: smb_llist_post, smb_ofile_delete
646 	 */
647 	smb_ofile_release(of);
648 }
649 
650 /*
651  * smb_ofile_close_all
652  *
653  *
654  */
655 void
656 smb_ofile_close_all(
657     smb_tree_t		*tree,
658     uint32_t		pid)
659 {
660 	smb_ofile_t	*of;
661 	smb_llist_t	*ll;
662 
663 	ASSERT(tree);
664 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
665 
666 	ll = &tree->t_ofile_list;
667 
668 	smb_llist_enter(ll, RW_READER);
669 	for (of = smb_llist_head(ll);
670 	    of != NULL;
671 	    of = smb_llist_next(ll, of)) {
672 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
673 		ASSERT(of->f_tree == tree);
674 		if (pid != 0 && of->f_opened_by_pid != pid)
675 			continue;
676 		if (smb_ofile_hold(of)) {
677 			smb_llist_post(ll, of, smb_ofile_drop);
678 		}
679 	}
680 
681 	/*
682 	 * Drop the lock and process the llist dtor queue.
683 	 * Calls smb_ofile_drop on ofiles that were open.
684 	 */
685 	smb_llist_exit(ll);
686 }
687 
688 /*
689  * If the enumeration request is for ofile data, handle it here.
690  * Otherwise, return.
691  *
692  * This function should be called with a hold on the ofile.
693  */
694 int
695 smb_ofile_enum(smb_ofile_t *of, smb_svcenum_t *svcenum)
696 {
697 	uint8_t *pb;
698 	uint_t nbytes;
699 	int rc;
700 
701 	ASSERT(of);
702 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
703 	ASSERT(of->f_refcnt);
704 
705 	if (svcenum->se_type != SMB_SVCENUM_TYPE_FILE)
706 		return (0);
707 
708 	if (svcenum->se_nskip > 0) {
709 		svcenum->se_nskip--;
710 		return (0);
711 	}
712 
713 	if (svcenum->se_nitems >= svcenum->se_nlimit) {
714 		svcenum->se_nitems = svcenum->se_nlimit;
715 		return (0);
716 	}
717 
718 	pb = &svcenum->se_buf[svcenum->se_bused];
719 
720 	rc = smb_ofile_netinfo_encode(of, pb, svcenum->se_bavail,
721 	    &nbytes);
722 	if (rc == 0) {
723 		svcenum->se_bavail -= nbytes;
724 		svcenum->se_bused += nbytes;
725 		svcenum->se_nitems++;
726 	}
727 
728 	return (rc);
729 }
730 
731 /*
732  * Take a reference on an open file, in any of the states:
733  *   RECONNECT, SAVE_DH, OPEN, ORPHANED.
734  * Return TRUE if ref taken.  Used for oplock breaks.
735  *
736  * Note: When the oplock break code calls this, it holds the
737  * node ofile list lock and node oplock mutex.  When we see
738  * an ofile in states RECONNECT or SAVING, we know the ofile
739  * is gaining or losing it's tree, and that happens quickly,
740  * so we just wait for that work to finish.  However, the
741  * waiting for state transitions here means we have to be
742  * careful not to re-enter the node list lock or otherwise
743  * block on things that could cause a deadlock.  Waiting
744  * just on of->f_mutex here is OK.
745  */
746 boolean_t
747 smb_ofile_hold_olbrk(smb_ofile_t *of)
748 {
749 	boolean_t ret = B_FALSE;
750 
751 	ASSERT(of);
752 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
753 
754 	mutex_enter(&of->f_mutex);
755 
756 again:
757 	switch (of->f_state) {
758 	case SMB_OFILE_STATE_RECONNECT:
759 	case SMB_OFILE_STATE_SAVING:
760 		cv_wait(&of->f_cv, &of->f_mutex);
761 		goto again;
762 
763 	case SMB_OFILE_STATE_OPEN:
764 	case SMB_OFILE_STATE_ORPHANED:
765 	case SMB_OFILE_STATE_SAVE_DH:
766 		of->f_refcnt++;
767 		ret = B_TRUE;
768 		break;
769 
770 	default:
771 		break;
772 	}
773 	mutex_exit(&of->f_mutex);
774 
775 	return (ret);
776 }
777 
778 /*
779  * Take a reference on an open file.
780  */
781 boolean_t
782 smb_ofile_hold(smb_ofile_t *of)
783 {
784 	ASSERT(of);
785 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
786 
787 	mutex_enter(&of->f_mutex);
788 
789 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
790 		mutex_exit(&of->f_mutex);
791 		return (B_FALSE);
792 	}
793 	of->f_refcnt++;
794 
795 	mutex_exit(&of->f_mutex);
796 	return (B_TRUE);
797 }
798 
799 /*
800  * Release a reference on a file.  If the reference count falls to
801  * zero and the file has been closed, post the object for deletion.
802  * Object deletion is deferred to avoid modifying a list while an
803  * iteration may be in progress.
804  *
805  * We're careful to avoid dropping f_session etc. until the last
806  * reference goes away.  The oplock break code depends on that
807  * not changing while it holds a ref. on an ofile.
808  */
809 void
810 smb_ofile_release(smb_ofile_t *of)
811 {
812 	smb_tree_t *tree = of->f_tree;
813 	boolean_t delete = B_FALSE;
814 
815 	SMB_OFILE_VALID(of);
816 
817 	mutex_enter(&of->f_mutex);
818 	ASSERT(of->f_refcnt > 0);
819 	of->f_refcnt--;
820 
821 	switch (of->f_state) {
822 	case SMB_OFILE_STATE_OPEN:
823 	case SMB_OFILE_STATE_ORPHANED:
824 	case SMB_OFILE_STATE_EXPIRED:
825 		break;
826 
827 	case SMB_OFILE_STATE_SAVE_DH:
828 		ASSERT(tree != NULL);
829 		if (of->f_refcnt == 0) {
830 			of->f_state = SMB_OFILE_STATE_SAVING;
831 			smb_llist_post(&tree->t_ofile_list, of,
832 			    smb_ofile_save_dh);
833 		}
834 		break;
835 
836 	case SMB_OFILE_STATE_CLOSING:
837 		/* Note, tree == NULL on _ORPHANED */
838 		if (of->f_refcnt == 0) {
839 			of->f_state = SMB_OFILE_STATE_CLOSED;
840 			if (tree == NULL) {
841 				/* Skip smb_llist_post */
842 				delete = B_TRUE;
843 				break;
844 			}
845 			smb_llist_post(&tree->t_ofile_list, of,
846 			    smb_ofile_delete);
847 		}
848 		break;
849 
850 	default:
851 		ASSERT(0);
852 		break;
853 	}
854 	mutex_exit(&of->f_mutex);
855 
856 	/*
857 	 * When we drop the last ref. on an expired DH, it's no longer
858 	 * in any tree, so skip the smb_llist_post and just call
859 	 * smb_ofile_delete directly.
860 	 */
861 	if (delete) {
862 		smb_ofile_delete(of);
863 	}
864 }
865 
866 /*
867  * smb_ofile_lookup_by_fid
868  *
869  * Find the open file whose fid matches the one specified in the request.
870  * If we can't find the fid or the shares (trees) don't match, we have a
871  * bad fid.
872  */
873 smb_ofile_t *
874 smb_ofile_lookup_by_fid(
875     smb_request_t	*sr,
876     uint16_t		fid)
877 {
878 	smb_tree_t	*tree = sr->tid_tree;
879 	smb_llist_t	*of_list;
880 	smb_ofile_t	*of;
881 
882 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
883 
884 	of_list = &tree->t_ofile_list;
885 
886 	smb_llist_enter(of_list, RW_READER);
887 	of = smb_llist_head(of_list);
888 	while (of) {
889 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
890 		ASSERT(of->f_tree == tree);
891 		if (of->f_fid == fid)
892 			break;
893 		of = smb_llist_next(of_list, of);
894 	}
895 	if (of == NULL)
896 		goto out;
897 
898 	/*
899 	 * Only allow use of a given FID with the same UID that
900 	 * was used to open it.  MS-CIFS 3.3.5.14
901 	 */
902 	if (of->f_user != sr->uid_user) {
903 		of = NULL;
904 		goto out;
905 	}
906 
907 	/* inline smb_ofile_hold() */
908 	mutex_enter(&of->f_mutex);
909 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
910 		mutex_exit(&of->f_mutex);
911 		of = NULL;
912 		goto out;
913 	}
914 	of->f_refcnt++;
915 	mutex_exit(&of->f_mutex);
916 
917 out:
918 	smb_llist_exit(of_list);
919 	return (of);
920 }
921 
922 /*
923  * smb_ofile_lookup_by_uniqid
924  *
925  * Find the open file whose uniqid matches the one specified in the request.
926  */
927 smb_ofile_t *
928 smb_ofile_lookup_by_uniqid(smb_tree_t *tree, uint32_t uniqid)
929 {
930 	smb_llist_t	*of_list;
931 	smb_ofile_t	*of;
932 
933 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
934 
935 	of_list = &tree->t_ofile_list;
936 	smb_llist_enter(of_list, RW_READER);
937 	of = smb_llist_head(of_list);
938 
939 	while (of) {
940 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
941 		ASSERT(of->f_tree == tree);
942 
943 		if (of->f_uniqid == uniqid) {
944 			if (smb_ofile_hold(of)) {
945 				smb_llist_exit(of_list);
946 				return (of);
947 			}
948 		}
949 
950 		of = smb_llist_next(of_list, of);
951 	}
952 
953 	smb_llist_exit(of_list);
954 	return (NULL);
955 }
956 
957 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 		ASSERT(of->f_node != NULL);
1457 		/*
1458 		 * Note smb_ofile_close did smb_node_dec_open_ofiles()
1459 		 */
1460 		smb_node_rem_ofile(of->f_node, of);
1461 	}
1462 
1463 	/*
1464 	 * This ofile is no longer on any lists, however...
1465 	 *
1466 	 * This is called via smb_llist_post, which means it may run
1467 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1468 	 * flushes the delete queue before we do).  Synchronize.
1469 	 */
1470 	mutex_enter(&of->f_mutex);
1471 	of->f_state = SMB_OFILE_STATE_ALLOC;
1472 	DTRACE_PROBE1(ofile__exit, smb_ofile_t, of);
1473 	mutex_exit(&of->f_mutex);
1474 
1475 	switch (of->f_ftype) {
1476 	case SMB_FTYPE_BYTE_PIPE:
1477 	case SMB_FTYPE_MESG_PIPE:
1478 		smb_opipe_dealloc(of->f_pipe);
1479 		of->f_pipe = NULL;
1480 		break;
1481 	case SMB_FTYPE_DISK:
1482 		ASSERT(of->f_notify.nc_subscribed == B_FALSE);
1483 		MBC_FLUSH(&of->f_notify.nc_buffer);
1484 		if (of->f_odir != NULL)
1485 			smb_odir_release(of->f_odir);
1486 		if (of->f_lease != NULL) {
1487 			smb2_lease_rele(of->f_lease);
1488 			of->f_lease = NULL;
1489 		}
1490 		/* FALLTHROUGH */
1491 	case SMB_FTYPE_PRINTER:
1492 		/*
1493 		 * Did smb_node_rem_ofile above.
1494 		 */
1495 		ASSERT(of->f_node != NULL);
1496 		smb_node_release(of->f_node);
1497 		break;
1498 	default:
1499 		ASSERT(!"f_ftype");
1500 		break;
1501 	}
1502 
1503 	smb_ofile_free(of);
1504 }
1505 
1506 void
1507 smb_ofile_free(smb_ofile_t *of)
1508 {
1509 	smb_tree_t	*tree = of->f_tree;
1510 
1511 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
1512 
1513 	if (tree != NULL) {
1514 		if (of->f_fid != 0)
1515 			smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1516 		smb_tree_release(of->f_tree);
1517 		smb_user_release(of->f_user);
1518 	}
1519 
1520 	if (of->f_cr != NULL)
1521 		crfree(of->f_cr);
1522 
1523 	of->f_magic = (uint32_t)~SMB_OFILE_MAGIC;
1524 	list_destroy(&of->f_notify.nc_waiters);
1525 	mutex_destroy(&of->dh_nvlock);
1526 	mutex_destroy(&of->f_mutex);
1527 	kmem_cache_free(smb_cache_ofile, of);
1528 }
1529 
1530 /*
1531  * smb_ofile_access
1532  *
1533  * This function will check to see if the access requested is granted.
1534  * Returns NT status codes.
1535  */
1536 uint32_t
1537 smb_ofile_access(smb_ofile_t *of, cred_t *cr, uint32_t access)
1538 {
1539 
1540 	if ((of == NULL) || (cr == zone_kcred()))
1541 		return (NT_STATUS_SUCCESS);
1542 
1543 	/*
1544 	 * If the request is for something
1545 	 * I don't grant it is an error
1546 	 */
1547 	if (~(of->f_granted_access) & access) {
1548 		if (!(of->f_granted_access & ACCESS_SYSTEM_SECURITY) &&
1549 		    (access & ACCESS_SYSTEM_SECURITY)) {
1550 			return (NT_STATUS_PRIVILEGE_NOT_HELD);
1551 		}
1552 		return (NT_STATUS_ACCESS_DENIED);
1553 	}
1554 
1555 	return (NT_STATUS_SUCCESS);
1556 }
1557 
1558 /*
1559  * smb_ofile_share_check
1560  *
1561  * Check if ofile was opened with share access NONE (0).
1562  * Returns: B_TRUE  - share access non-zero
1563  *          B_FALSE - share access NONE
1564  */
1565 boolean_t
1566 smb_ofile_share_check(smb_ofile_t *of)
1567 {
1568 	return (!SMB_DENY_ALL(of->f_share_access));
1569 }
1570 
1571 /*
1572  * check file sharing rules for current open request
1573  * against existing open instances of the same file
1574  *
1575  * Returns NT_STATUS_SHARING_VIOLATION if there is any
1576  * sharing conflict, otherwise returns NT_STATUS_SUCCESS.
1577  */
1578 uint32_t
1579 smb_ofile_open_check(smb_ofile_t *of, uint32_t desired_access,
1580     uint32_t share_access)
1581 {
1582 	uint32_t ret;
1583 
1584 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1585 
1586 	mutex_enter(&of->f_mutex);
1587 
1588 	if (!smb_ofile_is_open_locked(of)) {
1589 		ret = NT_STATUS_INVALID_HANDLE;
1590 		goto out;
1591 	}
1592 
1593 	/* if it's just meta data */
1594 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1595 		ret = NT_STATUS_SUCCESS;
1596 		goto out;
1597 	}
1598 
1599 	/*
1600 	 * Check requested share access against the
1601 	 * open granted (desired) access
1602 	 */
1603 	if (SMB_DENY_DELETE(share_access) && (of->f_granted_access & DELETE)) {
1604 		ret = NT_STATUS_SHARING_VIOLATION;
1605 		goto out;
1606 	}
1607 
1608 	if (SMB_DENY_READ(share_access) &&
1609 	    (of->f_granted_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1610 		ret = NT_STATUS_SHARING_VIOLATION;
1611 		goto out;
1612 	}
1613 
1614 	if (SMB_DENY_WRITE(share_access) &&
1615 	    (of->f_granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1616 		ret = NT_STATUS_SHARING_VIOLATION;
1617 		goto out;
1618 	}
1619 
1620 	/* check requested desired access against the open share access */
1621 	if (SMB_DENY_DELETE(of->f_share_access) && (desired_access & DELETE)) {
1622 		ret = NT_STATUS_SHARING_VIOLATION;
1623 		goto out;
1624 	}
1625 
1626 	if (SMB_DENY_READ(of->f_share_access) &&
1627 	    (desired_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1628 		ret = NT_STATUS_SHARING_VIOLATION;
1629 		goto out;
1630 	}
1631 
1632 	if (SMB_DENY_WRITE(of->f_share_access) &&
1633 	    (desired_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1634 		ret = NT_STATUS_SHARING_VIOLATION;
1635 		goto out;
1636 	}
1637 
1638 	ret = NT_STATUS_SUCCESS;
1639 out:
1640 	mutex_exit(&of->f_mutex);
1641 	return (ret);
1642 }
1643 
1644 /*
1645  * smb_ofile_rename_check
1646  *
1647  * This does the work described in MS-FSA 2.1.5.1.2.2 (Algorithm
1648  * to Check Sharing Access to an Existing Stream or Directory),
1649  * where the "open in-progress" has DesiredAccess = DELETE and
1650  * SharingMode = SHARE_READ | SHARE_WRITE | SHARE_DELETE.
1651  */
1652 
1653 uint32_t
1654 smb_ofile_rename_check(smb_ofile_t *of)
1655 {
1656 	uint32_t ret;
1657 
1658 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1659 
1660 	mutex_enter(&of->f_mutex);
1661 
1662 	if (!smb_ofile_is_open_locked(of)) {
1663 		ret = NT_STATUS_INVALID_HANDLE;
1664 		goto out;
1665 	}
1666 
1667 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1668 		ret = NT_STATUS_SUCCESS;
1669 		goto out;
1670 	}
1671 
1672 	if ((of->f_share_access & FILE_SHARE_DELETE) == 0) {
1673 		ret = NT_STATUS_SHARING_VIOLATION;
1674 		goto out;
1675 	}
1676 
1677 	ret = NT_STATUS_SUCCESS;
1678 out:
1679 	mutex_exit(&of->f_mutex);
1680 	return (ret);
1681 }
1682 
1683 /*
1684  * smb_ofile_delete_check
1685  *
1686  * An open file can be deleted only if opened for
1687  * accessing meta data. Share modes aren't important
1688  * in this case.
1689  *
1690  * NOTE: there is another mechanism for deleting an
1691  * open file that NT clients usually use.
1692  * That's setting "Delete on close" flag for an open
1693  * file.  In this way the file will be deleted after
1694  * last close. This flag can be set by SmbTrans2SetFileInfo
1695  * with FILE_DISPOSITION_INFO information level.
1696  * For setting this flag, the file should be opened by
1697  * DELETE access in the FID that is passed in the Trans2
1698  * request.
1699  */
1700 
1701 uint32_t
1702 smb_ofile_delete_check(smb_ofile_t *of)
1703 {
1704 	uint32_t ret;
1705 
1706 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1707 
1708 	mutex_enter(&of->f_mutex);
1709 
1710 	if (!smb_ofile_is_open_locked(of)) {
1711 		ret = NT_STATUS_INVALID_HANDLE;
1712 		goto out;
1713 	}
1714 
1715 	if (of->f_granted_access &
1716 	    (FILE_READ_DATA | FILE_WRITE_DATA |
1717 	    FILE_APPEND_DATA | FILE_EXECUTE | DELETE)) {
1718 		ret = NT_STATUS_SHARING_VIOLATION;
1719 		goto out;
1720 	}
1721 
1722 	ret = NT_STATUS_SUCCESS;
1723 out:
1724 	mutex_exit(&of->f_mutex);
1725 	return (ret);
1726 }
1727 
1728 cred_t *
1729 smb_ofile_getcred(smb_ofile_t *of)
1730 {
1731 	return (of->f_cr);
1732 }
1733 
1734 /*
1735  * smb_ofile_set_delete_on_close
1736  *
1737  * Set the DeleteOnClose flag on the smb file. When the file is closed,
1738  * the flag will be transferred to the smb node, which will commit the
1739  * delete operation and inhibit subsequent open requests.
1740  *
1741  * When DeleteOnClose is set on an smb_node, the common open code will
1742  * reject subsequent open requests for the file. Observation of Windows
1743  * 2000 indicates that subsequent opens should be allowed (assuming
1744  * there would be no sharing violation) until the file is closed using
1745  * the fid on which the DeleteOnClose was requested.
1746  */
1747 void
1748 smb_ofile_set_delete_on_close(smb_request_t *sr, smb_ofile_t *of)
1749 {
1750 	uint32_t	status;
1751 
1752 	/*
1753 	 * Break any oplock handle caching.
1754 	 */
1755 	status = smb_oplock_break_SETINFO(of->f_node, of,
1756 	    FileDispositionInformation);
1757 	if (status == NT_STATUS_OPLOCK_BREAK_IN_PROGRESS) {
1758 		if (sr->session->dialect >= SMB_VERS_2_BASE)
1759 			(void) smb2sr_go_async(sr);
1760 		(void) smb_oplock_wait_break(of->f_node, 0);
1761 	}
1762 
1763 	mutex_enter(&of->f_mutex);
1764 	of->f_flags |= SMB_OFLAGS_SET_DELETE_ON_CLOSE;
1765 	mutex_exit(&of->f_mutex);
1766 }
1767 
1768 /*
1769  * Encode open file information into a buffer; needed in user space to
1770  * support RPC requests.
1771  */
1772 static int
1773 smb_ofile_netinfo_encode(smb_ofile_t *of, uint8_t *buf, size_t buflen,
1774     uint32_t *nbytes)
1775 {
1776 	smb_netfileinfo_t	fi;
1777 	int			rc;
1778 
1779 	rc = smb_ofile_netinfo_init(of, &fi);
1780 	if (rc == 0) {
1781 		rc = smb_netfileinfo_encode(&fi, buf, buflen, nbytes);
1782 		smb_ofile_netinfo_fini(&fi);
1783 	}
1784 
1785 	return (rc);
1786 }
1787 
1788 static int
1789 smb_ofile_netinfo_init(smb_ofile_t *of, smb_netfileinfo_t *fi)
1790 {
1791 	smb_user_t	*user;
1792 	smb_tree_t	*tree;
1793 	smb_node_t	*node;
1794 	char		*path;
1795 	char		*buf;
1796 	int		rc;
1797 
1798 	ASSERT(of);
1799 	user = of->f_user;
1800 	tree = of->f_tree;
1801 	ASSERT(user);
1802 	ASSERT(tree);
1803 
1804 	buf = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1805 
1806 	switch (of->f_ftype) {
1807 	case SMB_FTYPE_DISK:
1808 		node = of->f_node;
1809 		ASSERT(node);
1810 
1811 		fi->fi_permissions = of->f_granted_access;
1812 		fi->fi_numlocks = smb_lock_get_lock_count(node, of);
1813 
1814 		path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1815 
1816 		if (node != tree->t_snode) {
1817 			rc = smb_node_getshrpath(node, tree, path, MAXPATHLEN);
1818 			if (rc != 0)
1819 				(void) strlcpy(path, node->od_name, MAXPATHLEN);
1820 		}
1821 
1822 		(void) snprintf(buf, MAXPATHLEN, "%s:%s", tree->t_sharename,
1823 		    path);
1824 		kmem_free(path, MAXPATHLEN);
1825 		break;
1826 
1827 	case SMB_FTYPE_MESG_PIPE:
1828 		ASSERT(of->f_pipe);
1829 
1830 		fi->fi_permissions = FILE_READ_DATA | FILE_WRITE_DATA |
1831 		    FILE_EXECUTE;
1832 		fi->fi_numlocks = 0;
1833 		(void) snprintf(buf, MAXPATHLEN, "\\PIPE\\%s",
1834 		    of->f_pipe->p_name);
1835 		break;
1836 
1837 	default:
1838 		kmem_free(buf, MAXPATHLEN);
1839 		return (-1);
1840 	}
1841 
1842 	fi->fi_fid = of->f_fid;
1843 	fi->fi_uniqid = of->f_uniqid;
1844 	fi->fi_pathlen = strlen(buf) + 1;
1845 	fi->fi_path = smb_mem_strdup(buf);
1846 	kmem_free(buf, MAXPATHLEN);
1847 
1848 	fi->fi_namelen = user->u_domain_len + user->u_name_len + 2;
1849 	fi->fi_username = kmem_alloc(fi->fi_namelen, KM_SLEEP);
1850 	(void) snprintf(fi->fi_username, fi->fi_namelen, "%s\\%s",
1851 	    user->u_domain, user->u_name);
1852 	return (0);
1853 }
1854 
1855 static void
1856 smb_ofile_netinfo_fini(smb_netfileinfo_t *fi)
1857 {
1858 	if (fi == NULL)
1859 		return;
1860 
1861 	if (fi->fi_path)
1862 		smb_mem_free(fi->fi_path);
1863 	if (fi->fi_username)
1864 		kmem_free(fi->fi_username, fi->fi_namelen);
1865 
1866 	bzero(fi, sizeof (smb_netfileinfo_t));
1867 }
1868 
1869 /*
1870  * A query of user and group quotas may span multiple requests.
1871  * f_quota_resume is used to determine where the query should
1872  * be resumed, in a subsequent request. f_quota_resume contains
1873  * the SID of the last quota entry returned to the client.
1874  */
1875 void
1876 smb_ofile_set_quota_resume(smb_ofile_t *ofile, char *resume)
1877 {
1878 	ASSERT(ofile);
1879 	mutex_enter(&ofile->f_mutex);
1880 	if (resume == NULL)
1881 		bzero(ofile->f_quota_resume, SMB_SID_STRSZ);
1882 	else
1883 		(void) strlcpy(ofile->f_quota_resume, resume, SMB_SID_STRSZ);
1884 	mutex_exit(&ofile->f_mutex);
1885 }
1886 
1887 void
1888 smb_ofile_get_quota_resume(smb_ofile_t *ofile, char *buf, int bufsize)
1889 {
1890 	ASSERT(ofile);
1891 	mutex_enter(&ofile->f_mutex);
1892 	(void) strlcpy(buf, ofile->f_quota_resume, bufsize);
1893 	mutex_exit(&ofile->f_mutex);
1894 }
1895