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