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