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