727f16b426be5c718a3209fbc6f22c589195e5ab
[platform/kernel/linux-starfive.git] / fs / cifs / smb2pdu.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
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  */
12
13  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
14  /* Note that there are handle based routines which must be                   */
15  /* treated slightly differently for reconnection purposes since we never     */
16  /* want to reuse a stale file handle and only the caller knows the file info */
17
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/vfs.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/uaccess.h>
23 #include <linux/uuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/xattr.h>
26 #include "cifsglob.h"
27 #include "cifsacl.h"
28 #include "cifsproto.h"
29 #include "smb2proto.h"
30 #include "cifs_unicode.h"
31 #include "cifs_debug.h"
32 #include "ntlmssp.h"
33 #include "smb2status.h"
34 #include "smb2glob.h"
35 #include "cifspdu.h"
36 #include "cifs_spnego.h"
37 #include "smbdirect.h"
38 #include "trace.h"
39 #ifdef CONFIG_CIFS_DFS_UPCALL
40 #include "dfs_cache.h"
41 #endif
42 #include "cached_dir.h"
43
44 /*
45  *  The following table defines the expected "StructureSize" of SMB2 requests
46  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
47  *
48  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
49  *  indexed by command in host byte order.
50  */
51 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
52         /* SMB2_NEGOTIATE */ 36,
53         /* SMB2_SESSION_SETUP */ 25,
54         /* SMB2_LOGOFF */ 4,
55         /* SMB2_TREE_CONNECT */ 9,
56         /* SMB2_TREE_DISCONNECT */ 4,
57         /* SMB2_CREATE */ 57,
58         /* SMB2_CLOSE */ 24,
59         /* SMB2_FLUSH */ 24,
60         /* SMB2_READ */ 49,
61         /* SMB2_WRITE */ 49,
62         /* SMB2_LOCK */ 48,
63         /* SMB2_IOCTL */ 57,
64         /* SMB2_CANCEL */ 4,
65         /* SMB2_ECHO */ 4,
66         /* SMB2_QUERY_DIRECTORY */ 33,
67         /* SMB2_CHANGE_NOTIFY */ 32,
68         /* SMB2_QUERY_INFO */ 41,
69         /* SMB2_SET_INFO */ 33,
70         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
71 };
72
73 int smb3_encryption_required(const struct cifs_tcon *tcon)
74 {
75         if (!tcon || !tcon->ses)
76                 return 0;
77         if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
78             (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
79                 return 1;
80         if (tcon->seal &&
81             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
82                 return 1;
83         return 0;
84 }
85
86 static void
87 smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
88                   const struct cifs_tcon *tcon,
89                   struct TCP_Server_Info *server)
90 {
91         shdr->ProtocolId = SMB2_PROTO_NUMBER;
92         shdr->StructureSize = cpu_to_le16(64);
93         shdr->Command = smb2_cmd;
94         if (server) {
95                 spin_lock(&server->req_lock);
96                 /* Request up to 10 credits but don't go over the limit. */
97                 if (server->credits >= server->max_credits)
98                         shdr->CreditRequest = cpu_to_le16(0);
99                 else
100                         shdr->CreditRequest = cpu_to_le16(
101                                 min_t(int, server->max_credits -
102                                                 server->credits, 10));
103                 spin_unlock(&server->req_lock);
104         } else {
105                 shdr->CreditRequest = cpu_to_le16(2);
106         }
107         shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
108
109         if (!tcon)
110                 goto out;
111
112         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
113         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
114         if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
115                 shdr->CreditCharge = cpu_to_le16(1);
116         /* else CreditCharge MBZ */
117
118         shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
119         /* Uid is not converted */
120         if (tcon->ses)
121                 shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
122
123         /*
124          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
125          * to pass the path on the Open SMB prefixed by \\server\share.
126          * Not sure when we would need to do the augmented path (if ever) and
127          * setting this flag breaks the SMB2 open operation since it is
128          * illegal to send an empty path name (without \\server\share prefix)
129          * when the DFS flag is set in the SMB open header. We could
130          * consider setting the flag on all operations other than open
131          * but it is safer to net set it for now.
132          */
133 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
134                 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
135
136         if (server && server->sign && !smb3_encryption_required(tcon))
137                 shdr->Flags |= SMB2_FLAGS_SIGNED;
138 out:
139         return;
140 }
141
142 static int
143 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
144                struct TCP_Server_Info *server)
145 {
146         int rc = 0;
147         struct nls_table *nls_codepage;
148         struct cifs_ses *ses;
149         int retries;
150
151         /*
152          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
153          * check for tcp and smb session status done differently
154          * for those three - in the calling routine.
155          */
156         if (tcon == NULL)
157                 return 0;
158
159         /*
160          * Need to also skip SMB2_IOCTL because it is used for checking nested dfs links in
161          * cifs_tree_connect().
162          */
163         if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
164                 return 0;
165
166         spin_lock(&tcon->tc_lock);
167         if (tcon->status == TID_EXITING) {
168                 /*
169                  * only tree disconnect, open, and write,
170                  * (and ulogoff which does not have tcon)
171                  * are allowed as we start force umount.
172                  */
173                 if ((smb2_command != SMB2_WRITE) &&
174                    (smb2_command != SMB2_CREATE) &&
175                    (smb2_command != SMB2_TREE_DISCONNECT)) {
176                         spin_unlock(&tcon->tc_lock);
177                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
178                                  smb2_command);
179                         return -ENODEV;
180                 }
181         }
182         spin_unlock(&tcon->tc_lock);
183         if ((!tcon->ses) || (tcon->ses->ses_status == SES_EXITING) ||
184             (!tcon->ses->server) || !server)
185                 return -EIO;
186
187         ses = tcon->ses;
188         retries = server->nr_targets;
189
190         /*
191          * Give demultiplex thread up to 10 seconds to each target available for
192          * reconnect -- should be greater than cifs socket timeout which is 7
193          * seconds.
194          */
195         while (server->tcpStatus == CifsNeedReconnect) {
196                 /*
197                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
198                  * here since they are implicitly done when session drops.
199                  */
200                 switch (smb2_command) {
201                 /*
202                  * BB Should we keep oplock break and add flush to exceptions?
203                  */
204                 case SMB2_TREE_DISCONNECT:
205                 case SMB2_CANCEL:
206                 case SMB2_CLOSE:
207                 case SMB2_OPLOCK_BREAK:
208                         return -EAGAIN;
209                 }
210
211                 rc = wait_event_interruptible_timeout(server->response_q,
212                                                       (server->tcpStatus != CifsNeedReconnect),
213                                                       10 * HZ);
214                 if (rc < 0) {
215                         cifs_dbg(FYI, "%s: aborting reconnect due to a received signal by the process\n",
216                                  __func__);
217                         return -ERESTARTSYS;
218                 }
219
220                 /* are we still trying to reconnect? */
221                 spin_lock(&server->srv_lock);
222                 if (server->tcpStatus != CifsNeedReconnect) {
223                         spin_unlock(&server->srv_lock);
224                         break;
225                 }
226                 spin_unlock(&server->srv_lock);
227
228                 if (retries && --retries)
229                         continue;
230
231                 /*
232                  * on "soft" mounts we wait once. Hard mounts keep
233                  * retrying until process is killed or server comes
234                  * back on-line
235                  */
236                 if (!tcon->retry) {
237                         cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
238                         return -EHOSTDOWN;
239                 }
240                 retries = server->nr_targets;
241         }
242
243         spin_lock(&ses->chan_lock);
244         if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
245                 spin_unlock(&ses->chan_lock);
246                 return 0;
247         }
248         spin_unlock(&ses->chan_lock);
249         cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
250                  tcon->ses->chans_need_reconnect,
251                  tcon->need_reconnect);
252
253         nls_codepage = load_nls_default();
254
255         /*
256          * Recheck after acquire mutex. If another thread is negotiating
257          * and the server never sends an answer the socket will be closed
258          * and tcpStatus set to reconnect.
259          */
260         spin_lock(&server->srv_lock);
261         if (server->tcpStatus == CifsNeedReconnect) {
262                 spin_unlock(&server->srv_lock);
263                 rc = -EHOSTDOWN;
264                 goto out;
265         }
266         spin_unlock(&server->srv_lock);
267
268         /*
269          * need to prevent multiple threads trying to simultaneously
270          * reconnect the same SMB session
271          */
272         spin_lock(&ses->chan_lock);
273         if (!cifs_chan_needs_reconnect(ses, server)) {
274                 spin_unlock(&ses->chan_lock);
275
276                 /* this means that we only need to tree connect */
277                 if (tcon->need_reconnect)
278                         goto skip_sess_setup;
279
280                 goto out;
281         }
282         spin_unlock(&ses->chan_lock);
283
284         mutex_lock(&ses->session_mutex);
285         rc = cifs_negotiate_protocol(0, ses, server);
286         if (!rc) {
287                 rc = cifs_setup_session(0, ses, server, nls_codepage);
288                 if ((rc == -EACCES) && !tcon->retry) {
289                         mutex_unlock(&ses->session_mutex);
290                         rc = -EHOSTDOWN;
291                         goto failed;
292                 } else if (rc) {
293                         mutex_unlock(&ses->session_mutex);
294                         goto out;
295                 }
296         } else {
297                 mutex_unlock(&ses->session_mutex);
298                 goto out;
299         }
300         mutex_unlock(&ses->session_mutex);
301
302 skip_sess_setup:
303         mutex_lock(&ses->session_mutex);
304         if (!tcon->need_reconnect) {
305                 mutex_unlock(&ses->session_mutex);
306                 goto out;
307         }
308         cifs_mark_open_files_invalid(tcon);
309         if (tcon->use_persistent)
310                 tcon->need_reopen_files = true;
311
312         rc = cifs_tree_connect(0, tcon, nls_codepage);
313         mutex_unlock(&ses->session_mutex);
314
315         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
316         if (rc) {
317                 /* If sess reconnected but tcon didn't, something strange ... */
318                 pr_warn_once("reconnect tcon failed rc = %d\n", rc);
319                 goto out;
320         }
321
322         if (smb2_command != SMB2_INTERNAL_CMD)
323                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
324
325         atomic_inc(&tconInfoReconnectCount);
326 out:
327         /*
328          * Check if handle based operation so we know whether we can continue
329          * or not without returning to caller to reset file handle.
330          */
331         /*
332          * BB Is flush done by server on drop of tcp session? Should we special
333          * case it and skip above?
334          */
335         switch (smb2_command) {
336         case SMB2_FLUSH:
337         case SMB2_READ:
338         case SMB2_WRITE:
339         case SMB2_LOCK:
340         case SMB2_IOCTL:
341         case SMB2_QUERY_DIRECTORY:
342         case SMB2_CHANGE_NOTIFY:
343         case SMB2_QUERY_INFO:
344         case SMB2_SET_INFO:
345                 rc = -EAGAIN;
346         }
347 failed:
348         unload_nls(nls_codepage);
349         return rc;
350 }
351
352 static void
353 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
354                struct TCP_Server_Info *server,
355                void *buf,
356                unsigned int *total_len)
357 {
358         struct smb2_pdu *spdu = buf;
359         /* lookup word count ie StructureSize from table */
360         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
361
362         /*
363          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
364          * largest operations (Create)
365          */
366         memset(buf, 0, 256);
367
368         smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
369         spdu->StructureSize2 = cpu_to_le16(parmsize);
370
371         *total_len = parmsize + sizeof(struct smb2_hdr);
372 }
373
374 /*
375  * Allocate and return pointer to an SMB request hdr, and set basic
376  * SMB information in the SMB header. If the return code is zero, this
377  * function must have filled in request_buf pointer.
378  */
379 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
380                                  struct TCP_Server_Info *server,
381                                  void **request_buf, unsigned int *total_len)
382 {
383         /* BB eventually switch this to SMB2 specific small buf size */
384         if (smb2_command == SMB2_SET_INFO)
385                 *request_buf = cifs_buf_get();
386         else
387                 *request_buf = cifs_small_buf_get();
388         if (*request_buf == NULL) {
389                 /* BB should we add a retry in here if not a writepage? */
390                 return -ENOMEM;
391         }
392
393         fill_small_buf(smb2_command, tcon, server,
394                        (struct smb2_hdr *)(*request_buf),
395                        total_len);
396
397         if (tcon != NULL) {
398                 uint16_t com_code = le16_to_cpu(smb2_command);
399                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
400                 cifs_stats_inc(&tcon->num_smbs_sent);
401         }
402
403         return 0;
404 }
405
406 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
407                                struct TCP_Server_Info *server,
408                                void **request_buf, unsigned int *total_len)
409 {
410         int rc;
411
412         rc = smb2_reconnect(smb2_command, tcon, server);
413         if (rc)
414                 return rc;
415
416         return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
417                                      total_len);
418 }
419
420 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
421                                struct TCP_Server_Info *server,
422                                void **request_buf, unsigned int *total_len)
423 {
424         /* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
425         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
426                 return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
427                                              request_buf, total_len);
428         }
429         return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
430                                    request_buf, total_len);
431 }
432
433 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
434
435 static void
436 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
437 {
438         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
439         pneg_ctxt->DataLength = cpu_to_le16(38);
440         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
441         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
442         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
443         pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
444 }
445
446 static void
447 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
448 {
449         pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
450         pneg_ctxt->DataLength =
451                 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
452                           - sizeof(struct smb2_neg_context));
453         pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
454         pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
455         pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
456         pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
457 }
458
459 static unsigned int
460 build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
461 {
462         unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
463         unsigned short num_algs = 1; /* number of signing algorithms sent */
464
465         pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
466         /*
467          * Context Data length must be rounded to multiple of 8 for some servers
468          */
469         pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
470                                             sizeof(struct smb2_neg_context) +
471                                             (num_algs * sizeof(u16)), 8));
472         pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
473         pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);
474
475         ctxt_len += sizeof(__le16) * num_algs;
476         ctxt_len = ALIGN(ctxt_len, 8);
477         return ctxt_len;
478         /* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
479 }
480
481 static void
482 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
483 {
484         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
485         if (require_gcm_256) {
486                 pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
487                 pneg_ctxt->CipherCount = cpu_to_le16(1);
488                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
489         } else if (enable_gcm_256) {
490                 pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
491                 pneg_ctxt->CipherCount = cpu_to_le16(3);
492                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
493                 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
494                 pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
495         } else {
496                 pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
497                 pneg_ctxt->CipherCount = cpu_to_le16(2);
498                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
499                 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
500         }
501 }
502
503 static unsigned int
504 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
505 {
506         struct nls_table *cp = load_nls_default();
507
508         pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
509
510         /* copy up to max of first 100 bytes of server name to NetName field */
511         pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
512         /* context size is DataLength + minimal smb2_neg_context */
513         return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
514 }
515
516 static void
517 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
518 {
519         pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
520         pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
521         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
522         pneg_ctxt->Name[0] = 0x93;
523         pneg_ctxt->Name[1] = 0xAD;
524         pneg_ctxt->Name[2] = 0x25;
525         pneg_ctxt->Name[3] = 0x50;
526         pneg_ctxt->Name[4] = 0x9C;
527         pneg_ctxt->Name[5] = 0xB4;
528         pneg_ctxt->Name[6] = 0x11;
529         pneg_ctxt->Name[7] = 0xE7;
530         pneg_ctxt->Name[8] = 0xB4;
531         pneg_ctxt->Name[9] = 0x23;
532         pneg_ctxt->Name[10] = 0x83;
533         pneg_ctxt->Name[11] = 0xDE;
534         pneg_ctxt->Name[12] = 0x96;
535         pneg_ctxt->Name[13] = 0x8B;
536         pneg_ctxt->Name[14] = 0xCD;
537         pneg_ctxt->Name[15] = 0x7C;
538 }
539
540 static void
541 assemble_neg_contexts(struct smb2_negotiate_req *req,
542                       struct TCP_Server_Info *server, unsigned int *total_len)
543 {
544         unsigned int ctxt_len, neg_context_count;
545         struct TCP_Server_Info *pserver;
546         char *pneg_ctxt;
547         char *hostname;
548
549         if (*total_len > 200) {
550                 /* In case length corrupted don't want to overrun smb buffer */
551                 cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
552                 return;
553         }
554
555         /*
556          * round up total_len of fixed part of SMB3 negotiate request to 8
557          * byte boundary before adding negotiate contexts
558          */
559         *total_len = ALIGN(*total_len, 8);
560
561         pneg_ctxt = (*total_len) + (char *)req;
562         req->NegotiateContextOffset = cpu_to_le32(*total_len);
563
564         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
565         ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
566         *total_len += ctxt_len;
567         pneg_ctxt += ctxt_len;
568
569         build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
570         ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
571         *total_len += ctxt_len;
572         pneg_ctxt += ctxt_len;
573
574         /*
575          * secondary channels don't have the hostname field populated
576          * use the hostname field in the primary channel instead
577          */
578         pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
579         cifs_server_lock(pserver);
580         hostname = pserver->hostname;
581         if (hostname && (hostname[0] != 0)) {
582                 ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
583                                               hostname);
584                 *total_len += ctxt_len;
585                 pneg_ctxt += ctxt_len;
586                 neg_context_count = 3;
587         } else
588                 neg_context_count = 2;
589         cifs_server_unlock(pserver);
590
591         build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
592         *total_len += sizeof(struct smb2_posix_neg_context);
593         pneg_ctxt += sizeof(struct smb2_posix_neg_context);
594         neg_context_count++;
595
596         if (server->compress_algorithm) {
597                 build_compression_ctxt((struct smb2_compression_capabilities_context *)
598                                 pneg_ctxt);
599                 ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
600                 *total_len += ctxt_len;
601                 pneg_ctxt += ctxt_len;
602                 neg_context_count++;
603         }
604
605         if (enable_negotiate_signing) {
606                 ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
607                                 pneg_ctxt);
608                 *total_len += ctxt_len;
609                 pneg_ctxt += ctxt_len;
610                 neg_context_count++;
611         }
612
613         /* check for and add transport_capabilities and signing capabilities */
614         req->NegotiateContextCount = cpu_to_le16(neg_context_count);
615
616 }
617
618 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
619 {
620         unsigned int len = le16_to_cpu(ctxt->DataLength);
621
622         /* If invalid preauth context warn but use what we requested, SHA-512 */
623         if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
624                 pr_warn_once("server sent bad preauth context\n");
625                 return;
626         } else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
627                 pr_warn_once("server sent invalid SaltLength\n");
628                 return;
629         }
630         if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
631                 pr_warn_once("Invalid SMB3 hash algorithm count\n");
632         if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
633                 pr_warn_once("unknown SMB3 hash algorithm\n");
634 }
635
636 static void decode_compress_ctx(struct TCP_Server_Info *server,
637                          struct smb2_compression_capabilities_context *ctxt)
638 {
639         unsigned int len = le16_to_cpu(ctxt->DataLength);
640
641         /* sizeof compress context is a one element compression capbility struct */
642         if (len < 10) {
643                 pr_warn_once("server sent bad compression cntxt\n");
644                 return;
645         }
646         if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
647                 pr_warn_once("Invalid SMB3 compress algorithm count\n");
648                 return;
649         }
650         if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
651                 pr_warn_once("unknown compression algorithm\n");
652                 return;
653         }
654         server->compress_algorithm = ctxt->CompressionAlgorithms[0];
655 }
656
657 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
658                               struct smb2_encryption_neg_context *ctxt)
659 {
660         unsigned int len = le16_to_cpu(ctxt->DataLength);
661
662         cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
663         if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
664                 pr_warn_once("server sent bad crypto ctxt len\n");
665                 return -EINVAL;
666         }
667
668         if (le16_to_cpu(ctxt->CipherCount) != 1) {
669                 pr_warn_once("Invalid SMB3.11 cipher count\n");
670                 return -EINVAL;
671         }
672         cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
673         if (require_gcm_256) {
674                 if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
675                         cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
676                         return -EOPNOTSUPP;
677                 }
678         } else if (ctxt->Ciphers[0] == 0) {
679                 /*
680                  * e.g. if server only supported AES256_CCM (very unlikely)
681                  * or server supported no encryption types or had all disabled.
682                  * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
683                  * in which mount requested encryption ("seal") checks later
684                  * on during tree connection will return proper rc, but if
685                  * seal not requested by client, since server is allowed to
686                  * return 0 to indicate no supported cipher, we can't fail here
687                  */
688                 server->cipher_type = 0;
689                 server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
690                 pr_warn_once("Server does not support requested encryption types\n");
691                 return 0;
692         } else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
693                    (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
694                    (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
695                 /* server returned a cipher we didn't ask for */
696                 pr_warn_once("Invalid SMB3.11 cipher returned\n");
697                 return -EINVAL;
698         }
699         server->cipher_type = ctxt->Ciphers[0];
700         server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
701         return 0;
702 }
703
704 static void decode_signing_ctx(struct TCP_Server_Info *server,
705                                struct smb2_signing_capabilities *pctxt)
706 {
707         unsigned int len = le16_to_cpu(pctxt->DataLength);
708
709         if ((len < 4) || (len > 16)) {
710                 pr_warn_once("server sent bad signing negcontext\n");
711                 return;
712         }
713         if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
714                 pr_warn_once("Invalid signing algorithm count\n");
715                 return;
716         }
717         if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
718                 pr_warn_once("unknown signing algorithm\n");
719                 return;
720         }
721
722         server->signing_negotiated = true;
723         server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
724         cifs_dbg(FYI, "signing algorithm %d chosen\n",
725                      server->signing_algorithm);
726 }
727
728
729 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
730                                      struct TCP_Server_Info *server,
731                                      unsigned int len_of_smb)
732 {
733         struct smb2_neg_context *pctx;
734         unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
735         unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
736         unsigned int len_of_ctxts, i;
737         int rc = 0;
738
739         cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
740         if (len_of_smb <= offset) {
741                 cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
742                 return -EINVAL;
743         }
744
745         len_of_ctxts = len_of_smb - offset;
746
747         for (i = 0; i < ctxt_cnt; i++) {
748                 int clen;
749                 /* check that offset is not beyond end of SMB */
750                 if (len_of_ctxts == 0)
751                         break;
752
753                 if (len_of_ctxts < sizeof(struct smb2_neg_context))
754                         break;
755
756                 pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
757                 clen = le16_to_cpu(pctx->DataLength);
758                 if (clen > len_of_ctxts)
759                         break;
760
761                 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
762                         decode_preauth_context(
763                                 (struct smb2_preauth_neg_context *)pctx);
764                 else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
765                         rc = decode_encrypt_ctx(server,
766                                 (struct smb2_encryption_neg_context *)pctx);
767                 else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
768                         decode_compress_ctx(server,
769                                 (struct smb2_compression_capabilities_context *)pctx);
770                 else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
771                         server->posix_ext_supported = true;
772                 else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
773                         decode_signing_ctx(server,
774                                 (struct smb2_signing_capabilities *)pctx);
775                 else
776                         cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
777                                 le16_to_cpu(pctx->ContextType));
778
779                 if (rc)
780                         break;
781                 /* offsets must be 8 byte aligned */
782                 clen = ALIGN(clen, 8);
783                 offset += clen + sizeof(struct smb2_neg_context);
784                 len_of_ctxts -= clen;
785         }
786         return rc;
787 }
788
789 static struct create_posix *
790 create_posix_buf(umode_t mode)
791 {
792         struct create_posix *buf;
793
794         buf = kzalloc(sizeof(struct create_posix),
795                         GFP_KERNEL);
796         if (!buf)
797                 return NULL;
798
799         buf->ccontext.DataOffset =
800                 cpu_to_le16(offsetof(struct create_posix, Mode));
801         buf->ccontext.DataLength = cpu_to_le32(4);
802         buf->ccontext.NameOffset =
803                 cpu_to_le16(offsetof(struct create_posix, Name));
804         buf->ccontext.NameLength = cpu_to_le16(16);
805
806         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
807         buf->Name[0] = 0x93;
808         buf->Name[1] = 0xAD;
809         buf->Name[2] = 0x25;
810         buf->Name[3] = 0x50;
811         buf->Name[4] = 0x9C;
812         buf->Name[5] = 0xB4;
813         buf->Name[6] = 0x11;
814         buf->Name[7] = 0xE7;
815         buf->Name[8] = 0xB4;
816         buf->Name[9] = 0x23;
817         buf->Name[10] = 0x83;
818         buf->Name[11] = 0xDE;
819         buf->Name[12] = 0x96;
820         buf->Name[13] = 0x8B;
821         buf->Name[14] = 0xCD;
822         buf->Name[15] = 0x7C;
823         buf->Mode = cpu_to_le32(mode);
824         cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
825         return buf;
826 }
827
828 static int
829 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
830 {
831         struct smb2_create_req *req = iov[0].iov_base;
832         unsigned int num = *num_iovec;
833
834         iov[num].iov_base = create_posix_buf(mode);
835         if (mode == ACL_NO_MODE)
836                 cifs_dbg(FYI, "Invalid mode\n");
837         if (iov[num].iov_base == NULL)
838                 return -ENOMEM;
839         iov[num].iov_len = sizeof(struct create_posix);
840         if (!req->CreateContextsOffset)
841                 req->CreateContextsOffset = cpu_to_le32(
842                                 sizeof(struct smb2_create_req) +
843                                 iov[num - 1].iov_len);
844         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix));
845         *num_iovec = num + 1;
846         return 0;
847 }
848
849
850 /*
851  *
852  *      SMB2 Worker functions follow:
853  *
854  *      The general structure of the worker functions is:
855  *      1) Call smb2_init (assembles SMB2 header)
856  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
857  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
858  *      4) Decode SMB2 command specific fields in the fixed length area
859  *      5) Decode variable length data area (if any for this SMB2 command type)
860  *      6) Call free smb buffer
861  *      7) return
862  *
863  */
864
865 int
866 SMB2_negotiate(const unsigned int xid,
867                struct cifs_ses *ses,
868                struct TCP_Server_Info *server)
869 {
870         struct smb_rqst rqst;
871         struct smb2_negotiate_req *req;
872         struct smb2_negotiate_rsp *rsp;
873         struct kvec iov[1];
874         struct kvec rsp_iov;
875         int rc;
876         int resp_buftype;
877         int blob_offset, blob_length;
878         char *security_blob;
879         int flags = CIFS_NEG_OP;
880         unsigned int total_len;
881
882         cifs_dbg(FYI, "Negotiate protocol\n");
883
884         if (!server) {
885                 WARN(1, "%s: server is NULL!\n", __func__);
886                 return -EIO;
887         }
888
889         rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
890                                  (void **) &req, &total_len);
891         if (rc)
892                 return rc;
893
894         req->hdr.SessionId = 0;
895
896         memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
897         memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
898
899         if (strcmp(server->vals->version_string,
900                    SMB3ANY_VERSION_STRING) == 0) {
901                 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
902                 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
903                 req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
904                 req->DialectCount = cpu_to_le16(3);
905                 total_len += 6;
906         } else if (strcmp(server->vals->version_string,
907                    SMBDEFAULT_VERSION_STRING) == 0) {
908                 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
909                 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
910                 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
911                 req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
912                 req->DialectCount = cpu_to_le16(4);
913                 total_len += 8;
914         } else {
915                 /* otherwise send specific dialect */
916                 req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
917                 req->DialectCount = cpu_to_le16(1);
918                 total_len += 2;
919         }
920
921         /* only one of SMB2 signing flags may be set in SMB2 request */
922         if (ses->sign)
923                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
924         else if (global_secflags & CIFSSEC_MAY_SIGN)
925                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
926         else
927                 req->SecurityMode = 0;
928
929         req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
930         if (ses->chan_max > 1)
931                 req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
932
933         /* ClientGUID must be zero for SMB2.02 dialect */
934         if (server->vals->protocol_id == SMB20_PROT_ID)
935                 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
936         else {
937                 memcpy(req->ClientGUID, server->client_guid,
938                         SMB2_CLIENT_GUID_SIZE);
939                 if ((server->vals->protocol_id == SMB311_PROT_ID) ||
940                     (strcmp(server->vals->version_string,
941                      SMB3ANY_VERSION_STRING) == 0) ||
942                     (strcmp(server->vals->version_string,
943                      SMBDEFAULT_VERSION_STRING) == 0))
944                         assemble_neg_contexts(req, server, &total_len);
945         }
946         iov[0].iov_base = (char *)req;
947         iov[0].iov_len = total_len;
948
949         memset(&rqst, 0, sizeof(struct smb_rqst));
950         rqst.rq_iov = iov;
951         rqst.rq_nvec = 1;
952
953         rc = cifs_send_recv(xid, ses, server,
954                             &rqst, &resp_buftype, flags, &rsp_iov);
955         cifs_small_buf_release(req);
956         rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
957         /*
958          * No tcon so can't do
959          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
960          */
961         if (rc == -EOPNOTSUPP) {
962                 cifs_server_dbg(VFS, "Dialect not supported by server. Consider  specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
963                 goto neg_exit;
964         } else if (rc != 0)
965                 goto neg_exit;
966
967         rc = -EIO;
968         if (strcmp(server->vals->version_string,
969                    SMB3ANY_VERSION_STRING) == 0) {
970                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
971                         cifs_server_dbg(VFS,
972                                 "SMB2 dialect returned but not requested\n");
973                         goto neg_exit;
974                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
975                         cifs_server_dbg(VFS,
976                                 "SMB2.1 dialect returned but not requested\n");
977                         goto neg_exit;
978                 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
979                         /* ops set to 3.0 by default for default so update */
980                         server->ops = &smb311_operations;
981                         server->vals = &smb311_values;
982                 }
983         } else if (strcmp(server->vals->version_string,
984                    SMBDEFAULT_VERSION_STRING) == 0) {
985                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
986                         cifs_server_dbg(VFS,
987                                 "SMB2 dialect returned but not requested\n");
988                         goto neg_exit;
989                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
990                         /* ops set to 3.0 by default for default so update */
991                         server->ops = &smb21_operations;
992                         server->vals = &smb21_values;
993                 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
994                         server->ops = &smb311_operations;
995                         server->vals = &smb311_values;
996                 }
997         } else if (le16_to_cpu(rsp->DialectRevision) !=
998                                 server->vals->protocol_id) {
999                 /* if requested single dialect ensure returned dialect matched */
1000                 cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
1001                                 le16_to_cpu(rsp->DialectRevision));
1002                 goto neg_exit;
1003         }
1004
1005         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1006
1007         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1008                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1009         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1010                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1011         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1012                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
1013         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
1014                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1015         else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
1016                 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1017         else {
1018                 cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
1019                                 le16_to_cpu(rsp->DialectRevision));
1020                 goto neg_exit;
1021         }
1022
1023         rc = 0;
1024         server->dialect = le16_to_cpu(rsp->DialectRevision);
1025
1026         /*
1027          * Keep a copy of the hash after negprot. This hash will be
1028          * the starting hash value for all sessions made from this
1029          * server.
1030          */
1031         memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
1032                SMB2_PREAUTH_HASH_SIZE);
1033
1034         /* SMB2 only has an extended negflavor */
1035         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1036         /* set it to the maximum buffer size value we can send with 1 credit */
1037         server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
1038                                SMB2_MAX_BUFFER_SIZE);
1039         server->max_read = le32_to_cpu(rsp->MaxReadSize);
1040         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
1041         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1042         if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
1043                 cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
1044                                 server->sec_mode);
1045         server->capabilities = le32_to_cpu(rsp->Capabilities);
1046         /* Internal types */
1047         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1048
1049         /*
1050          * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
1051          * Set the cipher type manually.
1052          */
1053         if (server->dialect == SMB30_PROT_ID && (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1054                 server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
1055
1056         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1057                                                (struct smb2_hdr *)rsp);
1058         /*
1059          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
1060          * for us will be
1061          *      ses->sectype = RawNTLMSSP;
1062          * but for time being this is our only auth choice so doesn't matter.
1063          * We just found a server which sets blob length to zero expecting raw.
1064          */
1065         if (blob_length == 0) {
1066                 cifs_dbg(FYI, "missing security blob on negprot\n");
1067                 server->sec_ntlmssp = true;
1068         }
1069
1070         rc = cifs_enable_signing(server, ses->sign);
1071         if (rc)
1072                 goto neg_exit;
1073         if (blob_length) {
1074                 rc = decode_negTokenInit(security_blob, blob_length, server);
1075                 if (rc == 1)
1076                         rc = 0;
1077                 else if (rc == 0)
1078                         rc = -EIO;
1079         }
1080
1081         if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1082                 if (rsp->NegotiateContextCount)
1083                         rc = smb311_decode_neg_context(rsp, server,
1084                                                        rsp_iov.iov_len);
1085                 else
1086                         cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1087         }
1088 neg_exit:
1089         free_rsp_buf(resp_buftype, rsp);
1090         return rc;
1091 }
1092
1093 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1094 {
1095         int rc;
1096         struct validate_negotiate_info_req *pneg_inbuf;
1097         struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1098         u32 rsplen;
1099         u32 inbuflen; /* max of 4 dialects */
1100         struct TCP_Server_Info *server = tcon->ses->server;
1101
1102         cifs_dbg(FYI, "validate negotiate\n");
1103
1104         /* In SMB3.11 preauth integrity supersedes validate negotiate */
1105         if (server->dialect == SMB311_PROT_ID)
1106                 return 0;
1107
1108         /*
1109          * validation ioctl must be signed, so no point sending this if we
1110          * can not sign it (ie are not known user).  Even if signing is not
1111          * required (enabled but not negotiated), in those cases we selectively
1112          * sign just this, the first and only signed request on a connection.
1113          * Having validation of negotiate info  helps reduce attack vectors.
1114          */
1115         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1116                 return 0; /* validation requires signing */
1117
1118         if (tcon->ses->user_name == NULL) {
1119                 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1120                 return 0; /* validation requires signing */
1121         }
1122
1123         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1124                 cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1125
1126         pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1127         if (!pneg_inbuf)
1128                 return -ENOMEM;
1129
1130         pneg_inbuf->Capabilities =
1131                         cpu_to_le32(server->vals->req_capabilities);
1132         if (tcon->ses->chan_max > 1)
1133                 pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1134
1135         memcpy(pneg_inbuf->Guid, server->client_guid,
1136                                         SMB2_CLIENT_GUID_SIZE);
1137
1138         if (tcon->ses->sign)
1139                 pneg_inbuf->SecurityMode =
1140                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1141         else if (global_secflags & CIFSSEC_MAY_SIGN)
1142                 pneg_inbuf->SecurityMode =
1143                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1144         else
1145                 pneg_inbuf->SecurityMode = 0;
1146
1147
1148         if (strcmp(server->vals->version_string,
1149                 SMB3ANY_VERSION_STRING) == 0) {
1150                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1151                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1152                 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1153                 pneg_inbuf->DialectCount = cpu_to_le16(3);
1154                 /* SMB 2.1 not included so subtract one dialect from len */
1155                 inbuflen = sizeof(*pneg_inbuf) -
1156                                 (sizeof(pneg_inbuf->Dialects[0]));
1157         } else if (strcmp(server->vals->version_string,
1158                 SMBDEFAULT_VERSION_STRING) == 0) {
1159                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1160                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1161                 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1162                 pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1163                 pneg_inbuf->DialectCount = cpu_to_le16(4);
1164                 /* structure is big enough for 4 dialects */
1165                 inbuflen = sizeof(*pneg_inbuf);
1166         } else {
1167                 /* otherwise specific dialect was requested */
1168                 pneg_inbuf->Dialects[0] =
1169                         cpu_to_le16(server->vals->protocol_id);
1170                 pneg_inbuf->DialectCount = cpu_to_le16(1);
1171                 /* structure is big enough for 4 dialects, sending only 1 */
1172                 inbuflen = sizeof(*pneg_inbuf) -
1173                                 sizeof(pneg_inbuf->Dialects[0]) * 3;
1174         }
1175
1176         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1177                 FSCTL_VALIDATE_NEGOTIATE_INFO,
1178                 (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1179                 (char **)&pneg_rsp, &rsplen);
1180         if (rc == -EOPNOTSUPP) {
1181                 /*
1182                  * Old Windows versions or Netapp SMB server can return
1183                  * not supported error. Client should accept it.
1184                  */
1185                 cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1186                 rc = 0;
1187                 goto out_free_inbuf;
1188         } else if (rc != 0) {
1189                 cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1190                               rc);
1191                 rc = -EIO;
1192                 goto out_free_inbuf;
1193         }
1194
1195         rc = -EIO;
1196         if (rsplen != sizeof(*pneg_rsp)) {
1197                 cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1198                               rsplen);
1199
1200                 /* relax check since Mac returns max bufsize allowed on ioctl */
1201                 if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1202                         goto out_free_rsp;
1203         }
1204
1205         /* check validate negotiate info response matches what we got earlier */
1206         if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1207                 goto vneg_out;
1208
1209         if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1210                 goto vneg_out;
1211
1212         /* do not validate server guid because not saved at negprot time yet */
1213
1214         if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1215               SMB2_LARGE_FILES) != server->capabilities)
1216                 goto vneg_out;
1217
1218         /* validate negotiate successful */
1219         rc = 0;
1220         cifs_dbg(FYI, "validate negotiate info successful\n");
1221         goto out_free_rsp;
1222
1223 vneg_out:
1224         cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1225 out_free_rsp:
1226         kfree(pneg_rsp);
1227 out_free_inbuf:
1228         kfree(pneg_inbuf);
1229         return rc;
1230 }
1231
1232 enum securityEnum
1233 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1234 {
1235         switch (requested) {
1236         case Kerberos:
1237         case RawNTLMSSP:
1238                 return requested;
1239         case NTLMv2:
1240                 return RawNTLMSSP;
1241         case Unspecified:
1242                 if (server->sec_ntlmssp &&
1243                         (global_secflags & CIFSSEC_MAY_NTLMSSP))
1244                         return RawNTLMSSP;
1245                 if ((server->sec_kerberos || server->sec_mskerberos) &&
1246                         (global_secflags & CIFSSEC_MAY_KRB5))
1247                         return Kerberos;
1248                 fallthrough;
1249         default:
1250                 return Unspecified;
1251         }
1252 }
1253
1254 struct SMB2_sess_data {
1255         unsigned int xid;
1256         struct cifs_ses *ses;
1257         struct TCP_Server_Info *server;
1258         struct nls_table *nls_cp;
1259         void (*func)(struct SMB2_sess_data *);
1260         int result;
1261         u64 previous_session;
1262
1263         /* we will send the SMB in three pieces:
1264          * a fixed length beginning part, an optional
1265          * SPNEGO blob (which can be zero length), and a
1266          * last part which will include the strings
1267          * and rest of bcc area. This allows us to avoid
1268          * a large buffer 17K allocation
1269          */
1270         int buf0_type;
1271         struct kvec iov[2];
1272 };
1273
1274 static int
1275 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1276 {
1277         int rc;
1278         struct cifs_ses *ses = sess_data->ses;
1279         struct TCP_Server_Info *server = sess_data->server;
1280         struct smb2_sess_setup_req *req;
1281         unsigned int total_len;
1282         bool is_binding = false;
1283
1284         rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1285                                  (void **) &req,
1286                                  &total_len);
1287         if (rc)
1288                 return rc;
1289
1290         spin_lock(&ses->chan_lock);
1291         is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1292         spin_unlock(&ses->chan_lock);
1293
1294         if (is_binding) {
1295                 req->hdr.SessionId = cpu_to_le64(ses->Suid);
1296                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1297                 req->PreviousSessionId = 0;
1298                 req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1299                 cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1300         } else {
1301                 /* First session, not a reauthenticate */
1302                 req->hdr.SessionId = 0;
1303                 /*
1304                  * if reconnect, we need to send previous sess id
1305                  * otherwise it is 0
1306                  */
1307                 req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1308                 req->Flags = 0; /* MBZ */
1309                 cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
1310                          sess_data->previous_session);
1311         }
1312
1313         /* enough to enable echos and oplocks and one max size write */
1314         req->hdr.CreditRequest = cpu_to_le16(130);
1315
1316         /* only one of SMB2 signing flags may be set in SMB2 request */
1317         if (server->sign)
1318                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1319         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1320                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1321         else
1322                 req->SecurityMode = 0;
1323
1324 #ifdef CONFIG_CIFS_DFS_UPCALL
1325         req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1326 #else
1327         req->Capabilities = 0;
1328 #endif /* DFS_UPCALL */
1329
1330         req->Channel = 0; /* MBZ */
1331
1332         sess_data->iov[0].iov_base = (char *)req;
1333         /* 1 for pad */
1334         sess_data->iov[0].iov_len = total_len - 1;
1335         /*
1336          * This variable will be used to clear the buffer
1337          * allocated above in case of any error in the calling function.
1338          */
1339         sess_data->buf0_type = CIFS_SMALL_BUFFER;
1340
1341         return 0;
1342 }
1343
1344 static void
1345 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1346 {
1347         struct kvec *iov = sess_data->iov;
1348
1349         /* iov[1] is already freed by caller */
1350         if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1351                 memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1352
1353         free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1354         sess_data->buf0_type = CIFS_NO_BUFFER;
1355 }
1356
1357 static int
1358 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1359 {
1360         int rc;
1361         struct smb_rqst rqst;
1362         struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1363         struct kvec rsp_iov = { NULL, 0 };
1364
1365         /* Testing shows that buffer offset must be at location of Buffer[0] */
1366         req->SecurityBufferOffset =
1367                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
1368         req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1369
1370         memset(&rqst, 0, sizeof(struct smb_rqst));
1371         rqst.rq_iov = sess_data->iov;
1372         rqst.rq_nvec = 2;
1373
1374         /* BB add code to build os and lm fields */
1375         rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1376                             sess_data->server,
1377                             &rqst,
1378                             &sess_data->buf0_type,
1379                             CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1380         cifs_small_buf_release(sess_data->iov[0].iov_base);
1381         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1382
1383         return rc;
1384 }
1385
1386 static int
1387 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1388 {
1389         int rc = 0;
1390         struct cifs_ses *ses = sess_data->ses;
1391         struct TCP_Server_Info *server = sess_data->server;
1392
1393         cifs_server_lock(server);
1394         if (server->ops->generate_signingkey) {
1395                 rc = server->ops->generate_signingkey(ses, server);
1396                 if (rc) {
1397                         cifs_dbg(FYI,
1398                                 "SMB3 session key generation failed\n");
1399                         cifs_server_unlock(server);
1400                         return rc;
1401                 }
1402         }
1403         if (!server->session_estab) {
1404                 server->sequence_number = 0x2;
1405                 server->session_estab = true;
1406         }
1407         cifs_server_unlock(server);
1408
1409         cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1410         return rc;
1411 }
1412
1413 #ifdef CONFIG_CIFS_UPCALL
1414 static void
1415 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1416 {
1417         int rc;
1418         struct cifs_ses *ses = sess_data->ses;
1419         struct TCP_Server_Info *server = sess_data->server;
1420         struct cifs_spnego_msg *msg;
1421         struct key *spnego_key = NULL;
1422         struct smb2_sess_setup_rsp *rsp = NULL;
1423         bool is_binding = false;
1424
1425         rc = SMB2_sess_alloc_buffer(sess_data);
1426         if (rc)
1427                 goto out;
1428
1429         spnego_key = cifs_get_spnego_key(ses, server);
1430         if (IS_ERR(spnego_key)) {
1431                 rc = PTR_ERR(spnego_key);
1432                 if (rc == -ENOKEY)
1433                         cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1434                 spnego_key = NULL;
1435                 goto out;
1436         }
1437
1438         msg = spnego_key->payload.data[0];
1439         /*
1440          * check version field to make sure that cifs.upcall is
1441          * sending us a response in an expected form
1442          */
1443         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1444                 cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1445                          CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1446                 rc = -EKEYREJECTED;
1447                 goto out_put_spnego_key;
1448         }
1449
1450         spin_lock(&ses->chan_lock);
1451         is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1452         spin_unlock(&ses->chan_lock);
1453
1454         /* keep session key if binding */
1455         if (!is_binding) {
1456                 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1457                                                  GFP_KERNEL);
1458                 if (!ses->auth_key.response) {
1459                         cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1460                                  msg->sesskey_len);
1461                         rc = -ENOMEM;
1462                         goto out_put_spnego_key;
1463                 }
1464                 ses->auth_key.len = msg->sesskey_len;
1465         }
1466
1467         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1468         sess_data->iov[1].iov_len = msg->secblob_len;
1469
1470         rc = SMB2_sess_sendreceive(sess_data);
1471         if (rc)
1472                 goto out_put_spnego_key;
1473
1474         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1475         /* keep session id and flags if binding */
1476         if (!is_binding) {
1477                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1478                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1479         }
1480
1481         rc = SMB2_sess_establish_session(sess_data);
1482 out_put_spnego_key:
1483         key_invalidate(spnego_key);
1484         key_put(spnego_key);
1485         if (rc) {
1486                 kfree_sensitive(ses->auth_key.response);
1487                 ses->auth_key.response = NULL;
1488                 ses->auth_key.len = 0;
1489         }
1490 out:
1491         sess_data->result = rc;
1492         sess_data->func = NULL;
1493         SMB2_sess_free_buffer(sess_data);
1494 }
1495 #else
1496 static void
1497 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1498 {
1499         cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1500         sess_data->result = -EOPNOTSUPP;
1501         sess_data->func = NULL;
1502 }
1503 #endif
1504
1505 static void
1506 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1507
1508 static void
1509 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1510 {
1511         int rc;
1512         struct cifs_ses *ses = sess_data->ses;
1513         struct TCP_Server_Info *server = sess_data->server;
1514         struct smb2_sess_setup_rsp *rsp = NULL;
1515         unsigned char *ntlmssp_blob = NULL;
1516         bool use_spnego = false; /* else use raw ntlmssp */
1517         u16 blob_length = 0;
1518         bool is_binding = false;
1519
1520         /*
1521          * If memory allocation is successful, caller of this function
1522          * frees it.
1523          */
1524         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1525         if (!ses->ntlmssp) {
1526                 rc = -ENOMEM;
1527                 goto out_err;
1528         }
1529         ses->ntlmssp->sesskey_per_smbsess = true;
1530
1531         rc = SMB2_sess_alloc_buffer(sess_data);
1532         if (rc)
1533                 goto out_err;
1534
1535         rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1536                                           &blob_length, ses, server,
1537                                           sess_data->nls_cp);
1538         if (rc)
1539                 goto out;
1540
1541         if (use_spnego) {
1542                 /* BB eventually need to add this */
1543                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1544                 rc = -EOPNOTSUPP;
1545                 goto out;
1546         }
1547         sess_data->iov[1].iov_base = ntlmssp_blob;
1548         sess_data->iov[1].iov_len = blob_length;
1549
1550         rc = SMB2_sess_sendreceive(sess_data);
1551         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1552
1553         /* If true, rc here is expected and not an error */
1554         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1555                 rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1556                 rc = 0;
1557
1558         if (rc)
1559                 goto out;
1560
1561         if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1562                         le16_to_cpu(rsp->SecurityBufferOffset)) {
1563                 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1564                         le16_to_cpu(rsp->SecurityBufferOffset));
1565                 rc = -EIO;
1566                 goto out;
1567         }
1568         rc = decode_ntlmssp_challenge(rsp->Buffer,
1569                         le16_to_cpu(rsp->SecurityBufferLength), ses);
1570         if (rc)
1571                 goto out;
1572
1573         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1574
1575         spin_lock(&ses->chan_lock);
1576         is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1577         spin_unlock(&ses->chan_lock);
1578
1579         /* keep existing ses id and flags if binding */
1580         if (!is_binding) {
1581                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1582                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1583         }
1584
1585 out:
1586         kfree_sensitive(ntlmssp_blob);
1587         SMB2_sess_free_buffer(sess_data);
1588         if (!rc) {
1589                 sess_data->result = 0;
1590                 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1591                 return;
1592         }
1593 out_err:
1594         kfree_sensitive(ses->ntlmssp);
1595         ses->ntlmssp = NULL;
1596         sess_data->result = rc;
1597         sess_data->func = NULL;
1598 }
1599
1600 static void
1601 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1602 {
1603         int rc;
1604         struct cifs_ses *ses = sess_data->ses;
1605         struct TCP_Server_Info *server = sess_data->server;
1606         struct smb2_sess_setup_req *req;
1607         struct smb2_sess_setup_rsp *rsp = NULL;
1608         unsigned char *ntlmssp_blob = NULL;
1609         bool use_spnego = false; /* else use raw ntlmssp */
1610         u16 blob_length = 0;
1611         bool is_binding = false;
1612
1613         rc = SMB2_sess_alloc_buffer(sess_data);
1614         if (rc)
1615                 goto out;
1616
1617         req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1618         req->hdr.SessionId = cpu_to_le64(ses->Suid);
1619
1620         rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
1621                                      ses, server,
1622                                      sess_data->nls_cp);
1623         if (rc) {
1624                 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1625                 goto out;
1626         }
1627
1628         if (use_spnego) {
1629                 /* BB eventually need to add this */
1630                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1631                 rc = -EOPNOTSUPP;
1632                 goto out;
1633         }
1634         sess_data->iov[1].iov_base = ntlmssp_blob;
1635         sess_data->iov[1].iov_len = blob_length;
1636
1637         rc = SMB2_sess_sendreceive(sess_data);
1638         if (rc)
1639                 goto out;
1640
1641         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1642
1643         spin_lock(&ses->chan_lock);
1644         is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1645         spin_unlock(&ses->chan_lock);
1646
1647         /* keep existing ses id and flags if binding */
1648         if (!is_binding) {
1649                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1650                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1651         }
1652
1653         rc = SMB2_sess_establish_session(sess_data);
1654 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1655         if (ses->server->dialect < SMB30_PROT_ID) {
1656                 cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1657                 /*
1658                  * The session id is opaque in terms of endianness, so we can't
1659                  * print it as a long long. we dump it as we got it on the wire
1660                  */
1661                 cifs_dbg(VFS, "Session Id    %*ph\n", (int)sizeof(ses->Suid),
1662                          &ses->Suid);
1663                 cifs_dbg(VFS, "Session Key   %*ph\n",
1664                          SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1665                 cifs_dbg(VFS, "Signing Key   %*ph\n",
1666                          SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1667         }
1668 #endif
1669 out:
1670         kfree_sensitive(ntlmssp_blob);
1671         SMB2_sess_free_buffer(sess_data);
1672         kfree_sensitive(ses->ntlmssp);
1673         ses->ntlmssp = NULL;
1674         sess_data->result = rc;
1675         sess_data->func = NULL;
1676 }
1677
1678 static int
1679 SMB2_select_sec(struct SMB2_sess_data *sess_data)
1680 {
1681         int type;
1682         struct cifs_ses *ses = sess_data->ses;
1683         struct TCP_Server_Info *server = sess_data->server;
1684
1685         type = smb2_select_sectype(server, ses->sectype);
1686         cifs_dbg(FYI, "sess setup type %d\n", type);
1687         if (type == Unspecified) {
1688                 cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1689                 return -EINVAL;
1690         }
1691
1692         switch (type) {
1693         case Kerberos:
1694                 sess_data->func = SMB2_auth_kerberos;
1695                 break;
1696         case RawNTLMSSP:
1697                 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1698                 break;
1699         default:
1700                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1701                 return -EOPNOTSUPP;
1702         }
1703
1704         return 0;
1705 }
1706
1707 int
1708 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1709                 struct TCP_Server_Info *server,
1710                 const struct nls_table *nls_cp)
1711 {
1712         int rc = 0;
1713         struct SMB2_sess_data *sess_data;
1714
1715         cifs_dbg(FYI, "Session Setup\n");
1716
1717         if (!server) {
1718                 WARN(1, "%s: server is NULL!\n", __func__);
1719                 return -EIO;
1720         }
1721
1722         sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1723         if (!sess_data)
1724                 return -ENOMEM;
1725
1726         sess_data->xid = xid;
1727         sess_data->ses = ses;
1728         sess_data->server = server;
1729         sess_data->buf0_type = CIFS_NO_BUFFER;
1730         sess_data->nls_cp = (struct nls_table *) nls_cp;
1731         sess_data->previous_session = ses->Suid;
1732
1733         rc = SMB2_select_sec(sess_data);
1734         if (rc)
1735                 goto out;
1736
1737         /*
1738          * Initialize the session hash with the server one.
1739          */
1740         memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1741                SMB2_PREAUTH_HASH_SIZE);
1742
1743         while (sess_data->func)
1744                 sess_data->func(sess_data);
1745
1746         if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1747                 cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1748         rc = sess_data->result;
1749 out:
1750         kfree_sensitive(sess_data);
1751         return rc;
1752 }
1753
1754 int
1755 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1756 {
1757         struct smb_rqst rqst;
1758         struct smb2_logoff_req *req; /* response is also trivial struct */
1759         int rc = 0;
1760         struct TCP_Server_Info *server;
1761         int flags = 0;
1762         unsigned int total_len;
1763         struct kvec iov[1];
1764         struct kvec rsp_iov;
1765         int resp_buf_type;
1766
1767         cifs_dbg(FYI, "disconnect session %p\n", ses);
1768
1769         if (ses && (ses->server))
1770                 server = ses->server;
1771         else
1772                 return -EIO;
1773
1774         /* no need to send SMB logoff if uid already closed due to reconnect */
1775         spin_lock(&ses->chan_lock);
1776         if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
1777                 spin_unlock(&ses->chan_lock);
1778                 goto smb2_session_already_dead;
1779         }
1780         spin_unlock(&ses->chan_lock);
1781
1782         rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
1783                                  (void **) &req, &total_len);
1784         if (rc)
1785                 return rc;
1786
1787          /* since no tcon, smb2_init can not do this, so do here */
1788         req->hdr.SessionId = cpu_to_le64(ses->Suid);
1789
1790         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1791                 flags |= CIFS_TRANSFORM_REQ;
1792         else if (server->sign)
1793                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1794
1795         flags |= CIFS_NO_RSP_BUF;
1796
1797         iov[0].iov_base = (char *)req;
1798         iov[0].iov_len = total_len;
1799
1800         memset(&rqst, 0, sizeof(struct smb_rqst));
1801         rqst.rq_iov = iov;
1802         rqst.rq_nvec = 1;
1803
1804         rc = cifs_send_recv(xid, ses, ses->server,
1805                             &rqst, &resp_buf_type, flags, &rsp_iov);
1806         cifs_small_buf_release(req);
1807         /*
1808          * No tcon so can't do
1809          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1810          */
1811
1812 smb2_session_already_dead:
1813         return rc;
1814 }
1815
1816 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1817 {
1818         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1819 }
1820
1821 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1822
1823 /* These are similar values to what Windows uses */
1824 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1825 {
1826         tcon->max_chunks = 256;
1827         tcon->max_bytes_chunk = 1048576;
1828         tcon->max_bytes_copy = 16777216;
1829 }
1830
1831 int
1832 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1833           struct cifs_tcon *tcon, const struct nls_table *cp)
1834 {
1835         struct smb_rqst rqst;
1836         struct smb2_tree_connect_req *req;
1837         struct smb2_tree_connect_rsp *rsp = NULL;
1838         struct kvec iov[2];
1839         struct kvec rsp_iov = { NULL, 0 };
1840         int rc = 0;
1841         int resp_buftype;
1842         int unc_path_len;
1843         __le16 *unc_path = NULL;
1844         int flags = 0;
1845         unsigned int total_len;
1846         struct TCP_Server_Info *server;
1847
1848         /* always use master channel */
1849         server = ses->server;
1850
1851         cifs_dbg(FYI, "TCON\n");
1852
1853         if (!server || !tree)
1854                 return -EIO;
1855
1856         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1857         if (unc_path == NULL)
1858                 return -ENOMEM;
1859
1860         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1861         unc_path_len *= 2;
1862         if (unc_path_len < 2) {
1863                 kfree(unc_path);
1864                 return -EINVAL;
1865         }
1866
1867         /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1868         tcon->tid = 0;
1869         atomic_set(&tcon->num_remote_opens, 0);
1870         rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
1871                                  (void **) &req, &total_len);
1872         if (rc) {
1873                 kfree(unc_path);
1874                 return rc;
1875         }
1876
1877         if (smb3_encryption_required(tcon))
1878                 flags |= CIFS_TRANSFORM_REQ;
1879
1880         iov[0].iov_base = (char *)req;
1881         /* 1 for pad */
1882         iov[0].iov_len = total_len - 1;
1883
1884         /* Testing shows that buffer offset must be at location of Buffer[0] */
1885         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1886                         - 1 /* pad */);
1887         req->PathLength = cpu_to_le16(unc_path_len - 2);
1888         iov[1].iov_base = unc_path;
1889         iov[1].iov_len = unc_path_len;
1890
1891         /*
1892          * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
1893          * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1894          * (Samba servers don't always set the flag so also check if null user)
1895          */
1896         if ((server->dialect == SMB311_PROT_ID) &&
1897             !smb3_encryption_required(tcon) &&
1898             !(ses->session_flags &
1899                     (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
1900             ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1901                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1902
1903         memset(&rqst, 0, sizeof(struct smb_rqst));
1904         rqst.rq_iov = iov;
1905         rqst.rq_nvec = 2;
1906
1907         /* Need 64 for max size write so ask for more in case not there yet */
1908         req->hdr.CreditRequest = cpu_to_le16(64);
1909
1910         rc = cifs_send_recv(xid, ses, server,
1911                             &rqst, &resp_buftype, flags, &rsp_iov);
1912         cifs_small_buf_release(req);
1913         rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1914         trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
1915         if ((rc != 0) || (rsp == NULL)) {
1916                 cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1917                 tcon->need_reconnect = true;
1918                 goto tcon_error_exit;
1919         }
1920
1921         switch (rsp->ShareType) {
1922         case SMB2_SHARE_TYPE_DISK:
1923                 cifs_dbg(FYI, "connection to disk share\n");
1924                 break;
1925         case SMB2_SHARE_TYPE_PIPE:
1926                 tcon->pipe = true;
1927                 cifs_dbg(FYI, "connection to pipe share\n");
1928                 break;
1929         case SMB2_SHARE_TYPE_PRINT:
1930                 tcon->print = true;
1931                 cifs_dbg(FYI, "connection to printer\n");
1932                 break;
1933         default:
1934                 cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1935                 rc = -EOPNOTSUPP;
1936                 goto tcon_error_exit;
1937         }
1938
1939         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1940         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1941         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1942         tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
1943         strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
1944
1945         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1946             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1947                 cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
1948
1949         if (tcon->seal &&
1950             !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1951                 cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
1952
1953         init_copy_chunk_defaults(tcon);
1954         if (server->ops->validate_negotiate)
1955                 rc = server->ops->validate_negotiate(xid, tcon);
1956 tcon_exit:
1957
1958         free_rsp_buf(resp_buftype, rsp);
1959         kfree(unc_path);
1960         return rc;
1961
1962 tcon_error_exit:
1963         if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
1964                 cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1965         goto tcon_exit;
1966 }
1967
1968 int
1969 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1970 {
1971         struct smb_rqst rqst;
1972         struct smb2_tree_disconnect_req *req; /* response is trivial */
1973         int rc = 0;
1974         struct cifs_ses *ses = tcon->ses;
1975         int flags = 0;
1976         unsigned int total_len;
1977         struct kvec iov[1];
1978         struct kvec rsp_iov;
1979         int resp_buf_type;
1980
1981         cifs_dbg(FYI, "Tree Disconnect\n");
1982
1983         if (!ses || !(ses->server))
1984                 return -EIO;
1985
1986         trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
1987         spin_lock(&ses->chan_lock);
1988         if ((tcon->need_reconnect) ||
1989             (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
1990                 spin_unlock(&ses->chan_lock);
1991                 return 0;
1992         }
1993         spin_unlock(&ses->chan_lock);
1994
1995         invalidate_all_cached_dirs(tcon);
1996
1997         rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, ses->server,
1998                                  (void **) &req,
1999                                  &total_len);
2000         if (rc)
2001                 return rc;
2002
2003         if (smb3_encryption_required(tcon))
2004                 flags |= CIFS_TRANSFORM_REQ;
2005
2006         flags |= CIFS_NO_RSP_BUF;
2007
2008         iov[0].iov_base = (char *)req;
2009         iov[0].iov_len = total_len;
2010
2011         memset(&rqst, 0, sizeof(struct smb_rqst));
2012         rqst.rq_iov = iov;
2013         rqst.rq_nvec = 1;
2014
2015         rc = cifs_send_recv(xid, ses, ses->server,
2016                             &rqst, &resp_buf_type, flags, &rsp_iov);
2017         cifs_small_buf_release(req);
2018         if (rc) {
2019                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2020                 trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
2021         }
2022         trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2023
2024         return rc;
2025 }
2026
2027
2028 static struct create_durable *
2029 create_durable_buf(void)
2030 {
2031         struct create_durable *buf;
2032
2033         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2034         if (!buf)
2035                 return NULL;
2036
2037         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2038                                         (struct create_durable, Data));
2039         buf->ccontext.DataLength = cpu_to_le32(16);
2040         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2041                                 (struct create_durable, Name));
2042         buf->ccontext.NameLength = cpu_to_le16(4);
2043         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2044         buf->Name[0] = 'D';
2045         buf->Name[1] = 'H';
2046         buf->Name[2] = 'n';
2047         buf->Name[3] = 'Q';
2048         return buf;
2049 }
2050
2051 static struct create_durable *
2052 create_reconnect_durable_buf(struct cifs_fid *fid)
2053 {
2054         struct create_durable *buf;
2055
2056         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2057         if (!buf)
2058                 return NULL;
2059
2060         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2061                                         (struct create_durable, Data));
2062         buf->ccontext.DataLength = cpu_to_le32(16);
2063         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2064                                 (struct create_durable, Name));
2065         buf->ccontext.NameLength = cpu_to_le16(4);
2066         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2067         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2068         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2069         buf->Name[0] = 'D';
2070         buf->Name[1] = 'H';
2071         buf->Name[2] = 'n';
2072         buf->Name[3] = 'C';
2073         return buf;
2074 }
2075
2076 static void
2077 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2078 {
2079         struct create_on_disk_id *pdisk_id = (struct create_on_disk_id *)cc;
2080
2081         cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2082                 pdisk_id->DiskFileId, pdisk_id->VolumeId);
2083         buf->IndexNumber = pdisk_id->DiskFileId;
2084 }
2085
2086 static void
2087 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2088                  struct create_posix_rsp *posix)
2089 {
2090         int sid_len;
2091         u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2092         u8 *end = beg + le32_to_cpu(cc->DataLength);
2093         u8 *sid;
2094
2095         memset(posix, 0, sizeof(*posix));
2096
2097         posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2098         posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2099         posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2100
2101         sid = beg + 12;
2102         sid_len = posix_info_sid_size(sid, end);
2103         if (sid_len < 0) {
2104                 cifs_dbg(VFS, "bad owner sid in posix create response\n");
2105                 return;
2106         }
2107         memcpy(&posix->owner, sid, sid_len);
2108
2109         sid = sid + sid_len;
2110         sid_len = posix_info_sid_size(sid, end);
2111         if (sid_len < 0) {
2112                 cifs_dbg(VFS, "bad group sid in posix create response\n");
2113                 return;
2114         }
2115         memcpy(&posix->group, sid, sid_len);
2116
2117         cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2118                  posix->nlink, posix->mode, posix->reparse_tag);
2119 }
2120
2121 void
2122 smb2_parse_contexts(struct TCP_Server_Info *server,
2123                     struct smb2_create_rsp *rsp,
2124                     unsigned int *epoch, char *lease_key, __u8 *oplock,
2125                     struct smb2_file_all_info *buf,
2126                     struct create_posix_rsp *posix)
2127 {
2128         char *data_offset;
2129         struct create_context *cc;
2130         unsigned int next;
2131         unsigned int remaining;
2132         char *name;
2133         static const char smb3_create_tag_posix[] = {
2134                 0x93, 0xAD, 0x25, 0x50, 0x9C,
2135                 0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2136                 0xDE, 0x96, 0x8B, 0xCD, 0x7C
2137         };
2138
2139         *oplock = 0;
2140         data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
2141         remaining = le32_to_cpu(rsp->CreateContextsLength);
2142         cc = (struct create_context *)data_offset;
2143
2144         /* Initialize inode number to 0 in case no valid data in qfid context */
2145         if (buf)
2146                 buf->IndexNumber = 0;
2147
2148         while (remaining >= sizeof(struct create_context)) {
2149                 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
2150                 if (le16_to_cpu(cc->NameLength) == 4 &&
2151                     strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4) == 0)
2152                         *oplock = server->ops->parse_lease_buf(cc, epoch,
2153                                                            lease_key);
2154                 else if (buf && (le16_to_cpu(cc->NameLength) == 4) &&
2155                     strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4) == 0)
2156                         parse_query_id_ctxt(cc, buf);
2157                 else if ((le16_to_cpu(cc->NameLength) == 16)) {
2158                         if (posix &&
2159                             memcmp(name, smb3_create_tag_posix, 16) == 0)
2160                                 parse_posix_ctxt(cc, buf, posix);
2161                 }
2162                 /* else {
2163                         cifs_dbg(FYI, "Context not matched with len %d\n",
2164                                 le16_to_cpu(cc->NameLength));
2165                         cifs_dump_mem("Cctxt name: ", name, 4);
2166                 } */
2167
2168                 next = le32_to_cpu(cc->Next);
2169                 if (!next)
2170                         break;
2171                 remaining -= next;
2172                 cc = (struct create_context *)((char *)cc + next);
2173         }
2174
2175         if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2176                 *oplock = rsp->OplockLevel;
2177
2178         return;
2179 }
2180
2181 static int
2182 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
2183                   unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2184 {
2185         struct smb2_create_req *req = iov[0].iov_base;
2186         unsigned int num = *num_iovec;
2187
2188         iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2189         if (iov[num].iov_base == NULL)
2190                 return -ENOMEM;
2191         iov[num].iov_len = server->vals->create_lease_size;
2192         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2193         if (!req->CreateContextsOffset)
2194                 req->CreateContextsOffset = cpu_to_le32(
2195                                 sizeof(struct smb2_create_req) +
2196                                 iov[num - 1].iov_len);
2197         le32_add_cpu(&req->CreateContextsLength,
2198                      server->vals->create_lease_size);
2199         *num_iovec = num + 1;
2200         return 0;
2201 }
2202
2203 static struct create_durable_v2 *
2204 create_durable_v2_buf(struct cifs_open_parms *oparms)
2205 {
2206         struct cifs_fid *pfid = oparms->fid;
2207         struct create_durable_v2 *buf;
2208
2209         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2210         if (!buf)
2211                 return NULL;
2212
2213         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2214                                         (struct create_durable_v2, dcontext));
2215         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2216         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2217                                 (struct create_durable_v2, Name));
2218         buf->ccontext.NameLength = cpu_to_le16(4);
2219
2220         /*
2221          * NB: Handle timeout defaults to 0, which allows server to choose
2222          * (most servers default to 120 seconds) and most clients default to 0.
2223          * This can be overridden at mount ("handletimeout=") if the user wants
2224          * a different persistent (or resilient) handle timeout for all opens
2225          * opens on a particular SMB3 mount.
2226          */
2227         buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2228         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2229         generate_random_uuid(buf->dcontext.CreateGuid);
2230         memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2231
2232         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2233         buf->Name[0] = 'D';
2234         buf->Name[1] = 'H';
2235         buf->Name[2] = '2';
2236         buf->Name[3] = 'Q';
2237         return buf;
2238 }
2239
2240 static struct create_durable_handle_reconnect_v2 *
2241 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2242 {
2243         struct create_durable_handle_reconnect_v2 *buf;
2244
2245         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2246                         GFP_KERNEL);
2247         if (!buf)
2248                 return NULL;
2249
2250         buf->ccontext.DataOffset =
2251                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2252                                      dcontext));
2253         buf->ccontext.DataLength =
2254                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2255         buf->ccontext.NameOffset =
2256                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2257                             Name));
2258         buf->ccontext.NameLength = cpu_to_le16(4);
2259
2260         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2261         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2262         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2263         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2264
2265         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2266         buf->Name[0] = 'D';
2267         buf->Name[1] = 'H';
2268         buf->Name[2] = '2';
2269         buf->Name[3] = 'C';
2270         return buf;
2271 }
2272
2273 static int
2274 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2275                     struct cifs_open_parms *oparms)
2276 {
2277         struct smb2_create_req *req = iov[0].iov_base;
2278         unsigned int num = *num_iovec;
2279
2280         iov[num].iov_base = create_durable_v2_buf(oparms);
2281         if (iov[num].iov_base == NULL)
2282                 return -ENOMEM;
2283         iov[num].iov_len = sizeof(struct create_durable_v2);
2284         if (!req->CreateContextsOffset)
2285                 req->CreateContextsOffset =
2286                         cpu_to_le32(sizeof(struct smb2_create_req) +
2287                                                                 iov[1].iov_len);
2288         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
2289         *num_iovec = num + 1;
2290         return 0;
2291 }
2292
2293 static int
2294 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2295                     struct cifs_open_parms *oparms)
2296 {
2297         struct smb2_create_req *req = iov[0].iov_base;
2298         unsigned int num = *num_iovec;
2299
2300         /* indicate that we don't need to relock the file */
2301         oparms->reconnect = false;
2302
2303         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2304         if (iov[num].iov_base == NULL)
2305                 return -ENOMEM;
2306         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2307         if (!req->CreateContextsOffset)
2308                 req->CreateContextsOffset =
2309                         cpu_to_le32(sizeof(struct smb2_create_req) +
2310                                                                 iov[1].iov_len);
2311         le32_add_cpu(&req->CreateContextsLength,
2312                         sizeof(struct create_durable_handle_reconnect_v2));
2313         *num_iovec = num + 1;
2314         return 0;
2315 }
2316
2317 static int
2318 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2319                     struct cifs_open_parms *oparms, bool use_persistent)
2320 {
2321         struct smb2_create_req *req = iov[0].iov_base;
2322         unsigned int num = *num_iovec;
2323
2324         if (use_persistent) {
2325                 if (oparms->reconnect)
2326                         return add_durable_reconnect_v2_context(iov, num_iovec,
2327                                                                 oparms);
2328                 else
2329                         return add_durable_v2_context(iov, num_iovec, oparms);
2330         }
2331
2332         if (oparms->reconnect) {
2333                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2334                 /* indicate that we don't need to relock the file */
2335                 oparms->reconnect = false;
2336         } else
2337                 iov[num].iov_base = create_durable_buf();
2338         if (iov[num].iov_base == NULL)
2339                 return -ENOMEM;
2340         iov[num].iov_len = sizeof(struct create_durable);
2341         if (!req->CreateContextsOffset)
2342                 req->CreateContextsOffset =
2343                         cpu_to_le32(sizeof(struct smb2_create_req) +
2344                                                                 iov[1].iov_len);
2345         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
2346         *num_iovec = num + 1;
2347         return 0;
2348 }
2349
2350 /* See MS-SMB2 2.2.13.2.7 */
2351 static struct crt_twarp_ctxt *
2352 create_twarp_buf(__u64 timewarp)
2353 {
2354         struct crt_twarp_ctxt *buf;
2355
2356         buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2357         if (!buf)
2358                 return NULL;
2359
2360         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2361                                         (struct crt_twarp_ctxt, Timestamp));
2362         buf->ccontext.DataLength = cpu_to_le32(8);
2363         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2364                                 (struct crt_twarp_ctxt, Name));
2365         buf->ccontext.NameLength = cpu_to_le16(4);
2366         /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2367         buf->Name[0] = 'T';
2368         buf->Name[1] = 'W';
2369         buf->Name[2] = 'r';
2370         buf->Name[3] = 'p';
2371         buf->Timestamp = cpu_to_le64(timewarp);
2372         return buf;
2373 }
2374
2375 /* See MS-SMB2 2.2.13.2.7 */
2376 static int
2377 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2378 {
2379         struct smb2_create_req *req = iov[0].iov_base;
2380         unsigned int num = *num_iovec;
2381
2382         iov[num].iov_base = create_twarp_buf(timewarp);
2383         if (iov[num].iov_base == NULL)
2384                 return -ENOMEM;
2385         iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2386         if (!req->CreateContextsOffset)
2387                 req->CreateContextsOffset = cpu_to_le32(
2388                                 sizeof(struct smb2_create_req) +
2389                                 iov[num - 1].iov_len);
2390         le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt));
2391         *num_iovec = num + 1;
2392         return 0;
2393 }
2394
2395 /* See See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2396 static void setup_owner_group_sids(char *buf)
2397 {
2398         struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2399
2400         /* Populate the user ownership fields S-1-5-88-1 */
2401         sids->owner.Revision = 1;
2402         sids->owner.NumAuth = 3;
2403         sids->owner.Authority[5] = 5;
2404         sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2405         sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2406         sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2407
2408         /* Populate the group ownership fields S-1-5-88-2 */
2409         sids->group.Revision = 1;
2410         sids->group.NumAuth = 3;
2411         sids->group.Authority[5] = 5;
2412         sids->group.SubAuthorities[0] = cpu_to_le32(88);
2413         sids->group.SubAuthorities[1] = cpu_to_le32(2);
2414         sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2415
2416         cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2417 }
2418
2419 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2420 static struct crt_sd_ctxt *
2421 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2422 {
2423         struct crt_sd_ctxt *buf;
2424         __u8 *ptr, *aclptr;
2425         unsigned int acelen, acl_size, ace_count;
2426         unsigned int owner_offset = 0;
2427         unsigned int group_offset = 0;
2428         struct smb3_acl acl = {};
2429
2430         *len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2431
2432         if (set_owner) {
2433                 /* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2434                 *len += sizeof(struct owner_group_sids);
2435         }
2436
2437         buf = kzalloc(*len, GFP_KERNEL);
2438         if (buf == NULL)
2439                 return buf;
2440
2441         ptr = (__u8 *)&buf[1];
2442         if (set_owner) {
2443                 /* offset fields are from beginning of security descriptor not of create context */
2444                 owner_offset = ptr - (__u8 *)&buf->sd;
2445                 buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2446                 group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2447                 buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2448
2449                 setup_owner_group_sids(ptr);
2450                 ptr += sizeof(struct owner_group_sids);
2451         } else {
2452                 buf->sd.OffsetOwner = 0;
2453                 buf->sd.OffsetGroup = 0;
2454         }
2455
2456         buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2457         buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2458         buf->ccontext.NameLength = cpu_to_le16(4);
2459         /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2460         buf->Name[0] = 'S';
2461         buf->Name[1] = 'e';
2462         buf->Name[2] = 'c';
2463         buf->Name[3] = 'D';
2464         buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2465
2466         /*
2467          * ACL is "self relative" ie ACL is stored in contiguous block of memory
2468          * and "DP" ie the DACL is present
2469          */
2470         buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2471
2472         /* offset owner, group and Sbz1 and SACL are all zero */
2473         buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2474         /* Ship the ACL for now. we will copy it into buf later. */
2475         aclptr = ptr;
2476         ptr += sizeof(struct smb3_acl);
2477
2478         /* create one ACE to hold the mode embedded in reserved special SID */
2479         acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2480         ptr += acelen;
2481         acl_size = acelen + sizeof(struct smb3_acl);
2482         ace_count = 1;
2483
2484         if (set_owner) {
2485                 /* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2486                 acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2487                 ptr += acelen;
2488                 acl_size += acelen;
2489                 ace_count += 1;
2490         }
2491
2492         /* and one more ACE to allow access for authenticated users */
2493         acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2494         ptr += acelen;
2495         acl_size += acelen;
2496         ace_count += 1;
2497
2498         acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2499         acl.AclSize = cpu_to_le16(acl_size);
2500         acl.AceCount = cpu_to_le16(ace_count);
2501         /* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2502         memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2503
2504         buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2505         *len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2506
2507         return buf;
2508 }
2509
2510 static int
2511 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2512 {
2513         struct smb2_create_req *req = iov[0].iov_base;
2514         unsigned int num = *num_iovec;
2515         unsigned int len = 0;
2516
2517         iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2518         if (iov[num].iov_base == NULL)
2519                 return -ENOMEM;
2520         iov[num].iov_len = len;
2521         if (!req->CreateContextsOffset)
2522                 req->CreateContextsOffset = cpu_to_le32(
2523                                 sizeof(struct smb2_create_req) +
2524                                 iov[num - 1].iov_len);
2525         le32_add_cpu(&req->CreateContextsLength, len);
2526         *num_iovec = num + 1;
2527         return 0;
2528 }
2529
2530 static struct crt_query_id_ctxt *
2531 create_query_id_buf(void)
2532 {
2533         struct crt_query_id_ctxt *buf;
2534
2535         buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2536         if (!buf)
2537                 return NULL;
2538
2539         buf->ccontext.DataOffset = cpu_to_le16(0);
2540         buf->ccontext.DataLength = cpu_to_le32(0);
2541         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2542                                 (struct crt_query_id_ctxt, Name));
2543         buf->ccontext.NameLength = cpu_to_le16(4);
2544         /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2545         buf->Name[0] = 'Q';
2546         buf->Name[1] = 'F';
2547         buf->Name[2] = 'i';
2548         buf->Name[3] = 'd';
2549         return buf;
2550 }
2551
2552 /* See MS-SMB2 2.2.13.2.9 */
2553 static int
2554 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2555 {
2556         struct smb2_create_req *req = iov[0].iov_base;
2557         unsigned int num = *num_iovec;
2558
2559         iov[num].iov_base = create_query_id_buf();
2560         if (iov[num].iov_base == NULL)
2561                 return -ENOMEM;
2562         iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2563         if (!req->CreateContextsOffset)
2564                 req->CreateContextsOffset = cpu_to_le32(
2565                                 sizeof(struct smb2_create_req) +
2566                                 iov[num - 1].iov_len);
2567         le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_query_id_ctxt));
2568         *num_iovec = num + 1;
2569         return 0;
2570 }
2571
2572 static int
2573 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2574                             const char *treename, const __le16 *path)
2575 {
2576         int treename_len, path_len;
2577         struct nls_table *cp;
2578         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2579
2580         /*
2581          * skip leading "\\"
2582          */
2583         treename_len = strlen(treename);
2584         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2585                 return -EINVAL;
2586
2587         treename += 2;
2588         treename_len -= 2;
2589
2590         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2591
2592         /* make room for one path separator only if @path isn't empty */
2593         *out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2594
2595         /*
2596          * final path needs to be 8-byte aligned as specified in
2597          * MS-SMB2 2.2.13 SMB2 CREATE Request.
2598          */
2599         *out_size = round_up(*out_len * sizeof(__le16), 8);
2600         *out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2601         if (!*out_path)
2602                 return -ENOMEM;
2603
2604         cp = load_nls_default();
2605         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2606
2607         /* Do not append the separator if the path is empty */
2608         if (path[0] != cpu_to_le16(0x0000)) {
2609                 UniStrcat(*out_path, sep);
2610                 UniStrcat(*out_path, path);
2611         }
2612
2613         unload_nls(cp);
2614
2615         return 0;
2616 }
2617
2618 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2619                                umode_t mode, struct cifs_tcon *tcon,
2620                                const char *full_path,
2621                                struct cifs_sb_info *cifs_sb)
2622 {
2623         struct smb_rqst rqst;
2624         struct smb2_create_req *req;
2625         struct smb2_create_rsp *rsp = NULL;
2626         struct cifs_ses *ses = tcon->ses;
2627         struct kvec iov[3]; /* make sure at least one for each open context */
2628         struct kvec rsp_iov = {NULL, 0};
2629         int resp_buftype;
2630         int uni_path_len;
2631         __le16 *copy_path = NULL;
2632         int copy_size;
2633         int rc = 0;
2634         unsigned int n_iov = 2;
2635         __u32 file_attributes = 0;
2636         char *pc_buf = NULL;
2637         int flags = 0;
2638         unsigned int total_len;
2639         __le16 *utf16_path = NULL;
2640         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2641
2642         cifs_dbg(FYI, "mkdir\n");
2643
2644         /* resource #1: path allocation */
2645         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2646         if (!utf16_path)
2647                 return -ENOMEM;
2648
2649         if (!ses || !server) {
2650                 rc = -EIO;
2651                 goto err_free_path;
2652         }
2653
2654         /* resource #2: request */
2655         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2656                                  (void **) &req, &total_len);
2657         if (rc)
2658                 goto err_free_path;
2659
2660
2661         if (smb3_encryption_required(tcon))
2662                 flags |= CIFS_TRANSFORM_REQ;
2663
2664         req->ImpersonationLevel = IL_IMPERSONATION;
2665         req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2666         /* File attributes ignored on open (used in create though) */
2667         req->FileAttributes = cpu_to_le32(file_attributes);
2668         req->ShareAccess = FILE_SHARE_ALL_LE;
2669         req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2670         req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2671
2672         iov[0].iov_base = (char *)req;
2673         /* -1 since last byte is buf[0] which is sent below (path) */
2674         iov[0].iov_len = total_len - 1;
2675
2676         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2677
2678         /* [MS-SMB2] 2.2.13 NameOffset:
2679          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2680          * the SMB2 header, the file name includes a prefix that will
2681          * be processed during DFS name normalization as specified in
2682          * section 3.3.5.9. Otherwise, the file name is relative to
2683          * the share that is identified by the TreeId in the SMB2
2684          * header.
2685          */
2686         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2687                 int name_len;
2688
2689                 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2690                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2691                                                  &name_len,
2692                                                  tcon->tree_name, utf16_path);
2693                 if (rc)
2694                         goto err_free_req;
2695
2696                 req->NameLength = cpu_to_le16(name_len * 2);
2697                 uni_path_len = copy_size;
2698                 /* free before overwriting resource */
2699                 kfree(utf16_path);
2700                 utf16_path = copy_path;
2701         } else {
2702                 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2703                 /* MUST set path len (NameLength) to 0 opening root of share */
2704                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2705                 if (uni_path_len % 8 != 0) {
2706                         copy_size = roundup(uni_path_len, 8);
2707                         copy_path = kzalloc(copy_size, GFP_KERNEL);
2708                         if (!copy_path) {
2709                                 rc = -ENOMEM;
2710                                 goto err_free_req;
2711                         }
2712                         memcpy((char *)copy_path, (const char *)utf16_path,
2713                                uni_path_len);
2714                         uni_path_len = copy_size;
2715                         /* free before overwriting resource */
2716                         kfree(utf16_path);
2717                         utf16_path = copy_path;
2718                 }
2719         }
2720
2721         iov[1].iov_len = uni_path_len;
2722         iov[1].iov_base = utf16_path;
2723         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2724
2725         if (tcon->posix_extensions) {
2726                 /* resource #3: posix buf */
2727                 rc = add_posix_context(iov, &n_iov, mode);
2728                 if (rc)
2729                         goto err_free_req;
2730                 pc_buf = iov[n_iov-1].iov_base;
2731         }
2732
2733
2734         memset(&rqst, 0, sizeof(struct smb_rqst));
2735         rqst.rq_iov = iov;
2736         rqst.rq_nvec = n_iov;
2737
2738         /* no need to inc num_remote_opens because we close it just below */
2739         trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE,
2740                                     FILE_WRITE_ATTRIBUTES);
2741         /* resource #4: response buffer */
2742         rc = cifs_send_recv(xid, ses, server,
2743                             &rqst, &resp_buftype, flags, &rsp_iov);
2744         if (rc) {
2745                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2746                 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2747                                            CREATE_NOT_FILE,
2748                                            FILE_WRITE_ATTRIBUTES, rc);
2749                 goto err_free_rsp_buf;
2750         }
2751
2752         /*
2753          * Although unlikely to be possible for rsp to be null and rc not set,
2754          * adding check below is slightly safer long term (and quiets Coverity
2755          * warning)
2756          */
2757         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2758         if (rsp == NULL) {
2759                 rc = -EIO;
2760                 kfree(pc_buf);
2761                 goto err_free_req;
2762         }
2763
2764         trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
2765                                     CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2766
2767         SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2768
2769         /* Eventually save off posix specific response info and timestaps */
2770
2771 err_free_rsp_buf:
2772         free_rsp_buf(resp_buftype, rsp);
2773         kfree(pc_buf);
2774 err_free_req:
2775         cifs_small_buf_release(req);
2776 err_free_path:
2777         kfree(utf16_path);
2778         return rc;
2779 }
2780
2781 int
2782 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2783                struct smb_rqst *rqst, __u8 *oplock,
2784                struct cifs_open_parms *oparms, __le16 *path)
2785 {
2786         struct smb2_create_req *req;
2787         unsigned int n_iov = 2;
2788         __u32 file_attributes = 0;
2789         int copy_size;
2790         int uni_path_len;
2791         unsigned int total_len;
2792         struct kvec *iov = rqst->rq_iov;
2793         __le16 *copy_path;
2794         int rc;
2795
2796         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2797                                  (void **) &req, &total_len);
2798         if (rc)
2799                 return rc;
2800
2801         iov[0].iov_base = (char *)req;
2802         /* -1 since last byte is buf[0] which is sent below (path) */
2803         iov[0].iov_len = total_len - 1;
2804
2805         if (oparms->create_options & CREATE_OPTION_READONLY)
2806                 file_attributes |= ATTR_READONLY;
2807         if (oparms->create_options & CREATE_OPTION_SPECIAL)
2808                 file_attributes |= ATTR_SYSTEM;
2809
2810         req->ImpersonationLevel = IL_IMPERSONATION;
2811         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2812         /* File attributes ignored on open (used in create though) */
2813         req->FileAttributes = cpu_to_le32(file_attributes);
2814         req->ShareAccess = FILE_SHARE_ALL_LE;
2815
2816         req->CreateDisposition = cpu_to_le32(oparms->disposition);
2817         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2818         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2819
2820         /* [MS-SMB2] 2.2.13 NameOffset:
2821          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2822          * the SMB2 header, the file name includes a prefix that will
2823          * be processed during DFS name normalization as specified in
2824          * section 3.3.5.9. Otherwise, the file name is relative to
2825          * the share that is identified by the TreeId in the SMB2
2826          * header.
2827          */
2828         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2829                 int name_len;
2830
2831                 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2832                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2833                                                  &name_len,
2834                                                  tcon->tree_name, path);
2835                 if (rc)
2836                         return rc;
2837                 req->NameLength = cpu_to_le16(name_len * 2);
2838                 uni_path_len = copy_size;
2839                 path = copy_path;
2840         } else {
2841                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2842                 /* MUST set path len (NameLength) to 0 opening root of share */
2843                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2844                 copy_size = round_up(uni_path_len, 8);
2845                 copy_path = kzalloc(copy_size, GFP_KERNEL);
2846                 if (!copy_path)
2847                         return -ENOMEM;
2848                 memcpy((char *)copy_path, (const char *)path,
2849                        uni_path_len);
2850                 uni_path_len = copy_size;
2851                 path = copy_path;
2852         }
2853
2854         iov[1].iov_len = uni_path_len;
2855         iov[1].iov_base = path;
2856
2857         if ((!server->oplocks) || (tcon->no_lease))
2858                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
2859
2860         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2861             *oplock == SMB2_OPLOCK_LEVEL_NONE)
2862                 req->RequestedOplockLevel = *oplock;
2863         else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2864                   (oparms->create_options & CREATE_NOT_FILE))
2865                 req->RequestedOplockLevel = *oplock; /* no srv lease support */
2866         else {
2867                 rc = add_lease_context(server, iov, &n_iov,
2868                                        oparms->fid->lease_key, oplock);
2869                 if (rc)
2870                         return rc;
2871         }
2872
2873         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2874                 /* need to set Next field of lease context if we request it */
2875                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2876                         struct create_context *ccontext =
2877                             (struct create_context *)iov[n_iov-1].iov_base;
2878                         ccontext->Next =
2879                                 cpu_to_le32(server->vals->create_lease_size);
2880                 }
2881
2882                 rc = add_durable_context(iov, &n_iov, oparms,
2883                                         tcon->use_persistent);
2884                 if (rc)
2885                         return rc;
2886         }
2887
2888         if (tcon->posix_extensions) {
2889                 if (n_iov > 2) {
2890                         struct create_context *ccontext =
2891                             (struct create_context *)iov[n_iov-1].iov_base;
2892                         ccontext->Next =
2893                                 cpu_to_le32(iov[n_iov-1].iov_len);
2894                 }
2895
2896                 rc = add_posix_context(iov, &n_iov, oparms->mode);
2897                 if (rc)
2898                         return rc;
2899         }
2900
2901         if (tcon->snapshot_time) {
2902                 cifs_dbg(FYI, "adding snapshot context\n");
2903                 if (n_iov > 2) {
2904                         struct create_context *ccontext =
2905                             (struct create_context *)iov[n_iov-1].iov_base;
2906                         ccontext->Next =
2907                                 cpu_to_le32(iov[n_iov-1].iov_len);
2908                 }
2909
2910                 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2911                 if (rc)
2912                         return rc;
2913         }
2914
2915         if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
2916                 bool set_mode;
2917                 bool set_owner;
2918
2919                 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2920                     (oparms->mode != ACL_NO_MODE))
2921                         set_mode = true;
2922                 else {
2923                         set_mode = false;
2924                         oparms->mode = ACL_NO_MODE;
2925                 }
2926
2927                 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
2928                         set_owner = true;
2929                 else
2930                         set_owner = false;
2931
2932                 if (set_owner | set_mode) {
2933                         if (n_iov > 2) {
2934                                 struct create_context *ccontext =
2935                                     (struct create_context *)iov[n_iov-1].iov_base;
2936                                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2937                         }
2938
2939                         cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2940                         rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
2941                         if (rc)
2942                                 return rc;
2943                 }
2944         }
2945
2946         if (n_iov > 2) {
2947                 struct create_context *ccontext =
2948                         (struct create_context *)iov[n_iov-1].iov_base;
2949                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2950         }
2951         add_query_id_context(iov, &n_iov);
2952
2953         rqst->rq_nvec = n_iov;
2954         return 0;
2955 }
2956
2957 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2958  * All other vectors are freed by kfree().
2959  */
2960 void
2961 SMB2_open_free(struct smb_rqst *rqst)
2962 {
2963         int i;
2964
2965         if (rqst && rqst->rq_iov) {
2966                 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2967                 for (i = 1; i < rqst->rq_nvec; i++)
2968                         if (rqst->rq_iov[i].iov_base != smb2_padding)
2969                                 kfree(rqst->rq_iov[i].iov_base);
2970         }
2971 }
2972
2973 int
2974 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2975           __u8 *oplock, struct smb2_file_all_info *buf,
2976           struct create_posix_rsp *posix,
2977           struct kvec *err_iov, int *buftype)
2978 {
2979         struct smb_rqst rqst;
2980         struct smb2_create_rsp *rsp = NULL;
2981         struct cifs_tcon *tcon = oparms->tcon;
2982         struct cifs_ses *ses = tcon->ses;
2983         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2984         struct kvec iov[SMB2_CREATE_IOV_SIZE];
2985         struct kvec rsp_iov = {NULL, 0};
2986         int resp_buftype = CIFS_NO_BUFFER;
2987         int rc = 0;
2988         int flags = 0;
2989
2990         cifs_dbg(FYI, "create/open\n");
2991         if (!ses || !server)
2992                 return -EIO;
2993
2994         if (smb3_encryption_required(tcon))
2995                 flags |= CIFS_TRANSFORM_REQ;
2996
2997         memset(&rqst, 0, sizeof(struct smb_rqst));
2998         memset(&iov, 0, sizeof(iov));
2999         rqst.rq_iov = iov;
3000         rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3001
3002         rc = SMB2_open_init(tcon, server,
3003                             &rqst, oplock, oparms, path);
3004         if (rc)
3005                 goto creat_exit;
3006
3007         trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
3008                 oparms->create_options, oparms->desired_access);
3009
3010         rc = cifs_send_recv(xid, ses, server,
3011                             &rqst, &resp_buftype, flags,
3012                             &rsp_iov);
3013         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3014
3015         if (rc != 0) {
3016                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3017                 if (err_iov && rsp) {
3018                         *err_iov = rsp_iov;
3019                         *buftype = resp_buftype;
3020                         resp_buftype = CIFS_NO_BUFFER;
3021                         rsp = NULL;
3022                 }
3023                 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3024                                     oparms->create_options, oparms->desired_access, rc);
3025                 if (rc == -EREMCHG) {
3026                         pr_warn_once("server share %s deleted\n",
3027                                      tcon->tree_name);
3028                         tcon->need_reconnect = true;
3029                 }
3030                 goto creat_exit;
3031         } else if (rsp == NULL) /* unlikely to happen, but safer to check */
3032                 goto creat_exit;
3033         else
3034                 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3035                                      oparms->create_options, oparms->desired_access);
3036
3037         atomic_inc(&tcon->num_remote_opens);
3038         oparms->fid->persistent_fid = rsp->PersistentFileId;
3039         oparms->fid->volatile_fid = rsp->VolatileFileId;
3040         oparms->fid->access = oparms->desired_access;
3041 #ifdef CONFIG_CIFS_DEBUG2
3042         oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3043 #endif /* CIFS_DEBUG2 */
3044
3045         if (buf) {
3046                 buf->CreationTime = rsp->CreationTime;
3047                 buf->LastAccessTime = rsp->LastAccessTime;
3048                 buf->LastWriteTime = rsp->LastWriteTime;
3049                 buf->ChangeTime = rsp->ChangeTime;
3050                 buf->AllocationSize = rsp->AllocationSize;
3051                 buf->EndOfFile = rsp->EndofFile;
3052                 buf->Attributes = rsp->FileAttributes;
3053                 buf->NumberOfLinks = cpu_to_le32(1);
3054                 buf->DeletePending = 0;
3055         }
3056
3057
3058         smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
3059                             oparms->fid->lease_key, oplock, buf, posix);
3060 creat_exit:
3061         SMB2_open_free(&rqst);
3062         free_rsp_buf(resp_buftype, rsp);
3063         return rc;
3064 }
3065
3066 int
3067 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3068                 struct smb_rqst *rqst,
3069                 u64 persistent_fid, u64 volatile_fid, u32 opcode,
3070                 char *in_data, u32 indatalen,
3071                 __u32 max_response_size)
3072 {
3073         struct smb2_ioctl_req *req;
3074         struct kvec *iov = rqst->rq_iov;
3075         unsigned int total_len;
3076         int rc;
3077         char *in_data_buf;
3078
3079         rc = smb2_ioctl_req_init(opcode, tcon, server,
3080                                  (void **) &req, &total_len);
3081         if (rc)
3082                 return rc;
3083
3084         if (indatalen) {
3085                 /*
3086                  * indatalen is usually small at a couple of bytes max, so
3087                  * just allocate through generic pool
3088                  */
3089                 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3090                 if (!in_data_buf) {
3091                         cifs_small_buf_release(req);
3092                         return -ENOMEM;
3093                 }
3094         }
3095
3096         req->CtlCode = cpu_to_le32(opcode);
3097         req->PersistentFileId = persistent_fid;
3098         req->VolatileFileId = volatile_fid;
3099
3100         iov[0].iov_base = (char *)req;
3101         /*
3102          * If no input data, the size of ioctl struct in
3103          * protocol spec still includes a 1 byte data buffer,
3104          * but if input data passed to ioctl, we do not
3105          * want to double count this, so we do not send
3106          * the dummy one byte of data in iovec[0] if sending
3107          * input data (in iovec[1]).
3108          */
3109         if (indatalen) {
3110                 req->InputCount = cpu_to_le32(indatalen);
3111                 /* do not set InputOffset if no input data */
3112                 req->InputOffset =
3113                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3114                 rqst->rq_nvec = 2;
3115                 iov[0].iov_len = total_len - 1;
3116                 iov[1].iov_base = in_data_buf;
3117                 iov[1].iov_len = indatalen;
3118         } else {
3119                 rqst->rq_nvec = 1;
3120                 iov[0].iov_len = total_len;
3121         }
3122
3123         req->OutputOffset = 0;
3124         req->OutputCount = 0; /* MBZ */
3125
3126         /*
3127          * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3128          * We Could increase default MaxOutputResponse, but that could require
3129          * more credits. Windows typically sets this smaller, but for some
3130          * ioctls it may be useful to allow server to send more. No point
3131          * limiting what the server can send as long as fits in one credit
3132          * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3133          * to increase this limit up in the future.
3134          * Note that for snapshot queries that servers like Azure expect that
3135          * the first query be minimal size (and just used to get the number/size
3136          * of previous versions) so response size must be specified as EXACTLY
3137          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3138          * of eight bytes.  Currently that is the only case where we set max
3139          * response size smaller.
3140          */
3141         req->MaxOutputResponse = cpu_to_le32(max_response_size);
3142         req->hdr.CreditCharge =
3143                 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3144                                          SMB2_MAX_BUFFER_SIZE));
3145         /* always an FSCTL (for now) */
3146         req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3147
3148         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3149         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3150                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3151
3152         return 0;
3153 }
3154
3155 void
3156 SMB2_ioctl_free(struct smb_rqst *rqst)
3157 {
3158         int i;
3159         if (rqst && rqst->rq_iov) {
3160                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3161                 for (i = 1; i < rqst->rq_nvec; i++)
3162                         if (rqst->rq_iov[i].iov_base != smb2_padding)
3163                                 kfree(rqst->rq_iov[i].iov_base);
3164         }
3165 }
3166
3167
3168 /*
3169  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
3170  */
3171 int
3172 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3173            u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3174            u32 max_out_data_len, char **out_data,
3175            u32 *plen /* returned data len */)
3176 {
3177         struct smb_rqst rqst;
3178         struct smb2_ioctl_rsp *rsp = NULL;
3179         struct cifs_ses *ses;
3180         struct TCP_Server_Info *server;
3181         struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3182         struct kvec rsp_iov = {NULL, 0};
3183         int resp_buftype = CIFS_NO_BUFFER;
3184         int rc = 0;
3185         int flags = 0;
3186
3187         cifs_dbg(FYI, "SMB2 IOCTL\n");
3188
3189         if (out_data != NULL)
3190                 *out_data = NULL;
3191
3192         /* zero out returned data len, in case of error */
3193         if (plen)
3194                 *plen = 0;
3195
3196         if (!tcon)
3197                 return -EIO;
3198
3199         ses = tcon->ses;
3200         if (!ses)
3201                 return -EIO;
3202
3203         server = cifs_pick_channel(ses);
3204         if (!server)
3205                 return -EIO;
3206
3207         if (smb3_encryption_required(tcon))
3208                 flags |= CIFS_TRANSFORM_REQ;
3209
3210         memset(&rqst, 0, sizeof(struct smb_rqst));
3211         memset(&iov, 0, sizeof(iov));
3212         rqst.rq_iov = iov;
3213         rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3214
3215         rc = SMB2_ioctl_init(tcon, server,
3216                              &rqst, persistent_fid, volatile_fid, opcode,
3217                              in_data, indatalen, max_out_data_len);
3218         if (rc)
3219                 goto ioctl_exit;
3220
3221         rc = cifs_send_recv(xid, ses, server,
3222                             &rqst, &resp_buftype, flags,
3223                             &rsp_iov);
3224         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3225
3226         if (rc != 0)
3227                 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3228                                 ses->Suid, 0, opcode, rc);
3229
3230         if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3231                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3232                 goto ioctl_exit;
3233         } else if (rc == -EINVAL) {
3234                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3235                     (opcode != FSCTL_SRV_COPYCHUNK)) {
3236                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3237                         goto ioctl_exit;
3238                 }
3239         } else if (rc == -E2BIG) {
3240                 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3241                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3242                         goto ioctl_exit;
3243                 }
3244         }
3245
3246         /* check if caller wants to look at return data or just return rc */
3247         if ((plen == NULL) || (out_data == NULL))
3248                 goto ioctl_exit;
3249
3250         /*
3251          * Although unlikely to be possible for rsp to be null and rc not set,
3252          * adding check below is slightly safer long term (and quiets Coverity
3253          * warning)
3254          */
3255         if (rsp == NULL) {
3256                 rc = -EIO;
3257                 goto ioctl_exit;
3258         }
3259
3260         *plen = le32_to_cpu(rsp->OutputCount);
3261
3262         /* We check for obvious errors in the output buffer length and offset */
3263         if (*plen == 0)
3264                 goto ioctl_exit; /* server returned no data */
3265         else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3266                 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3267                 *plen = 0;
3268                 rc = -EIO;
3269                 goto ioctl_exit;
3270         }
3271
3272         if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3273                 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3274                         le32_to_cpu(rsp->OutputOffset));
3275                 *plen = 0;
3276                 rc = -EIO;
3277                 goto ioctl_exit;
3278         }
3279
3280         *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3281                             *plen, GFP_KERNEL);
3282         if (*out_data == NULL) {
3283                 rc = -ENOMEM;
3284                 goto ioctl_exit;
3285         }
3286
3287 ioctl_exit:
3288         SMB2_ioctl_free(&rqst);
3289         free_rsp_buf(resp_buftype, rsp);
3290         return rc;
3291 }
3292
3293 /*
3294  *   Individual callers to ioctl worker function follow
3295  */
3296
3297 int
3298 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3299                      u64 persistent_fid, u64 volatile_fid)
3300 {
3301         int rc;
3302         struct  compress_ioctl fsctl_input;
3303         char *ret_data = NULL;
3304
3305         fsctl_input.CompressionState =
3306                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3307
3308         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3309                         FSCTL_SET_COMPRESSION,
3310                         (char *)&fsctl_input /* data input */,
3311                         2 /* in data len */, CIFSMaxBufSize /* max out data */,
3312                         &ret_data /* out data */, NULL);
3313
3314         cifs_dbg(FYI, "set compression rc %d\n", rc);
3315
3316         return rc;
3317 }
3318
3319 int
3320 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3321                 struct smb_rqst *rqst,
3322                 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3323 {
3324         struct smb2_close_req *req;
3325         struct kvec *iov = rqst->rq_iov;
3326         unsigned int total_len;
3327         int rc;
3328
3329         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3330                                  (void **) &req, &total_len);
3331         if (rc)
3332                 return rc;
3333
3334         req->PersistentFileId = persistent_fid;
3335         req->VolatileFileId = volatile_fid;
3336         if (query_attrs)
3337                 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3338         else
3339                 req->Flags = 0;
3340         iov[0].iov_base = (char *)req;
3341         iov[0].iov_len = total_len;
3342
3343         return 0;
3344 }
3345
3346 void
3347 SMB2_close_free(struct smb_rqst *rqst)
3348 {
3349         if (rqst && rqst->rq_iov)
3350                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3351 }
3352
3353 int
3354 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3355              u64 persistent_fid, u64 volatile_fid,
3356              struct smb2_file_network_open_info *pbuf)
3357 {
3358         struct smb_rqst rqst;
3359         struct smb2_close_rsp *rsp = NULL;
3360         struct cifs_ses *ses = tcon->ses;
3361         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3362         struct kvec iov[1];
3363         struct kvec rsp_iov;
3364         int resp_buftype = CIFS_NO_BUFFER;
3365         int rc = 0;
3366         int flags = 0;
3367         bool query_attrs = false;
3368
3369         cifs_dbg(FYI, "Close\n");
3370
3371         if (!ses || !server)
3372                 return -EIO;
3373
3374         if (smb3_encryption_required(tcon))
3375                 flags |= CIFS_TRANSFORM_REQ;
3376
3377         memset(&rqst, 0, sizeof(struct smb_rqst));
3378         memset(&iov, 0, sizeof(iov));
3379         rqst.rq_iov = iov;
3380         rqst.rq_nvec = 1;
3381
3382         /* check if need to ask server to return timestamps in close response */
3383         if (pbuf)
3384                 query_attrs = true;
3385
3386         trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3387         rc = SMB2_close_init(tcon, server,
3388                              &rqst, persistent_fid, volatile_fid,
3389                              query_attrs);
3390         if (rc)
3391                 goto close_exit;
3392
3393         rc = cifs_send_recv(xid, ses, server,
3394                             &rqst, &resp_buftype, flags, &rsp_iov);
3395         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3396
3397         if (rc != 0) {
3398                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3399                 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3400                                      rc);
3401                 goto close_exit;
3402         } else {
3403                 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3404                                       ses->Suid);
3405                 /*
3406                  * Note that have to subtract 4 since struct network_open_info
3407                  * has a final 4 byte pad that close response does not have
3408                  */
3409                 if (pbuf)
3410                         memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3411         }
3412
3413         atomic_dec(&tcon->num_remote_opens);
3414 close_exit:
3415         SMB2_close_free(&rqst);
3416         free_rsp_buf(resp_buftype, rsp);
3417
3418         /* retry close in a worker thread if this one is interrupted */
3419         if (is_interrupt_error(rc)) {
3420                 int tmp_rc;
3421
3422                 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3423                                                      volatile_fid);
3424                 if (tmp_rc)
3425                         cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3426                                  persistent_fid, tmp_rc);
3427         }
3428         return rc;
3429 }
3430
3431 int
3432 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3433                 u64 persistent_fid, u64 volatile_fid)
3434 {
3435         return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3436 }
3437
3438 int
3439 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3440                   struct kvec *iov, unsigned int min_buf_size)
3441 {
3442         unsigned int smb_len = iov->iov_len;
3443         char *end_of_smb = smb_len + (char *)iov->iov_base;
3444         char *begin_of_buf = offset + (char *)iov->iov_base;
3445         char *end_of_buf = begin_of_buf + buffer_length;
3446
3447
3448         if (buffer_length < min_buf_size) {
3449                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3450                          buffer_length, min_buf_size);
3451                 return -EINVAL;
3452         }
3453
3454         /* check if beyond RFC1001 maximum length */
3455         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3456                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3457                          buffer_length, smb_len);
3458                 return -EINVAL;
3459         }
3460
3461         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3462                 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3463                 return -EINVAL;
3464         }
3465
3466         return 0;
3467 }
3468
3469 /*
3470  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3471  * Caller must free buffer.
3472  */
3473 int
3474 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3475                            struct kvec *iov, unsigned int minbufsize,
3476                            char *data)
3477 {
3478         char *begin_of_buf = offset + (char *)iov->iov_base;
3479         int rc;
3480
3481         if (!data)
3482                 return -EINVAL;
3483
3484         rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3485         if (rc)
3486                 return rc;
3487
3488         memcpy(data, begin_of_buf, minbufsize);
3489
3490         return 0;
3491 }
3492
3493 int
3494 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3495                      struct smb_rqst *rqst,
3496                      u64 persistent_fid, u64 volatile_fid,
3497                      u8 info_class, u8 info_type, u32 additional_info,
3498                      size_t output_len, size_t input_len, void *input)
3499 {
3500         struct smb2_query_info_req *req;
3501         struct kvec *iov = rqst->rq_iov;
3502         unsigned int total_len;
3503         int rc;
3504
3505         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3506                                  (void **) &req, &total_len);
3507         if (rc)
3508                 return rc;
3509
3510         req->InfoType = info_type;
3511         req->FileInfoClass = info_class;
3512         req->PersistentFileId = persistent_fid;
3513         req->VolatileFileId = volatile_fid;
3514         req->AdditionalInformation = cpu_to_le32(additional_info);
3515
3516         req->OutputBufferLength = cpu_to_le32(output_len);
3517         if (input_len) {
3518                 req->InputBufferLength = cpu_to_le32(input_len);
3519                 /* total_len for smb query request never close to le16 max */
3520                 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3521                 memcpy(req->Buffer, input, input_len);
3522         }
3523
3524         iov[0].iov_base = (char *)req;
3525         /* 1 for Buffer */
3526         iov[0].iov_len = total_len - 1 + input_len;
3527         return 0;
3528 }
3529
3530 void
3531 SMB2_query_info_free(struct smb_rqst *rqst)
3532 {
3533         if (rqst && rqst->rq_iov)
3534                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3535 }
3536
3537 static int
3538 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3539            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3540            u32 additional_info, size_t output_len, size_t min_len, void **data,
3541                 u32 *dlen)
3542 {
3543         struct smb_rqst rqst;
3544         struct smb2_query_info_rsp *rsp = NULL;
3545         struct kvec iov[1];
3546         struct kvec rsp_iov;
3547         int rc = 0;
3548         int resp_buftype = CIFS_NO_BUFFER;
3549         struct cifs_ses *ses = tcon->ses;
3550         struct TCP_Server_Info *server;
3551         int flags = 0;
3552         bool allocated = false;
3553
3554         cifs_dbg(FYI, "Query Info\n");
3555
3556         if (!ses)
3557                 return -EIO;
3558         server = cifs_pick_channel(ses);
3559         if (!server)
3560                 return -EIO;
3561
3562         if (smb3_encryption_required(tcon))
3563                 flags |= CIFS_TRANSFORM_REQ;
3564
3565         memset(&rqst, 0, sizeof(struct smb_rqst));
3566         memset(&iov, 0, sizeof(iov));
3567         rqst.rq_iov = iov;
3568         rqst.rq_nvec = 1;
3569
3570         rc = SMB2_query_info_init(tcon, server,
3571                                   &rqst, persistent_fid, volatile_fid,
3572                                   info_class, info_type, additional_info,
3573                                   output_len, 0, NULL);
3574         if (rc)
3575                 goto qinf_exit;
3576
3577         trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3578                                     ses->Suid, info_class, (__u32)info_type);
3579
3580         rc = cifs_send_recv(xid, ses, server,
3581                             &rqst, &resp_buftype, flags, &rsp_iov);
3582         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3583
3584         if (rc) {
3585                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3586                 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3587                                 ses->Suid, info_class, (__u32)info_type, rc);
3588                 goto qinf_exit;
3589         }
3590
3591         trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3592                                 ses->Suid, info_class, (__u32)info_type);
3593
3594         if (dlen) {
3595                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3596                 if (!*data) {
3597                         *data = kmalloc(*dlen, GFP_KERNEL);
3598                         if (!*data) {
3599                                 cifs_tcon_dbg(VFS,
3600                                         "Error %d allocating memory for acl\n",
3601                                         rc);
3602                                 *dlen = 0;
3603                                 rc = -ENOMEM;
3604                                 goto qinf_exit;
3605                         }
3606                         allocated = true;
3607                 }
3608         }
3609
3610         rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3611                                         le32_to_cpu(rsp->OutputBufferLength),
3612                                         &rsp_iov, dlen ? *dlen : min_len, *data);
3613         if (rc && allocated) {
3614                 kfree(*data);
3615                 *data = NULL;
3616                 *dlen = 0;
3617         }
3618
3619 qinf_exit:
3620         SMB2_query_info_free(&rqst);
3621         free_rsp_buf(resp_buftype, rsp);
3622         return rc;
3623 }
3624
3625 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3626         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3627 {
3628         return query_info(xid, tcon, persistent_fid, volatile_fid,
3629                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3630                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3631                           sizeof(struct smb2_file_all_info), (void **)&data,
3632                           NULL);
3633 }
3634
3635 #if 0
3636 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3637 int
3638 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3639                 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3640 {
3641         size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3642                         (sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3643         *plen = 0;
3644
3645         return query_info(xid, tcon, persistent_fid, volatile_fid,
3646                           SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3647                           output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3648         /* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3649 }
3650 #endif
3651
3652 int
3653 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3654                u64 persistent_fid, u64 volatile_fid,
3655                void **data, u32 *plen, u32 extra_info)
3656 {
3657         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3658                                 extra_info;
3659         *plen = 0;
3660
3661         return query_info(xid, tcon, persistent_fid, volatile_fid,
3662                           0, SMB2_O_INFO_SECURITY, additional_info,
3663                           SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3664 }
3665
3666 int
3667 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3668                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3669 {
3670         return query_info(xid, tcon, persistent_fid, volatile_fid,
3671                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3672                           sizeof(struct smb2_file_internal_info),
3673                           sizeof(struct smb2_file_internal_info),
3674                           (void **)&uniqueid, NULL);
3675 }
3676
3677 /*
3678  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3679  * See MS-SMB2 2.2.35 and 2.2.36
3680  */
3681
3682 static int
3683 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3684                  struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3685                  u64 persistent_fid, u64 volatile_fid,
3686                  u32 completion_filter, bool watch_tree)
3687 {
3688         struct smb2_change_notify_req *req;
3689         struct kvec *iov = rqst->rq_iov;
3690         unsigned int total_len;
3691         int rc;
3692
3693         rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3694                                  (void **) &req, &total_len);
3695         if (rc)
3696                 return rc;
3697
3698         req->PersistentFileId = persistent_fid;
3699         req->VolatileFileId = volatile_fid;
3700         /* See note 354 of MS-SMB2, 64K max */
3701         req->OutputBufferLength =
3702                 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3703         req->CompletionFilter = cpu_to_le32(completion_filter);
3704         if (watch_tree)
3705                 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3706         else
3707                 req->Flags = 0;
3708
3709         iov[0].iov_base = (char *)req;
3710         iov[0].iov_len = total_len;
3711
3712         return 0;
3713 }
3714
3715 int
3716 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3717                 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3718                 u32 completion_filter, u32 max_out_data_len, char **out_data,
3719                 u32 *plen /* returned data len */)
3720 {
3721         struct cifs_ses *ses = tcon->ses;
3722         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3723         struct smb_rqst rqst;
3724         struct smb2_change_notify_rsp *smb_rsp;
3725         struct kvec iov[1];
3726         struct kvec rsp_iov = {NULL, 0};
3727         int resp_buftype = CIFS_NO_BUFFER;
3728         int flags = 0;
3729         int rc = 0;
3730
3731         cifs_dbg(FYI, "change notify\n");
3732         if (!ses || !server)
3733                 return -EIO;
3734
3735         if (smb3_encryption_required(tcon))
3736                 flags |= CIFS_TRANSFORM_REQ;
3737
3738         memset(&rqst, 0, sizeof(struct smb_rqst));
3739         memset(&iov, 0, sizeof(iov));
3740         if (plen)
3741                 *plen = 0;
3742
3743         rqst.rq_iov = iov;
3744         rqst.rq_nvec = 1;
3745
3746         rc = SMB2_notify_init(xid, &rqst, tcon, server,
3747                               persistent_fid, volatile_fid,
3748                               completion_filter, watch_tree);
3749         if (rc)
3750                 goto cnotify_exit;
3751
3752         trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3753                                 (u8)watch_tree, completion_filter);
3754         rc = cifs_send_recv(xid, ses, server,
3755                             &rqst, &resp_buftype, flags, &rsp_iov);
3756
3757         if (rc != 0) {
3758                 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3759                 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3760                                 (u8)watch_tree, completion_filter, rc);
3761         } else {
3762                 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3763                         ses->Suid, (u8)watch_tree, completion_filter);
3764                 /* validate that notify information is plausible */
3765                 if ((rsp_iov.iov_base == NULL) ||
3766                     (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp)))
3767                         goto cnotify_exit;
3768
3769                 smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
3770
3771                 smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
3772                                 le32_to_cpu(smb_rsp->OutputBufferLength), &rsp_iov,
3773                                 sizeof(struct file_notify_information));
3774
3775                 *out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
3776                                 le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
3777                 if (*out_data == NULL) {
3778                         rc = -ENOMEM;
3779                         goto cnotify_exit;
3780                 } else
3781                         *plen = le32_to_cpu(smb_rsp->OutputBufferLength);
3782         }
3783
3784  cnotify_exit:
3785         if (rqst.rq_iov)
3786                 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3787         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3788         return rc;
3789 }
3790
3791
3792
3793 /*
3794  * This is a no-op for now. We're not really interested in the reply, but
3795  * rather in the fact that the server sent one and that server->lstrp
3796  * gets updated.
3797  *
3798  * FIXME: maybe we should consider checking that the reply matches request?
3799  */
3800 static void
3801 smb2_echo_callback(struct mid_q_entry *mid)
3802 {
3803         struct TCP_Server_Info *server = mid->callback_data;
3804         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3805         struct cifs_credits credits = { .value = 0, .instance = 0 };
3806
3807         if (mid->mid_state == MID_RESPONSE_RECEIVED
3808             || mid->mid_state == MID_RESPONSE_MALFORMED) {
3809                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
3810                 credits.instance = server->reconnect_instance;
3811         }
3812
3813         release_mid(mid);
3814         add_credits(server, &credits, CIFS_ECHO_OP);
3815 }
3816
3817 void smb2_reconnect_server(struct work_struct *work)
3818 {
3819         struct TCP_Server_Info *server = container_of(work,
3820                                         struct TCP_Server_Info, reconnect.work);
3821         struct TCP_Server_Info *pserver;
3822         struct cifs_ses *ses, *ses2;
3823         struct cifs_tcon *tcon, *tcon2;
3824         struct list_head tmp_list, tmp_ses_list;
3825         bool tcon_exist = false, ses_exist = false;
3826         bool tcon_selected = false;
3827         int rc;
3828         bool resched = false;
3829
3830         /* If server is a channel, select the primary channel */
3831         pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
3832
3833         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3834         mutex_lock(&pserver->reconnect_mutex);
3835
3836         INIT_LIST_HEAD(&tmp_list);
3837         INIT_LIST_HEAD(&tmp_ses_list);
3838         cifs_dbg(FYI, "Reconnecting tcons and channels\n");
3839
3840         spin_lock(&cifs_tcp_ses_lock);
3841         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
3842
3843                 tcon_selected = false;
3844
3845                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3846                         if (tcon->need_reconnect || tcon->need_reopen_files) {
3847                                 tcon->tc_count++;
3848                                 list_add_tail(&tcon->rlist, &tmp_list);
3849                                 tcon_selected = tcon_exist = true;
3850                         }
3851                 }
3852                 /*
3853                  * IPC has the same lifetime as its session and uses its
3854                  * refcount.
3855                  */
3856                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3857                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3858                         tcon_selected = tcon_exist = true;
3859                         ses->ses_count++;
3860                 }
3861                 /*
3862                  * handle the case where channel needs to reconnect
3863                  * binding session, but tcon is healthy (some other channel
3864                  * is active)
3865                  */
3866                 spin_lock(&ses->chan_lock);
3867                 if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
3868                         list_add_tail(&ses->rlist, &tmp_ses_list);
3869                         ses_exist = true;
3870                         ses->ses_count++;
3871                 }
3872                 spin_unlock(&ses->chan_lock);
3873         }
3874         /*
3875          * Get the reference to server struct to be sure that the last call of
3876          * cifs_put_tcon() in the loop below won't release the server pointer.
3877          */
3878         if (tcon_exist || ses_exist)
3879                 server->srv_count++;
3880
3881         spin_unlock(&cifs_tcp_ses_lock);
3882
3883         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3884                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3885                 if (!rc)
3886                         cifs_reopen_persistent_handles(tcon);
3887                 else
3888                         resched = true;
3889                 list_del_init(&tcon->rlist);
3890                 if (tcon->ipc)
3891                         cifs_put_smb_ses(tcon->ses);
3892                 else
3893                         cifs_put_tcon(tcon);
3894         }
3895
3896         if (!ses_exist)
3897                 goto done;
3898
3899         /* allocate a dummy tcon struct used for reconnect */
3900         tcon = kzalloc(sizeof(struct cifs_tcon), GFP_KERNEL);
3901         if (!tcon) {
3902                 resched = true;
3903                 list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3904                         list_del_init(&ses->rlist);
3905                         cifs_put_smb_ses(ses);
3906                 }
3907                 goto done;
3908         }
3909
3910         tcon->status = TID_GOOD;
3911         tcon->retry = false;
3912         tcon->need_reconnect = false;
3913
3914         /* now reconnect sessions for necessary channels */
3915         list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3916                 tcon->ses = ses;
3917                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3918                 if (rc)
3919                         resched = true;
3920                 list_del_init(&ses->rlist);
3921                 cifs_put_smb_ses(ses);
3922         }
3923         kfree(tcon);
3924
3925 done:
3926         cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
3927         if (resched)
3928                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3929         mutex_unlock(&pserver->reconnect_mutex);
3930
3931         /* now we can safely release srv struct */
3932         if (tcon_exist || ses_exist)
3933                 cifs_put_tcp_session(server, 1);
3934 }
3935
3936 int
3937 SMB2_echo(struct TCP_Server_Info *server)
3938 {
3939         struct smb2_echo_req *req;
3940         int rc = 0;
3941         struct kvec iov[1];
3942         struct smb_rqst rqst = { .rq_iov = iov,
3943                                  .rq_nvec = 1 };
3944         unsigned int total_len;
3945
3946         cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
3947
3948         spin_lock(&server->srv_lock);
3949         if (server->ops->need_neg &&
3950             server->ops->need_neg(server)) {
3951                 spin_unlock(&server->srv_lock);
3952                 /* No need to send echo on newly established connections */
3953                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3954                 return rc;
3955         }
3956         spin_unlock(&server->srv_lock);
3957
3958         rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
3959                                  (void **)&req, &total_len);
3960         if (rc)
3961                 return rc;
3962
3963         req->hdr.CreditRequest = cpu_to_le16(1);
3964
3965         iov[0].iov_len = total_len;
3966         iov[0].iov_base = (char *)req;
3967
3968         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3969                              server, CIFS_ECHO_OP, NULL);
3970         if (rc)
3971                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3972
3973         cifs_small_buf_release(req);
3974         return rc;
3975 }
3976
3977 void
3978 SMB2_flush_free(struct smb_rqst *rqst)
3979 {
3980         if (rqst && rqst->rq_iov)
3981                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3982 }
3983
3984 int
3985 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3986                 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3987                 u64 persistent_fid, u64 volatile_fid)
3988 {
3989         struct smb2_flush_req *req;
3990         struct kvec *iov = rqst->rq_iov;
3991         unsigned int total_len;
3992         int rc;
3993
3994         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
3995                                  (void **) &req, &total_len);
3996         if (rc)
3997                 return rc;
3998
3999         req->PersistentFileId = persistent_fid;
4000         req->VolatileFileId = volatile_fid;
4001
4002         iov[0].iov_base = (char *)req;
4003         iov[0].iov_len = total_len;
4004
4005         return 0;
4006 }
4007
4008 int
4009 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4010            u64 volatile_fid)
4011 {
4012         struct cifs_ses *ses = tcon->ses;
4013         struct smb_rqst rqst;
4014         struct kvec iov[1];
4015         struct kvec rsp_iov = {NULL, 0};
4016         struct TCP_Server_Info *server = cifs_pick_channel(ses);
4017         int resp_buftype = CIFS_NO_BUFFER;
4018         int flags = 0;
4019         int rc = 0;
4020
4021         cifs_dbg(FYI, "flush\n");
4022         if (!ses || !(ses->server))
4023                 return -EIO;
4024
4025         if (smb3_encryption_required(tcon))
4026                 flags |= CIFS_TRANSFORM_REQ;
4027
4028         memset(&rqst, 0, sizeof(struct smb_rqst));
4029         memset(&iov, 0, sizeof(iov));
4030         rqst.rq_iov = iov;
4031         rqst.rq_nvec = 1;
4032
4033         rc = SMB2_flush_init(xid, &rqst, tcon, server,
4034                              persistent_fid, volatile_fid);
4035         if (rc)
4036                 goto flush_exit;
4037
4038         trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4039         rc = cifs_send_recv(xid, ses, server,
4040                             &rqst, &resp_buftype, flags, &rsp_iov);
4041
4042         if (rc != 0) {
4043                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4044                 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4045                                      rc);
4046         } else
4047                 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4048                                       ses->Suid);
4049
4050  flush_exit:
4051         SMB2_flush_free(&rqst);
4052         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4053         return rc;
4054 }
4055
4056 /*
4057  * To form a chain of read requests, any read requests after the first should
4058  * have the end_of_chain boolean set to true.
4059  */
4060 static int
4061 smb2_new_read_req(void **buf, unsigned int *total_len,
4062         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
4063         unsigned int remaining_bytes, int request_type)
4064 {
4065         int rc = -EACCES;
4066         struct smb2_read_req *req = NULL;
4067         struct smb2_hdr *shdr;
4068         struct TCP_Server_Info *server = io_parms->server;
4069
4070         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4071                                  (void **) &req, total_len);
4072         if (rc)
4073                 return rc;
4074
4075         if (server == NULL)
4076                 return -ECONNABORTED;
4077
4078         shdr = &req->hdr;
4079         shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4080
4081         req->PersistentFileId = io_parms->persistent_fid;
4082         req->VolatileFileId = io_parms->volatile_fid;
4083         req->ReadChannelInfoOffset = 0; /* reserved */
4084         req->ReadChannelInfoLength = 0; /* reserved */
4085         req->Channel = 0; /* reserved */
4086         req->MinimumCount = 0;
4087         req->Length = cpu_to_le32(io_parms->length);
4088         req->Offset = cpu_to_le64(io_parms->offset);
4089
4090         trace_smb3_read_enter(0 /* xid */,
4091                         io_parms->persistent_fid,
4092                         io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4093                         io_parms->offset, io_parms->length);
4094 #ifdef CONFIG_CIFS_SMB_DIRECT
4095         /*
4096          * If we want to do a RDMA write, fill in and append
4097          * smbd_buffer_descriptor_v1 to the end of read request
4098          */
4099         if (server->rdma && rdata && !server->sign &&
4100                 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
4101
4102                 struct smbd_buffer_descriptor_v1 *v1;
4103                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4104
4105                 rdata->mr = smbd_register_mr(
4106                                 server->smbd_conn, rdata->pages,
4107                                 rdata->nr_pages, rdata->page_offset,
4108                                 rdata->tailsz, true, need_invalidate);
4109                 if (!rdata->mr)
4110                         return -EAGAIN;
4111
4112                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4113                 if (need_invalidate)
4114                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4115                 req->ReadChannelInfoOffset =
4116                         cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4117                 req->ReadChannelInfoLength =
4118                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4119                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4120                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4121                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4122                 v1->length = cpu_to_le32(rdata->mr->mr->length);
4123
4124                 *total_len += sizeof(*v1) - 1;
4125         }
4126 #endif
4127         if (request_type & CHAINED_REQUEST) {
4128                 if (!(request_type & END_OF_CHAIN)) {
4129                         /* next 8-byte aligned request */
4130                         *total_len = ALIGN(*total_len, 8);
4131                         shdr->NextCommand = cpu_to_le32(*total_len);
4132                 } else /* END_OF_CHAIN */
4133                         shdr->NextCommand = 0;
4134                 if (request_type & RELATED_REQUEST) {
4135                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4136                         /*
4137                          * Related requests use info from previous read request
4138                          * in chain.
4139                          */
4140                         shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4141                         shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4142                         req->PersistentFileId = (u64)-1;
4143                         req->VolatileFileId = (u64)-1;
4144                 }
4145         }
4146         if (remaining_bytes > io_parms->length)
4147                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
4148         else
4149                 req->RemainingBytes = 0;
4150
4151         *buf = req;
4152         return rc;
4153 }
4154
4155 static void
4156 smb2_readv_callback(struct mid_q_entry *mid)
4157 {
4158         struct cifs_readdata *rdata = mid->callback_data;
4159         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4160         struct TCP_Server_Info *server = rdata->server;
4161         struct smb2_hdr *shdr =
4162                                 (struct smb2_hdr *)rdata->iov[0].iov_base;
4163         struct cifs_credits credits = { .value = 0, .instance = 0 };
4164         struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
4165                                  .rq_nvec = 1,
4166                                  .rq_pages = rdata->pages,
4167                                  .rq_offset = rdata->page_offset,
4168                                  .rq_npages = rdata->nr_pages,
4169                                  .rq_pagesz = rdata->pagesz,
4170                                  .rq_tailsz = rdata->tailsz };
4171
4172         WARN_ONCE(rdata->server != mid->server,
4173                   "rdata server %p != mid server %p",
4174                   rdata->server, mid->server);
4175
4176         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
4177                  __func__, mid->mid, mid->mid_state, rdata->result,
4178                  rdata->bytes);
4179
4180         switch (mid->mid_state) {
4181         case MID_RESPONSE_RECEIVED:
4182                 credits.value = le16_to_cpu(shdr->CreditRequest);
4183                 credits.instance = server->reconnect_instance;
4184                 /* result already set, check signature */
4185                 if (server->sign && !mid->decrypted) {
4186                         int rc;
4187
4188                         rc = smb2_verify_signature(&rqst, server);
4189                         if (rc)
4190                                 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4191                                          rc);
4192                 }
4193                 /* FIXME: should this be counted toward the initiating task? */
4194                 task_io_account_read(rdata->got_bytes);
4195                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4196                 break;
4197         case MID_REQUEST_SUBMITTED:
4198         case MID_RETRY_NEEDED:
4199                 rdata->result = -EAGAIN;
4200                 if (server->sign && rdata->got_bytes)
4201                         /* reset bytes number since we can not check a sign */
4202                         rdata->got_bytes = 0;
4203                 /* FIXME: should this be counted toward the initiating task? */
4204                 task_io_account_read(rdata->got_bytes);
4205                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4206                 break;
4207         case MID_RESPONSE_MALFORMED:
4208                 credits.value = le16_to_cpu(shdr->CreditRequest);
4209                 credits.instance = server->reconnect_instance;
4210                 fallthrough;
4211         default:
4212                 rdata->result = -EIO;
4213         }
4214 #ifdef CONFIG_CIFS_SMB_DIRECT
4215         /*
4216          * If this rdata has a memmory registered, the MR can be freed
4217          * MR needs to be freed as soon as I/O finishes to prevent deadlock
4218          * because they have limited number and are used for future I/Os
4219          */
4220         if (rdata->mr) {
4221                 smbd_deregister_mr(rdata->mr);
4222                 rdata->mr = NULL;
4223         }
4224 #endif
4225         if (rdata->result && rdata->result != -ENODATA) {
4226                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4227                 trace_smb3_read_err(0 /* xid */,
4228                                     rdata->cfile->fid.persistent_fid,
4229                                     tcon->tid, tcon->ses->Suid, rdata->offset,
4230                                     rdata->bytes, rdata->result);
4231         } else
4232                 trace_smb3_read_done(0 /* xid */,
4233                                      rdata->cfile->fid.persistent_fid,
4234                                      tcon->tid, tcon->ses->Suid,
4235                                      rdata->offset, rdata->got_bytes);
4236
4237         queue_work(cifsiod_wq, &rdata->work);
4238         release_mid(mid);
4239         add_credits(server, &credits, 0);
4240 }
4241
4242 /* smb2_async_readv - send an async read, and set up mid to handle result */
4243 int
4244 smb2_async_readv(struct cifs_readdata *rdata)
4245 {
4246         int rc, flags = 0;
4247         char *buf;
4248         struct smb2_hdr *shdr;
4249         struct cifs_io_parms io_parms;
4250         struct smb_rqst rqst = { .rq_iov = rdata->iov,
4251                                  .rq_nvec = 1 };
4252         struct TCP_Server_Info *server;
4253         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4254         unsigned int total_len;
4255
4256         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4257                  __func__, rdata->offset, rdata->bytes);
4258
4259         if (!rdata->server)
4260                 rdata->server = cifs_pick_channel(tcon->ses);
4261
4262         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4263         io_parms.server = server = rdata->server;
4264         io_parms.offset = rdata->offset;
4265         io_parms.length = rdata->bytes;
4266         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4267         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4268         io_parms.pid = rdata->pid;
4269
4270         rc = smb2_new_read_req(
4271                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4272         if (rc)
4273                 return rc;
4274
4275         if (smb3_encryption_required(io_parms.tcon))
4276                 flags |= CIFS_TRANSFORM_REQ;
4277
4278         rdata->iov[0].iov_base = buf;
4279         rdata->iov[0].iov_len = total_len;
4280
4281         shdr = (struct smb2_hdr *)buf;
4282
4283         if (rdata->credits.value > 0) {
4284                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4285                                                 SMB2_MAX_BUFFER_SIZE));
4286                 shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4287
4288                 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4289                 if (rc)
4290                         goto async_readv_out;
4291
4292                 flags |= CIFS_HAS_CREDITS;
4293         }
4294
4295         kref_get(&rdata->refcount);
4296         rc = cifs_call_async(server, &rqst,
4297                              cifs_readv_receive, smb2_readv_callback,
4298                              smb3_handle_read_data, rdata, flags,
4299                              &rdata->credits);
4300         if (rc) {
4301                 kref_put(&rdata->refcount, cifs_readdata_release);
4302                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4303                 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4304                                     io_parms.tcon->tid,
4305                                     io_parms.tcon->ses->Suid,
4306                                     io_parms.offset, io_parms.length, rc);
4307         }
4308
4309 async_readv_out:
4310         cifs_small_buf_release(buf);
4311         return rc;
4312 }
4313
4314 int
4315 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4316           unsigned int *nbytes, char **buf, int *buf_type)
4317 {
4318         struct smb_rqst rqst;
4319         int resp_buftype, rc;
4320         struct smb2_read_req *req = NULL;
4321         struct smb2_read_rsp *rsp = NULL;
4322         struct kvec iov[1];
4323         struct kvec rsp_iov;
4324         unsigned int total_len;
4325         int flags = CIFS_LOG_ERROR;
4326         struct cifs_ses *ses = io_parms->tcon->ses;
4327
4328         if (!io_parms->server)
4329                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4330
4331         *nbytes = 0;
4332         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4333         if (rc)
4334                 return rc;
4335
4336         if (smb3_encryption_required(io_parms->tcon))
4337                 flags |= CIFS_TRANSFORM_REQ;
4338
4339         iov[0].iov_base = (char *)req;
4340         iov[0].iov_len = total_len;
4341
4342         memset(&rqst, 0, sizeof(struct smb_rqst));
4343         rqst.rq_iov = iov;
4344         rqst.rq_nvec = 1;
4345
4346         rc = cifs_send_recv(xid, ses, io_parms->server,
4347                             &rqst, &resp_buftype, flags, &rsp_iov);
4348         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4349
4350         if (rc) {
4351                 if (rc != -ENODATA) {
4352                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4353                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
4354                         trace_smb3_read_err(xid,
4355                                             req->PersistentFileId,
4356                                             io_parms->tcon->tid, ses->Suid,
4357                                             io_parms->offset, io_parms->length,
4358                                             rc);
4359                 } else
4360                         trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
4361                                              ses->Suid, io_parms->offset, 0);
4362                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4363                 cifs_small_buf_release(req);
4364                 return rc == -ENODATA ? 0 : rc;
4365         } else
4366                 trace_smb3_read_done(xid,
4367                                     req->PersistentFileId,
4368                                     io_parms->tcon->tid, ses->Suid,
4369                                     io_parms->offset, io_parms->length);
4370
4371         cifs_small_buf_release(req);
4372
4373         *nbytes = le32_to_cpu(rsp->DataLength);
4374         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4375             (*nbytes > io_parms->length)) {
4376                 cifs_dbg(FYI, "bad length %d for count %d\n",
4377                          *nbytes, io_parms->length);
4378                 rc = -EIO;
4379                 *nbytes = 0;
4380         }
4381
4382         if (*buf) {
4383                 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4384                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4385         } else if (resp_buftype != CIFS_NO_BUFFER) {
4386                 *buf = rsp_iov.iov_base;
4387                 if (resp_buftype == CIFS_SMALL_BUFFER)
4388                         *buf_type = CIFS_SMALL_BUFFER;
4389                 else if (resp_buftype == CIFS_LARGE_BUFFER)
4390                         *buf_type = CIFS_LARGE_BUFFER;
4391         }
4392         return rc;
4393 }
4394
4395 /*
4396  * Check the mid_state and signature on received buffer (if any), and queue the
4397  * workqueue completion task.
4398  */
4399 static void
4400 smb2_writev_callback(struct mid_q_entry *mid)
4401 {
4402         struct cifs_writedata *wdata = mid->callback_data;
4403         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4404         struct TCP_Server_Info *server = wdata->server;
4405         unsigned int written;
4406         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4407         struct cifs_credits credits = { .value = 0, .instance = 0 };
4408
4409         WARN_ONCE(wdata->server != mid->server,
4410                   "wdata server %p != mid server %p",
4411                   wdata->server, mid->server);
4412
4413         switch (mid->mid_state) {
4414         case MID_RESPONSE_RECEIVED:
4415                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4416                 credits.instance = server->reconnect_instance;
4417                 wdata->result = smb2_check_receive(mid, server, 0);
4418                 if (wdata->result != 0)
4419                         break;
4420
4421                 written = le32_to_cpu(rsp->DataLength);
4422                 /*
4423                  * Mask off high 16 bits when bytes written as returned
4424                  * by the server is greater than bytes requested by the
4425                  * client. OS/2 servers are known to set incorrect
4426                  * CountHigh values.
4427                  */
4428                 if (written > wdata->bytes)
4429                         written &= 0xFFFF;
4430
4431                 if (written < wdata->bytes)
4432                         wdata->result = -ENOSPC;
4433                 else
4434                         wdata->bytes = written;
4435                 break;
4436         case MID_REQUEST_SUBMITTED:
4437         case MID_RETRY_NEEDED:
4438                 wdata->result = -EAGAIN;
4439                 break;
4440         case MID_RESPONSE_MALFORMED:
4441                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4442                 credits.instance = server->reconnect_instance;
4443                 fallthrough;
4444         default:
4445                 wdata->result = -EIO;
4446                 break;
4447         }
4448 #ifdef CONFIG_CIFS_SMB_DIRECT
4449         /*
4450          * If this wdata has a memory registered, the MR can be freed
4451          * The number of MRs available is limited, it's important to recover
4452          * used MR as soon as I/O is finished. Hold MR longer in the later
4453          * I/O process can possibly result in I/O deadlock due to lack of MR
4454          * to send request on I/O retry
4455          */
4456         if (wdata->mr) {
4457                 smbd_deregister_mr(wdata->mr);
4458                 wdata->mr = NULL;
4459         }
4460 #endif
4461         if (wdata->result) {
4462                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4463                 trace_smb3_write_err(0 /* no xid */,
4464                                      wdata->cfile->fid.persistent_fid,
4465                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4466                                      wdata->bytes, wdata->result);
4467                 if (wdata->result == -ENOSPC)
4468                         pr_warn_once("Out of space writing to %s\n",
4469                                      tcon->tree_name);
4470         } else
4471                 trace_smb3_write_done(0 /* no xid */,
4472                                       wdata->cfile->fid.persistent_fid,
4473                                       tcon->tid, tcon->ses->Suid,
4474                                       wdata->offset, wdata->bytes);
4475
4476         queue_work(cifsiod_wq, &wdata->work);
4477         release_mid(mid);
4478         add_credits(server, &credits, 0);
4479 }
4480
4481 /* smb2_async_writev - send an async write, and set up mid to handle result */
4482 int
4483 smb2_async_writev(struct cifs_writedata *wdata,
4484                   void (*release)(struct kref *kref))
4485 {
4486         int rc = -EACCES, flags = 0;
4487         struct smb2_write_req *req = NULL;
4488         struct smb2_hdr *shdr;
4489         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4490         struct TCP_Server_Info *server = wdata->server;
4491         struct kvec iov[1];
4492         struct smb_rqst rqst = { };
4493         unsigned int total_len;
4494
4495         if (!wdata->server)
4496                 server = wdata->server = cifs_pick_channel(tcon->ses);
4497
4498         rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4499                                  (void **) &req, &total_len);
4500         if (rc)
4501                 return rc;
4502
4503         if (smb3_encryption_required(tcon))
4504                 flags |= CIFS_TRANSFORM_REQ;
4505
4506         shdr = (struct smb2_hdr *)req;
4507         shdr->Id.SyncId.ProcessId = cpu_to_le32(wdata->cfile->pid);
4508
4509         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4510         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4511         req->WriteChannelInfoOffset = 0;
4512         req->WriteChannelInfoLength = 0;
4513         req->Channel = 0;
4514         req->Offset = cpu_to_le64(wdata->offset);
4515         req->DataOffset = cpu_to_le16(
4516                                 offsetof(struct smb2_write_req, Buffer));
4517         req->RemainingBytes = 0;
4518
4519         trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4520                 tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4521 #ifdef CONFIG_CIFS_SMB_DIRECT
4522         /*
4523          * If we want to do a server RDMA read, fill in and append
4524          * smbd_buffer_descriptor_v1 to the end of write request
4525          */
4526         if (server->rdma && !server->sign && wdata->bytes >=
4527                 server->smbd_conn->rdma_readwrite_threshold) {
4528
4529                 struct smbd_buffer_descriptor_v1 *v1;
4530                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4531
4532                 wdata->mr = smbd_register_mr(
4533                                 server->smbd_conn, wdata->pages,
4534                                 wdata->nr_pages, wdata->page_offset,
4535                                 wdata->tailsz, false, need_invalidate);
4536                 if (!wdata->mr) {
4537                         rc = -EAGAIN;
4538                         goto async_writev_out;
4539                 }
4540                 req->Length = 0;
4541                 req->DataOffset = 0;
4542                 if (wdata->nr_pages > 1)
4543                         req->RemainingBytes =
4544                                 cpu_to_le32(
4545                                         (wdata->nr_pages - 1) * wdata->pagesz -
4546                                         wdata->page_offset + wdata->tailsz
4547                                 );
4548                 else
4549                         req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4550                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4551                 if (need_invalidate)
4552                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4553                 req->WriteChannelInfoOffset =
4554                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4555                 req->WriteChannelInfoLength =
4556                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4557                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4558                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4559                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4560                 v1->length = cpu_to_le32(wdata->mr->mr->length);
4561         }
4562 #endif
4563         iov[0].iov_len = total_len - 1;
4564         iov[0].iov_base = (char *)req;
4565
4566         rqst.rq_iov = iov;
4567         rqst.rq_nvec = 1;
4568         rqst.rq_pages = wdata->pages;
4569         rqst.rq_offset = wdata->page_offset;
4570         rqst.rq_npages = wdata->nr_pages;
4571         rqst.rq_pagesz = wdata->pagesz;
4572         rqst.rq_tailsz = wdata->tailsz;
4573 #ifdef CONFIG_CIFS_SMB_DIRECT
4574         if (wdata->mr) {
4575                 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4576                 rqst.rq_npages = 0;
4577         }
4578 #endif
4579         cifs_dbg(FYI, "async write at %llu %u bytes\n",
4580                  wdata->offset, wdata->bytes);
4581
4582 #ifdef CONFIG_CIFS_SMB_DIRECT
4583         /* For RDMA read, I/O size is in RemainingBytes not in Length */
4584         if (!wdata->mr)
4585                 req->Length = cpu_to_le32(wdata->bytes);
4586 #else
4587         req->Length = cpu_to_le32(wdata->bytes);
4588 #endif
4589
4590         if (wdata->credits.value > 0) {
4591                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4592                                                     SMB2_MAX_BUFFER_SIZE));
4593                 shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4594
4595                 rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4596                 if (rc)
4597                         goto async_writev_out;
4598
4599                 flags |= CIFS_HAS_CREDITS;
4600         }
4601
4602         kref_get(&wdata->refcount);
4603         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4604                              wdata, flags, &wdata->credits);
4605
4606         if (rc) {
4607                 trace_smb3_write_err(0 /* no xid */,
4608                                      req->PersistentFileId,
4609                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4610                                      wdata->bytes, rc);
4611                 kref_put(&wdata->refcount, release);
4612                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4613         }
4614
4615 async_writev_out:
4616         cifs_small_buf_release(req);
4617         return rc;
4618 }
4619
4620 /*
4621  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4622  * The length field from io_parms must be at least 1 and indicates a number of
4623  * elements with data to write that begins with position 1 in iov array. All
4624  * data length is specified by count.
4625  */
4626 int
4627 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4628            unsigned int *nbytes, struct kvec *iov, int n_vec)
4629 {
4630         struct smb_rqst rqst;
4631         int rc = 0;
4632         struct smb2_write_req *req = NULL;
4633         struct smb2_write_rsp *rsp = NULL;
4634         int resp_buftype;
4635         struct kvec rsp_iov;
4636         int flags = 0;
4637         unsigned int total_len;
4638         struct TCP_Server_Info *server;
4639
4640         *nbytes = 0;
4641
4642         if (n_vec < 1)
4643                 return rc;
4644
4645         if (!io_parms->server)
4646                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4647         server = io_parms->server;
4648         if (server == NULL)
4649                 return -ECONNABORTED;
4650
4651         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4652                                  (void **) &req, &total_len);
4653         if (rc)
4654                 return rc;
4655
4656         if (smb3_encryption_required(io_parms->tcon))
4657                 flags |= CIFS_TRANSFORM_REQ;
4658
4659         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4660
4661         req->PersistentFileId = io_parms->persistent_fid;
4662         req->VolatileFileId = io_parms->volatile_fid;
4663         req->WriteChannelInfoOffset = 0;
4664         req->WriteChannelInfoLength = 0;
4665         req->Channel = 0;
4666         req->Length = cpu_to_le32(io_parms->length);
4667         req->Offset = cpu_to_le64(io_parms->offset);
4668         req->DataOffset = cpu_to_le16(
4669                                 offsetof(struct smb2_write_req, Buffer));
4670         req->RemainingBytes = 0;
4671
4672         trace_smb3_write_enter(xid, io_parms->persistent_fid,
4673                 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4674                 io_parms->offset, io_parms->length);
4675
4676         iov[0].iov_base = (char *)req;
4677         /* 1 for Buffer */
4678         iov[0].iov_len = total_len - 1;
4679
4680         memset(&rqst, 0, sizeof(struct smb_rqst));
4681         rqst.rq_iov = iov;
4682         rqst.rq_nvec = n_vec + 1;
4683
4684         rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4685                             &rqst,
4686                             &resp_buftype, flags, &rsp_iov);
4687         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4688
4689         if (rc) {
4690                 trace_smb3_write_err(xid,
4691                                      req->PersistentFileId,
4692                                      io_parms->tcon->tid,
4693                                      io_parms->tcon->ses->Suid,
4694                                      io_parms->offset, io_parms->length, rc);
4695                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4696                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
4697         } else {
4698                 *nbytes = le32_to_cpu(rsp->DataLength);
4699                 trace_smb3_write_done(xid,
4700                                       req->PersistentFileId,
4701                                       io_parms->tcon->tid,
4702                                       io_parms->tcon->ses->Suid,
4703                                       io_parms->offset, *nbytes);
4704         }
4705
4706         cifs_small_buf_release(req);
4707         free_rsp_buf(resp_buftype, rsp);
4708         return rc;
4709 }
4710
4711 int posix_info_sid_size(const void *beg, const void *end)
4712 {
4713         size_t subauth;
4714         int total;
4715
4716         if (beg + 1 > end)
4717                 return -1;
4718
4719         subauth = *(u8 *)(beg+1);
4720         if (subauth < 1 || subauth > 15)
4721                 return -1;
4722
4723         total = 1 + 1 + 6 + 4*subauth;
4724         if (beg + total > end)
4725                 return -1;
4726
4727         return total;
4728 }
4729
4730 int posix_info_parse(const void *beg, const void *end,
4731                      struct smb2_posix_info_parsed *out)
4732
4733 {
4734         int total_len = 0;
4735         int owner_len, group_len;
4736         int name_len;
4737         const void *owner_sid;
4738         const void *group_sid;
4739         const void *name;
4740
4741         /* if no end bound given, assume payload to be correct */
4742         if (!end) {
4743                 const struct smb2_posix_info *p = beg;
4744
4745                 end = beg + le32_to_cpu(p->NextEntryOffset);
4746                 /* last element will have a 0 offset, pick a sensible bound */
4747                 if (end == beg)
4748                         end += 0xFFFF;
4749         }
4750
4751         /* check base buf */
4752         if (beg + sizeof(struct smb2_posix_info) > end)
4753                 return -1;
4754         total_len = sizeof(struct smb2_posix_info);
4755
4756         /* check owner sid */
4757         owner_sid = beg + total_len;
4758         owner_len = posix_info_sid_size(owner_sid, end);
4759         if (owner_len < 0)
4760                 return -1;
4761         total_len += owner_len;
4762
4763         /* check group sid */
4764         group_sid = beg + total_len;
4765         group_len = posix_info_sid_size(group_sid, end);
4766         if (group_len < 0)
4767                 return -1;
4768         total_len += group_len;
4769
4770         /* check name len */
4771         if (beg + total_len + 4 > end)
4772                 return -1;
4773         name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4774         if (name_len < 1 || name_len > 0xFFFF)
4775                 return -1;
4776         total_len += 4;
4777
4778         /* check name */
4779         name = beg + total_len;
4780         if (name + name_len > end)
4781                 return -1;
4782         total_len += name_len;
4783
4784         if (out) {
4785                 out->base = beg;
4786                 out->size = total_len;
4787                 out->name_len = name_len;
4788                 out->name = name;
4789                 memcpy(&out->owner, owner_sid, owner_len);
4790                 memcpy(&out->group, group_sid, group_len);
4791         }
4792         return total_len;
4793 }
4794
4795 static int posix_info_extra_size(const void *beg, const void *end)
4796 {
4797         int len = posix_info_parse(beg, end, NULL);
4798
4799         if (len < 0)
4800                 return -1;
4801         return len - sizeof(struct smb2_posix_info);
4802 }
4803
4804 static unsigned int
4805 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4806             size_t size)
4807 {
4808         int len;
4809         unsigned int entrycount = 0;
4810         unsigned int next_offset = 0;
4811         char *entryptr;
4812         FILE_DIRECTORY_INFO *dir_info;
4813
4814         if (bufstart == NULL)
4815                 return 0;
4816
4817         entryptr = bufstart;
4818
4819         while (1) {
4820                 if (entryptr + next_offset < entryptr ||
4821                     entryptr + next_offset > end_of_buf ||
4822                     entryptr + next_offset + size > end_of_buf) {
4823                         cifs_dbg(VFS, "malformed search entry would overflow\n");
4824                         break;
4825                 }
4826
4827                 entryptr = entryptr + next_offset;
4828                 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4829
4830                 if (infotype == SMB_FIND_FILE_POSIX_INFO)
4831                         len = posix_info_extra_size(entryptr, end_of_buf);
4832                 else
4833                         len = le32_to_cpu(dir_info->FileNameLength);
4834
4835                 if (len < 0 ||
4836                     entryptr + len < entryptr ||
4837                     entryptr + len > end_of_buf ||
4838                     entryptr + len + size > end_of_buf) {
4839                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4840                                  end_of_buf);
4841                         break;
4842                 }
4843
4844                 *lastentry = entryptr;
4845                 entrycount++;
4846
4847                 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4848                 if (!next_offset)
4849                         break;
4850         }
4851
4852         return entrycount;
4853 }
4854
4855 /*
4856  * Readdir/FindFirst
4857  */
4858 int SMB2_query_directory_init(const unsigned int xid,
4859                               struct cifs_tcon *tcon,
4860                               struct TCP_Server_Info *server,
4861                               struct smb_rqst *rqst,
4862                               u64 persistent_fid, u64 volatile_fid,
4863                               int index, int info_level)
4864 {
4865         struct smb2_query_directory_req *req;
4866         unsigned char *bufptr;
4867         __le16 asteriks = cpu_to_le16('*');
4868         unsigned int output_size = CIFSMaxBufSize -
4869                 MAX_SMB2_CREATE_RESPONSE_SIZE -
4870                 MAX_SMB2_CLOSE_RESPONSE_SIZE;
4871         unsigned int total_len;
4872         struct kvec *iov = rqst->rq_iov;
4873         int len, rc;
4874
4875         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
4876                                  (void **) &req, &total_len);
4877         if (rc)
4878                 return rc;
4879
4880         switch (info_level) {
4881         case SMB_FIND_FILE_DIRECTORY_INFO:
4882                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4883                 break;
4884         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4885                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4886                 break;
4887         case SMB_FIND_FILE_POSIX_INFO:
4888                 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4889                 break;
4890         default:
4891                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4892                         info_level);
4893                 return -EINVAL;
4894         }
4895
4896         req->FileIndex = cpu_to_le32(index);
4897         req->PersistentFileId = persistent_fid;
4898         req->VolatileFileId = volatile_fid;
4899
4900         len = 0x2;
4901         bufptr = req->Buffer;
4902         memcpy(bufptr, &asteriks, len);
4903
4904         req->FileNameOffset =
4905                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4906         req->FileNameLength = cpu_to_le16(len);
4907         /*
4908          * BB could be 30 bytes or so longer if we used SMB2 specific
4909          * buffer lengths, but this is safe and close enough.
4910          */
4911         output_size = min_t(unsigned int, output_size, server->maxBuf);
4912         output_size = min_t(unsigned int, output_size, 2 << 15);
4913         req->OutputBufferLength = cpu_to_le32(output_size);
4914
4915         iov[0].iov_base = (char *)req;
4916         /* 1 for Buffer */
4917         iov[0].iov_len = total_len - 1;
4918
4919         iov[1].iov_base = (char *)(req->Buffer);
4920         iov[1].iov_len = len;
4921
4922         trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4923                         tcon->ses->Suid, index, output_size);
4924
4925         return 0;
4926 }
4927
4928 void SMB2_query_directory_free(struct smb_rqst *rqst)
4929 {
4930         if (rqst && rqst->rq_iov) {
4931                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4932         }
4933 }
4934
4935 int
4936 smb2_parse_query_directory(struct cifs_tcon *tcon,
4937                            struct kvec *rsp_iov,
4938                            int resp_buftype,
4939                            struct cifs_search_info *srch_inf)
4940 {
4941         struct smb2_query_directory_rsp *rsp;
4942         size_t info_buf_size;
4943         char *end_of_smb;
4944         int rc;
4945
4946         rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4947
4948         switch (srch_inf->info_level) {
4949         case SMB_FIND_FILE_DIRECTORY_INFO:
4950                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4951                 break;
4952         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4953                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4954                 break;
4955         case SMB_FIND_FILE_POSIX_INFO:
4956                 /* note that posix payload are variable size */
4957                 info_buf_size = sizeof(struct smb2_posix_info);
4958                 break;
4959         default:
4960                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4961                          srch_inf->info_level);
4962                 return -EINVAL;
4963         }
4964
4965         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4966                                le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4967                                info_buf_size);
4968         if (rc) {
4969                 cifs_tcon_dbg(VFS, "bad info payload");
4970                 return rc;
4971         }
4972
4973         srch_inf->unicode = true;
4974
4975         if (srch_inf->ntwrk_buf_start) {
4976                 if (srch_inf->smallBuf)
4977                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4978                 else
4979                         cifs_buf_release(srch_inf->ntwrk_buf_start);
4980         }
4981         srch_inf->ntwrk_buf_start = (char *)rsp;
4982         srch_inf->srch_entries_start = srch_inf->last_entry =
4983                 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4984         end_of_smb = rsp_iov->iov_len + (char *)rsp;
4985
4986         srch_inf->entries_in_buffer = num_entries(
4987                 srch_inf->info_level,
4988                 srch_inf->srch_entries_start,
4989                 end_of_smb,
4990                 &srch_inf->last_entry,
4991                 info_buf_size);
4992
4993         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4994         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4995                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4996                  srch_inf->srch_entries_start, srch_inf->last_entry);
4997         if (resp_buftype == CIFS_LARGE_BUFFER)
4998                 srch_inf->smallBuf = false;
4999         else if (resp_buftype == CIFS_SMALL_BUFFER)
5000                 srch_inf->smallBuf = true;
5001         else
5002                 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5003
5004         return 0;
5005 }
5006
5007 int
5008 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5009                      u64 persistent_fid, u64 volatile_fid, int index,
5010                      struct cifs_search_info *srch_inf)
5011 {
5012         struct smb_rqst rqst;
5013         struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5014         struct smb2_query_directory_rsp *rsp = NULL;
5015         int resp_buftype = CIFS_NO_BUFFER;
5016         struct kvec rsp_iov;
5017         int rc = 0;
5018         struct cifs_ses *ses = tcon->ses;
5019         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5020         int flags = 0;
5021
5022         if (!ses || !(ses->server))
5023                 return -EIO;
5024
5025         if (smb3_encryption_required(tcon))
5026                 flags |= CIFS_TRANSFORM_REQ;
5027
5028         memset(&rqst, 0, sizeof(struct smb_rqst));
5029         memset(&iov, 0, sizeof(iov));
5030         rqst.rq_iov = iov;
5031         rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5032
5033         rc = SMB2_query_directory_init(xid, tcon, server,
5034                                        &rqst, persistent_fid,
5035                                        volatile_fid, index,
5036                                        srch_inf->info_level);
5037         if (rc)
5038                 goto qdir_exit;
5039
5040         rc = cifs_send_recv(xid, ses, server,
5041                             &rqst, &resp_buftype, flags, &rsp_iov);
5042         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5043
5044         if (rc) {
5045                 if (rc == -ENODATA &&
5046                     rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5047                         trace_smb3_query_dir_done(xid, persistent_fid,
5048                                 tcon->tid, tcon->ses->Suid, index, 0);
5049                         srch_inf->endOfSearch = true;
5050                         rc = 0;
5051                 } else {
5052                         trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5053                                 tcon->ses->Suid, index, 0, rc);
5054                         cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5055                 }
5056                 goto qdir_exit;
5057         }
5058
5059         rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
5060                                         srch_inf);
5061         if (rc) {
5062                 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5063                         tcon->ses->Suid, index, 0, rc);
5064                 goto qdir_exit;
5065         }
5066         resp_buftype = CIFS_NO_BUFFER;
5067
5068         trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5069                         tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5070
5071 qdir_exit:
5072         SMB2_query_directory_free(&rqst);
5073         free_rsp_buf(resp_buftype, rsp);
5074         return rc;
5075 }
5076
5077 int
5078 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5079                    struct smb_rqst *rqst,
5080                    u64 persistent_fid, u64 volatile_fid, u32 pid,
5081                    u8 info_class, u8 info_type, u32 additional_info,
5082                    void **data, unsigned int *size)
5083 {
5084         struct smb2_set_info_req *req;
5085         struct kvec *iov = rqst->rq_iov;
5086         unsigned int i, total_len;
5087         int rc;
5088
5089         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5090                                  (void **) &req, &total_len);
5091         if (rc)
5092                 return rc;
5093
5094         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5095         req->InfoType = info_type;
5096         req->FileInfoClass = info_class;
5097         req->PersistentFileId = persistent_fid;
5098         req->VolatileFileId = volatile_fid;
5099         req->AdditionalInformation = cpu_to_le32(additional_info);
5100
5101         req->BufferOffset =
5102                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
5103         req->BufferLength = cpu_to_le32(*size);
5104
5105         memcpy(req->Buffer, *data, *size);
5106         total_len += *size;
5107
5108         iov[0].iov_base = (char *)req;
5109         /* 1 for Buffer */
5110         iov[0].iov_len = total_len - 1;
5111
5112         for (i = 1; i < rqst->rq_nvec; i++) {
5113                 le32_add_cpu(&req->BufferLength, size[i]);
5114                 iov[i].iov_base = (char *)data[i];
5115                 iov[i].iov_len = size[i];
5116         }
5117
5118         return 0;
5119 }
5120
5121 void
5122 SMB2_set_info_free(struct smb_rqst *rqst)
5123 {
5124         if (rqst && rqst->rq_iov)
5125                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5126 }
5127
5128 static int
5129 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5130                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5131                u8 info_type, u32 additional_info, unsigned int num,
5132                 void **data, unsigned int *size)
5133 {
5134         struct smb_rqst rqst;
5135         struct smb2_set_info_rsp *rsp = NULL;
5136         struct kvec *iov;
5137         struct kvec rsp_iov;
5138         int rc = 0;
5139         int resp_buftype;
5140         struct cifs_ses *ses = tcon->ses;
5141         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5142         int flags = 0;
5143
5144         if (!ses || !server)
5145                 return -EIO;
5146
5147         if (!num)
5148                 return -EINVAL;
5149
5150         if (smb3_encryption_required(tcon))
5151                 flags |= CIFS_TRANSFORM_REQ;
5152
5153         iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5154         if (!iov)
5155                 return -ENOMEM;
5156
5157         memset(&rqst, 0, sizeof(struct smb_rqst));
5158         rqst.rq_iov = iov;
5159         rqst.rq_nvec = num;
5160
5161         rc = SMB2_set_info_init(tcon, server,
5162                                 &rqst, persistent_fid, volatile_fid, pid,
5163                                 info_class, info_type, additional_info,
5164                                 data, size);
5165         if (rc) {
5166                 kfree(iov);
5167                 return rc;
5168         }
5169
5170
5171         rc = cifs_send_recv(xid, ses, server,
5172                             &rqst, &resp_buftype, flags,
5173                             &rsp_iov);
5174         SMB2_set_info_free(&rqst);
5175         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5176
5177         if (rc != 0) {
5178                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5179                 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5180                                 ses->Suid, info_class, (__u32)info_type, rc);
5181         }
5182
5183         free_rsp_buf(resp_buftype, rsp);
5184         kfree(iov);
5185         return rc;
5186 }
5187
5188 int
5189 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5190              u64 volatile_fid, u32 pid, __le64 *eof)
5191 {
5192         struct smb2_file_eof_info info;
5193         void *data;
5194         unsigned int size;
5195
5196         info.EndOfFile = *eof;
5197
5198         data = &info;
5199         size = sizeof(struct smb2_file_eof_info);
5200
5201         trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, le64_to_cpu(*eof));
5202
5203         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5204                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5205                         0, 1, &data, &size);
5206 }
5207
5208 int
5209 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5210                 u64 persistent_fid, u64 volatile_fid,
5211                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
5212 {
5213         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5214                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5215                         1, (void **)&pnntsd, &pacllen);
5216 }
5217
5218 int
5219 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5220             u64 persistent_fid, u64 volatile_fid,
5221             struct smb2_file_full_ea_info *buf, int len)
5222 {
5223         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5224                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5225                 0, 1, (void **)&buf, &len);
5226 }
5227
5228 int
5229 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5230                   const u64 persistent_fid, const u64 volatile_fid,
5231                   __u8 oplock_level)
5232 {
5233         struct smb_rqst rqst;
5234         int rc;
5235         struct smb2_oplock_break *req = NULL;
5236         struct cifs_ses *ses = tcon->ses;
5237         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5238         int flags = CIFS_OBREAK_OP;
5239         unsigned int total_len;
5240         struct kvec iov[1];
5241         struct kvec rsp_iov;
5242         int resp_buf_type;
5243
5244         cifs_dbg(FYI, "SMB2_oplock_break\n");
5245         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5246                                  (void **) &req, &total_len);
5247         if (rc)
5248                 return rc;
5249
5250         if (smb3_encryption_required(tcon))
5251                 flags |= CIFS_TRANSFORM_REQ;
5252
5253         req->VolatileFid = volatile_fid;
5254         req->PersistentFid = persistent_fid;
5255         req->OplockLevel = oplock_level;
5256         req->hdr.CreditRequest = cpu_to_le16(1);
5257
5258         flags |= CIFS_NO_RSP_BUF;
5259
5260         iov[0].iov_base = (char *)req;
5261         iov[0].iov_len = total_len;
5262
5263         memset(&rqst, 0, sizeof(struct smb_rqst));
5264         rqst.rq_iov = iov;
5265         rqst.rq_nvec = 1;
5266
5267         rc = cifs_send_recv(xid, ses, server,
5268                             &rqst, &resp_buf_type, flags, &rsp_iov);
5269         cifs_small_buf_release(req);
5270
5271         if (rc) {
5272                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5273                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5274         }
5275
5276         return rc;
5277 }
5278
5279 void
5280 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5281                              struct kstatfs *kst)
5282 {
5283         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5284                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5285         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5286         kst->f_bfree  = kst->f_bavail =
5287                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5288         return;
5289 }
5290
5291 static void
5292 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5293                         struct kstatfs *kst)
5294 {
5295         kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5296         kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5297         kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5298         if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5299                 kst->f_bavail = kst->f_bfree;
5300         else
5301                 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5302         if (response_data->TotalFileNodes != cpu_to_le64(-1))
5303                 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5304         if (response_data->FreeFileNodes != cpu_to_le64(-1))
5305                 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5306
5307         return;
5308 }
5309
5310 static int
5311 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5312                    struct TCP_Server_Info *server,
5313                    int level, int outbuf_len, u64 persistent_fid,
5314                    u64 volatile_fid)
5315 {
5316         int rc;
5317         struct smb2_query_info_req *req;
5318         unsigned int total_len;
5319
5320         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5321
5322         if ((tcon->ses == NULL) || server == NULL)
5323                 return -EIO;
5324
5325         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5326                                  (void **) &req, &total_len);
5327         if (rc)
5328                 return rc;
5329
5330         req->InfoType = SMB2_O_INFO_FILESYSTEM;
5331         req->FileInfoClass = level;
5332         req->PersistentFileId = persistent_fid;
5333         req->VolatileFileId = volatile_fid;
5334         /* 1 for pad */
5335         req->InputBufferOffset =
5336                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
5337         req->OutputBufferLength = cpu_to_le32(
5338                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
5339
5340         iov->iov_base = (char *)req;
5341         iov->iov_len = total_len;
5342         return 0;
5343 }
5344
5345 int
5346 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5347               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5348 {
5349         struct smb_rqst rqst;
5350         struct smb2_query_info_rsp *rsp = NULL;
5351         struct kvec iov;
5352         struct kvec rsp_iov;
5353         int rc = 0;
5354         int resp_buftype;
5355         struct cifs_ses *ses = tcon->ses;
5356         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5357         FILE_SYSTEM_POSIX_INFO *info = NULL;
5358         int flags = 0;
5359
5360         rc = build_qfs_info_req(&iov, tcon, server,
5361                                 FS_POSIX_INFORMATION,
5362                                 sizeof(FILE_SYSTEM_POSIX_INFO),
5363                                 persistent_fid, volatile_fid);
5364         if (rc)
5365                 return rc;
5366
5367         if (smb3_encryption_required(tcon))
5368                 flags |= CIFS_TRANSFORM_REQ;
5369
5370         memset(&rqst, 0, sizeof(struct smb_rqst));
5371         rqst.rq_iov = &iov;
5372         rqst.rq_nvec = 1;
5373
5374         rc = cifs_send_recv(xid, ses, server,
5375                             &rqst, &resp_buftype, flags, &rsp_iov);
5376         cifs_small_buf_release(iov.iov_base);
5377         if (rc) {
5378                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5379                 goto posix_qfsinf_exit;
5380         }
5381         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5382
5383         info = (FILE_SYSTEM_POSIX_INFO *)(
5384                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5385         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5386                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5387                                sizeof(FILE_SYSTEM_POSIX_INFO));
5388         if (!rc)
5389                 copy_posix_fs_info_to_kstatfs(info, fsdata);
5390
5391 posix_qfsinf_exit:
5392         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5393         return rc;
5394 }
5395
5396 int
5397 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5398               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5399 {
5400         struct smb_rqst rqst;
5401         struct smb2_query_info_rsp *rsp = NULL;
5402         struct kvec iov;
5403         struct kvec rsp_iov;
5404         int rc = 0;
5405         int resp_buftype;
5406         struct cifs_ses *ses = tcon->ses;
5407         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5408         struct smb2_fs_full_size_info *info = NULL;
5409         int flags = 0;
5410
5411         rc = build_qfs_info_req(&iov, tcon, server,
5412                                 FS_FULL_SIZE_INFORMATION,
5413                                 sizeof(struct smb2_fs_full_size_info),
5414                                 persistent_fid, volatile_fid);
5415         if (rc)
5416                 return rc;
5417
5418         if (smb3_encryption_required(tcon))
5419                 flags |= CIFS_TRANSFORM_REQ;
5420
5421         memset(&rqst, 0, sizeof(struct smb_rqst));
5422         rqst.rq_iov = &iov;
5423         rqst.rq_nvec = 1;
5424
5425         rc = cifs_send_recv(xid, ses, server,
5426                             &rqst, &resp_buftype, flags, &rsp_iov);
5427         cifs_small_buf_release(iov.iov_base);
5428         if (rc) {
5429                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5430                 goto qfsinf_exit;
5431         }
5432         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5433
5434         info = (struct smb2_fs_full_size_info *)(
5435                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5436         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5437                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5438                                sizeof(struct smb2_fs_full_size_info));
5439         if (!rc)
5440                 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5441
5442 qfsinf_exit:
5443         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5444         return rc;
5445 }
5446
5447 int
5448 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5449               u64 persistent_fid, u64 volatile_fid, int level)
5450 {
5451         struct smb_rqst rqst;
5452         struct smb2_query_info_rsp *rsp = NULL;
5453         struct kvec iov;
5454         struct kvec rsp_iov;
5455         int rc = 0;
5456         int resp_buftype, max_len, min_len;
5457         struct cifs_ses *ses = tcon->ses;
5458         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5459         unsigned int rsp_len, offset;
5460         int flags = 0;
5461
5462         if (level == FS_DEVICE_INFORMATION) {
5463                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5464                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5465         } else if (level == FS_ATTRIBUTE_INFORMATION) {
5466                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5467                 min_len = MIN_FS_ATTR_INFO_SIZE;
5468         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5469                 max_len = sizeof(struct smb3_fs_ss_info);
5470                 min_len = sizeof(struct smb3_fs_ss_info);
5471         } else if (level == FS_VOLUME_INFORMATION) {
5472                 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5473                 min_len = sizeof(struct smb3_fs_vol_info);
5474         } else {
5475                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5476                 return -EINVAL;
5477         }
5478
5479         rc = build_qfs_info_req(&iov, tcon, server,
5480                                 level, max_len,
5481                                 persistent_fid, volatile_fid);
5482         if (rc)
5483                 return rc;
5484
5485         if (smb3_encryption_required(tcon))
5486                 flags |= CIFS_TRANSFORM_REQ;
5487
5488         memset(&rqst, 0, sizeof(struct smb_rqst));
5489         rqst.rq_iov = &iov;
5490         rqst.rq_nvec = 1;
5491
5492         rc = cifs_send_recv(xid, ses, server,
5493                             &rqst, &resp_buftype, flags, &rsp_iov);
5494         cifs_small_buf_release(iov.iov_base);
5495         if (rc) {
5496                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5497                 goto qfsattr_exit;
5498         }
5499         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5500
5501         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5502         offset = le16_to_cpu(rsp->OutputBufferOffset);
5503         rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5504         if (rc)
5505                 goto qfsattr_exit;
5506
5507         if (level == FS_ATTRIBUTE_INFORMATION)
5508                 memcpy(&tcon->fsAttrInfo, offset
5509                         + (char *)rsp, min_t(unsigned int,
5510                         rsp_len, max_len));
5511         else if (level == FS_DEVICE_INFORMATION)
5512                 memcpy(&tcon->fsDevInfo, offset
5513                         + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5514         else if (level == FS_SECTOR_SIZE_INFORMATION) {
5515                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5516                         (offset + (char *)rsp);
5517                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5518                 tcon->perf_sector_size =
5519                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5520         } else if (level == FS_VOLUME_INFORMATION) {
5521                 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5522                         (offset + (char *)rsp);
5523                 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5524                 tcon->vol_create_time = vol_info->VolumeCreationTime;
5525         }
5526
5527 qfsattr_exit:
5528         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5529         return rc;
5530 }
5531
5532 int
5533 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5534            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5535            const __u32 num_lock, struct smb2_lock_element *buf)
5536 {
5537         struct smb_rqst rqst;
5538         int rc = 0;
5539         struct smb2_lock_req *req = NULL;
5540         struct kvec iov[2];
5541         struct kvec rsp_iov;
5542         int resp_buf_type;
5543         unsigned int count;
5544         int flags = CIFS_NO_RSP_BUF;
5545         unsigned int total_len;
5546         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5547
5548         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5549
5550         rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5551                                  (void **) &req, &total_len);
5552         if (rc)
5553                 return rc;
5554
5555         if (smb3_encryption_required(tcon))
5556                 flags |= CIFS_TRANSFORM_REQ;
5557
5558         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5559         req->LockCount = cpu_to_le16(num_lock);
5560
5561         req->PersistentFileId = persist_fid;
5562         req->VolatileFileId = volatile_fid;
5563
5564         count = num_lock * sizeof(struct smb2_lock_element);
5565
5566         iov[0].iov_base = (char *)req;
5567         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5568         iov[1].iov_base = (char *)buf;
5569         iov[1].iov_len = count;
5570
5571         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5572
5573         memset(&rqst, 0, sizeof(struct smb_rqst));
5574         rqst.rq_iov = iov;
5575         rqst.rq_nvec = 2;
5576
5577         rc = cifs_send_recv(xid, tcon->ses, server,
5578                             &rqst, &resp_buf_type, flags,
5579                             &rsp_iov);
5580         cifs_small_buf_release(req);
5581         if (rc) {
5582                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5583                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5584                 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5585                                     tcon->ses->Suid, rc);
5586         }
5587
5588         return rc;
5589 }
5590
5591 int
5592 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5593           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5594           const __u64 length, const __u64 offset, const __u32 lock_flags,
5595           const bool wait)
5596 {
5597         struct smb2_lock_element lock;
5598
5599         lock.Offset = cpu_to_le64(offset);
5600         lock.Length = cpu_to_le64(length);
5601         lock.Flags = cpu_to_le32(lock_flags);
5602         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5603                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5604
5605         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5606 }
5607
5608 int
5609 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5610                  __u8 *lease_key, const __le32 lease_state)
5611 {
5612         struct smb_rqst rqst;
5613         int rc;
5614         struct smb2_lease_ack *req = NULL;
5615         struct cifs_ses *ses = tcon->ses;
5616         int flags = CIFS_OBREAK_OP;
5617         unsigned int total_len;
5618         struct kvec iov[1];
5619         struct kvec rsp_iov;
5620         int resp_buf_type;
5621         __u64 *please_key_high;
5622         __u64 *please_key_low;
5623         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5624
5625         cifs_dbg(FYI, "SMB2_lease_break\n");
5626         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5627                                  (void **) &req, &total_len);
5628         if (rc)
5629                 return rc;
5630
5631         if (smb3_encryption_required(tcon))
5632                 flags |= CIFS_TRANSFORM_REQ;
5633
5634         req->hdr.CreditRequest = cpu_to_le16(1);
5635         req->StructureSize = cpu_to_le16(36);
5636         total_len += 12;
5637
5638         memcpy(req->LeaseKey, lease_key, 16);
5639         req->LeaseState = lease_state;
5640
5641         flags |= CIFS_NO_RSP_BUF;
5642
5643         iov[0].iov_base = (char *)req;
5644         iov[0].iov_len = total_len;
5645
5646         memset(&rqst, 0, sizeof(struct smb_rqst));
5647         rqst.rq_iov = iov;
5648         rqst.rq_nvec = 1;
5649
5650         rc = cifs_send_recv(xid, ses, server,
5651                             &rqst, &resp_buf_type, flags, &rsp_iov);
5652         cifs_small_buf_release(req);
5653
5654         please_key_low = (__u64 *)lease_key;
5655         please_key_high = (__u64 *)(lease_key+8);
5656         if (rc) {
5657                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5658                 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5659                         ses->Suid, *please_key_low, *please_key_high, rc);
5660                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5661         } else
5662                 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5663                         ses->Suid, *please_key_low, *please_key_high);
5664
5665         return rc;
5666 }