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