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