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