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