xref: /linux/fs/smb/client/connect.c (revision 778e73d2411abc8f3a2d60dbf038acaec218792e)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2011
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8 #include <linux/fs.h>
9 #include <linux/net.h>
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
32 #include <net/ipv6.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41 #include "ntlmssp.h"
42 #include "nterr.h"
43 #include "rfc1002pdu.h"
44 #include "fscache.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs.h"
50 #include "dfs_cache.h"
51 #endif
52 #include "fs_context.h"
53 #include "cifs_swn.h"
54 
55 extern mempool_t *cifs_req_poolp;
56 extern bool disable_legacy_dialects;
57 
58 /* FIXME: should these be tunable? */
59 #define TLINK_ERROR_EXPIRE	(1 * HZ)
60 #define TLINK_IDLE_EXPIRE	(600 * HZ)
61 
62 /* Drop the connection to not overload the server */
63 #define MAX_STATUS_IO_TIMEOUT   5
64 
65 static int ip_connect(struct TCP_Server_Info *server);
66 static int generic_ip_connect(struct TCP_Server_Info *server);
67 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
68 static void cifs_prune_tlinks(struct work_struct *work);
69 
70 /*
71  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
72  * get their ip addresses changed at some point.
73  *
74  * This should be called with server->srv_mutex held.
75  */
76 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
77 {
78 	int rc;
79 	int len;
80 	char *unc;
81 	struct sockaddr_storage ss;
82 
83 	if (!server->hostname)
84 		return -EINVAL;
85 
86 	/* if server hostname isn't populated, there's nothing to do here */
87 	if (server->hostname[0] == '\0')
88 		return 0;
89 
90 	len = strlen(server->hostname) + 3;
91 
92 	unc = kmalloc(len, GFP_KERNEL);
93 	if (!unc) {
94 		cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
95 		return -ENOMEM;
96 	}
97 	scnprintf(unc, len, "\\\\%s", server->hostname);
98 
99 	spin_lock(&server->srv_lock);
100 	ss = server->dstaddr;
101 	spin_unlock(&server->srv_lock);
102 
103 	rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
104 	kfree(unc);
105 
106 	if (rc < 0) {
107 		cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
108 			 __func__, server->hostname, rc);
109 	} else {
110 		spin_lock(&server->srv_lock);
111 		memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
112 		spin_unlock(&server->srv_lock);
113 		rc = 0;
114 	}
115 
116 	return rc;
117 }
118 
119 static void smb2_query_server_interfaces(struct work_struct *work)
120 {
121 	int rc;
122 	int xid;
123 	struct cifs_tcon *tcon = container_of(work,
124 					struct cifs_tcon,
125 					query_interfaces.work);
126 
127 	/*
128 	 * query server network interfaces, in case they change
129 	 */
130 	xid = get_xid();
131 	rc = SMB3_request_interfaces(xid, tcon, false);
132 	free_xid(xid);
133 
134 	if (rc) {
135 		if (rc == -EOPNOTSUPP)
136 			return;
137 
138 		cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
139 				__func__, rc);
140 	}
141 
142 	queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
143 			   (SMB_INTERFACE_POLL_INTERVAL * HZ));
144 }
145 
146 /*
147  * Update the tcpStatus for the server.
148  * This is used to signal the cifsd thread to call cifs_reconnect
149  * ONLY cifsd thread should call cifs_reconnect. For any other
150  * thread, use this function
151  *
152  * @server: the tcp ses for which reconnect is needed
153  * @all_channels: if this needs to be done for all channels
154  */
155 void
156 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
157 				bool all_channels)
158 {
159 	struct TCP_Server_Info *pserver;
160 	struct cifs_ses *ses;
161 	int i;
162 
163 	/* If server is a channel, select the primary channel */
164 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
165 
166 	/* if we need to signal just this channel */
167 	if (!all_channels) {
168 		spin_lock(&server->srv_lock);
169 		if (server->tcpStatus != CifsExiting)
170 			server->tcpStatus = CifsNeedReconnect;
171 		spin_unlock(&server->srv_lock);
172 		return;
173 	}
174 
175 	spin_lock(&cifs_tcp_ses_lock);
176 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
177 		spin_lock(&ses->chan_lock);
178 		for (i = 0; i < ses->chan_count; i++) {
179 			if (!ses->chans[i].server)
180 				continue;
181 
182 			spin_lock(&ses->chans[i].server->srv_lock);
183 			if (ses->chans[i].server->tcpStatus != CifsExiting)
184 				ses->chans[i].server->tcpStatus = CifsNeedReconnect;
185 			spin_unlock(&ses->chans[i].server->srv_lock);
186 		}
187 		spin_unlock(&ses->chan_lock);
188 	}
189 	spin_unlock(&cifs_tcp_ses_lock);
190 }
191 
192 /*
193  * Mark all sessions and tcons for reconnect.
194  * IMPORTANT: make sure that this gets called only from
195  * cifsd thread. For any other thread, use
196  * cifs_signal_cifsd_for_reconnect
197  *
198  * @server: the tcp ses for which reconnect is needed
199  * @server needs to be previously set to CifsNeedReconnect.
200  * @mark_smb_session: whether even sessions need to be marked
201  */
202 void
203 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
204 				      bool mark_smb_session)
205 {
206 	struct TCP_Server_Info *pserver;
207 	struct cifs_ses *ses, *nses;
208 	struct cifs_tcon *tcon;
209 
210 	/*
211 	 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
212 	 * are not used until reconnected.
213 	 */
214 	cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
215 
216 	/* If server is a channel, select the primary channel */
217 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
218 
219 	/*
220 	 * if the server has been marked for termination, there is a
221 	 * chance that the remaining channels all need reconnect. To be
222 	 * on the safer side, mark the session and trees for reconnect
223 	 * for this scenario. This might cause a few redundant session
224 	 * setup and tree connect requests, but it is better than not doing
225 	 * a tree connect when needed, and all following requests failing
226 	 */
227 	if (server->terminate) {
228 		mark_smb_session = true;
229 		server = pserver;
230 	}
231 
232 	spin_lock(&cifs_tcp_ses_lock);
233 	list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
234 		/* check if iface is still active */
235 		spin_lock(&ses->chan_lock);
236 		if (!cifs_chan_is_iface_active(ses, server)) {
237 			spin_unlock(&ses->chan_lock);
238 			cifs_chan_update_iface(ses, server);
239 			spin_lock(&ses->chan_lock);
240 		}
241 
242 		if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
243 			spin_unlock(&ses->chan_lock);
244 			continue;
245 		}
246 
247 		if (mark_smb_session)
248 			CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
249 		else
250 			cifs_chan_set_need_reconnect(ses, server);
251 
252 		cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
253 			 __func__, ses->chans_need_reconnect);
254 
255 		/* If all channels need reconnect, then tcon needs reconnect */
256 		if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
257 			spin_unlock(&ses->chan_lock);
258 			continue;
259 		}
260 		spin_unlock(&ses->chan_lock);
261 
262 		spin_lock(&ses->ses_lock);
263 		ses->ses_status = SES_NEED_RECON;
264 		spin_unlock(&ses->ses_lock);
265 
266 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
267 			tcon->need_reconnect = true;
268 			spin_lock(&tcon->tc_lock);
269 			tcon->status = TID_NEED_RECON;
270 			spin_unlock(&tcon->tc_lock);
271 
272 			cancel_delayed_work(&tcon->query_interfaces);
273 		}
274 		if (ses->tcon_ipc) {
275 			ses->tcon_ipc->need_reconnect = true;
276 			spin_lock(&ses->tcon_ipc->tc_lock);
277 			ses->tcon_ipc->status = TID_NEED_RECON;
278 			spin_unlock(&ses->tcon_ipc->tc_lock);
279 		}
280 	}
281 	spin_unlock(&cifs_tcp_ses_lock);
282 }
283 
284 static void
285 cifs_abort_connection(struct TCP_Server_Info *server)
286 {
287 	struct mid_q_entry *mid, *nmid;
288 	struct list_head retry_list;
289 
290 	server->maxBuf = 0;
291 	server->max_read = 0;
292 
293 	/* do not want to be sending data on a socket we are freeing */
294 	cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
295 	cifs_server_lock(server);
296 	if (server->ssocket) {
297 		cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
298 			 server->ssocket->flags);
299 		kernel_sock_shutdown(server->ssocket, SHUT_WR);
300 		cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
301 			 server->ssocket->flags);
302 		sock_release(server->ssocket);
303 		server->ssocket = NULL;
304 	}
305 	server->sequence_number = 0;
306 	server->session_estab = false;
307 	kfree_sensitive(server->session_key.response);
308 	server->session_key.response = NULL;
309 	server->session_key.len = 0;
310 	server->lstrp = jiffies;
311 
312 	/* mark submitted MIDs for retry and issue callback */
313 	INIT_LIST_HEAD(&retry_list);
314 	cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
315 	spin_lock(&server->mid_lock);
316 	list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
317 		kref_get(&mid->refcount);
318 		if (mid->mid_state == MID_REQUEST_SUBMITTED)
319 			mid->mid_state = MID_RETRY_NEEDED;
320 		list_move(&mid->qhead, &retry_list);
321 		mid->mid_flags |= MID_DELETED;
322 	}
323 	spin_unlock(&server->mid_lock);
324 	cifs_server_unlock(server);
325 
326 	cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
327 	list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
328 		list_del_init(&mid->qhead);
329 		mid->callback(mid);
330 		release_mid(mid);
331 	}
332 
333 	if (cifs_rdma_enabled(server)) {
334 		cifs_server_lock(server);
335 		smbd_destroy(server);
336 		cifs_server_unlock(server);
337 	}
338 }
339 
340 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
341 {
342 	spin_lock(&server->srv_lock);
343 	server->nr_targets = num_targets;
344 	if (server->tcpStatus == CifsExiting) {
345 		/* the demux thread will exit normally next time through the loop */
346 		spin_unlock(&server->srv_lock);
347 		wake_up(&server->response_q);
348 		return false;
349 	}
350 
351 	cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
352 	trace_smb3_reconnect(server->CurrentMid, server->conn_id,
353 			     server->hostname);
354 	server->tcpStatus = CifsNeedReconnect;
355 
356 	spin_unlock(&server->srv_lock);
357 	return true;
358 }
359 
360 /*
361  * cifs tcp session reconnection
362  *
363  * mark tcp session as reconnecting so temporarily locked
364  * mark all smb sessions as reconnecting for tcp session
365  * reconnect tcp session
366  * wake up waiters on reconnection? - (not needed currently)
367  *
368  * if mark_smb_session is passed as true, unconditionally mark
369  * the smb session (and tcon) for reconnect as well. This value
370  * doesn't really matter for non-multichannel scenario.
371  *
372  */
373 static int __cifs_reconnect(struct TCP_Server_Info *server,
374 			    bool mark_smb_session)
375 {
376 	int rc = 0;
377 
378 	if (!cifs_tcp_ses_needs_reconnect(server, 1))
379 		return 0;
380 
381 	cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
382 
383 	cifs_abort_connection(server);
384 
385 	do {
386 		try_to_freeze();
387 		cifs_server_lock(server);
388 
389 		if (!cifs_swn_set_server_dstaddr(server)) {
390 			/* resolve the hostname again to make sure that IP address is up-to-date */
391 			rc = reconn_set_ipaddr_from_hostname(server);
392 			cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
393 		}
394 
395 		if (cifs_rdma_enabled(server))
396 			rc = smbd_reconnect(server);
397 		else
398 			rc = generic_ip_connect(server);
399 		if (rc) {
400 			cifs_server_unlock(server);
401 			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
402 			msleep(3000);
403 		} else {
404 			atomic_inc(&tcpSesReconnectCount);
405 			set_credits(server, 1);
406 			spin_lock(&server->srv_lock);
407 			if (server->tcpStatus != CifsExiting)
408 				server->tcpStatus = CifsNeedNegotiate;
409 			spin_unlock(&server->srv_lock);
410 			cifs_swn_reset_server_dstaddr(server);
411 			cifs_server_unlock(server);
412 			mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
413 		}
414 	} while (server->tcpStatus == CifsNeedReconnect);
415 
416 	spin_lock(&server->srv_lock);
417 	if (server->tcpStatus == CifsNeedNegotiate)
418 		mod_delayed_work(cifsiod_wq, &server->echo, 0);
419 	spin_unlock(&server->srv_lock);
420 
421 	wake_up(&server->response_q);
422 	return rc;
423 }
424 
425 #ifdef CONFIG_CIFS_DFS_UPCALL
426 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
427 {
428 	int rc;
429 	char *hostname;
430 
431 	if (!cifs_swn_set_server_dstaddr(server)) {
432 		if (server->hostname != target) {
433 			hostname = extract_hostname(target);
434 			if (!IS_ERR(hostname)) {
435 				spin_lock(&server->srv_lock);
436 				kfree(server->hostname);
437 				server->hostname = hostname;
438 				spin_unlock(&server->srv_lock);
439 			} else {
440 				cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
441 					 __func__, PTR_ERR(hostname));
442 				cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
443 					 server->hostname);
444 			}
445 		}
446 		/* resolve the hostname again to make sure that IP address is up-to-date. */
447 		rc = reconn_set_ipaddr_from_hostname(server);
448 		cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
449 	}
450 	/* Reconnect the socket */
451 	if (cifs_rdma_enabled(server))
452 		rc = smbd_reconnect(server);
453 	else
454 		rc = generic_ip_connect(server);
455 
456 	return rc;
457 }
458 
459 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
460 				     struct dfs_cache_tgt_iterator **target_hint)
461 {
462 	int rc;
463 	struct dfs_cache_tgt_iterator *tit;
464 
465 	*target_hint = NULL;
466 
467 	/* If dfs target list is empty, then reconnect to last server */
468 	tit = dfs_cache_get_tgt_iterator(tl);
469 	if (!tit)
470 		return __reconnect_target_unlocked(server, server->hostname);
471 
472 	/* Otherwise, try every dfs target in @tl */
473 	for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
474 		rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
475 		if (!rc) {
476 			*target_hint = tit;
477 			break;
478 		}
479 	}
480 	return rc;
481 }
482 
483 static int reconnect_dfs_server(struct TCP_Server_Info *server)
484 {
485 	struct dfs_cache_tgt_iterator *target_hint = NULL;
486 
487 	DFS_CACHE_TGT_LIST(tl);
488 	int num_targets = 0;
489 	int rc = 0;
490 
491 	/*
492 	 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
493 	 *
494 	 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
495 	 * targets (server->nr_targets).  It's also possible that the cached referral was cleared
496 	 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
497 	 * refreshing the referral, so, in this case, default it to 1.
498 	 */
499 	mutex_lock(&server->refpath_lock);
500 	if (!dfs_cache_noreq_find(server->leaf_fullpath + 1, NULL, &tl))
501 		num_targets = dfs_cache_get_nr_tgts(&tl);
502 	mutex_unlock(&server->refpath_lock);
503 	if (!num_targets)
504 		num_targets = 1;
505 
506 	if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
507 		return 0;
508 
509 	/*
510 	 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
511 	 * different server or share during failover.  It could be improved by adding some logic to
512 	 * only do that in case it connects to a different server or share, though.
513 	 */
514 	cifs_mark_tcp_ses_conns_for_reconnect(server, true);
515 
516 	cifs_abort_connection(server);
517 
518 	do {
519 		try_to_freeze();
520 		cifs_server_lock(server);
521 
522 		rc = reconnect_target_unlocked(server, &tl, &target_hint);
523 		if (rc) {
524 			/* Failed to reconnect socket */
525 			cifs_server_unlock(server);
526 			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
527 			msleep(3000);
528 			continue;
529 		}
530 		/*
531 		 * Socket was created.  Update tcp session status to CifsNeedNegotiate so that a
532 		 * process waiting for reconnect will know it needs to re-establish session and tcon
533 		 * through the reconnected target server.
534 		 */
535 		atomic_inc(&tcpSesReconnectCount);
536 		set_credits(server, 1);
537 		spin_lock(&server->srv_lock);
538 		if (server->tcpStatus != CifsExiting)
539 			server->tcpStatus = CifsNeedNegotiate;
540 		spin_unlock(&server->srv_lock);
541 		cifs_swn_reset_server_dstaddr(server);
542 		cifs_server_unlock(server);
543 		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
544 	} while (server->tcpStatus == CifsNeedReconnect);
545 
546 	mutex_lock(&server->refpath_lock);
547 	dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
548 	mutex_unlock(&server->refpath_lock);
549 	dfs_cache_free_tgts(&tl);
550 
551 	/* Need to set up echo worker again once connection has been established */
552 	spin_lock(&server->srv_lock);
553 	if (server->tcpStatus == CifsNeedNegotiate)
554 		mod_delayed_work(cifsiod_wq, &server->echo, 0);
555 	spin_unlock(&server->srv_lock);
556 
557 	wake_up(&server->response_q);
558 	return rc;
559 }
560 
561 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
562 {
563 	mutex_lock(&server->refpath_lock);
564 	if (!server->leaf_fullpath) {
565 		mutex_unlock(&server->refpath_lock);
566 		return __cifs_reconnect(server, mark_smb_session);
567 	}
568 	mutex_unlock(&server->refpath_lock);
569 
570 	return reconnect_dfs_server(server);
571 }
572 #else
573 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
574 {
575 	return __cifs_reconnect(server, mark_smb_session);
576 }
577 #endif
578 
579 static void
580 cifs_echo_request(struct work_struct *work)
581 {
582 	int rc;
583 	struct TCP_Server_Info *server = container_of(work,
584 					struct TCP_Server_Info, echo.work);
585 
586 	/*
587 	 * We cannot send an echo if it is disabled.
588 	 * Also, no need to ping if we got a response recently.
589 	 */
590 
591 	if (server->tcpStatus == CifsNeedReconnect ||
592 	    server->tcpStatus == CifsExiting ||
593 	    server->tcpStatus == CifsNew ||
594 	    (server->ops->can_echo && !server->ops->can_echo(server)) ||
595 	    time_before(jiffies, server->lstrp + server->echo_interval - HZ))
596 		goto requeue_echo;
597 
598 	rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
599 	cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
600 
601 	/* Check witness registrations */
602 	cifs_swn_check();
603 
604 requeue_echo:
605 	queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
606 }
607 
608 static bool
609 allocate_buffers(struct TCP_Server_Info *server)
610 {
611 	if (!server->bigbuf) {
612 		server->bigbuf = (char *)cifs_buf_get();
613 		if (!server->bigbuf) {
614 			cifs_server_dbg(VFS, "No memory for large SMB response\n");
615 			msleep(3000);
616 			/* retry will check if exiting */
617 			return false;
618 		}
619 	} else if (server->large_buf) {
620 		/* we are reusing a dirty large buf, clear its start */
621 		memset(server->bigbuf, 0, HEADER_SIZE(server));
622 	}
623 
624 	if (!server->smallbuf) {
625 		server->smallbuf = (char *)cifs_small_buf_get();
626 		if (!server->smallbuf) {
627 			cifs_server_dbg(VFS, "No memory for SMB response\n");
628 			msleep(1000);
629 			/* retry will check if exiting */
630 			return false;
631 		}
632 		/* beginning of smb buffer is cleared in our buf_get */
633 	} else {
634 		/* if existing small buf clear beginning */
635 		memset(server->smallbuf, 0, HEADER_SIZE(server));
636 	}
637 
638 	return true;
639 }
640 
641 static bool
642 server_unresponsive(struct TCP_Server_Info *server)
643 {
644 	/*
645 	 * We need to wait 3 echo intervals to make sure we handle such
646 	 * situations right:
647 	 * 1s  client sends a normal SMB request
648 	 * 2s  client gets a response
649 	 * 30s echo workqueue job pops, and decides we got a response recently
650 	 *     and don't need to send another
651 	 * ...
652 	 * 65s kernel_recvmsg times out, and we see that we haven't gotten
653 	 *     a response in >60s.
654 	 */
655 	spin_lock(&server->srv_lock);
656 	if ((server->tcpStatus == CifsGood ||
657 	    server->tcpStatus == CifsNeedNegotiate) &&
658 	    (!server->ops->can_echo || server->ops->can_echo(server)) &&
659 	    time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
660 		spin_unlock(&server->srv_lock);
661 		cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
662 			 (3 * server->echo_interval) / HZ);
663 		cifs_reconnect(server, false);
664 		return true;
665 	}
666 	spin_unlock(&server->srv_lock);
667 
668 	return false;
669 }
670 
671 static inline bool
672 zero_credits(struct TCP_Server_Info *server)
673 {
674 	int val;
675 
676 	spin_lock(&server->req_lock);
677 	val = server->credits + server->echo_credits + server->oplock_credits;
678 	if (server->in_flight == 0 && val == 0) {
679 		spin_unlock(&server->req_lock);
680 		return true;
681 	}
682 	spin_unlock(&server->req_lock);
683 	return false;
684 }
685 
686 static int
687 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
688 {
689 	int length = 0;
690 	int total_read;
691 
692 	for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
693 		try_to_freeze();
694 
695 		/* reconnect if no credits and no requests in flight */
696 		if (zero_credits(server)) {
697 			cifs_reconnect(server, false);
698 			return -ECONNABORTED;
699 		}
700 
701 		if (server_unresponsive(server))
702 			return -ECONNABORTED;
703 		if (cifs_rdma_enabled(server) && server->smbd_conn)
704 			length = smbd_recv(server->smbd_conn, smb_msg);
705 		else
706 			length = sock_recvmsg(server->ssocket, smb_msg, 0);
707 
708 		spin_lock(&server->srv_lock);
709 		if (server->tcpStatus == CifsExiting) {
710 			spin_unlock(&server->srv_lock);
711 			return -ESHUTDOWN;
712 		}
713 
714 		if (server->tcpStatus == CifsNeedReconnect) {
715 			spin_unlock(&server->srv_lock);
716 			cifs_reconnect(server, false);
717 			return -ECONNABORTED;
718 		}
719 		spin_unlock(&server->srv_lock);
720 
721 		if (length == -ERESTARTSYS ||
722 		    length == -EAGAIN ||
723 		    length == -EINTR) {
724 			/*
725 			 * Minimum sleep to prevent looping, allowing socket
726 			 * to clear and app threads to set tcpStatus
727 			 * CifsNeedReconnect if server hung.
728 			 */
729 			usleep_range(1000, 2000);
730 			length = 0;
731 			continue;
732 		}
733 
734 		if (length <= 0) {
735 			cifs_dbg(FYI, "Received no data or error: %d\n", length);
736 			cifs_reconnect(server, false);
737 			return -ECONNABORTED;
738 		}
739 	}
740 	return total_read;
741 }
742 
743 int
744 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
745 		      unsigned int to_read)
746 {
747 	struct msghdr smb_msg = {};
748 	struct kvec iov = {.iov_base = buf, .iov_len = to_read};
749 
750 	iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
751 
752 	return cifs_readv_from_socket(server, &smb_msg);
753 }
754 
755 ssize_t
756 cifs_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, ITER_DEST, to_read);
766 
767 	return cifs_readv_from_socket(server, &smb_msg);
768 }
769 
770 int
771 cifs_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 
777 	bvec_set_page(&bv, page, to_read, page_offset);
778 	iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
779 	return cifs_readv_from_socket(server, &smb_msg);
780 }
781 
782 int
783 cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
784 			   unsigned int to_read)
785 {
786 	struct msghdr smb_msg = { .msg_iter = *iter };
787 	int ret;
788 
789 	iov_iter_truncate(&smb_msg.msg_iter, to_read);
790 	ret = cifs_readv_from_socket(server, &smb_msg);
791 	if (ret > 0)
792 		iov_iter_advance(iter, ret);
793 	return ret;
794 }
795 
796 static bool
797 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
798 {
799 	/*
800 	 * The first byte big endian of the length field,
801 	 * is actually not part of the length but the type
802 	 * with the most common, zero, as regular data.
803 	 */
804 	switch (type) {
805 	case RFC1002_SESSION_MESSAGE:
806 		/* Regular SMB response */
807 		return true;
808 	case RFC1002_SESSION_KEEP_ALIVE:
809 		cifs_dbg(FYI, "RFC 1002 session keep alive\n");
810 		break;
811 	case RFC1002_POSITIVE_SESSION_RESPONSE:
812 		cifs_dbg(FYI, "RFC 1002 positive session response\n");
813 		break;
814 	case RFC1002_NEGATIVE_SESSION_RESPONSE:
815 		/*
816 		 * We get this from Windows 98 instead of an error on
817 		 * SMB negprot response.
818 		 */
819 		cifs_dbg(FYI, "RFC 1002 negative session response\n");
820 		/* give server a second to clean up */
821 		msleep(1000);
822 		/*
823 		 * Always try 445 first on reconnect since we get NACK
824 		 * on some if we ever connected to port 139 (the NACK
825 		 * is since we do not begin with RFC1001 session
826 		 * initialize frame).
827 		 */
828 		cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
829 		cifs_reconnect(server, true);
830 		break;
831 	default:
832 		cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
833 		cifs_reconnect(server, true);
834 	}
835 
836 	return false;
837 }
838 
839 void
840 dequeue_mid(struct mid_q_entry *mid, bool malformed)
841 {
842 #ifdef CONFIG_CIFS_STATS2
843 	mid->when_received = jiffies;
844 #endif
845 	spin_lock(&mid->server->mid_lock);
846 	if (!malformed)
847 		mid->mid_state = MID_RESPONSE_RECEIVED;
848 	else
849 		mid->mid_state = MID_RESPONSE_MALFORMED;
850 	/*
851 	 * Trying to handle/dequeue a mid after the send_recv()
852 	 * function has finished processing it is a bug.
853 	 */
854 	if (mid->mid_flags & MID_DELETED) {
855 		spin_unlock(&mid->server->mid_lock);
856 		pr_warn_once("trying to dequeue a deleted mid\n");
857 	} else {
858 		list_del_init(&mid->qhead);
859 		mid->mid_flags |= MID_DELETED;
860 		spin_unlock(&mid->server->mid_lock);
861 	}
862 }
863 
864 static unsigned int
865 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
866 {
867 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
868 
869 	/*
870 	 * SMB1 does not use credits.
871 	 */
872 	if (is_smb1(server))
873 		return 0;
874 
875 	return le16_to_cpu(shdr->CreditRequest);
876 }
877 
878 static void
879 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
880 	   char *buf, int malformed)
881 {
882 	if (server->ops->check_trans2 &&
883 	    server->ops->check_trans2(mid, server, buf, malformed))
884 		return;
885 	mid->credits_received = smb2_get_credits_from_hdr(buf, server);
886 	mid->resp_buf = buf;
887 	mid->large_buf = server->large_buf;
888 	/* Was previous buf put in mpx struct for multi-rsp? */
889 	if (!mid->multiRsp) {
890 		/* smb buffer will be freed by user thread */
891 		if (server->large_buf)
892 			server->bigbuf = NULL;
893 		else
894 			server->smallbuf = NULL;
895 	}
896 	dequeue_mid(mid, malformed);
897 }
898 
899 int
900 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
901 {
902 	bool srv_sign_required = server->sec_mode & server->vals->signing_required;
903 	bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
904 	bool mnt_sign_enabled;
905 
906 	/*
907 	 * Is signing required by mnt options? If not then check
908 	 * global_secflags to see if it is there.
909 	 */
910 	if (!mnt_sign_required)
911 		mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
912 						CIFSSEC_MUST_SIGN);
913 
914 	/*
915 	 * If signing is required then it's automatically enabled too,
916 	 * otherwise, check to see if the secflags allow it.
917 	 */
918 	mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
919 				(global_secflags & CIFSSEC_MAY_SIGN);
920 
921 	/* If server requires signing, does client allow it? */
922 	if (srv_sign_required) {
923 		if (!mnt_sign_enabled) {
924 			cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
925 			return -EOPNOTSUPP;
926 		}
927 		server->sign = true;
928 	}
929 
930 	/* If client requires signing, does server allow it? */
931 	if (mnt_sign_required) {
932 		if (!srv_sign_enabled) {
933 			cifs_dbg(VFS, "Server does not support signing!\n");
934 			return -EOPNOTSUPP;
935 		}
936 		server->sign = true;
937 	}
938 
939 	if (cifs_rdma_enabled(server) && server->sign)
940 		cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
941 
942 	return 0;
943 }
944 
945 static noinline_for_stack void
946 clean_demultiplex_info(struct TCP_Server_Info *server)
947 {
948 	int length;
949 
950 	/* take it off the list, if it's not already */
951 	spin_lock(&server->srv_lock);
952 	list_del_init(&server->tcp_ses_list);
953 	spin_unlock(&server->srv_lock);
954 
955 	cancel_delayed_work_sync(&server->echo);
956 
957 	spin_lock(&server->srv_lock);
958 	server->tcpStatus = CifsExiting;
959 	spin_unlock(&server->srv_lock);
960 	wake_up_all(&server->response_q);
961 
962 	/* check if we have blocked requests that need to free */
963 	spin_lock(&server->req_lock);
964 	if (server->credits <= 0)
965 		server->credits = 1;
966 	spin_unlock(&server->req_lock);
967 	/*
968 	 * Although there should not be any requests blocked on this queue it
969 	 * can not hurt to be paranoid and try to wake up requests that may
970 	 * haven been blocked when more than 50 at time were on the wire to the
971 	 * same server - they now will see the session is in exit state and get
972 	 * out of SendReceive.
973 	 */
974 	wake_up_all(&server->request_q);
975 	/* give those requests time to exit */
976 	msleep(125);
977 	if (cifs_rdma_enabled(server))
978 		smbd_destroy(server);
979 	if (server->ssocket) {
980 		sock_release(server->ssocket);
981 		server->ssocket = NULL;
982 	}
983 
984 	if (!list_empty(&server->pending_mid_q)) {
985 		struct list_head dispose_list;
986 		struct mid_q_entry *mid_entry;
987 		struct list_head *tmp, *tmp2;
988 
989 		INIT_LIST_HEAD(&dispose_list);
990 		spin_lock(&server->mid_lock);
991 		list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
992 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
993 			cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
994 			kref_get(&mid_entry->refcount);
995 			mid_entry->mid_state = MID_SHUTDOWN;
996 			list_move(&mid_entry->qhead, &dispose_list);
997 			mid_entry->mid_flags |= MID_DELETED;
998 		}
999 		spin_unlock(&server->mid_lock);
1000 
1001 		/* now walk dispose list and issue callbacks */
1002 		list_for_each_safe(tmp, tmp2, &dispose_list) {
1003 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1004 			cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1005 			list_del_init(&mid_entry->qhead);
1006 			mid_entry->callback(mid_entry);
1007 			release_mid(mid_entry);
1008 		}
1009 		/* 1/8th of sec is more than enough time for them to exit */
1010 		msleep(125);
1011 	}
1012 
1013 	if (!list_empty(&server->pending_mid_q)) {
1014 		/*
1015 		 * mpx threads have not exited yet give them at least the smb
1016 		 * send timeout time for long ops.
1017 		 *
1018 		 * Due to delays on oplock break requests, we need to wait at
1019 		 * least 45 seconds before giving up on a request getting a
1020 		 * response and going ahead and killing cifsd.
1021 		 */
1022 		cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1023 		msleep(46000);
1024 		/*
1025 		 * If threads still have not exited they are probably never
1026 		 * coming home not much else we can do but free the memory.
1027 		 */
1028 	}
1029 
1030 	kfree(server->leaf_fullpath);
1031 	kfree(server);
1032 
1033 	length = atomic_dec_return(&tcpSesAllocCount);
1034 	if (length > 0)
1035 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1036 }
1037 
1038 static int
1039 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1040 {
1041 	int length;
1042 	char *buf = server->smallbuf;
1043 	unsigned int pdu_length = server->pdu_size;
1044 
1045 	/* make sure this will fit in a large buffer */
1046 	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1047 	    HEADER_PREAMBLE_SIZE(server)) {
1048 		cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1049 		cifs_reconnect(server, true);
1050 		return -ECONNABORTED;
1051 	}
1052 
1053 	/* switch to large buffer if too big for a small one */
1054 	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1055 		server->large_buf = true;
1056 		memcpy(server->bigbuf, buf, server->total_read);
1057 		buf = server->bigbuf;
1058 	}
1059 
1060 	/* now read the rest */
1061 	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1062 				       pdu_length - MID_HEADER_SIZE(server));
1063 
1064 	if (length < 0)
1065 		return length;
1066 	server->total_read += length;
1067 
1068 	dump_smb(buf, server->total_read);
1069 
1070 	return cifs_handle_standard(server, mid);
1071 }
1072 
1073 int
1074 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1075 {
1076 	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1077 	int rc;
1078 
1079 	/*
1080 	 * We know that we received enough to get to the MID as we
1081 	 * checked the pdu_length earlier. Now check to see
1082 	 * if the rest of the header is OK.
1083 	 *
1084 	 * 48 bytes is enough to display the header and a little bit
1085 	 * into the payload for debugging purposes.
1086 	 */
1087 	rc = server->ops->check_message(buf, server->total_read, server);
1088 	if (rc)
1089 		cifs_dump_mem("Bad SMB: ", buf,
1090 			min_t(unsigned int, server->total_read, 48));
1091 
1092 	if (server->ops->is_session_expired &&
1093 	    server->ops->is_session_expired(buf)) {
1094 		cifs_reconnect(server, true);
1095 		return -1;
1096 	}
1097 
1098 	if (server->ops->is_status_pending &&
1099 	    server->ops->is_status_pending(buf, server))
1100 		return -1;
1101 
1102 	if (!mid)
1103 		return rc;
1104 
1105 	handle_mid(mid, server, buf, rc);
1106 	return 0;
1107 }
1108 
1109 static void
1110 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1111 {
1112 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1113 	int scredits, in_flight;
1114 
1115 	/*
1116 	 * SMB1 does not use credits.
1117 	 */
1118 	if (is_smb1(server))
1119 		return;
1120 
1121 	if (shdr->CreditRequest) {
1122 		spin_lock(&server->req_lock);
1123 		server->credits += le16_to_cpu(shdr->CreditRequest);
1124 		scredits = server->credits;
1125 		in_flight = server->in_flight;
1126 		spin_unlock(&server->req_lock);
1127 		wake_up(&server->request_q);
1128 
1129 		trace_smb3_hdr_credits(server->CurrentMid,
1130 				server->conn_id, server->hostname, scredits,
1131 				le16_to_cpu(shdr->CreditRequest), in_flight);
1132 		cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1133 				__func__, le16_to_cpu(shdr->CreditRequest),
1134 				scredits);
1135 	}
1136 }
1137 
1138 
1139 static int
1140 cifs_demultiplex_thread(void *p)
1141 {
1142 	int i, num_mids, length;
1143 	struct TCP_Server_Info *server = p;
1144 	unsigned int pdu_length;
1145 	unsigned int next_offset;
1146 	char *buf = NULL;
1147 	struct task_struct *task_to_wake = NULL;
1148 	struct mid_q_entry *mids[MAX_COMPOUND];
1149 	char *bufs[MAX_COMPOUND];
1150 	unsigned int noreclaim_flag, num_io_timeout = 0;
1151 	bool pending_reconnect = false;
1152 
1153 	noreclaim_flag = memalloc_noreclaim_save();
1154 	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1155 
1156 	length = atomic_inc_return(&tcpSesAllocCount);
1157 	if (length > 1)
1158 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1159 
1160 	set_freezable();
1161 	allow_kernel_signal(SIGKILL);
1162 	while (server->tcpStatus != CifsExiting) {
1163 		if (try_to_freeze())
1164 			continue;
1165 
1166 		if (!allocate_buffers(server))
1167 			continue;
1168 
1169 		server->large_buf = false;
1170 		buf = server->smallbuf;
1171 		pdu_length = 4; /* enough to get RFC1001 header */
1172 
1173 		length = cifs_read_from_socket(server, buf, pdu_length);
1174 		if (length < 0)
1175 			continue;
1176 
1177 		if (is_smb1(server))
1178 			server->total_read = length;
1179 		else
1180 			server->total_read = 0;
1181 
1182 		/*
1183 		 * The right amount was read from socket - 4 bytes,
1184 		 * so we can now interpret the length field.
1185 		 */
1186 		pdu_length = get_rfc1002_length(buf);
1187 
1188 		cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1189 		if (!is_smb_response(server, buf[0]))
1190 			continue;
1191 
1192 		pending_reconnect = false;
1193 next_pdu:
1194 		server->pdu_size = pdu_length;
1195 
1196 		/* make sure we have enough to get to the MID */
1197 		if (server->pdu_size < MID_HEADER_SIZE(server)) {
1198 			cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1199 				 server->pdu_size);
1200 			cifs_reconnect(server, true);
1201 			continue;
1202 		}
1203 
1204 		/* read down to the MID */
1205 		length = cifs_read_from_socket(server,
1206 			     buf + HEADER_PREAMBLE_SIZE(server),
1207 			     MID_HEADER_SIZE(server));
1208 		if (length < 0)
1209 			continue;
1210 		server->total_read += length;
1211 
1212 		if (server->ops->next_header) {
1213 			if (server->ops->next_header(server, buf, &next_offset)) {
1214 				cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1215 					 __func__, next_offset);
1216 				cifs_reconnect(server, true);
1217 				continue;
1218 			}
1219 			if (next_offset)
1220 				server->pdu_size = next_offset;
1221 		}
1222 
1223 		memset(mids, 0, sizeof(mids));
1224 		memset(bufs, 0, sizeof(bufs));
1225 		num_mids = 0;
1226 
1227 		if (server->ops->is_transform_hdr &&
1228 		    server->ops->receive_transform &&
1229 		    server->ops->is_transform_hdr(buf)) {
1230 			length = server->ops->receive_transform(server,
1231 								mids,
1232 								bufs,
1233 								&num_mids);
1234 		} else {
1235 			mids[0] = server->ops->find_mid(server, buf);
1236 			bufs[0] = buf;
1237 			num_mids = 1;
1238 
1239 			if (!mids[0] || !mids[0]->receive)
1240 				length = standard_receive3(server, mids[0]);
1241 			else
1242 				length = mids[0]->receive(server, mids[0]);
1243 		}
1244 
1245 		if (length < 0) {
1246 			for (i = 0; i < num_mids; i++)
1247 				if (mids[i])
1248 					release_mid(mids[i]);
1249 			continue;
1250 		}
1251 
1252 		if (server->ops->is_status_io_timeout &&
1253 		    server->ops->is_status_io_timeout(buf)) {
1254 			num_io_timeout++;
1255 			if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1256 				cifs_server_dbg(VFS,
1257 						"Number of request timeouts exceeded %d. Reconnecting",
1258 						MAX_STATUS_IO_TIMEOUT);
1259 
1260 				pending_reconnect = true;
1261 				num_io_timeout = 0;
1262 			}
1263 		}
1264 
1265 		server->lstrp = jiffies;
1266 
1267 		for (i = 0; i < num_mids; i++) {
1268 			if (mids[i] != NULL) {
1269 				mids[i]->resp_buf_size = server->pdu_size;
1270 
1271 				if (bufs[i] != NULL) {
1272 					if (server->ops->is_network_name_deleted &&
1273 					    server->ops->is_network_name_deleted(bufs[i],
1274 										 server)) {
1275 						cifs_server_dbg(FYI,
1276 								"Share deleted. Reconnect needed");
1277 					}
1278 				}
1279 
1280 				if (!mids[i]->multiRsp || mids[i]->multiEnd)
1281 					mids[i]->callback(mids[i]);
1282 
1283 				release_mid(mids[i]);
1284 			} else if (server->ops->is_oplock_break &&
1285 				   server->ops->is_oplock_break(bufs[i],
1286 								server)) {
1287 				smb2_add_credits_from_hdr(bufs[i], server);
1288 				cifs_dbg(FYI, "Received oplock break\n");
1289 			} else {
1290 				cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1291 						atomic_read(&mid_count));
1292 				cifs_dump_mem("Received Data is: ", bufs[i],
1293 					      HEADER_SIZE(server));
1294 				smb2_add_credits_from_hdr(bufs[i], server);
1295 #ifdef CONFIG_CIFS_DEBUG2
1296 				if (server->ops->dump_detail)
1297 					server->ops->dump_detail(bufs[i],
1298 								 server);
1299 				cifs_dump_mids(server);
1300 #endif /* CIFS_DEBUG2 */
1301 			}
1302 		}
1303 
1304 		if (pdu_length > server->pdu_size) {
1305 			if (!allocate_buffers(server))
1306 				continue;
1307 			pdu_length -= server->pdu_size;
1308 			server->total_read = 0;
1309 			server->large_buf = false;
1310 			buf = server->smallbuf;
1311 			goto next_pdu;
1312 		}
1313 
1314 		/* do this reconnect at the very end after processing all MIDs */
1315 		if (pending_reconnect)
1316 			cifs_reconnect(server, true);
1317 
1318 	} /* end while !EXITING */
1319 
1320 	/* buffer usually freed in free_mid - need to free it here on exit */
1321 	cifs_buf_release(server->bigbuf);
1322 	if (server->smallbuf) /* no sense logging a debug message if NULL */
1323 		cifs_small_buf_release(server->smallbuf);
1324 
1325 	task_to_wake = xchg(&server->tsk, NULL);
1326 	clean_demultiplex_info(server);
1327 
1328 	/* if server->tsk was NULL then wait for a signal before exiting */
1329 	if (!task_to_wake) {
1330 		set_current_state(TASK_INTERRUPTIBLE);
1331 		while (!signal_pending(current)) {
1332 			schedule();
1333 			set_current_state(TASK_INTERRUPTIBLE);
1334 		}
1335 		set_current_state(TASK_RUNNING);
1336 	}
1337 
1338 	memalloc_noreclaim_restore(noreclaim_flag);
1339 	module_put_and_kthread_exit(0);
1340 }
1341 
1342 int
1343 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1344 {
1345 	struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1346 	struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1347 	struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1348 	struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1349 
1350 	switch (srcaddr->sa_family) {
1351 	case AF_UNSPEC:
1352 		switch (rhs->sa_family) {
1353 		case AF_UNSPEC:
1354 			return 0;
1355 		case AF_INET:
1356 		case AF_INET6:
1357 			return 1;
1358 		default:
1359 			return -1;
1360 		}
1361 	case AF_INET: {
1362 		switch (rhs->sa_family) {
1363 		case AF_UNSPEC:
1364 			return -1;
1365 		case AF_INET:
1366 			return memcmp(saddr4, vaddr4,
1367 				      sizeof(struct sockaddr_in));
1368 		case AF_INET6:
1369 			return 1;
1370 		default:
1371 			return -1;
1372 		}
1373 	}
1374 	case AF_INET6: {
1375 		switch (rhs->sa_family) {
1376 		case AF_UNSPEC:
1377 		case AF_INET:
1378 			return -1;
1379 		case AF_INET6:
1380 			return memcmp(saddr6,
1381 				      vaddr6,
1382 				      sizeof(struct sockaddr_in6));
1383 		default:
1384 			return -1;
1385 		}
1386 	}
1387 	default:
1388 		return -1; /* don't expect to be here */
1389 	}
1390 }
1391 
1392 /*
1393  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1394  * if srcaddr is specified and matches the IP address of the rhs argument
1395  */
1396 bool
1397 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1398 {
1399 	switch (srcaddr->sa_family) {
1400 	case AF_UNSPEC:
1401 		return (rhs->sa_family == AF_UNSPEC);
1402 	case AF_INET: {
1403 		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1404 		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1405 
1406 		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1407 	}
1408 	case AF_INET6: {
1409 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1410 		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1411 
1412 		return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1413 			&& saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1414 	}
1415 	default:
1416 		WARN_ON(1);
1417 		return false; /* don't expect to be here */
1418 	}
1419 }
1420 
1421 /*
1422  * If no port is specified in addr structure, we try to match with 445 port
1423  * and if it fails - with 139 ports. It should be called only if address
1424  * families of server and addr are equal.
1425  */
1426 static bool
1427 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1428 {
1429 	__be16 port, *sport;
1430 
1431 	/* SMBDirect manages its own ports, don't match it here */
1432 	if (server->rdma)
1433 		return true;
1434 
1435 	switch (addr->sa_family) {
1436 	case AF_INET:
1437 		sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1438 		port = ((struct sockaddr_in *) addr)->sin_port;
1439 		break;
1440 	case AF_INET6:
1441 		sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1442 		port = ((struct sockaddr_in6 *) addr)->sin6_port;
1443 		break;
1444 	default:
1445 		WARN_ON(1);
1446 		return false;
1447 	}
1448 
1449 	if (!port) {
1450 		port = htons(CIFS_PORT);
1451 		if (port == *sport)
1452 			return true;
1453 
1454 		port = htons(RFC1001_PORT);
1455 	}
1456 
1457 	return port == *sport;
1458 }
1459 
1460 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1461 {
1462 	if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1463 		return false;
1464 
1465 	return true;
1466 }
1467 
1468 static bool
1469 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1470 {
1471 	/*
1472 	 * The select_sectype function should either return the ctx->sectype
1473 	 * that was specified, or "Unspecified" if that sectype was not
1474 	 * compatible with the given NEGOTIATE request.
1475 	 */
1476 	if (server->ops->select_sectype(server, ctx->sectype)
1477 	     == Unspecified)
1478 		return false;
1479 
1480 	/*
1481 	 * Now check if signing mode is acceptable. No need to check
1482 	 * global_secflags at this point since if MUST_SIGN is set then
1483 	 * the server->sign had better be too.
1484 	 */
1485 	if (ctx->sign && !server->sign)
1486 		return false;
1487 
1488 	return true;
1489 }
1490 
1491 /* this function must be called with srv_lock held */
1492 static int match_server(struct TCP_Server_Info *server,
1493 			struct smb3_fs_context *ctx,
1494 			bool match_super)
1495 {
1496 	struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1497 
1498 	lockdep_assert_held(&server->srv_lock);
1499 
1500 	if (ctx->nosharesock)
1501 		return 0;
1502 
1503 	/* this server does not share socket */
1504 	if (server->nosharesock)
1505 		return 0;
1506 
1507 	/* If multidialect negotiation see if existing sessions match one */
1508 	if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1509 		if (server->vals->protocol_id < SMB30_PROT_ID)
1510 			return 0;
1511 	} else if (strcmp(ctx->vals->version_string,
1512 		   SMBDEFAULT_VERSION_STRING) == 0) {
1513 		if (server->vals->protocol_id < SMB21_PROT_ID)
1514 			return 0;
1515 	} else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1516 		return 0;
1517 
1518 	if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1519 		return 0;
1520 
1521 	if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1522 			       (struct sockaddr *)&server->srcaddr))
1523 		return 0;
1524 	/*
1525 	 * When matching cifs.ko superblocks (@match_super == true), we can't
1526 	 * really match either @server->leaf_fullpath or @server->dstaddr
1527 	 * directly since this @server might belong to a completely different
1528 	 * server -- in case of domain-based DFS referrals or DFS links -- as
1529 	 * provided earlier by mount(2) through 'source' and 'ip' options.
1530 	 *
1531 	 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1532 	 * destination address in @server->dstaddr.
1533 	 *
1534 	 * When using 'nodfs' mount option, we avoid sharing it with DFS
1535 	 * connections as they might failover.
1536 	 */
1537 	if (!match_super) {
1538 		if (!ctx->nodfs) {
1539 			if (server->leaf_fullpath) {
1540 				if (!ctx->leaf_fullpath ||
1541 				    strcasecmp(server->leaf_fullpath,
1542 					       ctx->leaf_fullpath))
1543 					return 0;
1544 			} else if (ctx->leaf_fullpath) {
1545 				return 0;
1546 			}
1547 		} else if (server->leaf_fullpath) {
1548 			return 0;
1549 		}
1550 	}
1551 
1552 	/*
1553 	 * Match for a regular connection (address/hostname/port) which has no
1554 	 * DFS referrals set.
1555 	 */
1556 	if (!server->leaf_fullpath &&
1557 	    (strcasecmp(server->hostname, ctx->server_hostname) ||
1558 	     !match_server_address(server, addr) ||
1559 	     !match_port(server, addr)))
1560 		return 0;
1561 
1562 	if (!match_security(server, ctx))
1563 		return 0;
1564 
1565 	if (server->echo_interval != ctx->echo_interval * HZ)
1566 		return 0;
1567 
1568 	if (server->rdma != ctx->rdma)
1569 		return 0;
1570 
1571 	if (server->ignore_signature != ctx->ignore_signature)
1572 		return 0;
1573 
1574 	if (server->min_offload != ctx->min_offload)
1575 		return 0;
1576 
1577 	return 1;
1578 }
1579 
1580 struct TCP_Server_Info *
1581 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1582 {
1583 	struct TCP_Server_Info *server;
1584 
1585 	spin_lock(&cifs_tcp_ses_lock);
1586 	list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1587 		spin_lock(&server->srv_lock);
1588 		/*
1589 		 * Skip ses channels since they're only handled in lower layers
1590 		 * (e.g. cifs_send_recv).
1591 		 */
1592 		if (SERVER_IS_CHAN(server) ||
1593 		    !match_server(server, ctx, false)) {
1594 			spin_unlock(&server->srv_lock);
1595 			continue;
1596 		}
1597 		spin_unlock(&server->srv_lock);
1598 
1599 		++server->srv_count;
1600 		spin_unlock(&cifs_tcp_ses_lock);
1601 		cifs_dbg(FYI, "Existing tcp session with server found\n");
1602 		return server;
1603 	}
1604 	spin_unlock(&cifs_tcp_ses_lock);
1605 	return NULL;
1606 }
1607 
1608 void
1609 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1610 {
1611 	struct task_struct *task;
1612 
1613 	spin_lock(&cifs_tcp_ses_lock);
1614 	if (--server->srv_count > 0) {
1615 		spin_unlock(&cifs_tcp_ses_lock);
1616 		return;
1617 	}
1618 
1619 	/* srv_count can never go negative */
1620 	WARN_ON(server->srv_count < 0);
1621 
1622 	put_net(cifs_net_ns(server));
1623 
1624 	list_del_init(&server->tcp_ses_list);
1625 	spin_unlock(&cifs_tcp_ses_lock);
1626 
1627 	cancel_delayed_work_sync(&server->echo);
1628 
1629 	if (from_reconnect)
1630 		/*
1631 		 * Avoid deadlock here: reconnect work calls
1632 		 * cifs_put_tcp_session() at its end. Need to be sure
1633 		 * that reconnect work does nothing with server pointer after
1634 		 * that step.
1635 		 */
1636 		cancel_delayed_work(&server->reconnect);
1637 	else
1638 		cancel_delayed_work_sync(&server->reconnect);
1639 
1640 	/* For secondary channels, we pick up ref-count on the primary server */
1641 	if (SERVER_IS_CHAN(server))
1642 		cifs_put_tcp_session(server->primary_server, from_reconnect);
1643 
1644 	spin_lock(&server->srv_lock);
1645 	server->tcpStatus = CifsExiting;
1646 	spin_unlock(&server->srv_lock);
1647 
1648 	cifs_crypto_secmech_release(server);
1649 
1650 	kfree_sensitive(server->session_key.response);
1651 	server->session_key.response = NULL;
1652 	server->session_key.len = 0;
1653 	kfree(server->hostname);
1654 	server->hostname = NULL;
1655 
1656 	task = xchg(&server->tsk, NULL);
1657 	if (task)
1658 		send_sig(SIGKILL, task, 1);
1659 }
1660 
1661 struct TCP_Server_Info *
1662 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1663 		     struct TCP_Server_Info *primary_server)
1664 {
1665 	struct TCP_Server_Info *tcp_ses = NULL;
1666 	int rc;
1667 
1668 	cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1669 
1670 	/* see if we already have a matching tcp_ses */
1671 	tcp_ses = cifs_find_tcp_session(ctx);
1672 	if (tcp_ses)
1673 		return tcp_ses;
1674 
1675 	tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1676 	if (!tcp_ses) {
1677 		rc = -ENOMEM;
1678 		goto out_err;
1679 	}
1680 
1681 	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1682 	if (!tcp_ses->hostname) {
1683 		rc = -ENOMEM;
1684 		goto out_err;
1685 	}
1686 
1687 	if (ctx->leaf_fullpath) {
1688 		tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1689 		if (!tcp_ses->leaf_fullpath) {
1690 			rc = -ENOMEM;
1691 			goto out_err;
1692 		}
1693 	}
1694 
1695 	if (ctx->nosharesock)
1696 		tcp_ses->nosharesock = true;
1697 
1698 	tcp_ses->ops = ctx->ops;
1699 	tcp_ses->vals = ctx->vals;
1700 	cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1701 
1702 	tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1703 	tcp_ses->noblockcnt = ctx->rootfs;
1704 	tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1705 	tcp_ses->noautotune = ctx->noautotune;
1706 	tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1707 	tcp_ses->rdma = ctx->rdma;
1708 	tcp_ses->in_flight = 0;
1709 	tcp_ses->max_in_flight = 0;
1710 	tcp_ses->credits = 1;
1711 	if (primary_server) {
1712 		spin_lock(&cifs_tcp_ses_lock);
1713 		++primary_server->srv_count;
1714 		spin_unlock(&cifs_tcp_ses_lock);
1715 		tcp_ses->primary_server = primary_server;
1716 	}
1717 	init_waitqueue_head(&tcp_ses->response_q);
1718 	init_waitqueue_head(&tcp_ses->request_q);
1719 	INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1720 	mutex_init(&tcp_ses->_srv_mutex);
1721 	memcpy(tcp_ses->workstation_RFC1001_name,
1722 		ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1723 	memcpy(tcp_ses->server_RFC1001_name,
1724 		ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1725 	tcp_ses->session_estab = false;
1726 	tcp_ses->sequence_number = 0;
1727 	tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1728 	tcp_ses->reconnect_instance = 1;
1729 	tcp_ses->lstrp = jiffies;
1730 	tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1731 	spin_lock_init(&tcp_ses->req_lock);
1732 	spin_lock_init(&tcp_ses->srv_lock);
1733 	spin_lock_init(&tcp_ses->mid_lock);
1734 	INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1735 	INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1736 	INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1737 	INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1738 	mutex_init(&tcp_ses->reconnect_mutex);
1739 #ifdef CONFIG_CIFS_DFS_UPCALL
1740 	mutex_init(&tcp_ses->refpath_lock);
1741 #endif
1742 	memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1743 	       sizeof(tcp_ses->srcaddr));
1744 	memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1745 		sizeof(tcp_ses->dstaddr));
1746 	if (ctx->use_client_guid)
1747 		memcpy(tcp_ses->client_guid, ctx->client_guid,
1748 		       SMB2_CLIENT_GUID_SIZE);
1749 	else
1750 		generate_random_uuid(tcp_ses->client_guid);
1751 	/*
1752 	 * at this point we are the only ones with the pointer
1753 	 * to the struct since the kernel thread not created yet
1754 	 * no need to spinlock this init of tcpStatus or srv_count
1755 	 */
1756 	tcp_ses->tcpStatus = CifsNew;
1757 	++tcp_ses->srv_count;
1758 
1759 	if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1760 		ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1761 		tcp_ses->echo_interval = ctx->echo_interval * HZ;
1762 	else
1763 		tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1764 	if (tcp_ses->rdma) {
1765 #ifndef CONFIG_CIFS_SMB_DIRECT
1766 		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1767 		rc = -ENOENT;
1768 		goto out_err_crypto_release;
1769 #endif
1770 		tcp_ses->smbd_conn = smbd_get_connection(
1771 			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1772 		if (tcp_ses->smbd_conn) {
1773 			cifs_dbg(VFS, "RDMA transport established\n");
1774 			rc = 0;
1775 			goto smbd_connected;
1776 		} else {
1777 			rc = -ENOENT;
1778 			goto out_err_crypto_release;
1779 		}
1780 	}
1781 	rc = ip_connect(tcp_ses);
1782 	if (rc < 0) {
1783 		cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1784 		goto out_err_crypto_release;
1785 	}
1786 smbd_connected:
1787 	/*
1788 	 * since we're in a cifs function already, we know that
1789 	 * this will succeed. No need for try_module_get().
1790 	 */
1791 	__module_get(THIS_MODULE);
1792 	tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1793 				  tcp_ses, "cifsd");
1794 	if (IS_ERR(tcp_ses->tsk)) {
1795 		rc = PTR_ERR(tcp_ses->tsk);
1796 		cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1797 		module_put(THIS_MODULE);
1798 		goto out_err_crypto_release;
1799 	}
1800 	tcp_ses->min_offload = ctx->min_offload;
1801 	/*
1802 	 * at this point we are the only ones with the pointer
1803 	 * to the struct since the kernel thread not created yet
1804 	 * no need to spinlock this update of tcpStatus
1805 	 */
1806 	spin_lock(&tcp_ses->srv_lock);
1807 	tcp_ses->tcpStatus = CifsNeedNegotiate;
1808 	spin_unlock(&tcp_ses->srv_lock);
1809 
1810 	if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1811 		tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1812 	else
1813 		tcp_ses->max_credits = ctx->max_credits;
1814 
1815 	tcp_ses->nr_targets = 1;
1816 	tcp_ses->ignore_signature = ctx->ignore_signature;
1817 	/* thread spawned, put it on the list */
1818 	spin_lock(&cifs_tcp_ses_lock);
1819 	list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1820 	spin_unlock(&cifs_tcp_ses_lock);
1821 
1822 	/* queue echo request delayed work */
1823 	queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1824 
1825 	return tcp_ses;
1826 
1827 out_err_crypto_release:
1828 	cifs_crypto_secmech_release(tcp_ses);
1829 
1830 	put_net(cifs_net_ns(tcp_ses));
1831 
1832 out_err:
1833 	if (tcp_ses) {
1834 		if (SERVER_IS_CHAN(tcp_ses))
1835 			cifs_put_tcp_session(tcp_ses->primary_server, false);
1836 		kfree(tcp_ses->hostname);
1837 		kfree(tcp_ses->leaf_fullpath);
1838 		if (tcp_ses->ssocket)
1839 			sock_release(tcp_ses->ssocket);
1840 		kfree(tcp_ses);
1841 	}
1842 	return ERR_PTR(rc);
1843 }
1844 
1845 /* this function must be called with ses_lock and chan_lock held */
1846 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1847 {
1848 	if (ctx->sectype != Unspecified &&
1849 	    ctx->sectype != ses->sectype)
1850 		return 0;
1851 
1852 	/*
1853 	 * If an existing session is limited to less channels than
1854 	 * requested, it should not be reused
1855 	 */
1856 	if (ses->chan_max < ctx->max_channels)
1857 		return 0;
1858 
1859 	switch (ses->sectype) {
1860 	case Kerberos:
1861 		if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1862 			return 0;
1863 		break;
1864 	default:
1865 		/* NULL username means anonymous session */
1866 		if (ses->user_name == NULL) {
1867 			if (!ctx->nullauth)
1868 				return 0;
1869 			break;
1870 		}
1871 
1872 		/* anything else takes username/password */
1873 		if (strncmp(ses->user_name,
1874 			    ctx->username ? ctx->username : "",
1875 			    CIFS_MAX_USERNAME_LEN))
1876 			return 0;
1877 		if ((ctx->username && strlen(ctx->username) != 0) &&
1878 		    ses->password != NULL &&
1879 		    strncmp(ses->password,
1880 			    ctx->password ? ctx->password : "",
1881 			    CIFS_MAX_PASSWORD_LEN))
1882 			return 0;
1883 	}
1884 
1885 	if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1886 		return 0;
1887 
1888 	return 1;
1889 }
1890 
1891 /**
1892  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1893  * @ses: smb session to issue the request on
1894  * @ctx: the superblock configuration context to use for building the
1895  *       new tree connection for the IPC (interprocess communication RPC)
1896  *
1897  * A new IPC connection is made and stored in the session
1898  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1899  */
1900 static int
1901 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1902 {
1903 	int rc = 0, xid;
1904 	struct cifs_tcon *tcon;
1905 	char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1906 	bool seal = false;
1907 	struct TCP_Server_Info *server = ses->server;
1908 
1909 	/*
1910 	 * If the mount request that resulted in the creation of the
1911 	 * session requires encryption, force IPC to be encrypted too.
1912 	 */
1913 	if (ctx->seal) {
1914 		if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1915 			seal = true;
1916 		else {
1917 			cifs_server_dbg(VFS,
1918 				 "IPC: server doesn't support encryption\n");
1919 			return -EOPNOTSUPP;
1920 		}
1921 	}
1922 
1923 	/* no need to setup directory caching on IPC share, so pass in false */
1924 	tcon = tcon_info_alloc(false);
1925 	if (tcon == NULL)
1926 		return -ENOMEM;
1927 
1928 	spin_lock(&server->srv_lock);
1929 	scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1930 	spin_unlock(&server->srv_lock);
1931 
1932 	xid = get_xid();
1933 	tcon->ses = ses;
1934 	tcon->ipc = true;
1935 	tcon->seal = seal;
1936 	rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1937 	free_xid(xid);
1938 
1939 	if (rc) {
1940 		cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1941 		tconInfoFree(tcon);
1942 		goto out;
1943 	}
1944 
1945 	cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1946 
1947 	spin_lock(&tcon->tc_lock);
1948 	tcon->status = TID_GOOD;
1949 	spin_unlock(&tcon->tc_lock);
1950 	ses->tcon_ipc = tcon;
1951 out:
1952 	return rc;
1953 }
1954 
1955 /**
1956  * cifs_free_ipc - helper to release the session IPC tcon
1957  * @ses: smb session to unmount the IPC from
1958  *
1959  * Needs to be called everytime a session is destroyed.
1960  *
1961  * On session close, the IPC is closed and the server must release all tcons of the session.
1962  * No need to send a tree disconnect here.
1963  *
1964  * Besides, it will make the server to not close durable and resilient files on session close, as
1965  * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1966  */
1967 static int
1968 cifs_free_ipc(struct cifs_ses *ses)
1969 {
1970 	struct cifs_tcon *tcon = ses->tcon_ipc;
1971 
1972 	if (tcon == NULL)
1973 		return 0;
1974 
1975 	tconInfoFree(tcon);
1976 	ses->tcon_ipc = NULL;
1977 	return 0;
1978 }
1979 
1980 static struct cifs_ses *
1981 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1982 {
1983 	struct cifs_ses *ses, *ret = NULL;
1984 
1985 	spin_lock(&cifs_tcp_ses_lock);
1986 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1987 		spin_lock(&ses->ses_lock);
1988 		if (ses->ses_status == SES_EXITING) {
1989 			spin_unlock(&ses->ses_lock);
1990 			continue;
1991 		}
1992 		spin_lock(&ses->chan_lock);
1993 		if (match_session(ses, ctx)) {
1994 			spin_unlock(&ses->chan_lock);
1995 			spin_unlock(&ses->ses_lock);
1996 			ret = ses;
1997 			break;
1998 		}
1999 		spin_unlock(&ses->chan_lock);
2000 		spin_unlock(&ses->ses_lock);
2001 	}
2002 	if (ret)
2003 		cifs_smb_ses_inc_refcount(ret);
2004 	spin_unlock(&cifs_tcp_ses_lock);
2005 	return ret;
2006 }
2007 
2008 void __cifs_put_smb_ses(struct cifs_ses *ses)
2009 {
2010 	struct TCP_Server_Info *server = ses->server;
2011 	unsigned int xid;
2012 	size_t i;
2013 	int rc;
2014 
2015 	spin_lock(&ses->ses_lock);
2016 	if (ses->ses_status == SES_EXITING) {
2017 		spin_unlock(&ses->ses_lock);
2018 		return;
2019 	}
2020 	spin_unlock(&ses->ses_lock);
2021 
2022 	cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2023 	cifs_dbg(FYI,
2024 		 "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
2025 
2026 	spin_lock(&cifs_tcp_ses_lock);
2027 	if (--ses->ses_count > 0) {
2028 		spin_unlock(&cifs_tcp_ses_lock);
2029 		return;
2030 	}
2031 	spin_lock(&ses->ses_lock);
2032 	if (ses->ses_status == SES_GOOD)
2033 		ses->ses_status = SES_EXITING;
2034 	spin_unlock(&ses->ses_lock);
2035 	spin_unlock(&cifs_tcp_ses_lock);
2036 
2037 	/* ses_count can never go negative */
2038 	WARN_ON(ses->ses_count < 0);
2039 
2040 	spin_lock(&ses->ses_lock);
2041 	if (ses->ses_status == SES_EXITING && server->ops->logoff) {
2042 		spin_unlock(&ses->ses_lock);
2043 		cifs_free_ipc(ses);
2044 		xid = get_xid();
2045 		rc = server->ops->logoff(xid, ses);
2046 		if (rc)
2047 			cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2048 				__func__, rc);
2049 		_free_xid(xid);
2050 	} else {
2051 		spin_unlock(&ses->ses_lock);
2052 		cifs_free_ipc(ses);
2053 	}
2054 
2055 	spin_lock(&cifs_tcp_ses_lock);
2056 	list_del_init(&ses->smb_ses_list);
2057 	spin_unlock(&cifs_tcp_ses_lock);
2058 
2059 	/* close any extra channels */
2060 	for (i = 1; i < ses->chan_count; i++) {
2061 		if (ses->chans[i].iface) {
2062 			kref_put(&ses->chans[i].iface->refcount, release_iface);
2063 			ses->chans[i].iface = NULL;
2064 		}
2065 		cifs_put_tcp_session(ses->chans[i].server, 0);
2066 		ses->chans[i].server = NULL;
2067 	}
2068 
2069 	/* we now account for primary channel in iface->refcount */
2070 	if (ses->chans[0].iface) {
2071 		kref_put(&ses->chans[0].iface->refcount, release_iface);
2072 		ses->chans[0].server = NULL;
2073 	}
2074 
2075 	sesInfoFree(ses);
2076 	cifs_put_tcp_session(server, 0);
2077 }
2078 
2079 #ifdef CONFIG_KEYS
2080 
2081 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2082 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2083 
2084 /* Populate username and pw fields from keyring if possible */
2085 static int
2086 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2087 {
2088 	int rc = 0;
2089 	int is_domain = 0;
2090 	const char *delim, *payload;
2091 	char *desc;
2092 	ssize_t len;
2093 	struct key *key;
2094 	struct TCP_Server_Info *server = ses->server;
2095 	struct sockaddr_in *sa;
2096 	struct sockaddr_in6 *sa6;
2097 	const struct user_key_payload *upayload;
2098 
2099 	desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2100 	if (!desc)
2101 		return -ENOMEM;
2102 
2103 	/* try to find an address key first */
2104 	switch (server->dstaddr.ss_family) {
2105 	case AF_INET:
2106 		sa = (struct sockaddr_in *)&server->dstaddr;
2107 		sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2108 		break;
2109 	case AF_INET6:
2110 		sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2111 		sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2112 		break;
2113 	default:
2114 		cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2115 			 server->dstaddr.ss_family);
2116 		rc = -EINVAL;
2117 		goto out_err;
2118 	}
2119 
2120 	cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2121 	key = request_key(&key_type_logon, desc, "");
2122 	if (IS_ERR(key)) {
2123 		if (!ses->domainName) {
2124 			cifs_dbg(FYI, "domainName is NULL\n");
2125 			rc = PTR_ERR(key);
2126 			goto out_err;
2127 		}
2128 
2129 		/* didn't work, try to find a domain key */
2130 		sprintf(desc, "cifs:d:%s", ses->domainName);
2131 		cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2132 		key = request_key(&key_type_logon, desc, "");
2133 		if (IS_ERR(key)) {
2134 			rc = PTR_ERR(key);
2135 			goto out_err;
2136 		}
2137 		is_domain = 1;
2138 	}
2139 
2140 	down_read(&key->sem);
2141 	upayload = user_key_payload_locked(key);
2142 	if (IS_ERR_OR_NULL(upayload)) {
2143 		rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2144 		goto out_key_put;
2145 	}
2146 
2147 	/* find first : in payload */
2148 	payload = upayload->data;
2149 	delim = strnchr(payload, upayload->datalen, ':');
2150 	cifs_dbg(FYI, "payload=%s\n", payload);
2151 	if (!delim) {
2152 		cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2153 			 upayload->datalen);
2154 		rc = -EINVAL;
2155 		goto out_key_put;
2156 	}
2157 
2158 	len = delim - payload;
2159 	if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2160 		cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2161 			 len);
2162 		rc = -EINVAL;
2163 		goto out_key_put;
2164 	}
2165 
2166 	ctx->username = kstrndup(payload, len, GFP_KERNEL);
2167 	if (!ctx->username) {
2168 		cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2169 			 len);
2170 		rc = -ENOMEM;
2171 		goto out_key_put;
2172 	}
2173 	cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2174 
2175 	len = key->datalen - (len + 1);
2176 	if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2177 		cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2178 		rc = -EINVAL;
2179 		kfree(ctx->username);
2180 		ctx->username = NULL;
2181 		goto out_key_put;
2182 	}
2183 
2184 	++delim;
2185 	ctx->password = kstrndup(delim, len, GFP_KERNEL);
2186 	if (!ctx->password) {
2187 		cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2188 			 len);
2189 		rc = -ENOMEM;
2190 		kfree(ctx->username);
2191 		ctx->username = NULL;
2192 		goto out_key_put;
2193 	}
2194 
2195 	/*
2196 	 * If we have a domain key then we must set the domainName in the
2197 	 * for the request.
2198 	 */
2199 	if (is_domain && ses->domainName) {
2200 		ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2201 		if (!ctx->domainname) {
2202 			cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2203 				 len);
2204 			rc = -ENOMEM;
2205 			kfree(ctx->username);
2206 			ctx->username = NULL;
2207 			kfree_sensitive(ctx->password);
2208 			ctx->password = NULL;
2209 			goto out_key_put;
2210 		}
2211 	}
2212 
2213 	strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2214 
2215 out_key_put:
2216 	up_read(&key->sem);
2217 	key_put(key);
2218 out_err:
2219 	kfree(desc);
2220 	cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2221 	return rc;
2222 }
2223 #else /* ! CONFIG_KEYS */
2224 static inline int
2225 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2226 		   struct cifs_ses *ses __attribute__((unused)))
2227 {
2228 	return -ENOSYS;
2229 }
2230 #endif /* CONFIG_KEYS */
2231 
2232 /**
2233  * cifs_get_smb_ses - get a session matching @ctx data from @server
2234  * @server: server to setup the session to
2235  * @ctx: superblock configuration context to use to setup the session
2236  *
2237  * This function assumes it is being called from cifs_mount() where we
2238  * already got a server reference (server refcount +1). See
2239  * cifs_get_tcon() for refcount explanations.
2240  */
2241 struct cifs_ses *
2242 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2243 {
2244 	int rc = 0;
2245 	unsigned int xid;
2246 	struct cifs_ses *ses;
2247 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2248 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2249 
2250 	xid = get_xid();
2251 
2252 	ses = cifs_find_smb_ses(server, ctx);
2253 	if (ses) {
2254 		cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2255 			 ses->ses_status);
2256 
2257 		spin_lock(&ses->chan_lock);
2258 		if (cifs_chan_needs_reconnect(ses, server)) {
2259 			spin_unlock(&ses->chan_lock);
2260 			cifs_dbg(FYI, "Session needs reconnect\n");
2261 
2262 			mutex_lock(&ses->session_mutex);
2263 			rc = cifs_negotiate_protocol(xid, ses, server);
2264 			if (rc) {
2265 				mutex_unlock(&ses->session_mutex);
2266 				/* problem -- put our ses reference */
2267 				cifs_put_smb_ses(ses);
2268 				free_xid(xid);
2269 				return ERR_PTR(rc);
2270 			}
2271 
2272 			rc = cifs_setup_session(xid, ses, server,
2273 						ctx->local_nls);
2274 			if (rc) {
2275 				mutex_unlock(&ses->session_mutex);
2276 				/* problem -- put our reference */
2277 				cifs_put_smb_ses(ses);
2278 				free_xid(xid);
2279 				return ERR_PTR(rc);
2280 			}
2281 			mutex_unlock(&ses->session_mutex);
2282 
2283 			spin_lock(&ses->chan_lock);
2284 		}
2285 		spin_unlock(&ses->chan_lock);
2286 
2287 		/* existing SMB ses has a server reference already */
2288 		cifs_put_tcp_session(server, 0);
2289 		free_xid(xid);
2290 		return ses;
2291 	}
2292 
2293 	rc = -ENOMEM;
2294 
2295 	cifs_dbg(FYI, "Existing smb sess not found\n");
2296 	ses = sesInfoAlloc();
2297 	if (ses == NULL)
2298 		goto get_ses_fail;
2299 
2300 	/* new SMB session uses our server ref */
2301 	ses->server = server;
2302 	if (server->dstaddr.ss_family == AF_INET6)
2303 		sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2304 	else
2305 		sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2306 
2307 	if (ctx->username) {
2308 		ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2309 		if (!ses->user_name)
2310 			goto get_ses_fail;
2311 	}
2312 
2313 	/* ctx->password freed at unmount */
2314 	if (ctx->password) {
2315 		ses->password = kstrdup(ctx->password, GFP_KERNEL);
2316 		if (!ses->password)
2317 			goto get_ses_fail;
2318 	}
2319 	if (ctx->domainname) {
2320 		ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2321 		if (!ses->domainName)
2322 			goto get_ses_fail;
2323 	}
2324 
2325 	strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2326 
2327 	if (ctx->domainauto)
2328 		ses->domainAuto = ctx->domainauto;
2329 	ses->cred_uid = ctx->cred_uid;
2330 	ses->linux_uid = ctx->linux_uid;
2331 
2332 	ses->sectype = ctx->sectype;
2333 	ses->sign = ctx->sign;
2334 	ses->local_nls = load_nls(ctx->local_nls->charset);
2335 
2336 	/* add server as first channel */
2337 	spin_lock(&ses->chan_lock);
2338 	ses->chans[0].server = server;
2339 	ses->chan_count = 1;
2340 	ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2341 	ses->chans_need_reconnect = 1;
2342 	spin_unlock(&ses->chan_lock);
2343 
2344 	mutex_lock(&ses->session_mutex);
2345 	rc = cifs_negotiate_protocol(xid, ses, server);
2346 	if (!rc)
2347 		rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2348 	mutex_unlock(&ses->session_mutex);
2349 
2350 	/* each channel uses a different signing key */
2351 	spin_lock(&ses->chan_lock);
2352 	memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2353 	       sizeof(ses->smb3signingkey));
2354 	spin_unlock(&ses->chan_lock);
2355 
2356 	if (rc)
2357 		goto get_ses_fail;
2358 
2359 	/*
2360 	 * success, put it on the list and add it as first channel
2361 	 * note: the session becomes active soon after this. So you'll
2362 	 * need to lock before changing something in the session.
2363 	 */
2364 	spin_lock(&cifs_tcp_ses_lock);
2365 	ses->dfs_root_ses = ctx->dfs_root_ses;
2366 	if (ses->dfs_root_ses)
2367 		ses->dfs_root_ses->ses_count++;
2368 	list_add(&ses->smb_ses_list, &server->smb_ses_list);
2369 	spin_unlock(&cifs_tcp_ses_lock);
2370 
2371 	cifs_setup_ipc(ses, ctx);
2372 
2373 	free_xid(xid);
2374 
2375 	return ses;
2376 
2377 get_ses_fail:
2378 	sesInfoFree(ses);
2379 	free_xid(xid);
2380 	return ERR_PTR(rc);
2381 }
2382 
2383 /* this function must be called with tc_lock held */
2384 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2385 {
2386 	struct TCP_Server_Info *server = tcon->ses->server;
2387 
2388 	if (tcon->status == TID_EXITING)
2389 		return 0;
2390 
2391 	if (tcon->origin_fullpath) {
2392 		if (!ctx->source ||
2393 		    !dfs_src_pathname_equal(ctx->source,
2394 					    tcon->origin_fullpath))
2395 			return 0;
2396 	} else if (!server->leaf_fullpath &&
2397 		   strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2398 		return 0;
2399 	}
2400 	if (tcon->seal != ctx->seal)
2401 		return 0;
2402 	if (tcon->snapshot_time != ctx->snapshot_time)
2403 		return 0;
2404 	if (tcon->handle_timeout != ctx->handle_timeout)
2405 		return 0;
2406 	if (tcon->no_lease != ctx->no_lease)
2407 		return 0;
2408 	if (tcon->nodelete != ctx->nodelete)
2409 		return 0;
2410 	return 1;
2411 }
2412 
2413 static struct cifs_tcon *
2414 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2415 {
2416 	struct cifs_tcon *tcon;
2417 
2418 	spin_lock(&cifs_tcp_ses_lock);
2419 	list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2420 		spin_lock(&tcon->tc_lock);
2421 		if (!match_tcon(tcon, ctx)) {
2422 			spin_unlock(&tcon->tc_lock);
2423 			continue;
2424 		}
2425 		++tcon->tc_count;
2426 		spin_unlock(&tcon->tc_lock);
2427 		spin_unlock(&cifs_tcp_ses_lock);
2428 		return tcon;
2429 	}
2430 	spin_unlock(&cifs_tcp_ses_lock);
2431 	return NULL;
2432 }
2433 
2434 void
2435 cifs_put_tcon(struct cifs_tcon *tcon)
2436 {
2437 	unsigned int xid;
2438 	struct cifs_ses *ses;
2439 
2440 	/*
2441 	 * IPC tcon share the lifetime of their session and are
2442 	 * destroyed in the session put function
2443 	 */
2444 	if (tcon == NULL || tcon->ipc)
2445 		return;
2446 
2447 	ses = tcon->ses;
2448 	cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2449 	spin_lock(&cifs_tcp_ses_lock);
2450 	spin_lock(&tcon->tc_lock);
2451 	if (--tcon->tc_count > 0) {
2452 		spin_unlock(&tcon->tc_lock);
2453 		spin_unlock(&cifs_tcp_ses_lock);
2454 		return;
2455 	}
2456 
2457 	/* tc_count can never go negative */
2458 	WARN_ON(tcon->tc_count < 0);
2459 
2460 	list_del_init(&tcon->tcon_list);
2461 	tcon->status = TID_EXITING;
2462 	spin_unlock(&tcon->tc_lock);
2463 	spin_unlock(&cifs_tcp_ses_lock);
2464 
2465 	/* cancel polling of interfaces */
2466 	cancel_delayed_work_sync(&tcon->query_interfaces);
2467 #ifdef CONFIG_CIFS_DFS_UPCALL
2468 	cancel_delayed_work_sync(&tcon->dfs_cache_work);
2469 #endif
2470 
2471 	if (tcon->use_witness) {
2472 		int rc;
2473 
2474 		rc = cifs_swn_unregister(tcon);
2475 		if (rc < 0) {
2476 			cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2477 					__func__, rc);
2478 		}
2479 	}
2480 
2481 	xid = get_xid();
2482 	if (ses->server->ops->tree_disconnect)
2483 		ses->server->ops->tree_disconnect(xid, tcon);
2484 	_free_xid(xid);
2485 
2486 	cifs_fscache_release_super_cookie(tcon);
2487 	tconInfoFree(tcon);
2488 	cifs_put_smb_ses(ses);
2489 }
2490 
2491 /**
2492  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2493  * @ses: smb session to issue the request on
2494  * @ctx: the superblock configuration context to use for building the
2495  *
2496  * - tcon refcount is the number of mount points using the tcon.
2497  * - ses refcount is the number of tcon using the session.
2498  *
2499  * 1. This function assumes it is being called from cifs_mount() where
2500  *    we already got a session reference (ses refcount +1).
2501  *
2502  * 2. Since we're in the context of adding a mount point, the end
2503  *    result should be either:
2504  *
2505  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2506  *    its session refcount incremented (1 new tcon). This +1 was
2507  *    already done in (1).
2508  *
2509  * b) an existing tcon with refcount+1 (add a mount point to it) and
2510  *    identical ses refcount (no new tcon). Because of (1) we need to
2511  *    decrement the ses refcount.
2512  */
2513 static struct cifs_tcon *
2514 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2515 {
2516 	struct cifs_tcon *tcon;
2517 	bool nohandlecache;
2518 	int rc, xid;
2519 
2520 	tcon = cifs_find_tcon(ses, ctx);
2521 	if (tcon) {
2522 		/*
2523 		 * tcon has refcount already incremented but we need to
2524 		 * decrement extra ses reference gotten by caller (case b)
2525 		 */
2526 		cifs_dbg(FYI, "Found match on UNC path\n");
2527 		cifs_put_smb_ses(ses);
2528 		return tcon;
2529 	}
2530 
2531 	if (!ses->server->ops->tree_connect) {
2532 		rc = -ENOSYS;
2533 		goto out_fail;
2534 	}
2535 
2536 	if (ses->server->dialect >= SMB20_PROT_ID &&
2537 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2538 		nohandlecache = ctx->nohandlecache;
2539 	else
2540 		nohandlecache = true;
2541 	tcon = tcon_info_alloc(!nohandlecache);
2542 	if (tcon == NULL) {
2543 		rc = -ENOMEM;
2544 		goto out_fail;
2545 	}
2546 	tcon->nohandlecache = nohandlecache;
2547 
2548 	if (ctx->snapshot_time) {
2549 		if (ses->server->vals->protocol_id == 0) {
2550 			cifs_dbg(VFS,
2551 			     "Use SMB2 or later for snapshot mount option\n");
2552 			rc = -EOPNOTSUPP;
2553 			goto out_fail;
2554 		} else
2555 			tcon->snapshot_time = ctx->snapshot_time;
2556 	}
2557 
2558 	if (ctx->handle_timeout) {
2559 		if (ses->server->vals->protocol_id == 0) {
2560 			cifs_dbg(VFS,
2561 			     "Use SMB2.1 or later for handle timeout option\n");
2562 			rc = -EOPNOTSUPP;
2563 			goto out_fail;
2564 		} else
2565 			tcon->handle_timeout = ctx->handle_timeout;
2566 	}
2567 
2568 	tcon->ses = ses;
2569 	if (ctx->password) {
2570 		tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2571 		if (!tcon->password) {
2572 			rc = -ENOMEM;
2573 			goto out_fail;
2574 		}
2575 	}
2576 
2577 	if (ctx->seal) {
2578 		if (ses->server->vals->protocol_id == 0) {
2579 			cifs_dbg(VFS,
2580 				 "SMB3 or later required for encryption\n");
2581 			rc = -EOPNOTSUPP;
2582 			goto out_fail;
2583 		} else if (tcon->ses->server->capabilities &
2584 					SMB2_GLOBAL_CAP_ENCRYPTION)
2585 			tcon->seal = true;
2586 		else {
2587 			cifs_dbg(VFS, "Encryption is not supported on share\n");
2588 			rc = -EOPNOTSUPP;
2589 			goto out_fail;
2590 		}
2591 	}
2592 
2593 	if (ctx->linux_ext) {
2594 		if (ses->server->posix_ext_supported) {
2595 			tcon->posix_extensions = true;
2596 			pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2597 		} else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2598 		    (strcmp(ses->server->vals->version_string,
2599 		     SMB3ANY_VERSION_STRING) == 0) ||
2600 		    (strcmp(ses->server->vals->version_string,
2601 		     SMBDEFAULT_VERSION_STRING) == 0)) {
2602 			cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2603 			rc = -EOPNOTSUPP;
2604 			goto out_fail;
2605 		} else {
2606 			cifs_dbg(VFS,
2607 				"Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2608 			rc = -EOPNOTSUPP;
2609 			goto out_fail;
2610 		}
2611 	}
2612 
2613 	xid = get_xid();
2614 	rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2615 					    ctx->local_nls);
2616 	free_xid(xid);
2617 	cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2618 	if (rc)
2619 		goto out_fail;
2620 
2621 	tcon->use_persistent = false;
2622 	/* check if SMB2 or later, CIFS does not support persistent handles */
2623 	if (ctx->persistent) {
2624 		if (ses->server->vals->protocol_id == 0) {
2625 			cifs_dbg(VFS,
2626 			     "SMB3 or later required for persistent handles\n");
2627 			rc = -EOPNOTSUPP;
2628 			goto out_fail;
2629 		} else if (ses->server->capabilities &
2630 			   SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2631 			tcon->use_persistent = true;
2632 		else /* persistent handles requested but not supported */ {
2633 			cifs_dbg(VFS,
2634 				"Persistent handles not supported on share\n");
2635 			rc = -EOPNOTSUPP;
2636 			goto out_fail;
2637 		}
2638 	} else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2639 	     && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2640 	     && (ctx->nopersistent == false)) {
2641 		cifs_dbg(FYI, "enabling persistent handles\n");
2642 		tcon->use_persistent = true;
2643 	} else if (ctx->resilient) {
2644 		if (ses->server->vals->protocol_id == 0) {
2645 			cifs_dbg(VFS,
2646 			     "SMB2.1 or later required for resilient handles\n");
2647 			rc = -EOPNOTSUPP;
2648 			goto out_fail;
2649 		}
2650 		tcon->use_resilient = true;
2651 	}
2652 
2653 	tcon->use_witness = false;
2654 	if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2655 		if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2656 			if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2657 				/*
2658 				 * Set witness in use flag in first place
2659 				 * to retry registration in the echo task
2660 				 */
2661 				tcon->use_witness = true;
2662 				/* And try to register immediately */
2663 				rc = cifs_swn_register(tcon);
2664 				if (rc < 0) {
2665 					cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2666 					goto out_fail;
2667 				}
2668 			} else {
2669 				/* TODO: try to extend for non-cluster uses (eg multichannel) */
2670 				cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2671 				rc = -EOPNOTSUPP;
2672 				goto out_fail;
2673 			}
2674 		} else {
2675 			cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2676 			rc = -EOPNOTSUPP;
2677 			goto out_fail;
2678 		}
2679 	}
2680 
2681 	/* If the user really knows what they are doing they can override */
2682 	if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2683 		if (ctx->cache_ro)
2684 			cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2685 		else if (ctx->cache_rw)
2686 			cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2687 	}
2688 
2689 	if (ctx->no_lease) {
2690 		if (ses->server->vals->protocol_id == 0) {
2691 			cifs_dbg(VFS,
2692 				"SMB2 or later required for nolease option\n");
2693 			rc = -EOPNOTSUPP;
2694 			goto out_fail;
2695 		} else
2696 			tcon->no_lease = ctx->no_lease;
2697 	}
2698 
2699 	/*
2700 	 * We can have only one retry value for a connection to a share so for
2701 	 * resources mounted more than once to the same server share the last
2702 	 * value passed in for the retry flag is used.
2703 	 */
2704 	tcon->retry = ctx->retry;
2705 	tcon->nocase = ctx->nocase;
2706 	tcon->broken_sparse_sup = ctx->no_sparse;
2707 	tcon->max_cached_dirs = ctx->max_cached_dirs;
2708 	tcon->nodelete = ctx->nodelete;
2709 	tcon->local_lease = ctx->local_lease;
2710 	INIT_LIST_HEAD(&tcon->pending_opens);
2711 	tcon->status = TID_GOOD;
2712 
2713 	INIT_DELAYED_WORK(&tcon->query_interfaces,
2714 			  smb2_query_server_interfaces);
2715 	if (ses->server->dialect >= SMB30_PROT_ID &&
2716 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2717 		/* schedule query interfaces poll */
2718 		queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2719 				   (SMB_INTERFACE_POLL_INTERVAL * HZ));
2720 	}
2721 #ifdef CONFIG_CIFS_DFS_UPCALL
2722 	INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2723 #endif
2724 	spin_lock(&cifs_tcp_ses_lock);
2725 	list_add(&tcon->tcon_list, &ses->tcon_list);
2726 	spin_unlock(&cifs_tcp_ses_lock);
2727 
2728 	return tcon;
2729 
2730 out_fail:
2731 	tconInfoFree(tcon);
2732 	return ERR_PTR(rc);
2733 }
2734 
2735 void
2736 cifs_put_tlink(struct tcon_link *tlink)
2737 {
2738 	if (!tlink || IS_ERR(tlink))
2739 		return;
2740 
2741 	if (!atomic_dec_and_test(&tlink->tl_count) ||
2742 	    test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2743 		tlink->tl_time = jiffies;
2744 		return;
2745 	}
2746 
2747 	if (!IS_ERR(tlink_tcon(tlink)))
2748 		cifs_put_tcon(tlink_tcon(tlink));
2749 	kfree(tlink);
2750 }
2751 
2752 static int
2753 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2754 {
2755 	struct cifs_sb_info *old = CIFS_SB(sb);
2756 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2757 	unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2758 	unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2759 
2760 	if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2761 		return 0;
2762 
2763 	if (old->mnt_cifs_serverino_autodisabled)
2764 		newflags &= ~CIFS_MOUNT_SERVER_INUM;
2765 
2766 	if (oldflags != newflags)
2767 		return 0;
2768 
2769 	/*
2770 	 * We want to share sb only if we don't specify an r/wsize or
2771 	 * specified r/wsize is greater than or equal to existing one.
2772 	 */
2773 	if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2774 		return 0;
2775 
2776 	if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2777 		return 0;
2778 
2779 	if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2780 	    !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2781 		return 0;
2782 
2783 	if (old->ctx->file_mode != new->ctx->file_mode ||
2784 	    old->ctx->dir_mode != new->ctx->dir_mode)
2785 		return 0;
2786 
2787 	if (strcmp(old->local_nls->charset, new->local_nls->charset))
2788 		return 0;
2789 
2790 	if (old->ctx->acregmax != new->ctx->acregmax)
2791 		return 0;
2792 	if (old->ctx->acdirmax != new->ctx->acdirmax)
2793 		return 0;
2794 	if (old->ctx->closetimeo != new->ctx->closetimeo)
2795 		return 0;
2796 
2797 	return 1;
2798 }
2799 
2800 static int match_prepath(struct super_block *sb,
2801 			 struct cifs_tcon *tcon,
2802 			 struct cifs_mnt_data *mnt_data)
2803 {
2804 	struct smb3_fs_context *ctx = mnt_data->ctx;
2805 	struct cifs_sb_info *old = CIFS_SB(sb);
2806 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2807 	bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2808 		old->prepath;
2809 	bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2810 		new->prepath;
2811 
2812 	if (tcon->origin_fullpath &&
2813 	    dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2814 		return 1;
2815 
2816 	if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2817 		return 1;
2818 	else if (!old_set && !new_set)
2819 		return 1;
2820 
2821 	return 0;
2822 }
2823 
2824 int
2825 cifs_match_super(struct super_block *sb, void *data)
2826 {
2827 	struct cifs_mnt_data *mnt_data = data;
2828 	struct smb3_fs_context *ctx;
2829 	struct cifs_sb_info *cifs_sb;
2830 	struct TCP_Server_Info *tcp_srv;
2831 	struct cifs_ses *ses;
2832 	struct cifs_tcon *tcon;
2833 	struct tcon_link *tlink;
2834 	int rc = 0;
2835 
2836 	spin_lock(&cifs_tcp_ses_lock);
2837 	cifs_sb = CIFS_SB(sb);
2838 
2839 	/* We do not want to use a superblock that has been shutdown */
2840 	if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2841 		spin_unlock(&cifs_tcp_ses_lock);
2842 		return 0;
2843 	}
2844 
2845 	tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2846 	if (IS_ERR_OR_NULL(tlink)) {
2847 		pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2848 			     __func__, tlink);
2849 		spin_unlock(&cifs_tcp_ses_lock);
2850 		return 0;
2851 	}
2852 	tcon = tlink_tcon(tlink);
2853 	ses = tcon->ses;
2854 	tcp_srv = ses->server;
2855 
2856 	ctx = mnt_data->ctx;
2857 
2858 	spin_lock(&tcp_srv->srv_lock);
2859 	spin_lock(&ses->ses_lock);
2860 	spin_lock(&ses->chan_lock);
2861 	spin_lock(&tcon->tc_lock);
2862 	if (!match_server(tcp_srv, ctx, true) ||
2863 	    !match_session(ses, ctx) ||
2864 	    !match_tcon(tcon, ctx) ||
2865 	    !match_prepath(sb, tcon, mnt_data)) {
2866 		rc = 0;
2867 		goto out;
2868 	}
2869 
2870 	rc = compare_mount_options(sb, mnt_data);
2871 out:
2872 	spin_unlock(&tcon->tc_lock);
2873 	spin_unlock(&ses->chan_lock);
2874 	spin_unlock(&ses->ses_lock);
2875 	spin_unlock(&tcp_srv->srv_lock);
2876 
2877 	spin_unlock(&cifs_tcp_ses_lock);
2878 	cifs_put_tlink(tlink);
2879 	return rc;
2880 }
2881 
2882 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2883 static struct lock_class_key cifs_key[2];
2884 static struct lock_class_key cifs_slock_key[2];
2885 
2886 static inline void
2887 cifs_reclassify_socket4(struct socket *sock)
2888 {
2889 	struct sock *sk = sock->sk;
2890 
2891 	BUG_ON(!sock_allow_reclassification(sk));
2892 	sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2893 		&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2894 }
2895 
2896 static inline void
2897 cifs_reclassify_socket6(struct socket *sock)
2898 {
2899 	struct sock *sk = sock->sk;
2900 
2901 	BUG_ON(!sock_allow_reclassification(sk));
2902 	sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2903 		&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2904 }
2905 #else
2906 static inline void
2907 cifs_reclassify_socket4(struct socket *sock)
2908 {
2909 }
2910 
2911 static inline void
2912 cifs_reclassify_socket6(struct socket *sock)
2913 {
2914 }
2915 #endif
2916 
2917 /* See RFC1001 section 14 on representation of Netbios names */
2918 static void rfc1002mangle(char *target, char *source, unsigned int length)
2919 {
2920 	unsigned int i, j;
2921 
2922 	for (i = 0, j = 0; i < (length); i++) {
2923 		/* mask a nibble at a time and encode */
2924 		target[j] = 'A' + (0x0F & (source[i] >> 4));
2925 		target[j+1] = 'A' + (0x0F & source[i]);
2926 		j += 2;
2927 	}
2928 
2929 }
2930 
2931 static int
2932 bind_socket(struct TCP_Server_Info *server)
2933 {
2934 	int rc = 0;
2935 
2936 	if (server->srcaddr.ss_family != AF_UNSPEC) {
2937 		/* Bind to the specified local IP address */
2938 		struct socket *socket = server->ssocket;
2939 
2940 		rc = kernel_bind(socket,
2941 				 (struct sockaddr *) &server->srcaddr,
2942 				 sizeof(server->srcaddr));
2943 		if (rc < 0) {
2944 			struct sockaddr_in *saddr4;
2945 			struct sockaddr_in6 *saddr6;
2946 
2947 			saddr4 = (struct sockaddr_in *)&server->srcaddr;
2948 			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2949 			if (saddr6->sin6_family == AF_INET6)
2950 				cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2951 					 &saddr6->sin6_addr, rc);
2952 			else
2953 				cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2954 					 &saddr4->sin_addr.s_addr, rc);
2955 		}
2956 	}
2957 	return rc;
2958 }
2959 
2960 static int
2961 ip_rfc1001_connect(struct TCP_Server_Info *server)
2962 {
2963 	int rc = 0;
2964 	/*
2965 	 * some servers require RFC1001 sessinit before sending
2966 	 * negprot - BB check reconnection in case where second
2967 	 * sessinit is sent but no second negprot
2968 	 */
2969 	struct rfc1002_session_packet req = {};
2970 	struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
2971 	unsigned int len;
2972 
2973 	req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2974 
2975 	if (server->server_RFC1001_name[0] != 0)
2976 		rfc1002mangle(req.trailer.session_req.called_name,
2977 			      server->server_RFC1001_name,
2978 			      RFC1001_NAME_LEN_WITH_NULL);
2979 	else
2980 		rfc1002mangle(req.trailer.session_req.called_name,
2981 			      DEFAULT_CIFS_CALLED_NAME,
2982 			      RFC1001_NAME_LEN_WITH_NULL);
2983 
2984 	req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2985 
2986 	/* calling name ends in null (byte 16) from old smb convention */
2987 	if (server->workstation_RFC1001_name[0] != 0)
2988 		rfc1002mangle(req.trailer.session_req.calling_name,
2989 			      server->workstation_RFC1001_name,
2990 			      RFC1001_NAME_LEN_WITH_NULL);
2991 	else
2992 		rfc1002mangle(req.trailer.session_req.calling_name,
2993 			      "LINUX_CIFS_CLNT",
2994 			      RFC1001_NAME_LEN_WITH_NULL);
2995 
2996 	/*
2997 	 * As per rfc1002, @len must be the number of bytes that follows the
2998 	 * length field of a rfc1002 session request payload.
2999 	 */
3000 	len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
3001 
3002 	smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
3003 	rc = smb_send(server, smb_buf, len);
3004 	/*
3005 	 * RFC1001 layer in at least one server requires very short break before
3006 	 * negprot presumably because not expecting negprot to follow so fast.
3007 	 * This is a simple solution that works without complicating the code
3008 	 * and causes no significant slowing down on mount for everyone else
3009 	 */
3010 	usleep_range(1000, 2000);
3011 
3012 	return rc;
3013 }
3014 
3015 static int
3016 generic_ip_connect(struct TCP_Server_Info *server)
3017 {
3018 	struct sockaddr *saddr;
3019 	struct socket *socket;
3020 	int slen, sfamily;
3021 	__be16 sport;
3022 	int rc = 0;
3023 
3024 	saddr = (struct sockaddr *) &server->dstaddr;
3025 
3026 	if (server->dstaddr.ss_family == AF_INET6) {
3027 		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3028 
3029 		sport = ipv6->sin6_port;
3030 		slen = sizeof(struct sockaddr_in6);
3031 		sfamily = AF_INET6;
3032 		cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3033 				ntohs(sport));
3034 	} else {
3035 		struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3036 
3037 		sport = ipv4->sin_port;
3038 		slen = sizeof(struct sockaddr_in);
3039 		sfamily = AF_INET;
3040 		cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3041 				ntohs(sport));
3042 	}
3043 
3044 	if (server->ssocket) {
3045 		socket = server->ssocket;
3046 	} else {
3047 		rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3048 				   IPPROTO_TCP, &server->ssocket, 1);
3049 		if (rc < 0) {
3050 			cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3051 			return rc;
3052 		}
3053 
3054 		/* BB other socket options to set KEEPALIVE, NODELAY? */
3055 		cifs_dbg(FYI, "Socket created\n");
3056 		socket = server->ssocket;
3057 		socket->sk->sk_allocation = GFP_NOFS;
3058 		socket->sk->sk_use_task_frag = false;
3059 		if (sfamily == AF_INET6)
3060 			cifs_reclassify_socket6(socket);
3061 		else
3062 			cifs_reclassify_socket4(socket);
3063 	}
3064 
3065 	rc = bind_socket(server);
3066 	if (rc < 0)
3067 		return rc;
3068 
3069 	/*
3070 	 * Eventually check for other socket options to change from
3071 	 * the default. sock_setsockopt not used because it expects
3072 	 * user space buffer
3073 	 */
3074 	socket->sk->sk_rcvtimeo = 7 * HZ;
3075 	socket->sk->sk_sndtimeo = 5 * HZ;
3076 
3077 	/* make the bufsizes depend on wsize/rsize and max requests */
3078 	if (server->noautotune) {
3079 		if (socket->sk->sk_sndbuf < (200 * 1024))
3080 			socket->sk->sk_sndbuf = 200 * 1024;
3081 		if (socket->sk->sk_rcvbuf < (140 * 1024))
3082 			socket->sk->sk_rcvbuf = 140 * 1024;
3083 	}
3084 
3085 	if (server->tcp_nodelay)
3086 		tcp_sock_set_nodelay(socket->sk);
3087 
3088 	cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3089 		 socket->sk->sk_sndbuf,
3090 		 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3091 
3092 	rc = kernel_connect(socket, saddr, slen,
3093 			    server->noblockcnt ? O_NONBLOCK : 0);
3094 	/*
3095 	 * When mounting SMB root file systems, we do not want to block in
3096 	 * connect. Otherwise bail out and then let cifs_reconnect() perform
3097 	 * reconnect failover - if possible.
3098 	 */
3099 	if (server->noblockcnt && rc == -EINPROGRESS)
3100 		rc = 0;
3101 	if (rc < 0) {
3102 		cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3103 		trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3104 		sock_release(socket);
3105 		server->ssocket = NULL;
3106 		return rc;
3107 	}
3108 	trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3109 	if (sport == htons(RFC1001_PORT))
3110 		rc = ip_rfc1001_connect(server);
3111 
3112 	return rc;
3113 }
3114 
3115 static int
3116 ip_connect(struct TCP_Server_Info *server)
3117 {
3118 	__be16 *sport;
3119 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3120 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3121 
3122 	if (server->dstaddr.ss_family == AF_INET6)
3123 		sport = &addr6->sin6_port;
3124 	else
3125 		sport = &addr->sin_port;
3126 
3127 	if (*sport == 0) {
3128 		int rc;
3129 
3130 		/* try with 445 port at first */
3131 		*sport = htons(CIFS_PORT);
3132 
3133 		rc = generic_ip_connect(server);
3134 		if (rc >= 0)
3135 			return rc;
3136 
3137 		/* if it failed, try with 139 port */
3138 		*sport = htons(RFC1001_PORT);
3139 	}
3140 
3141 	return generic_ip_connect(server);
3142 }
3143 
3144 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3145 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3146 			  struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3147 {
3148 	/*
3149 	 * If we are reconnecting then should we check to see if
3150 	 * any requested capabilities changed locally e.g. via
3151 	 * remount but we can not do much about it here
3152 	 * if they have (even if we could detect it by the following)
3153 	 * Perhaps we could add a backpointer to array of sb from tcon
3154 	 * or if we change to make all sb to same share the same
3155 	 * sb as NFS - then we only have one backpointer to sb.
3156 	 * What if we wanted to mount the server share twice once with
3157 	 * and once without posixacls or posix paths?
3158 	 */
3159 	__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3160 
3161 	if (ctx && ctx->no_linux_ext) {
3162 		tcon->fsUnixInfo.Capability = 0;
3163 		tcon->unix_ext = 0; /* Unix Extensions disabled */
3164 		cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3165 		return;
3166 	} else if (ctx)
3167 		tcon->unix_ext = 1; /* Unix Extensions supported */
3168 
3169 	if (!tcon->unix_ext) {
3170 		cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3171 		return;
3172 	}
3173 
3174 	if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3175 		__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3176 
3177 		cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3178 		/*
3179 		 * check for reconnect case in which we do not
3180 		 * want to change the mount behavior if we can avoid it
3181 		 */
3182 		if (ctx == NULL) {
3183 			/*
3184 			 * turn off POSIX ACL and PATHNAMES if not set
3185 			 * originally at mount time
3186 			 */
3187 			if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3188 				cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3189 			if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3190 				if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3191 					cifs_dbg(VFS, "POSIXPATH support change\n");
3192 				cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3193 			} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3194 				cifs_dbg(VFS, "possible reconnect error\n");
3195 				cifs_dbg(VFS, "server disabled POSIX path support\n");
3196 			}
3197 		}
3198 
3199 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3200 			cifs_dbg(VFS, "per-share encryption not supported yet\n");
3201 
3202 		cap &= CIFS_UNIX_CAP_MASK;
3203 		if (ctx && ctx->no_psx_acl)
3204 			cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3205 		else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3206 			cifs_dbg(FYI, "negotiated posix acl support\n");
3207 			if (cifs_sb)
3208 				cifs_sb->mnt_cifs_flags |=
3209 					CIFS_MOUNT_POSIXACL;
3210 		}
3211 
3212 		if (ctx && ctx->posix_paths == 0)
3213 			cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3214 		else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3215 			cifs_dbg(FYI, "negotiate posix pathnames\n");
3216 			if (cifs_sb)
3217 				cifs_sb->mnt_cifs_flags |=
3218 					CIFS_MOUNT_POSIX_PATHS;
3219 		}
3220 
3221 		cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3222 #ifdef CONFIG_CIFS_DEBUG2
3223 		if (cap & CIFS_UNIX_FCNTL_CAP)
3224 			cifs_dbg(FYI, "FCNTL cap\n");
3225 		if (cap & CIFS_UNIX_EXTATTR_CAP)
3226 			cifs_dbg(FYI, "EXTATTR cap\n");
3227 		if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3228 			cifs_dbg(FYI, "POSIX path cap\n");
3229 		if (cap & CIFS_UNIX_XATTR_CAP)
3230 			cifs_dbg(FYI, "XATTR cap\n");
3231 		if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3232 			cifs_dbg(FYI, "POSIX ACL cap\n");
3233 		if (cap & CIFS_UNIX_LARGE_READ_CAP)
3234 			cifs_dbg(FYI, "very large read cap\n");
3235 		if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3236 			cifs_dbg(FYI, "very large write cap\n");
3237 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3238 			cifs_dbg(FYI, "transport encryption cap\n");
3239 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3240 			cifs_dbg(FYI, "mandatory transport encryption cap\n");
3241 #endif /* CIFS_DEBUG2 */
3242 		if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3243 			if (ctx == NULL)
3244 				cifs_dbg(FYI, "resetting capabilities failed\n");
3245 			else
3246 				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");
3247 
3248 		}
3249 	}
3250 }
3251 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3252 
3253 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3254 {
3255 	struct smb3_fs_context *ctx = cifs_sb->ctx;
3256 
3257 	INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3258 
3259 	spin_lock_init(&cifs_sb->tlink_tree_lock);
3260 	cifs_sb->tlink_tree = RB_ROOT;
3261 
3262 	cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3263 		 ctx->file_mode, ctx->dir_mode);
3264 
3265 	/* this is needed for ASCII cp to Unicode converts */
3266 	if (ctx->iocharset == NULL) {
3267 		/* load_nls_default cannot return null */
3268 		cifs_sb->local_nls = load_nls_default();
3269 	} else {
3270 		cifs_sb->local_nls = load_nls(ctx->iocharset);
3271 		if (cifs_sb->local_nls == NULL) {
3272 			cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3273 				 ctx->iocharset);
3274 			return -ELIBACC;
3275 		}
3276 	}
3277 	ctx->local_nls = cifs_sb->local_nls;
3278 
3279 	smb3_update_mnt_flags(cifs_sb);
3280 
3281 	if (ctx->direct_io)
3282 		cifs_dbg(FYI, "mounting share using direct i/o\n");
3283 	if (ctx->cache_ro) {
3284 		cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3285 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3286 	} else if (ctx->cache_rw) {
3287 		cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3288 		cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3289 					    CIFS_MOUNT_RW_CACHE);
3290 	}
3291 
3292 	if ((ctx->cifs_acl) && (ctx->dynperm))
3293 		cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3294 
3295 	if (ctx->prepath) {
3296 		cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3297 		if (cifs_sb->prepath == NULL)
3298 			return -ENOMEM;
3299 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3300 	}
3301 
3302 	return 0;
3303 }
3304 
3305 /* Release all succeed connections */
3306 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3307 {
3308 	int rc = 0;
3309 
3310 	if (mnt_ctx->tcon)
3311 		cifs_put_tcon(mnt_ctx->tcon);
3312 	else if (mnt_ctx->ses)
3313 		cifs_put_smb_ses(mnt_ctx->ses);
3314 	else if (mnt_ctx->server)
3315 		cifs_put_tcp_session(mnt_ctx->server, 0);
3316 	mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3317 	free_xid(mnt_ctx->xid);
3318 }
3319 
3320 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3321 {
3322 	struct TCP_Server_Info *server = NULL;
3323 	struct smb3_fs_context *ctx;
3324 	struct cifs_ses *ses = NULL;
3325 	unsigned int xid;
3326 	int rc = 0;
3327 
3328 	xid = get_xid();
3329 
3330 	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3331 		rc = -EINVAL;
3332 		goto out;
3333 	}
3334 	ctx = mnt_ctx->fs_ctx;
3335 
3336 	/* get a reference to a tcp session */
3337 	server = cifs_get_tcp_session(ctx, NULL);
3338 	if (IS_ERR(server)) {
3339 		rc = PTR_ERR(server);
3340 		server = NULL;
3341 		goto out;
3342 	}
3343 
3344 	/* get a reference to a SMB session */
3345 	ses = cifs_get_smb_ses(server, ctx);
3346 	if (IS_ERR(ses)) {
3347 		rc = PTR_ERR(ses);
3348 		ses = NULL;
3349 		goto out;
3350 	}
3351 
3352 	if ((ctx->persistent == true) && (!(ses->server->capabilities &
3353 					    SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3354 		cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3355 		rc = -EOPNOTSUPP;
3356 	}
3357 
3358 out:
3359 	mnt_ctx->xid = xid;
3360 	mnt_ctx->server = server;
3361 	mnt_ctx->ses = ses;
3362 	mnt_ctx->tcon = NULL;
3363 
3364 	return rc;
3365 }
3366 
3367 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3368 {
3369 	struct TCP_Server_Info *server;
3370 	struct cifs_sb_info *cifs_sb;
3371 	struct smb3_fs_context *ctx;
3372 	struct cifs_tcon *tcon = NULL;
3373 	int rc = 0;
3374 
3375 	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3376 			 !mnt_ctx->cifs_sb)) {
3377 		rc = -EINVAL;
3378 		goto out;
3379 	}
3380 	server = mnt_ctx->server;
3381 	ctx = mnt_ctx->fs_ctx;
3382 	cifs_sb = mnt_ctx->cifs_sb;
3383 
3384 	/* search for existing tcon to this server share */
3385 	tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3386 	if (IS_ERR(tcon)) {
3387 		rc = PTR_ERR(tcon);
3388 		tcon = NULL;
3389 		goto out;
3390 	}
3391 
3392 	/* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3393 	if (tcon->posix_extensions)
3394 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3395 
3396 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3397 	/* tell server which Unix caps we support */
3398 	if (cap_unix(tcon->ses)) {
3399 		/*
3400 		 * reset of caps checks mount to see if unix extensions disabled
3401 		 * for just this mount.
3402 		 */
3403 		reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3404 		spin_lock(&tcon->ses->server->srv_lock);
3405 		if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3406 		    (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3407 		     CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3408 			spin_unlock(&tcon->ses->server->srv_lock);
3409 			rc = -EACCES;
3410 			goto out;
3411 		}
3412 		spin_unlock(&tcon->ses->server->srv_lock);
3413 	} else
3414 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3415 		tcon->unix_ext = 0; /* server does not support them */
3416 
3417 	/* do not care if a following call succeed - informational */
3418 	if (!tcon->pipe && server->ops->qfs_tcon) {
3419 		server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3420 		if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3421 			if (tcon->fsDevInfo.DeviceCharacteristics &
3422 			    cpu_to_le32(FILE_READ_ONLY_DEVICE))
3423 				cifs_dbg(VFS, "mounted to read only share\n");
3424 			else if ((cifs_sb->mnt_cifs_flags &
3425 				  CIFS_MOUNT_RW_CACHE) == 0)
3426 				cifs_dbg(VFS, "read only mount of RW share\n");
3427 			/* no need to log a RW mount of a typical RW share */
3428 		}
3429 	}
3430 
3431 	/*
3432 	 * Clamp the rsize/wsize mount arguments if they are too big for the server
3433 	 * and set the rsize/wsize to the negotiated values if not passed in by
3434 	 * the user on mount
3435 	 */
3436 	if ((cifs_sb->ctx->wsize == 0) ||
3437 	    (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3438 		cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3439 	if ((cifs_sb->ctx->rsize == 0) ||
3440 	    (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3441 		cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3442 
3443 	/*
3444 	 * The cookie is initialized from volume info returned above.
3445 	 * Inside cifs_fscache_get_super_cookie it checks
3446 	 * that we do not get super cookie twice.
3447 	 */
3448 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3449 		cifs_fscache_get_super_cookie(tcon);
3450 
3451 out:
3452 	mnt_ctx->tcon = tcon;
3453 	return rc;
3454 }
3455 
3456 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3457 			     struct cifs_tcon *tcon)
3458 {
3459 	struct tcon_link *tlink;
3460 
3461 	/* hang the tcon off of the superblock */
3462 	tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3463 	if (tlink == NULL)
3464 		return -ENOMEM;
3465 
3466 	tlink->tl_uid = ses->linux_uid;
3467 	tlink->tl_tcon = tcon;
3468 	tlink->tl_time = jiffies;
3469 	set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3470 	set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3471 
3472 	cifs_sb->master_tlink = tlink;
3473 	spin_lock(&cifs_sb->tlink_tree_lock);
3474 	tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3475 	spin_unlock(&cifs_sb->tlink_tree_lock);
3476 
3477 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3478 				TLINK_IDLE_EXPIRE);
3479 	return 0;
3480 }
3481 
3482 static int
3483 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3484 					unsigned int xid,
3485 					struct cifs_tcon *tcon,
3486 					struct cifs_sb_info *cifs_sb,
3487 					char *full_path,
3488 					int added_treename)
3489 {
3490 	int rc;
3491 	char *s;
3492 	char sep, tmp;
3493 	int skip = added_treename ? 1 : 0;
3494 
3495 	sep = CIFS_DIR_SEP(cifs_sb);
3496 	s = full_path;
3497 
3498 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3499 	while (rc == 0) {
3500 		/* skip separators */
3501 		while (*s == sep)
3502 			s++;
3503 		if (!*s)
3504 			break;
3505 		/* next separator */
3506 		while (*s && *s != sep)
3507 			s++;
3508 		/*
3509 		 * if the treename is added, we then have to skip the first
3510 		 * part within the separators
3511 		 */
3512 		if (skip) {
3513 			skip = 0;
3514 			continue;
3515 		}
3516 		/*
3517 		 * temporarily null-terminate the path at the end of
3518 		 * the current component
3519 		 */
3520 		tmp = *s;
3521 		*s = 0;
3522 		rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3523 						     full_path);
3524 		*s = tmp;
3525 	}
3526 	return rc;
3527 }
3528 
3529 /*
3530  * Check if path is remote (i.e. a DFS share).
3531  *
3532  * Return -EREMOTE if it is, otherwise 0 or -errno.
3533  */
3534 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3535 {
3536 	int rc;
3537 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3538 	struct TCP_Server_Info *server = mnt_ctx->server;
3539 	unsigned int xid = mnt_ctx->xid;
3540 	struct cifs_tcon *tcon = mnt_ctx->tcon;
3541 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3542 	char *full_path;
3543 
3544 	if (!server->ops->is_path_accessible)
3545 		return -EOPNOTSUPP;
3546 
3547 	/*
3548 	 * cifs_build_path_to_root works only when we have a valid tcon
3549 	 */
3550 	full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3551 					    tcon->Flags & SMB_SHARE_IS_IN_DFS);
3552 	if (full_path == NULL)
3553 		return -ENOMEM;
3554 
3555 	cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3556 
3557 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3558 					     full_path);
3559 	if (rc != 0 && rc != -EREMOTE)
3560 		goto out;
3561 
3562 	if (rc != -EREMOTE) {
3563 		rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3564 			cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3565 		if (rc != 0) {
3566 			cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3567 			cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3568 			rc = 0;
3569 		}
3570 	}
3571 
3572 out:
3573 	kfree(full_path);
3574 	return rc;
3575 }
3576 
3577 #ifdef CONFIG_CIFS_DFS_UPCALL
3578 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3579 {
3580 	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3581 	bool isdfs;
3582 	int rc;
3583 
3584 	INIT_LIST_HEAD(&mnt_ctx.dfs_ses_list);
3585 
3586 	rc = dfs_mount_share(&mnt_ctx, &isdfs);
3587 	if (rc)
3588 		goto error;
3589 	if (!isdfs)
3590 		goto out;
3591 
3592 	/*
3593 	 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3594 	 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3595 	 */
3596 	cifs_autodisable_serverino(cifs_sb);
3597 	/*
3598 	 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3599 	 * that have different prefix paths.
3600 	 */
3601 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3602 	kfree(cifs_sb->prepath);
3603 	cifs_sb->prepath = ctx->prepath;
3604 	ctx->prepath = NULL;
3605 
3606 out:
3607 	cifs_try_adding_channels(mnt_ctx.ses);
3608 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3609 	if (rc)
3610 		goto error;
3611 
3612 	free_xid(mnt_ctx.xid);
3613 	return rc;
3614 
3615 error:
3616 	dfs_put_root_smb_sessions(&mnt_ctx.dfs_ses_list);
3617 	cifs_mount_put_conns(&mnt_ctx);
3618 	return rc;
3619 }
3620 #else
3621 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3622 {
3623 	int rc = 0;
3624 	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3625 
3626 	rc = cifs_mount_get_session(&mnt_ctx);
3627 	if (rc)
3628 		goto error;
3629 
3630 	rc = cifs_mount_get_tcon(&mnt_ctx);
3631 	if (rc)
3632 		goto error;
3633 
3634 	rc = cifs_is_path_remote(&mnt_ctx);
3635 	if (rc == -EREMOTE)
3636 		rc = -EOPNOTSUPP;
3637 	if (rc)
3638 		goto error;
3639 
3640 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3641 	if (rc)
3642 		goto error;
3643 
3644 	free_xid(mnt_ctx.xid);
3645 	return rc;
3646 
3647 error:
3648 	cifs_mount_put_conns(&mnt_ctx);
3649 	return rc;
3650 }
3651 #endif
3652 
3653 /*
3654  * Issue a TREE_CONNECT request.
3655  */
3656 int
3657 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3658 	 const char *tree, struct cifs_tcon *tcon,
3659 	 const struct nls_table *nls_codepage)
3660 {
3661 	struct smb_hdr *smb_buffer;
3662 	struct smb_hdr *smb_buffer_response;
3663 	TCONX_REQ *pSMB;
3664 	TCONX_RSP *pSMBr;
3665 	unsigned char *bcc_ptr;
3666 	int rc = 0;
3667 	int length;
3668 	__u16 bytes_left, count;
3669 
3670 	if (ses == NULL)
3671 		return -EIO;
3672 
3673 	smb_buffer = cifs_buf_get();
3674 	if (smb_buffer == NULL)
3675 		return -ENOMEM;
3676 
3677 	smb_buffer_response = smb_buffer;
3678 
3679 	header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3680 			NULL /*no tid */, 4 /*wct */);
3681 
3682 	smb_buffer->Mid = get_next_mid(ses->server);
3683 	smb_buffer->Uid = ses->Suid;
3684 	pSMB = (TCONX_REQ *) smb_buffer;
3685 	pSMBr = (TCONX_RSP *) smb_buffer_response;
3686 
3687 	pSMB->AndXCommand = 0xFF;
3688 	pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3689 	bcc_ptr = &pSMB->Password[0];
3690 
3691 	pSMB->PasswordLength = cpu_to_le16(1);	/* minimum */
3692 	*bcc_ptr = 0; /* password is null byte */
3693 	bcc_ptr++;              /* skip password */
3694 	/* already aligned so no need to do it below */
3695 
3696 	if (ses->server->sign)
3697 		smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3698 
3699 	if (ses->capabilities & CAP_STATUS32)
3700 		smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3701 
3702 	if (ses->capabilities & CAP_DFS)
3703 		smb_buffer->Flags2 |= SMBFLG2_DFS;
3704 
3705 	if (ses->capabilities & CAP_UNICODE) {
3706 		smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3707 		length =
3708 		    cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3709 			6 /* max utf8 char length in bytes */ *
3710 			(/* server len*/ + 256 /* share len */), nls_codepage);
3711 		bcc_ptr += 2 * length;	/* convert num 16 bit words to bytes */
3712 		bcc_ptr += 2;	/* skip trailing null */
3713 	} else {		/* ASCII */
3714 		strcpy(bcc_ptr, tree);
3715 		bcc_ptr += strlen(tree) + 1;
3716 	}
3717 	strcpy(bcc_ptr, "?????");
3718 	bcc_ptr += strlen("?????");
3719 	bcc_ptr += 1;
3720 	count = bcc_ptr - &pSMB->Password[0];
3721 	be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3722 	pSMB->ByteCount = cpu_to_le16(count);
3723 
3724 	rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3725 			 0);
3726 
3727 	/* above now done in SendReceive */
3728 	if (rc == 0) {
3729 		bool is_unicode;
3730 
3731 		tcon->tid = smb_buffer_response->Tid;
3732 		bcc_ptr = pByteArea(smb_buffer_response);
3733 		bytes_left = get_bcc(smb_buffer_response);
3734 		length = strnlen(bcc_ptr, bytes_left - 2);
3735 		if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3736 			is_unicode = true;
3737 		else
3738 			is_unicode = false;
3739 
3740 
3741 		/* skip service field (NB: this field is always ASCII) */
3742 		if (length == 3) {
3743 			if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3744 			    (bcc_ptr[2] == 'C')) {
3745 				cifs_dbg(FYI, "IPC connection\n");
3746 				tcon->ipc = true;
3747 				tcon->pipe = true;
3748 			}
3749 		} else if (length == 2) {
3750 			if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3751 				/* the most common case */
3752 				cifs_dbg(FYI, "disk share connection\n");
3753 			}
3754 		}
3755 		bcc_ptr += length + 1;
3756 		bytes_left -= (length + 1);
3757 		strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3758 
3759 		/* mostly informational -- no need to fail on error here */
3760 		kfree(tcon->nativeFileSystem);
3761 		tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3762 						      bytes_left, is_unicode,
3763 						      nls_codepage);
3764 
3765 		cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3766 
3767 		if ((smb_buffer_response->WordCount == 3) ||
3768 			 (smb_buffer_response->WordCount == 7))
3769 			/* field is in same location */
3770 			tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3771 		else
3772 			tcon->Flags = 0;
3773 		cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3774 	}
3775 
3776 	cifs_buf_release(smb_buffer);
3777 	return rc;
3778 }
3779 
3780 static void delayed_free(struct rcu_head *p)
3781 {
3782 	struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3783 
3784 	unload_nls(cifs_sb->local_nls);
3785 	smb3_cleanup_fs_context(cifs_sb->ctx);
3786 	kfree(cifs_sb);
3787 }
3788 
3789 void
3790 cifs_umount(struct cifs_sb_info *cifs_sb)
3791 {
3792 	struct rb_root *root = &cifs_sb->tlink_tree;
3793 	struct rb_node *node;
3794 	struct tcon_link *tlink;
3795 
3796 	cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3797 
3798 	spin_lock(&cifs_sb->tlink_tree_lock);
3799 	while ((node = rb_first(root))) {
3800 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3801 		cifs_get_tlink(tlink);
3802 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3803 		rb_erase(node, root);
3804 
3805 		spin_unlock(&cifs_sb->tlink_tree_lock);
3806 		cifs_put_tlink(tlink);
3807 		spin_lock(&cifs_sb->tlink_tree_lock);
3808 	}
3809 	spin_unlock(&cifs_sb->tlink_tree_lock);
3810 
3811 	kfree(cifs_sb->prepath);
3812 	call_rcu(&cifs_sb->rcu, delayed_free);
3813 }
3814 
3815 int
3816 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3817 			struct TCP_Server_Info *server)
3818 {
3819 	int rc = 0;
3820 
3821 	if (!server->ops->need_neg || !server->ops->negotiate)
3822 		return -ENOSYS;
3823 
3824 	/* only send once per connect */
3825 	spin_lock(&server->srv_lock);
3826 	if (server->tcpStatus != CifsGood &&
3827 	    server->tcpStatus != CifsNew &&
3828 	    server->tcpStatus != CifsNeedNegotiate) {
3829 		spin_unlock(&server->srv_lock);
3830 		return -EHOSTDOWN;
3831 	}
3832 
3833 	if (!server->ops->need_neg(server) &&
3834 	    server->tcpStatus == CifsGood) {
3835 		spin_unlock(&server->srv_lock);
3836 		return 0;
3837 	}
3838 
3839 	server->tcpStatus = CifsInNegotiate;
3840 	spin_unlock(&server->srv_lock);
3841 
3842 	rc = server->ops->negotiate(xid, ses, server);
3843 	if (rc == 0) {
3844 		spin_lock(&server->srv_lock);
3845 		if (server->tcpStatus == CifsInNegotiate)
3846 			server->tcpStatus = CifsGood;
3847 		else
3848 			rc = -EHOSTDOWN;
3849 		spin_unlock(&server->srv_lock);
3850 	} else {
3851 		spin_lock(&server->srv_lock);
3852 		if (server->tcpStatus == CifsInNegotiate)
3853 			server->tcpStatus = CifsNeedNegotiate;
3854 		spin_unlock(&server->srv_lock);
3855 	}
3856 
3857 	return rc;
3858 }
3859 
3860 int
3861 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3862 		   struct TCP_Server_Info *server,
3863 		   struct nls_table *nls_info)
3864 {
3865 	int rc = -ENOSYS;
3866 	struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3867 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
3868 	struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
3869 	bool is_binding = false;
3870 
3871 	spin_lock(&ses->ses_lock);
3872 	cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
3873 		 __func__, ses->chans_need_reconnect);
3874 
3875 	if (ses->ses_status != SES_GOOD &&
3876 	    ses->ses_status != SES_NEW &&
3877 	    ses->ses_status != SES_NEED_RECON) {
3878 		spin_unlock(&ses->ses_lock);
3879 		return -EHOSTDOWN;
3880 	}
3881 
3882 	/* only send once per connect */
3883 	spin_lock(&ses->chan_lock);
3884 	if (CIFS_ALL_CHANS_GOOD(ses)) {
3885 		if (ses->ses_status == SES_NEED_RECON)
3886 			ses->ses_status = SES_GOOD;
3887 		spin_unlock(&ses->chan_lock);
3888 		spin_unlock(&ses->ses_lock);
3889 		return 0;
3890 	}
3891 
3892 	cifs_chan_set_in_reconnect(ses, server);
3893 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3894 	spin_unlock(&ses->chan_lock);
3895 
3896 	if (!is_binding) {
3897 		ses->ses_status = SES_IN_SETUP;
3898 
3899 		/* force iface_list refresh */
3900 		ses->iface_last_update = 0;
3901 	}
3902 	spin_unlock(&ses->ses_lock);
3903 
3904 	/* update ses ip_addr only for primary chan */
3905 	if (server == pserver) {
3906 		if (server->dstaddr.ss_family == AF_INET6)
3907 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
3908 		else
3909 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
3910 	}
3911 
3912 	if (!is_binding) {
3913 		ses->capabilities = server->capabilities;
3914 		if (!linuxExtEnabled)
3915 			ses->capabilities &= (~server->vals->cap_unix);
3916 
3917 		if (ses->auth_key.response) {
3918 			cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3919 				 ses->auth_key.response);
3920 			kfree_sensitive(ses->auth_key.response);
3921 			ses->auth_key.response = NULL;
3922 			ses->auth_key.len = 0;
3923 		}
3924 	}
3925 
3926 	cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3927 		 server->sec_mode, server->capabilities, server->timeAdj);
3928 
3929 	if (server->ops->sess_setup)
3930 		rc = server->ops->sess_setup(xid, ses, server, nls_info);
3931 
3932 	if (rc) {
3933 		cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3934 		spin_lock(&ses->ses_lock);
3935 		if (ses->ses_status == SES_IN_SETUP)
3936 			ses->ses_status = SES_NEED_RECON;
3937 		spin_lock(&ses->chan_lock);
3938 		cifs_chan_clear_in_reconnect(ses, server);
3939 		spin_unlock(&ses->chan_lock);
3940 		spin_unlock(&ses->ses_lock);
3941 	} else {
3942 		spin_lock(&ses->ses_lock);
3943 		if (ses->ses_status == SES_IN_SETUP)
3944 			ses->ses_status = SES_GOOD;
3945 		spin_lock(&ses->chan_lock);
3946 		cifs_chan_clear_in_reconnect(ses, server);
3947 		cifs_chan_clear_need_reconnect(ses, server);
3948 		spin_unlock(&ses->chan_lock);
3949 		spin_unlock(&ses->ses_lock);
3950 	}
3951 
3952 	return rc;
3953 }
3954 
3955 static int
3956 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3957 {
3958 	ctx->sectype = ses->sectype;
3959 
3960 	/* krb5 is special, since we don't need username or pw */
3961 	if (ctx->sectype == Kerberos)
3962 		return 0;
3963 
3964 	return cifs_set_cifscreds(ctx, ses);
3965 }
3966 
3967 static struct cifs_tcon *
3968 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3969 {
3970 	int rc;
3971 	struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3972 	struct cifs_ses *ses;
3973 	struct cifs_tcon *tcon = NULL;
3974 	struct smb3_fs_context *ctx;
3975 
3976 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3977 	if (ctx == NULL)
3978 		return ERR_PTR(-ENOMEM);
3979 
3980 	ctx->local_nls = cifs_sb->local_nls;
3981 	ctx->linux_uid = fsuid;
3982 	ctx->cred_uid = fsuid;
3983 	ctx->UNC = master_tcon->tree_name;
3984 	ctx->retry = master_tcon->retry;
3985 	ctx->nocase = master_tcon->nocase;
3986 	ctx->nohandlecache = master_tcon->nohandlecache;
3987 	ctx->local_lease = master_tcon->local_lease;
3988 	ctx->no_lease = master_tcon->no_lease;
3989 	ctx->resilient = master_tcon->use_resilient;
3990 	ctx->persistent = master_tcon->use_persistent;
3991 	ctx->handle_timeout = master_tcon->handle_timeout;
3992 	ctx->no_linux_ext = !master_tcon->unix_ext;
3993 	ctx->linux_ext = master_tcon->posix_extensions;
3994 	ctx->sectype = master_tcon->ses->sectype;
3995 	ctx->sign = master_tcon->ses->sign;
3996 	ctx->seal = master_tcon->seal;
3997 	ctx->witness = master_tcon->use_witness;
3998 
3999 	rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4000 	if (rc) {
4001 		tcon = ERR_PTR(rc);
4002 		goto out;
4003 	}
4004 
4005 	/* get a reference for the same TCP session */
4006 	spin_lock(&cifs_tcp_ses_lock);
4007 	++master_tcon->ses->server->srv_count;
4008 	spin_unlock(&cifs_tcp_ses_lock);
4009 
4010 	ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4011 	if (IS_ERR(ses)) {
4012 		tcon = (struct cifs_tcon *)ses;
4013 		cifs_put_tcp_session(master_tcon->ses->server, 0);
4014 		goto out;
4015 	}
4016 
4017 	tcon = cifs_get_tcon(ses, ctx);
4018 	if (IS_ERR(tcon)) {
4019 		cifs_put_smb_ses(ses);
4020 		goto out;
4021 	}
4022 
4023 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4024 	if (cap_unix(ses))
4025 		reset_cifs_unix_caps(0, tcon, NULL, ctx);
4026 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4027 
4028 out:
4029 	kfree(ctx->username);
4030 	kfree_sensitive(ctx->password);
4031 	kfree(ctx);
4032 
4033 	return tcon;
4034 }
4035 
4036 struct cifs_tcon *
4037 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4038 {
4039 	return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4040 }
4041 
4042 /* find and return a tlink with given uid */
4043 static struct tcon_link *
4044 tlink_rb_search(struct rb_root *root, kuid_t uid)
4045 {
4046 	struct rb_node *node = root->rb_node;
4047 	struct tcon_link *tlink;
4048 
4049 	while (node) {
4050 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4051 
4052 		if (uid_gt(tlink->tl_uid, uid))
4053 			node = node->rb_left;
4054 		else if (uid_lt(tlink->tl_uid, uid))
4055 			node = node->rb_right;
4056 		else
4057 			return tlink;
4058 	}
4059 	return NULL;
4060 }
4061 
4062 /* insert a tcon_link into the tree */
4063 static void
4064 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4065 {
4066 	struct rb_node **new = &(root->rb_node), *parent = NULL;
4067 	struct tcon_link *tlink;
4068 
4069 	while (*new) {
4070 		tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4071 		parent = *new;
4072 
4073 		if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4074 			new = &((*new)->rb_left);
4075 		else
4076 			new = &((*new)->rb_right);
4077 	}
4078 
4079 	rb_link_node(&new_tlink->tl_rbnode, parent, new);
4080 	rb_insert_color(&new_tlink->tl_rbnode, root);
4081 }
4082 
4083 /*
4084  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4085  * current task.
4086  *
4087  * If the superblock doesn't refer to a multiuser mount, then just return
4088  * the master tcon for the mount.
4089  *
4090  * First, search the rbtree for an existing tcon for this fsuid. If one
4091  * exists, then check to see if it's pending construction. If it is then wait
4092  * for construction to complete. Once it's no longer pending, check to see if
4093  * it failed and either return an error or retry construction, depending on
4094  * the timeout.
4095  *
4096  * If one doesn't exist then insert a new tcon_link struct into the tree and
4097  * try to construct a new one.
4098  */
4099 struct tcon_link *
4100 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4101 {
4102 	int ret;
4103 	kuid_t fsuid = current_fsuid();
4104 	struct tcon_link *tlink, *newtlink;
4105 
4106 	if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4107 		return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4108 
4109 	spin_lock(&cifs_sb->tlink_tree_lock);
4110 	tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4111 	if (tlink)
4112 		cifs_get_tlink(tlink);
4113 	spin_unlock(&cifs_sb->tlink_tree_lock);
4114 
4115 	if (tlink == NULL) {
4116 		newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4117 		if (newtlink == NULL)
4118 			return ERR_PTR(-ENOMEM);
4119 		newtlink->tl_uid = fsuid;
4120 		newtlink->tl_tcon = ERR_PTR(-EACCES);
4121 		set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4122 		set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4123 		cifs_get_tlink(newtlink);
4124 
4125 		spin_lock(&cifs_sb->tlink_tree_lock);
4126 		/* was one inserted after previous search? */
4127 		tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4128 		if (tlink) {
4129 			cifs_get_tlink(tlink);
4130 			spin_unlock(&cifs_sb->tlink_tree_lock);
4131 			kfree(newtlink);
4132 			goto wait_for_construction;
4133 		}
4134 		tlink = newtlink;
4135 		tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4136 		spin_unlock(&cifs_sb->tlink_tree_lock);
4137 	} else {
4138 wait_for_construction:
4139 		ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4140 				  TASK_INTERRUPTIBLE);
4141 		if (ret) {
4142 			cifs_put_tlink(tlink);
4143 			return ERR_PTR(-ERESTARTSYS);
4144 		}
4145 
4146 		/* if it's good, return it */
4147 		if (!IS_ERR(tlink->tl_tcon))
4148 			return tlink;
4149 
4150 		/* return error if we tried this already recently */
4151 		if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4152 			cifs_put_tlink(tlink);
4153 			return ERR_PTR(-EACCES);
4154 		}
4155 
4156 		if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4157 			goto wait_for_construction;
4158 	}
4159 
4160 	tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4161 	clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4162 	wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4163 
4164 	if (IS_ERR(tlink->tl_tcon)) {
4165 		cifs_put_tlink(tlink);
4166 		return ERR_PTR(-EACCES);
4167 	}
4168 
4169 	return tlink;
4170 }
4171 
4172 /*
4173  * periodic workqueue job that scans tcon_tree for a superblock and closes
4174  * out tcons.
4175  */
4176 static void
4177 cifs_prune_tlinks(struct work_struct *work)
4178 {
4179 	struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4180 						    prune_tlinks.work);
4181 	struct rb_root *root = &cifs_sb->tlink_tree;
4182 	struct rb_node *node;
4183 	struct rb_node *tmp;
4184 	struct tcon_link *tlink;
4185 
4186 	/*
4187 	 * Because we drop the spinlock in the loop in order to put the tlink
4188 	 * it's not guarded against removal of links from the tree. The only
4189 	 * places that remove entries from the tree are this function and
4190 	 * umounts. Because this function is non-reentrant and is canceled
4191 	 * before umount can proceed, this is safe.
4192 	 */
4193 	spin_lock(&cifs_sb->tlink_tree_lock);
4194 	node = rb_first(root);
4195 	while (node != NULL) {
4196 		tmp = node;
4197 		node = rb_next(tmp);
4198 		tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4199 
4200 		if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4201 		    atomic_read(&tlink->tl_count) != 0 ||
4202 		    time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4203 			continue;
4204 
4205 		cifs_get_tlink(tlink);
4206 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4207 		rb_erase(tmp, root);
4208 
4209 		spin_unlock(&cifs_sb->tlink_tree_lock);
4210 		cifs_put_tlink(tlink);
4211 		spin_lock(&cifs_sb->tlink_tree_lock);
4212 	}
4213 	spin_unlock(&cifs_sb->tlink_tree_lock);
4214 
4215 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4216 				TLINK_IDLE_EXPIRE);
4217 }
4218 
4219 #ifndef CONFIG_CIFS_DFS_UPCALL
4220 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4221 {
4222 	int rc;
4223 	const struct smb_version_operations *ops = tcon->ses->server->ops;
4224 
4225 	/* only send once per connect */
4226 	spin_lock(&tcon->tc_lock);
4227 	if (tcon->status == TID_GOOD) {
4228 		spin_unlock(&tcon->tc_lock);
4229 		return 0;
4230 	}
4231 
4232 	if (tcon->status != TID_NEW &&
4233 	    tcon->status != TID_NEED_TCON) {
4234 		spin_unlock(&tcon->tc_lock);
4235 		return -EHOSTDOWN;
4236 	}
4237 
4238 	tcon->status = TID_IN_TCON;
4239 	spin_unlock(&tcon->tc_lock);
4240 
4241 	rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4242 	if (rc) {
4243 		spin_lock(&tcon->tc_lock);
4244 		if (tcon->status == TID_IN_TCON)
4245 			tcon->status = TID_NEED_TCON;
4246 		spin_unlock(&tcon->tc_lock);
4247 	} else {
4248 		spin_lock(&tcon->tc_lock);
4249 		if (tcon->status == TID_IN_TCON)
4250 			tcon->status = TID_GOOD;
4251 		tcon->need_reconnect = false;
4252 		spin_unlock(&tcon->tc_lock);
4253 	}
4254 
4255 	return rc;
4256 }
4257 #endif
4258