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