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