connect.c 116 KB
Newer Older
1
// SPDX-License-Identifier: LGPL-2.1
Linus Torvalds's avatar
Linus Torvalds committed
2 3
/*
 *
4
 *   Copyright (C) International Business Machines  Corp., 2002,2011
Linus Torvalds's avatar
Linus Torvalds committed
5 6 7 8 9 10
 *   Author(s): Steve French (sfrench@us.ibm.com)
 *
 */
#include <linux/fs.h>
#include <linux/net.h>
#include <linux/string.h>
11
#include <linux/sched/mm.h>
12
#include <linux/sched/signal.h>
Linus Torvalds's avatar
Linus Torvalds committed
13 14
#include <linux/list.h>
#include <linux/wait.h>
15
#include <linux/slab.h>
Linus Torvalds's avatar
Linus Torvalds committed
16 17 18 19
#include <linux/pagemap.h>
#include <linux/ctype.h>
#include <linux/utsname.h>
#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>
Linus Torvalds's avatar
Linus Torvalds committed
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>
Linus Torvalds's avatar
Linus Torvalds committed
35 36 37 38 39 40 41 42 43
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_unicode.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include "ntlmssp.h"
#include "nterr.h"
#include "rfc1002pdu.h"
44
#include "fscache.h"
45
#include "smb2proto.h"
46
#include "smbdirect.h"
47 48
#include "dns_resolve.h"
#ifdef CONFIG_CIFS_DFS_UPCALL
49
#include "dfs.h"
50 51
#include "dfs_cache.h"
#endif
52
#include "fs_context.h"
53
#include "cifs_swn.h"
Linus Torvalds's avatar
Linus Torvalds committed
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 63
static int ip_connect(struct TCP_Server_Info *server);
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 69 70 71 72
/*
 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
 * get their ip addresses changed at some point.
 *
 * This should be called with server->srv_mutex held.
 */
73
static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
74 75 76
{
	int rc;
	int len;
77 78
	char *unc;
	struct sockaddr_storage ss;
79 80 81 82

	if (!server->hostname)
		return -EINVAL;

83 84 85 86
	/* if server hostname isn't populated, there's nothing to do here */
	if (server->hostname[0] == '\0')
		return 0;

87 88 89 90 91 92 93
	len = strlen(server->hostname) + 3;

	unc = kmalloc(len, GFP_KERNEL);
	if (!unc) {
		cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
		return -ENOMEM;
	}
94
	scnprintf(unc, len, "\\\\%s", server->hostname);
95

96 97 98 99
	spin_lock(&server->srv_lock);
	ss = server->dstaddr;
	spin_unlock(&server->srv_lock);

100
	rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
101 102 103 104 105
	kfree(unc);

	if (rc < 0) {
		cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
			 __func__, server->hostname, rc);
106 107 108 109 110
	} else {
		spin_lock(&server->srv_lock);
		memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
		spin_unlock(&server->srv_lock);
		rc = 0;
111 112
	}

113 114 115
	return rc;
}

116 117 118
static void smb2_query_server_interfaces(struct work_struct *work)
{
	int rc;
119
	int xid;
120 121 122
	struct cifs_tcon *tcon = container_of(work,
					struct cifs_tcon,
					query_interfaces.work);
123
	struct TCP_Server_Info *server = tcon->ses->server;
124 125 126 127

	/*
	 * query server network interfaces, in case they change
	 */
128 129 130
	if (!server->ops->query_server_interfaces)
		return;

131
	xid = get_xid();
132
	rc = server->ops->query_server_interfaces(xid, tcon, false);
133 134
	free_xid(xid);

135
	if (rc) {
136 137 138
		if (rc == -EOPNOTSUPP)
			return;

139 140 141 142 143 144 145
		cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
				__func__, rc);
	}

	queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
			   (SMB_INTERFACE_POLL_INTERVAL * HZ));
}
146

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
/*
 * Update the tcpStatus for the server.
 * This is used to signal the cifsd thread to call cifs_reconnect
 * ONLY cifsd thread should call cifs_reconnect. For any other
 * thread, use this function
 *
 * @server: the tcp ses for which reconnect is needed
 * @all_channels: if this needs to be done for all channels
 */
void
cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
				bool all_channels)
{
	struct TCP_Server_Info *pserver;
	struct cifs_ses *ses;
	int i;

	/* 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 170 171 172
		spin_lock(&server->srv_lock);
		if (server->tcpStatus != CifsExiting)
			server->tcpStatus = CifsNeedReconnect;
		spin_unlock(&server->srv_lock);
173 174 175
		return;
	}

176
	spin_lock(&cifs_tcp_ses_lock);
177
	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
178 179
		if (cifs_ses_exiting(ses))
			continue;
180
		spin_lock(&ses->chan_lock);
181
		for (i = 0; i < ses->chan_count; i++) {
182 183 184
			if (!ses->chans[i].server)
				continue;

185
			spin_lock(&ses->chans[i].server->srv_lock);
186 187
			if (ses->chans[i].server->tcpStatus != CifsExiting)
				ses->chans[i].server->tcpStatus = CifsNeedReconnect;
188 189
			spin_unlock(&ses->chans[i].server->srv_lock);
		}
190 191 192 193 194
		spin_unlock(&ses->chan_lock);
	}
	spin_unlock(&cifs_tcp_ses_lock);
}

195
/*
196
 * Mark all sessions and tcons for reconnect.
197 198 199
 * IMPORTANT: make sure that this gets called only from
 * cifsd thread. For any other thread, use
 * 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
206 207
cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
				      bool mark_smb_session)
Linus Torvalds's avatar
Linus Torvalds committed
208
{
209
	struct TCP_Server_Info *pserver;
210
	struct cifs_ses *ses, *nses;
211
	struct cifs_tcon *tcon;
Linus Torvalds's avatar
Linus Torvalds committed
212

213 214 215 216
	/*
	 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
	 * are not used until reconnected.
	 */
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 224 225 226 227 228 229 230 231 232 233
	/*
	 * if the server has been marked for termination, there is a
	 * chance that the remaining channels all need reconnect. To be
	 * on the safer side, mark the session and trees for reconnect
	 * for this scenario. This might cause a few redundant session
	 * setup and tree connect requests, but it is better than not doing
	 * a tree connect when needed, and all following requests failing
	 */
	if (server->terminate) {
		mark_smb_session = true;
		server = pserver;
	}
234

235
	spin_lock(&cifs_tcp_ses_lock);
236
	list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
237 238 239 240 241 242 243
		spin_lock(&ses->ses_lock);
		if (ses->ses_status == SES_EXITING) {
			spin_unlock(&ses->ses_lock);
			continue;
		}
		spin_unlock(&ses->ses_lock);

244
		spin_lock(&ses->chan_lock);
245 246 247 248 249 250
		if (cifs_ses_get_chan_index(ses, server) ==
		    CIFS_INVAL_CHAN_INDEX) {
			spin_unlock(&ses->chan_lock);
			continue;
		}

251 252
		if (!cifs_chan_is_iface_active(ses, server)) {
			spin_unlock(&ses->chan_lock);
253
			cifs_chan_update_iface(ses, server);
254 255
			spin_lock(&ses->chan_lock);
		}
256

257 258 259 260
		if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
			spin_unlock(&ses->chan_lock);
			continue;
		}
261

262 263 264 265
		if (mark_smb_session)
			CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
		else
			cifs_chan_set_need_reconnect(ses, server);
266

267 268 269
		cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
			 __func__, ses->chans_need_reconnect);

270
		/* If all channels need reconnect, then tcon needs reconnect */
271 272 273 274 275
		if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
			spin_unlock(&ses->chan_lock);
			continue;
		}
		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
		}
Linus Torvalds's avatar
Linus Torvalds committed
295
	}
296
	spin_unlock(&cifs_tcp_ses_lock);
297 298 299 300 301 302 303 304 305 306
}

static void
cifs_abort_connection(struct TCP_Server_Info *server)
{
	struct mid_q_entry *mid, *nmid;
	struct list_head retry_list;

	server->maxBuf = 0;
	server->max_read = 0;
307

Linus Torvalds's avatar
Linus Torvalds committed
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 313
		cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
			 server->ssocket->flags);
314
		kernel_sock_shutdown(server->ssocket, SHUT_WR);
315 316
		cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
			 server->ssocket->flags);
317 318 319 320 321
		sock_release(server->ssocket);
		server->ssocket = NULL;
	}
	server->sequence_number = 0;
	server->session_estab = false;
322
	kfree_sensitive(server->session_key.response);
323 324 325
	server->session_key.response = NULL;
	server->session_key.len = 0;
	server->lstrp = jiffies;
Linus Torvalds's avatar
Linus Torvalds committed
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 332 333 334 335 336
	list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
		kref_get(&mid->refcount);
		if (mid->mid_state == MID_REQUEST_SUBMITTED)
			mid->mid_state = MID_RETRY_NEEDED;
		list_move(&mid->qhead, &retry_list);
		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 343 344
	list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
		list_del_init(&mid->qhead);
		mid->callback(mid);
345
		release_mid(mid);
Linus Torvalds's avatar
Linus Torvalds committed
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
}

355 356
static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
{
357
	spin_lock(&server->srv_lock);
358 359 360
	server->nr_targets = num_targets;
	if (server->tcpStatus == CifsExiting) {
		/* the demux thread will exit normally next time through the loop */
361
		spin_unlock(&server->srv_lock);
362 363 364
		wake_up(&server->response_q);
		return false;
	}
365 366 367 368

	cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
	trace_smb3_reconnect(server->CurrentMid, server->conn_id,
			     server->hostname);
369
	server->tcpStatus = CifsNeedReconnect;
370

371
	spin_unlock(&server->srv_lock);
372 373 374
	return true;
}

375 376 377 378 379 380 381
/*
 * cifs tcp session reconnection
 *
 * mark tcp session as reconnecting so temporarily locked
 * mark all smb sessions as reconnecting for tcp session
 * reconnect tcp session
 * wake up waiters on reconnection? - (not needed currently)
382 383 384 385 386
 *
 * if mark_smb_session is passed as true, unconditionally mark
 * the smb session (and tcon) for reconnect as well. This value
 * doesn't really matter for non-multichannel scenario.
 *
387
 */
388 389
static int __cifs_reconnect(struct TCP_Server_Info *server,
			    bool mark_smb_session)
390 391 392
{
	int rc = 0;

393 394
	if (!cifs_tcp_ses_needs_reconnect(server, 1))
		return 0;
395

396
	cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
397

398 399
	cifs_abort_connection(server);

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 411 412 413
		if (cifs_rdma_enabled(server))
			rc = smbd_reconnect(server);
		else
			rc = generic_ip_connect(server);
Steve French's avatar
Steve French committed
414
		if (rc) {
415
			cifs_server_unlock(server);
416
			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
417
			msleep(3000);
Linus Torvalds's avatar
Linus Torvalds committed
418 419
		} else {
			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);
Linus Torvalds's avatar
Linus Torvalds committed
428
		}
429
	} while (server->tcpStatus == CifsNeedReconnect);
430

431
	spin_lock(&server->srv_lock);
432 433
	if (server->tcpStatus == CifsNeedNegotiate)
		mod_delayed_work(cifsiod_wq, &server->echo, 0);
434
	spin_unlock(&server->srv_lock);
435 436 437 438 439

	wake_up(&server->response_q);
	return rc;
}

440
#ifdef CONFIG_CIFS_DFS_UPCALL
441 442 443 444 445 446 447 448 449
static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
{
	int rc;
	char *hostname;

	if (!cifs_swn_set_server_dstaddr(server)) {
		if (server->hostname != target) {
			hostname = extract_hostname(target);
			if (!IS_ERR(hostname)) {
450
				spin_lock(&server->srv_lock);
451 452
				kfree(server->hostname);
				server->hostname = hostname;
453
				spin_unlock(&server->srv_lock);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
			} else {
				cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
					 __func__, PTR_ERR(hostname));
				cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
					 server->hostname);
			}
		}
		/* resolve the hostname again to make sure that IP address is up-to-date. */
		rc = reconn_set_ipaddr_from_hostname(server);
		cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
	}
	/* Reconnect the socket */
	if (cifs_rdma_enabled(server))
		rc = smbd_reconnect(server);
	else
		rc = generic_ip_connect(server);

	return rc;
}

static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
				     struct dfs_cache_tgt_iterator **target_hint)
{
	int rc;
	struct dfs_cache_tgt_iterator *tit;

	*target_hint = NULL;

	/* If dfs target list is empty, then reconnect to last server */
	tit = dfs_cache_get_tgt_iterator(tl);
	if (!tit)
		return __reconnect_target_unlocked(server, server->hostname);

	/* Otherwise, try every dfs target in @tl */
	for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
		rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
		if (!rc) {
			*target_hint = tit;
			break;
		}
	}
	return rc;
}

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 508 509 510 511 512 513

	/*
	 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
	 *
	 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
	 * targets (server->nr_targets).  It's also possible that the cached referral was cleared
	 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
	 * refreshing the referral, so, in this case, default it to 1.
	 */
514 515
	mutex_lock(&server->refpath_lock);
	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 519
	if (!num_targets)
		num_targets = 1;
520 521 522 523

	if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
		return 0;

524 525 526 527 528 529
	/*
	 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
	 * different server or share during failover.  It could be improved by adding some logic to
	 * only do that in case it connects to a different server or share, though.
	 */
	cifs_mark_tcp_ses_conns_for_reconnect(server, true);
530

531 532
	cifs_abort_connection(server);

533 534
	do {
		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 542 543
			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
			msleep(3000);
			continue;
544
		}
545 546 547 548 549 550 551
		/*
		 * Socket was created.  Update tcp session status to CifsNeedNegotiate so that a
		 * process waiting for reconnect will know it needs to re-establish session and tcon
		 * through the reconnected target server.
		 */
		atomic_inc(&tcpSesReconnectCount);
		set_credits(server, 1);
552
		spin_lock(&server->srv_lock);
553 554
		if (server->tcpStatus != CifsExiting)
			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 560
	} while (server->tcpStatus == CifsNeedReconnect);

561 562 563
	mutex_lock(&server->refpath_lock);
	dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
	mutex_unlock(&server->refpath_lock);
564 565 566
	dfs_cache_free_tgts(&tl);

	/* Need to set up echo worker again once connection has been established */
567
	spin_lock(&server->srv_lock);
568 569
	if (server->tcpStatus == CifsNeedNegotiate)
		mod_delayed_work(cifsiod_wq, &server->echo, 0);
570
	spin_unlock(&server->srv_lock);
571

572
	wake_up(&server->response_q);
Linus Torvalds's avatar
Linus Torvalds committed
573 574 575
	return rc;
}

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 581 582 583 584
		mutex_unlock(&server->refpath_lock);
		return __cifs_reconnect(server, mark_smb_session);
	}
	mutex_unlock(&server->refpath_lock);

585
	return reconnect_dfs_server(server);
586 587
}
#else
588
int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
589
{
590
	return __cifs_reconnect(server, mark_smb_session);
591 592 593
}
#endif

594 595 596 597 598 599 600
static void
cifs_echo_request(struct work_struct *work)
{
	int rc;
	struct TCP_Server_Info *server = container_of(work,
					struct TCP_Server_Info, echo.work);

601
	/*
602 603
	 * We cannot send an echo if it is disabled.
	 * Also, no need to ping if we got a response recently.
604
	 */
605 606

	if (server->tcpStatus == CifsNeedReconnect ||
607 608
	    server->tcpStatus == CifsExiting ||
	    server->tcpStatus == CifsNew ||
609
	    (server->ops->can_echo && !server->ops->can_echo(server)) ||
610
	    time_before(jiffies, server->lstrp + server->echo_interval - HZ))
611 612
		goto requeue_echo;

613
	rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
614
	cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
615

616 617 618
	/* Check witness registrations */
	cifs_swn_check();

619
requeue_echo:
620
	queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
621 622
}

623
static bool
624
allocate_buffers(struct TCP_Server_Info *server)
625
{
626 627 628
	if (!server->bigbuf) {
		server->bigbuf = (char *)cifs_buf_get();
		if (!server->bigbuf) {
629
			cifs_server_dbg(VFS, "No memory for large SMB response\n");
630 631 632 633
			msleep(3000);
			/* retry will check if exiting */
			return false;
		}
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 640 641
	if (!server->smallbuf) {
		server->smallbuf = (char *)cifs_small_buf_get();
		if (!server->smallbuf) {
642
			cifs_server_dbg(VFS, "No memory for SMB response\n");
643 644 645 646 647 648 649
			msleep(1000);
			/* retry will check if exiting */
			return false;
		}
		/* beginning of smb buffer is cleared in our buf_get */
	} else {
		/* if existing small buf clear beginning */
650
		memset(server->smallbuf, 0, HEADER_SIZE(server));
651 652 653 654 655
	}

	return true;
}

656 657 658
static bool
server_unresponsive(struct TCP_Server_Info *server)
{
659
	/*
660
	 * We need to wait 3 echo intervals to make sure we handle such
661 662
	 * situations right:
	 * 1s  client sends a normal SMB request
663
	 * 2s  client gets a response
664 665 666 667 668 669
	 * 30s echo workqueue job pops, and decides we got a response recently
	 *     and don't need to send another
	 * ...
	 * 65s kernel_recvmsg times out, and we see that we haven't gotten
	 *     a response in >60s.
	 */
670
	spin_lock(&server->srv_lock);
671 672
	if ((server->tcpStatus == CifsGood ||
	    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 677
		cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
			 (3 * server->echo_interval) / HZ);
678
		cifs_reconnect(server, false);
679 680
		return true;
	}
681
	spin_unlock(&server->srv_lock);
682 683 684 685

	return false;
}

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
static inline bool
zero_credits(struct TCP_Server_Info *server)
{
	int val;

	spin_lock(&server->req_lock);
	val = server->credits + server->echo_credits + server->oplock_credits;
	if (server->in_flight == 0 && val == 0) {
		spin_unlock(&server->req_lock);
		return true;
	}
	spin_unlock(&server->req_lock);
	return false;
}

701 702
static int
cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
703
{
704 705
	int length = 0;
	int total_read;
706

707
	for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
708 709
		try_to_freeze();

710 711
		/* reconnect if no credits and no requests in flight */
		if (zero_credits(server)) {
712
			cifs_reconnect(server, false);
713 714 715
			return -ECONNABORTED;
		}

716 717
		if (server_unresponsive(server))
			return -ECONNABORTED;
718 719 720 721
		if (cifs_rdma_enabled(server) && server->smbd_conn)
			length = smbd_recv(server->smbd_conn, smb_msg);
		else
			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 733
			return -ECONNABORTED;
		}
734
		spin_unlock(&server->srv_lock);
735 736 737 738

		if (length == -ERESTARTSYS ||
		    length == -EAGAIN ||
		    length == -EINTR) {
739 740 741 742 743 744 745
			/*
			 * Minimum sleep to prevent looping, allowing socket
			 * to clear and app threads to set tcpStatus
			 * CifsNeedReconnect if server hung.
			 */
			usleep_range(1000, 2000);
			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
}

Jeff Layton's avatar
Jeff Layton committed
758 759 760
int
cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
		      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 768
	return cifs_readv_from_socket(server, &smb_msg);
}
769

770 771 772
ssize_t
cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
{
773
	struct msghdr smb_msg = {};
774 775 776 777 778 779

	/*
	 *  iov_iter_discard already sets smb_msg.type and count and iov_offset
	 *  and cifs_readv_from_socket sets msg_control and msg_controllen
	 *  so little to initialize in struct msghdr
	 */
780
	iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
781 782 783 784

	return cifs_readv_from_socket(server, &smb_msg);
}

785 786
int
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 791 792
	struct bio_vec bv;

	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 798 799 800 801 802 803 804 805 806 807 808 809 810
int
cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
			   unsigned int to_read)
{
	struct msghdr smb_msg = { .msg_iter = *iter };
	int ret;

	iov_iter_truncate(&smb_msg.msg_iter, to_read);
	ret = cifs_readv_from_socket(server, &smb_msg);
	if (ret > 0)
		iov_iter_advance(iter, ret);
	return ret;
}

811
static bool
812
is_smb_response(struct TCP_Server_Info *server, unsigned char type)
813 814 815 816 817 818
{
	/*
	 * The first byte big endian of the length field,
	 * is actually not part of the length but the type
	 * with the most common, zero, as regular data.
	 */
819 820 821 822 823
	switch (type) {
	case RFC1002_SESSION_MESSAGE:
		/* Regular SMB response */
		return true;
	case RFC1002_SESSION_KEEP_ALIVE:
824
		cifs_dbg(FYI, "RFC 1002 session keep alive\n");
825 826
		break;
	case RFC1002_POSITIVE_SESSION_RESPONSE:
827
		cifs_dbg(FYI, "RFC 1002 positive session response\n");
828 829
		break;
	case RFC1002_NEGATIVE_SESSION_RESPONSE:
830 831 832 833
		/*
		 * We get this from Windows 98 instead of an error on
		 * SMB negprot response.
		 */
834
		cifs_dbg(FYI, "RFC 1002 negative session response\n");
835 836 837 838 839 840 841 842
		/* give server a second to clean up */
		msleep(1000);
		/*
		 * Always try 445 first on reconnect since we get NACK
		 * on some if we ever connected to port 139 (the NACK
		 * is since we do not begin with RFC1001 session
		 * initialize frame).
		 */
843
		cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
844
		cifs_reconnect(server, true);
845 846
		break;
	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
}

Jeff Layton's avatar
Jeff Layton committed
854 855
void
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 867 868
	/*
	 * Trying to handle/dequeue a mid after the send_recv()
	 * function has finished processing it is a bug.
	 */
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 880 881
static unsigned int
smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
{
882
	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
883 884 885 886

	/*
	 * SMB1 does not use credits.
	 */
887
	if (is_smb1(server))
888 889 890 891 892
		return 0;

	return le16_to_cpu(shdr->CreditRequest);
}

893 894
static void
handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
895
	   char *buf, int malformed)
896
{
897 898
	if (server->ops->check_trans2 &&
	    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 904 905 906 907 908 909 910
	/* Was previous buf put in mpx struct for multi-rsp? */
	if (!mid->multiRsp) {
		/* smb buffer will be freed by user thread */
		if (server->large_buf)
			server->bigbuf = NULL;
		else
			server->smallbuf = NULL;
	}
911
	dequeue_mid(mid, malformed);
912 913
}

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
int
cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
{
	bool srv_sign_required = server->sec_mode & server->vals->signing_required;
	bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
	bool mnt_sign_enabled;

	/*
	 * Is signing required by mnt options? If not then check
	 * global_secflags to see if it is there.
	 */
	if (!mnt_sign_required)
		mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
						CIFSSEC_MUST_SIGN);

	/*
	 * If signing is required then it's automatically enabled too,
	 * otherwise, check to see if the secflags allow it.
	 */
	mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
				(global_secflags & CIFSSEC_MAY_SIGN);

	/* If server requires signing, does client allow it? */
	if (srv_sign_required) {
		if (!mnt_sign_enabled) {
			cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
			return -EOPNOTSUPP;
		}
		server->sign = true;
	}

	/* If client requires signing, does server allow it? */
	if (mnt_sign_required) {
		if (!srv_sign_enabled) {
			cifs_dbg(VFS, "Server does not support signing!\n");
			return -EOPNOTSUPP;
		}
		server->sign = true;
	}

	if (cifs_rdma_enabled(server) && server->sign)
		cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");

	return 0;
}

960 961
static noinline_for_stack void
clean_demultiplex_info(struct TCP_Server_Info *server)
962 963 964 965
{
	int length;

	/* 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 971
	cancel_delayed_work_sync(&server->echo);

972
	spin_lock(&server->srv_lock);
973
	server->tcpStatus = CifsExiting;
974
	spin_unlock(&server->srv_lock);
975 976
	wake_up_all(&server->response_q);

977
	/* check if we have blocked requests that need to free */
978
	spin_lock(&server->req_lock);
979 980
	if (server->credits <= 0)
		server->credits = 1;
981
	spin_unlock(&server->req_lock);
982 983 984 985 986 987 988 989 990 991
	/*
	 * Although there should not be any requests blocked on this queue it
	 * can not hurt to be paranoid and try to wake up requests that may
	 * haven been blocked when more than 50 at time were on the wire to the
	 * same server - they now will see the session is in exit state and get
	 * out of SendReceive.
	 */
	wake_up_all(&server->request_q);
	/* give those requests time to exit */
	msleep(125);
992 993
	if (cifs_rdma_enabled(server))
		smbd_destroy(server);
994 995 996 997 998 999 1000 1001 1002 1003 1004
	if (server->ssocket) {
		sock_release(server->ssocket);
		server->ssocket = NULL;
	}

	if (!list_empty(&server->pending_mid_q)) {
		struct list_head dispose_list;
		struct mid_q_entry *mid_entry;
		struct list_head *tmp, *tmp2;

		INIT_LIST_HEAD(&dispose_list);
1005
		spin_lock(&server->mid_lock);
1006 1007
		list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
			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 1017 1018

		/* now walk dispose list and issue callbacks */
		list_for_each_safe(tmp, tmp2, &dispose_list) {
			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1019
			cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1020 1021
			list_del_init(&mid_entry->qhead);
			mid_entry->callback(mid_entry);
1022
			release_mid(mid_entry);
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
		}
		/* 1/8th of sec is more than enough time for them to exit */
		msleep(125);
	}

	if (!list_empty(&server->pending_mid_q)) {
		/*
		 * mpx threads have not exited yet give them at least the smb
		 * send timeout time for long ops.
		 *
		 * Due to delays on oplock break requests, we need to wait at
		 * least 45 seconds before giving up on a request getting a
		 * response and going ahead and killing cifsd.
		 */
1037
		cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1038 1039 1040 1041 1042 1043 1044
		msleep(46000);
		/*
		 * If threads still have not exited they are probably never
		 * coming home not much else we can do but free the memory.
		 */
	}

1045
	kfree(server->leaf_fullpath);
1046 1047 1048 1049
	kfree(server);

	length = atomic_dec_return(&tcpSesAllocCount);
	if (length > 0)
1050
		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1051 1052
}

1053 1054 1055 1056 1057
static int
standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
{
	int length;
	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 1069 1070
	}

	/* switch to large buffer if too big for a small one */
	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
		server->large_buf = true;
1071
		memcpy(server->bigbuf, buf, server->total_read);
1072 1073 1074 1075
		buf = server->bigbuf;
	}

	/* 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 1080 1081 1082
	if (length < 0)
		return length;
	server->total_read += length;

1083
	dump_smb(buf, server->total_read);
1084

1085 1086 1087 1088 1089 1090 1091
	return cifs_handle_standard(server, mid);
}

int
cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
{
	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1092
	int rc;
1093

1094 1095 1096
	/*
	 * We know that we received enough to get to the MID as we
	 * checked the pdu_length earlier. Now check to see
1097
	 * if the rest of the header is OK.
1098 1099 1100 1101
	 *
	 * 48 bytes is enough to display the header and a little bit
	 * into the payload for debugging purposes.
	 */
1102 1103
	rc = server->ops->check_message(buf, server->total_read, server);
	if (rc)
1104 1105 1106
		cifs_dump_mem("Bad SMB: ", buf,
			min_t(unsigned int, server->total_read, 48));

1107 1108
	if (server->ops->is_session_expired &&
	    server->ops->is_session_expired(buf)) {
1109
		cifs_reconnect(server, true);
1110 1111 1112
		return -1;
	}

1113
	if (server->ops->is_status_pending &&
1114
	    server->ops->is_status_pending(buf, server))
1115 1116
		return -1;

1117
	if (!mid)
1118
		return rc;
1119

1120
	handle_mid(mid, server, buf, rc);
1121
	return 0;
1122 1123
}

1124 1125 1126
static void
smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
{
1127
	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1128
	int scredits, in_flight;
1129 1130 1131 1132

	/*
	 * SMB1 does not use credits.
	 */
1133
	if (is_smb1(server))
1134 1135 1136 1137 1138
		return;

	if (shdr->CreditRequest) {
		spin_lock(&server->req_lock);
		server->credits += le16_to_cpu(shdr->CreditRequest);
1139 1140
		scredits = server->credits;
		in_flight = server->in_flight;
1141 1142
		spin_unlock(&server->req_lock);
		wake_up(&server->request_q);
1143

1144
		trace_smb3_hdr_credits(server->CurrentMid,
1145 1146
				server->conn_id, server->hostname, scredits,
				le16_to_cpu(shdr->CreditRequest), in_flight);
1147 1148 1149
		cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
				__func__, le16_to_cpu(shdr->CreditRequest),
				scredits);
1150 1151 1152 1153
	}
}


Linus Torvalds's avatar
Linus Torvalds committed
1154
static int
1155
cifs_demultiplex_thread(void *p)
Linus Torvalds's avatar
Linus Torvalds committed
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 1164
	struct mid_q_entry *mids[MAX_COMPOUND];
	char *bufs[MAX_COMPOUND];
1165
	unsigned int noreclaim_flag, num_io_timeout = 0;
1166
	bool pending_reconnect = false;
Linus Torvalds's avatar
Linus Torvalds committed
1167

1168
	noreclaim_flag = memalloc_noreclaim_save();
1169
	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1170 1171 1172

	length = atomic_inc_return(&tcpSesAllocCount);
	if (length > 1)
1173
		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
Linus Torvalds's avatar
Linus Torvalds committed
1174

1175
	set_freezable();
1176
	allow_kernel_signal(SIGKILL);
1177
	while (server->tcpStatus != CifsExiting) {
1178 1179
		if (try_to_freeze())
			continue;
1180

1181
		if (!allocate_buffers(server))
1182
			continue;
1183

1184 1185
		server->large_buf = false;
		buf = server->smallbuf;
1186
		pdu_length = 4; /* enough to get RFC1001 header */
1187

Jeff Layton's avatar
Jeff Layton committed
1188
		length = cifs_read_from_socket(server, buf, pdu_length);
1189
		if (length < 0)
Linus Torvalds's avatar
Linus Torvalds committed
1190
			continue;
1191

1192
		if (is_smb1(server))
1193
			server->total_read = length;
1194 1195
		else
			server->total_read = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1196

1197 1198 1199 1200
		/*
		 * The right amount was read from socket - 4 bytes,
		 * so we can now interpret the length field.
		 */
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]))
Steve French's avatar
Steve French committed
1205
			continue;
1206 1207

		pending_reconnect = false;
1208 1209
next_pdu:
		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;
Linus Torvalds's avatar
Linus Torvalds committed
1226

1227
		if (server->ops->next_header) {
1228 1229 1230 1231 1232 1233
			if (server->ops->next_header(server, buf, &next_offset)) {
				cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
					 __func__, next_offset);
				cifs_reconnect(server, true);
				continue;
			}
1234 1235 1236 1237
			if (next_offset)
				server->pdu_size = next_offset;
		}

1238 1239 1240 1241
		memset(mids, 0, sizeof(mids));
		memset(bufs, 0, sizeof(bufs));
		num_mids = 0;

1242 1243 1244 1245
		if (server->ops->is_transform_hdr &&
		    server->ops->receive_transform &&
		    server->ops->is_transform_hdr(buf)) {
			length = server->ops->receive_transform(server,
1246 1247 1248
								mids,
								bufs,
								&num_mids);
1249
		} else {
1250 1251
			mids[0] = server->ops->find_mid(server, buf);
			bufs[0] = buf;
1252
			num_mids = 1;
1253

1254 1255
			if (!mids[0] || !mids[0]->receive)
				length = standard_receive3(server, mids[0]);
1256
			else
1257
				length = mids[0]->receive(server, mids[0]);
1258
		}
1259

1260
		if (length < 0) {
1261 1262
			for (i = 0; i < num_mids; i++)
				if (mids[i])
1263
					release_mid(mids[i]);
1264
			continue;
1265
		}
Linus Torvalds's avatar
Linus Torvalds committed
1266

1267 1268 1269
		if (server->ops->is_status_io_timeout &&
		    server->ops->is_status_io_timeout(buf)) {
			num_io_timeout++;
1270 1271 1272 1273 1274 1275
			if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
				cifs_server_dbg(VFS,
						"Number of request timeouts exceeded %d. Reconnecting",
						MAX_STATUS_IO_TIMEOUT);

				pending_reconnect = true;
1276 1277 1278 1279
				num_io_timeout = 0;
			}
		}

1280
		server->lstrp = jiffies;
1281

1282 1283 1284
		for (i = 0; i < num_mids; i++) {
			if (mids[i] != NULL) {
				mids[i]->resp_buf_size = server->pdu_size;
1285

1286 1287 1288 1289 1290 1291 1292 1293
				if (bufs[i] != NULL) {
					if (server->ops->is_network_name_deleted &&
					    server->ops->is_network_name_deleted(bufs[i],
										 server)) {
						cifs_server_dbg(FYI,
								"Share deleted. Reconnect needed");
					}
				}
1294

1295 1296 1297
				if (!mids[i]->multiRsp || mids[i]->multiEnd)
					mids[i]->callback(mids[i]);

1298
				release_mid(mids[i]);
1299 1300 1301
			} else if (server->ops->is_oplock_break &&
				   server->ops->is_oplock_break(bufs[i],
								server)) {
1302
				smb2_add_credits_from_hdr(bufs[i], server);
1303 1304
				cifs_dbg(FYI, "Received oplock break\n");
			} else {
1305
				cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1306
						atomic_read(&mid_count));
1307 1308
				cifs_dump_mem("Received Data is: ", bufs[i],
					      HEADER_SIZE(server));
1309
				smb2_add_credits_from_hdr(bufs[i], server);
1310
#ifdef CONFIG_CIFS_DEBUG2
1311 1312 1313 1314
				if (server->ops->dump_detail)
					server->ops->dump_detail(bufs[i],
								 server);
				cifs_dump_mids(server);
1315
#endif /* CIFS_DEBUG2 */
1316
			}
1317
		}
1318

1319 1320 1321 1322 1323 1324 1325 1326
		if (pdu_length > server->pdu_size) {
			if (!allocate_buffers(server))
				continue;
			pdu_length -= server->pdu_size;
			server->total_read = 0;
			server->large_buf = false;
			buf = server->smallbuf;
			goto next_pdu;
1327
		}
1328 1329 1330 1331 1332

		/* do this reconnect at the very end after processing all MIDs */
		if (pending_reconnect)
			cifs_reconnect(server, true);

1333 1334
	} /* end while !EXITING */

1335
	/* buffer usually freed in free_mid - need to free it here on exit */
1336 1337 1338
	cifs_buf_release(server->bigbuf);
	if (server->smallbuf) /* no sense logging a debug message if NULL */
		cifs_small_buf_release(server->smallbuf);
Linus Torvalds's avatar
Linus Torvalds committed
1339

1340
	task_to_wake = xchg(&server->tsk, NULL);
1341
	clean_demultiplex_info(server);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

	/* if server->tsk was NULL then wait for a signal before exiting */
	if (!task_to_wake) {
		set_current_state(TASK_INTERRUPTIBLE);
		while (!signal_pending(current)) {
			schedule();
			set_current_state(TASK_INTERRUPTIBLE);
		}
		set_current_state(TASK_RUNNING);
	}

1353
	memalloc_noreclaim_restore(noreclaim_flag);
1354
	module_put_and_kthread_exit(0);
Linus Torvalds's avatar
Linus Torvalds committed
1355 1356
}

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
int
cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
{
	struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
	struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
	struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
	struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;

	switch (srcaddr->sa_family) {
	case AF_UNSPEC:
		switch (rhs->sa_family) {
		case AF_UNSPEC:
			return 0;
		case AF_INET:
		case AF_INET6:
			return 1;
		default:
			return -1;
		}
	case AF_INET: {
		switch (rhs->sa_family) {
		case AF_UNSPEC:
			return -1;
		case AF_INET:
			return memcmp(saddr4, vaddr4,
				      sizeof(struct sockaddr_in));
		case AF_INET6:
			return 1;
		default:
			return -1;
		}
	}
	case AF_INET6: {
		switch (rhs->sa_family) {
		case AF_UNSPEC:
		case AF_INET:
			return -1;
		case AF_INET6:
			return memcmp(saddr6,
				      vaddr6,
				      sizeof(struct sockaddr_in6));
		default:
			return -1;
		}
	}
	default:
		return -1; /* don't expect to be here */
	}
}

1407
/*
1408 1409
 * Returns true if srcaddr isn't specified and rhs isn't specified, or
 * if srcaddr is specified and matches the IP address of the rhs argument
1410
 */
1411 1412
bool
cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1413 1414 1415 1416 1417 1418 1419
{
	switch (srcaddr->sa_family) {
	case AF_UNSPEC:
		return (rhs->sa_family == AF_UNSPEC);
	case AF_INET: {
		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1420

1421 1422 1423 1424
		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
	}
	case AF_INET6: {
		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1425
		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1426

1427 1428
		return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
			&& saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1429 1430 1431 1432 1433 1434 1435
	}
	default:
		WARN_ON(1);
		return false; /* don't expect to be here */
	}
}

1436 1437 1438 1439 1440 1441 1442 1443
/*
 * If no port is specified in addr structure, we try to match with 445 port
 * and if it fails - with 139 ports. It should be called only if address
 * families of server and addr are equal.
 */
static bool
match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
{
1444
	__be16 port, *sport;
1445

1446 1447 1448 1449
	/* SMBDirect manages its own ports, don't match it here */
	if (server->rdma)
		return true;

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
	switch (addr->sa_family) {
	case AF_INET:
		sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
		port = ((struct sockaddr_in *) addr)->sin_port;
		break;
	case AF_INET6:
		sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
		port = ((struct sockaddr_in6 *) addr)->sin6_port;
		break;
	default:
		WARN_ON(1);
		return false;
	}

	if (!port) {
		port = htons(CIFS_PORT);
		if (port == *sport)
			return true;

		port = htons(RFC1001_PORT);
	}

	return port == *sport;
}
1474

1475
static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1476
{
1477 1478
	if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
		return false;
1479 1480 1481 1482

	return true;
}

1483
static bool
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 1489 1490
	 * that was specified, or "Unspecified" if that sectype was not
	 * compatible with the given NEGOTIATE request.
	 */
1491
	if (server->ops->select_sectype(server, ctx->sectype)
1492
	     == Unspecified)
1493 1494
		return false;

1495 1496 1497 1498 1499
	/*
	 * Now check if signing mode is acceptable. No need to check
	 * global_secflags at this point since if MUST_SIGN is set then
	 * the server->sign had better be too.
	 */
1500
	if (ctx->sign && !server->sign)
1501
		return false;
1502 1503 1504 1505

	return true;
}

1506
/* this function must be called with srv_lock held */
1507 1508 1509
static int match_server(struct TCP_Server_Info *server,
			struct smb3_fs_context *ctx,
			bool match_super)
1510
{
1511
	struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1512

1513 1514
	lockdep_assert_held(&server->srv_lock);

1515
	if (ctx->nosharesock)
1516 1517 1518 1519
		return 0;

	/* this server does not share socket */
	if (server->nosharesock)
1520 1521
		return 0;

1522
	/* If multidialect negotiation see if existing sessions match one */
1523
	if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1524 1525
		if (server->vals->protocol_id < SMB30_PROT_ID)
			return 0;
1526
	} else if (strcmp(ctx->vals->version_string,
1527 1528 1529
		   SMBDEFAULT_VERSION_STRING) == 0) {
		if (server->vals->protocol_id < SMB21_PROT_ID)
			return 0;
1530
	} else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1531 1532
		return 0;

1533 1534 1535
	if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
		return 0;

1536 1537
	if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
			       (struct sockaddr *)&server->srcaddr))
1538
		return 0;
1539
	/*
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
	 * When matching cifs.ko superblocks (@match_super == true), we can't
	 * really match either @server->leaf_fullpath or @server->dstaddr
	 * directly since this @server might belong to a completely different
	 * server -- in case of domain-based DFS referrals or DFS links -- as
	 * provided earlier by mount(2) through 'source' and 'ip' options.
	 *
	 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
	 * destination address in @server->dstaddr.
	 *
	 * When using 'nodfs' mount option, we avoid sharing it with DFS
	 * connections as they might failover.
1551
	 */
1552 1553 1554 1555 1556 1557 1558 1559
	if (!match_super) {
		if (!ctx->nodfs) {
			if (server->leaf_fullpath) {
				if (!ctx->leaf_fullpath ||
				    strcasecmp(server->leaf_fullpath,
					       ctx->leaf_fullpath))
					return 0;
			} else if (ctx->leaf_fullpath) {
1560
				return 0;
1561
			}
1562
		} else if (server->leaf_fullpath) {
1563 1564 1565
			return 0;
		}
	}
1566

1567 1568 1569 1570
	/*
	 * Match for a regular connection (address/hostname/port) which has no
	 * DFS referrals set.
	 */
1571
	if (!server->leaf_fullpath &&
1572 1573 1574 1575 1576
	    (strcasecmp(server->hostname, ctx->server_hostname) ||
	     !match_server_address(server, addr) ||
	     !match_port(server, addr)))
		return 0;

1577
	if (!match_security(server, ctx))
1578 1579
		return 0;

1580
	if (server->echo_interval != ctx->echo_interval * HZ)
1581 1582
		return 0;

1583
	if (server->rdma != ctx->rdma)
1584 1585
		return 0;

1586
	if (server->ignore_signature != ctx->ignore_signature)
1587 1588
		return 0;

1589
	if (server->min_offload != ctx->min_offload)
1590 1591
		return 0;

1592 1593 1594
	if (server->retrans != ctx->retrans)
		return 0;

1595 1596 1597
	return 1;
}

1598
struct TCP_Server_Info *
1599
cifs_find_tcp_session(struct smb3_fs_context *ctx)
Linus Torvalds's avatar
Linus Torvalds committed
1600
{
1601 1602
	struct TCP_Server_Info *server;

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 1608 1609
		/*
		 * Skip ses channels since they're only handled in lower layers
		 * (e.g. cifs_send_recv).
		 */
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;
Linus Torvalds's avatar
Linus Torvalds committed
1621
	}
1622
	spin_unlock(&cifs_tcp_ses_lock);
Linus Torvalds's avatar
Linus Torvalds committed
1623 1624
	return NULL;
}
1625

1626 1627
void
cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
Linus Torvalds's avatar
Linus Torvalds committed
1628
{
1629 1630
	struct task_struct *task;

1631
	spin_lock(&cifs_tcp_ses_lock);
1632
	if (--server->srv_count > 0) {
1633
		spin_unlock(&cifs_tcp_ses_lock);
1634
		return;
Linus Torvalds's avatar
Linus Torvalds committed
1635
	}
1636

1637 1638 1639
	/* srv_count can never go negative */
	WARN_ON(server->srv_count < 0);

1640 1641
	put_net(cifs_net_ns(server));

1642
	list_del_init(&server->tcp_ses_list);
1643
	spin_unlock(&cifs_tcp_ses_lock);
1644

1645 1646
	cancel_delayed_work_sync(&server->echo);

1647
	if (from_reconnect)
1648 1649 1650 1651 1652 1653
		/*
		 * Avoid deadlock here: reconnect work calls
		 * cifs_put_tcp_session() at its end. Need to be sure
		 * that reconnect work does nothing with server pointer after
		 * that step.
		 */
1654 1655 1656
		cancel_delayed_work(&server->reconnect);
	else
		cancel_delayed_work_sync(&server->reconnect);
1657

1658 1659 1660 1661
	/* For secondary channels, we pick up ref-count on the primary server */
	if (SERVER_IS_CHAN(server))
		cifs_put_tcp_session(server->primary_server, from_reconnect);

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 1670
	server->session_key.response = NULL;
	server->session_key.len = 0;
1671
	kfree(server->hostname);
1672
	server->hostname = NULL;
1673 1674 1675

	task = xchg(&server->tsk, NULL);
	if (task)
1676
		send_sig(SIGKILL, task, 1);
Linus Torvalds's avatar
Linus Torvalds committed
1677 1678
}

1679
struct TCP_Server_Info *
1680 1681
cifs_get_tcp_session(struct smb3_fs_context *ctx,
		     struct TCP_Server_Info *primary_server)
1682 1683 1684 1685
{
	struct TCP_Server_Info *tcp_ses = NULL;
	int rc;

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 1691 1692 1693 1694 1695 1696 1697 1698
	if (tcp_ses)
		return tcp_ses;

	tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
	if (!tcp_ses) {
		rc = -ENOMEM;
		goto out_err;
	}

1699 1700 1701 1702 1703 1704
	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
	if (!tcp_ses->hostname) {
		rc = -ENOMEM;
		goto out_err;
	}

1705 1706 1707 1708 1709 1710 1711 1712
	if (ctx->leaf_fullpath) {
		tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
		if (!tcp_ses->leaf_fullpath) {
			rc = -ENOMEM;
			goto out_err;
		}
	}

1713 1714 1715
	if (ctx->nosharesock)
		tcp_ses->nosharesock = true;

1716 1717
	tcp_ses->ops = ctx->ops;
	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 1722 1723 1724 1725
	tcp_ses->noblockcnt = ctx->rootfs;
	tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
	tcp_ses->noautotune = ctx->noautotune;
	tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
	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 1736 1737
	init_waitqueue_head(&tcp_ses->response_q);
	init_waitqueue_head(&tcp_ses->request_q);
	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 1751
	spin_lock_init(&tcp_ses->srv_lock);
	spin_lock_init(&tcp_ses->mid_lock);
1752 1753
	INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
	INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1754
	INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1755 1756
	INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
	mutex_init(&tcp_ses->reconnect_mutex);
1757 1758 1759
#ifdef CONFIG_CIFS_DFS_UPCALL
	mutex_init(&tcp_ses->refpath_lock);
#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 1765
	if (ctx->use_client_guid)
		memcpy(tcp_ses->client_guid, ctx->client_guid,
1766 1767 1768
		       SMB2_CLIENT_GUID_SIZE);
	else
		generate_random_uuid(tcp_ses->client_guid);
1769 1770 1771 1772 1773 1774 1775 1776
	/*
	 * at this point we are the only ones with the pointer
	 * to the struct since the kernel thread not created yet
	 * no need to spinlock this init of tcpStatus or srv_count
	 */
	tcp_ses->tcpStatus = CifsNew;
	++tcp_ses->srv_count;

1777 1778 1779
	if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
		ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
		tcp_ses->echo_interval = ctx->echo_interval * HZ;
1780 1781
	else
		tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1782 1783 1784 1785 1786 1787 1788
	if (tcp_ses->rdma) {
#ifndef CONFIG_CIFS_SMB_DIRECT
		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
		rc = -ENOENT;
		goto out_err_crypto_release;
#endif
		tcp_ses->smbd_conn = smbd_get_connection(
1789
			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1790 1791 1792 1793 1794 1795 1796 1797 1798
		if (tcp_ses->smbd_conn) {
			cifs_dbg(VFS, "RDMA transport established\n");
			rc = 0;
			goto smbd_connected;
		} else {
			rc = -ENOENT;
			goto out_err_crypto_release;
		}
	}
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 1807 1808 1809
	/*
	 * since we're in a cifs function already, we know that
	 * this will succeed. No need for try_module_get().
	 */
	__module_get(THIS_MODULE);
1810
	tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1811 1812 1813
				  tcp_ses, "cifsd");
	if (IS_ERR(tcp_ses->tsk)) {
		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 1822 1823 1824
	/*
	 * at this point we are the only ones with the pointer
	 * to the struct since the kernel thread not created yet
	 * no need to spinlock this update of tcpStatus
	 */
1825
	spin_lock(&tcp_ses->srv_lock);
1826
	tcp_ses->tcpStatus = CifsNeedNegotiate;
1827
	spin_unlock(&tcp_ses->srv_lock);
1828

1829 1830 1831 1832 1833
	if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
		tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
	else
		tcp_ses->max_credits = ctx->max_credits;

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 1845
	return tcp_ses;

1846
out_err_crypto_release:
1847
	cifs_crypto_secmech_release(tcp_ses);
1848

1849 1850
	put_net(cifs_net_ns(tcp_ses));

1851 1852
out_err:
	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 1858 1859 1860 1861 1862 1863
		if (tcp_ses->ssocket)
			sock_release(tcp_ses->ssocket);
		kfree(tcp_ses);
	}
	return ERR_PTR(rc);
}

1864
/* this function must be called with ses_lock and chan_lock held */
1865
static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1866
{
1867 1868
	if (ctx->sectype != Unspecified &&
	    ctx->sectype != ses->sectype)
1869 1870
		return 0;

1871 1872 1873
	if (ctx->dfs_root_ses != ses->dfs_root_ses)
		return 0;

1874 1875 1876 1877
	/*
	 * If an existing session is limited to less channels than
	 * requested, it should not be reused
	 */
1878
	if (ses->chan_max < ctx->max_channels)
1879 1880
		return 0;

1881
	switch (ses->sectype) {
1882
	case Kerberos:
1883
		if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1884 1885 1886
			return 0;
		break;
	default:
1887 1888
		/* NULL username means anonymous session */
		if (ses->user_name == NULL) {
1889
			if (!ctx->nullauth)
1890 1891 1892 1893
				return 0;
			break;
		}

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 1901
		    ses->password != NULL &&
		    strncmp(ses->password,
1902
			    ctx->password ? ctx->password : "",
1903
			    CIFS_MAX_PASSWORD_LEN))
1904 1905
			return 0;
	}
1906 1907 1908 1909

	if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
		return 0;

1910 1911 1912
	return 1;
}

1913 1914
/**
 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1915 1916 1917
 * @ses: smb session to issue the request on
 * @ctx: the superblock configuration context to use for building the
 *       new tree connection for the IPC (interprocess communication RPC)
1918 1919 1920 1921 1922
 *
 * A new IPC connection is made and stored in the session
 * tcon_ipc. The IPC tcon has the same lifetime as the session.
 */
static int
1923
cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1924 1925 1926 1927 1928
{
	int rc = 0, xid;
	struct cifs_tcon *tcon;
	char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
	bool seal = false;
1929
	struct TCP_Server_Info *server = ses->server;
1930 1931 1932 1933 1934

	/*
	 * If the mount request that resulted in the creation of the
	 * session requires encryption, force IPC to be encrypted too.
	 */
1935
	if (ctx->seal) {
1936
		if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1937 1938
			seal = true;
		else {
1939
			cifs_server_dbg(VFS,
1940 1941 1942 1943 1944
				 "IPC: server doesn't support encryption\n");
			return -EOPNOTSUPP;
		}
	}

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 1948 1949
	if (tcon == NULL)
		return -ENOMEM;

1950
	spin_lock(&server->srv_lock);
1951
	scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1952
	spin_unlock(&server->srv_lock);
1953 1954 1955 1956 1957

	xid = get_xid();
	tcon->ses = ses;
	tcon->ipc = true;
	tcon->seal = seal;
1958
	rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1959 1960 1961
	free_xid(xid);

	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 1965 1966
		goto out;
	}

Enzo Matsumiya's avatar
Enzo Matsumiya committed
1967
	cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1968

1969 1970 1971
	spin_lock(&tcon->tc_lock);
	tcon->status = TID_GOOD;
	spin_unlock(&tcon->tc_lock);
1972 1973 1974 1975 1976
	ses->tcon_ipc = tcon;
out:
	return rc;
}

1977
static struct cifs_ses *
1978
cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
Linus Torvalds's avatar
Linus Torvalds committed
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 1985 1986
		spin_lock(&ses->ses_lock);
		if (ses->ses_status == SES_EXITING) {
			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 1994
			ret = ses;
			break;
1995
		}
1996
		spin_unlock(&ses->chan_lock);
1997
		spin_unlock(&ses->ses_lock);
1998
	}
1999 2000
	if (ret)
		cifs_smb_ses_inc_refcount(ret);
2001
	spin_unlock(&cifs_tcp_ses_lock);
2002
	return ret;
2003
}
2004

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 2010
	unsigned int xid;
	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 2017 2018 2019
	cifs_dbg(FYI, "%s: id=0x%llx ses_count=%d ses_status=%u ipc=%s\n",
		 __func__, ses->Suid, ses->ses_count, ses->ses_status,
		 ses->tcon_ipc ? ses->tcon_ipc->tree_name : "none");
	if (ses->ses_status == SES_EXITING || --ses->ses_count > 0) {
2020
		spin_unlock(&ses->ses_lock);
2021
		spin_unlock(&cifs_tcp_ses_lock);
2022 2023
		return;
	}
2024 2025
	/* ses_count can never go negative */
	WARN_ON(ses->ses_count < 0);
2026

2027 2028 2029
	spin_lock(&ses->chan_lock);
	cifs_chan_clear_need_reconnect(ses, server);
	spin_unlock(&ses->chan_lock);
2030

2031 2032 2033 2034
	do_logoff = ses->ses_status == SES_GOOD && server->ops->logoff;
	ses->ses_status = SES_EXITING;
	tcon = ses->tcon_ipc;
	ses->tcon_ipc = NULL;
2035
	spin_unlock(&ses->ses_lock);
2036
	spin_unlock(&cifs_tcp_ses_lock);
2037

2038 2039 2040 2041 2042 2043 2044 2045
	/*
	 * On session close, the IPC is closed and the server must release all
	 * tcons of the session.  No need to send a tree disconnect here.
	 *
	 * Besides, it will make the server to not close durable and resilient
	 * files on session close, as specified in MS-SMB2 3.3.5.6 Receiving an
	 * SMB2 LOGOFF Request.
	 */
2046
	tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc);
2047
	if (do_logoff) {
2048
		xid = get_xid();
2049 2050
		rc = server->ops->logoff(xid, ses);
		if (rc)
2051
			cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2052
				__func__, rc);
2053
		_free_xid(xid);
2054
	}
2055 2056 2057 2058 2059

	spin_lock(&cifs_tcp_ses_lock);
	list_del_init(&ses->smb_ses_list);
	spin_unlock(&cifs_tcp_ses_lock);

2060
	/* close any extra channels */
2061 2062 2063 2064
	for (i = 1; i < ses->chan_count; i++) {
		if (ses->chans[i].iface) {
			kref_put(&ses->chans[i].iface->refcount, release_iface);
			ses->chans[i].iface = NULL;
2065
		}
2066 2067
		cifs_put_tcp_session(ses->chans[i].server, 0);
		ses->chans[i].server = NULL;
2068 2069
	}

2070 2071 2072 2073 2074 2075
	/* we now account for primary channel in iface->refcount */
	if (ses->chans[0].iface) {
		kref_put(&ses->chans[0].iface->refcount, release_iface);
		ses->chans[0].server = NULL;
	}

2076
	sesInfoFree(ses);
2077
	cifs_put_tcp_session(server, 0);
2078
}
2079

2080 2081
#ifdef CONFIG_KEYS

2082 2083
/* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
#define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2084 2085 2086

/* Populate username and pw fields from keyring if possible */
static int
2087
cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2088 2089
{
	int rc = 0;
2090
	int is_domain = 0;
2091 2092
	const char *delim, *payload;
	char *desc;
2093 2094 2095 2096 2097
	ssize_t len;
	struct key *key;
	struct TCP_Server_Info *server = ses->server;
	struct sockaddr_in *sa;
	struct sockaddr_in6 *sa6;
2098
	const struct user_key_payload *upayload;
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114

	desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
	if (!desc)
		return -ENOMEM;

	/* try to find an address key first */
	switch (server->dstaddr.ss_family) {
	case AF_INET:
		sa = (struct sockaddr_in *)&server->dstaddr;
		sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
		break;
	case AF_INET6:
		sa6 = (struct sockaddr_in6 *)&server->dstaddr;
		sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
		break;
	default:
2115 2116
		cifs_dbg(FYI, "Bad ss_family (%hu)\n",
			 server->dstaddr.ss_family);
2117 2118 2119 2120
		rc = -EINVAL;
		goto out_err;
	}

2121
	cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2122
	key = request_key(&key_type_logon, desc, "");
2123 2124
	if (IS_ERR(key)) {
		if (!ses->domainName) {
2125
			cifs_dbg(FYI, "domainName is NULL\n");
2126 2127 2128 2129 2130 2131
			rc = PTR_ERR(key);
			goto out_err;
		}

		/* didn't work, try to find a domain key */
		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 2135 2136 2137
		if (IS_ERR(key)) {
			rc = PTR_ERR(key);
			goto out_err;
		}
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 2146 2147 2148
		goto out_key_put;
	}

	/* 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 2154
		cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
			 upayload->datalen);
2155 2156 2157 2158 2159
		rc = -EINVAL;
		goto out_key_put;
	}

	len = delim - payload;
2160
	if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2161 2162
		cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
			 len);
2163 2164 2165 2166
		rc = -EINVAL;
		goto out_key_put;
	}

2167 2168
	ctx->username = kstrndup(payload, len, GFP_KERNEL);
	if (!ctx->username) {
2169 2170
		cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
			 len);
2171 2172 2173
		rc = -ENOMEM;
		goto out_key_put;
	}
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 2181
		kfree(ctx->username);
		ctx->username = NULL;
2182 2183 2184 2185
		goto out_key_put;
	}

	++delim;
2186
	/* BB consider adding support for password2 (Key Rotation) for multiuser in future */
2187 2188
	ctx->password = kstrndup(delim, len, GFP_KERNEL);
	if (!ctx->password) {
2189 2190
		cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
			 len);
2191
		rc = -ENOMEM;
2192 2193
		kfree(ctx->username);
		ctx->username = NULL;
2194 2195 2196
		goto out_key_put;
	}

2197 2198 2199 2200 2201
	/*
	 * If we have a domain key then we must set the domainName in the
	 * for the request.
	 */
	if (is_domain && ses->domainName) {
Al Viro's avatar
Al Viro committed
2202
		ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2203
		if (!ctx->domainname) {
2204 2205
			cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
				 len);
2206
			rc = -ENOMEM;
2207 2208 2209
			kfree(ctx->username);
			ctx->username = NULL;
			kfree_sensitive(ctx->password);
2210
			/* no need to free ctx->password2 since not allocated in this path */
2211
			ctx->password = NULL;
2212 2213 2214 2215
			goto out_key_put;
		}
	}

2216
	strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2217

2218 2219 2220 2221 2222
out_key_put:
	up_read(&key->sem);
	key_put(key);
out_err:
	kfree(desc);
2223
	cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2224 2225 2226 2227
	return rc;
}
#else /* ! CONFIG_KEYS */
static inline int
2228
cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2229 2230 2231 2232 2233 2234
		   struct cifs_ses *ses __attribute__((unused)))
{
	return -ENOSYS;
}
#endif /* CONFIG_KEYS */

2235
/**
2236
 * cifs_get_smb_ses - get a session matching @ctx data from @server
2237 2238
 * @server: server to setup the session to
 * @ctx: superblock configuration context to use to setup the session
2239 2240 2241 2242 2243
 *
 * This function assumes it is being called from cifs_mount() where we
 * already got a server reference (server refcount +1). See
 * cifs_get_tcon() for refcount explanations.
 */
2244
struct cifs_ses *
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 2251
	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
	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 2261 2262
		spin_lock(&ses->chan_lock);
		if (cifs_chan_needs_reconnect(ses, server)) {
			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 2268 2269 2270 2271 2272 2273 2274
			if (rc) {
				mutex_unlock(&ses->session_mutex);
				/* problem -- put our ses reference */
				cifs_put_smb_ses(ses);
				free_xid(xid);
				return ERR_PTR(rc);
			}

2275
			rc = cifs_setup_session(xid, ses, server,
2276
						ctx->local_nls);
2277 2278 2279 2280
			if (rc) {
				mutex_unlock(&ses->session_mutex);
				/* problem -- put our reference */
				cifs_put_smb_ses(ses);
2281
				free_xid(xid);
2282 2283
				return ERR_PTR(rc);
			}
2284 2285
			mutex_unlock(&ses->session_mutex);

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 2294 2295
		return ses;
	}

2296 2297
	rc = -ENOMEM;

2298
	cifs_dbg(FYI, "Existing smb sess not found\n");
2299 2300 2301 2302 2303 2304
	ses = sesInfoAlloc();
	if (ses == NULL)
		goto get_ses_fail;

	/* new SMB session uses our server ref */
	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 2311
	if (ctx->username) {
		ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2312 2313 2314
		if (!ses->user_name)
			goto get_ses_fail;
	}
2315

2316 2317 2318
	/* ctx->password freed at unmount */
	if (ctx->password) {
		ses->password = kstrdup(ctx->password, GFP_KERNEL);
2319 2320 2321
		if (!ses->password)
			goto get_ses_fail;
	}
2322 2323 2324 2325 2326 2327
	/* ctx->password freed at unmount */
	if (ctx->password2) {
		ses->password2 = kstrdup(ctx->password2, GFP_KERNEL);
		if (!ses->password2)
			goto get_ses_fail;
	}
2328 2329
	if (ctx->domainname) {
		ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2330 2331
		if (!ses->domainName)
			goto get_ses_fail;
2332
	}
2333 2334 2335

	strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));

2336 2337 2338 2339
	if (ctx->domainauto)
		ses->domainAuto = ctx->domainauto;
	ses->cred_uid = ctx->cred_uid;
	ses->linux_uid = ctx->linux_uid;
2340

2341 2342
	ses->sectype = ctx->sectype;
	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 2348
	ses->chans[0].server = server;
	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 2362
	memcpy(ses->chans[0].signkey, ses->smb3signingkey,
	       sizeof(ses->smb3signingkey));
2363
	spin_unlock(&ses->chan_lock);
2364

2365
	if (rc)
2366 2367
		goto get_ses_fail;

2368 2369 2370 2371 2372
	/*
	 * success, put it on the list and add it as first channel
	 * note: the session becomes active soon after this. So you'll
	 * need to lock before changing something in the session.
	 */
2373
	spin_lock(&cifs_tcp_ses_lock);
2374 2375
	if (ctx->dfs_root_ses)
		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 2383
	free_xid(xid);

2384 2385 2386 2387
	return ses;

get_ses_fail:
	sesInfoFree(ses);
2388
	free_xid(xid);
2389 2390 2391
	return ERR_PTR(rc);
}

2392
/* this function must be called with tc_lock held */
2393
static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2394
{
2395 2396
	struct TCP_Server_Info *server = tcon->ses->server;

2397
	if (tcon->status == TID_EXITING)
2398
		return 0;
2399 2400 2401 2402 2403 2404 2405 2406

	if (tcon->origin_fullpath) {
		if (!ctx->source ||
		    !dfs_src_pathname_equal(ctx->source,
					    tcon->origin_fullpath))
			return 0;
	} else if (!server->leaf_fullpath &&
		   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 2420 2421
	return 1;
}

2422
static struct cifs_tcon *
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 2436
		trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
				    netfs_trace_tcon_ref_get_find);
2437
		spin_unlock(&tcon->tc_lock);
2438
		spin_unlock(&cifs_tcp_ses_lock);
2439
		return tcon;
Linus Torvalds's avatar
Linus Torvalds committed
2440
	}
2441
	spin_unlock(&cifs_tcp_ses_lock);
Linus Torvalds's avatar
Linus Torvalds committed
2442 2443 2444
	return NULL;
}

2445
void
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 2453 2454 2455 2456 2457 2458
	/*
	 * IPC tcon share the lifetime of their session and are
	 * destroyed in the session put function
	 */
	if (tcon == NULL || tcon->ipc)
		return;

	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 2467 2468
		return;
	}

2469 2470 2471
	/* tc_count can never go negative */
	WARN_ON(tcon->tc_count < 0);

2472
	list_del_init(&tcon->tcon_list);
2473
	tcon->status = TID_EXITING;
2474
	spin_unlock(&tcon->tc_lock);
2475 2476
	spin_unlock(&cifs_tcp_ses_lock);

2477 2478
	/* cancel polling of interfaces */
	cancel_delayed_work_sync(&tcon->query_interfaces);
2479 2480 2481
#ifdef CONFIG_CIFS_DFS_UPCALL
	cancel_delayed_work_sync(&tcon->dfs_cache_work);
#endif
2482

2483 2484 2485 2486 2487 2488 2489 2490 2491
	if (tcon->use_witness) {
		int rc;

		rc = cifs_swn_unregister(tcon);
		if (rc < 0) {
			cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
					__func__, rc);
		}
	}
2492

2493
	xid = get_xid();
2494 2495
	if (ses->server->ops->tree_disconnect)
		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 2501 2502
	cifs_put_smb_ses(ses);
}

2503
/**
2504
 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2505 2506
 * @ses: smb session to issue the request on
 * @ctx: the superblock configuration context to use for building the
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
 *
 * - tcon refcount is the number of mount points using the tcon.
 * - ses refcount is the number of tcon using the session.
 *
 * 1. This function assumes it is being called from cifs_mount() where
 *    we already got a session reference (ses refcount +1).
 *
 * 2. Since we're in the context of adding a mount point, the end
 *    result should be either:
 *
 * a) a new tcon already allocated with refcount=1 (1 mount point) and
 *    its session refcount incremented (1 new tcon). This +1 was
 *    already done in (1).
 *
 * b) an existing tcon with refcount+1 (add a mount point to it) and
 *    identical ses refcount (no new tcon). Because of (1) we need to
 *    decrement the ses refcount.
 */
2525
static struct cifs_tcon *
2526
cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2527
{
2528
	struct cifs_tcon *tcon;
2529 2530
	bool nohandlecache;
	int rc, xid;
2531

2532
	tcon = cifs_find_tcon(ses, ctx);
2533
	if (tcon) {
2534 2535 2536 2537
		/*
		 * tcon has refcount already incremented but we need to
		 * decrement extra ses reference gotten by caller (case b)
		 */
2538
		cifs_dbg(FYI, "Found match on UNC path\n");
2539 2540 2541 2542
		cifs_put_smb_ses(ses);
		return tcon;
	}

2543 2544 2545 2546 2547
	if (!ses->server->ops->tree_connect) {
		rc = -ENOSYS;
		goto out_fail;
	}

2548 2549 2550
	if (ses->server->dialect >= SMB20_PROT_ID &&
	    (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
		nohandlecache = ctx->nohandlecache;
2551
	else
2552
		nohandlecache = true;
2553
	tcon = tcon_info_alloc(!nohandlecache, netfs_trace_tcon_ref_new);
2554 2555 2556 2557
	if (tcon == NULL) {
		rc = -ENOMEM;
		goto out_fail;
	}
2558
	tcon->nohandlecache = nohandlecache;
2559

2560
	if (ctx->snapshot_time) {
2561 2562 2563 2564 2565 2566
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
			     "Use SMB2 or later for snapshot mount option\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		} else
2567
			tcon->snapshot_time = ctx->snapshot_time;
2568 2569
	}

2570
	if (ctx->handle_timeout) {
2571 2572 2573 2574 2575 2576
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
			     "Use SMB2.1 or later for handle timeout option\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		} else
2577
			tcon->handle_timeout = ctx->handle_timeout;
2578 2579
	}

2580
	tcon->ses = ses;
2581 2582
	if (ctx->password) {
		tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2583 2584 2585 2586 2587 2588
		if (!tcon->password) {
			rc = -ENOMEM;
			goto out_fail;
		}
	}

2589
	if (ctx->seal) {
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
				 "SMB3 or later required for encryption\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		} else if (tcon->ses->server->capabilities &
					SMB2_GLOBAL_CAP_ENCRYPTION)
			tcon->seal = true;
		else {
			cifs_dbg(VFS, "Encryption is not supported on share\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		}
	}

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 2610 2611 2612 2613
		} else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
		    (strcmp(ses->server->vals->version_string,
		     SMB3ANY_VERSION_STRING) == 0) ||
		    (strcmp(ses->server->vals->version_string,
		     SMBDEFAULT_VERSION_STRING) == 0)) {
2614
			cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2615 2616
			rc = -EOPNOTSUPP;
			goto out_fail;
2617
		} else {
2618 2619
			cifs_dbg(VFS,
				"Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2620 2621
			rc = -EOPNOTSUPP;
			goto out_fail;
2622
		}
2623 2624
	}

2625
	xid = get_xid();
2626 2627
	rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
					    ctx->local_nls);
2628
	free_xid(xid);
2629
	cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2630 2631 2632
	if (rc)
		goto out_fail;

2633 2634
	tcon->use_persistent = false;
	/* check if SMB2 or later, CIFS does not support persistent handles */
2635
	if (ctx->persistent) {
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
			     "SMB3 or later required for persistent handles\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		} else if (ses->server->capabilities &
			   SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
			tcon->use_persistent = true;
		else /* persistent handles requested but not supported */ {
			cifs_dbg(VFS,
				"Persistent handles not supported on share\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		}
	} else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
	     && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2652
	     && (ctx->nopersistent == false)) {
2653 2654
		cifs_dbg(FYI, "enabling persistent handles\n");
		tcon->use_persistent = true;
2655
	} else if (ctx->resilient) {
2656 2657 2658 2659 2660 2661 2662
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
			     "SMB2.1 or later required for resilient handles\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		}
		tcon->use_resilient = true;
2663
	}
2664

2665
	tcon->use_witness = false;
2666
	if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2667 2668
		if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
			if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2669 2670 2671 2672
				/*
				 * Set witness in use flag in first place
				 * to retry registration in the echo task
				 */
2673
				tcon->use_witness = true;
2674 2675 2676 2677 2678 2679
				/* And try to register immediately */
				rc = cifs_swn_register(tcon);
				if (rc < 0) {
					cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
					goto out_fail;
				}
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
			} else {
				/* TODO: try to extend for non-cluster uses (eg multichannel) */
				cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
				rc = -EOPNOTSUPP;
				goto out_fail;
			}
		} else {
			cifs_dbg(VFS, "SMB3 or later required for witness option\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		}
	}
2692

2693 2694
	/* If the user really knows what they are doing they can override */
	if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2695
		if (ctx->cache_ro)
2696
			cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2697
		else if (ctx->cache_rw)
2698 2699 2700
			cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
	}

2701
	if (ctx->no_lease) {
2702 2703 2704 2705 2706 2707
		if (ses->server->vals->protocol_id == 0) {
			cifs_dbg(VFS,
				"SMB2 or later required for nolease option\n");
			rc = -EOPNOTSUPP;
			goto out_fail;
		} else
2708
			tcon->no_lease = ctx->no_lease;
2709 2710
	}

2711 2712 2713 2714 2715
	/*
	 * We can have only one retry value for a connection to a share so for
	 * resources mounted more than once to the same server share the last
	 * value passed in for the retry flag is used.
	 */
2716 2717
	tcon->retry = ctx->retry;
	tcon->nocase = ctx->nocase;
2718
	tcon->broken_sparse_sup = ctx->no_sparse;
2719
	tcon->max_cached_dirs = ctx->max_cached_dirs;
2720 2721
	tcon->nodelete = ctx->nodelete;
	tcon->local_lease = ctx->local_lease;
2722
	INIT_LIST_HEAD(&tcon->pending_opens);
2723
	tcon->status = TID_GOOD;
2724

2725 2726
	INIT_DELAYED_WORK(&tcon->query_interfaces,
			  smb2_query_server_interfaces);
2727 2728 2729 2730 2731 2732
	if (ses->server->dialect >= SMB30_PROT_ID &&
	    (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
		/* schedule query interfaces poll */
		queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
				   (SMB_INTERFACE_POLL_INTERVAL * HZ));
	}
2733 2734 2735
#ifdef CONFIG_CIFS_DFS_UPCALL
	INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
#endif
2736
	spin_lock(&cifs_tcp_ses_lock);
2737
	list_add(&tcon->tcon_list, &ses->tcon_list);
2738
	spin_unlock(&cifs_tcp_ses_lock);
2739 2740 2741 2742

	return tcon;

out_fail:
2743
	tconInfoFree(tcon, netfs_trace_tcon_ref_free_fail);
2744 2745 2746
	return ERR_PTR(rc);
}

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
void
cifs_put_tlink(struct tcon_link *tlink)
{
	if (!tlink || IS_ERR(tlink))
		return;

	if (!atomic_dec_and_test(&tlink->tl_count) ||
	    test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
		tlink->tl_time = jiffies;
		return;
	}

	if (!IS_ERR(tlink_tcon(tlink)))
2760
		cifs_put_tcon(tlink_tcon(tlink), netfs_trace_tcon_ref_put_tlink);
2761 2762
	kfree(tlink);
}
2763

2764 2765 2766 2767 2768
static int
compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
{
	struct cifs_sb_info *old = CIFS_SB(sb);
	struct cifs_sb_info *new = mnt_data->cifs_sb;
2769 2770
	unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
	unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2771 2772 2773 2774

	if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
		return 0;

2775 2776 2777 2778
	if (old->mnt_cifs_serverino_autodisabled)
		newflags &= ~CIFS_MOUNT_SERVER_INUM;

	if (oldflags != newflags)
2779 2780 2781
		return 0;

	/*
2782 2783
	 * We want to share sb only if we don't specify an r/wsize or
	 * specified r/wsize is greater than or equal to existing one.
2784
	 */
2785
	if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2786 2787
		return 0;

2788
	if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2789 2790
		return 0;

2791 2792
	if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
	    !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2793 2794
		return 0;

2795 2796
	if (old->ctx->file_mode != new->ctx->file_mode ||
	    old->ctx->dir_mode != new->ctx->dir_mode)
2797 2798 2799 2800 2801
		return 0;

	if (strcmp(old->local_nls->charset, new->local_nls->charset))
		return 0;

2802
	if (old->ctx->acregmax != new->ctx->acregmax)
2803
		return 0;
2804 2805
	if (old->ctx->acdirmax != new->ctx->acdirmax)
		return 0;
2806 2807
	if (old->ctx->closetimeo != new->ctx->closetimeo)
		return 0;
2808 2809
	if (old->ctx->reparse_type != new->ctx->reparse_type)
		return 0;
2810 2811 2812 2813

	return 1;
}

2814
static int match_prepath(struct super_block *sb,
2815
			 struct cifs_tcon *tcon,
2816
			 struct cifs_mnt_data *mnt_data)
2817
{
2818
	struct smb3_fs_context *ctx = mnt_data->ctx;
2819 2820
	struct cifs_sb_info *old = CIFS_SB(sb);
	struct cifs_sb_info *new = mnt_data->cifs_sb;
2821 2822 2823 2824
	bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
		old->prepath;
	bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
		new->prepath;
2825

2826 2827
	if (tcon->origin_fullpath &&
	    dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2828 2829
		return 1;

Sachin Prabhu's avatar
Sachin Prabhu committed
2830
	if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2831
		return 1;
Sachin Prabhu's avatar
Sachin Prabhu committed
2832 2833 2834
	else if (!old_set && !new_set)
		return 1;

2835 2836 2837
	return 0;
}

2838 2839 2840
int
cifs_match_super(struct super_block *sb, void *data)
{
2841
	struct cifs_mnt_data *mnt_data = data;
2842
	struct smb3_fs_context *ctx;
2843 2844
	struct cifs_sb_info *cifs_sb;
	struct TCP_Server_Info *tcp_srv;
2845 2846
	struct cifs_ses *ses;
	struct cifs_tcon *tcon;
2847 2848 2849 2850 2851
	struct tcon_link *tlink;
	int rc = 0;

	spin_lock(&cifs_tcp_ses_lock);
	cifs_sb = CIFS_SB(sb);
2852 2853 2854 2855 2856 2857 2858

	/* We do not want to use a superblock that has been shutdown */
	if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
		spin_unlock(&cifs_tcp_ses_lock);
		return 0;
	}

2859
	tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2860 2861 2862
	if (IS_ERR_OR_NULL(tlink)) {
		pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
			     __func__, tlink);
2863
		spin_unlock(&cifs_tcp_ses_lock);
2864
		return 0;
2865 2866 2867 2868 2869
	}
	tcon = tlink_tcon(tlink);
	ses = tcon->ses;
	tcp_srv = ses->server;

2870
	ctx = mnt_data->ctx;
2871

2872 2873
	spin_lock(&tcp_srv->srv_lock);
	spin_lock(&ses->ses_lock);
2874
	spin_lock(&ses->chan_lock);
2875
	spin_lock(&tcon->tc_lock);
2876
	if (!match_server(tcp_srv, ctx, true) ||
2877
	    !match_session(ses, ctx) ||
2878
	    !match_tcon(tcon, ctx) ||
2879
	    !match_prepath(sb, tcon, mnt_data)) {
2880 2881 2882 2883 2884 2885
		rc = 0;
		goto out;
	}

	rc = compare_mount_options(sb, mnt_data);
out:
2886
	spin_unlock(&tcon->tc_lock);
2887
	spin_unlock(&ses->chan_lock);
2888 2889 2890
	spin_unlock(&ses->ses_lock);
	spin_unlock(&tcp_srv->srv_lock);

2891
	spin_unlock(&cifs_tcp_ses_lock);
2892
	cifs_put_tlink(tlink);
2893 2894 2895
	return rc;
}

2896 2897 2898 2899 2900 2901 2902 2903
#ifdef CONFIG_DEBUG_LOCK_ALLOC
static struct lock_class_key cifs_key[2];
static struct lock_class_key cifs_slock_key[2];

static inline void
cifs_reclassify_socket4(struct socket *sock)
{
	struct sock *sk = sock->sk;
2904

2905
	BUG_ON(!sock_allow_reclassification(sk));
2906 2907 2908 2909 2910 2911 2912 2913
	sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
		&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
}

static inline void
cifs_reclassify_socket6(struct socket *sock)
{
	struct sock *sk = sock->sk;
2914

2915
	BUG_ON(!sock_allow_reclassification(sk));
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
	sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
		&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
}
#else
static inline void
cifs_reclassify_socket4(struct socket *sock)
{
}

static inline void
cifs_reclassify_socket6(struct socket *sock)
{
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
2931
/* See RFC1001 section 14 on representation of Netbios names */
2932
static void rfc1002mangle(char *target, char *source, unsigned int length)
Linus Torvalds's avatar
Linus Torvalds committed
2933
{
2934
	unsigned int i, j;
Linus Torvalds's avatar
Linus Torvalds committed
2935

2936
	for (i = 0, j = 0; i < (length); i++) {
Linus Torvalds's avatar
Linus Torvalds committed
2937 2938 2939
		/* mask a nibble at a time and encode */
		target[j] = 'A' + (0x0F & (source[i] >> 4));
		target[j+1] = 'A' + (0x0F & source[i]);
2940
		j += 2;
Linus Torvalds's avatar
Linus Torvalds committed
2941 2942 2943 2944
	}

}

2945 2946 2947 2948
static int
bind_socket(struct TCP_Server_Info *server)
{
	int rc = 0;
2949

2950 2951 2952
	if (server->srcaddr.ss_family != AF_UNSPEC) {
		/* Bind to the specified local IP address */
		struct socket *socket = server->ssocket;
2953

2954 2955 2956
		rc = kernel_bind(socket,
				 (struct sockaddr *) &server->srcaddr,
				 sizeof(server->srcaddr));
2957 2958 2959
		if (rc < 0) {
			struct sockaddr_in *saddr4;
			struct sockaddr_in6 *saddr6;
2960

2961 2962 2963
			saddr4 = (struct sockaddr_in *)&server->srcaddr;
			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
			if (saddr6->sin6_family == AF_INET6)
2964
				cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2965
					 &saddr6->sin6_addr, rc);
2966
			else
2967
				cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2968
					 &saddr4->sin_addr.s_addr, rc);
2969 2970 2971 2972
		}
	}
	return rc;
}
Linus Torvalds's avatar
Linus Torvalds committed
2973 2974

static int
2975
ip_rfc1001_connect(struct TCP_Server_Info *server)
Linus Torvalds's avatar
Linus Torvalds committed
2976 2977
{
	int rc = 0;
2978 2979 2980 2981 2982
	/*
	 * some servers require RFC1001 sessinit before sending
	 * negprot - BB check reconnection in case where second
	 * sessinit is sent but no second negprot
	 */
2983 2984 2985
	struct rfc1002_session_packet req = {};
	struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
	unsigned int len;
2986

2987
	req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2988

2989 2990 2991 2992 2993 2994 2995 2996
	if (server->server_RFC1001_name[0] != 0)
		rfc1002mangle(req.trailer.session_req.called_name,
			      server->server_RFC1001_name,
			      RFC1001_NAME_LEN_WITH_NULL);
	else
		rfc1002mangle(req.trailer.session_req.called_name,
			      DEFAULT_CIFS_CALLED_NAME,
			      RFC1001_NAME_LEN_WITH_NULL);
2997

2998
	req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2999

3000 3001 3002 3003 3004 3005 3006 3007 3008
	/* calling name ends in null (byte 16) from old smb convention */
	if (server->workstation_RFC1001_name[0] != 0)
		rfc1002mangle(req.trailer.session_req.calling_name,
			      server->workstation_RFC1001_name,
			      RFC1001_NAME_LEN_WITH_NULL);
	else
		rfc1002mangle(req.trailer.session_req.calling_name,
			      "LINUX_CIFS_CLNT",
			      RFC1001_NAME_LEN_WITH_NULL);
3009 3010

	/*
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
	 * As per rfc1002, @len must be the number of bytes that follows the
	 * length field of a rfc1002 session request payload.
	 */
	len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);

	smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
	rc = smb_send(server, smb_buf, len);
	/*
	 * RFC1001 layer in at least one server requires very short break before
	 * negprot presumably because not expecting negprot to follow so fast.
	 * This is a simple solution that works without complicating the code
	 * and causes no significant slowing down on mount for everyone else
3023
	 */
3024
	usleep_range(1000, 2000);
3025 3026 3027 3028 3029 3030 3031 3032

	return rc;
}

static int
generic_ip_connect(struct TCP_Server_Info *server)
{
	struct sockaddr *saddr;
3033 3034 3035 3036
	struct socket *socket;
	int slen, sfamily;
	__be16 sport;
	int rc = 0;
3037 3038 3039 3040

	saddr = (struct sockaddr *) &server->dstaddr;

	if (server->dstaddr.ss_family == AF_INET6) {
3041 3042 3043
		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;

		sport = ipv6->sin6_port;
3044 3045
		slen = sizeof(struct sockaddr_in6);
		sfamily = AF_INET6;
3046 3047
		cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
				ntohs(sport));
3048
	} else {
3049 3050 3051
		struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;

		sport = ipv4->sin_port;
3052 3053
		slen = sizeof(struct sockaddr_in);
		sfamily = AF_INET;
3054 3055
		cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
				ntohs(sport));
3056
	}
Linus Torvalds's avatar
Linus Torvalds committed
3057

3058 3059 3060
	if (server->ssocket) {
		socket = server->ssocket;
	} else {
3061
		rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3062
				   IPPROTO_TCP, &server->ssocket, 1);
Linus Torvalds's avatar
Linus Torvalds committed
3063
		if (rc < 0) {
3064
			cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
Linus Torvalds's avatar
Linus Torvalds committed
3065 3066
			return rc;
		}
3067 3068

		/* BB other socket options to set KEEPALIVE, NODELAY? */
3069
		cifs_dbg(FYI, "Socket created\n");
3070
		socket = server->ssocket;
3071
		socket->sk->sk_allocation = GFP_NOFS;
3072
		socket->sk->sk_use_task_frag = false;
3073 3074 3075 3076
		if (sfamily == AF_INET6)
			cifs_reclassify_socket6(socket);
		else
			cifs_reclassify_socket4(socket);
Linus Torvalds's avatar
Linus Torvalds committed
3077 3078
	}

3079 3080 3081 3082
	rc = bind_socket(server);
	if (rc < 0)
		return rc;

3083 3084
	/*
	 * Eventually check for other socket options to change from
3085 3086
	 * the default. sock_setsockopt not used because it expects
	 * user space buffer
3087 3088
	 */
	socket->sk->sk_rcvtimeo = 7 * HZ;
3089
	socket->sk->sk_sndtimeo = 5 * HZ;
3090

3091
	/* make the bufsizes depend on wsize/rsize and max requests */
3092 3093 3094 3095 3096
	if (server->noautotune) {
		if (socket->sk->sk_sndbuf < (200 * 1024))
			socket->sk->sk_sndbuf = 200 * 1024;
		if (socket->sk->sk_rcvbuf < (140 * 1024))
			socket->sk->sk_rcvbuf = 140 * 1024;
3097
	}
Linus Torvalds's avatar
Linus Torvalds committed
3098

3099 3100
	if (server->tcp_nodelay)
		tcp_sock_set_nodelay(socket->sk);
3101

3102
	cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3103
		 socket->sk->sk_sndbuf,
3104
		 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3105

3106 3107
	rc = kernel_connect(socket, saddr, slen,
			    server->noblockcnt ? O_NONBLOCK : 0);
3108 3109 3110 3111 3112 3113
	/*
	 * When mounting SMB root file systems, we do not want to block in
	 * connect. Otherwise bail out and then let cifs_reconnect() perform
	 * reconnect failover - if possible.
	 */
	if (server->noblockcnt && rc == -EINPROGRESS)
3114
		rc = 0;
3115
	if (rc < 0) {
3116
		cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3117
		trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3118 3119 3120 3121
		sock_release(socket);
		server->ssocket = NULL;
		return rc;
	}
3122
	trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3123 3124
	if (sport == htons(RFC1001_PORT))
		rc = ip_rfc1001_connect(server);
3125

Linus Torvalds's avatar
Linus Torvalds committed
3126 3127 3128 3129
	return rc;
}

static int
3130
ip_connect(struct TCP_Server_Info *server)
Linus Torvalds's avatar
Linus Torvalds committed
3131
{
3132
	__be16 *sport;
3133 3134
	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
Linus Torvalds's avatar
Linus Torvalds committed
3135

3136 3137 3138 3139
	if (server->dstaddr.ss_family == AF_INET6)
		sport = &addr6->sin6_port;
	else
		sport = &addr->sin_port;
Linus Torvalds's avatar
Linus Torvalds committed
3140

3141 3142
	if (*sport == 0) {
		int rc;
Linus Torvalds's avatar
Linus Torvalds committed
3143

3144 3145
		/* try with 445 port at first */
		*sport = htons(CIFS_PORT);
3146

3147
		rc = generic_ip_connect(server);
Linus Torvalds's avatar
Linus Torvalds committed
3148
		if (rc >= 0)
3149
			return rc;
3150

3151 3152
		/* if it failed, try with 139 port */
		*sport = htons(RFC1001_PORT);
3153 3154
	}

3155
	return generic_ip_connect(server);
Linus Torvalds's avatar
Linus Torvalds committed
3156 3157
}

3158
#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3159
void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3160
			  struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3161
{
3162 3163
	/*
	 * If we are reconnecting then should we check to see if
3164 3165 3166 3167 3168 3169 3170
	 * any requested capabilities changed locally e.g. via
	 * remount but we can not do much about it here
	 * if they have (even if we could detect it by the following)
	 * Perhaps we could add a backpointer to array of sb from tcon
	 * or if we change to make all sb to same share the same
	 * sb as NFS - then we only have one backpointer to sb.
	 * What if we wanted to mount the server share twice once with
3171 3172
	 * and once without posixacls or posix paths?
	 */
3173
	__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3174

3175
	if (ctx && ctx->no_linux_ext) {
3176 3177
		tcon->fsUnixInfo.Capability = 0;
		tcon->unix_ext = 0; /* Unix Extensions disabled */
3178
		cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3179
		return;
3180
	} else if (ctx)
3181 3182
		tcon->unix_ext = 1; /* Unix Extensions supported */

3183
	if (!tcon->unix_ext) {
3184
		cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3185 3186
		return;
	}
3187

Steve French's avatar
Steve French committed
3188
	if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3189
		__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3190

3191
		cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3192 3193 3194 3195
		/*
		 * check for reconnect case in which we do not
		 * want to change the mount behavior if we can avoid it
		 */
3196
		if (ctx == NULL) {
3197 3198 3199 3200
			/*
			 * turn off POSIX ACL and PATHNAMES if not set
			 * originally at mount time
			 */
3201 3202
			if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
				cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3203 3204
			if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
				if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3205
					cifs_dbg(VFS, "POSIXPATH support change\n");
3206
				cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3207
			} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3208 3209
				cifs_dbg(VFS, "possible reconnect error\n");
				cifs_dbg(VFS, "server disabled POSIX path support\n");
3210
			}
3211
		}
3212

3213
		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3214
			cifs_dbg(VFS, "per-share encryption not supported yet\n");
3215

3216
		cap &= CIFS_UNIX_CAP_MASK;
3217
		if (ctx && ctx->no_psx_acl)
3218
			cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3219
		else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3220
			cifs_dbg(FYI, "negotiated posix acl support\n");
3221 3222 3223
			if (cifs_sb)
				cifs_sb->mnt_cifs_flags |=
					CIFS_MOUNT_POSIXACL;
3224 3225
		}

3226
		if (ctx && ctx->posix_paths == 0)
3227
			cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3228
		else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3229
			cifs_dbg(FYI, "negotiate posix pathnames\n");
3230 3231
			if (cifs_sb)
				cifs_sb->mnt_cifs_flags |=
3232 3233
					CIFS_MOUNT_POSIX_PATHS;
		}
3234

3235
		cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3236
#ifdef CONFIG_CIFS_DEBUG2
3237
		if (cap & CIFS_UNIX_FCNTL_CAP)
3238
			cifs_dbg(FYI, "FCNTL cap\n");
3239
		if (cap & CIFS_UNIX_EXTATTR_CAP)
3240
			cifs_dbg(FYI, "EXTATTR cap\n");
3241
		if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3242
			cifs_dbg(FYI, "POSIX path cap\n");
3243
		if (cap & CIFS_UNIX_XATTR_CAP)
3244
			cifs_dbg(FYI, "XATTR cap\n");
3245
		if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3246
			cifs_dbg(FYI, "POSIX ACL cap\n");
3247
		if (cap & CIFS_UNIX_LARGE_READ_CAP)
3248
			cifs_dbg(FYI, "very large read cap\n");
3249
		if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3250
			cifs_dbg(FYI, "very large write cap\n");
3251
		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3252
			cifs_dbg(FYI, "transport encryption cap\n");
3253
		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3254
			cifs_dbg(FYI, "mandatory transport encryption cap\n");
3255 3256
#endif /* CIFS_DEBUG2 */
		if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3257
			if (ctx == NULL)
3258
				cifs_dbg(FYI, "resetting capabilities failed\n");
3259
			else
3260
				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");
3261

3262 3263 3264
		}
	}
}
3265
#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3266

3267
int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3268
{
3269 3270
	struct smb3_fs_context *ctx = cifs_sb->ctx;

3271 3272
	INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);

3273 3274 3275
	spin_lock_init(&cifs_sb->tlink_tree_lock);
	cifs_sb->tlink_tree = RB_ROOT;

3276
	cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3277
		 ctx->file_mode, ctx->dir_mode);
3278

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
	/* this is needed for ASCII cp to Unicode converts */
	if (ctx->iocharset == NULL) {
		/* load_nls_default cannot return null */
		cifs_sb->local_nls = load_nls_default();
	} else {
		cifs_sb->local_nls = load_nls(ctx->iocharset);
		if (cifs_sb->local_nls == NULL) {
			cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
				 ctx->iocharset);
			return -ELIBACC;
		}
	}
	ctx->local_nls = cifs_sb->local_nls;
3292

3293 3294 3295
	smb3_update_mnt_flags(cifs_sb);

	if (ctx->direct_io)
3296
		cifs_dbg(FYI, "mounting share using direct i/o\n");
3297
	if (ctx->cache_ro) {
3298 3299
		cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3300
	} else if (ctx->cache_rw) {
3301 3302 3303
		cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
		cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
					    CIFS_MOUNT_RW_CACHE);
3304
	}
3305

3306
	if ((ctx->cifs_acl) && (ctx->dynperm))
3307
		cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3308

3309 3310
	if (ctx->prepath) {
		cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3311 3312
		if (cifs_sb->prepath == NULL)
			return -ENOMEM;
3313
		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3314 3315 3316
	}

	return 0;
3317 3318
}

3319
/* Release all succeed connections */
3320
void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3321 3322 3323
{
	int rc = 0;

3324
	if (mnt_ctx->tcon)
3325
		cifs_put_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx);
3326 3327 3328 3329
	else if (mnt_ctx->ses)
		cifs_put_smb_ses(mnt_ctx->ses);
	else if (mnt_ctx->server)
		cifs_put_tcp_session(mnt_ctx->server, 0);
3330 3331 3332
	mnt_ctx->ses = NULL;
	mnt_ctx->tcon = NULL;
	mnt_ctx->server = NULL;
3333 3334
	mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
	free_xid(mnt_ctx->xid);
3335 3336
}

3337
int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3338
{
3339
	struct TCP_Server_Info *server = NULL;
3340
	struct smb3_fs_context *ctx;
3341 3342
	struct cifs_ses *ses = NULL;
	unsigned int xid;
3343
	int rc = 0;
3344

3345
	xid = get_xid();
3346

3347 3348 3349 3350 3351 3352
	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
		rc = -EINVAL;
		goto out;
	}
	ctx = mnt_ctx->fs_ctx;

3353
	/* get a reference to a tcp session */
3354
	server = cifs_get_tcp_session(ctx, NULL);
3355 3356
	if (IS_ERR(server)) {
		rc = PTR_ERR(server);
3357 3358
		server = NULL;
		goto out;
3359 3360 3361
	}

	/* get a reference to a SMB session */
3362
	ses = cifs_get_smb_ses(server, ctx);
3363 3364
	if (IS_ERR(ses)) {
		rc = PTR_ERR(ses);
3365 3366
		ses = NULL;
		goto out;
3367 3368
	}

3369
	if ((ctx->persistent == true) && (!(ses->server->capabilities &
3370
					    SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3371
		cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3372
		rc = -EOPNOTSUPP;
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
	}

out:
	mnt_ctx->xid = xid;
	mnt_ctx->server = server;
	mnt_ctx->ses = ses;
	mnt_ctx->tcon = NULL;

	return rc;
}

int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
{
	struct TCP_Server_Info *server;
	struct cifs_sb_info *cifs_sb;
	struct smb3_fs_context *ctx;
	struct cifs_tcon *tcon = NULL;
	int rc = 0;

	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
			 !mnt_ctx->cifs_sb)) {
		rc = -EINVAL;
3395
		goto out;
3396
	}
3397 3398 3399
	server = mnt_ctx->server;
	ctx = mnt_ctx->fs_ctx;
	cifs_sb = mnt_ctx->cifs_sb;
3400 3401

	/* search for existing tcon to this server share */
3402
	tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3403 3404
	if (IS_ERR(tcon)) {
		rc = PTR_ERR(tcon);
3405 3406
		tcon = NULL;
		goto out;
3407 3408 3409 3410 3411 3412
	}

	/* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
	if (tcon->posix_extensions)
		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;

3413
#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3414 3415 3416 3417 3418 3419
	/* tell server which Unix caps we support */
	if (cap_unix(tcon->ses)) {
		/*
		 * reset of caps checks mount to see if unix extensions disabled
		 * for just this mount.
		 */
3420
		reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3421
		spin_lock(&tcon->ses->server->srv_lock);
3422 3423
		if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
		    (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3424
		     CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3425
			spin_unlock(&tcon->ses->server->srv_lock);
3426 3427 3428
			rc = -EACCES;
			goto out;
		}
3429
		spin_unlock(&tcon->ses->server->srv_lock);
3430
	} else
3431
#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3432 3433 3434
		tcon->unix_ext = 0; /* server does not support them */

	/* do not care if a following call succeed - informational */
3435
	if (!tcon->pipe && server->ops->qfs_tcon) {
3436
		server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3437 3438
		if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
			if (tcon->fsDevInfo.DeviceCharacteristics &
3439
			    cpu_to_le32(FILE_READ_ONLY_DEVICE))
3440
				cifs_dbg(VFS, "mounted to read only share\n");
3441 3442
			else if ((cifs_sb->mnt_cifs_flags &
				  CIFS_MOUNT_RW_CACHE) == 0)
3443
				cifs_dbg(VFS, "read only mount of RW share\n");
3444
			/* no need to log a RW mount of a typical RW share */
3445 3446
		}
	}
3447

3448 3449
	/*
	 * Clamp the rsize/wsize mount arguments if they are too big for the server
3450 3451
	 * and set the rsize/wsize to the negotiated values if not passed in by
	 * the user on mount
3452
	 */
3453
	if ((cifs_sb->ctx->wsize == 0) ||
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
	    (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx))) {
		cifs_sb->ctx->wsize =
			round_down(server->ops->negotiate_wsize(tcon, ctx), PAGE_SIZE);
		/*
		 * in the very unlikely event that the server sent a max write size under PAGE_SIZE,
		 * (which would get rounded down to 0) then reset wsize to absolute minimum eg 4096
		 */
		if (cifs_sb->ctx->wsize == 0) {
			cifs_sb->ctx->wsize = PAGE_SIZE;
			cifs_dbg(VFS, "wsize too small, reset to minimum ie PAGE_SIZE, usually 4096\n");
		}
	}
3466 3467
	if ((cifs_sb->ctx->rsize == 0) ||
	    (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3468
		cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3469

3470 3471 3472 3473 3474
	/*
	 * The cookie is initialized from volume info returned above.
	 * Inside cifs_fscache_get_super_cookie it checks
	 * that we do not get super cookie twice.
	 */
3475 3476
	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
		cifs_fscache_get_super_cookie(tcon);
3477

3478 3479 3480
out:
	mnt_ctx->tcon = tcon;
	return rc;
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
}

static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
			     struct cifs_tcon *tcon)
{
	struct tcon_link *tlink;

	/* hang the tcon off of the superblock */
	tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
	if (tlink == NULL)
		return -ENOMEM;

	tlink->tl_uid = ses->linux_uid;
	tlink->tl_tcon = tcon;
	tlink->tl_time = jiffies;
	set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
	set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);

	cifs_sb->master_tlink = tlink;
	spin_lock(&cifs_sb->tlink_tree_lock);
	tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
	spin_unlock(&cifs_sb->tlink_tree_lock);

	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
				TLINK_IDLE_EXPIRE);
	return 0;
}
Jeff Layton's avatar
Jeff Layton committed
3508

3509 3510 3511 3512 3513
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,
3514 3515
					char *full_path,
					int added_treename)
3516 3517 3518 3519
{
	int rc;
	char *s;
	char sep, tmp;
3520
	int skip = added_treename ? 1 : 0;
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534

	sep = CIFS_DIR_SEP(cifs_sb);
	s = full_path;

	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
	while (rc == 0) {
		/* skip separators */
		while (*s == sep)
			s++;
		if (!*s)
			break;
		/* next separator */
		while (*s && *s != sep)
			s++;
3535 3536 3537 3538 3539 3540 3541 3542
		/*
		 * if the treename is added, we then have to skip the first
		 * part within the separators
		 */
		if (skip) {
			skip = 0;
			continue;
		}
3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
		/*
		 * temporarily null-terminate the path at the end of
		 * the current component
		 */
		tmp = *s;
		*s = 0;
		rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
						     full_path);
		*s = tmp;
	}
	return rc;
}

3556
/*
3557 3558 3559
 * Check if path is remote (i.e. a DFS share).
 *
 * Return -EREMOTE if it is, otherwise 0 or -errno.
3560
 */
3561
int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3562
{
3563
	int rc;
3564 3565 3566 3567 3568
	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
	struct TCP_Server_Info *server = mnt_ctx->server;
	unsigned int xid = mnt_ctx->xid;
	struct cifs_tcon *tcon = mnt_ctx->tcon;
	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3569
	char *full_path;
3570

3571 3572
	if (!server->ops->is_path_accessible)
		return -EOPNOTSUPP;
3573

3574 3575 3576
	/*
	 * cifs_build_path_to_root works only when we have a valid tcon
	 */
3577
	full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3578 3579 3580
					    tcon->Flags & SMB_SHARE_IS_IN_DFS);
	if (full_path == NULL)
		return -ENOMEM;
3581

3582
	cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
Linus Torvalds's avatar
Linus Torvalds committed
3583

3584 3585
	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
					     full_path);
3586 3587
	if (rc != 0 && rc != -EREMOTE)
		goto out;
3588

3589 3590
	if (rc != -EREMOTE) {
		rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3591
			cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3592
		if (rc != 0) {
3593
			cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3594 3595 3596
			cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
			rc = 0;
		}
3597
	}
Igor Mammedov's avatar
Igor Mammedov committed
3598

3599
out:
3600 3601 3602
	kfree(full_path);
	return rc;
}
3603

3604
#ifdef CONFIG_CIFS_DFS_UPCALL
3605 3606
int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
{
3607
	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3608
	bool isdfs;
3609
	int rc;
3610

3611
	rc = dfs_mount_share(&mnt_ctx, &isdfs);
3612
	if (rc)
3613
		goto error;
3614 3615
	if (!isdfs)
		goto out;
3616

3617
	/*
3618 3619
	 * After reconnecting to a different server, unique ids won't match anymore, so we disable
	 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3620 3621
	 */
	cifs_autodisable_serverino(cifs_sb);
3622
	/*
3623 3624
	 * Force the use of prefix path to support failover on DFS paths that resolve to targets
	 * that have different prefix paths.
3625 3626 3627
	 */
	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
	kfree(cifs_sb->prepath);
3628 3629
	cifs_sb->prepath = ctx->prepath;
	ctx->prepath = NULL;
3630

3631
out:
3632
	cifs_try_adding_channels(mnt_ctx.ses);
3633 3634 3635 3636 3637 3638
	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
	if (rc)
		goto error;

	free_xid(mnt_ctx.xid);
	return rc;
3639

3640
error:
3641
	cifs_mount_put_conns(&mnt_ctx);
3642 3643 3644
	return rc;
}
#else
3645
int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3646 3647
{
	int rc = 0;
3648
	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3649

3650
	rc = cifs_mount_get_session(&mnt_ctx);
3651 3652
	if (rc)
		goto error;
3653

3654
	rc = cifs_mount_get_tcon(&mnt_ctx);
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
	if (!rc) {
		/*
		 * Prevent superblock from being created with any missing
		 * connections.
		 */
		if (WARN_ON(!mnt_ctx.server))
			rc = -EHOSTDOWN;
		else if (WARN_ON(!mnt_ctx.ses))
			rc = -EACCES;
		else if (WARN_ON(!mnt_ctx.tcon))
			rc = -ENOENT;
	}
3667 3668 3669 3670 3671 3672 3673 3674
	if (rc)
		goto error;

	rc = cifs_is_path_remote(&mnt_ctx);
	if (rc == -EREMOTE)
		rc = -EOPNOTSUPP;
	if (rc)
		goto error;
Igor Mammedov's avatar
Igor Mammedov committed
3675

3676 3677 3678 3679
	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
	if (rc)
		goto error;

3680
	free_xid(mnt_ctx.xid);
3681
	return rc;
3682 3683

error:
3684
	cifs_mount_put_conns(&mnt_ctx);
Linus Torvalds's avatar
Linus Torvalds committed
3685 3686
	return rc;
}
3687
#endif
Linus Torvalds's avatar
Linus Torvalds committed
3688

3689
/*
3690
 * Issue a TREE_CONNECT request.
3691
 */
Linus Torvalds's avatar
Linus Torvalds committed
3692
int
3693
CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3694
	 const char *tree, struct cifs_tcon *tcon,
Linus Torvalds's avatar
Linus Torvalds committed
3695 3696 3697 3698 3699 3700 3701 3702
	 const struct nls_table *nls_codepage)
{
	struct smb_hdr *smb_buffer;
	struct smb_hdr *smb_buffer_response;
	TCONX_REQ *pSMB;
	TCONX_RSP *pSMBr;
	unsigned char *bcc_ptr;
	int rc = 0;
3703 3704
	int length;
	__u16 bytes_left, count;
Linus Torvalds's avatar
Linus Torvalds committed
3705 3706 3707 3708 3709

	if (ses == NULL)
		return -EIO;

	smb_buffer = cifs_buf_get();
3710
	if (smb_buffer == NULL)
Linus Torvalds's avatar
Linus Torvalds committed
3711
		return -ENOMEM;
3712

Linus Torvalds's avatar
Linus Torvalds committed
3713 3714 3715
	smb_buffer_response = smb_buffer;

	header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3716
			NULL /*no tid */, 4 /*wct */);
3717

3718
	smb_buffer->Mid = get_next_mid(ses->server);
Linus Torvalds's avatar
Linus Torvalds committed
3719 3720 3721 3722 3723 3724 3725
	smb_buffer->Uid = ses->Suid;
	pSMB = (TCONX_REQ *) smb_buffer;
	pSMBr = (TCONX_RSP *) smb_buffer_response;

	pSMB->AndXCommand = 0xFF;
	pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
	bcc_ptr = &pSMB->Password[0];
3726 3727 3728 3729 3730

	pSMB->PasswordLength = cpu_to_le16(1);	/* minimum */
	*bcc_ptr = 0; /* password is null byte */
	bcc_ptr++;              /* skip password */
	/* already aligned so no need to do it below */
Linus Torvalds's avatar
Linus Torvalds committed
3731

3732
	if (ses->server->sign)
Linus Torvalds's avatar
Linus Torvalds committed
3733 3734
		smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;

3735
	if (ses->capabilities & CAP_STATUS32)
Linus Torvalds's avatar
Linus Torvalds committed
3736
		smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3737 3738

	if (ses->capabilities & CAP_DFS)
Linus Torvalds's avatar
Linus Torvalds committed
3739
		smb_buffer->Flags2 |= SMBFLG2_DFS;
3740

Linus Torvalds's avatar
Linus Torvalds committed
3741 3742 3743
	if (ses->capabilities & CAP_UNICODE) {
		smb_buffer->Flags2 |= SMBFLG2_UNICODE;
		length =
3744
		    cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3745
			6 /* max utf8 char length in bytes */ *
3746 3747
			(/* server len*/ + 256 /* share len */), nls_codepage);
		bcc_ptr += 2 * length;	/* convert num 16 bit words to bytes */
Linus Torvalds's avatar
Linus Torvalds committed
3748 3749 3750 3751 3752 3753 3754 3755 3756
		bcc_ptr += 2;	/* skip trailing null */
	} else {		/* ASCII */
		strcpy(bcc_ptr, tree);
		bcc_ptr += strlen(tree) + 1;
	}
	strcpy(bcc_ptr, "?????");
	bcc_ptr += strlen("?????");
	bcc_ptr += 1;
	count = bcc_ptr - &pSMB->Password[0];
3757
	be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
Linus Torvalds's avatar
Linus Torvalds committed
3758 3759
	pSMB->ByteCount = cpu_to_le16(count);

3760
	rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3761
			 0);
Linus Torvalds's avatar
Linus Torvalds committed
3762 3763

	/* above now done in SendReceive */
3764
	if (rc == 0) {
3765 3766
		bool is_unicode;

Linus Torvalds's avatar
Linus Torvalds committed
3767 3768
		tcon->tid = smb_buffer_response->Tid;
		bcc_ptr = pByteArea(smb_buffer_response);
3769
		bytes_left = get_bcc(smb_buffer_response);
3770
		length = strnlen(bcc_ptr, bytes_left - 2);
3771 3772 3773 3774 3775
		if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
			is_unicode = true;
		else
			is_unicode = false;

3776

3777
		/* skip service field (NB: this field is always ASCII) */
3778 3779 3780
		if (length == 3) {
			if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
			    (bcc_ptr[2] == 'C')) {
3781
				cifs_dbg(FYI, "IPC connection\n");
3782 3783
				tcon->ipc = true;
				tcon->pipe = true;
3784 3785 3786 3787
			}
		} else if (length == 2) {
			if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
				/* the most common case */
3788
				cifs_dbg(FYI, "disk share connection\n");
3789 3790
			}
		}
3791
		bcc_ptr += length + 1;
3792
		bytes_left -= (length + 1);
3793
		strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3794 3795

		/* mostly informational -- no need to fail on error here */
3796
		kfree(tcon->nativeFileSystem);
3797
		tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3798
						      bytes_left, is_unicode,
3799 3800
						      nls_codepage);

3801
		cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3802

Steve French's avatar
Steve French committed
3803
		if ((smb_buffer_response->WordCount == 3) ||
Steve French's avatar
Steve French committed
3804 3805
			 (smb_buffer_response->WordCount == 7))
			/* field is in same location */
3806 3807 3808
			tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
		else
			tcon->Flags = 0;
3809
		cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
Linus Torvalds's avatar
Linus Torvalds committed
3810 3811
	}

3812
	cifs_buf_release(smb_buffer);
Linus Torvalds's avatar
Linus Torvalds committed
3813 3814 3815
	return rc;
}

3816 3817
static void delayed_free(struct rcu_head *p)
{
3818 3819 3820
	struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);

	unload_nls(cifs_sb->local_nls);
3821
	smb3_cleanup_fs_context(cifs_sb->ctx);
3822
	kfree(cifs_sb);
3823 3824
}

Al Viro's avatar
Al Viro committed
3825 3826
void
cifs_umount(struct cifs_sb_info *cifs_sb)
Linus Torvalds's avatar
Linus Torvalds committed
3827
{
3828 3829 3830
	struct rb_root *root = &cifs_sb->tlink_tree;
	struct rb_node *node;
	struct tcon_link *tlink;
3831

3832 3833
	cancel_delayed_work_sync(&cifs_sb->prune_tlinks);

3834 3835 3836 3837 3838 3839
	spin_lock(&cifs_sb->tlink_tree_lock);
	while ((node = rb_first(root))) {
		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
		cifs_get_tlink(tlink);
		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
		rb_erase(node, root);
Linus Torvalds's avatar
Linus Torvalds committed
3840

3841 3842 3843 3844 3845
		spin_unlock(&cifs_sb->tlink_tree_lock);
		cifs_put_tlink(tlink);
		spin_lock(&cifs_sb->tlink_tree_lock);
	}
	spin_unlock(&cifs_sb->tlink_tree_lock);
3846

3847
	kfree(cifs_sb->prepath);
3848
	call_rcu(&cifs_sb->rcu, delayed_free);
3849
}
Linus Torvalds's avatar
Linus Torvalds committed
3850

3851
int
3852 3853
cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
			struct TCP_Server_Info *server)
Linus Torvalds's avatar
Linus Torvalds committed
3854 3855 3856
{
	int rc = 0;

3857 3858 3859
	if (!server->ops->need_neg || !server->ops->negotiate)
		return -ENOSYS;

3860
	/* only send once per connect */
3861
	spin_lock(&server->srv_lock);
3862 3863
	if (server->tcpStatus != CifsGood &&
	    server->tcpStatus != CifsNew &&
3864
	    server->tcpStatus != CifsNeedNegotiate) {
3865 3866 3867 3868 3869 3870
		spin_unlock(&server->srv_lock);
		return -EHOSTDOWN;
	}

	if (!server->ops->need_neg(server) &&
	    server->tcpStatus == CifsGood) {
3871
		spin_unlock(&server->srv_lock);
3872
		return 0;
3873
	}
3874

3875
	server->tcpStatus = CifsInNegotiate;
3876
	spin_unlock(&server->srv_lock);
3877

3878
	rc = server->ops->negotiate(xid, ses, server);
3879
	if (rc == 0) {
3880
		spin_lock(&server->srv_lock);
3881
		if (server->tcpStatus == CifsInNegotiate)
3882
			server->tcpStatus = CifsGood;
3883 3884
		else
			rc = -EHOSTDOWN;
3885
		spin_unlock(&server->srv_lock);
3886
	} else {
3887
		spin_lock(&server->srv_lock);
3888 3889
		if (server->tcpStatus == CifsInNegotiate)
			server->tcpStatus = CifsNeedNegotiate;
3890
		spin_unlock(&server->srv_lock);
3891 3892 3893 3894 3895
	}

	return rc;
}

3896 3897
int
cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3898
		   struct TCP_Server_Info *server,
3899
		   struct nls_table *nls_info)
3900
{
3901
	int rc = -ENOSYS;
3902
	struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3903 3904
	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
	struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
3905
	bool is_binding = false;
3906

3907
	spin_lock(&ses->ses_lock);
3908 3909 3910
	cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
		 __func__, ses->chans_need_reconnect);

3911 3912 3913
	if (ses->ses_status != SES_GOOD &&
	    ses->ses_status != SES_NEW &&
	    ses->ses_status != SES_NEED_RECON) {
3914
		spin_unlock(&ses->ses_lock);
3915
		return -EHOSTDOWN;
3916
	}
3917

3918 3919
	/* only send once per connect */
	spin_lock(&ses->chan_lock);
3920 3921 3922
	if (CIFS_ALL_CHANS_GOOD(ses)) {
		if (ses->ses_status == SES_NEED_RECON)
			ses->ses_status = SES_GOOD;
3923
		spin_unlock(&ses->chan_lock);
3924
		spin_unlock(&ses->ses_lock);
3925 3926
		return 0;
	}
3927

3928
	cifs_chan_set_in_reconnect(ses, server);
3929
	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3930 3931
	spin_unlock(&ses->chan_lock);

3932
	if (!is_binding) {
3933
		ses->ses_status = SES_IN_SETUP;
3934 3935 3936 3937

		/* force iface_list refresh */
		ses->iface_last_update = 0;
	}
3938
	spin_unlock(&ses->ses_lock);
3939

3940 3941 3942 3943 3944 3945 3946 3947
	/* update ses ip_addr only for primary chan */
	if (server == pserver) {
		if (server->dstaddr.ss_family == AF_INET6)
			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
		else
			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
	}

3948
	if (!is_binding) {
3949
		ses->capabilities = server->capabilities;
3950
		if (!linuxExtEnabled)
3951 3952 3953 3954 3955
			ses->capabilities &= (~server->vals->cap_unix);

		if (ses->auth_key.response) {
			cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
				 ses->auth_key.response);
3956
			kfree_sensitive(ses->auth_key.response);
3957 3958 3959 3960
			ses->auth_key.response = NULL;
			ses->auth_key.len = 0;
		}
	}
3961

3962
	cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3963
		 server->sec_mode, server->capabilities, server->timeAdj);
3964

3965
	if (server->ops->sess_setup)
3966
		rc = server->ops->sess_setup(xid, ses, server, nls_info);
3967

3968
	if (rc) {
3969
		cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3970
		spin_lock(&ses->ses_lock);
3971 3972
		if (ses->ses_status == SES_IN_SETUP)
			ses->ses_status = SES_NEED_RECON;
3973 3974 3975
		spin_lock(&ses->chan_lock);
		cifs_chan_clear_in_reconnect(ses, server);
		spin_unlock(&ses->chan_lock);
3976
		spin_unlock(&ses->ses_lock);
3977
	} else {
3978
		spin_lock(&ses->ses_lock);
3979 3980
		if (ses->ses_status == SES_IN_SETUP)
			ses->ses_status = SES_GOOD;
3981
		spin_lock(&ses->chan_lock);
3982
		cifs_chan_clear_in_reconnect(ses, server);
3983 3984
		cifs_chan_clear_need_reconnect(ses, server);
		spin_unlock(&ses->chan_lock);
3985
		spin_unlock(&ses->ses_lock);
3986
	}
3987

Linus Torvalds's avatar
Linus Torvalds committed
3988 3989 3990
	return rc;
}

3991
static int
3992
cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3993
{
3994
	ctx->sectype = ses->sectype;
3995 3996

	/* krb5 is special, since we don't need username or pw */
3997
	if (ctx->sectype == Kerberos)
3998 3999
		return 0;

4000
	return cifs_set_cifscreds(ctx, ses);
4001 4002
}

4003
static struct cifs_tcon *
4004
__cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4005
{
4006
	int rc;
4007 4008 4009
	struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
	struct cifs_ses *ses;
	struct cifs_tcon *tcon = NULL;
4010
	struct smb3_fs_context *ctx;
4011
	char *origin_fullpath = NULL;
4012

4013 4014
	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
	if (ctx == NULL)
4015
		return ERR_PTR(-ENOMEM);
4016

4017 4018 4019
	ctx->local_nls = cifs_sb->local_nls;
	ctx->linux_uid = fsuid;
	ctx->cred_uid = fsuid;
4020
	ctx->UNC = master_tcon->tree_name;
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033
	ctx->retry = master_tcon->retry;
	ctx->nocase = master_tcon->nocase;
	ctx->nohandlecache = master_tcon->nohandlecache;
	ctx->local_lease = master_tcon->local_lease;
	ctx->no_lease = master_tcon->no_lease;
	ctx->resilient = master_tcon->use_resilient;
	ctx->persistent = master_tcon->use_persistent;
	ctx->handle_timeout = master_tcon->handle_timeout;
	ctx->no_linux_ext = !master_tcon->unix_ext;
	ctx->linux_ext = master_tcon->posix_extensions;
	ctx->sectype = master_tcon->ses->sectype;
	ctx->sign = master_tcon->ses->sign;
	ctx->seal = master_tcon->seal;
4034
	ctx->witness = master_tcon->use_witness;
4035
	ctx->dfs_root_ses = master_tcon->ses->dfs_root_ses;
4036 4037

	rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4038 4039 4040 4041
	if (rc) {
		tcon = ERR_PTR(rc);
		goto out;
	}
4042 4043

	/* get a reference for the same TCP session */
4044
	spin_lock(&cifs_tcp_ses_lock);
4045
	++master_tcon->ses->server->srv_count;
4046
	spin_unlock(&cifs_tcp_ses_lock);
4047

4048
	ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4049
	if (IS_ERR(ses)) {
4050
		tcon = (struct cifs_tcon *)ses;
4051
		cifs_put_tcp_session(master_tcon->ses->server, 0);
4052 4053 4054
		goto out;
	}

4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
#ifdef CONFIG_CIFS_DFS_UPCALL
	spin_lock(&master_tcon->tc_lock);
	if (master_tcon->origin_fullpath) {
		spin_unlock(&master_tcon->tc_lock);
		origin_fullpath = dfs_get_path(cifs_sb, cifs_sb->ctx->source);
		if (IS_ERR(origin_fullpath)) {
			tcon = ERR_CAST(origin_fullpath);
			origin_fullpath = NULL;
			cifs_put_smb_ses(ses);
			goto out;
		}
	} else {
		spin_unlock(&master_tcon->tc_lock);
	}
#endif

4071
	tcon = cifs_get_tcon(ses, ctx);
4072 4073 4074 4075 4076
	if (IS_ERR(tcon)) {
		cifs_put_smb_ses(ses);
		goto out;
	}

4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
#ifdef CONFIG_CIFS_DFS_UPCALL
	if (origin_fullpath) {
		spin_lock(&tcon->tc_lock);
		tcon->origin_fullpath = origin_fullpath;
		spin_unlock(&tcon->tc_lock);
		origin_fullpath = NULL;
		queue_delayed_work(dfscache_wq, &tcon->dfs_cache_work,
				   dfs_cache_get_ttl() * HZ);
	}
#endif

4088
#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4089
	if (cap_unix(ses))
4090
		reset_cifs_unix_caps(0, tcon, NULL, ctx);
4091
#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4092

4093
out:
4094 4095
	kfree(ctx->username);
	kfree_sensitive(ctx->password);
4096
	kfree(origin_fullpath);
4097
	kfree(ctx);
4098 4099 4100 4101

	return tcon;
}

4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
{
	struct cifs_tcon *ret;

	cifs_mount_lock();
	ret = __cifs_construct_tcon(cifs_sb, fsuid);
	cifs_mount_unlock();
	return ret;
}

4113
struct cifs_tcon *
4114 4115 4116 4117 4118
cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
{
	return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
}

4119 4120
/* find and return a tlink with given uid */
static struct tcon_link *
4121
tlink_rb_search(struct rb_root *root, kuid_t uid)
4122 4123 4124 4125 4126 4127 4128
{
	struct rb_node *node = root->rb_node;
	struct tcon_link *tlink;

	while (node) {
		tlink = rb_entry(node, struct tcon_link, tl_rbnode);

4129
		if (uid_gt(tlink->tl_uid, uid))
4130
			node = node->rb_left;
4131
		else if (uid_lt(tlink->tl_uid, uid))
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
			node = node->rb_right;
		else
			return tlink;
	}
	return NULL;
}

/* insert a tcon_link into the tree */
static void
tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
{
	struct rb_node **new = &(root->rb_node), *parent = NULL;
	struct tcon_link *tlink;

	while (*new) {
		tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
		parent = *new;

4150
		if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4151 4152 4153 4154 4155 4156 4157 4158 4159
			new = &((*new)->rb_left);
		else
			new = &((*new)->rb_right);
	}

	rb_link_node(&new_tlink->tl_rbnode, parent, new);
	rb_insert_color(&new_tlink->tl_rbnode, root);
}

4160 4161 4162 4163 4164 4165 4166
/*
 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
 * current task.
 *
 * If the superblock doesn't refer to a multiuser mount, then just return
 * the master tcon for the mount.
 *
4167
 * First, search the rbtree for an existing tcon for this fsuid. If one
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
 * exists, then check to see if it's pending construction. If it is then wait
 * for construction to complete. Once it's no longer pending, check to see if
 * it failed and either return an error or retry construction, depending on
 * the timeout.
 *
 * If one doesn't exist then insert a new tcon_link struct into the tree and
 * try to construct a new one.
 */
struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
{
	int ret;
4180
	kuid_t fsuid = current_fsuid();
4181 4182 4183 4184 4185 4186
	struct tcon_link *tlink, *newtlink;

	if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
		return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));

	spin_lock(&cifs_sb->tlink_tree_lock);
4187
	tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4188 4189 4190 4191 4192 4193 4194 4195
	if (tlink)
		cifs_get_tlink(tlink);
	spin_unlock(&cifs_sb->tlink_tree_lock);

	if (tlink == NULL) {
		newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
		if (newtlink == NULL)
			return ERR_PTR(-ENOMEM);
4196
		newtlink->tl_uid = fsuid;
4197 4198 4199 4200 4201 4202 4203
		newtlink->tl_tcon = ERR_PTR(-EACCES);
		set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
		set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
		cifs_get_tlink(newtlink);

		spin_lock(&cifs_sb->tlink_tree_lock);
		/* was one inserted after previous search? */
4204
		tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4205 4206 4207 4208 4209 4210 4211
		if (tlink) {
			cifs_get_tlink(tlink);
			spin_unlock(&cifs_sb->tlink_tree_lock);
			kfree(newtlink);
			goto wait_for_construction;
		}
		tlink = newtlink;
4212 4213
		tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
		spin_unlock(&cifs_sb->tlink_tree_lock);
4214 4215 4216 4217 4218 4219
	} else {
wait_for_construction:
		ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
				  TASK_INTERRUPTIBLE);
		if (ret) {
			cifs_put_tlink(tlink);
4220
			return ERR_PTR(-ERESTARTSYS);
4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
		}

		/* if it's good, return it */
		if (!IS_ERR(tlink->tl_tcon))
			return tlink;

		/* return error if we tried this already recently */
		if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
			cifs_put_tlink(tlink);
			return ERR_PTR(-EACCES);
		}

		if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
			goto wait_for_construction;
	}

	tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
	clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
	wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);

	if (IS_ERR(tlink->tl_tcon)) {
		cifs_put_tlink(tlink);
		return ERR_PTR(-EACCES);
	}

	return tlink;
}
4248 4249 4250 4251 4252 4253 4254 4255 4256 4257

/*
 * periodic workqueue job that scans tcon_tree for a superblock and closes
 * out tcons.
 */
static void
cifs_prune_tlinks(struct work_struct *work)
{
	struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
						    prune_tlinks.work);
4258
	struct rb_root *root = &cifs_sb->tlink_tree;
4259
	struct rb_node *node;
4260 4261
	struct rb_node *tmp;
	struct tcon_link *tlink;
4262

4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
	/*
	 * Because we drop the spinlock in the loop in order to put the tlink
	 * it's not guarded against removal of links from the tree. The only
	 * places that remove entries from the tree are this function and
	 * umounts. Because this function is non-reentrant and is canceled
	 * before umount can proceed, this is safe.
	 */
	spin_lock(&cifs_sb->tlink_tree_lock);
	node = rb_first(root);
	while (node != NULL) {
		tmp = node;
		node = rb_next(tmp);
		tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);

		if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
		    atomic_read(&tlink->tl_count) != 0 ||
		    time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
			continue;
4281

4282 4283 4284 4285 4286 4287 4288 4289 4290
		cifs_get_tlink(tlink);
		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
		rb_erase(tmp, root);

		spin_unlock(&cifs_sb->tlink_tree_lock);
		cifs_put_tlink(tlink);
		spin_lock(&cifs_sb->tlink_tree_lock);
	}
	spin_unlock(&cifs_sb->tlink_tree_lock);
4291

4292
	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4293 4294
				TLINK_IDLE_EXPIRE);
}
4295

4296
#ifndef CONFIG_CIFS_DFS_UPCALL
4297 4298
int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
{
4299
	int rc;
4300 4301
	const struct smb_version_operations *ops = tcon->ses->server->ops;

4302
	/* only send once per connect */
4303
	spin_lock(&tcon->tc_lock);
4304 4305 4306 4307 4308

	/* if tcon is marked for needing reconnect, update state */
	if (tcon->need_reconnect)
		tcon->status = TID_NEED_TCON;

4309 4310 4311 4312 4313
	if (tcon->status == TID_GOOD) {
		spin_unlock(&tcon->tc_lock);
		return 0;
	}

4314 4315 4316 4317 4318 4319
	if (tcon->status != TID_NEW &&
	    tcon->status != TID_NEED_TCON) {
		spin_unlock(&tcon->tc_lock);
		return -EHOSTDOWN;
	}

4320
	tcon->status = TID_IN_TCON;
4321
	spin_unlock(&tcon->tc_lock);
4322

4323
	rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4324
	if (rc) {
4325
		spin_lock(&tcon->tc_lock);
4326 4327
		if (tcon->status == TID_IN_TCON)
			tcon->status = TID_NEED_TCON;
4328
		spin_unlock(&tcon->tc_lock);
4329
	} else {
4330
		spin_lock(&tcon->tc_lock);
4331 4332
		if (tcon->status == TID_IN_TCON)
			tcon->status = TID_GOOD;
4333
		tcon->need_reconnect = false;
4334
		spin_unlock(&tcon->tc_lock);
4335 4336 4337
	}

	return rc;
4338 4339
}
#endif