connect.c 109 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3
/*
 *   fs/cifs/connect.c
 *
4
 *   Copyright (C) International Business Machines  Corp., 2002,2011
Linus Torvalds's avatar
Linus Torvalds committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *   Author(s): Steve French (sfrench@us.ibm.com)
 *
 *   This library is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published
 *   by the Free Software Foundation; either version 2.1 of the License, or
 *   (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
 *   the GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with this library; if not, write to the Free Software
Steve French's avatar
Steve French committed
19
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Linus Torvalds's avatar
Linus Torvalds committed
20 21 22 23 24 25
 */
#include <linux/fs.h>
#include <linux/net.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/wait.h>
26
#include <linux/slab.h>
Linus Torvalds's avatar
Linus Torvalds committed
27 28 29 30
#include <linux/pagemap.h>
#include <linux/ctype.h>
#include <linux/utsname.h>
#include <linux/mempool.h>
31
#include <linux/delay.h>
32
#include <linux/completion.h>
33
#include <linux/kthread.h>
34
#include <linux/pagevec.h>
35
#include <linux/freezer.h>
36
#include <linux/namei.h>
Linus Torvalds's avatar
Linus Torvalds committed
37 38
#include <asm/uaccess.h>
#include <asm/processor.h>
39
#include <linux/inet.h>
40
#include <linux/module.h>
41
#include <keys/user-type.h>
42
#include <net/ipv6.h>
43 44
#include <linux/parser.h>

Linus Torvalds's avatar
Linus Torvalds committed
45 46 47 48 49 50 51 52 53
#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"
54
#include "fscache.h"
Linus Torvalds's avatar
Linus Torvalds committed
55 56 57 58 59 60

#define CIFS_PORT 445
#define RFC1001_PORT 139

extern mempool_t *cifs_req_poolp;

61
/* FIXME: should these be tunable? */
62
#define TLINK_ERROR_EXPIRE	(1 * HZ)
63
#define TLINK_IDLE_EXPIRE	(600 * HZ)
64

65 66 67 68 69
enum {

	/* Mount options that take no arguments */
	Opt_user_xattr, Opt_nouser_xattr,
	Opt_forceuid, Opt_noforceuid,
70
	Opt_forcegid, Opt_noforcegid,
71 72
	Opt_noblocksend, Opt_noautotune,
	Opt_hard, Opt_soft, Opt_perm, Opt_noperm,
73
	Opt_mapposix, Opt_nomapposix,
74 75 76 77 78 79 80 81 82 83 84 85 86
	Opt_mapchars, Opt_nomapchars, Opt_sfu,
	Opt_nosfu, Opt_nodfs, Opt_posixpaths,
	Opt_noposixpaths, Opt_nounix,
	Opt_nocase,
	Opt_brl, Opt_nobrl,
	Opt_forcemandatorylock, Opt_setuids,
	Opt_nosetuids, Opt_dynperm, Opt_nodynperm,
	Opt_nohard, Opt_nosoft,
	Opt_nointr, Opt_intr,
	Opt_nostrictsync, Opt_strictsync,
	Opt_serverino, Opt_noserverino,
	Opt_rwpidforward, Opt_cifsacl, Opt_nocifsacl,
	Opt_acl, Opt_noacl, Opt_locallease,
87
	Opt_sign, Opt_seal, Opt_noac,
88
	Opt_fsc, Opt_mfsymlinks,
89
	Opt_multiuser, Opt_sloppy, Opt_nosharesock,
90
	Opt_persistent, Opt_nopersistent,
Steve French's avatar
Steve French committed
91
	Opt_resilient, Opt_noresilient,
92 93 94 95 96 97

	/* Mount options which take numeric value */
	Opt_backupuid, Opt_backupgid, Opt_uid,
	Opt_cruid, Opt_gid, Opt_file_mode,
	Opt_dirmode, Opt_port,
	Opt_rsize, Opt_wsize, Opt_actimeo,
98
	Opt_echo_interval,
99 100 101

	/* Mount options which take string value */
	Opt_user, Opt_pass, Opt_ip,
102
	Opt_domain, Opt_srcaddr, Opt_iocharset,
103
	Opt_netbiosname, Opt_servern,
104
	Opt_ver, Opt_vers, Opt_sec, Opt_cache,
105 106 107 108 109 110

	/* Mount options to be ignored */
	Opt_ignore,

	/* Options which could be blank */
	Opt_blank_pass,
111 112
	Opt_blank_user,
	Opt_blank_ip,
113 114 115 116 117 118 119 120 121 122

	Opt_err
};

static const match_table_t cifs_mount_option_tokens = {

	{ Opt_user_xattr, "user_xattr" },
	{ Opt_nouser_xattr, "nouser_xattr" },
	{ Opt_forceuid, "forceuid" },
	{ Opt_noforceuid, "noforceuid" },
123 124
	{ Opt_forcegid, "forcegid" },
	{ Opt_noforcegid, "noforcegid" },
125 126 127 128 129 130
	{ Opt_noblocksend, "noblocksend" },
	{ Opt_noautotune, "noautotune" },
	{ Opt_hard, "hard" },
	{ Opt_soft, "soft" },
	{ Opt_perm, "perm" },
	{ Opt_noperm, "noperm" },
131
	{ Opt_mapchars, "mapchars" }, /* SFU style */
132
	{ Opt_nomapchars, "nomapchars" },
133 134
	{ Opt_mapposix, "mapposix" }, /* SFM style */
	{ Opt_nomapposix, "nomapposix" },
135 136 137 138 139 140 141 142 143 144 145 146 147
	{ Opt_sfu, "sfu" },
	{ Opt_nosfu, "nosfu" },
	{ Opt_nodfs, "nodfs" },
	{ Opt_posixpaths, "posixpaths" },
	{ Opt_noposixpaths, "noposixpaths" },
	{ Opt_nounix, "nounix" },
	{ Opt_nounix, "nolinux" },
	{ Opt_nocase, "nocase" },
	{ Opt_nocase, "ignorecase" },
	{ Opt_brl, "brl" },
	{ Opt_nobrl, "nobrl" },
	{ Opt_nobrl, "nolock" },
	{ Opt_forcemandatorylock, "forcemandatorylock" },
148
	{ Opt_forcemandatorylock, "forcemand" },
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
	{ Opt_setuids, "setuids" },
	{ Opt_nosetuids, "nosetuids" },
	{ Opt_dynperm, "dynperm" },
	{ Opt_nodynperm, "nodynperm" },
	{ Opt_nohard, "nohard" },
	{ Opt_nosoft, "nosoft" },
	{ Opt_nointr, "nointr" },
	{ Opt_intr, "intr" },
	{ Opt_nostrictsync, "nostrictsync" },
	{ Opt_strictsync, "strictsync" },
	{ Opt_serverino, "serverino" },
	{ Opt_noserverino, "noserverino" },
	{ Opt_rwpidforward, "rwpidforward" },
	{ Opt_cifsacl, "cifsacl" },
	{ Opt_nocifsacl, "nocifsacl" },
	{ Opt_acl, "acl" },
	{ Opt_noacl, "noacl" },
	{ Opt_locallease, "locallease" },
	{ Opt_sign, "sign" },
	{ Opt_seal, "seal" },
	{ Opt_noac, "noac" },
	{ Opt_fsc, "fsc" },
	{ Opt_mfsymlinks, "mfsymlinks" },
	{ Opt_multiuser, "multiuser" },
173
	{ Opt_sloppy, "sloppy" },
174
	{ Opt_nosharesock, "nosharesock" },
175 176
	{ Opt_persistent, "persistenthandles"},
	{ Opt_nopersistent, "nopersistenthandles"},
Steve French's avatar
Steve French committed
177 178
	{ Opt_resilient, "resilienthandles"},
	{ Opt_noresilient, "noresilienthandles"},
179 180 181 182 183 184 185 186 187 188 189 190 191

	{ Opt_backupuid, "backupuid=%s" },
	{ Opt_backupgid, "backupgid=%s" },
	{ Opt_uid, "uid=%s" },
	{ Opt_cruid, "cruid=%s" },
	{ Opt_gid, "gid=%s" },
	{ Opt_file_mode, "file_mode=%s" },
	{ Opt_dirmode, "dirmode=%s" },
	{ Opt_dirmode, "dir_mode=%s" },
	{ Opt_port, "port=%s" },
	{ Opt_rsize, "rsize=%s" },
	{ Opt_wsize, "wsize=%s" },
	{ Opt_actimeo, "actimeo=%s" },
192
	{ Opt_echo_interval, "echo_interval=%s" },
193

194 195
	{ Opt_blank_user, "user=" },
	{ Opt_blank_user, "username=" },
196 197 198
	{ Opt_user, "user=%s" },
	{ Opt_user, "username=%s" },
	{ Opt_blank_pass, "pass=" },
199
	{ Opt_blank_pass, "password=" },
200 201
	{ Opt_pass, "pass=%s" },
	{ Opt_pass, "password=%s" },
202 203
	{ Opt_blank_ip, "ip=" },
	{ Opt_blank_ip, "addr=" },
204 205
	{ Opt_ip, "ip=%s" },
	{ Opt_ip, "addr=%s" },
206 207 208
	{ Opt_ignore, "unc=%s" },
	{ Opt_ignore, "target=%s" },
	{ Opt_ignore, "path=%s" },
209 210 211 212
	{ Opt_domain, "dom=%s" },
	{ Opt_domain, "domain=%s" },
	{ Opt_domain, "workgroup=%s" },
	{ Opt_srcaddr, "srcaddr=%s" },
213
	{ Opt_ignore, "prefixpath=%s" },
214 215 216 217
	{ Opt_iocharset, "iocharset=%s" },
	{ Opt_netbiosname, "netbiosname=%s" },
	{ Opt_servern, "servern=%s" },
	{ Opt_ver, "ver=%s" },
218
	{ Opt_vers, "vers=%s" },
219
	{ Opt_sec, "sec=%s" },
220
	{ Opt_cache, "cache=%s" },
221 222 223

	{ Opt_ignore, "cred" },
	{ Opt_ignore, "credentials" },
224 225
	{ Opt_ignore, "cred=%s" },
	{ Opt_ignore, "credentials=%s" },
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	{ Opt_ignore, "guest" },
	{ Opt_ignore, "rw" },
	{ Opt_ignore, "ro" },
	{ Opt_ignore, "suid" },
	{ Opt_ignore, "nosuid" },
	{ Opt_ignore, "exec" },
	{ Opt_ignore, "noexec" },
	{ Opt_ignore, "nodev" },
	{ Opt_ignore, "noauto" },
	{ Opt_ignore, "dev" },
	{ Opt_ignore, "mand" },
	{ Opt_ignore, "nomand" },
	{ Opt_ignore, "_netdev" },

	{ Opt_err, NULL }
};

enum {
	Opt_sec_krb5, Opt_sec_krb5i, Opt_sec_krb5p,
	Opt_sec_ntlmsspi, Opt_sec_ntlmssp,
246 247
	Opt_ntlm, Opt_sec_ntlmi, Opt_sec_ntlmv2,
	Opt_sec_ntlmv2i, Opt_sec_lanman,
248 249 250 251 252 253 254 255 256 257 258 259 260
	Opt_sec_none,

	Opt_sec_err
};

static const match_table_t cifs_secflavor_tokens = {
	{ Opt_sec_krb5, "krb5" },
	{ Opt_sec_krb5i, "krb5i" },
	{ Opt_sec_krb5p, "krb5p" },
	{ Opt_sec_ntlmsspi, "ntlmsspi" },
	{ Opt_sec_ntlmssp, "ntlmssp" },
	{ Opt_ntlm, "ntlm" },
	{ Opt_sec_ntlmi, "ntlmi" },
261 262
	{ Opt_sec_ntlmv2, "nontlm" },
	{ Opt_sec_ntlmv2, "ntlmv2" },
263 264 265 266 267 268 269
	{ Opt_sec_ntlmv2i, "ntlmv2i" },
	{ Opt_sec_lanman, "lanman" },
	{ Opt_sec_none, "none" },

	{ Opt_sec_err, NULL }
};

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
/* cache flavors */
enum {
	Opt_cache_loose,
	Opt_cache_strict,
	Opt_cache_none,
	Opt_cache_err
};

static const match_table_t cifs_cacheflavor_tokens = {
	{ Opt_cache_loose, "loose" },
	{ Opt_cache_strict, "strict" },
	{ Opt_cache_none, "none" },
	{ Opt_cache_err, NULL }
};

285 286
static const match_table_t cifs_smb_version_tokens = {
	{ Smb_1, SMB1_VERSION_STRING },
Steve French's avatar
Steve French committed
287
	{ Smb_20, SMB20_VERSION_STRING},
288
	{ Smb_21, SMB21_VERSION_STRING },
289
	{ Smb_30, SMB30_VERSION_STRING },
Steve French's avatar
Steve French committed
290
	{ Smb_302, SMB302_VERSION_STRING },
291 292
#ifdef CONFIG_CIFS_SMB311
	{ Smb_311, SMB311_VERSION_STRING },
293
	{ Smb_311, ALT_SMB311_VERSION_STRING },
294 295
#endif /* SMB311 */
	{ Smb_version_err, NULL }
296 297
};

298 299
static int ip_connect(struct TCP_Server_Info *server);
static int generic_ip_connect(struct TCP_Server_Info *server);
300
static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
301
static void cifs_prune_tlinks(struct work_struct *work);
Jeff Layton's avatar
Jeff Layton committed
302 303
static int cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
					const char *devname);
Linus Torvalds's avatar
Linus Torvalds committed
304

305 306 307 308 309 310 311 312
/*
 * 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)
 */
313
int
Linus Torvalds's avatar
Linus Torvalds committed
314 315 316
cifs_reconnect(struct TCP_Server_Info *server)
{
	int rc = 0;
317
	struct list_head *tmp, *tmp2;
318 319
	struct cifs_ses *ses;
	struct cifs_tcon *tcon;
Steve French's avatar
Steve French committed
320
	struct mid_q_entry *mid_entry;
321
	struct list_head retry_list;
322

Linus Torvalds's avatar
Linus Torvalds committed
323
	spin_lock(&GlobalMid_Lock);
324
	if (server->tcpStatus == CifsExiting) {
Steve French's avatar
Steve French committed
325
		/* the demux thread will exit normally
Linus Torvalds's avatar
Linus Torvalds committed
326 327 328 329 330 331 332
		next time through the loop */
		spin_unlock(&GlobalMid_Lock);
		return rc;
	} else
		server->tcpStatus = CifsNeedReconnect;
	spin_unlock(&GlobalMid_Lock);
	server->maxBuf = 0;
333 334 335
#ifdef CONFIG_CIFS_SMB2
	server->max_read = 0;
#endif
Linus Torvalds's avatar
Linus Torvalds committed
336

337
	cifs_dbg(FYI, "Reconnecting tcp session\n");
Linus Torvalds's avatar
Linus Torvalds committed
338 339 340

	/* before reconnecting the tcp session, mark the smb session (uid)
		and the tid bad so they are not used until reconnected */
341 342
	cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n",
		 __func__);
343
	spin_lock(&cifs_tcp_ses_lock);
344
	list_for_each(tmp, &server->smb_ses_list) {
345
		ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
346 347
		ses->need_reconnect = true;
		ses->ipc_tid = 0;
348
		list_for_each(tmp2, &ses->tcon_list) {
349
			tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
350
			tcon->need_reconnect = true;
Linus Torvalds's avatar
Linus Torvalds committed
351 352
		}
	}
353
	spin_unlock(&cifs_tcp_ses_lock);
354

Linus Torvalds's avatar
Linus Torvalds committed
355
	/* do not want to be sending data on a socket we are freeing */
356
	cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
Jeff Layton's avatar
Jeff Layton committed
357
	mutex_lock(&server->srv_mutex);
Steve French's avatar
Steve French committed
358
	if (server->ssocket) {
359 360
		cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n",
			 server->ssocket->state, server->ssocket->flags);
361
		kernel_sock_shutdown(server->ssocket, SHUT_WR);
362 363
		cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n",
			 server->ssocket->state, server->ssocket->flags);
Linus Torvalds's avatar
Linus Torvalds committed
364 365 366
		sock_release(server->ssocket);
		server->ssocket = NULL;
	}
367 368
	server->sequence_number = 0;
	server->session_estab = false;
369 370 371
	kfree(server->session_key.response);
	server->session_key.response = NULL;
	server->session_key.len = 0;
372
	server->lstrp = jiffies;
Linus Torvalds's avatar
Linus Torvalds committed
373

374
	/* mark submitted MIDs for retry and issue callback */
375
	INIT_LIST_HEAD(&retry_list);
376
	cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
Linus Torvalds's avatar
Linus Torvalds committed
377
	spin_lock(&GlobalMid_Lock);
378 379
	list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
		mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
380 381
		if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
			mid_entry->mid_state = MID_RETRY_NEEDED;
382 383 384
		list_move(&mid_entry->qhead, &retry_list);
	}
	spin_unlock(&GlobalMid_Lock);
385
	mutex_unlock(&server->srv_mutex);
386

387
	cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
388 389
	list_for_each_safe(tmp, tmp2, &retry_list) {
		mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
390 391
		list_del_init(&mid_entry->qhead);
		mid_entry->callback(mid_entry);
Linus Torvalds's avatar
Linus Torvalds committed
392 393
	}

394
	do {
395
		try_to_freeze();
396 397

		/* we should try only the port we connected to before */
398
		mutex_lock(&server->srv_mutex);
399
		rc = generic_ip_connect(server);
Steve French's avatar
Steve French committed
400
		if (rc) {
401
			cifs_dbg(FYI, "reconnect error %d\n", rc);
402
			mutex_unlock(&server->srv_mutex);
403
			msleep(3000);
Linus Torvalds's avatar
Linus Torvalds committed
404 405 406
		} else {
			atomic_inc(&tcpSesReconnectCount);
			spin_lock(&GlobalMid_Lock);
407
			if (server->tcpStatus != CifsExiting)
408
				server->tcpStatus = CifsNeedNegotiate;
Steve French's avatar
Steve French committed
409
			spin_unlock(&GlobalMid_Lock);
410
			mutex_unlock(&server->srv_mutex);
Linus Torvalds's avatar
Linus Torvalds committed
411
		}
412
	} while (server->tcpStatus == CifsNeedReconnect);
413

Linus Torvalds's avatar
Linus Torvalds committed
414 415 416
	return rc;
}

417 418 419 420 421 422
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);
423
	unsigned long echo_interval = server->echo_interval;
424

425
	/*
426 427 428 429
	 * We cannot send an echo if it is disabled or until the
	 * NEGOTIATE_PROTOCOL request is done, which is indicated by
	 * server->ops->need_neg() == true. Also, no need to ping if
	 * we got a response recently.
430
	 */
431
	if (!server->ops->need_neg || server->ops->need_neg(server) ||
432
	    (server->ops->can_echo && !server->ops->can_echo(server)) ||
433
	    time_before(jiffies, server->lstrp + echo_interval - HZ))
434 435
		goto requeue_echo;

436
	rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
437
	if (rc)
438 439
		cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
			 server->hostname);
440 441

requeue_echo:
442
	queue_delayed_work(cifsiod_wq, &server->echo, echo_interval);
443 444
}

445
static bool
446
allocate_buffers(struct TCP_Server_Info *server)
447
{
448 449 450
	if (!server->bigbuf) {
		server->bigbuf = (char *)cifs_buf_get();
		if (!server->bigbuf) {
451
			cifs_dbg(VFS, "No memory for large SMB response\n");
452 453 454 455
			msleep(3000);
			/* retry will check if exiting */
			return false;
		}
456
	} else if (server->large_buf) {
457
		/* we are reusing a dirty large buf, clear its start */
458
		memset(server->bigbuf, 0, HEADER_SIZE(server));
459 460
	}

461 462 463
	if (!server->smallbuf) {
		server->smallbuf = (char *)cifs_small_buf_get();
		if (!server->smallbuf) {
464
			cifs_dbg(VFS, "No memory for SMB response\n");
465 466 467 468 469 470 471
			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 */
472
		memset(server->smallbuf, 0, HEADER_SIZE(server));
473 474 475 476 477
	}

	return true;
}

478 479 480
static bool
server_unresponsive(struct TCP_Server_Info *server)
{
481 482 483 484 485 486 487 488 489 490 491 492
	/*
	 * We need to wait 2 echo intervals to make sure we handle such
	 * situations right:
	 * 1s  client sends a normal SMB request
	 * 2s  client gets a response
	 * 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.
	 */
	if (server->tcpStatus == CifsGood &&
493 494 495
	    time_after(jiffies, server->lstrp + 2 * server->echo_interval)) {
		cifs_dbg(VFS, "Server %s has not responded in %lu seconds. Reconnecting...\n",
			 server->hostname, (2 * server->echo_interval) / HZ);
496 497 498 499 500 501 502 503
		cifs_reconnect(server);
		wake_up(&server->response_q);
		return true;
	}

	return false;
}

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
/*
 * kvec_array_init - clone a kvec array, and advance into it
 * @new:	pointer to memory for cloned array
 * @iov:	pointer to original array
 * @nr_segs:	number of members in original array
 * @bytes:	number of bytes to advance into the cloned array
 *
 * This function will copy the array provided in iov to a section of memory
 * and advance the specified number of bytes into the new array. It returns
 * the number of segments in the new array. "new" must be at least as big as
 * the original iov array.
 */
static unsigned int
kvec_array_init(struct kvec *new, struct kvec *iov, unsigned int nr_segs,
		size_t bytes)
{
	size_t base = 0;

	while (bytes || !iov->iov_len) {
		int copy = min(bytes, iov->iov_len);

		bytes -= copy;
		base += copy;
		if (iov->iov_len == base) {
			iov++;
			nr_segs--;
			base = 0;
		}
	}
	memcpy(new, iov, sizeof(*iov) * nr_segs);
	new->iov_base += base;
	new->iov_len -= base;
	return nr_segs;
}

539 540
static struct kvec *
get_server_iovec(struct TCP_Server_Info *server, unsigned int nr_segs)
541
{
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
	struct kvec *new_iov;

	if (server->iov && nr_segs <= server->nr_iov)
		return server->iov;

	/* not big enough -- allocate a new one and release the old */
	new_iov = kmalloc(sizeof(*new_iov) * nr_segs, GFP_NOFS);
	if (new_iov) {
		kfree(server->iov);
		server->iov = new_iov;
		server->nr_iov = nr_segs;
	}
	return new_iov;
}

Jeff Layton's avatar
Jeff Layton committed
557 558 559
int
cifs_readv_from_socket(struct TCP_Server_Info *server, struct kvec *iov_orig,
		       unsigned int nr_segs, unsigned int to_read)
560
{
Jeff Layton's avatar
Jeff Layton committed
561 562
	int length = 0;
	int total_read;
563
	unsigned int segs;
564
	struct msghdr smb_msg;
565 566
	struct kvec *iov;

567
	iov = get_server_iovec(server, nr_segs);
568 569
	if (!iov)
		return -ENOMEM;
570

571 572 573
	smb_msg.msg_control = NULL;
	smb_msg.msg_controllen = 0;

Jeff Layton's avatar
Jeff Layton committed
574
	for (total_read = 0; to_read; total_read += length, to_read -= length) {
575 576
		try_to_freeze();

577
		if (server_unresponsive(server)) {
578
			total_read = -ECONNABORTED;
579 580 581
			break;
		}

582 583 584 585
		segs = kvec_array_init(iov, iov_orig, nr_segs, total_read);

		length = kernel_recvmsg(server->ssocket, &smb_msg,
					iov, segs, to_read, 0);
586 587

		if (server->tcpStatus == CifsExiting) {
Jeff Layton's avatar
Jeff Layton committed
588
			total_read = -ESHUTDOWN;
589 590 591
			break;
		} else if (server->tcpStatus == CifsNeedReconnect) {
			cifs_reconnect(server);
592
			total_read = -ECONNABORTED;
593 594 595 596 597 598 599 600 601 602 603
			break;
		} else if (length == -ERESTARTSYS ||
			   length == -EAGAIN ||
			   length == -EINTR) {
			/*
			 * 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;
Jeff Layton's avatar
Jeff Layton committed
604
			continue;
605
		} else if (length <= 0) {
606 607
			cifs_dbg(FYI, "Received no data or error: expecting %d\n"
				 "got %d", to_read, length);
608
			cifs_reconnect(server);
609
			total_read = -ECONNABORTED;
610 611 612
			break;
		}
	}
Jeff Layton's avatar
Jeff Layton committed
613
	return total_read;
614 615
}

Jeff Layton's avatar
Jeff Layton committed
616 617 618
int
cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
		      unsigned int to_read)
619 620 621 622 623 624
{
	struct kvec iov;

	iov.iov_base = buf;
	iov.iov_len = to_read;

Jeff Layton's avatar
Jeff Layton committed
625
	return cifs_readv_from_socket(server, &iov, 1, to_read);
626 627
}

628
static bool
629
is_smb_response(struct TCP_Server_Info *server, unsigned char type)
630 631 632 633 634 635
{
	/*
	 * 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.
	 */
636 637 638 639 640
	switch (type) {
	case RFC1002_SESSION_MESSAGE:
		/* Regular SMB response */
		return true;
	case RFC1002_SESSION_KEEP_ALIVE:
641
		cifs_dbg(FYI, "RFC 1002 session keep alive\n");
642 643
		break;
	case RFC1002_POSITIVE_SESSION_RESPONSE:
644
		cifs_dbg(FYI, "RFC 1002 positive session response\n");
645 646
		break;
	case RFC1002_NEGATIVE_SESSION_RESPONSE:
647 648 649 650
		/*
		 * We get this from Windows 98 instead of an error on
		 * SMB negprot response.
		 */
651
		cifs_dbg(FYI, "RFC 1002 negative session response\n");
652 653 654 655 656 657 658 659
		/* 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).
		 */
660
		cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
661 662
		cifs_reconnect(server);
		wake_up(&server->response_q);
663 664
		break;
	default:
665
		cifs_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
666 667 668
		cifs_reconnect(server);
	}

669
	return false;
670 671
}

Jeff Layton's avatar
Jeff Layton committed
672 673
void
dequeue_mid(struct mid_q_entry *mid, bool malformed)
674
{
675
#ifdef CONFIG_CIFS_STATS2
676
	mid->when_received = jiffies;
677
#endif
678 679
	spin_lock(&GlobalMid_Lock);
	if (!malformed)
680
		mid->mid_state = MID_RESPONSE_RECEIVED;
681
	else
682
		mid->mid_state = MID_RESPONSE_MALFORMED;
683
	list_del_init(&mid->qhead);
684
	spin_unlock(&GlobalMid_Lock);
685
}
686

687 688
static void
handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
689
	   char *buf, int malformed)
690
{
691 692
	if (server->ops->check_trans2 &&
	    server->ops->check_trans2(mid, server, buf, malformed))
693
		return;
694
	mid->resp_buf = buf;
695
	mid->large_buf = server->large_buf;
696 697 698 699 700 701 702 703
	/* 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;
	}
704
	dequeue_mid(mid, malformed);
705 706
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720
static void clean_demultiplex_info(struct TCP_Server_Info *server)
{
	int length;

	/* take it off the list, if it's not already */
	spin_lock(&cifs_tcp_ses_lock);
	list_del_init(&server->tcp_ses_list);
	spin_unlock(&cifs_tcp_ses_lock);

	spin_lock(&GlobalMid_Lock);
	server->tcpStatus = CifsExiting;
	spin_unlock(&GlobalMid_Lock);
	wake_up_all(&server->response_q);

721
	/* check if we have blocked requests that need to free */
722
	spin_lock(&server->req_lock);
723 724
	if (server->credits <= 0)
		server->credits = 1;
725
	spin_unlock(&server->req_lock);
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
	/*
	 * 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);

	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);
		spin_lock(&GlobalMid_Lock);
		list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
751
			cifs_dbg(FYI, "Clearing mid 0x%llx\n", mid_entry->mid);
752
			mid_entry->mid_state = MID_SHUTDOWN;
753 754 755 756 757 758 759
			list_move(&mid_entry->qhead, &dispose_list);
		}
		spin_unlock(&GlobalMid_Lock);

		/* 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);
760
			cifs_dbg(FYI, "Callback mid 0x%llx\n", mid_entry->mid);
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
			list_del_init(&mid_entry->qhead);
			mid_entry->callback(mid_entry);
		}
		/* 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.
		 */
777
		cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
778 779 780 781 782 783 784 785
		msleep(46000);
		/*
		 * If threads still have not exited they are probably never
		 * coming home not much else we can do but free the memory.
		 */
	}

	kfree(server->hostname);
786
	kfree(server->iov);
787 788 789 790
	kfree(server);

	length = atomic_dec_return(&tcpSesAllocCount);
	if (length > 0)
791
		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
792 793
}

794 795 796 797 798
static int
standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
{
	int length;
	char *buf = server->smallbuf;
799
	unsigned int pdu_length = get_rfc1002_length(buf);
800 801

	/* make sure this will fit in a large buffer */
802
	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) - 4) {
803
		cifs_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
804 805
		cifs_reconnect(server);
		wake_up(&server->response_q);
806
		return -ECONNABORTED;
807 808 809 810 811
	}

	/* switch to large buffer if too big for a small one */
	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
		server->large_buf = true;
812
		memcpy(server->bigbuf, buf, server->total_read);
813 814 815 816
		buf = server->bigbuf;
	}

	/* now read the rest */
817 818
	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
				pdu_length - HEADER_SIZE(server) + 1 + 4);
819 820 821 822
	if (length < 0)
		return length;
	server->total_read += length;

823
	dump_smb(buf, server->total_read);
824 825 826 827 828 829 830 831 832 833

	/*
	 * We know that we received enough to get to the MID as we
	 * checked the pdu_length earlier. Now check to see
	 * if the rest of the header is OK. We borrow the length
	 * var for the rest of the loop to avoid a new stack var.
	 *
	 * 48 bytes is enough to display the header and a little bit
	 * into the payload for debugging purposes.
	 */
834
	length = server->ops->check_message(buf, server->total_read, server);
835 836 837 838
	if (length != 0)
		cifs_dump_mem("Bad SMB: ", buf,
			min_t(unsigned int, server->total_read, 48));

839 840 841 842
	if (server->ops->is_status_pending &&
	    server->ops->is_status_pending(buf, server, length))
		return -1;

843 844
	if (!mid)
		return length;
845

846
	handle_mid(mid, server, buf, length);
847
	return 0;
848 849
}

Linus Torvalds's avatar
Linus Torvalds committed
850
static int
851
cifs_demultiplex_thread(void *p)
Linus Torvalds's avatar
Linus Torvalds committed
852 853
{
	int length;
854
	struct TCP_Server_Info *server = p;
855 856
	unsigned int pdu_length;
	char *buf = NULL;
857
	struct task_struct *task_to_wake = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
858 859 860
	struct mid_q_entry *mid_entry;

	current->flags |= PF_MEMALLOC;
861
	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
862 863 864

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

867
	set_freezable();
868
	while (server->tcpStatus != CifsExiting) {
869 870
		if (try_to_freeze())
			continue;
871

872
		if (!allocate_buffers(server))
873
			continue;
874

875 876
		server->large_buf = false;
		buf = server->smallbuf;
877
		pdu_length = 4; /* enough to get RFC1001 header */
878

Jeff Layton's avatar
Jeff Layton committed
879
		length = cifs_read_from_socket(server, buf, pdu_length);
Jeff Layton's avatar
Jeff Layton committed
880
		if (length < 0)
Linus Torvalds's avatar
Linus Torvalds committed
881
			continue;
882
		server->total_read = length;
Linus Torvalds's avatar
Linus Torvalds committed
883

884 885 886 887
		/*
		 * The right amount was read from socket - 4 bytes,
		 * so we can now interpret the length field.
		 */
888
		pdu_length = get_rfc1002_length(buf);
889

890
		cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
891
		if (!is_smb_response(server, buf[0]))
Steve French's avatar
Steve French committed
892
			continue;
893

894
		/* make sure we have enough to get to the MID */
895
		if (pdu_length < HEADER_SIZE(server) - 1 - 4) {
896 897
			cifs_dbg(VFS, "SMB response too short (%u bytes)\n",
				 pdu_length);
898 899 900
			cifs_reconnect(server);
			wake_up(&server->response_q);
			continue;
901
		}
902

903
		/* read down to the MID */
Jeff Layton's avatar
Jeff Layton committed
904
		length = cifs_read_from_socket(server, buf + 4,
905
					       HEADER_SIZE(server) - 1 - 4);
906
		if (length < 0)
907
			continue;
908
		server->total_read += length;
Linus Torvalds's avatar
Linus Torvalds committed
909

910
		mid_entry = server->ops->find_mid(server, buf);
911

912 913 914 915
		if (!mid_entry || !mid_entry->receive)
			length = standard_receive3(server, mid_entry);
		else
			length = mid_entry->receive(server, mid_entry);
916

917
		if (length < 0)
918
			continue;
Linus Torvalds's avatar
Linus Torvalds committed
919

920
		if (server->large_buf)
921
			buf = server->bigbuf;
922 923

		server->lstrp = jiffies;
924
		if (mid_entry != NULL) {
925 926
			if (!mid_entry->multiRsp || mid_entry->multiEnd)
				mid_entry->callback(mid_entry);
927 928
		} else if (!server->ops->is_oplock_break ||
			   !server->ops->is_oplock_break(buf, server)) {
929 930
			cifs_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
				 atomic_read(&midCount));
931 932
			cifs_dump_mem("Received Data is: ", buf,
				      HEADER_SIZE(server));
933
#ifdef CONFIG_CIFS_DEBUG2
934 935
			if (server->ops->dump_detail)
				server->ops->dump_detail(buf);
936 937
			cifs_dump_mids(server);
#endif /* CIFS_DEBUG2 */
938

939 940 941
		}
	} /* end while !EXITING */

942
	/* buffer usually freed in free_mid - need to free it here on exit */
943 944 945
	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
946

947
	task_to_wake = xchg(&server->tsk, NULL);
948
	clean_demultiplex_info(server);
949 950 951 952 953 954 955 956 957 958 959

	/* 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);
	}

960
	module_put_and_exit(0);
Linus Torvalds's avatar
Linus Torvalds committed
961 962
}

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
/* extract the host portion of the UNC string */
static char *
extract_hostname(const char *unc)
{
	const char *src;
	char *dst, *delim;
	unsigned int len;

	/* skip double chars at beginning of string */
	/* BB: check validity of these bytes? */
	src = unc + 2;

	/* delimiter between hostname and sharename is always '\\' now */
	delim = strchr(src, '\\');
	if (!delim)
		return ERR_PTR(-EINVAL);

	len = delim - src;
	dst = kmalloc((len + 1), GFP_KERNEL);
	if (dst == NULL)
		return ERR_PTR(-ENOMEM);

	memcpy(dst, src, len);
	dst[len] = '\0';

	return dst;
}

991 992 993 994 995 996 997 998
static int get_option_ul(substring_t args[], unsigned long *option)
{
	int rc;
	char *string;

	string = match_strdup(args);
	if (string == NULL)
		return -ENOMEM;