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