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