root/fs/cifs/smb2pdu.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. smb3_encryption_required
  2. smb2_hdr_assemble
  3. __smb2_reconnect
  4. __smb2_reconnect
  5. smb2_reconnect
  6. fill_small_buf
  7. __smb2_plain_req_init
  8. smb2_plain_req_init
  9. smb2_ioctl_req_init
  10. build_preauth_ctxt
  11. build_compression_ctxt
  12. build_encrypt_ctxt
  13. build_netname_ctxt
  14. build_posix_ctxt
  15. assemble_neg_contexts
  16. decode_preauth_context
  17. decode_compress_ctx
  18. decode_encrypt_ctx
  19. smb311_decode_neg_context
  20. create_posix_buf
  21. add_posix_context
  22. SMB2_negotiate
  23. smb3_validate_negotiate
  24. smb2_select_sectype
  25. SMB2_sess_alloc_buffer
  26. SMB2_sess_free_buffer
  27. SMB2_sess_sendreceive
  28. SMB2_sess_establish_session
  29. SMB2_auth_kerberos
  30. SMB2_auth_kerberos
  31. SMB2_sess_auth_rawntlmssp_negotiate
  32. SMB2_sess_auth_rawntlmssp_authenticate
  33. SMB2_select_sec
  34. SMB2_sess_setup
  35. SMB2_logoff
  36. cifs_stats_fail_inc
  37. init_copy_chunk_defaults
  38. SMB2_tcon
  39. SMB2_tdis
  40. create_durable_buf
  41. create_reconnect_durable_buf
  42. parse_query_id_ctxt
  43. smb2_parse_contexts
  44. add_lease_context
  45. create_durable_v2_buf
  46. create_reconnect_durable_v2_buf
  47. add_durable_v2_context
  48. add_durable_reconnect_v2_context
  49. add_durable_context
  50. create_twarp_buf
  51. add_twarp_context
  52. create_query_id_buf
  53. add_query_id_context
  54. alloc_path_with_tree_prefix
  55. smb311_posix_mkdir
  56. SMB2_open_init
  57. SMB2_open_free
  58. SMB2_open
  59. SMB2_ioctl_init
  60. SMB2_ioctl_free
  61. SMB2_ioctl
  62. SMB2_set_compression
  63. SMB2_close_init
  64. SMB2_close_free
  65. SMB2_close_flags
  66. SMB2_close
  67. smb2_validate_iov
  68. smb2_validate_and_copy_iov
  69. SMB2_query_info_init
  70. SMB2_query_info_free
  71. query_info
  72. SMB2_query_info
  73. SMB2_query_acl
  74. SMB2_get_srv_num
  75. SMB2_notify_init
  76. SMB2_change_notify
  77. smb2_echo_callback
  78. smb2_reconnect_server
  79. SMB2_echo
  80. SMB2_flush_free
  81. SMB2_flush_init
  82. SMB2_flush
  83. smb2_new_read_req
  84. smb2_readv_callback
  85. smb2_async_readv
  86. SMB2_read
  87. smb2_writev_callback
  88. smb2_async_writev
  89. SMB2_write
  90. num_entries
  91. SMB2_query_directory
  92. SMB2_set_info_init
  93. SMB2_set_info_free
  94. send_set_info
  95. SMB2_set_eof
  96. SMB2_set_acl
  97. SMB2_set_ea
  98. SMB2_oplock_break
  99. smb2_copy_fs_info_to_kstatfs
  100. copy_posix_fs_info_to_kstatfs
  101. build_qfs_info_req
  102. SMB311_posix_qfs_info
  103. SMB2_QFS_info
  104. SMB2_QFS_attr
  105. smb2_lockv
  106. SMB2_lock
  107. SMB2_lease_break

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

/* [<][>][^][v][top][bottom][index][help] */