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