xref: /linux/fs/smb/server/oplock.c (revision fafb66e5903c2bcfc7b7e259042a8282f18a6faa)
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 	ksmbd_conn_put(conn);
879 }
880 
881 /**
882  * smb2_oplock_break_noti() - send smb2 exclusive/batch to level2 oplock
883  *		break command from server to client
884  * @opinfo:		oplock info object
885  *
886  * Return:      0 on success, otherwise error
887  */
888 static int smb2_oplock_break_noti(struct oplock_info *opinfo)
889 {
890 	struct ksmbd_conn *conn;
891 	struct oplock_break_info *br_info;
892 	int ret = 0;
893 	struct ksmbd_work *work;
894 
895 	conn = READ_ONCE(opinfo->conn);
896 	if (!conn)
897 		return ksmbd_invalidate_durable_fd(opinfo->fid);
898 
899 	work = ksmbd_alloc_work_struct();
900 	if (!work)
901 		return -ENOMEM;
902 
903 	br_info = kmalloc_obj(struct oplock_break_info, KSMBD_DEFAULT_GFP);
904 	if (!br_info) {
905 		ksmbd_free_work_struct(work);
906 		return -ENOMEM;
907 	}
908 
909 	br_info->level = opinfo->level;
910 	br_info->fid = opinfo->fid;
911 	br_info->open_trunc = opinfo->open_trunc;
912 
913 	work->request_buf = (char *)br_info;
914 	work->conn = ksmbd_conn_get(conn);
915 	work->sess = opinfo->sess;
916 
917 	ksmbd_conn_r_count_inc(conn);
918 	if (opinfo->op_state == OPLOCK_ACK_WAIT) {
919 		INIT_WORK(&work->work, __smb2_oplock_break_noti);
920 		ksmbd_queue_work(work);
921 
922 		if (wait_for_break_ack(opinfo))
923 			ret = ksmbd_invalidate_durable_fd(opinfo->fid);
924 	} else {
925 		__smb2_oplock_break_noti(&work->work);
926 		if (opinfo->level == SMB2_OPLOCK_LEVEL_II)
927 			opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
928 	}
929 	return ret;
930 }
931 
932 /**
933  * __smb2_lease_break_noti() - send lease break command from server
934  * to client
935  * @wk:     smb work object
936  */
937 static void __smb2_lease_break_noti(struct work_struct *wk)
938 {
939 	struct smb2_lease_break *rsp = NULL;
940 	struct ksmbd_work *work = container_of(wk, struct ksmbd_work, work);
941 	struct ksmbd_conn *conn = work->conn;
942 	struct lease_break_info *br_info = work->request_buf;
943 	struct smb2_hdr *rsp_hdr;
944 
945 	if (allocate_interim_rsp_buf(work)) {
946 		ksmbd_debug(OPLOCK, "smb2_allocate_rsp_buf failed! ");
947 		goto out;
948 	}
949 
950 	rsp_hdr = smb_get_msg(work->response_buf);
951 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
952 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
953 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
954 	rsp_hdr->CreditRequest = cpu_to_le16(0);
955 	rsp_hdr->Command = SMB2_OPLOCK_BREAK;
956 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
957 	rsp_hdr->NextCommand = 0;
958 	rsp_hdr->MessageId = cpu_to_le64(-1);
959 	rsp_hdr->Id.SyncId.ProcessId = 0;
960 	rsp_hdr->Id.SyncId.TreeId = 0;
961 	rsp_hdr->SessionId = 0;
962 	memset(rsp_hdr->Signature, 0, 16);
963 
964 	rsp = smb_get_msg(work->response_buf);
965 	rsp->StructureSize = cpu_to_le16(44);
966 	rsp->Epoch = br_info->epoch;
967 	rsp->Flags = 0;
968 
969 	if (br_info->curr_state & (SMB2_LEASE_WRITE_CACHING_LE |
970 			SMB2_LEASE_HANDLE_CACHING_LE))
971 		rsp->Flags = SMB2_NOTIFY_BREAK_LEASE_FLAG_ACK_REQUIRED;
972 
973 	memcpy(rsp->LeaseKey, br_info->lease_key, SMB2_LEASE_KEY_SIZE);
974 	rsp->CurrentLeaseState = br_info->curr_state;
975 	rsp->NewLeaseState = br_info->new_state;
976 	rsp->BreakReason = 0;
977 	rsp->AccessMaskHint = 0;
978 	rsp->ShareMaskHint = 0;
979 
980 	if (ksmbd_iov_pin_rsp(work, (void *)rsp,
981 			      sizeof(struct smb2_lease_break)))
982 		goto out;
983 
984 	ksmbd_conn_write(work);
985 
986 out:
987 	ksmbd_free_work_struct(work);
988 	ksmbd_conn_r_count_dec(conn);
989 	ksmbd_conn_put(conn);
990 }
991 
992 /**
993  * smb2_lease_break_noti() - break lease when a new client request
994  *			write lease
995  * @opinfo:		contains lease state information
996  * @wait_ack:		wait for lease break acknowledgment from the client
997  * @inc_epoch:		increment the lease epoch before sending the break
998  *
999  * Return:	0 on success, otherwise error
1000  */
1001 static int smb2_lease_break_noti(struct oplock_info *opinfo, bool wait_ack,
1002 				 bool inc_epoch)
1003 {
1004 	struct ksmbd_conn *conn;
1005 	struct ksmbd_work *work;
1006 	struct lease_break_info *br_info;
1007 	struct lease *lease = opinfo->o_lease;
1008 	int ret = 0;
1009 
1010 	conn = READ_ONCE(opinfo->conn);
1011 	if (lease->version == 2 && lease->l_lb && lease->l_lb->conn &&
1012 	    !ksmbd_conn_releasing(lease->l_lb->conn))
1013 		conn = lease->l_lb->conn;
1014 	if (!conn)
1015 		return ksmbd_invalidate_durable_fd(opinfo->fid);
1016 
1017 	work = ksmbd_alloc_work_struct();
1018 	if (!work)
1019 		return -ENOMEM;
1020 
1021 	br_info = kmalloc_obj(struct lease_break_info, KSMBD_DEFAULT_GFP);
1022 	if (!br_info) {
1023 		ksmbd_free_work_struct(work);
1024 		return -ENOMEM;
1025 	}
1026 
1027 	br_info->curr_state = lease->state;
1028 	br_info->new_state = lease->new_state;
1029 	if (lease->version == 2) {
1030 		if (inc_epoch)
1031 			lease->epoch++;
1032 		br_info->epoch = cpu_to_le16(lease->epoch);
1033 	} else {
1034 		br_info->epoch = 0;
1035 	}
1036 	memcpy(br_info->lease_key, lease->lease_key, SMB2_LEASE_KEY_SIZE);
1037 
1038 	work->request_buf = (char *)br_info;
1039 	work->conn = ksmbd_conn_get(conn);
1040 	work->sess = opinfo->sess;
1041 
1042 	ksmbd_conn_r_count_inc(conn);
1043 	if (opinfo->op_state == OPLOCK_ACK_WAIT) {
1044 		INIT_WORK(&work->work, __smb2_lease_break_noti);
1045 		ksmbd_queue_work(work);
1046 		if (wait_ack) {
1047 			if (wait_for_break_ack(opinfo))
1048 				ret = ksmbd_invalidate_durable_fd(opinfo->fid);
1049 		}
1050 	} else {
1051 		__smb2_lease_break_noti(&work->work);
1052 		if (opinfo->o_lease->new_state == SMB2_LEASE_NONE_LE) {
1053 			opinfo->o_lease->state = SMB2_LEASE_NONE_LE;
1054 			lease_update_oplock_levels(opinfo->o_lease);
1055 		}
1056 	}
1057 	return ret;
1058 }
1059 
1060 static void wait_lease_breaking(struct oplock_info *opinfo)
1061 {
1062 	if (!opinfo->is_lease)
1063 		return;
1064 
1065 	wake_up_interruptible_all(&opinfo->oplock_brk);
1066 	if (atomic_read(&opinfo->breaking_cnt)) {
1067 		int ret = 0;
1068 
1069 		ret = wait_event_interruptible_timeout(opinfo->oplock_brk,
1070 						       atomic_read(&opinfo->breaking_cnt) == 0,
1071 						       HZ);
1072 		if (!ret)
1073 			atomic_set(&opinfo->breaking_cnt, 0);
1074 	}
1075 }
1076 
1077 static int oplock_break(struct oplock_info *brk_opinfo, int req_op_level,
1078 			struct ksmbd_work *in_work, bool share_break)
1079 {
1080 	int err = 0;
1081 	bool sent_interim = false;
1082 
1083 	/* Need to break exclusive/batch oplock, write lease or overwrite_if */
1084 	ksmbd_debug(OPLOCK,
1085 		    "request to send oplock(level : 0x%x) break notification\n",
1086 		    brk_opinfo->level);
1087 
1088 	if (brk_opinfo->is_lease) {
1089 		struct lease *lease = brk_opinfo->o_lease;
1090 		bool open_trunc = brk_opinfo->open_trunc;
1091 		bool was_pending = test_bit(0, &brk_opinfo->pending_break);
1092 		bool wait_ack;
1093 		bool inc_epoch = true;
1094 
1095 		if (in_work && was_pending) {
1096 			setup_async_work(in_work, NULL, NULL);
1097 			smb2_send_interim_resp(in_work, STATUS_PENDING);
1098 			release_async_work(in_work);
1099 			sent_interim = true;
1100 		}
1101 
1102 		err = oplock_break_pending(brk_opinfo, req_op_level);
1103 		if (err)
1104 			return err < 0 ? err : 0;
1105 		if (was_pending)
1106 			open_trunc = brk_opinfo->open_trunc;
1107 
1108 again:
1109 		atomic_inc(&brk_opinfo->breaking_cnt);
1110 		if (open_trunc) {
1111 			/*
1112 			 * Create overwrite break trigger the lease break to
1113 			 * none.
1114 			 */
1115 			lease->new_state = SMB2_LEASE_NONE_LE;
1116 		} else if (share_break &&
1117 			   lease->state & SMB2_LEASE_HANDLE_CACHING_LE) {
1118 			lease->new_state =
1119 				lease->state & ~SMB2_LEASE_HANDLE_CACHING_LE;
1120 		} else {
1121 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE) {
1122 				if (lease->state & SMB2_LEASE_HANDLE_CACHING_LE)
1123 					lease->new_state =
1124 						SMB2_LEASE_READ_CACHING_LE |
1125 						SMB2_LEASE_HANDLE_CACHING_LE;
1126 				else
1127 					lease->new_state =
1128 						SMB2_LEASE_READ_CACHING_LE;
1129 			} else {
1130 				if (lease->state & SMB2_LEASE_HANDLE_CACHING_LE &&
1131 						!lease->is_dir)
1132 					lease->new_state =
1133 						SMB2_LEASE_READ_CACHING_LE;
1134 				else
1135 					lease->new_state = SMB2_LEASE_NONE_LE;
1136 			}
1137 		}
1138 
1139 		if (in_work && !sent_interim) {
1140 			setup_async_work(in_work, NULL, NULL);
1141 			smb2_send_interim_resp(in_work, STATUS_PENDING);
1142 			release_async_work(in_work);
1143 			sent_interim = true;
1144 		}
1145 
1146 		if (lease->state & (SMB2_LEASE_WRITE_CACHING_LE |
1147 				SMB2_LEASE_HANDLE_CACHING_LE)) {
1148 			brk_opinfo->op_state = OPLOCK_ACK_WAIT;
1149 		} else
1150 			atomic_dec(&brk_opinfo->breaking_cnt);
1151 
1152 		wait_ack = !(open_trunc &&
1153 			     lease->state == (SMB2_LEASE_READ_CACHING_LE |
1154 					      SMB2_LEASE_HANDLE_CACHING_LE));
1155 		if (lease->reuse_epoch) {
1156 			inc_epoch = false;
1157 			lease->reuse_epoch = false;
1158 		}
1159 		err = smb2_lease_break_noti(brk_opinfo, wait_ack, inc_epoch);
1160 		inc_epoch = false;
1161 
1162 		ksmbd_debug(OPLOCK, "oplock granted = %d\n", brk_opinfo->level);
1163 		if (brk_opinfo->op_state == OPLOCK_CLOSING)
1164 			err = -ENOENT;
1165 
1166 		if (wait_ack)
1167 			wait_lease_breaking(brk_opinfo);
1168 		/*
1169 		 * A share-mode conflict break only drops the conflicting
1170 		 * caching bit; the triggering open fails with a sharing
1171 		 * violation, so keep it to a single break.
1172 		 *
1173 		 * Otherwise chain another break while the lease is still
1174 		 * incompatible with this open (req_op_level), or while a
1175 		 * truncating waiter that arrived during the break still needs
1176 		 * the lease dropped to none.  open_trunc snapshotted for this
1177 		 * break stays cleared, so the next state is computed from the
1178 		 * lease state and the cascade steps down (e.g. RH->R->none)
1179 		 * instead of collapsing straight to none.
1180 		 */
1181 		if (wait_ack && !err && !share_break &&
1182 		    (lease_break_needed(brk_opinfo, req_op_level, open_trunc) ||
1183 		     (brk_opinfo->open_trunc &&
1184 		      lease->state != SMB2_LEASE_NONE_LE)))
1185 			goto again;
1186 
1187 		wake_up_oplock_break(brk_opinfo);
1188 		return err;
1189 	} else {
1190 		err = oplock_break_pending(brk_opinfo, req_op_level);
1191 		if (err)
1192 			return err < 0 ? err : 0;
1193 
1194 		if (brk_opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
1195 		    brk_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
1196 			brk_opinfo->op_state = OPLOCK_ACK_WAIT;
1197 	}
1198 
1199 	err = smb2_oplock_break_noti(brk_opinfo);
1200 
1201 	ksmbd_debug(OPLOCK, "oplock granted = %d\n", brk_opinfo->level);
1202 	if (brk_opinfo->op_state == OPLOCK_CLOSING)
1203 		err = -EAGAIN;
1204 	wake_up_oplock_break(brk_opinfo);
1205 
1206 	return err;
1207 }
1208 
1209 struct oplock_break_entry {
1210 	struct list_head	list;
1211 	struct oplock_info	*opinfo;
1212 };
1213 
1214 static int oplock_break_add(struct list_head *head, struct oplock_info *opinfo)
1215 {
1216 	struct oplock_break_entry *ent;
1217 
1218 	ent = kmalloc_obj(struct oplock_break_entry, KSMBD_DEFAULT_GFP);
1219 	if (!ent)
1220 		return -ENOMEM;
1221 
1222 	ent->opinfo = opinfo;
1223 	list_add_tail(&ent->list, head);
1224 	return 0;
1225 }
1226 
1227 static void oplock_break_drain_none(struct list_head *head)
1228 {
1229 	struct oplock_break_entry *ent, *tmp;
1230 
1231 	list_for_each_entry_safe(ent, tmp, head, list) {
1232 		oplock_break(ent->opinfo, SMB2_OPLOCK_LEVEL_NONE, NULL, false);
1233 		list_del(&ent->list);
1234 		opinfo_put(ent->opinfo);
1235 		kfree(ent);
1236 	}
1237 }
1238 
1239 void destroy_lease_table(struct ksmbd_conn *conn)
1240 {
1241 	struct lease_table *lb, *lbtmp;
1242 	struct lease *lease, *ltmp;
1243 
1244 	write_lock(&lease_list_lock);
1245 	if (list_empty(&lease_table_list)) {
1246 		write_unlock(&lease_list_lock);
1247 		return;
1248 	}
1249 
1250 	list_for_each_entry_safe(lb, lbtmp, &lease_table_list, l_entry) {
1251 		if (conn && memcmp(lb->client_guid, conn->ClientGUID,
1252 				   SMB2_CLIENT_GUID_SIZE))
1253 			continue;
1254 		list_for_each_entry_safe(lease, ltmp, &lb->lease_list, l_entry)
1255 			lease_del_table(lease);
1256 		list_del(&lb->l_entry);
1257 		free_lease_table(lb);
1258 	}
1259 	write_unlock(&lease_list_lock);
1260 }
1261 
1262 int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci,
1263 			struct lease_ctx_info *lctx)
1264 {
1265 	struct lease *lease;
1266 	int err = 0;
1267 	struct lease_table *lb;
1268 
1269 	if (!lctx)
1270 		return err;
1271 
1272 	read_lock(&lease_list_lock);
1273 	if (list_empty(&lease_table_list)) {
1274 		read_unlock(&lease_list_lock);
1275 		return 0;
1276 	}
1277 
1278 	list_for_each_entry(lb, &lease_table_list, l_entry) {
1279 		if (!memcmp(lb->client_guid, conn->ClientGUID,
1280 			    SMB2_CLIENT_GUID_SIZE))
1281 			goto found;
1282 	}
1283 	read_unlock(&lease_list_lock);
1284 
1285 	return 0;
1286 
1287 found:
1288 	list_for_each_entry(lease, &lb->lease_list, l_entry) {
1289 		if (lease->ci == ci)
1290 			continue;
1291 		if (!memcmp(lease->lease_key, lctx->lease_key,
1292 			    SMB2_LEASE_KEY_SIZE)) {
1293 			err = -EINVAL;
1294 			ksmbd_debug(OPLOCK,
1295 				    "found same lease key is already used in other files\n");
1296 			goto out;
1297 		}
1298 	}
1299 
1300 out:
1301 	read_unlock(&lease_list_lock);
1302 	return err;
1303 }
1304 
1305 static void add_lease_global_list(struct lease *lease, struct ksmbd_conn *conn,
1306 				  struct lease_table *new_lb)
1307 {
1308 	struct lease_table *lb;
1309 
1310 	write_lock(&lease_list_lock);
1311 	list_for_each_entry(lb, &lease_table_list, l_entry) {
1312 		if (!memcmp(lb->client_guid, conn->ClientGUID,
1313 			    SMB2_CLIENT_GUID_SIZE)) {
1314 			lease_add_table(lease, lb);
1315 			write_unlock(&lease_list_lock);
1316 			free_lease_table(new_lb);
1317 			return;
1318 		}
1319 	}
1320 
1321 	lease_add_table(lease, new_lb);
1322 	list_add(&new_lb->l_entry, &lease_table_list);
1323 	write_unlock(&lease_list_lock);
1324 }
1325 
1326 static void set_oplock_level(struct oplock_info *opinfo, int level,
1327 			     struct lease_ctx_info *lctx)
1328 {
1329 	switch (level) {
1330 	case SMB2_OPLOCK_LEVEL_BATCH:
1331 	case SMB2_OPLOCK_LEVEL_EXCLUSIVE:
1332 		grant_write_oplock(opinfo, level, lctx);
1333 		break;
1334 	case SMB2_OPLOCK_LEVEL_II:
1335 		grant_read_oplock(opinfo, lctx);
1336 		break;
1337 	default:
1338 		grant_none_oplock(opinfo, lctx);
1339 		break;
1340 	}
1341 }
1342 
1343 void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
1344 				      struct lease_ctx_info *lctx)
1345 {
1346 	struct oplock_info *opinfo;
1347 	struct ksmbd_inode *p_ci = NULL;
1348 	LIST_HEAD(brk_list);
1349 
1350 	if (lctx->version != 2)
1351 		return;
1352 
1353 	p_ci = ksmbd_inode_lookup_lock(fp->filp->f_path.dentry->d_parent);
1354 	if (!p_ci)
1355 		return;
1356 
1357 	down_read(&p_ci->m_lock);
1358 	list_for_each_entry(opinfo, &p_ci->m_op_list, op_entry) {
1359 		if (opinfo->conn == NULL || !opinfo->is_lease)
1360 			continue;
1361 
1362 		if (opinfo->o_lease->state != SMB2_OPLOCK_LEVEL_NONE &&
1363 		    (!(lctx->flags & SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE) ||
1364 		     !compare_guid_key(opinfo, fp->conn->ClientGUID,
1365 				      lctx->parent_lease_key))) {
1366 			if (!atomic_inc_not_zero(&opinfo->refcount))
1367 				continue;
1368 
1369 			if (ksmbd_conn_releasing(opinfo->conn)) {
1370 				opinfo_put(opinfo);
1371 				continue;
1372 			}
1373 
1374 			if (oplock_break_add(&brk_list, opinfo))
1375 				opinfo_put(opinfo);
1376 		}
1377 	}
1378 	up_read(&p_ci->m_lock);
1379 
1380 	oplock_break_drain_none(&brk_list);
1381 
1382 	ksmbd_inode_put(p_ci);
1383 }
1384 
1385 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp)
1386 {
1387 	struct oplock_info *opinfo;
1388 	struct ksmbd_inode *p_ci = NULL;
1389 	LIST_HEAD(brk_list);
1390 
1391 	rcu_read_lock();
1392 	opinfo = rcu_dereference(fp->f_opinfo);
1393 
1394 	if (!opinfo || !opinfo->is_lease || opinfo->o_lease->version != 2) {
1395 		rcu_read_unlock();
1396 		return;
1397 	}
1398 	rcu_read_unlock();
1399 
1400 	p_ci = ksmbd_inode_lookup_lock(fp->filp->f_path.dentry->d_parent);
1401 	if (!p_ci)
1402 		return;
1403 
1404 	down_read(&p_ci->m_lock);
1405 	list_for_each_entry(opinfo, &p_ci->m_op_list, op_entry) {
1406 		if (opinfo->conn == NULL || !opinfo->is_lease)
1407 			continue;
1408 
1409 		if (opinfo->o_lease->state != SMB2_OPLOCK_LEVEL_NONE) {
1410 			if (!atomic_inc_not_zero(&opinfo->refcount))
1411 				continue;
1412 
1413 			if (ksmbd_conn_releasing(opinfo->conn)) {
1414 				opinfo_put(opinfo);
1415 				continue;
1416 			}
1417 
1418 			if (oplock_break_add(&brk_list, opinfo))
1419 				opinfo_put(opinfo);
1420 		}
1421 	}
1422 	up_read(&p_ci->m_lock);
1423 
1424 	oplock_break_drain_none(&brk_list);
1425 
1426 	ksmbd_inode_put(p_ci);
1427 }
1428 
1429 /**
1430  * smb_grant_oplock() - handle oplock/lease request on file open
1431  * @work:		smb work
1432  * @req_op_level:	oplock level
1433  * @pid:		id of open file
1434  * @fp:			ksmbd file pointer
1435  * @tid:		Tree id of connection
1436  * @lctx:		lease context information on file open
1437  * @share_ret:		share mode
1438  *
1439  * Return:      0 on success, otherwise error
1440  */
1441 int smb_grant_oplock(struct ksmbd_work *work, int req_op_level, u64 pid,
1442 		     struct ksmbd_file *fp, __u16 tid,
1443 		     struct lease_ctx_info *lctx, int share_ret)
1444 {
1445 	int err = 0;
1446 	int break_level = SMB2_OPLOCK_LEVEL_II;
1447 	struct oplock_info *opinfo = NULL, *prev_opinfo = NULL;
1448 	struct ksmbd_inode *ci = fp->f_ci;
1449 	struct lease_table *new_lb = NULL;
1450 	struct oplock_snapshot prev_op_snapshot;
1451 	bool prev_op_has_lease;
1452 	bool prev_durable_open = false;
1453 	bool prev_durable_detached = false;
1454 	unsigned long long prev_fid = KSMBD_NO_FID;
1455 	bool new_lease = false;
1456 	__le32 prev_op_state = 0;
1457 
1458 	/* Only v2 leases handle the directory */
1459 	if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
1460 		if (!lctx || lctx->version != 2)
1461 			return 0;
1462 	}
1463 
1464 	opinfo = alloc_opinfo(work, pid, tid);
1465 	if (!opinfo)
1466 		return -ENOMEM;
1467 
1468 	if (lctx) {
1469 		opinfo->o_lease = alloc_lease(lctx, ci);
1470 		if (!opinfo->o_lease) {
1471 			err = -ENOMEM;
1472 			goto err_out;
1473 		}
1474 		opinfo->is_lease = 1;
1475 		new_lease = true;
1476 	}
1477 
1478 	/* ci does not have any oplock */
1479 	if (!opinfo_count(fp))
1480 		goto set_lev;
1481 
1482 	/*
1483 	 * A stat open that only requests metadata access must not break the
1484 	 * existing caching state. READ_CONTROL (reading the security
1485 	 * descriptor) does not conflict with a lease, but it does conflict
1486 	 * with an oplock, so only treat a read-control-only open as a stat
1487 	 * open when the existing holder is a lease.
1488 	 */
1489 	if (fp->cdoption != FILE_OVERWRITE_IF_LE &&
1490 	    fp->cdoption != FILE_OVERWRITE_LE &&
1491 	    fp->cdoption != FILE_SUPERSEDE_LE &&
1492 	    (fp->attrib_only ||
1493 	     (!(fp->daccess & ~(FILE_READ_ATTRIBUTES_LE |
1494 				FILE_WRITE_ATTRIBUTES_LE |
1495 				FILE_SYNCHRONIZE_LE |
1496 				FILE_READ_CONTROL_LE)) &&
1497 	      ksmbd_inode_has_lease(ci)))) {
1498 		req_op_level = SMB2_OPLOCK_LEVEL_NONE;
1499 		goto set_lev;
1500 	}
1501 
1502 	if (lctx) {
1503 		struct oplock_info *m_opinfo;
1504 
1505 		/* is lease already granted ? */
1506 		m_opinfo = same_client_has_lease(ci, work->conn->ClientGUID,
1507 						 lctx);
1508 		if (m_opinfo) {
1509 			lease_put(opinfo->o_lease);
1510 			lease_get(m_opinfo->o_lease);
1511 			opinfo->o_lease = m_opinfo->o_lease;
1512 			opinfo->level = m_opinfo->level;
1513 			new_lease = false;
1514 			opinfo_put(m_opinfo);
1515 			goto out;
1516 		}
1517 	}
1518 	prev_opinfo = opinfo_get_list(ci, fp, &prev_op_snapshot);
1519 	if (!prev_opinfo ||
1520 	    (prev_opinfo->level == SMB2_OPLOCK_LEVEL_NONE && lctx)) {
1521 		opinfo_put(prev_opinfo);
1522 		goto set_lev;
1523 	}
1524 	prev_op_has_lease = prev_opinfo->is_lease;
1525 	if (prev_op_has_lease)
1526 		prev_op_state = prev_opinfo->o_lease->state;
1527 	if (share_ret < 0 &&
1528 	    prev_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1529 		err = share_ret;
1530 		opinfo_put(prev_opinfo);
1531 		goto err_out;
1532 	}
1533 
1534 	if (prev_opinfo->level != SMB2_OPLOCK_LEVEL_BATCH &&
1535 	    prev_opinfo->level != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1536 		opinfo_put(prev_opinfo);
1537 		goto op_break_not_needed;
1538 	}
1539 
1540 	prev_durable_open = prev_op_snapshot.durable_open;
1541 	prev_durable_detached = prev_op_snapshot.durable_detached;
1542 	prev_fid = prev_op_snapshot.fid;
1543 
1544 	err = oplock_break(prev_opinfo, break_level, work,
1545 			   share_ret < 0 && prev_opinfo->is_lease);
1546 	if (prev_durable_detached || (prev_durable_open && err == -ENOENT))
1547 		ksmbd_invalidate_durable_fd(prev_fid);
1548 	opinfo_put(prev_opinfo);
1549 	if (err == -EAGAIN) {
1550 		share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
1551 		if (share_ret < 0) {
1552 			err = share_ret;
1553 			goto err_out;
1554 		}
1555 		goto set_lev;
1556 	}
1557 	if (err == -ENOENT) {
1558 		if (req_op_level != SMB2_OPLOCK_LEVEL_NONE)
1559 			req_op_level = SMB2_OPLOCK_LEVEL_II;
1560 		goto set_lev;
1561 	}
1562 	/* Check all oplock was freed by close */
1563 	else if (err < 0)
1564 		goto err_out;
1565 
1566 op_break_not_needed:
1567 	if (share_ret < 0) {
1568 		err = share_ret;
1569 		goto err_out;
1570 	}
1571 
1572 	if (req_op_level != SMB2_OPLOCK_LEVEL_NONE)
1573 		req_op_level = SMB2_OPLOCK_LEVEL_II;
1574 
1575 	/* grant fixed oplock on stacked locking between lease and oplock */
1576 	if (prev_op_has_lease && !lctx)
1577 		if (prev_op_state & SMB2_LEASE_HANDLE_CACHING_LE)
1578 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
1579 
1580 	if (!prev_op_has_lease && lctx) {
1581 		req_op_level = SMB2_OPLOCK_LEVEL_II;
1582 		lctx->req_state = SMB2_LEASE_READ_CACHING_LE;
1583 	}
1584 
1585 set_lev:
1586 	set_oplock_level(opinfo, req_op_level, lctx);
1587 
1588 out:
1589 	/*
1590 	 * Keep the original publication order so concurrent opens can
1591 	 * still observe the in-flight grant via ci->m_op_list, but make
1592 	 * everything after opinfo_add() no-fail by preallocating any new
1593 	 * lease_table first.
1594 	 */
1595 	opinfo->o_fp = fp;
1596 	if (new_lease) {
1597 		new_lb = alloc_lease_table(opinfo);
1598 		if (!new_lb) {
1599 			err = -ENOMEM;
1600 			goto err_out;
1601 		}
1602 	}
1603 
1604 	opinfo_count_inc(fp);
1605 	opinfo_add(opinfo, fp);
1606 
1607 	if (new_lease)
1608 		add_lease_global_list(opinfo->o_lease, opinfo->conn, new_lb);
1609 	if (opinfo->is_lease)
1610 		lease_add_open(opinfo->o_lease, opinfo);
1611 
1612 	rcu_assign_pointer(fp->f_opinfo, opinfo);
1613 
1614 	return 0;
1615 err_out:
1616 	kfree(new_lb);
1617 	opinfo_put(opinfo);
1618 	return err;
1619 }
1620 
1621 /**
1622  * smb_break_all_write_oplock() - break batch/exclusive oplock to level2
1623  * @work:	smb work
1624  * @fp:		ksmbd file pointer
1625  * @is_trunc:	truncate on open
1626  */
1627 static bool smb_break_all_write_oplock(struct ksmbd_work *work,
1628 				       struct ksmbd_file *fp, int is_trunc)
1629 {
1630 	struct oplock_info *brk_opinfo;
1631 	bool sent_break = false;
1632 
1633 	brk_opinfo = opinfo_get_list(fp->f_ci, NULL, NULL);
1634 	if (!brk_opinfo)
1635 		return false;
1636 	if (brk_opinfo->level != SMB2_OPLOCK_LEVEL_BATCH &&
1637 	    brk_opinfo->level != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
1638 		opinfo_put(brk_opinfo);
1639 		return false;
1640 	}
1641 
1642 	brk_opinfo->open_trunc = is_trunc;
1643 	oplock_break(brk_opinfo, SMB2_OPLOCK_LEVEL_II, work, false);
1644 	sent_break = true;
1645 	opinfo_put(brk_opinfo);
1646 
1647 	return sent_break;
1648 }
1649 
1650 /**
1651  * __smb_break_all_levII_oplock() - send level2 oplock or read lease break command
1652  *	from server to client
1653  * @work:		smb work
1654  * @fp:			ksmbd file pointer
1655  * @is_trunc:		truncate on open
1656  * @send_interim:	send interim response to the client
1657  * @send_oplock_break:	send oplock break notification to the client
1658  */
1659 static void __smb_break_all_levII_oplock(struct ksmbd_work *work,
1660 					 struct ksmbd_file *fp, int is_trunc,
1661 					 bool send_interim, bool send_oplock_break)
1662 {
1663 	struct oplock_info *op, *brk_op;
1664 	struct oplock_break_entry *ent, *tmp;
1665 	struct ksmbd_inode *ci;
1666 	struct ksmbd_conn *conn = work->conn;
1667 	bool sent_interim = false;
1668 	LIST_HEAD(brk_list);
1669 
1670 	if (!test_share_config_flag(work->tcon->share_conf,
1671 				    KSMBD_SHARE_FLAG_OPLOCKS))
1672 		return;
1673 
1674 	ci = fp->f_ci;
1675 	op = opinfo_get(fp);
1676 
1677 	down_read(&ci->m_lock);
1678 	list_for_each_entry(brk_op, &ci->m_op_list, op_entry) {
1679 		if (brk_op->conn == NULL)
1680 			continue;
1681 
1682 		if (!atomic_inc_not_zero(&brk_op->refcount))
1683 			continue;
1684 
1685 		if (ksmbd_conn_releasing(brk_op->conn)) {
1686 			opinfo_put(brk_op);
1687 			continue;
1688 		}
1689 
1690 		if (!brk_op->is_lease &&
1691 		    brk_op->level != SMB2_OPLOCK_LEVEL_II) {
1692 			ksmbd_debug(OPLOCK, "unexpected oplock(0x%x)\n",
1693 				    brk_op->level);
1694 			goto next;
1695 		}
1696 
1697 		/* Skip oplock being break to none */
1698 		if (brk_op->is_lease &&
1699 		    brk_op->o_lease->new_state == SMB2_LEASE_NONE_LE &&
1700 		    atomic_read(&brk_op->breaking_cnt))
1701 			goto next;
1702 
1703 		if (op && op->is_lease && brk_op->is_lease &&
1704 		    !memcmp(conn->ClientGUID, brk_op->conn->ClientGUID,
1705 			    SMB2_CLIENT_GUID_SIZE) &&
1706 		    !memcmp(op->o_lease->lease_key, brk_op->o_lease->lease_key,
1707 			    SMB2_LEASE_KEY_SIZE))
1708 			goto next;
1709 		brk_op->open_trunc = is_trunc;
1710 
1711 		/*
1712 		 * Defer the break until ci->m_lock is released: oplock_break()
1713 		 * may block waiting for the lease break acknowledgment, and the
1714 		 * close that wakes that wait needs ci->m_lock for write.
1715 		 */
1716 		if (!oplock_break_add(&brk_list, brk_op))
1717 			continue;
1718 next:
1719 		opinfo_put(brk_op);
1720 	}
1721 	up_read(&ci->m_lock);
1722 
1723 	list_for_each_entry_safe(ent, tmp, &brk_list, list) {
1724 		brk_op = ent->opinfo;
1725 
1726 		if (!brk_op->is_lease && !send_oplock_break) {
1727 			brk_op->level = SMB2_OPLOCK_LEVEL_NONE;
1728 			brk_op->op_state = OPLOCK_STATE_NONE;
1729 		} else {
1730 			oplock_break(brk_op,
1731 				     brk_op->is_lease && !is_trunc ?
1732 				     SMB2_OPLOCK_LEVEL_II : SMB2_OPLOCK_LEVEL_NONE,
1733 				     send_interim && !sent_interim ? work : NULL,
1734 				     false);
1735 		}
1736 		sent_interim = true;
1737 		list_del(&ent->list);
1738 		opinfo_put(brk_op);
1739 		kfree(ent);
1740 	}
1741 
1742 	if (op)
1743 		opinfo_put(op);
1744 }
1745 
1746 void smb_break_all_levII_oplock(struct ksmbd_work *work, struct ksmbd_file *fp,
1747 				int is_trunc)
1748 {
1749 	__smb_break_all_levII_oplock(work, fp, is_trunc, true, true);
1750 }
1751 
1752 void smb_break_all_levII_oplock_no_interim(struct ksmbd_work *work,
1753 					   struct ksmbd_file *fp, int is_trunc)
1754 {
1755 	__smb_break_all_levII_oplock(work, fp, is_trunc, false, true);
1756 }
1757 
1758 void smb_break_all_levII_oplock_for_delete(struct ksmbd_work *work,
1759 					   struct ksmbd_file *fp)
1760 {
1761 	__smb_break_all_levII_oplock(work, fp, 0, false, false);
1762 }
1763 
1764 /**
1765  * smb_break_all_oplock() - break both batch/exclusive and level2 oplock
1766  * @work:	smb work
1767  * @fp:		ksmbd file pointer
1768  */
1769 void smb_break_all_oplock(struct ksmbd_work *work, struct ksmbd_file *fp)
1770 {
1771 	bool sent_break;
1772 
1773 	if (!test_share_config_flag(work->tcon->share_conf,
1774 				    KSMBD_SHARE_FLAG_OPLOCKS))
1775 		return;
1776 
1777 	sent_break = smb_break_all_write_oplock(work, fp, 1);
1778 	__smb_break_all_levII_oplock(work, fp, 1, !sent_break, true);
1779 }
1780 
1781 /**
1782  * smb2_map_lease_to_oplock() - map lease state to corresponding oplock type
1783  * @lease_state:     lease type
1784  *
1785  * Return:      0 if no mapping, otherwise corresponding oplock type
1786  */
1787 __u8 smb2_map_lease_to_oplock(__le32 lease_state)
1788 {
1789 	if ((lease_state & SMB2_LEASE_WRITE_CACHING_LE) &&
1790 	    (lease_state & SMB2_LEASE_HANDLE_CACHING_LE)) {
1791 		return SMB2_OPLOCK_LEVEL_BATCH;
1792 	} else if (lease_state & SMB2_LEASE_WRITE_CACHING_LE) {
1793 		return SMB2_OPLOCK_LEVEL_EXCLUSIVE;
1794 	} else if (lease_state & (SMB2_LEASE_READ_CACHING_LE |
1795 				  SMB2_LEASE_HANDLE_CACHING_LE)) {
1796 		return SMB2_OPLOCK_LEVEL_II;
1797 	}
1798 	return 0;
1799 }
1800 
1801 /**
1802  * create_lease_buf() - create lease context for open cmd response
1803  * @rbuf:	buffer to create lease context response
1804  * @lease:	buffer to stored parsed lease state information
1805  */
1806 void create_lease_buf(u8 *rbuf, struct lease *lease)
1807 {
1808 	if (lease->version == 2) {
1809 		struct create_lease_v2 *buf = (struct create_lease_v2 *)rbuf;
1810 		__le32 flags = 0;
1811 
1812 		memset(buf, 0, sizeof(struct create_lease_v2));
1813 		memcpy(buf->lcontext.LeaseKey, lease->lease_key,
1814 		       SMB2_LEASE_KEY_SIZE);
1815 		if (lease_has_parent_key(lease))
1816 			flags |= SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE;
1817 		if (lease_break_in_progress(lease))
1818 			flags |= SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE;
1819 		buf->lcontext.LeaseFlags = flags;
1820 		buf->lcontext.Epoch = cpu_to_le16(lease->epoch);
1821 		buf->lcontext.LeaseState = lease->state;
1822 		if (lease_has_parent_key(lease))
1823 			memcpy(buf->lcontext.ParentLeaseKey, lease->parent_lease_key,
1824 			       SMB2_LEASE_KEY_SIZE);
1825 		buf->ccontext.DataOffset = cpu_to_le16(offsetof
1826 				(struct create_lease_v2, lcontext));
1827 		buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
1828 		buf->ccontext.NameOffset = cpu_to_le16(offsetof
1829 				(struct create_lease_v2, Name));
1830 		buf->ccontext.NameLength = cpu_to_le16(4);
1831 		buf->Name[0] = 'R';
1832 		buf->Name[1] = 'q';
1833 		buf->Name[2] = 'L';
1834 		buf->Name[3] = 's';
1835 	} else {
1836 		struct create_lease *buf = (struct create_lease *)rbuf;
1837 
1838 		memset(buf, 0, sizeof(struct create_lease));
1839 		memcpy(buf->lcontext.LeaseKey, lease->lease_key, SMB2_LEASE_KEY_SIZE);
1840 		if (lease_break_in_progress(lease))
1841 			buf->lcontext.LeaseFlags =
1842 				SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE;
1843 		buf->lcontext.LeaseState = lease->state;
1844 		buf->ccontext.DataOffset = cpu_to_le16(offsetof
1845 				(struct create_lease, lcontext));
1846 		buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
1847 		buf->ccontext.NameOffset = cpu_to_le16(offsetof
1848 				(struct create_lease, Name));
1849 		buf->ccontext.NameLength = cpu_to_le16(4);
1850 		buf->Name[0] = 'R';
1851 		buf->Name[1] = 'q';
1852 		buf->Name[2] = 'L';
1853 		buf->Name[3] = 's';
1854 	}
1855 }
1856 
1857 /**
1858  * parse_lease_state() - parse lease context contained in file open request
1859  * @open_req:	buffer containing smb2 file open(create) request
1860  *
1861  * Return: allocated lease context object on success, otherwise NULL
1862  */
1863 struct lease_ctx_info *parse_lease_state(void *open_req)
1864 {
1865 	struct create_context *cc;
1866 	struct smb2_create_req *req = (struct smb2_create_req *)open_req;
1867 	struct lease_ctx_info *lreq;
1868 
1869 	cc = smb2_find_context_vals(req, SMB2_CREATE_REQUEST_LEASE, 4);
1870 	if (IS_ERR(cc))
1871 		return ERR_CAST(cc);
1872 	if (!cc)
1873 		return NULL;
1874 
1875 	lreq = kzalloc_obj(struct lease_ctx_info, KSMBD_DEFAULT_GFP);
1876 	if (!lreq)
1877 		return ERR_PTR(-ENOMEM);
1878 
1879 	if (sizeof(struct lease_context_v2) == le32_to_cpu(cc->DataLength)) {
1880 		struct create_lease_v2 *lc = (struct create_lease_v2 *)cc;
1881 
1882 		if (le16_to_cpu(cc->DataOffset) + le32_to_cpu(cc->DataLength) <
1883 		    sizeof(struct create_lease_v2) - 4)
1884 			goto err_out;
1885 
1886 		memcpy(lreq->lease_key, lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
1887 		lreq->req_state = lc->lcontext.LeaseState;
1888 		lreq->flags = lc->lcontext.LeaseFlags;
1889 		lreq->epoch = lc->lcontext.Epoch;
1890 		lreq->duration = lc->lcontext.LeaseDuration;
1891 		if (!lease_state_valid(lreq->req_state) ||
1892 		    !lease_v2_flags_valid(lreq->flags))
1893 			goto err_out;
1894 		lreq->req_state = lease_state_grantable(lreq->req_state);
1895 		if (lreq->flags == SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE)
1896 			memcpy(lreq->parent_lease_key, lc->lcontext.ParentLeaseKey,
1897 			       SMB2_LEASE_KEY_SIZE);
1898 		lreq->version = 2;
1899 	} else if (sizeof(struct lease_context) == le32_to_cpu(cc->DataLength)) {
1900 		struct create_lease *lc = (struct create_lease *)cc;
1901 
1902 		if (le16_to_cpu(cc->DataOffset) + le32_to_cpu(cc->DataLength) <
1903 		    sizeof(struct create_lease))
1904 			goto err_out;
1905 
1906 		memcpy(lreq->lease_key, lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
1907 		lreq->req_state = lc->lcontext.LeaseState;
1908 		lreq->flags = 0;
1909 		lreq->duration = lc->lcontext.LeaseDuration;
1910 		if (!lease_state_valid(lreq->req_state))
1911 			goto err_out;
1912 		lreq->req_state = lease_state_grantable(lreq->req_state);
1913 		lreq->version = 1;
1914 	} else
1915 		goto err_out;
1916 	return lreq;
1917 err_out:
1918 	kfree(lreq);
1919 	return ERR_PTR(-EINVAL);
1920 }
1921 
1922 /**
1923  * smb2_find_context_vals() - find a particular context info in open request
1924  * @open_req:	buffer containing smb2 file open(create) request
1925  * @tag:	context name to search for
1926  * @tag_len:	the length of tag
1927  *
1928  * Return:	pointer to requested context, NULL if @str context not found
1929  *		or error pointer if name length is invalid.
1930  */
1931 struct create_context *smb2_find_context_vals(void *open_req, const char *tag, int tag_len)
1932 {
1933 	struct create_context *cc;
1934 	unsigned int next = 0;
1935 	char *name;
1936 	struct smb2_create_req *req = (struct smb2_create_req *)open_req;
1937 	unsigned int remain_len, name_off, name_len, value_off, value_len,
1938 		     cc_len;
1939 
1940 	/*
1941 	 * CreateContextsOffset and CreateContextsLength are guaranteed to
1942 	 * be valid because of ksmbd_smb2_check_message().
1943 	 */
1944 	if (!req->CreateContextsOffset || !req->CreateContextsLength)
1945 		return NULL;
1946 
1947 	cc = (struct create_context *)((char *)req +
1948 				       le32_to_cpu(req->CreateContextsOffset));
1949 	remain_len = le32_to_cpu(req->CreateContextsLength);
1950 	do {
1951 		cc = (struct create_context *)((char *)cc + next);
1952 		if (remain_len < offsetof(struct create_context, Buffer))
1953 			return ERR_PTR(-EINVAL);
1954 
1955 		next = le32_to_cpu(cc->Next);
1956 		name_off = le16_to_cpu(cc->NameOffset);
1957 		name_len = le16_to_cpu(cc->NameLength);
1958 		value_off = le16_to_cpu(cc->DataOffset);
1959 		value_len = le32_to_cpu(cc->DataLength);
1960 		cc_len = next ? next : remain_len;
1961 
1962 		if ((next & 0x7) != 0 ||
1963 		    next > remain_len ||
1964 		    name_off != offsetof(struct create_context, Buffer) ||
1965 		    name_len < 4 ||
1966 		    name_off + name_len > cc_len ||
1967 		    (value_off & 0x7) != 0 ||
1968 		    (value_len && value_off < name_off + (name_len < 8 ? 8 : name_len)) ||
1969 		    ((u64)value_off + value_len > cc_len))
1970 			return ERR_PTR(-EINVAL);
1971 
1972 		name = (char *)cc + name_off;
1973 		if (name_len == tag_len && !memcmp(name, tag, name_len))
1974 			return cc;
1975 
1976 		remain_len -= next;
1977 	} while (next != 0);
1978 
1979 	return NULL;
1980 }
1981 
1982 /**
1983  * create_durable_rsp_buf() - create durable handle context
1984  * @cc:	buffer to create durable context response
1985  */
1986 void create_durable_rsp_buf(char *cc)
1987 {
1988 	struct create_durable_rsp *buf;
1989 
1990 	buf = (struct create_durable_rsp *)cc;
1991 	memset(buf, 0, sizeof(struct create_durable_rsp));
1992 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1993 			(struct create_durable_rsp, Data));
1994 	buf->ccontext.DataLength = cpu_to_le32(8);
1995 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1996 			(struct create_durable_rsp, Name));
1997 	buf->ccontext.NameLength = cpu_to_le16(4);
1998 	/* SMB2_CREATE_DURABLE_HANDLE_RESPONSE is "DHnQ" */
1999 	buf->Name[0] = 'D';
2000 	buf->Name[1] = 'H';
2001 	buf->Name[2] = 'n';
2002 	buf->Name[3] = 'Q';
2003 }
2004 
2005 /**
2006  * create_durable_v2_rsp_buf() - create durable handle v2 context
2007  * @cc:	buffer to create durable context response
2008  * @fp: ksmbd file pointer
2009  */
2010 void create_durable_v2_rsp_buf(char *cc, struct ksmbd_file *fp)
2011 {
2012 	struct create_durable_rsp_v2 *buf;
2013 
2014 	buf = (struct create_durable_rsp_v2 *)cc;
2015 	memset(buf, 0, sizeof(struct create_durable_rsp));
2016 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2017 			(struct create_durable_rsp, Data));
2018 	buf->ccontext.DataLength = cpu_to_le32(8);
2019 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2020 			(struct create_durable_rsp, Name));
2021 	buf->ccontext.NameLength = cpu_to_le16(4);
2022 	/* SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2 is "DH2Q" */
2023 	buf->Name[0] = 'D';
2024 	buf->Name[1] = 'H';
2025 	buf->Name[2] = '2';
2026 	buf->Name[3] = 'Q';
2027 
2028 	buf->dcontext.Timeout = cpu_to_le32(fp->durable_timeout);
2029 	if (fp->is_persistent)
2030 		buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2031 }
2032 
2033 /**
2034  * create_mxac_rsp_buf() - create query maximal access context
2035  * @cc:			buffer to create maximal access context response
2036  * @maximal_access:	maximal access
2037  */
2038 void create_mxac_rsp_buf(char *cc, int maximal_access)
2039 {
2040 	struct create_mxac_rsp *buf;
2041 
2042 	buf = (struct create_mxac_rsp *)cc;
2043 	memset(buf, 0, sizeof(struct create_mxac_rsp));
2044 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2045 			(struct create_mxac_rsp, QueryStatus));
2046 	buf->ccontext.DataLength = cpu_to_le32(8);
2047 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2048 			(struct create_mxac_rsp, Name));
2049 	buf->ccontext.NameLength = cpu_to_le16(4);
2050 	/* SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE is "MxAc" */
2051 	buf->Name[0] = 'M';
2052 	buf->Name[1] = 'x';
2053 	buf->Name[2] = 'A';
2054 	buf->Name[3] = 'c';
2055 
2056 	buf->QueryStatus = STATUS_SUCCESS;
2057 	buf->MaximalAccess = cpu_to_le32(maximal_access);
2058 }
2059 
2060 void create_disk_id_rsp_buf(char *cc, __u64 file_id, __u64 vol_id)
2061 {
2062 	struct create_disk_id_rsp *buf;
2063 
2064 	buf = (struct create_disk_id_rsp *)cc;
2065 	memset(buf, 0, sizeof(struct create_disk_id_rsp));
2066 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2067 			(struct create_disk_id_rsp, DiskFileId));
2068 	buf->ccontext.DataLength = cpu_to_le32(32);
2069 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2070 			(struct create_mxac_rsp, Name));
2071 	buf->ccontext.NameLength = cpu_to_le16(4);
2072 	/* SMB2_CREATE_QUERY_ON_DISK_ID_RESPONSE is "QFid" */
2073 	buf->Name[0] = 'Q';
2074 	buf->Name[1] = 'F';
2075 	buf->Name[2] = 'i';
2076 	buf->Name[3] = 'd';
2077 
2078 	buf->DiskFileId = cpu_to_le64(file_id);
2079 	buf->VolumeId = cpu_to_le64(vol_id);
2080 }
2081 
2082 /**
2083  * create_posix_rsp_buf() - create posix extension context
2084  * @cc:	buffer to create posix on posix response
2085  * @fp: ksmbd file pointer
2086  */
2087 void create_posix_rsp_buf(char *cc, struct ksmbd_file *fp)
2088 {
2089 	struct create_posix_rsp *buf;
2090 	struct inode *inode = file_inode(fp->filp);
2091 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
2092 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2093 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2094 
2095 	buf = (struct create_posix_rsp *)cc;
2096 	memset(buf, 0, sizeof(struct create_posix_rsp));
2097 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2098 			(struct create_posix_rsp, nlink));
2099 	/*
2100 	 * DataLength = nlink(4) + reparse_tag(4) + mode(4) +
2101 	 * domain sid(28) + unix group sid(16).
2102 	 */
2103 	buf->ccontext.DataLength = cpu_to_le32(56);
2104 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2105 			(struct create_posix_rsp, Name));
2106 	buf->ccontext.NameLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
2107 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
2108 	buf->Name[0] = 0x93;
2109 	buf->Name[1] = 0xAD;
2110 	buf->Name[2] = 0x25;
2111 	buf->Name[3] = 0x50;
2112 	buf->Name[4] = 0x9C;
2113 	buf->Name[5] = 0xB4;
2114 	buf->Name[6] = 0x11;
2115 	buf->Name[7] = 0xE7;
2116 	buf->Name[8] = 0xB4;
2117 	buf->Name[9] = 0x23;
2118 	buf->Name[10] = 0x83;
2119 	buf->Name[11] = 0xDE;
2120 	buf->Name[12] = 0x96;
2121 	buf->Name[13] = 0x8B;
2122 	buf->Name[14] = 0xCD;
2123 	buf->Name[15] = 0x7C;
2124 
2125 	buf->nlink = cpu_to_le32(inode->i_nlink);
2126 	buf->reparse_tag = cpu_to_le32(fp->volatile_id);
2127 	buf->mode = cpu_to_le32(inode->i_mode & 0777);
2128 	/*
2129 	 * SidBuffer(44) contain two sids(Domain sid(28), UNIX group sid(16)).
2130 	 * Domain sid(28) = revision(1) + num_subauth(1) + authority(6) +
2131 	 *		    sub_auth(4 * 4(num_subauth)) + RID(4).
2132 	 * UNIX group id(16) = revision(1) + num_subauth(1) + authority(6) +
2133 	 *		       sub_auth(4 * 1(num_subauth)) + RID(4).
2134 	 */
2135 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
2136 		  SIDOWNER, (struct smb_sid *)&buf->SidBuffer[0]);
2137 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
2138 		  SIDUNIX_GROUP, (struct smb_sid *)&buf->SidBuffer[28]);
2139 }
2140 
2141 /*
2142  * Find lease object(opinfo) for given lease key/fid from lease
2143  * break/file close path.
2144  */
2145 /**
2146  * lookup_lease_in_table() - find a matching lease info object
2147  * @conn:	connection instance
2148  * @lease_key:	lease key to be searched for
2149  *
2150  * Return:      opinfo if found matching opinfo, otherwise NULL
2151  */
2152 struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
2153 					  char *lease_key)
2154 {
2155 	struct oplock_info *opinfo = NULL, *ret_op = NULL;
2156 	struct lease *lease;
2157 	struct lease_table *lt;
2158 
2159 	read_lock(&lease_list_lock);
2160 	list_for_each_entry(lt, &lease_table_list, l_entry) {
2161 		if (!memcmp(lt->client_guid, conn->ClientGUID,
2162 			    SMB2_CLIENT_GUID_SIZE))
2163 			goto found;
2164 	}
2165 
2166 	read_unlock(&lease_list_lock);
2167 	return NULL;
2168 
2169 found:
2170 	list_for_each_entry(lease, &lt->lease_list, l_entry) {
2171 		if (memcmp(lease->lease_key, lease_key, SMB2_LEASE_KEY_SIZE))
2172 			continue;
2173 		if (!(lease->state & (SMB2_LEASE_HANDLE_CACHING_LE |
2174 				      SMB2_LEASE_WRITE_CACHING_LE)))
2175 			break;
2176 
2177 		spin_lock(&lease->lock);
2178 		list_for_each_entry(opinfo, &lease->open_list, lease_entry) {
2179 			if (!opinfo->op_state ||
2180 			    opinfo->op_state == OPLOCK_CLOSING)
2181 				continue;
2182 			if (!atomic_inc_not_zero(&opinfo->refcount))
2183 				continue;
2184 			ret_op = opinfo;
2185 			break;
2186 		}
2187 		spin_unlock(&lease->lock);
2188 		if (ret_op) {
2189 			ksmbd_debug(OPLOCK, "found opinfo\n");
2190 			goto out;
2191 		}
2192 		break;
2193 	}
2194 
2195 out:
2196 	read_unlock(&lease_list_lock);
2197 	return ret_op;
2198 }
2199 
2200 int smb2_check_durable_oplock(struct ksmbd_conn *conn,
2201 			      struct ksmbd_share_config *share,
2202 			      struct ksmbd_file *fp,
2203 			      struct lease_ctx_info *lctx,
2204 			      struct ksmbd_user *user,
2205 			      char *name)
2206 {
2207 	struct oplock_info *opinfo = opinfo_get(fp);
2208 	int ret = 0;
2209 
2210 	if (!opinfo)
2211 		return 0;
2212 
2213 	if (ksmbd_has_other_active_fd(fp)) {
2214 		ksmbd_debug(SMB, "Durable handle reconnect failed: competing open\n");
2215 		ret = -EBADF;
2216 		goto out;
2217 	}
2218 
2219 	if (ksmbd_vfs_compare_durable_owner(fp, user) == false) {
2220 		ksmbd_debug(SMB, "Durable handle reconnect failed: owner mismatch\n");
2221 		ret = -EBADF;
2222 		goto out;
2223 	}
2224 
2225 	if (opinfo->is_lease == false) {
2226 		if (lctx) {
2227 			pr_err("create context include lease\n");
2228 			ret = -EBADF;
2229 			goto out;
2230 		}
2231 
2232 		if (opinfo->level != SMB2_OPLOCK_LEVEL_BATCH) {
2233 			pr_err("oplock level is not equal to SMB2_OPLOCK_LEVEL_BATCH\n");
2234 			ret = -EBADF;
2235 		}
2236 
2237 		goto out;
2238 	}
2239 
2240 	if (memcmp(conn->ClientGUID, fp->client_guid,
2241 				SMB2_CLIENT_GUID_SIZE)) {
2242 		ksmbd_debug(SMB, "Client guid of fp is not equal to the one of connection\n");
2243 		ret = -EBADF;
2244 		goto out;
2245 	}
2246 
2247 	if (!lctx) {
2248 		ksmbd_debug(SMB, "create context does not include lease\n");
2249 		ret = -EBADF;
2250 		goto out;
2251 	}
2252 
2253 	if (memcmp(opinfo->o_lease->lease_key, lctx->lease_key,
2254 				SMB2_LEASE_KEY_SIZE)) {
2255 		ksmbd_debug(SMB,
2256 			    "lease key of fp does not match lease key in create context\n");
2257 		ret = -EBADF;
2258 		goto out;
2259 	}
2260 
2261 	if (!(opinfo->o_lease->state & SMB2_LEASE_HANDLE_CACHING_LE)) {
2262 		ksmbd_debug(SMB, "lease state does not contain SMB2_LEASE_HANDLE_CACHING\n");
2263 		ret = -EBADF;
2264 		goto out;
2265 	}
2266 
2267 	if (opinfo->o_lease->version != lctx->version) {
2268 		ksmbd_debug(SMB,
2269 			    "lease version of fp does not match the one in create context\n");
2270 		ret = -EBADF;
2271 		goto out;
2272 	}
2273 
2274 	if (!ksmbd_inode_pending_delete(fp))
2275 		ret = ksmbd_validate_name_reconnect(share, fp, name);
2276 out:
2277 	opinfo_put(opinfo);
2278 	return ret;
2279 }
2280