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