1// SPDX-License-Identifier: GPL-2.0
2/*
3 *  Functions to handle the cached directory entries
4 *
5 *  Copyright (c) 2022, Ronnie Sahlberg <lsahlber@redhat.com>
6 */
7
8#include <linux/namei.h>
9#include "cifsglob.h"
10#include "cifsproto.h"
11#include "cifs_debug.h"
12#include "smb2proto.h"
13#include "cached_dir.h"
14
15static struct cached_fid *init_cached_dir(const char *path);
16static void free_cached_dir(struct cached_fid *cfid);
17static void smb2_close_cached_fid(struct kref *ref);
18static void cfids_laundromat_worker(struct work_struct *work);
19
20static struct cached_fid *find_or_create_cached_dir(struct cached_fids *cfids,
21						    const char *path,
22						    bool lookup_only,
23						    __u32 max_cached_dirs)
24{
25	struct cached_fid *cfid;
26
27	spin_lock(&cfids->cfid_list_lock);
28	list_for_each_entry(cfid, &cfids->entries, entry) {
29		if (!strcmp(cfid->path, path)) {
30			/*
31			 * If it doesn't have a lease it is either not yet
32			 * fully cached or it may be in the process of
33			 * being deleted due to a lease break.
34			 */
35			if (!cfid->time || !cfid->has_lease) {
36				spin_unlock(&cfids->cfid_list_lock);
37				return NULL;
38			}
39			kref_get(&cfid->refcount);
40			spin_unlock(&cfids->cfid_list_lock);
41			return cfid;
42		}
43	}
44	if (lookup_only) {
45		spin_unlock(&cfids->cfid_list_lock);
46		return NULL;
47	}
48	if (cfids->num_entries >= max_cached_dirs) {
49		spin_unlock(&cfids->cfid_list_lock);
50		return NULL;
51	}
52	cfid = init_cached_dir(path);
53	if (cfid == NULL) {
54		spin_unlock(&cfids->cfid_list_lock);
55		return NULL;
56	}
57	cfid->cfids = cfids;
58	cfids->num_entries++;
59	list_add(&cfid->entry, &cfids->entries);
60	cfid->on_list = true;
61	kref_get(&cfid->refcount);
62	spin_unlock(&cfids->cfid_list_lock);
63	return cfid;
64}
65
66static struct dentry *
67path_to_dentry(struct cifs_sb_info *cifs_sb, const char *path)
68{
69	struct dentry *dentry;
70	const char *s, *p;
71	char sep;
72
73	sep = CIFS_DIR_SEP(cifs_sb);
74	dentry = dget(cifs_sb->root);
75	s = path;
76
77	do {
78		struct inode *dir = d_inode(dentry);
79		struct dentry *child;
80
81		if (!S_ISDIR(dir->i_mode)) {
82			dput(dentry);
83			dentry = ERR_PTR(-ENOTDIR);
84			break;
85		}
86
87		/* skip separators */
88		while (*s == sep)
89			s++;
90		if (!*s)
91			break;
92		p = s++;
93		/* next separator */
94		while (*s && *s != sep)
95			s++;
96
97		child = lookup_positive_unlocked(p, dentry, s - p);
98		dput(dentry);
99		dentry = child;
100	} while (!IS_ERR(dentry));
101	return dentry;
102}
103
104static const char *path_no_prefix(struct cifs_sb_info *cifs_sb,
105				  const char *path)
106{
107	size_t len = 0;
108
109	if (!*path)
110		return path;
111
112	if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
113	    cifs_sb->prepath) {
114		len = strlen(cifs_sb->prepath) + 1;
115		if (unlikely(len > strlen(path)))
116			return ERR_PTR(-EINVAL);
117	}
118	return path + len;
119}
120
121/*
122 * Open the and cache a directory handle.
123 * If error then *cfid is not initialized.
124 */
125int open_cached_dir(unsigned int xid, struct cifs_tcon *tcon,
126		    const char *path,
127		    struct cifs_sb_info *cifs_sb,
128		    bool lookup_only, struct cached_fid **ret_cfid)
129{
130	struct cifs_ses *ses;
131	struct TCP_Server_Info *server;
132	struct cifs_open_parms oparms;
133	struct smb2_create_rsp *o_rsp = NULL;
134	struct smb2_query_info_rsp *qi_rsp = NULL;
135	int resp_buftype[2];
136	struct smb_rqst rqst[2];
137	struct kvec rsp_iov[2];
138	struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
139	struct kvec qi_iov[1];
140	int rc, flags = 0;
141	__le16 *utf16_path = NULL;
142	u8 oplock = SMB2_OPLOCK_LEVEL_II;
143	struct cifs_fid *pfid;
144	struct dentry *dentry = NULL;
145	struct cached_fid *cfid;
146	struct cached_fids *cfids;
147	const char *npath;
148
149	if (tcon == NULL || tcon->cfids == NULL || tcon->nohandlecache ||
150	    is_smb1_server(tcon->ses->server) || (dir_cache_timeout == 0))
151		return -EOPNOTSUPP;
152
153	ses = tcon->ses;
154	server = cifs_pick_channel(ses);
155	cfids = tcon->cfids;
156
157	if (!server->ops->new_lease_key)
158		return -EIO;
159
160	if (cifs_sb->root == NULL)
161		return -ENOENT;
162
163	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
164	if (!utf16_path)
165		return -ENOMEM;
166
167	cfid = find_or_create_cached_dir(cfids, path, lookup_only, tcon->max_cached_dirs);
168	if (cfid == NULL) {
169		kfree(utf16_path);
170		return -ENOENT;
171	}
172	/*
173	 * Return cached fid if it has a lease.  Otherwise, it is either a new
174	 * entry or laundromat worker removed it from @cfids->entries.  Caller
175	 * will put last reference if the latter.
176	 */
177	spin_lock(&cfids->cfid_list_lock);
178	if (cfid->has_lease) {
179		spin_unlock(&cfids->cfid_list_lock);
180		*ret_cfid = cfid;
181		kfree(utf16_path);
182		return 0;
183	}
184	spin_unlock(&cfids->cfid_list_lock);
185
186	/*
187	 * Skip any prefix paths in @path as lookup_positive_unlocked() ends up
188	 * calling ->lookup() which already adds those through
189	 * build_path_from_dentry().  Also, do it earlier as we might reconnect
190	 * below when trying to send compounded request and then potentially
191	 * having a different prefix path (e.g. after DFS failover).
192	 */
193	npath = path_no_prefix(cifs_sb, path);
194	if (IS_ERR(npath)) {
195		rc = PTR_ERR(npath);
196		goto out;
197	}
198
199	if (!npath[0]) {
200		dentry = dget(cifs_sb->root);
201	} else {
202		dentry = path_to_dentry(cifs_sb, npath);
203		if (IS_ERR(dentry)) {
204			rc = -ENOENT;
205			goto out;
206		}
207	}
208	cfid->dentry = dentry;
209
210	/*
211	 * We do not hold the lock for the open because in case
212	 * SMB2_open needs to reconnect.
213	 * This is safe because no other thread will be able to get a ref
214	 * to the cfid until we have finished opening the file and (possibly)
215	 * acquired a lease.
216	 */
217	if (smb3_encryption_required(tcon))
218		flags |= CIFS_TRANSFORM_REQ;
219
220	pfid = &cfid->fid;
221	server->ops->new_lease_key(pfid);
222
223	memset(rqst, 0, sizeof(rqst));
224	resp_buftype[0] = resp_buftype[1] = CIFS_NO_BUFFER;
225	memset(rsp_iov, 0, sizeof(rsp_iov));
226
227	/* Open */
228	memset(&open_iov, 0, sizeof(open_iov));
229	rqst[0].rq_iov = open_iov;
230	rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
231
232	oparms = (struct cifs_open_parms) {
233		.tcon = tcon,
234		.path = path,
235		.create_options = cifs_create_options(cifs_sb, CREATE_NOT_FILE),
236		.desired_access =  FILE_READ_DATA | FILE_READ_ATTRIBUTES,
237		.disposition = FILE_OPEN,
238		.fid = pfid,
239	};
240
241	rc = SMB2_open_init(tcon, server,
242			    &rqst[0], &oplock, &oparms, utf16_path);
243	if (rc)
244		goto oshr_free;
245	smb2_set_next_command(tcon, &rqst[0]);
246
247	memset(&qi_iov, 0, sizeof(qi_iov));
248	rqst[1].rq_iov = qi_iov;
249	rqst[1].rq_nvec = 1;
250
251	rc = SMB2_query_info_init(tcon, server,
252				  &rqst[1], COMPOUND_FID,
253				  COMPOUND_FID, FILE_ALL_INFORMATION,
254				  SMB2_O_INFO_FILE, 0,
255				  sizeof(struct smb2_file_all_info) +
256				  PATH_MAX * 2, 0, NULL);
257	if (rc)
258		goto oshr_free;
259
260	smb2_set_related(&rqst[1]);
261
262	/*
263	 * Set @cfid->has_lease to true before sending out compounded request so
264	 * its lease reference can be put in cached_dir_lease_break() due to a
265	 * potential lease break right after the request is sent or while @cfid
266	 * is still being cached.  Concurrent processes won't be to use it yet
267	 * due to @cfid->time being zero.
268	 */
269	cfid->has_lease = true;
270
271	rc = compound_send_recv(xid, ses, server,
272				flags, 2, rqst,
273				resp_buftype, rsp_iov);
274	if (rc) {
275		if (rc == -EREMCHG) {
276			tcon->need_reconnect = true;
277			pr_warn_once("server share %s deleted\n",
278				     tcon->tree_name);
279		}
280		goto oshr_free;
281	}
282	cfid->tcon = tcon;
283	cfid->is_open = true;
284
285	spin_lock(&cfids->cfid_list_lock);
286
287	o_rsp = (struct smb2_create_rsp *)rsp_iov[0].iov_base;
288	oparms.fid->persistent_fid = o_rsp->PersistentFileId;
289	oparms.fid->volatile_fid = o_rsp->VolatileFileId;
290#ifdef CONFIG_CIFS_DEBUG2
291	oparms.fid->mid = le64_to_cpu(o_rsp->hdr.MessageId);
292#endif /* CIFS_DEBUG2 */
293
294
295	if (o_rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE) {
296		spin_unlock(&cfids->cfid_list_lock);
297		rc = -EINVAL;
298		goto oshr_free;
299	}
300
301	rc = smb2_parse_contexts(server, rsp_iov,
302				 &oparms.fid->epoch,
303				 oparms.fid->lease_key,
304				 &oplock, NULL, NULL);
305	if (rc) {
306		spin_unlock(&cfids->cfid_list_lock);
307		goto oshr_free;
308	}
309
310	rc = -EINVAL;
311	if (!(oplock & SMB2_LEASE_READ_CACHING_HE)) {
312		spin_unlock(&cfids->cfid_list_lock);
313		goto oshr_free;
314	}
315	qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
316	if (le32_to_cpu(qi_rsp->OutputBufferLength) < sizeof(struct smb2_file_all_info)) {
317		spin_unlock(&cfids->cfid_list_lock);
318		goto oshr_free;
319	}
320	if (!smb2_validate_and_copy_iov(
321				le16_to_cpu(qi_rsp->OutputBufferOffset),
322				sizeof(struct smb2_file_all_info),
323				&rsp_iov[1], sizeof(struct smb2_file_all_info),
324				(char *)&cfid->file_all_info))
325		cfid->file_all_info_is_valid = true;
326
327	cfid->time = jiffies;
328	spin_unlock(&cfids->cfid_list_lock);
329	/* At this point the directory handle is fully cached */
330	rc = 0;
331
332oshr_free:
333	SMB2_open_free(&rqst[0]);
334	SMB2_query_info_free(&rqst[1]);
335	free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
336	free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
337	if (rc) {
338		spin_lock(&cfids->cfid_list_lock);
339		if (cfid->on_list) {
340			list_del(&cfid->entry);
341			cfid->on_list = false;
342			cfids->num_entries--;
343		}
344		if (cfid->has_lease) {
345			/*
346			 * We are guaranteed to have two references at this
347			 * point. One for the caller and one for a potential
348			 * lease. Release the Lease-ref so that the directory
349			 * will be closed when the caller closes the cached
350			 * handle.
351			 */
352			cfid->has_lease = false;
353			spin_unlock(&cfids->cfid_list_lock);
354			kref_put(&cfid->refcount, smb2_close_cached_fid);
355			goto out;
356		}
357		spin_unlock(&cfids->cfid_list_lock);
358	}
359out:
360	if (rc) {
361		if (cfid->is_open)
362			SMB2_close(0, cfid->tcon, cfid->fid.persistent_fid,
363				   cfid->fid.volatile_fid);
364		free_cached_dir(cfid);
365	} else {
366		*ret_cfid = cfid;
367		atomic_inc(&tcon->num_remote_opens);
368	}
369	kfree(utf16_path);
370
371	return rc;
372}
373
374int open_cached_dir_by_dentry(struct cifs_tcon *tcon,
375			      struct dentry *dentry,
376			      struct cached_fid **ret_cfid)
377{
378	struct cached_fid *cfid;
379	struct cached_fids *cfids = tcon->cfids;
380
381	if (cfids == NULL)
382		return -ENOENT;
383
384	spin_lock(&cfids->cfid_list_lock);
385	list_for_each_entry(cfid, &cfids->entries, entry) {
386		if (dentry && cfid->dentry == dentry) {
387			cifs_dbg(FYI, "found a cached root file handle by dentry\n");
388			kref_get(&cfid->refcount);
389			*ret_cfid = cfid;
390			spin_unlock(&cfids->cfid_list_lock);
391			return 0;
392		}
393	}
394	spin_unlock(&cfids->cfid_list_lock);
395	return -ENOENT;
396}
397
398static void
399smb2_close_cached_fid(struct kref *ref)
400{
401	struct cached_fid *cfid = container_of(ref, struct cached_fid,
402					       refcount);
403
404	spin_lock(&cfid->cfids->cfid_list_lock);
405	if (cfid->on_list) {
406		list_del(&cfid->entry);
407		cfid->on_list = false;
408		cfid->cfids->num_entries--;
409	}
410	spin_unlock(&cfid->cfids->cfid_list_lock);
411
412	dput(cfid->dentry);
413	cfid->dentry = NULL;
414
415	if (cfid->is_open) {
416		SMB2_close(0, cfid->tcon, cfid->fid.persistent_fid,
417			   cfid->fid.volatile_fid);
418		atomic_dec(&cfid->tcon->num_remote_opens);
419	}
420
421	free_cached_dir(cfid);
422}
423
424void drop_cached_dir_by_name(const unsigned int xid, struct cifs_tcon *tcon,
425			     const char *name, struct cifs_sb_info *cifs_sb)
426{
427	struct cached_fid *cfid = NULL;
428	int rc;
429
430	rc = open_cached_dir(xid, tcon, name, cifs_sb, true, &cfid);
431	if (rc) {
432		cifs_dbg(FYI, "no cached dir found for rmdir(%s)\n", name);
433		return;
434	}
435	spin_lock(&cfid->cfids->cfid_list_lock);
436	if (cfid->has_lease) {
437		cfid->has_lease = false;
438		kref_put(&cfid->refcount, smb2_close_cached_fid);
439	}
440	spin_unlock(&cfid->cfids->cfid_list_lock);
441	close_cached_dir(cfid);
442}
443
444
445void close_cached_dir(struct cached_fid *cfid)
446{
447	kref_put(&cfid->refcount, smb2_close_cached_fid);
448}
449
450/*
451 * Called from cifs_kill_sb when we unmount a share
452 */
453void close_all_cached_dirs(struct cifs_sb_info *cifs_sb)
454{
455	struct rb_root *root = &cifs_sb->tlink_tree;
456	struct rb_node *node;
457	struct cached_fid *cfid;
458	struct cifs_tcon *tcon;
459	struct tcon_link *tlink;
460	struct cached_fids *cfids;
461
462	for (node = rb_first(root); node; node = rb_next(node)) {
463		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
464		tcon = tlink_tcon(tlink);
465		if (IS_ERR(tcon))
466			continue;
467		cfids = tcon->cfids;
468		if (cfids == NULL)
469			continue;
470		list_for_each_entry(cfid, &cfids->entries, entry) {
471			dput(cfid->dentry);
472			cfid->dentry = NULL;
473		}
474	}
475}
476
477/*
478 * Invalidate all cached dirs when a TCON has been reset
479 * due to a session loss.
480 */
481void invalidate_all_cached_dirs(struct cifs_tcon *tcon)
482{
483	struct cached_fids *cfids = tcon->cfids;
484	struct cached_fid *cfid, *q;
485	LIST_HEAD(entry);
486
487	if (cfids == NULL)
488		return;
489
490	spin_lock(&cfids->cfid_list_lock);
491	list_for_each_entry_safe(cfid, q, &cfids->entries, entry) {
492		list_move(&cfid->entry, &entry);
493		cfids->num_entries--;
494		cfid->is_open = false;
495		cfid->on_list = false;
496		/* To prevent race with smb2_cached_lease_break() */
497		kref_get(&cfid->refcount);
498	}
499	spin_unlock(&cfids->cfid_list_lock);
500
501	list_for_each_entry_safe(cfid, q, &entry, entry) {
502		list_del(&cfid->entry);
503		cancel_work_sync(&cfid->lease_break);
504		if (cfid->has_lease) {
505			/*
506			 * We lease was never cancelled from the server so we
507			 * need to drop the reference.
508			 */
509			spin_lock(&cfids->cfid_list_lock);
510			cfid->has_lease = false;
511			spin_unlock(&cfids->cfid_list_lock);
512			kref_put(&cfid->refcount, smb2_close_cached_fid);
513		}
514		/* Drop the extra reference opened above*/
515		kref_put(&cfid->refcount, smb2_close_cached_fid);
516	}
517}
518
519static void
520smb2_cached_lease_break(struct work_struct *work)
521{
522	struct cached_fid *cfid = container_of(work,
523				struct cached_fid, lease_break);
524
525	spin_lock(&cfid->cfids->cfid_list_lock);
526	cfid->has_lease = false;
527	spin_unlock(&cfid->cfids->cfid_list_lock);
528	kref_put(&cfid->refcount, smb2_close_cached_fid);
529}
530
531int cached_dir_lease_break(struct cifs_tcon *tcon, __u8 lease_key[16])
532{
533	struct cached_fids *cfids = tcon->cfids;
534	struct cached_fid *cfid;
535
536	if (cfids == NULL)
537		return false;
538
539	spin_lock(&cfids->cfid_list_lock);
540	list_for_each_entry(cfid, &cfids->entries, entry) {
541		if (cfid->has_lease &&
542		    !memcmp(lease_key,
543			    cfid->fid.lease_key,
544			    SMB2_LEASE_KEY_SIZE)) {
545			cfid->time = 0;
546			/*
547			 * We found a lease remove it from the list
548			 * so no threads can access it.
549			 */
550			list_del(&cfid->entry);
551			cfid->on_list = false;
552			cfids->num_entries--;
553
554			queue_work(cifsiod_wq,
555				   &cfid->lease_break);
556			spin_unlock(&cfids->cfid_list_lock);
557			return true;
558		}
559	}
560	spin_unlock(&cfids->cfid_list_lock);
561	return false;
562}
563
564static struct cached_fid *init_cached_dir(const char *path)
565{
566	struct cached_fid *cfid;
567
568	cfid = kzalloc(sizeof(*cfid), GFP_ATOMIC);
569	if (!cfid)
570		return NULL;
571	cfid->path = kstrdup(path, GFP_ATOMIC);
572	if (!cfid->path) {
573		kfree(cfid);
574		return NULL;
575	}
576
577	INIT_WORK(&cfid->lease_break, smb2_cached_lease_break);
578	INIT_LIST_HEAD(&cfid->entry);
579	INIT_LIST_HEAD(&cfid->dirents.entries);
580	mutex_init(&cfid->dirents.de_mutex);
581	spin_lock_init(&cfid->fid_lock);
582	kref_init(&cfid->refcount);
583	return cfid;
584}
585
586static void free_cached_dir(struct cached_fid *cfid)
587{
588	struct cached_dirent *dirent, *q;
589
590	dput(cfid->dentry);
591	cfid->dentry = NULL;
592
593	/*
594	 * Delete all cached dirent names
595	 */
596	list_for_each_entry_safe(dirent, q, &cfid->dirents.entries, entry) {
597		list_del(&dirent->entry);
598		kfree(dirent->name);
599		kfree(dirent);
600	}
601
602	kfree(cfid->path);
603	cfid->path = NULL;
604	kfree(cfid);
605}
606
607static void cfids_laundromat_worker(struct work_struct *work)
608{
609	struct cached_fids *cfids;
610	struct cached_fid *cfid, *q;
611	LIST_HEAD(entry);
612
613	cfids = container_of(work, struct cached_fids, laundromat_work.work);
614
615	spin_lock(&cfids->cfid_list_lock);
616	list_for_each_entry_safe(cfid, q, &cfids->entries, entry) {
617		if (cfid->time &&
618		    time_after(jiffies, cfid->time + HZ * dir_cache_timeout)) {
619			cfid->on_list = false;
620			list_move(&cfid->entry, &entry);
621			cfids->num_entries--;
622			/* To prevent race with smb2_cached_lease_break() */
623			kref_get(&cfid->refcount);
624		}
625	}
626	spin_unlock(&cfids->cfid_list_lock);
627
628	list_for_each_entry_safe(cfid, q, &entry, entry) {
629		list_del(&cfid->entry);
630		/*
631		 * Cancel and wait for the work to finish in case we are racing
632		 * with it.
633		 */
634		cancel_work_sync(&cfid->lease_break);
635		if (cfid->has_lease) {
636			/*
637			 * Our lease has not yet been cancelled from the server
638			 * so we need to drop the reference.
639			 */
640			spin_lock(&cfids->cfid_list_lock);
641			cfid->has_lease = false;
642			spin_unlock(&cfids->cfid_list_lock);
643			kref_put(&cfid->refcount, smb2_close_cached_fid);
644		}
645		/* Drop the extra reference opened above */
646		kref_put(&cfid->refcount, smb2_close_cached_fid);
647	}
648	queue_delayed_work(cifsiod_wq, &cfids->laundromat_work,
649			   dir_cache_timeout * HZ);
650}
651
652struct cached_fids *init_cached_dirs(void)
653{
654	struct cached_fids *cfids;
655
656	cfids = kzalloc(sizeof(*cfids), GFP_KERNEL);
657	if (!cfids)
658		return NULL;
659	spin_lock_init(&cfids->cfid_list_lock);
660	INIT_LIST_HEAD(&cfids->entries);
661
662	INIT_DELAYED_WORK(&cfids->laundromat_work, cfids_laundromat_worker);
663	queue_delayed_work(cifsiod_wq, &cfids->laundromat_work,
664			   dir_cache_timeout * HZ);
665
666	return cfids;
667}
668
669/*
670 * Called from tconInfoFree when we are tearing down the tcon.
671 * There are no active users or open files/directories at this point.
672 */
673void free_cached_dirs(struct cached_fids *cfids)
674{
675	struct cached_fid *cfid, *q;
676	LIST_HEAD(entry);
677
678	if (cfids == NULL)
679		return;
680
681	cancel_delayed_work_sync(&cfids->laundromat_work);
682
683	spin_lock(&cfids->cfid_list_lock);
684	list_for_each_entry_safe(cfid, q, &cfids->entries, entry) {
685		cfid->on_list = false;
686		cfid->is_open = false;
687		list_move(&cfid->entry, &entry);
688	}
689	spin_unlock(&cfids->cfid_list_lock);
690
691	list_for_each_entry_safe(cfid, q, &entry, entry) {
692		list_del(&cfid->entry);
693		free_cached_dir(cfid);
694	}
695
696	kfree(cfids);
697}
698