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