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