Tree connect for SMB3.1.1 must be signed for non-encrypted shares
[linux-block.git] / fs / cifs / smb2pdu.c
1 /*
2  *   fs/cifs/smb2pdu.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  *   This library is free software; you can redistribute it and/or modify
12  *   it under the terms of the GNU Lesser General Public License as published
13  *   by the Free Software Foundation; either version 2.1 of the License, or
14  *   (at your option) any later version.
15  *
16  *   This library is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
19  *   the GNU Lesser General Public License for more details.
20  *
21  *   You should have received a copy of the GNU Lesser General Public License
22  *   along with this library; if not, write to the Free Software
23  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  */
25
26  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
27  /* Note that there are handle based routines which must be                   */
28  /* treated slightly differently for reconnection purposes since we never     */
29  /* want to reuse a stale file handle and only the caller knows the file info */
30
31 #include <linux/fs.h>
32 #include <linux/kernel.h>
33 #include <linux/vfs.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/uaccess.h>
36 #include <linux/uuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/xattr.h>
39 #include "smb2pdu.h"
40 #include "cifsglob.h"
41 #include "cifsacl.h"
42 #include "cifsproto.h"
43 #include "smb2proto.h"
44 #include "cifs_unicode.h"
45 #include "cifs_debug.h"
46 #include "ntlmssp.h"
47 #include "smb2status.h"
48 #include "smb2glob.h"
49 #include "cifspdu.h"
50 #include "cifs_spnego.h"
51 #include "smbdirect.h"
52
53 /*
54  *  The following table defines the expected "StructureSize" of SMB2 requests
55  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
56  *
57  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
58  *  indexed by command in host byte order.
59  */
60 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
61         /* SMB2_NEGOTIATE */ 36,
62         /* SMB2_SESSION_SETUP */ 25,
63         /* SMB2_LOGOFF */ 4,
64         /* SMB2_TREE_CONNECT */ 9,
65         /* SMB2_TREE_DISCONNECT */ 4,
66         /* SMB2_CREATE */ 57,
67         /* SMB2_CLOSE */ 24,
68         /* SMB2_FLUSH */ 24,
69         /* SMB2_READ */ 49,
70         /* SMB2_WRITE */ 49,
71         /* SMB2_LOCK */ 48,
72         /* SMB2_IOCTL */ 57,
73         /* SMB2_CANCEL */ 4,
74         /* SMB2_ECHO */ 4,
75         /* SMB2_QUERY_DIRECTORY */ 33,
76         /* SMB2_CHANGE_NOTIFY */ 32,
77         /* SMB2_QUERY_INFO */ 41,
78         /* SMB2_SET_INFO */ 33,
79         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
80 };
81
82 static int encryption_required(const struct cifs_tcon *tcon)
83 {
84         if (!tcon)
85                 return 0;
86         if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
87             (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
88                 return 1;
89         if (tcon->seal &&
90             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
91                 return 1;
92         return 0;
93 }
94
95 static void
96 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
97                   const struct cifs_tcon *tcon)
98 {
99         shdr->ProtocolId = SMB2_PROTO_NUMBER;
100         shdr->StructureSize = cpu_to_le16(64);
101         shdr->Command = smb2_cmd;
102         if (tcon && tcon->ses && tcon->ses->server) {
103                 struct TCP_Server_Info *server = tcon->ses->server;
104
105                 spin_lock(&server->req_lock);
106                 /* Request up to 2 credits but don't go over the limit. */
107                 if (server->credits >= server->max_credits)
108                         shdr->CreditRequest = cpu_to_le16(0);
109                 else
110                         shdr->CreditRequest = cpu_to_le16(
111                                 min_t(int, server->max_credits -
112                                                 server->credits, 2));
113                 spin_unlock(&server->req_lock);
114         } else {
115                 shdr->CreditRequest = cpu_to_le16(2);
116         }
117         shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
118
119         if (!tcon)
120                 goto out;
121
122         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
123         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
124         if ((tcon->ses) && (tcon->ses->server) &&
125             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
126                 shdr->CreditCharge = cpu_to_le16(1);
127         /* else CreditCharge MBZ */
128
129         shdr->TreeId = tcon->tid;
130         /* Uid is not converted */
131         if (tcon->ses)
132                 shdr->SessionId = tcon->ses->Suid;
133
134         /*
135          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
136          * to pass the path on the Open SMB prefixed by \\server\share.
137          * Not sure when we would need to do the augmented path (if ever) and
138          * setting this flag breaks the SMB2 open operation since it is
139          * illegal to send an empty path name (without \\server\share prefix)
140          * when the DFS flag is set in the SMB open header. We could
141          * consider setting the flag on all operations other than open
142          * but it is safer to net set it for now.
143          */
144 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
145                 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
146
147         if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
148             !encryption_required(tcon))
149                 shdr->Flags |= SMB2_FLAGS_SIGNED;
150 out:
151         return;
152 }
153
154 static int
155 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
156 {
157         int rc = 0;
158         struct nls_table *nls_codepage;
159         struct cifs_ses *ses;
160         struct TCP_Server_Info *server;
161
162         /*
163          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
164          * check for tcp and smb session status done differently
165          * for those three - in the calling routine.
166          */
167         if (tcon == NULL)
168                 return rc;
169
170         if (smb2_command == SMB2_TREE_CONNECT)
171                 return rc;
172
173         if (tcon->tidStatus == CifsExiting) {
174                 /*
175                  * only tree disconnect, open, and write,
176                  * (and ulogoff which does not have tcon)
177                  * are allowed as we start force umount.
178                  */
179                 if ((smb2_command != SMB2_WRITE) &&
180                    (smb2_command != SMB2_CREATE) &&
181                    (smb2_command != SMB2_TREE_DISCONNECT)) {
182                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
183                                  smb2_command);
184                         return -ENODEV;
185                 }
186         }
187         if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
188             (!tcon->ses->server))
189                 return -EIO;
190
191         ses = tcon->ses;
192         server = ses->server;
193
194         /*
195          * Give demultiplex thread up to 10 seconds to reconnect, should be
196          * greater than cifs socket timeout which is 7 seconds
197          */
198         while (server->tcpStatus == CifsNeedReconnect) {
199                 /*
200                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
201                  * here since they are implicitly done when session drops.
202                  */
203                 switch (smb2_command) {
204                 /*
205                  * BB Should we keep oplock break and add flush to exceptions?
206                  */
207                 case SMB2_TREE_DISCONNECT:
208                 case SMB2_CANCEL:
209                 case SMB2_CLOSE:
210                 case SMB2_OPLOCK_BREAK:
211                         return -EAGAIN;
212                 }
213
214                 wait_event_interruptible_timeout(server->response_q,
215                         (server->tcpStatus != CifsNeedReconnect), 10 * HZ);
216
217                 /* are we still trying to reconnect? */
218                 if (server->tcpStatus != CifsNeedReconnect)
219                         break;
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         }
231
232         if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
233                 return rc;
234
235         nls_codepage = load_nls_default();
236
237         /*
238          * need to prevent multiple threads trying to simultaneously reconnect
239          * the same SMB session
240          */
241         mutex_lock(&tcon->ses->session_mutex);
242
243         /*
244          * Recheck after acquire mutex. If another thread is negotiating
245          * and the server never sends an answer the socket will be closed
246          * and tcpStatus set to reconnect.
247          */
248         if (server->tcpStatus == CifsNeedReconnect) {
249                 rc = -EHOSTDOWN;
250                 mutex_unlock(&tcon->ses->session_mutex);
251                 goto out;
252         }
253
254         rc = cifs_negotiate_protocol(0, tcon->ses);
255         if (!rc && tcon->ses->need_reconnect)
256                 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
257
258         if (rc || !tcon->need_reconnect) {
259                 mutex_unlock(&tcon->ses->session_mutex);
260                 goto out;
261         }
262
263         cifs_mark_open_files_invalid(tcon);
264         if (tcon->use_persistent)
265                 tcon->need_reopen_files = true;
266
267         rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
268         mutex_unlock(&tcon->ses->session_mutex);
269
270         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
271         if (rc)
272                 goto out;
273
274         if (smb2_command != SMB2_INTERNAL_CMD)
275                 queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
276
277         atomic_inc(&tconInfoReconnectCount);
278 out:
279         /*
280          * Check if handle based operation so we know whether we can continue
281          * or not without returning to caller to reset file handle.
282          */
283         /*
284          * BB Is flush done by server on drop of tcp session? Should we special
285          * case it and skip above?
286          */
287         switch (smb2_command) {
288         case SMB2_FLUSH:
289         case SMB2_READ:
290         case SMB2_WRITE:
291         case SMB2_LOCK:
292         case SMB2_IOCTL:
293         case SMB2_QUERY_DIRECTORY:
294         case SMB2_CHANGE_NOTIFY:
295         case SMB2_QUERY_INFO:
296         case SMB2_SET_INFO:
297                 rc = -EAGAIN;
298         }
299         unload_nls(nls_codepage);
300         return rc;
301 }
302
303 static void
304 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
305                unsigned int *total_len)
306 {
307         struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
308         /* lookup word count ie StructureSize from table */
309         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
310
311         /*
312          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
313          * largest operations (Create)
314          */
315         memset(buf, 0, 256);
316
317         smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
318         spdu->StructureSize2 = cpu_to_le16(parmsize);
319
320         *total_len = parmsize + sizeof(struct smb2_sync_hdr);
321 }
322
323 /*
324  * Allocate and return pointer to an SMB request hdr, and set basic
325  * SMB information in the SMB header. If the return code is zero, this
326  * function must have filled in request_buf pointer.
327  */
328 static int
329 smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
330                     void **request_buf, unsigned int *total_len)
331 {
332         int rc;
333
334         rc = smb2_reconnect(smb2_command, tcon);
335         if (rc)
336                 return rc;
337
338         /* BB eventually switch this to SMB2 specific small buf size */
339         *request_buf = cifs_small_buf_get();
340         if (*request_buf == NULL) {
341                 /* BB should we add a retry in here if not a writepage? */
342                 return -ENOMEM;
343         }
344
345         fill_small_buf(smb2_command, tcon,
346                        (struct smb2_sync_hdr *)(*request_buf),
347                        total_len);
348
349         if (tcon != NULL) {
350 #ifdef CONFIG_CIFS_STATS2
351                 uint16_t com_code = le16_to_cpu(smb2_command);
352                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
353 #endif
354                 cifs_stats_inc(&tcon->num_smbs_sent);
355         }
356
357         return rc;
358 }
359
360 #ifdef CONFIG_CIFS_SMB311
361 /* offset is sizeof smb2_negotiate_req but rounded up to 8 bytes */
362 #define OFFSET_OF_NEG_CONTEXT 0x68  /* sizeof(struct smb2_negotiate_req) */
363
364
365 #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES     cpu_to_le16(1)
366 #define SMB2_ENCRYPTION_CAPABILITIES            cpu_to_le16(2)
367
368 static void
369 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
370 {
371         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
372         pneg_ctxt->DataLength = cpu_to_le16(38);
373         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
374         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
375         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
376         pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
377 }
378
379 static void
380 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
381 {
382         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
383         pneg_ctxt->DataLength = cpu_to_le16(6);
384         pneg_ctxt->CipherCount = cpu_to_le16(2);
385         pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
386         pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
387 }
388
389 static void
390 assemble_neg_contexts(struct smb2_negotiate_req *req,
391                       unsigned int *total_len)
392 {
393         char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT;
394
395         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
396         /* Add 2 to size to round to 8 byte boundary */
397
398         pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context);
399         build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
400         req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
401         req->NegotiateContextCount = cpu_to_le16(2);
402
403         *total_len += 4 + sizeof(struct smb2_preauth_neg_context)
404                 + sizeof(struct smb2_encryption_neg_context);
405 }
406 #else
407 static void assemble_neg_contexts(struct smb2_negotiate_req *req,
408                                   unsigned int *total_len)
409 {
410         return;
411 }
412 #endif /* SMB311 */
413
414 /*
415  *
416  *      SMB2 Worker functions follow:
417  *
418  *      The general structure of the worker functions is:
419  *      1) Call smb2_init (assembles SMB2 header)
420  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
421  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
422  *      4) Decode SMB2 command specific fields in the fixed length area
423  *      5) Decode variable length data area (if any for this SMB2 command type)
424  *      6) Call free smb buffer
425  *      7) return
426  *
427  */
428
429 int
430 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
431 {
432         struct smb2_negotiate_req *req;
433         struct smb2_negotiate_rsp *rsp;
434         struct kvec iov[1];
435         struct kvec rsp_iov;
436         int rc = 0;
437         int resp_buftype;
438         struct TCP_Server_Info *server = ses->server;
439         int blob_offset, blob_length;
440         char *security_blob;
441         int flags = CIFS_NEG_OP;
442         unsigned int total_len;
443
444         cifs_dbg(FYI, "Negotiate protocol\n");
445
446         if (!server) {
447                 WARN(1, "%s: server is NULL!\n", __func__);
448                 return -EIO;
449         }
450
451         rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
452         if (rc)
453                 return rc;
454
455         req->sync_hdr.SessionId = 0;
456 #ifdef CONFIG_CIFS_SMB311
457         memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
458         memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
459 #endif
460
461         if (strcmp(ses->server->vals->version_string,
462                    SMB3ANY_VERSION_STRING) == 0) {
463                 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
464                 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
465                 req->DialectCount = cpu_to_le16(2);
466                 total_len += 4;
467         } else if (strcmp(ses->server->vals->version_string,
468                    SMBDEFAULT_VERSION_STRING) == 0) {
469                 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
470                 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
471                 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
472                 req->DialectCount = cpu_to_le16(3);
473                 total_len += 6;
474         } else {
475                 /* otherwise send specific dialect */
476                 req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
477                 req->DialectCount = cpu_to_le16(1);
478                 total_len += 2;
479         }
480
481         /* only one of SMB2 signing flags may be set in SMB2 request */
482         if (ses->sign)
483                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
484         else if (global_secflags & CIFSSEC_MAY_SIGN)
485                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
486         else
487                 req->SecurityMode = 0;
488
489         req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
490
491         /* ClientGUID must be zero for SMB2.02 dialect */
492         if (ses->server->vals->protocol_id == SMB20_PROT_ID)
493                 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
494         else {
495                 memcpy(req->ClientGUID, server->client_guid,
496                         SMB2_CLIENT_GUID_SIZE);
497                 if (ses->server->vals->protocol_id == SMB311_PROT_ID)
498                         assemble_neg_contexts(req, &total_len);
499         }
500         iov[0].iov_base = (char *)req;
501         iov[0].iov_len = total_len;
502
503         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
504         cifs_small_buf_release(req);
505         rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
506         /*
507          * No tcon so can't do
508          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
509          */
510         if (rc == -EOPNOTSUPP) {
511                 cifs_dbg(VFS, "Dialect not supported by server. Consider "
512                         "specifying vers=1.0 or vers=2.0 on mount for accessing"
513                         " older servers\n");
514                 goto neg_exit;
515         } else if (rc != 0)
516                 goto neg_exit;
517
518         if (strcmp(ses->server->vals->version_string,
519                    SMB3ANY_VERSION_STRING) == 0) {
520                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
521                         cifs_dbg(VFS,
522                                 "SMB2 dialect returned but not requested\n");
523                         return -EIO;
524                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
525                         cifs_dbg(VFS,
526                                 "SMB2.1 dialect returned but not requested\n");
527                         return -EIO;
528                 }
529         } else if (strcmp(ses->server->vals->version_string,
530                    SMBDEFAULT_VERSION_STRING) == 0) {
531                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
532                         cifs_dbg(VFS,
533                                 "SMB2 dialect returned but not requested\n");
534                         return -EIO;
535                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
536                         /* ops set to 3.0 by default for default so update */
537                         ses->server->ops = &smb21_operations;
538                 }
539         } else if (le16_to_cpu(rsp->DialectRevision) !=
540                                 ses->server->vals->protocol_id) {
541                 /* if requested single dialect ensure returned dialect matched */
542                 cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
543                         le16_to_cpu(rsp->DialectRevision));
544                 return -EIO;
545         }
546
547         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
548
549         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
550                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
551         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
552                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
553         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
554                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
555         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
556                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
557 #ifdef CONFIG_CIFS_SMB311
558         else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
559                 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
560 #endif /* SMB311 */
561         else {
562                 cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
563                          le16_to_cpu(rsp->DialectRevision));
564                 rc = -EIO;
565                 goto neg_exit;
566         }
567         server->dialect = le16_to_cpu(rsp->DialectRevision);
568
569         /* BB: add check that dialect was valid given dialect(s) we asked for */
570
571 #ifdef CONFIG_CIFS_SMB311
572         /*
573          * Keep a copy of the hash after negprot. This hash will be
574          * the starting hash value for all sessions made from this
575          * server.
576          */
577         memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
578                SMB2_PREAUTH_HASH_SIZE);
579 #endif
580         /* SMB2 only has an extended negflavor */
581         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
582         /* set it to the maximum buffer size value we can send with 1 credit */
583         server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
584                                SMB2_MAX_BUFFER_SIZE);
585         server->max_read = le32_to_cpu(rsp->MaxReadSize);
586         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
587         /* BB Do we need to validate the SecurityMode? */
588         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
589         server->capabilities = le32_to_cpu(rsp->Capabilities);
590         /* Internal types */
591         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
592
593         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
594                                                &rsp->hdr);
595         /*
596          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
597          * for us will be
598          *      ses->sectype = RawNTLMSSP;
599          * but for time being this is our only auth choice so doesn't matter.
600          * We just found a server which sets blob length to zero expecting raw.
601          */
602         if (blob_length == 0) {
603                 cifs_dbg(FYI, "missing security blob on negprot\n");
604                 server->sec_ntlmssp = true;
605         }
606
607         rc = cifs_enable_signing(server, ses->sign);
608         if (rc)
609                 goto neg_exit;
610         if (blob_length) {
611                 rc = decode_negTokenInit(security_blob, blob_length, server);
612                 if (rc == 1)
613                         rc = 0;
614                 else if (rc == 0)
615                         rc = -EIO;
616         }
617 neg_exit:
618         free_rsp_buf(resp_buftype, rsp);
619         return rc;
620 }
621
622 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
623 {
624         int rc = 0;
625         struct validate_negotiate_info_req vneg_inbuf;
626         struct validate_negotiate_info_rsp *pneg_rsp = NULL;
627         u32 rsplen;
628         u32 inbuflen; /* max of 4 dialects */
629
630         cifs_dbg(FYI, "validate negotiate\n");
631
632 #ifdef CONFIG_CIFS_SMB_DIRECT
633         if (tcon->ses->server->rdma)
634                 return 0;
635 #endif
636
637         /* In SMB3.11 preauth integrity supersedes validate negotiate */
638         if (tcon->ses->server->dialect == SMB311_PROT_ID)
639                 return 0;
640
641         /*
642          * validation ioctl must be signed, so no point sending this if we
643          * can not sign it (ie are not known user).  Even if signing is not
644          * required (enabled but not negotiated), in those cases we selectively
645          * sign just this, the first and only signed request on a connection.
646          * Having validation of negotiate info  helps reduce attack vectors.
647          */
648         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
649                 return 0; /* validation requires signing */
650
651         if (tcon->ses->user_name == NULL) {
652                 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
653                 return 0; /* validation requires signing */
654         }
655
656         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
657                 cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
658
659         vneg_inbuf.Capabilities =
660                         cpu_to_le32(tcon->ses->server->vals->req_capabilities);
661         memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid,
662                                         SMB2_CLIENT_GUID_SIZE);
663
664         if (tcon->ses->sign)
665                 vneg_inbuf.SecurityMode =
666                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
667         else if (global_secflags & CIFSSEC_MAY_SIGN)
668                 vneg_inbuf.SecurityMode =
669                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
670         else
671                 vneg_inbuf.SecurityMode = 0;
672
673
674         if (strcmp(tcon->ses->server->vals->version_string,
675                 SMB3ANY_VERSION_STRING) == 0) {
676                 vneg_inbuf.Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
677                 vneg_inbuf.Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
678                 vneg_inbuf.DialectCount = cpu_to_le16(2);
679                 /* structure is big enough for 3 dialects, sending only 2 */
680                 inbuflen = sizeof(struct validate_negotiate_info_req) - 2;
681         } else if (strcmp(tcon->ses->server->vals->version_string,
682                 SMBDEFAULT_VERSION_STRING) == 0) {
683                 vneg_inbuf.Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
684                 vneg_inbuf.Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
685                 vneg_inbuf.Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
686                 vneg_inbuf.DialectCount = cpu_to_le16(3);
687                 /* structure is big enough for 3 dialects */
688                 inbuflen = sizeof(struct validate_negotiate_info_req);
689         } else {
690                 /* otherwise specific dialect was requested */
691                 vneg_inbuf.Dialects[0] =
692                         cpu_to_le16(tcon->ses->server->vals->protocol_id);
693                 vneg_inbuf.DialectCount = cpu_to_le16(1);
694                 /* structure is big enough for 3 dialects, sending only 1 */
695                 inbuflen = sizeof(struct validate_negotiate_info_req) - 4;
696         }
697
698         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
699                 FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
700                 (char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req),
701                 (char **)&pneg_rsp, &rsplen);
702
703         if (rc != 0) {
704                 cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
705                 return -EIO;
706         }
707
708         if (rsplen != sizeof(struct validate_negotiate_info_rsp)) {
709                 cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n",
710                          rsplen);
711
712                 /* relax check since Mac returns max bufsize allowed on ioctl */
713                 if ((rsplen > CIFSMaxBufSize)
714                      || (rsplen < sizeof(struct validate_negotiate_info_rsp)))
715                         goto err_rsp_free;
716         }
717
718         /* check validate negotiate info response matches what we got earlier */
719         if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->dialect))
720                 goto vneg_out;
721
722         if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
723                 goto vneg_out;
724
725         /* do not validate server guid because not saved at negprot time yet */
726
727         if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
728               SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
729                 goto vneg_out;
730
731         /* validate negotiate successful */
732         cifs_dbg(FYI, "validate negotiate info successful\n");
733         kfree(pneg_rsp);
734         return 0;
735
736 vneg_out:
737         cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
738 err_rsp_free:
739         kfree(pneg_rsp);
740         return -EIO;
741 }
742
743 enum securityEnum
744 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
745 {
746         switch (requested) {
747         case Kerberos:
748         case RawNTLMSSP:
749                 return requested;
750         case NTLMv2:
751                 return RawNTLMSSP;
752         case Unspecified:
753                 if (server->sec_ntlmssp &&
754                         (global_secflags & CIFSSEC_MAY_NTLMSSP))
755                         return RawNTLMSSP;
756                 if ((server->sec_kerberos || server->sec_mskerberos) &&
757                         (global_secflags & CIFSSEC_MAY_KRB5))
758                         return Kerberos;
759                 /* Fallthrough */
760         default:
761                 return Unspecified;
762         }
763 }
764
765 struct SMB2_sess_data {
766         unsigned int xid;
767         struct cifs_ses *ses;
768         struct nls_table *nls_cp;
769         void (*func)(struct SMB2_sess_data *);
770         int result;
771         u64 previous_session;
772
773         /* we will send the SMB in three pieces:
774          * a fixed length beginning part, an optional
775          * SPNEGO blob (which can be zero length), and a
776          * last part which will include the strings
777          * and rest of bcc area. This allows us to avoid
778          * a large buffer 17K allocation
779          */
780         int buf0_type;
781         struct kvec iov[2];
782 };
783
784 static int
785 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
786 {
787         int rc;
788         struct cifs_ses *ses = sess_data->ses;
789         struct smb2_sess_setup_req *req;
790         struct TCP_Server_Info *server = ses->server;
791         unsigned int total_len;
792
793         rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, (void **) &req,
794                              &total_len);
795         if (rc)
796                 return rc;
797
798         /* First session, not a reauthenticate */
799         req->sync_hdr.SessionId = 0;
800
801         /* if reconnect, we need to send previous sess id, otherwise it is 0 */
802         req->PreviousSessionId = sess_data->previous_session;
803
804         req->Flags = 0; /* MBZ */
805         /* to enable echos and oplocks */
806         req->sync_hdr.CreditRequest = cpu_to_le16(3);
807
808         /* only one of SMB2 signing flags may be set in SMB2 request */
809         if (server->sign)
810                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
811         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
812                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
813         else
814                 req->SecurityMode = 0;
815
816         req->Capabilities = 0;
817         req->Channel = 0; /* MBZ */
818
819         sess_data->iov[0].iov_base = (char *)req;
820         /* 1 for pad */
821         sess_data->iov[0].iov_len = total_len - 1;
822         /*
823          * This variable will be used to clear the buffer
824          * allocated above in case of any error in the calling function.
825          */
826         sess_data->buf0_type = CIFS_SMALL_BUFFER;
827
828         return 0;
829 }
830
831 static void
832 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
833 {
834         free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
835         sess_data->buf0_type = CIFS_NO_BUFFER;
836 }
837
838 static int
839 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
840 {
841         int rc;
842         struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
843         struct kvec rsp_iov = { NULL, 0 };
844
845         /* Testing shows that buffer offset must be at location of Buffer[0] */
846         req->SecurityBufferOffset =
847                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
848         req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
849
850         /* BB add code to build os and lm fields */
851
852         rc = smb2_send_recv(sess_data->xid, sess_data->ses,
853                             sess_data->iov, 2,
854                             &sess_data->buf0_type,
855                             CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
856         cifs_small_buf_release(sess_data->iov[0].iov_base);
857         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
858
859         return rc;
860 }
861
862 static int
863 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
864 {
865         int rc = 0;
866         struct cifs_ses *ses = sess_data->ses;
867
868         mutex_lock(&ses->server->srv_mutex);
869         if (ses->server->ops->generate_signingkey) {
870                 rc = ses->server->ops->generate_signingkey(ses);
871                 if (rc) {
872                         cifs_dbg(FYI,
873                                 "SMB3 session key generation failed\n");
874                         mutex_unlock(&ses->server->srv_mutex);
875                         return rc;
876                 }
877         }
878         if (!ses->server->session_estab) {
879                 ses->server->sequence_number = 0x2;
880                 ses->server->session_estab = true;
881         }
882         mutex_unlock(&ses->server->srv_mutex);
883
884         cifs_dbg(FYI, "SMB2/3 session established successfully\n");
885         spin_lock(&GlobalMid_Lock);
886         ses->status = CifsGood;
887         ses->need_reconnect = false;
888         spin_unlock(&GlobalMid_Lock);
889         return rc;
890 }
891
892 #ifdef CONFIG_CIFS_UPCALL
893 static void
894 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
895 {
896         int rc;
897         struct cifs_ses *ses = sess_data->ses;
898         struct cifs_spnego_msg *msg;
899         struct key *spnego_key = NULL;
900         struct smb2_sess_setup_rsp *rsp = NULL;
901
902         rc = SMB2_sess_alloc_buffer(sess_data);
903         if (rc)
904                 goto out;
905
906         spnego_key = cifs_get_spnego_key(ses);
907         if (IS_ERR(spnego_key)) {
908                 rc = PTR_ERR(spnego_key);
909                 spnego_key = NULL;
910                 goto out;
911         }
912
913         msg = spnego_key->payload.data[0];
914         /*
915          * check version field to make sure that cifs.upcall is
916          * sending us a response in an expected form
917          */
918         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
919                 cifs_dbg(VFS,
920                           "bad cifs.upcall version. Expected %d got %d",
921                           CIFS_SPNEGO_UPCALL_VERSION, msg->version);
922                 rc = -EKEYREJECTED;
923                 goto out_put_spnego_key;
924         }
925
926         ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
927                                          GFP_KERNEL);
928         if (!ses->auth_key.response) {
929                 cifs_dbg(VFS,
930                         "Kerberos can't allocate (%u bytes) memory",
931                         msg->sesskey_len);
932                 rc = -ENOMEM;
933                 goto out_put_spnego_key;
934         }
935         ses->auth_key.len = msg->sesskey_len;
936
937         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
938         sess_data->iov[1].iov_len = msg->secblob_len;
939
940         rc = SMB2_sess_sendreceive(sess_data);
941         if (rc)
942                 goto out_put_spnego_key;
943
944         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
945         ses->Suid = rsp->hdr.sync_hdr.SessionId;
946
947         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
948
949         rc = SMB2_sess_establish_session(sess_data);
950 out_put_spnego_key:
951         key_invalidate(spnego_key);
952         key_put(spnego_key);
953 out:
954         sess_data->result = rc;
955         sess_data->func = NULL;
956         SMB2_sess_free_buffer(sess_data);
957 }
958 #else
959 static void
960 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
961 {
962         cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
963         sess_data->result = -EOPNOTSUPP;
964         sess_data->func = NULL;
965 }
966 #endif
967
968 static void
969 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
970
971 static void
972 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
973 {
974         int rc;
975         struct cifs_ses *ses = sess_data->ses;
976         struct smb2_sess_setup_rsp *rsp = NULL;
977         char *ntlmssp_blob = NULL;
978         bool use_spnego = false; /* else use raw ntlmssp */
979         u16 blob_length = 0;
980
981         /*
982          * If memory allocation is successful, caller of this function
983          * frees it.
984          */
985         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
986         if (!ses->ntlmssp) {
987                 rc = -ENOMEM;
988                 goto out_err;
989         }
990         ses->ntlmssp->sesskey_per_smbsess = true;
991
992         rc = SMB2_sess_alloc_buffer(sess_data);
993         if (rc)
994                 goto out_err;
995
996         ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
997                                GFP_KERNEL);
998         if (ntlmssp_blob == NULL) {
999                 rc = -ENOMEM;
1000                 goto out;
1001         }
1002
1003         build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
1004         if (use_spnego) {
1005                 /* BB eventually need to add this */
1006                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1007                 rc = -EOPNOTSUPP;
1008                 goto out;
1009         } else {
1010                 blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
1011                 /* with raw NTLMSSP we don't encapsulate in SPNEGO */
1012         }
1013         sess_data->iov[1].iov_base = ntlmssp_blob;
1014         sess_data->iov[1].iov_len = blob_length;
1015
1016         rc = SMB2_sess_sendreceive(sess_data);
1017         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1018
1019         /* If true, rc here is expected and not an error */
1020         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1021                 rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1022                 rc = 0;
1023
1024         if (rc)
1025                 goto out;
1026
1027         if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
1028                         le16_to_cpu(rsp->SecurityBufferOffset)) {
1029                 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1030                         le16_to_cpu(rsp->SecurityBufferOffset));
1031                 rc = -EIO;
1032                 goto out;
1033         }
1034         rc = decode_ntlmssp_challenge(rsp->Buffer,
1035                         le16_to_cpu(rsp->SecurityBufferLength), ses);
1036         if (rc)
1037                 goto out;
1038
1039         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1040
1041
1042         ses->Suid = rsp->hdr.sync_hdr.SessionId;
1043         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1044
1045 out:
1046         kfree(ntlmssp_blob);
1047         SMB2_sess_free_buffer(sess_data);
1048         if (!rc) {
1049                 sess_data->result = 0;
1050                 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1051                 return;
1052         }
1053 out_err:
1054         kfree(ses->ntlmssp);
1055         ses->ntlmssp = NULL;
1056         sess_data->result = rc;
1057         sess_data->func = NULL;
1058 }
1059
1060 static void
1061 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1062 {
1063         int rc;
1064         struct cifs_ses *ses = sess_data->ses;
1065         struct smb2_sess_setup_req *req;
1066         struct smb2_sess_setup_rsp *rsp = NULL;
1067         unsigned char *ntlmssp_blob = NULL;
1068         bool use_spnego = false; /* else use raw ntlmssp */
1069         u16 blob_length = 0;
1070
1071         rc = SMB2_sess_alloc_buffer(sess_data);
1072         if (rc)
1073                 goto out;
1074
1075         req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1076         req->sync_hdr.SessionId = ses->Suid;
1077
1078         rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1079                                         sess_data->nls_cp);
1080         if (rc) {
1081                 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1082                 goto out;
1083         }
1084
1085         if (use_spnego) {
1086                 /* BB eventually need to add this */
1087                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1088                 rc = -EOPNOTSUPP;
1089                 goto out;
1090         }
1091         sess_data->iov[1].iov_base = ntlmssp_blob;
1092         sess_data->iov[1].iov_len = blob_length;
1093
1094         rc = SMB2_sess_sendreceive(sess_data);
1095         if (rc)
1096                 goto out;
1097
1098         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1099
1100         ses->Suid = rsp->hdr.sync_hdr.SessionId;
1101         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1102
1103         rc = SMB2_sess_establish_session(sess_data);
1104 out:
1105         kfree(ntlmssp_blob);
1106         SMB2_sess_free_buffer(sess_data);
1107         kfree(ses->ntlmssp);
1108         ses->ntlmssp = NULL;
1109         sess_data->result = rc;
1110         sess_data->func = NULL;
1111 }
1112
1113 static int
1114 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1115 {
1116         int type;
1117
1118         type = smb2_select_sectype(ses->server, ses->sectype);
1119         cifs_dbg(FYI, "sess setup type %d\n", type);
1120         if (type == Unspecified) {
1121                 cifs_dbg(VFS,
1122                         "Unable to select appropriate authentication method!");
1123                 return -EINVAL;
1124         }
1125
1126         switch (type) {
1127         case Kerberos:
1128                 sess_data->func = SMB2_auth_kerberos;
1129                 break;
1130         case RawNTLMSSP:
1131                 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1132                 break;
1133         default:
1134                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1135                 return -EOPNOTSUPP;
1136         }
1137
1138         return 0;
1139 }
1140
1141 int
1142 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1143                 const struct nls_table *nls_cp)
1144 {
1145         int rc = 0;
1146         struct TCP_Server_Info *server = ses->server;
1147         struct SMB2_sess_data *sess_data;
1148
1149         cifs_dbg(FYI, "Session Setup\n");
1150
1151         if (!server) {
1152                 WARN(1, "%s: server is NULL!\n", __func__);
1153                 return -EIO;
1154         }
1155
1156         sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1157         if (!sess_data)
1158                 return -ENOMEM;
1159
1160         rc = SMB2_select_sec(ses, sess_data);
1161         if (rc)
1162                 goto out;
1163         sess_data->xid = xid;
1164         sess_data->ses = ses;
1165         sess_data->buf0_type = CIFS_NO_BUFFER;
1166         sess_data->nls_cp = (struct nls_table *) nls_cp;
1167
1168 #ifdef CONFIG_CIFS_SMB311
1169         /*
1170          * Initialize the session hash with the server one.
1171          */
1172         memcpy(ses->preauth_sha_hash, ses->server->preauth_sha_hash,
1173                SMB2_PREAUTH_HASH_SIZE);
1174 #endif
1175
1176         while (sess_data->func)
1177                 sess_data->func(sess_data);
1178
1179         if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1180                 cifs_dbg(VFS, "signing requested but authenticated as guest\n");
1181         rc = sess_data->result;
1182 out:
1183         kfree(sess_data);
1184         return rc;
1185 }
1186
1187 int
1188 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1189 {
1190         struct smb2_logoff_req *req; /* response is also trivial struct */
1191         int rc = 0;
1192         struct TCP_Server_Info *server;
1193         int flags = 0;
1194         unsigned int total_len;
1195         struct kvec iov[1];
1196         struct kvec rsp_iov;
1197         int resp_buf_type;
1198
1199         cifs_dbg(FYI, "disconnect session %p\n", ses);
1200
1201         if (ses && (ses->server))
1202                 server = ses->server;
1203         else
1204                 return -EIO;
1205
1206         /* no need to send SMB logoff if uid already closed due to reconnect */
1207         if (ses->need_reconnect)
1208                 goto smb2_session_already_dead;
1209
1210         rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, (void **) &req, &total_len);
1211         if (rc)
1212                 return rc;
1213
1214          /* since no tcon, smb2_init can not do this, so do here */
1215         req->sync_hdr.SessionId = ses->Suid;
1216
1217         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1218                 flags |= CIFS_TRANSFORM_REQ;
1219         else if (server->sign)
1220                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1221
1222         flags |= CIFS_NO_RESP;
1223
1224         iov[0].iov_base = (char *)req;
1225         iov[0].iov_len = total_len;
1226
1227         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buf_type, flags, &rsp_iov);
1228         cifs_small_buf_release(req);
1229         /*
1230          * No tcon so can't do
1231          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1232          */
1233
1234 smb2_session_already_dead:
1235         return rc;
1236 }
1237
1238 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1239 {
1240         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1241 }
1242
1243 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1244
1245 /* These are similar values to what Windows uses */
1246 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1247 {
1248         tcon->max_chunks = 256;
1249         tcon->max_bytes_chunk = 1048576;
1250         tcon->max_bytes_copy = 16777216;
1251 }
1252
1253 int
1254 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1255           struct cifs_tcon *tcon, const struct nls_table *cp)
1256 {
1257         struct smb2_tree_connect_req *req;
1258         struct smb2_tree_connect_rsp *rsp = NULL;
1259         struct kvec iov[2];
1260         struct kvec rsp_iov = { NULL, 0 };
1261         int rc = 0;
1262         int resp_buftype;
1263         int unc_path_len;
1264         __le16 *unc_path = NULL;
1265         int flags = 0;
1266         unsigned int total_len;
1267
1268         cifs_dbg(FYI, "TCON\n");
1269
1270         if (!(ses->server) || !tree)
1271                 return -EIO;
1272
1273         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1274         if (unc_path == NULL)
1275                 return -ENOMEM;
1276
1277         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1278         unc_path_len *= 2;
1279         if (unc_path_len < 2) {
1280                 kfree(unc_path);
1281                 return -EINVAL;
1282         }
1283
1284         /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1285         tcon->tid = 0;
1286
1287         rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, (void **) &req,
1288                              &total_len);
1289         if (rc) {
1290                 kfree(unc_path);
1291                 return rc;
1292         }
1293
1294         if (encryption_required(tcon))
1295                 flags |= CIFS_TRANSFORM_REQ;
1296
1297         iov[0].iov_base = (char *)req;
1298         /* 1 for pad */
1299         iov[0].iov_len = total_len - 1;
1300
1301         /* Testing shows that buffer offset must be at location of Buffer[0] */
1302         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1303                         - 1 /* pad */);
1304         req->PathLength = cpu_to_le16(unc_path_len - 2);
1305         iov[1].iov_base = unc_path;
1306         iov[1].iov_len = unc_path_len;
1307
1308         /* 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1 */
1309         if ((ses->server->dialect == SMB311_PROT_ID) &&
1310             !encryption_required(tcon))
1311                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1312
1313         rc = smb2_send_recv(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
1314         cifs_small_buf_release(req);
1315         rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1316
1317         if (rc != 0) {
1318                 if (tcon) {
1319                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1320                         tcon->need_reconnect = true;
1321                 }
1322                 goto tcon_error_exit;
1323         }
1324
1325         switch (rsp->ShareType) {
1326         case SMB2_SHARE_TYPE_DISK:
1327                 cifs_dbg(FYI, "connection to disk share\n");
1328                 break;
1329         case SMB2_SHARE_TYPE_PIPE:
1330                 tcon->pipe = true;
1331                 cifs_dbg(FYI, "connection to pipe share\n");
1332                 break;
1333         case SMB2_SHARE_TYPE_PRINT:
1334                 tcon->print = true;
1335                 cifs_dbg(FYI, "connection to printer\n");
1336                 break;
1337         default:
1338                 cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1339                 rc = -EOPNOTSUPP;
1340                 goto tcon_error_exit;
1341         }
1342
1343         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1344         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1345         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1346         tcon->tidStatus = CifsGood;
1347         tcon->need_reconnect = false;
1348         tcon->tid = rsp->hdr.sync_hdr.TreeId;
1349         strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1350
1351         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1352             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1353                 cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1354
1355         if (tcon->seal &&
1356             !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1357                 cifs_dbg(VFS, "Encryption is requested but not supported\n");
1358
1359         init_copy_chunk_defaults(tcon);
1360         if (tcon->ses->server->ops->validate_negotiate)
1361                 rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1362 tcon_exit:
1363         free_rsp_buf(resp_buftype, rsp);
1364         kfree(unc_path);
1365         return rc;
1366
1367 tcon_error_exit:
1368         if (rsp && rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1369                 cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1370         }
1371         goto tcon_exit;
1372 }
1373
1374 int
1375 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1376 {
1377         struct smb2_tree_disconnect_req *req; /* response is trivial */
1378         int rc = 0;
1379         struct cifs_ses *ses = tcon->ses;
1380         int flags = 0;
1381         unsigned int total_len;
1382         struct kvec iov[1];
1383         struct kvec rsp_iov;
1384         int resp_buf_type;
1385
1386         cifs_dbg(FYI, "Tree Disconnect\n");
1387
1388         if (!ses || !(ses->server))
1389                 return -EIO;
1390
1391         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1392                 return 0;
1393
1394         rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req,
1395                              &total_len);
1396         if (rc)
1397                 return rc;
1398
1399         if (encryption_required(tcon))
1400                 flags |= CIFS_TRANSFORM_REQ;
1401
1402         flags |= CIFS_NO_RESP;
1403
1404         iov[0].iov_base = (char *)req;
1405         iov[0].iov_len = total_len;
1406
1407         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buf_type, flags, &rsp_iov);
1408         cifs_small_buf_release(req);
1409         if (rc)
1410                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1411
1412         return rc;
1413 }
1414
1415
1416 static struct create_durable *
1417 create_durable_buf(void)
1418 {
1419         struct create_durable *buf;
1420
1421         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1422         if (!buf)
1423                 return NULL;
1424
1425         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1426                                         (struct create_durable, Data));
1427         buf->ccontext.DataLength = cpu_to_le32(16);
1428         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1429                                 (struct create_durable, Name));
1430         buf->ccontext.NameLength = cpu_to_le16(4);
1431         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1432         buf->Name[0] = 'D';
1433         buf->Name[1] = 'H';
1434         buf->Name[2] = 'n';
1435         buf->Name[3] = 'Q';
1436         return buf;
1437 }
1438
1439 static struct create_durable *
1440 create_reconnect_durable_buf(struct cifs_fid *fid)
1441 {
1442         struct create_durable *buf;
1443
1444         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1445         if (!buf)
1446                 return NULL;
1447
1448         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1449                                         (struct create_durable, Data));
1450         buf->ccontext.DataLength = cpu_to_le32(16);
1451         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1452                                 (struct create_durable, Name));
1453         buf->ccontext.NameLength = cpu_to_le16(4);
1454         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1455         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1456         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1457         buf->Name[0] = 'D';
1458         buf->Name[1] = 'H';
1459         buf->Name[2] = 'n';
1460         buf->Name[3] = 'C';
1461         return buf;
1462 }
1463
1464 static __u8
1465 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1466                   unsigned int *epoch)
1467 {
1468         char *data_offset;
1469         struct create_context *cc;
1470         unsigned int next;
1471         unsigned int remaining;
1472         char *name;
1473
1474         data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
1475         remaining = le32_to_cpu(rsp->CreateContextsLength);
1476         cc = (struct create_context *)data_offset;
1477         while (remaining >= sizeof(struct create_context)) {
1478                 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1479                 if (le16_to_cpu(cc->NameLength) == 4 &&
1480                     strncmp(name, "RqLs", 4) == 0)
1481                         return server->ops->parse_lease_buf(cc, epoch);
1482
1483                 next = le32_to_cpu(cc->Next);
1484                 if (!next)
1485                         break;
1486                 remaining -= next;
1487                 cc = (struct create_context *)((char *)cc + next);
1488         }
1489
1490         return 0;
1491 }
1492
1493 static int
1494 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1495                   unsigned int *num_iovec, __u8 *oplock)
1496 {
1497         struct smb2_create_req *req = iov[0].iov_base;
1498         unsigned int num = *num_iovec;
1499
1500         iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
1501         if (iov[num].iov_base == NULL)
1502                 return -ENOMEM;
1503         iov[num].iov_len = server->vals->create_lease_size;
1504         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1505         if (!req->CreateContextsOffset)
1506                 req->CreateContextsOffset = cpu_to_le32(
1507                                 sizeof(struct smb2_create_req) +
1508                                 iov[num - 1].iov_len);
1509         le32_add_cpu(&req->CreateContextsLength,
1510                      server->vals->create_lease_size);
1511         *num_iovec = num + 1;
1512         return 0;
1513 }
1514
1515 static struct create_durable_v2 *
1516 create_durable_v2_buf(struct cifs_fid *pfid)
1517 {
1518         struct create_durable_v2 *buf;
1519
1520         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1521         if (!buf)
1522                 return NULL;
1523
1524         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1525                                         (struct create_durable_v2, dcontext));
1526         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1527         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1528                                 (struct create_durable_v2, Name));
1529         buf->ccontext.NameLength = cpu_to_le16(4);
1530
1531         buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1532         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1533         generate_random_uuid(buf->dcontext.CreateGuid);
1534         memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1535
1536         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1537         buf->Name[0] = 'D';
1538         buf->Name[1] = 'H';
1539         buf->Name[2] = '2';
1540         buf->Name[3] = 'Q';
1541         return buf;
1542 }
1543
1544 static struct create_durable_handle_reconnect_v2 *
1545 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1546 {
1547         struct create_durable_handle_reconnect_v2 *buf;
1548
1549         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1550                         GFP_KERNEL);
1551         if (!buf)
1552                 return NULL;
1553
1554         buf->ccontext.DataOffset =
1555                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1556                                      dcontext));
1557         buf->ccontext.DataLength =
1558                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1559         buf->ccontext.NameOffset =
1560                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1561                             Name));
1562         buf->ccontext.NameLength = cpu_to_le16(4);
1563
1564         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1565         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1566         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1567         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1568
1569         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1570         buf->Name[0] = 'D';
1571         buf->Name[1] = 'H';
1572         buf->Name[2] = '2';
1573         buf->Name[3] = 'C';
1574         return buf;
1575 }
1576
1577 static int
1578 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1579                     struct cifs_open_parms *oparms)
1580 {
1581         struct smb2_create_req *req = iov[0].iov_base;
1582         unsigned int num = *num_iovec;
1583
1584         iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1585         if (iov[num].iov_base == NULL)
1586                 return -ENOMEM;
1587         iov[num].iov_len = sizeof(struct create_durable_v2);
1588         if (!req->CreateContextsOffset)
1589                 req->CreateContextsOffset =
1590                         cpu_to_le32(sizeof(struct smb2_create_req) +
1591                                                                 iov[1].iov_len);
1592         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1593         *num_iovec = num + 1;
1594         return 0;
1595 }
1596
1597 static int
1598 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1599                     struct cifs_open_parms *oparms)
1600 {
1601         struct smb2_create_req *req = iov[0].iov_base;
1602         unsigned int num = *num_iovec;
1603
1604         /* indicate that we don't need to relock the file */
1605         oparms->reconnect = false;
1606
1607         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1608         if (iov[num].iov_base == NULL)
1609                 return -ENOMEM;
1610         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1611         if (!req->CreateContextsOffset)
1612                 req->CreateContextsOffset =
1613                         cpu_to_le32(sizeof(struct smb2_create_req) +
1614                                                                 iov[1].iov_len);
1615         le32_add_cpu(&req->CreateContextsLength,
1616                         sizeof(struct create_durable_handle_reconnect_v2));
1617         *num_iovec = num + 1;
1618         return 0;
1619 }
1620
1621 static int
1622 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1623                     struct cifs_open_parms *oparms, bool use_persistent)
1624 {
1625         struct smb2_create_req *req = iov[0].iov_base;
1626         unsigned int num = *num_iovec;
1627
1628         if (use_persistent) {
1629                 if (oparms->reconnect)
1630                         return add_durable_reconnect_v2_context(iov, num_iovec,
1631                                                                 oparms);
1632                 else
1633                         return add_durable_v2_context(iov, num_iovec, oparms);
1634         }
1635
1636         if (oparms->reconnect) {
1637                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1638                 /* indicate that we don't need to relock the file */
1639                 oparms->reconnect = false;
1640         } else
1641                 iov[num].iov_base = create_durable_buf();
1642         if (iov[num].iov_base == NULL)
1643                 return -ENOMEM;
1644         iov[num].iov_len = sizeof(struct create_durable);
1645         if (!req->CreateContextsOffset)
1646                 req->CreateContextsOffset =
1647                         cpu_to_le32(sizeof(struct smb2_create_req) +
1648                                                                 iov[1].iov_len);
1649         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1650         *num_iovec = num + 1;
1651         return 0;
1652 }
1653
1654 static int
1655 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
1656                             const char *treename, const __le16 *path)
1657 {
1658         int treename_len, path_len;
1659         struct nls_table *cp;
1660         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
1661
1662         /*
1663          * skip leading "\\"
1664          */
1665         treename_len = strlen(treename);
1666         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
1667                 return -EINVAL;
1668
1669         treename += 2;
1670         treename_len -= 2;
1671
1672         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
1673
1674         /*
1675          * make room for one path separator between the treename and
1676          * path
1677          */
1678         *out_len = treename_len + 1 + path_len;
1679
1680         /*
1681          * final path needs to be null-terminated UTF16 with a
1682          * size aligned to 8
1683          */
1684
1685         *out_size = roundup((*out_len+1)*2, 8);
1686         *out_path = kzalloc(*out_size, GFP_KERNEL);
1687         if (!*out_path)
1688                 return -ENOMEM;
1689
1690         cp = load_nls_default();
1691         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
1692         UniStrcat(*out_path, sep);
1693         UniStrcat(*out_path, path);
1694         unload_nls(cp);
1695
1696         return 0;
1697 }
1698
1699 int
1700 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
1701           __u8 *oplock, struct smb2_file_all_info *buf,
1702           struct smb2_err_rsp **err_buf)
1703 {
1704         struct smb2_create_req *req;
1705         struct smb2_create_rsp *rsp;
1706         struct TCP_Server_Info *server;
1707         struct cifs_tcon *tcon = oparms->tcon;
1708         struct cifs_ses *ses = tcon->ses;
1709         struct kvec iov[4];
1710         struct kvec rsp_iov = {NULL, 0};
1711         int resp_buftype;
1712         int uni_path_len;
1713         __le16 *copy_path = NULL;
1714         int copy_size;
1715         int rc = 0;
1716         unsigned int n_iov = 2;
1717         __u32 file_attributes = 0;
1718         char *dhc_buf = NULL, *lc_buf = NULL;
1719         int flags = 0;
1720         unsigned int total_len;
1721
1722         cifs_dbg(FYI, "create/open\n");
1723
1724         if (ses && (ses->server))
1725                 server = ses->server;
1726         else
1727                 return -EIO;
1728
1729         rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len);
1730
1731         if (rc)
1732                 return rc;
1733
1734         if (encryption_required(tcon))
1735                 flags |= CIFS_TRANSFORM_REQ;
1736
1737         if (oparms->create_options & CREATE_OPTION_READONLY)
1738                 file_attributes |= ATTR_READONLY;
1739         if (oparms->create_options & CREATE_OPTION_SPECIAL)
1740                 file_attributes |= ATTR_SYSTEM;
1741
1742         req->ImpersonationLevel = IL_IMPERSONATION;
1743         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
1744         /* File attributes ignored on open (used in create though) */
1745         req->FileAttributes = cpu_to_le32(file_attributes);
1746         req->ShareAccess = FILE_SHARE_ALL_LE;
1747         req->CreateDisposition = cpu_to_le32(oparms->disposition);
1748         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
1749
1750         iov[0].iov_base = (char *)req;
1751         /* -1 since last byte is buf[0] which is sent below (path) */
1752         iov[0].iov_len = total_len - 1;
1753
1754         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
1755
1756         /* [MS-SMB2] 2.2.13 NameOffset:
1757          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
1758          * the SMB2 header, the file name includes a prefix that will
1759          * be processed during DFS name normalization as specified in
1760          * section 3.3.5.9. Otherwise, the file name is relative to
1761          * the share that is identified by the TreeId in the SMB2
1762          * header.
1763          */
1764         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
1765                 int name_len;
1766
1767                 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
1768                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
1769                                                  &name_len,
1770                                                  tcon->treeName, path);
1771                 if (rc) {
1772                         cifs_small_buf_release(req);
1773                         return rc;
1774                 }
1775                 req->NameLength = cpu_to_le16(name_len * 2);
1776                 uni_path_len = copy_size;
1777                 path = copy_path;
1778         } else {
1779                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
1780                 /* MUST set path len (NameLength) to 0 opening root of share */
1781                 req->NameLength = cpu_to_le16(uni_path_len - 2);
1782                 if (uni_path_len % 8 != 0) {
1783                         copy_size = roundup(uni_path_len, 8);
1784                         copy_path = kzalloc(copy_size, GFP_KERNEL);
1785                         if (!copy_path) {
1786                                 cifs_small_buf_release(req);
1787                                 return -ENOMEM;
1788                         }
1789                         memcpy((char *)copy_path, (const char *)path,
1790                                uni_path_len);
1791                         uni_path_len = copy_size;
1792                         path = copy_path;
1793                 }
1794         }
1795
1796         iov[1].iov_len = uni_path_len;
1797         iov[1].iov_base = path;
1798
1799         if (!server->oplocks)
1800                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
1801
1802         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1803             *oplock == SMB2_OPLOCK_LEVEL_NONE)
1804                 req->RequestedOplockLevel = *oplock;
1805         else {
1806                 rc = add_lease_context(server, iov, &n_iov, oplock);
1807                 if (rc) {
1808                         cifs_small_buf_release(req);
1809                         kfree(copy_path);
1810                         return rc;
1811                 }
1812                 lc_buf = iov[n_iov-1].iov_base;
1813         }
1814
1815         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1816                 /* need to set Next field of lease context if we request it */
1817                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1818                         struct create_context *ccontext =
1819                             (struct create_context *)iov[n_iov-1].iov_base;
1820                         ccontext->Next =
1821                                 cpu_to_le32(server->vals->create_lease_size);
1822                 }
1823
1824                 rc = add_durable_context(iov, &n_iov, oparms,
1825                                         tcon->use_persistent);
1826                 if (rc) {
1827                         cifs_small_buf_release(req);
1828                         kfree(copy_path);
1829                         kfree(lc_buf);
1830                         return rc;
1831                 }
1832                 dhc_buf = iov[n_iov-1].iov_base;
1833         }
1834
1835         rc = smb2_send_recv(xid, ses, iov, n_iov, &resp_buftype, flags,
1836                             &rsp_iov);
1837         cifs_small_buf_release(req);
1838         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
1839
1840         if (rc != 0) {
1841                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1842                 if (err_buf && rsp)
1843                         *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
1844                                            GFP_KERNEL);
1845                 goto creat_exit;
1846         }
1847
1848         oparms->fid->persistent_fid = rsp->PersistentFileId;
1849         oparms->fid->volatile_fid = rsp->VolatileFileId;
1850
1851         if (buf) {
1852                 memcpy(buf, &rsp->CreationTime, 32);
1853                 buf->AllocationSize = rsp->AllocationSize;
1854                 buf->EndOfFile = rsp->EndofFile;
1855                 buf->Attributes = rsp->FileAttributes;
1856                 buf->NumberOfLinks = cpu_to_le32(1);
1857                 buf->DeletePending = 0;
1858         }
1859
1860         if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1861                 *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
1862         else
1863                 *oplock = rsp->OplockLevel;
1864 creat_exit:
1865         kfree(copy_path);
1866         kfree(lc_buf);
1867         kfree(dhc_buf);
1868         free_rsp_buf(resp_buftype, rsp);
1869         return rc;
1870 }
1871
1872 /*
1873  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
1874  */
1875 int
1876 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1877            u64 volatile_fid, u32 opcode, bool is_fsctl,
1878            char *in_data, u32 indatalen,
1879            char **out_data, u32 *plen /* returned data len */)
1880 {
1881         struct smb2_ioctl_req *req;
1882         struct smb2_ioctl_rsp *rsp;
1883         struct smb2_sync_hdr *shdr;
1884         struct cifs_ses *ses;
1885         struct kvec iov[2];
1886         struct kvec rsp_iov;
1887         int resp_buftype;
1888         int n_iov;
1889         int rc = 0;
1890         int flags = 0;
1891         unsigned int total_len;
1892
1893         cifs_dbg(FYI, "SMB2 IOCTL\n");
1894
1895         if (out_data != NULL)
1896                 *out_data = NULL;
1897
1898         /* zero out returned data len, in case of error */
1899         if (plen)
1900                 *plen = 0;
1901
1902         if (tcon)
1903                 ses = tcon->ses;
1904         else
1905                 return -EIO;
1906
1907         if (!ses || !(ses->server))
1908                 return -EIO;
1909
1910         rc = smb2_plain_req_init(SMB2_IOCTL, tcon, (void **) &req, &total_len);
1911         if (rc)
1912                 return rc;
1913
1914         if (encryption_required(tcon))
1915                 flags |= CIFS_TRANSFORM_REQ;
1916
1917         req->CtlCode = cpu_to_le32(opcode);
1918         req->PersistentFileId = persistent_fid;
1919         req->VolatileFileId = volatile_fid;
1920
1921         if (indatalen) {
1922                 req->InputCount = cpu_to_le32(indatalen);
1923                 /* do not set InputOffset if no input data */
1924                 req->InputOffset =
1925                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
1926                 iov[1].iov_base = in_data;
1927                 iov[1].iov_len = indatalen;
1928                 n_iov = 2;
1929         } else
1930                 n_iov = 1;
1931
1932         req->OutputOffset = 0;
1933         req->OutputCount = 0; /* MBZ */
1934
1935         /*
1936          * Could increase MaxOutputResponse, but that would require more
1937          * than one credit. Windows typically sets this smaller, but for some
1938          * ioctls it may be useful to allow server to send more. No point
1939          * limiting what the server can send as long as fits in one credit
1940          * Unfortunately - we can not handle more than CIFS_MAX_MSG_SIZE
1941          * (by default, note that it can be overridden to make max larger)
1942          * in responses (except for read responses which can be bigger.
1943          * We may want to bump this limit up
1944          */
1945         req->MaxOutputResponse = cpu_to_le32(CIFSMaxBufSize);
1946
1947         if (is_fsctl)
1948                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1949         else
1950                 req->Flags = 0;
1951
1952         iov[0].iov_base = (char *)req;
1953
1954         /*
1955          * If no input data, the size of ioctl struct in
1956          * protocol spec still includes a 1 byte data buffer,
1957          * but if input data passed to ioctl, we do not
1958          * want to double count this, so we do not send
1959          * the dummy one byte of data in iovec[0] if sending
1960          * input data (in iovec[1]).
1961          */
1962
1963         if (indatalen) {
1964                 iov[0].iov_len = total_len - 1;
1965         } else
1966                 iov[0].iov_len = total_len;
1967
1968         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
1969         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
1970                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1971
1972         rc = smb2_send_recv(xid, ses, iov, n_iov, &resp_buftype, flags,
1973                             &rsp_iov);
1974         cifs_small_buf_release(req);
1975         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
1976
1977         if ((rc != 0) && (rc != -EINVAL)) {
1978                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1979                 goto ioctl_exit;
1980         } else if (rc == -EINVAL) {
1981                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
1982                     (opcode != FSCTL_SRV_COPYCHUNK)) {
1983                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1984                         goto ioctl_exit;
1985                 }
1986         }
1987
1988         /* check if caller wants to look at return data or just return rc */
1989         if ((plen == NULL) || (out_data == NULL))
1990                 goto ioctl_exit;
1991
1992         *plen = le32_to_cpu(rsp->OutputCount);
1993
1994         /* We check for obvious errors in the output buffer length and offset */
1995         if (*plen == 0)
1996                 goto ioctl_exit; /* server returned no data */
1997         else if (*plen > 0xFF00) {
1998                 cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
1999                 *plen = 0;
2000                 rc = -EIO;
2001                 goto ioctl_exit;
2002         }
2003
2004         if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
2005                 cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
2006                         le32_to_cpu(rsp->OutputOffset));
2007                 *plen = 0;
2008                 rc = -EIO;
2009                 goto ioctl_exit;
2010         }
2011
2012         *out_data = kmalloc(*plen, GFP_KERNEL);
2013         if (*out_data == NULL) {
2014                 rc = -ENOMEM;
2015                 goto ioctl_exit;
2016         }
2017
2018         shdr = get_sync_hdr(rsp);
2019         memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen);
2020 ioctl_exit:
2021         free_rsp_buf(resp_buftype, rsp);
2022         return rc;
2023 }
2024
2025 /*
2026  *   Individual callers to ioctl worker function follow
2027  */
2028
2029 int
2030 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
2031                      u64 persistent_fid, u64 volatile_fid)
2032 {
2033         int rc;
2034         struct  compress_ioctl fsctl_input;
2035         char *ret_data = NULL;
2036
2037         fsctl_input.CompressionState =
2038                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
2039
2040         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
2041                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
2042                         (char *)&fsctl_input /* data input */,
2043                         2 /* in data len */, &ret_data /* out data */, NULL);
2044
2045         cifs_dbg(FYI, "set compression rc %d\n", rc);
2046
2047         return rc;
2048 }
2049
2050 int
2051 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
2052            u64 persistent_fid, u64 volatile_fid)
2053 {
2054         struct smb2_close_req *req;
2055         struct smb2_close_rsp *rsp;
2056         struct cifs_ses *ses = tcon->ses;
2057         struct kvec iov[1];
2058         struct kvec rsp_iov;
2059         int resp_buftype;
2060         int rc = 0;
2061         int flags = 0;
2062         unsigned int total_len;
2063
2064         cifs_dbg(FYI, "Close\n");
2065
2066         if (!ses || !(ses->server))
2067                 return -EIO;
2068
2069         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, (void **) &req, &total_len);
2070         if (rc)
2071                 return rc;
2072
2073         if (encryption_required(tcon))
2074                 flags |= CIFS_TRANSFORM_REQ;
2075
2076         req->PersistentFileId = persistent_fid;
2077         req->VolatileFileId = volatile_fid;
2078
2079         iov[0].iov_base = (char *)req;
2080         iov[0].iov_len = total_len;
2081
2082         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2083         cifs_small_buf_release(req);
2084         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
2085
2086         if (rc != 0) {
2087                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
2088                 goto close_exit;
2089         }
2090
2091         /* BB FIXME - decode close response, update inode for caching */
2092
2093 close_exit:
2094         free_rsp_buf(resp_buftype, rsp);
2095         return rc;
2096 }
2097
2098 static int
2099 validate_buf(unsigned int offset, unsigned int buffer_length,
2100              struct smb2_hdr *hdr, unsigned int min_buf_size)
2101
2102 {
2103         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
2104         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
2105         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2106         char *end_of_buf = begin_of_buf + buffer_length;
2107
2108
2109         if (buffer_length < min_buf_size) {
2110                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
2111                          buffer_length, min_buf_size);
2112                 return -EINVAL;
2113         }
2114
2115         /* check if beyond RFC1001 maximum length */
2116         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
2117                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
2118                          buffer_length, smb_len);
2119                 return -EINVAL;
2120         }
2121
2122         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
2123                 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
2124                 return -EINVAL;
2125         }
2126
2127         return 0;
2128 }
2129
2130 /*
2131  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
2132  * Caller must free buffer.
2133  */
2134 static int
2135 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
2136                       struct smb2_hdr *hdr, unsigned int minbufsize,
2137                       char *data)
2138
2139 {
2140         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2141         int rc;
2142
2143         if (!data)
2144                 return -EINVAL;
2145
2146         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
2147         if (rc)
2148                 return rc;
2149
2150         memcpy(data, begin_of_buf, buffer_length);
2151
2152         return 0;
2153 }
2154
2155 static int
2156 query_info(const unsigned int xid, struct cifs_tcon *tcon,
2157            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
2158            u32 additional_info, size_t output_len, size_t min_len, void **data,
2159                 u32 *dlen)
2160 {
2161         struct smb2_query_info_req *req;
2162         struct smb2_query_info_rsp *rsp = NULL;
2163         struct kvec iov[2];
2164         struct kvec rsp_iov;
2165         int rc = 0;
2166         int resp_buftype;
2167         struct cifs_ses *ses = tcon->ses;
2168         int flags = 0;
2169         unsigned int total_len;
2170
2171         cifs_dbg(FYI, "Query Info\n");
2172
2173         if (!ses || !(ses->server))
2174                 return -EIO;
2175
2176         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
2177                              &total_len);
2178         if (rc)
2179                 return rc;
2180
2181         if (encryption_required(tcon))
2182                 flags |= CIFS_TRANSFORM_REQ;
2183
2184         req->InfoType = info_type;
2185         req->FileInfoClass = info_class;
2186         req->PersistentFileId = persistent_fid;
2187         req->VolatileFileId = volatile_fid;
2188         req->AdditionalInformation = cpu_to_le32(additional_info);
2189
2190         /*
2191          * We do not use the input buffer (do not send extra byte)
2192          */
2193         req->InputBufferOffset = 0;
2194
2195         req->OutputBufferLength = cpu_to_le32(output_len);
2196
2197         iov[0].iov_base = (char *)req;
2198         /* 1 for Buffer */
2199         iov[0].iov_len = total_len - 1;
2200
2201         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2202         cifs_small_buf_release(req);
2203         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2204
2205         if (rc) {
2206                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2207                 goto qinf_exit;
2208         }
2209
2210         if (dlen) {
2211                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
2212                 if (!*data) {
2213                         *data = kmalloc(*dlen, GFP_KERNEL);
2214                         if (!*data) {
2215                                 cifs_dbg(VFS,
2216                                         "Error %d allocating memory for acl\n",
2217                                         rc);
2218                                 *dlen = 0;
2219                                 goto qinf_exit;
2220                         }
2221                 }
2222         }
2223
2224         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
2225                                    le32_to_cpu(rsp->OutputBufferLength),
2226                                    &rsp->hdr, min_len, *data);
2227
2228 qinf_exit:
2229         free_rsp_buf(resp_buftype, rsp);
2230         return rc;
2231 }
2232
2233 int SMB2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
2234                    u64 persistent_fid, u64 volatile_fid,
2235                    int ea_buf_size, struct smb2_file_full_ea_info *data)
2236 {
2237         return query_info(xid, tcon, persistent_fid, volatile_fid,
2238                           FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0,
2239                           ea_buf_size,
2240                           sizeof(struct smb2_file_full_ea_info),
2241                           (void **)&data,
2242                           NULL);
2243 }
2244
2245 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
2246         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
2247 {
2248         return query_info(xid, tcon, persistent_fid, volatile_fid,
2249                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
2250                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
2251                           sizeof(struct smb2_file_all_info), (void **)&data,
2252                           NULL);
2253 }
2254
2255 int
2256 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
2257                 u64 persistent_fid, u64 volatile_fid,
2258                 void **data, u32 *plen)
2259 {
2260         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO;
2261         *plen = 0;
2262
2263         return query_info(xid, tcon, persistent_fid, volatile_fid,
2264                           0, SMB2_O_INFO_SECURITY, additional_info,
2265                           SMB2_MAX_BUFFER_SIZE,
2266                           sizeof(struct smb2_file_all_info), data, plen);
2267 }
2268
2269 int
2270 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
2271                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
2272 {
2273         return query_info(xid, tcon, persistent_fid, volatile_fid,
2274                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
2275                           sizeof(struct smb2_file_internal_info),
2276                           sizeof(struct smb2_file_internal_info),
2277                           (void **)&uniqueid, NULL);
2278 }
2279
2280 /*
2281  * This is a no-op for now. We're not really interested in the reply, but
2282  * rather in the fact that the server sent one and that server->lstrp
2283  * gets updated.
2284  *
2285  * FIXME: maybe we should consider checking that the reply matches request?
2286  */
2287 static void
2288 smb2_echo_callback(struct mid_q_entry *mid)
2289 {
2290         struct TCP_Server_Info *server = mid->callback_data;
2291         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
2292         unsigned int credits_received = 1;
2293
2294         if (mid->mid_state == MID_RESPONSE_RECEIVED)
2295                 credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2296
2297         DeleteMidQEntry(mid);
2298         add_credits(server, credits_received, CIFS_ECHO_OP);
2299 }
2300
2301 void smb2_reconnect_server(struct work_struct *work)
2302 {
2303         struct TCP_Server_Info *server = container_of(work,
2304                                         struct TCP_Server_Info, reconnect.work);
2305         struct cifs_ses *ses;
2306         struct cifs_tcon *tcon, *tcon2;
2307         struct list_head tmp_list;
2308         int tcon_exist = false;
2309         int rc;
2310         int resched = false;
2311
2312
2313         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
2314         mutex_lock(&server->reconnect_mutex);
2315
2316         INIT_LIST_HEAD(&tmp_list);
2317         cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
2318
2319         spin_lock(&cifs_tcp_ses_lock);
2320         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2321                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2322                         if (tcon->need_reconnect || tcon->need_reopen_files) {
2323                                 tcon->tc_count++;
2324                                 list_add_tail(&tcon->rlist, &tmp_list);
2325                                 tcon_exist = true;
2326                         }
2327                 }
2328                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
2329                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
2330                         tcon_exist = true;
2331                 }
2332         }
2333         /*
2334          * Get the reference to server struct to be sure that the last call of
2335          * cifs_put_tcon() in the loop below won't release the server pointer.
2336          */
2337         if (tcon_exist)
2338                 server->srv_count++;
2339
2340         spin_unlock(&cifs_tcp_ses_lock);
2341
2342         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
2343                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon);
2344                 if (!rc)
2345                         cifs_reopen_persistent_handles(tcon);
2346                 else
2347                         resched = true;
2348                 list_del_init(&tcon->rlist);
2349                 cifs_put_tcon(tcon);
2350         }
2351
2352         cifs_dbg(FYI, "Reconnecting tcons finished\n");
2353         if (resched)
2354                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
2355         mutex_unlock(&server->reconnect_mutex);
2356
2357         /* now we can safely release srv struct */
2358         if (tcon_exist)
2359                 cifs_put_tcp_session(server, 1);
2360 }
2361
2362 int
2363 SMB2_echo(struct TCP_Server_Info *server)
2364 {
2365         struct smb2_echo_req *req;
2366         int rc = 0;
2367         struct kvec iov[2];
2368         struct smb_rqst rqst = { .rq_iov = iov,
2369                                  .rq_nvec = 2 };
2370         unsigned int total_len;
2371         __be32 rfc1002_marker;
2372
2373         cifs_dbg(FYI, "In echo request\n");
2374
2375         if (server->tcpStatus == CifsNeedNegotiate) {
2376                 /* No need to send echo on newly established connections */
2377                 queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
2378                 return rc;
2379         }
2380
2381         rc = smb2_plain_req_init(SMB2_ECHO, NULL, (void **)&req, &total_len);
2382         if (rc)
2383                 return rc;
2384
2385         req->sync_hdr.CreditRequest = cpu_to_le16(1);
2386
2387         iov[0].iov_len = 4;
2388         rfc1002_marker = cpu_to_be32(total_len);
2389         iov[0].iov_base = &rfc1002_marker;
2390         iov[1].iov_len = total_len;
2391         iov[1].iov_base = (char *)req;
2392
2393         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
2394                              server, CIFS_ECHO_OP);
2395         if (rc)
2396                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
2397
2398         cifs_small_buf_release(req);
2399         return rc;
2400 }
2401
2402 int
2403 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2404            u64 volatile_fid)
2405 {
2406         struct smb2_flush_req *req;
2407         struct cifs_ses *ses = tcon->ses;
2408         struct kvec iov[1];
2409         struct kvec rsp_iov;
2410         int resp_buftype;
2411         int rc = 0;
2412         int flags = 0;
2413         unsigned int total_len;
2414
2415         cifs_dbg(FYI, "Flush\n");
2416
2417         if (!ses || !(ses->server))
2418                 return -EIO;
2419
2420         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, (void **) &req, &total_len);
2421         if (rc)
2422                 return rc;
2423
2424         if (encryption_required(tcon))
2425                 flags |= CIFS_TRANSFORM_REQ;
2426
2427         req->PersistentFileId = persistent_fid;
2428         req->VolatileFileId = volatile_fid;
2429
2430         iov[0].iov_base = (char *)req;
2431         iov[0].iov_len = total_len;
2432
2433         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2434         cifs_small_buf_release(req);
2435
2436         if (rc != 0)
2437                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
2438
2439         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2440         return rc;
2441 }
2442
2443 /*
2444  * To form a chain of read requests, any read requests after the first should
2445  * have the end_of_chain boolean set to true.
2446  */
2447 static int
2448 smb2_new_read_req(void **buf, unsigned int *total_len,
2449         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
2450         unsigned int remaining_bytes, int request_type)
2451 {
2452         int rc = -EACCES;
2453         struct smb2_read_plain_req *req = NULL;
2454         struct smb2_sync_hdr *shdr;
2455         struct TCP_Server_Info *server;
2456
2457         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
2458                                  total_len);
2459         if (rc)
2460                 return rc;
2461
2462         server = io_parms->tcon->ses->server;
2463         if (server == NULL)
2464                 return -ECONNABORTED;
2465
2466         shdr = &req->sync_hdr;
2467         shdr->ProcessId = cpu_to_le32(io_parms->pid);
2468
2469         req->PersistentFileId = io_parms->persistent_fid;
2470         req->VolatileFileId = io_parms->volatile_fid;
2471         req->ReadChannelInfoOffset = 0; /* reserved */
2472         req->ReadChannelInfoLength = 0; /* reserved */
2473         req->Channel = 0; /* reserved */
2474         req->MinimumCount = 0;
2475         req->Length = cpu_to_le32(io_parms->length);
2476         req->Offset = cpu_to_le64(io_parms->offset);
2477 #ifdef CONFIG_CIFS_SMB_DIRECT
2478         /*
2479          * If we want to do a RDMA write, fill in and append
2480          * smbd_buffer_descriptor_v1 to the end of read request
2481          */
2482         if (server->rdma && rdata &&
2483                 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
2484
2485                 struct smbd_buffer_descriptor_v1 *v1;
2486                 bool need_invalidate =
2487                         io_parms->tcon->ses->server->dialect == SMB30_PROT_ID;
2488
2489                 rdata->mr = smbd_register_mr(
2490                                 server->smbd_conn, rdata->pages,
2491                                 rdata->nr_pages, rdata->tailsz,
2492                                 true, need_invalidate);
2493                 if (!rdata->mr)
2494                         return -ENOBUFS;
2495
2496                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
2497                 if (need_invalidate)
2498                         req->Channel = SMB2_CHANNEL_RDMA_V1;
2499                 req->ReadChannelInfoOffset =
2500                         cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer));
2501                 req->ReadChannelInfoLength =
2502                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
2503                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
2504                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
2505                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
2506                 v1->length = cpu_to_le32(rdata->mr->mr->length);
2507
2508                 *total_len += sizeof(*v1) - 1;
2509         }
2510 #endif
2511         if (request_type & CHAINED_REQUEST) {
2512                 if (!(request_type & END_OF_CHAIN)) {
2513                         /* next 8-byte aligned request */
2514                         *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
2515                         shdr->NextCommand = cpu_to_le32(*total_len);
2516                 } else /* END_OF_CHAIN */
2517                         shdr->NextCommand = 0;
2518                 if (request_type & RELATED_REQUEST) {
2519                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2520                         /*
2521                          * Related requests use info from previous read request
2522                          * in chain.
2523                          */
2524                         shdr->SessionId = 0xFFFFFFFF;
2525                         shdr->TreeId = 0xFFFFFFFF;
2526                         req->PersistentFileId = 0xFFFFFFFF;
2527                         req->VolatileFileId = 0xFFFFFFFF;
2528                 }
2529         }
2530         if (remaining_bytes > io_parms->length)
2531                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
2532         else
2533                 req->RemainingBytes = 0;
2534
2535         *buf = req;
2536         return rc;
2537 }
2538
2539 static void
2540 smb2_readv_callback(struct mid_q_entry *mid)
2541 {
2542         struct cifs_readdata *rdata = mid->callback_data;
2543         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
2544         struct TCP_Server_Info *server = tcon->ses->server;
2545         struct smb2_sync_hdr *shdr =
2546                                 (struct smb2_sync_hdr *)rdata->iov[1].iov_base;
2547         unsigned int credits_received = 1;
2548         struct smb_rqst rqst = { .rq_iov = rdata->iov,
2549                                  .rq_nvec = 2,
2550                                  .rq_pages = rdata->pages,
2551                                  .rq_npages = rdata->nr_pages,
2552                                  .rq_pagesz = rdata->pagesz,
2553                                  .rq_tailsz = rdata->tailsz };
2554
2555         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
2556                  __func__, mid->mid, mid->mid_state, rdata->result,
2557                  rdata->bytes);
2558
2559         switch (mid->mid_state) {
2560         case MID_RESPONSE_RECEIVED:
2561                 credits_received = le16_to_cpu(shdr->CreditRequest);
2562                 /* result already set, check signature */
2563                 if (server->sign && !mid->decrypted) {
2564                         int rc;
2565
2566                         rc = smb2_verify_signature(&rqst, server);
2567                         if (rc)
2568                                 cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
2569                                          rc);
2570                 }
2571                 /* FIXME: should this be counted toward the initiating task? */
2572                 task_io_account_read(rdata->got_bytes);
2573                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2574                 break;
2575         case MID_REQUEST_SUBMITTED:
2576         case MID_RETRY_NEEDED:
2577                 rdata->result = -EAGAIN;
2578                 if (server->sign && rdata->got_bytes)
2579                         /* reset bytes number since we can not check a sign */
2580                         rdata->got_bytes = 0;
2581                 /* FIXME: should this be counted toward the initiating task? */
2582                 task_io_account_read(rdata->got_bytes);
2583                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2584                 break;
2585         default:
2586                 if (rdata->result != -ENODATA)
2587                         rdata->result = -EIO;
2588         }
2589 #ifdef CONFIG_CIFS_SMB_DIRECT
2590         /*
2591          * If this rdata has a memmory registered, the MR can be freed
2592          * MR needs to be freed as soon as I/O finishes to prevent deadlock
2593          * because they have limited number and are used for future I/Os
2594          */
2595         if (rdata->mr) {
2596                 smbd_deregister_mr(rdata->mr);
2597                 rdata->mr = NULL;
2598         }
2599 #endif
2600         if (rdata->result)
2601                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
2602
2603         queue_work(cifsiod_wq, &rdata->work);
2604         DeleteMidQEntry(mid);
2605         add_credits(server, credits_received, 0);
2606 }
2607
2608 /* smb2_async_readv - send an async read, and set up mid to handle result */
2609 int
2610 smb2_async_readv(struct cifs_readdata *rdata)
2611 {
2612         int rc, flags = 0;
2613         char *buf;
2614         struct smb2_sync_hdr *shdr;
2615         struct cifs_io_parms io_parms;
2616         struct smb_rqst rqst = { .rq_iov = rdata->iov,
2617                                  .rq_nvec = 2 };
2618         struct TCP_Server_Info *server;
2619         unsigned int total_len;
2620         __be32 req_len;
2621
2622         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
2623                  __func__, rdata->offset, rdata->bytes);
2624
2625         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
2626         io_parms.offset = rdata->offset;
2627         io_parms.length = rdata->bytes;
2628         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
2629         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
2630         io_parms.pid = rdata->pid;
2631
2632         server = io_parms.tcon->ses->server;
2633
2634         rc = smb2_new_read_req(
2635                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
2636         if (rc) {
2637                 if (rc == -EAGAIN && rdata->credits) {
2638                         /* credits was reset by reconnect */
2639                         rdata->credits = 0;
2640                         /* reduce in_flight value since we won't send the req */
2641                         spin_lock(&server->req_lock);
2642                         server->in_flight--;
2643                         spin_unlock(&server->req_lock);
2644                 }
2645                 return rc;
2646         }
2647
2648         if (encryption_required(io_parms.tcon))
2649                 flags |= CIFS_TRANSFORM_REQ;
2650
2651         req_len = cpu_to_be32(total_len);
2652
2653         rdata->iov[0].iov_base = &req_len;
2654         rdata->iov[0].iov_len = sizeof(__be32);
2655         rdata->iov[1].iov_base = buf;
2656         rdata->iov[1].iov_len = total_len;
2657
2658         shdr = (struct smb2_sync_hdr *)buf;
2659
2660         if (rdata->credits) {
2661                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
2662                                                 SMB2_MAX_BUFFER_SIZE));
2663                 shdr->CreditRequest = shdr->CreditCharge;
2664                 spin_lock(&server->req_lock);
2665                 server->credits += rdata->credits -
2666                                                 le16_to_cpu(shdr->CreditCharge);
2667                 spin_unlock(&server->req_lock);
2668                 wake_up(&server->request_q);
2669                 flags |= CIFS_HAS_CREDITS;
2670         }
2671
2672         kref_get(&rdata->refcount);
2673         rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
2674                              cifs_readv_receive, smb2_readv_callback,
2675                              smb3_handle_read_data, rdata, flags);
2676         if (rc) {
2677                 kref_put(&rdata->refcount, cifs_readdata_release);
2678                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
2679         }
2680
2681         cifs_small_buf_release(buf);
2682         return rc;
2683 }
2684
2685 int
2686 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
2687           unsigned int *nbytes, char **buf, int *buf_type)
2688 {
2689         int resp_buftype, rc = -EACCES;
2690         struct smb2_read_plain_req *req = NULL;
2691         struct smb2_read_rsp *rsp = NULL;
2692         struct smb2_sync_hdr *shdr;
2693         struct kvec iov[1];
2694         struct kvec rsp_iov;
2695         unsigned int total_len;
2696         int flags = CIFS_LOG_ERROR;
2697         struct cifs_ses *ses = io_parms->tcon->ses;
2698
2699         *nbytes = 0;
2700         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
2701         if (rc)
2702                 return rc;
2703
2704         if (encryption_required(io_parms->tcon))
2705                 flags |= CIFS_TRANSFORM_REQ;
2706
2707         iov[0].iov_base = (char *)req;
2708         iov[0].iov_len = total_len;
2709
2710         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2711         cifs_small_buf_release(req);
2712
2713         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
2714
2715         if (rc) {
2716                 if (rc != -ENODATA) {
2717                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
2718                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
2719                 }
2720                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2721                 return rc == -ENODATA ? 0 : rc;
2722         }
2723
2724         *nbytes = le32_to_cpu(rsp->DataLength);
2725         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
2726             (*nbytes > io_parms->length)) {
2727                 cifs_dbg(FYI, "bad length %d for count %d\n",
2728                          *nbytes, io_parms->length);
2729                 rc = -EIO;
2730                 *nbytes = 0;
2731         }
2732
2733         shdr = get_sync_hdr(rsp);
2734
2735         if (*buf) {
2736                 memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes);
2737                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2738         } else if (resp_buftype != CIFS_NO_BUFFER) {
2739                 *buf = rsp_iov.iov_base;
2740                 if (resp_buftype == CIFS_SMALL_BUFFER)
2741                         *buf_type = CIFS_SMALL_BUFFER;
2742                 else if (resp_buftype == CIFS_LARGE_BUFFER)
2743                         *buf_type = CIFS_LARGE_BUFFER;
2744         }
2745         return rc;
2746 }
2747
2748 /*
2749  * Check the mid_state and signature on received buffer (if any), and queue the
2750  * workqueue completion task.
2751  */
2752 static void
2753 smb2_writev_callback(struct mid_q_entry *mid)
2754 {
2755         struct cifs_writedata *wdata = mid->callback_data;
2756         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2757         unsigned int written;
2758         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
2759         unsigned int credits_received = 1;
2760
2761         switch (mid->mid_state) {
2762         case MID_RESPONSE_RECEIVED:
2763                 credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2764                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
2765                 if (wdata->result != 0)
2766                         break;
2767
2768                 written = le32_to_cpu(rsp->DataLength);
2769                 /*
2770                  * Mask off high 16 bits when bytes written as returned
2771                  * by the server is greater than bytes requested by the
2772                  * client. OS/2 servers are known to set incorrect
2773                  * CountHigh values.
2774                  */
2775                 if (written > wdata->bytes)
2776                         written &= 0xFFFF;
2777
2778                 if (written < wdata->bytes)
2779                         wdata->result = -ENOSPC;
2780                 else
2781                         wdata->bytes = written;
2782                 break;
2783         case MID_REQUEST_SUBMITTED:
2784         case MID_RETRY_NEEDED:
2785                 wdata->result = -EAGAIN;
2786                 break;
2787         default:
2788                 wdata->result = -EIO;
2789                 break;
2790         }
2791 #ifdef CONFIG_CIFS_SMB_DIRECT
2792         /*
2793          * If this wdata has a memory registered, the MR can be freed
2794          * The number of MRs available is limited, it's important to recover
2795          * used MR as soon as I/O is finished. Hold MR longer in the later
2796          * I/O process can possibly result in I/O deadlock due to lack of MR
2797          * to send request on I/O retry
2798          */
2799         if (wdata->mr) {
2800                 smbd_deregister_mr(wdata->mr);
2801                 wdata->mr = NULL;
2802         }
2803 #endif
2804         if (wdata->result)
2805                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2806
2807         queue_work(cifsiod_wq, &wdata->work);
2808         DeleteMidQEntry(mid);
2809         add_credits(tcon->ses->server, credits_received, 0);
2810 }
2811
2812 /* smb2_async_writev - send an async write, and set up mid to handle result */
2813 int
2814 smb2_async_writev(struct cifs_writedata *wdata,
2815                   void (*release)(struct kref *kref))
2816 {
2817         int rc = -EACCES, flags = 0;
2818         struct smb2_write_req *req = NULL;
2819         struct smb2_sync_hdr *shdr;
2820         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2821         struct TCP_Server_Info *server = tcon->ses->server;
2822         struct kvec iov[2];
2823         struct smb_rqst rqst = { };
2824         unsigned int total_len;
2825         __be32 rfc1002_marker;
2826
2827         rc = smb2_plain_req_init(SMB2_WRITE, tcon, (void **) &req, &total_len);
2828         if (rc) {
2829                 if (rc == -EAGAIN && wdata->credits) {
2830                         /* credits was reset by reconnect */
2831                         wdata->credits = 0;
2832                         /* reduce in_flight value since we won't send the req */
2833                         spin_lock(&server->req_lock);
2834                         server->in_flight--;
2835                         spin_unlock(&server->req_lock);
2836                 }
2837                 goto async_writev_out;
2838         }
2839
2840         if (encryption_required(tcon))
2841                 flags |= CIFS_TRANSFORM_REQ;
2842
2843         shdr = (struct smb2_sync_hdr *)req;
2844         shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
2845
2846         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
2847         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
2848         req->WriteChannelInfoOffset = 0;
2849         req->WriteChannelInfoLength = 0;
2850         req->Channel = 0;
2851         req->Offset = cpu_to_le64(wdata->offset);
2852         req->DataOffset = cpu_to_le16(
2853                                 offsetof(struct smb2_write_req, Buffer));
2854         req->RemainingBytes = 0;
2855 #ifdef CONFIG_CIFS_SMB_DIRECT
2856         /*
2857          * If we want to do a server RDMA read, fill in and append
2858          * smbd_buffer_descriptor_v1 to the end of write request
2859          */
2860         if (server->rdma && wdata->bytes >=
2861                 server->smbd_conn->rdma_readwrite_threshold) {
2862
2863                 struct smbd_buffer_descriptor_v1 *v1;
2864                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
2865
2866                 wdata->mr = smbd_register_mr(
2867                                 server->smbd_conn, wdata->pages,
2868                                 wdata->nr_pages, wdata->tailsz,
2869                                 false, need_invalidate);
2870                 if (!wdata->mr) {
2871                         rc = -ENOBUFS;
2872                         goto async_writev_out;
2873                 }
2874                 req->Length = 0;
2875                 req->DataOffset = 0;
2876                 req->RemainingBytes =
2877                         cpu_to_le32((wdata->nr_pages-1)*PAGE_SIZE + wdata->tailsz);
2878                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
2879                 if (need_invalidate)
2880                         req->Channel = SMB2_CHANNEL_RDMA_V1;
2881                 req->WriteChannelInfoOffset =
2882                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
2883                 req->WriteChannelInfoLength =
2884                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
2885                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
2886                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
2887                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
2888                 v1->length = cpu_to_le32(wdata->mr->mr->length);
2889         }
2890 #endif
2891         /* 4 for rfc1002 length field and 1 for Buffer */
2892         iov[0].iov_len = 4;
2893         rfc1002_marker = cpu_to_be32(total_len - 1 + wdata->bytes);
2894         iov[0].iov_base = &rfc1002_marker;
2895         iov[1].iov_len = total_len - 1;
2896         iov[1].iov_base = (char *)req;
2897
2898         rqst.rq_iov = iov;
2899         rqst.rq_nvec = 2;
2900         rqst.rq_pages = wdata->pages;
2901         rqst.rq_npages = wdata->nr_pages;
2902         rqst.rq_pagesz = wdata->pagesz;
2903         rqst.rq_tailsz = wdata->tailsz;
2904 #ifdef CONFIG_CIFS_SMB_DIRECT
2905         if (wdata->mr) {
2906                 iov[1].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
2907                 rqst.rq_npages = 0;
2908         }
2909 #endif
2910         cifs_dbg(FYI, "async write at %llu %u bytes\n",
2911                  wdata->offset, wdata->bytes);
2912
2913 #ifdef CONFIG_CIFS_SMB_DIRECT
2914         /* For RDMA read, I/O size is in RemainingBytes not in Length */
2915         if (!wdata->mr)
2916                 req->Length = cpu_to_le32(wdata->bytes);
2917 #else
2918         req->Length = cpu_to_le32(wdata->bytes);
2919 #endif
2920
2921         if (wdata->credits) {
2922                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
2923                                                     SMB2_MAX_BUFFER_SIZE));
2924                 shdr->CreditRequest = shdr->CreditCharge;
2925                 spin_lock(&server->req_lock);
2926                 server->credits += wdata->credits -
2927                                                 le16_to_cpu(shdr->CreditCharge);
2928                 spin_unlock(&server->req_lock);
2929                 wake_up(&server->request_q);
2930                 flags |= CIFS_HAS_CREDITS;
2931         }
2932
2933         kref_get(&wdata->refcount);
2934         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
2935                              wdata, flags);
2936
2937         if (rc) {
2938                 kref_put(&wdata->refcount, release);
2939                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2940         }
2941
2942 async_writev_out:
2943         cifs_small_buf_release(req);
2944         return rc;
2945 }
2946
2947 /*
2948  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
2949  * The length field from io_parms must be at least 1 and indicates a number of
2950  * elements with data to write that begins with position 1 in iov array. All
2951  * data length is specified by count.
2952  */
2953 int
2954 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
2955            unsigned int *nbytes, struct kvec *iov, int n_vec)
2956 {
2957         int rc = 0;
2958         struct smb2_write_req *req = NULL;
2959         struct smb2_write_rsp *rsp = NULL;
2960         int resp_buftype;
2961         struct kvec rsp_iov;
2962         int flags = 0;
2963         unsigned int total_len;
2964
2965         *nbytes = 0;
2966
2967         if (n_vec < 1)
2968                 return rc;
2969
2970         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,
2971                              &total_len);
2972         if (rc)
2973                 return rc;
2974
2975         if (io_parms->tcon->ses->server == NULL)
2976                 return -ECONNABORTED;
2977
2978         if (encryption_required(io_parms->tcon))
2979                 flags |= CIFS_TRANSFORM_REQ;
2980
2981         req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
2982
2983         req->PersistentFileId = io_parms->persistent_fid;
2984         req->VolatileFileId = io_parms->volatile_fid;
2985         req->WriteChannelInfoOffset = 0;
2986         req->WriteChannelInfoLength = 0;
2987         req->Channel = 0;
2988         req->Length = cpu_to_le32(io_parms->length);
2989         req->Offset = cpu_to_le64(io_parms->offset);
2990         req->DataOffset = cpu_to_le16(
2991                                 offsetof(struct smb2_write_req, Buffer));
2992         req->RemainingBytes = 0;
2993
2994         iov[0].iov_base = (char *)req;
2995         /* 1 for Buffer */
2996         iov[0].iov_len = total_len - 1;
2997
2998         rc = smb2_send_recv(xid, io_parms->tcon->ses, iov, n_vec + 1,
2999                             &resp_buftype, flags, &rsp_iov);
3000         cifs_small_buf_release(req);
3001         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
3002
3003         if (rc) {
3004                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
3005                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
3006         } else
3007                 *nbytes = le32_to_cpu(rsp->DataLength);
3008
3009         free_rsp_buf(resp_buftype, rsp);
3010         return rc;
3011 }
3012
3013 static unsigned int
3014 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
3015 {
3016         int len;
3017         unsigned int entrycount = 0;
3018         unsigned int next_offset = 0;
3019         FILE_DIRECTORY_INFO *entryptr;
3020
3021         if (bufstart == NULL)
3022                 return 0;
3023
3024         entryptr = (FILE_DIRECTORY_INFO *)bufstart;
3025
3026         while (1) {
3027                 entryptr = (FILE_DIRECTORY_INFO *)
3028                                         ((char *)entryptr + next_offset);
3029
3030                 if ((char *)entryptr + size > end_of_buf) {
3031                         cifs_dbg(VFS, "malformed search entry would overflow\n");
3032                         break;
3033                 }
3034
3035                 len = le32_to_cpu(entryptr->FileNameLength);
3036                 if ((char *)entryptr + len + size > end_of_buf) {
3037                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
3038                                  end_of_buf);
3039                         break;
3040                 }
3041
3042                 *lastentry = (char *)entryptr;
3043                 entrycount++;
3044
3045                 next_offset = le32_to_cpu(entryptr->NextEntryOffset);
3046                 if (!next_offset)
3047                         break;
3048         }
3049
3050         return entrycount;
3051 }
3052
3053 /*
3054  * Readdir/FindFirst
3055  */
3056 int
3057 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
3058                      u64 persistent_fid, u64 volatile_fid, int index,
3059                      struct cifs_search_info *srch_inf)
3060 {
3061         struct smb2_query_directory_req *req;
3062         struct smb2_query_directory_rsp *rsp = NULL;
3063         struct kvec iov[2];
3064         struct kvec rsp_iov;
3065         int rc = 0;
3066         int len;
3067         int resp_buftype = CIFS_NO_BUFFER;
3068         unsigned char *bufptr;
3069         struct TCP_Server_Info *server;
3070         struct cifs_ses *ses = tcon->ses;
3071         __le16 asteriks = cpu_to_le16('*');
3072         char *end_of_smb;
3073         unsigned int output_size = CIFSMaxBufSize;
3074         size_t info_buf_size;
3075         int flags = 0;
3076         unsigned int total_len;
3077
3078         if (ses && (ses->server))
3079                 server = ses->server;
3080         else
3081                 return -EIO;
3082
3083         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req,
3084                              &total_len);
3085         if (rc)
3086                 return rc;
3087
3088         if (encryption_required(tcon))
3089                 flags |= CIFS_TRANSFORM_REQ;
3090
3091         switch (srch_inf->info_level) {
3092         case SMB_FIND_FILE_DIRECTORY_INFO:
3093                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
3094                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
3095                 break;
3096         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
3097                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
3098                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
3099                 break;
3100         default:
3101                 cifs_dbg(VFS, "info level %u isn't supported\n",
3102                          srch_inf->info_level);
3103                 rc = -EINVAL;
3104                 goto qdir_exit;
3105         }
3106
3107         req->FileIndex = cpu_to_le32(index);
3108         req->PersistentFileId = persistent_fid;
3109         req->VolatileFileId = volatile_fid;
3110
3111         len = 0x2;
3112         bufptr = req->Buffer;
3113         memcpy(bufptr, &asteriks, len);
3114
3115         req->FileNameOffset =
3116                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
3117         req->FileNameLength = cpu_to_le16(len);
3118         /*
3119          * BB could be 30 bytes or so longer if we used SMB2 specific
3120          * buffer lengths, but this is safe and close enough.
3121          */
3122         output_size = min_t(unsigned int, output_size, server->maxBuf);
3123         output_size = min_t(unsigned int, output_size, 2 << 15);
3124         req->OutputBufferLength = cpu_to_le32(output_size);
3125
3126         iov[0].iov_base = (char *)req;
3127         /* 1 for Buffer */
3128         iov[0].iov_len = total_len - 1;
3129
3130         iov[1].iov_base = (char *)(req->Buffer);
3131         iov[1].iov_len = len;
3132
3133         rc = smb2_send_recv(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
3134         cifs_small_buf_release(req);
3135         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
3136
3137         if (rc) {
3138                 if (rc == -ENODATA &&
3139                     rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) {
3140                         srch_inf->endOfSearch = true;
3141                         rc = 0;
3142                 }
3143                 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
3144                 goto qdir_exit;
3145         }
3146
3147         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
3148                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
3149                           info_buf_size);
3150         if (rc)
3151                 goto qdir_exit;
3152
3153         srch_inf->unicode = true;
3154
3155         if (srch_inf->ntwrk_buf_start) {
3156                 if (srch_inf->smallBuf)
3157                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
3158                 else
3159                         cifs_buf_release(srch_inf->ntwrk_buf_start);
3160         }
3161         srch_inf->ntwrk_buf_start = (char *)rsp;
3162         srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
3163                 (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
3164         /* 4 for rfc1002 length field */
3165         end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
3166         srch_inf->entries_in_buffer =
3167                         num_entries(srch_inf->srch_entries_start, end_of_smb,
3168                                     &srch_inf->last_entry, info_buf_size);
3169         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
3170         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
3171                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
3172                  srch_inf->srch_entries_start, srch_inf->last_entry);
3173         if (resp_buftype == CIFS_LARGE_BUFFER)
3174                 srch_inf->smallBuf = false;
3175         else if (resp_buftype == CIFS_SMALL_BUFFER)
3176                 srch_inf->smallBuf = true;
3177         else
3178                 cifs_dbg(VFS, "illegal search buffer type\n");
3179
3180         return rc;
3181
3182 qdir_exit:
3183         free_rsp_buf(resp_buftype, rsp);
3184         return rc;
3185 }
3186
3187 static int
3188 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3189                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
3190                u8 info_type, u32 additional_info, unsigned int num,
3191                 void **data, unsigned int *size)
3192 {
3193         struct smb2_set_info_req *req;
3194         struct smb2_set_info_rsp *rsp = NULL;
3195         struct kvec *iov;
3196         struct kvec rsp_iov;
3197         int rc = 0;
3198         int resp_buftype;
3199         unsigned int i;
3200         struct cifs_ses *ses = tcon->ses;
3201         int flags = 0;
3202         unsigned int total_len;
3203
3204         if (!ses || !(ses->server))
3205                 return -EIO;
3206
3207         if (!num)
3208                 return -EINVAL;
3209
3210         iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
3211         if (!iov)
3212                 return -ENOMEM;
3213
3214         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, (void **) &req, &total_len);
3215         if (rc) {
3216                 kfree(iov);
3217                 return rc;
3218         }
3219
3220         if (encryption_required(tcon))
3221                 flags |= CIFS_TRANSFORM_REQ;
3222
3223         req->sync_hdr.ProcessId = cpu_to_le32(pid);
3224
3225         req->InfoType = info_type;
3226         req->FileInfoClass = info_class;
3227         req->PersistentFileId = persistent_fid;
3228         req->VolatileFileId = volatile_fid;
3229         req->AdditionalInformation = cpu_to_le32(additional_info);
3230
3231         req->BufferOffset =
3232                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
3233         req->BufferLength = cpu_to_le32(*size);
3234
3235         memcpy(req->Buffer, *data, *size);
3236         total_len += *size;
3237
3238         iov[0].iov_base = (char *)req;
3239         /* 1 for Buffer */
3240         iov[0].iov_len = total_len - 1;
3241
3242         for (i = 1; i < num; i++) {
3243                 le32_add_cpu(&req->BufferLength, size[i]);
3244                 iov[i].iov_base = (char *)data[i];
3245                 iov[i].iov_len = size[i];
3246         }
3247
3248         rc = smb2_send_recv(xid, ses, iov, num, &resp_buftype, flags,
3249                             &rsp_iov);
3250         cifs_small_buf_release(req);
3251         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
3252
3253         if (rc != 0)
3254                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
3255
3256         free_rsp_buf(resp_buftype, rsp);
3257         kfree(iov);
3258         return rc;
3259 }
3260
3261 int
3262 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
3263             u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3264 {
3265         struct smb2_file_rename_info info;
3266         void **data;
3267         unsigned int size[2];
3268         int rc;
3269         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3270
3271         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3272         if (!data)
3273                 return -ENOMEM;
3274
3275         info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
3276                               /* 0 = fail if target already exists */
3277         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3278         info.FileNameLength = cpu_to_le32(len);
3279
3280         data[0] = &info;
3281         size[0] = sizeof(struct smb2_file_rename_info);
3282
3283         data[1] = target_file;
3284         size[1] = len + 2 /* null */;
3285
3286         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3287                 current->tgid, FILE_RENAME_INFORMATION, SMB2_O_INFO_FILE,
3288                 0, 2, data, size);
3289         kfree(data);
3290         return rc;
3291 }
3292
3293 int
3294 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
3295                   u64 persistent_fid, u64 volatile_fid)
3296 {
3297         __u8 delete_pending = 1;
3298         void *data;
3299         unsigned int size;
3300
3301         data = &delete_pending;
3302         size = 1; /* sizeof __u8 */
3303
3304         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3305                 current->tgid, FILE_DISPOSITION_INFORMATION, SMB2_O_INFO_FILE,
3306                 0, 1, &data, &size);
3307 }
3308
3309 int
3310 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
3311                   u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3312 {
3313         struct smb2_file_link_info info;
3314         void **data;
3315         unsigned int size[2];
3316         int rc;
3317         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3318
3319         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3320         if (!data)
3321                 return -ENOMEM;
3322
3323         info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
3324                               /* 0 = fail if link already exists */
3325         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3326         info.FileNameLength = cpu_to_le32(len);
3327
3328         data[0] = &info;
3329         size[0] = sizeof(struct smb2_file_link_info);
3330
3331         data[1] = target_file;
3332         size[1] = len + 2 /* null */;
3333
3334         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3335                         current->tgid, FILE_LINK_INFORMATION, SMB2_O_INFO_FILE,
3336                         0, 2, data, size);
3337         kfree(data);
3338         return rc;
3339 }
3340
3341 int
3342 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3343              u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
3344 {
3345         struct smb2_file_eof_info info;
3346         void *data;
3347         unsigned int size;
3348
3349         info.EndOfFile = *eof;
3350
3351         data = &info;
3352         size = sizeof(struct smb2_file_eof_info);
3353
3354         if (is_falloc)
3355                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3356                         pid, FILE_ALLOCATION_INFORMATION, SMB2_O_INFO_FILE,
3357                         0, 1, &data, &size);
3358         else
3359                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3360                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
3361                         0, 1, &data, &size);
3362 }
3363
3364 int
3365 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3366               u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
3367 {
3368         unsigned int size;
3369         size = sizeof(FILE_BASIC_INFO);
3370         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3371                 current->tgid, FILE_BASIC_INFORMATION, SMB2_O_INFO_FILE,
3372                 0, 1, (void **)&buf, &size);
3373 }
3374
3375 int
3376 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
3377                 u64 persistent_fid, u64 volatile_fid,
3378                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
3379 {
3380         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3381                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
3382                         1, (void **)&pnntsd, &pacllen);
3383 }
3384
3385 int
3386 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
3387             u64 persistent_fid, u64 volatile_fid,
3388             struct smb2_file_full_ea_info *buf, int len)
3389 {
3390         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3391                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
3392                 0, 1, (void **)&buf, &len);
3393 }
3394
3395 int
3396 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
3397                   const u64 persistent_fid, const u64 volatile_fid,
3398                   __u8 oplock_level)
3399 {
3400         int rc;
3401         struct smb2_oplock_break_req *req = NULL;
3402         struct cifs_ses *ses = tcon->ses;
3403         int flags = CIFS_OBREAK_OP;
3404         unsigned int total_len;
3405         struct kvec iov[1];
3406         struct kvec rsp_iov;
3407         int resp_buf_type;
3408
3409         cifs_dbg(FYI, "SMB2_oplock_break\n");
3410         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
3411                              &total_len);
3412         if (rc)
3413                 return rc;
3414
3415         if (encryption_required(tcon))
3416                 flags |= CIFS_TRANSFORM_REQ;
3417
3418         req->VolatileFid = volatile_fid;
3419         req->PersistentFid = persistent_fid;
3420         req->OplockLevel = oplock_level;
3421         req->sync_hdr.CreditRequest = cpu_to_le16(1);
3422
3423         flags |= CIFS_NO_RESP;
3424
3425         iov[0].iov_base = (char *)req;
3426         iov[0].iov_len = total_len;
3427
3428         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buf_type, flags, &rsp_iov);
3429         cifs_small_buf_release(req);
3430
3431         if (rc) {
3432                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3433                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
3434         }
3435
3436         return rc;
3437 }
3438
3439 static void
3440 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
3441                         struct kstatfs *kst)
3442 {
3443         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
3444                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
3445         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
3446         kst->f_bfree  = kst->f_bavail =
3447                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
3448         return;
3449 }
3450
3451 static int
3452 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
3453                    int outbuf_len, u64 persistent_fid, u64 volatile_fid)
3454 {
3455         int rc;
3456         struct smb2_query_info_req *req;
3457         unsigned int total_len;
3458
3459         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
3460
3461         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
3462                 return -EIO;
3463
3464         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
3465                              &total_len);
3466         if (rc)
3467                 return rc;
3468
3469         req->InfoType = SMB2_O_INFO_FILESYSTEM;
3470         req->FileInfoClass = level;
3471         req->PersistentFileId = persistent_fid;
3472         req->VolatileFileId = volatile_fid;
3473         /* 1 for pad */
3474         req->InputBufferOffset =
3475                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
3476         req->OutputBufferLength = cpu_to_le32(
3477                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
3478
3479         iov->iov_base = (char *)req;
3480         iov->iov_len = total_len;
3481         return 0;
3482 }
3483
3484 int
3485 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
3486               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
3487 {
3488         struct smb2_query_info_rsp *rsp = NULL;
3489         struct kvec iov;
3490         struct kvec rsp_iov;
3491         int rc = 0;
3492         int resp_buftype;
3493         struct cifs_ses *ses = tcon->ses;
3494         struct smb2_fs_full_size_info *info = NULL;
3495         int flags = 0;
3496
3497         rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
3498                                 sizeof(struct smb2_fs_full_size_info),
3499                                 persistent_fid, volatile_fid);
3500         if (rc)
3501                 return rc;
3502
3503         if (encryption_required(tcon))
3504                 flags |= CIFS_TRANSFORM_REQ;
3505
3506         rc = smb2_send_recv(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3507         cifs_small_buf_release(iov.iov_base);
3508         if (rc) {
3509                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3510                 goto qfsinf_exit;
3511         }
3512         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3513
3514         info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
3515                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
3516         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
3517                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
3518                           sizeof(struct smb2_fs_full_size_info));
3519         if (!rc)
3520                 copy_fs_info_to_kstatfs(info, fsdata);
3521
3522 qfsinf_exit:
3523         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3524         return rc;
3525 }
3526
3527 int
3528 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
3529               u64 persistent_fid, u64 volatile_fid, int level)
3530 {
3531         struct smb2_query_info_rsp *rsp = NULL;
3532         struct kvec iov;
3533         struct kvec rsp_iov;
3534         int rc = 0;
3535         int resp_buftype, max_len, min_len;
3536         struct cifs_ses *ses = tcon->ses;
3537         unsigned int rsp_len, offset;
3538         int flags = 0;
3539
3540         if (level == FS_DEVICE_INFORMATION) {
3541                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3542                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3543         } else if (level == FS_ATTRIBUTE_INFORMATION) {
3544                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
3545                 min_len = MIN_FS_ATTR_INFO_SIZE;
3546         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
3547                 max_len = sizeof(struct smb3_fs_ss_info);
3548                 min_len = sizeof(struct smb3_fs_ss_info);
3549         } else {
3550                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
3551                 return -EINVAL;
3552         }
3553
3554         rc = build_qfs_info_req(&iov, tcon, level, max_len,
3555                                 persistent_fid, volatile_fid);
3556         if (rc)
3557                 return rc;
3558
3559         if (encryption_required(tcon))
3560                 flags |= CIFS_TRANSFORM_REQ;
3561
3562         rc = smb2_send_recv(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3563         cifs_small_buf_release(iov.iov_base);
3564         if (rc) {
3565                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3566                 goto qfsattr_exit;
3567         }
3568         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3569
3570         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
3571         offset = le16_to_cpu(rsp->OutputBufferOffset);
3572         rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
3573         if (rc)
3574                 goto qfsattr_exit;
3575
3576         if (level == FS_ATTRIBUTE_INFORMATION)
3577                 memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
3578                         + (char *)&rsp->hdr, min_t(unsigned int,
3579                         rsp_len, max_len));
3580         else if (level == FS_DEVICE_INFORMATION)
3581                 memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
3582                         + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
3583         else if (level == FS_SECTOR_SIZE_INFORMATION) {
3584                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
3585                         (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
3586                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
3587                 tcon->perf_sector_size =
3588                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
3589         }
3590
3591 qfsattr_exit:
3592         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3593         return rc;
3594 }
3595
3596 int
3597 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
3598            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3599            const __u32 num_lock, struct smb2_lock_element *buf)
3600 {
3601         int rc = 0;
3602         struct smb2_lock_req *req = NULL;
3603         struct kvec iov[2];
3604         struct kvec rsp_iov;
3605         int resp_buf_type;
3606         unsigned int count;
3607         int flags = CIFS_NO_RESP;
3608         unsigned int total_len;
3609
3610         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
3611
3612         rc = smb2_plain_req_init(SMB2_LOCK, tcon, (void **) &req, &total_len);
3613         if (rc)
3614                 return rc;
3615
3616         if (encryption_required(tcon))
3617                 flags |= CIFS_TRANSFORM_REQ;
3618
3619         req->sync_hdr.ProcessId = cpu_to_le32(pid);
3620         req->LockCount = cpu_to_le16(num_lock);
3621
3622         req->PersistentFileId = persist_fid;
3623         req->VolatileFileId = volatile_fid;
3624
3625         count = num_lock * sizeof(struct smb2_lock_element);
3626
3627         iov[0].iov_base = (char *)req;
3628         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
3629         iov[1].iov_base = (char *)buf;
3630         iov[1].iov_len = count;
3631
3632         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
3633         rc = smb2_send_recv(xid, tcon->ses, iov, 2, &resp_buf_type, flags,
3634                             &rsp_iov);
3635         cifs_small_buf_release(req);
3636         if (rc) {
3637                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
3638                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
3639         }
3640
3641         return rc;
3642 }
3643
3644 int
3645 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
3646           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3647           const __u64 length, const __u64 offset, const __u32 lock_flags,
3648           const bool wait)
3649 {
3650         struct smb2_lock_element lock;
3651
3652         lock.Offset = cpu_to_le64(offset);
3653         lock.Length = cpu_to_le64(length);
3654         lock.Flags = cpu_to_le32(lock_flags);
3655         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
3656                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
3657
3658         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
3659 }
3660
3661 int
3662 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
3663                  __u8 *lease_key, const __le32 lease_state)
3664 {
3665         int rc;
3666         struct smb2_lease_ack *req = NULL;
3667         struct cifs_ses *ses = tcon->ses;
3668         int flags = CIFS_OBREAK_OP;
3669         unsigned int total_len;
3670         struct kvec iov[1];
3671         struct kvec rsp_iov;
3672         int resp_buf_type;
3673
3674         cifs_dbg(FYI, "SMB2_lease_break\n");
3675         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
3676                              &total_len);
3677         if (rc)
3678                 return rc;
3679
3680         if (encryption_required(tcon))
3681                 flags |= CIFS_TRANSFORM_REQ;
3682
3683         req->sync_hdr.CreditRequest = cpu_to_le16(1);
3684         req->StructureSize = cpu_to_le16(36);
3685         total_len += 12;
3686
3687         memcpy(req->LeaseKey, lease_key, 16);
3688         req->LeaseState = lease_state;
3689
3690         flags |= CIFS_NO_RESP;
3691
3692         iov[0].iov_base = (char *)req;
3693         iov[0].iov_len = total_len;
3694
3695         rc = smb2_send_recv(xid, ses, iov, 1, &resp_buf_type, flags, &rsp_iov);
3696         cifs_small_buf_release(req);
3697
3698         if (rc) {
3699                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3700                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
3701         }
3702
3703         return rc;
3704 }