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