OSDN Git Service

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