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