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