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