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