cifs: Limit the overall credit acquired
[cascardo/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
608         cifs_dbg(FYI, "Session Setup\n");
609
610         if (!server) {
611                 WARN(1, "%s: server is NULL!\n", __func__);
612                 return -EIO;
613         }
614
615         /*
616          * If we are here due to reconnect, free per-smb session key
617          * in case signing was required.
618          */
619         kfree(ses->auth_key.response);
620         ses->auth_key.response = NULL;
621
622         /*
623          * If memory allocation is successful, caller of this function
624          * frees it.
625          */
626         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
627         if (!ses->ntlmssp)
628                 return -ENOMEM;
629         ses->ntlmssp->sesskey_per_smbsess = true;
630
631         /* FIXME: allow for other auth types besides NTLMSSP (e.g. krb5) */
632         if (ses->sectype != Kerberos && ses->sectype != RawNTLMSSP)
633                 ses->sectype = RawNTLMSSP;
634
635 ssetup_ntlmssp_authenticate:
636         if (phase == NtLmChallenge)
637                 phase = NtLmAuthenticate; /* if ntlmssp, now final phase */
638
639         rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
640         if (rc)
641                 return rc;
642
643         req->hdr.SessionId = 0; /* First session, not a reauthenticate */
644         req->Flags = 0; /* MBZ */
645         /* to enable echos and oplocks */
646         req->hdr.CreditRequest = cpu_to_le16(3);
647
648         /* only one of SMB2 signing flags may be set in SMB2 request */
649         if (server->sign)
650                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
651         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
652                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
653         else
654                 req->SecurityMode = 0;
655
656         req->Capabilities = 0;
657         req->Channel = 0; /* MBZ */
658
659         iov[0].iov_base = (char *)req;
660         /* 4 for rfc1002 length field and 1 for pad */
661         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
662
663         if (ses->sectype == Kerberos) {
664 #ifdef CONFIG_CIFS_UPCALL
665                 struct cifs_spnego_msg *msg;
666
667                 spnego_key = cifs_get_spnego_key(ses);
668                 if (IS_ERR(spnego_key)) {
669                         rc = PTR_ERR(spnego_key);
670                         spnego_key = NULL;
671                         goto ssetup_exit;
672                 }
673
674                 msg = spnego_key->payload.data[0];
675                 /*
676                  * check version field to make sure that cifs.upcall is
677                  * sending us a response in an expected form
678                  */
679                 if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
680                         cifs_dbg(VFS,
681                                   "bad cifs.upcall version. Expected %d got %d",
682                                   CIFS_SPNEGO_UPCALL_VERSION, msg->version);
683                         rc = -EKEYREJECTED;
684                         goto ssetup_exit;
685                 }
686                 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
687                                                  GFP_KERNEL);
688                 if (!ses->auth_key.response) {
689                         cifs_dbg(VFS,
690                                 "Kerberos can't allocate (%u bytes) memory",
691                                 msg->sesskey_len);
692                         rc = -ENOMEM;
693                         goto ssetup_exit;
694                 }
695                 ses->auth_key.len = msg->sesskey_len;
696                 blob_length = msg->secblob_len;
697                 iov[1].iov_base = msg->data + msg->sesskey_len;
698                 iov[1].iov_len = blob_length;
699 #else
700                 rc = -EOPNOTSUPP;
701                 goto ssetup_exit;
702 #endif /* CONFIG_CIFS_UPCALL */
703         } else if (phase == NtLmNegotiate) { /* if not krb5 must be ntlmssp */
704                 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
705                                        GFP_KERNEL);
706                 if (ntlmssp_blob == NULL) {
707                         rc = -ENOMEM;
708                         goto ssetup_exit;
709                 }
710                 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
711                 if (use_spnego) {
712                         /* blob_length = build_spnego_ntlmssp_blob(
713                                         &security_blob,
714                                         sizeof(struct _NEGOTIATE_MESSAGE),
715                                         ntlmssp_blob); */
716                         /* BB eventually need to add this */
717                         cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
718                         rc = -EOPNOTSUPP;
719                         kfree(ntlmssp_blob);
720                         goto ssetup_exit;
721                 } else {
722                         blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
723                         /* with raw NTLMSSP we don't encapsulate in SPNEGO */
724                         security_blob = ntlmssp_blob;
725                 }
726                 iov[1].iov_base = security_blob;
727                 iov[1].iov_len = blob_length;
728         } else if (phase == NtLmAuthenticate) {
729                 req->hdr.SessionId = ses->Suid;
730                 rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
731                                              nls_cp);
732                 if (rc) {
733                         cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n",
734                                  rc);
735                         goto ssetup_exit; /* BB double check error handling */
736                 }
737                 if (use_spnego) {
738                         /* blob_length = build_spnego_ntlmssp_blob(
739                                                         &security_blob,
740                                                         blob_length,
741                                                         ntlmssp_blob); */
742                         cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
743                         rc = -EOPNOTSUPP;
744                         kfree(ntlmssp_blob);
745                         goto ssetup_exit;
746                 } else {
747                         security_blob = ntlmssp_blob;
748                 }
749                 iov[1].iov_base = security_blob;
750                 iov[1].iov_len = blob_length;
751         } else {
752                 cifs_dbg(VFS, "illegal ntlmssp phase\n");
753                 rc = -EIO;
754                 goto ssetup_exit;
755         }
756
757         /* Testing shows that buffer offset must be at location of Buffer[0] */
758         req->SecurityBufferOffset =
759                                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
760                                             1 /* pad */ - 4 /* rfc1001 len */);
761         req->SecurityBufferLength = cpu_to_le16(blob_length);
762
763         inc_rfc1001_len(req, blob_length - 1 /* pad */);
764
765         /* BB add code to build os and lm fields */
766
767         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype,
768                           CIFS_LOG_ERROR | CIFS_NEG_OP);
769
770         kfree(security_blob);
771         rsp = (struct smb2_sess_setup_rsp *)iov[0].iov_base;
772         ses->Suid = rsp->hdr.SessionId;
773         if (resp_buftype != CIFS_NO_BUFFER &&
774             rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) {
775                 if (phase != NtLmNegotiate) {
776                         cifs_dbg(VFS, "Unexpected more processing error\n");
777                         goto ssetup_exit;
778                 }
779                 if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
780                                 le16_to_cpu(rsp->SecurityBufferOffset)) {
781                         cifs_dbg(VFS, "Invalid security buffer offset %d\n",
782                                  le16_to_cpu(rsp->SecurityBufferOffset));
783                         rc = -EIO;
784                         goto ssetup_exit;
785                 }
786
787                 /* NTLMSSP Negotiate sent now processing challenge (response) */
788                 phase = NtLmChallenge; /* process ntlmssp challenge */
789                 rc = 0; /* MORE_PROCESSING is not an error here but expected */
790                 rc = decode_ntlmssp_challenge(rsp->Buffer,
791                                 le16_to_cpu(rsp->SecurityBufferLength), ses);
792         }
793
794         /*
795          * BB eventually add code for SPNEGO decoding of NtlmChallenge blob,
796          * but at least the raw NTLMSSP case works.
797          */
798         /*
799          * No tcon so can't do
800          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
801          */
802         if (rc != 0)
803                 goto ssetup_exit;
804
805         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
806         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
807                 cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
808 ssetup_exit:
809         free_rsp_buf(resp_buftype, rsp);
810
811         /* if ntlmssp, and negotiate succeeded, proceed to authenticate phase */
812         if ((phase == NtLmChallenge) && (rc == 0))
813                 goto ssetup_ntlmssp_authenticate;
814
815         if (!rc) {
816                 mutex_lock(&server->srv_mutex);
817                 if (server->sign && server->ops->generate_signingkey) {
818                         rc = server->ops->generate_signingkey(ses);
819                         kfree(ses->auth_key.response);
820                         ses->auth_key.response = NULL;
821                         if (rc) {
822                                 cifs_dbg(FYI,
823                                         "SMB3 session key generation failed\n");
824                                 mutex_unlock(&server->srv_mutex);
825                                 goto keygen_exit;
826                         }
827                 }
828                 if (!server->session_estab) {
829                         server->sequence_number = 0x2;
830                         server->session_estab = true;
831                 }
832                 mutex_unlock(&server->srv_mutex);
833
834                 cifs_dbg(FYI, "SMB2/3 session established successfully\n");
835                 spin_lock(&GlobalMid_Lock);
836                 ses->status = CifsGood;
837                 ses->need_reconnect = false;
838                 spin_unlock(&GlobalMid_Lock);
839         }
840
841 keygen_exit:
842         if (!server->sign) {
843                 kfree(ses->auth_key.response);
844                 ses->auth_key.response = NULL;
845         }
846         if (spnego_key) {
847                 key_invalidate(spnego_key);
848                 key_put(spnego_key);
849         }
850         kfree(ses->ntlmssp);
851
852         return rc;
853 }
854
855 int
856 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
857 {
858         struct smb2_logoff_req *req; /* response is also trivial struct */
859         int rc = 0;
860         struct TCP_Server_Info *server;
861
862         cifs_dbg(FYI, "disconnect session %p\n", ses);
863
864         if (ses && (ses->server))
865                 server = ses->server;
866         else
867                 return -EIO;
868
869         /* no need to send SMB logoff if uid already closed due to reconnect */
870         if (ses->need_reconnect)
871                 goto smb2_session_already_dead;
872
873         rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
874         if (rc)
875                 return rc;
876
877          /* since no tcon, smb2_init can not do this, so do here */
878         req->hdr.SessionId = ses->Suid;
879         if (server->sign)
880                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
881
882         rc = SendReceiveNoRsp(xid, ses, (char *) &req->hdr, 0);
883         /*
884          * No tcon so can't do
885          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
886          */
887
888 smb2_session_already_dead:
889         return rc;
890 }
891
892 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
893 {
894         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
895 }
896
897 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
898
899 /* These are similar values to what Windows uses */
900 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
901 {
902         tcon->max_chunks = 256;
903         tcon->max_bytes_chunk = 1048576;
904         tcon->max_bytes_copy = 16777216;
905 }
906
907 int
908 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
909           struct cifs_tcon *tcon, const struct nls_table *cp)
910 {
911         struct smb2_tree_connect_req *req;
912         struct smb2_tree_connect_rsp *rsp = NULL;
913         struct kvec iov[2];
914         int rc = 0;
915         int resp_buftype;
916         int unc_path_len;
917         struct TCP_Server_Info *server;
918         __le16 *unc_path = NULL;
919
920         cifs_dbg(FYI, "TCON\n");
921
922         if ((ses->server) && tree)
923                 server = ses->server;
924         else
925                 return -EIO;
926
927         if (tcon && tcon->bad_network_name)
928                 return -ENOENT;
929
930         if ((tcon && tcon->seal) &&
931             ((ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) == 0)) {
932                 cifs_dbg(VFS, "encryption requested but no server support");
933                 return -EOPNOTSUPP;
934         }
935
936         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
937         if (unc_path == NULL)
938                 return -ENOMEM;
939
940         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
941         unc_path_len *= 2;
942         if (unc_path_len < 2) {
943                 kfree(unc_path);
944                 return -EINVAL;
945         }
946
947         rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
948         if (rc) {
949                 kfree(unc_path);
950                 return rc;
951         }
952
953         if (tcon == NULL) {
954                 /* since no tcon, smb2_init can not do this, so do here */
955                 req->hdr.SessionId = ses->Suid;
956                 /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
957                         req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
958         }
959
960         iov[0].iov_base = (char *)req;
961         /* 4 for rfc1002 length field and 1 for pad */
962         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
963
964         /* Testing shows that buffer offset must be at location of Buffer[0] */
965         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
966                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
967         req->PathLength = cpu_to_le16(unc_path_len - 2);
968         iov[1].iov_base = unc_path;
969         iov[1].iov_len = unc_path_len;
970
971         inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
972
973         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
974         rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
975
976         if (rc != 0) {
977                 if (tcon) {
978                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
979                         tcon->need_reconnect = true;
980                 }
981                 goto tcon_error_exit;
982         }
983
984         if (tcon == NULL) {
985                 ses->ipc_tid = rsp->hdr.TreeId;
986                 goto tcon_exit;
987         }
988
989         if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
990                 cifs_dbg(FYI, "connection to disk share\n");
991         else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
992                 tcon->ipc = true;
993                 cifs_dbg(FYI, "connection to pipe share\n");
994         } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
995                 tcon->print = true;
996                 cifs_dbg(FYI, "connection to printer\n");
997         } else {
998                 cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
999                 rc = -EOPNOTSUPP;
1000                 goto tcon_error_exit;
1001         }
1002
1003         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1004         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1005         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1006         tcon->tidStatus = CifsGood;
1007         tcon->need_reconnect = false;
1008         tcon->tid = rsp->hdr.TreeId;
1009         strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1010
1011         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1012             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1013                 cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1014         init_copy_chunk_defaults(tcon);
1015         if (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)
1016                 cifs_dbg(VFS, "Encrypted shares not supported");
1017         if (tcon->ses->server->ops->validate_negotiate)
1018                 rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1019 tcon_exit:
1020         free_rsp_buf(resp_buftype, rsp);
1021         kfree(unc_path);
1022         return rc;
1023
1024 tcon_error_exit:
1025         if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
1026                 cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1027                 if (tcon)
1028                         tcon->bad_network_name = true;
1029         }
1030         goto tcon_exit;
1031 }
1032
1033 int
1034 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1035 {
1036         struct smb2_tree_disconnect_req *req; /* response is trivial */
1037         int rc = 0;
1038         struct TCP_Server_Info *server;
1039         struct cifs_ses *ses = tcon->ses;
1040
1041         cifs_dbg(FYI, "Tree Disconnect\n");
1042
1043         if (ses && (ses->server))
1044                 server = ses->server;
1045         else
1046                 return -EIO;
1047
1048         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1049                 return 0;
1050
1051         rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
1052         if (rc)
1053                 return rc;
1054
1055         rc = SendReceiveNoRsp(xid, ses, (char *)&req->hdr, 0);
1056         if (rc)
1057                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1058
1059         return rc;
1060 }
1061
1062
1063 static struct create_durable *
1064 create_durable_buf(void)
1065 {
1066         struct create_durable *buf;
1067
1068         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1069         if (!buf)
1070                 return NULL;
1071
1072         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1073                                         (struct create_durable, Data));
1074         buf->ccontext.DataLength = cpu_to_le32(16);
1075         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1076                                 (struct create_durable, Name));
1077         buf->ccontext.NameLength = cpu_to_le16(4);
1078         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1079         buf->Name[0] = 'D';
1080         buf->Name[1] = 'H';
1081         buf->Name[2] = 'n';
1082         buf->Name[3] = 'Q';
1083         return buf;
1084 }
1085
1086 static struct create_durable *
1087 create_reconnect_durable_buf(struct cifs_fid *fid)
1088 {
1089         struct create_durable *buf;
1090
1091         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1092         if (!buf)
1093                 return NULL;
1094
1095         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1096                                         (struct create_durable, Data));
1097         buf->ccontext.DataLength = cpu_to_le32(16);
1098         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1099                                 (struct create_durable, Name));
1100         buf->ccontext.NameLength = cpu_to_le16(4);
1101         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1102         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1103         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1104         buf->Name[0] = 'D';
1105         buf->Name[1] = 'H';
1106         buf->Name[2] = 'n';
1107         buf->Name[3] = 'C';
1108         return buf;
1109 }
1110
1111 static __u8
1112 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1113                   unsigned int *epoch)
1114 {
1115         char *data_offset;
1116         struct create_context *cc;
1117         unsigned int next;
1118         unsigned int remaining;
1119         char *name;
1120
1121         data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
1122         remaining = le32_to_cpu(rsp->CreateContextsLength);
1123         cc = (struct create_context *)data_offset;
1124         while (remaining >= sizeof(struct create_context)) {
1125                 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1126                 if (le16_to_cpu(cc->NameLength) == 4 &&
1127                     strncmp(name, "RqLs", 4) == 0)
1128                         return server->ops->parse_lease_buf(cc, epoch);
1129
1130                 next = le32_to_cpu(cc->Next);
1131                 if (!next)
1132                         break;
1133                 remaining -= next;
1134                 cc = (struct create_context *)((char *)cc + next);
1135         }
1136
1137         return 0;
1138 }
1139
1140 static int
1141 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1142                   unsigned int *num_iovec, __u8 *oplock)
1143 {
1144         struct smb2_create_req *req = iov[0].iov_base;
1145         unsigned int num = *num_iovec;
1146
1147         iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
1148         if (iov[num].iov_base == NULL)
1149                 return -ENOMEM;
1150         iov[num].iov_len = server->vals->create_lease_size;
1151         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1152         if (!req->CreateContextsOffset)
1153                 req->CreateContextsOffset = cpu_to_le32(
1154                                 sizeof(struct smb2_create_req) - 4 +
1155                                 iov[num - 1].iov_len);
1156         le32_add_cpu(&req->CreateContextsLength,
1157                      server->vals->create_lease_size);
1158         inc_rfc1001_len(&req->hdr, server->vals->create_lease_size);
1159         *num_iovec = num + 1;
1160         return 0;
1161 }
1162
1163 static struct create_durable_v2 *
1164 create_durable_v2_buf(struct cifs_fid *pfid)
1165 {
1166         struct create_durable_v2 *buf;
1167
1168         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1169         if (!buf)
1170                 return NULL;
1171
1172         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1173                                         (struct create_durable_v2, dcontext));
1174         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1175         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1176                                 (struct create_durable_v2, Name));
1177         buf->ccontext.NameLength = cpu_to_le16(4);
1178
1179         buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1180         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1181         get_random_bytes(buf->dcontext.CreateGuid, 16);
1182         memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1183
1184         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1185         buf->Name[0] = 'D';
1186         buf->Name[1] = 'H';
1187         buf->Name[2] = '2';
1188         buf->Name[3] = 'Q';
1189         return buf;
1190 }
1191
1192 static struct create_durable_handle_reconnect_v2 *
1193 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1194 {
1195         struct create_durable_handle_reconnect_v2 *buf;
1196
1197         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1198                         GFP_KERNEL);
1199         if (!buf)
1200                 return NULL;
1201
1202         buf->ccontext.DataOffset =
1203                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1204                                      dcontext));
1205         buf->ccontext.DataLength =
1206                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1207         buf->ccontext.NameOffset =
1208                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1209                             Name));
1210         buf->ccontext.NameLength = cpu_to_le16(4);
1211
1212         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1213         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1214         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1215         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1216
1217         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1218         buf->Name[0] = 'D';
1219         buf->Name[1] = 'H';
1220         buf->Name[2] = '2';
1221         buf->Name[3] = 'C';
1222         return buf;
1223 }
1224
1225 static int
1226 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1227                     struct cifs_open_parms *oparms)
1228 {
1229         struct smb2_create_req *req = iov[0].iov_base;
1230         unsigned int num = *num_iovec;
1231
1232         iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1233         if (iov[num].iov_base == NULL)
1234                 return -ENOMEM;
1235         iov[num].iov_len = sizeof(struct create_durable_v2);
1236         if (!req->CreateContextsOffset)
1237                 req->CreateContextsOffset =
1238                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1239                                                                 iov[1].iov_len);
1240         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1241         inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2));
1242         *num_iovec = num + 1;
1243         return 0;
1244 }
1245
1246 static int
1247 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1248                     struct cifs_open_parms *oparms)
1249 {
1250         struct smb2_create_req *req = iov[0].iov_base;
1251         unsigned int num = *num_iovec;
1252
1253         /* indicate that we don't need to relock the file */
1254         oparms->reconnect = false;
1255
1256         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1257         if (iov[num].iov_base == NULL)
1258                 return -ENOMEM;
1259         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1260         if (!req->CreateContextsOffset)
1261                 req->CreateContextsOffset =
1262                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1263                                                                 iov[1].iov_len);
1264         le32_add_cpu(&req->CreateContextsLength,
1265                         sizeof(struct create_durable_handle_reconnect_v2));
1266         inc_rfc1001_len(&req->hdr,
1267                         sizeof(struct create_durable_handle_reconnect_v2));
1268         *num_iovec = num + 1;
1269         return 0;
1270 }
1271
1272 static int
1273 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1274                     struct cifs_open_parms *oparms, bool use_persistent)
1275 {
1276         struct smb2_create_req *req = iov[0].iov_base;
1277         unsigned int num = *num_iovec;
1278
1279         if (use_persistent) {
1280                 if (oparms->reconnect)
1281                         return add_durable_reconnect_v2_context(iov, num_iovec,
1282                                                                 oparms);
1283                 else
1284                         return add_durable_v2_context(iov, num_iovec, oparms);
1285         }
1286
1287         if (oparms->reconnect) {
1288                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1289                 /* indicate that we don't need to relock the file */
1290                 oparms->reconnect = false;
1291         } else
1292                 iov[num].iov_base = create_durable_buf();
1293         if (iov[num].iov_base == NULL)
1294                 return -ENOMEM;
1295         iov[num].iov_len = sizeof(struct create_durable);
1296         if (!req->CreateContextsOffset)
1297                 req->CreateContextsOffset =
1298                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1299                                                                 iov[1].iov_len);
1300         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1301         inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
1302         *num_iovec = num + 1;
1303         return 0;
1304 }
1305
1306 int
1307 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
1308           __u8 *oplock, struct smb2_file_all_info *buf,
1309           struct smb2_err_rsp **err_buf)
1310 {
1311         struct smb2_create_req *req;
1312         struct smb2_create_rsp *rsp;
1313         struct TCP_Server_Info *server;
1314         struct cifs_tcon *tcon = oparms->tcon;
1315         struct cifs_ses *ses = tcon->ses;
1316         struct kvec iov[4];
1317         int resp_buftype;
1318         int uni_path_len;
1319         __le16 *copy_path = NULL;
1320         int copy_size;
1321         int rc = 0;
1322         unsigned int num_iovecs = 2;
1323         __u32 file_attributes = 0;
1324         char *dhc_buf = NULL, *lc_buf = NULL;
1325
1326         cifs_dbg(FYI, "create/open\n");
1327
1328         if (ses && (ses->server))
1329                 server = ses->server;
1330         else
1331                 return -EIO;
1332
1333         rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
1334         if (rc)
1335                 return rc;
1336
1337         if (oparms->create_options & CREATE_OPTION_READONLY)
1338                 file_attributes |= ATTR_READONLY;
1339         if (oparms->create_options & CREATE_OPTION_SPECIAL)
1340                 file_attributes |= ATTR_SYSTEM;
1341
1342         req->ImpersonationLevel = IL_IMPERSONATION;
1343         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
1344         /* File attributes ignored on open (used in create though) */
1345         req->FileAttributes = cpu_to_le32(file_attributes);
1346         req->ShareAccess = FILE_SHARE_ALL_LE;
1347         req->CreateDisposition = cpu_to_le32(oparms->disposition);
1348         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
1349         uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
1350         /* do not count rfc1001 len field */
1351         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
1352
1353         iov[0].iov_base = (char *)req;
1354         /* 4 for rfc1002 length field */
1355         iov[0].iov_len = get_rfc1002_length(req) + 4;
1356
1357         /* MUST set path len (NameLength) to 0 opening root of share */
1358         req->NameLength = cpu_to_le16(uni_path_len - 2);
1359         /* -1 since last byte is buf[0] which is sent below (path) */
1360         iov[0].iov_len--;
1361         if (uni_path_len % 8 != 0) {
1362                 copy_size = uni_path_len / 8 * 8;
1363                 if (copy_size < uni_path_len)
1364                         copy_size += 8;
1365
1366                 copy_path = kzalloc(copy_size, GFP_KERNEL);
1367                 if (!copy_path)
1368                         return -ENOMEM;
1369                 memcpy((char *)copy_path, (const char *)path,
1370                         uni_path_len);
1371                 uni_path_len = copy_size;
1372                 path = copy_path;
1373         }
1374
1375         iov[1].iov_len = uni_path_len;
1376         iov[1].iov_base = path;
1377         /* -1 since last byte is buf[0] which was counted in smb2_buf_len */
1378         inc_rfc1001_len(req, uni_path_len - 1);
1379
1380         if (!server->oplocks)
1381                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
1382
1383         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1384             *oplock == SMB2_OPLOCK_LEVEL_NONE)
1385                 req->RequestedOplockLevel = *oplock;
1386         else {
1387                 rc = add_lease_context(server, iov, &num_iovecs, oplock);
1388                 if (rc) {
1389                         cifs_small_buf_release(req);
1390                         kfree(copy_path);
1391                         return rc;
1392                 }
1393                 lc_buf = iov[num_iovecs-1].iov_base;
1394         }
1395
1396         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1397                 /* need to set Next field of lease context if we request it */
1398                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1399                         struct create_context *ccontext =
1400                             (struct create_context *)iov[num_iovecs-1].iov_base;
1401                         ccontext->Next =
1402                                 cpu_to_le32(server->vals->create_lease_size);
1403                 }
1404
1405                 rc = add_durable_context(iov, &num_iovecs, oparms,
1406                                         tcon->use_persistent);
1407                 if (rc) {
1408                         cifs_small_buf_release(req);
1409                         kfree(copy_path);
1410                         kfree(lc_buf);
1411                         return rc;
1412                 }
1413                 dhc_buf = iov[num_iovecs-1].iov_base;
1414         }
1415
1416         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1417         rsp = (struct smb2_create_rsp *)iov[0].iov_base;
1418
1419         if (rc != 0) {
1420                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1421                 if (err_buf)
1422                         *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
1423                                            GFP_KERNEL);
1424                 goto creat_exit;
1425         }
1426
1427         oparms->fid->persistent_fid = rsp->PersistentFileId;
1428         oparms->fid->volatile_fid = rsp->VolatileFileId;
1429
1430         if (buf) {
1431                 memcpy(buf, &rsp->CreationTime, 32);
1432                 buf->AllocationSize = rsp->AllocationSize;
1433                 buf->EndOfFile = rsp->EndofFile;
1434                 buf->Attributes = rsp->FileAttributes;
1435                 buf->NumberOfLinks = cpu_to_le32(1);
1436                 buf->DeletePending = 0;
1437         }
1438
1439         if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1440                 *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
1441         else
1442                 *oplock = rsp->OplockLevel;
1443 creat_exit:
1444         kfree(copy_path);
1445         kfree(lc_buf);
1446         kfree(dhc_buf);
1447         free_rsp_buf(resp_buftype, rsp);
1448         return rc;
1449 }
1450
1451 /*
1452  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
1453  */
1454 int
1455 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1456            u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data,
1457            u32 indatalen, char **out_data, u32 *plen /* returned data len */)
1458 {
1459         struct smb2_ioctl_req *req;
1460         struct smb2_ioctl_rsp *rsp;
1461         struct TCP_Server_Info *server;
1462         struct cifs_ses *ses;
1463         struct kvec iov[2];
1464         int resp_buftype;
1465         int num_iovecs;
1466         int rc = 0;
1467
1468         cifs_dbg(FYI, "SMB2 IOCTL\n");
1469
1470         if (out_data != NULL)
1471                 *out_data = NULL;
1472
1473         /* zero out returned data len, in case of error */
1474         if (plen)
1475                 *plen = 0;
1476
1477         if (tcon)
1478                 ses = tcon->ses;
1479         else
1480                 return -EIO;
1481
1482         if (ses && (ses->server))
1483                 server = ses->server;
1484         else
1485                 return -EIO;
1486
1487         rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
1488         if (rc)
1489                 return rc;
1490
1491         req->CtlCode = cpu_to_le32(opcode);
1492         req->PersistentFileId = persistent_fid;
1493         req->VolatileFileId = volatile_fid;
1494
1495         if (indatalen) {
1496                 req->InputCount = cpu_to_le32(indatalen);
1497                 /* do not set InputOffset if no input data */
1498                 req->InputOffset =
1499                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
1500                 iov[1].iov_base = in_data;
1501                 iov[1].iov_len = indatalen;
1502                 num_iovecs = 2;
1503         } else
1504                 num_iovecs = 1;
1505
1506         req->OutputOffset = 0;
1507         req->OutputCount = 0; /* MBZ */
1508
1509         /*
1510          * Could increase MaxOutputResponse, but that would require more
1511          * than one credit. Windows typically sets this smaller, but for some
1512          * ioctls it may be useful to allow server to send more. No point
1513          * limiting what the server can send as long as fits in one credit
1514          */
1515         req->MaxOutputResponse = cpu_to_le32(0xFF00); /* < 64K uses 1 credit */
1516
1517         if (is_fsctl)
1518                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1519         else
1520                 req->Flags = 0;
1521
1522         iov[0].iov_base = (char *)req;
1523
1524         /*
1525          * If no input data, the size of ioctl struct in
1526          * protocol spec still includes a 1 byte data buffer,
1527          * but if input data passed to ioctl, we do not
1528          * want to double count this, so we do not send
1529          * the dummy one byte of data in iovec[0] if sending
1530          * input data (in iovec[1]). We also must add 4 bytes
1531          * in first iovec to allow for rfc1002 length field.
1532          */
1533
1534         if (indatalen) {
1535                 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1536                 inc_rfc1001_len(req, indatalen - 1);
1537         } else
1538                 iov[0].iov_len = get_rfc1002_length(req) + 4;
1539
1540
1541         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1542         rsp = (struct smb2_ioctl_rsp *)iov[0].iov_base;
1543
1544         if ((rc != 0) && (rc != -EINVAL)) {
1545                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1546                 goto ioctl_exit;
1547         } else if (rc == -EINVAL) {
1548                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
1549                     (opcode != FSCTL_SRV_COPYCHUNK)) {
1550                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1551                         goto ioctl_exit;
1552                 }
1553         }
1554
1555         /* check if caller wants to look at return data or just return rc */
1556         if ((plen == NULL) || (out_data == NULL))
1557                 goto ioctl_exit;
1558
1559         *plen = le32_to_cpu(rsp->OutputCount);
1560
1561         /* We check for obvious errors in the output buffer length and offset */
1562         if (*plen == 0)
1563                 goto ioctl_exit; /* server returned no data */
1564         else if (*plen > 0xFF00) {
1565                 cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
1566                 *plen = 0;
1567                 rc = -EIO;
1568                 goto ioctl_exit;
1569         }
1570
1571         if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
1572                 cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
1573                         le32_to_cpu(rsp->OutputOffset));
1574                 *plen = 0;
1575                 rc = -EIO;
1576                 goto ioctl_exit;
1577         }
1578
1579         *out_data = kmalloc(*plen, GFP_KERNEL);
1580         if (*out_data == NULL) {
1581                 rc = -ENOMEM;
1582                 goto ioctl_exit;
1583         }
1584
1585         memcpy(*out_data,
1586                (char *)&rsp->hdr.ProtocolId + le32_to_cpu(rsp->OutputOffset),
1587                *plen);
1588 ioctl_exit:
1589         free_rsp_buf(resp_buftype, rsp);
1590         return rc;
1591 }
1592
1593 /*
1594  *   Individual callers to ioctl worker function follow
1595  */
1596
1597 int
1598 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1599                      u64 persistent_fid, u64 volatile_fid)
1600 {
1601         int rc;
1602         struct  compress_ioctl fsctl_input;
1603         char *ret_data = NULL;
1604
1605         fsctl_input.CompressionState =
1606                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
1607
1608         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1609                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
1610                         (char *)&fsctl_input /* data input */,
1611                         2 /* in data len */, &ret_data /* out data */, NULL);
1612
1613         cifs_dbg(FYI, "set compression rc %d\n", rc);
1614
1615         return rc;
1616 }
1617
1618 int
1619 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
1620            u64 persistent_fid, u64 volatile_fid)
1621 {
1622         struct smb2_close_req *req;
1623         struct smb2_close_rsp *rsp;
1624         struct TCP_Server_Info *server;
1625         struct cifs_ses *ses = tcon->ses;
1626         struct kvec iov[1];
1627         int resp_buftype;
1628         int rc = 0;
1629
1630         cifs_dbg(FYI, "Close\n");
1631
1632         if (ses && (ses->server))
1633                 server = ses->server;
1634         else
1635                 return -EIO;
1636
1637         rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
1638         if (rc)
1639                 return rc;
1640
1641         req->PersistentFileId = persistent_fid;
1642         req->VolatileFileId = volatile_fid;
1643
1644         iov[0].iov_base = (char *)req;
1645         /* 4 for rfc1002 length field */
1646         iov[0].iov_len = get_rfc1002_length(req) + 4;
1647
1648         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1649         rsp = (struct smb2_close_rsp *)iov[0].iov_base;
1650
1651         if (rc != 0) {
1652                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
1653                 goto close_exit;
1654         }
1655
1656         /* BB FIXME - decode close response, update inode for caching */
1657
1658 close_exit:
1659         free_rsp_buf(resp_buftype, rsp);
1660         return rc;
1661 }
1662
1663 static int
1664 validate_buf(unsigned int offset, unsigned int buffer_length,
1665              struct smb2_hdr *hdr, unsigned int min_buf_size)
1666
1667 {
1668         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
1669         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
1670         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1671         char *end_of_buf = begin_of_buf + buffer_length;
1672
1673
1674         if (buffer_length < min_buf_size) {
1675                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
1676                          buffer_length, min_buf_size);
1677                 return -EINVAL;
1678         }
1679
1680         /* check if beyond RFC1001 maximum length */
1681         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
1682                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
1683                          buffer_length, smb_len);
1684                 return -EINVAL;
1685         }
1686
1687         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
1688                 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
1689                 return -EINVAL;
1690         }
1691
1692         return 0;
1693 }
1694
1695 /*
1696  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
1697  * Caller must free buffer.
1698  */
1699 static int
1700 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
1701                       struct smb2_hdr *hdr, unsigned int minbufsize,
1702                       char *data)
1703
1704 {
1705         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1706         int rc;
1707
1708         if (!data)
1709                 return -EINVAL;
1710
1711         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
1712         if (rc)
1713                 return rc;
1714
1715         memcpy(data, begin_of_buf, buffer_length);
1716
1717         return 0;
1718 }
1719
1720 static int
1721 query_info(const unsigned int xid, struct cifs_tcon *tcon,
1722            u64 persistent_fid, u64 volatile_fid, u8 info_class,
1723            size_t output_len, size_t min_len, void *data)
1724 {
1725         struct smb2_query_info_req *req;
1726         struct smb2_query_info_rsp *rsp = NULL;
1727         struct kvec iov[2];
1728         int rc = 0;
1729         int resp_buftype;
1730         struct TCP_Server_Info *server;
1731         struct cifs_ses *ses = tcon->ses;
1732
1733         cifs_dbg(FYI, "Query Info\n");
1734
1735         if (ses && (ses->server))
1736                 server = ses->server;
1737         else
1738                 return -EIO;
1739
1740         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
1741         if (rc)
1742                 return rc;
1743
1744         req->InfoType = SMB2_O_INFO_FILE;
1745         req->FileInfoClass = info_class;
1746         req->PersistentFileId = persistent_fid;
1747         req->VolatileFileId = volatile_fid;
1748         /* 4 for rfc1002 length field and 1 for Buffer */
1749         req->InputBufferOffset =
1750                 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
1751         req->OutputBufferLength = cpu_to_le32(output_len);
1752
1753         iov[0].iov_base = (char *)req;
1754         /* 4 for rfc1002 length field */
1755         iov[0].iov_len = get_rfc1002_length(req) + 4;
1756
1757         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1758         rsp = (struct smb2_query_info_rsp *)iov[0].iov_base;
1759
1760         if (rc) {
1761                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
1762                 goto qinf_exit;
1763         }
1764
1765         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
1766                                    le32_to_cpu(rsp->OutputBufferLength),
1767                                    &rsp->hdr, min_len, data);
1768
1769 qinf_exit:
1770         free_rsp_buf(resp_buftype, rsp);
1771         return rc;
1772 }
1773
1774 int
1775 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
1776                 u64 persistent_fid, u64 volatile_fid,
1777                 struct smb2_file_all_info *data)
1778 {
1779         return query_info(xid, tcon, persistent_fid, volatile_fid,
1780                           FILE_ALL_INFORMATION,
1781                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
1782                           sizeof(struct smb2_file_all_info), data);
1783 }
1784
1785 int
1786 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
1787                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
1788 {
1789         return query_info(xid, tcon, persistent_fid, volatile_fid,
1790                           FILE_INTERNAL_INFORMATION,
1791                           sizeof(struct smb2_file_internal_info),
1792                           sizeof(struct smb2_file_internal_info), uniqueid);
1793 }
1794
1795 /*
1796  * This is a no-op for now. We're not really interested in the reply, but
1797  * rather in the fact that the server sent one and that server->lstrp
1798  * gets updated.
1799  *
1800  * FIXME: maybe we should consider checking that the reply matches request?
1801  */
1802 static void
1803 smb2_echo_callback(struct mid_q_entry *mid)
1804 {
1805         struct TCP_Server_Info *server = mid->callback_data;
1806         struct smb2_echo_rsp *smb2 = (struct smb2_echo_rsp *)mid->resp_buf;
1807         unsigned int credits_received = 1;
1808
1809         if (mid->mid_state == MID_RESPONSE_RECEIVED)
1810                 credits_received = le16_to_cpu(smb2->hdr.CreditRequest);
1811
1812         mutex_lock(&server->srv_mutex);
1813         DeleteMidQEntry(mid);
1814         mutex_unlock(&server->srv_mutex);
1815         add_credits(server, credits_received, CIFS_ECHO_OP);
1816 }
1817
1818 int
1819 SMB2_echo(struct TCP_Server_Info *server)
1820 {
1821         struct smb2_echo_req *req;
1822         int rc = 0;
1823         struct kvec iov;
1824         struct smb_rqst rqst = { .rq_iov = &iov,
1825                                  .rq_nvec = 1 };
1826
1827         cifs_dbg(FYI, "In echo request\n");
1828
1829         if (server->tcpStatus == CifsNeedNegotiate) {
1830                 struct list_head *tmp, *tmp2;
1831                 struct cifs_ses *ses;
1832                 struct cifs_tcon *tcon;
1833
1834                 cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
1835                 spin_lock(&cifs_tcp_ses_lock);
1836                 list_for_each(tmp, &server->smb_ses_list) {
1837                         ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
1838                         list_for_each(tmp2, &ses->tcon_list) {
1839                                 tcon = list_entry(tmp2, struct cifs_tcon,
1840                                                   tcon_list);
1841                                 /* add check for persistent handle reconnect */
1842                                 if (tcon && tcon->need_reconnect) {
1843                                         spin_unlock(&cifs_tcp_ses_lock);
1844                                         rc = smb2_reconnect(SMB2_ECHO, tcon);
1845                                         spin_lock(&cifs_tcp_ses_lock);
1846                                 }
1847                         }
1848                 }
1849                 spin_unlock(&cifs_tcp_ses_lock);
1850         }
1851
1852         /* if no session, renegotiate failed above */
1853         if (server->tcpStatus == CifsNeedNegotiate)
1854                 return -EIO;
1855
1856         rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
1857         if (rc)
1858                 return rc;
1859
1860         req->hdr.CreditRequest = cpu_to_le16(1);
1861
1862         iov.iov_base = (char *)req;
1863         /* 4 for rfc1002 length field */
1864         iov.iov_len = get_rfc1002_length(req) + 4;
1865
1866         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, server,
1867                              CIFS_ECHO_OP);
1868         if (rc)
1869                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
1870
1871         cifs_small_buf_release(req);
1872         return rc;
1873 }
1874
1875 int
1876 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1877            u64 volatile_fid)
1878 {
1879         struct smb2_flush_req *req;
1880         struct TCP_Server_Info *server;
1881         struct cifs_ses *ses = tcon->ses;
1882         struct kvec iov[1];
1883         int resp_buftype;
1884         int rc = 0;
1885
1886         cifs_dbg(FYI, "Flush\n");
1887
1888         if (ses && (ses->server))
1889                 server = ses->server;
1890         else
1891                 return -EIO;
1892
1893         rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
1894         if (rc)
1895                 return rc;
1896
1897         req->PersistentFileId = persistent_fid;
1898         req->VolatileFileId = volatile_fid;
1899
1900         iov[0].iov_base = (char *)req;
1901         /* 4 for rfc1002 length field */
1902         iov[0].iov_len = get_rfc1002_length(req) + 4;
1903
1904         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1905
1906         if (rc != 0)
1907                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
1908
1909         free_rsp_buf(resp_buftype, iov[0].iov_base);
1910         return rc;
1911 }
1912
1913 /*
1914  * To form a chain of read requests, any read requests after the first should
1915  * have the end_of_chain boolean set to true.
1916  */
1917 static int
1918 smb2_new_read_req(struct kvec *iov, struct cifs_io_parms *io_parms,
1919                   unsigned int remaining_bytes, int request_type)
1920 {
1921         int rc = -EACCES;
1922         struct smb2_read_req *req = NULL;
1923
1924         rc = small_smb2_init(SMB2_READ, io_parms->tcon, (void **) &req);
1925         if (rc)
1926                 return rc;
1927         if (io_parms->tcon->ses->server == NULL)
1928                 return -ECONNABORTED;
1929
1930         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1931
1932         req->PersistentFileId = io_parms->persistent_fid;
1933         req->VolatileFileId = io_parms->volatile_fid;
1934         req->ReadChannelInfoOffset = 0; /* reserved */
1935         req->ReadChannelInfoLength = 0; /* reserved */
1936         req->Channel = 0; /* reserved */
1937         req->MinimumCount = 0;
1938         req->Length = cpu_to_le32(io_parms->length);
1939         req->Offset = cpu_to_le64(io_parms->offset);
1940
1941         if (request_type & CHAINED_REQUEST) {
1942                 if (!(request_type & END_OF_CHAIN)) {
1943                         /* 4 for rfc1002 length field */
1944                         req->hdr.NextCommand =
1945                                 cpu_to_le32(get_rfc1002_length(req) + 4);
1946                 } else /* END_OF_CHAIN */
1947                         req->hdr.NextCommand = 0;
1948                 if (request_type & RELATED_REQUEST) {
1949                         req->hdr.Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
1950                         /*
1951                          * Related requests use info from previous read request
1952                          * in chain.
1953                          */
1954                         req->hdr.SessionId = 0xFFFFFFFF;
1955                         req->hdr.TreeId = 0xFFFFFFFF;
1956                         req->PersistentFileId = 0xFFFFFFFF;
1957                         req->VolatileFileId = 0xFFFFFFFF;
1958                 }
1959         }
1960         if (remaining_bytes > io_parms->length)
1961                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
1962         else
1963                 req->RemainingBytes = 0;
1964
1965         iov[0].iov_base = (char *)req;
1966         /* 4 for rfc1002 length field */
1967         iov[0].iov_len = get_rfc1002_length(req) + 4;
1968         return rc;
1969 }
1970
1971 static void
1972 smb2_readv_callback(struct mid_q_entry *mid)
1973 {
1974         struct cifs_readdata *rdata = mid->callback_data;
1975         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1976         struct TCP_Server_Info *server = tcon->ses->server;
1977         struct smb2_hdr *buf = (struct smb2_hdr *)rdata->iov.iov_base;
1978         unsigned int credits_received = 1;
1979         struct smb_rqst rqst = { .rq_iov = &rdata->iov,
1980                                  .rq_nvec = 1,
1981                                  .rq_pages = rdata->pages,
1982                                  .rq_npages = rdata->nr_pages,
1983                                  .rq_pagesz = rdata->pagesz,
1984                                  .rq_tailsz = rdata->tailsz };
1985
1986         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
1987                  __func__, mid->mid, mid->mid_state, rdata->result,
1988                  rdata->bytes);
1989
1990         switch (mid->mid_state) {
1991         case MID_RESPONSE_RECEIVED:
1992                 credits_received = le16_to_cpu(buf->CreditRequest);
1993                 /* result already set, check signature */
1994                 if (server->sign) {
1995                         int rc;
1996
1997                         rc = smb2_verify_signature(&rqst, server);
1998                         if (rc)
1999                                 cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
2000                                          rc);
2001                 }
2002                 /* FIXME: should this be counted toward the initiating task? */
2003                 task_io_account_read(rdata->got_bytes);
2004                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2005                 break;
2006         case MID_REQUEST_SUBMITTED:
2007         case MID_RETRY_NEEDED:
2008                 rdata->result = -EAGAIN;
2009                 if (server->sign && rdata->got_bytes)
2010                         /* reset bytes number since we can not check a sign */
2011                         rdata->got_bytes = 0;
2012                 /* FIXME: should this be counted toward the initiating task? */
2013                 task_io_account_read(rdata->got_bytes);
2014                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2015                 break;
2016         default:
2017                 if (rdata->result != -ENODATA)
2018                         rdata->result = -EIO;
2019         }
2020
2021         if (rdata->result)
2022                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
2023
2024         queue_work(cifsiod_wq, &rdata->work);
2025         mutex_lock(&server->srv_mutex);
2026         DeleteMidQEntry(mid);
2027         mutex_unlock(&server->srv_mutex);
2028         add_credits(server, credits_received, 0);
2029 }
2030
2031 /* smb2_async_readv - send an async write, and set up mid to handle result */
2032 int
2033 smb2_async_readv(struct cifs_readdata *rdata)
2034 {
2035         int rc, flags = 0;
2036         struct smb2_hdr *buf;
2037         struct cifs_io_parms io_parms;
2038         struct smb_rqst rqst = { .rq_iov = &rdata->iov,
2039                                  .rq_nvec = 1 };
2040         struct TCP_Server_Info *server;
2041
2042         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
2043                  __func__, rdata->offset, rdata->bytes);
2044
2045         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
2046         io_parms.offset = rdata->offset;
2047         io_parms.length = rdata->bytes;
2048         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
2049         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
2050         io_parms.pid = rdata->pid;
2051
2052         server = io_parms.tcon->ses->server;
2053
2054         rc = smb2_new_read_req(&rdata->iov, &io_parms, 0, 0);
2055         if (rc) {
2056                 if (rc == -EAGAIN && rdata->credits) {
2057                         /* credits was reset by reconnect */
2058                         rdata->credits = 0;
2059                         /* reduce in_flight value since we won't send the req */
2060                         spin_lock(&server->req_lock);
2061                         server->in_flight--;
2062                         spin_unlock(&server->req_lock);
2063                 }
2064                 return rc;
2065         }
2066
2067         buf = (struct smb2_hdr *)rdata->iov.iov_base;
2068         /* 4 for rfc1002 length field */
2069         rdata->iov.iov_len = get_rfc1002_length(rdata->iov.iov_base) + 4;
2070
2071         if (rdata->credits) {
2072                 buf->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
2073                                                 SMB2_MAX_BUFFER_SIZE));
2074                 buf->CreditRequest = buf->CreditCharge;
2075                 spin_lock(&server->req_lock);
2076                 server->credits += rdata->credits -
2077                                                 le16_to_cpu(buf->CreditCharge);
2078                 spin_unlock(&server->req_lock);
2079                 wake_up(&server->request_q);
2080                 flags = CIFS_HAS_CREDITS;
2081         }
2082
2083         kref_get(&rdata->refcount);
2084         rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
2085                              cifs_readv_receive, smb2_readv_callback,
2086                              rdata, flags);
2087         if (rc) {
2088                 kref_put(&rdata->refcount, cifs_readdata_release);
2089                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
2090         }
2091
2092         cifs_small_buf_release(buf);
2093         return rc;
2094 }
2095
2096 int
2097 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
2098           unsigned int *nbytes, char **buf, int *buf_type)
2099 {
2100         int resp_buftype, rc = -EACCES;
2101         struct smb2_read_rsp *rsp = NULL;
2102         struct kvec iov[1];
2103
2104         *nbytes = 0;
2105         rc = smb2_new_read_req(iov, io_parms, 0, 0);
2106         if (rc)
2107                 return rc;
2108
2109         rc = SendReceive2(xid, io_parms->tcon->ses, iov, 1,
2110                           &resp_buftype, CIFS_LOG_ERROR);
2111
2112         rsp = (struct smb2_read_rsp *)iov[0].iov_base;
2113
2114         if (rsp->hdr.Status == STATUS_END_OF_FILE) {
2115                 free_rsp_buf(resp_buftype, iov[0].iov_base);
2116                 return 0;
2117         }
2118
2119         if (rc) {
2120                 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
2121                 cifs_dbg(VFS, "Send error in read = %d\n", rc);
2122         } else {
2123                 *nbytes = le32_to_cpu(rsp->DataLength);
2124                 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
2125                     (*nbytes > io_parms->length)) {
2126                         cifs_dbg(FYI, "bad length %d for count %d\n",
2127                                  *nbytes, io_parms->length);
2128                         rc = -EIO;
2129                         *nbytes = 0;
2130                 }
2131         }
2132
2133         if (*buf) {
2134                 memcpy(*buf, (char *)&rsp->hdr.ProtocolId + rsp->DataOffset,
2135                        *nbytes);
2136                 free_rsp_buf(resp_buftype, iov[0].iov_base);
2137         } else if (resp_buftype != CIFS_NO_BUFFER) {
2138                 *buf = iov[0].iov_base;
2139                 if (resp_buftype == CIFS_SMALL_BUFFER)
2140                         *buf_type = CIFS_SMALL_BUFFER;
2141                 else if (resp_buftype == CIFS_LARGE_BUFFER)
2142                         *buf_type = CIFS_LARGE_BUFFER;
2143         }
2144         return rc;
2145 }
2146
2147 /*
2148  * Check the mid_state and signature on received buffer (if any), and queue the
2149  * workqueue completion task.
2150  */
2151 static void
2152 smb2_writev_callback(struct mid_q_entry *mid)
2153 {
2154         struct cifs_writedata *wdata = mid->callback_data;
2155         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2156         struct TCP_Server_Info *server = tcon->ses->server;
2157         unsigned int written;
2158         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
2159         unsigned int credits_received = 1;
2160
2161         switch (mid->mid_state) {
2162         case MID_RESPONSE_RECEIVED:
2163                 credits_received = le16_to_cpu(rsp->hdr.CreditRequest);
2164                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
2165                 if (wdata->result != 0)
2166                         break;
2167
2168                 written = le32_to_cpu(rsp->DataLength);
2169                 /*
2170                  * Mask off high 16 bits when bytes written as returned
2171                  * by the server is greater than bytes requested by the
2172                  * client. OS/2 servers are known to set incorrect
2173                  * CountHigh values.
2174                  */
2175                 if (written > wdata->bytes)
2176                         written &= 0xFFFF;
2177
2178                 if (written < wdata->bytes)
2179                         wdata->result = -ENOSPC;
2180                 else
2181                         wdata->bytes = written;
2182                 break;
2183         case MID_REQUEST_SUBMITTED:
2184         case MID_RETRY_NEEDED:
2185                 wdata->result = -EAGAIN;
2186                 break;
2187         default:
2188                 wdata->result = -EIO;
2189                 break;
2190         }
2191
2192         if (wdata->result)
2193                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2194
2195         queue_work(cifsiod_wq, &wdata->work);
2196         mutex_lock(&server->srv_mutex);
2197         DeleteMidQEntry(mid);
2198         mutex_unlock(&server->srv_mutex);
2199         add_credits(tcon->ses->server, credits_received, 0);
2200 }
2201
2202 /* smb2_async_writev - send an async write, and set up mid to handle result */
2203 int
2204 smb2_async_writev(struct cifs_writedata *wdata,
2205                   void (*release)(struct kref *kref))
2206 {
2207         int rc = -EACCES, flags = 0;
2208         struct smb2_write_req *req = NULL;
2209         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2210         struct TCP_Server_Info *server = tcon->ses->server;
2211         struct kvec iov;
2212         struct smb_rqst rqst;
2213
2214         rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
2215         if (rc) {
2216                 if (rc == -EAGAIN && wdata->credits) {
2217                         /* credits was reset by reconnect */
2218                         wdata->credits = 0;
2219                         /* reduce in_flight value since we won't send the req */
2220                         spin_lock(&server->req_lock);
2221                         server->in_flight--;
2222                         spin_unlock(&server->req_lock);
2223                 }
2224                 goto async_writev_out;
2225         }
2226
2227         req->hdr.ProcessId = cpu_to_le32(wdata->cfile->pid);
2228
2229         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
2230         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
2231         req->WriteChannelInfoOffset = 0;
2232         req->WriteChannelInfoLength = 0;
2233         req->Channel = 0;
2234         req->Offset = cpu_to_le64(wdata->offset);
2235         /* 4 for rfc1002 length field */
2236         req->DataOffset = cpu_to_le16(
2237                                 offsetof(struct smb2_write_req, Buffer) - 4);
2238         req->RemainingBytes = 0;
2239
2240         /* 4 for rfc1002 length field and 1 for Buffer */
2241         iov.iov_len = get_rfc1002_length(req) + 4 - 1;
2242         iov.iov_base = req;
2243
2244         rqst.rq_iov = &iov;
2245         rqst.rq_nvec = 1;
2246         rqst.rq_pages = wdata->pages;
2247         rqst.rq_npages = wdata->nr_pages;
2248         rqst.rq_pagesz = wdata->pagesz;
2249         rqst.rq_tailsz = wdata->tailsz;
2250
2251         cifs_dbg(FYI, "async write at %llu %u bytes\n",
2252                  wdata->offset, wdata->bytes);
2253
2254         req->Length = cpu_to_le32(wdata->bytes);
2255
2256         inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
2257
2258         if (wdata->credits) {
2259                 req->hdr.CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
2260                                                     SMB2_MAX_BUFFER_SIZE));
2261                 req->hdr.CreditRequest = req->hdr.CreditCharge;
2262                 spin_lock(&server->req_lock);
2263                 server->credits += wdata->credits -
2264                                         le16_to_cpu(req->hdr.CreditCharge);
2265                 spin_unlock(&server->req_lock);
2266                 wake_up(&server->request_q);
2267                 flags = CIFS_HAS_CREDITS;
2268         }
2269
2270         kref_get(&wdata->refcount);
2271         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, wdata,
2272                              flags);
2273
2274         if (rc) {
2275                 kref_put(&wdata->refcount, release);
2276                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2277         }
2278
2279 async_writev_out:
2280         cifs_small_buf_release(req);
2281         return rc;
2282 }
2283
2284 /*
2285  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
2286  * The length field from io_parms must be at least 1 and indicates a number of
2287  * elements with data to write that begins with position 1 in iov array. All
2288  * data length is specified by count.
2289  */
2290 int
2291 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
2292            unsigned int *nbytes, struct kvec *iov, int n_vec)
2293 {
2294         int rc = 0;
2295         struct smb2_write_req *req = NULL;
2296         struct smb2_write_rsp *rsp = NULL;
2297         int resp_buftype;
2298         *nbytes = 0;
2299
2300         if (n_vec < 1)
2301                 return rc;
2302
2303         rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
2304         if (rc)
2305                 return rc;
2306
2307         if (io_parms->tcon->ses->server == NULL)
2308                 return -ECONNABORTED;
2309
2310         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
2311
2312         req->PersistentFileId = io_parms->persistent_fid;
2313         req->VolatileFileId = io_parms->volatile_fid;
2314         req->WriteChannelInfoOffset = 0;
2315         req->WriteChannelInfoLength = 0;
2316         req->Channel = 0;
2317         req->Length = cpu_to_le32(io_parms->length);
2318         req->Offset = cpu_to_le64(io_parms->offset);
2319         /* 4 for rfc1002 length field */
2320         req->DataOffset = cpu_to_le16(
2321                                 offsetof(struct smb2_write_req, Buffer) - 4);
2322         req->RemainingBytes = 0;
2323
2324         iov[0].iov_base = (char *)req;
2325         /* 4 for rfc1002 length field and 1 for Buffer */
2326         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2327
2328         /* length of entire message including data to be written */
2329         inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
2330
2331         rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
2332                           &resp_buftype, 0);
2333         rsp = (struct smb2_write_rsp *)iov[0].iov_base;
2334
2335         if (rc) {
2336                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
2337                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
2338         } else
2339                 *nbytes = le32_to_cpu(rsp->DataLength);
2340
2341         free_rsp_buf(resp_buftype, rsp);
2342         return rc;
2343 }
2344
2345 static unsigned int
2346 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
2347 {
2348         int len;
2349         unsigned int entrycount = 0;
2350         unsigned int next_offset = 0;
2351         FILE_DIRECTORY_INFO *entryptr;
2352
2353         if (bufstart == NULL)
2354                 return 0;
2355
2356         entryptr = (FILE_DIRECTORY_INFO *)bufstart;
2357
2358         while (1) {
2359                 entryptr = (FILE_DIRECTORY_INFO *)
2360                                         ((char *)entryptr + next_offset);
2361
2362                 if ((char *)entryptr + size > end_of_buf) {
2363                         cifs_dbg(VFS, "malformed search entry would overflow\n");
2364                         break;
2365                 }
2366
2367                 len = le32_to_cpu(entryptr->FileNameLength);
2368                 if ((char *)entryptr + len + size > end_of_buf) {
2369                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
2370                                  end_of_buf);
2371                         break;
2372                 }
2373
2374                 *lastentry = (char *)entryptr;
2375                 entrycount++;
2376
2377                 next_offset = le32_to_cpu(entryptr->NextEntryOffset);
2378                 if (!next_offset)
2379                         break;
2380         }
2381
2382         return entrycount;
2383 }
2384
2385 /*
2386  * Readdir/FindFirst
2387  */
2388 int
2389 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
2390                      u64 persistent_fid, u64 volatile_fid, int index,
2391                      struct cifs_search_info *srch_inf)
2392 {
2393         struct smb2_query_directory_req *req;
2394         struct smb2_query_directory_rsp *rsp = NULL;
2395         struct kvec iov[2];
2396         int rc = 0;
2397         int len;
2398         int resp_buftype = CIFS_NO_BUFFER;
2399         unsigned char *bufptr;
2400         struct TCP_Server_Info *server;
2401         struct cifs_ses *ses = tcon->ses;
2402         __le16 asteriks = cpu_to_le16('*');
2403         char *end_of_smb;
2404         unsigned int output_size = CIFSMaxBufSize;
2405         size_t info_buf_size;
2406
2407         if (ses && (ses->server))
2408                 server = ses->server;
2409         else
2410                 return -EIO;
2411
2412         rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
2413         if (rc)
2414                 return rc;
2415
2416         switch (srch_inf->info_level) {
2417         case SMB_FIND_FILE_DIRECTORY_INFO:
2418                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
2419                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
2420                 break;
2421         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
2422                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
2423                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
2424                 break;
2425         default:
2426                 cifs_dbg(VFS, "info level %u isn't supported\n",
2427                          srch_inf->info_level);
2428                 rc = -EINVAL;
2429                 goto qdir_exit;
2430         }
2431
2432         req->FileIndex = cpu_to_le32(index);
2433         req->PersistentFileId = persistent_fid;
2434         req->VolatileFileId = volatile_fid;
2435
2436         len = 0x2;
2437         bufptr = req->Buffer;
2438         memcpy(bufptr, &asteriks, len);
2439
2440         req->FileNameOffset =
2441                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
2442         req->FileNameLength = cpu_to_le16(len);
2443         /*
2444          * BB could be 30 bytes or so longer if we used SMB2 specific
2445          * buffer lengths, but this is safe and close enough.
2446          */
2447         output_size = min_t(unsigned int, output_size, server->maxBuf);
2448         output_size = min_t(unsigned int, output_size, 2 << 15);
2449         req->OutputBufferLength = cpu_to_le32(output_size);
2450
2451         iov[0].iov_base = (char *)req;
2452         /* 4 for RFC1001 length and 1 for Buffer */
2453         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2454
2455         iov[1].iov_base = (char *)(req->Buffer);
2456         iov[1].iov_len = len;
2457
2458         inc_rfc1001_len(req, len - 1 /* Buffer */);
2459
2460         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
2461         rsp = (struct smb2_query_directory_rsp *)iov[0].iov_base;
2462
2463         if (rc) {
2464                 if (rc == -ENODATA && rsp->hdr.Status == STATUS_NO_MORE_FILES) {
2465                         srch_inf->endOfSearch = true;
2466                         rc = 0;
2467                 }
2468                 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
2469                 goto qdir_exit;
2470         }
2471
2472         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2473                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2474                           info_buf_size);
2475         if (rc)
2476                 goto qdir_exit;
2477
2478         srch_inf->unicode = true;
2479
2480         if (srch_inf->ntwrk_buf_start) {
2481                 if (srch_inf->smallBuf)
2482                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
2483                 else
2484                         cifs_buf_release(srch_inf->ntwrk_buf_start);
2485         }
2486         srch_inf->ntwrk_buf_start = (char *)rsp;
2487         srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
2488                 (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
2489         /* 4 for rfc1002 length field */
2490         end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
2491         srch_inf->entries_in_buffer =
2492                         num_entries(srch_inf->srch_entries_start, end_of_smb,
2493                                     &srch_inf->last_entry, info_buf_size);
2494         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
2495         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
2496                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
2497                  srch_inf->srch_entries_start, srch_inf->last_entry);
2498         if (resp_buftype == CIFS_LARGE_BUFFER)
2499                 srch_inf->smallBuf = false;
2500         else if (resp_buftype == CIFS_SMALL_BUFFER)
2501                 srch_inf->smallBuf = true;
2502         else
2503                 cifs_dbg(VFS, "illegal search buffer type\n");
2504
2505         return rc;
2506
2507 qdir_exit:
2508         free_rsp_buf(resp_buftype, rsp);
2509         return rc;
2510 }
2511
2512 static int
2513 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2514                u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class,
2515                unsigned int num, void **data, unsigned int *size)
2516 {
2517         struct smb2_set_info_req *req;
2518         struct smb2_set_info_rsp *rsp = NULL;
2519         struct kvec *iov;
2520         int rc = 0;
2521         int resp_buftype;
2522         unsigned int i;
2523         struct TCP_Server_Info *server;
2524         struct cifs_ses *ses = tcon->ses;
2525
2526         if (ses && (ses->server))
2527                 server = ses->server;
2528         else
2529                 return -EIO;
2530
2531         if (!num)
2532                 return -EINVAL;
2533
2534         iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
2535         if (!iov)
2536                 return -ENOMEM;
2537
2538         rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
2539         if (rc) {
2540                 kfree(iov);
2541                 return rc;
2542         }
2543
2544         req->hdr.ProcessId = cpu_to_le32(pid);
2545
2546         req->InfoType = SMB2_O_INFO_FILE;
2547         req->FileInfoClass = info_class;
2548         req->PersistentFileId = persistent_fid;
2549         req->VolatileFileId = volatile_fid;
2550
2551         /* 4 for RFC1001 length and 1 for Buffer */
2552         req->BufferOffset =
2553                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
2554         req->BufferLength = cpu_to_le32(*size);
2555
2556         inc_rfc1001_len(req, *size - 1 /* Buffer */);
2557
2558         memcpy(req->Buffer, *data, *size);
2559
2560         iov[0].iov_base = (char *)req;
2561         /* 4 for RFC1001 length */
2562         iov[0].iov_len = get_rfc1002_length(req) + 4;
2563
2564         for (i = 1; i < num; i++) {
2565                 inc_rfc1001_len(req, size[i]);
2566                 le32_add_cpu(&req->BufferLength, size[i]);
2567                 iov[i].iov_base = (char *)data[i];
2568                 iov[i].iov_len = size[i];
2569         }
2570
2571         rc = SendReceive2(xid, ses, iov, num, &resp_buftype, 0);
2572         rsp = (struct smb2_set_info_rsp *)iov[0].iov_base;
2573
2574         if (rc != 0)
2575                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
2576
2577         free_rsp_buf(resp_buftype, rsp);
2578         kfree(iov);
2579         return rc;
2580 }
2581
2582 int
2583 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
2584             u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2585 {
2586         struct smb2_file_rename_info info;
2587         void **data;
2588         unsigned int size[2];
2589         int rc;
2590         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2591
2592         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2593         if (!data)
2594                 return -ENOMEM;
2595
2596         info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
2597                               /* 0 = fail if target already exists */
2598         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
2599         info.FileNameLength = cpu_to_le32(len);
2600
2601         data[0] = &info;
2602         size[0] = sizeof(struct smb2_file_rename_info);
2603
2604         data[1] = target_file;
2605         size[1] = len + 2 /* null */;
2606
2607         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2608                            current->tgid, FILE_RENAME_INFORMATION, 2, data,
2609                            size);
2610         kfree(data);
2611         return rc;
2612 }
2613
2614 int
2615 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
2616                   u64 persistent_fid, u64 volatile_fid)
2617 {
2618         __u8 delete_pending = 1;
2619         void *data;
2620         unsigned int size;
2621
2622         data = &delete_pending;
2623         size = 1; /* sizeof __u8 */
2624
2625         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2626                         current->tgid, FILE_DISPOSITION_INFORMATION, 1, &data,
2627                         &size);
2628 }
2629
2630 int
2631 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
2632                   u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2633 {
2634         struct smb2_file_link_info info;
2635         void **data;
2636         unsigned int size[2];
2637         int rc;
2638         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2639
2640         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2641         if (!data)
2642                 return -ENOMEM;
2643
2644         info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
2645                               /* 0 = fail if link already exists */
2646         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
2647         info.FileNameLength = cpu_to_le32(len);
2648
2649         data[0] = &info;
2650         size[0] = sizeof(struct smb2_file_link_info);
2651
2652         data[1] = target_file;
2653         size[1] = len + 2 /* null */;
2654
2655         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2656                            current->tgid, FILE_LINK_INFORMATION, 2, data, size);
2657         kfree(data);
2658         return rc;
2659 }
2660
2661 int
2662 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2663              u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
2664 {
2665         struct smb2_file_eof_info info;
2666         void *data;
2667         unsigned int size;
2668
2669         info.EndOfFile = *eof;
2670
2671         data = &info;
2672         size = sizeof(struct smb2_file_eof_info);
2673
2674         if (is_falloc)
2675                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2676                         pid, FILE_ALLOCATION_INFORMATION, 1, &data, &size);
2677         else
2678                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2679                         pid, FILE_END_OF_FILE_INFORMATION, 1, &data, &size);
2680 }
2681
2682 int
2683 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2684               u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
2685 {
2686         unsigned int size;
2687         size = sizeof(FILE_BASIC_INFO);
2688         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2689                              current->tgid, FILE_BASIC_INFORMATION, 1,
2690                              (void **)&buf, &size);
2691 }
2692
2693 int
2694 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
2695                   const u64 persistent_fid, const u64 volatile_fid,
2696                   __u8 oplock_level)
2697 {
2698         int rc;
2699         struct smb2_oplock_break *req = NULL;
2700
2701         cifs_dbg(FYI, "SMB2_oplock_break\n");
2702         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
2703
2704         if (rc)
2705                 return rc;
2706
2707         req->VolatileFid = volatile_fid;
2708         req->PersistentFid = persistent_fid;
2709         req->OplockLevel = oplock_level;
2710         req->hdr.CreditRequest = cpu_to_le16(1);
2711
2712         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
2713         /* SMB2 buffer freed by function above */
2714
2715         if (rc) {
2716                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
2717                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
2718         }
2719
2720         return rc;
2721 }
2722
2723 static void
2724 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
2725                         struct kstatfs *kst)
2726 {
2727         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
2728                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
2729         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
2730         kst->f_bfree  = le64_to_cpu(pfs_inf->ActualAvailableAllocationUnits);
2731         kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
2732         return;
2733 }
2734
2735 static int
2736 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
2737                    int outbuf_len, u64 persistent_fid, u64 volatile_fid)
2738 {
2739         int rc;
2740         struct smb2_query_info_req *req;
2741
2742         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
2743
2744         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
2745                 return -EIO;
2746
2747         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
2748         if (rc)
2749                 return rc;
2750
2751         req->InfoType = SMB2_O_INFO_FILESYSTEM;
2752         req->FileInfoClass = level;
2753         req->PersistentFileId = persistent_fid;
2754         req->VolatileFileId = volatile_fid;
2755         /* 4 for rfc1002 length field and 1 for pad */
2756         req->InputBufferOffset =
2757                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
2758         req->OutputBufferLength = cpu_to_le32(
2759                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
2760
2761         iov->iov_base = (char *)req;
2762         /* 4 for rfc1002 length field */
2763         iov->iov_len = get_rfc1002_length(req) + 4;
2764         return 0;
2765 }
2766
2767 int
2768 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
2769               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
2770 {
2771         struct smb2_query_info_rsp *rsp = NULL;
2772         struct kvec iov;
2773         int rc = 0;
2774         int resp_buftype;
2775         struct cifs_ses *ses = tcon->ses;
2776         struct smb2_fs_full_size_info *info = NULL;
2777
2778         rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
2779                                 sizeof(struct smb2_fs_full_size_info),
2780                                 persistent_fid, volatile_fid);
2781         if (rc)
2782                 return rc;
2783
2784         rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, 0);
2785         if (rc) {
2786                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2787                 goto qfsinf_exit;
2788         }
2789         rsp = (struct smb2_query_info_rsp *)iov.iov_base;
2790
2791         info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
2792                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
2793         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2794                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2795                           sizeof(struct smb2_fs_full_size_info));
2796         if (!rc)
2797                 copy_fs_info_to_kstatfs(info, fsdata);
2798
2799 qfsinf_exit:
2800         free_rsp_buf(resp_buftype, iov.iov_base);
2801         return rc;
2802 }
2803
2804 int
2805 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
2806               u64 persistent_fid, u64 volatile_fid, int level)
2807 {
2808         struct smb2_query_info_rsp *rsp = NULL;
2809         struct kvec iov;
2810         int rc = 0;
2811         int resp_buftype, max_len, min_len;
2812         struct cifs_ses *ses = tcon->ses;
2813         unsigned int rsp_len, offset;
2814
2815         if (level == FS_DEVICE_INFORMATION) {
2816                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
2817                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
2818         } else if (level == FS_ATTRIBUTE_INFORMATION) {
2819                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
2820                 min_len = MIN_FS_ATTR_INFO_SIZE;
2821         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
2822                 max_len = sizeof(struct smb3_fs_ss_info);
2823                 min_len = sizeof(struct smb3_fs_ss_info);
2824         } else {
2825                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
2826                 return -EINVAL;
2827         }
2828
2829         rc = build_qfs_info_req(&iov, tcon, level, max_len,
2830                                 persistent_fid, volatile_fid);
2831         if (rc)
2832                 return rc;
2833
2834         rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, 0);
2835         if (rc) {
2836                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2837                 goto qfsattr_exit;
2838         }
2839         rsp = (struct smb2_query_info_rsp *)iov.iov_base;
2840
2841         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
2842         offset = le16_to_cpu(rsp->OutputBufferOffset);
2843         rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
2844         if (rc)
2845                 goto qfsattr_exit;
2846
2847         if (level == FS_ATTRIBUTE_INFORMATION)
2848                 memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
2849                         + (char *)&rsp->hdr, min_t(unsigned int,
2850                         rsp_len, max_len));
2851         else if (level == FS_DEVICE_INFORMATION)
2852                 memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
2853                         + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
2854         else if (level == FS_SECTOR_SIZE_INFORMATION) {
2855                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
2856                         (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
2857                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
2858                 tcon->perf_sector_size =
2859                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
2860         }
2861
2862 qfsattr_exit:
2863         free_rsp_buf(resp_buftype, iov.iov_base);
2864         return rc;
2865 }
2866
2867 int
2868 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
2869            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2870            const __u32 num_lock, struct smb2_lock_element *buf)
2871 {
2872         int rc = 0;
2873         struct smb2_lock_req *req = NULL;
2874         struct kvec iov[2];
2875         int resp_buf_type;
2876         unsigned int count;
2877
2878         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
2879
2880         rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
2881         if (rc)
2882                 return rc;
2883
2884         req->hdr.ProcessId = cpu_to_le32(pid);
2885         req->LockCount = cpu_to_le16(num_lock);
2886
2887         req->PersistentFileId = persist_fid;
2888         req->VolatileFileId = volatile_fid;
2889
2890         count = num_lock * sizeof(struct smb2_lock_element);
2891         inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
2892
2893         iov[0].iov_base = (char *)req;
2894         /* 4 for rfc1002 length field and count for all locks */
2895         iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
2896         iov[1].iov_base = (char *)buf;
2897         iov[1].iov_len = count;
2898
2899         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
2900         rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, CIFS_NO_RESP);
2901         if (rc) {
2902                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
2903                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
2904         }
2905
2906         return rc;
2907 }
2908
2909 int
2910 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
2911           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2912           const __u64 length, const __u64 offset, const __u32 lock_flags,
2913           const bool wait)
2914 {
2915         struct smb2_lock_element lock;
2916
2917         lock.Offset = cpu_to_le64(offset);
2918         lock.Length = cpu_to_le64(length);
2919         lock.Flags = cpu_to_le32(lock_flags);
2920         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
2921                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
2922
2923         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
2924 }
2925
2926 int
2927 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
2928                  __u8 *lease_key, const __le32 lease_state)
2929 {
2930         int rc;
2931         struct smb2_lease_ack *req = NULL;
2932
2933         cifs_dbg(FYI, "SMB2_lease_break\n");
2934         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
2935
2936         if (rc)
2937                 return rc;
2938
2939         req->hdr.CreditRequest = cpu_to_le16(1);
2940         req->StructureSize = cpu_to_le16(36);
2941         inc_rfc1001_len(req, 12);
2942
2943         memcpy(req->LeaseKey, lease_key, 16);
2944         req->LeaseState = lease_state;
2945
2946         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
2947         /* SMB2 buffer freed by function above */
2948
2949         if (rc) {
2950                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
2951                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
2952         }
2953
2954         return rc;
2955 }