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