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