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