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

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

Version: ~ [ linux-5.6 ] ~ [ linux-5.5.13 ] ~ [ linux-5.4.28 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.113 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.174 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.217 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.217 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.82 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

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

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

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

osdn.jp