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