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