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