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