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