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