xref: /linux/fs/smb/client/smb2pdu.c (revision bf4afc53b77aeaa48b5409da5c8da6bb4eff7f43)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  */
12 
13  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
14  /* Note that there are handle based routines which must be		      */
15  /* treated slightly differently for reconnection purposes since we never     */
16  /* want to reuse a stale file handle and only the caller knows the file info */
17 
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/vfs.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/uaccess.h>
23 #include <linux/uuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/xattr.h>
26 #include <linux/netfs.h>
27 #include <trace/events/netfs.h>
28 #include "cifsglob.h"
29 #include "cifsproto.h"
30 #include "cifsacl.h"
31 #include "smb2proto.h"
32 #include "cifs_unicode.h"
33 #include "cifs_debug.h"
34 #include "ntlmssp.h"
35 #include "../common/smbfsctl.h"
36 #include "../common/smb2status.h"
37 #include "smb2glob.h"
38 #include "cifs_spnego.h"
39 #include "../common/smbdirect/smbdirect.h"
40 #include "smbdirect.h"
41 #include "trace.h"
42 #ifdef CONFIG_CIFS_DFS_UPCALL
43 #include "dfs_cache.h"
44 #endif
45 #include "cached_dir.h"
46 #include "compress.h"
47 #include "fs_context.h"
48 
49 /*
50  *  The following table defines the expected "StructureSize" of SMB2 requests
51  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
52  *
53  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
54  *  indexed by command in host byte order.
55  */
56 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
57 	/* SMB2_NEGOTIATE */ 36,
58 	/* SMB2_SESSION_SETUP */ 25,
59 	/* SMB2_LOGOFF */ 4,
60 	/* SMB2_TREE_CONNECT */	9,
61 	/* SMB2_TREE_DISCONNECT */ 4,
62 	/* SMB2_CREATE */ 57,
63 	/* SMB2_CLOSE */ 24,
64 	/* SMB2_FLUSH */ 24,
65 	/* SMB2_READ */	49,
66 	/* SMB2_WRITE */ 49,
67 	/* SMB2_LOCK */	48,
68 	/* SMB2_IOCTL */ 57,
69 	/* SMB2_CANCEL */ 4,
70 	/* SMB2_ECHO */ 4,
71 	/* SMB2_QUERY_DIRECTORY */ 33,
72 	/* SMB2_CHANGE_NOTIFY */ 32,
73 	/* SMB2_QUERY_INFO */ 41,
74 	/* SMB2_SET_INFO */ 33,
75 	/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
76 };
77 
smb3_encryption_required(const struct cifs_tcon * tcon)78 int smb3_encryption_required(const struct cifs_tcon *tcon)
79 {
80 	if (!tcon || !tcon->ses)
81 		return 0;
82 	if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
83 	    (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
84 		return 1;
85 	if (tcon->seal &&
86 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
87 		return 1;
88 	if (((global_secflags & CIFSSEC_MUST_SEAL) == CIFSSEC_MUST_SEAL) &&
89 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
90 		return 1;
91 	return 0;
92 }
93 
94 static void
smb2_hdr_assemble(struct smb2_hdr * shdr,__le16 smb2_cmd,const struct cifs_tcon * tcon,struct TCP_Server_Info * server)95 smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
96 		  const struct cifs_tcon *tcon,
97 		  struct TCP_Server_Info *server)
98 {
99 	struct smb3_hdr_req *smb3_hdr;
100 
101 	shdr->ProtocolId = SMB2_PROTO_NUMBER;
102 	shdr->StructureSize = cpu_to_le16(64);
103 	shdr->Command = smb2_cmd;
104 
105 	if (server) {
106 		/* After reconnect SMB3 must set ChannelSequence on subsequent reqs */
107 		if (server->dialect >= SMB30_PROT_ID) {
108 			smb3_hdr = (struct smb3_hdr_req *)shdr;
109 			/*
110 			 * if primary channel is not set yet, use default
111 			 * channel for chan sequence num
112 			 */
113 			if (SERVER_IS_CHAN(server))
114 				smb3_hdr->ChannelSequence =
115 					cpu_to_le16(server->primary_server->channel_sequence_num);
116 			else
117 				smb3_hdr->ChannelSequence =
118 					cpu_to_le16(server->channel_sequence_num);
119 		}
120 		spin_lock(&server->req_lock);
121 		/* Request up to 10 credits but don't go over the limit. */
122 		if (server->credits >= server->max_credits)
123 			shdr->CreditRequest = cpu_to_le16(0);
124 		else
125 			shdr->CreditRequest = cpu_to_le16(
126 				min_t(int, server->max_credits -
127 						server->credits, 10));
128 		spin_unlock(&server->req_lock);
129 	} else {
130 		shdr->CreditRequest = cpu_to_le16(2);
131 	}
132 	shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
133 
134 	if (!tcon)
135 		goto out;
136 
137 	/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
138 	/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
139 	if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
140 		shdr->CreditCharge = cpu_to_le16(1);
141 	/* else CreditCharge MBZ */
142 
143 	shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
144 	/* Uid is not converted */
145 	if (tcon->ses)
146 		shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
147 
148 	/*
149 	 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
150 	 * to pass the path on the Open SMB prefixed by \\server\share.
151 	 * Not sure when we would need to do the augmented path (if ever) and
152 	 * setting this flag breaks the SMB2 open operation since it is
153 	 * illegal to send an empty path name (without \\server\share prefix)
154 	 * when the DFS flag is set in the SMB open header. We could
155 	 * consider setting the flag on all operations other than open
156 	 * but it is safer to net set it for now.
157 	 */
158 /*	if (tcon->share_flags & SHI1005_FLAGS_DFS)
159 		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
160 
161 	if (server && server->sign && !smb3_encryption_required(tcon))
162 		shdr->Flags |= SMB2_FLAGS_SIGNED;
163 out:
164 	return;
165 }
166 
167 /* helper function for code reuse */
168 static int
cifs_chan_skip_or_disable(struct cifs_ses * ses,struct TCP_Server_Info * server,bool from_reconnect,bool disable_mchan)169 cifs_chan_skip_or_disable(struct cifs_ses *ses,
170 			  struct TCP_Server_Info *server,
171 			  bool from_reconnect, bool disable_mchan)
172 {
173 	struct TCP_Server_Info *pserver;
174 	unsigned int chan_index;
175 
176 	if (SERVER_IS_CHAN(server)) {
177 		cifs_dbg(VFS,
178 			"server %s does not support multichannel anymore. Skip secondary channel\n",
179 			 ses->server->hostname);
180 
181 		spin_lock(&ses->chan_lock);
182 		chan_index = cifs_ses_get_chan_index(ses, server);
183 		if (chan_index == CIFS_INVAL_CHAN_INDEX) {
184 			spin_unlock(&ses->chan_lock);
185 			goto skip_terminate;
186 		}
187 
188 		ses->chans[chan_index].server = NULL;
189 		server->terminate = true;
190 		spin_unlock(&ses->chan_lock);
191 
192 		/*
193 		 * the above reference of server by channel
194 		 * needs to be dropped without holding chan_lock
195 		 * as cifs_put_tcp_session takes a higher lock
196 		 * i.e. cifs_tcp_ses_lock
197 		 */
198 		cifs_put_tcp_session(server, from_reconnect);
199 
200 		cifs_signal_cifsd_for_reconnect(server, false);
201 
202 		/* mark primary server as needing reconnect */
203 		pserver = server->primary_server;
204 		cifs_signal_cifsd_for_reconnect(pserver, false);
205 skip_terminate:
206 		return -EHOSTDOWN;
207 	}
208 
209 	cifs_decrease_secondary_channels(ses, disable_mchan);
210 
211 	return 0;
212 }
213 
214 /*
215  * smb3_update_ses_channels - Synchronize session channels with new configuration
216  * @ses: pointer to the CIFS session structure
217  * @server: pointer to the TCP server info structure
218  * @from_reconnect: indicates if called from reconnect context
219  * @disable_mchan: indicates if called from reconnect to disable multichannel
220  *
221  * Returns 0 on success or error code on failure.
222  *
223  * Outside of reconfigure, this function is called from cifs_mount() during mount
224  * and from reconnect scenarios to adjust channel count when the
225  * server's multichannel support changes.
226  */
smb3_update_ses_channels(struct cifs_ses * ses,struct TCP_Server_Info * server,bool from_reconnect,bool disable_mchan)227 int smb3_update_ses_channels(struct cifs_ses *ses, struct TCP_Server_Info *server,
228 			bool from_reconnect, bool disable_mchan)
229 {
230 	int rc = 0;
231 	/*
232 	 * Manage session channels based on current count vs max:
233 	 * - If disable requested, skip or disable the channel
234 	 * - If below max channels, attempt to add more
235 	 * - If above max channels, skip or disable excess channels
236 	 */
237 	if (disable_mchan)
238 		rc = cifs_chan_skip_or_disable(ses, server, from_reconnect, disable_mchan);
239 	else {
240 		if (ses->chan_count < ses->chan_max)
241 			rc = cifs_try_adding_channels(ses);
242 		else if (ses->chan_count > ses->chan_max)
243 			rc = cifs_chan_skip_or_disable(ses, server, from_reconnect, disable_mchan);
244 	}
245 
246 	return rc;
247 }
248 
249 static int
smb2_reconnect(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,bool from_reconnect)250 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
251 	       struct TCP_Server_Info *server, bool from_reconnect)
252 {
253 	struct cifs_ses *ses;
254 	int xid;
255 	int rc = 0;
256 
257 	/*
258 	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
259 	 * check for tcp and smb session status done differently
260 	 * for those three - in the calling routine.
261 	 */
262 	if (tcon == NULL)
263 		return 0;
264 
265 	if (smb2_command == SMB2_TREE_CONNECT)
266 		return 0;
267 
268 	spin_lock(&tcon->tc_lock);
269 	if (tcon->status == TID_EXITING) {
270 		/*
271 		 * only tree disconnect allowed when disconnecting ...
272 		 */
273 		if (smb2_command != SMB2_TREE_DISCONNECT) {
274 			spin_unlock(&tcon->tc_lock);
275 			cifs_tcon_dbg(FYI, "can not send cmd %d while umounting\n",
276 				      smb2_command);
277 			return -ENODEV;
278 		}
279 	}
280 	spin_unlock(&tcon->tc_lock);
281 
282 	ses = tcon->ses;
283 	if (!ses)
284 		return smb_EIO(smb_eio_trace_null_pointers);
285 	spin_lock(&ses->ses_lock);
286 	if (ses->ses_status == SES_EXITING) {
287 		spin_unlock(&ses->ses_lock);
288 		return smb_EIO(smb_eio_trace_sess_exiting);
289 	}
290 	spin_unlock(&ses->ses_lock);
291 	if (!ses->server || !server)
292 		return smb_EIO(smb_eio_trace_null_pointers);
293 
294 	spin_lock(&server->srv_lock);
295 	if (server->tcpStatus == CifsNeedReconnect) {
296 		/*
297 		 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
298 		 * here since they are implicitly done when session drops.
299 		 */
300 		switch (smb2_command) {
301 		/*
302 		 * BB Should we keep oplock break and add flush to exceptions?
303 		 */
304 		case SMB2_TREE_DISCONNECT:
305 		case SMB2_CANCEL:
306 		case SMB2_CLOSE:
307 		case SMB2_OPLOCK_BREAK:
308 			spin_unlock(&server->srv_lock);
309 			return -EAGAIN;
310 		}
311 	}
312 
313 	/* if server is marked for termination, cifsd will cleanup */
314 	if (server->terminate) {
315 		spin_unlock(&server->srv_lock);
316 		return -EHOSTDOWN;
317 	}
318 	spin_unlock(&server->srv_lock);
319 
320 again:
321 	rc = cifs_wait_for_server_reconnect(server, tcon->retry);
322 	if (rc)
323 		return rc;
324 
325 	spin_lock(&ses->chan_lock);
326 	if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
327 		spin_unlock(&ses->chan_lock);
328 		return 0;
329 	}
330 	spin_unlock(&ses->chan_lock);
331 	cifs_tcon_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d\n",
332 		      tcon->ses->chans_need_reconnect,
333 		      tcon->need_reconnect);
334 
335 	mutex_lock(&ses->session_mutex);
336 	/*
337 	 * Handle the case where a concurrent thread failed to negotiate or
338 	 * killed a channel.
339 	 */
340 	spin_lock(&server->srv_lock);
341 	switch (server->tcpStatus) {
342 	case CifsExiting:
343 		spin_unlock(&server->srv_lock);
344 		mutex_unlock(&ses->session_mutex);
345 		return -EHOSTDOWN;
346 	case CifsNeedReconnect:
347 		spin_unlock(&server->srv_lock);
348 		mutex_unlock(&ses->session_mutex);
349 		if (!tcon->retry)
350 			return -EHOSTDOWN;
351 		goto again;
352 	default:
353 		break;
354 	}
355 	spin_unlock(&server->srv_lock);
356 
357 	/*
358 	 * need to prevent multiple threads trying to simultaneously
359 	 * reconnect the same SMB session
360 	 */
361 	spin_lock(&ses->ses_lock);
362 	spin_lock(&ses->chan_lock);
363 	if (!cifs_chan_needs_reconnect(ses, server) &&
364 	    ses->ses_status == SES_GOOD) {
365 		spin_unlock(&ses->chan_lock);
366 		spin_unlock(&ses->ses_lock);
367 		/* this means that we only need to tree connect */
368 		if (tcon->need_reconnect)
369 			goto skip_sess_setup;
370 
371 		mutex_unlock(&ses->session_mutex);
372 		goto out;
373 	}
374 	spin_unlock(&ses->chan_lock);
375 	spin_unlock(&ses->ses_lock);
376 
377 	rc = cifs_negotiate_protocol(0, ses, server);
378 	if (rc) {
379 		mutex_unlock(&ses->session_mutex);
380 		if (!tcon->retry)
381 			return -EHOSTDOWN;
382 		goto again;
383 	}
384 	/*
385 	 * if server stopped supporting multichannel
386 	 * and the first channel reconnected, disable all the others.
387 	 */
388 	if (ses->chan_count > 1 &&
389 	    !(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
390 		rc = smb3_update_ses_channels(ses, server,
391 					       from_reconnect, true /* disable_mchan */);
392 		if (rc) {
393 			mutex_unlock(&ses->session_mutex);
394 			goto out;
395 		}
396 	}
397 
398 	rc = cifs_setup_session(0, ses, server, ses->local_nls);
399 	if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED)) {
400 		/*
401 		 * Try alternate password for next reconnect (key rotation
402 		 * could be enabled on the server e.g.) if an alternate
403 		 * password is available and the current password is expired,
404 		 * but do not swap on non pwd related errors like host down
405 		 */
406 		if (ses->password2)
407 			swap(ses->password2, ses->password);
408 	}
409 	if (rc) {
410 		mutex_unlock(&ses->session_mutex);
411 		if (rc == -EACCES && !tcon->retry)
412 			return -EHOSTDOWN;
413 		goto out;
414 	}
415 
416 skip_sess_setup:
417 	if (!tcon->need_reconnect) {
418 		mutex_unlock(&ses->session_mutex);
419 		goto out;
420 	}
421 	cifs_mark_open_files_invalid(tcon);
422 	if (tcon->use_persistent)
423 		tcon->need_reopen_files = true;
424 
425 	rc = cifs_tree_connect(0, tcon);
426 
427 	cifs_tcon_dbg(FYI, "reconnect tcon rc = %d\n", rc);
428 	if (rc) {
429 		/* If sess reconnected but tcon didn't, something strange ... */
430 		mutex_unlock(&ses->session_mutex);
431 		cifs_tcon_dbg(VFS, "reconnect tcon failed rc = %d\n", rc);
432 		goto out;
433 	}
434 
435 	spin_lock(&ses->ses_lock);
436 	if (ses->flags & CIFS_SES_FLAG_SCALE_CHANNELS) {
437 		spin_unlock(&ses->ses_lock);
438 		mutex_unlock(&ses->session_mutex);
439 		goto skip_add_channels;
440 	}
441 	ses->flags |= CIFS_SES_FLAG_SCALE_CHANNELS;
442 	spin_unlock(&ses->ses_lock);
443 
444 	if (!rc &&
445 	    (server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL) &&
446 	    server->ops->query_server_interfaces) {
447 		/*
448 		 * query server network interfaces, in case they change.
449 		 * Also mark the session as pending this update while the query
450 		 * is in progress. This will be used to avoid calling
451 		 * smb2_reconnect recursively.
452 		 */
453 		ses->flags |= CIFS_SES_FLAGS_PENDING_QUERY_INTERFACES;
454 		xid = get_xid();
455 		rc = server->ops->query_server_interfaces(xid, tcon, false);
456 		free_xid(xid);
457 		ses->flags &= ~CIFS_SES_FLAGS_PENDING_QUERY_INTERFACES;
458 
459 		if (!tcon->ipc && !tcon->dummy)
460 			queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
461 					   (SMB_INTERFACE_POLL_INTERVAL * HZ));
462 
463 		mutex_unlock(&ses->session_mutex);
464 
465 		if (rc == -EOPNOTSUPP && ses->chan_count > 1) {
466 			/*
467 			 * some servers like Azure SMB server do not advertise
468 			 * that multichannel has been disabled with server
469 			 * capabilities, rather return STATUS_NOT_IMPLEMENTED.
470 			 * treat this as server not supporting multichannel
471 			 */
472 
473 			rc = smb3_update_ses_channels(ses, server,
474 						       from_reconnect,
475 						       true /* disable_mchan */);
476 			goto skip_add_channels;
477 		} else if (rc)
478 			cifs_tcon_dbg(FYI, "%s: failed to query server interfaces: %d\n",
479 				      __func__, rc);
480 
481 		if (ses->chan_max > ses->chan_count &&
482 		    ses->iface_count &&
483 		    !SERVER_IS_CHAN(server)) {
484 			if (ses->chan_count == 1)
485 				cifs_server_dbg(VFS, "supports multichannel now\n");
486 
487 			smb3_update_ses_channels(ses, server, from_reconnect,
488 						  false /* disable_mchan */);
489 		}
490 	} else {
491 		mutex_unlock(&ses->session_mutex);
492 	}
493 
494 skip_add_channels:
495 	spin_lock(&ses->ses_lock);
496 	ses->flags &= ~CIFS_SES_FLAG_SCALE_CHANNELS;
497 	spin_unlock(&ses->ses_lock);
498 
499 	if (smb2_command != SMB2_INTERNAL_CMD)
500 		cifs_queue_server_reconn(server);
501 
502 	atomic_inc(&tconInfoReconnectCount);
503 out:
504 	/*
505 	 * Check if handle based operation so we know whether we can continue
506 	 * or not without returning to caller to reset file handle.
507 	 */
508 	/*
509 	 * BB Is flush done by server on drop of tcp session? Should we special
510 	 * case it and skip above?
511 	 */
512 	switch (smb2_command) {
513 	case SMB2_FLUSH:
514 	case SMB2_READ:
515 	case SMB2_WRITE:
516 	case SMB2_LOCK:
517 	case SMB2_QUERY_DIRECTORY:
518 	case SMB2_CHANGE_NOTIFY:
519 	case SMB2_QUERY_INFO:
520 	case SMB2_SET_INFO:
521 	case SMB2_IOCTL:
522 		rc = -EAGAIN;
523 	}
524 	return rc;
525 }
526 
527 static void
fill_small_buf(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void * buf,unsigned int * total_len)528 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
529 	       struct TCP_Server_Info *server,
530 	       void *buf,
531 	       unsigned int *total_len)
532 {
533 	struct smb2_pdu *spdu = buf;
534 	/* lookup word count ie StructureSize from table */
535 	__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
536 
537 	/*
538 	 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
539 	 * largest operations (Create)
540 	 */
541 	memset(buf, 0, 256);
542 
543 	smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
544 	spdu->StructureSize2 = cpu_to_le16(parmsize);
545 
546 	*total_len = parmsize + sizeof(struct smb2_hdr);
547 }
548 
549 /*
550  * Allocate and return pointer to an SMB request hdr, and set basic
551  * SMB information in the SMB header. If the return code is zero, this
552  * function must have filled in request_buf pointer.
553  */
__smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)554 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
555 				 struct TCP_Server_Info *server,
556 				 void **request_buf, unsigned int *total_len)
557 {
558 	/* BB eventually switch this to SMB2 specific small buf size */
559 	switch (smb2_command) {
560 	case SMB2_SET_INFO:
561 	case SMB2_QUERY_INFO:
562 		*request_buf = cifs_buf_get();
563 		break;
564 	default:
565 		*request_buf = cifs_small_buf_get();
566 		break;
567 	}
568 	if (*request_buf == NULL) {
569 		/* BB should we add a retry in here if not a writepage? */
570 		return -ENOMEM;
571 	}
572 
573 	fill_small_buf(smb2_command, tcon, server,
574 		       (struct smb2_hdr *)(*request_buf),
575 		       total_len);
576 
577 	if (tcon != NULL) {
578 		uint16_t com_code = le16_to_cpu(smb2_command);
579 		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
580 		cifs_stats_inc(&tcon->num_smbs_sent);
581 	}
582 
583 	return 0;
584 }
585 
smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)586 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
587 			       struct TCP_Server_Info *server,
588 			       void **request_buf, unsigned int *total_len)
589 {
590 	int rc;
591 
592 	rc = smb2_reconnect(smb2_command, tcon, server, false);
593 	if (rc)
594 		return rc;
595 
596 	return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
597 				     total_len);
598 }
599 
smb2_ioctl_req_init(u32 opcode,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)600 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
601 			       struct TCP_Server_Info *server,
602 			       void **request_buf, unsigned int *total_len)
603 {
604 	/*
605 	 * Skip reconnect in one of the following cases:
606 	 * 1. For FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs
607 	 * 2. For FSCTL_QUERY_NETWORK_INTERFACE_INFO IOCTL when called from
608 	 * smb2_reconnect (indicated by CIFS_SES_FLAG_SCALE_CHANNELS ses flag)
609 	 */
610 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO ||
611 	    (opcode == FSCTL_QUERY_NETWORK_INTERFACE_INFO &&
612 	     (tcon->ses->flags & CIFS_SES_FLAGS_PENDING_QUERY_INTERFACES)))
613 		return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
614 					     request_buf, total_len);
615 
616 	return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
617 				   request_buf, total_len);
618 }
619 
620 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
621 
622 static void
build_preauth_ctxt(struct smb2_preauth_neg_context * pneg_ctxt)623 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
624 {
625 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
626 	pneg_ctxt->DataLength = cpu_to_le16(38);
627 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
628 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
629 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
630 	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
631 }
632 
633 static void
build_compression_ctxt(struct smb2_compression_capabilities_context * pneg_ctxt)634 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
635 {
636 	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
637 	pneg_ctxt->DataLength =
638 		cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
639 			  - sizeof(struct smb2_neg_context));
640 	pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
641 	pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
642 	pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
643 	pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
644 }
645 
646 static unsigned int
build_signing_ctxt(struct smb2_signing_capabilities * pneg_ctxt)647 build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
648 {
649 	unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
650 	unsigned short num_algs = 1; /* number of signing algorithms sent */
651 
652 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
653 	/*
654 	 * Context Data length must be rounded to multiple of 8 for some servers
655 	 */
656 	pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
657 					    sizeof(struct smb2_neg_context) +
658 					    (num_algs * sizeof(u16)), 8));
659 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
660 	pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);
661 
662 	ctxt_len += sizeof(__le16) * num_algs;
663 	ctxt_len = ALIGN(ctxt_len, 8);
664 	return ctxt_len;
665 	/* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
666 }
667 
668 static void
build_encrypt_ctxt(struct smb2_encryption_neg_context * pneg_ctxt)669 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
670 {
671 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
672 	if (require_gcm_256) {
673 		pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
674 		pneg_ctxt->CipherCount = cpu_to_le16(1);
675 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
676 	} else if (enable_gcm_256) {
677 		pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
678 		pneg_ctxt->CipherCount = cpu_to_le16(3);
679 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
680 		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
681 		pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
682 	} else {
683 		pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
684 		pneg_ctxt->CipherCount = cpu_to_le16(2);
685 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
686 		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
687 	}
688 }
689 
690 static unsigned int
build_netname_ctxt(struct smb2_netname_neg_context * pneg_ctxt,char * hostname)691 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
692 {
693 	struct nls_table *cp = load_nls_default();
694 
695 	pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
696 
697 	/* copy up to max of first 100 bytes of server name to NetName field */
698 	pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
699 	/* context size is DataLength + minimal smb2_neg_context */
700 	return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
701 }
702 
703 static void
build_posix_ctxt(struct smb2_posix_neg_context * pneg_ctxt)704 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
705 {
706 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
707 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
708 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
709 	pneg_ctxt->Name[0] = 0x93;
710 	pneg_ctxt->Name[1] = 0xAD;
711 	pneg_ctxt->Name[2] = 0x25;
712 	pneg_ctxt->Name[3] = 0x50;
713 	pneg_ctxt->Name[4] = 0x9C;
714 	pneg_ctxt->Name[5] = 0xB4;
715 	pneg_ctxt->Name[6] = 0x11;
716 	pneg_ctxt->Name[7] = 0xE7;
717 	pneg_ctxt->Name[8] = 0xB4;
718 	pneg_ctxt->Name[9] = 0x23;
719 	pneg_ctxt->Name[10] = 0x83;
720 	pneg_ctxt->Name[11] = 0xDE;
721 	pneg_ctxt->Name[12] = 0x96;
722 	pneg_ctxt->Name[13] = 0x8B;
723 	pneg_ctxt->Name[14] = 0xCD;
724 	pneg_ctxt->Name[15] = 0x7C;
725 }
726 
727 static void
assemble_neg_contexts(struct smb2_negotiate_req * req,struct TCP_Server_Info * server,unsigned int * total_len)728 assemble_neg_contexts(struct smb2_negotiate_req *req,
729 		      struct TCP_Server_Info *server, unsigned int *total_len)
730 {
731 	unsigned int ctxt_len, neg_context_count;
732 	struct TCP_Server_Info *pserver;
733 	char *pneg_ctxt;
734 	char *hostname;
735 
736 	if (*total_len > 200) {
737 		/* In case length corrupted don't want to overrun smb buffer */
738 		cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
739 		return;
740 	}
741 
742 	/*
743 	 * round up total_len of fixed part of SMB3 negotiate request to 8
744 	 * byte boundary before adding negotiate contexts
745 	 */
746 	*total_len = ALIGN(*total_len, 8);
747 
748 	pneg_ctxt = (*total_len) + (char *)req;
749 	req->NegotiateContextOffset = cpu_to_le32(*total_len);
750 
751 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
752 	ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
753 	*total_len += ctxt_len;
754 	pneg_ctxt += ctxt_len;
755 
756 	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
757 	ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
758 	*total_len += ctxt_len;
759 	pneg_ctxt += ctxt_len;
760 
761 	/*
762 	 * secondary channels don't have the hostname field populated
763 	 * use the hostname field in the primary channel instead
764 	 */
765 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
766 	cifs_server_lock(pserver);
767 	hostname = pserver->hostname;
768 	if (hostname && (hostname[0] != 0)) {
769 		ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
770 					      hostname);
771 		*total_len += ctxt_len;
772 		pneg_ctxt += ctxt_len;
773 		neg_context_count = 3;
774 	} else
775 		neg_context_count = 2;
776 	cifs_server_unlock(pserver);
777 
778 	build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
779 	*total_len += sizeof(struct smb2_posix_neg_context);
780 	pneg_ctxt += sizeof(struct smb2_posix_neg_context);
781 	neg_context_count++;
782 
783 	if (server->compression.requested) {
784 		build_compression_ctxt((struct smb2_compression_capabilities_context *)
785 				pneg_ctxt);
786 		ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
787 		*total_len += ctxt_len;
788 		pneg_ctxt += ctxt_len;
789 		neg_context_count++;
790 	}
791 
792 	if (enable_negotiate_signing) {
793 		ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
794 				pneg_ctxt);
795 		*total_len += ctxt_len;
796 		pneg_ctxt += ctxt_len;
797 		neg_context_count++;
798 	}
799 
800 	/* check for and add transport_capabilities and signing capabilities */
801 	req->NegotiateContextCount = cpu_to_le16(neg_context_count);
802 
803 }
804 
805 /* If invalid preauth context warn but use what we requested, SHA-512 */
decode_preauth_context(struct smb2_preauth_neg_context * ctxt)806 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
807 {
808 	unsigned int len = le16_to_cpu(ctxt->DataLength);
809 
810 	/*
811 	 * Caller checked that DataLength remains within SMB boundary. We still
812 	 * need to confirm that one HashAlgorithms member is accounted for.
813 	 */
814 	if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
815 		pr_warn_once("server sent bad preauth context\n");
816 		return;
817 	} else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
818 		pr_warn_once("server sent invalid SaltLength\n");
819 		return;
820 	}
821 	if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
822 		pr_warn_once("Invalid SMB3 hash algorithm count\n");
823 	if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
824 		pr_warn_once("unknown SMB3 hash algorithm\n");
825 }
826 
decode_compress_ctx(struct TCP_Server_Info * server,struct smb2_compression_capabilities_context * ctxt)827 static void decode_compress_ctx(struct TCP_Server_Info *server,
828 			 struct smb2_compression_capabilities_context *ctxt)
829 {
830 	unsigned int len = le16_to_cpu(ctxt->DataLength);
831 	__le16 alg;
832 
833 	server->compression.enabled = false;
834 
835 	/*
836 	 * Caller checked that DataLength remains within SMB boundary. We still
837 	 * need to confirm that one CompressionAlgorithms member is accounted
838 	 * for.
839 	 */
840 	if (len < 10) {
841 		pr_warn_once("server sent bad compression cntxt\n");
842 		return;
843 	}
844 
845 	if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
846 		pr_warn_once("invalid SMB3 compress algorithm count\n");
847 		return;
848 	}
849 
850 	alg = ctxt->CompressionAlgorithms[0];
851 
852 	/* 'NONE' (0) compressor type is never negotiated */
853 	if (alg == 0 || le16_to_cpu(alg) > 3) {
854 		pr_warn_once("invalid compression algorithm '%u'\n", alg);
855 		return;
856 	}
857 
858 	server->compression.alg = alg;
859 	server->compression.enabled = true;
860 }
861 
decode_encrypt_ctx(struct TCP_Server_Info * server,struct smb2_encryption_neg_context * ctxt)862 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
863 			      struct smb2_encryption_neg_context *ctxt)
864 {
865 	unsigned int len = le16_to_cpu(ctxt->DataLength);
866 
867 	cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
868 	/*
869 	 * Caller checked that DataLength remains within SMB boundary. We still
870 	 * need to confirm that one Cipher flexible array member is accounted
871 	 * for.
872 	 */
873 	if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
874 		pr_warn_once("server sent bad crypto ctxt len\n");
875 		return -EINVAL;
876 	}
877 
878 	if (le16_to_cpu(ctxt->CipherCount) != 1) {
879 		pr_warn_once("Invalid SMB3.11 cipher count\n");
880 		return -EINVAL;
881 	}
882 	cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
883 	if (require_gcm_256) {
884 		if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
885 			cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
886 			return -EOPNOTSUPP;
887 		}
888 	} else if (ctxt->Ciphers[0] == 0) {
889 		/*
890 		 * e.g. if server only supported AES256_CCM (very unlikely)
891 		 * or server supported no encryption types or had all disabled.
892 		 * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
893 		 * in which mount requested encryption ("seal") checks later
894 		 * on during tree connection will return proper rc, but if
895 		 * seal not requested by client, since server is allowed to
896 		 * return 0 to indicate no supported cipher, we can't fail here
897 		 */
898 		server->cipher_type = 0;
899 		server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
900 		pr_warn_once("Server does not support requested encryption types\n");
901 		return 0;
902 	} else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
903 		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
904 		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
905 		/* server returned a cipher we didn't ask for */
906 		pr_warn_once("Invalid SMB3.11 cipher returned\n");
907 		return -EINVAL;
908 	}
909 	server->cipher_type = ctxt->Ciphers[0];
910 	server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
911 	return 0;
912 }
913 
decode_signing_ctx(struct TCP_Server_Info * server,struct smb2_signing_capabilities * pctxt)914 static void decode_signing_ctx(struct TCP_Server_Info *server,
915 			       struct smb2_signing_capabilities *pctxt)
916 {
917 	unsigned int len = le16_to_cpu(pctxt->DataLength);
918 
919 	/*
920 	 * Caller checked that DataLength remains within SMB boundary. We still
921 	 * need to confirm that one SigningAlgorithms flexible array member is
922 	 * accounted for.
923 	 */
924 	if ((len < 4) || (len > 16)) {
925 		pr_warn_once("server sent bad signing negcontext\n");
926 		return;
927 	}
928 	if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
929 		pr_warn_once("Invalid signing algorithm count\n");
930 		return;
931 	}
932 	if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
933 		pr_warn_once("unknown signing algorithm\n");
934 		return;
935 	}
936 
937 	server->signing_negotiated = true;
938 	server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
939 	cifs_dbg(FYI, "signing algorithm %d chosen\n",
940 		     server->signing_algorithm);
941 }
942 
943 
smb311_decode_neg_context(struct smb2_negotiate_rsp * rsp,struct TCP_Server_Info * server,unsigned int len_of_smb)944 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
945 				     struct TCP_Server_Info *server,
946 				     unsigned int len_of_smb)
947 {
948 	struct smb2_neg_context *pctx;
949 	unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
950 	unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
951 	unsigned int len_of_ctxts, i;
952 	int rc = 0;
953 
954 	cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
955 	if (len_of_smb <= offset) {
956 		cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
957 		return -EINVAL;
958 	}
959 
960 	len_of_ctxts = len_of_smb - offset;
961 
962 	for (i = 0; i < ctxt_cnt; i++) {
963 		int clen;
964 		/* check that offset is not beyond end of SMB */
965 		if (len_of_ctxts < sizeof(struct smb2_neg_context))
966 			break;
967 
968 		pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
969 		clen = sizeof(struct smb2_neg_context)
970 			+ le16_to_cpu(pctx->DataLength);
971 		/*
972 		 * 2.2.4 SMB2 NEGOTIATE Response
973 		 * Subsequent negotiate contexts MUST appear at the first 8-byte
974 		 * aligned offset following the previous negotiate context.
975 		 */
976 		if (i + 1 != ctxt_cnt)
977 			clen = ALIGN(clen, 8);
978 		if (clen > len_of_ctxts)
979 			break;
980 
981 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
982 			decode_preauth_context(
983 				(struct smb2_preauth_neg_context *)pctx);
984 		else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
985 			rc = decode_encrypt_ctx(server,
986 				(struct smb2_encryption_neg_context *)pctx);
987 		else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
988 			decode_compress_ctx(server,
989 				(struct smb2_compression_capabilities_context *)pctx);
990 		else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
991 			server->posix_ext_supported = true;
992 		else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
993 			decode_signing_ctx(server,
994 				(struct smb2_signing_capabilities *)pctx);
995 		else
996 			cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
997 				le16_to_cpu(pctx->ContextType));
998 		if (rc)
999 			break;
1000 
1001 		offset += clen;
1002 		len_of_ctxts -= clen;
1003 	}
1004 	return rc;
1005 }
1006 
1007 static struct create_posix *
create_posix_buf(umode_t mode)1008 create_posix_buf(umode_t mode)
1009 {
1010 	struct create_posix *buf;
1011 
1012 	buf = kzalloc_obj(struct create_posix);
1013 	if (!buf)
1014 		return NULL;
1015 
1016 	buf->ccontext.DataOffset =
1017 		cpu_to_le16(offsetof(struct create_posix, Mode));
1018 	buf->ccontext.DataLength = cpu_to_le32(4);
1019 	buf->ccontext.NameOffset =
1020 		cpu_to_le16(offsetof(struct create_posix, Name));
1021 	buf->ccontext.NameLength = cpu_to_le16(16);
1022 
1023 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
1024 	buf->Name[0] = 0x93;
1025 	buf->Name[1] = 0xAD;
1026 	buf->Name[2] = 0x25;
1027 	buf->Name[3] = 0x50;
1028 	buf->Name[4] = 0x9C;
1029 	buf->Name[5] = 0xB4;
1030 	buf->Name[6] = 0x11;
1031 	buf->Name[7] = 0xE7;
1032 	buf->Name[8] = 0xB4;
1033 	buf->Name[9] = 0x23;
1034 	buf->Name[10] = 0x83;
1035 	buf->Name[11] = 0xDE;
1036 	buf->Name[12] = 0x96;
1037 	buf->Name[13] = 0x8B;
1038 	buf->Name[14] = 0xCD;
1039 	buf->Name[15] = 0x7C;
1040 	buf->Mode = cpu_to_le32(mode);
1041 	cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
1042 	return buf;
1043 }
1044 
1045 static int
add_posix_context(struct kvec * iov,unsigned int * num_iovec,umode_t mode)1046 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
1047 {
1048 	unsigned int num = *num_iovec;
1049 
1050 	iov[num].iov_base = create_posix_buf(mode);
1051 	if (mode == ACL_NO_MODE)
1052 		cifs_dbg(FYI, "%s: no mode\n", __func__);
1053 	if (iov[num].iov_base == NULL)
1054 		return -ENOMEM;
1055 	iov[num].iov_len = sizeof(struct create_posix);
1056 	*num_iovec = num + 1;
1057 	return 0;
1058 }
1059 
1060 
1061 /*
1062  *
1063  *	SMB2 Worker functions follow:
1064  *
1065  *	The general structure of the worker functions is:
1066  *	1) Call smb2_init (assembles SMB2 header)
1067  *	2) Initialize SMB2 command specific fields in fixed length area of SMB
1068  *	3) Call smb_sendrcv2 (sends request on socket and waits for response)
1069  *	4) Decode SMB2 command specific fields in the fixed length area
1070  *	5) Decode variable length data area (if any for this SMB2 command type)
1071  *	6) Call free smb buffer
1072  *	7) return
1073  *
1074  */
1075 
1076 int
SMB2_negotiate(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server)1077 SMB2_negotiate(const unsigned int xid,
1078 	       struct cifs_ses *ses,
1079 	       struct TCP_Server_Info *server)
1080 {
1081 	struct smb_rqst rqst;
1082 	struct smb2_negotiate_req *req;
1083 	struct smb2_negotiate_rsp *rsp;
1084 	struct kvec iov[1];
1085 	struct kvec rsp_iov;
1086 	int rc;
1087 	int resp_buftype;
1088 	int blob_offset, blob_length;
1089 	char *security_blob;
1090 	int flags = CIFS_NEG_OP;
1091 	unsigned int total_len;
1092 
1093 	cifs_dbg(FYI, "Negotiate protocol\n");
1094 
1095 	if (!server) {
1096 		WARN(1, "%s: server is NULL!\n", __func__);
1097 		return smb_EIO(smb_eio_trace_null_pointers);
1098 	}
1099 
1100 	rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
1101 				 (void **) &req, &total_len);
1102 	if (rc)
1103 		return rc;
1104 
1105 	req->hdr.SessionId = 0;
1106 
1107 	memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1108 	memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1109 
1110 	if (strcmp(server->vals->version_string,
1111 		   SMB3ANY_VERSION_STRING) == 0) {
1112 		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1113 		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1114 		req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1115 		req->DialectCount = cpu_to_le16(3);
1116 		total_len += 6;
1117 	} else if (strcmp(server->vals->version_string,
1118 		   SMBDEFAULT_VERSION_STRING) == 0) {
1119 		req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1120 		req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1121 		req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1122 		req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1123 		req->DialectCount = cpu_to_le16(4);
1124 		total_len += 8;
1125 	} else {
1126 		/* otherwise send specific dialect */
1127 		req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
1128 		req->DialectCount = cpu_to_le16(1);
1129 		total_len += 2;
1130 	}
1131 
1132 	/* only one of SMB2 signing flags may be set in SMB2 request */
1133 	if (ses->sign)
1134 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1135 	else if (global_secflags & CIFSSEC_MAY_SIGN)
1136 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1137 	else
1138 		req->SecurityMode = 0;
1139 
1140 	req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
1141 	req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1142 
1143 	/* ClientGUID must be zero for SMB2.02 dialect */
1144 	if (server->vals->protocol_id == SMB20_PROT_ID)
1145 		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
1146 	else {
1147 		memcpy(req->ClientGUID, server->client_guid,
1148 			SMB2_CLIENT_GUID_SIZE);
1149 		if ((server->vals->protocol_id == SMB311_PROT_ID) ||
1150 		    (strcmp(server->vals->version_string,
1151 		     SMB3ANY_VERSION_STRING) == 0) ||
1152 		    (strcmp(server->vals->version_string,
1153 		     SMBDEFAULT_VERSION_STRING) == 0))
1154 			assemble_neg_contexts(req, server, &total_len);
1155 	}
1156 	iov[0].iov_base = (char *)req;
1157 	iov[0].iov_len = total_len;
1158 
1159 	memset(&rqst, 0, sizeof(struct smb_rqst));
1160 	rqst.rq_iov = iov;
1161 	rqst.rq_nvec = 1;
1162 
1163 	rc = cifs_send_recv(xid, ses, server,
1164 			    &rqst, &resp_buftype, flags, &rsp_iov);
1165 	cifs_small_buf_release(req);
1166 	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
1167 	/*
1168 	 * No tcon so can't do
1169 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1170 	 */
1171 	if (rc == -EOPNOTSUPP) {
1172 		cifs_server_dbg(VFS, "Dialect not supported by server. Consider  specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
1173 		goto neg_exit;
1174 	} else if (rc != 0)
1175 		goto neg_exit;
1176 
1177 	u16 dialect = le16_to_cpu(rsp->DialectRevision);
1178 	if (strcmp(server->vals->version_string,
1179 		   SMB3ANY_VERSION_STRING) == 0) {
1180 		switch (dialect) {
1181 		case SMB20_PROT_ID:
1182 			cifs_server_dbg(VFS,
1183 				"SMB2 dialect returned but not requested\n");
1184 			rc = smb_EIO2(smb_eio_trace_neg_unreq_dialect, dialect, 3);
1185 			goto neg_exit;
1186 		case SMB21_PROT_ID:
1187 			cifs_server_dbg(VFS,
1188 				"SMB2.1 dialect returned but not requested\n");
1189 			rc = smb_EIO2(smb_eio_trace_neg_unreq_dialect, dialect, 3);
1190 			goto neg_exit;
1191 		case SMB311_PROT_ID:
1192 			/* ops set to 3.0 by default for default so update */
1193 			server->ops = &smb311_operations;
1194 			server->vals = &smb311_values;
1195 			break;
1196 		default:
1197 			break;
1198 		}
1199 	} else if (strcmp(server->vals->version_string,
1200 			  SMBDEFAULT_VERSION_STRING) == 0) {
1201 		switch (dialect) {
1202 		case SMB20_PROT_ID:
1203 			cifs_server_dbg(VFS,
1204 				"SMB2 dialect returned but not requested\n");
1205 			rc = smb_EIO2(smb_eio_trace_neg_unreq_dialect, dialect, 0);
1206 			goto neg_exit;
1207 		case SMB21_PROT_ID:
1208 			/* ops set to 3.0 by default for default so update */
1209 			server->ops = &smb21_operations;
1210 			server->vals = &smb21_values;
1211 			break;
1212 		case SMB311_PROT_ID:
1213 			server->ops = &smb311_operations;
1214 			server->vals = &smb311_values;
1215 			break;
1216 		default:
1217 			break;
1218 		}
1219 	} else if (dialect != server->vals->protocol_id) {
1220 		/* if requested single dialect ensure returned dialect matched */
1221 		cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
1222 				dialect);
1223 		rc = smb_EIO2(smb_eio_trace_neg_unreq_dialect,
1224 			      dialect, server->vals->protocol_id);
1225 		goto neg_exit;
1226 	}
1227 
1228 	cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1229 
1230 	switch (dialect) {
1231 	case SMB20_PROT_ID:
1232 		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1233 		break;
1234 	case SMB21_PROT_ID:
1235 		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1236 		break;
1237 	case SMB30_PROT_ID:
1238 		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
1239 		break;
1240 	case SMB302_PROT_ID:
1241 		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1242 		break;
1243 	case SMB311_PROT_ID:
1244 		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1245 		break;
1246 	default:
1247 		cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
1248 				dialect);
1249 		rc = smb_EIO1(smb_eio_trace_neg_inval_dialect, dialect);
1250 		goto neg_exit;
1251 	}
1252 
1253 	rc = 0;
1254 	server->dialect = dialect;
1255 
1256 	/*
1257 	 * Keep a copy of the hash after negprot. This hash will be
1258 	 * the starting hash value for all sessions made from this
1259 	 * server.
1260 	 */
1261 	memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
1262 	       SMB2_PREAUTH_HASH_SIZE);
1263 
1264 	/* SMB2 only has an extended negflavor */
1265 	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1266 	/* set it to the maximum buffer size value we can send with 1 credit */
1267 	server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
1268 			       SMB2_MAX_BUFFER_SIZE);
1269 	server->max_read = le32_to_cpu(rsp->MaxReadSize);
1270 	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
1271 	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1272 	if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
1273 		cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
1274 				server->sec_mode);
1275 	server->capabilities = le32_to_cpu(rsp->Capabilities);
1276 	/* Internal types */
1277 	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1278 
1279 	/*
1280 	 * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
1281 	 * Set the cipher type manually.
1282 	 */
1283 	if ((server->dialect == SMB30_PROT_ID ||
1284 	     server->dialect == SMB302_PROT_ID) &&
1285 	    (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1286 		server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
1287 
1288 	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1289 					       (struct smb2_hdr *)rsp);
1290 	/*
1291 	 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
1292 	 * for us will be
1293 	 *	ses->sectype = RawNTLMSSP;
1294 	 * but for time being this is our only auth choice so doesn't matter.
1295 	 * We just found a server which sets blob length to zero expecting raw.
1296 	 */
1297 	if (blob_length == 0) {
1298 		cifs_dbg(FYI, "missing security blob on negprot\n");
1299 		server->sec_ntlmssp = true;
1300 	}
1301 
1302 	rc = cifs_enable_signing(server, ses->sign);
1303 	if (rc)
1304 		goto neg_exit;
1305 	if (blob_length) {
1306 		rc = decode_negTokenInit(security_blob, blob_length, server);
1307 		if (rc == 1)
1308 			rc = 0;
1309 		else if (rc == 0)
1310 			rc = smb_EIO1(smb_eio_trace_neg_decode_token, rc);
1311 	}
1312 
1313 	if (server->dialect == SMB311_PROT_ID) {
1314 		if (rsp->NegotiateContextCount)
1315 			rc = smb311_decode_neg_context(rsp, server,
1316 						       rsp_iov.iov_len);
1317 		else
1318 			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1319 	}
1320 
1321 	if (server->cipher_type && !rc)
1322 		rc = smb3_crypto_aead_allocate(server);
1323 neg_exit:
1324 	free_rsp_buf(resp_buftype, rsp);
1325 	return rc;
1326 }
1327 
smb3_validate_negotiate(const unsigned int xid,struct cifs_tcon * tcon)1328 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1329 {
1330 	int rc;
1331 	struct validate_negotiate_info_req *pneg_inbuf;
1332 	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1333 	u32 rsplen;
1334 	u32 inbuflen; /* max of 4 dialects */
1335 	struct TCP_Server_Info *server = tcon->ses->server;
1336 
1337 	cifs_dbg(FYI, "validate negotiate\n");
1338 
1339 	/* In SMB3.11 preauth integrity supersedes validate negotiate */
1340 	if (server->dialect == SMB311_PROT_ID)
1341 		return 0;
1342 
1343 	/*
1344 	 * validation ioctl must be signed, so no point sending this if we
1345 	 * can not sign it (ie are not known user).  Even if signing is not
1346 	 * required (enabled but not negotiated), in those cases we selectively
1347 	 * sign just this, the first and only signed request on a connection.
1348 	 * Having validation of negotiate info  helps reduce attack vectors.
1349 	 */
1350 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1351 		return 0; /* validation requires signing */
1352 
1353 	if (tcon->ses->user_name == NULL) {
1354 		cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1355 		return 0; /* validation requires signing */
1356 	}
1357 
1358 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1359 		cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1360 
1361 	pneg_inbuf = kmalloc_obj(*pneg_inbuf, GFP_NOFS);
1362 	if (!pneg_inbuf)
1363 		return -ENOMEM;
1364 
1365 	pneg_inbuf->Capabilities =
1366 			cpu_to_le32(server->vals->req_capabilities);
1367 	pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1368 
1369 	memcpy(pneg_inbuf->Guid, server->client_guid,
1370 					SMB2_CLIENT_GUID_SIZE);
1371 
1372 	if (tcon->ses->sign)
1373 		pneg_inbuf->SecurityMode =
1374 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1375 	else if (global_secflags & CIFSSEC_MAY_SIGN)
1376 		pneg_inbuf->SecurityMode =
1377 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1378 	else
1379 		pneg_inbuf->SecurityMode = 0;
1380 
1381 
1382 	if (strcmp(server->vals->version_string,
1383 		SMB3ANY_VERSION_STRING) == 0) {
1384 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1385 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1386 		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1387 		pneg_inbuf->DialectCount = cpu_to_le16(3);
1388 		/* SMB 2.1 not included so subtract one dialect from len */
1389 		inbuflen = sizeof(*pneg_inbuf) -
1390 				(sizeof(pneg_inbuf->Dialects[0]));
1391 	} else if (strcmp(server->vals->version_string,
1392 		SMBDEFAULT_VERSION_STRING) == 0) {
1393 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1394 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1395 		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1396 		pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1397 		pneg_inbuf->DialectCount = cpu_to_le16(4);
1398 		/* structure is big enough for 4 dialects */
1399 		inbuflen = sizeof(*pneg_inbuf);
1400 	} else {
1401 		/* otherwise specific dialect was requested */
1402 		pneg_inbuf->Dialects[0] =
1403 			cpu_to_le16(server->vals->protocol_id);
1404 		pneg_inbuf->DialectCount = cpu_to_le16(1);
1405 		/* structure is big enough for 4 dialects, sending only 1 */
1406 		inbuflen = sizeof(*pneg_inbuf) -
1407 				sizeof(pneg_inbuf->Dialects[0]) * 3;
1408 	}
1409 
1410 	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1411 		FSCTL_VALIDATE_NEGOTIATE_INFO,
1412 		(char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1413 		(char **)&pneg_rsp, &rsplen);
1414 	if (rc == -EOPNOTSUPP) {
1415 		/*
1416 		 * Old Windows versions or Netapp SMB server can return
1417 		 * not supported error. Client should accept it.
1418 		 */
1419 		cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1420 		rc = 0;
1421 		goto out_free_inbuf;
1422 	} else if (rc != 0) {
1423 		cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1424 			      rc);
1425 		rc = smb_EIO1(smb_eio_trace_neg_info_fail, rc);
1426 		goto out_free_inbuf;
1427 	}
1428 
1429 	if (rsplen != sizeof(*pneg_rsp)) {
1430 		cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1431 			      rsplen);
1432 
1433 		/* relax check since Mac returns max bufsize allowed on ioctl */
1434 		if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp)) {
1435 			rc = smb_EIO1(smb_eio_trace_neg_bad_rsplen, rsplen);
1436 			goto out_free_rsp;
1437 		}
1438 	}
1439 
1440 	/* check validate negotiate info response matches what we got earlier */
1441 	u16 dialect = le16_to_cpu(pneg_rsp->Dialect);
1442 
1443 	if (dialect != server->dialect) {
1444 		rc = smb_EIO2(smb_eio_trace_neg_info_dialect,
1445 			      dialect, server->dialect);
1446 		goto vneg_out;
1447 	}
1448 
1449 	u16 sec_mode = le16_to_cpu(pneg_rsp->SecurityMode);
1450 
1451 	if (sec_mode != server->sec_mode) {
1452 		rc = smb_EIO2(smb_eio_trace_neg_info_sec_mode,
1453 			      sec_mode, server->sec_mode);
1454 		goto vneg_out;
1455 	}
1456 
1457 	/* do not validate server guid because not saved at negprot time yet */
1458 	u32 caps = le32_to_cpu(pneg_rsp->Capabilities);
1459 
1460 	if ((caps | SMB2_NT_FIND |
1461 	     SMB2_LARGE_FILES) != server->capabilities) {
1462 		rc = smb_EIO2(smb_eio_trace_neg_info_caps,
1463 			      caps, server->capabilities);
1464 		goto vneg_out;
1465 	}
1466 
1467 	/* validate negotiate successful */
1468 	rc = 0;
1469 	cifs_dbg(FYI, "validate negotiate info successful\n");
1470 	goto out_free_rsp;
1471 
1472 vneg_out:
1473 	cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1474 out_free_rsp:
1475 	kfree(pneg_rsp);
1476 out_free_inbuf:
1477 	kfree(pneg_inbuf);
1478 	return rc;
1479 }
1480 
1481 enum securityEnum
smb2_select_sectype(struct TCP_Server_Info * server,enum securityEnum requested)1482 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1483 {
1484 	switch (requested) {
1485 	case Kerberos:
1486 	case RawNTLMSSP:
1487 		return requested;
1488 	case NTLMv2:
1489 		return RawNTLMSSP;
1490 	case Unspecified:
1491 		if (server->sec_ntlmssp &&
1492 			(global_secflags & CIFSSEC_MAY_NTLMSSP))
1493 			return RawNTLMSSP;
1494 		if ((server->sec_kerberos || server->sec_mskerberos || server->sec_iakerb) &&
1495 			(global_secflags & CIFSSEC_MAY_KRB5))
1496 			return Kerberos;
1497 		fallthrough;
1498 	default:
1499 		return Unspecified;
1500 	}
1501 }
1502 
1503 struct SMB2_sess_data {
1504 	unsigned int xid;
1505 	struct cifs_ses *ses;
1506 	struct TCP_Server_Info *server;
1507 	struct nls_table *nls_cp;
1508 	void (*func)(struct SMB2_sess_data *);
1509 	int result;
1510 	u64 previous_session;
1511 
1512 	/* we will send the SMB in three pieces:
1513 	 * a fixed length beginning part, an optional
1514 	 * SPNEGO blob (which can be zero length), and a
1515 	 * last part which will include the strings
1516 	 * and rest of bcc area. This allows us to avoid
1517 	 * a large buffer 17K allocation
1518 	 */
1519 	int buf0_type;
1520 	struct kvec iov[2];
1521 };
1522 
1523 static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data * sess_data)1524 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1525 {
1526 	int rc;
1527 	struct cifs_ses *ses = sess_data->ses;
1528 	struct TCP_Server_Info *server = sess_data->server;
1529 	struct smb2_sess_setup_req *req;
1530 	unsigned int total_len;
1531 	bool is_binding = false;
1532 
1533 	rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1534 				 (void **) &req,
1535 				 &total_len);
1536 	if (rc)
1537 		return rc;
1538 
1539 	spin_lock(&ses->ses_lock);
1540 	is_binding = (ses->ses_status == SES_GOOD);
1541 	spin_unlock(&ses->ses_lock);
1542 
1543 	if (is_binding) {
1544 		req->hdr.SessionId = cpu_to_le64(ses->Suid);
1545 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1546 		req->PreviousSessionId = 0;
1547 		req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1548 		cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1549 	} else {
1550 		/* First session, not a reauthenticate */
1551 		req->hdr.SessionId = 0;
1552 		/*
1553 		 * if reconnect, we need to send previous sess id
1554 		 * otherwise it is 0
1555 		 */
1556 		req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1557 		req->Flags = 0; /* MBZ */
1558 		cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
1559 			 sess_data->previous_session);
1560 	}
1561 
1562 	/* enough to enable echos and oplocks and one max size write */
1563 	if (server->credits >= server->max_credits)
1564 		req->hdr.CreditRequest = cpu_to_le16(0);
1565 	else
1566 		req->hdr.CreditRequest = cpu_to_le16(
1567 			min_t(int, server->max_credits -
1568 			      server->credits, 130));
1569 
1570 	/* only one of SMB2 signing flags may be set in SMB2 request */
1571 	if (server->sign)
1572 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1573 	else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1574 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1575 	else
1576 		req->SecurityMode = 0;
1577 
1578 #ifdef CONFIG_CIFS_DFS_UPCALL
1579 	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1580 #else
1581 	req->Capabilities = 0;
1582 #endif /* DFS_UPCALL */
1583 
1584 	req->Channel = 0; /* MBZ */
1585 
1586 	sess_data->iov[0].iov_base = (char *)req;
1587 	/* 1 for pad */
1588 	sess_data->iov[0].iov_len = total_len - 1;
1589 	/*
1590 	 * This variable will be used to clear the buffer
1591 	 * allocated above in case of any error in the calling function.
1592 	 */
1593 	sess_data->buf0_type = CIFS_SMALL_BUFFER;
1594 
1595 	return 0;
1596 }
1597 
1598 static void
SMB2_sess_free_buffer(struct SMB2_sess_data * sess_data)1599 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1600 {
1601 	struct kvec *iov = sess_data->iov;
1602 
1603 	/* iov[1] is already freed by caller */
1604 	if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1605 		memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1606 
1607 	free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1608 	sess_data->buf0_type = CIFS_NO_BUFFER;
1609 }
1610 
1611 static int
SMB2_sess_sendreceive(struct SMB2_sess_data * sess_data)1612 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1613 {
1614 	int rc;
1615 	struct smb_rqst rqst;
1616 	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1617 	struct kvec rsp_iov = { NULL, 0 };
1618 
1619 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1620 	req->SecurityBufferOffset =
1621 		cpu_to_le16(sizeof(struct smb2_sess_setup_req));
1622 	req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1623 
1624 	memset(&rqst, 0, sizeof(struct smb_rqst));
1625 	rqst.rq_iov = sess_data->iov;
1626 	rqst.rq_nvec = 2;
1627 
1628 	/* BB add code to build os and lm fields */
1629 	rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1630 			    sess_data->server,
1631 			    &rqst,
1632 			    &sess_data->buf0_type,
1633 			    CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1634 	cifs_small_buf_release(sess_data->iov[0].iov_base);
1635 	if (rc == 0)
1636 		sess_data->ses->expired_pwd = false;
1637 	else if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED)) {
1638 		if (sess_data->ses->expired_pwd == false)
1639 			trace_smb3_key_expired(sess_data->server->hostname,
1640 					       sess_data->ses->user_name,
1641 					       sess_data->server->conn_id,
1642 					       &sess_data->server->dstaddr, rc);
1643 		sess_data->ses->expired_pwd = true;
1644 	}
1645 
1646 	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1647 
1648 	return rc;
1649 }
1650 
1651 static int
SMB2_sess_establish_session(struct SMB2_sess_data * sess_data)1652 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1653 {
1654 	int rc = 0;
1655 	struct cifs_ses *ses = sess_data->ses;
1656 	struct TCP_Server_Info *server = sess_data->server;
1657 
1658 	cifs_server_lock(server);
1659 	if (server->ops->generate_signingkey) {
1660 		rc = server->ops->generate_signingkey(ses, server);
1661 		if (rc) {
1662 			cifs_dbg(FYI,
1663 				"SMB3 session key generation failed\n");
1664 			cifs_server_unlock(server);
1665 			return rc;
1666 		}
1667 	}
1668 	if (!server->session_estab) {
1669 		server->sequence_number = 0x2;
1670 		server->session_estab = true;
1671 	}
1672 	cifs_server_unlock(server);
1673 
1674 	cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1675 	return rc;
1676 }
1677 
1678 #ifdef CONFIG_CIFS_UPCALL
1679 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1680 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1681 {
1682 	int rc;
1683 	struct cifs_ses *ses = sess_data->ses;
1684 	struct TCP_Server_Info *server = sess_data->server;
1685 	struct cifs_spnego_msg *msg;
1686 	struct key *spnego_key = NULL;
1687 	struct smb2_sess_setup_rsp *rsp = NULL;
1688 	bool is_binding = false;
1689 
1690 	rc = SMB2_sess_alloc_buffer(sess_data);
1691 	if (rc)
1692 		goto out;
1693 
1694 	spnego_key = cifs_get_spnego_key(ses, server);
1695 	if (IS_ERR(spnego_key)) {
1696 		rc = PTR_ERR(spnego_key);
1697 		spnego_key = NULL;
1698 		goto out;
1699 	}
1700 
1701 	msg = spnego_key->payload.data[0];
1702 	/*
1703 	 * check version field to make sure that cifs.upcall is
1704 	 * sending us a response in an expected form
1705 	 */
1706 	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1707 		cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1708 			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1709 		rc = -EKEYREJECTED;
1710 		goto out_put_spnego_key;
1711 	}
1712 
1713 	spin_lock(&ses->ses_lock);
1714 	is_binding = (ses->ses_status == SES_GOOD);
1715 	spin_unlock(&ses->ses_lock);
1716 
1717 	/* keep session key if binding */
1718 	if (!is_binding) {
1719 		kfree_sensitive(ses->auth_key.response);
1720 		ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1721 						 GFP_KERNEL);
1722 		if (!ses->auth_key.response) {
1723 			cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1724 				 msg->sesskey_len);
1725 			rc = -ENOMEM;
1726 			goto out_put_spnego_key;
1727 		}
1728 		ses->auth_key.len = msg->sesskey_len;
1729 	}
1730 
1731 	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1732 	sess_data->iov[1].iov_len = msg->secblob_len;
1733 
1734 	rc = SMB2_sess_sendreceive(sess_data);
1735 	if (rc)
1736 		goto out_put_spnego_key;
1737 
1738 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1739 	/* keep session id and flags if binding */
1740 	if (!is_binding) {
1741 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1742 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1743 	}
1744 
1745 	rc = SMB2_sess_establish_session(sess_data);
1746 out_put_spnego_key:
1747 	key_invalidate(spnego_key);
1748 	key_put(spnego_key);
1749 	if (rc) {
1750 		kfree_sensitive(ses->auth_key.response);
1751 		ses->auth_key.response = NULL;
1752 		ses->auth_key.len = 0;
1753 	}
1754 out:
1755 	sess_data->result = rc;
1756 	sess_data->func = NULL;
1757 	SMB2_sess_free_buffer(sess_data);
1758 }
1759 #else
1760 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1761 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1762 {
1763 	cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1764 	sess_data->result = -EOPNOTSUPP;
1765 	sess_data->func = NULL;
1766 }
1767 #endif
1768 
1769 static void
1770 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1771 
1772 static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data * sess_data)1773 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1774 {
1775 	int rc;
1776 	struct cifs_ses *ses = sess_data->ses;
1777 	struct TCP_Server_Info *server = sess_data->server;
1778 	struct smb2_sess_setup_rsp *rsp = NULL;
1779 	unsigned char *ntlmssp_blob = NULL;
1780 	bool use_spnego = false; /* else use raw ntlmssp */
1781 	u16 blob_length = 0;
1782 	bool is_binding = false;
1783 
1784 	/*
1785 	 * If memory allocation is successful, caller of this function
1786 	 * frees it.
1787 	 */
1788 	ses->ntlmssp = kmalloc_obj(struct ntlmssp_auth);
1789 	if (!ses->ntlmssp) {
1790 		rc = -ENOMEM;
1791 		goto out_err;
1792 	}
1793 	ses->ntlmssp->sesskey_per_smbsess = true;
1794 
1795 	rc = SMB2_sess_alloc_buffer(sess_data);
1796 	if (rc)
1797 		goto out_err;
1798 
1799 	rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1800 					  &blob_length, ses, server,
1801 					  sess_data->nls_cp);
1802 	if (rc)
1803 		goto out;
1804 
1805 	if (use_spnego) {
1806 		/* BB eventually need to add this */
1807 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1808 		rc = -EOPNOTSUPP;
1809 		goto out;
1810 	}
1811 	sess_data->iov[1].iov_base = ntlmssp_blob;
1812 	sess_data->iov[1].iov_len = blob_length;
1813 
1814 	rc = SMB2_sess_sendreceive(sess_data);
1815 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1816 
1817 	/* If true, rc here is expected and not an error */
1818 	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1819 		rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1820 		rc = 0;
1821 
1822 	if (rc)
1823 		goto out;
1824 
1825 	u16 boff = le16_to_cpu(rsp->SecurityBufferOffset);
1826 
1827 	if (offsetof(struct smb2_sess_setup_rsp, Buffer) != boff) {
1828 		cifs_dbg(VFS, "Invalid security buffer offset %d\n", boff);
1829 		rc = smb_EIO1(smb_eio_trace_sess_buf_off, boff);
1830 		goto out;
1831 	}
1832 	rc = decode_ntlmssp_challenge(rsp->Buffer,
1833 			le16_to_cpu(rsp->SecurityBufferLength), ses);
1834 	if (rc)
1835 		goto out;
1836 
1837 	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1838 
1839 	spin_lock(&ses->ses_lock);
1840 	is_binding = (ses->ses_status == SES_GOOD);
1841 	spin_unlock(&ses->ses_lock);
1842 
1843 	/* keep existing ses id and flags if binding */
1844 	if (!is_binding) {
1845 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1846 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1847 	}
1848 
1849 out:
1850 	kfree_sensitive(ntlmssp_blob);
1851 	SMB2_sess_free_buffer(sess_data);
1852 	if (!rc) {
1853 		sess_data->result = 0;
1854 		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1855 		return;
1856 	}
1857 out_err:
1858 	kfree_sensitive(ses->ntlmssp);
1859 	ses->ntlmssp = NULL;
1860 	sess_data->result = rc;
1861 	sess_data->func = NULL;
1862 }
1863 
1864 static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data * sess_data)1865 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1866 {
1867 	int rc;
1868 	struct cifs_ses *ses = sess_data->ses;
1869 	struct TCP_Server_Info *server = sess_data->server;
1870 	struct smb2_sess_setup_req *req;
1871 	struct smb2_sess_setup_rsp *rsp = NULL;
1872 	unsigned char *ntlmssp_blob = NULL;
1873 	bool use_spnego = false; /* else use raw ntlmssp */
1874 	u16 blob_length = 0;
1875 	bool is_binding = false;
1876 
1877 	rc = SMB2_sess_alloc_buffer(sess_data);
1878 	if (rc)
1879 		goto out;
1880 
1881 	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1882 	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1883 
1884 	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
1885 				     ses, server,
1886 				     sess_data->nls_cp);
1887 	if (rc) {
1888 		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1889 		goto out;
1890 	}
1891 
1892 	if (use_spnego) {
1893 		/* BB eventually need to add this */
1894 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1895 		rc = -EOPNOTSUPP;
1896 		goto out;
1897 	}
1898 	sess_data->iov[1].iov_base = ntlmssp_blob;
1899 	sess_data->iov[1].iov_len = blob_length;
1900 
1901 	rc = SMB2_sess_sendreceive(sess_data);
1902 	if (rc)
1903 		goto out;
1904 
1905 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1906 
1907 	spin_lock(&ses->ses_lock);
1908 	is_binding = (ses->ses_status == SES_GOOD);
1909 	spin_unlock(&ses->ses_lock);
1910 
1911 	/* keep existing ses id and flags if binding */
1912 	if (!is_binding) {
1913 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1914 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1915 	}
1916 
1917 	rc = SMB2_sess_establish_session(sess_data);
1918 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1919 	if (ses->server->dialect < SMB30_PROT_ID) {
1920 		cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1921 		/*
1922 		 * The session id is opaque in terms of endianness, so we can't
1923 		 * print it as a long long. we dump it as we got it on the wire
1924 		 */
1925 		cifs_dbg(VFS, "Session Id    %*ph\n", (int)sizeof(ses->Suid),
1926 			 &ses->Suid);
1927 		cifs_dbg(VFS, "Session Key   %*ph\n",
1928 			 SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1929 		cifs_dbg(VFS, "Signing Key   %*ph\n",
1930 			 SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1931 	}
1932 #endif
1933 out:
1934 	kfree_sensitive(ntlmssp_blob);
1935 	SMB2_sess_free_buffer(sess_data);
1936 	kfree_sensitive(ses->ntlmssp);
1937 	ses->ntlmssp = NULL;
1938 	sess_data->result = rc;
1939 	sess_data->func = NULL;
1940 }
1941 
1942 static int
SMB2_select_sec(struct SMB2_sess_data * sess_data)1943 SMB2_select_sec(struct SMB2_sess_data *sess_data)
1944 {
1945 	int type;
1946 	struct cifs_ses *ses = sess_data->ses;
1947 	struct TCP_Server_Info *server = sess_data->server;
1948 
1949 	type = smb2_select_sectype(server, ses->sectype);
1950 	cifs_dbg(FYI, "sess setup type %d\n", type);
1951 	if (type == Unspecified) {
1952 		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1953 		return -EINVAL;
1954 	}
1955 
1956 	switch (type) {
1957 	case Kerberos:
1958 		sess_data->func = SMB2_auth_kerberos;
1959 		break;
1960 	case RawNTLMSSP:
1961 		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1962 		break;
1963 	default:
1964 		cifs_dbg(VFS, "secType %d not supported!\n", type);
1965 		return -EOPNOTSUPP;
1966 	}
1967 
1968 	return 0;
1969 }
1970 
1971 int
SMB2_sess_setup(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,const struct nls_table * nls_cp)1972 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1973 		struct TCP_Server_Info *server,
1974 		const struct nls_table *nls_cp)
1975 {
1976 	int rc = 0;
1977 	struct SMB2_sess_data *sess_data;
1978 
1979 	cifs_dbg(FYI, "Session Setup\n");
1980 
1981 	if (!server) {
1982 		WARN(1, "%s: server is NULL!\n", __func__);
1983 		return smb_EIO(smb_eio_trace_null_pointers);
1984 	}
1985 
1986 	sess_data = kzalloc_obj(struct SMB2_sess_data);
1987 	if (!sess_data)
1988 		return -ENOMEM;
1989 
1990 	sess_data->xid = xid;
1991 	sess_data->ses = ses;
1992 	sess_data->server = server;
1993 	sess_data->buf0_type = CIFS_NO_BUFFER;
1994 	sess_data->nls_cp = (struct nls_table *) nls_cp;
1995 	sess_data->previous_session = ses->Suid;
1996 
1997 	rc = SMB2_select_sec(sess_data);
1998 	if (rc)
1999 		goto out;
2000 
2001 	/*
2002 	 * Initialize the session hash with the server one.
2003 	 */
2004 	memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
2005 	       SMB2_PREAUTH_HASH_SIZE);
2006 
2007 	while (sess_data->func)
2008 		sess_data->func(sess_data);
2009 
2010 	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
2011 		cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
2012 	rc = sess_data->result;
2013 out:
2014 	kfree_sensitive(sess_data);
2015 	return rc;
2016 }
2017 
2018 int
SMB2_logoff(const unsigned int xid,struct cifs_ses * ses)2019 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
2020 {
2021 	struct smb_rqst rqst;
2022 	struct smb2_logoff_req *req; /* response is also trivial struct */
2023 	int rc = 0;
2024 	struct TCP_Server_Info *server;
2025 	int flags = 0;
2026 	unsigned int total_len;
2027 	struct kvec iov[1];
2028 	struct kvec rsp_iov;
2029 	int resp_buf_type;
2030 
2031 	cifs_dbg(FYI, "disconnect session %p\n", ses);
2032 
2033 	if (!ses || !ses->server)
2034 		return smb_EIO(smb_eio_trace_null_pointers);
2035 	server = ses->server;
2036 
2037 	/* no need to send SMB logoff if uid already closed due to reconnect */
2038 	spin_lock(&ses->chan_lock);
2039 	if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
2040 		spin_unlock(&ses->chan_lock);
2041 		goto smb2_session_already_dead;
2042 	}
2043 	spin_unlock(&ses->chan_lock);
2044 
2045 	rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
2046 				 (void **) &req, &total_len);
2047 	if (rc)
2048 		return rc;
2049 
2050 	 /* since no tcon, smb2_init can not do this, so do here */
2051 	req->hdr.SessionId = cpu_to_le64(ses->Suid);
2052 
2053 	if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
2054 		flags |= CIFS_TRANSFORM_REQ;
2055 	else if (server->sign)
2056 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2057 
2058 	flags |= CIFS_NO_RSP_BUF;
2059 
2060 	iov[0].iov_base = (char *)req;
2061 	iov[0].iov_len = total_len;
2062 
2063 	memset(&rqst, 0, sizeof(struct smb_rqst));
2064 	rqst.rq_iov = iov;
2065 	rqst.rq_nvec = 1;
2066 
2067 	rc = cifs_send_recv(xid, ses, ses->server,
2068 			    &rqst, &resp_buf_type, flags, &rsp_iov);
2069 	cifs_small_buf_release(req);
2070 	/*
2071 	 * No tcon so can't do
2072 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
2073 	 */
2074 
2075 smb2_session_already_dead:
2076 	return rc;
2077 }
2078 
cifs_stats_fail_inc(struct cifs_tcon * tcon,uint16_t code)2079 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
2080 {
2081 	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
2082 }
2083 
2084 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
2085 
2086 /* These are similar values to what Windows uses */
init_copy_chunk_defaults(struct cifs_tcon * tcon)2087 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
2088 {
2089 	tcon->max_chunks = 256;
2090 	tcon->max_bytes_chunk = 1048576;
2091 	tcon->max_bytes_copy = 16777216;
2092 }
2093 
2094 int
SMB2_tcon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * cp)2095 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
2096 	  struct cifs_tcon *tcon, const struct nls_table *cp)
2097 {
2098 	struct smb_rqst rqst;
2099 	struct smb2_tree_connect_req *req;
2100 	struct smb2_tree_connect_rsp *rsp = NULL;
2101 	struct kvec iov[2];
2102 	struct kvec rsp_iov = { NULL, 0 };
2103 	int rc = 0;
2104 	int resp_buftype;
2105 	int unc_path_len;
2106 	__le16 *unc_path = NULL;
2107 	int flags = 0;
2108 	unsigned int total_len;
2109 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2110 
2111 	cifs_dbg(FYI, "TCON\n");
2112 
2113 	if (!server || !tree)
2114 		return smb_EIO(smb_eio_trace_null_pointers);
2115 
2116 	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
2117 	if (unc_path == NULL)
2118 		return -ENOMEM;
2119 
2120 	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
2121 	if (unc_path_len <= 0) {
2122 		kfree(unc_path);
2123 		return -EINVAL;
2124 	}
2125 	unc_path_len *= 2;
2126 
2127 	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
2128 	tcon->tid = 0;
2129 	atomic_set(&tcon->num_remote_opens, 0);
2130 	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
2131 				 (void **) &req, &total_len);
2132 	if (rc) {
2133 		kfree(unc_path);
2134 		return rc;
2135 	}
2136 
2137 	if (smb3_encryption_required(tcon))
2138 		flags |= CIFS_TRANSFORM_REQ;
2139 
2140 	iov[0].iov_base = (char *)req;
2141 	/* 1 for pad */
2142 	iov[0].iov_len = total_len - 1;
2143 
2144 	/* Testing shows that buffer offset must be at location of Buffer[0] */
2145 	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
2146 	req->PathLength = cpu_to_le16(unc_path_len);
2147 	iov[1].iov_base = unc_path;
2148 	iov[1].iov_len = unc_path_len;
2149 
2150 	/*
2151 	 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
2152 	 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
2153 	 * (Samba servers don't always set the flag so also check if null user)
2154 	 */
2155 	if ((server->dialect == SMB311_PROT_ID) &&
2156 	    !smb3_encryption_required(tcon) &&
2157 	    !(ses->session_flags &
2158 		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
2159 	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
2160 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2161 
2162 	memset(&rqst, 0, sizeof(struct smb_rqst));
2163 	rqst.rq_iov = iov;
2164 	rqst.rq_nvec = 2;
2165 
2166 	/* Need 64 for max size write so ask for more in case not there yet */
2167 	if (server->credits >= server->max_credits)
2168 		req->hdr.CreditRequest = cpu_to_le16(0);
2169 	else
2170 		req->hdr.CreditRequest = cpu_to_le16(
2171 			min_t(int, server->max_credits -
2172 			      server->credits, 64));
2173 
2174 	rc = cifs_send_recv(xid, ses, server,
2175 			    &rqst, &resp_buftype, flags, &rsp_iov);
2176 	cifs_small_buf_release(req);
2177 	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
2178 	trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
2179 	if ((rc != 0) || (rsp == NULL)) {
2180 		cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
2181 		tcon->need_reconnect = true;
2182 		goto tcon_error_exit;
2183 	}
2184 
2185 	switch (rsp->ShareType) {
2186 	case SMB2_SHARE_TYPE_DISK:
2187 		cifs_dbg(FYI, "connection to disk share\n");
2188 		break;
2189 	case SMB2_SHARE_TYPE_PIPE:
2190 		tcon->pipe = true;
2191 		cifs_dbg(FYI, "connection to pipe share\n");
2192 		break;
2193 	case SMB2_SHARE_TYPE_PRINT:
2194 		tcon->print = true;
2195 		cifs_dbg(FYI, "connection to printer\n");
2196 		break;
2197 	default:
2198 		cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
2199 		rc = -EOPNOTSUPP;
2200 		goto tcon_error_exit;
2201 	}
2202 
2203 	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
2204 	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
2205 	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2206 	tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
2207 	strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
2208 
2209 	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
2210 	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
2211 		cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
2212 
2213 	if (tcon->seal &&
2214 	    !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
2215 		cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
2216 
2217 	init_copy_chunk_defaults(tcon);
2218 	if (server->ops->validate_negotiate)
2219 		rc = server->ops->validate_negotiate(xid, tcon);
2220 	if (rc == 0) /* See MS-SMB2 2.2.10 and 3.2.5.5 */
2221 		if (tcon->share_flags & SMB2_SHAREFLAG_ISOLATED_TRANSPORT)
2222 			server->nosharesock = true;
2223 tcon_exit:
2224 
2225 	free_rsp_buf(resp_buftype, rsp);
2226 	kfree(unc_path);
2227 	return rc;
2228 
2229 tcon_error_exit:
2230 	if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
2231 		cifs_dbg(VFS | ONCE, "BAD_NETWORK_NAME: %s\n", tree);
2232 	goto tcon_exit;
2233 }
2234 
2235 int
SMB2_tdis(const unsigned int xid,struct cifs_tcon * tcon)2236 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
2237 {
2238 	struct smb_rqst rqst;
2239 	struct smb2_tree_disconnect_req *req; /* response is trivial */
2240 	int rc = 0;
2241 	struct cifs_ses *ses = tcon->ses;
2242 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2243 	int flags = 0;
2244 	unsigned int total_len;
2245 	struct kvec iov[1];
2246 	struct kvec rsp_iov;
2247 	int resp_buf_type;
2248 
2249 	cifs_dbg(FYI, "Tree Disconnect\n");
2250 
2251 	if (!ses || !(ses->server))
2252 		return smb_EIO(smb_eio_trace_null_pointers);
2253 
2254 	trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2255 	spin_lock(&ses->chan_lock);
2256 	if ((tcon->need_reconnect) ||
2257 	    (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
2258 		spin_unlock(&ses->chan_lock);
2259 		return 0;
2260 	}
2261 	spin_unlock(&ses->chan_lock);
2262 
2263 	invalidate_all_cached_dirs(tcon);
2264 
2265 	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, server,
2266 				 (void **) &req,
2267 				 &total_len);
2268 	if (rc)
2269 		return rc;
2270 
2271 	if (smb3_encryption_required(tcon))
2272 		flags |= CIFS_TRANSFORM_REQ;
2273 
2274 	flags |= CIFS_NO_RSP_BUF;
2275 
2276 	iov[0].iov_base = (char *)req;
2277 	iov[0].iov_len = total_len;
2278 
2279 	memset(&rqst, 0, sizeof(struct smb_rqst));
2280 	rqst.rq_iov = iov;
2281 	rqst.rq_nvec = 1;
2282 
2283 	rc = cifs_send_recv(xid, ses, server,
2284 			    &rqst, &resp_buf_type, flags, &rsp_iov);
2285 	cifs_small_buf_release(req);
2286 	if (rc) {
2287 		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2288 		trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
2289 	}
2290 	trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2291 
2292 	return rc;
2293 }
2294 
2295 static create_durable_req_t *
create_durable_buf(void)2296 create_durable_buf(void)
2297 {
2298 	create_durable_req_t *buf;
2299 
2300 	buf = kzalloc_obj(create_durable_req_t);
2301 	if (!buf)
2302 		return NULL;
2303 
2304 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2305 					(create_durable_req_t, Data));
2306 	buf->ccontext.DataLength = cpu_to_le32(16);
2307 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2308 				(create_durable_req_t, Name));
2309 	buf->ccontext.NameLength = cpu_to_le16(4);
2310 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2311 	buf->Name[0] = 'D';
2312 	buf->Name[1] = 'H';
2313 	buf->Name[2] = 'n';
2314 	buf->Name[3] = 'Q';
2315 	return buf;
2316 }
2317 
2318 static create_durable_req_t *
create_reconnect_durable_buf(struct cifs_fid * fid)2319 create_reconnect_durable_buf(struct cifs_fid *fid)
2320 {
2321 	create_durable_req_t *buf;
2322 
2323 	buf = kzalloc_obj(create_durable_req_t);
2324 	if (!buf)
2325 		return NULL;
2326 
2327 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2328 					(create_durable_req_t, Data));
2329 	buf->ccontext.DataLength = cpu_to_le32(16);
2330 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2331 				(create_durable_req_t, Name));
2332 	buf->ccontext.NameLength = cpu_to_le16(4);
2333 	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2334 	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2335 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2336 	buf->Name[0] = 'D';
2337 	buf->Name[1] = 'H';
2338 	buf->Name[2] = 'n';
2339 	buf->Name[3] = 'C';
2340 	return buf;
2341 }
2342 
2343 static void
parse_query_id_ctxt(struct create_context * cc,struct smb2_file_all_info * buf)2344 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2345 {
2346 	struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2347 
2348 	cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2349 		pdisk_id->DiskFileId, pdisk_id->VolumeId);
2350 	buf->IndexNumber = pdisk_id->DiskFileId;
2351 }
2352 
2353 static void
parse_posix_ctxt(struct create_context * cc,struct smb2_file_all_info * info,struct create_posix_rsp * posix)2354 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2355 		 struct create_posix_rsp *posix)
2356 {
2357 	int sid_len;
2358 	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2359 	u8 *end = beg + le32_to_cpu(cc->DataLength);
2360 	u8 *sid;
2361 
2362 	memset(posix, 0, sizeof(*posix));
2363 
2364 	posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2365 	posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2366 	posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2367 
2368 	sid = beg + 12;
2369 	sid_len = posix_info_sid_size(sid, end);
2370 	if (sid_len < 0) {
2371 		cifs_dbg(VFS, "bad owner sid in posix create response\n");
2372 		return;
2373 	}
2374 	memcpy(&posix->owner, sid, sid_len);
2375 
2376 	sid = sid + sid_len;
2377 	sid_len = posix_info_sid_size(sid, end);
2378 	if (sid_len < 0) {
2379 		cifs_dbg(VFS, "bad group sid in posix create response\n");
2380 		return;
2381 	}
2382 	memcpy(&posix->group, sid, sid_len);
2383 
2384 	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2385 		 posix->nlink, posix->mode, posix->reparse_tag);
2386 }
2387 
smb2_parse_contexts(struct TCP_Server_Info * server,struct kvec * rsp_iov,__u16 * epoch,char * lease_key,__u8 * oplock,struct smb2_file_all_info * buf,struct create_posix_rsp * posix)2388 int smb2_parse_contexts(struct TCP_Server_Info *server,
2389 			struct kvec *rsp_iov,
2390 			__u16 *epoch,
2391 			char *lease_key, __u8 *oplock,
2392 			struct smb2_file_all_info *buf,
2393 			struct create_posix_rsp *posix)
2394 {
2395 	struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2396 	struct create_context *cc;
2397 	size_t rem, off, len;
2398 	size_t doff, dlen;
2399 	size_t noff, nlen;
2400 	char *name;
2401 	static const char smb3_create_tag_posix[] = {
2402 		0x93, 0xAD, 0x25, 0x50, 0x9C,
2403 		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2404 		0xDE, 0x96, 0x8B, 0xCD, 0x7C
2405 	};
2406 
2407 	*oplock = 0;
2408 
2409 	off = le32_to_cpu(rsp->CreateContextsOffset);
2410 	rem = le32_to_cpu(rsp->CreateContextsLength);
2411 	if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
2412 		return -EINVAL;
2413 	cc = (struct create_context *)((u8 *)rsp + off);
2414 
2415 	/* Initialize inode number to 0 in case no valid data in qfid context */
2416 	if (buf)
2417 		buf->IndexNumber = 0;
2418 
2419 	while (rem >= sizeof(*cc)) {
2420 		doff = le16_to_cpu(cc->DataOffset);
2421 		dlen = le32_to_cpu(cc->DataLength);
2422 		if (check_add_overflow(doff, dlen, &len) || len > rem)
2423 			return -EINVAL;
2424 
2425 		noff = le16_to_cpu(cc->NameOffset);
2426 		nlen = le16_to_cpu(cc->NameLength);
2427 		if (noff + nlen > doff)
2428 			return -EINVAL;
2429 
2430 		name = (char *)cc + noff;
2431 		switch (nlen) {
2432 		case 4:
2433 			if (!strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
2434 				*oplock = server->ops->parse_lease_buf(cc, epoch,
2435 								       lease_key);
2436 			} else if (buf &&
2437 				   !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
2438 				parse_query_id_ctxt(cc, buf);
2439 			}
2440 			break;
2441 		case 16:
2442 			if (posix && !memcmp(name, smb3_create_tag_posix, 16))
2443 				parse_posix_ctxt(cc, buf, posix);
2444 			break;
2445 		default:
2446 			cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
2447 				 __func__, nlen, dlen);
2448 			if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
2449 				cifs_dump_mem("context data: ", cc, dlen);
2450 			break;
2451 		}
2452 
2453 		off = le32_to_cpu(cc->Next);
2454 		if (!off)
2455 			break;
2456 		if (check_sub_overflow(rem, off, &rem))
2457 			return -EINVAL;
2458 		cc = (struct create_context *)((u8 *)cc + off);
2459 	}
2460 
2461 	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2462 		*oplock = rsp->OplockLevel;
2463 
2464 	return 0;
2465 }
2466 
2467 static int
add_lease_context(struct TCP_Server_Info * server,struct smb2_create_req * req,struct kvec * iov,unsigned int * num_iovec,u8 * lease_key,__u8 * oplock,u8 * parent_lease_key,__le32 flags)2468 add_lease_context(struct TCP_Server_Info *server,
2469 		  struct smb2_create_req *req,
2470 		  struct kvec *iov,
2471 		  unsigned int *num_iovec,
2472 		  u8 *lease_key,
2473 		  __u8 *oplock,
2474 		  u8 *parent_lease_key,
2475 		  __le32 flags)
2476 {
2477 	unsigned int num = *num_iovec;
2478 
2479 	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock,
2480 							  parent_lease_key, flags);
2481 	if (iov[num].iov_base == NULL)
2482 		return -ENOMEM;
2483 	iov[num].iov_len = server->vals->create_lease_size;
2484 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2485 	*num_iovec = num + 1;
2486 	return 0;
2487 }
2488 
2489 static struct create_durable_req_v2 *
create_durable_v2_buf(struct cifs_open_parms * oparms)2490 create_durable_v2_buf(struct cifs_open_parms *oparms)
2491 {
2492 	struct cifs_fid *pfid = oparms->fid;
2493 	struct create_durable_req_v2 *buf;
2494 
2495 	buf = kzalloc_obj(struct create_durable_req_v2);
2496 	if (!buf)
2497 		return NULL;
2498 
2499 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2500 					(struct create_durable_req_v2, dcontext));
2501 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2_req));
2502 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2503 				(struct create_durable_req_v2, Name));
2504 	buf->ccontext.NameLength = cpu_to_le16(4);
2505 
2506 	/*
2507 	 * NB: Handle timeout defaults to 0, which allows server to choose
2508 	 * (most servers default to 120 seconds) and most clients default to 0.
2509 	 * This can be overridden at mount ("handletimeout=") if the user wants
2510 	 * a different persistent (or resilient) handle timeout for all opens
2511 	 * on a particular SMB3 mount.
2512 	 */
2513 	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2514 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2515 
2516 	/* for replay, we should not overwrite the existing create guid */
2517 	if (!oparms->replay) {
2518 		generate_random_uuid(buf->dcontext.CreateGuid);
2519 		memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2520 	} else
2521 		memcpy(buf->dcontext.CreateGuid, pfid->create_guid, 16);
2522 
2523 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2524 	buf->Name[0] = 'D';
2525 	buf->Name[1] = 'H';
2526 	buf->Name[2] = '2';
2527 	buf->Name[3] = 'Q';
2528 	return buf;
2529 }
2530 
2531 static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid * fid)2532 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2533 {
2534 	struct create_durable_handle_reconnect_v2 *buf;
2535 
2536 	buf = kzalloc_obj(struct create_durable_handle_reconnect_v2);
2537 	if (!buf)
2538 		return NULL;
2539 
2540 	buf->ccontext.DataOffset =
2541 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2542 				     dcontext));
2543 	buf->ccontext.DataLength =
2544 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2545 	buf->ccontext.NameOffset =
2546 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2547 			    Name));
2548 	buf->ccontext.NameLength = cpu_to_le16(4);
2549 
2550 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2551 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2552 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2553 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2554 
2555 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2556 	buf->Name[0] = 'D';
2557 	buf->Name[1] = 'H';
2558 	buf->Name[2] = '2';
2559 	buf->Name[3] = 'C';
2560 	return buf;
2561 }
2562 
2563 static int
add_durable_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)2564 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2565 		    struct cifs_open_parms *oparms)
2566 {
2567 	unsigned int num = *num_iovec;
2568 
2569 	iov[num].iov_base = create_durable_v2_buf(oparms);
2570 	if (iov[num].iov_base == NULL)
2571 		return -ENOMEM;
2572 	iov[num].iov_len = sizeof(struct create_durable_req_v2);
2573 	*num_iovec = num + 1;
2574 	return 0;
2575 }
2576 
2577 static int
add_durable_reconnect_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)2578 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2579 		    struct cifs_open_parms *oparms)
2580 {
2581 	unsigned int num = *num_iovec;
2582 
2583 	/* indicate that we don't need to relock the file */
2584 	oparms->reconnect = false;
2585 
2586 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2587 	if (iov[num].iov_base == NULL)
2588 		return -ENOMEM;
2589 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2590 	*num_iovec = num + 1;
2591 	return 0;
2592 }
2593 
2594 static int
add_durable_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms,bool use_persistent)2595 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2596 		    struct cifs_open_parms *oparms, bool use_persistent)
2597 {
2598 	unsigned int num = *num_iovec;
2599 
2600 	if (use_persistent) {
2601 		if (oparms->reconnect)
2602 			return add_durable_reconnect_v2_context(iov, num_iovec,
2603 								oparms);
2604 		else
2605 			return add_durable_v2_context(iov, num_iovec, oparms);
2606 	}
2607 
2608 	if (oparms->reconnect) {
2609 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2610 		/* indicate that we don't need to relock the file */
2611 		oparms->reconnect = false;
2612 	} else
2613 		iov[num].iov_base = create_durable_buf();
2614 	if (iov[num].iov_base == NULL)
2615 		return -ENOMEM;
2616 	iov[num].iov_len = sizeof(create_durable_req_t);
2617 	*num_iovec = num + 1;
2618 	return 0;
2619 }
2620 
2621 /* See MS-SMB2 2.2.13.2.7 */
2622 static struct crt_twarp_ctxt *
create_twarp_buf(__u64 timewarp)2623 create_twarp_buf(__u64 timewarp)
2624 {
2625 	struct crt_twarp_ctxt *buf;
2626 
2627 	buf = kzalloc_obj(struct crt_twarp_ctxt);
2628 	if (!buf)
2629 		return NULL;
2630 
2631 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2632 					(struct crt_twarp_ctxt, Timestamp));
2633 	buf->ccontext.DataLength = cpu_to_le32(8);
2634 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2635 				(struct crt_twarp_ctxt, Name));
2636 	buf->ccontext.NameLength = cpu_to_le16(4);
2637 	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2638 	buf->Name[0] = 'T';
2639 	buf->Name[1] = 'W';
2640 	buf->Name[2] = 'r';
2641 	buf->Name[3] = 'p';
2642 	buf->Timestamp = cpu_to_le64(timewarp);
2643 	return buf;
2644 }
2645 
2646 /* See MS-SMB2 2.2.13.2.7 */
2647 static int
add_twarp_context(struct kvec * iov,unsigned int * num_iovec,__u64 timewarp)2648 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2649 {
2650 	unsigned int num = *num_iovec;
2651 
2652 	iov[num].iov_base = create_twarp_buf(timewarp);
2653 	if (iov[num].iov_base == NULL)
2654 		return -ENOMEM;
2655 	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2656 	*num_iovec = num + 1;
2657 	return 0;
2658 }
2659 
2660 /* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
setup_owner_group_sids(char * buf)2661 static void setup_owner_group_sids(char *buf)
2662 {
2663 	struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2664 
2665 	/* Populate the user ownership fields S-1-5-88-1 */
2666 	sids->owner.Revision = 1;
2667 	sids->owner.NumAuth = 3;
2668 	sids->owner.Authority[5] = 5;
2669 	sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2670 	sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2671 	sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2672 
2673 	/* Populate the group ownership fields S-1-5-88-2 */
2674 	sids->group.Revision = 1;
2675 	sids->group.NumAuth = 3;
2676 	sids->group.Authority[5] = 5;
2677 	sids->group.SubAuthorities[0] = cpu_to_le32(88);
2678 	sids->group.SubAuthorities[1] = cpu_to_le32(2);
2679 	sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2680 
2681 	cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2682 }
2683 
2684 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2685 static struct crt_sd_ctxt *
create_sd_buf(umode_t mode,bool set_owner,unsigned int * len)2686 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2687 {
2688 	struct crt_sd_ctxt *buf;
2689 	__u8 *ptr, *aclptr;
2690 	unsigned int acelen, acl_size, ace_count;
2691 	unsigned int owner_offset = 0;
2692 	unsigned int group_offset = 0;
2693 	struct smb3_acl acl = {};
2694 
2695 	*len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct smb_ace) * 4), 8);
2696 
2697 	if (set_owner) {
2698 		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2699 		*len += sizeof(struct owner_group_sids);
2700 	}
2701 
2702 	buf = kzalloc(*len, GFP_KERNEL);
2703 	if (buf == NULL)
2704 		return buf;
2705 
2706 	ptr = (__u8 *)&buf[1];
2707 	if (set_owner) {
2708 		/* offset fields are from beginning of security descriptor not of create context */
2709 		owner_offset = ptr - (__u8 *)&buf->sd;
2710 		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2711 		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2712 		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2713 
2714 		setup_owner_group_sids(ptr);
2715 		ptr += sizeof(struct owner_group_sids);
2716 	} else {
2717 		buf->sd.OffsetOwner = 0;
2718 		buf->sd.OffsetGroup = 0;
2719 	}
2720 
2721 	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2722 	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2723 	buf->ccontext.NameLength = cpu_to_le16(4);
2724 	/* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2725 	buf->Name[0] = 'S';
2726 	buf->Name[1] = 'e';
2727 	buf->Name[2] = 'c';
2728 	buf->Name[3] = 'D';
2729 	buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2730 
2731 	/*
2732 	 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2733 	 * and "DP" ie the DACL is present
2734 	 */
2735 	buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2736 
2737 	/* offset owner, group and Sbz1 and SACL are all zero */
2738 	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2739 	/* Ship the ACL for now. we will copy it into buf later. */
2740 	aclptr = ptr;
2741 	ptr += sizeof(struct smb3_acl);
2742 
2743 	/* create one ACE to hold the mode embedded in reserved special SID */
2744 	acelen = setup_special_mode_ACE((struct smb_ace *)ptr, false, (__u64)mode);
2745 	ptr += acelen;
2746 	acl_size = acelen + sizeof(struct smb3_acl);
2747 	ace_count = 1;
2748 
2749 	if (set_owner) {
2750 		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2751 		acelen = setup_special_user_owner_ACE((struct smb_ace *)ptr);
2752 		ptr += acelen;
2753 		acl_size += acelen;
2754 		ace_count += 1;
2755 	}
2756 
2757 	/* and one more ACE to allow access for authenticated users */
2758 	acelen = setup_authusers_ACE((struct smb_ace *)ptr);
2759 	ptr += acelen;
2760 	acl_size += acelen;
2761 	ace_count += 1;
2762 
2763 	acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2764 	acl.AclSize = cpu_to_le16(acl_size);
2765 	acl.AceCount = cpu_to_le16(ace_count);
2766 	/* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2767 	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2768 
2769 	buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2770 	*len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2771 
2772 	return buf;
2773 }
2774 
2775 static int
add_sd_context(struct kvec * iov,unsigned int * num_iovec,umode_t mode,bool set_owner)2776 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2777 {
2778 	unsigned int num = *num_iovec;
2779 	unsigned int len = 0;
2780 
2781 	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2782 	if (iov[num].iov_base == NULL)
2783 		return -ENOMEM;
2784 	iov[num].iov_len = len;
2785 	*num_iovec = num + 1;
2786 	return 0;
2787 }
2788 
2789 static struct crt_query_id_ctxt *
create_query_id_buf(void)2790 create_query_id_buf(void)
2791 {
2792 	struct crt_query_id_ctxt *buf;
2793 
2794 	buf = kzalloc_obj(struct crt_query_id_ctxt);
2795 	if (!buf)
2796 		return NULL;
2797 
2798 	buf->ccontext.DataOffset = cpu_to_le16(0);
2799 	buf->ccontext.DataLength = cpu_to_le32(0);
2800 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2801 				(struct crt_query_id_ctxt, Name));
2802 	buf->ccontext.NameLength = cpu_to_le16(4);
2803 	/* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2804 	buf->Name[0] = 'Q';
2805 	buf->Name[1] = 'F';
2806 	buf->Name[2] = 'i';
2807 	buf->Name[3] = 'd';
2808 	return buf;
2809 }
2810 
2811 /* See MS-SMB2 2.2.13.2.9 */
2812 static int
add_query_id_context(struct kvec * iov,unsigned int * num_iovec)2813 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2814 {
2815 	unsigned int num = *num_iovec;
2816 
2817 	iov[num].iov_base = create_query_id_buf();
2818 	if (iov[num].iov_base == NULL)
2819 		return -ENOMEM;
2820 	iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2821 	*num_iovec = num + 1;
2822 	return 0;
2823 }
2824 
add_ea_context(struct cifs_open_parms * oparms,struct kvec * rq_iov,unsigned int * num_iovs)2825 static void add_ea_context(struct cifs_open_parms *oparms,
2826 			   struct kvec *rq_iov, unsigned int *num_iovs)
2827 {
2828 	struct kvec *iov = oparms->ea_cctx;
2829 
2830 	if (iov && iov->iov_base && iov->iov_len) {
2831 		rq_iov[(*num_iovs)++] = *iov;
2832 		memset(iov, 0, sizeof(*iov));
2833 	}
2834 }
2835 
2836 static int
alloc_path_with_tree_prefix(__le16 ** out_path,int * out_size,int * out_len,const char * treename,const __le16 * path)2837 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2838 			    const char *treename, const __le16 *path)
2839 {
2840 	int treename_len, path_len;
2841 	struct nls_table *cp;
2842 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2843 
2844 	/*
2845 	 * skip leading "\\"
2846 	 */
2847 	treename_len = strlen(treename);
2848 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2849 		return -EINVAL;
2850 
2851 	treename += 2;
2852 	treename_len -= 2;
2853 
2854 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2855 
2856 	/* make room for one path separator only if @path isn't empty */
2857 	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2858 
2859 	/*
2860 	 * final path needs to be 8-byte aligned as specified in
2861 	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2862 	 */
2863 	*out_size = round_up(*out_len * sizeof(__le16), 8);
2864 	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2865 	if (!*out_path)
2866 		return -ENOMEM;
2867 
2868 	cp = load_nls_default();
2869 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2870 
2871 	/* Do not append the separator if the path is empty */
2872 	if (path[0] != cpu_to_le16(0x0000)) {
2873 		UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
2874 		UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2875 	}
2876 
2877 	unload_nls(cp);
2878 
2879 	return 0;
2880 }
2881 
smb311_posix_mkdir(const unsigned int xid,struct inode * inode,umode_t mode,struct cifs_tcon * tcon,const char * full_path,struct cifs_sb_info * cifs_sb)2882 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2883 			       umode_t mode, struct cifs_tcon *tcon,
2884 			       const char *full_path,
2885 			       struct cifs_sb_info *cifs_sb)
2886 {
2887 	struct smb_rqst rqst;
2888 	struct smb2_create_req *req;
2889 	struct smb2_create_rsp *rsp = NULL;
2890 	struct cifs_ses *ses = tcon->ses;
2891 	struct kvec iov[3]; /* make sure at least one for each open context */
2892 	struct kvec rsp_iov = {NULL, 0};
2893 	int resp_buftype;
2894 	int uni_path_len;
2895 	__le16 *copy_path = NULL;
2896 	int copy_size;
2897 	int rc = 0;
2898 	unsigned int n_iov = 2;
2899 	__u32 file_attributes = 0;
2900 	char *pc_buf = NULL;
2901 	int flags = 0;
2902 	unsigned int total_len;
2903 	__le16 *utf16_path = NULL;
2904 	struct TCP_Server_Info *server;
2905 	int retries = 0, cur_sleep = 0;
2906 
2907 replay_again:
2908 	/* reinitialize for possible replay */
2909 	pc_buf = NULL;
2910 	flags = 0;
2911 	n_iov = 2;
2912 	server = cifs_pick_channel(ses);
2913 
2914 	cifs_dbg(FYI, "mkdir\n");
2915 
2916 	/* resource #1: path allocation */
2917 	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2918 	if (!utf16_path)
2919 		return -ENOMEM;
2920 
2921 	if (!ses || !server) {
2922 		rc = smb_EIO(smb_eio_trace_null_pointers);
2923 		goto err_free_path;
2924 	}
2925 
2926 	/* resource #2: request */
2927 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2928 				 (void **) &req, &total_len);
2929 	if (rc)
2930 		goto err_free_path;
2931 
2932 
2933 	if (smb3_encryption_required(tcon))
2934 		flags |= CIFS_TRANSFORM_REQ;
2935 
2936 	req->ImpersonationLevel = IL_IMPERSONATION;
2937 	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2938 	/* File attributes ignored on open (used in create though) */
2939 	req->FileAttributes = cpu_to_le32(file_attributes);
2940 	req->ShareAccess = FILE_SHARE_ALL_LE;
2941 	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2942 	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2943 
2944 	iov[0].iov_base = (char *)req;
2945 	/* -1 since last byte is buf[0] which is sent below (path) */
2946 	iov[0].iov_len = total_len - 1;
2947 
2948 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2949 
2950 	/* [MS-SMB2] 2.2.13 NameOffset:
2951 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2952 	 * the SMB2 header, the file name includes a prefix that will
2953 	 * be processed during DFS name normalization as specified in
2954 	 * section 3.3.5.9. Otherwise, the file name is relative to
2955 	 * the share that is identified by the TreeId in the SMB2
2956 	 * header.
2957 	 */
2958 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2959 		int name_len;
2960 
2961 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2962 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2963 						 &name_len,
2964 						 tcon->tree_name, utf16_path);
2965 		if (rc)
2966 			goto err_free_req;
2967 
2968 		req->NameLength = cpu_to_le16(name_len * 2);
2969 		uni_path_len = copy_size;
2970 		/* free before overwriting resource */
2971 		kfree(utf16_path);
2972 		utf16_path = copy_path;
2973 	} else {
2974 		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2975 		/* MUST set path len (NameLength) to 0 opening root of share */
2976 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2977 		if (uni_path_len % 8 != 0) {
2978 			copy_size = roundup(uni_path_len, 8);
2979 			copy_path = kzalloc(copy_size, GFP_KERNEL);
2980 			if (!copy_path) {
2981 				rc = -ENOMEM;
2982 				goto err_free_req;
2983 			}
2984 			memcpy((char *)copy_path, (const char *)utf16_path,
2985 			       uni_path_len);
2986 			uni_path_len = copy_size;
2987 			/* free before overwriting resource */
2988 			kfree(utf16_path);
2989 			utf16_path = copy_path;
2990 		}
2991 	}
2992 
2993 	iov[1].iov_len = uni_path_len;
2994 	iov[1].iov_base = utf16_path;
2995 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2996 
2997 	if (tcon->posix_extensions) {
2998 		/* resource #3: posix buf */
2999 		rc = add_posix_context(iov, &n_iov, mode);
3000 		if (rc)
3001 			goto err_free_req;
3002 		req->CreateContextsOffset = cpu_to_le32(
3003 			sizeof(struct smb2_create_req) +
3004 			iov[1].iov_len);
3005 		le32_add_cpu(&req->CreateContextsLength, iov[n_iov-1].iov_len);
3006 		pc_buf = iov[n_iov-1].iov_base;
3007 	}
3008 
3009 
3010 	memset(&rqst, 0, sizeof(struct smb_rqst));
3011 	rqst.rq_iov = iov;
3012 	rqst.rq_nvec = n_iov;
3013 
3014 	/* no need to inc num_remote_opens because we close it just below */
3015 	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
3016 				    FILE_WRITE_ATTRIBUTES);
3017 
3018 	if (retries) {
3019 		/* Back-off before retry */
3020 		if (cur_sleep)
3021 			msleep(cur_sleep);
3022 		smb2_set_replay(server, &rqst);
3023 	}
3024 
3025 	/* resource #4: response buffer */
3026 	rc = cifs_send_recv(xid, ses, server,
3027 			    &rqst, &resp_buftype, flags, &rsp_iov);
3028 	if (rc) {
3029 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3030 		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
3031 					   CREATE_NOT_FILE,
3032 					   FILE_WRITE_ATTRIBUTES, rc);
3033 		goto err_free_rsp_buf;
3034 	}
3035 
3036 	/*
3037 	 * Although unlikely to be possible for rsp to be null and rc not set,
3038 	 * adding check below is slightly safer long term (and quiets Coverity
3039 	 * warning)
3040 	 */
3041 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3042 	if (rsp == NULL) {
3043 		rc = smb_EIO(smb_eio_trace_mkdir_no_rsp);
3044 		kfree(pc_buf);
3045 		goto err_free_req;
3046 	}
3047 
3048 	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3049 				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
3050 
3051 	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
3052 
3053 	/* Eventually save off posix specific response info and timestamps */
3054 
3055 err_free_rsp_buf:
3056 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3057 	kfree(pc_buf);
3058 err_free_req:
3059 	cifs_small_buf_release(req);
3060 err_free_path:
3061 	kfree(utf16_path);
3062 
3063 	if (is_replayable_error(rc) &&
3064 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3065 		goto replay_again;
3066 
3067 	return rc;
3068 }
3069 
3070 int
SMB2_open_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,__u8 * oplock,struct cifs_open_parms * oparms,__le16 * path)3071 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3072 	       struct smb_rqst *rqst, __u8 *oplock,
3073 	       struct cifs_open_parms *oparms, __le16 *path)
3074 {
3075 	struct smb2_create_req *req;
3076 	unsigned int n_iov = 2;
3077 	__u32 file_attributes = 0;
3078 	int copy_size;
3079 	int uni_path_len;
3080 	unsigned int total_len;
3081 	struct kvec *iov = rqst->rq_iov;
3082 	__le16 *copy_path;
3083 	int rc;
3084 
3085 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
3086 				 (void **) &req, &total_len);
3087 	if (rc)
3088 		return rc;
3089 
3090 	iov[0].iov_base = (char *)req;
3091 	/* -1 since last byte is buf[0] which is sent below (path) */
3092 	iov[0].iov_len = total_len - 1;
3093 
3094 	if (oparms->create_options & CREATE_OPTION_READONLY)
3095 		file_attributes |= ATTR_READONLY;
3096 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
3097 		file_attributes |= ATTR_SYSTEM;
3098 
3099 	req->ImpersonationLevel = IL_IMPERSONATION;
3100 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
3101 	/* File attributes ignored on open (used in create though) */
3102 	req->FileAttributes = cpu_to_le32(file_attributes);
3103 	req->ShareAccess = FILE_SHARE_ALL_LE;
3104 
3105 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
3106 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
3107 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
3108 
3109 	/* [MS-SMB2] 2.2.13 NameOffset:
3110 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
3111 	 * the SMB2 header, the file name includes a prefix that will
3112 	 * be processed during DFS name normalization as specified in
3113 	 * section 3.3.5.9. Otherwise, the file name is relative to
3114 	 * the share that is identified by the TreeId in the SMB2
3115 	 * header.
3116 	 */
3117 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
3118 		int name_len;
3119 
3120 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3121 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
3122 						 &name_len,
3123 						 tcon->tree_name, path);
3124 		if (rc)
3125 			return rc;
3126 		req->NameLength = cpu_to_le16(name_len * 2);
3127 		uni_path_len = copy_size;
3128 		path = copy_path;
3129 	} else {
3130 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
3131 		/* MUST set path len (NameLength) to 0 opening root of share */
3132 		req->NameLength = cpu_to_le16(uni_path_len - 2);
3133 		copy_size = round_up(uni_path_len, 8);
3134 		copy_path = kzalloc(copy_size, GFP_KERNEL);
3135 		if (!copy_path)
3136 			return -ENOMEM;
3137 		memcpy((char *)copy_path, (const char *)path,
3138 		       uni_path_len);
3139 		uni_path_len = copy_size;
3140 		path = copy_path;
3141 	}
3142 
3143 	iov[1].iov_len = uni_path_len;
3144 	iov[1].iov_base = path;
3145 
3146 	if ((!server->oplocks) || (tcon->no_lease))
3147 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
3148 
3149 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3150 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
3151 		req->RequestedOplockLevel = *oplock;
3152 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
3153 		  (oparms->create_options & CREATE_NOT_FILE))
3154 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
3155 	else {
3156 		rc = add_lease_context(server, req, iov, &n_iov,
3157 				       oparms->fid->lease_key, oplock,
3158 				       oparms->fid->parent_lease_key,
3159 				       oparms->lease_flags);
3160 		if (rc)
3161 			return rc;
3162 	}
3163 
3164 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3165 		rc = add_durable_context(iov, &n_iov, oparms,
3166 					tcon->use_persistent);
3167 		if (rc)
3168 			return rc;
3169 	}
3170 
3171 	if (tcon->posix_extensions) {
3172 		rc = add_posix_context(iov, &n_iov, oparms->mode);
3173 		if (rc)
3174 			return rc;
3175 	}
3176 
3177 	if (tcon->snapshot_time) {
3178 		cifs_dbg(FYI, "adding snapshot context\n");
3179 		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
3180 		if (rc)
3181 			return rc;
3182 	}
3183 
3184 	if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
3185 		bool set_mode;
3186 		bool set_owner;
3187 
3188 		if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
3189 		    (oparms->mode != ACL_NO_MODE))
3190 			set_mode = true;
3191 		else {
3192 			set_mode = false;
3193 			oparms->mode = ACL_NO_MODE;
3194 		}
3195 
3196 		if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
3197 			set_owner = true;
3198 		else
3199 			set_owner = false;
3200 
3201 		if (set_owner | set_mode) {
3202 			cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
3203 			rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
3204 			if (rc)
3205 				return rc;
3206 		}
3207 	}
3208 
3209 	add_query_id_context(iov, &n_iov);
3210 	add_ea_context(oparms, iov, &n_iov);
3211 
3212 	if (n_iov > 2) {
3213 		/*
3214 		 * We have create contexts behind iov[1] (the file
3215 		 * name), point at them from the main create request
3216 		 */
3217 		req->CreateContextsOffset = cpu_to_le32(
3218 			sizeof(struct smb2_create_req) +
3219 			iov[1].iov_len);
3220 		req->CreateContextsLength = 0;
3221 
3222 		for (unsigned int i = 2; i < (n_iov-1); i++) {
3223 			struct kvec *v = &iov[i];
3224 			size_t len = v->iov_len;
3225 			struct create_context *cctx =
3226 				(struct create_context *)v->iov_base;
3227 
3228 			cctx->Next = cpu_to_le32(len);
3229 			le32_add_cpu(&req->CreateContextsLength, len);
3230 		}
3231 		le32_add_cpu(&req->CreateContextsLength,
3232 			     iov[n_iov-1].iov_len);
3233 	}
3234 
3235 	rqst->rq_nvec = n_iov;
3236 	return 0;
3237 }
3238 
3239 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
3240  * All other vectors are freed by kfree().
3241  */
3242 void
SMB2_open_free(struct smb_rqst * rqst)3243 SMB2_open_free(struct smb_rqst *rqst)
3244 {
3245 	int i;
3246 
3247 	if (rqst && rqst->rq_iov) {
3248 		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
3249 		for (i = 1; i < rqst->rq_nvec; i++)
3250 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3251 				kfree(rqst->rq_iov[i].iov_base);
3252 	}
3253 }
3254 
3255 int
SMB2_open(const unsigned int xid,struct cifs_open_parms * oparms,__le16 * path,__u8 * oplock,struct smb2_file_all_info * buf,struct create_posix_rsp * posix,struct kvec * err_iov,int * buftype)3256 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
3257 	  __u8 *oplock, struct smb2_file_all_info *buf,
3258 	  struct create_posix_rsp *posix,
3259 	  struct kvec *err_iov, int *buftype)
3260 {
3261 	struct smb_rqst rqst;
3262 	struct smb2_create_rsp *rsp = NULL;
3263 	struct cifs_tcon *tcon = oparms->tcon;
3264 	struct cifs_ses *ses = tcon->ses;
3265 	struct TCP_Server_Info *server;
3266 	struct kvec iov[SMB2_CREATE_IOV_SIZE];
3267 	struct kvec rsp_iov = {NULL, 0};
3268 	int resp_buftype = CIFS_NO_BUFFER;
3269 	int rc = 0;
3270 	int flags = 0;
3271 	int retries = 0, cur_sleep = 0;
3272 
3273 replay_again:
3274 	/* reinitialize for possible replay */
3275 	flags = 0;
3276 	server = cifs_pick_channel(ses);
3277 	oparms->replay = !!(retries);
3278 
3279 	cifs_dbg(FYI, "create/open\n");
3280 	if (!ses || !server)
3281 		return smb_EIO(smb_eio_trace_null_pointers);
3282 
3283 	if (smb3_encryption_required(tcon))
3284 		flags |= CIFS_TRANSFORM_REQ;
3285 
3286 	memset(&rqst, 0, sizeof(struct smb_rqst));
3287 	memset(&iov, 0, sizeof(iov));
3288 	rqst.rq_iov = iov;
3289 	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3290 
3291 	rc = SMB2_open_init(tcon, server,
3292 			    &rqst, oplock, oparms, path);
3293 	if (rc)
3294 		goto creat_exit;
3295 
3296 	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3297 		oparms->create_options, oparms->desired_access);
3298 
3299 	if (retries) {
3300 		/* Back-off before retry */
3301 		if (cur_sleep)
3302 			msleep(cur_sleep);
3303 		smb2_set_replay(server, &rqst);
3304 	}
3305 
3306 	rc = cifs_send_recv(xid, ses, server,
3307 			    &rqst, &resp_buftype, flags,
3308 			    &rsp_iov);
3309 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3310 
3311 	if (rc != 0) {
3312 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3313 		if (err_iov && rsp) {
3314 			*err_iov = rsp_iov;
3315 			*buftype = resp_buftype;
3316 			resp_buftype = CIFS_NO_BUFFER;
3317 			rsp = NULL;
3318 		}
3319 		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3320 				    oparms->create_options, oparms->desired_access, rc);
3321 		if (rc == -EREMCHG) {
3322 			pr_warn_once("server share %s deleted\n",
3323 				     tcon->tree_name);
3324 			tcon->need_reconnect = true;
3325 		}
3326 		goto creat_exit;
3327 	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
3328 		goto creat_exit;
3329 	else
3330 		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3331 				     oparms->create_options, oparms->desired_access);
3332 
3333 	atomic_inc(&tcon->num_remote_opens);
3334 	oparms->fid->persistent_fid = rsp->PersistentFileId;
3335 	oparms->fid->volatile_fid = rsp->VolatileFileId;
3336 	oparms->fid->access = oparms->desired_access;
3337 #ifdef CONFIG_CIFS_DEBUG2
3338 	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3339 #endif /* CIFS_DEBUG2 */
3340 
3341 	if (buf) {
3342 		buf->CreationTime = rsp->CreationTime;
3343 		buf->LastAccessTime = rsp->LastAccessTime;
3344 		buf->LastWriteTime = rsp->LastWriteTime;
3345 		buf->ChangeTime = rsp->ChangeTime;
3346 		buf->AllocationSize = rsp->AllocationSize;
3347 		buf->EndOfFile = rsp->EndofFile;
3348 		buf->Attributes = rsp->FileAttributes;
3349 		buf->NumberOfLinks = cpu_to_le32(1);
3350 		buf->DeletePending = 0; /* successful open = not delete pending */
3351 	}
3352 
3353 
3354 	rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
3355 				 oparms->fid->lease_key, oplock, buf, posix);
3356 creat_exit:
3357 	SMB2_open_free(&rqst);
3358 	free_rsp_buf(resp_buftype, rsp);
3359 
3360 	if (is_replayable_error(rc) &&
3361 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3362 		goto replay_again;
3363 
3364 	return rc;
3365 }
3366 
3367 int
SMB2_ioctl_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u32 opcode,char * in_data,u32 indatalen,__u32 max_response_size)3368 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3369 		struct smb_rqst *rqst,
3370 		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3371 		char *in_data, u32 indatalen,
3372 		__u32 max_response_size)
3373 {
3374 	struct smb2_ioctl_req *req;
3375 	struct kvec *iov = rqst->rq_iov;
3376 	unsigned int total_len;
3377 	int rc;
3378 	char *in_data_buf;
3379 
3380 	rc = smb2_ioctl_req_init(opcode, tcon, server,
3381 				 (void **) &req, &total_len);
3382 	if (rc)
3383 		return rc;
3384 
3385 	if (indatalen) {
3386 		/*
3387 		 * indatalen is usually small at a couple of bytes max, so
3388 		 * just allocate through generic pool
3389 		 */
3390 		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3391 		if (!in_data_buf) {
3392 			cifs_small_buf_release(req);
3393 			return -ENOMEM;
3394 		}
3395 	}
3396 
3397 	req->CtlCode = cpu_to_le32(opcode);
3398 	req->PersistentFileId = persistent_fid;
3399 	req->VolatileFileId = volatile_fid;
3400 
3401 	iov[0].iov_base = (char *)req;
3402 	/*
3403 	 * If no input data, the size of ioctl struct in
3404 	 * protocol spec still includes a 1 byte data buffer,
3405 	 * but if input data passed to ioctl, we do not
3406 	 * want to double count this, so we do not send
3407 	 * the dummy one byte of data in iovec[0] if sending
3408 	 * input data (in iovec[1]).
3409 	 */
3410 	if (indatalen) {
3411 		req->InputCount = cpu_to_le32(indatalen);
3412 		/* do not set InputOffset if no input data */
3413 		req->InputOffset =
3414 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3415 		rqst->rq_nvec = 2;
3416 		iov[0].iov_len = total_len - 1;
3417 		iov[1].iov_base = in_data_buf;
3418 		iov[1].iov_len = indatalen;
3419 	} else {
3420 		rqst->rq_nvec = 1;
3421 		iov[0].iov_len = total_len;
3422 	}
3423 
3424 	req->OutputOffset = 0;
3425 	req->OutputCount = 0; /* MBZ */
3426 
3427 	/*
3428 	 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3429 	 * We Could increase default MaxOutputResponse, but that could require
3430 	 * more credits. Windows typically sets this smaller, but for some
3431 	 * ioctls it may be useful to allow server to send more. No point
3432 	 * limiting what the server can send as long as fits in one credit
3433 	 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3434 	 * to increase this limit up in the future.
3435 	 * Note that for snapshot queries that servers like Azure expect that
3436 	 * the first query be minimal size (and just used to get the number/size
3437 	 * of previous versions) so response size must be specified as EXACTLY
3438 	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3439 	 * of eight bytes.  Currently that is the only case where we set max
3440 	 * response size smaller.
3441 	 */
3442 	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3443 	req->hdr.CreditCharge =
3444 		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3445 					 SMB2_MAX_BUFFER_SIZE));
3446 	/* always an FSCTL (for now) */
3447 	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3448 
3449 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3450 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3451 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3452 
3453 	return 0;
3454 }
3455 
3456 void
SMB2_ioctl_free(struct smb_rqst * rqst)3457 SMB2_ioctl_free(struct smb_rqst *rqst)
3458 {
3459 	int i;
3460 
3461 	if (rqst && rqst->rq_iov) {
3462 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3463 		for (i = 1; i < rqst->rq_nvec; i++)
3464 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3465 				kfree(rqst->rq_iov[i].iov_base);
3466 	}
3467 }
3468 
3469 
3470 /*
3471  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
3472  */
3473 int
SMB2_ioctl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 opcode,char * in_data,u32 indatalen,u32 max_out_data_len,char ** out_data,u32 * plen)3474 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3475 	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3476 	   u32 max_out_data_len, char **out_data,
3477 	   u32 *plen /* returned data len */)
3478 {
3479 	struct smb_rqst rqst;
3480 	struct smb2_ioctl_rsp *rsp = NULL;
3481 	struct cifs_ses *ses;
3482 	struct TCP_Server_Info *server;
3483 	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3484 	struct kvec rsp_iov = {NULL, 0};
3485 	int resp_buftype = CIFS_NO_BUFFER;
3486 	int rc = 0;
3487 	int flags = 0;
3488 	int retries = 0, cur_sleep = 0;
3489 
3490 	if (!tcon)
3491 		return smb_EIO(smb_eio_trace_null_pointers);
3492 
3493 	ses = tcon->ses;
3494 	if (!ses)
3495 		return smb_EIO(smb_eio_trace_null_pointers);
3496 
3497 replay_again:
3498 	/* reinitialize for possible replay */
3499 	flags = 0;
3500 	server = cifs_pick_channel(ses);
3501 
3502 	if (!server)
3503 		return smb_EIO(smb_eio_trace_null_pointers);
3504 
3505 	cifs_dbg(FYI, "SMB2 IOCTL\n");
3506 
3507 	if (out_data != NULL)
3508 		*out_data = NULL;
3509 
3510 	/* zero out returned data len, in case of error */
3511 	if (plen)
3512 		*plen = 0;
3513 
3514 	if (smb3_encryption_required(tcon))
3515 		flags |= CIFS_TRANSFORM_REQ;
3516 
3517 	memset(&rqst, 0, sizeof(struct smb_rqst));
3518 	memset(&iov, 0, sizeof(iov));
3519 	rqst.rq_iov = iov;
3520 	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3521 
3522 	rc = SMB2_ioctl_init(tcon, server,
3523 			     &rqst, persistent_fid, volatile_fid, opcode,
3524 			     in_data, indatalen, max_out_data_len);
3525 	if (rc)
3526 		goto ioctl_exit;
3527 
3528 	if (retries) {
3529 		/* Back-off before retry */
3530 		if (cur_sleep)
3531 			msleep(cur_sleep);
3532 		smb2_set_replay(server, &rqst);
3533 	}
3534 
3535 	rc = cifs_send_recv(xid, ses, server,
3536 			    &rqst, &resp_buftype, flags,
3537 			    &rsp_iov);
3538 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3539 
3540 	if (rc != 0)
3541 		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3542 				ses->Suid, 0, opcode, rc);
3543 
3544 	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3545 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3546 		goto ioctl_exit;
3547 	} else if (rc == -EINVAL) {
3548 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3549 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3550 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3551 			goto ioctl_exit;
3552 		}
3553 	} else if (rc == -E2BIG) {
3554 		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3555 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3556 			goto ioctl_exit;
3557 		}
3558 	}
3559 
3560 	/* check if caller wants to look at return data or just return rc */
3561 	if ((plen == NULL) || (out_data == NULL))
3562 		goto ioctl_exit;
3563 
3564 	/*
3565 	 * Although unlikely to be possible for rsp to be null and rc not set,
3566 	 * adding check below is slightly safer long term (and quiets Coverity
3567 	 * warning)
3568 	 */
3569 	if (rsp == NULL) {
3570 		rc = smb_EIO(smb_eio_trace_ioctl_no_rsp);
3571 		goto ioctl_exit;
3572 	}
3573 
3574 	*plen = le32_to_cpu(rsp->OutputCount);
3575 
3576 	/* We check for obvious errors in the output buffer length and offset */
3577 	if (*plen == 0)
3578 		goto ioctl_exit; /* server returned no data */
3579 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3580 		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3581 		rc = smb_EIO2(smb_eio_trace_ioctl_data_len, *plen, rsp_iov.iov_len);
3582 		*plen = 0;
3583 		goto ioctl_exit;
3584 	}
3585 
3586 	u32 outoff = le32_to_cpu(rsp->OutputOffset);
3587 
3588 	if (rsp_iov.iov_len - *plen < outoff) {
3589 		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n",
3590 			      *plen, outoff);
3591 		rc = smb_EIO2(smb_eio_trace_ioctl_out_off, rsp_iov.iov_len - *plen, outoff);
3592 		*plen = 0;
3593 		goto ioctl_exit;
3594 	}
3595 
3596 	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3597 			    *plen, GFP_KERNEL);
3598 	if (*out_data == NULL) {
3599 		rc = -ENOMEM;
3600 		goto ioctl_exit;
3601 	}
3602 
3603 ioctl_exit:
3604 	SMB2_ioctl_free(&rqst);
3605 	free_rsp_buf(resp_buftype, rsp);
3606 
3607 	if (is_replayable_error(rc) &&
3608 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3609 		goto replay_again;
3610 
3611 	return rc;
3612 }
3613 
3614 /*
3615  *   Individual callers to ioctl worker function follow
3616  */
3617 
3618 int
SMB2_set_compression(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3619 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3620 		     u64 persistent_fid, u64 volatile_fid)
3621 {
3622 	int rc;
3623 	struct  compress_ioctl fsctl_input;
3624 	char *ret_data = NULL;
3625 
3626 	fsctl_input.CompressionState =
3627 			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3628 
3629 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3630 			FSCTL_SET_COMPRESSION,
3631 			(char *)&fsctl_input /* data input */,
3632 			2 /* in data len */, CIFSMaxBufSize /* max out data */,
3633 			&ret_data /* out data */, NULL);
3634 
3635 	cifs_dbg(FYI, "set compression rc %d\n", rc);
3636 
3637 	return rc;
3638 }
3639 
3640 int
SMB2_close_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,bool query_attrs)3641 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3642 		struct smb_rqst *rqst,
3643 		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3644 {
3645 	struct smb2_close_req *req;
3646 	struct kvec *iov = rqst->rq_iov;
3647 	unsigned int total_len;
3648 	int rc;
3649 
3650 	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3651 				 (void **) &req, &total_len);
3652 	if (rc)
3653 		return rc;
3654 
3655 	req->PersistentFileId = persistent_fid;
3656 	req->VolatileFileId = volatile_fid;
3657 	if (query_attrs)
3658 		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3659 	else
3660 		req->Flags = 0;
3661 	iov[0].iov_base = (char *)req;
3662 	iov[0].iov_len = total_len;
3663 
3664 	return 0;
3665 }
3666 
3667 void
SMB2_close_free(struct smb_rqst * rqst)3668 SMB2_close_free(struct smb_rqst *rqst)
3669 {
3670 	if (rqst && rqst->rq_iov)
3671 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3672 }
3673 
3674 int
__SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_network_open_info * pbuf)3675 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3676 	     u64 persistent_fid, u64 volatile_fid,
3677 	     struct smb2_file_network_open_info *pbuf)
3678 {
3679 	struct smb_rqst rqst;
3680 	struct smb2_close_rsp *rsp = NULL;
3681 	struct cifs_ses *ses = tcon->ses;
3682 	struct TCP_Server_Info *server;
3683 	struct kvec iov[1];
3684 	struct kvec rsp_iov;
3685 	int resp_buftype = CIFS_NO_BUFFER;
3686 	int rc = 0;
3687 	int flags = 0;
3688 	bool query_attrs = false;
3689 	int retries = 0, cur_sleep = 0;
3690 
3691 replay_again:
3692 	/* reinitialize for possible replay */
3693 	flags = 0;
3694 	query_attrs = false;
3695 	server = cifs_pick_channel(ses);
3696 
3697 	cifs_dbg(FYI, "Close\n");
3698 
3699 	if (!ses || !server)
3700 		return smb_EIO(smb_eio_trace_null_pointers);
3701 
3702 	if (smb3_encryption_required(tcon))
3703 		flags |= CIFS_TRANSFORM_REQ;
3704 
3705 	memset(&rqst, 0, sizeof(struct smb_rqst));
3706 	memset(&iov, 0, sizeof(iov));
3707 	rqst.rq_iov = iov;
3708 	rqst.rq_nvec = 1;
3709 
3710 	/* check if need to ask server to return timestamps in close response */
3711 	if (pbuf)
3712 		query_attrs = true;
3713 
3714 	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3715 	rc = SMB2_close_init(tcon, server,
3716 			     &rqst, persistent_fid, volatile_fid,
3717 			     query_attrs);
3718 	if (rc)
3719 		goto close_exit;
3720 
3721 	if (retries) {
3722 		/* Back-off before retry */
3723 		if (cur_sleep)
3724 			msleep(cur_sleep);
3725 		smb2_set_replay(server, &rqst);
3726 	}
3727 
3728 	rc = cifs_send_recv(xid, ses, server,
3729 			    &rqst, &resp_buftype, flags, &rsp_iov);
3730 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3731 
3732 	if (rc != 0) {
3733 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3734 		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3735 				     rc);
3736 		goto close_exit;
3737 	} else {
3738 		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3739 				      ses->Suid);
3740 		if (pbuf)
3741 			memcpy(&pbuf->network_open_info,
3742 			       &rsp->network_open_info,
3743 			       sizeof(pbuf->network_open_info));
3744 		atomic_dec(&tcon->num_remote_opens);
3745 	}
3746 
3747 close_exit:
3748 	SMB2_close_free(&rqst);
3749 	free_rsp_buf(resp_buftype, rsp);
3750 
3751 	/* retry close in a worker thread if this one is interrupted */
3752 	if (is_interrupt_error(rc)) {
3753 		int tmp_rc;
3754 
3755 		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3756 						     volatile_fid);
3757 		if (tmp_rc)
3758 			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3759 				 persistent_fid, tmp_rc);
3760 	}
3761 
3762 	if (is_replayable_error(rc) &&
3763 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3764 		goto replay_again;
3765 
3766 	return rc;
3767 }
3768 
3769 int
SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3770 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3771 		u64 persistent_fid, u64 volatile_fid)
3772 {
3773 	return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3774 }
3775 
3776 int
smb2_validate_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int min_buf_size)3777 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3778 		  struct kvec *iov, unsigned int min_buf_size)
3779 {
3780 	unsigned int smb_len = iov->iov_len;
3781 	char *end_of_smb = smb_len + (char *)iov->iov_base;
3782 	char *begin_of_buf = offset + (char *)iov->iov_base;
3783 	char *end_of_buf = begin_of_buf + buffer_length;
3784 
3785 
3786 	if (buffer_length < min_buf_size) {
3787 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3788 			 buffer_length, min_buf_size);
3789 		return -EINVAL;
3790 	}
3791 
3792 	/* check if beyond RFC1001 maximum length */
3793 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3794 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3795 			 buffer_length, smb_len);
3796 		return -EINVAL;
3797 	}
3798 
3799 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3800 		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3801 		return -EINVAL;
3802 	}
3803 
3804 	return 0;
3805 }
3806 
3807 /*
3808  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3809  * Caller must free buffer.
3810  */
3811 int
smb2_validate_and_copy_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int minbufsize,char * data)3812 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3813 			   struct kvec *iov, unsigned int minbufsize,
3814 			   char *data)
3815 {
3816 	char *begin_of_buf = offset + (char *)iov->iov_base;
3817 	int rc;
3818 
3819 	if (!data)
3820 		return -EINVAL;
3821 
3822 	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3823 	if (rc)
3824 		return rc;
3825 
3826 	memcpy(data, begin_of_buf, minbufsize);
3827 
3828 	return 0;
3829 }
3830 
3831 int
SMB2_query_info_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len,size_t input_len,void * input)3832 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3833 		     struct smb_rqst *rqst,
3834 		     u64 persistent_fid, u64 volatile_fid,
3835 		     u8 info_class, u8 info_type, u32 additional_info,
3836 		     size_t output_len, size_t input_len, void *input)
3837 {
3838 	struct smb2_query_info_req *req;
3839 	struct kvec *iov = rqst->rq_iov;
3840 	unsigned int total_len;
3841 	size_t len;
3842 	int rc;
3843 
3844 	if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
3845 		     len > CIFSMaxBufSize))
3846 		return -EINVAL;
3847 
3848 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3849 				 (void **) &req, &total_len);
3850 	if (rc)
3851 		return rc;
3852 
3853 	req->InfoType = info_type;
3854 	req->FileInfoClass = info_class;
3855 	req->PersistentFileId = persistent_fid;
3856 	req->VolatileFileId = volatile_fid;
3857 	req->AdditionalInformation = cpu_to_le32(additional_info);
3858 
3859 	req->OutputBufferLength = cpu_to_le32(output_len);
3860 	if (input_len) {
3861 		req->InputBufferLength = cpu_to_le32(input_len);
3862 		/* total_len for smb query request never close to le16 max */
3863 		req->InputBufferOffset = cpu_to_le16(total_len - 1);
3864 		memcpy(req->Buffer, input, input_len);
3865 	}
3866 
3867 	iov[0].iov_base = (char *)req;
3868 	/* 1 for Buffer */
3869 	iov[0].iov_len = len;
3870 	return 0;
3871 }
3872 
3873 void
SMB2_query_info_free(struct smb_rqst * rqst)3874 SMB2_query_info_free(struct smb_rqst *rqst)
3875 {
3876 	if (rqst && rqst->rq_iov)
3877 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3878 }
3879 
3880 static int
query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len,size_t min_len,void ** data,u32 * dlen)3881 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3882 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3883 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
3884 		u32 *dlen)
3885 {
3886 	struct smb_rqst rqst;
3887 	struct smb2_query_info_rsp *rsp = NULL;
3888 	struct kvec iov[1];
3889 	struct kvec rsp_iov;
3890 	int rc = 0;
3891 	int resp_buftype = CIFS_NO_BUFFER;
3892 	struct cifs_ses *ses = tcon->ses;
3893 	struct TCP_Server_Info *server;
3894 	int flags = 0;
3895 	bool allocated = false;
3896 	int retries = 0, cur_sleep = 0;
3897 
3898 	cifs_dbg(FYI, "Query Info\n");
3899 
3900 	if (!ses)
3901 		return smb_EIO(smb_eio_trace_null_pointers);
3902 
3903 replay_again:
3904 	/* reinitialize for possible replay */
3905 	flags = 0;
3906 	allocated = false;
3907 	server = cifs_pick_channel(ses);
3908 
3909 	if (!server)
3910 		return smb_EIO(smb_eio_trace_null_pointers);
3911 
3912 	if (smb3_encryption_required(tcon))
3913 		flags |= CIFS_TRANSFORM_REQ;
3914 
3915 	memset(&rqst, 0, sizeof(struct smb_rqst));
3916 	memset(&iov, 0, sizeof(iov));
3917 	rqst.rq_iov = iov;
3918 	rqst.rq_nvec = 1;
3919 
3920 	rc = SMB2_query_info_init(tcon, server,
3921 				  &rqst, persistent_fid, volatile_fid,
3922 				  info_class, info_type, additional_info,
3923 				  output_len, 0, NULL);
3924 	if (rc)
3925 		goto qinf_exit;
3926 
3927 	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3928 				    ses->Suid, info_class, (__u32)info_type);
3929 
3930 	if (retries) {
3931 		/* Back-off before retry */
3932 		if (cur_sleep)
3933 			msleep(cur_sleep);
3934 		smb2_set_replay(server, &rqst);
3935 	}
3936 
3937 	rc = cifs_send_recv(xid, ses, server,
3938 			    &rqst, &resp_buftype, flags, &rsp_iov);
3939 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3940 
3941 	if (rc) {
3942 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3943 		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3944 				ses->Suid, info_class, (__u32)info_type, rc);
3945 		goto qinf_exit;
3946 	}
3947 
3948 	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3949 				ses->Suid, info_class, (__u32)info_type);
3950 
3951 	if (dlen) {
3952 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
3953 		if (!*data) {
3954 			*data = kmalloc(*dlen, GFP_KERNEL);
3955 			if (!*data) {
3956 				cifs_tcon_dbg(VFS,
3957 					"Error %d allocating memory for acl\n",
3958 					rc);
3959 				*dlen = 0;
3960 				rc = -ENOMEM;
3961 				goto qinf_exit;
3962 			}
3963 			allocated = true;
3964 		}
3965 	}
3966 
3967 	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3968 					le32_to_cpu(rsp->OutputBufferLength),
3969 					&rsp_iov, dlen ? *dlen : min_len, *data);
3970 	if (rc && allocated) {
3971 		kfree(*data);
3972 		*data = NULL;
3973 		*dlen = 0;
3974 	}
3975 
3976 qinf_exit:
3977 	SMB2_query_info_free(&rqst);
3978 	free_rsp_buf(resp_buftype, rsp);
3979 
3980 	if (is_replayable_error(rc) &&
3981 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3982 		goto replay_again;
3983 
3984 	return rc;
3985 }
3986 
SMB2_query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_all_info * data)3987 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3988 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3989 {
3990 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3991 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3992 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3993 			  sizeof(struct smb2_file_all_info), (void **)&data,
3994 			  NULL);
3995 }
3996 
3997 #if 0
3998 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3999 int
4000 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
4001 			u64 persistent_fid, u64 volatile_fid,
4002 			struct smb311_posix_qinfo *data, u32 *plen)
4003 {
4004 	size_t output_len = sizeof(struct smb311_posix_qinfo *) +
4005 			(sizeof(struct smb_sid) * 2) + (PATH_MAX * 2);
4006 	*plen = 0;
4007 
4008 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4009 			  SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
4010 			  output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
4011 	/* Note caller must free "data" (passed in above). It may be allocated in query_info call */
4012 }
4013 #endif
4014 
4015 int
SMB2_query_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,void ** data,u32 * plen,u32 extra_info)4016 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
4017 	       u64 persistent_fid, u64 volatile_fid,
4018 	       void **data, u32 *plen, u32 extra_info)
4019 {
4020 	*plen = 0;
4021 
4022 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4023 			  0, SMB2_O_INFO_SECURITY, extra_info,
4024 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
4025 }
4026 
4027 int
SMB2_get_srv_num(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le64 * uniqueid)4028 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
4029 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
4030 {
4031 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4032 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
4033 			  sizeof(struct smb2_file_internal_info),
4034 			  sizeof(struct smb2_file_internal_info),
4035 			  (void **)&uniqueid, NULL);
4036 }
4037 
4038 /*
4039  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
4040  * See MS-SMB2 2.2.35 and 2.2.36
4041  */
4042 
4043 static int
SMB2_notify_init(const unsigned int xid,struct smb_rqst * rqst,struct cifs_tcon * tcon,struct TCP_Server_Info * server,u64 persistent_fid,u64 volatile_fid,u32 completion_filter,bool watch_tree)4044 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
4045 		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4046 		 u64 persistent_fid, u64 volatile_fid,
4047 		 u32 completion_filter, bool watch_tree)
4048 {
4049 	struct smb2_change_notify_req *req;
4050 	struct kvec *iov = rqst->rq_iov;
4051 	unsigned int total_len;
4052 	int rc;
4053 
4054 	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
4055 				 (void **) &req, &total_len);
4056 	if (rc)
4057 		return rc;
4058 
4059 	req->PersistentFileId = persistent_fid;
4060 	req->VolatileFileId = volatile_fid;
4061 	/* See note 354 of MS-SMB2, 64K max */
4062 	req->OutputBufferLength =
4063 		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
4064 	req->CompletionFilter = cpu_to_le32(completion_filter);
4065 	if (watch_tree)
4066 		req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
4067 	else
4068 		req->Flags = 0;
4069 
4070 	iov[0].iov_base = (char *)req;
4071 	iov[0].iov_len = total_len;
4072 
4073 	return 0;
4074 }
4075 
4076 int
SMB2_change_notify(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,bool watch_tree,u32 completion_filter,u32 max_out_data_len,char ** out_data,u32 * plen)4077 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
4078 		u64 persistent_fid, u64 volatile_fid, bool watch_tree,
4079 		u32 completion_filter, u32 max_out_data_len, char **out_data,
4080 		u32 *plen /* returned data len */)
4081 {
4082 	struct cifs_ses *ses = tcon->ses;
4083 	struct TCP_Server_Info *server;
4084 	struct smb_rqst rqst;
4085 	struct smb2_change_notify_rsp *smb_rsp;
4086 	struct kvec iov[1];
4087 	struct kvec rsp_iov = {NULL, 0};
4088 	int resp_buftype = CIFS_NO_BUFFER;
4089 	int flags = 0;
4090 	int rc = 0;
4091 	int retries = 0, cur_sleep = 0;
4092 
4093 replay_again:
4094 	/* reinitialize for possible replay */
4095 	flags = 0;
4096 	server = cifs_pick_channel(ses);
4097 
4098 	cifs_dbg(FYI, "change notify\n");
4099 	if (!ses || !server)
4100 		return smb_EIO(smb_eio_trace_null_pointers);
4101 
4102 	if (smb3_encryption_required(tcon))
4103 		flags |= CIFS_TRANSFORM_REQ;
4104 
4105 	memset(&rqst, 0, sizeof(struct smb_rqst));
4106 	memset(&iov, 0, sizeof(iov));
4107 	if (plen)
4108 		*plen = 0;
4109 
4110 	rqst.rq_iov = iov;
4111 	rqst.rq_nvec = 1;
4112 
4113 	rc = SMB2_notify_init(xid, &rqst, tcon, server,
4114 			      persistent_fid, volatile_fid,
4115 			      completion_filter, watch_tree);
4116 	if (rc)
4117 		goto cnotify_exit;
4118 
4119 	trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
4120 				(u8)watch_tree, completion_filter);
4121 
4122 	if (retries) {
4123 		/* Back-off before retry */
4124 		if (cur_sleep)
4125 			msleep(cur_sleep);
4126 		smb2_set_replay(server, &rqst);
4127 	}
4128 
4129 	rc = cifs_send_recv(xid, ses, server,
4130 			    &rqst, &resp_buftype, flags, &rsp_iov);
4131 
4132 	if (rc != 0) {
4133 		cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
4134 		trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
4135 				(u8)watch_tree, completion_filter, rc);
4136 	} else {
4137 		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
4138 			ses->Suid, (u8)watch_tree, completion_filter);
4139 		/* validate that notify information is plausible */
4140 		if ((rsp_iov.iov_base == NULL) ||
4141 		    (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
4142 			goto cnotify_exit;
4143 
4144 		smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
4145 
4146 		rc = smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
4147 				le32_to_cpu(smb_rsp->OutputBufferLength),
4148 				&rsp_iov,
4149 				sizeof(struct file_notify_information));
4150 		if (rc)
4151 			goto cnotify_exit;
4152 
4153 		*out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
4154 				le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
4155 		if (*out_data == NULL) {
4156 			rc = -ENOMEM;
4157 			goto cnotify_exit;
4158 		} else if (plen)
4159 			*plen = le32_to_cpu(smb_rsp->OutputBufferLength);
4160 	}
4161 
4162  cnotify_exit:
4163 	if (rqst.rq_iov)
4164 		cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
4165 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4166 
4167 	if (is_replayable_error(rc) &&
4168 	    smb2_should_replay(tcon, &retries, &cur_sleep))
4169 		goto replay_again;
4170 
4171 	return rc;
4172 }
4173 
4174 
4175 
4176 /*
4177  * This is a no-op for now. We're not really interested in the reply, but
4178  * rather in the fact that the server sent one and that server->lstrp
4179  * gets updated.
4180  *
4181  * FIXME: maybe we should consider checking that the reply matches request?
4182  */
4183 static void
smb2_echo_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)4184 smb2_echo_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4185 {
4186 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
4187 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4188 
4189 	if (mid->mid_state == MID_RESPONSE_RECEIVED
4190 	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
4191 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4192 		credits.instance = server->reconnect_instance;
4193 	}
4194 
4195 	release_mid(server, mid);
4196 	add_credits(server, &credits, CIFS_ECHO_OP);
4197 }
4198 
cifs_renegotiate_iosize(struct TCP_Server_Info * server,struct cifs_tcon * tcon)4199 static void cifs_renegotiate_iosize(struct TCP_Server_Info *server,
4200 				    struct cifs_tcon *tcon)
4201 {
4202 	struct cifs_sb_info *cifs_sb;
4203 
4204 	if (server == NULL || tcon == NULL)
4205 		return;
4206 
4207 	spin_lock(&tcon->sb_list_lock);
4208 	list_for_each_entry(cifs_sb, &tcon->cifs_sb_list, tcon_sb_link)
4209 		cifs_negotiate_iosize(server, cifs_sb->ctx, tcon);
4210 	spin_unlock(&tcon->sb_list_lock);
4211 }
4212 
smb2_reconnect_server(struct work_struct * work)4213 void smb2_reconnect_server(struct work_struct *work)
4214 {
4215 	struct TCP_Server_Info *server = container_of(work,
4216 					struct TCP_Server_Info, reconnect.work);
4217 	struct TCP_Server_Info *pserver;
4218 	struct cifs_ses *ses, *ses2;
4219 	struct cifs_tcon *tcon, *tcon2;
4220 	struct list_head tmp_list, tmp_ses_list;
4221 	bool ses_exist = false;
4222 	bool tcon_selected = false;
4223 	int rc;
4224 	bool resched = false;
4225 
4226 	/* first check if ref count has reached 0, if not inc ref count */
4227 	spin_lock(&cifs_tcp_ses_lock);
4228 	if (!server->srv_count) {
4229 		spin_unlock(&cifs_tcp_ses_lock);
4230 		return;
4231 	}
4232 	server->srv_count++;
4233 	spin_unlock(&cifs_tcp_ses_lock);
4234 
4235 	/* If server is a channel, select the primary channel */
4236 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4237 
4238 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
4239 	mutex_lock(&pserver->reconnect_mutex);
4240 
4241 	/* if the server is marked for termination, drop the ref count here */
4242 	if (server->terminate) {
4243 		cifs_put_tcp_session(server, true);
4244 		mutex_unlock(&pserver->reconnect_mutex);
4245 		return;
4246 	}
4247 
4248 	INIT_LIST_HEAD(&tmp_list);
4249 	INIT_LIST_HEAD(&tmp_ses_list);
4250 	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4251 
4252 	spin_lock(&cifs_tcp_ses_lock);
4253 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4254 		spin_lock(&ses->ses_lock);
4255 		if (ses->ses_status == SES_EXITING) {
4256 			spin_unlock(&ses->ses_lock);
4257 			continue;
4258 		}
4259 		spin_unlock(&ses->ses_lock);
4260 
4261 		tcon_selected = false;
4262 
4263 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4264 			if (tcon->need_reconnect || tcon->need_reopen_files) {
4265 				spin_lock(&tcon->tc_lock);
4266 				tcon->tc_count++;
4267 				spin_unlock(&tcon->tc_lock);
4268 				trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
4269 						    netfs_trace_tcon_ref_get_reconnect_server);
4270 				list_add_tail(&tcon->rlist, &tmp_list);
4271 				tcon_selected = true;
4272 			}
4273 		}
4274 		/*
4275 		 * IPC has the same lifetime as its session and uses its
4276 		 * refcount.
4277 		 */
4278 		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
4279 			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4280 			tcon_selected = true;
4281 			cifs_smb_ses_inc_refcount(ses);
4282 		}
4283 		/*
4284 		 * handle the case where channel needs to reconnect
4285 		 * binding session, but tcon is healthy (some other channel
4286 		 * is active)
4287 		 */
4288 		spin_lock(&ses->chan_lock);
4289 		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
4290 			list_add_tail(&ses->rlist, &tmp_ses_list);
4291 			ses_exist = true;
4292 			cifs_smb_ses_inc_refcount(ses);
4293 		}
4294 		spin_unlock(&ses->chan_lock);
4295 	}
4296 	spin_unlock(&cifs_tcp_ses_lock);
4297 
4298 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4299 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4300 		if (!rc) {
4301 			cifs_renegotiate_iosize(server, tcon);
4302 			cifs_reopen_persistent_handles(tcon);
4303 		} else
4304 			resched = true;
4305 		list_del_init(&tcon->rlist);
4306 		if (tcon->ipc)
4307 			cifs_put_smb_ses(tcon->ses);
4308 		else
4309 			cifs_put_tcon(tcon, netfs_trace_tcon_ref_put_reconnect_server);
4310 	}
4311 
4312 	if (!ses_exist)
4313 		goto done;
4314 
4315 	/* allocate a dummy tcon struct used for reconnect */
4316 	tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_reconnect_server);
4317 	if (!tcon) {
4318 		resched = true;
4319 		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4320 			list_del_init(&ses->rlist);
4321 			cifs_put_smb_ses(ses);
4322 		}
4323 		goto done;
4324 	}
4325 	tcon->status = TID_GOOD;
4326 	tcon->dummy = true;
4327 
4328 	/* now reconnect sessions for necessary channels */
4329 	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4330 		tcon->ses = ses;
4331 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4332 		if (rc)
4333 			resched = true;
4334 		list_del_init(&ses->rlist);
4335 		cifs_put_smb_ses(ses);
4336 	}
4337 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_reconnect_server);
4338 
4339 done:
4340 	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4341 	if (resched)
4342 		cifs_requeue_server_reconn(server);
4343 	mutex_unlock(&pserver->reconnect_mutex);
4344 
4345 	/* now we can safely release srv struct */
4346 	cifs_put_tcp_session(server, true);
4347 }
4348 
4349 int
SMB2_echo(struct TCP_Server_Info * server)4350 SMB2_echo(struct TCP_Server_Info *server)
4351 {
4352 	struct smb2_echo_req *req;
4353 	int rc = 0;
4354 	struct kvec iov[1];
4355 	struct smb_rqst rqst = { .rq_iov = iov,
4356 				 .rq_nvec = 1 };
4357 	unsigned int total_len;
4358 
4359 	cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
4360 
4361 	spin_lock(&server->srv_lock);
4362 	if (server->ops->need_neg &&
4363 	    server->ops->need_neg(server)) {
4364 		spin_unlock(&server->srv_lock);
4365 		/* No need to send echo on newly established connections */
4366 		cifs_queue_server_reconn(server);
4367 		return rc;
4368 	}
4369 	spin_unlock(&server->srv_lock);
4370 
4371 	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
4372 				 (void **)&req, &total_len);
4373 	if (rc)
4374 		return rc;
4375 
4376 	req->hdr.CreditRequest = cpu_to_le16(1);
4377 
4378 	iov[0].iov_len = total_len;
4379 	iov[0].iov_base = (char *)req;
4380 
4381 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4382 			     server, CIFS_ECHO_OP, NULL);
4383 	if (rc)
4384 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4385 
4386 	cifs_small_buf_release(req);
4387 	return rc;
4388 }
4389 
4390 void
SMB2_flush_free(struct smb_rqst * rqst)4391 SMB2_flush_free(struct smb_rqst *rqst)
4392 {
4393 	if (rqst && rqst->rq_iov)
4394 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4395 }
4396 
4397 int
SMB2_flush_init(const unsigned int xid,struct smb_rqst * rqst,struct cifs_tcon * tcon,struct TCP_Server_Info * server,u64 persistent_fid,u64 volatile_fid)4398 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4399 		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4400 		u64 persistent_fid, u64 volatile_fid)
4401 {
4402 	struct smb2_flush_req *req;
4403 	struct kvec *iov = rqst->rq_iov;
4404 	unsigned int total_len;
4405 	int rc;
4406 
4407 	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
4408 				 (void **) &req, &total_len);
4409 	if (rc)
4410 		return rc;
4411 
4412 	req->PersistentFileId = persistent_fid;
4413 	req->VolatileFileId = volatile_fid;
4414 
4415 	iov[0].iov_base = (char *)req;
4416 	iov[0].iov_len = total_len;
4417 
4418 	return 0;
4419 }
4420 
4421 int
SMB2_flush(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)4422 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4423 	   u64 volatile_fid)
4424 {
4425 	struct cifs_ses *ses = tcon->ses;
4426 	struct smb_rqst rqst;
4427 	struct kvec iov[1];
4428 	struct kvec rsp_iov = {NULL, 0};
4429 	struct TCP_Server_Info *server;
4430 	int resp_buftype = CIFS_NO_BUFFER;
4431 	int flags = 0;
4432 	int rc = 0;
4433 	int retries = 0, cur_sleep = 0;
4434 
4435 replay_again:
4436 	/* reinitialize for possible replay */
4437 	flags = 0;
4438 	server = cifs_pick_channel(ses);
4439 
4440 	cifs_dbg(FYI, "flush\n");
4441 	if (!ses || !(ses->server))
4442 		return smb_EIO(smb_eio_trace_null_pointers);
4443 
4444 	if (smb3_encryption_required(tcon))
4445 		flags |= CIFS_TRANSFORM_REQ;
4446 
4447 	memset(&rqst, 0, sizeof(struct smb_rqst));
4448 	memset(&iov, 0, sizeof(iov));
4449 	rqst.rq_iov = iov;
4450 	rqst.rq_nvec = 1;
4451 
4452 	rc = SMB2_flush_init(xid, &rqst, tcon, server,
4453 			     persistent_fid, volatile_fid);
4454 	if (rc)
4455 		goto flush_exit;
4456 
4457 	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4458 
4459 	if (retries) {
4460 		/* Back-off before retry */
4461 		if (cur_sleep)
4462 			msleep(cur_sleep);
4463 		smb2_set_replay(server, &rqst);
4464 	}
4465 
4466 	rc = cifs_send_recv(xid, ses, server,
4467 			    &rqst, &resp_buftype, flags, &rsp_iov);
4468 
4469 	if (rc != 0) {
4470 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4471 		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4472 				     rc);
4473 	} else
4474 		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4475 				      ses->Suid);
4476 
4477  flush_exit:
4478 	SMB2_flush_free(&rqst);
4479 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4480 
4481 	if (is_replayable_error(rc) &&
4482 	    smb2_should_replay(tcon, &retries, &cur_sleep))
4483 		goto replay_again;
4484 
4485 	return rc;
4486 }
4487 
4488 #ifdef CONFIG_CIFS_SMB_DIRECT
smb3_use_rdma_offload(struct cifs_io_parms * io_parms)4489 static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
4490 {
4491 	struct TCP_Server_Info *server = io_parms->server;
4492 	struct cifs_tcon *tcon = io_parms->tcon;
4493 
4494 	/* we can only offload if we're connected */
4495 	if (!server || !tcon)
4496 		return false;
4497 
4498 	/* we can only offload on an rdma connection */
4499 	if (!server->rdma || !server->smbd_conn)
4500 		return false;
4501 
4502 	/* we don't support signed offload yet */
4503 	if (server->sign)
4504 		return false;
4505 
4506 	/* we don't support encrypted offload yet */
4507 	if (smb3_encryption_required(tcon))
4508 		return false;
4509 
4510 	/* offload also has its overhead, so only do it if desired */
4511 	if (io_parms->length < server->rdma_readwrite_threshold)
4512 		return false;
4513 
4514 	return true;
4515 }
4516 #endif /* CONFIG_CIFS_SMB_DIRECT */
4517 
4518 /*
4519  * To form a chain of read requests, any read requests after the first should
4520  * have the end_of_chain boolean set to true.
4521  */
4522 static int
smb2_new_read_req(void ** buf,unsigned int * total_len,struct cifs_io_parms * io_parms,struct cifs_io_subrequest * rdata,unsigned int remaining_bytes,int request_type)4523 smb2_new_read_req(void **buf, unsigned int *total_len,
4524 	struct cifs_io_parms *io_parms, struct cifs_io_subrequest *rdata,
4525 	unsigned int remaining_bytes, int request_type)
4526 {
4527 	int rc = -EACCES;
4528 	struct smb2_read_req *req = NULL;
4529 	struct smb2_hdr *shdr;
4530 	struct TCP_Server_Info *server = io_parms->server;
4531 
4532 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4533 				 (void **) &req, total_len);
4534 	if (rc)
4535 		return rc;
4536 
4537 	if (server == NULL)
4538 		return -ECONNABORTED;
4539 
4540 	shdr = &req->hdr;
4541 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4542 
4543 	req->PersistentFileId = io_parms->persistent_fid;
4544 	req->VolatileFileId = io_parms->volatile_fid;
4545 	req->ReadChannelInfoOffset = 0; /* reserved */
4546 	req->ReadChannelInfoLength = 0; /* reserved */
4547 	req->Channel = 0; /* reserved */
4548 	req->MinimumCount = 0;
4549 	req->Length = cpu_to_le32(io_parms->length);
4550 	req->Offset = cpu_to_le64(io_parms->offset);
4551 
4552 	trace_smb3_read_enter(rdata ? rdata->rreq->debug_id : 0,
4553 			      rdata ? rdata->subreq.debug_index : 0,
4554 			      rdata ? rdata->xid : 0,
4555 			      io_parms->persistent_fid,
4556 			      io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4557 			      io_parms->offset, io_parms->length);
4558 #ifdef CONFIG_CIFS_SMB_DIRECT
4559 	/*
4560 	 * If we want to do a RDMA write, fill in and append
4561 	 * smbdirect_buffer_descriptor_v1 to the end of read request
4562 	 */
4563 	if (rdata && smb3_use_rdma_offload(io_parms)) {
4564 		struct smbdirect_buffer_descriptor_v1 *v1;
4565 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4566 
4567 		rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->subreq.io_iter,
4568 					     true, need_invalidate);
4569 		if (!rdata->mr)
4570 			return -EAGAIN;
4571 
4572 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4573 		if (need_invalidate)
4574 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4575 		req->ReadChannelInfoOffset =
4576 			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4577 		req->ReadChannelInfoLength =
4578 			cpu_to_le16(sizeof(struct smbdirect_buffer_descriptor_v1));
4579 		v1 = (struct smbdirect_buffer_descriptor_v1 *) &req->Buffer[0];
4580 		v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4581 		v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4582 		v1->length = cpu_to_le32(rdata->mr->mr->length);
4583 
4584 		*total_len += sizeof(*v1) - 1;
4585 	}
4586 #endif
4587 	if (request_type & CHAINED_REQUEST) {
4588 		if (!(request_type & END_OF_CHAIN)) {
4589 			/* next 8-byte aligned request */
4590 			*total_len = ALIGN(*total_len, 8);
4591 			shdr->NextCommand = cpu_to_le32(*total_len);
4592 		} else /* END_OF_CHAIN */
4593 			shdr->NextCommand = 0;
4594 		if (request_type & RELATED_REQUEST) {
4595 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4596 			/*
4597 			 * Related requests use info from previous read request
4598 			 * in chain.
4599 			 */
4600 			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4601 			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4602 			req->PersistentFileId = (u64)-1;
4603 			req->VolatileFileId = (u64)-1;
4604 		}
4605 	}
4606 	if (remaining_bytes > io_parms->length)
4607 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
4608 	else
4609 		req->RemainingBytes = 0;
4610 
4611 	*buf = req;
4612 	return rc;
4613 }
4614 
4615 static void
smb2_readv_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)4616 smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4617 {
4618 	struct cifs_io_subrequest *rdata = mid->callback_data;
4619 	struct netfs_inode *ictx = netfs_inode(rdata->rreq->inode);
4620 	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4621 	struct smb2_hdr *shdr = (struct smb2_hdr *)rdata->iov[0].iov_base;
4622 	struct cifs_credits credits = {
4623 		.value = 0,
4624 		.instance = 0,
4625 		.rreq_debug_id = rdata->rreq->debug_id,
4626 		.rreq_debug_index = rdata->subreq.debug_index,
4627 	};
4628 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[0], .rq_nvec = 1 };
4629 	unsigned int rreq_debug_id = rdata->rreq->debug_id;
4630 	unsigned int subreq_debug_index = rdata->subreq.debug_index;
4631 
4632 	if (rdata->got_bytes) {
4633 		rqst.rq_iter	  = rdata->subreq.io_iter;
4634 	}
4635 
4636 	WARN_ONCE(rdata->server != server,
4637 		  "rdata server %p != mid server %p",
4638 		  rdata->server, server);
4639 
4640 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%zu/%zu\n",
4641 		 __func__, mid->mid, mid->mid_state, rdata->result,
4642 		 rdata->got_bytes, rdata->subreq.len - rdata->subreq.transferred);
4643 
4644 	switch (mid->mid_state) {
4645 	case MID_RESPONSE_RECEIVED:
4646 		credits.value = le16_to_cpu(shdr->CreditRequest);
4647 		credits.instance = server->reconnect_instance;
4648 		/* result already set, check signature */
4649 		if (server->sign && !mid->decrypted) {
4650 			int rc;
4651 
4652 			iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4653 			rc = smb2_verify_signature(&rqst, server);
4654 			if (rc) {
4655 				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4656 					      rc);
4657 				rdata->subreq.error = rc;
4658 				rdata->result = rc;
4659 
4660 				if (is_replayable_error(rc)) {
4661 					trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4662 					__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4663 				} else
4664 					trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_bad);
4665 			} else
4666 				trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_progress);
4667 		}
4668 		/* FIXME: should this be counted toward the initiating task? */
4669 		task_io_account_read(rdata->got_bytes);
4670 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4671 		break;
4672 	case MID_REQUEST_SUBMITTED:
4673 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_req_submitted);
4674 		goto do_retry;
4675 	case MID_RETRY_NEEDED:
4676 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4677 do_retry:
4678 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4679 		rdata->result = -EAGAIN;
4680 		if (server->sign && rdata->got_bytes)
4681 			/* reset bytes number since we can not check a sign */
4682 			rdata->got_bytes = 0;
4683 		/* FIXME: should this be counted toward the initiating task? */
4684 		task_io_account_read(rdata->got_bytes);
4685 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4686 		break;
4687 	case MID_RESPONSE_MALFORMED:
4688 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_malformed);
4689 		credits.value = le16_to_cpu(shdr->CreditRequest);
4690 		credits.instance = server->reconnect_instance;
4691 		rdata->result = smb_EIO(smb_eio_trace_read_rsp_malformed);
4692 		break;
4693 	default:
4694 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_unknown);
4695 		rdata->result = smb_EIO1(smb_eio_trace_read_mid_state_unknown,
4696 					 mid->mid_state);
4697 		break;
4698 	}
4699 #ifdef CONFIG_CIFS_SMB_DIRECT
4700 	/*
4701 	 * If this rdata has a memory registered, the MR can be freed
4702 	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
4703 	 * because they have limited number and are used for future I/Os
4704 	 */
4705 	if (rdata->mr) {
4706 		smbd_deregister_mr(rdata->mr);
4707 		rdata->mr = NULL;
4708 	}
4709 #endif
4710 	if (rdata->result && rdata->result != -ENODATA) {
4711 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4712 		trace_smb3_read_err(rdata->rreq->debug_id,
4713 				    rdata->subreq.debug_index,
4714 				    rdata->xid,
4715 				    rdata->req->cfile->fid.persistent_fid,
4716 				    tcon->tid, tcon->ses->Suid,
4717 				    rdata->subreq.start + rdata->subreq.transferred,
4718 				    rdata->subreq.len   - rdata->subreq.transferred,
4719 				    rdata->result);
4720 	} else
4721 		trace_smb3_read_done(rdata->rreq->debug_id,
4722 				     rdata->subreq.debug_index,
4723 				     rdata->xid,
4724 				     rdata->req->cfile->fid.persistent_fid,
4725 				     tcon->tid, tcon->ses->Suid,
4726 				     rdata->subreq.start + rdata->subreq.transferred,
4727 				     rdata->got_bytes);
4728 
4729 	if (rdata->result == -ENODATA) {
4730 		__set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4731 		rdata->result = 0;
4732 	} else {
4733 		size_t trans = rdata->subreq.transferred + rdata->got_bytes;
4734 		if (trans < rdata->subreq.len &&
4735 		    rdata->subreq.start + trans >= ictx->remote_i_size) {
4736 			__set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4737 			rdata->result = 0;
4738 		}
4739 		if (rdata->got_bytes)
4740 			__set_bit(NETFS_SREQ_MADE_PROGRESS, &rdata->subreq.flags);
4741 	}
4742 
4743 	/* see if we need to retry */
4744 	if (is_replayable_error(rdata->result) &&
4745 	    smb2_should_replay(tcon,
4746 			       &rdata->retries,
4747 			       &rdata->cur_sleep))
4748 		rdata->replay = true;
4749 
4750 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
4751 			      server->credits, server->in_flight,
4752 			      0, cifs_trace_rw_credits_read_response_clear);
4753 	rdata->credits.value = 0;
4754 	rdata->subreq.error = rdata->result;
4755 	rdata->subreq.transferred += rdata->got_bytes;
4756 	trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_progress);
4757 	netfs_read_subreq_terminated(&rdata->subreq);
4758 	release_mid(server, mid);
4759 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
4760 			      server->credits, server->in_flight,
4761 			      credits.value, cifs_trace_rw_credits_read_response_add);
4762 	add_credits(server, &credits, 0);
4763 }
4764 
4765 /* smb2_async_readv - send an async read, and set up mid to handle result */
4766 int
smb2_async_readv(struct cifs_io_subrequest * rdata)4767 smb2_async_readv(struct cifs_io_subrequest *rdata)
4768 {
4769 	int rc, flags = 0;
4770 	char *buf;
4771 	struct netfs_io_subrequest *subreq = &rdata->subreq;
4772 	struct smb2_hdr *shdr;
4773 	struct cifs_io_parms io_parms;
4774 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4775 				 .rq_nvec = 1 };
4776 	struct TCP_Server_Info *server;
4777 	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4778 	unsigned int total_len;
4779 	int credit_request;
4780 
4781 	cifs_dbg(FYI, "%s: offset=%llu bytes=%zu\n",
4782 		 __func__, subreq->start, subreq->len);
4783 
4784 	if (!rdata->server)
4785 		rdata->server = cifs_pick_channel(tcon->ses);
4786 
4787 	io_parms.tcon = tlink_tcon(rdata->req->cfile->tlink);
4788 	io_parms.server = server = rdata->server;
4789 	io_parms.offset = subreq->start + subreq->transferred;
4790 	io_parms.length = subreq->len   - subreq->transferred;
4791 	io_parms.persistent_fid = rdata->req->cfile->fid.persistent_fid;
4792 	io_parms.volatile_fid = rdata->req->cfile->fid.volatile_fid;
4793 	io_parms.pid = rdata->req->pid;
4794 
4795 	rc = smb2_new_read_req(
4796 		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4797 	if (rc)
4798 		goto out;
4799 
4800 	if (smb3_encryption_required(io_parms.tcon))
4801 		flags |= CIFS_TRANSFORM_REQ;
4802 
4803 	rdata->iov[0].iov_base = buf;
4804 	rdata->iov[0].iov_len = total_len;
4805 	rdata->got_bytes = 0;
4806 	rdata->result = 0;
4807 
4808 	shdr = (struct smb2_hdr *)buf;
4809 
4810 	if (rdata->replay) {
4811 		/* Back-off before retry */
4812 		if (rdata->cur_sleep)
4813 			msleep(rdata->cur_sleep);
4814 		smb2_set_replay(server, &rqst);
4815 	}
4816 
4817 	if (rdata->credits.value > 0) {
4818 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length,
4819 						SMB2_MAX_BUFFER_SIZE));
4820 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4821 		if (server->credits >= server->max_credits)
4822 			shdr->CreditRequest = cpu_to_le16(0);
4823 		else
4824 			shdr->CreditRequest = cpu_to_le16(
4825 				min_t(int, server->max_credits -
4826 						server->credits, credit_request));
4827 
4828 		rc = adjust_credits(server, rdata, cifs_trace_rw_credits_call_readv_adjust);
4829 		if (rc)
4830 			goto async_readv_out;
4831 
4832 		flags |= CIFS_HAS_CREDITS;
4833 	}
4834 
4835 	rc = cifs_call_async(server, &rqst,
4836 			     cifs_readv_receive, smb2_readv_callback,
4837 			     smb3_handle_read_data, rdata, flags,
4838 			     &rdata->credits);
4839 	if (rc) {
4840 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4841 		trace_smb3_read_err(rdata->rreq->debug_id,
4842 				    subreq->debug_index,
4843 				    rdata->xid, io_parms.persistent_fid,
4844 				    io_parms.tcon->tid,
4845 				    io_parms.tcon->ses->Suid,
4846 				    io_parms.offset,
4847 				    subreq->len - subreq->transferred, rc);
4848 	}
4849 
4850 async_readv_out:
4851 	cifs_small_buf_release(buf);
4852 
4853 out:
4854 	/* if the send error is retryable, let netfs know about it */
4855 	if (is_replayable_error(rc) &&
4856 	    smb2_should_replay(tcon,
4857 			       &rdata->retries,
4858 			       &rdata->cur_sleep)) {
4859 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4860 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4861 	}
4862 
4863 	return rc;
4864 }
4865 
4866 int
SMB2_read(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,char ** buf,int * buf_type)4867 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4868 	  unsigned int *nbytes, char **buf, int *buf_type)
4869 {
4870 	struct smb_rqst rqst;
4871 	int resp_buftype, rc;
4872 	struct smb2_read_req *req = NULL;
4873 	struct smb2_read_rsp *rsp = NULL;
4874 	struct kvec iov[1];
4875 	struct kvec rsp_iov;
4876 	unsigned int total_len;
4877 	int flags = CIFS_LOG_ERROR;
4878 	struct cifs_ses *ses = io_parms->tcon->ses;
4879 
4880 	if (!io_parms->server)
4881 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4882 
4883 	*nbytes = 0;
4884 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4885 	if (rc)
4886 		return rc;
4887 
4888 	if (smb3_encryption_required(io_parms->tcon))
4889 		flags |= CIFS_TRANSFORM_REQ;
4890 
4891 	iov[0].iov_base = (char *)req;
4892 	iov[0].iov_len = total_len;
4893 
4894 	memset(&rqst, 0, sizeof(struct smb_rqst));
4895 	rqst.rq_iov = iov;
4896 	rqst.rq_nvec = 1;
4897 
4898 	rc = cifs_send_recv(xid, ses, io_parms->server,
4899 			    &rqst, &resp_buftype, flags, &rsp_iov);
4900 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4901 
4902 	if (rc) {
4903 		if (rc != -ENODATA) {
4904 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4905 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
4906 			trace_smb3_read_err(0, 0, xid,
4907 					    req->PersistentFileId,
4908 					    io_parms->tcon->tid, ses->Suid,
4909 					    io_parms->offset, io_parms->length,
4910 					    rc);
4911 		} else
4912 			trace_smb3_read_done(0, 0, xid,
4913 					     req->PersistentFileId, io_parms->tcon->tid,
4914 					     ses->Suid, io_parms->offset, 0);
4915 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4916 		cifs_small_buf_release(req);
4917 		return rc == -ENODATA ? 0 : rc;
4918 	} else
4919 		trace_smb3_read_done(0, 0, xid,
4920 				     req->PersistentFileId,
4921 				     io_parms->tcon->tid, ses->Suid,
4922 				     io_parms->offset, io_parms->length);
4923 
4924 	cifs_small_buf_release(req);
4925 
4926 	*nbytes = le32_to_cpu(rsp->DataLength);
4927 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4928 	    (*nbytes > io_parms->length)) {
4929 		cifs_dbg(FYI, "bad length %d for count %d\n",
4930 			 *nbytes, io_parms->length);
4931 		rc = smb_EIO2(smb_eio_trace_read_overlarge,
4932 			      *nbytes, io_parms->length);
4933 		*nbytes = 0;
4934 	}
4935 
4936 	if (*buf) {
4937 		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4938 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4939 	} else if (resp_buftype != CIFS_NO_BUFFER) {
4940 		*buf = rsp_iov.iov_base;
4941 		if (resp_buftype == CIFS_SMALL_BUFFER)
4942 			*buf_type = CIFS_SMALL_BUFFER;
4943 		else if (resp_buftype == CIFS_LARGE_BUFFER)
4944 			*buf_type = CIFS_LARGE_BUFFER;
4945 	}
4946 	return rc;
4947 }
4948 
4949 /*
4950  * Check the mid_state and signature on received buffer (if any), and queue the
4951  * workqueue completion task.
4952  */
4953 static void
smb2_writev_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)4954 smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4955 {
4956 	struct cifs_io_subrequest *wdata = mid->callback_data;
4957 	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
4958 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4959 	struct cifs_credits credits = {
4960 		.value = 0,
4961 		.instance = 0,
4962 		.rreq_debug_id = wdata->rreq->debug_id,
4963 		.rreq_debug_index = wdata->subreq.debug_index,
4964 	};
4965 	unsigned int rreq_debug_id = wdata->rreq->debug_id;
4966 	unsigned int subreq_debug_index = wdata->subreq.debug_index;
4967 	ssize_t result = 0;
4968 	size_t written;
4969 
4970 	WARN_ONCE(wdata->server != server,
4971 		  "wdata server %p != mid server %p",
4972 		  wdata->server, server);
4973 
4974 	switch (mid->mid_state) {
4975 	case MID_RESPONSE_RECEIVED:
4976 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4977 		credits.instance = server->reconnect_instance;
4978 		result = smb2_check_receive(mid, server, 0);
4979 		if (result != 0) {
4980 			if (is_replayable_error(result)) {
4981 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
4982 				__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
4983 			} else {
4984 				wdata->subreq.error = result;
4985 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_bad);
4986 			}
4987 			break;
4988 		}
4989 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_progress);
4990 
4991 		written = le32_to_cpu(rsp->DataLength);
4992 		/*
4993 		 * Mask off high 16 bits when bytes written as returned
4994 		 * by the server is greater than bytes requested by the
4995 		 * client. OS/2 servers are known to set incorrect
4996 		 * CountHigh values.
4997 		 */
4998 		if (written > wdata->subreq.len)
4999 			written &= 0xFFFF;
5000 
5001 		cifs_stats_bytes_written(tcon, written);
5002 
5003 		if (written < wdata->subreq.len) {
5004 			result = -ENOSPC;
5005 		} else if (written > 0) {
5006 			wdata->subreq.len = written;
5007 			__set_bit(NETFS_SREQ_MADE_PROGRESS, &wdata->subreq.flags);
5008 		}
5009 		break;
5010 	case MID_REQUEST_SUBMITTED:
5011 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted);
5012 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5013 		result = -EAGAIN;
5014 		break;
5015 	case MID_RETRY_NEEDED:
5016 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
5017 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5018 		result = -EAGAIN;
5019 		break;
5020 	case MID_RESPONSE_MALFORMED:
5021 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_malformed);
5022 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
5023 		credits.instance = server->reconnect_instance;
5024 		result = smb_EIO(smb_eio_trace_write_rsp_malformed);
5025 		break;
5026 	default:
5027 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_unknown);
5028 		result = smb_EIO1(smb_eio_trace_write_mid_state_unknown,
5029 				  mid->mid_state);
5030 		break;
5031 	}
5032 #ifdef CONFIG_CIFS_SMB_DIRECT
5033 	/*
5034 	 * If this wdata has a memory registered, the MR can be freed
5035 	 * The number of MRs available is limited, it's important to recover
5036 	 * used MR as soon as I/O is finished. Hold MR longer in the later
5037 	 * I/O process can possibly result in I/O deadlock due to lack of MR
5038 	 * to send request on I/O retry
5039 	 */
5040 	if (wdata->mr) {
5041 		smbd_deregister_mr(wdata->mr);
5042 		wdata->mr = NULL;
5043 	}
5044 #endif
5045 	if (result) {
5046 		wdata->result = result;
5047 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
5048 		trace_smb3_write_err(wdata->rreq->debug_id,
5049 				     wdata->subreq.debug_index,
5050 				     wdata->xid,
5051 				     wdata->req->cfile->fid.persistent_fid,
5052 				     tcon->tid, tcon->ses->Suid, wdata->subreq.start,
5053 				     wdata->subreq.len, wdata->result);
5054 		if (wdata->result == -ENOSPC)
5055 			pr_warn_once("Out of space writing to %s\n",
5056 				     tcon->tree_name);
5057 	} else
5058 		trace_smb3_write_done(wdata->rreq->debug_id,
5059 				      wdata->subreq.debug_index,
5060 				      wdata->xid,
5061 				      wdata->req->cfile->fid.persistent_fid,
5062 				      tcon->tid, tcon->ses->Suid,
5063 				      wdata->subreq.start, wdata->subreq.len);
5064 
5065 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, wdata->credits.value,
5066 			      server->credits, server->in_flight,
5067 			      0, cifs_trace_rw_credits_write_response_clear);
5068 	wdata->credits.value = 0;
5069 
5070 	/* see if we need to retry */
5071 	if (is_replayable_error(wdata->result) &&
5072 	    smb2_should_replay(tcon,
5073 			       &wdata->retries,
5074 			       &wdata->cur_sleep))
5075 		wdata->replay = true;
5076 
5077 	cifs_write_subrequest_terminated(wdata, result ?: written);
5078 	release_mid(server, mid);
5079 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
5080 			      server->credits, server->in_flight,
5081 			      credits.value, cifs_trace_rw_credits_write_response_add);
5082 	add_credits(server, &credits, 0);
5083 }
5084 
5085 /* smb2_async_writev - send an async write, and set up mid to handle result */
5086 void
smb2_async_writev(struct cifs_io_subrequest * wdata)5087 smb2_async_writev(struct cifs_io_subrequest *wdata)
5088 {
5089 	int rc = -EACCES, flags = 0;
5090 	struct smb2_write_req *req = NULL;
5091 	struct smb2_hdr *shdr;
5092 	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
5093 	struct TCP_Server_Info *server = wdata->server;
5094 	struct kvec iov[1];
5095 	struct smb_rqst rqst = { };
5096 	unsigned int total_len, xid = wdata->xid;
5097 	struct cifs_io_parms _io_parms;
5098 	struct cifs_io_parms *io_parms = NULL;
5099 	int credit_request;
5100 
5101 	/*
5102 	 * in future we may get cifs_io_parms passed in from the caller,
5103 	 * but for now we construct it here...
5104 	 */
5105 	_io_parms = (struct cifs_io_parms) {
5106 		.tcon = tcon,
5107 		.server = server,
5108 		.offset = wdata->subreq.start,
5109 		.length = wdata->subreq.len,
5110 		.persistent_fid = wdata->req->cfile->fid.persistent_fid,
5111 		.volatile_fid = wdata->req->cfile->fid.volatile_fid,
5112 		.pid = wdata->req->pid,
5113 	};
5114 	io_parms = &_io_parms;
5115 
5116 	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
5117 				 (void **) &req, &total_len);
5118 	if (rc)
5119 		goto out;
5120 
5121 	rqst.rq_iov = iov;
5122 	rqst.rq_iter = wdata->subreq.io_iter;
5123 
5124 	rqst.rq_iov[0].iov_len = total_len - 1;
5125 	rqst.rq_iov[0].iov_base = (char *)req;
5126 	rqst.rq_nvec += 1;
5127 
5128 	if (smb3_encryption_required(tcon))
5129 		flags |= CIFS_TRANSFORM_REQ;
5130 
5131 	shdr = (struct smb2_hdr *)req;
5132 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5133 
5134 	req->PersistentFileId = io_parms->persistent_fid;
5135 	req->VolatileFileId = io_parms->volatile_fid;
5136 	req->WriteChannelInfoOffset = 0;
5137 	req->WriteChannelInfoLength = 0;
5138 	req->Channel = SMB2_CHANNEL_NONE;
5139 	req->Length = cpu_to_le32(io_parms->length);
5140 	req->Offset = cpu_to_le64(io_parms->offset);
5141 	req->DataOffset = cpu_to_le16(
5142 				offsetof(struct smb2_write_req, Buffer));
5143 	req->RemainingBytes = 0;
5144 
5145 	trace_smb3_write_enter(wdata->rreq->debug_id,
5146 			       wdata->subreq.debug_index,
5147 			       wdata->xid,
5148 			       io_parms->persistent_fid,
5149 			       io_parms->tcon->tid,
5150 			       io_parms->tcon->ses->Suid,
5151 			       io_parms->offset,
5152 			       io_parms->length);
5153 
5154 #ifdef CONFIG_CIFS_SMB_DIRECT
5155 	/*
5156 	 * If we want to do a server RDMA read, fill in and append
5157 	 * smbdirect_buffer_descriptor_v1 to the end of write request
5158 	 */
5159 	if (smb3_use_rdma_offload(io_parms)) {
5160 		struct smbdirect_buffer_descriptor_v1 *v1;
5161 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
5162 
5163 		wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->subreq.io_iter,
5164 					     false, need_invalidate);
5165 		if (!wdata->mr) {
5166 			rc = -EAGAIN;
5167 			goto async_writev_out;
5168 		}
5169 		/* For RDMA read, I/O size is in RemainingBytes not in Length */
5170 		req->RemainingBytes = req->Length;
5171 		req->Length = 0;
5172 		req->DataOffset = 0;
5173 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
5174 		if (need_invalidate)
5175 			req->Channel = SMB2_CHANNEL_RDMA_V1;
5176 		req->WriteChannelInfoOffset =
5177 			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
5178 		req->WriteChannelInfoLength =
5179 			cpu_to_le16(sizeof(struct smbdirect_buffer_descriptor_v1));
5180 		v1 = (struct smbdirect_buffer_descriptor_v1 *) &req->Buffer[0];
5181 		v1->offset = cpu_to_le64(wdata->mr->mr->iova);
5182 		v1->token = cpu_to_le32(wdata->mr->mr->rkey);
5183 		v1->length = cpu_to_le32(wdata->mr->mr->length);
5184 
5185 		rqst.rq_iov[0].iov_len += sizeof(*v1);
5186 
5187 		/*
5188 		 * We keep wdata->subreq.io_iter,
5189 		 * but we have to truncate rqst.rq_iter
5190 		 */
5191 		iov_iter_truncate(&rqst.rq_iter, 0);
5192 	}
5193 #endif
5194 
5195 	if (wdata->replay) {
5196 		/* Back-off before retry */
5197 		if (wdata->cur_sleep)
5198 			msleep(wdata->cur_sleep);
5199 		smb2_set_replay(server, &rqst);
5200 	}
5201 
5202 	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
5203 		 io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter));
5204 
5205 	if (wdata->credits.value > 0) {
5206 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->subreq.len,
5207 						    SMB2_MAX_BUFFER_SIZE));
5208 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
5209 		if (server->credits >= server->max_credits)
5210 			shdr->CreditRequest = cpu_to_le16(0);
5211 		else
5212 			shdr->CreditRequest = cpu_to_le16(
5213 				min_t(int, server->max_credits -
5214 						server->credits, credit_request));
5215 
5216 		rc = adjust_credits(server, wdata, cifs_trace_rw_credits_call_writev_adjust);
5217 		if (rc)
5218 			goto async_writev_out;
5219 
5220 		flags |= CIFS_HAS_CREDITS;
5221 	}
5222 
5223 	/* XXX: compression + encryption is unsupported for now */
5224 	if (((flags & CIFS_TRANSFORM_REQ) != CIFS_TRANSFORM_REQ) && should_compress(tcon, &rqst))
5225 		flags |= CIFS_COMPRESS_REQ;
5226 
5227 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
5228 			     wdata, flags, &wdata->credits);
5229 	/* Can't touch wdata if rc == 0 */
5230 	if (rc) {
5231 		trace_smb3_write_err(wdata->rreq->debug_id,
5232 				     wdata->subreq.debug_index,
5233 				     xid,
5234 				     io_parms->persistent_fid,
5235 				     io_parms->tcon->tid,
5236 				     io_parms->tcon->ses->Suid,
5237 				     io_parms->offset,
5238 				     io_parms->length,
5239 				     rc);
5240 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
5241 	}
5242 
5243 async_writev_out:
5244 	cifs_small_buf_release(req);
5245 out:
5246 	/* if the send error is retryable, let netfs know about it */
5247 	if (is_replayable_error(rc) &&
5248 	    smb2_should_replay(tcon,
5249 			       &wdata->retries,
5250 			       &wdata->cur_sleep)) {
5251 		wdata->replay = true;
5252 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
5253 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5254 	}
5255 
5256 	if (rc) {
5257 		trace_smb3_rw_credits(wdata->rreq->debug_id,
5258 				      wdata->subreq.debug_index,
5259 				      wdata->credits.value,
5260 				      server->credits, server->in_flight,
5261 				      -(int)wdata->credits.value,
5262 				      cifs_trace_rw_credits_write_response_clear);
5263 		add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
5264 		cifs_write_subrequest_terminated(wdata, rc);
5265 	}
5266 }
5267 
5268 /*
5269  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
5270  * The length field from io_parms must be at least 1 and indicates a number of
5271  * elements with data to write that begins with position 1 in iov array. All
5272  * data length is specified by count.
5273  */
5274 int
SMB2_write(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,struct kvec * iov,int n_vec)5275 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
5276 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
5277 {
5278 	struct smb_rqst rqst;
5279 	int rc = 0;
5280 	struct smb2_write_req *req = NULL;
5281 	struct smb2_write_rsp *rsp = NULL;
5282 	int resp_buftype;
5283 	struct kvec rsp_iov;
5284 	int flags = 0;
5285 	unsigned int total_len;
5286 	struct TCP_Server_Info *server;
5287 	int retries = 0, cur_sleep = 0;
5288 
5289 replay_again:
5290 	/* reinitialize for possible replay */
5291 	flags = 0;
5292 	*nbytes = 0;
5293 	if (!io_parms->server)
5294 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
5295 	server = io_parms->server;
5296 	if (server == NULL)
5297 		return -ECONNABORTED;
5298 
5299 	if (n_vec < 1)
5300 		return rc;
5301 
5302 	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
5303 				 (void **) &req, &total_len);
5304 	if (rc)
5305 		return rc;
5306 
5307 	if (smb3_encryption_required(io_parms->tcon))
5308 		flags |= CIFS_TRANSFORM_REQ;
5309 
5310 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5311 
5312 	req->PersistentFileId = io_parms->persistent_fid;
5313 	req->VolatileFileId = io_parms->volatile_fid;
5314 	req->WriteChannelInfoOffset = 0;
5315 	req->WriteChannelInfoLength = 0;
5316 	req->Channel = 0;
5317 	req->Length = cpu_to_le32(io_parms->length);
5318 	req->Offset = cpu_to_le64(io_parms->offset);
5319 	req->DataOffset = cpu_to_le16(
5320 				offsetof(struct smb2_write_req, Buffer));
5321 	req->RemainingBytes = 0;
5322 
5323 	trace_smb3_write_enter(0, 0, xid, io_parms->persistent_fid,
5324 		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
5325 		io_parms->offset, io_parms->length);
5326 
5327 	iov[0].iov_base = (char *)req;
5328 	/* 1 for Buffer */
5329 	iov[0].iov_len = total_len - 1;
5330 
5331 	memset(&rqst, 0, sizeof(struct smb_rqst));
5332 	rqst.rq_iov = iov;
5333 	rqst.rq_nvec = n_vec + 1;
5334 
5335 	if (retries) {
5336 		/* Back-off before retry */
5337 		if (cur_sleep)
5338 			msleep(cur_sleep);
5339 		smb2_set_replay(server, &rqst);
5340 	}
5341 
5342 	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
5343 			    &rqst,
5344 			    &resp_buftype, flags, &rsp_iov);
5345 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
5346 
5347 	if (rc) {
5348 		trace_smb3_write_err(0, 0, xid,
5349 				     req->PersistentFileId,
5350 				     io_parms->tcon->tid,
5351 				     io_parms->tcon->ses->Suid,
5352 				     io_parms->offset, io_parms->length, rc);
5353 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
5354 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
5355 	} else {
5356 		*nbytes = le32_to_cpu(rsp->DataLength);
5357 		cifs_stats_bytes_written(io_parms->tcon, *nbytes);
5358 		trace_smb3_write_done(0, 0, xid,
5359 				      req->PersistentFileId,
5360 				      io_parms->tcon->tid,
5361 				      io_parms->tcon->ses->Suid,
5362 				      io_parms->offset, *nbytes);
5363 	}
5364 
5365 	cifs_small_buf_release(req);
5366 	free_rsp_buf(resp_buftype, rsp);
5367 
5368 	if (is_replayable_error(rc) &&
5369 	    smb2_should_replay(io_parms->tcon, &retries, &cur_sleep))
5370 		goto replay_again;
5371 
5372 	return rc;
5373 }
5374 
posix_info_sid_size(const void * beg,const void * end)5375 int posix_info_sid_size(const void *beg, const void *end)
5376 {
5377 	size_t subauth;
5378 	int total;
5379 
5380 	if (beg + 1 > end)
5381 		return -1;
5382 
5383 	subauth = *(u8 *)(beg+1);
5384 	if (subauth < 1 || subauth > 15)
5385 		return -1;
5386 
5387 	total = 1 + 1 + 6 + 4*subauth;
5388 	if (beg + total > end)
5389 		return -1;
5390 
5391 	return total;
5392 }
5393 
posix_info_parse(const void * beg,const void * end,struct smb2_posix_info_parsed * out)5394 int posix_info_parse(const void *beg, const void *end,
5395 		     struct smb2_posix_info_parsed *out)
5396 
5397 {
5398 	int total_len = 0;
5399 	int owner_len, group_len;
5400 	int name_len;
5401 	const void *owner_sid;
5402 	const void *group_sid;
5403 	const void *name;
5404 
5405 	/* if no end bound given, assume payload to be correct */
5406 	if (!end) {
5407 		const struct smb2_posix_info *p = beg;
5408 
5409 		end = beg + le32_to_cpu(p->NextEntryOffset);
5410 		/* last element will have a 0 offset, pick a sensible bound */
5411 		if (end == beg)
5412 			end += 0xFFFF;
5413 	}
5414 
5415 	/* check base buf */
5416 	if (beg + sizeof(struct smb2_posix_info) > end)
5417 		return -1;
5418 	total_len = sizeof(struct smb2_posix_info);
5419 
5420 	/* check owner sid */
5421 	owner_sid = beg + total_len;
5422 	owner_len = posix_info_sid_size(owner_sid, end);
5423 	if (owner_len < 0)
5424 		return -1;
5425 	total_len += owner_len;
5426 
5427 	/* check group sid */
5428 	group_sid = beg + total_len;
5429 	group_len = posix_info_sid_size(group_sid, end);
5430 	if (group_len < 0)
5431 		return -1;
5432 	total_len += group_len;
5433 
5434 	/* check name len */
5435 	if (beg + total_len + 4 > end)
5436 		return -1;
5437 	name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
5438 	if (name_len < 1 || name_len > 0xFFFF)
5439 		return -1;
5440 	total_len += 4;
5441 
5442 	/* check name */
5443 	name = beg + total_len;
5444 	if (name + name_len > end)
5445 		return -1;
5446 	total_len += name_len;
5447 
5448 	if (out) {
5449 		out->base = beg;
5450 		out->size = total_len;
5451 		out->name_len = name_len;
5452 		out->name = name;
5453 		memcpy(&out->owner, owner_sid, owner_len);
5454 		memcpy(&out->group, group_sid, group_len);
5455 	}
5456 	return total_len;
5457 }
5458 
posix_info_extra_size(const void * beg,const void * end)5459 static int posix_info_extra_size(const void *beg, const void *end)
5460 {
5461 	int len = posix_info_parse(beg, end, NULL);
5462 
5463 	if (len < 0)
5464 		return -1;
5465 	return len - sizeof(struct smb2_posix_info);
5466 }
5467 
5468 static unsigned int
num_entries(int infotype,char * bufstart,char * end_of_buf,char ** lastentry,size_t size)5469 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
5470 	    size_t size)
5471 {
5472 	int len;
5473 	unsigned int entrycount = 0;
5474 	unsigned int next_offset = 0;
5475 	char *entryptr;
5476 	FILE_DIRECTORY_INFO *dir_info;
5477 
5478 	if (bufstart == NULL)
5479 		return 0;
5480 
5481 	entryptr = bufstart;
5482 
5483 	while (1) {
5484 		if (entryptr + next_offset < entryptr ||
5485 		    entryptr + next_offset > end_of_buf ||
5486 		    entryptr + next_offset + size > end_of_buf) {
5487 			cifs_dbg(VFS, "malformed search entry would overflow\n");
5488 			break;
5489 		}
5490 
5491 		entryptr = entryptr + next_offset;
5492 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
5493 
5494 		if (infotype == SMB_FIND_FILE_POSIX_INFO)
5495 			len = posix_info_extra_size(entryptr, end_of_buf);
5496 		else
5497 			len = le32_to_cpu(dir_info->FileNameLength);
5498 
5499 		if (len < 0 ||
5500 		    entryptr + len < entryptr ||
5501 		    entryptr + len > end_of_buf ||
5502 		    entryptr + len + size > end_of_buf) {
5503 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
5504 				 end_of_buf);
5505 			break;
5506 		}
5507 
5508 		*lastentry = entryptr;
5509 		entrycount++;
5510 
5511 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5512 		if (!next_offset)
5513 			break;
5514 	}
5515 
5516 	return entrycount;
5517 }
5518 
5519 /*
5520  * Readdir/FindFirst
5521  */
SMB2_query_directory_init(const unsigned int xid,struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,int index,int info_level)5522 int SMB2_query_directory_init(const unsigned int xid,
5523 			      struct cifs_tcon *tcon,
5524 			      struct TCP_Server_Info *server,
5525 			      struct smb_rqst *rqst,
5526 			      u64 persistent_fid, u64 volatile_fid,
5527 			      int index, int info_level)
5528 {
5529 	struct smb2_query_directory_req *req;
5530 	unsigned char *bufptr;
5531 	__le16 asteriks = cpu_to_le16('*');
5532 	unsigned int output_size = CIFSMaxBufSize -
5533 		MAX_SMB2_CREATE_RESPONSE_SIZE -
5534 		MAX_SMB2_CLOSE_RESPONSE_SIZE;
5535 	unsigned int total_len;
5536 	struct kvec *iov = rqst->rq_iov;
5537 	int len, rc;
5538 
5539 	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
5540 				 (void **) &req, &total_len);
5541 	if (rc)
5542 		return rc;
5543 
5544 	switch (info_level) {
5545 	case SMB_FIND_FILE_DIRECTORY_INFO:
5546 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
5547 		break;
5548 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5549 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
5550 		break;
5551 	case SMB_FIND_FILE_POSIX_INFO:
5552 		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
5553 		break;
5554 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5555 		req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
5556 		break;
5557 	default:
5558 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5559 			info_level);
5560 		return -EINVAL;
5561 	}
5562 
5563 	req->FileIndex = cpu_to_le32(index);
5564 	req->PersistentFileId = persistent_fid;
5565 	req->VolatileFileId = volatile_fid;
5566 
5567 	len = 0x2;
5568 	bufptr = req->Buffer;
5569 	memcpy(bufptr, &asteriks, len);
5570 
5571 	req->FileNameOffset =
5572 		cpu_to_le16(sizeof(struct smb2_query_directory_req));
5573 	req->FileNameLength = cpu_to_le16(len);
5574 	/*
5575 	 * BB could be 30 bytes or so longer if we used SMB2 specific
5576 	 * buffer lengths, but this is safe and close enough.
5577 	 */
5578 	output_size = min_t(unsigned int, output_size, server->maxBuf);
5579 	output_size = min_t(unsigned int, output_size, 2 << 15);
5580 	req->OutputBufferLength = cpu_to_le32(output_size);
5581 
5582 	iov[0].iov_base = (char *)req;
5583 	/* 1 for Buffer */
5584 	iov[0].iov_len = total_len - 1;
5585 
5586 	iov[1].iov_base = (char *)(req->Buffer);
5587 	iov[1].iov_len = len;
5588 
5589 	trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
5590 			tcon->ses->Suid, index, output_size);
5591 
5592 	return 0;
5593 }
5594 
SMB2_query_directory_free(struct smb_rqst * rqst)5595 void SMB2_query_directory_free(struct smb_rqst *rqst)
5596 {
5597 	if (rqst && rqst->rq_iov) {
5598 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
5599 	}
5600 }
5601 
5602 int
smb2_parse_query_directory(struct cifs_tcon * tcon,struct kvec * rsp_iov,int resp_buftype,struct cifs_search_info * srch_inf)5603 smb2_parse_query_directory(struct cifs_tcon *tcon,
5604 			   struct kvec *rsp_iov,
5605 			   int resp_buftype,
5606 			   struct cifs_search_info *srch_inf)
5607 {
5608 	struct smb2_query_directory_rsp *rsp;
5609 	size_t info_buf_size;
5610 	char *end_of_smb;
5611 	int rc;
5612 
5613 	rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
5614 
5615 	switch (srch_inf->info_level) {
5616 	case SMB_FIND_FILE_DIRECTORY_INFO:
5617 		info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5618 		break;
5619 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5620 		info_buf_size = sizeof(FILE_ID_FULL_DIR_INFO);
5621 		break;
5622 	case SMB_FIND_FILE_POSIX_INFO:
5623 		/* note that posix payload are variable size */
5624 		info_buf_size = sizeof(struct smb2_posix_info);
5625 		break;
5626 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5627 		info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
5628 		break;
5629 	default:
5630 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5631 			 srch_inf->info_level);
5632 		return -EINVAL;
5633 	}
5634 
5635 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5636 			       le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
5637 			       info_buf_size);
5638 	if (rc) {
5639 		cifs_tcon_dbg(VFS, "bad info payload");
5640 		return rc;
5641 	}
5642 
5643 	srch_inf->unicode = true;
5644 
5645 	if (srch_inf->ntwrk_buf_start) {
5646 		if (srch_inf->smallBuf)
5647 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
5648 		else
5649 			cifs_buf_release(srch_inf->ntwrk_buf_start);
5650 	}
5651 	srch_inf->ntwrk_buf_start = (char *)rsp;
5652 	srch_inf->srch_entries_start = srch_inf->last_entry =
5653 		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
5654 	end_of_smb = rsp_iov->iov_len + (char *)rsp;
5655 
5656 	srch_inf->entries_in_buffer = num_entries(
5657 		srch_inf->info_level,
5658 		srch_inf->srch_entries_start,
5659 		end_of_smb,
5660 		&srch_inf->last_entry,
5661 		info_buf_size);
5662 
5663 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
5664 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
5665 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
5666 		 srch_inf->srch_entries_start, srch_inf->last_entry);
5667 	if (resp_buftype == CIFS_LARGE_BUFFER)
5668 		srch_inf->smallBuf = false;
5669 	else if (resp_buftype == CIFS_SMALL_BUFFER)
5670 		srch_inf->smallBuf = true;
5671 	else
5672 		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5673 
5674 	return 0;
5675 }
5676 
5677 int
SMB2_query_directory(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int index,struct cifs_search_info * srch_inf)5678 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5679 		     u64 persistent_fid, u64 volatile_fid, int index,
5680 		     struct cifs_search_info *srch_inf)
5681 {
5682 	struct smb_rqst rqst;
5683 	struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5684 	struct smb2_query_directory_rsp *rsp = NULL;
5685 	int resp_buftype = CIFS_NO_BUFFER;
5686 	struct kvec rsp_iov;
5687 	int rc = 0;
5688 	struct cifs_ses *ses = tcon->ses;
5689 	struct TCP_Server_Info *server;
5690 	int flags = 0;
5691 	int retries = 0, cur_sleep = 0;
5692 
5693 replay_again:
5694 	/* reinitialize for possible replay */
5695 	flags = 0;
5696 	server = cifs_pick_channel(ses);
5697 
5698 	if (!ses || !(ses->server))
5699 		return smb_EIO(smb_eio_trace_null_pointers);
5700 
5701 	if (smb3_encryption_required(tcon))
5702 		flags |= CIFS_TRANSFORM_REQ;
5703 
5704 	memset(&rqst, 0, sizeof(struct smb_rqst));
5705 	memset(&iov, 0, sizeof(iov));
5706 	rqst.rq_iov = iov;
5707 	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5708 
5709 	rc = SMB2_query_directory_init(xid, tcon, server,
5710 				       &rqst, persistent_fid,
5711 				       volatile_fid, index,
5712 				       srch_inf->info_level);
5713 	if (rc)
5714 		goto qdir_exit;
5715 
5716 	if (retries) {
5717 		/* Back-off before retry */
5718 		if (cur_sleep)
5719 			msleep(cur_sleep);
5720 		smb2_set_replay(server, &rqst);
5721 	}
5722 
5723 	rc = cifs_send_recv(xid, ses, server,
5724 			    &rqst, &resp_buftype, flags, &rsp_iov);
5725 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5726 
5727 	if (rc) {
5728 		if (rc == -ENODATA &&
5729 		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5730 			trace_smb3_query_dir_done(xid, persistent_fid,
5731 				tcon->tid, tcon->ses->Suid, index, 0);
5732 			srch_inf->endOfSearch = true;
5733 			rc = 0;
5734 		} else {
5735 			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5736 				tcon->ses->Suid, index, 0, rc);
5737 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5738 		}
5739 		goto qdir_exit;
5740 	}
5741 
5742 	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
5743 					srch_inf);
5744 	if (rc) {
5745 		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5746 			tcon->ses->Suid, index, 0, rc);
5747 		goto qdir_exit;
5748 	}
5749 	resp_buftype = CIFS_NO_BUFFER;
5750 
5751 	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5752 			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5753 
5754 qdir_exit:
5755 	SMB2_query_directory_free(&rqst);
5756 	free_rsp_buf(resp_buftype, rsp);
5757 
5758 	if (is_replayable_error(rc) &&
5759 	    smb2_should_replay(tcon, &retries, &cur_sleep))
5760 		goto replay_again;
5761 
5762 	return rc;
5763 }
5764 
5765 int
SMB2_set_info_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u32 pid,u8 info_class,u8 info_type,u32 additional_info,void ** data,unsigned int * size)5766 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5767 		   struct smb_rqst *rqst,
5768 		   u64 persistent_fid, u64 volatile_fid, u32 pid,
5769 		   u8 info_class, u8 info_type, u32 additional_info,
5770 		   void **data, unsigned int *size)
5771 {
5772 	struct smb2_set_info_req *req;
5773 	struct kvec *iov = rqst->rq_iov;
5774 	unsigned int i, total_len;
5775 	int rc;
5776 
5777 	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5778 				 (void **) &req, &total_len);
5779 	if (rc)
5780 		return rc;
5781 
5782 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5783 	req->InfoType = info_type;
5784 	req->FileInfoClass = info_class;
5785 	req->PersistentFileId = persistent_fid;
5786 	req->VolatileFileId = volatile_fid;
5787 	req->AdditionalInformation = cpu_to_le32(additional_info);
5788 
5789 	req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5790 	req->BufferLength = cpu_to_le32(*size);
5791 
5792 	memcpy(req->Buffer, *data, *size);
5793 	total_len += *size;
5794 
5795 	iov[0].iov_base = (char *)req;
5796 	/* 1 for Buffer */
5797 	iov[0].iov_len = total_len - 1;
5798 
5799 	for (i = 1; i < rqst->rq_nvec; i++) {
5800 		le32_add_cpu(&req->BufferLength, size[i]);
5801 		iov[i].iov_base = (char *)data[i];
5802 		iov[i].iov_len = size[i];
5803 	}
5804 
5805 	return 0;
5806 }
5807 
5808 void
SMB2_set_info_free(struct smb_rqst * rqst)5809 SMB2_set_info_free(struct smb_rqst *rqst)
5810 {
5811 	if (rqst && rqst->rq_iov)
5812 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5813 }
5814 
5815 static int
send_set_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,u8 info_class,u8 info_type,u32 additional_info,unsigned int num,void ** data,unsigned int * size)5816 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5817 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5818 	       u8 info_type, u32 additional_info, unsigned int num,
5819 		void **data, unsigned int *size)
5820 {
5821 	struct smb_rqst rqst;
5822 	struct smb2_set_info_rsp *rsp = NULL;
5823 	struct kvec *iov;
5824 	struct kvec rsp_iov;
5825 	int rc = 0;
5826 	int resp_buftype;
5827 	struct cifs_ses *ses = tcon->ses;
5828 	struct TCP_Server_Info *server;
5829 	int flags = 0;
5830 	int retries = 0, cur_sleep = 0;
5831 
5832 replay_again:
5833 	/* reinitialize for possible replay */
5834 	flags = 0;
5835 	server = cifs_pick_channel(ses);
5836 
5837 	if (!ses || !server)
5838 		return smb_EIO(smb_eio_trace_null_pointers);
5839 
5840 	if (!num)
5841 		return -EINVAL;
5842 
5843 	if (smb3_encryption_required(tcon))
5844 		flags |= CIFS_TRANSFORM_REQ;
5845 
5846 	iov = kmalloc_objs(struct kvec, num);
5847 	if (!iov)
5848 		return -ENOMEM;
5849 
5850 	memset(&rqst, 0, sizeof(struct smb_rqst));
5851 	rqst.rq_iov = iov;
5852 	rqst.rq_nvec = num;
5853 
5854 	rc = SMB2_set_info_init(tcon, server,
5855 				&rqst, persistent_fid, volatile_fid, pid,
5856 				info_class, info_type, additional_info,
5857 				data, size);
5858 	if (rc) {
5859 		kfree(iov);
5860 		return rc;
5861 	}
5862 
5863 	if (retries) {
5864 		/* Back-off before retry */
5865 		if (cur_sleep)
5866 			msleep(cur_sleep);
5867 		smb2_set_replay(server, &rqst);
5868 	}
5869 
5870 	rc = cifs_send_recv(xid, ses, server,
5871 			    &rqst, &resp_buftype, flags,
5872 			    &rsp_iov);
5873 	SMB2_set_info_free(&rqst);
5874 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5875 
5876 	if (rc != 0) {
5877 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5878 		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5879 				ses->Suid, info_class, (__u32)info_type, rc);
5880 	}
5881 
5882 	free_rsp_buf(resp_buftype, rsp);
5883 	kfree(iov);
5884 
5885 	if (is_replayable_error(rc) &&
5886 	    smb2_should_replay(tcon, &retries, &cur_sleep))
5887 		goto replay_again;
5888 
5889 	return rc;
5890 }
5891 
5892 int
SMB2_set_eof(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,loff_t new_eof)5893 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5894 	     u64 volatile_fid, u32 pid, loff_t new_eof)
5895 {
5896 	struct smb2_file_eof_info info;
5897 	void *data;
5898 	unsigned int size;
5899 
5900 	info.EndOfFile = cpu_to_le64(new_eof);
5901 
5902 	data = &info;
5903 	size = sizeof(struct smb2_file_eof_info);
5904 
5905 	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5906 
5907 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5908 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5909 			0, 1, &data, &size);
5910 }
5911 
5912 int
SMB2_set_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb_ntsd * pnntsd,int pacllen,int aclflag)5913 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5914 		u64 persistent_fid, u64 volatile_fid,
5915 		struct smb_ntsd *pnntsd, int pacllen, int aclflag)
5916 {
5917 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5918 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5919 			1, (void **)&pnntsd, &pacllen);
5920 }
5921 
5922 int
SMB2_set_ea(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_full_ea_info * buf,int len)5923 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5924 	    u64 persistent_fid, u64 volatile_fid,
5925 	    struct smb2_file_full_ea_info *buf, int len)
5926 {
5927 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5928 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5929 		0, 1, (void **)&buf, &len);
5930 }
5931 
5932 int
SMB2_oplock_break(const unsigned int xid,struct cifs_tcon * tcon,const u64 persistent_fid,const u64 volatile_fid,__u8 oplock_level)5933 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5934 		  const u64 persistent_fid, const u64 volatile_fid,
5935 		  __u8 oplock_level)
5936 {
5937 	struct smb_rqst rqst;
5938 	int rc;
5939 	struct smb2_oplock_break *req = NULL;
5940 	struct cifs_ses *ses = tcon->ses;
5941 	struct TCP_Server_Info *server;
5942 	int flags = CIFS_OBREAK_OP;
5943 	unsigned int total_len;
5944 	struct kvec iov[1];
5945 	struct kvec rsp_iov;
5946 	int resp_buf_type;
5947 	int retries = 0, cur_sleep = 0;
5948 
5949 replay_again:
5950 	/* reinitialize for possible replay */
5951 	flags = CIFS_OBREAK_OP;
5952 	server = cifs_pick_channel(ses);
5953 
5954 	cifs_dbg(FYI, "SMB2_oplock_break\n");
5955 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5956 				 (void **) &req, &total_len);
5957 	if (rc)
5958 		return rc;
5959 
5960 	if (smb3_encryption_required(tcon))
5961 		flags |= CIFS_TRANSFORM_REQ;
5962 
5963 	req->VolatileFid = volatile_fid;
5964 	req->PersistentFid = persistent_fid;
5965 	req->OplockLevel = oplock_level;
5966 	req->hdr.CreditRequest = cpu_to_le16(1);
5967 
5968 	flags |= CIFS_NO_RSP_BUF;
5969 
5970 	iov[0].iov_base = (char *)req;
5971 	iov[0].iov_len = total_len;
5972 
5973 	memset(&rqst, 0, sizeof(struct smb_rqst));
5974 	rqst.rq_iov = iov;
5975 	rqst.rq_nvec = 1;
5976 
5977 	if (retries) {
5978 		/* Back-off before retry */
5979 		if (cur_sleep)
5980 			msleep(cur_sleep);
5981 		smb2_set_replay(server, &rqst);
5982 	}
5983 
5984 	rc = cifs_send_recv(xid, ses, server,
5985 			    &rqst, &resp_buf_type, flags, &rsp_iov);
5986 	cifs_small_buf_release(req);
5987 	if (rc) {
5988 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5989 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5990 	}
5991 
5992 	if (is_replayable_error(rc) &&
5993 	    smb2_should_replay(tcon, &retries, &cur_sleep))
5994 		goto replay_again;
5995 
5996 	return rc;
5997 }
5998 
5999 void
smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info * pfs_inf,struct kstatfs * kst)6000 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
6001 			     struct kstatfs *kst)
6002 {
6003 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
6004 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
6005 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
6006 	kst->f_bfree  = kst->f_bavail =
6007 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
6008 	return;
6009 }
6010 
6011 static void
copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO * response_data,struct kstatfs * kst)6012 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
6013 			struct kstatfs *kst)
6014 {
6015 	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
6016 	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
6017 	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
6018 	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
6019 		kst->f_bavail = kst->f_bfree;
6020 	else
6021 		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
6022 	if (response_data->TotalFileNodes != cpu_to_le64(-1))
6023 		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
6024 	if (response_data->FreeFileNodes != cpu_to_le64(-1))
6025 		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
6026 
6027 	return;
6028 }
6029 
6030 static int
build_qfs_info_req(struct kvec * iov,struct cifs_tcon * tcon,struct TCP_Server_Info * server,int level,int outbuf_len,u64 persistent_fid,u64 volatile_fid)6031 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
6032 		   struct TCP_Server_Info *server,
6033 		   int level, int outbuf_len, u64 persistent_fid,
6034 		   u64 volatile_fid)
6035 {
6036 	int rc;
6037 	struct smb2_query_info_req *req;
6038 	unsigned int total_len;
6039 
6040 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
6041 
6042 	if ((tcon->ses == NULL) || server == NULL)
6043 		return smb_EIO(smb_eio_trace_null_pointers);
6044 
6045 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
6046 				 (void **) &req, &total_len);
6047 	if (rc)
6048 		return rc;
6049 
6050 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
6051 	req->FileInfoClass = level;
6052 	req->PersistentFileId = persistent_fid;
6053 	req->VolatileFileId = volatile_fid;
6054 	/* 1 for pad */
6055 	req->InputBufferOffset =
6056 			cpu_to_le16(sizeof(struct smb2_query_info_req));
6057 	req->OutputBufferLength = cpu_to_le32(
6058 		outbuf_len + sizeof(struct smb2_query_info_rsp));
6059 
6060 	iov->iov_base = (char *)req;
6061 	iov->iov_len = total_len;
6062 	return 0;
6063 }
6064 
free_qfs_info_req(struct kvec * iov)6065 static inline void free_qfs_info_req(struct kvec *iov)
6066 {
6067 	cifs_buf_release(iov->iov_base);
6068 }
6069 
6070 int
SMB311_posix_qfs_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)6071 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
6072 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
6073 {
6074 	struct smb_rqst rqst;
6075 	struct smb2_query_info_rsp *rsp = NULL;
6076 	struct kvec iov;
6077 	struct kvec rsp_iov;
6078 	int rc = 0;
6079 	int resp_buftype;
6080 	struct cifs_ses *ses = tcon->ses;
6081 	struct TCP_Server_Info *server;
6082 	FILE_SYSTEM_POSIX_INFO *info = NULL;
6083 	int flags = 0;
6084 	int retries = 0, cur_sleep = 0;
6085 
6086 replay_again:
6087 	/* reinitialize for possible replay */
6088 	flags = 0;
6089 	server = cifs_pick_channel(ses);
6090 
6091 	rc = build_qfs_info_req(&iov, tcon, server,
6092 				FS_POSIX_INFORMATION,
6093 				sizeof(FILE_SYSTEM_POSIX_INFO),
6094 				persistent_fid, volatile_fid);
6095 	if (rc)
6096 		return rc;
6097 
6098 	if (smb3_encryption_required(tcon))
6099 		flags |= CIFS_TRANSFORM_REQ;
6100 
6101 	memset(&rqst, 0, sizeof(struct smb_rqst));
6102 	rqst.rq_iov = &iov;
6103 	rqst.rq_nvec = 1;
6104 
6105 	if (retries) {
6106 		/* Back-off before retry */
6107 		if (cur_sleep)
6108 			msleep(cur_sleep);
6109 		smb2_set_replay(server, &rqst);
6110 	}
6111 
6112 	rc = cifs_send_recv(xid, ses, server,
6113 			    &rqst, &resp_buftype, flags, &rsp_iov);
6114 	free_qfs_info_req(&iov);
6115 	if (rc) {
6116 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
6117 		goto posix_qfsinf_exit;
6118 	}
6119 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
6120 
6121 	info = (FILE_SYSTEM_POSIX_INFO *)(
6122 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
6123 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
6124 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
6125 			       sizeof(FILE_SYSTEM_POSIX_INFO));
6126 	if (!rc)
6127 		copy_posix_fs_info_to_kstatfs(info, fsdata);
6128 
6129 posix_qfsinf_exit:
6130 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6131 
6132 	if (is_replayable_error(rc) &&
6133 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6134 		goto replay_again;
6135 
6136 	return rc;
6137 }
6138 
6139 int
SMB2_QFS_attr(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int level)6140 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
6141 	      u64 persistent_fid, u64 volatile_fid, int level)
6142 {
6143 	struct smb_rqst rqst;
6144 	struct smb2_query_info_rsp *rsp = NULL;
6145 	struct kvec iov;
6146 	struct kvec rsp_iov;
6147 	int rc = 0;
6148 	int resp_buftype, max_len, min_len;
6149 	struct cifs_ses *ses = tcon->ses;
6150 	struct TCP_Server_Info *server;
6151 	unsigned int rsp_len, offset;
6152 	int flags = 0;
6153 	int retries = 0, cur_sleep = 0;
6154 
6155 replay_again:
6156 	/* reinitialize for possible replay */
6157 	flags = 0;
6158 	server = cifs_pick_channel(ses);
6159 
6160 	if (level == FS_DEVICE_INFORMATION) {
6161 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6162 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6163 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
6164 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + MAX_FS_NAME_LEN;
6165 		min_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
6166 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
6167 		max_len = sizeof(struct smb3_fs_ss_info);
6168 		min_len = sizeof(struct smb3_fs_ss_info);
6169 	} else if (level == FS_VOLUME_INFORMATION) {
6170 		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
6171 		min_len = sizeof(struct smb3_fs_vol_info);
6172 	} else {
6173 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
6174 		return -EINVAL;
6175 	}
6176 
6177 	rc = build_qfs_info_req(&iov, tcon, server,
6178 				level, max_len,
6179 				persistent_fid, volatile_fid);
6180 	if (rc)
6181 		return rc;
6182 
6183 	if (smb3_encryption_required(tcon))
6184 		flags |= CIFS_TRANSFORM_REQ;
6185 
6186 	memset(&rqst, 0, sizeof(struct smb_rqst));
6187 	rqst.rq_iov = &iov;
6188 	rqst.rq_nvec = 1;
6189 
6190 	if (retries) {
6191 		/* Back-off before retry */
6192 		if (cur_sleep)
6193 			msleep(cur_sleep);
6194 		smb2_set_replay(server, &rqst);
6195 	}
6196 
6197 	rc = cifs_send_recv(xid, ses, server,
6198 			    &rqst, &resp_buftype, flags, &rsp_iov);
6199 	free_qfs_info_req(&iov);
6200 	if (rc) {
6201 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
6202 		goto qfsattr_exit;
6203 	}
6204 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
6205 
6206 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
6207 	offset = le16_to_cpu(rsp->OutputBufferOffset);
6208 	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
6209 	if (rc)
6210 		goto qfsattr_exit;
6211 
6212 	if (level == FS_ATTRIBUTE_INFORMATION)
6213 		memcpy(&tcon->fsAttrInfo, offset
6214 			+ (char *)rsp, min_t(unsigned int,
6215 			rsp_len, min_len));
6216 	else if (level == FS_DEVICE_INFORMATION)
6217 		memcpy(&tcon->fsDevInfo, offset
6218 			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
6219 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
6220 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
6221 			(offset + (char *)rsp);
6222 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
6223 		tcon->perf_sector_size =
6224 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
6225 	} else if (level == FS_VOLUME_INFORMATION) {
6226 		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
6227 			(offset + (char *)rsp);
6228 		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
6229 		tcon->vol_create_time = vol_info->VolumeCreationTime;
6230 	}
6231 
6232 qfsattr_exit:
6233 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6234 
6235 	if (is_replayable_error(rc) &&
6236 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6237 		goto replay_again;
6238 
6239 	return rc;
6240 }
6241 
6242 int
smb2_lockv(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u32 num_lock,struct smb2_lock_element * buf)6243 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
6244 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6245 	   const __u32 num_lock, struct smb2_lock_element *buf)
6246 {
6247 	struct smb_rqst rqst;
6248 	int rc = 0;
6249 	struct smb2_lock_req *req = NULL;
6250 	struct kvec iov[2];
6251 	struct kvec rsp_iov;
6252 	int resp_buf_type;
6253 	unsigned int count;
6254 	int flags = CIFS_NO_RSP_BUF;
6255 	unsigned int total_len;
6256 	struct TCP_Server_Info *server;
6257 	int retries = 0, cur_sleep = 0;
6258 
6259 replay_again:
6260 	/* reinitialize for possible replay */
6261 	flags = CIFS_NO_RSP_BUF;
6262 	server = cifs_pick_channel(tcon->ses);
6263 
6264 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
6265 
6266 	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
6267 				 (void **) &req, &total_len);
6268 	if (rc)
6269 		return rc;
6270 
6271 	if (smb3_encryption_required(tcon))
6272 		flags |= CIFS_TRANSFORM_REQ;
6273 
6274 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
6275 	req->LockCount = cpu_to_le16(num_lock);
6276 
6277 	req->PersistentFileId = persist_fid;
6278 	req->VolatileFileId = volatile_fid;
6279 
6280 	count = num_lock * sizeof(struct smb2_lock_element);
6281 
6282 	iov[0].iov_base = (char *)req;
6283 	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
6284 	iov[1].iov_base = (char *)buf;
6285 	iov[1].iov_len = count;
6286 
6287 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
6288 
6289 	memset(&rqst, 0, sizeof(struct smb_rqst));
6290 	rqst.rq_iov = iov;
6291 	rqst.rq_nvec = 2;
6292 
6293 	if (retries) {
6294 		/* Back-off before retry */
6295 		if (cur_sleep)
6296 			msleep(cur_sleep);
6297 		smb2_set_replay(server, &rqst);
6298 	}
6299 
6300 	rc = cifs_send_recv(xid, tcon->ses, server,
6301 			    &rqst, &resp_buf_type, flags,
6302 			    &rsp_iov);
6303 	cifs_small_buf_release(req);
6304 	if (rc) {
6305 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
6306 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
6307 		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
6308 				    tcon->ses->Suid, rc);
6309 	}
6310 
6311 	if (is_replayable_error(rc) &&
6312 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6313 		goto replay_again;
6314 
6315 	return rc;
6316 }
6317 
6318 int
SMB2_lock(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u64 length,const __u64 offset,const __u32 lock_flags,const bool wait)6319 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
6320 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6321 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
6322 	  const bool wait)
6323 {
6324 	struct smb2_lock_element lock;
6325 
6326 	lock.Offset = cpu_to_le64(offset);
6327 	lock.Length = cpu_to_le64(length);
6328 	lock.Flags = cpu_to_le32(lock_flags);
6329 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
6330 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
6331 
6332 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
6333 }
6334 
6335 int
SMB2_lease_break(const unsigned int xid,struct cifs_tcon * tcon,__u8 * lease_key,const __le32 lease_state)6336 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
6337 		 __u8 *lease_key, const __le32 lease_state)
6338 {
6339 	struct smb_rqst rqst;
6340 	int rc;
6341 	struct smb2_lease_ack *req = NULL;
6342 	struct cifs_ses *ses = tcon->ses;
6343 	int flags = CIFS_OBREAK_OP;
6344 	unsigned int total_len;
6345 	struct kvec iov[1];
6346 	struct kvec rsp_iov;
6347 	int resp_buf_type;
6348 	__u64 *please_key_high;
6349 	__u64 *please_key_low;
6350 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
6351 
6352 	cifs_dbg(FYI, "SMB2_lease_break\n");
6353 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
6354 				 (void **) &req, &total_len);
6355 	if (rc)
6356 		return rc;
6357 
6358 	if (smb3_encryption_required(tcon))
6359 		flags |= CIFS_TRANSFORM_REQ;
6360 
6361 	req->hdr.CreditRequest = cpu_to_le16(1);
6362 	req->StructureSize = cpu_to_le16(36);
6363 	total_len += 12;
6364 
6365 	memcpy(req->LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
6366 	req->LeaseState = lease_state;
6367 
6368 	flags |= CIFS_NO_RSP_BUF;
6369 
6370 	iov[0].iov_base = (char *)req;
6371 	iov[0].iov_len = total_len;
6372 
6373 	memset(&rqst, 0, sizeof(struct smb_rqst));
6374 	rqst.rq_iov = iov;
6375 	rqst.rq_nvec = 1;
6376 
6377 	rc = cifs_send_recv(xid, ses, server,
6378 			    &rqst, &resp_buf_type, flags, &rsp_iov);
6379 	cifs_small_buf_release(req);
6380 
6381 	please_key_low = (__u64 *)lease_key;
6382 	please_key_high = (__u64 *)(lease_key+8);
6383 	if (rc) {
6384 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6385 		trace_smb3_lease_ack_err(le32_to_cpu(lease_state), tcon->tid,
6386 			ses->Suid, *please_key_low, *please_key_high, rc);
6387 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
6388 	} else
6389 		trace_smb3_lease_ack_done(le32_to_cpu(lease_state), tcon->tid,
6390 			ses->Suid, *please_key_low, *please_key_high);
6391 
6392 	return rc;
6393 }
6394