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