Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / fs / cifs / connect.c
1 /*
2  *   fs/cifs/connect.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2011
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  *   This library is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU Lesser General Public License as published
9  *   by the Free Software Foundation; either version 2.1 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This library is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
15  *   the GNU Lesser General Public License for more details.
16  *
17  *   You should have received a copy of the GNU Lesser General Public License
18  *   along with this library; if not, write to the Free Software
19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */
21 #include <linux/fs.h>
22 #include <linux/net.h>
23 #include <linux/string.h>
24 #include <linux/sched/signal.h>
25 #include <linux/list.h>
26 #include <linux/wait.h>
27 #include <linux/slab.h>
28 #include <linux/pagemap.h>
29 #include <linux/ctype.h>
30 #include <linux/utsname.h>
31 #include <linux/mempool.h>
32 #include <linux/delay.h>
33 #include <linux/completion.h>
34 #include <linux/kthread.h>
35 #include <linux/pagevec.h>
36 #include <linux/freezer.h>
37 #include <linux/namei.h>
38 #include <linux/uuid.h>
39 #include <linux/uaccess.h>
40 #include <asm/processor.h>
41 #include <linux/inet.h>
42 #include <linux/module.h>
43 #include <keys/user-type.h>
44 #include <net/ipv6.h>
45 #include <linux/parser.h>
46 #include <linux/bvec.h>
47 #include "cifspdu.h"
48 #include "cifsglob.h"
49 #include "cifsproto.h"
50 #include "cifs_unicode.h"
51 #include "cifs_debug.h"
52 #include "cifs_fs_sb.h"
53 #include "ntlmssp.h"
54 #include "nterr.h"
55 #include "rfc1002pdu.h"
56 #include "fscache.h"
57 #include "smb2proto.h"
58 #include "smbdirect.h"
59 #include "dns_resolve.h"
60 #include "cifsfs.h"
61 #ifdef CONFIG_CIFS_DFS_UPCALL
62 #include "dfs_cache.h"
63 #endif
64
65 extern mempool_t *cifs_req_poolp;
66 extern bool disable_legacy_dialects;
67
68 /* FIXME: should these be tunable? */
69 #define TLINK_ERROR_EXPIRE      (1 * HZ)
70 #define TLINK_IDLE_EXPIRE       (600 * HZ)
71
72 enum {
73         /* Mount options that take no arguments */
74         Opt_user_xattr, Opt_nouser_xattr,
75         Opt_forceuid, Opt_noforceuid,
76         Opt_forcegid, Opt_noforcegid,
77         Opt_noblocksend, Opt_noautotune, Opt_nolease,
78         Opt_hard, Opt_soft, Opt_perm, Opt_noperm,
79         Opt_mapposix, Opt_nomapposix,
80         Opt_mapchars, Opt_nomapchars, Opt_sfu,
81         Opt_nosfu, Opt_nodfs, Opt_posixpaths,
82         Opt_noposixpaths, Opt_nounix, Opt_unix,
83         Opt_nocase,
84         Opt_brl, Opt_nobrl,
85         Opt_handlecache, Opt_nohandlecache,
86         Opt_forcemandatorylock, Opt_setuidfromacl, Opt_setuids,
87         Opt_nosetuids, Opt_dynperm, Opt_nodynperm,
88         Opt_nohard, Opt_nosoft,
89         Opt_nointr, Opt_intr,
90         Opt_nostrictsync, Opt_strictsync,
91         Opt_serverino, Opt_noserverino,
92         Opt_rwpidforward, Opt_cifsacl, Opt_nocifsacl,
93         Opt_acl, Opt_noacl, Opt_locallease,
94         Opt_sign, Opt_seal, Opt_noac,
95         Opt_fsc, Opt_mfsymlinks,
96         Opt_multiuser, Opt_sloppy, Opt_nosharesock,
97         Opt_persistent, Opt_nopersistent,
98         Opt_resilient, Opt_noresilient,
99         Opt_domainauto, Opt_rdma, Opt_modesid,
100         Opt_compress,
101
102         /* Mount options which take numeric value */
103         Opt_backupuid, Opt_backupgid, Opt_uid,
104         Opt_cruid, Opt_gid, Opt_file_mode,
105         Opt_dirmode, Opt_port,
106         Opt_blocksize, Opt_rsize, Opt_wsize, Opt_actimeo,
107         Opt_echo_interval, Opt_max_credits, Opt_handletimeout,
108         Opt_snapshot,
109
110         /* Mount options which take string value */
111         Opt_user, Opt_pass, Opt_ip,
112         Opt_domain, Opt_srcaddr, Opt_iocharset,
113         Opt_netbiosname, Opt_servern,
114         Opt_ver, Opt_vers, Opt_sec, Opt_cache,
115
116         /* Mount options to be ignored */
117         Opt_ignore,
118
119         /* Options which could be blank */
120         Opt_blank_pass,
121         Opt_blank_user,
122         Opt_blank_ip,
123
124         Opt_err
125 };
126
127 static const match_table_t cifs_mount_option_tokens = {
128
129         { Opt_user_xattr, "user_xattr" },
130         { Opt_nouser_xattr, "nouser_xattr" },
131         { Opt_forceuid, "forceuid" },
132         { Opt_noforceuid, "noforceuid" },
133         { Opt_forcegid, "forcegid" },
134         { Opt_noforcegid, "noforcegid" },
135         { Opt_noblocksend, "noblocksend" },
136         { Opt_noautotune, "noautotune" },
137         { Opt_nolease, "nolease" },
138         { Opt_hard, "hard" },
139         { Opt_soft, "soft" },
140         { Opt_perm, "perm" },
141         { Opt_noperm, "noperm" },
142         { Opt_mapchars, "mapchars" }, /* SFU style */
143         { Opt_nomapchars, "nomapchars" },
144         { Opt_mapposix, "mapposix" }, /* SFM style */
145         { Opt_nomapposix, "nomapposix" },
146         { Opt_sfu, "sfu" },
147         { Opt_nosfu, "nosfu" },
148         { Opt_nodfs, "nodfs" },
149         { Opt_posixpaths, "posixpaths" },
150         { Opt_noposixpaths, "noposixpaths" },
151         { Opt_nounix, "nounix" },
152         { Opt_nounix, "nolinux" },
153         { Opt_nounix, "noposix" },
154         { Opt_unix, "unix" },
155         { Opt_unix, "linux" },
156         { Opt_unix, "posix" },
157         { Opt_nocase, "nocase" },
158         { Opt_nocase, "ignorecase" },
159         { Opt_brl, "brl" },
160         { Opt_nobrl, "nobrl" },
161         { Opt_handlecache, "handlecache" },
162         { Opt_nohandlecache, "nohandlecache" },
163         { Opt_nobrl, "nolock" },
164         { Opt_forcemandatorylock, "forcemandatorylock" },
165         { Opt_forcemandatorylock, "forcemand" },
166         { Opt_setuids, "setuids" },
167         { Opt_nosetuids, "nosetuids" },
168         { Opt_setuidfromacl, "idsfromsid" },
169         { Opt_dynperm, "dynperm" },
170         { Opt_nodynperm, "nodynperm" },
171         { Opt_nohard, "nohard" },
172         { Opt_nosoft, "nosoft" },
173         { Opt_nointr, "nointr" },
174         { Opt_intr, "intr" },
175         { Opt_nostrictsync, "nostrictsync" },
176         { Opt_strictsync, "strictsync" },
177         { Opt_serverino, "serverino" },
178         { Opt_noserverino, "noserverino" },
179         { Opt_rwpidforward, "rwpidforward" },
180         { Opt_modesid, "modefromsid" },
181         { Opt_cifsacl, "cifsacl" },
182         { Opt_nocifsacl, "nocifsacl" },
183         { Opt_acl, "acl" },
184         { Opt_noacl, "noacl" },
185         { Opt_locallease, "locallease" },
186         { Opt_sign, "sign" },
187         { Opt_seal, "seal" },
188         { Opt_noac, "noac" },
189         { Opt_fsc, "fsc" },
190         { Opt_mfsymlinks, "mfsymlinks" },
191         { Opt_multiuser, "multiuser" },
192         { Opt_sloppy, "sloppy" },
193         { Opt_nosharesock, "nosharesock" },
194         { Opt_persistent, "persistenthandles"},
195         { Opt_nopersistent, "nopersistenthandles"},
196         { Opt_resilient, "resilienthandles"},
197         { Opt_noresilient, "noresilienthandles"},
198         { Opt_domainauto, "domainauto"},
199         { Opt_rdma, "rdma"},
200
201         { Opt_backupuid, "backupuid=%s" },
202         { Opt_backupgid, "backupgid=%s" },
203         { Opt_uid, "uid=%s" },
204         { Opt_cruid, "cruid=%s" },
205         { Opt_gid, "gid=%s" },
206         { Opt_file_mode, "file_mode=%s" },
207         { Opt_dirmode, "dirmode=%s" },
208         { Opt_dirmode, "dir_mode=%s" },
209         { Opt_port, "port=%s" },
210         { Opt_blocksize, "bsize=%s" },
211         { Opt_rsize, "rsize=%s" },
212         { Opt_wsize, "wsize=%s" },
213         { Opt_actimeo, "actimeo=%s" },
214         { Opt_handletimeout, "handletimeout=%s" },
215         { Opt_echo_interval, "echo_interval=%s" },
216         { Opt_max_credits, "max_credits=%s" },
217         { Opt_snapshot, "snapshot=%s" },
218         { Opt_compress, "compress=%s" },
219
220         { Opt_blank_user, "user=" },
221         { Opt_blank_user, "username=" },
222         { Opt_user, "user=%s" },
223         { Opt_user, "username=%s" },
224         { Opt_blank_pass, "pass=" },
225         { Opt_blank_pass, "password=" },
226         { Opt_pass, "pass=%s" },
227         { Opt_pass, "password=%s" },
228         { Opt_blank_ip, "ip=" },
229         { Opt_blank_ip, "addr=" },
230         { Opt_ip, "ip=%s" },
231         { Opt_ip, "addr=%s" },
232         { Opt_ignore, "unc=%s" },
233         { Opt_ignore, "target=%s" },
234         { Opt_ignore, "path=%s" },
235         { Opt_domain, "dom=%s" },
236         { Opt_domain, "domain=%s" },
237         { Opt_domain, "workgroup=%s" },
238         { Opt_srcaddr, "srcaddr=%s" },
239         { Opt_ignore, "prefixpath=%s" },
240         { Opt_iocharset, "iocharset=%s" },
241         { Opt_netbiosname, "netbiosname=%s" },
242         { Opt_servern, "servern=%s" },
243         { Opt_ver, "ver=%s" },
244         { Opt_vers, "vers=%s" },
245         { Opt_sec, "sec=%s" },
246         { Opt_cache, "cache=%s" },
247
248         { Opt_ignore, "cred" },
249         { Opt_ignore, "credentials" },
250         { Opt_ignore, "cred=%s" },
251         { Opt_ignore, "credentials=%s" },
252         { Opt_ignore, "guest" },
253         { Opt_ignore, "rw" },
254         { Opt_ignore, "ro" },
255         { Opt_ignore, "suid" },
256         { Opt_ignore, "nosuid" },
257         { Opt_ignore, "exec" },
258         { Opt_ignore, "noexec" },
259         { Opt_ignore, "nodev" },
260         { Opt_ignore, "noauto" },
261         { Opt_ignore, "dev" },
262         { Opt_ignore, "mand" },
263         { Opt_ignore, "nomand" },
264         { Opt_ignore, "relatime" },
265         { Opt_ignore, "_netdev" },
266
267         { Opt_err, NULL }
268 };
269
270 enum {
271         Opt_sec_krb5, Opt_sec_krb5i, Opt_sec_krb5p,
272         Opt_sec_ntlmsspi, Opt_sec_ntlmssp,
273         Opt_ntlm, Opt_sec_ntlmi, Opt_sec_ntlmv2,
274         Opt_sec_ntlmv2i, Opt_sec_lanman,
275         Opt_sec_none,
276
277         Opt_sec_err
278 };
279
280 static const match_table_t cifs_secflavor_tokens = {
281         { Opt_sec_krb5, "krb5" },
282         { Opt_sec_krb5i, "krb5i" },
283         { Opt_sec_krb5p, "krb5p" },
284         { Opt_sec_ntlmsspi, "ntlmsspi" },
285         { Opt_sec_ntlmssp, "ntlmssp" },
286         { Opt_ntlm, "ntlm" },
287         { Opt_sec_ntlmi, "ntlmi" },
288         { Opt_sec_ntlmv2, "nontlm" },
289         { Opt_sec_ntlmv2, "ntlmv2" },
290         { Opt_sec_ntlmv2i, "ntlmv2i" },
291         { Opt_sec_lanman, "lanman" },
292         { Opt_sec_none, "none" },
293
294         { Opt_sec_err, NULL }
295 };
296
297 /* cache flavors */
298 enum {
299         Opt_cache_loose,
300         Opt_cache_strict,
301         Opt_cache_none,
302         Opt_cache_err
303 };
304
305 static const match_table_t cifs_cacheflavor_tokens = {
306         { Opt_cache_loose, "loose" },
307         { Opt_cache_strict, "strict" },
308         { Opt_cache_none, "none" },
309         { Opt_cache_err, NULL }
310 };
311
312 static const match_table_t cifs_smb_version_tokens = {
313         { Smb_1, SMB1_VERSION_STRING },
314         { Smb_20, SMB20_VERSION_STRING},
315         { Smb_21, SMB21_VERSION_STRING },
316         { Smb_30, SMB30_VERSION_STRING },
317         { Smb_302, SMB302_VERSION_STRING },
318         { Smb_302, ALT_SMB302_VERSION_STRING },
319         { Smb_311, SMB311_VERSION_STRING },
320         { Smb_311, ALT_SMB311_VERSION_STRING },
321         { Smb_3any, SMB3ANY_VERSION_STRING },
322         { Smb_default, SMBDEFAULT_VERSION_STRING },
323         { Smb_version_err, NULL }
324 };
325
326 static int ip_connect(struct TCP_Server_Info *server);
327 static int generic_ip_connect(struct TCP_Server_Info *server);
328 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
329 static void cifs_prune_tlinks(struct work_struct *work);
330 static char *extract_hostname(const char *unc);
331
332 /*
333  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
334  * get their ip addresses changed at some point.
335  *
336  * This should be called with server->srv_mutex held.
337  */
338 #ifdef CONFIG_CIFS_DFS_UPCALL
339 static int reconn_set_ipaddr(struct TCP_Server_Info *server)
340 {
341         int rc;
342         int len;
343         char *unc, *ipaddr = NULL;
344
345         if (!server->hostname)
346                 return -EINVAL;
347
348         len = strlen(server->hostname) + 3;
349
350         unc = kmalloc(len, GFP_KERNEL);
351         if (!unc) {
352                 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
353                 return -ENOMEM;
354         }
355         scnprintf(unc, len, "\\\\%s", server->hostname);
356
357         rc = dns_resolve_server_name_to_ip(unc, &ipaddr);
358         kfree(unc);
359
360         if (rc < 0) {
361                 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
362                          __func__, server->hostname, rc);
363                 return rc;
364         }
365
366         rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
367                                   strlen(ipaddr));
368         kfree(ipaddr);
369
370         return !rc ? -1 : 0;
371 }
372 #else
373 static inline int reconn_set_ipaddr(struct TCP_Server_Info *server)
374 {
375         return 0;
376 }
377 #endif
378
379 #ifdef CONFIG_CIFS_DFS_UPCALL
380 struct super_cb_data {
381         struct TCP_Server_Info *server;
382         struct cifs_sb_info *cifs_sb;
383 };
384
385 /* These functions must be called with server->srv_mutex held */
386
387 static void super_cb(struct super_block *sb, void *arg)
388 {
389         struct super_cb_data *d = arg;
390         struct cifs_sb_info *cifs_sb;
391         struct cifs_tcon *tcon;
392
393         if (d->cifs_sb)
394                 return;
395
396         cifs_sb = CIFS_SB(sb);
397         tcon = cifs_sb_master_tcon(cifs_sb);
398         if (tcon->ses->server == d->server)
399                 d->cifs_sb = cifs_sb;
400 }
401
402 static inline struct cifs_sb_info *
403 find_super_by_tcp(struct TCP_Server_Info *server)
404 {
405         struct super_cb_data d = {
406                 .server = server,
407                 .cifs_sb = NULL,
408         };
409
410         iterate_supers_type(&cifs_fs_type, super_cb, &d);
411         return d.cifs_sb ? d.cifs_sb : ERR_PTR(-ENOENT);
412 }
413
414 static void reconn_inval_dfs_target(struct TCP_Server_Info *server,
415                                     struct cifs_sb_info *cifs_sb,
416                                     struct dfs_cache_tgt_list *tgt_list,
417                                     struct dfs_cache_tgt_iterator **tgt_it)
418 {
419         const char *name;
420
421         if (!cifs_sb || !cifs_sb->origin_fullpath || !tgt_list ||
422             !server->nr_targets)
423                 return;
424
425         if (!*tgt_it) {
426                 *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
427         } else {
428                 *tgt_it = dfs_cache_get_next_tgt(tgt_list, *tgt_it);
429                 if (!*tgt_it)
430                         *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
431         }
432
433         cifs_dbg(FYI, "%s: UNC: %s\n", __func__, cifs_sb->origin_fullpath);
434
435         name = dfs_cache_get_tgt_name(*tgt_it);
436
437         kfree(server->hostname);
438
439         server->hostname = extract_hostname(name);
440         if (IS_ERR(server->hostname)) {
441                 cifs_dbg(FYI,
442                          "%s: failed to extract hostname from target: %ld\n",
443                          __func__, PTR_ERR(server->hostname));
444         }
445 }
446
447 static inline int reconn_setup_dfs_targets(struct cifs_sb_info *cifs_sb,
448                                            struct dfs_cache_tgt_list *tl,
449                                            struct dfs_cache_tgt_iterator **it)
450 {
451         if (!cifs_sb->origin_fullpath)
452                 return -EOPNOTSUPP;
453         return dfs_cache_noreq_find(cifs_sb->origin_fullpath + 1, NULL, tl);
454 }
455 #endif
456
457 /*
458  * cifs tcp session reconnection
459  *
460  * mark tcp session as reconnecting so temporarily locked
461  * mark all smb sessions as reconnecting for tcp session
462  * reconnect tcp session
463  * wake up waiters on reconnection? - (not needed currently)
464  */
465 int
466 cifs_reconnect(struct TCP_Server_Info *server)
467 {
468         int rc = 0;
469         struct list_head *tmp, *tmp2;
470         struct cifs_ses *ses;
471         struct cifs_tcon *tcon;
472         struct mid_q_entry *mid_entry;
473         struct list_head retry_list;
474 #ifdef CONFIG_CIFS_DFS_UPCALL
475         struct cifs_sb_info *cifs_sb = NULL;
476         struct dfs_cache_tgt_list tgt_list = {0};
477         struct dfs_cache_tgt_iterator *tgt_it = NULL;
478 #endif
479
480         spin_lock(&GlobalMid_Lock);
481         server->nr_targets = 1;
482 #ifdef CONFIG_CIFS_DFS_UPCALL
483         spin_unlock(&GlobalMid_Lock);
484         cifs_sb = find_super_by_tcp(server);
485         if (IS_ERR(cifs_sb)) {
486                 rc = PTR_ERR(cifs_sb);
487                 cifs_dbg(FYI, "%s: will not do DFS failover: rc = %d\n",
488                          __func__, rc);
489                 cifs_sb = NULL;
490         } else {
491                 rc = reconn_setup_dfs_targets(cifs_sb, &tgt_list, &tgt_it);
492                 if (rc && (rc != -EOPNOTSUPP)) {
493                         cifs_dbg(VFS, "%s: no target servers for DFS failover\n",
494                                  __func__);
495                 } else {
496                         server->nr_targets = dfs_cache_get_nr_tgts(&tgt_list);
497                 }
498         }
499         cifs_dbg(FYI, "%s: will retry %d target(s)\n", __func__,
500                  server->nr_targets);
501         spin_lock(&GlobalMid_Lock);
502 #endif
503         if (server->tcpStatus == CifsExiting) {
504                 /* the demux thread will exit normally
505                 next time through the loop */
506                 spin_unlock(&GlobalMid_Lock);
507                 return rc;
508         } else
509                 server->tcpStatus = CifsNeedReconnect;
510         spin_unlock(&GlobalMid_Lock);
511         server->maxBuf = 0;
512         server->max_read = 0;
513
514         cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
515         trace_smb3_reconnect(server->CurrentMid, server->hostname);
516
517         /* before reconnecting the tcp session, mark the smb session (uid)
518                 and the tid bad so they are not used until reconnected */
519         cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n",
520                  __func__);
521         spin_lock(&cifs_tcp_ses_lock);
522         list_for_each(tmp, &server->smb_ses_list) {
523                 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
524                 ses->need_reconnect = true;
525                 list_for_each(tmp2, &ses->tcon_list) {
526                         tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
527                         tcon->need_reconnect = true;
528                 }
529                 if (ses->tcon_ipc)
530                         ses->tcon_ipc->need_reconnect = true;
531         }
532         spin_unlock(&cifs_tcp_ses_lock);
533
534         /* do not want to be sending data on a socket we are freeing */
535         cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
536         mutex_lock(&server->srv_mutex);
537         if (server->ssocket) {
538                 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n",
539                          server->ssocket->state, server->ssocket->flags);
540                 kernel_sock_shutdown(server->ssocket, SHUT_WR);
541                 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n",
542                          server->ssocket->state, server->ssocket->flags);
543                 sock_release(server->ssocket);
544                 server->ssocket = NULL;
545         }
546         server->sequence_number = 0;
547         server->session_estab = false;
548         kfree(server->session_key.response);
549         server->session_key.response = NULL;
550         server->session_key.len = 0;
551         server->lstrp = jiffies;
552
553         /* mark submitted MIDs for retry and issue callback */
554         INIT_LIST_HEAD(&retry_list);
555         cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
556         spin_lock(&GlobalMid_Lock);
557         list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
558                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
559                 kref_get(&mid_entry->refcount);
560                 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
561                         mid_entry->mid_state = MID_RETRY_NEEDED;
562                 list_move(&mid_entry->qhead, &retry_list);
563                 mid_entry->mid_flags |= MID_DELETED;
564         }
565         spin_unlock(&GlobalMid_Lock);
566         mutex_unlock(&server->srv_mutex);
567
568         cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
569         list_for_each_safe(tmp, tmp2, &retry_list) {
570                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
571                 list_del_init(&mid_entry->qhead);
572                 mid_entry->callback(mid_entry);
573                 cifs_mid_q_entry_release(mid_entry);
574         }
575
576         if (cifs_rdma_enabled(server)) {
577                 mutex_lock(&server->srv_mutex);
578                 smbd_destroy(server);
579                 mutex_unlock(&server->srv_mutex);
580         }
581
582         do {
583                 try_to_freeze();
584
585                 mutex_lock(&server->srv_mutex);
586                 /*
587                  * Set up next DFS target server (if any) for reconnect. If DFS
588                  * feature is disabled, then we will retry last server we
589                  * connected to before.
590                  */
591                 if (cifs_rdma_enabled(server))
592                         rc = smbd_reconnect(server);
593                 else
594                         rc = generic_ip_connect(server);
595                 if (rc) {
596                         cifs_dbg(FYI, "reconnect error %d\n", rc);
597 #ifdef CONFIG_CIFS_DFS_UPCALL
598                         reconn_inval_dfs_target(server, cifs_sb, &tgt_list,
599                                                 &tgt_it);
600 #endif
601                         rc = reconn_set_ipaddr(server);
602                         if (rc) {
603                                 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
604                                          __func__, rc);
605                         }
606                         mutex_unlock(&server->srv_mutex);
607                         msleep(3000);
608                 } else {
609                         atomic_inc(&tcpSesReconnectCount);
610                         set_credits(server, 1);
611                         spin_lock(&GlobalMid_Lock);
612                         if (server->tcpStatus != CifsExiting)
613                                 server->tcpStatus = CifsNeedNegotiate;
614                         spin_unlock(&GlobalMid_Lock);
615                         mutex_unlock(&server->srv_mutex);
616                 }
617         } while (server->tcpStatus == CifsNeedReconnect);
618
619 #ifdef CONFIG_CIFS_DFS_UPCALL
620         if (tgt_it) {
621                 rc = dfs_cache_noreq_update_tgthint(cifs_sb->origin_fullpath + 1,
622                                                     tgt_it);
623                 if (rc) {
624                         cifs_dbg(VFS, "%s: failed to update DFS target hint: rc = %d\n",
625                                  __func__, rc);
626                 }
627                 rc = dfs_cache_update_vol(cifs_sb->origin_fullpath, server);
628                 if (rc) {
629                         cifs_dbg(VFS, "%s: failed to update vol info in DFS cache: rc = %d\n",
630                                  __func__, rc);
631                 }
632                 dfs_cache_free_tgts(&tgt_list);
633         }
634 #endif
635         if (server->tcpStatus == CifsNeedNegotiate)
636                 mod_delayed_work(cifsiod_wq, &server->echo, 0);
637
638         return rc;
639 }
640
641 static void
642 cifs_echo_request(struct work_struct *work)
643 {
644         int rc;
645         struct TCP_Server_Info *server = container_of(work,
646                                         struct TCP_Server_Info, echo.work);
647         unsigned long echo_interval;
648
649         /*
650          * If we need to renegotiate, set echo interval to zero to
651          * immediately call echo service where we can renegotiate.
652          */
653         if (server->tcpStatus == CifsNeedNegotiate)
654                 echo_interval = 0;
655         else
656                 echo_interval = server->echo_interval;
657
658         /*
659          * We cannot send an echo if it is disabled.
660          * Also, no need to ping if we got a response recently.
661          */
662
663         if (server->tcpStatus == CifsNeedReconnect ||
664             server->tcpStatus == CifsExiting ||
665             server->tcpStatus == CifsNew ||
666             (server->ops->can_echo && !server->ops->can_echo(server)) ||
667             time_before(jiffies, server->lstrp + echo_interval - HZ))
668                 goto requeue_echo;
669
670         rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
671         if (rc)
672                 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
673                          server->hostname);
674
675 requeue_echo:
676         queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
677 }
678
679 static bool
680 allocate_buffers(struct TCP_Server_Info *server)
681 {
682         if (!server->bigbuf) {
683                 server->bigbuf = (char *)cifs_buf_get();
684                 if (!server->bigbuf) {
685                         cifs_dbg(VFS, "No memory for large SMB response\n");
686                         msleep(3000);
687                         /* retry will check if exiting */
688                         return false;
689                 }
690         } else if (server->large_buf) {
691                 /* we are reusing a dirty large buf, clear its start */
692                 memset(server->bigbuf, 0, HEADER_SIZE(server));
693         }
694
695         if (!server->smallbuf) {
696                 server->smallbuf = (char *)cifs_small_buf_get();
697                 if (!server->smallbuf) {
698                         cifs_dbg(VFS, "No memory for SMB response\n");
699                         msleep(1000);
700                         /* retry will check if exiting */
701                         return false;
702                 }
703                 /* beginning of smb buffer is cleared in our buf_get */
704         } else {
705                 /* if existing small buf clear beginning */
706                 memset(server->smallbuf, 0, HEADER_SIZE(server));
707         }
708
709         return true;
710 }
711
712 static bool
713 server_unresponsive(struct TCP_Server_Info *server)
714 {
715         /*
716          * We need to wait 3 echo intervals to make sure we handle such
717          * situations right:
718          * 1s  client sends a normal SMB request
719          * 3s  client gets a response
720          * 30s echo workqueue job pops, and decides we got a response recently
721          *     and don't need to send another
722          * ...
723          * 65s kernel_recvmsg times out, and we see that we haven't gotten
724          *     a response in >60s.
725          */
726         if ((server->tcpStatus == CifsGood ||
727             server->tcpStatus == CifsNeedNegotiate) &&
728             time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
729                 cifs_dbg(VFS, "Server %s has not responded in %lu seconds. Reconnecting...\n",
730                          server->hostname, (3 * server->echo_interval) / HZ);
731                 cifs_reconnect(server);
732                 wake_up(&server->response_q);
733                 return true;
734         }
735
736         return false;
737 }
738
739 static inline bool
740 zero_credits(struct TCP_Server_Info *server)
741 {
742         int val;
743
744         spin_lock(&server->req_lock);
745         val = server->credits + server->echo_credits + server->oplock_credits;
746         if (server->in_flight == 0 && val == 0) {
747                 spin_unlock(&server->req_lock);
748                 return true;
749         }
750         spin_unlock(&server->req_lock);
751         return false;
752 }
753
754 static int
755 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
756 {
757         int length = 0;
758         int total_read;
759
760         smb_msg->msg_control = NULL;
761         smb_msg->msg_controllen = 0;
762
763         for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
764                 try_to_freeze();
765
766                 /* reconnect if no credits and no requests in flight */
767                 if (zero_credits(server)) {
768                         cifs_reconnect(server);
769                         return -ECONNABORTED;
770                 }
771
772                 if (server_unresponsive(server))
773                         return -ECONNABORTED;
774                 if (cifs_rdma_enabled(server) && server->smbd_conn)
775                         length = smbd_recv(server->smbd_conn, smb_msg);
776                 else
777                         length = sock_recvmsg(server->ssocket, smb_msg, 0);
778
779                 if (server->tcpStatus == CifsExiting)
780                         return -ESHUTDOWN;
781
782                 if (server->tcpStatus == CifsNeedReconnect) {
783                         cifs_reconnect(server);
784                         return -ECONNABORTED;
785                 }
786
787                 if (length == -ERESTARTSYS ||
788                     length == -EAGAIN ||
789                     length == -EINTR) {
790                         /*
791                          * Minimum sleep to prevent looping, allowing socket
792                          * to clear and app threads to set tcpStatus
793                          * CifsNeedReconnect if server hung.
794                          */
795                         usleep_range(1000, 2000);
796                         length = 0;
797                         continue;
798                 }
799
800                 if (length <= 0) {
801                         cifs_dbg(FYI, "Received no data or error: %d\n", length);
802                         cifs_reconnect(server);
803                         return -ECONNABORTED;
804                 }
805         }
806         return total_read;
807 }
808
809 int
810 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
811                       unsigned int to_read)
812 {
813         struct msghdr smb_msg;
814         struct kvec iov = {.iov_base = buf, .iov_len = to_read};
815         iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
816
817         return cifs_readv_from_socket(server, &smb_msg);
818 }
819
820 int
821 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
822         unsigned int page_offset, unsigned int to_read)
823 {
824         struct msghdr smb_msg;
825         struct bio_vec bv = {
826                 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
827         iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
828         return cifs_readv_from_socket(server, &smb_msg);
829 }
830
831 static bool
832 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
833 {
834         /*
835          * The first byte big endian of the length field,
836          * is actually not part of the length but the type
837          * with the most common, zero, as regular data.
838          */
839         switch (type) {
840         case RFC1002_SESSION_MESSAGE:
841                 /* Regular SMB response */
842                 return true;
843         case RFC1002_SESSION_KEEP_ALIVE:
844                 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
845                 break;
846         case RFC1002_POSITIVE_SESSION_RESPONSE:
847                 cifs_dbg(FYI, "RFC 1002 positive session response\n");
848                 break;
849         case RFC1002_NEGATIVE_SESSION_RESPONSE:
850                 /*
851                  * We get this from Windows 98 instead of an error on
852                  * SMB negprot response.
853                  */
854                 cifs_dbg(FYI, "RFC 1002 negative session response\n");
855                 /* give server a second to clean up */
856                 msleep(1000);
857                 /*
858                  * Always try 445 first on reconnect since we get NACK
859                  * on some if we ever connected to port 139 (the NACK
860                  * is since we do not begin with RFC1001 session
861                  * initialize frame).
862                  */
863                 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
864                 cifs_reconnect(server);
865                 wake_up(&server->response_q);
866                 break;
867         default:
868                 cifs_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
869                 cifs_reconnect(server);
870         }
871
872         return false;
873 }
874
875 void
876 dequeue_mid(struct mid_q_entry *mid, bool malformed)
877 {
878 #ifdef CONFIG_CIFS_STATS2
879         mid->when_received = jiffies;
880 #endif
881         spin_lock(&GlobalMid_Lock);
882         if (!malformed)
883                 mid->mid_state = MID_RESPONSE_RECEIVED;
884         else
885                 mid->mid_state = MID_RESPONSE_MALFORMED;
886         /*
887          * Trying to handle/dequeue a mid after the send_recv()
888          * function has finished processing it is a bug.
889          */
890         if (mid->mid_flags & MID_DELETED)
891                 printk_once(KERN_WARNING
892                             "trying to dequeue a deleted mid\n");
893         else {
894                 list_del_init(&mid->qhead);
895                 mid->mid_flags |= MID_DELETED;
896         }
897         spin_unlock(&GlobalMid_Lock);
898 }
899
900 static void
901 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
902            char *buf, int malformed)
903 {
904         if (server->ops->check_trans2 &&
905             server->ops->check_trans2(mid, server, buf, malformed))
906                 return;
907         mid->resp_buf = buf;
908         mid->large_buf = server->large_buf;
909         /* Was previous buf put in mpx struct for multi-rsp? */
910         if (!mid->multiRsp) {
911                 /* smb buffer will be freed by user thread */
912                 if (server->large_buf)
913                         server->bigbuf = NULL;
914                 else
915                         server->smallbuf = NULL;
916         }
917         dequeue_mid(mid, malformed);
918 }
919
920 static void clean_demultiplex_info(struct TCP_Server_Info *server)
921 {
922         int length;
923
924         /* take it off the list, if it's not already */
925         spin_lock(&cifs_tcp_ses_lock);
926         list_del_init(&server->tcp_ses_list);
927         spin_unlock(&cifs_tcp_ses_lock);
928
929         spin_lock(&GlobalMid_Lock);
930         server->tcpStatus = CifsExiting;
931         spin_unlock(&GlobalMid_Lock);
932         wake_up_all(&server->response_q);
933
934         /* check if we have blocked requests that need to free */
935         spin_lock(&server->req_lock);
936         if (server->credits <= 0)
937                 server->credits = 1;
938         spin_unlock(&server->req_lock);
939         /*
940          * Although there should not be any requests blocked on this queue it
941          * can not hurt to be paranoid and try to wake up requests that may
942          * haven been blocked when more than 50 at time were on the wire to the
943          * same server - they now will see the session is in exit state and get
944          * out of SendReceive.
945          */
946         wake_up_all(&server->request_q);
947         /* give those requests time to exit */
948         msleep(125);
949         if (cifs_rdma_enabled(server))
950                 smbd_destroy(server);
951         if (server->ssocket) {
952                 sock_release(server->ssocket);
953                 server->ssocket = NULL;
954         }
955
956         if (!list_empty(&server->pending_mid_q)) {
957                 struct list_head dispose_list;
958                 struct mid_q_entry *mid_entry;
959                 struct list_head *tmp, *tmp2;
960
961                 INIT_LIST_HEAD(&dispose_list);
962                 spin_lock(&GlobalMid_Lock);
963                 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
964                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
965                         cifs_dbg(FYI, "Clearing mid 0x%llx\n", mid_entry->mid);
966                         kref_get(&mid_entry->refcount);
967                         mid_entry->mid_state = MID_SHUTDOWN;
968                         list_move(&mid_entry->qhead, &dispose_list);
969                         mid_entry->mid_flags |= MID_DELETED;
970                 }
971                 spin_unlock(&GlobalMid_Lock);
972
973                 /* now walk dispose list and issue callbacks */
974                 list_for_each_safe(tmp, tmp2, &dispose_list) {
975                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
976                         cifs_dbg(FYI, "Callback mid 0x%llx\n", mid_entry->mid);
977                         list_del_init(&mid_entry->qhead);
978                         mid_entry->callback(mid_entry);
979                         cifs_mid_q_entry_release(mid_entry);
980                 }
981                 /* 1/8th of sec is more than enough time for them to exit */
982                 msleep(125);
983         }
984
985         if (!list_empty(&server->pending_mid_q)) {
986                 /*
987                  * mpx threads have not exited yet give them at least the smb
988                  * send timeout time for long ops.
989                  *
990                  * Due to delays on oplock break requests, we need to wait at
991                  * least 45 seconds before giving up on a request getting a
992                  * response and going ahead and killing cifsd.
993                  */
994                 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
995                 msleep(46000);
996                 /*
997                  * If threads still have not exited they are probably never
998                  * coming home not much else we can do but free the memory.
999                  */
1000         }
1001
1002         kfree(server->hostname);
1003         kfree(server);
1004
1005         length = atomic_dec_return(&tcpSesAllocCount);
1006         if (length > 0)
1007                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1008 }
1009
1010 static int
1011 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1012 {
1013         int length;
1014         char *buf = server->smallbuf;
1015         unsigned int pdu_length = server->pdu_size;
1016
1017         /* make sure this will fit in a large buffer */
1018         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1019                 server->vals->header_preamble_size) {
1020                 cifs_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1021                 cifs_reconnect(server);
1022                 wake_up(&server->response_q);
1023                 return -ECONNABORTED;
1024         }
1025
1026         /* switch to large buffer if too big for a small one */
1027         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1028                 server->large_buf = true;
1029                 memcpy(server->bigbuf, buf, server->total_read);
1030                 buf = server->bigbuf;
1031         }
1032
1033         /* now read the rest */
1034         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1035                                        pdu_length - HEADER_SIZE(server) + 1
1036                                        + server->vals->header_preamble_size);
1037
1038         if (length < 0)
1039                 return length;
1040         server->total_read += length;
1041
1042         dump_smb(buf, server->total_read);
1043
1044         return cifs_handle_standard(server, mid);
1045 }
1046
1047 int
1048 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1049 {
1050         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1051         int length;
1052
1053         /*
1054          * We know that we received enough to get to the MID as we
1055          * checked the pdu_length earlier. Now check to see
1056          * if the rest of the header is OK. We borrow the length
1057          * var for the rest of the loop to avoid a new stack var.
1058          *
1059          * 48 bytes is enough to display the header and a little bit
1060          * into the payload for debugging purposes.
1061          */
1062         length = server->ops->check_message(buf, server->total_read, server);
1063         if (length != 0)
1064                 cifs_dump_mem("Bad SMB: ", buf,
1065                         min_t(unsigned int, server->total_read, 48));
1066
1067         if (server->ops->is_session_expired &&
1068             server->ops->is_session_expired(buf)) {
1069                 cifs_reconnect(server);
1070                 wake_up(&server->response_q);
1071                 return -1;
1072         }
1073
1074         if (server->ops->is_status_pending &&
1075             server->ops->is_status_pending(buf, server))
1076                 return -1;
1077
1078         if (!mid)
1079                 return length;
1080
1081         handle_mid(mid, server, buf, length);
1082         return 0;
1083 }
1084
1085 static void
1086 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1087 {
1088         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buffer;
1089
1090         /*
1091          * SMB1 does not use credits.
1092          */
1093         if (server->vals->header_preamble_size)
1094                 return;
1095
1096         if (shdr->CreditRequest) {
1097                 spin_lock(&server->req_lock);
1098                 server->credits += le16_to_cpu(shdr->CreditRequest);
1099                 spin_unlock(&server->req_lock);
1100                 wake_up(&server->request_q);
1101         }
1102 }
1103
1104
1105 static int
1106 cifs_demultiplex_thread(void *p)
1107 {
1108         int i, num_mids, length;
1109         struct TCP_Server_Info *server = p;
1110         unsigned int pdu_length;
1111         unsigned int next_offset;
1112         char *buf = NULL;
1113         struct task_struct *task_to_wake = NULL;
1114         struct mid_q_entry *mids[MAX_COMPOUND];
1115         char *bufs[MAX_COMPOUND];
1116
1117         current->flags |= PF_MEMALLOC;
1118         cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1119
1120         length = atomic_inc_return(&tcpSesAllocCount);
1121         if (length > 1)
1122                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1123
1124         set_freezable();
1125         allow_kernel_signal(SIGKILL);
1126         while (server->tcpStatus != CifsExiting) {
1127                 if (try_to_freeze())
1128                         continue;
1129
1130                 if (!allocate_buffers(server))
1131                         continue;
1132
1133                 server->large_buf = false;
1134                 buf = server->smallbuf;
1135                 pdu_length = 4; /* enough to get RFC1001 header */
1136
1137                 length = cifs_read_from_socket(server, buf, pdu_length);
1138                 if (length < 0)
1139                         continue;
1140
1141                 if (server->vals->header_preamble_size == 0)
1142                         server->total_read = 0;
1143                 else
1144                         server->total_read = length;
1145
1146                 /*
1147                  * The right amount was read from socket - 4 bytes,
1148                  * so we can now interpret the length field.
1149                  */
1150                 pdu_length = get_rfc1002_length(buf);
1151
1152                 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1153                 if (!is_smb_response(server, buf[0]))
1154                         continue;
1155 next_pdu:
1156                 server->pdu_size = pdu_length;
1157
1158                 /* make sure we have enough to get to the MID */
1159                 if (server->pdu_size < HEADER_SIZE(server) - 1 -
1160                     server->vals->header_preamble_size) {
1161                         cifs_dbg(VFS, "SMB response too short (%u bytes)\n",
1162                                  server->pdu_size);
1163                         cifs_reconnect(server);
1164                         wake_up(&server->response_q);
1165                         continue;
1166                 }
1167
1168                 /* read down to the MID */
1169                 length = cifs_read_from_socket(server,
1170                              buf + server->vals->header_preamble_size,
1171                              HEADER_SIZE(server) - 1
1172                              - server->vals->header_preamble_size);
1173                 if (length < 0)
1174                         continue;
1175                 server->total_read += length;
1176
1177                 if (server->ops->next_header) {
1178                         next_offset = server->ops->next_header(buf);
1179                         if (next_offset)
1180                                 server->pdu_size = next_offset;
1181                 }
1182
1183                 memset(mids, 0, sizeof(mids));
1184                 memset(bufs, 0, sizeof(bufs));
1185                 num_mids = 0;
1186
1187                 if (server->ops->is_transform_hdr &&
1188                     server->ops->receive_transform &&
1189                     server->ops->is_transform_hdr(buf)) {
1190                         length = server->ops->receive_transform(server,
1191                                                                 mids,
1192                                                                 bufs,
1193                                                                 &num_mids);
1194                 } else {
1195                         mids[0] = server->ops->find_mid(server, buf);
1196                         bufs[0] = buf;
1197                         num_mids = 1;
1198
1199                         if (!mids[0] || !mids[0]->receive)
1200                                 length = standard_receive3(server, mids[0]);
1201                         else
1202                                 length = mids[0]->receive(server, mids[0]);
1203                 }
1204
1205                 if (length < 0) {
1206                         for (i = 0; i < num_mids; i++)
1207                                 if (mids[i])
1208                                         cifs_mid_q_entry_release(mids[i]);
1209                         continue;
1210                 }
1211
1212                 server->lstrp = jiffies;
1213
1214                 for (i = 0; i < num_mids; i++) {
1215                         if (mids[i] != NULL) {
1216                                 mids[i]->resp_buf_size = server->pdu_size;
1217                                 if ((mids[i]->mid_flags & MID_WAIT_CANCELLED) &&
1218                                     mids[i]->mid_state == MID_RESPONSE_RECEIVED &&
1219                                     server->ops->handle_cancelled_mid)
1220                                         server->ops->handle_cancelled_mid(
1221                                                         mids[i]->resp_buf,
1222                                                         server);
1223
1224                                 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1225                                         mids[i]->callback(mids[i]);
1226
1227                                 cifs_mid_q_entry_release(mids[i]);
1228                         } else if (server->ops->is_oplock_break &&
1229                                    server->ops->is_oplock_break(bufs[i],
1230                                                                 server)) {
1231                                 smb2_add_credits_from_hdr(bufs[i], server);
1232                                 cifs_dbg(FYI, "Received oplock break\n");
1233                         } else {
1234                                 cifs_dbg(VFS, "No task to wake, unknown frame "
1235                                          "received! NumMids %d\n",
1236                                          atomic_read(&midCount));
1237                                 cifs_dump_mem("Received Data is: ", bufs[i],
1238                                               HEADER_SIZE(server));
1239                                 smb2_add_credits_from_hdr(bufs[i], server);
1240 #ifdef CONFIG_CIFS_DEBUG2
1241                                 if (server->ops->dump_detail)
1242                                         server->ops->dump_detail(bufs[i],
1243                                                                  server);
1244                                 cifs_dump_mids(server);
1245 #endif /* CIFS_DEBUG2 */
1246                         }
1247                 }
1248
1249                 if (pdu_length > server->pdu_size) {
1250                         if (!allocate_buffers(server))
1251                                 continue;
1252                         pdu_length -= server->pdu_size;
1253                         server->total_read = 0;
1254                         server->large_buf = false;
1255                         buf = server->smallbuf;
1256                         goto next_pdu;
1257                 }
1258         } /* end while !EXITING */
1259
1260         /* buffer usually freed in free_mid - need to free it here on exit */
1261         cifs_buf_release(server->bigbuf);
1262         if (server->smallbuf) /* no sense logging a debug message if NULL */
1263                 cifs_small_buf_release(server->smallbuf);
1264
1265         task_to_wake = xchg(&server->tsk, NULL);
1266         clean_demultiplex_info(server);
1267
1268         /* if server->tsk was NULL then wait for a signal before exiting */
1269         if (!task_to_wake) {
1270                 set_current_state(TASK_INTERRUPTIBLE);
1271                 while (!signal_pending(current)) {
1272                         schedule();
1273                         set_current_state(TASK_INTERRUPTIBLE);
1274                 }
1275                 set_current_state(TASK_RUNNING);
1276         }
1277
1278         module_put_and_exit(0);
1279 }
1280
1281 /* extract the host portion of the UNC string */
1282 static char *
1283 extract_hostname(const char *unc)
1284 {
1285         const char *src;
1286         char *dst, *delim;
1287         unsigned int len;
1288
1289         /* skip double chars at beginning of string */
1290         /* BB: check validity of these bytes? */
1291         if (strlen(unc) < 3)
1292                 return ERR_PTR(-EINVAL);
1293         for (src = unc; *src && *src == '\\'; src++)
1294                 ;
1295         if (!*src)
1296                 return ERR_PTR(-EINVAL);
1297
1298         /* delimiter between hostname and sharename is always '\\' now */
1299         delim = strchr(src, '\\');
1300         if (!delim)
1301                 return ERR_PTR(-EINVAL);
1302
1303         len = delim - src;
1304         dst = kmalloc((len + 1), GFP_KERNEL);
1305         if (dst == NULL)
1306                 return ERR_PTR(-ENOMEM);
1307
1308         memcpy(dst, src, len);
1309         dst[len] = '\0';
1310
1311         return dst;
1312 }
1313
1314 static int get_option_ul(substring_t args[], unsigned long *option)
1315 {
1316         int rc;
1317         char *string;
1318
1319         string = match_strdup(args);
1320         if (string == NULL)
1321                 return -ENOMEM;
1322         rc = kstrtoul(string, 0, option);
1323         kfree(string);
1324
1325         return rc;
1326 }
1327
1328 static int get_option_uid(substring_t args[], kuid_t *result)
1329 {
1330         unsigned long value;
1331         kuid_t uid;
1332         int rc;
1333
1334         rc = get_option_ul(args, &value);
1335         if (rc)
1336                 return rc;
1337
1338         uid = make_kuid(current_user_ns(), value);
1339         if (!uid_valid(uid))
1340                 return -EINVAL;
1341
1342         *result = uid;
1343         return 0;
1344 }
1345
1346 static int get_option_gid(substring_t args[], kgid_t *result)
1347 {
1348         unsigned long value;
1349         kgid_t gid;
1350         int rc;
1351
1352         rc = get_option_ul(args, &value);
1353         if (rc)
1354                 return rc;
1355
1356         gid = make_kgid(current_user_ns(), value);
1357         if (!gid_valid(gid))
1358                 return -EINVAL;
1359
1360         *result = gid;
1361         return 0;
1362 }
1363
1364 static int cifs_parse_security_flavors(char *value,
1365                                        struct smb_vol *vol)
1366 {
1367
1368         substring_t args[MAX_OPT_ARGS];
1369
1370         /*
1371          * With mount options, the last one should win. Reset any existing
1372          * settings back to default.
1373          */
1374         vol->sectype = Unspecified;
1375         vol->sign = false;
1376
1377         switch (match_token(value, cifs_secflavor_tokens, args)) {
1378         case Opt_sec_krb5p:
1379                 cifs_dbg(VFS, "sec=krb5p is not supported!\n");
1380                 return 1;
1381         case Opt_sec_krb5i:
1382                 vol->sign = true;
1383                 /* Fallthrough */
1384         case Opt_sec_krb5:
1385                 vol->sectype = Kerberos;
1386                 break;
1387         case Opt_sec_ntlmsspi:
1388                 vol->sign = true;
1389                 /* Fallthrough */
1390         case Opt_sec_ntlmssp:
1391                 vol->sectype = RawNTLMSSP;
1392                 break;
1393         case Opt_sec_ntlmi:
1394                 vol->sign = true;
1395                 /* Fallthrough */
1396         case Opt_ntlm:
1397                 vol->sectype = NTLM;
1398                 break;
1399         case Opt_sec_ntlmv2i:
1400                 vol->sign = true;
1401                 /* Fallthrough */
1402         case Opt_sec_ntlmv2:
1403                 vol->sectype = NTLMv2;
1404                 break;
1405 #ifdef CONFIG_CIFS_WEAK_PW_HASH
1406         case Opt_sec_lanman:
1407                 vol->sectype = LANMAN;
1408                 break;
1409 #endif
1410         case Opt_sec_none:
1411                 vol->nullauth = 1;
1412                 break;
1413         default:
1414                 cifs_dbg(VFS, "bad security option: %s\n", value);
1415                 return 1;
1416         }
1417
1418         return 0;
1419 }
1420
1421 static int
1422 cifs_parse_cache_flavor(char *value, struct smb_vol *vol)
1423 {
1424         substring_t args[MAX_OPT_ARGS];
1425
1426         switch (match_token(value, cifs_cacheflavor_tokens, args)) {
1427         case Opt_cache_loose:
1428                 vol->direct_io = false;
1429                 vol->strict_io = false;
1430                 break;
1431         case Opt_cache_strict:
1432                 vol->direct_io = false;
1433                 vol->strict_io = true;
1434                 break;
1435         case Opt_cache_none:
1436                 vol->direct_io = true;
1437                 vol->strict_io = false;
1438                 break;
1439         default:
1440                 cifs_dbg(VFS, "bad cache= option: %s\n", value);
1441                 return 1;
1442         }
1443         return 0;
1444 }
1445
1446 static int
1447 cifs_parse_smb_version(char *value, struct smb_vol *vol, bool is_smb3)
1448 {
1449         substring_t args[MAX_OPT_ARGS];
1450
1451         switch (match_token(value, cifs_smb_version_tokens, args)) {
1452 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1453         case Smb_1:
1454                 if (disable_legacy_dialects) {
1455                         cifs_dbg(VFS, "mount with legacy dialect disabled\n");
1456                         return 1;
1457                 }
1458                 if (is_smb3) {
1459                         cifs_dbg(VFS, "vers=1.0 (cifs) not permitted when mounting with smb3\n");
1460                         return 1;
1461                 }
1462                 vol->ops = &smb1_operations;
1463                 vol->vals = &smb1_values;
1464                 break;
1465         case Smb_20:
1466                 if (disable_legacy_dialects) {
1467                         cifs_dbg(VFS, "mount with legacy dialect disabled\n");
1468                         return 1;
1469                 }
1470                 if (is_smb3) {
1471                         cifs_dbg(VFS, "vers=2.0 not permitted when mounting with smb3\n");
1472                         return 1;
1473                 }
1474                 vol->ops = &smb20_operations;
1475                 vol->vals = &smb20_values;
1476                 break;
1477 #else
1478         case Smb_1:
1479                 cifs_dbg(VFS, "vers=1.0 (cifs) mount not permitted when legacy dialects disabled\n");
1480                 return 1;
1481         case Smb_20:
1482                 cifs_dbg(VFS, "vers=2.0 mount not permitted when legacy dialects disabled\n");
1483                 return 1;
1484 #endif /* CIFS_ALLOW_INSECURE_LEGACY */
1485         case Smb_21:
1486                 vol->ops = &smb21_operations;
1487                 vol->vals = &smb21_values;
1488                 break;
1489         case Smb_30:
1490                 vol->ops = &smb30_operations;
1491                 vol->vals = &smb30_values;
1492                 break;
1493         case Smb_302:
1494                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1495                 vol->vals = &smb302_values;
1496                 break;
1497         case Smb_311:
1498                 vol->ops = &smb311_operations;
1499                 vol->vals = &smb311_values;
1500                 break;
1501         case Smb_3any:
1502                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1503                 vol->vals = &smb3any_values;
1504                 break;
1505         case Smb_default:
1506                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1507                 vol->vals = &smbdefault_values;
1508                 break;
1509         default:
1510                 cifs_dbg(VFS, "Unknown vers= option specified: %s\n", value);
1511                 return 1;
1512         }
1513         return 0;
1514 }
1515
1516 /*
1517  * Parse a devname into substrings and populate the vol->UNC and vol->prepath
1518  * fields with the result. Returns 0 on success and an error otherwise.
1519  */
1520 static int
1521 cifs_parse_devname(const char *devname, struct smb_vol *vol)
1522 {
1523         char *pos;
1524         const char *delims = "/\\";
1525         size_t len;
1526
1527         if (unlikely(!devname || !*devname)) {
1528                 cifs_dbg(VFS, "Device name not specified.\n");
1529                 return -EINVAL;
1530         }
1531
1532         /* make sure we have a valid UNC double delimiter prefix */
1533         len = strspn(devname, delims);
1534         if (len != 2)
1535                 return -EINVAL;
1536
1537         /* find delimiter between host and sharename */
1538         pos = strpbrk(devname + 2, delims);
1539         if (!pos)
1540                 return -EINVAL;
1541
1542         /* skip past delimiter */
1543         ++pos;
1544
1545         /* now go until next delimiter or end of string */
1546         len = strcspn(pos, delims);
1547
1548         /* move "pos" up to delimiter or NULL */
1549         pos += len;
1550         vol->UNC = kstrndup(devname, pos - devname, GFP_KERNEL);
1551         if (!vol->UNC)
1552                 return -ENOMEM;
1553
1554         convert_delimiter(vol->UNC, '\\');
1555
1556         /* skip any delimiter */
1557         if (*pos == '/' || *pos == '\\')
1558                 pos++;
1559
1560         /* If pos is NULL then no prepath */
1561         if (!*pos)
1562                 return 0;
1563
1564         vol->prepath = kstrdup(pos, GFP_KERNEL);
1565         if (!vol->prepath)
1566                 return -ENOMEM;
1567
1568         return 0;
1569 }
1570
1571 static int
1572 cifs_parse_mount_options(const char *mountdata, const char *devname,
1573                          struct smb_vol *vol, bool is_smb3)
1574 {
1575         char *data, *end;
1576         char *mountdata_copy = NULL, *options;
1577         unsigned int  temp_len, i, j;
1578         char separator[2];
1579         short int override_uid = -1;
1580         short int override_gid = -1;
1581         bool uid_specified = false;
1582         bool gid_specified = false;
1583         bool sloppy = false;
1584         char *invalid = NULL;
1585         char *nodename = utsname()->nodename;
1586         char *string = NULL;
1587         char *tmp_end, *value;
1588         char delim;
1589         bool got_ip = false;
1590         bool got_version = false;
1591         unsigned short port = 0;
1592         struct sockaddr *dstaddr = (struct sockaddr *)&vol->dstaddr;
1593
1594         separator[0] = ',';
1595         separator[1] = 0;
1596         delim = separator[0];
1597
1598         /* ensure we always start with zeroed-out smb_vol */
1599         memset(vol, 0, sizeof(*vol));
1600
1601         /*
1602          * does not have to be perfect mapping since field is
1603          * informational, only used for servers that do not support
1604          * port 445 and it can be overridden at mount time
1605          */
1606         memset(vol->source_rfc1001_name, 0x20, RFC1001_NAME_LEN);
1607         for (i = 0; i < strnlen(nodename, RFC1001_NAME_LEN); i++)
1608                 vol->source_rfc1001_name[i] = toupper(nodename[i]);
1609
1610         vol->source_rfc1001_name[RFC1001_NAME_LEN] = 0;
1611         /* null target name indicates to use *SMBSERVR default called name
1612            if we end up sending RFC1001 session initialize */
1613         vol->target_rfc1001_name[0] = 0;
1614         vol->cred_uid = current_uid();
1615         vol->linux_uid = current_uid();
1616         vol->linux_gid = current_gid();
1617         vol->bsize = 1024 * 1024; /* can improve cp performance significantly */
1618         /*
1619          * default to SFM style remapping of seven reserved characters
1620          * unless user overrides it or we negotiate CIFS POSIX where
1621          * it is unnecessary.  Can not simultaneously use more than one mapping
1622          * since then readdir could list files that open could not open
1623          */
1624         vol->remap = true;
1625
1626         /* default to only allowing write access to owner of the mount */
1627         vol->dir_mode = vol->file_mode = S_IRUGO | S_IXUGO | S_IWUSR;
1628
1629         /* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */
1630         /* default is always to request posix paths. */
1631         vol->posix_paths = 1;
1632         /* default to using server inode numbers where available */
1633         vol->server_ino = 1;
1634
1635         /* default is to use strict cifs caching semantics */
1636         vol->strict_io = true;
1637
1638         vol->actimeo = CIFS_DEF_ACTIMEO;
1639
1640         /* Most clients set timeout to 0, allows server to use its default */
1641         vol->handle_timeout = 0; /* See MS-SMB2 spec section 2.2.14.2.12 */
1642
1643         /* offer SMB2.1 and later (SMB3 etc). Secure and widely accepted */
1644         vol->ops = &smb30_operations;
1645         vol->vals = &smbdefault_values;
1646
1647         vol->echo_interval = SMB_ECHO_INTERVAL_DEFAULT;
1648
1649         if (!mountdata)
1650                 goto cifs_parse_mount_err;
1651
1652         mountdata_copy = kstrndup(mountdata, PAGE_SIZE, GFP_KERNEL);
1653         if (!mountdata_copy)
1654                 goto cifs_parse_mount_err;
1655
1656         options = mountdata_copy;
1657         end = options + strlen(options);
1658
1659         if (strncmp(options, "sep=", 4) == 0) {
1660                 if (options[4] != 0) {
1661                         separator[0] = options[4];
1662                         options += 5;
1663                 } else {
1664                         cifs_dbg(FYI, "Null separator not allowed\n");
1665                 }
1666         }
1667         vol->backupuid_specified = false; /* no backup intent for a user */
1668         vol->backupgid_specified = false; /* no backup intent for a group */
1669
1670         switch (cifs_parse_devname(devname, vol)) {
1671         case 0:
1672                 break;
1673         case -ENOMEM:
1674                 cifs_dbg(VFS, "Unable to allocate memory for devname.\n");
1675                 goto cifs_parse_mount_err;
1676         case -EINVAL:
1677                 cifs_dbg(VFS, "Malformed UNC in devname.\n");
1678                 goto cifs_parse_mount_err;
1679         default:
1680                 cifs_dbg(VFS, "Unknown error parsing devname.\n");
1681                 goto cifs_parse_mount_err;
1682         }
1683
1684         while ((data = strsep(&options, separator)) != NULL) {
1685                 substring_t args[MAX_OPT_ARGS];
1686                 unsigned long option;
1687                 int token;
1688
1689                 if (!*data)
1690                         continue;
1691
1692                 token = match_token(data, cifs_mount_option_tokens, args);
1693
1694                 switch (token) {
1695
1696                 /* Ingnore the following */
1697                 case Opt_ignore:
1698                         break;
1699
1700                 /* Boolean values */
1701                 case Opt_user_xattr:
1702                         vol->no_xattr = 0;
1703                         break;
1704                 case Opt_nouser_xattr:
1705                         vol->no_xattr = 1;
1706                         break;
1707                 case Opt_forceuid:
1708                         override_uid = 1;
1709                         break;
1710                 case Opt_noforceuid:
1711                         override_uid = 0;
1712                         break;
1713                 case Opt_forcegid:
1714                         override_gid = 1;
1715                         break;
1716                 case Opt_noforcegid:
1717                         override_gid = 0;
1718                         break;
1719                 case Opt_noblocksend:
1720                         vol->noblocksnd = 1;
1721                         break;
1722                 case Opt_noautotune:
1723                         vol->noautotune = 1;
1724                         break;
1725                 case Opt_nolease:
1726                         vol->no_lease = 1;
1727                         break;
1728                 case Opt_hard:
1729                         vol->retry = 1;
1730                         break;
1731                 case Opt_soft:
1732                         vol->retry = 0;
1733                         break;
1734                 case Opt_perm:
1735                         vol->noperm = 0;
1736                         break;
1737                 case Opt_noperm:
1738                         vol->noperm = 1;
1739                         break;
1740                 case Opt_mapchars:
1741                         vol->sfu_remap = true;
1742                         vol->remap = false; /* disable SFM mapping */
1743                         break;
1744                 case Opt_nomapchars:
1745                         vol->sfu_remap = false;
1746                         break;
1747                 case Opt_mapposix:
1748                         vol->remap = true;
1749                         vol->sfu_remap = false; /* disable SFU mapping */
1750                         break;
1751                 case Opt_nomapposix:
1752                         vol->remap = false;
1753                         break;
1754                 case Opt_sfu:
1755                         vol->sfu_emul = 1;
1756                         break;
1757                 case Opt_nosfu:
1758                         vol->sfu_emul = 0;
1759                         break;
1760                 case Opt_nodfs:
1761                         vol->nodfs = 1;
1762                         break;
1763                 case Opt_posixpaths:
1764                         vol->posix_paths = 1;
1765                         break;
1766                 case Opt_noposixpaths:
1767                         vol->posix_paths = 0;
1768                         break;
1769                 case Opt_nounix:
1770                         if (vol->linux_ext)
1771                                 cifs_dbg(VFS,
1772                                         "conflicting unix mount options\n");
1773                         vol->no_linux_ext = 1;
1774                         break;
1775                 case Opt_unix:
1776                         if (vol->no_linux_ext)
1777                                 cifs_dbg(VFS,
1778                                         "conflicting unix mount options\n");
1779                         vol->linux_ext = 1;
1780                         break;
1781                 case Opt_nocase:
1782                         vol->nocase = 1;
1783                         break;
1784                 case Opt_brl:
1785                         vol->nobrl =  0;
1786                         break;
1787                 case Opt_nobrl:
1788                         vol->nobrl =  1;
1789                         /*
1790                          * turn off mandatory locking in mode
1791                          * if remote locking is turned off since the
1792                          * local vfs will do advisory
1793                          */
1794                         if (vol->file_mode ==
1795                                 (S_IALLUGO & ~(S_ISUID | S_IXGRP)))
1796                                 vol->file_mode = S_IALLUGO;
1797                         break;
1798                 case Opt_nohandlecache:
1799                         vol->nohandlecache = 1;
1800                         break;
1801                 case Opt_handlecache:
1802                         vol->nohandlecache = 0;
1803                         break;
1804                 case Opt_forcemandatorylock:
1805                         vol->mand_lock = 1;
1806                         break;
1807                 case Opt_setuids:
1808                         vol->setuids = 1;
1809                         break;
1810                 case Opt_nosetuids:
1811                         vol->setuids = 0;
1812                         break;
1813                 case Opt_setuidfromacl:
1814                         vol->setuidfromacl = 1;
1815                         break;
1816                 case Opt_dynperm:
1817                         vol->dynperm = true;
1818                         break;
1819                 case Opt_nodynperm:
1820                         vol->dynperm = false;
1821                         break;
1822                 case Opt_nohard:
1823                         vol->retry = 0;
1824                         break;
1825                 case Opt_nosoft:
1826                         vol->retry = 1;
1827                         break;
1828                 case Opt_nointr:
1829                         vol->intr = 0;
1830                         break;
1831                 case Opt_intr:
1832                         vol->intr = 1;
1833                         break;
1834                 case Opt_nostrictsync:
1835                         vol->nostrictsync = 1;
1836                         break;
1837                 case Opt_strictsync:
1838                         vol->nostrictsync = 0;
1839                         break;
1840                 case Opt_serverino:
1841                         vol->server_ino = 1;
1842                         break;
1843                 case Opt_noserverino:
1844                         vol->server_ino = 0;
1845                         break;
1846                 case Opt_rwpidforward:
1847                         vol->rwpidforward = 1;
1848                         break;
1849                 case Opt_modesid:
1850                         vol->mode_ace = 1;
1851                         break;
1852                 case Opt_cifsacl:
1853                         vol->cifs_acl = 1;
1854                         break;
1855                 case Opt_nocifsacl:
1856                         vol->cifs_acl = 0;
1857                         break;
1858                 case Opt_acl:
1859                         vol->no_psx_acl = 0;
1860                         break;
1861                 case Opt_noacl:
1862                         vol->no_psx_acl = 1;
1863                         break;
1864                 case Opt_locallease:
1865                         vol->local_lease = 1;
1866                         break;
1867                 case Opt_sign:
1868                         vol->sign = true;
1869                         break;
1870                 case Opt_seal:
1871                         /* we do not do the following in secFlags because seal
1872                          * is a per tree connection (mount) not a per socket
1873                          * or per-smb connection option in the protocol
1874                          * vol->secFlg |= CIFSSEC_MUST_SEAL;
1875                          */
1876                         vol->seal = 1;
1877                         break;
1878                 case Opt_noac:
1879                         pr_warn("CIFS: Mount option noac not supported. Instead set /proc/fs/cifs/LookupCacheEnabled to 0\n");
1880                         break;
1881                 case Opt_fsc:
1882 #ifndef CONFIG_CIFS_FSCACHE
1883                         cifs_dbg(VFS, "FS-Cache support needs CONFIG_CIFS_FSCACHE kernel config option set\n");
1884                         goto cifs_parse_mount_err;
1885 #endif
1886                         vol->fsc = true;
1887                         break;
1888                 case Opt_mfsymlinks:
1889                         vol->mfsymlinks = true;
1890                         break;
1891                 case Opt_multiuser:
1892                         vol->multiuser = true;
1893                         break;
1894                 case Opt_sloppy:
1895                         sloppy = true;
1896                         break;
1897                 case Opt_nosharesock:
1898                         vol->nosharesock = true;
1899                         break;
1900                 case Opt_nopersistent:
1901                         vol->nopersistent = true;
1902                         if (vol->persistent) {
1903                                 cifs_dbg(VFS,
1904                                   "persistenthandles mount options conflict\n");
1905                                 goto cifs_parse_mount_err;
1906                         }
1907                         break;
1908                 case Opt_persistent:
1909                         vol->persistent = true;
1910                         if ((vol->nopersistent) || (vol->resilient)) {
1911                                 cifs_dbg(VFS,
1912                                   "persistenthandles mount options conflict\n");
1913                                 goto cifs_parse_mount_err;
1914                         }
1915                         break;
1916                 case Opt_resilient:
1917                         vol->resilient = true;
1918                         if (vol->persistent) {
1919                                 cifs_dbg(VFS,
1920                                   "persistenthandles mount options conflict\n");
1921                                 goto cifs_parse_mount_err;
1922                         }
1923                         break;
1924                 case Opt_noresilient:
1925                         vol->resilient = false; /* already the default */
1926                         break;
1927                 case Opt_domainauto:
1928                         vol->domainauto = true;
1929                         break;
1930                 case Opt_rdma:
1931                         vol->rdma = true;
1932                         break;
1933                 case Opt_compress:
1934                         vol->compression = UNKNOWN_TYPE;
1935                         cifs_dbg(VFS,
1936                                 "SMB3 compression support is experimental\n");
1937                         break;
1938
1939                 /* Numeric Values */
1940                 case Opt_backupuid:
1941                         if (get_option_uid(args, &vol->backupuid)) {
1942                                 cifs_dbg(VFS, "%s: Invalid backupuid value\n",
1943                                          __func__);
1944                                 goto cifs_parse_mount_err;
1945                         }
1946                         vol->backupuid_specified = true;
1947                         break;
1948                 case Opt_backupgid:
1949                         if (get_option_gid(args, &vol->backupgid)) {
1950                                 cifs_dbg(VFS, "%s: Invalid backupgid value\n",
1951                                          __func__);
1952                                 goto cifs_parse_mount_err;
1953                         }
1954                         vol->backupgid_specified = true;
1955                         break;
1956                 case Opt_uid:
1957                         if (get_option_uid(args, &vol->linux_uid)) {
1958                                 cifs_dbg(VFS, "%s: Invalid uid value\n",
1959                                          __func__);
1960                                 goto cifs_parse_mount_err;
1961                         }
1962                         uid_specified = true;
1963                         break;
1964                 case Opt_cruid:
1965                         if (get_option_uid(args, &vol->cred_uid)) {
1966                                 cifs_dbg(VFS, "%s: Invalid cruid value\n",
1967                                          __func__);
1968                                 goto cifs_parse_mount_err;
1969                         }
1970                         break;
1971                 case Opt_gid:
1972                         if (get_option_gid(args, &vol->linux_gid)) {
1973                                 cifs_dbg(VFS, "%s: Invalid gid value\n",
1974                                          __func__);
1975                                 goto cifs_parse_mount_err;
1976                         }
1977                         gid_specified = true;
1978                         break;
1979                 case Opt_file_mode:
1980                         if (get_option_ul(args, &option)) {
1981                                 cifs_dbg(VFS, "%s: Invalid file_mode value\n",
1982                                          __func__);
1983                                 goto cifs_parse_mount_err;
1984                         }
1985                         vol->file_mode = option;
1986                         break;
1987                 case Opt_dirmode:
1988                         if (get_option_ul(args, &option)) {
1989                                 cifs_dbg(VFS, "%s: Invalid dir_mode value\n",
1990                                          __func__);
1991                                 goto cifs_parse_mount_err;
1992                         }
1993                         vol->dir_mode = option;
1994                         break;
1995                 case Opt_port:
1996                         if (get_option_ul(args, &option) ||
1997                             option > USHRT_MAX) {
1998                                 cifs_dbg(VFS, "%s: Invalid port value\n",
1999                                          __func__);
2000                                 goto cifs_parse_mount_err;
2001                         }
2002                         port = (unsigned short)option;
2003                         break;
2004                 case Opt_blocksize:
2005                         if (get_option_ul(args, &option)) {
2006                                 cifs_dbg(VFS, "%s: Invalid blocksize value\n",
2007                                         __func__);
2008                                 goto cifs_parse_mount_err;
2009                         }
2010                         /*
2011                          * inode blocksize realistically should never need to be
2012                          * less than 16K or greater than 16M and default is 1MB.
2013                          * Note that small inode block sizes (e.g. 64K) can lead
2014                          * to very poor performance of common tools like cp and scp
2015                          */
2016                         if ((option < CIFS_MAX_MSGSIZE) ||
2017                            (option > (4 * SMB3_DEFAULT_IOSIZE))) {
2018                                 cifs_dbg(VFS, "%s: Invalid blocksize\n",
2019                                         __func__);
2020                                 goto cifs_parse_mount_err;
2021                         }
2022                         vol->bsize = option;
2023                         break;
2024                 case Opt_rsize:
2025                         if (get_option_ul(args, &option)) {
2026                                 cifs_dbg(VFS, "%s: Invalid rsize value\n",
2027                                          __func__);
2028                                 goto cifs_parse_mount_err;
2029                         }
2030                         vol->rsize = option;
2031                         break;
2032                 case Opt_wsize:
2033                         if (get_option_ul(args, &option)) {
2034                                 cifs_dbg(VFS, "%s: Invalid wsize value\n",
2035                                          __func__);
2036                                 goto cifs_parse_mount_err;
2037                         }
2038                         vol->wsize = option;
2039                         break;
2040                 case Opt_actimeo:
2041                         if (get_option_ul(args, &option)) {
2042                                 cifs_dbg(VFS, "%s: Invalid actimeo value\n",
2043                                          __func__);
2044                                 goto cifs_parse_mount_err;
2045                         }
2046                         vol->actimeo = HZ * option;
2047                         if (vol->actimeo > CIFS_MAX_ACTIMEO) {
2048                                 cifs_dbg(VFS, "attribute cache timeout too large\n");
2049                                 goto cifs_parse_mount_err;
2050                         }
2051                         break;
2052                 case Opt_handletimeout:
2053                         if (get_option_ul(args, &option)) {
2054                                 cifs_dbg(VFS, "%s: Invalid handletimeout value\n",
2055                                          __func__);
2056                                 goto cifs_parse_mount_err;
2057                         }
2058                         vol->handle_timeout = option;
2059                         if (vol->handle_timeout > SMB3_MAX_HANDLE_TIMEOUT) {
2060                                 cifs_dbg(VFS, "Invalid handle cache timeout, longer than 16 minutes\n");
2061                                 goto cifs_parse_mount_err;
2062                         }
2063                         break;
2064                 case Opt_echo_interval:
2065                         if (get_option_ul(args, &option)) {
2066                                 cifs_dbg(VFS, "%s: Invalid echo interval value\n",
2067                                          __func__);
2068                                 goto cifs_parse_mount_err;
2069                         }
2070                         vol->echo_interval = option;
2071                         break;
2072                 case Opt_snapshot:
2073                         if (get_option_ul(args, &option)) {
2074                                 cifs_dbg(VFS, "%s: Invalid snapshot time\n",
2075                                          __func__);
2076                                 goto cifs_parse_mount_err;
2077                         }
2078                         vol->snapshot_time = option;
2079                         break;
2080                 case Opt_max_credits:
2081                         if (get_option_ul(args, &option) || (option < 20) ||
2082                             (option > 60000)) {
2083                                 cifs_dbg(VFS, "%s: Invalid max_credits value\n",
2084                                          __func__);
2085                                 goto cifs_parse_mount_err;
2086                         }
2087                         vol->max_credits = option;
2088                         break;
2089
2090                 /* String Arguments */
2091
2092                 case Opt_blank_user:
2093                         /* null user, ie. anonymous authentication */
2094                         vol->nullauth = 1;
2095                         vol->username = NULL;
2096                         break;
2097                 case Opt_user:
2098                         string = match_strdup(args);
2099                         if (string == NULL)
2100                                 goto out_nomem;
2101
2102                         if (strnlen(string, CIFS_MAX_USERNAME_LEN) >
2103                                                         CIFS_MAX_USERNAME_LEN) {
2104                                 pr_warn("CIFS: username too long\n");
2105                                 goto cifs_parse_mount_err;
2106                         }
2107
2108                         kfree(vol->username);
2109                         vol->username = kstrdup(string, GFP_KERNEL);
2110                         if (!vol->username)
2111                                 goto cifs_parse_mount_err;
2112                         break;
2113                 case Opt_blank_pass:
2114                         /* passwords have to be handled differently
2115                          * to allow the character used for deliminator
2116                          * to be passed within them
2117                          */
2118
2119                         /*
2120                          * Check if this is a case where the  password
2121                          * starts with a delimiter
2122                          */
2123                         tmp_end = strchr(data, '=');
2124                         tmp_end++;
2125                         if (!(tmp_end < end && tmp_end[1] == delim)) {
2126                                 /* No it is not. Set the password to NULL */
2127                                 kzfree(vol->password);
2128                                 vol->password = NULL;
2129                                 break;
2130                         }
2131                         /* Fallthrough - to Opt_pass below.*/
2132                 case Opt_pass:
2133                         /* Obtain the value string */
2134                         value = strchr(data, '=');
2135                         value++;
2136
2137                         /* Set tmp_end to end of the string */
2138                         tmp_end = (char *) value + strlen(value);
2139
2140                         /* Check if following character is the deliminator
2141                          * If yes, we have encountered a double deliminator
2142                          * reset the NULL character to the deliminator
2143                          */
2144                         if (tmp_end < end && tmp_end[1] == delim) {
2145                                 tmp_end[0] = delim;
2146
2147                                 /* Keep iterating until we get to a single
2148                                  * deliminator OR the end
2149                                  */
2150                                 while ((tmp_end = strchr(tmp_end, delim))
2151                                         != NULL && (tmp_end[1] == delim)) {
2152                                                 tmp_end = (char *) &tmp_end[2];
2153                                 }
2154
2155                                 /* Reset var options to point to next element */
2156                                 if (tmp_end) {
2157                                         tmp_end[0] = '\0';
2158                                         options = (char *) &tmp_end[1];
2159                                 } else
2160                                         /* Reached the end of the mount option
2161                                          * string */
2162                                         options = end;
2163                         }
2164
2165                         kzfree(vol->password);
2166                         /* Now build new password string */
2167                         temp_len = strlen(value);
2168                         vol->password = kzalloc(temp_len+1, GFP_KERNEL);
2169                         if (vol->password == NULL) {
2170                                 pr_warn("CIFS: no memory for password\n");
2171                                 goto cifs_parse_mount_err;
2172                         }
2173
2174                         for (i = 0, j = 0; i < temp_len; i++, j++) {
2175                                 vol->password[j] = value[i];
2176                                 if ((value[i] == delim) &&
2177                                      value[i+1] == delim)
2178                                         /* skip the second deliminator */
2179                                         i++;
2180                         }
2181                         vol->password[j] = '\0';
2182                         break;
2183                 case Opt_blank_ip:
2184                         /* FIXME: should this be an error instead? */
2185                         got_ip = false;
2186                         break;
2187                 case Opt_ip:
2188                         string = match_strdup(args);
2189                         if (string == NULL)
2190                                 goto out_nomem;
2191
2192                         if (!cifs_convert_address(dstaddr, string,
2193                                         strlen(string))) {
2194                                 pr_err("CIFS: bad ip= option (%s).\n", string);
2195                                 goto cifs_parse_mount_err;
2196                         }
2197                         got_ip = true;
2198                         break;
2199                 case Opt_domain:
2200                         string = match_strdup(args);
2201                         if (string == NULL)
2202                                 goto out_nomem;
2203
2204                         if (strnlen(string, CIFS_MAX_DOMAINNAME_LEN)
2205                                         == CIFS_MAX_DOMAINNAME_LEN) {
2206                                 pr_warn("CIFS: domain name too long\n");
2207                                 goto cifs_parse_mount_err;
2208                         }
2209
2210                         kfree(vol->domainname);
2211                         vol->domainname = kstrdup(string, GFP_KERNEL);
2212                         if (!vol->domainname) {
2213                                 pr_warn("CIFS: no memory for domainname\n");
2214                                 goto cifs_parse_mount_err;
2215                         }
2216                         cifs_dbg(FYI, "Domain name set\n");
2217                         break;
2218                 case Opt_srcaddr:
2219                         string = match_strdup(args);
2220                         if (string == NULL)
2221                                 goto out_nomem;
2222
2223                         if (!cifs_convert_address(
2224                                         (struct sockaddr *)&vol->srcaddr,
2225                                         string, strlen(string))) {
2226                                 pr_warn("CIFS: Could not parse srcaddr: %s\n",
2227                                         string);
2228                                 goto cifs_parse_mount_err;
2229                         }
2230                         break;
2231                 case Opt_iocharset:
2232                         string = match_strdup(args);
2233                         if (string == NULL)
2234                                 goto out_nomem;
2235
2236                         if (strnlen(string, 1024) >= 65) {
2237                                 pr_warn("CIFS: iocharset name too long.\n");
2238                                 goto cifs_parse_mount_err;
2239                         }
2240
2241                          if (strncasecmp(string, "default", 7) != 0) {
2242                                 kfree(vol->iocharset);
2243                                 vol->iocharset = kstrdup(string,
2244                                                          GFP_KERNEL);
2245                                 if (!vol->iocharset) {
2246                                         pr_warn("CIFS: no memory for charset\n");
2247                                         goto cifs_parse_mount_err;
2248                                 }
2249                         }
2250                         /* if iocharset not set then load_nls_default
2251                          * is used by caller
2252                          */
2253                          cifs_dbg(FYI, "iocharset set to %s\n", string);
2254                         break;
2255                 case Opt_netbiosname:
2256                         string = match_strdup(args);
2257                         if (string == NULL)
2258                                 goto out_nomem;
2259
2260                         memset(vol->source_rfc1001_name, 0x20,
2261                                 RFC1001_NAME_LEN);
2262                         /*
2263                          * FIXME: are there cases in which a comma can
2264                          * be valid in workstation netbios name (and
2265                          * need special handling)?
2266                          */
2267                         for (i = 0; i < RFC1001_NAME_LEN; i++) {
2268                                 /* don't ucase netbiosname for user */
2269                                 if (string[i] == 0)
2270                                         break;
2271                                 vol->source_rfc1001_name[i] = string[i];
2272                         }
2273                         /* The string has 16th byte zero still from
2274                          * set at top of the function
2275                          */
2276                         if (i == RFC1001_NAME_LEN && string[i] != 0)
2277                                 pr_warn("CIFS: netbiosname longer than 15 truncated.\n");
2278                         break;
2279                 case Opt_servern:
2280                         /* servernetbiosname specified override *SMBSERVER */
2281                         string = match_strdup(args);
2282                         if (string == NULL)
2283                                 goto out_nomem;
2284
2285                         /* last byte, type, is 0x20 for servr type */
2286                         memset(vol->target_rfc1001_name, 0x20,
2287                                 RFC1001_NAME_LEN_WITH_NULL);
2288
2289                         /* BB are there cases in which a comma can be
2290                            valid in this workstation netbios name
2291                            (and need special handling)? */
2292
2293                         /* user or mount helper must uppercase the
2294                            netbios name */
2295                         for (i = 0; i < 15; i++) {
2296                                 if (string[i] == 0)
2297                                         break;
2298                                 vol->target_rfc1001_name[i] = string[i];
2299                         }
2300                         /* The string has 16th byte zero still from
2301                            set at top of the function  */
2302                         if (i == RFC1001_NAME_LEN && string[i] != 0)
2303                                 pr_warn("CIFS: server netbiosname longer than 15 truncated.\n");
2304                         break;
2305                 case Opt_ver:
2306                         /* version of mount userspace tools, not dialect */
2307                         string = match_strdup(args);
2308                         if (string == NULL)
2309                                 goto out_nomem;
2310
2311                         /* If interface changes in mount.cifs bump to new ver */
2312                         if (strncasecmp(string, "1", 1) == 0) {
2313                                 if (strlen(string) > 1) {
2314                                         pr_warn("Bad mount helper ver=%s. Did "
2315                                                 "you want SMB1 (CIFS) dialect "
2316                                                 "and mean to type vers=1.0 "
2317                                                 "instead?\n", string);
2318                                         goto cifs_parse_mount_err;
2319                                 }
2320                                 /* This is the default */
2321                                 break;
2322                         }
2323                         /* For all other value, error */
2324                         pr_warn("CIFS: Invalid mount helper version specified\n");
2325                         goto cifs_parse_mount_err;
2326                 case Opt_vers:
2327                         /* protocol version (dialect) */
2328                         string = match_strdup(args);
2329                         if (string == NULL)
2330                                 goto out_nomem;
2331
2332                         if (cifs_parse_smb_version(string, vol, is_smb3) != 0)
2333                                 goto cifs_parse_mount_err;
2334                         got_version = true;
2335                         break;
2336                 case Opt_sec:
2337                         string = match_strdup(args);
2338                         if (string == NULL)
2339                                 goto out_nomem;
2340
2341                         if (cifs_parse_security_flavors(string, vol) != 0)
2342                                 goto cifs_parse_mount_err;
2343                         break;
2344                 case Opt_cache:
2345                         string = match_strdup(args);
2346                         if (string == NULL)
2347                                 goto out_nomem;
2348
2349                         if (cifs_parse_cache_flavor(string, vol) != 0)
2350                                 goto cifs_parse_mount_err;
2351                         break;
2352                 default:
2353                         /*
2354                          * An option we don't recognize. Save it off for later
2355                          * if we haven't already found one
2356                          */
2357                         if (!invalid)
2358                                 invalid = data;
2359                         break;
2360                 }
2361                 /* Free up any allocated string */
2362                 kfree(string);
2363                 string = NULL;
2364         }
2365
2366         if (!sloppy && invalid) {
2367                 pr_err("CIFS: Unknown mount option \"%s\"\n", invalid);
2368                 goto cifs_parse_mount_err;
2369         }
2370
2371         if (vol->rdma && vol->vals->protocol_id < SMB30_PROT_ID) {
2372                 cifs_dbg(VFS, "SMB Direct requires Version >=3.0\n");
2373                 goto cifs_parse_mount_err;
2374         }
2375
2376 #ifndef CONFIG_KEYS
2377         /* Muliuser mounts require CONFIG_KEYS support */
2378         if (vol->multiuser) {
2379                 cifs_dbg(VFS, "Multiuser mounts require kernels with CONFIG_KEYS enabled\n");
2380                 goto cifs_parse_mount_err;
2381         }
2382 #endif
2383         if (!vol->UNC) {
2384                 cifs_dbg(VFS, "CIFS mount error: No usable UNC path provided in device string!\n");
2385                 goto cifs_parse_mount_err;
2386         }
2387
2388         /* make sure UNC has a share name */
2389         if (!strchr(vol->UNC + 3, '\\')) {
2390                 cifs_dbg(VFS, "Malformed UNC. Unable to find share name.\n");
2391                 goto cifs_parse_mount_err;
2392         }
2393
2394         if (!got_ip) {
2395                 int len;
2396                 const char *slash;
2397
2398                 /* No ip= option specified? Try to get it from UNC */
2399                 /* Use the address part of the UNC. */
2400                 slash = strchr(&vol->UNC[2], '\\');
2401                 len = slash - &vol->UNC[2];
2402                 if (!cifs_convert_address(dstaddr, &vol->UNC[2], len)) {
2403                         pr_err("Unable to determine destination address.\n");
2404                         goto cifs_parse_mount_err;
2405                 }
2406         }
2407
2408         /* set the port that we got earlier */
2409         cifs_set_port(dstaddr, port);
2410
2411         if (uid_specified)
2412                 vol->override_uid = override_uid;
2413         else if (override_uid == 1)
2414                 pr_notice("CIFS: ignoring forceuid mount option specified with no uid= option.\n");
2415
2416         if (gid_specified)
2417                 vol->override_gid = override_gid;
2418         else if (override_gid == 1)
2419                 pr_notice("CIFS: ignoring forcegid mount option specified with no gid= option.\n");
2420
2421         if (got_version == false)
2422                 pr_warn("No dialect specified on mount. Default has changed to "
2423                         "a more secure dialect, SMB2.1 or later (e.g. SMB3), from CIFS "
2424                         "(SMB1). To use the less secure SMB1 dialect to access "
2425                         "old servers which do not support SMB3 (or SMB2.1) specify vers=1.0"
2426                         " on mount.\n");
2427
2428         kfree(mountdata_copy);
2429         return 0;
2430
2431 out_nomem:
2432         pr_warn("Could not allocate temporary buffer\n");
2433 cifs_parse_mount_err:
2434         kfree(string);
2435         kfree(mountdata_copy);
2436         return 1;
2437 }
2438
2439 /** Returns true if srcaddr isn't specified and rhs isn't
2440  * specified, or if srcaddr is specified and
2441  * matches the IP address of the rhs argument.
2442  */
2443 static bool
2444 srcip_matches(struct sockaddr *srcaddr, struct sockaddr *rhs)
2445 {
2446         switch (srcaddr->sa_family) {
2447         case AF_UNSPEC:
2448                 return (rhs->sa_family == AF_UNSPEC);
2449         case AF_INET: {
2450                 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
2451                 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
2452                 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
2453         }
2454         case AF_INET6: {
2455                 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
2456                 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
2457                 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
2458         }
2459         default:
2460                 WARN_ON(1);
2461                 return false; /* don't expect to be here */
2462         }
2463 }
2464
2465 /*
2466  * If no port is specified in addr structure, we try to match with 445 port
2467  * and if it fails - with 139 ports. It should be called only if address
2468  * families of server and addr are equal.
2469  */
2470 static bool
2471 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
2472 {
2473         __be16 port, *sport;
2474
2475         /* SMBDirect manages its own ports, don't match it here */
2476         if (server->rdma)
2477                 return true;
2478
2479         switch (addr->sa_family) {
2480         case AF_INET:
2481                 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
2482                 port = ((struct sockaddr_in *) addr)->sin_port;
2483                 break;
2484         case AF_INET6:
2485                 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
2486                 port = ((struct sockaddr_in6 *) addr)->sin6_port;
2487                 break;
2488         default:
2489                 WARN_ON(1);
2490                 return false;
2491         }
2492
2493         if (!port) {
2494                 port = htons(CIFS_PORT);
2495                 if (port == *sport)
2496                         return true;
2497
2498                 port = htons(RFC1001_PORT);
2499         }
2500
2501         return port == *sport;
2502 }
2503
2504 static bool
2505 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
2506               struct sockaddr *srcaddr)
2507 {
2508         switch (addr->sa_family) {
2509         case AF_INET: {
2510                 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
2511                 struct sockaddr_in *srv_addr4 =
2512                                         (struct sockaddr_in *)&server->dstaddr;
2513
2514                 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
2515                         return false;
2516                 break;
2517         }
2518         case AF_INET6: {
2519                 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
2520                 struct sockaddr_in6 *srv_addr6 =
2521                                         (struct sockaddr_in6 *)&server->dstaddr;
2522
2523                 if (!ipv6_addr_equal(&addr6->sin6_addr,
2524                                      &srv_addr6->sin6_addr))
2525                         return false;
2526                 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
2527                         return false;
2528                 break;
2529         }
2530         default:
2531                 WARN_ON(1);
2532                 return false; /* don't expect to be here */
2533         }
2534
2535         if (!srcip_matches(srcaddr, (struct sockaddr *)&server->srcaddr))
2536                 return false;
2537
2538         return true;
2539 }
2540
2541 static bool
2542 match_security(struct TCP_Server_Info *server, struct smb_vol *vol)
2543 {
2544         /*
2545          * The select_sectype function should either return the vol->sectype
2546          * that was specified, or "Unspecified" if that sectype was not
2547          * compatible with the given NEGOTIATE request.
2548          */
2549         if (server->ops->select_sectype(server, vol->sectype)
2550              == Unspecified)
2551                 return false;
2552
2553         /*
2554          * Now check if signing mode is acceptable. No need to check
2555          * global_secflags at this point since if MUST_SIGN is set then
2556          * the server->sign had better be too.
2557          */
2558         if (vol->sign && !server->sign)
2559                 return false;
2560
2561         return true;
2562 }
2563
2564 static int match_server(struct TCP_Server_Info *server, struct smb_vol *vol)
2565 {
2566         struct sockaddr *addr = (struct sockaddr *)&vol->dstaddr;
2567
2568         if (vol->nosharesock)
2569                 return 0;
2570
2571         /* If multidialect negotiation see if existing sessions match one */
2572         if (strcmp(vol->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
2573                 if (server->vals->protocol_id < SMB30_PROT_ID)
2574                         return 0;
2575         } else if (strcmp(vol->vals->version_string,
2576                    SMBDEFAULT_VERSION_STRING) == 0) {
2577                 if (server->vals->protocol_id < SMB21_PROT_ID)
2578                         return 0;
2579         } else if ((server->vals != vol->vals) || (server->ops != vol->ops))
2580                 return 0;
2581
2582         if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
2583                 return 0;
2584
2585         if (!match_address(server, addr,
2586                            (struct sockaddr *)&vol->srcaddr))
2587                 return 0;
2588
2589         if (!match_port(server, addr))
2590                 return 0;
2591
2592         if (!match_security(server, vol))
2593                 return 0;
2594
2595         if (server->echo_interval != vol->echo_interval * HZ)
2596                 return 0;
2597
2598         if (server->rdma != vol->rdma)
2599                 return 0;
2600
2601         return 1;
2602 }
2603
2604 struct TCP_Server_Info *
2605 cifs_find_tcp_session(struct smb_vol *vol)
2606 {
2607         struct TCP_Server_Info *server;
2608
2609         spin_lock(&cifs_tcp_ses_lock);
2610         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
2611                 if (!match_server(server, vol))
2612                         continue;
2613
2614                 ++server->srv_count;
2615                 spin_unlock(&cifs_tcp_ses_lock);
2616                 cifs_dbg(FYI, "Existing tcp session with server found\n");
2617                 return server;
2618         }
2619         spin_unlock(&cifs_tcp_ses_lock);
2620         return NULL;
2621 }
2622
2623 void
2624 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
2625 {
2626         struct task_struct *task;
2627
2628         spin_lock(&cifs_tcp_ses_lock);
2629         if (--server->srv_count > 0) {
2630                 spin_unlock(&cifs_tcp_ses_lock);
2631                 return;
2632         }
2633
2634         put_net(cifs_net_ns(server));
2635
2636         list_del_init(&server->tcp_ses_list);
2637         spin_unlock(&cifs_tcp_ses_lock);
2638
2639         cancel_delayed_work_sync(&server->echo);
2640
2641         if (from_reconnect)
2642                 /*
2643                  * Avoid deadlock here: reconnect work calls
2644                  * cifs_put_tcp_session() at its end. Need to be sure
2645                  * that reconnect work does nothing with server pointer after
2646                  * that step.
2647                  */
2648                 cancel_delayed_work(&server->reconnect);
2649         else
2650                 cancel_delayed_work_sync(&server->reconnect);
2651
2652         spin_lock(&GlobalMid_Lock);
2653         server->tcpStatus = CifsExiting;
2654         spin_unlock(&GlobalMid_Lock);
2655
2656         cifs_crypto_secmech_release(server);
2657         cifs_fscache_release_client_cookie(server);
2658
2659         kfree(server->session_key.response);
2660         server->session_key.response = NULL;
2661         server->session_key.len = 0;
2662
2663         task = xchg(&server->tsk, NULL);
2664         if (task)
2665                 send_sig(SIGKILL, task, 1);
2666 }
2667
2668 static struct TCP_Server_Info *
2669 cifs_get_tcp_session(struct smb_vol *volume_info)
2670 {
2671         struct TCP_Server_Info *tcp_ses = NULL;
2672         int rc;
2673
2674         cifs_dbg(FYI, "UNC: %s\n", volume_info->UNC);
2675
2676         /* see if we already have a matching tcp_ses */
2677         tcp_ses = cifs_find_tcp_session(volume_info);
2678         if (tcp_ses)
2679                 return tcp_ses;
2680
2681         tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
2682         if (!tcp_ses) {
2683                 rc = -ENOMEM;
2684                 goto out_err;
2685         }
2686
2687         tcp_ses->ops = volume_info->ops;
2688         tcp_ses->vals = volume_info->vals;
2689         cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
2690         tcp_ses->hostname = extract_hostname(volume_info->UNC);
2691         if (IS_ERR(tcp_ses->hostname)) {
2692                 rc = PTR_ERR(tcp_ses->hostname);
2693                 goto out_err_crypto_release;
2694         }
2695
2696         tcp_ses->noblocksnd = volume_info->noblocksnd;
2697         tcp_ses->noautotune = volume_info->noautotune;
2698         tcp_ses->tcp_nodelay = volume_info->sockopt_tcp_nodelay;
2699         tcp_ses->rdma = volume_info->rdma;
2700         tcp_ses->in_flight = 0;
2701         tcp_ses->credits = 1;
2702         init_waitqueue_head(&tcp_ses->response_q);
2703         init_waitqueue_head(&tcp_ses->request_q);
2704         INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
2705         mutex_init(&tcp_ses->srv_mutex);
2706         memcpy(tcp_ses->workstation_RFC1001_name,
2707                 volume_info->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2708         memcpy(tcp_ses->server_RFC1001_name,
2709                 volume_info->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2710         tcp_ses->session_estab = false;
2711         tcp_ses->sequence_number = 0;
2712         tcp_ses->reconnect_instance = 1;
2713         tcp_ses->lstrp = jiffies;
2714         tcp_ses->compress_algorithm = cpu_to_le16(volume_info->compression);
2715         spin_lock_init(&tcp_ses->req_lock);
2716         INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
2717         INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
2718         INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
2719         INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
2720         mutex_init(&tcp_ses->reconnect_mutex);
2721         memcpy(&tcp_ses->srcaddr, &volume_info->srcaddr,
2722                sizeof(tcp_ses->srcaddr));
2723         memcpy(&tcp_ses->dstaddr, &volume_info->dstaddr,
2724                 sizeof(tcp_ses->dstaddr));
2725         generate_random_uuid(tcp_ses->client_guid);
2726         /*
2727          * at this point we are the only ones with the pointer
2728          * to the struct since the kernel thread not created yet
2729          * no need to spinlock this init of tcpStatus or srv_count
2730          */
2731         tcp_ses->tcpStatus = CifsNew;
2732         ++tcp_ses->srv_count;
2733
2734         if (volume_info->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
2735                 volume_info->echo_interval <= SMB_ECHO_INTERVAL_MAX)
2736                 tcp_ses->echo_interval = volume_info->echo_interval * HZ;
2737         else
2738                 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
2739         if (tcp_ses->rdma) {
2740 #ifndef CONFIG_CIFS_SMB_DIRECT
2741                 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
2742                 rc = -ENOENT;
2743                 goto out_err_crypto_release;
2744 #endif
2745                 tcp_ses->smbd_conn = smbd_get_connection(
2746                         tcp_ses, (struct sockaddr *)&volume_info->dstaddr);
2747                 if (tcp_ses->smbd_conn) {
2748                         cifs_dbg(VFS, "RDMA transport established\n");
2749                         rc = 0;
2750                         goto smbd_connected;
2751                 } else {
2752                         rc = -ENOENT;
2753                         goto out_err_crypto_release;
2754                 }
2755         }
2756         rc = ip_connect(tcp_ses);
2757         if (rc < 0) {
2758                 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
2759                 goto out_err_crypto_release;
2760         }
2761 smbd_connected:
2762         /*
2763          * since we're in a cifs function already, we know that
2764          * this will succeed. No need for try_module_get().
2765          */
2766         __module_get(THIS_MODULE);
2767         tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
2768                                   tcp_ses, "cifsd");
2769         if (IS_ERR(tcp_ses->tsk)) {
2770                 rc = PTR_ERR(tcp_ses->tsk);
2771                 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
2772                 module_put(THIS_MODULE);
2773                 goto out_err_crypto_release;
2774         }
2775         tcp_ses->tcpStatus = CifsNeedNegotiate;
2776
2777         tcp_ses->nr_targets = 1;
2778
2779         /* thread spawned, put it on the list */
2780         spin_lock(&cifs_tcp_ses_lock);
2781         list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
2782         spin_unlock(&cifs_tcp_ses_lock);
2783
2784         cifs_fscache_get_client_cookie(tcp_ses);
2785
2786         /* queue echo request delayed work */
2787         queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
2788
2789         return tcp_ses;
2790
2791 out_err_crypto_release:
2792         cifs_crypto_secmech_release(tcp_ses);
2793
2794         put_net(cifs_net_ns(tcp_ses));
2795
2796 out_err:
2797         if (tcp_ses) {
2798                 if (!IS_ERR(tcp_ses->hostname))
2799                         kfree(tcp_ses->hostname);
2800                 if (tcp_ses->ssocket)
2801                         sock_release(tcp_ses->ssocket);
2802                 kfree(tcp_ses);
2803         }
2804         return ERR_PTR(rc);
2805 }
2806
2807 static int match_session(struct cifs_ses *ses, struct smb_vol *vol)
2808 {
2809         if (vol->sectype != Unspecified &&
2810             vol->sectype != ses->sectype)
2811                 return 0;
2812
2813         switch (ses->sectype) {
2814         case Kerberos:
2815                 if (!uid_eq(vol->cred_uid, ses->cred_uid))
2816                         return 0;
2817                 break;
2818         default:
2819                 /* NULL username means anonymous session */
2820                 if (ses->user_name == NULL) {
2821                         if (!vol->nullauth)
2822                                 return 0;
2823                         break;
2824                 }
2825
2826                 /* anything else takes username/password */
2827                 if (strncmp(ses->user_name,
2828                             vol->username ? vol->username : "",
2829                             CIFS_MAX_USERNAME_LEN))
2830                         return 0;
2831                 if ((vol->username && strlen(vol->username) != 0) &&
2832                     ses->password != NULL &&
2833                     strncmp(ses->password,
2834                             vol->password ? vol->password : "",
2835                             CIFS_MAX_PASSWORD_LEN))
2836                         return 0;
2837         }
2838         return 1;
2839 }
2840
2841 /**
2842  * cifs_setup_ipc - helper to setup the IPC tcon for the session
2843  *
2844  * A new IPC connection is made and stored in the session
2845  * tcon_ipc. The IPC tcon has the same lifetime as the session.
2846  */
2847 static int
2848 cifs_setup_ipc(struct cifs_ses *ses, struct smb_vol *volume_info)
2849 {
2850         int rc = 0, xid;
2851         struct cifs_tcon *tcon;
2852         struct nls_table *nls_codepage;
2853         char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
2854         bool seal = false;
2855
2856         /*
2857          * If the mount request that resulted in the creation of the
2858          * session requires encryption, force IPC to be encrypted too.
2859          */
2860         if (volume_info->seal) {
2861                 if (ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
2862                         seal = true;
2863                 else {
2864                         cifs_dbg(VFS,
2865                                  "IPC: server doesn't support encryption\n");
2866                         return -EOPNOTSUPP;
2867                 }
2868         }
2869
2870         tcon = tconInfoAlloc();
2871         if (tcon == NULL)
2872                 return -ENOMEM;
2873
2874         scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", ses->server->hostname);
2875
2876         /* cannot fail */
2877         nls_codepage = load_nls_default();
2878
2879         xid = get_xid();
2880         tcon->ses = ses;
2881         tcon->ipc = true;
2882         tcon->seal = seal;
2883         rc = ses->server->ops->tree_connect(xid, ses, unc, tcon, nls_codepage);
2884         free_xid(xid);
2885
2886         if (rc) {
2887                 cifs_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
2888                 tconInfoFree(tcon);
2889                 goto out;
2890         }
2891
2892         cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
2893
2894         ses->tcon_ipc = tcon;
2895 out:
2896         unload_nls(nls_codepage);
2897         return rc;
2898 }
2899
2900 /**
2901  * cifs_free_ipc - helper to release the session IPC tcon
2902  *
2903  * Needs to be called everytime a session is destroyed
2904  */
2905 static int
2906 cifs_free_ipc(struct cifs_ses *ses)
2907 {
2908         int rc = 0, xid;
2909         struct cifs_tcon *tcon = ses->tcon_ipc;
2910
2911         if (tcon == NULL)
2912                 return 0;
2913
2914         if (ses->server->ops->tree_disconnect) {
2915                 xid = get_xid();
2916                 rc = ses->server->ops->tree_disconnect(xid, tcon);
2917                 free_xid(xid);
2918         }
2919
2920         if (rc)
2921                 cifs_dbg(FYI, "failed to disconnect IPC tcon (rc=%d)\n", rc);
2922
2923         tconInfoFree(tcon);
2924         ses->tcon_ipc = NULL;
2925         return rc;
2926 }
2927
2928 static struct cifs_ses *
2929 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol)
2930 {
2931         struct cifs_ses *ses;
2932
2933         spin_lock(&cifs_tcp_ses_lock);
2934         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2935                 if (ses->status == CifsExiting)
2936                         continue;
2937                 if (!match_session(ses, vol))
2938                         continue;
2939                 ++ses->ses_count;
2940                 spin_unlock(&cifs_tcp_ses_lock);
2941                 return ses;
2942         }
2943         spin_unlock(&cifs_tcp_ses_lock);
2944         return NULL;
2945 }
2946
2947 void cifs_put_smb_ses(struct cifs_ses *ses)
2948 {
2949         unsigned int rc, xid;
2950         struct TCP_Server_Info *server = ses->server;
2951
2952         cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2953
2954         spin_lock(&cifs_tcp_ses_lock);
2955         if (ses->status == CifsExiting) {
2956                 spin_unlock(&cifs_tcp_ses_lock);
2957                 return;
2958         }
2959         if (--ses->ses_count > 0) {
2960                 spin_unlock(&cifs_tcp_ses_lock);
2961                 return;
2962         }
2963         if (ses->status == CifsGood)
2964                 ses->status = CifsExiting;
2965         spin_unlock(&cifs_tcp_ses_lock);
2966
2967         cifs_free_ipc(ses);
2968
2969         if (ses->status == CifsExiting && server->ops->logoff) {
2970                 xid = get_xid();
2971                 rc = server->ops->logoff(xid, ses);
2972                 if (rc)
2973                         cifs_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2974                                 __func__, rc);
2975                 _free_xid(xid);
2976         }
2977
2978         spin_lock(&cifs_tcp_ses_lock);
2979         list_del_init(&ses->smb_ses_list);
2980         spin_unlock(&cifs_tcp_ses_lock);
2981
2982         sesInfoFree(ses);
2983         cifs_put_tcp_session(server, 0);
2984 }
2985
2986 #ifdef CONFIG_KEYS
2987
2988 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2989 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2990
2991 /* Populate username and pw fields from keyring if possible */
2992 static int
2993 cifs_set_cifscreds(struct smb_vol *vol, struct cifs_ses *ses)
2994 {
2995         int rc = 0;
2996         int is_domain = 0;
2997         const char *delim, *payload;
2998         char *desc;
2999         ssize_t len;
3000         struct key *key;
3001         struct TCP_Server_Info *server = ses->server;
3002         struct sockaddr_in *sa;
3003         struct sockaddr_in6 *sa6;
3004         const struct user_key_payload *upayload;
3005
3006         desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
3007         if (!desc)
3008                 return -ENOMEM;
3009
3010         /* try to find an address key first */
3011         switch (server->dstaddr.ss_family) {
3012         case AF_INET:
3013                 sa = (struct sockaddr_in *)&server->dstaddr;
3014                 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
3015                 break;
3016         case AF_INET6:
3017                 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
3018                 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
3019                 break;
3020         default:
3021                 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
3022                          server->dstaddr.ss_family);
3023                 rc = -EINVAL;
3024                 goto out_err;
3025         }
3026
3027         cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
3028         key = request_key(&key_type_logon, desc, "");
3029         if (IS_ERR(key)) {
3030                 if (!ses->domainName) {
3031                         cifs_dbg(FYI, "domainName is NULL\n");
3032                         rc = PTR_ERR(key);
3033                         goto out_err;
3034                 }
3035
3036                 /* didn't work, try to find a domain key */
3037                 sprintf(desc, "cifs:d:%s", ses->domainName);
3038                 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
3039                 key = request_key(&key_type_logon, desc, "");
3040                 if (IS_ERR(key)) {
3041                         rc = PTR_ERR(key);
3042                         goto out_err;
3043                 }
3044                 is_domain = 1;
3045         }
3046
3047         down_read(&key->sem);
3048         upayload = user_key_payload_locked(key);
3049         if (IS_ERR_OR_NULL(upayload)) {
3050                 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
3051                 goto out_key_put;
3052         }
3053
3054         /* find first : in payload */
3055         payload = upayload->data;
3056         delim = strnchr(payload, upayload->datalen, ':');
3057         cifs_dbg(FYI, "payload=%s\n", payload);
3058         if (!delim) {
3059                 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
3060                          upayload->datalen);
3061                 rc = -EINVAL;
3062                 goto out_key_put;
3063         }
3064
3065         len = delim - payload;
3066         if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
3067                 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
3068                          len);
3069                 rc = -EINVAL;
3070                 goto out_key_put;
3071         }
3072
3073         vol->username = kstrndup(payload, len, GFP_KERNEL);
3074         if (!vol->username) {
3075                 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
3076                          len);
3077                 rc = -ENOMEM;
3078                 goto out_key_put;
3079         }
3080         cifs_dbg(FYI, "%s: username=%s\n", __func__, vol->username);
3081
3082         len = key->datalen - (len + 1);
3083         if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
3084                 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
3085                 rc = -EINVAL;
3086                 kfree(vol->username);
3087                 vol->username = NULL;
3088                 goto out_key_put;
3089         }
3090
3091         ++delim;
3092         vol->password = kstrndup(delim, len, GFP_KERNEL);
3093         if (!vol->password) {
3094                 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
3095                          len);
3096                 rc = -ENOMEM;
3097                 kfree(vol->username);
3098                 vol->username = NULL;
3099                 goto out_key_put;
3100         }
3101
3102         /*
3103          * If we have a domain key then we must set the domainName in the
3104          * for the request.
3105          */
3106         if (is_domain && ses->domainName) {
3107                 vol->domainname = kstrndup(ses->domainName,
3108                                            strlen(ses->domainName),
3109                                            GFP_KERNEL);
3110                 if (!vol->domainname) {
3111                         cifs_dbg(FYI, "Unable to allocate %zd bytes for "
3112                                  "domain\n", len);
3113                         rc = -ENOMEM;
3114                         kfree(vol->username);
3115                         vol->username = NULL;
3116                         kzfree(vol->password);
3117                         vol->password = NULL;
3118                         goto out_key_put;
3119                 }
3120         }
3121
3122 out_key_put:
3123         up_read(&key->sem);
3124         key_put(key);
3125 out_err:
3126         kfree(desc);
3127         cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
3128         return rc;
3129 }
3130 #else /* ! CONFIG_KEYS */
3131 static inline int
3132 cifs_set_cifscreds(struct smb_vol *vol __attribute__((unused)),
3133                    struct cifs_ses *ses __attribute__((unused)))
3134 {
3135         return -ENOSYS;
3136 }
3137 #endif /* CONFIG_KEYS */
3138
3139 /**
3140  * cifs_get_smb_ses - get a session matching @volume_info data from @server
3141  *
3142  * This function assumes it is being called from cifs_mount() where we
3143  * already got a server reference (server refcount +1). See
3144  * cifs_get_tcon() for refcount explanations.
3145  */
3146 struct cifs_ses *
3147 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
3148 {
3149         int rc = -ENOMEM;
3150         unsigned int xid;
3151         struct cifs_ses *ses;
3152         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3153         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3154
3155         xid = get_xid();
3156
3157         ses = cifs_find_smb_ses(server, volume_info);
3158         if (ses) {
3159                 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
3160                          ses->status);
3161
3162                 mutex_lock(&ses->session_mutex);
3163                 rc = cifs_negotiate_protocol(xid, ses);
3164                 if (rc) {
3165                         mutex_unlock(&ses->session_mutex);
3166                         /* problem -- put our ses reference */
3167                         cifs_put_smb_ses(ses);
3168                         free_xid(xid);
3169                         return ERR_PTR(rc);
3170                 }
3171                 if (ses->need_reconnect) {
3172                         cifs_dbg(FYI, "Session needs reconnect\n");
3173                         rc = cifs_setup_session(xid, ses,
3174                                                 volume_info->local_nls);
3175                         if (rc) {
3176                                 mutex_unlock(&ses->session_mutex);
3177                                 /* problem -- put our reference */
3178                                 cifs_put_smb_ses(ses);
3179                                 free_xid(xid);
3180                                 return ERR_PTR(rc);
3181                         }
3182                 }
3183                 mutex_unlock(&ses->session_mutex);
3184
3185                 /* existing SMB ses has a server reference already */
3186                 cifs_put_tcp_session(server, 0);
3187                 free_xid(xid);
3188                 return ses;
3189         }
3190
3191         cifs_dbg(FYI, "Existing smb sess not found\n");
3192         ses = sesInfoAlloc();
3193         if (ses == NULL)
3194                 goto get_ses_fail;
3195
3196         /* new SMB session uses our server ref */
3197         ses->server = server;
3198         if (server->dstaddr.ss_family == AF_INET6)
3199                 sprintf(ses->serverName, "%pI6", &addr6->sin6_addr);
3200         else
3201                 sprintf(ses->serverName, "%pI4", &addr->sin_addr);
3202
3203         if (volume_info->username) {
3204                 ses->user_name = kstrdup(volume_info->username, GFP_KERNEL);
3205                 if (!ses->user_name)
3206                         goto get_ses_fail;
3207         }
3208
3209         /* volume_info->password freed at unmount */
3210         if (volume_info->password) {
3211                 ses->password = kstrdup(volume_info->password, GFP_KERNEL);
3212                 if (!ses->password)
3213                         goto get_ses_fail;
3214         }
3215         if (volume_info->domainname) {
3216                 ses->domainName = kstrdup(volume_info->domainname, GFP_KERNEL);
3217                 if (!ses->domainName)
3218                         goto get_ses_fail;
3219         }
3220         if (volume_info->domainauto)
3221                 ses->domainAuto = volume_info->domainauto;
3222         ses->cred_uid = volume_info->cred_uid;
3223         ses->linux_uid = volume_info->linux_uid;
3224
3225         ses->sectype = volume_info->sectype;
3226         ses->sign = volume_info->sign;
3227
3228         mutex_lock(&ses->session_mutex);
3229         rc = cifs_negotiate_protocol(xid, ses);
3230         if (!rc)
3231                 rc = cifs_setup_session(xid, ses, volume_info->local_nls);
3232         mutex_unlock(&ses->session_mutex);
3233         if (rc)
3234                 goto get_ses_fail;
3235
3236         /* success, put it on the list */
3237         spin_lock(&cifs_tcp_ses_lock);
3238         list_add(&ses->smb_ses_list, &server->smb_ses_list);
3239         spin_unlock(&cifs_tcp_ses_lock);
3240
3241         free_xid(xid);
3242
3243         cifs_setup_ipc(ses, volume_info);
3244
3245         return ses;
3246
3247 get_ses_fail:
3248         sesInfoFree(ses);
3249         free_xid(xid);
3250         return ERR_PTR(rc);
3251 }
3252
3253 static int match_tcon(struct cifs_tcon *tcon, struct smb_vol *volume_info)
3254 {
3255         if (tcon->tidStatus == CifsExiting)
3256                 return 0;
3257         if (strncmp(tcon->treeName, volume_info->UNC, MAX_TREE_SIZE))
3258                 return 0;
3259         if (tcon->seal != volume_info->seal)
3260                 return 0;
3261         if (tcon->snapshot_time != volume_info->snapshot_time)
3262                 return 0;
3263         if (tcon->handle_timeout != volume_info->handle_timeout)
3264                 return 0;
3265         if (tcon->no_lease != volume_info->no_lease)
3266                 return 0;
3267         return 1;
3268 }
3269
3270 static struct cifs_tcon *
3271 cifs_find_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
3272 {
3273         struct list_head *tmp;
3274         struct cifs_tcon *tcon;
3275
3276         spin_lock(&cifs_tcp_ses_lock);
3277         list_for_each(tmp, &ses->tcon_list) {
3278                 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
3279                 if (!match_tcon(tcon, volume_info))
3280                         continue;
3281                 ++tcon->tc_count;
3282                 spin_unlock(&cifs_tcp_ses_lock);
3283                 return tcon;
3284         }
3285         spin_unlock(&cifs_tcp_ses_lock);
3286         return NULL;
3287 }
3288
3289 void
3290 cifs_put_tcon(struct cifs_tcon *tcon)
3291 {
3292         unsigned int xid;
3293         struct cifs_ses *ses;
3294
3295         /*
3296          * IPC tcon share the lifetime of their session and are
3297          * destroyed in the session put function
3298          */
3299         if (tcon == NULL || tcon->ipc)
3300                 return;
3301
3302         ses = tcon->ses;
3303         cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
3304         spin_lock(&cifs_tcp_ses_lock);
3305         if (--tcon->tc_count > 0) {
3306                 spin_unlock(&cifs_tcp_ses_lock);
3307                 return;
3308         }
3309
3310         list_del_init(&tcon->tcon_list);
3311         spin_unlock(&cifs_tcp_ses_lock);
3312
3313         xid = get_xid();
3314         if (ses->server->ops->tree_disconnect)
3315                 ses->server->ops->tree_disconnect(xid, tcon);
3316         _free_xid(xid);
3317
3318         cifs_fscache_release_super_cookie(tcon);
3319         tconInfoFree(tcon);
3320         cifs_put_smb_ses(ses);
3321 }
3322
3323 /**
3324  * cifs_get_tcon - get a tcon matching @volume_info data from @ses
3325  *
3326  * - tcon refcount is the number of mount points using the tcon.
3327  * - ses refcount is the number of tcon using the session.
3328  *
3329  * 1. This function assumes it is being called from cifs_mount() where
3330  *    we already got a session reference (ses refcount +1).
3331  *
3332  * 2. Since we're in the context of adding a mount point, the end
3333  *    result should be either:
3334  *
3335  * a) a new tcon already allocated with refcount=1 (1 mount point) and
3336  *    its session refcount incremented (1 new tcon). This +1 was
3337  *    already done in (1).
3338  *
3339  * b) an existing tcon with refcount+1 (add a mount point to it) and
3340  *    identical ses refcount (no new tcon). Because of (1) we need to
3341  *    decrement the ses refcount.
3342  */
3343 static struct cifs_tcon *
3344 cifs_get_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
3345 {
3346         int rc, xid;
3347         struct cifs_tcon *tcon;
3348
3349         tcon = cifs_find_tcon(ses, volume_info);
3350         if (tcon) {
3351                 /*
3352                  * tcon has refcount already incremented but we need to
3353                  * decrement extra ses reference gotten by caller (case b)
3354                  */
3355                 cifs_dbg(FYI, "Found match on UNC path\n");
3356                 cifs_put_smb_ses(ses);
3357                 return tcon;
3358         }
3359
3360         if (!ses->server->ops->tree_connect) {
3361                 rc = -ENOSYS;
3362                 goto out_fail;
3363         }
3364
3365         tcon = tconInfoAlloc();
3366         if (tcon == NULL) {
3367                 rc = -ENOMEM;
3368                 goto out_fail;
3369         }
3370
3371         if (volume_info->snapshot_time) {
3372                 if (ses->server->vals->protocol_id == 0) {
3373                         cifs_dbg(VFS,
3374                              "Use SMB2 or later for snapshot mount option\n");
3375                         rc = -EOPNOTSUPP;
3376                         goto out_fail;
3377                 } else
3378                         tcon->snapshot_time = volume_info->snapshot_time;
3379         }
3380
3381         if (volume_info->handle_timeout) {
3382                 if (ses->server->vals->protocol_id == 0) {
3383                         cifs_dbg(VFS,
3384                              "Use SMB2.1 or later for handle timeout option\n");
3385                         rc = -EOPNOTSUPP;
3386                         goto out_fail;
3387                 } else
3388                         tcon->handle_timeout = volume_info->handle_timeout;
3389         }
3390
3391         tcon->ses = ses;
3392         if (volume_info->password) {
3393                 tcon->password = kstrdup(volume_info->password, GFP_KERNEL);
3394                 if (!tcon->password) {
3395                         rc = -ENOMEM;
3396                         goto out_fail;
3397                 }
3398         }
3399
3400         if (volume_info->seal) {
3401                 if (ses->server->vals->protocol_id == 0) {
3402                         cifs_dbg(VFS,
3403                                  "SMB3 or later required for encryption\n");
3404                         rc = -EOPNOTSUPP;
3405                         goto out_fail;
3406                 } else if (tcon->ses->server->capabilities &
3407                                         SMB2_GLOBAL_CAP_ENCRYPTION)
3408                         tcon->seal = true;
3409                 else {
3410                         cifs_dbg(VFS, "Encryption is not supported on share\n");
3411                         rc = -EOPNOTSUPP;
3412                         goto out_fail;
3413                 }
3414         }
3415
3416         if (volume_info->linux_ext) {
3417                 if (ses->server->posix_ext_supported) {
3418                         tcon->posix_extensions = true;
3419                         printk_once(KERN_WARNING
3420                                 "SMB3.11 POSIX Extensions are experimental\n");
3421                 } else {
3422                         cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions.\n");
3423                         rc = -EOPNOTSUPP;
3424                         goto out_fail;
3425                 }
3426         }
3427
3428         /*
3429          * BB Do we need to wrap session_mutex around this TCon call and Unix
3430          * SetFS as we do on SessSetup and reconnect?
3431          */
3432         xid = get_xid();
3433         rc = ses->server->ops->tree_connect(xid, ses, volume_info->UNC, tcon,
3434                                             volume_info->local_nls);
3435         free_xid(xid);
3436         cifs_dbg(FYI, "Tcon rc = %d\n", rc);
3437         if (rc)
3438                 goto out_fail;
3439
3440         tcon->use_persistent = false;
3441         /* check if SMB2 or later, CIFS does not support persistent handles */
3442         if (volume_info->persistent) {
3443                 if (ses->server->vals->protocol_id == 0) {
3444                         cifs_dbg(VFS,
3445                              "SMB3 or later required for persistent handles\n");
3446                         rc = -EOPNOTSUPP;
3447                         goto out_fail;
3448                 } else if (ses->server->capabilities &
3449                            SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
3450                         tcon->use_persistent = true;
3451                 else /* persistent handles requested but not supported */ {
3452                         cifs_dbg(VFS,
3453                                 "Persistent handles not supported on share\n");
3454                         rc = -EOPNOTSUPP;
3455                         goto out_fail;
3456                 }
3457         } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
3458              && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
3459              && (volume_info->nopersistent == false)) {
3460                 cifs_dbg(FYI, "enabling persistent handles\n");
3461                 tcon->use_persistent = true;
3462         } else if (volume_info->resilient) {
3463                 if (ses->server->vals->protocol_id == 0) {
3464                         cifs_dbg(VFS,
3465                              "SMB2.1 or later required for resilient handles\n");
3466                         rc = -EOPNOTSUPP;
3467                         goto out_fail;
3468                 }
3469                 tcon->use_resilient = true;
3470         }
3471
3472         /*
3473          * We can have only one retry value for a connection to a share so for
3474          * resources mounted more than once to the same server share the last
3475          * value passed in for the retry flag is used.
3476          */
3477         tcon->retry = volume_info->retry;
3478         tcon->nocase = volume_info->nocase;
3479         tcon->nohandlecache = volume_info->nohandlecache;
3480         tcon->local_lease = volume_info->local_lease;
3481         tcon->no_lease = volume_info->no_lease;
3482         INIT_LIST_HEAD(&tcon->pending_opens);
3483
3484         spin_lock(&cifs_tcp_ses_lock);
3485         list_add(&tcon->tcon_list, &ses->tcon_list);
3486         spin_unlock(&cifs_tcp_ses_lock);
3487
3488         cifs_fscache_get_super_cookie(tcon);
3489
3490         return tcon;
3491
3492 out_fail:
3493         tconInfoFree(tcon);
3494         return ERR_PTR(rc);
3495 }
3496
3497 void
3498 cifs_put_tlink(struct tcon_link *tlink)
3499 {
3500         if (!tlink || IS_ERR(tlink))
3501                 return;
3502
3503         if (!atomic_dec_and_test(&tlink->tl_count) ||
3504             test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
3505                 tlink->tl_time = jiffies;
3506                 return;
3507         }
3508
3509         if (!IS_ERR(tlink_tcon(tlink)))
3510                 cifs_put_tcon(tlink_tcon(tlink));
3511         kfree(tlink);
3512         return;
3513 }
3514
3515 static int
3516 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3517 {
3518         struct cifs_sb_info *old = CIFS_SB(sb);
3519         struct cifs_sb_info *new = mnt_data->cifs_sb;
3520         unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
3521         unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
3522
3523         if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
3524                 return 0;
3525
3526         if (old->mnt_cifs_serverino_autodisabled)
3527                 newflags &= ~CIFS_MOUNT_SERVER_INUM;
3528
3529         if (oldflags != newflags)
3530                 return 0;
3531
3532         /*
3533          * We want to share sb only if we don't specify an r/wsize or
3534          * specified r/wsize is greater than or equal to existing one.
3535          */
3536         if (new->wsize && new->wsize < old->wsize)
3537                 return 0;
3538
3539         if (new->rsize && new->rsize < old->rsize)
3540                 return 0;
3541
3542         if (!uid_eq(old->mnt_uid, new->mnt_uid) || !gid_eq(old->mnt_gid, new->mnt_gid))
3543                 return 0;
3544
3545         if (old->mnt_file_mode != new->mnt_file_mode ||
3546             old->mnt_dir_mode != new->mnt_dir_mode)
3547                 return 0;
3548
3549         if (strcmp(old->local_nls->charset, new->local_nls->charset))
3550                 return 0;
3551
3552         if (old->actimeo != new->actimeo)
3553                 return 0;
3554
3555         return 1;
3556 }
3557
3558 static int
3559 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3560 {
3561         struct cifs_sb_info *old = CIFS_SB(sb);
3562         struct cifs_sb_info *new = mnt_data->cifs_sb;
3563         bool old_set = old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH;
3564         bool new_set = new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH;
3565
3566         if (old_set && new_set && !strcmp(new->prepath, old->prepath))
3567                 return 1;
3568         else if (!old_set && !new_set)
3569                 return 1;
3570
3571         return 0;
3572 }
3573
3574 int
3575 cifs_match_super(struct super_block *sb, void *data)
3576 {
3577         struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
3578         struct smb_vol *volume_info;
3579         struct cifs_sb_info *cifs_sb;
3580         struct TCP_Server_Info *tcp_srv;
3581         struct cifs_ses *ses;
3582         struct cifs_tcon *tcon;
3583         struct tcon_link *tlink;
3584         int rc = 0;
3585
3586         spin_lock(&cifs_tcp_ses_lock);
3587         cifs_sb = CIFS_SB(sb);
3588         tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3589         if (IS_ERR(tlink)) {
3590                 spin_unlock(&cifs_tcp_ses_lock);
3591                 return rc;
3592         }
3593         tcon = tlink_tcon(tlink);
3594         ses = tcon->ses;
3595         tcp_srv = ses->server;
3596
3597         volume_info = mnt_data->vol;
3598
3599         if (!match_server(tcp_srv, volume_info) ||
3600             !match_session(ses, volume_info) ||
3601             !match_tcon(tcon, volume_info) ||
3602             !match_prepath(sb, mnt_data)) {
3603                 rc = 0;
3604                 goto out;
3605         }
3606
3607         rc = compare_mount_options(sb, mnt_data);
3608 out:
3609         spin_unlock(&cifs_tcp_ses_lock);
3610         cifs_put_tlink(tlink);
3611         return rc;
3612 }
3613
3614 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3615 static struct lock_class_key cifs_key[2];
3616 static struct lock_class_key cifs_slock_key[2];
3617
3618 static inline void
3619 cifs_reclassify_socket4(struct socket *sock)
3620 {
3621         struct sock *sk = sock->sk;
3622         BUG_ON(!sock_allow_reclassification(sk));
3623         sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
3624                 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
3625 }
3626
3627 static inline void
3628 cifs_reclassify_socket6(struct socket *sock)
3629 {
3630         struct sock *sk = sock->sk;
3631         BUG_ON(!sock_allow_reclassification(sk));
3632         sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
3633                 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3634 }
3635 #else
3636 static inline void
3637 cifs_reclassify_socket4(struct socket *sock)
3638 {
3639 }
3640
3641 static inline void
3642 cifs_reclassify_socket6(struct socket *sock)
3643 {
3644 }
3645 #endif
3646
3647 /* See RFC1001 section 14 on representation of Netbios names */
3648 static void rfc1002mangle(char *target, char *source, unsigned int length)
3649 {
3650         unsigned int i, j;
3651
3652         for (i = 0, j = 0; i < (length); i++) {
3653                 /* mask a nibble at a time and encode */
3654                 target[j] = 'A' + (0x0F & (source[i] >> 4));
3655                 target[j+1] = 'A' + (0x0F & source[i]);
3656                 j += 2;
3657         }
3658
3659 }
3660
3661 static int
3662 bind_socket(struct TCP_Server_Info *server)
3663 {
3664         int rc = 0;
3665         if (server->srcaddr.ss_family != AF_UNSPEC) {
3666                 /* Bind to the specified local IP address */
3667                 struct socket *socket = server->ssocket;
3668                 rc = socket->ops->bind(socket,
3669                                        (struct sockaddr *) &server->srcaddr,
3670                                        sizeof(server->srcaddr));
3671                 if (rc < 0) {
3672                         struct sockaddr_in *saddr4;
3673                         struct sockaddr_in6 *saddr6;
3674                         saddr4 = (struct sockaddr_in *)&server->srcaddr;
3675                         saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3676                         if (saddr6->sin6_family == AF_INET6)
3677                                 cifs_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3678                                          &saddr6->sin6_addr, rc);
3679                         else
3680                                 cifs_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3681                                          &saddr4->sin_addr.s_addr, rc);
3682                 }
3683         }
3684         return rc;
3685 }
3686
3687 static int
3688 ip_rfc1001_connect(struct TCP_Server_Info *server)
3689 {
3690         int rc = 0;
3691         /*
3692          * some servers require RFC1001 sessinit before sending
3693          * negprot - BB check reconnection in case where second
3694          * sessinit is sent but no second negprot
3695          */
3696         struct rfc1002_session_packet *ses_init_buf;
3697         struct smb_hdr *smb_buf;
3698         ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
3699                                GFP_KERNEL);
3700         if (ses_init_buf) {
3701                 ses_init_buf->trailer.session_req.called_len = 32;
3702
3703                 if (server->server_RFC1001_name[0] != 0)
3704                         rfc1002mangle(ses_init_buf->trailer.
3705                                       session_req.called_name,
3706                                       server->server_RFC1001_name,
3707                                       RFC1001_NAME_LEN_WITH_NULL);
3708                 else
3709                         rfc1002mangle(ses_init_buf->trailer.
3710                                       session_req.called_name,
3711                                       DEFAULT_CIFS_CALLED_NAME,
3712                                       RFC1001_NAME_LEN_WITH_NULL);
3713
3714                 ses_init_buf->trailer.session_req.calling_len = 32;
3715
3716                 /*
3717                  * calling name ends in null (byte 16) from old smb
3718                  * convention.
3719                  */
3720                 if (server->workstation_RFC1001_name[0] != 0)
3721                         rfc1002mangle(ses_init_buf->trailer.
3722                                       session_req.calling_name,
3723                                       server->workstation_RFC1001_name,
3724                                       RFC1001_NAME_LEN_WITH_NULL);
3725                 else
3726                         rfc1002mangle(ses_init_buf->trailer.
3727                                       session_req.calling_name,
3728                                       "LINUX_CIFS_CLNT",
3729                                       RFC1001_NAME_LEN_WITH_NULL);
3730
3731                 ses_init_buf->trailer.session_req.scope1 = 0;
3732                 ses_init_buf->trailer.session_req.scope2 = 0;
3733                 smb_buf = (struct smb_hdr *)ses_init_buf;
3734
3735                 /* sizeof RFC1002_SESSION_REQUEST with no scope */
3736                 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
3737                 rc = smb_send(server, smb_buf, 0x44);
3738                 kfree(ses_init_buf);
3739                 /*
3740                  * RFC1001 layer in at least one server
3741                  * requires very short break before negprot
3742                  * presumably because not expecting negprot
3743                  * to follow so fast.  This is a simple
3744                  * solution that works without
3745                  * complicating the code and causes no
3746                  * significant slowing down on mount
3747                  * for everyone else
3748                  */
3749                 usleep_range(1000, 2000);
3750         }
3751         /*
3752          * else the negprot may still work without this
3753          * even though malloc failed
3754          */
3755
3756         return rc;
3757 }
3758
3759 static int
3760 generic_ip_connect(struct TCP_Server_Info *server)
3761 {
3762         int rc = 0;
3763         __be16 sport;
3764         int slen, sfamily;
3765         struct socket *socket = server->ssocket;
3766         struct sockaddr *saddr;
3767
3768         saddr = (struct sockaddr *) &server->dstaddr;
3769
3770         if (server->dstaddr.ss_family == AF_INET6) {
3771                 sport = ((struct sockaddr_in6 *) saddr)->sin6_port;
3772                 slen = sizeof(struct sockaddr_in6);
3773                 sfamily = AF_INET6;
3774         } else {
3775                 sport = ((struct sockaddr_in *) saddr)->sin_port;
3776                 slen = sizeof(struct sockaddr_in);
3777                 sfamily = AF_INET;
3778         }
3779
3780         if (socket == NULL) {
3781                 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3782                                    IPPROTO_TCP, &socket, 1);
3783                 if (rc < 0) {
3784                         cifs_dbg(VFS, "Error %d creating socket\n", rc);
3785                         server->ssocket = NULL;
3786                         return rc;
3787                 }
3788
3789                 /* BB other socket options to set KEEPALIVE, NODELAY? */
3790                 cifs_dbg(FYI, "Socket created\n");
3791                 server->ssocket = socket;
3792                 socket->sk->sk_allocation = GFP_NOFS;
3793                 if (sfamily == AF_INET6)
3794                         cifs_reclassify_socket6(socket);
3795                 else
3796                         cifs_reclassify_socket4(socket);
3797         }
3798
3799         rc = bind_socket(server);
3800         if (rc < 0)
3801                 return rc;
3802
3803         /*
3804          * Eventually check for other socket options to change from
3805          * the default. sock_setsockopt not used because it expects
3806          * user space buffer
3807          */
3808         socket->sk->sk_rcvtimeo = 7 * HZ;
3809         socket->sk->sk_sndtimeo = 5 * HZ;
3810
3811         /* make the bufsizes depend on wsize/rsize and max requests */
3812         if (server->noautotune) {
3813                 if (socket->sk->sk_sndbuf < (200 * 1024))
3814                         socket->sk->sk_sndbuf = 200 * 1024;
3815                 if (socket->sk->sk_rcvbuf < (140 * 1024))
3816                         socket->sk->sk_rcvbuf = 140 * 1024;
3817         }
3818
3819         if (server->tcp_nodelay) {
3820                 int val = 1;
3821                 rc = kernel_setsockopt(socket, SOL_TCP, TCP_NODELAY,
3822                                 (char *)&val, sizeof(val));
3823                 if (rc)
3824                         cifs_dbg(FYI, "set TCP_NODELAY socket option error %d\n",
3825                                  rc);
3826         }
3827
3828         cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3829                  socket->sk->sk_sndbuf,
3830                  socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3831
3832         rc = socket->ops->connect(socket, saddr, slen, 0);
3833         if (rc < 0) {
3834                 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3835                 sock_release(socket);
3836                 server->ssocket = NULL;
3837                 return rc;
3838         }
3839
3840         if (sport == htons(RFC1001_PORT))
3841                 rc = ip_rfc1001_connect(server);
3842
3843         return rc;
3844 }
3845
3846 static int
3847 ip_connect(struct TCP_Server_Info *server)
3848 {
3849         __be16 *sport;
3850         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3851         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3852
3853         if (server->dstaddr.ss_family == AF_INET6)
3854                 sport = &addr6->sin6_port;
3855         else
3856                 sport = &addr->sin_port;
3857
3858         if (*sport == 0) {
3859                 int rc;
3860
3861                 /* try with 445 port at first */
3862                 *sport = htons(CIFS_PORT);
3863
3864                 rc = generic_ip_connect(server);
3865                 if (rc >= 0)
3866                         return rc;
3867
3868                 /* if it failed, try with 139 port */
3869                 *sport = htons(RFC1001_PORT);
3870         }
3871
3872         return generic_ip_connect(server);
3873 }
3874
3875 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3876                           struct cifs_sb_info *cifs_sb, struct smb_vol *vol_info)
3877 {
3878         /* if we are reconnecting then should we check to see if
3879          * any requested capabilities changed locally e.g. via
3880          * remount but we can not do much about it here
3881          * if they have (even if we could detect it by the following)
3882          * Perhaps we could add a backpointer to array of sb from tcon
3883          * or if we change to make all sb to same share the same
3884          * sb as NFS - then we only have one backpointer to sb.
3885          * What if we wanted to mount the server share twice once with
3886          * and once without posixacls or posix paths? */
3887         __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3888
3889         if (vol_info && vol_info->no_linux_ext) {
3890                 tcon->fsUnixInfo.Capability = 0;
3891                 tcon->unix_ext = 0; /* Unix Extensions disabled */
3892                 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3893                 return;
3894         } else if (vol_info)
3895                 tcon->unix_ext = 1; /* Unix Extensions supported */
3896
3897         if (tcon->unix_ext == 0) {
3898                 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3899                 return;
3900         }
3901
3902         if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3903                 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3904                 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3905                 /* check for reconnect case in which we do not
3906                    want to change the mount behavior if we can avoid it */
3907                 if (vol_info == NULL) {
3908                         /* turn off POSIX ACL and PATHNAMES if not set
3909                            originally at mount time */
3910                         if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3911                                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3912                         if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3913                                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3914                                         cifs_dbg(VFS, "POSIXPATH support change\n");
3915                                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3916                         } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3917                                 cifs_dbg(VFS, "possible reconnect error\n");
3918                                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3919                         }
3920                 }
3921
3922                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3923                         cifs_dbg(VFS, "per-share encryption not supported yet\n");
3924
3925                 cap &= CIFS_UNIX_CAP_MASK;
3926                 if (vol_info && vol_info->no_psx_acl)
3927                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3928                 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3929                         cifs_dbg(FYI, "negotiated posix acl support\n");
3930                         if (cifs_sb)
3931                                 cifs_sb->mnt_cifs_flags |=
3932                                         CIFS_MOUNT_POSIXACL;
3933                 }
3934
3935                 if (vol_info && vol_info->posix_paths == 0)
3936                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3937                 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3938                         cifs_dbg(FYI, "negotiate posix pathnames\n");
3939                         if (cifs_sb)
3940                                 cifs_sb->mnt_cifs_flags |=
3941                                         CIFS_MOUNT_POSIX_PATHS;
3942                 }
3943
3944                 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3945 #ifdef CONFIG_CIFS_DEBUG2
3946                 if (cap & CIFS_UNIX_FCNTL_CAP)
3947                         cifs_dbg(FYI, "FCNTL cap\n");
3948                 if (cap & CIFS_UNIX_EXTATTR_CAP)
3949                         cifs_dbg(FYI, "EXTATTR cap\n");
3950                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3951                         cifs_dbg(FYI, "POSIX path cap\n");
3952                 if (cap & CIFS_UNIX_XATTR_CAP)
3953                         cifs_dbg(FYI, "XATTR cap\n");
3954                 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3955                         cifs_dbg(FYI, "POSIX ACL cap\n");
3956                 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3957                         cifs_dbg(FYI, "very large read cap\n");
3958                 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3959                         cifs_dbg(FYI, "very large write cap\n");
3960                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3961                         cifs_dbg(FYI, "transport encryption cap\n");
3962                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3963                         cifs_dbg(FYI, "mandatory transport encryption cap\n");
3964 #endif /* CIFS_DEBUG2 */
3965                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3966                         if (vol_info == NULL) {
3967                                 cifs_dbg(FYI, "resetting capabilities failed\n");
3968                         } else
3969                                 cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
3970
3971                 }
3972         }
3973 }
3974
3975 int cifs_setup_cifs_sb(struct smb_vol *pvolume_info,
3976                         struct cifs_sb_info *cifs_sb)
3977 {
3978         INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3979
3980         spin_lock_init(&cifs_sb->tlink_tree_lock);
3981         cifs_sb->tlink_tree = RB_ROOT;
3982
3983         cifs_sb->bsize = pvolume_info->bsize;
3984         /*
3985          * Temporarily set r/wsize for matching superblock. If we end up using
3986          * new sb then client will later negotiate it downward if needed.
3987          */
3988         cifs_sb->rsize = pvolume_info->rsize;
3989         cifs_sb->wsize = pvolume_info->wsize;
3990
3991         cifs_sb->mnt_uid = pvolume_info->linux_uid;
3992         cifs_sb->mnt_gid = pvolume_info->linux_gid;
3993         cifs_sb->mnt_file_mode = pvolume_info->file_mode;
3994         cifs_sb->mnt_dir_mode = pvolume_info->dir_mode;
3995         cifs_dbg(FYI, "file mode: 0x%hx  dir mode: 0x%hx\n",
3996                  cifs_sb->mnt_file_mode, cifs_sb->mnt_dir_mode);
3997
3998         cifs_sb->actimeo = pvolume_info->actimeo;
3999         cifs_sb->local_nls = pvolume_info->local_nls;
4000
4001         if (pvolume_info->nodfs)
4002                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_DFS;
4003         if (pvolume_info->noperm)
4004                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
4005         if (pvolume_info->setuids)
4006                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
4007         if (pvolume_info->setuidfromacl)
4008                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UID_FROM_ACL;
4009         if (pvolume_info->server_ino)
4010                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
4011         if (pvolume_info->remap)
4012                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SFM_CHR;
4013         if (pvolume_info->sfu_remap)
4014                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
4015         if (pvolume_info->no_xattr)
4016                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
4017         if (pvolume_info->sfu_emul)
4018                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
4019         if (pvolume_info->nobrl)
4020                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
4021         if (pvolume_info->nohandlecache)
4022                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_HANDLE_CACHE;
4023         if (pvolume_info->nostrictsync)
4024                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOSSYNC;
4025         if (pvolume_info->mand_lock)
4026                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOPOSIXBRL;
4027         if (pvolume_info->rwpidforward)
4028                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RWPIDFORWARD;
4029         if (pvolume_info->mode_ace)
4030                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MODE_FROM_SID;
4031         if (pvolume_info->cifs_acl)
4032                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
4033         if (pvolume_info->backupuid_specified) {
4034                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPUID;
4035                 cifs_sb->mnt_backupuid = pvolume_info->backupuid;
4036         }
4037         if (pvolume_info->backupgid_specified) {
4038                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPGID;
4039                 cifs_sb->mnt_backupgid = pvolume_info->backupgid;
4040         }
4041         if (pvolume_info->override_uid)
4042                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_UID;
4043         if (pvolume_info->override_gid)
4044                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_GID;
4045         if (pvolume_info->dynperm)
4046                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DYNPERM;
4047         if (pvolume_info->fsc)
4048                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_FSCACHE;
4049         if (pvolume_info->multiuser)
4050                 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_MULTIUSER |
4051                                             CIFS_MOUNT_NO_PERM);
4052         if (pvolume_info->strict_io)
4053                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_STRICT_IO;
4054         if (pvolume_info->direct_io) {
4055                 cifs_dbg(FYI, "mounting share using direct i/o\n");
4056                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
4057         }
4058         if (pvolume_info->mfsymlinks) {
4059                 if (pvolume_info->sfu_emul) {
4060                         /*
4061                          * Our SFU ("Services for Unix" emulation does not allow
4062                          * creating symlinks but does allow reading existing SFU
4063                          * symlinks (it does allow both creating and reading SFU
4064                          * style mknod and FIFOs though). When "mfsymlinks" and
4065                          * "sfu" are both enabled at the same time, it allows
4066                          * reading both types of symlinks, but will only create
4067                          * them with mfsymlinks format. This allows better
4068                          * Apple compatibility (probably better for Samba too)
4069                          * while still recognizing old Windows style symlinks.
4070                          */
4071                         cifs_dbg(VFS, "mount options mfsymlinks and sfu both enabled\n");
4072                 }
4073                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MF_SYMLINKS;
4074         }
4075
4076         if ((pvolume_info->cifs_acl) && (pvolume_info->dynperm))
4077                 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
4078
4079         if (pvolume_info->prepath) {
4080                 cifs_sb->prepath = kstrdup(pvolume_info->prepath, GFP_KERNEL);
4081                 if (cifs_sb->prepath == NULL)
4082                         return -ENOMEM;
4083         }
4084
4085         return 0;
4086 }
4087
4088 void
4089 cifs_cleanup_volume_info_contents(struct smb_vol *volume_info)
4090 {
4091         kfree(volume_info->username);
4092         kzfree(volume_info->password);
4093         kfree(volume_info->UNC);
4094         kfree(volume_info->domainname);
4095         kfree(volume_info->iocharset);
4096         kfree(volume_info->prepath);
4097 }
4098
4099 void
4100 cifs_cleanup_volume_info(struct smb_vol *volume_info)
4101 {
4102         if (!volume_info)
4103                 return;
4104         cifs_cleanup_volume_info_contents(volume_info);
4105         kfree(volume_info);
4106 }
4107
4108 /* Release all succeed connections */
4109 static inline void mount_put_conns(struct cifs_sb_info *cifs_sb,
4110                                    unsigned int xid,
4111                                    struct TCP_Server_Info *server,
4112                                    struct cifs_ses *ses, struct cifs_tcon *tcon)
4113 {
4114         int rc = 0;
4115
4116         if (tcon)
4117                 cifs_put_tcon(tcon);
4118         else if (ses)
4119                 cifs_put_smb_ses(ses);
4120         else if (server)
4121                 cifs_put_tcp_session(server, 0);
4122         cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
4123         free_xid(xid);
4124 }
4125
4126 /* Get connections for tcp, ses and tcon */
4127 static int mount_get_conns(struct smb_vol *vol, struct cifs_sb_info *cifs_sb,
4128                            unsigned int *xid,
4129                            struct TCP_Server_Info **nserver,
4130                            struct cifs_ses **nses, struct cifs_tcon **ntcon)
4131 {
4132         int rc = 0;
4133         struct TCP_Server_Info *server;
4134         struct cifs_ses *ses;
4135         struct cifs_tcon *tcon;
4136
4137         *nserver = NULL;
4138         *nses = NULL;
4139         *ntcon = NULL;
4140
4141         *xid = get_xid();
4142
4143         /* get a reference to a tcp session */
4144         server = cifs_get_tcp_session(vol);
4145         if (IS_ERR(server)) {
4146                 rc = PTR_ERR(server);
4147                 return rc;
4148         }
4149
4150         *nserver = server;
4151
4152         if ((vol->max_credits < 20) || (vol->max_credits > 60000))
4153                 server->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
4154         else
4155                 server->max_credits = vol->max_credits;
4156
4157         /* get a reference to a SMB session */
4158         ses = cifs_get_smb_ses(server, vol);
4159         if (IS_ERR(ses)) {
4160                 rc = PTR_ERR(ses);
4161                 return rc;
4162         }
4163
4164         *nses = ses;
4165
4166         if ((vol->persistent == true) && (!(ses->server->capabilities &
4167                                             SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
4168                 cifs_dbg(VFS, "persistent handles not supported by server\n");
4169                 return -EOPNOTSUPP;
4170         }
4171
4172         /* search for existing tcon to this server share */
4173         tcon = cifs_get_tcon(ses, vol);
4174         if (IS_ERR(tcon)) {
4175                 rc = PTR_ERR(tcon);
4176                 return rc;
4177         }
4178
4179         *ntcon = tcon;
4180
4181         /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
4182         if (tcon->posix_extensions)
4183                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
4184
4185         /* tell server which Unix caps we support */
4186         if (cap_unix(tcon->ses)) {
4187                 /*
4188                  * reset of caps checks mount to see if unix extensions disabled
4189                  * for just this mount.
4190                  */
4191                 reset_cifs_unix_caps(*xid, tcon, cifs_sb, vol);
4192                 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
4193                     (le64_to_cpu(tcon->fsUnixInfo.Capability) &
4194                      CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP))
4195                         return -EACCES;
4196         } else
4197                 tcon->unix_ext = 0; /* server does not support them */
4198
4199         /* do not care if a following call succeed - informational */
4200         if (!tcon->pipe && server->ops->qfs_tcon)
4201                 server->ops->qfs_tcon(*xid, tcon);
4202
4203         cifs_sb->wsize = server->ops->negotiate_wsize(tcon, vol);
4204         cifs_sb->rsize = server->ops->negotiate_rsize(tcon, vol);
4205
4206         return 0;
4207 }
4208
4209 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
4210                              struct cifs_tcon *tcon)
4211 {
4212         struct tcon_link *tlink;
4213
4214         /* hang the tcon off of the superblock */
4215         tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4216         if (tlink == NULL)
4217                 return -ENOMEM;
4218
4219         tlink->tl_uid = ses->linux_uid;
4220         tlink->tl_tcon = tcon;
4221         tlink->tl_time = jiffies;
4222         set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
4223         set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4224
4225         cifs_sb->master_tlink = tlink;
4226         spin_lock(&cifs_sb->tlink_tree_lock);
4227         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4228         spin_unlock(&cifs_sb->tlink_tree_lock);
4229
4230         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4231                                 TLINK_IDLE_EXPIRE);
4232         return 0;
4233 }
4234
4235 #ifdef CONFIG_CIFS_DFS_UPCALL
4236 /*
4237  * cifs_build_path_to_root returns full path to root when we do not have an
4238  * exiting connection (tcon)
4239  */
4240 static char *
4241 build_unc_path_to_root(const struct smb_vol *vol,
4242                        const struct cifs_sb_info *cifs_sb, bool useppath)
4243 {
4244         char *full_path, *pos;
4245         unsigned int pplen = useppath && vol->prepath ?
4246                 strlen(vol->prepath) + 1 : 0;
4247         unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1);
4248
4249         if (unc_len > MAX_TREE_SIZE)
4250                 return ERR_PTR(-EINVAL);
4251
4252         full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
4253         if (full_path == NULL)
4254                 return ERR_PTR(-ENOMEM);
4255
4256         memcpy(full_path, vol->UNC, unc_len);
4257         pos = full_path + unc_len;
4258
4259         if (pplen) {
4260                 *pos = CIFS_DIR_SEP(cifs_sb);
4261                 memcpy(pos + 1, vol->prepath, pplen);
4262                 pos += pplen;
4263         }
4264
4265         *pos = '\0'; /* add trailing null */
4266         convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
4267         cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
4268         return full_path;
4269 }
4270
4271 /**
4272  * expand_dfs_referral - Perform a dfs referral query and update the cifs_sb
4273  *
4274  *
4275  * If a referral is found, cifs_sb->mountdata will be (re-)allocated
4276  * to a string containing updated options for the submount.  Otherwise it
4277  * will be left untouched.
4278  *
4279  * Returns the rc from get_dfs_path to the caller, which can be used to
4280  * determine whether there were referrals.
4281  */
4282 static int
4283 expand_dfs_referral(const unsigned int xid, struct cifs_ses *ses,
4284                     struct smb_vol *volume_info, struct cifs_sb_info *cifs_sb,
4285                     int check_prefix)
4286 {
4287         int rc;
4288         struct dfs_info3_param referral = {0};
4289         char *full_path = NULL, *ref_path = NULL, *mdata = NULL;
4290
4291         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS)
4292                 return -EREMOTE;
4293
4294         full_path = build_unc_path_to_root(volume_info, cifs_sb, true);
4295         if (IS_ERR(full_path))
4296                 return PTR_ERR(full_path);
4297
4298         /* For DFS paths, skip the first '\' of the UNC */
4299         ref_path = check_prefix ? full_path + 1 : volume_info->UNC + 1;
4300
4301         rc = dfs_cache_find(xid, ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
4302                             ref_path, &referral, NULL);
4303         if (!rc) {
4304                 char *fake_devname = NULL;
4305
4306                 mdata = cifs_compose_mount_options(cifs_sb->mountdata,
4307                                                    full_path + 1, &referral,
4308                                                    &fake_devname);
4309                 free_dfs_info_param(&referral);
4310
4311                 if (IS_ERR(mdata)) {
4312                         rc = PTR_ERR(mdata);
4313                         mdata = NULL;
4314                 } else {
4315                         cifs_cleanup_volume_info_contents(volume_info);
4316                         rc = cifs_setup_volume_info(volume_info, mdata,
4317                                                     fake_devname, false);
4318                 }
4319                 kfree(fake_devname);
4320                 kfree(cifs_sb->mountdata);
4321                 cifs_sb->mountdata = mdata;
4322         }
4323         kfree(full_path);
4324         return rc;
4325 }
4326
4327 static inline int get_next_dfs_tgt(const char *path,
4328                                    struct dfs_cache_tgt_list *tgt_list,
4329                                    struct dfs_cache_tgt_iterator **tgt_it)
4330 {
4331         if (!*tgt_it)
4332                 *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
4333         else
4334                 *tgt_it = dfs_cache_get_next_tgt(tgt_list, *tgt_it);
4335         return !*tgt_it ? -EHOSTDOWN : 0;
4336 }
4337
4338 static int update_vol_info(const struct dfs_cache_tgt_iterator *tgt_it,
4339                            struct smb_vol *fake_vol, struct smb_vol *vol)
4340 {
4341         const char *tgt = dfs_cache_get_tgt_name(tgt_it);
4342         int len = strlen(tgt) + 2;
4343         char *new_unc;
4344
4345         new_unc = kmalloc(len, GFP_KERNEL);
4346         if (!new_unc)
4347                 return -ENOMEM;
4348         scnprintf(new_unc, len, "\\%s", tgt);
4349
4350         kfree(vol->UNC);
4351         vol->UNC = new_unc;
4352
4353         if (fake_vol->prepath) {
4354                 kfree(vol->prepath);
4355                 vol->prepath = fake_vol->prepath;
4356                 fake_vol->prepath = NULL;
4357         }
4358         memcpy(&vol->dstaddr, &fake_vol->dstaddr, sizeof(vol->dstaddr));
4359
4360         return 0;
4361 }
4362
4363 static int setup_dfs_tgt_conn(const char *path,
4364                               const struct dfs_cache_tgt_iterator *tgt_it,
4365                               struct cifs_sb_info *cifs_sb,
4366                               struct smb_vol *vol,
4367                               unsigned int *xid,
4368                               struct TCP_Server_Info **server,
4369                               struct cifs_ses **ses,
4370                               struct cifs_tcon **tcon)
4371 {
4372         int rc;
4373         struct dfs_info3_param ref = {0};
4374         char *mdata = NULL, *fake_devname = NULL;
4375         struct smb_vol fake_vol = {0};
4376
4377         cifs_dbg(FYI, "%s: dfs path: %s\n", __func__, path);
4378
4379         rc = dfs_cache_get_tgt_referral(path, tgt_it, &ref);
4380         if (rc)
4381                 return rc;
4382
4383         mdata = cifs_compose_mount_options(cifs_sb->mountdata, path, &ref,
4384                                            &fake_devname);
4385         free_dfs_info_param(&ref);
4386
4387         if (IS_ERR(mdata)) {
4388                 rc = PTR_ERR(mdata);
4389                 mdata = NULL;
4390         } else {
4391                 cifs_dbg(FYI, "%s: fake_devname: %s\n", __func__, fake_devname);
4392                 rc = cifs_setup_volume_info(&fake_vol, mdata, fake_devname,
4393                                             false);
4394         }
4395         kfree(mdata);
4396         kfree(fake_devname);
4397
4398         if (!rc) {
4399                 /*
4400                  * We use a 'fake_vol' here because we need pass it down to the
4401                  * mount_{get,put} functions to test connection against new DFS
4402                  * targets.
4403                  */
4404                 mount_put_conns(cifs_sb, *xid, *server, *ses, *tcon);
4405                 rc = mount_get_conns(&fake_vol, cifs_sb, xid, server, ses,
4406                                      tcon);
4407                 if (!rc) {
4408                         /*
4409                          * We were able to connect to new target server.
4410                          * Update current volume info with new target server.
4411                          */
4412                         rc = update_vol_info(tgt_it, &fake_vol, vol);
4413                 }
4414         }
4415         cifs_cleanup_volume_info_contents(&fake_vol);
4416         return rc;
4417 }
4418
4419 static int mount_do_dfs_failover(const char *path,
4420                                  struct cifs_sb_info *cifs_sb,
4421                                  struct smb_vol *vol,
4422                                  struct cifs_ses *root_ses,
4423                                  unsigned int *xid,
4424                                  struct TCP_Server_Info **server,
4425                                  struct cifs_ses **ses,
4426                                  struct cifs_tcon **tcon)
4427 {
4428         int rc;
4429         struct dfs_cache_tgt_list tgt_list;
4430         struct dfs_cache_tgt_iterator *tgt_it = NULL;
4431
4432         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS)
4433                 return -EOPNOTSUPP;
4434
4435         rc = dfs_cache_noreq_find(path, NULL, &tgt_list);
4436         if (rc)
4437                 return rc;
4438
4439         for (;;) {
4440                 /* Get next DFS target server - if any */
4441                 rc = get_next_dfs_tgt(path, &tgt_list, &tgt_it);
4442                 if (rc)
4443                         break;
4444                 /* Connect to next DFS target */
4445                 rc = setup_dfs_tgt_conn(path, tgt_it, cifs_sb, vol, xid, server,
4446                                         ses, tcon);
4447                 if (!rc || rc == -EACCES || rc == -EOPNOTSUPP)
4448                         break;
4449         }
4450         if (!rc) {
4451                 /*
4452                  * Update DFS target hint in DFS referral cache with the target
4453                  * server we successfully reconnected to.
4454                  */
4455                 rc = dfs_cache_update_tgthint(*xid, root_ses ? root_ses : *ses,
4456                                               cifs_sb->local_nls,
4457                                               cifs_remap(cifs_sb), path,
4458                                               tgt_it);
4459         }
4460         dfs_cache_free_tgts(&tgt_list);
4461         return rc;
4462 }
4463 #endif
4464
4465 int
4466 cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
4467                         const char *devname, bool is_smb3)
4468 {
4469         int rc = 0;
4470
4471         if (cifs_parse_mount_options(mount_data, devname, volume_info, is_smb3))
4472                 return -EINVAL;
4473
4474         if (volume_info->nullauth) {
4475                 cifs_dbg(FYI, "Anonymous login\n");
4476                 kfree(volume_info->username);
4477                 volume_info->username = NULL;
4478         } else if (volume_info->username) {
4479                 /* BB fixme parse for domain name here */
4480                 cifs_dbg(FYI, "Username: %s\n", volume_info->username);
4481         } else {
4482                 cifs_dbg(VFS, "No username specified\n");
4483         /* In userspace mount helper we can get user name from alternate
4484            locations such as env variables and files on disk */
4485                 return -EINVAL;
4486         }
4487
4488         /* this is needed for ASCII cp to Unicode converts */
4489         if (volume_info->iocharset == NULL) {
4490                 /* load_nls_default cannot return null */
4491                 volume_info->local_nls = load_nls_default();
4492         } else {
4493                 volume_info->local_nls = load_nls(volume_info->iocharset);
4494                 if (volume_info->local_nls == NULL) {
4495                         cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
4496                                  volume_info->iocharset);
4497                         return -ELIBACC;
4498                 }
4499         }
4500
4501         return rc;
4502 }
4503
4504 struct smb_vol *
4505 cifs_get_volume_info(char *mount_data, const char *devname, bool is_smb3)
4506 {
4507         int rc;
4508         struct smb_vol *volume_info;
4509
4510         volume_info = kmalloc(sizeof(struct smb_vol), GFP_KERNEL);
4511         if (!volume_info)
4512                 return ERR_PTR(-ENOMEM);
4513
4514         rc = cifs_setup_volume_info(volume_info, mount_data, devname, is_smb3);
4515         if (rc) {
4516                 cifs_cleanup_volume_info(volume_info);
4517                 volume_info = ERR_PTR(rc);
4518         }
4519
4520         return volume_info;
4521 }
4522
4523 static int
4524 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
4525                                         unsigned int xid,
4526                                         struct cifs_tcon *tcon,
4527                                         struct cifs_sb_info *cifs_sb,
4528                                         char *full_path,
4529                                         int added_treename)
4530 {
4531         int rc;
4532         char *s;
4533         char sep, tmp;
4534         int skip = added_treename ? 1 : 0;
4535
4536         sep = CIFS_DIR_SEP(cifs_sb);
4537         s = full_path;
4538
4539         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
4540         while (rc == 0) {
4541                 /* skip separators */
4542                 while (*s == sep)
4543                         s++;
4544                 if (!*s)
4545                         break;
4546                 /* next separator */
4547                 while (*s && *s != sep)
4548                         s++;
4549                 /*
4550                  * if the treename is added, we then have to skip the first
4551                  * part within the separators
4552                  */
4553                 if (skip) {
4554                         skip = 0;
4555                         continue;
4556                 }
4557                 /*
4558                  * temporarily null-terminate the path at the end of
4559                  * the current component
4560                  */
4561                 tmp = *s;
4562                 *s = 0;
4563                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
4564                                                      full_path);
4565                 *s = tmp;
4566         }
4567         return rc;
4568 }
4569
4570 /*
4571  * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
4572  * otherwise 0.
4573  */
4574 static int is_path_remote(struct cifs_sb_info *cifs_sb, struct smb_vol *vol,
4575                           const unsigned int xid,
4576                           struct TCP_Server_Info *server,
4577                           struct cifs_tcon *tcon)
4578 {
4579         int rc;
4580         char *full_path;
4581
4582         if (!server->ops->is_path_accessible)
4583                 return -EOPNOTSUPP;
4584
4585         /*
4586          * cifs_build_path_to_root works only when we have a valid tcon
4587          */
4588         full_path = cifs_build_path_to_root(vol, cifs_sb, tcon,
4589                                             tcon->Flags & SMB_SHARE_IS_IN_DFS);
4590         if (full_path == NULL)
4591                 return -ENOMEM;
4592
4593         cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
4594
4595         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
4596                                              full_path);
4597         if (rc != 0 && rc != -EREMOTE) {
4598                 kfree(full_path);
4599                 return rc;
4600         }
4601
4602         if (rc != -EREMOTE) {
4603                 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
4604                         cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
4605                 if (rc != 0) {
4606                         cifs_dbg(VFS, "cannot query dirs between root and final path, "
4607                                  "enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
4608                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
4609                         rc = 0;
4610                 }
4611         }
4612
4613         kfree(full_path);
4614         return rc;
4615 }
4616
4617 #ifdef CONFIG_CIFS_DFS_UPCALL
4618 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb_vol *vol)
4619 {
4620         int rc = 0;
4621         unsigned int xid;
4622         struct cifs_ses *ses;
4623         struct cifs_tcon *root_tcon = NULL;
4624         struct cifs_tcon *tcon = NULL;
4625         struct TCP_Server_Info *server;
4626         char *root_path = NULL, *full_path = NULL;
4627         char *old_mountdata, *origin_mountdata = NULL;
4628         int count;
4629
4630         rc = mount_get_conns(vol, cifs_sb, &xid, &server, &ses, &tcon);
4631         if (!rc && tcon) {
4632                 /* If not a standalone DFS root, then check if path is remote */
4633                 rc = dfs_cache_find(xid, ses, cifs_sb->local_nls,
4634                                     cifs_remap(cifs_sb), vol->UNC + 1, NULL,
4635                                     NULL);
4636                 if (rc) {
4637                         rc = is_path_remote(cifs_sb, vol, xid, server, tcon);
4638                         if (!rc)
4639                                 goto out;
4640                         if (rc != -EREMOTE)
4641                                 goto error;
4642                 }
4643         }
4644         /*
4645          * If first DFS target server went offline and we failed to connect it,
4646          * server and ses pointers are NULL at this point, though we still have
4647          * chance to get a cached DFS referral in expand_dfs_referral() and
4648          * retry next target available in it.
4649          *
4650          * If a NULL ses ptr is passed to dfs_cache_find(), a lookup will be
4651          * performed against DFS path and *no* requests will be sent to server
4652          * for any new DFS referrals. Hence it's safe to skip checking whether
4653          * server or ses ptr is NULL.
4654          */
4655         if (rc == -EACCES || rc == -EOPNOTSUPP)
4656                 goto error;
4657
4658         root_path = build_unc_path_to_root(vol, cifs_sb, false);
4659         if (IS_ERR(root_path)) {
4660                 rc = PTR_ERR(root_path);
4661                 root_path = NULL;
4662                 goto error;
4663         }
4664
4665         full_path = build_unc_path_to_root(vol, cifs_sb, true);
4666         if (IS_ERR(full_path)) {
4667                 rc = PTR_ERR(full_path);
4668                 full_path = NULL;
4669                 goto error;
4670         }
4671         /*
4672          * Perform an unconditional check for whether there are DFS
4673          * referrals for this path without prefix, to provide support
4674          * for DFS referrals from w2k8 servers which don't seem to respond
4675          * with PATH_NOT_COVERED to requests that include the prefix.
4676          * Chase the referral if found, otherwise continue normally.
4677          */
4678         old_mountdata = cifs_sb->mountdata;
4679         (void)expand_dfs_referral(xid, ses, vol, cifs_sb, false);
4680
4681         if (cifs_sb->mountdata == NULL) {
4682                 rc = -ENOENT;
4683                 goto error;
4684         }
4685
4686         /* Save DFS root volume information for DFS refresh worker */
4687         origin_mountdata = kstrndup(cifs_sb->mountdata,
4688                                     strlen(cifs_sb->mountdata), GFP_KERNEL);
4689         if (!origin_mountdata) {
4690                 rc = -ENOMEM;
4691                 goto error;
4692         }
4693
4694         if (cifs_sb->mountdata != old_mountdata) {
4695                 /* If we were redirected, reconnect to new target server */
4696                 mount_put_conns(cifs_sb, xid, server, ses, tcon);
4697                 rc = mount_get_conns(vol, cifs_sb, &xid, &server, &ses, &tcon);
4698         }
4699         if (rc) {
4700                 if (rc == -EACCES || rc == -EOPNOTSUPP)
4701                         goto error;
4702                 /* Perform DFS failover to any other DFS targets */
4703                 rc = mount_do_dfs_failover(root_path + 1, cifs_sb, vol, NULL,
4704                                            &xid, &server, &ses, &tcon);
4705                 if (rc)
4706                         goto error;
4707         }
4708
4709         kfree(root_path);
4710         root_path = build_unc_path_to_root(vol, cifs_sb, false);
4711         if (IS_ERR(root_path)) {
4712                 rc = PTR_ERR(root_path);
4713                 root_path = NULL;
4714                 goto error;
4715         }
4716         /* Cache out resolved root server */
4717         (void)dfs_cache_find(xid, ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
4718                              root_path + 1, NULL, NULL);
4719         /*
4720          * Save root tcon for additional DFS requests to update or create a new
4721          * DFS cache entry, or even perform DFS failover.
4722          */
4723         spin_lock(&cifs_tcp_ses_lock);
4724         tcon->tc_count++;
4725         tcon->dfs_path = root_path;
4726         root_path = NULL;
4727         tcon->remap = cifs_remap(cifs_sb);
4728         spin_unlock(&cifs_tcp_ses_lock);
4729
4730         root_tcon = tcon;
4731
4732         for (count = 1; ;) {
4733                 if (!rc && tcon) {
4734                         rc = is_path_remote(cifs_sb, vol, xid, server, tcon);
4735                         if (!rc || rc != -EREMOTE)
4736                                 break;
4737                 }
4738                 /*
4739                  * BB: when we implement proper loop detection,
4740                  *     we will remove this check. But now we need it
4741                  *     to prevent an indefinite loop if 'DFS tree' is
4742                  *     misconfigured (i.e. has loops).
4743                  */
4744                 if (count++ > MAX_NESTED_LINKS) {
4745                         rc = -ELOOP;
4746                         break;
4747                 }
4748
4749                 kfree(full_path);
4750                 full_path = build_unc_path_to_root(vol, cifs_sb, true);
4751                 if (IS_ERR(full_path)) {
4752                         rc = PTR_ERR(full_path);
4753                         full_path = NULL;
4754                         break;
4755                 }
4756
4757                 old_mountdata = cifs_sb->mountdata;
4758                 rc = expand_dfs_referral(xid, root_tcon->ses, vol, cifs_sb,
4759                                          true);
4760                 if (rc)
4761                         break;
4762
4763                 if (cifs_sb->mountdata != old_mountdata) {
4764                         mount_put_conns(cifs_sb, xid, server, ses, tcon);
4765                         rc = mount_get_conns(vol, cifs_sb, &xid, &server, &ses,
4766                                              &tcon);
4767                 }
4768                 if (rc) {
4769                         if (rc == -EACCES || rc == -EOPNOTSUPP)
4770                                 break;
4771                         /* Perform DFS failover to any other DFS targets */
4772                         rc = mount_do_dfs_failover(full_path + 1, cifs_sb, vol,
4773                                                    root_tcon->ses, &xid,
4774                                                    &server, &ses, &tcon);
4775                         if (rc == -EACCES || rc == -EOPNOTSUPP || !server ||
4776                             !ses)
4777                                 goto error;
4778                 }
4779         }
4780         cifs_put_tcon(root_tcon);
4781
4782         if (rc)
4783                 goto error;
4784
4785         spin_lock(&cifs_tcp_ses_lock);
4786         if (!tcon->dfs_path) {
4787                 /* Save full path in new tcon to do failover when reconnecting tcons */
4788                 tcon->dfs_path = full_path;
4789                 full_path = NULL;
4790                 tcon->remap = cifs_remap(cifs_sb);
4791         }
4792         cifs_sb->origin_fullpath = kstrndup(tcon->dfs_path,
4793                                             strlen(tcon->dfs_path),
4794                                             GFP_ATOMIC);
4795         if (!cifs_sb->origin_fullpath) {
4796                 spin_unlock(&cifs_tcp_ses_lock);
4797                 rc = -ENOMEM;
4798                 goto error;
4799         }
4800         spin_unlock(&cifs_tcp_ses_lock);
4801
4802         rc = dfs_cache_add_vol(origin_mountdata, vol, cifs_sb->origin_fullpath);
4803         if (rc) {
4804                 kfree(cifs_sb->origin_fullpath);
4805                 goto error;
4806         }
4807         /*
4808          * After reconnecting to a different server, unique ids won't
4809          * match anymore, so we disable serverino. This prevents
4810          * dentry revalidation to think the dentry are stale (ESTALE).
4811          */
4812         cifs_autodisable_serverino(cifs_sb);
4813 out:
4814         free_xid(xid);
4815         return mount_setup_tlink(cifs_sb, ses, tcon);
4816
4817 error:
4818         kfree(full_path);
4819         kfree(root_path);
4820         kfree(origin_mountdata);
4821         mount_put_conns(cifs_sb, xid, server, ses, tcon);
4822         return rc;
4823 }
4824 #else
4825 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb_vol *vol)
4826 {
4827         int rc = 0;
4828         unsigned int xid;
4829         struct cifs_ses *ses;
4830         struct cifs_tcon *tcon;
4831         struct TCP_Server_Info *server;
4832
4833         rc = mount_get_conns(vol, cifs_sb, &xid, &server, &ses, &tcon);
4834         if (rc)
4835                 goto error;
4836
4837         if (tcon) {
4838                 rc = is_path_remote(cifs_sb, vol, xid, server, tcon);
4839                 if (rc == -EREMOTE)
4840                         rc = -EOPNOTSUPP;
4841                 if (rc)
4842                         goto error;
4843         }
4844
4845         free_xid(xid);
4846
4847         return mount_setup_tlink(cifs_sb, ses, tcon);
4848
4849 error:
4850         mount_put_conns(cifs_sb, xid, server, ses, tcon);
4851         return rc;
4852 }
4853 #endif
4854
4855 /*
4856  * Issue a TREE_CONNECT request.
4857  */
4858 int
4859 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
4860          const char *tree, struct cifs_tcon *tcon,
4861          const struct nls_table *nls_codepage)
4862 {
4863         struct smb_hdr *smb_buffer;
4864         struct smb_hdr *smb_buffer_response;
4865         TCONX_REQ *pSMB;
4866         TCONX_RSP *pSMBr;
4867         unsigned char *bcc_ptr;
4868         int rc = 0;
4869         int length;
4870         __u16 bytes_left, count;
4871
4872         if (ses == NULL)
4873                 return -EIO;
4874
4875         smb_buffer = cifs_buf_get();
4876         if (smb_buffer == NULL)
4877                 return -ENOMEM;
4878
4879         smb_buffer_response = smb_buffer;
4880
4881         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
4882                         NULL /*no tid */ , 4 /*wct */ );
4883
4884         smb_buffer->Mid = get_next_mid(ses->server);
4885         smb_buffer->Uid = ses->Suid;
4886         pSMB = (TCONX_REQ *) smb_buffer;
4887         pSMBr = (TCONX_RSP *) smb_buffer_response;
4888
4889         pSMB->AndXCommand = 0xFF;
4890         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
4891         bcc_ptr = &pSMB->Password[0];
4892         if (tcon->pipe || (ses->server->sec_mode & SECMODE_USER)) {
4893                 pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
4894                 *bcc_ptr = 0; /* password is null byte */
4895                 bcc_ptr++;              /* skip password */
4896                 /* already aligned so no need to do it below */
4897         } else {
4898                 pSMB->PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
4899                 /* BB FIXME add code to fail this if NTLMv2 or Kerberos
4900                    specified as required (when that support is added to
4901                    the vfs in the future) as only NTLM or the much
4902                    weaker LANMAN (which we do not send by default) is accepted
4903                    by Samba (not sure whether other servers allow
4904                    NTLMv2 password here) */
4905 #ifdef CONFIG_CIFS_WEAK_PW_HASH
4906                 if ((global_secflags & CIFSSEC_MAY_LANMAN) &&
4907                     (ses->sectype == LANMAN))
4908                         calc_lanman_hash(tcon->password, ses->server->cryptkey,
4909                                          ses->server->sec_mode &
4910                                             SECMODE_PW_ENCRYPT ? true : false,
4911                                          bcc_ptr);
4912                 else
4913 #endif /* CIFS_WEAK_PW_HASH */
4914                 rc = SMBNTencrypt(tcon->password, ses->server->cryptkey,
4915                                         bcc_ptr, nls_codepage);
4916                 if (rc) {
4917                         cifs_dbg(FYI, "%s Can't generate NTLM rsp. Error: %d\n",
4918                                  __func__, rc);
4919                         cifs_buf_release(smb_buffer);
4920                         return rc;
4921                 }
4922
4923                 bcc_ptr += CIFS_AUTH_RESP_SIZE;
4924                 if (ses->capabilities & CAP_UNICODE) {
4925                         /* must align unicode strings */
4926                         *bcc_ptr = 0; /* null byte password */
4927                         bcc_ptr++;
4928                 }
4929         }
4930
4931         if (ses->server->sign)
4932                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
4933
4934         if (ses->capabilities & CAP_STATUS32) {
4935                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
4936         }
4937         if (ses->capabilities & CAP_DFS) {
4938                 smb_buffer->Flags2 |= SMBFLG2_DFS;
4939         }
4940         if (ses->capabilities & CAP_UNICODE) {
4941                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
4942                 length =
4943                     cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
4944                         6 /* max utf8 char length in bytes */ *
4945                         (/* server len*/ + 256 /* share len */), nls_codepage);
4946                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
4947                 bcc_ptr += 2;   /* skip trailing null */
4948         } else {                /* ASCII */
4949                 strcpy(bcc_ptr, tree);
4950                 bcc_ptr += strlen(tree) + 1;
4951         }
4952         strcpy(bcc_ptr, "?????");
4953         bcc_ptr += strlen("?????");
4954         bcc_ptr += 1;
4955         count = bcc_ptr - &pSMB->Password[0];
4956         pSMB->hdr.smb_buf_length = cpu_to_be32(be32_to_cpu(
4957                                         pSMB->hdr.smb_buf_length) + count);
4958         pSMB->ByteCount = cpu_to_le16(count);
4959
4960         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
4961                          0);
4962
4963         /* above now done in SendReceive */
4964         if (rc == 0) {
4965                 bool is_unicode;
4966
4967                 tcon->tidStatus = CifsGood;
4968                 tcon->need_reconnect = false;
4969                 tcon->tid = smb_buffer_response->Tid;
4970                 bcc_ptr = pByteArea(smb_buffer_response);
4971                 bytes_left = get_bcc(smb_buffer_response);
4972                 length = strnlen(bcc_ptr, bytes_left - 2);
4973                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
4974                         is_unicode = true;
4975                 else
4976                         is_unicode = false;
4977
4978
4979                 /* skip service field (NB: this field is always ASCII) */
4980                 if (length == 3) {
4981                         if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
4982                             (bcc_ptr[2] == 'C')) {
4983                                 cifs_dbg(FYI, "IPC connection\n");
4984                                 tcon->ipc = true;
4985                                 tcon->pipe = true;
4986                         }
4987                 } else if (length == 2) {
4988                         if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
4989                                 /* the most common case */
4990                                 cifs_dbg(FYI, "disk share connection\n");
4991                         }
4992                 }
4993                 bcc_ptr += length + 1;
4994                 bytes_left -= (length + 1);
4995                 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
4996
4997                 /* mostly informational -- no need to fail on error here */
4998                 kfree(tcon->nativeFileSystem);
4999                 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
5000                                                       bytes_left, is_unicode,
5001                                                       nls_codepage);
5002
5003                 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
5004
5005                 if ((smb_buffer_response->WordCount == 3) ||
5006                          (smb_buffer_response->WordCount == 7))
5007                         /* field is in same location */
5008                         tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
5009                 else
5010                         tcon->Flags = 0;
5011                 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
5012         }
5013
5014         cifs_buf_release(smb_buffer);
5015         return rc;
5016 }
5017
5018 static void delayed_free(struct rcu_head *p)
5019 {
5020         struct cifs_sb_info *sbi = container_of(p, struct cifs_sb_info, rcu);
5021         unload_nls(sbi->local_nls);
5022         kfree(sbi);
5023 }
5024
5025 void
5026 cifs_umount(struct cifs_sb_info *cifs_sb)
5027 {
5028         struct rb_root *root = &cifs_sb->tlink_tree;
5029         struct rb_node *node;
5030         struct tcon_link *tlink;
5031
5032         cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
5033
5034         spin_lock(&cifs_sb->tlink_tree_lock);
5035         while ((node = rb_first(root))) {
5036                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
5037                 cifs_get_tlink(tlink);
5038                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
5039                 rb_erase(node, root);
5040
5041                 spin_unlock(&cifs_sb->tlink_tree_lock);
5042                 cifs_put_tlink(tlink);
5043                 spin_lock(&cifs_sb->tlink_tree_lock);
5044         }
5045         spin_unlock(&cifs_sb->tlink_tree_lock);
5046
5047         kfree(cifs_sb->mountdata);
5048         kfree(cifs_sb->prepath);
5049 #ifdef CONFIG_CIFS_DFS_UPCALL
5050         dfs_cache_del_vol(cifs_sb->origin_fullpath);
5051         kfree(cifs_sb->origin_fullpath);
5052 #endif
5053         call_rcu(&cifs_sb->rcu, delayed_free);
5054 }
5055
5056 int
5057 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
5058 {
5059         int rc = 0;
5060         struct TCP_Server_Info *server = ses->server;
5061
5062         if (!server->ops->need_neg || !server->ops->negotiate)
5063                 return -ENOSYS;
5064
5065         /* only send once per connect */
5066         if (!server->ops->need_neg(server))
5067                 return 0;
5068
5069         rc = server->ops->negotiate(xid, ses);
5070         if (rc == 0) {
5071                 spin_lock(&GlobalMid_Lock);
5072                 if (server->tcpStatus == CifsNeedNegotiate)
5073                         server->tcpStatus = CifsGood;
5074                 else
5075                         rc = -EHOSTDOWN;
5076                 spin_unlock(&GlobalMid_Lock);
5077         }
5078
5079         return rc;
5080 }
5081
5082 int
5083 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
5084                    struct nls_table *nls_info)
5085 {
5086         int rc = -ENOSYS;
5087         struct TCP_Server_Info *server = ses->server;
5088
5089         ses->capabilities = server->capabilities;
5090         if (linuxExtEnabled == 0)
5091                 ses->capabilities &= (~server->vals->cap_unix);
5092
5093         cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
5094                  server->sec_mode, server->capabilities, server->timeAdj);
5095
5096         if (ses->auth_key.response) {
5097                 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
5098                          ses->auth_key.response);
5099                 kfree(ses->auth_key.response);
5100                 ses->auth_key.response = NULL;
5101                 ses->auth_key.len = 0;
5102         }
5103
5104         if (server->ops->sess_setup)
5105                 rc = server->ops->sess_setup(xid, ses, nls_info);
5106
5107         if (rc)
5108                 cifs_dbg(VFS, "Send error in SessSetup = %d\n", rc);
5109
5110         return rc;
5111 }
5112
5113 static int
5114 cifs_set_vol_auth(struct smb_vol *vol, struct cifs_ses *ses)
5115 {
5116         vol->sectype = ses->sectype;
5117
5118         /* krb5 is special, since we don't need username or pw */
5119         if (vol->sectype == Kerberos)
5120                 return 0;
5121
5122         return cifs_set_cifscreds(vol, ses);
5123 }
5124
5125 static struct cifs_tcon *
5126 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
5127 {
5128         int rc;
5129         struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
5130         struct cifs_ses *ses;
5131         struct cifs_tcon *tcon = NULL;
5132         struct smb_vol *vol_info;
5133
5134         vol_info = kzalloc(sizeof(*vol_info), GFP_KERNEL);
5135         if (vol_info == NULL)
5136                 return ERR_PTR(-ENOMEM);
5137
5138         vol_info->local_nls = cifs_sb->local_nls;
5139         vol_info->linux_uid = fsuid;
5140         vol_info->cred_uid = fsuid;
5141         vol_info->UNC = master_tcon->treeName;
5142         vol_info->retry = master_tcon->retry;
5143         vol_info->nocase = master_tcon->nocase;
5144         vol_info->nohandlecache = master_tcon->nohandlecache;
5145         vol_info->local_lease = master_tcon->local_lease;
5146         vol_info->no_linux_ext = !master_tcon->unix_ext;
5147         vol_info->sectype = master_tcon->ses->sectype;
5148         vol_info->sign = master_tcon->ses->sign;
5149
5150         rc = cifs_set_vol_auth(vol_info, master_tcon->ses);
5151         if (rc) {
5152                 tcon = ERR_PTR(rc);
5153                 goto out;
5154         }
5155
5156         /* get a reference for the same TCP session */
5157         spin_lock(&cifs_tcp_ses_lock);
5158         ++master_tcon->ses->server->srv_count;
5159         spin_unlock(&cifs_tcp_ses_lock);
5160
5161         ses = cifs_get_smb_ses(master_tcon->ses->server, vol_info);
5162         if (IS_ERR(ses)) {
5163                 tcon = (struct cifs_tcon *)ses;
5164                 cifs_put_tcp_session(master_tcon->ses->server, 0);
5165                 goto out;
5166         }
5167
5168         tcon = cifs_get_tcon(ses, vol_info);
5169         if (IS_ERR(tcon)) {
5170                 cifs_put_smb_ses(ses);
5171                 goto out;
5172         }
5173
5174         /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
5175         if (tcon->posix_extensions)
5176                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
5177
5178         if (cap_unix(ses))
5179                 reset_cifs_unix_caps(0, tcon, NULL, vol_info);
5180
5181 out:
5182         kfree(vol_info->username);
5183         kzfree(vol_info->password);
5184         kfree(vol_info);
5185
5186         return tcon;
5187 }
5188
5189 struct cifs_tcon *
5190 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
5191 {
5192         return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
5193 }
5194
5195 /* find and return a tlink with given uid */
5196 static struct tcon_link *
5197 tlink_rb_search(struct rb_root *root, kuid_t uid)
5198 {
5199         struct rb_node *node = root->rb_node;
5200         struct tcon_link *tlink;
5201
5202         while (node) {
5203                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
5204
5205                 if (uid_gt(tlink->tl_uid, uid))
5206                         node = node->rb_left;
5207                 else if (uid_lt(tlink->tl_uid, uid))
5208                         node = node->rb_right;
5209                 else
5210                         return tlink;
5211         }
5212         return NULL;
5213 }
5214
5215 /* insert a tcon_link into the tree */
5216 static void
5217 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
5218 {
5219         struct rb_node **new = &(root->rb_node), *parent = NULL;
5220         struct tcon_link *tlink;
5221
5222         while (*new) {
5223                 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
5224                 parent = *new;
5225
5226                 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
5227                         new = &((*new)->rb_left);
5228                 else
5229                         new = &((*new)->rb_right);
5230         }
5231
5232         rb_link_node(&new_tlink->tl_rbnode, parent, new);
5233         rb_insert_color(&new_tlink->tl_rbnode, root);
5234 }
5235
5236 /*
5237  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
5238  * current task.
5239  *
5240  * If the superblock doesn't refer to a multiuser mount, then just return
5241  * the master tcon for the mount.
5242  *
5243  * First, search the rbtree for an existing tcon for this fsuid. If one
5244  * exists, then check to see if it's pending construction. If it is then wait
5245  * for construction to complete. Once it's no longer pending, check to see if
5246  * it failed and either return an error or retry construction, depending on
5247  * the timeout.
5248  *
5249  * If one doesn't exist then insert a new tcon_link struct into the tree and
5250  * try to construct a new one.
5251  */
5252 struct tcon_link *
5253 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
5254 {
5255         int ret;
5256         kuid_t fsuid = current_fsuid();
5257         struct tcon_link *tlink, *newtlink;
5258
5259         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
5260                 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
5261
5262         spin_lock(&cifs_sb->tlink_tree_lock);
5263         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
5264         if (tlink)
5265                 cifs_get_tlink(tlink);
5266         spin_unlock(&cifs_sb->tlink_tree_lock);
5267
5268         if (tlink == NULL) {
5269                 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
5270                 if (newtlink == NULL)
5271                         return ERR_PTR(-ENOMEM);
5272                 newtlink->tl_uid = fsuid;
5273                 newtlink->tl_tcon = ERR_PTR(-EACCES);
5274                 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
5275                 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
5276                 cifs_get_tlink(newtlink);
5277
5278                 spin_lock(&cifs_sb->tlink_tree_lock);
5279                 /* was one inserted after previous search? */
5280                 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
5281                 if (tlink) {
5282                         cifs_get_tlink(tlink);
5283                         spin_unlock(&cifs_sb->tlink_tree_lock);
5284                         kfree(newtlink);
5285                         goto wait_for_construction;
5286                 }
5287                 tlink = newtlink;
5288                 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
5289                 spin_unlock(&cifs_sb->tlink_tree_lock);
5290         } else {
5291 wait_for_construction:
5292                 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
5293                                   TASK_INTERRUPTIBLE);
5294                 if (ret) {
5295                         cifs_put_tlink(tlink);
5296                         return ERR_PTR(-ERESTARTSYS);
5297                 }
5298
5299                 /* if it's good, return it */
5300                 if (!IS_ERR(tlink->tl_tcon))
5301                         return tlink;
5302
5303                 /* return error if we tried this already recently */
5304                 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
5305                         cifs_put_tlink(tlink);
5306                         return ERR_PTR(-EACCES);
5307                 }
5308
5309                 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
5310                         goto wait_for_construction;
5311         }
5312
5313         tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
5314         clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
5315         wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
5316
5317         if (IS_ERR(tlink->tl_tcon)) {
5318                 cifs_put_tlink(tlink);
5319                 return ERR_PTR(-EACCES);
5320         }
5321
5322         return tlink;
5323 }
5324
5325 /*
5326  * periodic workqueue job that scans tcon_tree for a superblock and closes
5327  * out tcons.
5328  */
5329 static void
5330 cifs_prune_tlinks(struct work_struct *work)
5331 {
5332         struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
5333                                                     prune_tlinks.work);
5334         struct rb_root *root = &cifs_sb->tlink_tree;
5335         struct rb_node *node;
5336         struct rb_node *tmp;
5337         struct tcon_link *tlink;
5338
5339         /*
5340          * Because we drop the spinlock in the loop in order to put the tlink
5341          * it's not guarded against removal of links from the tree. The only
5342          * places that remove entries from the tree are this function and
5343          * umounts. Because this function is non-reentrant and is canceled
5344          * before umount can proceed, this is safe.
5345          */
5346         spin_lock(&cifs_sb->tlink_tree_lock);
5347         node = rb_first(root);
5348         while (node != NULL) {
5349                 tmp = node;
5350                 node = rb_next(tmp);
5351                 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
5352
5353                 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
5354                     atomic_read(&tlink->tl_count) != 0 ||
5355                     time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
5356                         continue;
5357
5358                 cifs_get_tlink(tlink);
5359                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
5360                 rb_erase(tmp, root);
5361
5362                 spin_unlock(&cifs_sb->tlink_tree_lock);
5363                 cifs_put_tlink(tlink);
5364                 spin_lock(&cifs_sb->tlink_tree_lock);
5365         }
5366         spin_unlock(&cifs_sb->tlink_tree_lock);
5367
5368         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
5369                                 TLINK_IDLE_EXPIRE);
5370 }