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