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