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