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