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