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