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