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