~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/cifs/smb2pdu.c

Version: ~ [ linux-5.8-rc5 ] ~ [ linux-5.7.8 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.51 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.132 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.188 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.230 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.230 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp