GNU Linux-libre 5.15.137-gnu
[releases.git] / fs / cifs / dfs_cache.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * DFS referral cache routines
4  *
5  * Copyright (c) 2018-2019 Paulo Alcantara <palcantara@suse.de>
6  */
7
8 #include <linux/jhash.h>
9 #include <linux/ktime.h>
10 #include <linux/slab.h>
11 #include <linux/proc_fs.h>
12 #include <linux/nls.h>
13 #include <linux/workqueue.h>
14 #include <linux/uuid.h>
15 #include "cifsglob.h"
16 #include "smb2pdu.h"
17 #include "smb2proto.h"
18 #include "cifsproto.h"
19 #include "cifs_debug.h"
20 #include "cifs_unicode.h"
21 #include "smb2glob.h"
22 #include "dns_resolve.h"
23
24 #include "dfs_cache.h"
25
26 #define CACHE_HTABLE_SIZE 32
27 #define CACHE_MAX_ENTRIES 64
28 #define CACHE_MIN_TTL 120 /* 2 minutes */
29
30 #define IS_DFS_INTERLINK(v) (((v) & DFSREF_REFERRAL_SERVER) && !((v) & DFSREF_STORAGE_SERVER))
31
32 struct cache_dfs_tgt {
33         char *name;
34         int path_consumed;
35         struct list_head list;
36 };
37
38 struct cache_entry {
39         struct hlist_node hlist;
40         const char *path;
41         int hdr_flags; /* RESP_GET_DFS_REFERRAL.ReferralHeaderFlags */
42         int ttl; /* DFS_REREFERRAL_V3.TimeToLive */
43         int srvtype; /* DFS_REREFERRAL_V3.ServerType */
44         int ref_flags; /* DFS_REREFERRAL_V3.ReferralEntryFlags */
45         struct timespec64 etime;
46         int path_consumed; /* RESP_GET_DFS_REFERRAL.PathConsumed */
47         int numtgts;
48         struct list_head tlist;
49         struct cache_dfs_tgt *tgthint;
50 };
51
52 /* List of referral server sessions per dfs mount */
53 struct mount_group {
54         struct list_head list;
55         uuid_t id;
56         struct cifs_ses *sessions[CACHE_MAX_ENTRIES];
57         int num_sessions;
58         spinlock_t lock;
59         struct list_head refresh_list;
60         struct kref refcount;
61 };
62
63 static struct kmem_cache *cache_slab __read_mostly;
64 static struct workqueue_struct *dfscache_wq __read_mostly;
65
66 static int cache_ttl;
67 static DEFINE_SPINLOCK(cache_ttl_lock);
68
69 static struct nls_table *cache_cp;
70
71 /*
72  * Number of entries in the cache
73  */
74 static atomic_t cache_count;
75
76 static struct hlist_head cache_htable[CACHE_HTABLE_SIZE];
77 static DECLARE_RWSEM(htable_rw_lock);
78
79 static LIST_HEAD(mount_group_list);
80 static DEFINE_MUTEX(mount_group_list_lock);
81
82 static void refresh_cache_worker(struct work_struct *work);
83
84 static DECLARE_DELAYED_WORK(refresh_task, refresh_cache_worker);
85
86 static void get_ipc_unc(const char *ref_path, char *ipc, size_t ipclen)
87 {
88         const char *host;
89         size_t len;
90
91         extract_unc_hostname(ref_path, &host, &len);
92         scnprintf(ipc, ipclen, "\\\\%.*s\\IPC$", (int)len, host);
93 }
94
95 static struct cifs_ses *find_ipc_from_server_path(struct cifs_ses **ses, const char *path)
96 {
97         char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
98
99         get_ipc_unc(path, unc, sizeof(unc));
100         for (; *ses; ses++) {
101                 if (!strcasecmp(unc, (*ses)->tcon_ipc->treeName))
102                         return *ses;
103         }
104         return ERR_PTR(-ENOENT);
105 }
106
107 static void __mount_group_release(struct mount_group *mg)
108 {
109         int i;
110
111         for (i = 0; i < mg->num_sessions; i++)
112                 cifs_put_smb_ses(mg->sessions[i]);
113         kfree(mg);
114 }
115
116 static void mount_group_release(struct kref *kref)
117 {
118         struct mount_group *mg = container_of(kref, struct mount_group, refcount);
119
120         mutex_lock(&mount_group_list_lock);
121         list_del(&mg->list);
122         mutex_unlock(&mount_group_list_lock);
123         __mount_group_release(mg);
124 }
125
126 static struct mount_group *find_mount_group_locked(const uuid_t *id)
127 {
128         struct mount_group *mg;
129
130         list_for_each_entry(mg, &mount_group_list, list) {
131                 if (uuid_equal(&mg->id, id))
132                         return mg;
133         }
134         return ERR_PTR(-ENOENT);
135 }
136
137 static struct mount_group *__get_mount_group_locked(const uuid_t *id)
138 {
139         struct mount_group *mg;
140
141         mg = find_mount_group_locked(id);
142         if (!IS_ERR(mg))
143                 return mg;
144
145         mg = kmalloc(sizeof(*mg), GFP_KERNEL);
146         if (!mg)
147                 return ERR_PTR(-ENOMEM);
148         kref_init(&mg->refcount);
149         uuid_copy(&mg->id, id);
150         mg->num_sessions = 0;
151         spin_lock_init(&mg->lock);
152         list_add(&mg->list, &mount_group_list);
153         return mg;
154 }
155
156 static struct mount_group *get_mount_group(const uuid_t *id)
157 {
158         struct mount_group *mg;
159
160         mutex_lock(&mount_group_list_lock);
161         mg = __get_mount_group_locked(id);
162         if (!IS_ERR(mg))
163                 kref_get(&mg->refcount);
164         mutex_unlock(&mount_group_list_lock);
165
166         return mg;
167 }
168
169 static void free_mount_group_list(void)
170 {
171         struct mount_group *mg, *tmp_mg;
172
173         list_for_each_entry_safe(mg, tmp_mg, &mount_group_list, list) {
174                 list_del_init(&mg->list);
175                 __mount_group_release(mg);
176         }
177 }
178
179 /**
180  * dfs_cache_canonical_path - get a canonical DFS path
181  *
182  * @path: DFS path
183  * @cp: codepage
184  * @remap: mapping type
185  *
186  * Return canonical path if success, otherwise error.
187  */
188 char *dfs_cache_canonical_path(const char *path, const struct nls_table *cp, int remap)
189 {
190         char *tmp;
191         int plen = 0;
192         char *npath;
193
194         if (!path || strlen(path) < 3 || (*path != '\\' && *path != '/'))
195                 return ERR_PTR(-EINVAL);
196
197         if (unlikely(strcmp(cp->charset, cache_cp->charset))) {
198                 tmp = (char *)cifs_strndup_to_utf16(path, strlen(path), &plen, cp, remap);
199                 if (!tmp) {
200                         cifs_dbg(VFS, "%s: failed to convert path to utf16\n", __func__);
201                         return ERR_PTR(-EINVAL);
202                 }
203
204                 npath = cifs_strndup_from_utf16(tmp, plen, true, cache_cp);
205                 kfree(tmp);
206
207                 if (!npath) {
208                         cifs_dbg(VFS, "%s: failed to convert path from utf16\n", __func__);
209                         return ERR_PTR(-EINVAL);
210                 }
211         } else {
212                 npath = kstrdup(path, GFP_KERNEL);
213                 if (!npath)
214                         return ERR_PTR(-ENOMEM);
215         }
216         convert_delimiter(npath, '\\');
217         return npath;
218 }
219
220 static inline bool cache_entry_expired(const struct cache_entry *ce)
221 {
222         struct timespec64 ts;
223
224         ktime_get_coarse_real_ts64(&ts);
225         return timespec64_compare(&ts, &ce->etime) >= 0;
226 }
227
228 static inline void free_tgts(struct cache_entry *ce)
229 {
230         struct cache_dfs_tgt *t, *n;
231
232         list_for_each_entry_safe(t, n, &ce->tlist, list) {
233                 list_del(&t->list);
234                 kfree(t->name);
235                 kfree(t);
236         }
237 }
238
239 static inline void flush_cache_ent(struct cache_entry *ce)
240 {
241         hlist_del_init(&ce->hlist);
242         kfree(ce->path);
243         free_tgts(ce);
244         atomic_dec(&cache_count);
245         kmem_cache_free(cache_slab, ce);
246 }
247
248 static void flush_cache_ents(void)
249 {
250         int i;
251
252         for (i = 0; i < CACHE_HTABLE_SIZE; i++) {
253                 struct hlist_head *l = &cache_htable[i];
254                 struct hlist_node *n;
255                 struct cache_entry *ce;
256
257                 hlist_for_each_entry_safe(ce, n, l, hlist) {
258                         if (!hlist_unhashed(&ce->hlist))
259                                 flush_cache_ent(ce);
260                 }
261         }
262 }
263
264 /*
265  * dfs cache /proc file
266  */
267 static int dfscache_proc_show(struct seq_file *m, void *v)
268 {
269         int i;
270         struct cache_entry *ce;
271         struct cache_dfs_tgt *t;
272
273         seq_puts(m, "DFS cache\n---------\n");
274
275         down_read(&htable_rw_lock);
276         for (i = 0; i < CACHE_HTABLE_SIZE; i++) {
277                 struct hlist_head *l = &cache_htable[i];
278
279                 hlist_for_each_entry(ce, l, hlist) {
280                         if (hlist_unhashed(&ce->hlist))
281                                 continue;
282
283                         seq_printf(m,
284                                    "cache entry: path=%s,type=%s,ttl=%d,etime=%ld,hdr_flags=0x%x,ref_flags=0x%x,interlink=%s,path_consumed=%d,expired=%s\n",
285                                    ce->path, ce->srvtype == DFS_TYPE_ROOT ? "root" : "link",
286                                    ce->ttl, ce->etime.tv_nsec, ce->ref_flags, ce->hdr_flags,
287                                    IS_DFS_INTERLINK(ce->hdr_flags) ? "yes" : "no",
288                                    ce->path_consumed, cache_entry_expired(ce) ? "yes" : "no");
289
290                         list_for_each_entry(t, &ce->tlist, list) {
291                                 seq_printf(m, "  %s%s\n",
292                                            t->name,
293                                            ce->tgthint == t ? " (target hint)" : "");
294                         }
295                 }
296         }
297         up_read(&htable_rw_lock);
298
299         return 0;
300 }
301
302 static ssize_t dfscache_proc_write(struct file *file, const char __user *buffer,
303                                    size_t count, loff_t *ppos)
304 {
305         char c;
306         int rc;
307
308         rc = get_user(c, buffer);
309         if (rc)
310                 return rc;
311
312         if (c != '0')
313                 return -EINVAL;
314
315         cifs_dbg(FYI, "clearing dfs cache\n");
316
317         down_write(&htable_rw_lock);
318         flush_cache_ents();
319         up_write(&htable_rw_lock);
320
321         return count;
322 }
323
324 static int dfscache_proc_open(struct inode *inode, struct file *file)
325 {
326         return single_open(file, dfscache_proc_show, NULL);
327 }
328
329 const struct proc_ops dfscache_proc_ops = {
330         .proc_open      = dfscache_proc_open,
331         .proc_read      = seq_read,
332         .proc_lseek     = seq_lseek,
333         .proc_release   = single_release,
334         .proc_write     = dfscache_proc_write,
335 };
336
337 #ifdef CONFIG_CIFS_DEBUG2
338 static inline void dump_tgts(const struct cache_entry *ce)
339 {
340         struct cache_dfs_tgt *t;
341
342         cifs_dbg(FYI, "target list:\n");
343         list_for_each_entry(t, &ce->tlist, list) {
344                 cifs_dbg(FYI, "  %s%s\n", t->name,
345                          ce->tgthint == t ? " (target hint)" : "");
346         }
347 }
348
349 static inline void dump_ce(const struct cache_entry *ce)
350 {
351         cifs_dbg(FYI, "cache entry: path=%s,type=%s,ttl=%d,etime=%ld,hdr_flags=0x%x,ref_flags=0x%x,interlink=%s,path_consumed=%d,expired=%s\n",
352                  ce->path,
353                  ce->srvtype == DFS_TYPE_ROOT ? "root" : "link", ce->ttl,
354                  ce->etime.tv_nsec,
355                  ce->hdr_flags, ce->ref_flags,
356                  IS_DFS_INTERLINK(ce->hdr_flags) ? "yes" : "no",
357                  ce->path_consumed,
358                  cache_entry_expired(ce) ? "yes" : "no");
359         dump_tgts(ce);
360 }
361
362 static inline void dump_refs(const struct dfs_info3_param *refs, int numrefs)
363 {
364         int i;
365
366         cifs_dbg(FYI, "DFS referrals returned by the server:\n");
367         for (i = 0; i < numrefs; i++) {
368                 const struct dfs_info3_param *ref = &refs[i];
369
370                 cifs_dbg(FYI,
371                          "\n"
372                          "flags:         0x%x\n"
373                          "path_consumed: %d\n"
374                          "server_type:   0x%x\n"
375                          "ref_flag:      0x%x\n"
376                          "path_name:     %s\n"
377                          "node_name:     %s\n"
378                          "ttl:           %d (%dm)\n",
379                          ref->flags, ref->path_consumed, ref->server_type,
380                          ref->ref_flag, ref->path_name, ref->node_name,
381                          ref->ttl, ref->ttl / 60);
382         }
383 }
384 #else
385 #define dump_tgts(e)
386 #define dump_ce(e)
387 #define dump_refs(r, n)
388 #endif
389
390 /**
391  * dfs_cache_init - Initialize DFS referral cache.
392  *
393  * Return zero if initialized successfully, otherwise non-zero.
394  */
395 int dfs_cache_init(void)
396 {
397         int rc;
398         int i;
399
400         dfscache_wq = alloc_workqueue("cifs-dfscache", WQ_FREEZABLE | WQ_UNBOUND, 1);
401         if (!dfscache_wq)
402                 return -ENOMEM;
403
404         cache_slab = kmem_cache_create("cifs_dfs_cache",
405                                        sizeof(struct cache_entry), 0,
406                                        SLAB_HWCACHE_ALIGN, NULL);
407         if (!cache_slab) {
408                 rc = -ENOMEM;
409                 goto out_destroy_wq;
410         }
411
412         for (i = 0; i < CACHE_HTABLE_SIZE; i++)
413                 INIT_HLIST_HEAD(&cache_htable[i]);
414
415         atomic_set(&cache_count, 0);
416         cache_cp = load_nls("utf8");
417         if (!cache_cp)
418                 cache_cp = load_nls_default();
419
420         cifs_dbg(FYI, "%s: initialized DFS referral cache\n", __func__);
421         return 0;
422
423 out_destroy_wq:
424         destroy_workqueue(dfscache_wq);
425         return rc;
426 }
427
428 static int cache_entry_hash(const void *data, int size, unsigned int *hash)
429 {
430         int i, clen;
431         const unsigned char *s = data;
432         wchar_t c;
433         unsigned int h = 0;
434
435         for (i = 0; i < size; i += clen) {
436                 clen = cache_cp->char2uni(&s[i], size - i, &c);
437                 if (unlikely(clen < 0)) {
438                         cifs_dbg(VFS, "%s: can't convert char\n", __func__);
439                         return clen;
440                 }
441                 c = cifs_toupper(c);
442                 h = jhash(&c, sizeof(c), h);
443         }
444         *hash = h % CACHE_HTABLE_SIZE;
445         return 0;
446 }
447
448 /* Return target hint of a DFS cache entry */
449 static inline char *get_tgt_name(const struct cache_entry *ce)
450 {
451         struct cache_dfs_tgt *t = ce->tgthint;
452
453         return t ? t->name : ERR_PTR(-ENOENT);
454 }
455
456 /* Return expire time out of a new entry's TTL */
457 static inline struct timespec64 get_expire_time(int ttl)
458 {
459         struct timespec64 ts = {
460                 .tv_sec = ttl,
461                 .tv_nsec = 0,
462         };
463         struct timespec64 now;
464
465         ktime_get_coarse_real_ts64(&now);
466         return timespec64_add(now, ts);
467 }
468
469 /* Allocate a new DFS target */
470 static struct cache_dfs_tgt *alloc_target(const char *name, int path_consumed)
471 {
472         struct cache_dfs_tgt *t;
473
474         t = kmalloc(sizeof(*t), GFP_ATOMIC);
475         if (!t)
476                 return ERR_PTR(-ENOMEM);
477         t->name = kstrdup(name, GFP_ATOMIC);
478         if (!t->name) {
479                 kfree(t);
480                 return ERR_PTR(-ENOMEM);
481         }
482         t->path_consumed = path_consumed;
483         INIT_LIST_HEAD(&t->list);
484         return t;
485 }
486
487 /*
488  * Copy DFS referral information to a cache entry and conditionally update
489  * target hint.
490  */
491 static int copy_ref_data(const struct dfs_info3_param *refs, int numrefs,
492                          struct cache_entry *ce, const char *tgthint)
493 {
494         int i;
495
496         ce->ttl = max_t(int, refs[0].ttl, CACHE_MIN_TTL);
497         ce->etime = get_expire_time(ce->ttl);
498         ce->srvtype = refs[0].server_type;
499         ce->hdr_flags = refs[0].flags;
500         ce->ref_flags = refs[0].ref_flag;
501         ce->path_consumed = refs[0].path_consumed;
502
503         for (i = 0; i < numrefs; i++) {
504                 struct cache_dfs_tgt *t;
505
506                 t = alloc_target(refs[i].node_name, refs[i].path_consumed);
507                 if (IS_ERR(t)) {
508                         free_tgts(ce);
509                         return PTR_ERR(t);
510                 }
511                 if (tgthint && !strcasecmp(t->name, tgthint)) {
512                         list_add(&t->list, &ce->tlist);
513                         tgthint = NULL;
514                 } else {
515                         list_add_tail(&t->list, &ce->tlist);
516                 }
517                 ce->numtgts++;
518         }
519
520         ce->tgthint = list_first_entry_or_null(&ce->tlist,
521                                                struct cache_dfs_tgt, list);
522
523         return 0;
524 }
525
526 /* Allocate a new cache entry */
527 static struct cache_entry *alloc_cache_entry(struct dfs_info3_param *refs, int numrefs)
528 {
529         struct cache_entry *ce;
530         int rc;
531
532         ce = kmem_cache_zalloc(cache_slab, GFP_KERNEL);
533         if (!ce)
534                 return ERR_PTR(-ENOMEM);
535
536         ce->path = refs[0].path_name;
537         refs[0].path_name = NULL;
538
539         INIT_HLIST_NODE(&ce->hlist);
540         INIT_LIST_HEAD(&ce->tlist);
541
542         rc = copy_ref_data(refs, numrefs, ce, NULL);
543         if (rc) {
544                 kfree(ce->path);
545                 kmem_cache_free(cache_slab, ce);
546                 ce = ERR_PTR(rc);
547         }
548         return ce;
549 }
550
551 static void remove_oldest_entry_locked(void)
552 {
553         int i;
554         struct cache_entry *ce;
555         struct cache_entry *to_del = NULL;
556
557         WARN_ON(!rwsem_is_locked(&htable_rw_lock));
558
559         for (i = 0; i < CACHE_HTABLE_SIZE; i++) {
560                 struct hlist_head *l = &cache_htable[i];
561
562                 hlist_for_each_entry(ce, l, hlist) {
563                         if (hlist_unhashed(&ce->hlist))
564                                 continue;
565                         if (!to_del || timespec64_compare(&ce->etime,
566                                                           &to_del->etime) < 0)
567                                 to_del = ce;
568                 }
569         }
570
571         if (!to_del) {
572                 cifs_dbg(FYI, "%s: no entry to remove\n", __func__);
573                 return;
574         }
575
576         cifs_dbg(FYI, "%s: removing entry\n", __func__);
577         dump_ce(to_del);
578         flush_cache_ent(to_del);
579 }
580
581 /* Add a new DFS cache entry */
582 static int add_cache_entry_locked(struct dfs_info3_param *refs, int numrefs)
583 {
584         int rc;
585         struct cache_entry *ce;
586         unsigned int hash;
587
588         WARN_ON(!rwsem_is_locked(&htable_rw_lock));
589
590         if (atomic_read(&cache_count) >= CACHE_MAX_ENTRIES) {
591                 cifs_dbg(FYI, "%s: reached max cache size (%d)\n", __func__, CACHE_MAX_ENTRIES);
592                 remove_oldest_entry_locked();
593         }
594
595         rc = cache_entry_hash(refs[0].path_name, strlen(refs[0].path_name), &hash);
596         if (rc)
597                 return rc;
598
599         ce = alloc_cache_entry(refs, numrefs);
600         if (IS_ERR(ce))
601                 return PTR_ERR(ce);
602
603         spin_lock(&cache_ttl_lock);
604         if (!cache_ttl) {
605                 cache_ttl = ce->ttl;
606                 queue_delayed_work(dfscache_wq, &refresh_task, cache_ttl * HZ);
607         } else {
608                 cache_ttl = min_t(int, cache_ttl, ce->ttl);
609                 mod_delayed_work(dfscache_wq, &refresh_task, cache_ttl * HZ);
610         }
611         spin_unlock(&cache_ttl_lock);
612
613         hlist_add_head(&ce->hlist, &cache_htable[hash]);
614         dump_ce(ce);
615
616         atomic_inc(&cache_count);
617
618         return 0;
619 }
620
621 /* Check if two DFS paths are equal.  @s1 and @s2 are expected to be in @cache_cp's charset */
622 static bool dfs_path_equal(const char *s1, int len1, const char *s2, int len2)
623 {
624         int i, l1, l2;
625         wchar_t c1, c2;
626
627         if (len1 != len2)
628                 return false;
629
630         for (i = 0; i < len1; i += l1) {
631                 l1 = cache_cp->char2uni(&s1[i], len1 - i, &c1);
632                 l2 = cache_cp->char2uni(&s2[i], len2 - i, &c2);
633                 if (unlikely(l1 < 0 && l2 < 0)) {
634                         if (s1[i] != s2[i])
635                                 return false;
636                         l1 = 1;
637                         continue;
638                 }
639                 if (l1 != l2)
640                         return false;
641                 if (cifs_toupper(c1) != cifs_toupper(c2))
642                         return false;
643         }
644         return true;
645 }
646
647 static struct cache_entry *__lookup_cache_entry(const char *path, unsigned int hash, int len)
648 {
649         struct cache_entry *ce;
650
651         hlist_for_each_entry(ce, &cache_htable[hash], hlist) {
652                 if (dfs_path_equal(ce->path, strlen(ce->path), path, len)) {
653                         dump_ce(ce);
654                         return ce;
655                 }
656         }
657         return ERR_PTR(-EEXIST);
658 }
659
660 /*
661  * Find a DFS cache entry in hash table and optionally check prefix path against normalized @path.
662  *
663  * Use whole path components in the match.  Must be called with htable_rw_lock held.
664  *
665  * Return ERR_PTR(-EEXIST) if the entry is not found.
666  */
667 static struct cache_entry *lookup_cache_entry(const char *path)
668 {
669         struct cache_entry *ce;
670         int cnt = 0;
671         const char *s = path, *e;
672         char sep = *s;
673         unsigned int hash;
674         int rc;
675
676         while ((s = strchr(s, sep)) && ++cnt < 3)
677                 s++;
678
679         if (cnt < 3) {
680                 rc = cache_entry_hash(path, strlen(path), &hash);
681                 if (rc)
682                         return ERR_PTR(rc);
683                 return __lookup_cache_entry(path, hash, strlen(path));
684         }
685         /*
686          * Handle paths that have more than two path components and are a complete prefix of the DFS
687          * referral request path (@path).
688          *
689          * See MS-DFSC 3.2.5.5 "Receiving a Root Referral Request or Link Referral Request".
690          */
691         e = path + strlen(path) - 1;
692         while (e > s) {
693                 int len;
694
695                 /* skip separators */
696                 while (e > s && *e == sep)
697                         e--;
698                 if (e == s)
699                         break;
700
701                 len = e + 1 - path;
702                 rc = cache_entry_hash(path, len, &hash);
703                 if (rc)
704                         return ERR_PTR(rc);
705                 ce = __lookup_cache_entry(path, hash, len);
706                 if (!IS_ERR(ce))
707                         return ce;
708
709                 /* backward until separator */
710                 while (e > s && *e != sep)
711                         e--;
712         }
713         return ERR_PTR(-EEXIST);
714 }
715
716 /**
717  * dfs_cache_destroy - destroy DFS referral cache
718  */
719 void dfs_cache_destroy(void)
720 {
721         cancel_delayed_work_sync(&refresh_task);
722         unload_nls(cache_cp);
723         free_mount_group_list();
724         flush_cache_ents();
725         kmem_cache_destroy(cache_slab);
726         destroy_workqueue(dfscache_wq);
727
728         cifs_dbg(FYI, "%s: destroyed DFS referral cache\n", __func__);
729 }
730
731 /* Update a cache entry with the new referral in @refs */
732 static int update_cache_entry_locked(struct cache_entry *ce, const struct dfs_info3_param *refs,
733                                      int numrefs)
734 {
735         int rc;
736         char *s, *th = NULL;
737
738         WARN_ON(!rwsem_is_locked(&htable_rw_lock));
739
740         if (ce->tgthint) {
741                 s = ce->tgthint->name;
742                 th = kstrdup(s, GFP_ATOMIC);
743                 if (!th)
744                         return -ENOMEM;
745         }
746
747         free_tgts(ce);
748         ce->numtgts = 0;
749
750         rc = copy_ref_data(refs, numrefs, ce, th);
751
752         kfree(th);
753
754         return rc;
755 }
756
757 static int get_dfs_referral(const unsigned int xid, struct cifs_ses *ses, const char *path,
758                             struct dfs_info3_param **refs, int *numrefs)
759 {
760         int rc;
761         int i;
762
763         cifs_dbg(FYI, "%s: get an DFS referral for %s\n", __func__, path);
764
765         *refs = NULL;
766         *numrefs = 0;
767
768         if (!ses || !ses->server || !ses->server->ops->get_dfs_refer)
769                 return -EOPNOTSUPP;
770         if (unlikely(!cache_cp))
771                 return -EINVAL;
772
773         rc =  ses->server->ops->get_dfs_refer(xid, ses, path, refs, numrefs, cache_cp,
774                                               NO_MAP_UNI_RSVD);
775         if (!rc) {
776                 struct dfs_info3_param *ref = *refs;
777
778                 for (i = 0; i < *numrefs; i++)
779                         convert_delimiter(ref[i].path_name, '\\');
780         }
781         return rc;
782 }
783
784 /*
785  * Find, create or update a DFS cache entry.
786  *
787  * If the entry wasn't found, it will create a new one. Or if it was found but
788  * expired, then it will update the entry accordingly.
789  *
790  * For interlinks, cifs_mount() and expand_dfs_referral() are supposed to
791  * handle them properly.
792  */
793 static int cache_refresh_path(const unsigned int xid, struct cifs_ses *ses, const char *path)
794 {
795         struct dfs_info3_param *refs = NULL;
796         struct cache_entry *ce;
797         int numrefs = 0;
798         int rc;
799
800         cifs_dbg(FYI, "%s: search path: %s\n", __func__, path);
801
802         down_read(&htable_rw_lock);
803
804         ce = lookup_cache_entry(path);
805         if (!IS_ERR(ce) && !cache_entry_expired(ce)) {
806                 up_read(&htable_rw_lock);
807                 return 0;
808         }
809         /*
810          * Unlock shared access as we don't want to hold any locks while getting
811          * a new referral.  The @ses used for performing the I/O could be
812          * reconnecting and it acquires @htable_rw_lock to look up the dfs cache
813          * in order to failover -- if necessary.
814          */
815         up_read(&htable_rw_lock);
816
817         /*
818          * Either the entry was not found, or it is expired.
819          * Request a new DFS referral in order to create or update a cache entry.
820          */
821         rc = get_dfs_referral(xid, ses, path, &refs, &numrefs);
822         if (rc)
823                 goto out;
824
825         dump_refs(refs, numrefs);
826
827         down_write(&htable_rw_lock);
828         /* Re-check as another task might have it added or refreshed already */
829         ce = lookup_cache_entry(path);
830         if (!IS_ERR(ce)) {
831                 if (cache_entry_expired(ce))
832                         rc = update_cache_entry_locked(ce, refs, numrefs);
833         } else {
834                 rc = add_cache_entry_locked(refs, numrefs);
835         }
836
837         up_write(&htable_rw_lock);
838 out:
839         free_dfs_info_array(refs, numrefs);
840         return rc;
841 }
842
843 /*
844  * Set up a DFS referral from a given cache entry.
845  *
846  * Must be called with htable_rw_lock held.
847  */
848 static int setup_referral(const char *path, struct cache_entry *ce,
849                           struct dfs_info3_param *ref, const char *target)
850 {
851         int rc;
852
853         cifs_dbg(FYI, "%s: set up new ref\n", __func__);
854
855         memset(ref, 0, sizeof(*ref));
856
857         ref->path_name = kstrdup(path, GFP_ATOMIC);
858         if (!ref->path_name)
859                 return -ENOMEM;
860
861         ref->node_name = kstrdup(target, GFP_ATOMIC);
862         if (!ref->node_name) {
863                 rc = -ENOMEM;
864                 goto err_free_path;
865         }
866
867         ref->path_consumed = ce->path_consumed;
868         ref->ttl = ce->ttl;
869         ref->server_type = ce->srvtype;
870         ref->ref_flag = ce->ref_flags;
871         ref->flags = ce->hdr_flags;
872
873         return 0;
874
875 err_free_path:
876         kfree(ref->path_name);
877         ref->path_name = NULL;
878         return rc;
879 }
880
881 /* Return target list of a DFS cache entry */
882 static int get_targets(struct cache_entry *ce, struct dfs_cache_tgt_list *tl)
883 {
884         int rc;
885         struct list_head *head = &tl->tl_list;
886         struct cache_dfs_tgt *t;
887         struct dfs_cache_tgt_iterator *it, *nit;
888
889         memset(tl, 0, sizeof(*tl));
890         INIT_LIST_HEAD(head);
891
892         list_for_each_entry(t, &ce->tlist, list) {
893                 it = kzalloc(sizeof(*it), GFP_ATOMIC);
894                 if (!it) {
895                         rc = -ENOMEM;
896                         goto err_free_it;
897                 }
898
899                 it->it_name = kstrdup(t->name, GFP_ATOMIC);
900                 if (!it->it_name) {
901                         kfree(it);
902                         rc = -ENOMEM;
903                         goto err_free_it;
904                 }
905                 it->it_path_consumed = t->path_consumed;
906
907                 if (ce->tgthint == t)
908                         list_add(&it->it_list, head);
909                 else
910                         list_add_tail(&it->it_list, head);
911         }
912
913         tl->tl_numtgts = ce->numtgts;
914
915         return 0;
916
917 err_free_it:
918         list_for_each_entry_safe(it, nit, head, it_list) {
919                 list_del(&it->it_list);
920                 kfree(it->it_name);
921                 kfree(it);
922         }
923         return rc;
924 }
925
926 /**
927  * dfs_cache_find - find a DFS cache entry
928  *
929  * If it doesn't find the cache entry, then it will get a DFS referral
930  * for @path and create a new entry.
931  *
932  * In case the cache entry exists but expired, it will get a DFS referral
933  * for @path and then update the respective cache entry.
934  *
935  * These parameters are passed down to the get_dfs_refer() call if it
936  * needs to be issued:
937  * @xid: syscall xid
938  * @ses: smb session to issue the request on
939  * @cp: codepage
940  * @remap: path character remapping type
941  * @path: path to lookup in DFS referral cache.
942  *
943  * @ref: when non-NULL, store single DFS referral result in it.
944  * @tgt_list: when non-NULL, store complete DFS target list in it.
945  *
946  * Return zero if the target was found, otherwise non-zero.
947  */
948 int dfs_cache_find(const unsigned int xid, struct cifs_ses *ses, const struct nls_table *cp,
949                    int remap, const char *path, struct dfs_info3_param *ref,
950                    struct dfs_cache_tgt_list *tgt_list)
951 {
952         int rc;
953         const char *npath;
954         struct cache_entry *ce;
955
956         npath = dfs_cache_canonical_path(path, cp, remap);
957         if (IS_ERR(npath))
958                 return PTR_ERR(npath);
959
960         rc = cache_refresh_path(xid, ses, npath);
961         if (rc)
962                 goto out_free_path;
963
964         down_read(&htable_rw_lock);
965
966         ce = lookup_cache_entry(npath);
967         if (IS_ERR(ce)) {
968                 up_read(&htable_rw_lock);
969                 rc = PTR_ERR(ce);
970                 goto out_free_path;
971         }
972
973         if (ref)
974                 rc = setup_referral(path, ce, ref, get_tgt_name(ce));
975         else
976                 rc = 0;
977         if (!rc && tgt_list)
978                 rc = get_targets(ce, tgt_list);
979
980         up_read(&htable_rw_lock);
981
982 out_free_path:
983         kfree(npath);
984         return rc;
985 }
986
987 /**
988  * dfs_cache_noreq_find - find a DFS cache entry without sending any requests to
989  * the currently connected server.
990  *
991  * NOTE: This function will neither update a cache entry in case it was
992  * expired, nor create a new cache entry if @path hasn't been found. It heavily
993  * relies on an existing cache entry.
994  *
995  * @path: canonical DFS path to lookup in the DFS referral cache.
996  * @ref: when non-NULL, store single DFS referral result in it.
997  * @tgt_list: when non-NULL, store complete DFS target list in it.
998  *
999  * Return 0 if successful.
1000  * Return -ENOENT if the entry was not found.
1001  * Return non-zero for other errors.
1002  */
1003 int dfs_cache_noreq_find(const char *path, struct dfs_info3_param *ref,
1004                          struct dfs_cache_tgt_list *tgt_list)
1005 {
1006         int rc;
1007         struct cache_entry *ce;
1008
1009         cifs_dbg(FYI, "%s: path: %s\n", __func__, path);
1010
1011         down_read(&htable_rw_lock);
1012
1013         ce = lookup_cache_entry(path);
1014         if (IS_ERR(ce)) {
1015                 rc = PTR_ERR(ce);
1016                 goto out_unlock;
1017         }
1018
1019         if (ref)
1020                 rc = setup_referral(path, ce, ref, get_tgt_name(ce));
1021         else
1022                 rc = 0;
1023         if (!rc && tgt_list)
1024                 rc = get_targets(ce, tgt_list);
1025
1026 out_unlock:
1027         up_read(&htable_rw_lock);
1028         return rc;
1029 }
1030
1031 /**
1032  * dfs_cache_update_tgthint - update target hint of a DFS cache entry
1033  *
1034  * If it doesn't find the cache entry, then it will get a DFS referral for @path
1035  * and create a new entry.
1036  *
1037  * In case the cache entry exists but expired, it will get a DFS referral
1038  * for @path and then update the respective cache entry.
1039  *
1040  * @xid: syscall id
1041  * @ses: smb session
1042  * @cp: codepage
1043  * @remap: type of character remapping for paths
1044  * @path: path to lookup in DFS referral cache
1045  * @it: DFS target iterator
1046  *
1047  * Return zero if the target hint was updated successfully, otherwise non-zero.
1048  */
1049 int dfs_cache_update_tgthint(const unsigned int xid, struct cifs_ses *ses,
1050                              const struct nls_table *cp, int remap, const char *path,
1051                              const struct dfs_cache_tgt_iterator *it)
1052 {
1053         struct cache_dfs_tgt *t;
1054         struct cache_entry *ce;
1055         const char *npath;
1056         int rc = 0;
1057
1058         npath = dfs_cache_canonical_path(path, cp, remap);
1059         if (IS_ERR(npath))
1060                 return PTR_ERR(npath);
1061
1062         cifs_dbg(FYI, "%s: update target hint - path: %s\n", __func__, npath);
1063
1064         rc = cache_refresh_path(xid, ses, npath);
1065         if (rc)
1066                 goto out_free_path;
1067
1068         down_write(&htable_rw_lock);
1069
1070         ce = lookup_cache_entry(npath);
1071         if (IS_ERR(ce)) {
1072                 rc = PTR_ERR(ce);
1073                 goto out_unlock;
1074         }
1075
1076         t = ce->tgthint;
1077
1078         if (likely(!strcasecmp(it->it_name, t->name)))
1079                 goto out_unlock;
1080
1081         list_for_each_entry(t, &ce->tlist, list) {
1082                 if (!strcasecmp(t->name, it->it_name)) {
1083                         ce->tgthint = t;
1084                         cifs_dbg(FYI, "%s: new target hint: %s\n", __func__,
1085                                  it->it_name);
1086                         break;
1087                 }
1088         }
1089
1090 out_unlock:
1091         up_write(&htable_rw_lock);
1092 out_free_path:
1093         kfree(npath);
1094         return rc;
1095 }
1096
1097 /**
1098  * dfs_cache_noreq_update_tgthint - update target hint of a DFS cache entry
1099  * without sending any requests to the currently connected server.
1100  *
1101  * NOTE: This function will neither update a cache entry in case it was
1102  * expired, nor create a new cache entry if @path hasn't been found. It heavily
1103  * relies on an existing cache entry.
1104  *
1105  * @path: canonical DFS path to lookup in DFS referral cache.
1106  * @it: target iterator which contains the target hint to update the cache
1107  * entry with.
1108  *
1109  * Return zero if the target hint was updated successfully, otherwise non-zero.
1110  */
1111 int dfs_cache_noreq_update_tgthint(const char *path, const struct dfs_cache_tgt_iterator *it)
1112 {
1113         int rc;
1114         struct cache_entry *ce;
1115         struct cache_dfs_tgt *t;
1116
1117         if (!it)
1118                 return -EINVAL;
1119
1120         cifs_dbg(FYI, "%s: path: %s\n", __func__, path);
1121
1122         down_write(&htable_rw_lock);
1123
1124         ce = lookup_cache_entry(path);
1125         if (IS_ERR(ce)) {
1126                 rc = PTR_ERR(ce);
1127                 goto out_unlock;
1128         }
1129
1130         rc = 0;
1131         t = ce->tgthint;
1132
1133         if (unlikely(!strcasecmp(it->it_name, t->name)))
1134                 goto out_unlock;
1135
1136         list_for_each_entry(t, &ce->tlist, list) {
1137                 if (!strcasecmp(t->name, it->it_name)) {
1138                         ce->tgthint = t;
1139                         cifs_dbg(FYI, "%s: new target hint: %s\n", __func__,
1140                                  it->it_name);
1141                         break;
1142                 }
1143         }
1144
1145 out_unlock:
1146         up_write(&htable_rw_lock);
1147         return rc;
1148 }
1149
1150 /**
1151  * dfs_cache_get_tgt_referral - returns a DFS referral (@ref) from a given
1152  * target iterator (@it).
1153  *
1154  * @path: canonical DFS path to lookup in DFS referral cache.
1155  * @it: DFS target iterator.
1156  * @ref: DFS referral pointer to set up the gathered information.
1157  *
1158  * Return zero if the DFS referral was set up correctly, otherwise non-zero.
1159  */
1160 int dfs_cache_get_tgt_referral(const char *path, const struct dfs_cache_tgt_iterator *it,
1161                                struct dfs_info3_param *ref)
1162 {
1163         int rc;
1164         struct cache_entry *ce;
1165
1166         if (!it || !ref)
1167                 return -EINVAL;
1168
1169         cifs_dbg(FYI, "%s: path: %s\n", __func__, path);
1170
1171         down_read(&htable_rw_lock);
1172
1173         ce = lookup_cache_entry(path);
1174         if (IS_ERR(ce)) {
1175                 rc = PTR_ERR(ce);
1176                 goto out_unlock;
1177         }
1178
1179         cifs_dbg(FYI, "%s: target name: %s\n", __func__, it->it_name);
1180
1181         rc = setup_referral(path, ce, ref, it->it_name);
1182
1183 out_unlock:
1184         up_read(&htable_rw_lock);
1185         return rc;
1186 }
1187
1188 /**
1189  * dfs_cache_add_refsrv_session - add SMB session of referral server
1190  *
1191  * @mount_id: mount group uuid to lookup.
1192  * @ses: reference counted SMB session of referral server.
1193  */
1194 void dfs_cache_add_refsrv_session(const uuid_t *mount_id, struct cifs_ses *ses)
1195 {
1196         struct mount_group *mg;
1197
1198         if (WARN_ON_ONCE(!mount_id || uuid_is_null(mount_id) || !ses))
1199                 return;
1200
1201         mg = get_mount_group(mount_id);
1202         if (WARN_ON_ONCE(IS_ERR(mg)))
1203                 return;
1204
1205         spin_lock(&mg->lock);
1206         if (mg->num_sessions < ARRAY_SIZE(mg->sessions))
1207                 mg->sessions[mg->num_sessions++] = ses;
1208         spin_unlock(&mg->lock);
1209         kref_put(&mg->refcount, mount_group_release);
1210 }
1211
1212 /**
1213  * dfs_cache_put_refsrv_sessions - put all referral server sessions
1214  *
1215  * Put all SMB sessions from the given mount group id.
1216  *
1217  * @mount_id: mount group uuid to lookup.
1218  */
1219 void dfs_cache_put_refsrv_sessions(const uuid_t *mount_id)
1220 {
1221         struct mount_group *mg;
1222
1223         if (!mount_id || uuid_is_null(mount_id))
1224                 return;
1225
1226         mutex_lock(&mount_group_list_lock);
1227         mg = find_mount_group_locked(mount_id);
1228         if (IS_ERR(mg)) {
1229                 mutex_unlock(&mount_group_list_lock);
1230                 return;
1231         }
1232         mutex_unlock(&mount_group_list_lock);
1233         kref_put(&mg->refcount, mount_group_release);
1234 }
1235
1236 /**
1237  * dfs_cache_get_tgt_share - parse a DFS target
1238  *
1239  * @path: DFS full path
1240  * @it: DFS target iterator.
1241  * @share: tree name.
1242  * @prefix: prefix path.
1243  *
1244  * Return zero if target was parsed correctly, otherwise non-zero.
1245  */
1246 int dfs_cache_get_tgt_share(char *path, const struct dfs_cache_tgt_iterator *it, char **share,
1247                             char **prefix)
1248 {
1249         char *s, sep, *p;
1250         size_t len;
1251         size_t plen1, plen2;
1252
1253         if (!it || !path || !share || !prefix || strlen(path) < it->it_path_consumed)
1254                 return -EINVAL;
1255
1256         *share = NULL;
1257         *prefix = NULL;
1258
1259         sep = it->it_name[0];
1260         if (sep != '\\' && sep != '/')
1261                 return -EINVAL;
1262
1263         s = strchr(it->it_name + 1, sep);
1264         if (!s)
1265                 return -EINVAL;
1266
1267         /* point to prefix in target node */
1268         s = strchrnul(s + 1, sep);
1269
1270         /* extract target share */
1271         *share = kstrndup(it->it_name, s - it->it_name, GFP_KERNEL);
1272         if (!*share)
1273                 return -ENOMEM;
1274
1275         /* skip separator */
1276         if (*s)
1277                 s++;
1278         /* point to prefix in DFS path */
1279         p = path + it->it_path_consumed;
1280         if (*p == sep)
1281                 p++;
1282
1283         /* merge prefix paths from DFS path and target node */
1284         plen1 = it->it_name + strlen(it->it_name) - s;
1285         plen2 = path + strlen(path) - p;
1286         if (plen1 || plen2) {
1287                 len = plen1 + plen2 + 2;
1288                 *prefix = kmalloc(len, GFP_KERNEL);
1289                 if (!*prefix) {
1290                         kfree(*share);
1291                         *share = NULL;
1292                         return -ENOMEM;
1293                 }
1294                 if (plen1)
1295                         scnprintf(*prefix, len, "%.*s%c%.*s", (int)plen1, s, sep, (int)plen2, p);
1296                 else
1297                         strscpy(*prefix, p, len);
1298         }
1299         return 0;
1300 }
1301
1302 static bool target_share_equal(struct TCP_Server_Info *server, const char *s1, const char *s2)
1303 {
1304         char unc[sizeof("\\\\") + SERVER_NAME_LENGTH] = {0};
1305         const char *host;
1306         size_t hostlen;
1307         char *ip = NULL;
1308         struct sockaddr sa;
1309         bool match;
1310         int rc;
1311
1312         if (strcasecmp(s1, s2))
1313                 return false;
1314
1315         /*
1316          * Resolve share's hostname and check if server address matches.  Otherwise just ignore it
1317          * as we could not have upcall to resolve hostname or failed to convert ip address.
1318          */
1319         match = true;
1320         extract_unc_hostname(s1, &host, &hostlen);
1321         scnprintf(unc, sizeof(unc), "\\\\%.*s", (int)hostlen, host);
1322
1323         rc = dns_resolve_server_name_to_ip(unc, &ip, NULL);
1324         if (rc < 0) {
1325                 cifs_dbg(FYI, "%s: could not resolve %.*s. assuming server address matches.\n",
1326                          __func__, (int)hostlen, host);
1327                 return true;
1328         }
1329
1330         if (!cifs_convert_address(&sa, ip, strlen(ip))) {
1331                 cifs_dbg(VFS, "%s: failed to convert address \'%s\'. skip address matching.\n",
1332                          __func__, ip);
1333         } else {
1334                 mutex_lock(&server->srv_mutex);
1335                 match = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, &sa);
1336                 mutex_unlock(&server->srv_mutex);
1337         }
1338
1339         kfree(ip);
1340         return match;
1341 }
1342
1343 /*
1344  * Mark dfs tcon for reconnecting when the currently connected tcon does not match any of the new
1345  * target shares in @refs.
1346  */
1347 static void mark_for_reconnect_if_needed(struct cifs_tcon *tcon, struct dfs_cache_tgt_list *tl,
1348                                          const struct dfs_info3_param *refs, int numrefs)
1349 {
1350         struct dfs_cache_tgt_iterator *it;
1351         int i;
1352
1353         for (it = dfs_cache_get_tgt_iterator(tl); it; it = dfs_cache_get_next_tgt(tl, it)) {
1354                 for (i = 0; i < numrefs; i++) {
1355                         if (target_share_equal(tcon->ses->server, dfs_cache_get_tgt_name(it),
1356                                                refs[i].node_name))
1357                                 return;
1358                 }
1359         }
1360
1361         cifs_dbg(FYI, "%s: no cached or matched targets. mark dfs share for reconnect.\n", __func__);
1362         for (i = 0; i < tcon->ses->chan_count; i++) {
1363                 spin_lock(&GlobalMid_Lock);
1364                 if (tcon->ses->chans[i].server->tcpStatus != CifsExiting)
1365                         tcon->ses->chans[i].server->tcpStatus = CifsNeedReconnect;
1366                 spin_unlock(&GlobalMid_Lock);
1367         }
1368 }
1369
1370 /* Refresh dfs referral of tcon and mark it for reconnect if needed */
1371 static int __refresh_tcon(const char *path, struct cifs_ses **sessions, struct cifs_tcon *tcon,
1372                           bool force_refresh)
1373 {
1374         struct cifs_ses *ses;
1375         struct cache_entry *ce;
1376         struct dfs_info3_param *refs = NULL;
1377         int numrefs = 0;
1378         bool needs_refresh = false;
1379         struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
1380         int rc = 0;
1381         unsigned int xid;
1382
1383         ses = find_ipc_from_server_path(sessions, path);
1384         if (IS_ERR(ses)) {
1385                 cifs_dbg(FYI, "%s: could not find ipc session\n", __func__);
1386                 return PTR_ERR(ses);
1387         }
1388
1389         down_read(&htable_rw_lock);
1390         ce = lookup_cache_entry(path);
1391         needs_refresh = force_refresh || IS_ERR(ce) || cache_entry_expired(ce);
1392         if (!IS_ERR(ce)) {
1393                 rc = get_targets(ce, &tl);
1394                 if (rc)
1395                         cifs_dbg(FYI, "%s: could not get dfs targets: %d\n", __func__, rc);
1396         }
1397         up_read(&htable_rw_lock);
1398
1399         if (!needs_refresh) {
1400                 rc = 0;
1401                 goto out;
1402         }
1403
1404         xid = get_xid();
1405         rc = get_dfs_referral(xid, ses, path, &refs, &numrefs);
1406         free_xid(xid);
1407
1408         /* Create or update a cache entry with the new referral */
1409         if (!rc) {
1410                 dump_refs(refs, numrefs);
1411
1412                 down_write(&htable_rw_lock);
1413                 ce = lookup_cache_entry(path);
1414                 if (IS_ERR(ce))
1415                         add_cache_entry_locked(refs, numrefs);
1416                 else if (force_refresh || cache_entry_expired(ce))
1417                         update_cache_entry_locked(ce, refs, numrefs);
1418                 up_write(&htable_rw_lock);
1419
1420                 mark_for_reconnect_if_needed(tcon, &tl, refs, numrefs);
1421         }
1422
1423 out:
1424         dfs_cache_free_tgts(&tl);
1425         free_dfs_info_array(refs, numrefs);
1426         return rc;
1427 }
1428
1429 static int refresh_tcon(struct cifs_ses **sessions, struct cifs_tcon *tcon, bool force_refresh)
1430 {
1431         struct TCP_Server_Info *server = tcon->ses->server;
1432
1433         mutex_lock(&server->refpath_lock);
1434         if (strcasecmp(server->leaf_fullpath, server->origin_fullpath))
1435                 __refresh_tcon(server->leaf_fullpath + 1, sessions, tcon, force_refresh);
1436         mutex_unlock(&server->refpath_lock);
1437
1438         __refresh_tcon(server->origin_fullpath + 1, sessions, tcon, force_refresh);
1439
1440         return 0;
1441 }
1442
1443 /**
1444  * dfs_cache_remount_fs - remount a DFS share
1445  *
1446  * Reconfigure dfs mount by forcing a new DFS referral and if the currently cached targets do not
1447  * match any of the new targets, mark it for reconnect.
1448  *
1449  * @cifs_sb: cifs superblock.
1450  *
1451  * Return zero if remounted, otherwise non-zero.
1452  */
1453 int dfs_cache_remount_fs(struct cifs_sb_info *cifs_sb)
1454 {
1455         struct cifs_tcon *tcon;
1456         struct TCP_Server_Info *server;
1457         struct mount_group *mg;
1458         struct cifs_ses *sessions[CACHE_MAX_ENTRIES + 1] = {NULL};
1459         int rc;
1460
1461         if (!cifs_sb || !cifs_sb->master_tlink)
1462                 return -EINVAL;
1463
1464         tcon = cifs_sb_master_tcon(cifs_sb);
1465         server = tcon->ses->server;
1466
1467         if (!server->origin_fullpath) {
1468                 cifs_dbg(FYI, "%s: not a dfs mount\n", __func__);
1469                 return 0;
1470         }
1471
1472         if (uuid_is_null(&cifs_sb->dfs_mount_id)) {
1473                 cifs_dbg(FYI, "%s: no dfs mount group id\n", __func__);
1474                 return -EINVAL;
1475         }
1476
1477         mutex_lock(&mount_group_list_lock);
1478         mg = find_mount_group_locked(&cifs_sb->dfs_mount_id);
1479         if (IS_ERR(mg)) {
1480                 mutex_unlock(&mount_group_list_lock);
1481                 cifs_dbg(FYI, "%s: no ipc session for refreshing referral\n", __func__);
1482                 return PTR_ERR(mg);
1483         }
1484         kref_get(&mg->refcount);
1485         mutex_unlock(&mount_group_list_lock);
1486
1487         spin_lock(&mg->lock);
1488         memcpy(&sessions, mg->sessions, mg->num_sessions * sizeof(mg->sessions[0]));
1489         spin_unlock(&mg->lock);
1490
1491         /*
1492          * After reconnecting to a different server, unique ids won't match anymore, so we disable
1493          * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
1494          */
1495         cifs_autodisable_serverino(cifs_sb);
1496         /*
1497          * Force the use of prefix path to support failover on DFS paths that resolve to targets
1498          * that have different prefix paths.
1499          */
1500         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1501         rc = refresh_tcon(sessions, tcon, true);
1502
1503         kref_put(&mg->refcount, mount_group_release);
1504         return rc;
1505 }
1506
1507 /*
1508  * Refresh all active dfs mounts regardless of whether they are in cache or not.
1509  * (cache can be cleared)
1510  */
1511 static void refresh_mounts(struct cifs_ses **sessions)
1512 {
1513         struct TCP_Server_Info *server;
1514         struct cifs_ses *ses;
1515         struct cifs_tcon *tcon, *ntcon;
1516         struct list_head tcons;
1517
1518         INIT_LIST_HEAD(&tcons);
1519
1520         spin_lock(&cifs_tcp_ses_lock);
1521         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1522                 if (!server->is_dfs_conn)
1523                         continue;
1524
1525                 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1526                         list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
1527                                 if (!tcon->ipc && !tcon->need_reconnect) {
1528                                         tcon->tc_count++;
1529                                         list_add_tail(&tcon->ulist, &tcons);
1530                                 }
1531                         }
1532                 }
1533         }
1534         spin_unlock(&cifs_tcp_ses_lock);
1535
1536         list_for_each_entry_safe(tcon, ntcon, &tcons, ulist) {
1537                 struct TCP_Server_Info *server = tcon->ses->server;
1538
1539                 list_del_init(&tcon->ulist);
1540
1541                 mutex_lock(&server->refpath_lock);
1542                 if (strcasecmp(server->leaf_fullpath, server->origin_fullpath))
1543                         __refresh_tcon(server->leaf_fullpath + 1, sessions, tcon, false);
1544                 mutex_unlock(&server->refpath_lock);
1545
1546                 __refresh_tcon(server->origin_fullpath + 1, sessions, tcon, false);
1547                 cifs_put_tcon(tcon);
1548         }
1549 }
1550
1551 static void refresh_cache(struct cifs_ses **sessions)
1552 {
1553         int i;
1554         struct cifs_ses *ses;
1555         unsigned int xid;
1556         char *ref_paths[CACHE_MAX_ENTRIES];
1557         int count = 0;
1558         struct cache_entry *ce;
1559
1560         /*
1561          * Refresh all cached entries.  Get all new referrals outside critical section to avoid
1562          * starvation while performing SMB2 IOCTL on broken or slow connections.
1563
1564          * The cache entries may cover more paths than the active mounts
1565          * (e.g. domain-based DFS referrals or multi tier DFS setups).
1566          */
1567         down_read(&htable_rw_lock);
1568         for (i = 0; i < CACHE_HTABLE_SIZE; i++) {
1569                 struct hlist_head *l = &cache_htable[i];
1570
1571                 hlist_for_each_entry(ce, l, hlist) {
1572                         if (count == ARRAY_SIZE(ref_paths))
1573                                 goto out_unlock;
1574                         if (hlist_unhashed(&ce->hlist) || !cache_entry_expired(ce) ||
1575                             IS_ERR(find_ipc_from_server_path(sessions, ce->path)))
1576                                 continue;
1577                         ref_paths[count++] = kstrdup(ce->path, GFP_ATOMIC);
1578                 }
1579         }
1580
1581 out_unlock:
1582         up_read(&htable_rw_lock);
1583
1584         for (i = 0; i < count; i++) {
1585                 char *path = ref_paths[i];
1586                 struct dfs_info3_param *refs = NULL;
1587                 int numrefs = 0;
1588                 int rc = 0;
1589
1590                 if (!path)
1591                         continue;
1592
1593                 ses = find_ipc_from_server_path(sessions, path);
1594                 if (IS_ERR(ses))
1595                         goto next_referral;
1596
1597                 xid = get_xid();
1598                 rc = get_dfs_referral(xid, ses, path, &refs, &numrefs);
1599                 free_xid(xid);
1600
1601                 if (!rc) {
1602                         down_write(&htable_rw_lock);
1603                         ce = lookup_cache_entry(path);
1604                         /*
1605                          * We need to re-check it because other tasks might have it deleted or
1606                          * updated.
1607                          */
1608                         if (!IS_ERR(ce) && cache_entry_expired(ce))
1609                                 update_cache_entry_locked(ce, refs, numrefs);
1610                         up_write(&htable_rw_lock);
1611                 }
1612
1613 next_referral:
1614                 kfree(path);
1615                 free_dfs_info_array(refs, numrefs);
1616         }
1617 }
1618
1619 /*
1620  * Worker that will refresh DFS cache and active mounts based on lowest TTL value from a DFS
1621  * referral.
1622  */
1623 static void refresh_cache_worker(struct work_struct *work)
1624 {
1625         struct list_head mglist;
1626         struct mount_group *mg, *tmp_mg;
1627         struct cifs_ses *sessions[CACHE_MAX_ENTRIES + 1] = {NULL};
1628         int max_sessions = ARRAY_SIZE(sessions) - 1;
1629         int i = 0, count;
1630
1631         INIT_LIST_HEAD(&mglist);
1632
1633         /* Get refereces of mount groups */
1634         mutex_lock(&mount_group_list_lock);
1635         list_for_each_entry(mg, &mount_group_list, list) {
1636                 kref_get(&mg->refcount);
1637                 list_add(&mg->refresh_list, &mglist);
1638         }
1639         mutex_unlock(&mount_group_list_lock);
1640
1641         /* Fill in local array with an NULL-terminated list of all referral server sessions */
1642         list_for_each_entry(mg, &mglist, refresh_list) {
1643                 if (i >= max_sessions)
1644                         break;
1645
1646                 spin_lock(&mg->lock);
1647                 if (i + mg->num_sessions > max_sessions)
1648                         count = max_sessions - i;
1649                 else
1650                         count = mg->num_sessions;
1651                 memcpy(&sessions[i], mg->sessions, count * sizeof(mg->sessions[0]));
1652                 spin_unlock(&mg->lock);
1653                 i += count;
1654         }
1655
1656         if (sessions[0]) {
1657                 /* Refresh all active mounts and cached entries */
1658                 refresh_mounts(sessions);
1659                 refresh_cache(sessions);
1660         }
1661
1662         list_for_each_entry_safe(mg, tmp_mg, &mglist, refresh_list) {
1663                 list_del_init(&mg->refresh_list);
1664                 kref_put(&mg->refcount, mount_group_release);
1665         }
1666
1667         spin_lock(&cache_ttl_lock);
1668         queue_delayed_work(dfscache_wq, &refresh_task, cache_ttl * HZ);
1669         spin_unlock(&cache_ttl_lock);
1670 }