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