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