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