OSDN Git Service

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