xref: /linux/fs/smb/server/oplock.c (revision 14c5eb685cdefbd32e73d2723071ecbd8effbce9)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6 
7 #include <linux/moduleparam.h>
8 #include <linux/err.h>
9 
10 #include "glob.h"
11 #include "oplock.h"
12 
13 #include "smb_common.h"
14 #include "../common/smb2status.h"
15 #include "connection.h"
16 #include "mgmt/user_session.h"
17 #include "mgmt/share_config.h"
18 #include "mgmt/tree_connect.h"
19 #include "server.h"
20 
21 static LIST_HEAD(lease_table_list);
22 static DEFINE_RWLOCK(lease_list_lock);
23 
24 #define SMB2_LEASE_STATE_MASK_LE	(SMB2_LEASE_READ_CACHING_LE | \
25 					 SMB2_LEASE_HANDLE_CACHING_LE | \
26 					 SMB2_LEASE_WRITE_CACHING_LE)
27 
28 static bool lease_state_valid(__le32 state)
29 {
30 	return !(state & ~SMB2_LEASE_STATE_MASK_LE);
31 }
32 
33 static __le32 lease_state_grantable(__le32 state)
34 {
35 	if (state == SMB2_LEASE_READ_CACHING_LE ||
36 	    state == (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE) ||
37 	    state == (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_WRITE_CACHING_LE) ||
38 	    state == SMB2_LEASE_STATE_MASK_LE)
39 		return state;
40 
41 	return 0;
42 }
43 
44 static bool lease_v2_flags_valid(__le32 flags)
45 {
46 	return !(flags & ~SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE);
47 }
48 
49 static bool lease_has_parent_key(struct lease *lease)
50 {
51 	return lease->flags & SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE;
52 }
53 
54 static bool lease_break_in_progress(struct lease *lease)
55 {
56 	struct oplock_info *opinfo;
57 	bool ret = false;
58 
59 	spin_lock(&lease->lock);
60 	list_for_each_entry(opinfo, &lease->open_list, lease_entry) {
61 		if (opinfo->op_state == OPLOCK_ACK_WAIT) {
62 			ret = true;
63 			break;
64 		}
65 	}
66 	spin_unlock(&lease->lock);
67 
68 	return ret;
69 }
70 
71 /**
72  * alloc_opinfo() - allocate a new opinfo object for oplock info
73  * @work:	smb work
74  * @id:		fid of open file
75  * @Tid:	tree id of connection
76  *
77  * Return:      allocated opinfo object on success, otherwise NULL
78  */
79 static struct oplock_info *alloc_opinfo(struct ksmbd_work *work,
80 					u64 id, __u16 Tid)
81 {
82 	struct ksmbd_session *sess = work->sess;
83 	struct oplock_info *opinfo;
84 
85 	opinfo = kzalloc_obj(struct oplock_info, KSMBD_DEFAULT_GFP);
86 	if (!opinfo)
87 		return NULL;
88 
89 	opinfo->sess = sess;
90 	opinfo->conn = ksmbd_conn_get(work->conn);
91 	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
92 	opinfo->op_state = OPLOCK_STATE_NONE;
93 	spin_lock_init(&opinfo->state_lock);
94 	opinfo->pending_break = 0;
95 	opinfo->fid = id;
96 	opinfo->Tid = Tid;
97 	INIT_LIST_HEAD(&opinfo->op_entry);
98 	INIT_LIST_HEAD(&opinfo->lease_entry);
99 	init_waitqueue_head(&opinfo->oplock_q);
100 	init_waitqueue_head(&opinfo->oplock_brk);
101 	atomic_set(&opinfo->refcount, 1);
102 	atomic_set(&opinfo->breaking_cnt, 0);
103 
104 	return opinfo;
105 }
106 
107 static void lease_get(struct lease *lease)
108 {
109 	atomic_inc(&lease->refcount);
110 }
111 
112 static void lease_put(struct lease *lease)
113 {
114 	if (lease && atomic_dec_and_test(&lease->refcount))
115 		kfree(lease);
116 }
117 
118 static void lease_add_table(struct lease *lease, struct lease_table *lb)
119 {
120 	lease_get(lease);
121 	lease->l_lb = lb;
122 	spin_lock(&lb->lb_lock);
123 	list_add_rcu(&lease->l_entry, &lb->lease_list);
124 	spin_unlock(&lb->lb_lock);
125 }
126 
127 static void lease_del_table(struct lease *lease)
128 {
129 	struct lease_table *lb = lease->l_lb;
130 
131 	if (!lb)
132 		return;
133 
134 	spin_lock(&lb->lb_lock);
135 	if (list_empty(&lease->l_entry)) {
136 		spin_unlock(&lb->lb_lock);
137 		return;
138 	}
139 
140 	list_del_init(&lease->l_entry);
141 	lease->l_lb = NULL;
142 	spin_unlock(&lb->lb_lock);
143 
144 	lease_put(lease);
145 }
146 
147 static struct lease_table *alloc_lease_table(struct oplock_info *opinfo)
148 {
149 	struct lease_table *lb;
150 
151 	lb = kmalloc_obj(struct lease_table, KSMBD_DEFAULT_GFP);
152 	if (!lb)
153 		return NULL;
154 
155 	memcpy(lb->client_guid, opinfo->conn->ClientGUID,
156 	       SMB2_CLIENT_GUID_SIZE);
157 	lb->conn = ksmbd_conn_get(opinfo->conn);
158 	INIT_LIST_HEAD(&lb->lease_list);
159 	spin_lock_init(&lb->lb_lock);
160 	return lb;
161 }
162 
163 static void free_lease_table(struct lease_table *lb)
164 {
165 	if (!lb)
166 		return;
167 
168 	ksmbd_conn_put(lb->conn);
169 	kfree(lb);
170 }
171 
172 static struct lease *alloc_lease(struct lease_ctx_info *lctx,
173 				 struct ksmbd_inode *ci)
174 {
175 	struct lease *lease;
176 
177 	lease = kmalloc_obj(struct lease, KSMBD_DEFAULT_GFP);
178 	if (!lease)
179 		return NULL;
180 
181 	memcpy(lease->lease_key, lctx->lease_key, SMB2_LEASE_KEY_SIZE);
182 	lease->state = lctx->req_state;
183 	lease->new_state = 0;
184 	lease->flags = lctx->flags;
185 	lease->duration = lctx->duration;
186 	lease->is_dir = lctx->is_dir;
187 	memcpy(lease->parent_lease_key, lctx->parent_lease_key, SMB2_LEASE_KEY_SIZE);
188 	lease->version = lctx->version;
189 	lease->epoch = lctx->version == 2 ? le16_to_cpu(lctx->epoch) + 1 : 0;
190 	lease->ci = ci;
191 	lease->reuse_epoch = false;
192 	lease->l_lb = NULL;
193 	INIT_LIST_HEAD(&lease->l_entry);
194 	INIT_LIST_HEAD(&lease->open_list);
195 	spin_lock_init(&lease->lock);
196 	atomic_set(&lease->refcount, 1);
197 
198 	return lease;
199 }
200 
201 static void lease_add_open(struct lease *lease, struct oplock_info *opinfo)
202 {
203 	spin_lock(&lease->lock);
204 	list_add(&opinfo->lease_entry, &lease->open_list);
205 	spin_unlock(&lease->lock);
206 }
207 
208 static void lease_del_open(struct oplock_info *opinfo)
209 {
210 	struct lease *lease = opinfo->o_lease;
211 	bool remove_table = false;
212 
213 	if (!lease)
214 		return;
215 
216 	spin_lock(&lease->lock);
217 	if (!list_empty(&opinfo->lease_entry)) {
218 		list_del_init(&opinfo->lease_entry);
219 		remove_table = list_empty(&lease->open_list);
220 	}
221 	spin_unlock(&lease->lock);
222 
223 	if (remove_table) {
224 		write_lock(&lease_list_lock);
225 		lease_del_table(lease);
226 		write_unlock(&lease_list_lock);
227 	}
228 }
229 
230 static void free_lease(struct oplock_info *opinfo)
231 {
232 	lease_put(opinfo->o_lease);
233 }
234 
235 static void __free_opinfo(struct oplock_info *opinfo)
236 {
237 	if (opinfo->is_lease)
238 		free_lease(opinfo);
239 	ksmbd_conn_put(opinfo->conn);
240 	kfree(opinfo);
241 }
242 
243 static void free_opinfo_rcu(struct rcu_head *rcu)
244 {
245 	struct oplock_info *opinfo = container_of(rcu, struct oplock_info, rcu);
246 
247 	__free_opinfo(opinfo);
248 }
249 
250 static void free_opinfo(struct oplock_info *opinfo)
251 {
252 	call_rcu(&opinfo->rcu, free_opinfo_rcu);
253 }
254 
255 void lease_update_oplock_levels(struct lease *lease)
256 {
257 	struct oplock_info *opinfo;
258 	__u8 level;
259 
260 	if (!lease)
261 		return;
262 
263 	level = smb2_map_lease_to_oplock(lease->state);
264 	spin_lock(&lease->lock);
265 	list_for_each_entry(opinfo, &lease->open_list, lease_entry)
266 		opinfo->level = level;
267 	spin_unlock(&lease->lock);
268 }
269 
270 struct oplock_info *opinfo_get(struct ksmbd_file *fp)
271 {
272 	struct oplock_info *opinfo;
273 
274 	rcu_read_lock();
275 	opinfo = rcu_dereference(fp->f_opinfo);
276 	if (opinfo && !atomic_inc_not_zero(&opinfo->refcount))
277 		opinfo = NULL;
278 	rcu_read_unlock();
279 
280 	return opinfo;
281 }
282 
283 struct oplock_snapshot {
284 	bool durable_open;
285 	bool durable_detached;
286 	unsigned long long fid;
287 };
288 
289 static struct oplock_info *opinfo_get_list(struct ksmbd_inode *ci,
290 					   struct ksmbd_file *skip_fp,
291 					   struct oplock_snapshot *snapshot)
292 {
293 	struct oplock_info *opinfo;
294 
295 	if (snapshot) {
296 		snapshot->durable_open = false;
297 		snapshot->durable_detached = false;
298 		snapshot->fid = KSMBD_NO_FID;
299 	}
300 
301 	down_read(&ci->m_lock);
302 	opinfo = list_first_entry_or_null(&ci->m_op_list, struct oplock_info,
303 					  op_entry);
304 	if (opinfo) {
305 		if (opinfo->conn == NULL ||
306 		    !atomic_inc_not_zero(&opinfo->refcount))
307 			opinfo = NULL;
308 		else {
309 			if (ksmbd_conn_releasing(opinfo->conn)) {
310 				atomic_dec(&opinfo->refcount);
311 				opinfo = NULL;
312 			}
313 		}
314 
315 		if (opinfo && snapshot && opinfo->o_fp &&
316 		    opinfo->o_fp != skip_fp &&
317 		    READ_ONCE(opinfo->o_fp->is_durable)) {
318 			snapshot->durable_open = true;
319 			snapshot->durable_detached =
320 				!READ_ONCE(opinfo->o_fp->conn) ||
321 				!READ_ONCE(opinfo->o_fp->tcon);
322 			snapshot->fid = opinfo->fid;
323 		}
324 	}
325 	up_read(&ci->m_lock);
326 
327 	return opinfo;
328 }
329 
330 void opinfo_put(struct oplock_info *opinfo)
331 {
332 	if (!opinfo)
333 		return;
334 
335 	if (!atomic_dec_and_test(&opinfo->refcount))
336 		return;
337 
338 	free_opinfo(opinfo);
339 }
340 
341 static bool ksmbd_inode_has_lease(struct ksmbd_inode *ci)
342 {
343 	struct oplock_info *opinfo = opinfo_get_list(ci, NULL, NULL);
344 	bool is_lease;
345 
346 	if (!opinfo)
347 		return false;
348 	is_lease = opinfo->is_lease;
349 	opinfo_put(opinfo);
350 	return is_lease;
351 }
352 
353 static void opinfo_add(struct oplock_info *opinfo, struct ksmbd_file *fp)
354 {
355 	struct ksmbd_inode *ci = fp->f_ci;
356 
357 	down_write(&ci->m_lock);
358 	list_add(&opinfo->op_entry, &ci->m_op_list);
359 	up_write(&ci->m_lock);
360 }
361 
362 static void opinfo_del(struct oplock_info *opinfo)
363 {
364 	struct ksmbd_inode *ci = opinfo->o_fp->f_ci;
365 
366 	if (opinfo->is_lease)
367 		lease_del_open(opinfo);
368 
369 	down_write(&ci->m_lock);
370 	list_del(&opinfo->op_entry);
371 	up_write(&ci->m_lock);
372 }
373 
374 static unsigned long opinfo_count(struct ksmbd_file *fp)
375 {
376 	if (ksmbd_stream_fd(fp))
377 		return atomic_read(&fp->f_ci->sop_count);
378 	else
379 		return atomic_read(&fp->f_ci->op_count);
380 }
381 
382 static void opinfo_count_inc(struct ksmbd_file *fp)
383 {
384 	if (ksmbd_stream_fd(fp))
385 		return atomic_inc(&fp->f_ci->sop_count);
386 	else
387 		return atomic_inc(&fp->f_ci->op_count);
388 }
389 
390 static void opinfo_count_dec(struct ksmbd_file *fp)
391 {
392 	if (ksmbd_stream_fd(fp))
393 		return atomic_dec(&fp->f_ci->sop_count);
394 	else
395 		return atomic_dec(&fp->f_ci->op_count);
396 }
397 
398 /**
399  * opinfo_write_to_read() - convert a write oplock to read oplock
400  * @opinfo:		current oplock info
401  *
402  * Return:      0 on success, otherwise -EINVAL
403  */
404 int opinfo_write_to_read(struct oplock_info *opinfo)
405 {
406 	struct lease *lease = opinfo->o_lease;
407 
408 	if (!(opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
409 	      opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)) {
410 		pr_err("bad oplock(0x%x)\n", opinfo->level);
411 		if (opinfo->is_lease)
412 			pr_err("lease state(0x%x)\n", lease->state);
413 		return -EINVAL;
414 	}
415 	opinfo->level = SMB2_OPLOCK_LEVEL_II;
416 
417 	if (opinfo->is_lease) {
418 		lease->state = lease->new_state;
419 		lease_update_oplock_levels(lease);
420 	}
421 	return 0;
422 }
423 
424 /**
425  * opinfo_read_handle_to_read() - convert a read/handle oplock to read oplock
426  * @opinfo:		current oplock info
427  *
428  * Return:      0 on success, otherwise -EINVAL
429  */
430 int opinfo_read_handle_to_read(struct oplock_info *opinfo)
431 {
432 	struct lease *lease = opinfo->o_lease;
433 
434 	lease->state = lease->new_state;
435 	lease_update_oplock_levels(lease);
436 	return 0;
437 }
438 
439 /**
440  * opinfo_write_to_none() - convert a write oplock to none
441  * @opinfo:	current oplock info
442  *
443  * Return:      0 on success, otherwise -EINVAL
444  */
445 int opinfo_write_to_none(struct oplock_info *opinfo)
446 {
447 	struct lease *lease = opinfo->o_lease;
448 
449 	if (!(opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
450 	      opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)) {
451 		pr_err("bad oplock(0x%x)\n", opinfo->level);
452 		if (opinfo->is_lease)
453 			pr_err("lease state(0x%x)\n", lease->state);
454 		return -EINVAL;
455 	}
456 	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
457 	if (opinfo->is_lease) {
458 		lease->state = lease->new_state;
459 		lease_update_oplock_levels(lease);
460 	}
461 	return 0;
462 }
463 
464 /**
465  * opinfo_read_to_none() - convert a write read to none
466  * @opinfo:	current oplock info
467  *
468  * Return:      0 on success, otherwise -EINVAL
469  */
470 int opinfo_read_to_none(struct oplock_info *opinfo)
471 {
472 	struct lease *lease = opinfo->o_lease;
473 
474 	if (opinfo->level != SMB2_OPLOCK_LEVEL_II) {
475 		pr_err("bad oplock(0x%x)\n", opinfo->level);
476 		if (opinfo->is_lease)
477 			pr_err("lease state(0x%x)\n", lease->state);
478 		return -EINVAL;
479 	}
480 	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
481 	if (opinfo->is_lease) {
482 		lease->state = lease->new_state;
483 		lease_update_oplock_levels(lease);
484 	}
485 	return 0;
486 }
487 
488 /**
489  * lease_read_to_write() - upgrade lease state from read to write
490  * @opinfo:	current lease info
491  *
492  * Return:      0 on success, otherwise -EINVAL
493  */
494 int lease_read_to_write(struct oplock_info *opinfo)
495 {
496 	struct lease *lease = opinfo->o_lease;
497 
498 	if (!(lease->state & SMB2_LEASE_READ_CACHING_LE)) {
499 		ksmbd_debug(OPLOCK, "bad lease state(0x%x)\n", lease->state);
500 		return -EINVAL;
501 	}
502 
503 	lease->new_state = SMB2_LEASE_NONE_LE;
504 	lease->state |= SMB2_LEASE_WRITE_CACHING_LE;
505 	lease_update_oplock_levels(lease);
506 	return 0;
507 }
508 
509 /**
510  * lease_none_upgrade() - upgrade lease state from none
511  * @opinfo:	current lease info
512  * @new_state:	new lease state
513  *
514  * Return:	0 on success, otherwise -EINVAL
515  */
516 static int lease_none_upgrade(struct oplock_info *opinfo, __le32 new_state)
517 {
518 	struct lease *lease = opinfo->o_lease;
519 
520 	if (!(lease->state == SMB2_LEASE_NONE_LE)) {
521 		ksmbd_debug(OPLOCK, "bad lease state(0x%x)\n", lease->state);
522 		return -EINVAL;
523 	}
524 
525 	lease->new_state = SMB2_LEASE_NONE_LE;
526 	lease->state = new_state;
527 	lease_update_oplock_levels(lease);
528 
529 	return 0;
530 }
531 
532 /**
533  * close_id_del_oplock() - release oplock object at file close time
534  * @fp:		ksmbd file pointer
535  */
536 void close_id_del_oplock(struct ksmbd_file *fp)
537 {
538 	struct oplock_info *opinfo;
539 
540 	if (fp->reserve_lease_break)
541 		smb_lazy_parent_lease_break_close(fp);
542 
543 	opinfo = opinfo_get(fp);
544 	if (!opinfo)
545 		return;
546 
547 	opinfo_del(opinfo);
548 
549 	rcu_assign_pointer(fp->f_opinfo, NULL);
550 	spin_lock(&opinfo->state_lock);
551 	if (opinfo->op_state == OPLOCK_ACK_WAIT && opinfo->is_lease)
552 		atomic_set(&opinfo->breaking_cnt, 0);
553 	/*
554 	 * An opinfo that has been removed from the inode list is terminal. Keep
555 	 * this transition and releasing pending_break under state_lock. a breaker
556 	 * takes the same lock before it acquires pending_break or sets ACK_WAIT.
557 	 */
558 	opinfo->op_state = OPLOCK_CLOSING;
559 	clear_bit_unlock(0, &opinfo->pending_break);
560 	spin_unlock(&opinfo->state_lock);
561 	wake_up_interruptible_all(&opinfo->oplock_q);
562 	if (opinfo->is_lease)
563 		wake_up_interruptible_all(&opinfo->oplock_brk);
564 	/* memory barrier is needed for wake_up_bit() */
565 	smp_mb__after_atomic();
566 	wake_up_bit(&opinfo->pending_break, 0);
567 
568 	opinfo_count_dec(fp);
569 	atomic_dec(&opinfo->refcount);
570 	opinfo_put(opinfo);
571 }
572 
573 /**
574  * grant_write_oplock() - grant exclusive/batch oplock or write lease
575  * @opinfo_new:	new oplock info object
576  * @req_oplock: request oplock
577  * @lctx:	lease context information
578  *
579  * Return:      0
580  */
581 static void grant_write_oplock(struct oplock_info *opinfo_new, int req_oplock,
582 			       struct lease_ctx_info *lctx)
583 {
584 	struct lease *lease = opinfo_new->o_lease;
585 
586 	if (req_oplock == SMB2_OPLOCK_LEVEL_BATCH)
587 		opinfo_new->level = SMB2_OPLOCK_LEVEL_BATCH;
588 	else
589 		opinfo_new->level = SMB2_OPLOCK_LEVEL_EXCLUSIVE;
590 
591 	if (lctx) {
592 		lease->state = lctx->req_state;
593 		memcpy(lease->lease_key, lctx->lease_key, SMB2_LEASE_KEY_SIZE);
594 	}
595 }
596 
597 /**
598  * grant_read_oplock() - grant level2 oplock or read lease
599  * @opinfo_new:	new oplock info object
600  * @lctx:	lease context information
601  *
602  * Return:      0
603  */
604 static void grant_read_oplock(struct oplock_info *opinfo_new,
605 			      struct lease_ctx_info *lctx)
606 {
607 	struct lease *lease = opinfo_new->o_lease;
608 
609 	opinfo_new->level = SMB2_OPLOCK_LEVEL_II;
610 
611 	if (lctx) {
612 		lease->state = SMB2_LEASE_READ_CACHING_LE;
613 		if (lctx->req_state & SMB2_LEASE_HANDLE_CACHING_LE)
614 			lease->state |= SMB2_LEASE_HANDLE_CACHING_LE;
615 		memcpy(lease->lease_key, lctx->lease_key, SMB2_LEASE_KEY_SIZE);
616 	}
617 }
618 
619 /**
620  * grant_none_oplock() - grant none oplock or none lease
621  * @opinfo_new:	new oplock info object
622  * @lctx:	lease context information
623  *
624  * Return:      0
625  */
626 static void grant_none_oplock(struct oplock_info *opinfo_new,
627 			      struct lease_ctx_info *lctx)
628 {
629 	struct lease *lease = opinfo_new->o_lease;
630 
631 	opinfo_new->level = SMB2_OPLOCK_LEVEL_NONE;
632 
633 	if (lctx) {
634 		lease->state = 0;
635 		memcpy(lease->lease_key, lctx->lease_key, SMB2_LEASE_KEY_SIZE);
636 	}
637 }
638 
639 static inline int compare_guid_key(struct oplock_info *opinfo,
640 				   const char *guid1, const char *key1)
641 {
642 	const char *guid2, *key2;
643 	struct ksmbd_conn *conn;
644 
645 	conn = READ_ONCE(opinfo->conn);
646 	if (!conn)
647 		return 0;
648 	guid2 = conn->ClientGUID;
649 	key2 = opinfo->o_lease->lease_key;
650 	if (!memcmp(guid1, guid2, SMB2_CLIENT_GUID_SIZE) &&
651 	    !memcmp(key1, key2, SMB2_LEASE_KEY_SIZE))
652 		return 1;
653 
654 	return 0;
655 }
656 
657 /**
658  * same_client_has_lease() - check whether current lease request is
659  *		from lease owner of file
660  * @ci:		master file pointer
661  * @client_guid:	Client GUID
662  * @lctx:		lease context information
663  *
664  * Return:      oplock(lease) object on success, otherwise NULL
665  */
666 static struct oplock_info *same_client_has_lease(struct ksmbd_inode *ci,
667 						 const char *client_guid,
668 						 struct lease_ctx_info *lctx)
669 {
670 	int ret;
671 	struct lease *lease;
672 	struct oplock_info *opinfo;
673 	struct oplock_info *m_opinfo = NULL;
674 
675 	if (!lctx)
676 		return NULL;
677 
678 	/*
679 	 * Compare lease key and client_guid to know request from same owner
680 	 * of same client
681 	 */
682 	down_read(&ci->m_lock);
683 	list_for_each_entry(opinfo, &ci->m_op_list, op_entry) {
684 		if (!opinfo->is_lease || !opinfo->conn)
685 			continue;
686 		lease = opinfo->o_lease;
687 
688 		ret = compare_guid_key(opinfo, client_guid, lctx->lease_key);
689 		if (ret) {
690 			if (!atomic_inc_not_zero(&opinfo->refcount))
691 				continue;
692 			if (m_opinfo)
693 				opinfo_put(m_opinfo);
694 			m_opinfo = opinfo;
695 
696 			/* skip upgrading lease about breaking lease */
697 			if (atomic_read(&opinfo->breaking_cnt))
698 				continue;
699 
700 			/* upgrading lease */
701 			if ((atomic_read(&ci->op_count) +
702 			     atomic_read(&ci->sop_count)) == 1) {
703 				if (lease->state != SMB2_LEASE_NONE_LE &&
704 				    lease->state == (lctx->req_state & lease->state)) {
705 					lease->epoch++;
706 					lease->state |= lctx->req_state;
707 					if (lctx->req_state &
708 						SMB2_LEASE_WRITE_CACHING_LE)
709 						lease_read_to_write(opinfo);
710 
711 				}
712 			} else if ((atomic_read(&ci->op_count) +
713 				    atomic_read(&ci->sop_count)) > 1) {
714 				if (lctx->req_state ==
715 				    (SMB2_LEASE_READ_CACHING_LE |
716 				     SMB2_LEASE_HANDLE_CACHING_LE)) {
717 					if (lease->state != lctx->req_state) {
718 						lease->epoch++;
719 						lease->state = lctx->req_state;
720 						lease_update_oplock_levels(lease);
721 					}
722 				}
723 			}
724 
725 			if (lctx->req_state && lease->state ==
726 			    SMB2_LEASE_NONE_LE) {
727 				lease->epoch++;
728 				lease_none_upgrade(opinfo, lctx->req_state);
729 			}
730 		}
731 	}
732 	up_read(&ci->m_lock);
733 
734 	return m_opinfo;
735 }
736 
737 static bool wait_for_break_ack(struct oplock_info *opinfo)
738 {
739 	int rc = 0;
740 
741 	rc = wait_event_interruptible_timeout(opinfo->oplock_q,
742 					      opinfo->op_state == OPLOCK_STATE_NONE ||
743 					      opinfo->op_state == OPLOCK_CLOSING,
744 					      OPLOCK_WAIT_TIME);
745 
746 	/* is this a timeout ? */
747 	if (!rc) {
748 		spin_lock(&opinfo->state_lock);
749 		if (opinfo->op_state == OPLOCK_CLOSING) {
750 			spin_unlock(&opinfo->state_lock);
751 			return false;
752 		}
753 		if (opinfo->is_lease) {
754 			opinfo->o_lease->state = SMB2_LEASE_NONE_LE;
755 			lease_update_oplock_levels(opinfo->o_lease);
756 		}
757 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
758 		opinfo->op_state = OPLOCK_STATE_NONE;
759 		spin_unlock(&opinfo->state_lock);
760 		return true;
761 	}
762 
763 	return false;
764 }
765 
766 static void wake_up_oplock_break(struct oplock_info *opinfo)
767 {
768 	clear_bit_unlock(0, &opinfo->pending_break);
769 	/* memory barrier is needed for wake_up_bit() */
770 	smp_mb__after_atomic();
771 	wake_up_bit(&opinfo->pending_break, 0);
772 }
773 
774 static bool oplock_break_set_ack_wait(struct oplock_info *opinfo)
775 {
776 	bool ret = false;
777 
778 	spin_lock(&opinfo->state_lock);
779 	if (opinfo->op_state != OPLOCK_CLOSING) {
780 		opinfo->op_state = OPLOCK_ACK_WAIT;
781 		ret = true;
782 	}
783 	spin_unlock(&opinfo->state_lock);
784 
785 	return ret;
786 }
787 
788 static int oplock_break_pending(struct oplock_info *opinfo, int req_op_level)
789 {
790 	for (;;) {
791 		bool closing;
792 
793 		spin_lock(&opinfo->state_lock);
794 		closing = opinfo->op_state == OPLOCK_CLOSING;
795 		if (!closing && !test_and_set_bit(0, &opinfo->pending_break)) {
796 			spin_unlock(&opinfo->state_lock);
797 			break;
798 		}
799 		spin_unlock(&opinfo->state_lock);
800 		if (closing)
801 			return -ENOENT;
802 
803 		if (opinfo->is_lease)
804 			opinfo->o_lease->reuse_epoch = true;
805 
806 		wait_on_bit(&opinfo->pending_break, 0, TASK_UNINTERRUPTIBLE);
807 
808 		/* Not immediately break to none. */
809 		opinfo->open_trunc = 0;
810 
811 		spin_lock(&opinfo->state_lock);
812 		closing = opinfo->op_state == OPLOCK_CLOSING;
813 		spin_unlock(&opinfo->state_lock);
814 		if (closing)
815 			return -ENOENT;
816 		if (opinfo->level <= req_op_level) {
817 			if (opinfo->is_lease == false)
818 				return 1;
819 
820 			if (opinfo->o_lease->state !=
821 			    (SMB2_LEASE_HANDLE_CACHING_LE |
822 			     SMB2_LEASE_READ_CACHING_LE))
823 				return 1;
824 		}
825 	}
826 
827 	if (opinfo->level <= req_op_level) {
828 		if (opinfo->is_lease == false) {
829 			wake_up_oplock_break(opinfo);
830 			return 1;
831 		}
832 		if (opinfo->o_lease->state !=
833 		    (SMB2_LEASE_HANDLE_CACHING_LE |
834 		     SMB2_LEASE_READ_CACHING_LE)) {
835 			wake_up_oplock_break(opinfo);
836 			return 1;
837 		}
838 	}
839 	return 0;
840 }
841 
842 static bool lease_break_needed(struct oplock_info *opinfo, int req_op_level,
843 			       bool open_trunc)
844 {
845 	struct lease *lease = opinfo->o_lease;
846 
847 	if (open_trunc)
848 		return lease->state != SMB2_LEASE_NONE_LE;
849 
850 	return opinfo->level > req_op_level;
851 }
852 
853 /**
854  * __smb2_oplock_break_noti() - send smb2 oplock break cmd from conn
855  * to client
856  * @wk:     smb work object
857  *
858  * There are two ways this function can be called. 1- while file open we break
859  * from exclusive/batch lock to levelII oplock and 2- while file write/truncate
860  * we break from levelII oplock no oplock.
861  * work->request_buf contains oplock_info.
862  */
863 static void __smb2_oplock_break_noti(struct work_struct *wk)
864 {
865 	struct smb2_oplock_break *rsp = NULL;
866 	struct ksmbd_work *work = container_of(wk, struct ksmbd_work, work);
867 	struct ksmbd_conn *conn = work->conn;
868 	struct oplock_break_info *br_info = work->request_buf;
869 	struct smb2_hdr *rsp_hdr;
870 	struct ksmbd_file *fp;
871 
872 	fp = ksmbd_lookup_global_fd(br_info->fid);
873 	if (!fp)
874 		goto out;
875 
876 	if (allocate_interim_rsp_buf(work)) {
877 		pr_err("smb2_allocate_rsp_buf failed! ");
878 		ksmbd_fd_put(work, fp);
879 		goto out;
880 	}
881 
882 	rsp_hdr = smb_get_msg(work->response_buf);
883 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
884 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
885 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
886 	rsp_hdr->CreditRequest = cpu_to_le16(0);
887 	rsp_hdr->Command = SMB2_OPLOCK_BREAK;
888 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
889 	rsp_hdr->NextCommand = 0;
890 	rsp_hdr->MessageId = cpu_to_le64(-1);
891 	rsp_hdr->Id.SyncId.ProcessId = 0;
892 	rsp_hdr->Id.SyncId.TreeId = 0;
893 	rsp_hdr->SessionId = 0;
894 	memset(rsp_hdr->Signature, 0, 16);
895 
896 	rsp = smb_get_msg(work->response_buf);
897 
898 	rsp->StructureSize = cpu_to_le16(24);
899 	if (!br_info->open_trunc &&
900 	    (br_info->level == SMB2_OPLOCK_LEVEL_BATCH ||
901 	     br_info->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
902 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_II;
903 	else
904 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
905 	rsp->Reserved = 0;
906 	rsp->Reserved2 = 0;
907 	rsp->PersistentFid = fp->persistent_id;
908 	rsp->VolatileFid = fp->volatile_id;
909 
910 	ksmbd_fd_put(work, fp);
911 	if (ksmbd_iov_pin_rsp(work, (void *)rsp,
912 			      sizeof(struct smb2_oplock_break)))
913 		goto out;
914 
915 	ksmbd_debug(OPLOCK,
916 		    "sending oplock break v_id %llu p_id = %llu lock level = %d\n",
917 		    rsp->VolatileFid, rsp->PersistentFid, rsp->OplockLevel);
918 
919 	ksmbd_conn_write(work);
920 
921 out:
922 	ksmbd_free_work_struct(work);
923 	ksmbd_conn_r_count_dec(conn);
924 	ksmbd_conn_put(conn);
925 }
926 
927 /*
928  * Select and pin the connection used for an oplock break before doing any
929  * allocations which may sleep.  The caller of oplock_break() holds a live
930  * reference on ci (a file being opened, a file being operated on, or an
931  * explicit ksmbd_inode_lookup_lock() reference in the parent lease break
932  * paths), so the inode cannot be freed during the call and its lock is
933  * reachable without dereferencing opinfo->o_fp, which is not pinned by
934  * the oplock reference and may be freed by a concurrent close.
935  *
936  * opinfo->conn is cleared under ci->m_lock by session_fd_check() when the
937  * durable handle owning the oplock is disconnected, reassigned by
938  * ksmbd_reopen_durable_fd() under the same lock, and the last
939  * ksmbd_conn_put() of the old connection frees it.  Holding the read lock
940  * excludes both writers, so the connection cannot be freed while it is
941  * selected.
942  */
943 static struct ksmbd_conn *smb2_oplock_break_conn_get(struct oplock_info *opinfo,
944 						     struct ksmbd_inode *ci)
945 {
946 	struct ksmbd_conn *conn;
947 
948 	down_read(&ci->m_lock);
949 	conn = READ_ONCE(opinfo->conn);
950 	if (conn && !ksmbd_conn_releasing(conn))
951 		conn = ksmbd_conn_get(conn);
952 	else
953 		conn = NULL;
954 	up_read(&ci->m_lock);
955 
956 	return conn;
957 }
958 
959 /**
960  * smb2_oplock_break_noti() - send smb2 exclusive/batch to level2 oplock
961  *		break command from server to client
962  * @opinfo:		oplock info object
963  * @ci:		inode owning the break target's oplock list, pinned by
964  *		the caller
965  *
966  * Return:      0 on success, otherwise error
967  */
968 static int smb2_oplock_break_noti(struct oplock_info *opinfo,
969 				  struct ksmbd_inode *ci)
970 {
971 	struct ksmbd_conn *conn;
972 	struct oplock_break_info *br_info;
973 	int ret = 0;
974 	struct ksmbd_work *work;
975 
976 	conn = smb2_oplock_break_conn_get(opinfo, ci);
977 	if (!conn)
978 		return ksmbd_invalidate_durable_fd(opinfo->fid);
979 
980 	work = ksmbd_alloc_work_struct();
981 	if (!work) {
982 		ksmbd_conn_put(conn);
983 		return -ENOMEM;
984 	}
985 
986 	br_info = kmalloc_obj(struct oplock_break_info, KSMBD_DEFAULT_GFP);
987 	if (!br_info) {
988 		ksmbd_free_work_struct(work);
989 		ksmbd_conn_put(conn);
990 		return -ENOMEM;
991 	}
992 
993 	br_info->level = opinfo->level;
994 	br_info->fid = opinfo->fid;
995 	br_info->open_trunc = opinfo->open_trunc;
996 
997 	work->request_buf = (char *)br_info;
998 	/* Transfer the reference acquired by smb2_oplock_break_conn_get(). */
999 	work->conn = conn;
1000 	work->sess = opinfo->sess;
1001 
1002 	ksmbd_conn_r_count_inc(conn);
1003 	if (opinfo->op_state == OPLOCK_ACK_WAIT) {
1004 		INIT_WORK(&work->work, __smb2_oplock_break_noti);
1005 		ksmbd_queue_work(work);
1006 
1007 		if (wait_for_break_ack(opinfo))
1008 			ret = ksmbd_invalidate_durable_fd(opinfo->fid);
1009 	} else {
1010 		__smb2_oplock_break_noti(&work->work);
1011 		if (opinfo->level == SMB2_OPLOCK_LEVEL_II)
1012 			opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
1013 	}
1014 	return ret;
1015 }
1016 
1017 /**
1018  * __smb2_lease_break_noti() - send lease break command from server
1019  * to client
1020  * @wk:     smb work object
1021  */
1022 static void __smb2_lease_break_noti(struct work_struct *wk)
1023 {
1024 	struct smb2_lease_break *rsp = NULL;
1025 	struct ksmbd_work *work = container_of(wk, struct ksmbd_work, work);
1026 	struct ksmbd_conn *conn = work->conn;
1027 	struct lease_break_info *br_info = work->request_buf;
1028 	struct smb2_hdr *rsp_hdr;
1029 
1030 	if (allocate_interim_rsp_buf(work)) {
1031 		ksmbd_debug(OPLOCK, "smb2_allocate_rsp_buf failed! ");
1032 		goto out;
1033 	}
1034 
1035 	rsp_hdr = smb_get_msg(work->response_buf);
1036 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
1037 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
1038 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
1039 	rsp_hdr->CreditRequest = cpu_to_le16(0);
1040 	rsp_hdr->Command = SMB2_OPLOCK_BREAK;
1041 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
1042 	rsp_hdr->NextCommand = 0;
1043 	rsp_hdr->MessageId = cpu_to_le64(-1);
1044 	rsp_hdr->Id.SyncId.ProcessId = 0;
1045 	rsp_hdr->Id.SyncId.TreeId = 0;
1046 	rsp_hdr->SessionId = 0;
1047 	memset(rsp_hdr->Signature, 0, 16);
1048 
1049 	rsp = smb_get_msg(work->response_buf);
1050 	rsp->StructureSize = cpu_to_le16(44);
1051 	rsp->Epoch = br_info->epoch;
1052 	rsp->Flags = 0;
1053 
1054 	if (br_info->curr_state & (SMB2_LEASE_WRITE_CACHING_LE |
1055 			SMB2_LEASE_HANDLE_CACHING_LE))
1056 		rsp->Flags = SMB2_NOTIFY_BREAK_LEASE_FLAG_ACK_REQUIRED;
1057 
1058 	memcpy(rsp->LeaseKey, br_info->lease_key, SMB2_LEASE_KEY_SIZE);
1059 	rsp->CurrentLeaseState = br_info->curr_state;
1060 	rsp->NewLeaseState = br_info->new_state;
1061 	rsp->BreakReason = 0;
1062 	rsp->AccessMaskHint = 0;
1063 	rsp->ShareMaskHint = 0;
1064 
1065 	if (ksmbd_iov_pin_rsp(work, (void *)rsp,
1066 			      sizeof(struct smb2_lease_break)))
1067 		goto out;
1068 
1069 	ksmbd_conn_write(work);
1070 
1071 out:
1072 	ksmbd_free_work_struct(work);
1073 	ksmbd_conn_r_count_dec(conn);
1074 	ksmbd_conn_put(conn);
1075 }
1076 
1077 /*
1078  * Select and pin the connection used for a lease break before doing any
1079  * allocations which may sleep. opinfo->conn is cleared under ci->m_lock,
1080  * while lease->l_lb and the lease table lifetime are protected by
1081  * lease_list_lock.
1082  */
1083 static struct ksmbd_conn *smb2_lease_break_conn_get(struct oplock_info *opinfo)
1084 {
1085 	struct lease *lease = opinfo->o_lease;
1086 	struct lease_table *lb;
1087 	struct ksmbd_conn *conn;
1088 
1089 	/* Keep the connection which owns the open, when it is still active. */
1090 	down_read(&lease->ci->m_lock);
1091 	conn = READ_ONCE(opinfo->conn);
1092 	if (conn && !ksmbd_conn_releasing(conn))
1093 		conn = ksmbd_conn_get(conn);
1094 	else
1095 		conn = NULL;
1096 	up_read(&lease->ci->m_lock);
1097 
1098 	if (conn || lease->version != 2)
1099 		return conn;
1100 
1101 	/* Otherwise route v2 lease breaks through the shared lease channel. */
1102 	read_lock(&lease_list_lock);
1103 	lb = lease->l_lb;
1104 	if (lb && lb->conn && !ksmbd_conn_releasing(lb->conn))
1105 		conn = ksmbd_conn_get(lb->conn);
1106 	read_unlock(&lease_list_lock);
1107 
1108 	return conn;
1109 }
1110 
1111 /**
1112  * smb2_lease_break_noti() - break lease when a new client request
1113  *			write lease
1114  * @opinfo:		contains lease state information
1115  * @sync:		send the lease break notification synchronously
1116  * @inc_epoch:		increment the lease epoch before sending the break
1117  *
1118  * Return:	0 on success, otherwise error
1119  */
1120 static int smb2_lease_break_noti(struct oplock_info *opinfo, bool sync,
1121 				 bool inc_epoch)
1122 {
1123 	struct ksmbd_conn *conn;
1124 	struct ksmbd_work *work;
1125 	struct lease_break_info *br_info;
1126 	struct lease *lease = opinfo->o_lease;
1127 
1128 	conn = smb2_lease_break_conn_get(opinfo);
1129 	if (!conn)
1130 		return ksmbd_invalidate_durable_fd(opinfo->fid);
1131 
1132 	work = ksmbd_alloc_work_struct();
1133 	if (!work) {
1134 		ksmbd_conn_put(conn);
1135 		return -ENOMEM;
1136 	}
1137 
1138 	br_info = kmalloc_obj(struct lease_break_info, KSMBD_DEFAULT_GFP);
1139 	if (!br_info) {
1140 		ksmbd_free_work_struct(work);
1141 		ksmbd_conn_put(conn);
1142 		return -ENOMEM;
1143 	}
1144 
1145 	br_info->curr_state = lease->state;
1146 	br_info->new_state = lease->new_state;
1147 	if (lease->version == 2) {
1148 		if (inc_epoch)
1149 			lease->epoch++;
1150 		br_info->epoch = cpu_to_le16(lease->epoch);
1151 	} else {
1152 		br_info->epoch = 0;
1153 	}
1154 	memcpy(br_info->lease_key, lease->lease_key, SMB2_LEASE_KEY_SIZE);
1155 
1156 	work->request_buf = (char *)br_info;
1157 	/* Transfer the reference acquired by smb2_lease_break_conn_get(). */
1158 	work->conn = conn;
1159 	work->sess = opinfo->sess;
1160 
1161 	ksmbd_conn_r_count_inc(conn);
1162 	if (opinfo->op_state == OPLOCK_ACK_WAIT) {
1163 		if (sync) {
1164 			__smb2_lease_break_noti(&work->work);
1165 		} else {
1166 			INIT_WORK(&work->work, __smb2_lease_break_noti);
1167 			ksmbd_queue_work(work);
1168 		}
1169 	} else {
1170 		__smb2_lease_break_noti(&work->work);
1171 		if (opinfo->o_lease->new_state == SMB2_LEASE_NONE_LE) {
1172 			opinfo->o_lease->state = SMB2_LEASE_NONE_LE;
1173 			lease_update_oplock_levels(opinfo->o_lease);
1174 		}
1175 	}
1176 	return 0;
1177 }
1178 
1179 static void wait_lease_breaking(struct oplock_info *opinfo)
1180 {
1181 	if (!opinfo->is_lease)
1182 		return;
1183 
1184 	wake_up_interruptible_all(&opinfo->oplock_brk);
1185 	if (atomic_read(&opinfo->breaking_cnt)) {
1186 		int ret = 0;
1187 
1188 		ret = wait_event_interruptible_timeout(opinfo->oplock_brk,
1189 						       atomic_read(&opinfo->breaking_cnt) == 0,
1190 						       HZ);
1191 		if (!ret)
1192 			atomic_set(&opinfo->breaking_cnt, 0);
1193 	}
1194 }
1195 
1196 static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
1197 			int req_op_level, struct ksmbd_work *in_work,
1198 			bool share_break, bool sync_lease_break)
1199 {
1200 	int err = 0;
1201 	bool sent_interim = false;
1202 
1203 	/* Need to break exclusive/batch oplock, write lease or overwrite_if */
1204 	ksmbd_debug(OPLOCK,
1205 		    "request to send oplock(level : 0x%x) break notification\n",
1206 		    brk_opinfo->level);
1207 
1208 	if (brk_opinfo->is_lease) {
1209 		struct lease *lease = brk_opinfo->o_lease;
1210 		bool open_trunc = brk_opinfo->open_trunc;
1211 		bool was_pending = test_bit(0, &brk_opinfo->pending_break);
1212 		bool wait_ack;
1213 		bool inc_epoch = true;
1214 
1215 		if (in_work && was_pending) {
1216 			setup_async_work(in_work, NULL, NULL);
1217 			smb2_send_interim_resp(in_work, STATUS_PENDING);
1218 			release_async_work(in_work);
1219 			sent_interim = true;
1220 		}
1221 
1222 		err = oplock_break_pending(brk_opinfo, req_op_level);
1223 		if (err)
1224 			return err < 0 ? err : 0;
1225 		if (was_pending)
1226 			open_trunc = brk_opinfo->open_trunc;
1227 
1228 again:
1229 		atomic_inc(&brk_opinfo->breaking_cnt);
1230 		if (open_trunc) {
1231 			/*
1232 			 * Create overwrite break trigger the lease break to
1233 			 * none.
1234 			 */
1235 			lease->new_state = SMB2_LEASE_NONE_LE;
1236 		} else if (share_break &&
1237 			   lease->state & SMB2_LEASE_HANDLE_CACHING_LE) {
1238 			lease->new_state =
1239 				lease->state & ~SMB2_LEASE_HANDLE_CACHING_LE;
1240 		} else {
1241 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE) {
1242 				if (lease->state & SMB2_LEASE_HANDLE_CACHING_LE)
1243 					lease->new_state =
1244 						SMB2_LEASE_READ_CACHING_LE |
1245 						SMB2_LEASE_HANDLE_CACHING_LE;
1246 				else
1247 					lease->new_state =
1248 						SMB2_LEASE_READ_CACHING_LE;
1249 			} else {
1250 				if (lease->state & SMB2_LEASE_HANDLE_CACHING_LE &&
1251 						!lease->is_dir)
1252 					lease->new_state =
1253 						SMB2_LEASE_READ_CACHING_LE;
1254 				else
1255 					lease->new_state = SMB2_LEASE_NONE_LE;
1256 			}
1257 		}
1258 
1259 		if (lease->state & (SMB2_LEASE_WRITE_CACHING_LE |
1260 				SMB2_LEASE_HANDLE_CACHING_LE)) {
1261 			if (!oplock_break_set_ack_wait(brk_opinfo)) {
1262 				atomic_dec_if_positive(&brk_opinfo->breaking_cnt);
1263 				wake_up_oplock_break(brk_opinfo);
1264 				return -ENOENT;
1265 			}
1266 		} else
1267 			atomic_dec(&brk_opinfo->breaking_cnt);
1268 
1269 		wait_ack = !(open_trunc &&
1270 			     lease->state == (SMB2_LEASE_READ_CACHING_LE |
1271 					      SMB2_LEASE_HANDLE_CACHING_LE));
1272 		if (lease->reuse_epoch) {
1273 			inc_epoch = false;
1274 			lease->reuse_epoch = false;
1275 		}
1276 		err = smb2_lease_break_noti(brk_opinfo, sync_lease_break, inc_epoch);
1277 		inc_epoch = false;
1278 		if (in_work && !sent_interim) {
1279 			setup_async_work(in_work, NULL, NULL);
1280 			smb2_send_interim_resp(in_work, STATUS_PENDING);
1281 			release_async_work(in_work);
1282 			sent_interim = true;
1283 		}
1284 		if (wait_ack && !err && wait_for_break_ack(brk_opinfo))
1285 			err = ksmbd_invalidate_durable_fd(brk_opinfo->fid);
1286 
1287 		ksmbd_debug(OPLOCK, "oplock granted = %d\n", brk_opinfo->level);
1288 		if (brk_opinfo->op_state == OPLOCK_CLOSING)
1289 			err = -ENOENT;
1290 
1291 		if (wait_ack)
1292 			wait_lease_breaking(brk_opinfo);
1293 		/*
1294 		 * A share-mode conflict break only drops the conflicting
1295 		 * caching bit; the triggering open fails with a sharing
1296 		 * violation, so keep it to a single break.
1297 		 *
1298 		 * Otherwise chain another break while the lease is still
1299 		 * incompatible with this open (req_op_level), or while a
1300 		 * truncating waiter that arrived during the break still needs
1301 		 * the lease dropped to none.  open_trunc snapshotted for this
1302 		 * break stays cleared, so the next state is computed from the
1303 		 * lease state and the cascade steps down (e.g. RH->R->none)
1304 		 * instead of collapsing straight to none.
1305 		 */
1306 		if (wait_ack && !err && !share_break &&
1307 		    (lease_break_needed(brk_opinfo, req_op_level, open_trunc) ||
1308 		     (brk_opinfo->open_trunc &&
1309 		      lease->state != SMB2_LEASE_NONE_LE)))
1310 			goto again;
1311 
1312 		wake_up_oplock_break(brk_opinfo);
1313 		return err;
1314 	} else {
1315 		err = oplock_break_pending(brk_opinfo, req_op_level);
1316 		if (err)
1317 			return err < 0 ? err : 0;
1318 
1319 		if (brk_opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
1320 		    brk_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1321 			if (!oplock_break_set_ack_wait(brk_opinfo)) {
1322 				wake_up_oplock_break(brk_opinfo);
1323 				return -ENOENT;
1324 			}
1325 		}
1326 
1327 		/*
1328 		 * Keep a conflicting CREATE asynchronous while waiting for an
1329 		 * oplock-break acknowledgement.  Besides avoiding a blocked client
1330 		 * request, this lets a replay arrive while the original CREATE is
1331 		 * still pending and be rejected with FILE_NOT_AVAILABLE.
1332 		 */
1333 		if (in_work) {
1334 			setup_async_work(in_work, NULL, NULL);
1335 			smb2_send_interim_resp(in_work, STATUS_PENDING);
1336 			release_async_work(in_work);
1337 		}
1338 	}
1339 
1340 	err = smb2_oplock_break_noti(brk_opinfo, ci);
1341 
1342 	ksmbd_debug(OPLOCK, "oplock granted = %d\n", brk_opinfo->level);
1343 	if (brk_opinfo->op_state == OPLOCK_CLOSING)
1344 		err = -EAGAIN;
1345 	wake_up_oplock_break(brk_opinfo);
1346 
1347 	return err;
1348 }
1349 
1350 struct oplock_break_entry {
1351 	struct list_head	list;
1352 	struct oplock_info	*opinfo;
1353 };
1354 
1355 static int oplock_break_add(struct list_head *head, struct oplock_info *opinfo)
1356 {
1357 	struct oplock_break_entry *ent;
1358 
1359 	ent = kmalloc_obj(struct oplock_break_entry, KSMBD_DEFAULT_GFP);
1360 	if (!ent)
1361 		return -ENOMEM;
1362 
1363 	ent->opinfo = opinfo;
1364 	list_add_tail(&ent->list, head);
1365 	return 0;
1366 }
1367 
1368 static void oplock_break_drain_none(struct list_head *head,
1369 				    struct ksmbd_inode *ci)
1370 {
1371 	struct oplock_break_entry *ent, *tmp;
1372 
1373 	list_for_each_entry_safe(ent, tmp, head, list) {
1374 		oplock_break(ent->opinfo, ci, SMB2_OPLOCK_LEVEL_NONE, NULL,
1375 			     false, false);
1376 		list_del(&ent->list);
1377 		opinfo_put(ent->opinfo);
1378 		kfree(ent);
1379 	}
1380 }
1381 
1382 void destroy_lease_table(struct ksmbd_conn *conn)
1383 {
1384 	struct lease_table *lb, *lbtmp;
1385 	struct lease *lease, *ltmp;
1386 
1387 	write_lock(&lease_list_lock);
1388 	if (list_empty(&lease_table_list)) {
1389 		write_unlock(&lease_list_lock);
1390 		return;
1391 	}
1392 
1393 	list_for_each_entry_safe(lb, lbtmp, &lease_table_list, l_entry) {
1394 		if (conn && memcmp(lb->client_guid, conn->ClientGUID,
1395 				   SMB2_CLIENT_GUID_SIZE))
1396 			continue;
1397 		list_for_each_entry_safe(lease, ltmp, &lb->lease_list, l_entry)
1398 			lease_del_table(lease);
1399 		list_del(&lb->l_entry);
1400 		free_lease_table(lb);
1401 	}
1402 	write_unlock(&lease_list_lock);
1403 }
1404 
1405 int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci,
1406 			struct lease_ctx_info *lctx)
1407 {
1408 	struct lease *lease;
1409 	int err = 0;
1410 	struct lease_table *lb;
1411 
1412 	if (!lctx)
1413 		return err;
1414 
1415 	read_lock(&lease_list_lock);
1416 	if (list_empty(&lease_table_list)) {
1417 		read_unlock(&lease_list_lock);
1418 		return 0;
1419 	}
1420 
1421 	list_for_each_entry(lb, &lease_table_list, l_entry) {
1422 		if (!memcmp(lb->client_guid, conn->ClientGUID,
1423 			    SMB2_CLIENT_GUID_SIZE))
1424 			goto found;
1425 	}
1426 	read_unlock(&lease_list_lock);
1427 
1428 	return 0;
1429 
1430 found:
1431 	list_for_each_entry(lease, &lb->lease_list, l_entry) {
1432 		if (lease->ci == ci)
1433 			continue;
1434 		if (!memcmp(lease->lease_key, lctx->lease_key,
1435 			    SMB2_LEASE_KEY_SIZE)) {
1436 			err = -EINVAL;
1437 			ksmbd_debug(OPLOCK,
1438 				    "found same lease key is already used in other files\n");
1439 			goto out;
1440 		}
1441 	}
1442 
1443 out:
1444 	read_unlock(&lease_list_lock);
1445 	return err;
1446 }
1447 
1448 static void add_lease_global_list(struct lease *lease, struct ksmbd_conn *conn,
1449 				  struct lease_table *new_lb)
1450 {
1451 	struct lease_table *lb;
1452 
1453 	write_lock(&lease_list_lock);
1454 	list_for_each_entry(lb, &lease_table_list, l_entry) {
1455 		if (!memcmp(lb->client_guid, conn->ClientGUID,
1456 			    SMB2_CLIENT_GUID_SIZE)) {
1457 			lease_add_table(lease, lb);
1458 			write_unlock(&lease_list_lock);
1459 			free_lease_table(new_lb);
1460 			return;
1461 		}
1462 	}
1463 
1464 	lease_add_table(lease, new_lb);
1465 	list_add(&new_lb->l_entry, &lease_table_list);
1466 	write_unlock(&lease_list_lock);
1467 }
1468 
1469 static void set_oplock_level(struct oplock_info *opinfo, int level,
1470 			     struct lease_ctx_info *lctx)
1471 {
1472 	switch (level) {
1473 	case SMB2_OPLOCK_LEVEL_BATCH:
1474 	case SMB2_OPLOCK_LEVEL_EXCLUSIVE:
1475 		grant_write_oplock(opinfo, level, lctx);
1476 		break;
1477 	case SMB2_OPLOCK_LEVEL_II:
1478 		grant_read_oplock(opinfo, lctx);
1479 		break;
1480 	default:
1481 		grant_none_oplock(opinfo, lctx);
1482 		break;
1483 	}
1484 }
1485 
1486 void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
1487 				      struct lease_ctx_info *lctx)
1488 {
1489 	struct oplock_info *opinfo;
1490 	struct ksmbd_inode *p_ci = NULL;
1491 	LIST_HEAD(brk_list);
1492 
1493 	if (lctx && lctx->version != 2)
1494 		return;
1495 
1496 	p_ci = ksmbd_inode_lookup_lock(fp->filp->f_path.dentry->d_parent);
1497 	if (!p_ci)
1498 		return;
1499 
1500 	down_read(&p_ci->m_lock);
1501 	list_for_each_entry(opinfo, &p_ci->m_op_list, op_entry) {
1502 		if (opinfo->conn == NULL || !opinfo->is_lease)
1503 			continue;
1504 
1505 		if (opinfo->o_lease->state != SMB2_OPLOCK_LEVEL_NONE &&
1506 		    (!lctx ||
1507 		     (!(lctx->flags & SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE) ||
1508 		      !compare_guid_key(opinfo, fp->conn->ClientGUID,
1509 			       lctx->parent_lease_key)))) {
1510 			if (!atomic_inc_not_zero(&opinfo->refcount))
1511 				continue;
1512 
1513 			if (ksmbd_conn_releasing(opinfo->conn)) {
1514 				opinfo_put(opinfo);
1515 				continue;
1516 			}
1517 
1518 			if (oplock_break_add(&brk_list, opinfo))
1519 				opinfo_put(opinfo);
1520 		}
1521 	}
1522 	up_read(&p_ci->m_lock);
1523 
1524 	oplock_break_drain_none(&brk_list, p_ci);
1525 
1526 	ksmbd_inode_put(p_ci);
1527 }
1528 
1529 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp)
1530 {
1531 	struct oplock_info *opinfo;
1532 	struct ksmbd_inode *p_ci = NULL;
1533 	LIST_HEAD(brk_list);
1534 
1535 	rcu_read_lock();
1536 	opinfo = rcu_dereference(fp->f_opinfo);
1537 
1538 	if (!opinfo || !opinfo->is_lease || opinfo->o_lease->version != 2) {
1539 		rcu_read_unlock();
1540 		return;
1541 	}
1542 	rcu_read_unlock();
1543 
1544 	p_ci = ksmbd_inode_lookup_lock(fp->filp->f_path.dentry->d_parent);
1545 	if (!p_ci)
1546 		return;
1547 
1548 	down_read(&p_ci->m_lock);
1549 	list_for_each_entry(opinfo, &p_ci->m_op_list, op_entry) {
1550 		if (opinfo->conn == NULL || !opinfo->is_lease)
1551 			continue;
1552 
1553 		if (opinfo->o_lease->state != SMB2_OPLOCK_LEVEL_NONE) {
1554 			if (!atomic_inc_not_zero(&opinfo->refcount))
1555 				continue;
1556 
1557 			if (ksmbd_conn_releasing(opinfo->conn)) {
1558 				opinfo_put(opinfo);
1559 				continue;
1560 			}
1561 
1562 			if (oplock_break_add(&brk_list, opinfo))
1563 				opinfo_put(opinfo);
1564 		}
1565 	}
1566 	up_read(&p_ci->m_lock);
1567 
1568 	oplock_break_drain_none(&brk_list, p_ci);
1569 
1570 	ksmbd_inode_put(p_ci);
1571 }
1572 
1573 /**
1574  * smb_grant_oplock() - handle oplock/lease request on file open
1575  * @work:		smb work
1576  * @req_op_level:	oplock level
1577  * @pid:		id of open file
1578  * @fp:			ksmbd file pointer
1579  * @tid:		Tree id of connection
1580  * @lctx:		lease context information on file open
1581  * @share_ret:		share mode
1582  * @replay:		whether this is a replayed CREATE request
1583  *
1584  * Return:      0 on success, otherwise error
1585  */
1586 int smb_grant_oplock(struct ksmbd_work *work, int req_op_level, u64 pid,
1587 		     struct ksmbd_file *fp, __u16 tid,
1588 		     struct lease_ctx_info *lctx, int share_ret, bool replay)
1589 {
1590 	int err = 0;
1591 	int break_level = SMB2_OPLOCK_LEVEL_II;
1592 	struct oplock_info *opinfo = NULL, *prev_opinfo = NULL;
1593 	struct ksmbd_inode *ci = fp->f_ci;
1594 	struct lease_table *new_lb = NULL;
1595 	struct oplock_snapshot prev_op_snapshot;
1596 	bool prev_op_has_lease;
1597 	bool prev_durable_open = false;
1598 	bool prev_durable_detached = false;
1599 	unsigned long long prev_fid = KSMBD_NO_FID;
1600 	bool new_lease = false;
1601 	bool break_needed;
1602 	__le32 prev_op_state = 0;
1603 
1604 	/* Only v2 leases handle the directory */
1605 	if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
1606 		if (!lctx || lctx->version != 2)
1607 			return 0;
1608 	}
1609 
1610 	opinfo = alloc_opinfo(work, pid, tid);
1611 	if (!opinfo)
1612 		return -ENOMEM;
1613 
1614 	if (lctx) {
1615 		opinfo->o_lease = alloc_lease(lctx, ci);
1616 		if (!opinfo->o_lease) {
1617 			err = -ENOMEM;
1618 			goto err_out;
1619 		}
1620 		opinfo->is_lease = 1;
1621 		new_lease = true;
1622 	}
1623 
1624 	/* ci does not have any oplock */
1625 	if (!opinfo_count(fp))
1626 		goto set_lev;
1627 
1628 	/*
1629 	 * A stat open that only requests metadata access must not break the
1630 	 * existing caching state. READ_CONTROL (reading the security
1631 	 * descriptor) does not conflict with a lease, but it does conflict
1632 	 * with an oplock, so only treat a read-control-only open as a stat
1633 	 * open when the existing holder is a lease.
1634 	 */
1635 	if (fp->cdoption != FILE_OVERWRITE_IF_LE &&
1636 	    fp->cdoption != FILE_OVERWRITE_LE &&
1637 	    fp->cdoption != FILE_SUPERSEDE_LE &&
1638 	    (fp->attrib_only ||
1639 	     (!(fp->daccess & ~(FILE_READ_ATTRIBUTES_LE |
1640 				FILE_WRITE_ATTRIBUTES_LE |
1641 				FILE_SYNCHRONIZE_LE |
1642 				FILE_READ_CONTROL_LE)) &&
1643 	      ksmbd_inode_has_lease(ci)))) {
1644 		req_op_level = SMB2_OPLOCK_LEVEL_NONE;
1645 		goto set_lev;
1646 	}
1647 
1648 	if (lctx) {
1649 		struct oplock_info *m_opinfo;
1650 
1651 		/* is lease already granted ? */
1652 		m_opinfo = same_client_has_lease(ci, work->conn->ClientGUID,
1653 						 lctx);
1654 		if (m_opinfo) {
1655 			lease_put(opinfo->o_lease);
1656 			lease_get(m_opinfo->o_lease);
1657 			opinfo->o_lease = m_opinfo->o_lease;
1658 			opinfo->level = m_opinfo->level;
1659 			new_lease = false;
1660 			opinfo_put(m_opinfo);
1661 			goto out;
1662 		}
1663 	}
1664 	prev_opinfo = opinfo_get_list(ci, fp, &prev_op_snapshot);
1665 	if (!prev_opinfo ||
1666 	    (prev_opinfo->level == SMB2_OPLOCK_LEVEL_NONE && lctx)) {
1667 		opinfo_put(prev_opinfo);
1668 		goto set_lev;
1669 	}
1670 	prev_op_has_lease = prev_opinfo->is_lease;
1671 	if (prev_op_has_lease)
1672 		prev_op_state = prev_opinfo->o_lease->state;
1673 	/*
1674 	 * A replay received while this open is waiting for an oplock or lease
1675 	 * break must not observe an intermediate level and proceed as a new
1676 	 * open. This check has to precede break_needed. an oplock may already
1677 	 * have been downgraded from Batch to II while its acknowledgement is
1678 	 * still pending.
1679 	 */
1680 	if (replay &&
1681 	    (test_bit(0, &prev_opinfo->pending_break) ||
1682 	     prev_opinfo->op_state == OPLOCK_ACK_WAIT)) {
1683 		err = -EINPROGRESS;
1684 		opinfo_put(prev_opinfo);
1685 		goto err_out;
1686 	}
1687 
1688 	if (share_ret < 0 &&
1689 	    prev_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1690 		err = share_ret;
1691 		opinfo_put(prev_opinfo);
1692 		goto err_out;
1693 	}
1694 
1695 	break_needed = prev_opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
1696 		prev_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
1697 		(share_ret < 0 && prev_op_has_lease &&
1698 		 (prev_op_state & SMB2_LEASE_HANDLE_CACHING_LE));
1699 	if (!break_needed) {
1700 		opinfo_put(prev_opinfo);
1701 		goto op_break_not_needed;
1702 	}
1703 
1704 	prev_durable_open = prev_op_snapshot.durable_open;
1705 	prev_durable_detached = prev_op_snapshot.durable_detached;
1706 	prev_fid = prev_op_snapshot.fid;
1707 
1708 	err = oplock_break(prev_opinfo, ci, break_level, work,
1709 			   share_ret < 0 && prev_opinfo->is_lease, false);
1710 	if (prev_durable_detached || (prev_durable_open && err == -ENOENT))
1711 		ksmbd_invalidate_durable_fd(prev_fid);
1712 	opinfo_put(prev_opinfo);
1713 	if (err == -EAGAIN) {
1714 		share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
1715 		if (share_ret < 0) {
1716 			err = share_ret;
1717 			goto err_out;
1718 		}
1719 		goto set_lev;
1720 	}
1721 	if (err == -ENOENT) {
1722 		/*
1723 		 * A pending durable CREATE can lose the previous oplock when
1724 		 * its holder closes the file. In that case grant the original
1725 		 * request its full caching state. Other opens still need the
1726 		 * normal shared-open downgrade below.
1727 		 */
1728 		if (!prev_durable_open &&
1729 		    req_op_level != SMB2_OPLOCK_LEVEL_NONE)
1730 			req_op_level = SMB2_OPLOCK_LEVEL_II;
1731 		goto set_lev;
1732 	}
1733 	/* Check all oplock was freed by close */
1734 	else if (err < 0)
1735 		goto err_out;
1736 
1737 op_break_not_needed:
1738 	if (share_ret < 0) {
1739 		err = share_ret;
1740 		goto err_out;
1741 	}
1742 
1743 	if (req_op_level != SMB2_OPLOCK_LEVEL_NONE)
1744 		req_op_level = SMB2_OPLOCK_LEVEL_II;
1745 
1746 	/* grant fixed oplock on stacked locking between lease and oplock */
1747 	if (prev_op_has_lease && !lctx)
1748 		if (prev_op_state & SMB2_LEASE_HANDLE_CACHING_LE)
1749 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
1750 
1751 	if (!prev_op_has_lease && lctx) {
1752 		req_op_level = SMB2_OPLOCK_LEVEL_II;
1753 		lctx->req_state = SMB2_LEASE_READ_CACHING_LE;
1754 	}
1755 
1756 set_lev:
1757 	set_oplock_level(opinfo, req_op_level, lctx);
1758 
1759 out:
1760 	/*
1761 	 * Keep the original publication order so concurrent opens can
1762 	 * still observe the in-flight grant via ci->m_op_list, but make
1763 	 * everything after opinfo_add() no-fail by preallocating any new
1764 	 * lease_table first.
1765 	 */
1766 	opinfo->o_fp = fp;
1767 	if (new_lease) {
1768 		new_lb = alloc_lease_table(opinfo);
1769 		if (!new_lb) {
1770 			err = -ENOMEM;
1771 			goto err_out;
1772 		}
1773 	}
1774 
1775 	opinfo_count_inc(fp);
1776 	opinfo_add(opinfo, fp);
1777 
1778 	if (new_lease)
1779 		add_lease_global_list(opinfo->o_lease, opinfo->conn, new_lb);
1780 	if (opinfo->is_lease)
1781 		lease_add_open(opinfo->o_lease, opinfo);
1782 
1783 	rcu_assign_pointer(fp->f_opinfo, opinfo);
1784 
1785 	return 0;
1786 err_out:
1787 	kfree(new_lb);
1788 	opinfo_put(opinfo);
1789 	return err;
1790 }
1791 
1792 /**
1793  * smb_break_all_write_oplock() - break batch/exclusive oplock to level2
1794  * @work:	smb work
1795  * @fp:		ksmbd file pointer
1796  * @is_trunc:	truncate on open
1797  */
1798 static bool smb_break_all_write_oplock(struct ksmbd_work *work,
1799 				       struct ksmbd_file *fp, int is_trunc)
1800 {
1801 	struct oplock_info *brk_opinfo;
1802 	bool sent_break = false;
1803 
1804 	brk_opinfo = opinfo_get_list(fp->f_ci, NULL, NULL);
1805 	if (!brk_opinfo)
1806 		return false;
1807 	if (brk_opinfo->level != SMB2_OPLOCK_LEVEL_BATCH &&
1808 	    brk_opinfo->level != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1809 		opinfo_put(brk_opinfo);
1810 		return false;
1811 	}
1812 
1813 	brk_opinfo->open_trunc = is_trunc;
1814 	oplock_break(brk_opinfo, fp->f_ci, SMB2_OPLOCK_LEVEL_II, work, false,
1815 		     false);
1816 	sent_break = true;
1817 	opinfo_put(brk_opinfo);
1818 
1819 	return sent_break;
1820 }
1821 
1822 /**
1823  * __smb_break_all_levII_oplock() - send level2 oplock or read lease break command
1824  *	from server to client
1825  * @work:		smb work
1826  * @fp:			ksmbd file pointer
1827  * @is_trunc:		truncate on open
1828  * @send_interim:	send interim response to the client
1829  * @send_oplock_break:	send oplock break notification to the client
1830  * @sync_lease_break:	send the lease break notification synchronously
1831  */
1832 static void __smb_break_all_levII_oplock(struct ksmbd_work *work,
1833 					 struct ksmbd_file *fp, int is_trunc,
1834 					 bool send_interim, bool send_oplock_break,
1835 					 bool sync_lease_break)
1836 {
1837 	struct oplock_info *op, *brk_op;
1838 	struct oplock_break_entry *ent, *tmp;
1839 	struct ksmbd_inode *ci;
1840 	struct ksmbd_conn *conn = work->conn;
1841 	bool sent_interim = false;
1842 	LIST_HEAD(brk_list);
1843 
1844 	if (!test_share_config_flag(work->tcon->share_conf,
1845 				    KSMBD_SHARE_FLAG_OPLOCKS))
1846 		return;
1847 
1848 	ci = fp->f_ci;
1849 	op = opinfo_get(fp);
1850 
1851 	down_read(&ci->m_lock);
1852 	list_for_each_entry(brk_op, &ci->m_op_list, op_entry) {
1853 		if (brk_op->conn == NULL)
1854 			continue;
1855 
1856 		if (!atomic_inc_not_zero(&brk_op->refcount))
1857 			continue;
1858 
1859 		if (ksmbd_conn_releasing(brk_op->conn)) {
1860 			opinfo_put(brk_op);
1861 			continue;
1862 		}
1863 
1864 		if (!brk_op->is_lease &&
1865 		    brk_op->level != SMB2_OPLOCK_LEVEL_II) {
1866 			ksmbd_debug(OPLOCK, "unexpected oplock(0x%x)\n",
1867 				    brk_op->level);
1868 			goto next;
1869 		}
1870 
1871 		/* Skip oplock being break to none */
1872 		if (brk_op->is_lease &&
1873 		    brk_op->o_lease->new_state == SMB2_LEASE_NONE_LE &&
1874 		    atomic_read(&brk_op->breaking_cnt))
1875 			goto next;
1876 
1877 		if (op && op->is_lease && brk_op->is_lease &&
1878 		    !memcmp(conn->ClientGUID, brk_op->conn->ClientGUID,
1879 			    SMB2_CLIENT_GUID_SIZE) &&
1880 		    !memcmp(op->o_lease->lease_key, brk_op->o_lease->lease_key,
1881 			    SMB2_LEASE_KEY_SIZE))
1882 			goto next;
1883 		brk_op->open_trunc = is_trunc;
1884 
1885 		/*
1886 		 * Defer the break until ci->m_lock is released: oplock_break()
1887 		 * may block waiting for the lease break acknowledgment, and the
1888 		 * close that wakes that wait needs ci->m_lock for write.
1889 		 */
1890 		if (!oplock_break_add(&brk_list, brk_op))
1891 			continue;
1892 next:
1893 		opinfo_put(brk_op);
1894 	}
1895 	up_read(&ci->m_lock);
1896 
1897 	list_for_each_entry_safe(ent, tmp, &brk_list, list) {
1898 		brk_op = ent->opinfo;
1899 
1900 		if (!brk_op->is_lease && !send_oplock_break) {
1901 			brk_op->level = SMB2_OPLOCK_LEVEL_NONE;
1902 			spin_lock(&brk_op->state_lock);
1903 			if (brk_op->op_state != OPLOCK_CLOSING)
1904 				brk_op->op_state = OPLOCK_STATE_NONE;
1905 			spin_unlock(&brk_op->state_lock);
1906 		} else {
1907 			oplock_break(brk_op, ci,
1908 				     brk_op->is_lease && !is_trunc ?
1909 				     SMB2_OPLOCK_LEVEL_II : SMB2_OPLOCK_LEVEL_NONE,
1910 				     send_interim && !sent_interim ? work : NULL,
1911 				     false, sync_lease_break);
1912 		}
1913 		sent_interim = true;
1914 		list_del(&ent->list);
1915 		opinfo_put(brk_op);
1916 		kfree(ent);
1917 	}
1918 
1919 	if (op)
1920 		opinfo_put(op);
1921 }
1922 
1923 void smb_break_all_levII_oplock(struct ksmbd_work *work, struct ksmbd_file *fp,
1924 				int is_trunc)
1925 {
1926 	__smb_break_all_levII_oplock(work, fp, is_trunc, true, true, false);
1927 }
1928 
1929 void smb_break_all_levII_oplock_rename(struct ksmbd_work *work, struct ksmbd_file *fp)
1930 {
1931 	__smb_break_all_levII_oplock(work, fp, 0, true, true, true);
1932 }
1933 
1934 void smb_break_all_levII_oplock_no_interim(struct ksmbd_work *work,
1935 					   struct ksmbd_file *fp, int is_trunc)
1936 {
1937 	__smb_break_all_levII_oplock(work, fp, is_trunc, false, true, false);
1938 }
1939 
1940 void smb_break_all_levII_oplock_for_delete(struct ksmbd_work *work,
1941 					   struct ksmbd_file *fp)
1942 {
1943 	__smb_break_all_levII_oplock(work, fp, 0, false, false, false);
1944 }
1945 
1946 /**
1947  * smb_break_all_oplock() - break both batch/exclusive and level2 oplock
1948  * @work:	smb work
1949  * @fp:		ksmbd file pointer
1950  */
1951 void smb_break_all_oplock(struct ksmbd_work *work, struct ksmbd_file *fp)
1952 {
1953 	bool sent_break;
1954 
1955 	if (!test_share_config_flag(work->tcon->share_conf,
1956 				    KSMBD_SHARE_FLAG_OPLOCKS))
1957 		return;
1958 
1959 	sent_break = smb_break_all_write_oplock(work, fp, 1);
1960 	__smb_break_all_levII_oplock(work, fp, 1, !sent_break, true, false);
1961 }
1962 
1963 /**
1964  * smb2_map_lease_to_oplock() - map lease state to corresponding oplock type
1965  * @lease_state:     lease type
1966  *
1967  * Return:      0 if no mapping, otherwise corresponding oplock type
1968  */
1969 __u8 smb2_map_lease_to_oplock(__le32 lease_state)
1970 {
1971 	if ((lease_state & SMB2_LEASE_WRITE_CACHING_LE) &&
1972 	    (lease_state & SMB2_LEASE_HANDLE_CACHING_LE)) {
1973 		return SMB2_OPLOCK_LEVEL_BATCH;
1974 	} else if (lease_state & SMB2_LEASE_WRITE_CACHING_LE) {
1975 		return SMB2_OPLOCK_LEVEL_EXCLUSIVE;
1976 	} else if (lease_state & (SMB2_LEASE_READ_CACHING_LE |
1977 				  SMB2_LEASE_HANDLE_CACHING_LE)) {
1978 		return SMB2_OPLOCK_LEVEL_II;
1979 	}
1980 	return 0;
1981 }
1982 
1983 /**
1984  * create_lease_buf() - create lease context for open cmd response
1985  * @rbuf:	buffer to create lease context response
1986  * @lease:	buffer to stored parsed lease state information
1987  */
1988 void create_lease_buf(u8 *rbuf, struct lease *lease)
1989 {
1990 	if (lease->version == 2) {
1991 		struct create_lease_v2 *buf = (struct create_lease_v2 *)rbuf;
1992 		__le32 flags = 0;
1993 
1994 		memset(buf, 0, sizeof(struct create_lease_v2));
1995 		memcpy(buf->lcontext.LeaseKey, lease->lease_key,
1996 		       SMB2_LEASE_KEY_SIZE);
1997 		if (lease_has_parent_key(lease))
1998 			flags |= SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE;
1999 		if (lease_break_in_progress(lease))
2000 			flags |= SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE;
2001 		buf->lcontext.LeaseFlags = flags;
2002 		buf->lcontext.Epoch = cpu_to_le16(lease->epoch);
2003 		buf->lcontext.LeaseState = lease->state;
2004 		if (lease_has_parent_key(lease))
2005 			memcpy(buf->lcontext.ParentLeaseKey, lease->parent_lease_key,
2006 			       SMB2_LEASE_KEY_SIZE);
2007 		buf->ccontext.DataOffset = cpu_to_le16(offsetof
2008 				(struct create_lease_v2, lcontext));
2009 		buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
2010 		buf->ccontext.NameOffset = cpu_to_le16(offsetof
2011 				(struct create_lease_v2, Name));
2012 		buf->ccontext.NameLength = cpu_to_le16(4);
2013 		buf->Name[0] = 'R';
2014 		buf->Name[1] = 'q';
2015 		buf->Name[2] = 'L';
2016 		buf->Name[3] = 's';
2017 	} else {
2018 		struct create_lease *buf = (struct create_lease *)rbuf;
2019 
2020 		memset(buf, 0, sizeof(struct create_lease));
2021 		memcpy(buf->lcontext.LeaseKey, lease->lease_key, SMB2_LEASE_KEY_SIZE);
2022 		if (lease_break_in_progress(lease))
2023 			buf->lcontext.LeaseFlags =
2024 				SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE;
2025 		buf->lcontext.LeaseState = lease->state;
2026 		buf->ccontext.DataOffset = cpu_to_le16(offsetof
2027 				(struct create_lease, lcontext));
2028 		buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
2029 		buf->ccontext.NameOffset = cpu_to_le16(offsetof
2030 				(struct create_lease, Name));
2031 		buf->ccontext.NameLength = cpu_to_le16(4);
2032 		buf->Name[0] = 'R';
2033 		buf->Name[1] = 'q';
2034 		buf->Name[2] = 'L';
2035 		buf->Name[3] = 's';
2036 	}
2037 }
2038 
2039 /**
2040  * parse_lease_state() - parse lease context contained in file open request
2041  * @open_req:	buffer containing smb2 file open(create) request
2042  *
2043  * Return: allocated lease context object on success, otherwise NULL
2044  */
2045 struct lease_ctx_info *parse_lease_state(void *open_req)
2046 {
2047 	struct create_context *cc;
2048 	struct smb2_create_req *req = (struct smb2_create_req *)open_req;
2049 	struct lease_ctx_info *lreq;
2050 
2051 	cc = smb2_find_context_vals(req, SMB2_CREATE_REQUEST_LEASE, 4);
2052 	if (IS_ERR(cc))
2053 		return ERR_CAST(cc);
2054 	if (!cc)
2055 		return NULL;
2056 
2057 	lreq = kzalloc_obj(struct lease_ctx_info, KSMBD_DEFAULT_GFP);
2058 	if (!lreq)
2059 		return ERR_PTR(-ENOMEM);
2060 
2061 	if (sizeof(struct lease_context_v2) == le32_to_cpu(cc->DataLength)) {
2062 		struct create_lease_v2 *lc = (struct create_lease_v2 *)cc;
2063 
2064 		if (le16_to_cpu(cc->DataOffset) + le32_to_cpu(cc->DataLength) <
2065 		    sizeof(struct create_lease_v2) - 4)
2066 			goto err_out;
2067 
2068 		memcpy(lreq->lease_key, lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
2069 		lreq->req_state = lc->lcontext.LeaseState;
2070 		lreq->flags = lc->lcontext.LeaseFlags;
2071 		lreq->epoch = lc->lcontext.Epoch;
2072 		lreq->duration = lc->lcontext.LeaseDuration;
2073 		if (!lease_state_valid(lreq->req_state) ||
2074 		    !lease_v2_flags_valid(lreq->flags))
2075 			goto err_out;
2076 		lreq->req_state = lease_state_grantable(lreq->req_state);
2077 		if (lreq->flags == SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE)
2078 			memcpy(lreq->parent_lease_key, lc->lcontext.ParentLeaseKey,
2079 			       SMB2_LEASE_KEY_SIZE);
2080 		lreq->version = 2;
2081 	} else if (sizeof(struct lease_context) == le32_to_cpu(cc->DataLength)) {
2082 		struct create_lease *lc = (struct create_lease *)cc;
2083 
2084 		if (le16_to_cpu(cc->DataOffset) + le32_to_cpu(cc->DataLength) <
2085 		    sizeof(struct create_lease))
2086 			goto err_out;
2087 
2088 		memcpy(lreq->lease_key, lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
2089 		lreq->req_state = lc->lcontext.LeaseState;
2090 		lreq->flags = 0;
2091 		lreq->duration = lc->lcontext.LeaseDuration;
2092 		if (!lease_state_valid(lreq->req_state))
2093 			goto err_out;
2094 		lreq->req_state = lease_state_grantable(lreq->req_state);
2095 		lreq->version = 1;
2096 	} else
2097 		goto err_out;
2098 	return lreq;
2099 err_out:
2100 	kfree(lreq);
2101 	return ERR_PTR(-EINVAL);
2102 }
2103 
2104 /**
2105  * smb2_find_context_vals() - find a particular context info in open request
2106  * @open_req:	buffer containing smb2 file open(create) request
2107  * @tag:	context name to search for
2108  * @tag_len:	the length of tag
2109  *
2110  * Return:	pointer to requested context, NULL if @str context not found
2111  *		or error pointer if name length is invalid.
2112  */
2113 struct create_context *smb2_find_context_vals(void *open_req, const char *tag, int tag_len)
2114 {
2115 	struct create_context *cc;
2116 	unsigned int next = 0;
2117 	char *name;
2118 	struct smb2_create_req *req = (struct smb2_create_req *)open_req;
2119 	unsigned int remain_len, name_off, name_len, value_off, value_len,
2120 		     cc_len;
2121 
2122 	/*
2123 	 * CreateContextsOffset and CreateContextsLength are guaranteed to
2124 	 * be valid because of ksmbd_smb2_check_message().
2125 	 */
2126 	if (!req->CreateContextsOffset || !req->CreateContextsLength)
2127 		return NULL;
2128 
2129 	cc = (struct create_context *)((char *)req +
2130 				       le32_to_cpu(req->CreateContextsOffset));
2131 	remain_len = le32_to_cpu(req->CreateContextsLength);
2132 	do {
2133 		cc = (struct create_context *)((char *)cc + next);
2134 		if (remain_len < offsetof(struct create_context, Buffer))
2135 			return ERR_PTR(-EINVAL);
2136 
2137 		next = le32_to_cpu(cc->Next);
2138 		name_off = le16_to_cpu(cc->NameOffset);
2139 		name_len = le16_to_cpu(cc->NameLength);
2140 		value_off = le16_to_cpu(cc->DataOffset);
2141 		value_len = le32_to_cpu(cc->DataLength);
2142 		cc_len = next ? next : remain_len;
2143 
2144 		if ((next & 0x7) != 0 ||
2145 		    next > remain_len ||
2146 		    name_off != offsetof(struct create_context, Buffer) ||
2147 		    name_len < 4 ||
2148 		    name_off + name_len > cc_len ||
2149 		    (value_off & 0x7) != 0 ||
2150 		    (value_len && value_off < name_off + (name_len < 8 ? 8 : name_len)) ||
2151 		    ((u64)value_off + value_len > cc_len))
2152 			return ERR_PTR(-EINVAL);
2153 
2154 		name = (char *)cc + name_off;
2155 		if (name_len == tag_len && !memcmp(name, tag, name_len))
2156 			return cc;
2157 
2158 		remain_len -= next;
2159 	} while (next != 0);
2160 
2161 	return NULL;
2162 }
2163 
2164 /**
2165  * create_durable_rsp_buf() - create durable handle context
2166  * @cc:	buffer to create durable context response
2167  */
2168 void create_durable_rsp_buf(char *cc)
2169 {
2170 	struct create_durable_rsp *buf;
2171 
2172 	buf = (struct create_durable_rsp *)cc;
2173 	memset(buf, 0, sizeof(struct create_durable_rsp));
2174 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2175 			(struct create_durable_rsp, Data));
2176 	buf->ccontext.DataLength = cpu_to_le32(8);
2177 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2178 			(struct create_durable_rsp, Name));
2179 	buf->ccontext.NameLength = cpu_to_le16(4);
2180 	/* SMB2_CREATE_DURABLE_HANDLE_RESPONSE is "DHnQ" */
2181 	buf->Name[0] = 'D';
2182 	buf->Name[1] = 'H';
2183 	buf->Name[2] = 'n';
2184 	buf->Name[3] = 'Q';
2185 }
2186 
2187 /**
2188  * create_durable_v2_rsp_buf() - create durable handle v2 context
2189  * @cc:	buffer to create durable context response
2190  * @fp: ksmbd file pointer
2191  */
2192 void create_durable_v2_rsp_buf(char *cc, struct ksmbd_file *fp)
2193 {
2194 	struct create_durable_rsp_v2 *buf;
2195 
2196 	buf = (struct create_durable_rsp_v2 *)cc;
2197 	memset(buf, 0, sizeof(*buf));
2198 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2199 			(struct create_durable_rsp_v2, dcontext));
2200 	buf->ccontext.DataLength = cpu_to_le32(8);
2201 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2202 			(struct create_durable_rsp_v2, Name));
2203 	buf->ccontext.NameLength = cpu_to_le16(4);
2204 	/* SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2 is "DH2Q" */
2205 	buf->Name[0] = 'D';
2206 	buf->Name[1] = 'H';
2207 	buf->Name[2] = '2';
2208 	buf->Name[3] = 'Q';
2209 
2210 	buf->dcontext.Timeout = cpu_to_le32(fp->durable_timeout);
2211 	if (fp->is_persistent)
2212 		buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2213 }
2214 
2215 /**
2216  * create_mxac_rsp_buf() - create query maximal access context
2217  * @cc:			buffer to create maximal access context response
2218  * @maximal_access:	maximal access
2219  */
2220 void create_mxac_rsp_buf(char *cc, int maximal_access)
2221 {
2222 	struct create_mxac_rsp *buf;
2223 
2224 	buf = (struct create_mxac_rsp *)cc;
2225 	memset(buf, 0, sizeof(struct create_mxac_rsp));
2226 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2227 			(struct create_mxac_rsp, QueryStatus));
2228 	buf->ccontext.DataLength = cpu_to_le32(8);
2229 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2230 			(struct create_mxac_rsp, Name));
2231 	buf->ccontext.NameLength = cpu_to_le16(4);
2232 	/* SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE is "MxAc" */
2233 	buf->Name[0] = 'M';
2234 	buf->Name[1] = 'x';
2235 	buf->Name[2] = 'A';
2236 	buf->Name[3] = 'c';
2237 
2238 	buf->QueryStatus = STATUS_SUCCESS;
2239 	buf->MaximalAccess = cpu_to_le32(maximal_access);
2240 }
2241 
2242 void create_disk_id_rsp_buf(char *cc, __u64 file_id, __u64 vol_id)
2243 {
2244 	struct create_disk_id_rsp *buf;
2245 
2246 	buf = (struct create_disk_id_rsp *)cc;
2247 	memset(buf, 0, sizeof(struct create_disk_id_rsp));
2248 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2249 			(struct create_disk_id_rsp, DiskFileId));
2250 	buf->ccontext.DataLength = cpu_to_le32(32);
2251 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2252 			(struct create_mxac_rsp, Name));
2253 	buf->ccontext.NameLength = cpu_to_le16(4);
2254 	/* SMB2_CREATE_QUERY_ON_DISK_ID_RESPONSE is "QFid" */
2255 	buf->Name[0] = 'Q';
2256 	buf->Name[1] = 'F';
2257 	buf->Name[2] = 'i';
2258 	buf->Name[3] = 'd';
2259 
2260 	buf->DiskFileId = cpu_to_le64(file_id);
2261 	buf->VolumeId = cpu_to_le64(vol_id);
2262 }
2263 
2264 /**
2265  * create_posix_rsp_buf() - create posix extension context
2266  * @cc:	buffer to create posix on posix response
2267  * @fp: ksmbd file pointer
2268  */
2269 void create_posix_rsp_buf(char *cc, struct ksmbd_file *fp)
2270 {
2271 	struct create_posix_rsp *buf;
2272 	struct inode *inode = file_inode(fp->filp);
2273 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
2274 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2275 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2276 
2277 	buf = (struct create_posix_rsp *)cc;
2278 	memset(buf, 0, sizeof(struct create_posix_rsp));
2279 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2280 			(struct create_posix_rsp, nlink));
2281 	/*
2282 	 * DataLength = nlink(4) + reparse_tag(4) + mode(4) +
2283 	 * domain sid(28) + unix group sid(16).
2284 	 */
2285 	buf->ccontext.DataLength = cpu_to_le32(56);
2286 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2287 			(struct create_posix_rsp, Name));
2288 	buf->ccontext.NameLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
2289 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
2290 	buf->Name[0] = 0x93;
2291 	buf->Name[1] = 0xAD;
2292 	buf->Name[2] = 0x25;
2293 	buf->Name[3] = 0x50;
2294 	buf->Name[4] = 0x9C;
2295 	buf->Name[5] = 0xB4;
2296 	buf->Name[6] = 0x11;
2297 	buf->Name[7] = 0xE7;
2298 	buf->Name[8] = 0xB4;
2299 	buf->Name[9] = 0x23;
2300 	buf->Name[10] = 0x83;
2301 	buf->Name[11] = 0xDE;
2302 	buf->Name[12] = 0x96;
2303 	buf->Name[13] = 0x8B;
2304 	buf->Name[14] = 0xCD;
2305 	buf->Name[15] = 0x7C;
2306 
2307 	buf->nlink = cpu_to_le32(inode->i_nlink);
2308 	buf->reparse_tag = cpu_to_le32(fp->volatile_id);
2309 	buf->mode = cpu_to_le32(inode->i_mode & 0777);
2310 	/*
2311 	 * SidBuffer(44) contain two sids(Domain sid(28), UNIX group sid(16)).
2312 	 * Domain sid(28) = revision(1) + num_subauth(1) + authority(6) +
2313 	 *		    sub_auth(4 * 4(num_subauth)) + RID(4).
2314 	 * UNIX group id(16) = revision(1) + num_subauth(1) + authority(6) +
2315 	 *		       sub_auth(4 * 1(num_subauth)) + RID(4).
2316 	 */
2317 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
2318 		  SIDOWNER, (struct smb_sid *)&buf->SidBuffer[0]);
2319 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
2320 		  SIDUNIX_GROUP, (struct smb_sid *)&buf->SidBuffer[28]);
2321 }
2322 
2323 /**
2324  * create_aapl_rsp_buf() - build AAPL kAAPL_SERVER_QUERY response
2325  * @cc:         buffer to write the create context into (AAPL_RSP_MAX_SIZE bytes)
2326  * @vol_caps:   volume capability flags (SMB2_CRTCTX_AAPL_* volume bits)
2327  * @req_bitmap: the client's request bitmap, echoed back in reply_bitmap
2328  *
2329  * Response format follows the layout observed from macOS's own smbd, and
2330  * matches the client-side parsing in AAPL's published public client kernel
2331  * source (public client behavior reference, kAAPL_SERVER_QUERY
2332  * case): reply_bitmap, then server_caps/vol_caps/model-info fields present
2333  * only when their reply_bitmap bit is set:
2334  *   reply_bitmap = req_bitmap masked to the fields we support
2335  *   server_caps  = AAPL_SERVER_CAPS_KSMBD when requested
2336  *   vol_caps     = caller-supplied
2337  *   model string = server_conf.aapl_model (default "Xserve") in UTF-16LE,
2338  *                  when SMB2_CRTCTX_AAPL_MODEL_INFO requested
2339  *
2340  * Sending reply_bitmap with MODEL_INFO set but no model string causes
2341  * smbfs.kext to enter a broken disconnect path requiring a macOS reboot.
2342  * @readdir_attr_v2: advertise SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2
2343  *                    instead of the V1 bit
2344  */
2345 void create_aapl_rsp_buf(char *cc, __u64 vol_caps, __u64 req_bitmap,
2346 			 bool readdir_attr_v2)
2347 {
2348 	struct create_aapl_rsp *buf;
2349 	u64 reply_bitmap;
2350 	u64 server_caps;
2351 	u32 data_len;
2352 
2353 	buf = (struct create_aapl_rsp *)cc;
2354 	memset(buf, 0, AAPL_RSP_MAX_SIZE);
2355 
2356 	reply_bitmap = req_bitmap & (SMB2_CRTCTX_AAPL_SERVER_CAPS |
2357 				     SMB2_CRTCTX_AAPL_VOLUME_CAPS |
2358 				     SMB2_CRTCTX_AAPL_MODEL_INFO);
2359 
2360 	/* base data: cmd(4)+reserved(4)+reply_bitmap(8)+server_caps(8)+vol_caps(8) */
2361 	data_len = 32;
2362 	if (reply_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO)
2363 		data_len += 4 + 4 + AAPL_MODEL_UTF16_BYTES; /* pad2+model_bytes+string */
2364 
2365 	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct create_aapl_rsp, cmd));
2366 	buf->ccontext.DataLength = cpu_to_le32(data_len);
2367 	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct create_aapl_rsp, Name));
2368 	buf->ccontext.NameLength = cpu_to_le16(SMB2_CREATE_AAPL_LEN);
2369 	buf->Name[0] = 'A';
2370 	buf->Name[1] = 'A';
2371 	buf->Name[2] = 'P';
2372 	buf->Name[3] = 'L';
2373 
2374 	buf->cmd = cpu_to_le32(SMB2_CRTCTX_AAPL_SERVER_QUERY);
2375 	buf->reply_bitmap = cpu_to_le64(reply_bitmap);
2376 	server_caps = AAPL_SERVER_CAPS_KSMBD;
2377 	if (readdir_attr_v2)
2378 		server_caps = (server_caps & ~SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) |
2379 			      SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2;
2380 	buf->server_caps = (reply_bitmap & SMB2_CRTCTX_AAPL_SERVER_CAPS) ?
2381 			   cpu_to_le64(server_caps) : 0;
2382 	buf->vol_caps = (reply_bitmap & SMB2_CRTCTX_AAPL_VOLUME_CAPS) ?
2383 			cpu_to_le64(vol_caps) : 0;
2384 
2385 	if (reply_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO) {
2386 		__le32 *p = (__le32 *)((u8 *)buf + sizeof(*buf));
2387 		__le16 *model_str = (__le16 *)(p + 2);
2388 		const char *src = server_conf.aapl_model[0] ?
2389 				  server_conf.aapl_model : "Xserve";
2390 		int i, model_bytes = 0;
2391 
2392 		/* Convert ASCII model string to UTF-16LE in-place */
2393 		for (i = 0; src[i] && i < AAPL_MODEL_MAX_CHARS; i++) {
2394 			model_str[i] = cpu_to_le16((unsigned char)src[i]);
2395 			model_bytes += 2;
2396 		}
2397 
2398 		p[0] = 0; /* pad2 */
2399 		p[1] = cpu_to_le32(model_bytes);
2400 
2401 		/* Update DataLength to reflect actual model string size */
2402 		buf->ccontext.DataLength =
2403 			cpu_to_le32(data_len - AAPL_MODEL_UTF16_BYTES + model_bytes);
2404 	}
2405 }
2406 
2407 /*
2408  * Find lease object(opinfo) for given lease key/fid from lease
2409  * break/file close path.
2410  */
2411 /**
2412  * lookup_lease_in_table() - find a matching lease info object
2413  * @conn:	connection instance
2414  * @lease_key:	lease key to be searched for
2415  *
2416  * Return:      opinfo if found matching opinfo, otherwise NULL
2417  */
2418 struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
2419 					  char *lease_key)
2420 {
2421 	struct oplock_info *opinfo = NULL, *ret_op = NULL;
2422 	struct lease *lease;
2423 	struct lease_table *lt;
2424 
2425 	read_lock(&lease_list_lock);
2426 	list_for_each_entry(lt, &lease_table_list, l_entry) {
2427 		if (!memcmp(lt->client_guid, conn->ClientGUID,
2428 			    SMB2_CLIENT_GUID_SIZE))
2429 			goto found;
2430 	}
2431 
2432 	read_unlock(&lease_list_lock);
2433 	return NULL;
2434 
2435 found:
2436 	list_for_each_entry(lease, &lt->lease_list, l_entry) {
2437 		if (memcmp(lease->lease_key, lease_key, SMB2_LEASE_KEY_SIZE))
2438 			continue;
2439 		if (!(lease->state & (SMB2_LEASE_HANDLE_CACHING_LE |
2440 				      SMB2_LEASE_WRITE_CACHING_LE)))
2441 			break;
2442 
2443 		spin_lock(&lease->lock);
2444 		list_for_each_entry(opinfo, &lease->open_list, lease_entry) {
2445 			if (!opinfo->op_state ||
2446 			    opinfo->op_state == OPLOCK_CLOSING)
2447 				continue;
2448 			if (!atomic_inc_not_zero(&opinfo->refcount))
2449 				continue;
2450 			ret_op = opinfo;
2451 		}
2452 		spin_unlock(&lease->lock);
2453 		if (ret_op) {
2454 			ksmbd_debug(OPLOCK, "found opinfo\n");
2455 			goto out;
2456 		}
2457 		break;
2458 	}
2459 
2460 out:
2461 	read_unlock(&lease_list_lock);
2462 	return ret_op;
2463 }
2464 
2465 int smb2_check_durable_oplock(struct ksmbd_conn *conn,
2466 			      struct ksmbd_share_config *share,
2467 			      struct ksmbd_file *fp,
2468 			      struct lease_ctx_info *lctx,
2469 			      struct ksmbd_user *user,
2470 			      char *name)
2471 {
2472 	struct oplock_info *opinfo = opinfo_get(fp);
2473 	int ret = 0;
2474 
2475 	if (!opinfo)
2476 		return 0;
2477 
2478 	if (ksmbd_has_other_active_fd(fp)) {
2479 		ksmbd_debug(SMB, "Durable handle reconnect failed: competing open\n");
2480 		ret = -EBADF;
2481 		goto out;
2482 	}
2483 
2484 	if (ksmbd_vfs_compare_durable_owner(fp, user) == false) {
2485 		ksmbd_debug(SMB, "Durable handle reconnect failed: owner mismatch\n");
2486 		ret = -EBADF;
2487 		goto out;
2488 	}
2489 
2490 	if (opinfo->is_lease == false) {
2491 		if (lctx) {
2492 			pr_err("create context include lease\n");
2493 			ret = -EBADF;
2494 			goto out;
2495 		}
2496 
2497 		if (opinfo->level != SMB2_OPLOCK_LEVEL_BATCH) {
2498 			pr_err("oplock level is not equal to SMB2_OPLOCK_LEVEL_BATCH\n");
2499 			ret = -EBADF;
2500 		}
2501 
2502 		goto out;
2503 	}
2504 
2505 	if (memcmp(conn->ClientGUID, fp->client_guid,
2506 				SMB2_CLIENT_GUID_SIZE)) {
2507 		ksmbd_debug(SMB, "Client guid of fp is not equal to the one of connection\n");
2508 		ret = -EBADF;
2509 		goto out;
2510 	}
2511 
2512 	if (!lctx) {
2513 		ksmbd_debug(SMB, "create context does not include lease\n");
2514 		ret = -EBADF;
2515 		goto out;
2516 	}
2517 
2518 	if (memcmp(opinfo->o_lease->lease_key, lctx->lease_key,
2519 				SMB2_LEASE_KEY_SIZE)) {
2520 		ksmbd_debug(SMB,
2521 			    "lease key of fp does not match lease key in create context\n");
2522 		ret = -EBADF;
2523 		goto out;
2524 	}
2525 
2526 	if (!(opinfo->o_lease->state & SMB2_LEASE_HANDLE_CACHING_LE)) {
2527 		ksmbd_debug(SMB, "lease state does not contain SMB2_LEASE_HANDLE_CACHING\n");
2528 		ret = -EBADF;
2529 		goto out;
2530 	}
2531 
2532 	if (opinfo->o_lease->version != lctx->version) {
2533 		ksmbd_debug(SMB,
2534 			    "lease version of fp does not match the one in create context\n");
2535 		ret = -EBADF;
2536 		goto out;
2537 	}
2538 
2539 	if (!ksmbd_inode_pending_delete(fp))
2540 		ret = ksmbd_validate_name_reconnect(share, fp, name);
2541 out:
2542 	opinfo_put(opinfo);
2543 	return ret;
2544 }
2545