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