KVM: selftests: Restrict test region to 48-bit physical addresses when using nested
[linux-2.6-microblaze.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->status == TID_EXITING) {
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->ses_status == SES_EXITING) ||
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         cifs_server_lock(server);
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                         cifs_server_unlock(server);
1379                         return rc;
1380                 }
1381         }
1382         if (!server->session_estab) {
1383                 server->sequence_number = 0x2;
1384                 server->session_estab = true;
1385         }
1386         cifs_server_unlock(server);
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_smb3_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, rsp->PersistentFileId, tcon->tid, ses->Suid,
2738                                     CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2739
2740         SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2741
2742         /* Eventually save off posix specific response info and timestaps */
2743
2744 err_free_rsp_buf:
2745         free_rsp_buf(resp_buftype, rsp);
2746         kfree(pc_buf);
2747 err_free_req:
2748         cifs_small_buf_release(req);
2749 err_free_path:
2750         kfree(utf16_path);
2751         return rc;
2752 }
2753
2754 int
2755 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2756                struct smb_rqst *rqst, __u8 *oplock,
2757                struct cifs_open_parms *oparms, __le16 *path)
2758 {
2759         struct smb2_create_req *req;
2760         unsigned int n_iov = 2;
2761         __u32 file_attributes = 0;
2762         int copy_size;
2763         int uni_path_len;
2764         unsigned int total_len;
2765         struct kvec *iov = rqst->rq_iov;
2766         __le16 *copy_path;
2767         int rc;
2768
2769         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2770                                  (void **) &req, &total_len);
2771         if (rc)
2772                 return rc;
2773
2774         iov[0].iov_base = (char *)req;
2775         /* -1 since last byte is buf[0] which is sent below (path) */
2776         iov[0].iov_len = total_len - 1;
2777
2778         if (oparms->create_options & CREATE_OPTION_READONLY)
2779                 file_attributes |= ATTR_READONLY;
2780         if (oparms->create_options & CREATE_OPTION_SPECIAL)
2781                 file_attributes |= ATTR_SYSTEM;
2782
2783         req->ImpersonationLevel = IL_IMPERSONATION;
2784         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2785         /* File attributes ignored on open (used in create though) */
2786         req->FileAttributes = cpu_to_le32(file_attributes);
2787         req->ShareAccess = FILE_SHARE_ALL_LE;
2788
2789         req->CreateDisposition = cpu_to_le32(oparms->disposition);
2790         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2791         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2792
2793         /* [MS-SMB2] 2.2.13 NameOffset:
2794          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2795          * the SMB2 header, the file name includes a prefix that will
2796          * be processed during DFS name normalization as specified in
2797          * section 3.3.5.9. Otherwise, the file name is relative to
2798          * the share that is identified by the TreeId in the SMB2
2799          * header.
2800          */
2801         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2802                 int name_len;
2803
2804                 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2805                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2806                                                  &name_len,
2807                                                  tcon->treeName, path);
2808                 if (rc)
2809                         return rc;
2810                 req->NameLength = cpu_to_le16(name_len * 2);
2811                 uni_path_len = copy_size;
2812                 path = copy_path;
2813         } else {
2814                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2815                 /* MUST set path len (NameLength) to 0 opening root of share */
2816                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2817                 copy_size = uni_path_len;
2818                 if (copy_size % 8 != 0)
2819                         copy_size = roundup(copy_size, 8);
2820                 copy_path = kzalloc(copy_size, GFP_KERNEL);
2821                 if (!copy_path)
2822                         return -ENOMEM;
2823                 memcpy((char *)copy_path, (const char *)path,
2824                        uni_path_len);
2825                 uni_path_len = copy_size;
2826                 path = copy_path;
2827         }
2828
2829         iov[1].iov_len = uni_path_len;
2830         iov[1].iov_base = path;
2831
2832         if ((!server->oplocks) || (tcon->no_lease))
2833                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
2834
2835         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2836             *oplock == SMB2_OPLOCK_LEVEL_NONE)
2837                 req->RequestedOplockLevel = *oplock;
2838         else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2839                   (oparms->create_options & CREATE_NOT_FILE))
2840                 req->RequestedOplockLevel = *oplock; /* no srv lease support */
2841         else {
2842                 rc = add_lease_context(server, iov, &n_iov,
2843                                        oparms->fid->lease_key, oplock);
2844                 if (rc)
2845                         return rc;
2846         }
2847
2848         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2849                 /* need to set Next field of lease context if we request it */
2850                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2851                         struct create_context *ccontext =
2852                             (struct create_context *)iov[n_iov-1].iov_base;
2853                         ccontext->Next =
2854                                 cpu_to_le32(server->vals->create_lease_size);
2855                 }
2856
2857                 rc = add_durable_context(iov, &n_iov, oparms,
2858                                         tcon->use_persistent);
2859                 if (rc)
2860                         return rc;
2861         }
2862
2863         if (tcon->posix_extensions) {
2864                 if (n_iov > 2) {
2865                         struct create_context *ccontext =
2866                             (struct create_context *)iov[n_iov-1].iov_base;
2867                         ccontext->Next =
2868                                 cpu_to_le32(iov[n_iov-1].iov_len);
2869                 }
2870
2871                 rc = add_posix_context(iov, &n_iov, oparms->mode);
2872                 if (rc)
2873                         return rc;
2874         }
2875
2876         if (tcon->snapshot_time) {
2877                 cifs_dbg(FYI, "adding snapshot context\n");
2878                 if (n_iov > 2) {
2879                         struct create_context *ccontext =
2880                             (struct create_context *)iov[n_iov-1].iov_base;
2881                         ccontext->Next =
2882                                 cpu_to_le32(iov[n_iov-1].iov_len);
2883                 }
2884
2885                 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2886                 if (rc)
2887                         return rc;
2888         }
2889
2890         if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
2891                 bool set_mode;
2892                 bool set_owner;
2893
2894                 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2895                     (oparms->mode != ACL_NO_MODE))
2896                         set_mode = true;
2897                 else {
2898                         set_mode = false;
2899                         oparms->mode = ACL_NO_MODE;
2900                 }
2901
2902                 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
2903                         set_owner = true;
2904                 else
2905                         set_owner = false;
2906
2907                 if (set_owner | set_mode) {
2908                         if (n_iov > 2) {
2909                                 struct create_context *ccontext =
2910                                     (struct create_context *)iov[n_iov-1].iov_base;
2911                                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2912                         }
2913
2914                         cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2915                         rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
2916                         if (rc)
2917                                 return rc;
2918                 }
2919         }
2920
2921         if (n_iov > 2) {
2922                 struct create_context *ccontext =
2923                         (struct create_context *)iov[n_iov-1].iov_base;
2924                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2925         }
2926         add_query_id_context(iov, &n_iov);
2927
2928         rqst->rq_nvec = n_iov;
2929         return 0;
2930 }
2931
2932 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2933  * All other vectors are freed by kfree().
2934  */
2935 void
2936 SMB2_open_free(struct smb_rqst *rqst)
2937 {
2938         int i;
2939
2940         if (rqst && rqst->rq_iov) {
2941                 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2942                 for (i = 1; i < rqst->rq_nvec; i++)
2943                         if (rqst->rq_iov[i].iov_base != smb2_padding)
2944                                 kfree(rqst->rq_iov[i].iov_base);
2945         }
2946 }
2947
2948 int
2949 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2950           __u8 *oplock, struct smb2_file_all_info *buf,
2951           struct create_posix_rsp *posix,
2952           struct kvec *err_iov, int *buftype)
2953 {
2954         struct smb_rqst rqst;
2955         struct smb2_create_rsp *rsp = NULL;
2956         struct cifs_tcon *tcon = oparms->tcon;
2957         struct cifs_ses *ses = tcon->ses;
2958         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2959         struct kvec iov[SMB2_CREATE_IOV_SIZE];
2960         struct kvec rsp_iov = {NULL, 0};
2961         int resp_buftype = CIFS_NO_BUFFER;
2962         int rc = 0;
2963         int flags = 0;
2964
2965         cifs_dbg(FYI, "create/open\n");
2966         if (!ses || !server)
2967                 return -EIO;
2968
2969         if (smb3_encryption_required(tcon))
2970                 flags |= CIFS_TRANSFORM_REQ;
2971
2972         memset(&rqst, 0, sizeof(struct smb_rqst));
2973         memset(&iov, 0, sizeof(iov));
2974         rqst.rq_iov = iov;
2975         rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2976
2977         rc = SMB2_open_init(tcon, server,
2978                             &rqst, oplock, oparms, path);
2979         if (rc)
2980                 goto creat_exit;
2981
2982         trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
2983                 oparms->create_options, oparms->desired_access);
2984
2985         rc = cifs_send_recv(xid, ses, server,
2986                             &rqst, &resp_buftype, flags,
2987                             &rsp_iov);
2988         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2989
2990         if (rc != 0) {
2991                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2992                 if (err_iov && rsp) {
2993                         *err_iov = rsp_iov;
2994                         *buftype = resp_buftype;
2995                         resp_buftype = CIFS_NO_BUFFER;
2996                         rsp = NULL;
2997                 }
2998                 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
2999                                     oparms->create_options, oparms->desired_access, rc);
3000                 if (rc == -EREMCHG) {
3001                         pr_warn_once("server share %s deleted\n",
3002                                      tcon->treeName);
3003                         tcon->need_reconnect = true;
3004                 }
3005                 goto creat_exit;
3006         } else if (rsp == NULL) /* unlikely to happen, but safer to check */
3007                 goto creat_exit;
3008         else
3009                 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3010                                      oparms->create_options, oparms->desired_access);
3011
3012         atomic_inc(&tcon->num_remote_opens);
3013         oparms->fid->persistent_fid = rsp->PersistentFileId;
3014         oparms->fid->volatile_fid = rsp->VolatileFileId;
3015         oparms->fid->access = oparms->desired_access;
3016 #ifdef CONFIG_CIFS_DEBUG2
3017         oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3018 #endif /* CIFS_DEBUG2 */
3019
3020         if (buf) {
3021                 buf->CreationTime = rsp->CreationTime;
3022                 buf->LastAccessTime = rsp->LastAccessTime;
3023                 buf->LastWriteTime = rsp->LastWriteTime;
3024                 buf->ChangeTime = rsp->ChangeTime;
3025                 buf->AllocationSize = rsp->AllocationSize;
3026                 buf->EndOfFile = rsp->EndofFile;
3027                 buf->Attributes = rsp->FileAttributes;
3028                 buf->NumberOfLinks = cpu_to_le32(1);
3029                 buf->DeletePending = 0;
3030         }
3031
3032
3033         smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
3034                             oparms->fid->lease_key, oplock, buf, posix);
3035 creat_exit:
3036         SMB2_open_free(&rqst);
3037         free_rsp_buf(resp_buftype, rsp);
3038         return rc;
3039 }
3040
3041 int
3042 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3043                 struct smb_rqst *rqst,
3044                 u64 persistent_fid, u64 volatile_fid, u32 opcode,
3045                 bool is_fsctl, char *in_data, u32 indatalen,
3046                 __u32 max_response_size)
3047 {
3048         struct smb2_ioctl_req *req;
3049         struct kvec *iov = rqst->rq_iov;
3050         unsigned int total_len;
3051         int rc;
3052         char *in_data_buf;
3053
3054         rc = smb2_ioctl_req_init(opcode, tcon, server,
3055                                  (void **) &req, &total_len);
3056         if (rc)
3057                 return rc;
3058
3059         if (indatalen) {
3060                 /*
3061                  * indatalen is usually small at a couple of bytes max, so
3062                  * just allocate through generic pool
3063                  */
3064                 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3065                 if (!in_data_buf) {
3066                         cifs_small_buf_release(req);
3067                         return -ENOMEM;
3068                 }
3069         }
3070
3071         req->CtlCode = cpu_to_le32(opcode);
3072         req->PersistentFileId = persistent_fid;
3073         req->VolatileFileId = volatile_fid;
3074
3075         iov[0].iov_base = (char *)req;
3076         /*
3077          * If no input data, the size of ioctl struct in
3078          * protocol spec still includes a 1 byte data buffer,
3079          * but if input data passed to ioctl, we do not
3080          * want to double count this, so we do not send
3081          * the dummy one byte of data in iovec[0] if sending
3082          * input data (in iovec[1]).
3083          */
3084         if (indatalen) {
3085                 req->InputCount = cpu_to_le32(indatalen);
3086                 /* do not set InputOffset if no input data */
3087                 req->InputOffset =
3088                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3089                 rqst->rq_nvec = 2;
3090                 iov[0].iov_len = total_len - 1;
3091                 iov[1].iov_base = in_data_buf;
3092                 iov[1].iov_len = indatalen;
3093         } else {
3094                 rqst->rq_nvec = 1;
3095                 iov[0].iov_len = total_len;
3096         }
3097
3098         req->OutputOffset = 0;
3099         req->OutputCount = 0; /* MBZ */
3100
3101         /*
3102          * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3103          * We Could increase default MaxOutputResponse, but that could require
3104          * more credits. Windows typically sets this smaller, but for some
3105          * ioctls it may be useful to allow server to send more. No point
3106          * limiting what the server can send as long as fits in one credit
3107          * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3108          * to increase this limit up in the future.
3109          * Note that for snapshot queries that servers like Azure expect that
3110          * the first query be minimal size (and just used to get the number/size
3111          * of previous versions) so response size must be specified as EXACTLY
3112          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3113          * of eight bytes.  Currently that is the only case where we set max
3114          * response size smaller.
3115          */
3116         req->MaxOutputResponse = cpu_to_le32(max_response_size);
3117         req->hdr.CreditCharge =
3118                 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3119                                          SMB2_MAX_BUFFER_SIZE));
3120         if (is_fsctl)
3121                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3122         else
3123                 req->Flags = 0;
3124
3125         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3126         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3127                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3128
3129         return 0;
3130 }
3131
3132 void
3133 SMB2_ioctl_free(struct smb_rqst *rqst)
3134 {
3135         int i;
3136         if (rqst && rqst->rq_iov) {
3137                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3138                 for (i = 1; i < rqst->rq_nvec; i++)
3139                         if (rqst->rq_iov[i].iov_base != smb2_padding)
3140                                 kfree(rqst->rq_iov[i].iov_base);
3141         }
3142 }
3143
3144
3145 /*
3146  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
3147  */
3148 int
3149 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3150            u64 volatile_fid, u32 opcode, bool is_fsctl,
3151            char *in_data, u32 indatalen, u32 max_out_data_len,
3152            char **out_data, u32 *plen /* returned data len */)
3153 {
3154         struct smb_rqst rqst;
3155         struct smb2_ioctl_rsp *rsp = NULL;
3156         struct cifs_ses *ses;
3157         struct TCP_Server_Info *server;
3158         struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3159         struct kvec rsp_iov = {NULL, 0};
3160         int resp_buftype = CIFS_NO_BUFFER;
3161         int rc = 0;
3162         int flags = 0;
3163
3164         cifs_dbg(FYI, "SMB2 IOCTL\n");
3165
3166         if (out_data != NULL)
3167                 *out_data = NULL;
3168
3169         /* zero out returned data len, in case of error */
3170         if (plen)
3171                 *plen = 0;
3172
3173         if (!tcon)
3174                 return -EIO;
3175
3176         ses = tcon->ses;
3177         if (!ses)
3178                 return -EIO;
3179
3180         server = cifs_pick_channel(ses);
3181         if (!server)
3182                 return -EIO;
3183
3184         if (smb3_encryption_required(tcon))
3185                 flags |= CIFS_TRANSFORM_REQ;
3186
3187         memset(&rqst, 0, sizeof(struct smb_rqst));
3188         memset(&iov, 0, sizeof(iov));
3189         rqst.rq_iov = iov;
3190         rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3191
3192         rc = SMB2_ioctl_init(tcon, server,
3193                              &rqst, persistent_fid, volatile_fid, opcode,
3194                              is_fsctl, in_data, indatalen, max_out_data_len);
3195         if (rc)
3196                 goto ioctl_exit;
3197
3198         rc = cifs_send_recv(xid, ses, server,
3199                             &rqst, &resp_buftype, flags,
3200                             &rsp_iov);
3201         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3202
3203         if (rc != 0)
3204                 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3205                                 ses->Suid, 0, opcode, rc);
3206
3207         if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3208                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3209                 goto ioctl_exit;
3210         } else if (rc == -EINVAL) {
3211                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3212                     (opcode != FSCTL_SRV_COPYCHUNK)) {
3213                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3214                         goto ioctl_exit;
3215                 }
3216         } else if (rc == -E2BIG) {
3217                 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3218                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3219                         goto ioctl_exit;
3220                 }
3221         }
3222
3223         /* check if caller wants to look at return data or just return rc */
3224         if ((plen == NULL) || (out_data == NULL))
3225                 goto ioctl_exit;
3226
3227         /*
3228          * Although unlikely to be possible for rsp to be null and rc not set,
3229          * adding check below is slightly safer long term (and quiets Coverity
3230          * warning)
3231          */
3232         if (rsp == NULL) {
3233                 rc = -EIO;
3234                 goto ioctl_exit;
3235         }
3236
3237         *plen = le32_to_cpu(rsp->OutputCount);
3238
3239         /* We check for obvious errors in the output buffer length and offset */
3240         if (*plen == 0)
3241                 goto ioctl_exit; /* server returned no data */
3242         else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3243                 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3244                 *plen = 0;
3245                 rc = -EIO;
3246                 goto ioctl_exit;
3247         }
3248
3249         if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3250                 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3251                         le32_to_cpu(rsp->OutputOffset));
3252                 *plen = 0;
3253                 rc = -EIO;
3254                 goto ioctl_exit;
3255         }
3256
3257         *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3258                             *plen, GFP_KERNEL);
3259         if (*out_data == NULL) {
3260                 rc = -ENOMEM;
3261                 goto ioctl_exit;
3262         }
3263
3264 ioctl_exit:
3265         SMB2_ioctl_free(&rqst);
3266         free_rsp_buf(resp_buftype, rsp);
3267         return rc;
3268 }
3269
3270 /*
3271  *   Individual callers to ioctl worker function follow
3272  */
3273
3274 int
3275 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3276                      u64 persistent_fid, u64 volatile_fid)
3277 {
3278         int rc;
3279         struct  compress_ioctl fsctl_input;
3280         char *ret_data = NULL;
3281
3282         fsctl_input.CompressionState =
3283                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3284
3285         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3286                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
3287                         (char *)&fsctl_input /* data input */,
3288                         2 /* in data len */, CIFSMaxBufSize /* max out data */,
3289                         &ret_data /* out data */, NULL);
3290
3291         cifs_dbg(FYI, "set compression rc %d\n", rc);
3292
3293         return rc;
3294 }
3295
3296 int
3297 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3298                 struct smb_rqst *rqst,
3299                 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3300 {
3301         struct smb2_close_req *req;
3302         struct kvec *iov = rqst->rq_iov;
3303         unsigned int total_len;
3304         int rc;
3305
3306         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3307                                  (void **) &req, &total_len);
3308         if (rc)
3309                 return rc;
3310
3311         req->PersistentFileId = persistent_fid;
3312         req->VolatileFileId = volatile_fid;
3313         if (query_attrs)
3314                 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3315         else
3316                 req->Flags = 0;
3317         iov[0].iov_base = (char *)req;
3318         iov[0].iov_len = total_len;
3319
3320         return 0;
3321 }
3322
3323 void
3324 SMB2_close_free(struct smb_rqst *rqst)
3325 {
3326         if (rqst && rqst->rq_iov)
3327                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3328 }
3329
3330 int
3331 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3332              u64 persistent_fid, u64 volatile_fid,
3333              struct smb2_file_network_open_info *pbuf)
3334 {
3335         struct smb_rqst rqst;
3336         struct smb2_close_rsp *rsp = NULL;
3337         struct cifs_ses *ses = tcon->ses;
3338         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3339         struct kvec iov[1];
3340         struct kvec rsp_iov;
3341         int resp_buftype = CIFS_NO_BUFFER;
3342         int rc = 0;
3343         int flags = 0;
3344         bool query_attrs = false;
3345
3346         cifs_dbg(FYI, "Close\n");
3347
3348         if (!ses || !server)
3349                 return -EIO;
3350
3351         if (smb3_encryption_required(tcon))
3352                 flags |= CIFS_TRANSFORM_REQ;
3353
3354         memset(&rqst, 0, sizeof(struct smb_rqst));
3355         memset(&iov, 0, sizeof(iov));
3356         rqst.rq_iov = iov;
3357         rqst.rq_nvec = 1;
3358
3359         /* check if need to ask server to return timestamps in close response */
3360         if (pbuf)
3361                 query_attrs = true;
3362
3363         trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3364         rc = SMB2_close_init(tcon, server,
3365                              &rqst, persistent_fid, volatile_fid,
3366                              query_attrs);
3367         if (rc)
3368                 goto close_exit;
3369
3370         rc = cifs_send_recv(xid, ses, server,
3371                             &rqst, &resp_buftype, flags, &rsp_iov);
3372         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3373
3374         if (rc != 0) {
3375                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3376                 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3377                                      rc);
3378                 goto close_exit;
3379         } else {
3380                 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3381                                       ses->Suid);
3382                 /*
3383                  * Note that have to subtract 4 since struct network_open_info
3384                  * has a final 4 byte pad that close response does not have
3385                  */
3386                 if (pbuf)
3387                         memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3388         }
3389
3390         atomic_dec(&tcon->num_remote_opens);
3391 close_exit:
3392         SMB2_close_free(&rqst);
3393         free_rsp_buf(resp_buftype, rsp);
3394
3395         /* retry close in a worker thread if this one is interrupted */
3396         if (is_interrupt_error(rc)) {
3397                 int tmp_rc;
3398
3399                 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3400                                                      volatile_fid);
3401                 if (tmp_rc)
3402                         cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3403                                  persistent_fid, tmp_rc);
3404         }
3405         return rc;
3406 }
3407
3408 int
3409 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3410                 u64 persistent_fid, u64 volatile_fid)
3411 {
3412         return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3413 }
3414
3415 int
3416 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3417                   struct kvec *iov, unsigned int min_buf_size)
3418 {
3419         unsigned int smb_len = iov->iov_len;
3420         char *end_of_smb = smb_len + (char *)iov->iov_base;
3421         char *begin_of_buf = offset + (char *)iov->iov_base;
3422         char *end_of_buf = begin_of_buf + buffer_length;
3423
3424
3425         if (buffer_length < min_buf_size) {
3426                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3427                          buffer_length, min_buf_size);
3428                 return -EINVAL;
3429         }
3430
3431         /* check if beyond RFC1001 maximum length */
3432         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3433                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3434                          buffer_length, smb_len);
3435                 return -EINVAL;
3436         }
3437
3438         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3439                 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3440                 return -EINVAL;
3441         }
3442
3443         return 0;
3444 }
3445
3446 /*
3447  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3448  * Caller must free buffer.
3449  */
3450 int
3451 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3452                            struct kvec *iov, unsigned int minbufsize,
3453                            char *data)
3454 {
3455         char *begin_of_buf = offset + (char *)iov->iov_base;
3456         int rc;
3457
3458         if (!data)
3459                 return -EINVAL;
3460
3461         rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3462         if (rc)
3463                 return rc;
3464
3465         memcpy(data, begin_of_buf, buffer_length);
3466
3467         return 0;
3468 }
3469
3470 int
3471 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3472                      struct smb_rqst *rqst,
3473                      u64 persistent_fid, u64 volatile_fid,
3474                      u8 info_class, u8 info_type, u32 additional_info,
3475                      size_t output_len, size_t input_len, void *input)
3476 {
3477         struct smb2_query_info_req *req;
3478         struct kvec *iov = rqst->rq_iov;
3479         unsigned int total_len;
3480         int rc;
3481
3482         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3483                                  (void **) &req, &total_len);
3484         if (rc)
3485                 return rc;
3486
3487         req->InfoType = info_type;
3488         req->FileInfoClass = info_class;
3489         req->PersistentFileId = persistent_fid;
3490         req->VolatileFileId = volatile_fid;
3491         req->AdditionalInformation = cpu_to_le32(additional_info);
3492
3493         req->OutputBufferLength = cpu_to_le32(output_len);
3494         if (input_len) {
3495                 req->InputBufferLength = cpu_to_le32(input_len);
3496                 /* total_len for smb query request never close to le16 max */
3497                 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3498                 memcpy(req->Buffer, input, input_len);
3499         }
3500
3501         iov[0].iov_base = (char *)req;
3502         /* 1 for Buffer */
3503         iov[0].iov_len = total_len - 1 + input_len;
3504         return 0;
3505 }
3506
3507 void
3508 SMB2_query_info_free(struct smb_rqst *rqst)
3509 {
3510         if (rqst && rqst->rq_iov)
3511                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3512 }
3513
3514 static int
3515 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3516            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3517            u32 additional_info, size_t output_len, size_t min_len, void **data,
3518                 u32 *dlen)
3519 {
3520         struct smb_rqst rqst;
3521         struct smb2_query_info_rsp *rsp = NULL;
3522         struct kvec iov[1];
3523         struct kvec rsp_iov;
3524         int rc = 0;
3525         int resp_buftype = CIFS_NO_BUFFER;
3526         struct cifs_ses *ses = tcon->ses;
3527         struct TCP_Server_Info *server;
3528         int flags = 0;
3529         bool allocated = false;
3530
3531         cifs_dbg(FYI, "Query Info\n");
3532
3533         if (!ses)
3534                 return -EIO;
3535         server = cifs_pick_channel(ses);
3536         if (!server)
3537                 return -EIO;
3538
3539         if (smb3_encryption_required(tcon))
3540                 flags |= CIFS_TRANSFORM_REQ;
3541
3542         memset(&rqst, 0, sizeof(struct smb_rqst));
3543         memset(&iov, 0, sizeof(iov));
3544         rqst.rq_iov = iov;
3545         rqst.rq_nvec = 1;
3546
3547         rc = SMB2_query_info_init(tcon, server,
3548                                   &rqst, persistent_fid, volatile_fid,
3549                                   info_class, info_type, additional_info,
3550                                   output_len, 0, NULL);
3551         if (rc)
3552                 goto qinf_exit;
3553
3554         trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3555                                     ses->Suid, info_class, (__u32)info_type);
3556
3557         rc = cifs_send_recv(xid, ses, server,
3558                             &rqst, &resp_buftype, flags, &rsp_iov);
3559         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3560
3561         if (rc) {
3562                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3563                 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3564                                 ses->Suid, info_class, (__u32)info_type, rc);
3565                 goto qinf_exit;
3566         }
3567
3568         trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3569                                 ses->Suid, info_class, (__u32)info_type);
3570
3571         if (dlen) {
3572                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3573                 if (!*data) {
3574                         *data = kmalloc(*dlen, GFP_KERNEL);
3575                         if (!*data) {
3576                                 cifs_tcon_dbg(VFS,
3577                                         "Error %d allocating memory for acl\n",
3578                                         rc);
3579                                 *dlen = 0;
3580                                 rc = -ENOMEM;
3581                                 goto qinf_exit;
3582                         }
3583                         allocated = true;
3584                 }
3585         }
3586
3587         rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3588                                         le32_to_cpu(rsp->OutputBufferLength),
3589                                         &rsp_iov, min_len, *data);
3590         if (rc && allocated) {
3591                 kfree(*data);
3592                 *data = NULL;
3593                 *dlen = 0;
3594         }
3595
3596 qinf_exit:
3597         SMB2_query_info_free(&rqst);
3598         free_rsp_buf(resp_buftype, rsp);
3599         return rc;
3600 }
3601
3602 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3603         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3604 {
3605         return query_info(xid, tcon, persistent_fid, volatile_fid,
3606                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3607                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3608                           sizeof(struct smb2_file_all_info), (void **)&data,
3609                           NULL);
3610 }
3611
3612 #if 0
3613 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3614 int
3615 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3616                 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3617 {
3618         size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3619                         (sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3620         *plen = 0;
3621
3622         return query_info(xid, tcon, persistent_fid, volatile_fid,
3623                           SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3624                           output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3625         /* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3626 }
3627 #endif
3628
3629 int
3630 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3631                u64 persistent_fid, u64 volatile_fid,
3632                void **data, u32 *plen, u32 extra_info)
3633 {
3634         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3635                                 extra_info;
3636         *plen = 0;
3637
3638         return query_info(xid, tcon, persistent_fid, volatile_fid,
3639                           0, SMB2_O_INFO_SECURITY, additional_info,
3640                           SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3641 }
3642
3643 int
3644 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3645                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3646 {
3647         return query_info(xid, tcon, persistent_fid, volatile_fid,
3648                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3649                           sizeof(struct smb2_file_internal_info),
3650                           sizeof(struct smb2_file_internal_info),
3651                           (void **)&uniqueid, NULL);
3652 }
3653
3654 /*
3655  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3656  * See MS-SMB2 2.2.35 and 2.2.36
3657  */
3658
3659 static int
3660 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3661                  struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3662                  u64 persistent_fid, u64 volatile_fid,
3663                  u32 completion_filter, bool watch_tree)
3664 {
3665         struct smb2_change_notify_req *req;
3666         struct kvec *iov = rqst->rq_iov;
3667         unsigned int total_len;
3668         int rc;
3669
3670         rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3671                                  (void **) &req, &total_len);
3672         if (rc)
3673                 return rc;
3674
3675         req->PersistentFileId = persistent_fid;
3676         req->VolatileFileId = volatile_fid;
3677         /* See note 354 of MS-SMB2, 64K max */
3678         req->OutputBufferLength =
3679                 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3680         req->CompletionFilter = cpu_to_le32(completion_filter);
3681         if (watch_tree)
3682                 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3683         else
3684                 req->Flags = 0;
3685
3686         iov[0].iov_base = (char *)req;
3687         iov[0].iov_len = total_len;
3688
3689         return 0;
3690 }
3691
3692 int
3693 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3694                 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3695                 u32 completion_filter)
3696 {
3697         struct cifs_ses *ses = tcon->ses;
3698         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3699         struct smb_rqst rqst;
3700         struct kvec iov[1];
3701         struct kvec rsp_iov = {NULL, 0};
3702         int resp_buftype = CIFS_NO_BUFFER;
3703         int flags = 0;
3704         int rc = 0;
3705
3706         cifs_dbg(FYI, "change notify\n");
3707         if (!ses || !server)
3708                 return -EIO;
3709
3710         if (smb3_encryption_required(tcon))
3711                 flags |= CIFS_TRANSFORM_REQ;
3712
3713         memset(&rqst, 0, sizeof(struct smb_rqst));
3714         memset(&iov, 0, sizeof(iov));
3715         rqst.rq_iov = iov;
3716         rqst.rq_nvec = 1;
3717
3718         rc = SMB2_notify_init(xid, &rqst, tcon, server,
3719                               persistent_fid, volatile_fid,
3720                               completion_filter, watch_tree);
3721         if (rc)
3722                 goto cnotify_exit;
3723
3724         trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3725                                 (u8)watch_tree, completion_filter);
3726         rc = cifs_send_recv(xid, ses, server,
3727                             &rqst, &resp_buftype, flags, &rsp_iov);
3728
3729         if (rc != 0) {
3730                 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3731                 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3732                                 (u8)watch_tree, completion_filter, rc);
3733         } else
3734                 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3735                                 ses->Suid, (u8)watch_tree, completion_filter);
3736
3737  cnotify_exit:
3738         if (rqst.rq_iov)
3739                 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3740         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3741         return rc;
3742 }
3743
3744
3745
3746 /*
3747  * This is a no-op for now. We're not really interested in the reply, but
3748  * rather in the fact that the server sent one and that server->lstrp
3749  * gets updated.
3750  *
3751  * FIXME: maybe we should consider checking that the reply matches request?
3752  */
3753 static void
3754 smb2_echo_callback(struct mid_q_entry *mid)
3755 {
3756         struct TCP_Server_Info *server = mid->callback_data;
3757         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3758         struct cifs_credits credits = { .value = 0, .instance = 0 };
3759
3760         if (mid->mid_state == MID_RESPONSE_RECEIVED
3761             || mid->mid_state == MID_RESPONSE_MALFORMED) {
3762                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
3763                 credits.instance = server->reconnect_instance;
3764         }
3765
3766         DeleteMidQEntry(mid);
3767         add_credits(server, &credits, CIFS_ECHO_OP);
3768 }
3769
3770 void smb2_reconnect_server(struct work_struct *work)
3771 {
3772         struct TCP_Server_Info *server = container_of(work,
3773                                         struct TCP_Server_Info, reconnect.work);
3774         struct TCP_Server_Info *pserver;
3775         struct cifs_ses *ses, *ses2;
3776         struct cifs_tcon *tcon, *tcon2;
3777         struct list_head tmp_list, tmp_ses_list;
3778         bool tcon_exist = false, ses_exist = false;
3779         bool tcon_selected = false;
3780         int rc;
3781         bool resched = false;
3782
3783         /* If server is a channel, select the primary channel */
3784         pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
3785
3786         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3787         mutex_lock(&pserver->reconnect_mutex);
3788
3789         INIT_LIST_HEAD(&tmp_list);
3790         INIT_LIST_HEAD(&tmp_ses_list);
3791         cifs_dbg(FYI, "Reconnecting tcons and channels\n");
3792
3793         spin_lock(&cifs_tcp_ses_lock);
3794         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
3795
3796                 tcon_selected = false;
3797
3798                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3799                         if (tcon->need_reconnect || tcon->need_reopen_files) {
3800                                 tcon->tc_count++;
3801                                 list_add_tail(&tcon->rlist, &tmp_list);
3802                                 tcon_selected = tcon_exist = true;
3803                         }
3804                 }
3805                 /*
3806                  * IPC has the same lifetime as its session and uses its
3807                  * refcount.
3808                  */
3809                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3810                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3811                         tcon_selected = tcon_exist = true;
3812                         ses->ses_count++;
3813                 }
3814                 /*
3815                  * handle the case where channel needs to reconnect
3816                  * binding session, but tcon is healthy (some other channel
3817                  * is active)
3818                  */
3819                 spin_lock(&ses->chan_lock);
3820                 if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
3821                         list_add_tail(&ses->rlist, &tmp_ses_list);
3822                         ses_exist = true;
3823                         ses->ses_count++;
3824                 }
3825                 spin_unlock(&ses->chan_lock);
3826         }
3827         /*
3828          * Get the reference to server struct to be sure that the last call of
3829          * cifs_put_tcon() in the loop below won't release the server pointer.
3830          */
3831         if (tcon_exist || ses_exist)
3832                 server->srv_count++;
3833
3834         spin_unlock(&cifs_tcp_ses_lock);
3835
3836         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3837                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3838                 if (!rc)
3839                         cifs_reopen_persistent_handles(tcon);
3840                 else
3841                         resched = true;
3842                 list_del_init(&tcon->rlist);
3843                 if (tcon->ipc)
3844                         cifs_put_smb_ses(tcon->ses);
3845                 else
3846                         cifs_put_tcon(tcon);
3847         }
3848
3849         if (!ses_exist)
3850                 goto done;
3851
3852         /* allocate a dummy tcon struct used for reconnect */
3853         tcon = kzalloc(sizeof(struct cifs_tcon), GFP_KERNEL);
3854         if (!tcon) {
3855                 resched = true;
3856                 list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3857                         list_del_init(&ses->rlist);
3858                         cifs_put_smb_ses(ses);
3859                 }
3860                 goto done;
3861         }
3862
3863         tcon->status = TID_GOOD;
3864         tcon->retry = false;
3865         tcon->need_reconnect = false;
3866
3867         /* now reconnect sessions for necessary channels */
3868         list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3869                 tcon->ses = ses;
3870                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3871                 if (rc)
3872                         resched = true;
3873                 list_del_init(&ses->rlist);
3874                 cifs_put_smb_ses(ses);
3875         }
3876         kfree(tcon);
3877
3878 done:
3879         cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
3880         if (resched)
3881                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3882         mutex_unlock(&pserver->reconnect_mutex);
3883
3884         /* now we can safely release srv struct */
3885         if (tcon_exist || ses_exist)
3886                 cifs_put_tcp_session(server, 1);
3887 }
3888
3889 int
3890 SMB2_echo(struct TCP_Server_Info *server)
3891 {
3892         struct smb2_echo_req *req;
3893         int rc = 0;
3894         struct kvec iov[1];
3895         struct smb_rqst rqst = { .rq_iov = iov,
3896                                  .rq_nvec = 1 };
3897         unsigned int total_len;
3898
3899         cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
3900
3901         spin_lock(&cifs_tcp_ses_lock);
3902         if (server->ops->need_neg &&
3903             server->ops->need_neg(server)) {
3904                 spin_unlock(&cifs_tcp_ses_lock);
3905                 /* No need to send echo on newly established connections */
3906                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3907                 return rc;
3908         }
3909         spin_unlock(&cifs_tcp_ses_lock);
3910
3911         rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
3912                                  (void **)&req, &total_len);
3913         if (rc)
3914                 return rc;
3915
3916         req->hdr.CreditRequest = cpu_to_le16(1);
3917
3918         iov[0].iov_len = total_len;
3919         iov[0].iov_base = (char *)req;
3920
3921         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3922                              server, CIFS_ECHO_OP, NULL);
3923         if (rc)
3924                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3925
3926         cifs_small_buf_release(req);
3927         return rc;
3928 }
3929
3930 void
3931 SMB2_flush_free(struct smb_rqst *rqst)
3932 {
3933         if (rqst && rqst->rq_iov)
3934                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3935 }
3936
3937 int
3938 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3939                 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3940                 u64 persistent_fid, u64 volatile_fid)
3941 {
3942         struct smb2_flush_req *req;
3943         struct kvec *iov = rqst->rq_iov;
3944         unsigned int total_len;
3945         int rc;
3946
3947         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
3948                                  (void **) &req, &total_len);
3949         if (rc)
3950                 return rc;
3951
3952         req->PersistentFileId = persistent_fid;
3953         req->VolatileFileId = volatile_fid;
3954
3955         iov[0].iov_base = (char *)req;
3956         iov[0].iov_len = total_len;
3957
3958         return 0;
3959 }
3960
3961 int
3962 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3963            u64 volatile_fid)
3964 {
3965         struct cifs_ses *ses = tcon->ses;
3966         struct smb_rqst rqst;
3967         struct kvec iov[1];
3968         struct kvec rsp_iov = {NULL, 0};
3969         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3970         int resp_buftype = CIFS_NO_BUFFER;
3971         int flags = 0;
3972         int rc = 0;
3973
3974         cifs_dbg(FYI, "flush\n");
3975         if (!ses || !(ses->server))
3976                 return -EIO;
3977
3978         if (smb3_encryption_required(tcon))
3979                 flags |= CIFS_TRANSFORM_REQ;
3980
3981         memset(&rqst, 0, sizeof(struct smb_rqst));
3982         memset(&iov, 0, sizeof(iov));
3983         rqst.rq_iov = iov;
3984         rqst.rq_nvec = 1;
3985
3986         rc = SMB2_flush_init(xid, &rqst, tcon, server,
3987                              persistent_fid, volatile_fid);
3988         if (rc)
3989                 goto flush_exit;
3990
3991         trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3992         rc = cifs_send_recv(xid, ses, server,
3993                             &rqst, &resp_buftype, flags, &rsp_iov);
3994
3995         if (rc != 0) {
3996                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
3997                 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
3998                                      rc);
3999         } else
4000                 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4001                                       ses->Suid);
4002
4003  flush_exit:
4004         SMB2_flush_free(&rqst);
4005         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4006         return rc;
4007 }
4008
4009 /*
4010  * To form a chain of read requests, any read requests after the first should
4011  * have the end_of_chain boolean set to true.
4012  */
4013 static int
4014 smb2_new_read_req(void **buf, unsigned int *total_len,
4015         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
4016         unsigned int remaining_bytes, int request_type)
4017 {
4018         int rc = -EACCES;
4019         struct smb2_read_req *req = NULL;
4020         struct smb2_hdr *shdr;
4021         struct TCP_Server_Info *server = io_parms->server;
4022
4023         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4024                                  (void **) &req, total_len);
4025         if (rc)
4026                 return rc;
4027
4028         if (server == NULL)
4029                 return -ECONNABORTED;
4030
4031         shdr = &req->hdr;
4032         shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4033
4034         req->PersistentFileId = io_parms->persistent_fid;
4035         req->VolatileFileId = io_parms->volatile_fid;
4036         req->ReadChannelInfoOffset = 0; /* reserved */
4037         req->ReadChannelInfoLength = 0; /* reserved */
4038         req->Channel = 0; /* reserved */
4039         req->MinimumCount = 0;
4040         req->Length = cpu_to_le32(io_parms->length);
4041         req->Offset = cpu_to_le64(io_parms->offset);
4042
4043         trace_smb3_read_enter(0 /* xid */,
4044                         io_parms->persistent_fid,
4045                         io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4046                         io_parms->offset, io_parms->length);
4047 #ifdef CONFIG_CIFS_SMB_DIRECT
4048         /*
4049          * If we want to do a RDMA write, fill in and append
4050          * smbd_buffer_descriptor_v1 to the end of read request
4051          */
4052         if (server->rdma && rdata && !server->sign &&
4053                 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
4054
4055                 struct smbd_buffer_descriptor_v1 *v1;
4056                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4057
4058                 rdata->mr = smbd_register_mr(
4059                                 server->smbd_conn, rdata->pages,
4060                                 rdata->nr_pages, rdata->page_offset,
4061                                 rdata->tailsz, true, need_invalidate);
4062                 if (!rdata->mr)
4063                         return -EAGAIN;
4064
4065                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4066                 if (need_invalidate)
4067                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4068                 req->ReadChannelInfoOffset =
4069                         cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4070                 req->ReadChannelInfoLength =
4071                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4072                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4073                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4074                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4075                 v1->length = cpu_to_le32(rdata->mr->mr->length);
4076
4077                 *total_len += sizeof(*v1) - 1;
4078         }
4079 #endif
4080         if (request_type & CHAINED_REQUEST) {
4081                 if (!(request_type & END_OF_CHAIN)) {
4082                         /* next 8-byte aligned request */
4083                         *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
4084                         shdr->NextCommand = cpu_to_le32(*total_len);
4085                 } else /* END_OF_CHAIN */
4086                         shdr->NextCommand = 0;
4087                 if (request_type & RELATED_REQUEST) {
4088                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4089                         /*
4090                          * Related requests use info from previous read request
4091                          * in chain.
4092                          */
4093                         shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4094                         shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4095                         req->PersistentFileId = (u64)-1;
4096                         req->VolatileFileId = (u64)-1;
4097                 }
4098         }
4099         if (remaining_bytes > io_parms->length)
4100                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
4101         else
4102                 req->RemainingBytes = 0;
4103
4104         *buf = req;
4105         return rc;
4106 }
4107
4108 static void
4109 smb2_readv_callback(struct mid_q_entry *mid)
4110 {
4111         struct cifs_readdata *rdata = mid->callback_data;
4112         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4113         struct TCP_Server_Info *server = rdata->server;
4114         struct smb2_hdr *shdr =
4115                                 (struct smb2_hdr *)rdata->iov[0].iov_base;
4116         struct cifs_credits credits = { .value = 0, .instance = 0 };
4117         struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
4118                                  .rq_nvec = 1,
4119                                  .rq_pages = rdata->pages,
4120                                  .rq_offset = rdata->page_offset,
4121                                  .rq_npages = rdata->nr_pages,
4122                                  .rq_pagesz = rdata->pagesz,
4123                                  .rq_tailsz = rdata->tailsz };
4124
4125         WARN_ONCE(rdata->server != mid->server,
4126                   "rdata server %p != mid server %p",
4127                   rdata->server, mid->server);
4128
4129         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
4130                  __func__, mid->mid, mid->mid_state, rdata->result,
4131                  rdata->bytes);
4132
4133         switch (mid->mid_state) {
4134         case MID_RESPONSE_RECEIVED:
4135                 credits.value = le16_to_cpu(shdr->CreditRequest);
4136                 credits.instance = server->reconnect_instance;
4137                 /* result already set, check signature */
4138                 if (server->sign && !mid->decrypted) {
4139                         int rc;
4140
4141                         rc = smb2_verify_signature(&rqst, server);
4142                         if (rc)
4143                                 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4144                                          rc);
4145                 }
4146                 /* FIXME: should this be counted toward the initiating task? */
4147                 task_io_account_read(rdata->got_bytes);
4148                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4149                 break;
4150         case MID_REQUEST_SUBMITTED:
4151         case MID_RETRY_NEEDED:
4152                 rdata->result = -EAGAIN;
4153                 if (server->sign && rdata->got_bytes)
4154                         /* reset bytes number since we can not check a sign */
4155                         rdata->got_bytes = 0;
4156                 /* FIXME: should this be counted toward the initiating task? */
4157                 task_io_account_read(rdata->got_bytes);
4158                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4159                 break;
4160         case MID_RESPONSE_MALFORMED:
4161                 credits.value = le16_to_cpu(shdr->CreditRequest);
4162                 credits.instance = server->reconnect_instance;
4163                 fallthrough;
4164         default:
4165                 rdata->result = -EIO;
4166         }
4167 #ifdef CONFIG_CIFS_SMB_DIRECT
4168         /*
4169          * If this rdata has a memmory registered, the MR can be freed
4170          * MR needs to be freed as soon as I/O finishes to prevent deadlock
4171          * because they have limited number and are used for future I/Os
4172          */
4173         if (rdata->mr) {
4174                 smbd_deregister_mr(rdata->mr);
4175                 rdata->mr = NULL;
4176         }
4177 #endif
4178         if (rdata->result && rdata->result != -ENODATA) {
4179                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4180                 trace_smb3_read_err(0 /* xid */,
4181                                     rdata->cfile->fid.persistent_fid,
4182                                     tcon->tid, tcon->ses->Suid, rdata->offset,
4183                                     rdata->bytes, rdata->result);
4184         } else
4185                 trace_smb3_read_done(0 /* xid */,
4186                                      rdata->cfile->fid.persistent_fid,
4187                                      tcon->tid, tcon->ses->Suid,
4188                                      rdata->offset, rdata->got_bytes);
4189
4190         queue_work(cifsiod_wq, &rdata->work);
4191         DeleteMidQEntry(mid);
4192         add_credits(server, &credits, 0);
4193 }
4194
4195 /* smb2_async_readv - send an async read, and set up mid to handle result */
4196 int
4197 smb2_async_readv(struct cifs_readdata *rdata)
4198 {
4199         int rc, flags = 0;
4200         char *buf;
4201         struct smb2_hdr *shdr;
4202         struct cifs_io_parms io_parms;
4203         struct smb_rqst rqst = { .rq_iov = rdata->iov,
4204                                  .rq_nvec = 1 };
4205         struct TCP_Server_Info *server;
4206         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4207         unsigned int total_len;
4208
4209         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4210                  __func__, rdata->offset, rdata->bytes);
4211
4212         if (!rdata->server)
4213                 rdata->server = cifs_pick_channel(tcon->ses);
4214
4215         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4216         io_parms.server = server = rdata->server;
4217         io_parms.offset = rdata->offset;
4218         io_parms.length = rdata->bytes;
4219         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4220         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4221         io_parms.pid = rdata->pid;
4222
4223         rc = smb2_new_read_req(
4224                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4225         if (rc)
4226                 return rc;
4227
4228         if (smb3_encryption_required(io_parms.tcon))
4229                 flags |= CIFS_TRANSFORM_REQ;
4230
4231         rdata->iov[0].iov_base = buf;
4232         rdata->iov[0].iov_len = total_len;
4233
4234         shdr = (struct smb2_hdr *)buf;
4235
4236         if (rdata->credits.value > 0) {
4237                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4238                                                 SMB2_MAX_BUFFER_SIZE));
4239                 shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4240
4241                 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4242                 if (rc)
4243                         goto async_readv_out;
4244
4245                 flags |= CIFS_HAS_CREDITS;
4246         }
4247
4248         kref_get(&rdata->refcount);
4249         rc = cifs_call_async(server, &rqst,
4250                              cifs_readv_receive, smb2_readv_callback,
4251                              smb3_handle_read_data, rdata, flags,
4252                              &rdata->credits);
4253         if (rc) {
4254                 kref_put(&rdata->refcount, cifs_readdata_release);
4255                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4256                 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4257                                     io_parms.tcon->tid,
4258                                     io_parms.tcon->ses->Suid,
4259                                     io_parms.offset, io_parms.length, rc);
4260         }
4261
4262 async_readv_out:
4263         cifs_small_buf_release(buf);
4264         return rc;
4265 }
4266
4267 int
4268 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4269           unsigned int *nbytes, char **buf, int *buf_type)
4270 {
4271         struct smb_rqst rqst;
4272         int resp_buftype, rc;
4273         struct smb2_read_req *req = NULL;
4274         struct smb2_read_rsp *rsp = NULL;
4275         struct kvec iov[1];
4276         struct kvec rsp_iov;
4277         unsigned int total_len;
4278         int flags = CIFS_LOG_ERROR;
4279         struct cifs_ses *ses = io_parms->tcon->ses;
4280
4281         if (!io_parms->server)
4282                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4283
4284         *nbytes = 0;
4285         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4286         if (rc)
4287                 return rc;
4288
4289         if (smb3_encryption_required(io_parms->tcon))
4290                 flags |= CIFS_TRANSFORM_REQ;
4291
4292         iov[0].iov_base = (char *)req;
4293         iov[0].iov_len = total_len;
4294
4295         memset(&rqst, 0, sizeof(struct smb_rqst));
4296         rqst.rq_iov = iov;
4297         rqst.rq_nvec = 1;
4298
4299         rc = cifs_send_recv(xid, ses, io_parms->server,
4300                             &rqst, &resp_buftype, flags, &rsp_iov);
4301         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4302
4303         if (rc) {
4304                 if (rc != -ENODATA) {
4305                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4306                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
4307                         trace_smb3_read_err(xid,
4308                                             req->PersistentFileId,
4309                                             io_parms->tcon->tid, ses->Suid,
4310                                             io_parms->offset, io_parms->length,
4311                                             rc);
4312                 } else
4313                         trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
4314                                              ses->Suid, io_parms->offset, 0);
4315                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4316                 cifs_small_buf_release(req);
4317                 return rc == -ENODATA ? 0 : rc;
4318         } else
4319                 trace_smb3_read_done(xid,
4320                                     req->PersistentFileId,
4321                                     io_parms->tcon->tid, ses->Suid,
4322                                     io_parms->offset, io_parms->length);
4323
4324         cifs_small_buf_release(req);
4325
4326         *nbytes = le32_to_cpu(rsp->DataLength);
4327         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4328             (*nbytes > io_parms->length)) {
4329                 cifs_dbg(FYI, "bad length %d for count %d\n",
4330                          *nbytes, io_parms->length);
4331                 rc = -EIO;
4332                 *nbytes = 0;
4333         }
4334
4335         if (*buf) {
4336                 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4337                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4338         } else if (resp_buftype != CIFS_NO_BUFFER) {
4339                 *buf = rsp_iov.iov_base;
4340                 if (resp_buftype == CIFS_SMALL_BUFFER)
4341                         *buf_type = CIFS_SMALL_BUFFER;
4342                 else if (resp_buftype == CIFS_LARGE_BUFFER)
4343                         *buf_type = CIFS_LARGE_BUFFER;
4344         }
4345         return rc;
4346 }
4347
4348 /*
4349  * Check the mid_state and signature on received buffer (if any), and queue the
4350  * workqueue completion task.
4351  */
4352 static void
4353 smb2_writev_callback(struct mid_q_entry *mid)
4354 {
4355         struct cifs_writedata *wdata = mid->callback_data;
4356         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4357         struct TCP_Server_Info *server = wdata->server;
4358         unsigned int written;
4359         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4360         struct cifs_credits credits = { .value = 0, .instance = 0 };
4361
4362         WARN_ONCE(wdata->server != mid->server,
4363                   "wdata server %p != mid server %p",
4364                   wdata->server, mid->server);
4365
4366         switch (mid->mid_state) {
4367         case MID_RESPONSE_RECEIVED:
4368                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4369                 credits.instance = server->reconnect_instance;
4370                 wdata->result = smb2_check_receive(mid, server, 0);
4371                 if (wdata->result != 0)
4372                         break;
4373
4374                 written = le32_to_cpu(rsp->DataLength);
4375                 /*
4376                  * Mask off high 16 bits when bytes written as returned
4377                  * by the server is greater than bytes requested by the
4378                  * client. OS/2 servers are known to set incorrect
4379                  * CountHigh values.
4380                  */
4381                 if (written > wdata->bytes)
4382                         written &= 0xFFFF;
4383
4384                 if (written < wdata->bytes)
4385                         wdata->result = -ENOSPC;
4386                 else
4387                         wdata->bytes = written;
4388                 break;
4389         case MID_REQUEST_SUBMITTED:
4390         case MID_RETRY_NEEDED:
4391                 wdata->result = -EAGAIN;
4392                 break;
4393         case MID_RESPONSE_MALFORMED:
4394                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4395                 credits.instance = server->reconnect_instance;
4396                 fallthrough;
4397         default:
4398                 wdata->result = -EIO;
4399                 break;
4400         }
4401 #ifdef CONFIG_CIFS_SMB_DIRECT
4402         /*
4403          * If this wdata has a memory registered, the MR can be freed
4404          * The number of MRs available is limited, it's important to recover
4405          * used MR as soon as I/O is finished. Hold MR longer in the later
4406          * I/O process can possibly result in I/O deadlock due to lack of MR
4407          * to send request on I/O retry
4408          */
4409         if (wdata->mr) {
4410                 smbd_deregister_mr(wdata->mr);
4411                 wdata->mr = NULL;
4412         }
4413 #endif
4414         if (wdata->result) {
4415                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4416                 trace_smb3_write_err(0 /* no xid */,
4417                                      wdata->cfile->fid.persistent_fid,
4418                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4419                                      wdata->bytes, wdata->result);
4420                 if (wdata->result == -ENOSPC)
4421                         pr_warn_once("Out of space writing to %s\n",
4422                                      tcon->treeName);
4423         } else
4424                 trace_smb3_write_done(0 /* no xid */,
4425                                       wdata->cfile->fid.persistent_fid,
4426                                       tcon->tid, tcon->ses->Suid,
4427                                       wdata->offset, wdata->bytes);
4428
4429         queue_work(cifsiod_wq, &wdata->work);
4430         DeleteMidQEntry(mid);
4431         add_credits(server, &credits, 0);
4432 }
4433
4434 /* smb2_async_writev - send an async write, and set up mid to handle result */
4435 int
4436 smb2_async_writev(struct cifs_writedata *wdata,
4437                   void (*release)(struct kref *kref))
4438 {
4439         int rc = -EACCES, flags = 0;
4440         struct smb2_write_req *req = NULL;
4441         struct smb2_hdr *shdr;
4442         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4443         struct TCP_Server_Info *server = wdata->server;
4444         struct kvec iov[1];
4445         struct smb_rqst rqst = { };
4446         unsigned int total_len;
4447
4448         if (!wdata->server)
4449                 server = wdata->server = cifs_pick_channel(tcon->ses);
4450
4451         rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4452                                  (void **) &req, &total_len);
4453         if (rc)
4454                 return rc;
4455
4456         if (smb3_encryption_required(tcon))
4457                 flags |= CIFS_TRANSFORM_REQ;
4458
4459         shdr = (struct smb2_hdr *)req;
4460         shdr->Id.SyncId.ProcessId = cpu_to_le32(wdata->cfile->pid);
4461
4462         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4463         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4464         req->WriteChannelInfoOffset = 0;
4465         req->WriteChannelInfoLength = 0;
4466         req->Channel = 0;
4467         req->Offset = cpu_to_le64(wdata->offset);
4468         req->DataOffset = cpu_to_le16(
4469                                 offsetof(struct smb2_write_req, Buffer));
4470         req->RemainingBytes = 0;
4471
4472         trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4473                 tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4474 #ifdef CONFIG_CIFS_SMB_DIRECT
4475         /*
4476          * If we want to do a server RDMA read, fill in and append
4477          * smbd_buffer_descriptor_v1 to the end of write request
4478          */
4479         if (server->rdma && !server->sign && wdata->bytes >=
4480                 server->smbd_conn->rdma_readwrite_threshold) {
4481
4482                 struct smbd_buffer_descriptor_v1 *v1;
4483                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4484
4485                 wdata->mr = smbd_register_mr(
4486                                 server->smbd_conn, wdata->pages,
4487                                 wdata->nr_pages, wdata->page_offset,
4488                                 wdata->tailsz, false, need_invalidate);
4489                 if (!wdata->mr) {
4490                         rc = -EAGAIN;
4491                         goto async_writev_out;
4492                 }
4493                 req->Length = 0;
4494                 req->DataOffset = 0;
4495                 if (wdata->nr_pages > 1)
4496                         req->RemainingBytes =
4497                                 cpu_to_le32(
4498                                         (wdata->nr_pages - 1) * wdata->pagesz -
4499                                         wdata->page_offset + wdata->tailsz
4500                                 );
4501                 else
4502                         req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4503                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4504                 if (need_invalidate)
4505                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4506                 req->WriteChannelInfoOffset =
4507                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4508                 req->WriteChannelInfoLength =
4509                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4510                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4511                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4512                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4513                 v1->length = cpu_to_le32(wdata->mr->mr->length);
4514         }
4515 #endif
4516         iov[0].iov_len = total_len - 1;
4517         iov[0].iov_base = (char *)req;
4518
4519         rqst.rq_iov = iov;
4520         rqst.rq_nvec = 1;
4521         rqst.rq_pages = wdata->pages;
4522         rqst.rq_offset = wdata->page_offset;
4523         rqst.rq_npages = wdata->nr_pages;
4524         rqst.rq_pagesz = wdata->pagesz;
4525         rqst.rq_tailsz = wdata->tailsz;
4526 #ifdef CONFIG_CIFS_SMB_DIRECT
4527         if (wdata->mr) {
4528                 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4529                 rqst.rq_npages = 0;
4530         }
4531 #endif
4532         cifs_dbg(FYI, "async write at %llu %u bytes\n",
4533                  wdata->offset, wdata->bytes);
4534
4535 #ifdef CONFIG_CIFS_SMB_DIRECT
4536         /* For RDMA read, I/O size is in RemainingBytes not in Length */
4537         if (!wdata->mr)
4538                 req->Length = cpu_to_le32(wdata->bytes);
4539 #else
4540         req->Length = cpu_to_le32(wdata->bytes);
4541 #endif
4542
4543         if (wdata->credits.value > 0) {
4544                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4545                                                     SMB2_MAX_BUFFER_SIZE));
4546                 shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4547
4548                 rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4549                 if (rc)
4550                         goto async_writev_out;
4551
4552                 flags |= CIFS_HAS_CREDITS;
4553         }
4554
4555         kref_get(&wdata->refcount);
4556         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4557                              wdata, flags, &wdata->credits);
4558
4559         if (rc) {
4560                 trace_smb3_write_err(0 /* no xid */,
4561                                      req->PersistentFileId,
4562                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4563                                      wdata->bytes, rc);
4564                 kref_put(&wdata->refcount, release);
4565                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4566         }
4567
4568 async_writev_out:
4569         cifs_small_buf_release(req);
4570         return rc;
4571 }
4572
4573 /*
4574  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4575  * The length field from io_parms must be at least 1 and indicates a number of
4576  * elements with data to write that begins with position 1 in iov array. All
4577  * data length is specified by count.
4578  */
4579 int
4580 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4581            unsigned int *nbytes, struct kvec *iov, int n_vec)
4582 {
4583         struct smb_rqst rqst;
4584         int rc = 0;
4585         struct smb2_write_req *req = NULL;
4586         struct smb2_write_rsp *rsp = NULL;
4587         int resp_buftype;
4588         struct kvec rsp_iov;
4589         int flags = 0;
4590         unsigned int total_len;
4591         struct TCP_Server_Info *server;
4592
4593         *nbytes = 0;
4594
4595         if (n_vec < 1)
4596                 return rc;
4597
4598         if (!io_parms->server)
4599                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4600         server = io_parms->server;
4601         if (server == NULL)
4602                 return -ECONNABORTED;
4603
4604         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4605                                  (void **) &req, &total_len);
4606         if (rc)
4607                 return rc;
4608
4609         if (smb3_encryption_required(io_parms->tcon))
4610                 flags |= CIFS_TRANSFORM_REQ;
4611
4612         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4613
4614         req->PersistentFileId = io_parms->persistent_fid;
4615         req->VolatileFileId = io_parms->volatile_fid;
4616         req->WriteChannelInfoOffset = 0;
4617         req->WriteChannelInfoLength = 0;
4618         req->Channel = 0;
4619         req->Length = cpu_to_le32(io_parms->length);
4620         req->Offset = cpu_to_le64(io_parms->offset);
4621         req->DataOffset = cpu_to_le16(
4622                                 offsetof(struct smb2_write_req, Buffer));
4623         req->RemainingBytes = 0;
4624
4625         trace_smb3_write_enter(xid, io_parms->persistent_fid,
4626                 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4627                 io_parms->offset, io_parms->length);
4628
4629         iov[0].iov_base = (char *)req;
4630         /* 1 for Buffer */
4631         iov[0].iov_len = total_len - 1;
4632
4633         memset(&rqst, 0, sizeof(struct smb_rqst));
4634         rqst.rq_iov = iov;
4635         rqst.rq_nvec = n_vec + 1;
4636
4637         rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4638                             &rqst,
4639                             &resp_buftype, flags, &rsp_iov);
4640         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4641
4642         if (rc) {
4643                 trace_smb3_write_err(xid,
4644                                      req->PersistentFileId,
4645                                      io_parms->tcon->tid,
4646                                      io_parms->tcon->ses->Suid,
4647                                      io_parms->offset, io_parms->length, rc);
4648                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4649                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
4650         } else {
4651                 *nbytes = le32_to_cpu(rsp->DataLength);
4652                 trace_smb3_write_done(xid,
4653                                       req->PersistentFileId,
4654                                       io_parms->tcon->tid,
4655                                       io_parms->tcon->ses->Suid,
4656                                       io_parms->offset, *nbytes);
4657         }
4658
4659         cifs_small_buf_release(req);
4660         free_rsp_buf(resp_buftype, rsp);
4661         return rc;
4662 }
4663
4664 int posix_info_sid_size(const void *beg, const void *end)
4665 {
4666         size_t subauth;
4667         int total;
4668
4669         if (beg + 1 > end)
4670                 return -1;
4671
4672         subauth = *(u8 *)(beg+1);
4673         if (subauth < 1 || subauth > 15)
4674                 return -1;
4675
4676         total = 1 + 1 + 6 + 4*subauth;
4677         if (beg + total > end)
4678                 return -1;
4679
4680         return total;
4681 }
4682
4683 int posix_info_parse(const void *beg, const void *end,
4684                      struct smb2_posix_info_parsed *out)
4685
4686 {
4687         int total_len = 0;
4688         int owner_len, group_len;
4689         int name_len;
4690         const void *owner_sid;
4691         const void *group_sid;
4692         const void *name;
4693
4694         /* if no end bound given, assume payload to be correct */
4695         if (!end) {
4696                 const struct smb2_posix_info *p = beg;
4697
4698                 end = beg + le32_to_cpu(p->NextEntryOffset);
4699                 /* last element will have a 0 offset, pick a sensible bound */
4700                 if (end == beg)
4701                         end += 0xFFFF;
4702         }
4703
4704         /* check base buf */
4705         if (beg + sizeof(struct smb2_posix_info) > end)
4706                 return -1;
4707         total_len = sizeof(struct smb2_posix_info);
4708
4709         /* check owner sid */
4710         owner_sid = beg + total_len;
4711         owner_len = posix_info_sid_size(owner_sid, end);
4712         if (owner_len < 0)
4713                 return -1;
4714         total_len += owner_len;
4715
4716         /* check group sid */
4717         group_sid = beg + total_len;
4718         group_len = posix_info_sid_size(group_sid, end);
4719         if (group_len < 0)
4720                 return -1;
4721         total_len += group_len;
4722
4723         /* check name len */
4724         if (beg + total_len + 4 > end)
4725                 return -1;
4726         name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4727         if (name_len < 1 || name_len > 0xFFFF)
4728                 return -1;
4729         total_len += 4;
4730
4731         /* check name */
4732         name = beg + total_len;
4733         if (name + name_len > end)
4734                 return -1;
4735         total_len += name_len;
4736
4737         if (out) {
4738                 out->base = beg;
4739                 out->size = total_len;
4740                 out->name_len = name_len;
4741                 out->name = name;
4742                 memcpy(&out->owner, owner_sid, owner_len);
4743                 memcpy(&out->group, group_sid, group_len);
4744         }
4745         return total_len;
4746 }
4747
4748 static int posix_info_extra_size(const void *beg, const void *end)
4749 {
4750         int len = posix_info_parse(beg, end, NULL);
4751
4752         if (len < 0)
4753                 return -1;
4754         return len - sizeof(struct smb2_posix_info);
4755 }
4756
4757 static unsigned int
4758 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4759             size_t size)
4760 {
4761         int len;
4762         unsigned int entrycount = 0;
4763         unsigned int next_offset = 0;
4764         char *entryptr;
4765         FILE_DIRECTORY_INFO *dir_info;
4766
4767         if (bufstart == NULL)
4768                 return 0;
4769
4770         entryptr = bufstart;
4771
4772         while (1) {
4773                 if (entryptr + next_offset < entryptr ||
4774                     entryptr + next_offset > end_of_buf ||
4775                     entryptr + next_offset + size > end_of_buf) {
4776                         cifs_dbg(VFS, "malformed search entry would overflow\n");
4777                         break;
4778                 }
4779
4780                 entryptr = entryptr + next_offset;
4781                 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4782
4783                 if (infotype == SMB_FIND_FILE_POSIX_INFO)
4784                         len = posix_info_extra_size(entryptr, end_of_buf);
4785                 else
4786                         len = le32_to_cpu(dir_info->FileNameLength);
4787
4788                 if (len < 0 ||
4789                     entryptr + len < entryptr ||
4790                     entryptr + len > end_of_buf ||
4791                     entryptr + len + size > end_of_buf) {
4792                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4793                                  end_of_buf);
4794                         break;
4795                 }
4796
4797                 *lastentry = entryptr;
4798                 entrycount++;
4799
4800                 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4801                 if (!next_offset)
4802                         break;
4803         }
4804
4805         return entrycount;
4806 }
4807
4808 /*
4809  * Readdir/FindFirst
4810  */
4811 int SMB2_query_directory_init(const unsigned int xid,
4812                               struct cifs_tcon *tcon,
4813                               struct TCP_Server_Info *server,
4814                               struct smb_rqst *rqst,
4815                               u64 persistent_fid, u64 volatile_fid,
4816                               int index, int info_level)
4817 {
4818         struct smb2_query_directory_req *req;
4819         unsigned char *bufptr;
4820         __le16 asteriks = cpu_to_le16('*');
4821         unsigned int output_size = CIFSMaxBufSize -
4822                 MAX_SMB2_CREATE_RESPONSE_SIZE -
4823                 MAX_SMB2_CLOSE_RESPONSE_SIZE;
4824         unsigned int total_len;
4825         struct kvec *iov = rqst->rq_iov;
4826         int len, rc;
4827
4828         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
4829                                  (void **) &req, &total_len);
4830         if (rc)
4831                 return rc;
4832
4833         switch (info_level) {
4834         case SMB_FIND_FILE_DIRECTORY_INFO:
4835                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4836                 break;
4837         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4838                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4839                 break;
4840         case SMB_FIND_FILE_POSIX_INFO:
4841                 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4842                 break;
4843         default:
4844                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4845                         info_level);
4846                 return -EINVAL;
4847         }
4848
4849         req->FileIndex = cpu_to_le32(index);
4850         req->PersistentFileId = persistent_fid;
4851         req->VolatileFileId = volatile_fid;
4852
4853         len = 0x2;
4854         bufptr = req->Buffer;
4855         memcpy(bufptr, &asteriks, len);
4856
4857         req->FileNameOffset =
4858                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4859         req->FileNameLength = cpu_to_le16(len);
4860         /*
4861          * BB could be 30 bytes or so longer if we used SMB2 specific
4862          * buffer lengths, but this is safe and close enough.
4863          */
4864         output_size = min_t(unsigned int, output_size, server->maxBuf);
4865         output_size = min_t(unsigned int, output_size, 2 << 15);
4866         req->OutputBufferLength = cpu_to_le32(output_size);
4867
4868         iov[0].iov_base = (char *)req;
4869         /* 1 for Buffer */
4870         iov[0].iov_len = total_len - 1;
4871
4872         iov[1].iov_base = (char *)(req->Buffer);
4873         iov[1].iov_len = len;
4874
4875         trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4876                         tcon->ses->Suid, index, output_size);
4877
4878         return 0;
4879 }
4880
4881 void SMB2_query_directory_free(struct smb_rqst *rqst)
4882 {
4883         if (rqst && rqst->rq_iov) {
4884                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4885         }
4886 }
4887
4888 int
4889 smb2_parse_query_directory(struct cifs_tcon *tcon,
4890                            struct kvec *rsp_iov,
4891                            int resp_buftype,
4892                            struct cifs_search_info *srch_inf)
4893 {
4894         struct smb2_query_directory_rsp *rsp;
4895         size_t info_buf_size;
4896         char *end_of_smb;
4897         int rc;
4898
4899         rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4900
4901         switch (srch_inf->info_level) {
4902         case SMB_FIND_FILE_DIRECTORY_INFO:
4903                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4904                 break;
4905         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4906                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4907                 break;
4908         case SMB_FIND_FILE_POSIX_INFO:
4909                 /* note that posix payload are variable size */
4910                 info_buf_size = sizeof(struct smb2_posix_info);
4911                 break;
4912         default:
4913                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4914                          srch_inf->info_level);
4915                 return -EINVAL;
4916         }
4917
4918         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4919                                le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4920                                info_buf_size);
4921         if (rc) {
4922                 cifs_tcon_dbg(VFS, "bad info payload");
4923                 return rc;
4924         }
4925
4926         srch_inf->unicode = true;
4927
4928         if (srch_inf->ntwrk_buf_start) {
4929                 if (srch_inf->smallBuf)
4930                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4931                 else
4932                         cifs_buf_release(srch_inf->ntwrk_buf_start);
4933         }
4934         srch_inf->ntwrk_buf_start = (char *)rsp;
4935         srch_inf->srch_entries_start = srch_inf->last_entry =
4936                 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4937         end_of_smb = rsp_iov->iov_len + (char *)rsp;
4938
4939         srch_inf->entries_in_buffer = num_entries(
4940                 srch_inf->info_level,
4941                 srch_inf->srch_entries_start,
4942                 end_of_smb,
4943                 &srch_inf->last_entry,
4944                 info_buf_size);
4945
4946         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4947         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4948                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4949                  srch_inf->srch_entries_start, srch_inf->last_entry);
4950         if (resp_buftype == CIFS_LARGE_BUFFER)
4951                 srch_inf->smallBuf = false;
4952         else if (resp_buftype == CIFS_SMALL_BUFFER)
4953                 srch_inf->smallBuf = true;
4954         else
4955                 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
4956
4957         return 0;
4958 }
4959
4960 int
4961 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
4962                      u64 persistent_fid, u64 volatile_fid, int index,
4963                      struct cifs_search_info *srch_inf)
4964 {
4965         struct smb_rqst rqst;
4966         struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
4967         struct smb2_query_directory_rsp *rsp = NULL;
4968         int resp_buftype = CIFS_NO_BUFFER;
4969         struct kvec rsp_iov;
4970         int rc = 0;
4971         struct cifs_ses *ses = tcon->ses;
4972         struct TCP_Server_Info *server = cifs_pick_channel(ses);
4973         int flags = 0;
4974
4975         if (!ses || !(ses->server))
4976                 return -EIO;
4977
4978         if (smb3_encryption_required(tcon))
4979                 flags |= CIFS_TRANSFORM_REQ;
4980
4981         memset(&rqst, 0, sizeof(struct smb_rqst));
4982         memset(&iov, 0, sizeof(iov));
4983         rqst.rq_iov = iov;
4984         rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
4985
4986         rc = SMB2_query_directory_init(xid, tcon, server,
4987                                        &rqst, persistent_fid,
4988                                        volatile_fid, index,
4989                                        srch_inf->info_level);
4990         if (rc)
4991                 goto qdir_exit;
4992
4993         rc = cifs_send_recv(xid, ses, server,
4994                             &rqst, &resp_buftype, flags, &rsp_iov);
4995         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
4996
4997         if (rc) {
4998                 if (rc == -ENODATA &&
4999                     rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5000                         trace_smb3_query_dir_done(xid, persistent_fid,
5001                                 tcon->tid, tcon->ses->Suid, index, 0);
5002                         srch_inf->endOfSearch = true;
5003                         rc = 0;
5004                 } else {
5005                         trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5006                                 tcon->ses->Suid, index, 0, rc);
5007                         cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5008                 }
5009                 goto qdir_exit;
5010         }
5011
5012         rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
5013                                         srch_inf);
5014         if (rc) {
5015                 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5016                         tcon->ses->Suid, index, 0, rc);
5017                 goto qdir_exit;
5018         }
5019         resp_buftype = CIFS_NO_BUFFER;
5020
5021         trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5022                         tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5023
5024 qdir_exit:
5025         SMB2_query_directory_free(&rqst);
5026         free_rsp_buf(resp_buftype, rsp);
5027         return rc;
5028 }
5029
5030 int
5031 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5032                    struct smb_rqst *rqst,
5033                    u64 persistent_fid, u64 volatile_fid, u32 pid,
5034                    u8 info_class, u8 info_type, u32 additional_info,
5035                    void **data, unsigned int *size)
5036 {
5037         struct smb2_set_info_req *req;
5038         struct kvec *iov = rqst->rq_iov;
5039         unsigned int i, total_len;
5040         int rc;
5041
5042         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5043                                  (void **) &req, &total_len);
5044         if (rc)
5045                 return rc;
5046
5047         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5048         req->InfoType = info_type;
5049         req->FileInfoClass = info_class;
5050         req->PersistentFileId = persistent_fid;
5051         req->VolatileFileId = volatile_fid;
5052         req->AdditionalInformation = cpu_to_le32(additional_info);
5053
5054         req->BufferOffset =
5055                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
5056         req->BufferLength = cpu_to_le32(*size);
5057
5058         memcpy(req->Buffer, *data, *size);
5059         total_len += *size;
5060
5061         iov[0].iov_base = (char *)req;
5062         /* 1 for Buffer */
5063         iov[0].iov_len = total_len - 1;
5064
5065         for (i = 1; i < rqst->rq_nvec; i++) {
5066                 le32_add_cpu(&req->BufferLength, size[i]);
5067                 iov[i].iov_base = (char *)data[i];
5068                 iov[i].iov_len = size[i];
5069         }
5070
5071         return 0;
5072 }
5073
5074 void
5075 SMB2_set_info_free(struct smb_rqst *rqst)
5076 {
5077         if (rqst && rqst->rq_iov)
5078                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5079 }
5080
5081 static int
5082 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5083                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5084                u8 info_type, u32 additional_info, unsigned int num,
5085                 void **data, unsigned int *size)
5086 {
5087         struct smb_rqst rqst;
5088         struct smb2_set_info_rsp *rsp = NULL;
5089         struct kvec *iov;
5090         struct kvec rsp_iov;
5091         int rc = 0;
5092         int resp_buftype;
5093         struct cifs_ses *ses = tcon->ses;
5094         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5095         int flags = 0;
5096
5097         if (!ses || !server)
5098                 return -EIO;
5099
5100         if (!num)
5101                 return -EINVAL;
5102
5103         if (smb3_encryption_required(tcon))
5104                 flags |= CIFS_TRANSFORM_REQ;
5105
5106         iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5107         if (!iov)
5108                 return -ENOMEM;
5109
5110         memset(&rqst, 0, sizeof(struct smb_rqst));
5111         rqst.rq_iov = iov;
5112         rqst.rq_nvec = num;
5113
5114         rc = SMB2_set_info_init(tcon, server,
5115                                 &rqst, persistent_fid, volatile_fid, pid,
5116                                 info_class, info_type, additional_info,
5117                                 data, size);
5118         if (rc) {
5119                 kfree(iov);
5120                 return rc;
5121         }
5122
5123
5124         rc = cifs_send_recv(xid, ses, server,
5125                             &rqst, &resp_buftype, flags,
5126                             &rsp_iov);
5127         SMB2_set_info_free(&rqst);
5128         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5129
5130         if (rc != 0) {
5131                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5132                 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5133                                 ses->Suid, info_class, (__u32)info_type, rc);
5134         }
5135
5136         free_rsp_buf(resp_buftype, rsp);
5137         kfree(iov);
5138         return rc;
5139 }
5140
5141 int
5142 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5143              u64 volatile_fid, u32 pid, __le64 *eof)
5144 {
5145         struct smb2_file_eof_info info;
5146         void *data;
5147         unsigned int size;
5148
5149         info.EndOfFile = *eof;
5150
5151         data = &info;
5152         size = sizeof(struct smb2_file_eof_info);
5153
5154         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5155                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5156                         0, 1, &data, &size);
5157 }
5158
5159 int
5160 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5161                 u64 persistent_fid, u64 volatile_fid,
5162                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
5163 {
5164         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5165                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5166                         1, (void **)&pnntsd, &pacllen);
5167 }
5168
5169 int
5170 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5171             u64 persistent_fid, u64 volatile_fid,
5172             struct smb2_file_full_ea_info *buf, int len)
5173 {
5174         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5175                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5176                 0, 1, (void **)&buf, &len);
5177 }
5178
5179 int
5180 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5181                   const u64 persistent_fid, const u64 volatile_fid,
5182                   __u8 oplock_level)
5183 {
5184         struct smb_rqst rqst;
5185         int rc;
5186         struct smb2_oplock_break *req = NULL;
5187         struct cifs_ses *ses = tcon->ses;
5188         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5189         int flags = CIFS_OBREAK_OP;
5190         unsigned int total_len;
5191         struct kvec iov[1];
5192         struct kvec rsp_iov;
5193         int resp_buf_type;
5194
5195         cifs_dbg(FYI, "SMB2_oplock_break\n");
5196         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5197                                  (void **) &req, &total_len);
5198         if (rc)
5199                 return rc;
5200
5201         if (smb3_encryption_required(tcon))
5202                 flags |= CIFS_TRANSFORM_REQ;
5203
5204         req->VolatileFid = volatile_fid;
5205         req->PersistentFid = persistent_fid;
5206         req->OplockLevel = oplock_level;
5207         req->hdr.CreditRequest = cpu_to_le16(1);
5208
5209         flags |= CIFS_NO_RSP_BUF;
5210
5211         iov[0].iov_base = (char *)req;
5212         iov[0].iov_len = total_len;
5213
5214         memset(&rqst, 0, sizeof(struct smb_rqst));
5215         rqst.rq_iov = iov;
5216         rqst.rq_nvec = 1;
5217
5218         rc = cifs_send_recv(xid, ses, server,
5219                             &rqst, &resp_buf_type, flags, &rsp_iov);
5220         cifs_small_buf_release(req);
5221
5222         if (rc) {
5223                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5224                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5225         }
5226
5227         return rc;
5228 }
5229
5230 void
5231 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5232                              struct kstatfs *kst)
5233 {
5234         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5235                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5236         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5237         kst->f_bfree  = kst->f_bavail =
5238                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5239         return;
5240 }
5241
5242 static void
5243 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5244                         struct kstatfs *kst)
5245 {
5246         kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5247         kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5248         kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5249         if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5250                 kst->f_bavail = kst->f_bfree;
5251         else
5252                 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5253         if (response_data->TotalFileNodes != cpu_to_le64(-1))
5254                 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5255         if (response_data->FreeFileNodes != cpu_to_le64(-1))
5256                 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5257
5258         return;
5259 }
5260
5261 static int
5262 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5263                    struct TCP_Server_Info *server,
5264                    int level, int outbuf_len, u64 persistent_fid,
5265                    u64 volatile_fid)
5266 {
5267         int rc;
5268         struct smb2_query_info_req *req;
5269         unsigned int total_len;
5270
5271         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5272
5273         if ((tcon->ses == NULL) || server == NULL)
5274                 return -EIO;
5275
5276         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5277                                  (void **) &req, &total_len);
5278         if (rc)
5279                 return rc;
5280
5281         req->InfoType = SMB2_O_INFO_FILESYSTEM;
5282         req->FileInfoClass = level;
5283         req->PersistentFileId = persistent_fid;
5284         req->VolatileFileId = volatile_fid;
5285         /* 1 for pad */
5286         req->InputBufferOffset =
5287                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
5288         req->OutputBufferLength = cpu_to_le32(
5289                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
5290
5291         iov->iov_base = (char *)req;
5292         iov->iov_len = total_len;
5293         return 0;
5294 }
5295
5296 int
5297 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5298               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5299 {
5300         struct smb_rqst rqst;
5301         struct smb2_query_info_rsp *rsp = NULL;
5302         struct kvec iov;
5303         struct kvec rsp_iov;
5304         int rc = 0;
5305         int resp_buftype;
5306         struct cifs_ses *ses = tcon->ses;
5307         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5308         FILE_SYSTEM_POSIX_INFO *info = NULL;
5309         int flags = 0;
5310
5311         rc = build_qfs_info_req(&iov, tcon, server,
5312                                 FS_POSIX_INFORMATION,
5313                                 sizeof(FILE_SYSTEM_POSIX_INFO),
5314                                 persistent_fid, volatile_fid);
5315         if (rc)
5316                 return rc;
5317
5318         if (smb3_encryption_required(tcon))
5319                 flags |= CIFS_TRANSFORM_REQ;
5320
5321         memset(&rqst, 0, sizeof(struct smb_rqst));
5322         rqst.rq_iov = &iov;
5323         rqst.rq_nvec = 1;
5324
5325         rc = cifs_send_recv(xid, ses, server,
5326                             &rqst, &resp_buftype, flags, &rsp_iov);
5327         cifs_small_buf_release(iov.iov_base);
5328         if (rc) {
5329                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5330                 goto posix_qfsinf_exit;
5331         }
5332         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5333
5334         info = (FILE_SYSTEM_POSIX_INFO *)(
5335                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5336         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5337                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5338                                sizeof(FILE_SYSTEM_POSIX_INFO));
5339         if (!rc)
5340                 copy_posix_fs_info_to_kstatfs(info, fsdata);
5341
5342 posix_qfsinf_exit:
5343         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5344         return rc;
5345 }
5346
5347 int
5348 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5349               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5350 {
5351         struct smb_rqst rqst;
5352         struct smb2_query_info_rsp *rsp = NULL;
5353         struct kvec iov;
5354         struct kvec rsp_iov;
5355         int rc = 0;
5356         int resp_buftype;
5357         struct cifs_ses *ses = tcon->ses;
5358         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5359         struct smb2_fs_full_size_info *info = NULL;
5360         int flags = 0;
5361
5362         rc = build_qfs_info_req(&iov, tcon, server,
5363                                 FS_FULL_SIZE_INFORMATION,
5364                                 sizeof(struct smb2_fs_full_size_info),
5365                                 persistent_fid, volatile_fid);
5366         if (rc)
5367                 return rc;
5368
5369         if (smb3_encryption_required(tcon))
5370                 flags |= CIFS_TRANSFORM_REQ;
5371
5372         memset(&rqst, 0, sizeof(struct smb_rqst));
5373         rqst.rq_iov = &iov;
5374         rqst.rq_nvec = 1;
5375
5376         rc = cifs_send_recv(xid, ses, server,
5377                             &rqst, &resp_buftype, flags, &rsp_iov);
5378         cifs_small_buf_release(iov.iov_base);
5379         if (rc) {
5380                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5381                 goto qfsinf_exit;
5382         }
5383         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5384
5385         info = (struct smb2_fs_full_size_info *)(
5386                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5387         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5388                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5389                                sizeof(struct smb2_fs_full_size_info));
5390         if (!rc)
5391                 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5392
5393 qfsinf_exit:
5394         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5395         return rc;
5396 }
5397
5398 int
5399 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5400               u64 persistent_fid, u64 volatile_fid, int level)
5401 {
5402         struct smb_rqst rqst;
5403         struct smb2_query_info_rsp *rsp = NULL;
5404         struct kvec iov;
5405         struct kvec rsp_iov;
5406         int rc = 0;
5407         int resp_buftype, max_len, min_len;
5408         struct cifs_ses *ses = tcon->ses;
5409         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5410         unsigned int rsp_len, offset;
5411         int flags = 0;
5412
5413         if (level == FS_DEVICE_INFORMATION) {
5414                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5415                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5416         } else if (level == FS_ATTRIBUTE_INFORMATION) {
5417                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5418                 min_len = MIN_FS_ATTR_INFO_SIZE;
5419         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5420                 max_len = sizeof(struct smb3_fs_ss_info);
5421                 min_len = sizeof(struct smb3_fs_ss_info);
5422         } else if (level == FS_VOLUME_INFORMATION) {
5423                 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5424                 min_len = sizeof(struct smb3_fs_vol_info);
5425         } else {
5426                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5427                 return -EINVAL;
5428         }
5429
5430         rc = build_qfs_info_req(&iov, tcon, server,
5431                                 level, max_len,
5432                                 persistent_fid, volatile_fid);
5433         if (rc)
5434                 return rc;
5435
5436         if (smb3_encryption_required(tcon))
5437                 flags |= CIFS_TRANSFORM_REQ;
5438
5439         memset(&rqst, 0, sizeof(struct smb_rqst));
5440         rqst.rq_iov = &iov;
5441         rqst.rq_nvec = 1;
5442
5443         rc = cifs_send_recv(xid, ses, server,
5444                             &rqst, &resp_buftype, flags, &rsp_iov);
5445         cifs_small_buf_release(iov.iov_base);
5446         if (rc) {
5447                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5448                 goto qfsattr_exit;
5449         }
5450         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5451
5452         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5453         offset = le16_to_cpu(rsp->OutputBufferOffset);
5454         rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5455         if (rc)
5456                 goto qfsattr_exit;
5457
5458         if (level == FS_ATTRIBUTE_INFORMATION)
5459                 memcpy(&tcon->fsAttrInfo, offset
5460                         + (char *)rsp, min_t(unsigned int,
5461                         rsp_len, max_len));
5462         else if (level == FS_DEVICE_INFORMATION)
5463                 memcpy(&tcon->fsDevInfo, offset
5464                         + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5465         else if (level == FS_SECTOR_SIZE_INFORMATION) {
5466                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5467                         (offset + (char *)rsp);
5468                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5469                 tcon->perf_sector_size =
5470                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5471         } else if (level == FS_VOLUME_INFORMATION) {
5472                 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5473                         (offset + (char *)rsp);
5474                 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5475                 tcon->vol_create_time = vol_info->VolumeCreationTime;
5476         }
5477
5478 qfsattr_exit:
5479         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5480         return rc;
5481 }
5482
5483 int
5484 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5485            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5486            const __u32 num_lock, struct smb2_lock_element *buf)
5487 {
5488         struct smb_rqst rqst;
5489         int rc = 0;
5490         struct smb2_lock_req *req = NULL;
5491         struct kvec iov[2];
5492         struct kvec rsp_iov;
5493         int resp_buf_type;
5494         unsigned int count;
5495         int flags = CIFS_NO_RSP_BUF;
5496         unsigned int total_len;
5497         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5498
5499         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5500
5501         rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5502                                  (void **) &req, &total_len);
5503         if (rc)
5504                 return rc;
5505
5506         if (smb3_encryption_required(tcon))
5507                 flags |= CIFS_TRANSFORM_REQ;
5508
5509         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5510         req->LockCount = cpu_to_le16(num_lock);
5511
5512         req->PersistentFileId = persist_fid;
5513         req->VolatileFileId = volatile_fid;
5514
5515         count = num_lock * sizeof(struct smb2_lock_element);
5516
5517         iov[0].iov_base = (char *)req;
5518         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5519         iov[1].iov_base = (char *)buf;
5520         iov[1].iov_len = count;
5521
5522         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5523
5524         memset(&rqst, 0, sizeof(struct smb_rqst));
5525         rqst.rq_iov = iov;
5526         rqst.rq_nvec = 2;
5527
5528         rc = cifs_send_recv(xid, tcon->ses, server,
5529                             &rqst, &resp_buf_type, flags,
5530                             &rsp_iov);
5531         cifs_small_buf_release(req);
5532         if (rc) {
5533                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5534                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5535                 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5536                                     tcon->ses->Suid, rc);
5537         }
5538
5539         return rc;
5540 }
5541
5542 int
5543 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5544           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5545           const __u64 length, const __u64 offset, const __u32 lock_flags,
5546           const bool wait)
5547 {
5548         struct smb2_lock_element lock;
5549
5550         lock.Offset = cpu_to_le64(offset);
5551         lock.Length = cpu_to_le64(length);
5552         lock.Flags = cpu_to_le32(lock_flags);
5553         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5554                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5555
5556         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5557 }
5558
5559 int
5560 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5561                  __u8 *lease_key, const __le32 lease_state)
5562 {
5563         struct smb_rqst rqst;
5564         int rc;
5565         struct smb2_lease_ack *req = NULL;
5566         struct cifs_ses *ses = tcon->ses;
5567         int flags = CIFS_OBREAK_OP;
5568         unsigned int total_len;
5569         struct kvec iov[1];
5570         struct kvec rsp_iov;
5571         int resp_buf_type;
5572         __u64 *please_key_high;
5573         __u64 *please_key_low;
5574         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5575
5576         cifs_dbg(FYI, "SMB2_lease_break\n");
5577         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5578                                  (void **) &req, &total_len);
5579         if (rc)
5580                 return rc;
5581
5582         if (smb3_encryption_required(tcon))
5583                 flags |= CIFS_TRANSFORM_REQ;
5584
5585         req->hdr.CreditRequest = cpu_to_le16(1);
5586         req->StructureSize = cpu_to_le16(36);
5587         total_len += 12;
5588
5589         memcpy(req->LeaseKey, lease_key, 16);
5590         req->LeaseState = lease_state;
5591
5592         flags |= CIFS_NO_RSP_BUF;
5593
5594         iov[0].iov_base = (char *)req;
5595         iov[0].iov_len = total_len;
5596
5597         memset(&rqst, 0, sizeof(struct smb_rqst));
5598         rqst.rq_iov = iov;
5599         rqst.rq_nvec = 1;
5600
5601         rc = cifs_send_recv(xid, ses, server,
5602                             &rqst, &resp_buf_type, flags, &rsp_iov);
5603         cifs_small_buf_release(req);
5604
5605         please_key_low = (__u64 *)lease_key;
5606         please_key_high = (__u64 *)(lease_key+8);
5607         if (rc) {
5608                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5609                 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5610                         ses->Suid, *please_key_low, *please_key_high, rc);
5611                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5612         } else
5613                 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5614                         ses->Suid, *please_key_low, *please_key_high);
5615
5616         return rc;
5617 }