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