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