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