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