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