io_uring: ensure finish_wait() is always called in __io_uring_task_cancel()
[linux/fpc-iii.git] / fs / cifs / smb2pdu.c
blob067eb44c7baa863c1e7ccd2c2f599be0b067f320
1 /*
2 * fs/cifs/smb2pdu.c
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
9 * Contains the routines for constructing the SMB2 PDUs themselves
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.
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.
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
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 */
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
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.
61 * Note that commands are defined in smb2pdu.h in le16 but the array below is
62 * indexed by command in host byte order.
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 */
86 int smb3_encryption_required(const struct cifs_tcon *tcon)
88 if (!tcon || !tcon->ses)
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;
99 static void
100 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
101 const struct cifs_tcon *tcon,
102 struct TCP_Server_Info *server)
104 shdr->ProtocolId = SMB2_PROTO_NUMBER;
105 shdr->StructureSize = cpu_to_le16(64);
106 shdr->Command = smb2_cmd;
107 if (server) {
108 spin_lock(&server->req_lock);
109 /* Request up to 10 credits but don't go over the limit. */
110 if (server->credits >= server->max_credits)
111 shdr->CreditRequest = cpu_to_le16(0);
112 else
113 shdr->CreditRequest = cpu_to_le16(
114 min_t(int, server->max_credits -
115 server->credits, 10));
116 spin_unlock(&server->req_lock);
117 } else {
118 shdr->CreditRequest = cpu_to_le16(2);
120 shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
122 if (!tcon)
123 goto out;
125 /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
126 /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
127 if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
128 shdr->CreditCharge = cpu_to_le16(1);
129 /* else CreditCharge MBZ */
131 shdr->TreeId = tcon->tid;
132 /* Uid is not converted */
133 if (tcon->ses)
134 shdr->SessionId = tcon->ses->Suid;
137 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
138 * to pass the path on the Open SMB prefixed by \\server\share.
139 * Not sure when we would need to do the augmented path (if ever) and
140 * setting this flag breaks the SMB2 open operation since it is
141 * illegal to send an empty path name (without \\server\share prefix)
142 * when the DFS flag is set in the SMB open header. We could
143 * consider setting the flag on all operations other than open
144 * but it is safer to net set it for now.
146 /* if (tcon->share_flags & SHI1005_FLAGS_DFS)
147 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
149 if (server && server->sign && !smb3_encryption_required(tcon))
150 shdr->Flags |= SMB2_FLAGS_SIGNED;
151 out:
152 return;
155 static int
156 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
157 struct TCP_Server_Info *server)
159 int rc;
160 struct nls_table *nls_codepage;
161 struct cifs_ses *ses;
162 int retries;
165 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
166 * check for tcp and smb session status done differently
167 * for those three - in the calling routine.
169 if (tcon == NULL)
170 return 0;
172 if (smb2_command == SMB2_TREE_CONNECT)
173 return 0;
175 if (tcon->tidStatus == CifsExiting) {
177 * only tree disconnect, open, and write,
178 * (and ulogoff which does not have tcon)
179 * are allowed as we start force umount.
181 if ((smb2_command != SMB2_WRITE) &&
182 (smb2_command != SMB2_CREATE) &&
183 (smb2_command != SMB2_TREE_DISCONNECT)) {
184 cifs_dbg(FYI, "can not send cmd %d while umounting\n",
185 smb2_command);
186 return -ENODEV;
189 if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
190 (!tcon->ses->server) || !server)
191 return -EIO;
193 ses = tcon->ses;
194 retries = server->nr_targets;
197 * Give demultiplex thread up to 10 seconds to each target available for
198 * reconnect -- should be greater than cifs socket timeout which is 7
199 * seconds.
201 while (server->tcpStatus == CifsNeedReconnect) {
203 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
204 * here since they are implicitly done when session drops.
206 switch (smb2_command) {
208 * BB Should we keep oplock break and add flush to exceptions?
210 case SMB2_TREE_DISCONNECT:
211 case SMB2_CANCEL:
212 case SMB2_CLOSE:
213 case SMB2_OPLOCK_BREAK:
214 return -EAGAIN;
217 rc = wait_event_interruptible_timeout(server->response_q,
218 (server->tcpStatus != CifsNeedReconnect),
219 10 * HZ);
220 if (rc < 0) {
221 cifs_dbg(FYI, "%s: aborting reconnect due to a received signal by the process\n",
222 __func__);
223 return -ERESTARTSYS;
226 /* are we still trying to reconnect? */
227 if (server->tcpStatus != CifsNeedReconnect)
228 break;
230 if (retries && --retries)
231 continue;
234 * on "soft" mounts we wait once. Hard mounts keep
235 * retrying until process is killed or server comes
236 * back on-line
238 if (!tcon->retry) {
239 cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
240 return -EHOSTDOWN;
242 retries = server->nr_targets;
245 if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
246 return 0;
248 nls_codepage = load_nls_default();
251 * need to prevent multiple threads trying to simultaneously reconnect
252 * the same SMB session
254 mutex_lock(&tcon->ses->session_mutex);
257 * Recheck after acquire mutex. If another thread is negotiating
258 * and the server never sends an answer the socket will be closed
259 * and tcpStatus set to reconnect.
261 if (server->tcpStatus == CifsNeedReconnect) {
262 rc = -EHOSTDOWN;
263 mutex_unlock(&tcon->ses->session_mutex);
264 goto out;
268 * If we are reconnecting an extra channel, bind
270 if (server->is_channel) {
271 ses->binding = true;
272 ses->binding_chan = cifs_ses_find_chan(ses, server);
275 rc = cifs_negotiate_protocol(0, tcon->ses);
276 if (!rc && tcon->ses->need_reconnect) {
277 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
278 if ((rc == -EACCES) && !tcon->retry) {
279 rc = -EHOSTDOWN;
280 ses->binding = false;
281 ses->binding_chan = NULL;
282 mutex_unlock(&tcon->ses->session_mutex);
283 goto failed;
287 * End of channel binding
289 ses->binding = false;
290 ses->binding_chan = NULL;
292 if (rc || !tcon->need_reconnect) {
293 mutex_unlock(&tcon->ses->session_mutex);
294 goto out;
297 cifs_mark_open_files_invalid(tcon);
298 if (tcon->use_persistent)
299 tcon->need_reopen_files = true;
301 rc = cifs_tree_connect(0, tcon, nls_codepage);
302 mutex_unlock(&tcon->ses->session_mutex);
304 cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
305 if (rc) {
306 /* If sess reconnected but tcon didn't, something strange ... */
307 pr_warn_once("reconnect tcon failed rc = %d\n", rc);
308 goto out;
311 if (smb2_command != SMB2_INTERNAL_CMD)
312 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
314 atomic_inc(&tconInfoReconnectCount);
315 out:
317 * Check if handle based operation so we know whether we can continue
318 * or not without returning to caller to reset file handle.
321 * BB Is flush done by server on drop of tcp session? Should we special
322 * case it and skip above?
324 switch (smb2_command) {
325 case SMB2_FLUSH:
326 case SMB2_READ:
327 case SMB2_WRITE:
328 case SMB2_LOCK:
329 case SMB2_IOCTL:
330 case SMB2_QUERY_DIRECTORY:
331 case SMB2_CHANGE_NOTIFY:
332 case SMB2_QUERY_INFO:
333 case SMB2_SET_INFO:
334 rc = -EAGAIN;
336 failed:
337 unload_nls(nls_codepage);
338 return rc;
341 static void
342 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
343 struct TCP_Server_Info *server,
344 void *buf,
345 unsigned int *total_len)
347 struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
348 /* lookup word count ie StructureSize from table */
349 __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
352 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
353 * largest operations (Create)
355 memset(buf, 0, 256);
357 smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon, server);
358 spdu->StructureSize2 = cpu_to_le16(parmsize);
360 *total_len = parmsize + sizeof(struct smb2_sync_hdr);
364 * Allocate and return pointer to an SMB request hdr, and set basic
365 * SMB information in the SMB header. If the return code is zero, this
366 * function must have filled in request_buf pointer.
368 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
369 struct TCP_Server_Info *server,
370 void **request_buf, unsigned int *total_len)
372 /* BB eventually switch this to SMB2 specific small buf size */
373 if (smb2_command == SMB2_SET_INFO)
374 *request_buf = cifs_buf_get();
375 else
376 *request_buf = cifs_small_buf_get();
377 if (*request_buf == NULL) {
378 /* BB should we add a retry in here if not a writepage? */
379 return -ENOMEM;
382 fill_small_buf(smb2_command, tcon, server,
383 (struct smb2_sync_hdr *)(*request_buf),
384 total_len);
386 if (tcon != NULL) {
387 uint16_t com_code = le16_to_cpu(smb2_command);
388 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
389 cifs_stats_inc(&tcon->num_smbs_sent);
392 return 0;
395 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
396 struct TCP_Server_Info *server,
397 void **request_buf, unsigned int *total_len)
399 int rc;
401 rc = smb2_reconnect(smb2_command, tcon, server);
402 if (rc)
403 return rc;
405 return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
406 total_len);
409 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
410 struct TCP_Server_Info *server,
411 void **request_buf, unsigned int *total_len)
413 /* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
414 if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
415 return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
416 request_buf, total_len);
418 return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
419 request_buf, total_len);
422 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
424 static void
425 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
427 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
428 pneg_ctxt->DataLength = cpu_to_le16(38);
429 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
430 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_LINUX_CLIENT_SALT_SIZE);
431 get_random_bytes(pneg_ctxt->Salt, SMB311_LINUX_CLIENT_SALT_SIZE);
432 pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
435 static void
436 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
438 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
439 pneg_ctxt->DataLength =
440 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
441 - sizeof(struct smb2_neg_context));
442 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
443 pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
444 pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
445 pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
448 static void
449 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
451 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
452 if (require_gcm_256) {
453 pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
454 pneg_ctxt->CipherCount = cpu_to_le16(1);
455 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
456 } else if (enable_gcm_256) {
457 pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
458 pneg_ctxt->CipherCount = cpu_to_le16(3);
459 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
460 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
461 pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
462 } else {
463 pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
464 pneg_ctxt->CipherCount = cpu_to_le16(2);
465 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
466 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
470 static unsigned int
471 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
473 struct nls_table *cp = load_nls_default();
475 pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
477 /* copy up to max of first 100 bytes of server name to NetName field */
478 pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
479 /* context size is DataLength + minimal smb2_neg_context */
480 return DIV_ROUND_UP(le16_to_cpu(pneg_ctxt->DataLength) +
481 sizeof(struct smb2_neg_context), 8) * 8;
484 static void
485 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
487 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
488 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
489 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
490 pneg_ctxt->Name[0] = 0x93;
491 pneg_ctxt->Name[1] = 0xAD;
492 pneg_ctxt->Name[2] = 0x25;
493 pneg_ctxt->Name[3] = 0x50;
494 pneg_ctxt->Name[4] = 0x9C;
495 pneg_ctxt->Name[5] = 0xB4;
496 pneg_ctxt->Name[6] = 0x11;
497 pneg_ctxt->Name[7] = 0xE7;
498 pneg_ctxt->Name[8] = 0xB4;
499 pneg_ctxt->Name[9] = 0x23;
500 pneg_ctxt->Name[10] = 0x83;
501 pneg_ctxt->Name[11] = 0xDE;
502 pneg_ctxt->Name[12] = 0x96;
503 pneg_ctxt->Name[13] = 0x8B;
504 pneg_ctxt->Name[14] = 0xCD;
505 pneg_ctxt->Name[15] = 0x7C;
508 static void
509 assemble_neg_contexts(struct smb2_negotiate_req *req,
510 struct TCP_Server_Info *server, unsigned int *total_len)
512 char *pneg_ctxt;
513 unsigned int ctxt_len;
515 if (*total_len > 200) {
516 /* In case length corrupted don't want to overrun smb buffer */
517 cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
518 return;
522 * round up total_len of fixed part of SMB3 negotiate request to 8
523 * byte boundary before adding negotiate contexts
525 *total_len = roundup(*total_len, 8);
527 pneg_ctxt = (*total_len) + (char *)req;
528 req->NegotiateContextOffset = cpu_to_le32(*total_len);
530 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
531 ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_preauth_neg_context), 8) * 8;
532 *total_len += ctxt_len;
533 pneg_ctxt += ctxt_len;
535 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
536 ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_encryption_neg_context), 8) * 8;
537 *total_len += ctxt_len;
538 pneg_ctxt += ctxt_len;
540 if (server->compress_algorithm) {
541 build_compression_ctxt((struct smb2_compression_capabilities_context *)
542 pneg_ctxt);
543 ctxt_len = DIV_ROUND_UP(
544 sizeof(struct smb2_compression_capabilities_context),
545 8) * 8;
546 *total_len += ctxt_len;
547 pneg_ctxt += ctxt_len;
548 req->NegotiateContextCount = cpu_to_le16(5);
549 } else
550 req->NegotiateContextCount = cpu_to_le16(4);
552 ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
553 server->hostname);
554 *total_len += ctxt_len;
555 pneg_ctxt += ctxt_len;
557 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
558 *total_len += sizeof(struct smb2_posix_neg_context);
561 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
563 unsigned int len = le16_to_cpu(ctxt->DataLength);
565 /* If invalid preauth context warn but use what we requested, SHA-512 */
566 if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
567 pr_warn_once("server sent bad preauth context\n");
568 return;
569 } else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
570 pr_warn_once("server sent invalid SaltLength\n");
571 return;
573 if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
574 pr_warn_once("Invalid SMB3 hash algorithm count\n");
575 if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
576 pr_warn_once("unknown SMB3 hash algorithm\n");
579 static void decode_compress_ctx(struct TCP_Server_Info *server,
580 struct smb2_compression_capabilities_context *ctxt)
582 unsigned int len = le16_to_cpu(ctxt->DataLength);
584 /* sizeof compress context is a one element compression capbility struct */
585 if (len < 10) {
586 pr_warn_once("server sent bad compression cntxt\n");
587 return;
589 if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
590 pr_warn_once("Invalid SMB3 compress algorithm count\n");
591 return;
593 if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
594 pr_warn_once("unknown compression algorithm\n");
595 return;
597 server->compress_algorithm = ctxt->CompressionAlgorithms[0];
600 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
601 struct smb2_encryption_neg_context *ctxt)
603 unsigned int len = le16_to_cpu(ctxt->DataLength);
605 cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
606 if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
607 pr_warn_once("server sent bad crypto ctxt len\n");
608 return -EINVAL;
611 if (le16_to_cpu(ctxt->CipherCount) != 1) {
612 pr_warn_once("Invalid SMB3.11 cipher count\n");
613 return -EINVAL;
615 cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
616 if (require_gcm_256) {
617 if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
618 cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
619 return -EOPNOTSUPP;
621 } else if (ctxt->Ciphers[0] == 0) {
623 * e.g. if server only supported AES256_CCM (very unlikely)
624 * or server supported no encryption types or had all disabled.
625 * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
626 * in which mount requested encryption ("seal") checks later
627 * on during tree connection will return proper rc, but if
628 * seal not requested by client, since server is allowed to
629 * return 0 to indicate no supported cipher, we can't fail here
631 server->cipher_type = 0;
632 server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
633 pr_warn_once("Server does not support requested encryption types\n");
634 return 0;
635 } else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
636 (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
637 (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
638 /* server returned a cipher we didn't ask for */
639 pr_warn_once("Invalid SMB3.11 cipher returned\n");
640 return -EINVAL;
642 server->cipher_type = ctxt->Ciphers[0];
643 server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
644 return 0;
647 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
648 struct TCP_Server_Info *server,
649 unsigned int len_of_smb)
651 struct smb2_neg_context *pctx;
652 unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
653 unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
654 unsigned int len_of_ctxts, i;
655 int rc = 0;
657 cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
658 if (len_of_smb <= offset) {
659 cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
660 return -EINVAL;
663 len_of_ctxts = len_of_smb - offset;
665 for (i = 0; i < ctxt_cnt; i++) {
666 int clen;
667 /* check that offset is not beyond end of SMB */
668 if (len_of_ctxts == 0)
669 break;
671 if (len_of_ctxts < sizeof(struct smb2_neg_context))
672 break;
674 pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
675 clen = le16_to_cpu(pctx->DataLength);
676 if (clen > len_of_ctxts)
677 break;
679 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
680 decode_preauth_context(
681 (struct smb2_preauth_neg_context *)pctx);
682 else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
683 rc = decode_encrypt_ctx(server,
684 (struct smb2_encryption_neg_context *)pctx);
685 else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
686 decode_compress_ctx(server,
687 (struct smb2_compression_capabilities_context *)pctx);
688 else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
689 server->posix_ext_supported = true;
690 else
691 cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
692 le16_to_cpu(pctx->ContextType));
694 if (rc)
695 break;
696 /* offsets must be 8 byte aligned */
697 clen = (clen + 7) & ~0x7;
698 offset += clen + sizeof(struct smb2_neg_context);
699 len_of_ctxts -= clen;
701 return rc;
704 static struct create_posix *
705 create_posix_buf(umode_t mode)
707 struct create_posix *buf;
709 buf = kzalloc(sizeof(struct create_posix),
710 GFP_KERNEL);
711 if (!buf)
712 return NULL;
714 buf->ccontext.DataOffset =
715 cpu_to_le16(offsetof(struct create_posix, Mode));
716 buf->ccontext.DataLength = cpu_to_le32(4);
717 buf->ccontext.NameOffset =
718 cpu_to_le16(offsetof(struct create_posix, Name));
719 buf->ccontext.NameLength = cpu_to_le16(16);
721 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
722 buf->Name[0] = 0x93;
723 buf->Name[1] = 0xAD;
724 buf->Name[2] = 0x25;
725 buf->Name[3] = 0x50;
726 buf->Name[4] = 0x9C;
727 buf->Name[5] = 0xB4;
728 buf->Name[6] = 0x11;
729 buf->Name[7] = 0xE7;
730 buf->Name[8] = 0xB4;
731 buf->Name[9] = 0x23;
732 buf->Name[10] = 0x83;
733 buf->Name[11] = 0xDE;
734 buf->Name[12] = 0x96;
735 buf->Name[13] = 0x8B;
736 buf->Name[14] = 0xCD;
737 buf->Name[15] = 0x7C;
738 buf->Mode = cpu_to_le32(mode);
739 cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
740 return buf;
743 static int
744 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
746 struct smb2_create_req *req = iov[0].iov_base;
747 unsigned int num = *num_iovec;
749 iov[num].iov_base = create_posix_buf(mode);
750 if (mode == ACL_NO_MODE)
751 cifs_dbg(FYI, "Invalid mode\n");
752 if (iov[num].iov_base == NULL)
753 return -ENOMEM;
754 iov[num].iov_len = sizeof(struct create_posix);
755 if (!req->CreateContextsOffset)
756 req->CreateContextsOffset = cpu_to_le32(
757 sizeof(struct smb2_create_req) +
758 iov[num - 1].iov_len);
759 le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix));
760 *num_iovec = num + 1;
761 return 0;
767 * SMB2 Worker functions follow:
769 * The general structure of the worker functions is:
770 * 1) Call smb2_init (assembles SMB2 header)
771 * 2) Initialize SMB2 command specific fields in fixed length area of SMB
772 * 3) Call smb_sendrcv2 (sends request on socket and waits for response)
773 * 4) Decode SMB2 command specific fields in the fixed length area
774 * 5) Decode variable length data area (if any for this SMB2 command type)
775 * 6) Call free smb buffer
776 * 7) return
781 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
783 struct smb_rqst rqst;
784 struct smb2_negotiate_req *req;
785 struct smb2_negotiate_rsp *rsp;
786 struct kvec iov[1];
787 struct kvec rsp_iov;
788 int rc = 0;
789 int resp_buftype;
790 struct TCP_Server_Info *server = cifs_ses_server(ses);
791 int blob_offset, blob_length;
792 char *security_blob;
793 int flags = CIFS_NEG_OP;
794 unsigned int total_len;
796 cifs_dbg(FYI, "Negotiate protocol\n");
798 if (!server) {
799 WARN(1, "%s: server is NULL!\n", __func__);
800 return -EIO;
803 rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
804 (void **) &req, &total_len);
805 if (rc)
806 return rc;
808 req->sync_hdr.SessionId = 0;
810 memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
811 memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
813 if (strcmp(server->vals->version_string,
814 SMB3ANY_VERSION_STRING) == 0) {
815 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
816 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
817 req->DialectCount = cpu_to_le16(2);
818 total_len += 4;
819 } else if (strcmp(server->vals->version_string,
820 SMBDEFAULT_VERSION_STRING) == 0) {
821 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
822 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
823 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
824 req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
825 req->DialectCount = cpu_to_le16(4);
826 total_len += 8;
827 } else {
828 /* otherwise send specific dialect */
829 req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
830 req->DialectCount = cpu_to_le16(1);
831 total_len += 2;
834 /* only one of SMB2 signing flags may be set in SMB2 request */
835 if (ses->sign)
836 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
837 else if (global_secflags & CIFSSEC_MAY_SIGN)
838 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
839 else
840 req->SecurityMode = 0;
842 req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
844 /* ClientGUID must be zero for SMB2.02 dialect */
845 if (server->vals->protocol_id == SMB20_PROT_ID)
846 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
847 else {
848 memcpy(req->ClientGUID, server->client_guid,
849 SMB2_CLIENT_GUID_SIZE);
850 if ((server->vals->protocol_id == SMB311_PROT_ID) ||
851 (strcmp(server->vals->version_string,
852 SMBDEFAULT_VERSION_STRING) == 0))
853 assemble_neg_contexts(req, server, &total_len);
855 iov[0].iov_base = (char *)req;
856 iov[0].iov_len = total_len;
858 memset(&rqst, 0, sizeof(struct smb_rqst));
859 rqst.rq_iov = iov;
860 rqst.rq_nvec = 1;
862 rc = cifs_send_recv(xid, ses, server,
863 &rqst, &resp_buftype, flags, &rsp_iov);
864 cifs_small_buf_release(req);
865 rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
867 * No tcon so can't do
868 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
870 if (rc == -EOPNOTSUPP) {
871 cifs_server_dbg(VFS, "Dialect not supported by server. Consider specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
872 goto neg_exit;
873 } else if (rc != 0)
874 goto neg_exit;
876 if (strcmp(server->vals->version_string,
877 SMB3ANY_VERSION_STRING) == 0) {
878 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
879 cifs_server_dbg(VFS,
880 "SMB2 dialect returned but not requested\n");
881 return -EIO;
882 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
883 cifs_server_dbg(VFS,
884 "SMB2.1 dialect returned but not requested\n");
885 return -EIO;
887 } else if (strcmp(server->vals->version_string,
888 SMBDEFAULT_VERSION_STRING) == 0) {
889 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
890 cifs_server_dbg(VFS,
891 "SMB2 dialect returned but not requested\n");
892 return -EIO;
893 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
894 /* ops set to 3.0 by default for default so update */
895 server->ops = &smb21_operations;
896 server->vals = &smb21_values;
897 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
898 server->ops = &smb311_operations;
899 server->vals = &smb311_values;
901 } else if (le16_to_cpu(rsp->DialectRevision) !=
902 server->vals->protocol_id) {
903 /* if requested single dialect ensure returned dialect matched */
904 cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
905 le16_to_cpu(rsp->DialectRevision));
906 return -EIO;
909 cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
911 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
912 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
913 else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
914 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
915 else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
916 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
917 else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
918 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
919 else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
920 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
921 else {
922 cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
923 le16_to_cpu(rsp->DialectRevision));
924 rc = -EIO;
925 goto neg_exit;
927 server->dialect = le16_to_cpu(rsp->DialectRevision);
930 * Keep a copy of the hash after negprot. This hash will be
931 * the starting hash value for all sessions made from this
932 * server.
934 memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
935 SMB2_PREAUTH_HASH_SIZE);
937 /* SMB2 only has an extended negflavor */
938 server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
939 /* set it to the maximum buffer size value we can send with 1 credit */
940 server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
941 SMB2_MAX_BUFFER_SIZE);
942 server->max_read = le32_to_cpu(rsp->MaxReadSize);
943 server->max_write = le32_to_cpu(rsp->MaxWriteSize);
944 server->sec_mode = le16_to_cpu(rsp->SecurityMode);
945 if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
946 cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
947 server->sec_mode);
948 server->capabilities = le32_to_cpu(rsp->Capabilities);
949 /* Internal types */
950 server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
952 security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
953 (struct smb2_sync_hdr *)rsp);
955 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
956 * for us will be
957 * ses->sectype = RawNTLMSSP;
958 * but for time being this is our only auth choice so doesn't matter.
959 * We just found a server which sets blob length to zero expecting raw.
961 if (blob_length == 0) {
962 cifs_dbg(FYI, "missing security blob on negprot\n");
963 server->sec_ntlmssp = true;
966 rc = cifs_enable_signing(server, ses->sign);
967 if (rc)
968 goto neg_exit;
969 if (blob_length) {
970 rc = decode_negTokenInit(security_blob, blob_length, server);
971 if (rc == 1)
972 rc = 0;
973 else if (rc == 0)
974 rc = -EIO;
977 if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
978 if (rsp->NegotiateContextCount)
979 rc = smb311_decode_neg_context(rsp, server,
980 rsp_iov.iov_len);
981 else
982 cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
984 neg_exit:
985 free_rsp_buf(resp_buftype, rsp);
986 return rc;
989 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
991 int rc;
992 struct validate_negotiate_info_req *pneg_inbuf;
993 struct validate_negotiate_info_rsp *pneg_rsp = NULL;
994 u32 rsplen;
995 u32 inbuflen; /* max of 4 dialects */
996 struct TCP_Server_Info *server = tcon->ses->server;
998 cifs_dbg(FYI, "validate negotiate\n");
1000 /* In SMB3.11 preauth integrity supersedes validate negotiate */
1001 if (server->dialect == SMB311_PROT_ID)
1002 return 0;
1005 * validation ioctl must be signed, so no point sending this if we
1006 * can not sign it (ie are not known user). Even if signing is not
1007 * required (enabled but not negotiated), in those cases we selectively
1008 * sign just this, the first and only signed request on a connection.
1009 * Having validation of negotiate info helps reduce attack vectors.
1011 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1012 return 0; /* validation requires signing */
1014 if (tcon->ses->user_name == NULL) {
1015 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1016 return 0; /* validation requires signing */
1019 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1020 cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1022 pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1023 if (!pneg_inbuf)
1024 return -ENOMEM;
1026 pneg_inbuf->Capabilities =
1027 cpu_to_le32(server->vals->req_capabilities);
1028 memcpy(pneg_inbuf->Guid, server->client_guid,
1029 SMB2_CLIENT_GUID_SIZE);
1031 if (tcon->ses->sign)
1032 pneg_inbuf->SecurityMode =
1033 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1034 else if (global_secflags & CIFSSEC_MAY_SIGN)
1035 pneg_inbuf->SecurityMode =
1036 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1037 else
1038 pneg_inbuf->SecurityMode = 0;
1041 if (strcmp(server->vals->version_string,
1042 SMB3ANY_VERSION_STRING) == 0) {
1043 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1044 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1045 pneg_inbuf->DialectCount = cpu_to_le16(2);
1046 /* structure is big enough for 3 dialects, sending only 2 */
1047 inbuflen = sizeof(*pneg_inbuf) -
1048 (2 * sizeof(pneg_inbuf->Dialects[0]));
1049 } else if (strcmp(server->vals->version_string,
1050 SMBDEFAULT_VERSION_STRING) == 0) {
1051 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1052 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1053 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1054 pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1055 pneg_inbuf->DialectCount = cpu_to_le16(4);
1056 /* structure is big enough for 3 dialects */
1057 inbuflen = sizeof(*pneg_inbuf);
1058 } else {
1059 /* otherwise specific dialect was requested */
1060 pneg_inbuf->Dialects[0] =
1061 cpu_to_le16(server->vals->protocol_id);
1062 pneg_inbuf->DialectCount = cpu_to_le16(1);
1063 /* structure is big enough for 3 dialects, sending only 1 */
1064 inbuflen = sizeof(*pneg_inbuf) -
1065 sizeof(pneg_inbuf->Dialects[0]) * 2;
1068 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1069 FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
1070 (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1071 (char **)&pneg_rsp, &rsplen);
1072 if (rc == -EOPNOTSUPP) {
1074 * Old Windows versions or Netapp SMB server can return
1075 * not supported error. Client should accept it.
1077 cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1078 rc = 0;
1079 goto out_free_inbuf;
1080 } else if (rc != 0) {
1081 cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1082 rc);
1083 rc = -EIO;
1084 goto out_free_inbuf;
1087 rc = -EIO;
1088 if (rsplen != sizeof(*pneg_rsp)) {
1089 cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1090 rsplen);
1092 /* relax check since Mac returns max bufsize allowed on ioctl */
1093 if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1094 goto out_free_rsp;
1097 /* check validate negotiate info response matches what we got earlier */
1098 if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1099 goto vneg_out;
1101 if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1102 goto vneg_out;
1104 /* do not validate server guid because not saved at negprot time yet */
1106 if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1107 SMB2_LARGE_FILES) != server->capabilities)
1108 goto vneg_out;
1110 /* validate negotiate successful */
1111 rc = 0;
1112 cifs_dbg(FYI, "validate negotiate info successful\n");
1113 goto out_free_rsp;
1115 vneg_out:
1116 cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1117 out_free_rsp:
1118 kfree(pneg_rsp);
1119 out_free_inbuf:
1120 kfree(pneg_inbuf);
1121 return rc;
1124 enum securityEnum
1125 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1127 switch (requested) {
1128 case Kerberos:
1129 case RawNTLMSSP:
1130 return requested;
1131 case NTLMv2:
1132 return RawNTLMSSP;
1133 case Unspecified:
1134 if (server->sec_ntlmssp &&
1135 (global_secflags & CIFSSEC_MAY_NTLMSSP))
1136 return RawNTLMSSP;
1137 if ((server->sec_kerberos || server->sec_mskerberos) &&
1138 (global_secflags & CIFSSEC_MAY_KRB5))
1139 return Kerberos;
1140 fallthrough;
1141 default:
1142 return Unspecified;
1146 struct SMB2_sess_data {
1147 unsigned int xid;
1148 struct cifs_ses *ses;
1149 struct nls_table *nls_cp;
1150 void (*func)(struct SMB2_sess_data *);
1151 int result;
1152 u64 previous_session;
1154 /* we will send the SMB in three pieces:
1155 * a fixed length beginning part, an optional
1156 * SPNEGO blob (which can be zero length), and a
1157 * last part which will include the strings
1158 * and rest of bcc area. This allows us to avoid
1159 * a large buffer 17K allocation
1161 int buf0_type;
1162 struct kvec iov[2];
1165 static int
1166 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1168 int rc;
1169 struct cifs_ses *ses = sess_data->ses;
1170 struct smb2_sess_setup_req *req;
1171 struct TCP_Server_Info *server = cifs_ses_server(ses);
1172 unsigned int total_len;
1174 rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1175 (void **) &req,
1176 &total_len);
1177 if (rc)
1178 return rc;
1180 if (sess_data->ses->binding) {
1181 req->sync_hdr.SessionId = sess_data->ses->Suid;
1182 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1183 req->PreviousSessionId = 0;
1184 req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1185 } else {
1186 /* First session, not a reauthenticate */
1187 req->sync_hdr.SessionId = 0;
1189 * if reconnect, we need to send previous sess id
1190 * otherwise it is 0
1192 req->PreviousSessionId = sess_data->previous_session;
1193 req->Flags = 0; /* MBZ */
1196 /* enough to enable echos and oplocks and one max size write */
1197 req->sync_hdr.CreditRequest = cpu_to_le16(130);
1199 /* only one of SMB2 signing flags may be set in SMB2 request */
1200 if (server->sign)
1201 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1202 else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1203 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1204 else
1205 req->SecurityMode = 0;
1207 #ifdef CONFIG_CIFS_DFS_UPCALL
1208 req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1209 #else
1210 req->Capabilities = 0;
1211 #endif /* DFS_UPCALL */
1213 req->Channel = 0; /* MBZ */
1215 sess_data->iov[0].iov_base = (char *)req;
1216 /* 1 for pad */
1217 sess_data->iov[0].iov_len = total_len - 1;
1219 * This variable will be used to clear the buffer
1220 * allocated above in case of any error in the calling function.
1222 sess_data->buf0_type = CIFS_SMALL_BUFFER;
1224 return 0;
1227 static void
1228 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1230 free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
1231 sess_data->buf0_type = CIFS_NO_BUFFER;
1234 static int
1235 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1237 int rc;
1238 struct smb_rqst rqst;
1239 struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1240 struct kvec rsp_iov = { NULL, 0 };
1242 /* Testing shows that buffer offset must be at location of Buffer[0] */
1243 req->SecurityBufferOffset =
1244 cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
1245 req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1247 memset(&rqst, 0, sizeof(struct smb_rqst));
1248 rqst.rq_iov = sess_data->iov;
1249 rqst.rq_nvec = 2;
1251 /* BB add code to build os and lm fields */
1252 rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1253 cifs_ses_server(sess_data->ses),
1254 &rqst,
1255 &sess_data->buf0_type,
1256 CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
1257 cifs_small_buf_release(sess_data->iov[0].iov_base);
1258 memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1260 return rc;
1263 static int
1264 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1266 int rc = 0;
1267 struct cifs_ses *ses = sess_data->ses;
1268 struct TCP_Server_Info *server = cifs_ses_server(ses);
1270 mutex_lock(&server->srv_mutex);
1271 if (server->ops->generate_signingkey) {
1272 rc = server->ops->generate_signingkey(ses);
1273 if (rc) {
1274 cifs_dbg(FYI,
1275 "SMB3 session key generation failed\n");
1276 mutex_unlock(&server->srv_mutex);
1277 return rc;
1280 if (!server->session_estab) {
1281 server->sequence_number = 0x2;
1282 server->session_estab = true;
1284 mutex_unlock(&server->srv_mutex);
1286 cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1287 /* keep existing ses state if binding */
1288 if (!ses->binding) {
1289 spin_lock(&GlobalMid_Lock);
1290 ses->status = CifsGood;
1291 ses->need_reconnect = false;
1292 spin_unlock(&GlobalMid_Lock);
1295 return rc;
1298 #ifdef CONFIG_CIFS_UPCALL
1299 static void
1300 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1302 int rc;
1303 struct cifs_ses *ses = sess_data->ses;
1304 struct cifs_spnego_msg *msg;
1305 struct key *spnego_key = NULL;
1306 struct smb2_sess_setup_rsp *rsp = NULL;
1308 rc = SMB2_sess_alloc_buffer(sess_data);
1309 if (rc)
1310 goto out;
1312 spnego_key = cifs_get_spnego_key(ses);
1313 if (IS_ERR(spnego_key)) {
1314 rc = PTR_ERR(spnego_key);
1315 if (rc == -ENOKEY)
1316 cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1317 spnego_key = NULL;
1318 goto out;
1321 msg = spnego_key->payload.data[0];
1323 * check version field to make sure that cifs.upcall is
1324 * sending us a response in an expected form
1326 if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1327 cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1328 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1329 rc = -EKEYREJECTED;
1330 goto out_put_spnego_key;
1333 /* keep session key if binding */
1334 if (!ses->binding) {
1335 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1336 GFP_KERNEL);
1337 if (!ses->auth_key.response) {
1338 cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1339 msg->sesskey_len);
1340 rc = -ENOMEM;
1341 goto out_put_spnego_key;
1343 ses->auth_key.len = msg->sesskey_len;
1346 sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1347 sess_data->iov[1].iov_len = msg->secblob_len;
1349 rc = SMB2_sess_sendreceive(sess_data);
1350 if (rc)
1351 goto out_put_spnego_key;
1353 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1354 /* keep session id and flags if binding */
1355 if (!ses->binding) {
1356 ses->Suid = rsp->sync_hdr.SessionId;
1357 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1360 rc = SMB2_sess_establish_session(sess_data);
1361 out_put_spnego_key:
1362 key_invalidate(spnego_key);
1363 key_put(spnego_key);
1364 out:
1365 sess_data->result = rc;
1366 sess_data->func = NULL;
1367 SMB2_sess_free_buffer(sess_data);
1369 #else
1370 static void
1371 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1373 cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1374 sess_data->result = -EOPNOTSUPP;
1375 sess_data->func = NULL;
1377 #endif
1379 static void
1380 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1382 static void
1383 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1385 int rc;
1386 struct cifs_ses *ses = sess_data->ses;
1387 struct smb2_sess_setup_rsp *rsp = NULL;
1388 char *ntlmssp_blob = NULL;
1389 bool use_spnego = false; /* else use raw ntlmssp */
1390 u16 blob_length = 0;
1393 * If memory allocation is successful, caller of this function
1394 * frees it.
1396 ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1397 if (!ses->ntlmssp) {
1398 rc = -ENOMEM;
1399 goto out_err;
1401 ses->ntlmssp->sesskey_per_smbsess = true;
1403 rc = SMB2_sess_alloc_buffer(sess_data);
1404 if (rc)
1405 goto out_err;
1407 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
1408 GFP_KERNEL);
1409 if (ntlmssp_blob == NULL) {
1410 rc = -ENOMEM;
1411 goto out;
1414 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
1415 if (use_spnego) {
1416 /* BB eventually need to add this */
1417 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1418 rc = -EOPNOTSUPP;
1419 goto out;
1420 } else {
1421 blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
1422 /* with raw NTLMSSP we don't encapsulate in SPNEGO */
1424 sess_data->iov[1].iov_base = ntlmssp_blob;
1425 sess_data->iov[1].iov_len = blob_length;
1427 rc = SMB2_sess_sendreceive(sess_data);
1428 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1430 /* If true, rc here is expected and not an error */
1431 if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1432 rsp->sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1433 rc = 0;
1435 if (rc)
1436 goto out;
1438 if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1439 le16_to_cpu(rsp->SecurityBufferOffset)) {
1440 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1441 le16_to_cpu(rsp->SecurityBufferOffset));
1442 rc = -EIO;
1443 goto out;
1445 rc = decode_ntlmssp_challenge(rsp->Buffer,
1446 le16_to_cpu(rsp->SecurityBufferLength), ses);
1447 if (rc)
1448 goto out;
1450 cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1452 /* keep existing ses id and flags if binding */
1453 if (!ses->binding) {
1454 ses->Suid = rsp->sync_hdr.SessionId;
1455 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1458 out:
1459 kfree(ntlmssp_blob);
1460 SMB2_sess_free_buffer(sess_data);
1461 if (!rc) {
1462 sess_data->result = 0;
1463 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1464 return;
1466 out_err:
1467 kfree(ses->ntlmssp);
1468 ses->ntlmssp = NULL;
1469 sess_data->result = rc;
1470 sess_data->func = NULL;
1473 static void
1474 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1476 int rc;
1477 struct cifs_ses *ses = sess_data->ses;
1478 struct smb2_sess_setup_req *req;
1479 struct smb2_sess_setup_rsp *rsp = NULL;
1480 unsigned char *ntlmssp_blob = NULL;
1481 bool use_spnego = false; /* else use raw ntlmssp */
1482 u16 blob_length = 0;
1484 rc = SMB2_sess_alloc_buffer(sess_data);
1485 if (rc)
1486 goto out;
1488 req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1489 req->sync_hdr.SessionId = ses->Suid;
1491 rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1492 sess_data->nls_cp);
1493 if (rc) {
1494 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1495 goto out;
1498 if (use_spnego) {
1499 /* BB eventually need to add this */
1500 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1501 rc = -EOPNOTSUPP;
1502 goto out;
1504 sess_data->iov[1].iov_base = ntlmssp_blob;
1505 sess_data->iov[1].iov_len = blob_length;
1507 rc = SMB2_sess_sendreceive(sess_data);
1508 if (rc)
1509 goto out;
1511 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1513 /* keep existing ses id and flags if binding */
1514 if (!ses->binding) {
1515 ses->Suid = rsp->sync_hdr.SessionId;
1516 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1519 rc = SMB2_sess_establish_session(sess_data);
1520 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1521 if (ses->server->dialect < SMB30_PROT_ID) {
1522 cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1524 * The session id is opaque in terms of endianness, so we can't
1525 * print it as a long long. we dump it as we got it on the wire
1527 cifs_dbg(VFS, "Session Id %*ph\n", (int)sizeof(ses->Suid),
1528 &ses->Suid);
1529 cifs_dbg(VFS, "Session Key %*ph\n",
1530 SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1531 cifs_dbg(VFS, "Signing Key %*ph\n",
1532 SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1534 #endif
1535 out:
1536 kfree(ntlmssp_blob);
1537 SMB2_sess_free_buffer(sess_data);
1538 kfree(ses->ntlmssp);
1539 ses->ntlmssp = NULL;
1540 sess_data->result = rc;
1541 sess_data->func = NULL;
1544 static int
1545 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1547 int type;
1549 type = smb2_select_sectype(cifs_ses_server(ses), ses->sectype);
1550 cifs_dbg(FYI, "sess setup type %d\n", type);
1551 if (type == Unspecified) {
1552 cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1553 return -EINVAL;
1556 switch (type) {
1557 case Kerberos:
1558 sess_data->func = SMB2_auth_kerberos;
1559 break;
1560 case RawNTLMSSP:
1561 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1562 break;
1563 default:
1564 cifs_dbg(VFS, "secType %d not supported!\n", type);
1565 return -EOPNOTSUPP;
1568 return 0;
1572 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1573 const struct nls_table *nls_cp)
1575 int rc = 0;
1576 struct TCP_Server_Info *server = cifs_ses_server(ses);
1577 struct SMB2_sess_data *sess_data;
1579 cifs_dbg(FYI, "Session Setup\n");
1581 if (!server) {
1582 WARN(1, "%s: server is NULL!\n", __func__);
1583 return -EIO;
1586 sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1587 if (!sess_data)
1588 return -ENOMEM;
1590 rc = SMB2_select_sec(ses, sess_data);
1591 if (rc)
1592 goto out;
1593 sess_data->xid = xid;
1594 sess_data->ses = ses;
1595 sess_data->buf0_type = CIFS_NO_BUFFER;
1596 sess_data->nls_cp = (struct nls_table *) nls_cp;
1597 sess_data->previous_session = ses->Suid;
1600 * Initialize the session hash with the server one.
1602 memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1603 SMB2_PREAUTH_HASH_SIZE);
1605 while (sess_data->func)
1606 sess_data->func(sess_data);
1608 if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1609 cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1610 rc = sess_data->result;
1611 out:
1612 kfree(sess_data);
1613 return rc;
1617 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1619 struct smb_rqst rqst;
1620 struct smb2_logoff_req *req; /* response is also trivial struct */
1621 int rc = 0;
1622 struct TCP_Server_Info *server;
1623 int flags = 0;
1624 unsigned int total_len;
1625 struct kvec iov[1];
1626 struct kvec rsp_iov;
1627 int resp_buf_type;
1629 cifs_dbg(FYI, "disconnect session %p\n", ses);
1631 if (ses && (ses->server))
1632 server = ses->server;
1633 else
1634 return -EIO;
1636 /* no need to send SMB logoff if uid already closed due to reconnect */
1637 if (ses->need_reconnect)
1638 goto smb2_session_already_dead;
1640 rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
1641 (void **) &req, &total_len);
1642 if (rc)
1643 return rc;
1645 /* since no tcon, smb2_init can not do this, so do here */
1646 req->sync_hdr.SessionId = ses->Suid;
1648 if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1649 flags |= CIFS_TRANSFORM_REQ;
1650 else if (server->sign)
1651 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1653 flags |= CIFS_NO_RSP_BUF;
1655 iov[0].iov_base = (char *)req;
1656 iov[0].iov_len = total_len;
1658 memset(&rqst, 0, sizeof(struct smb_rqst));
1659 rqst.rq_iov = iov;
1660 rqst.rq_nvec = 1;
1662 rc = cifs_send_recv(xid, ses, ses->server,
1663 &rqst, &resp_buf_type, flags, &rsp_iov);
1664 cifs_small_buf_release(req);
1666 * No tcon so can't do
1667 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1670 smb2_session_already_dead:
1671 return rc;
1674 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1676 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1679 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1681 /* These are similar values to what Windows uses */
1682 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1684 tcon->max_chunks = 256;
1685 tcon->max_bytes_chunk = 1048576;
1686 tcon->max_bytes_copy = 16777216;
1690 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1691 struct cifs_tcon *tcon, const struct nls_table *cp)
1693 struct smb_rqst rqst;
1694 struct smb2_tree_connect_req *req;
1695 struct smb2_tree_connect_rsp *rsp = NULL;
1696 struct kvec iov[2];
1697 struct kvec rsp_iov = { NULL, 0 };
1698 int rc = 0;
1699 int resp_buftype;
1700 int unc_path_len;
1701 __le16 *unc_path = NULL;
1702 int flags = 0;
1703 unsigned int total_len;
1704 struct TCP_Server_Info *server;
1706 /* always use master channel */
1707 server = ses->server;
1709 cifs_dbg(FYI, "TCON\n");
1711 if (!server || !tree)
1712 return -EIO;
1714 unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1715 if (unc_path == NULL)
1716 return -ENOMEM;
1718 unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1719 unc_path_len *= 2;
1720 if (unc_path_len < 2) {
1721 kfree(unc_path);
1722 return -EINVAL;
1725 /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1726 tcon->tid = 0;
1727 atomic_set(&tcon->num_remote_opens, 0);
1728 rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
1729 (void **) &req, &total_len);
1730 if (rc) {
1731 kfree(unc_path);
1732 return rc;
1735 if (smb3_encryption_required(tcon))
1736 flags |= CIFS_TRANSFORM_REQ;
1738 iov[0].iov_base = (char *)req;
1739 /* 1 for pad */
1740 iov[0].iov_len = total_len - 1;
1742 /* Testing shows that buffer offset must be at location of Buffer[0] */
1743 req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1744 - 1 /* pad */);
1745 req->PathLength = cpu_to_le16(unc_path_len - 2);
1746 iov[1].iov_base = unc_path;
1747 iov[1].iov_len = unc_path_len;
1750 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
1751 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1752 * (Samba servers don't always set the flag so also check if null user)
1754 if ((server->dialect == SMB311_PROT_ID) &&
1755 !smb3_encryption_required(tcon) &&
1756 !(ses->session_flags &
1757 (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
1758 ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1759 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1761 memset(&rqst, 0, sizeof(struct smb_rqst));
1762 rqst.rq_iov = iov;
1763 rqst.rq_nvec = 2;
1765 /* Need 64 for max size write so ask for more in case not there yet */
1766 req->sync_hdr.CreditRequest = cpu_to_le16(64);
1768 rc = cifs_send_recv(xid, ses, server,
1769 &rqst, &resp_buftype, flags, &rsp_iov);
1770 cifs_small_buf_release(req);
1771 rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1772 trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
1773 if (rc != 0) {
1774 if (tcon) {
1775 cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1776 tcon->need_reconnect = true;
1778 goto tcon_error_exit;
1781 switch (rsp->ShareType) {
1782 case SMB2_SHARE_TYPE_DISK:
1783 cifs_dbg(FYI, "connection to disk share\n");
1784 break;
1785 case SMB2_SHARE_TYPE_PIPE:
1786 tcon->pipe = true;
1787 cifs_dbg(FYI, "connection to pipe share\n");
1788 break;
1789 case SMB2_SHARE_TYPE_PRINT:
1790 tcon->print = true;
1791 cifs_dbg(FYI, "connection to printer\n");
1792 break;
1793 default:
1794 cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1795 rc = -EOPNOTSUPP;
1796 goto tcon_error_exit;
1799 tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1800 tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1801 tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1802 tcon->tidStatus = CifsGood;
1803 tcon->need_reconnect = false;
1804 tcon->tid = rsp->sync_hdr.TreeId;
1805 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1807 if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1808 ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1809 cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
1811 if (tcon->seal &&
1812 !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1813 cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
1815 init_copy_chunk_defaults(tcon);
1816 if (server->ops->validate_negotiate)
1817 rc = server->ops->validate_negotiate(xid, tcon);
1818 tcon_exit:
1820 free_rsp_buf(resp_buftype, rsp);
1821 kfree(unc_path);
1822 return rc;
1824 tcon_error_exit:
1825 if (rsp && rsp->sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1826 cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1828 goto tcon_exit;
1832 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1834 struct smb_rqst rqst;
1835 struct smb2_tree_disconnect_req *req; /* response is trivial */
1836 int rc = 0;
1837 struct cifs_ses *ses = tcon->ses;
1838 int flags = 0;
1839 unsigned int total_len;
1840 struct kvec iov[1];
1841 struct kvec rsp_iov;
1842 int resp_buf_type;
1844 cifs_dbg(FYI, "Tree Disconnect\n");
1846 if (!ses || !(ses->server))
1847 return -EIO;
1849 if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1850 return 0;
1852 close_shroot_lease(&tcon->crfid);
1854 rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, ses->server,
1855 (void **) &req,
1856 &total_len);
1857 if (rc)
1858 return rc;
1860 if (smb3_encryption_required(tcon))
1861 flags |= CIFS_TRANSFORM_REQ;
1863 flags |= CIFS_NO_RSP_BUF;
1865 iov[0].iov_base = (char *)req;
1866 iov[0].iov_len = total_len;
1868 memset(&rqst, 0, sizeof(struct smb_rqst));
1869 rqst.rq_iov = iov;
1870 rqst.rq_nvec = 1;
1872 rc = cifs_send_recv(xid, ses, ses->server,
1873 &rqst, &resp_buf_type, flags, &rsp_iov);
1874 cifs_small_buf_release(req);
1875 if (rc)
1876 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1878 return rc;
1882 static struct create_durable *
1883 create_durable_buf(void)
1885 struct create_durable *buf;
1887 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1888 if (!buf)
1889 return NULL;
1891 buf->ccontext.DataOffset = cpu_to_le16(offsetof
1892 (struct create_durable, Data));
1893 buf->ccontext.DataLength = cpu_to_le32(16);
1894 buf->ccontext.NameOffset = cpu_to_le16(offsetof
1895 (struct create_durable, Name));
1896 buf->ccontext.NameLength = cpu_to_le16(4);
1897 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1898 buf->Name[0] = 'D';
1899 buf->Name[1] = 'H';
1900 buf->Name[2] = 'n';
1901 buf->Name[3] = 'Q';
1902 return buf;
1905 static struct create_durable *
1906 create_reconnect_durable_buf(struct cifs_fid *fid)
1908 struct create_durable *buf;
1910 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1911 if (!buf)
1912 return NULL;
1914 buf->ccontext.DataOffset = cpu_to_le16(offsetof
1915 (struct create_durable, Data));
1916 buf->ccontext.DataLength = cpu_to_le32(16);
1917 buf->ccontext.NameOffset = cpu_to_le16(offsetof
1918 (struct create_durable, Name));
1919 buf->ccontext.NameLength = cpu_to_le16(4);
1920 buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1921 buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1922 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1923 buf->Name[0] = 'D';
1924 buf->Name[1] = 'H';
1925 buf->Name[2] = 'n';
1926 buf->Name[3] = 'C';
1927 return buf;
1930 static void
1931 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
1933 struct create_on_disk_id *pdisk_id = (struct create_on_disk_id *)cc;
1935 cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
1936 pdisk_id->DiskFileId, pdisk_id->VolumeId);
1937 buf->IndexNumber = pdisk_id->DiskFileId;
1940 static void
1941 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
1942 struct create_posix_rsp *posix)
1944 int sid_len;
1945 u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
1946 u8 *end = beg + le32_to_cpu(cc->DataLength);
1947 u8 *sid;
1949 memset(posix, 0, sizeof(*posix));
1951 posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
1952 posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
1953 posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
1955 sid = beg + 12;
1956 sid_len = posix_info_sid_size(sid, end);
1957 if (sid_len < 0) {
1958 cifs_dbg(VFS, "bad owner sid in posix create response\n");
1959 return;
1961 memcpy(&posix->owner, sid, sid_len);
1963 sid = sid + sid_len;
1964 sid_len = posix_info_sid_size(sid, end);
1965 if (sid_len < 0) {
1966 cifs_dbg(VFS, "bad group sid in posix create response\n");
1967 return;
1969 memcpy(&posix->group, sid, sid_len);
1971 cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
1972 posix->nlink, posix->mode, posix->reparse_tag);
1975 void
1976 smb2_parse_contexts(struct TCP_Server_Info *server,
1977 struct smb2_create_rsp *rsp,
1978 unsigned int *epoch, char *lease_key, __u8 *oplock,
1979 struct smb2_file_all_info *buf,
1980 struct create_posix_rsp *posix)
1982 char *data_offset;
1983 struct create_context *cc;
1984 unsigned int next;
1985 unsigned int remaining;
1986 char *name;
1987 static const char smb3_create_tag_posix[] = {
1988 0x93, 0xAD, 0x25, 0x50, 0x9C,
1989 0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
1990 0xDE, 0x96, 0x8B, 0xCD, 0x7C
1993 *oplock = 0;
1994 data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
1995 remaining = le32_to_cpu(rsp->CreateContextsLength);
1996 cc = (struct create_context *)data_offset;
1998 /* Initialize inode number to 0 in case no valid data in qfid context */
1999 if (buf)
2000 buf->IndexNumber = 0;
2002 while (remaining >= sizeof(struct create_context)) {
2003 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
2004 if (le16_to_cpu(cc->NameLength) == 4 &&
2005 strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4) == 0)
2006 *oplock = server->ops->parse_lease_buf(cc, epoch,
2007 lease_key);
2008 else if (buf && (le16_to_cpu(cc->NameLength) == 4) &&
2009 strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4) == 0)
2010 parse_query_id_ctxt(cc, buf);
2011 else if ((le16_to_cpu(cc->NameLength) == 16)) {
2012 if (posix &&
2013 memcmp(name, smb3_create_tag_posix, 16) == 0)
2014 parse_posix_ctxt(cc, buf, posix);
2016 /* else {
2017 cifs_dbg(FYI, "Context not matched with len %d\n",
2018 le16_to_cpu(cc->NameLength));
2019 cifs_dump_mem("Cctxt name: ", name, 4);
2020 } */
2022 next = le32_to_cpu(cc->Next);
2023 if (!next)
2024 break;
2025 remaining -= next;
2026 cc = (struct create_context *)((char *)cc + next);
2029 if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2030 *oplock = rsp->OplockLevel;
2032 return;
2035 static int
2036 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
2037 unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2039 struct smb2_create_req *req = iov[0].iov_base;
2040 unsigned int num = *num_iovec;
2042 iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2043 if (iov[num].iov_base == NULL)
2044 return -ENOMEM;
2045 iov[num].iov_len = server->vals->create_lease_size;
2046 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2047 if (!req->CreateContextsOffset)
2048 req->CreateContextsOffset = cpu_to_le32(
2049 sizeof(struct smb2_create_req) +
2050 iov[num - 1].iov_len);
2051 le32_add_cpu(&req->CreateContextsLength,
2052 server->vals->create_lease_size);
2053 *num_iovec = num + 1;
2054 return 0;
2057 static struct create_durable_v2 *
2058 create_durable_v2_buf(struct cifs_open_parms *oparms)
2060 struct cifs_fid *pfid = oparms->fid;
2061 struct create_durable_v2 *buf;
2063 buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2064 if (!buf)
2065 return NULL;
2067 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2068 (struct create_durable_v2, dcontext));
2069 buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2070 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2071 (struct create_durable_v2, Name));
2072 buf->ccontext.NameLength = cpu_to_le16(4);
2075 * NB: Handle timeout defaults to 0, which allows server to choose
2076 * (most servers default to 120 seconds) and most clients default to 0.
2077 * This can be overridden at mount ("handletimeout=") if the user wants
2078 * a different persistent (or resilient) handle timeout for all opens
2079 * opens on a particular SMB3 mount.
2081 buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2082 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2083 generate_random_uuid(buf->dcontext.CreateGuid);
2084 memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2086 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2087 buf->Name[0] = 'D';
2088 buf->Name[1] = 'H';
2089 buf->Name[2] = '2';
2090 buf->Name[3] = 'Q';
2091 return buf;
2094 static struct create_durable_handle_reconnect_v2 *
2095 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2097 struct create_durable_handle_reconnect_v2 *buf;
2099 buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2100 GFP_KERNEL);
2101 if (!buf)
2102 return NULL;
2104 buf->ccontext.DataOffset =
2105 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2106 dcontext));
2107 buf->ccontext.DataLength =
2108 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2109 buf->ccontext.NameOffset =
2110 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2111 Name));
2112 buf->ccontext.NameLength = cpu_to_le16(4);
2114 buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2115 buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2116 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2117 memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2119 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2120 buf->Name[0] = 'D';
2121 buf->Name[1] = 'H';
2122 buf->Name[2] = '2';
2123 buf->Name[3] = 'C';
2124 return buf;
2127 static int
2128 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2129 struct cifs_open_parms *oparms)
2131 struct smb2_create_req *req = iov[0].iov_base;
2132 unsigned int num = *num_iovec;
2134 iov[num].iov_base = create_durable_v2_buf(oparms);
2135 if (iov[num].iov_base == NULL)
2136 return -ENOMEM;
2137 iov[num].iov_len = sizeof(struct create_durable_v2);
2138 if (!req->CreateContextsOffset)
2139 req->CreateContextsOffset =
2140 cpu_to_le32(sizeof(struct smb2_create_req) +
2141 iov[1].iov_len);
2142 le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
2143 *num_iovec = num + 1;
2144 return 0;
2147 static int
2148 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2149 struct cifs_open_parms *oparms)
2151 struct smb2_create_req *req = iov[0].iov_base;
2152 unsigned int num = *num_iovec;
2154 /* indicate that we don't need to relock the file */
2155 oparms->reconnect = false;
2157 iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2158 if (iov[num].iov_base == NULL)
2159 return -ENOMEM;
2160 iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2161 if (!req->CreateContextsOffset)
2162 req->CreateContextsOffset =
2163 cpu_to_le32(sizeof(struct smb2_create_req) +
2164 iov[1].iov_len);
2165 le32_add_cpu(&req->CreateContextsLength,
2166 sizeof(struct create_durable_handle_reconnect_v2));
2167 *num_iovec = num + 1;
2168 return 0;
2171 static int
2172 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2173 struct cifs_open_parms *oparms, bool use_persistent)
2175 struct smb2_create_req *req = iov[0].iov_base;
2176 unsigned int num = *num_iovec;
2178 if (use_persistent) {
2179 if (oparms->reconnect)
2180 return add_durable_reconnect_v2_context(iov, num_iovec,
2181 oparms);
2182 else
2183 return add_durable_v2_context(iov, num_iovec, oparms);
2186 if (oparms->reconnect) {
2187 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2188 /* indicate that we don't need to relock the file */
2189 oparms->reconnect = false;
2190 } else
2191 iov[num].iov_base = create_durable_buf();
2192 if (iov[num].iov_base == NULL)
2193 return -ENOMEM;
2194 iov[num].iov_len = sizeof(struct create_durable);
2195 if (!req->CreateContextsOffset)
2196 req->CreateContextsOffset =
2197 cpu_to_le32(sizeof(struct smb2_create_req) +
2198 iov[1].iov_len);
2199 le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
2200 *num_iovec = num + 1;
2201 return 0;
2204 /* See MS-SMB2 2.2.13.2.7 */
2205 static struct crt_twarp_ctxt *
2206 create_twarp_buf(__u64 timewarp)
2208 struct crt_twarp_ctxt *buf;
2210 buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2211 if (!buf)
2212 return NULL;
2214 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2215 (struct crt_twarp_ctxt, Timestamp));
2216 buf->ccontext.DataLength = cpu_to_le32(8);
2217 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2218 (struct crt_twarp_ctxt, Name));
2219 buf->ccontext.NameLength = cpu_to_le16(4);
2220 /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2221 buf->Name[0] = 'T';
2222 buf->Name[1] = 'W';
2223 buf->Name[2] = 'r';
2224 buf->Name[3] = 'p';
2225 buf->Timestamp = cpu_to_le64(timewarp);
2226 return buf;
2229 /* See MS-SMB2 2.2.13.2.7 */
2230 static int
2231 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2233 struct smb2_create_req *req = iov[0].iov_base;
2234 unsigned int num = *num_iovec;
2236 iov[num].iov_base = create_twarp_buf(timewarp);
2237 if (iov[num].iov_base == NULL)
2238 return -ENOMEM;
2239 iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2240 if (!req->CreateContextsOffset)
2241 req->CreateContextsOffset = cpu_to_le32(
2242 sizeof(struct smb2_create_req) +
2243 iov[num - 1].iov_len);
2244 le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt));
2245 *num_iovec = num + 1;
2246 return 0;
2249 /* See See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2250 static void setup_owner_group_sids(char *buf)
2252 struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2254 /* Populate the user ownership fields S-1-5-88-1 */
2255 sids->owner.Revision = 1;
2256 sids->owner.NumAuth = 3;
2257 sids->owner.Authority[5] = 5;
2258 sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2259 sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2260 sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2262 /* Populate the group ownership fields S-1-5-88-2 */
2263 sids->group.Revision = 1;
2264 sids->group.NumAuth = 3;
2265 sids->group.Authority[5] = 5;
2266 sids->group.SubAuthorities[0] = cpu_to_le32(88);
2267 sids->group.SubAuthorities[1] = cpu_to_le32(2);
2268 sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2270 cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2273 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2274 static struct crt_sd_ctxt *
2275 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2277 struct crt_sd_ctxt *buf;
2278 __u8 *ptr, *aclptr;
2279 unsigned int acelen, acl_size, ace_count;
2280 unsigned int owner_offset = 0;
2281 unsigned int group_offset = 0;
2282 struct smb3_acl acl;
2284 *len = roundup(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2286 if (set_owner) {
2287 /* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2288 *len += sizeof(struct owner_group_sids);
2291 buf = kzalloc(*len, GFP_KERNEL);
2292 if (buf == NULL)
2293 return buf;
2295 ptr = (__u8 *)&buf[1];
2296 if (set_owner) {
2297 /* offset fields are from beginning of security descriptor not of create context */
2298 owner_offset = ptr - (__u8 *)&buf->sd;
2299 buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2300 group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2301 buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2303 setup_owner_group_sids(ptr);
2304 ptr += sizeof(struct owner_group_sids);
2305 } else {
2306 buf->sd.OffsetOwner = 0;
2307 buf->sd.OffsetGroup = 0;
2310 buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2311 buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2312 buf->ccontext.NameLength = cpu_to_le16(4);
2313 /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2314 buf->Name[0] = 'S';
2315 buf->Name[1] = 'e';
2316 buf->Name[2] = 'c';
2317 buf->Name[3] = 'D';
2318 buf->sd.Revision = 1; /* Must be one see MS-DTYP 2.4.6 */
2321 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2322 * and "DP" ie the DACL is present
2324 buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2326 /* offset owner, group and Sbz1 and SACL are all zero */
2327 buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2328 /* Ship the ACL for now. we will copy it into buf later. */
2329 aclptr = ptr;
2330 ptr += sizeof(struct cifs_acl);
2332 /* create one ACE to hold the mode embedded in reserved special SID */
2333 acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2334 ptr += acelen;
2335 acl_size = acelen + sizeof(struct smb3_acl);
2336 ace_count = 1;
2338 if (set_owner) {
2339 /* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2340 acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2341 ptr += acelen;
2342 acl_size += acelen;
2343 ace_count += 1;
2346 /* and one more ACE to allow access for authenticated users */
2347 acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2348 ptr += acelen;
2349 acl_size += acelen;
2350 ace_count += 1;
2352 acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2353 acl.AclSize = cpu_to_le16(acl_size);
2354 acl.AceCount = cpu_to_le16(ace_count);
2355 memcpy(aclptr, &acl, sizeof(struct cifs_acl));
2357 buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2358 *len = ptr - (__u8 *)buf;
2360 return buf;
2363 static int
2364 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2366 struct smb2_create_req *req = iov[0].iov_base;
2367 unsigned int num = *num_iovec;
2368 unsigned int len = 0;
2370 iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2371 if (iov[num].iov_base == NULL)
2372 return -ENOMEM;
2373 iov[num].iov_len = len;
2374 if (!req->CreateContextsOffset)
2375 req->CreateContextsOffset = cpu_to_le32(
2376 sizeof(struct smb2_create_req) +
2377 iov[num - 1].iov_len);
2378 le32_add_cpu(&req->CreateContextsLength, len);
2379 *num_iovec = num + 1;
2380 return 0;
2383 static struct crt_query_id_ctxt *
2384 create_query_id_buf(void)
2386 struct crt_query_id_ctxt *buf;
2388 buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2389 if (!buf)
2390 return NULL;
2392 buf->ccontext.DataOffset = cpu_to_le16(0);
2393 buf->ccontext.DataLength = cpu_to_le32(0);
2394 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2395 (struct crt_query_id_ctxt, Name));
2396 buf->ccontext.NameLength = cpu_to_le16(4);
2397 /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2398 buf->Name[0] = 'Q';
2399 buf->Name[1] = 'F';
2400 buf->Name[2] = 'i';
2401 buf->Name[3] = 'd';
2402 return buf;
2405 /* See MS-SMB2 2.2.13.2.9 */
2406 static int
2407 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2409 struct smb2_create_req *req = iov[0].iov_base;
2410 unsigned int num = *num_iovec;
2412 iov[num].iov_base = create_query_id_buf();
2413 if (iov[num].iov_base == NULL)
2414 return -ENOMEM;
2415 iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2416 if (!req->CreateContextsOffset)
2417 req->CreateContextsOffset = cpu_to_le32(
2418 sizeof(struct smb2_create_req) +
2419 iov[num - 1].iov_len);
2420 le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_query_id_ctxt));
2421 *num_iovec = num + 1;
2422 return 0;
2425 static int
2426 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2427 const char *treename, const __le16 *path)
2429 int treename_len, path_len;
2430 struct nls_table *cp;
2431 const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2434 * skip leading "\\"
2436 treename_len = strlen(treename);
2437 if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2438 return -EINVAL;
2440 treename += 2;
2441 treename_len -= 2;
2443 path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2446 * make room for one path separator between the treename and
2447 * path
2449 *out_len = treename_len + 1 + path_len;
2452 * final path needs to be null-terminated UTF16 with a
2453 * size aligned to 8
2456 *out_size = roundup((*out_len+1)*2, 8);
2457 *out_path = kzalloc(*out_size, GFP_KERNEL);
2458 if (!*out_path)
2459 return -ENOMEM;
2461 cp = load_nls_default();
2462 cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2463 UniStrcat(*out_path, sep);
2464 UniStrcat(*out_path, path);
2465 unload_nls(cp);
2467 return 0;
2470 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2471 umode_t mode, struct cifs_tcon *tcon,
2472 const char *full_path,
2473 struct cifs_sb_info *cifs_sb)
2475 struct smb_rqst rqst;
2476 struct smb2_create_req *req;
2477 struct smb2_create_rsp *rsp = NULL;
2478 struct cifs_ses *ses = tcon->ses;
2479 struct kvec iov[3]; /* make sure at least one for each open context */
2480 struct kvec rsp_iov = {NULL, 0};
2481 int resp_buftype;
2482 int uni_path_len;
2483 __le16 *copy_path = NULL;
2484 int copy_size;
2485 int rc = 0;
2486 unsigned int n_iov = 2;
2487 __u32 file_attributes = 0;
2488 char *pc_buf = NULL;
2489 int flags = 0;
2490 unsigned int total_len;
2491 __le16 *utf16_path = NULL;
2492 struct TCP_Server_Info *server = cifs_pick_channel(ses);
2494 cifs_dbg(FYI, "mkdir\n");
2496 /* resource #1: path allocation */
2497 utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2498 if (!utf16_path)
2499 return -ENOMEM;
2501 if (!ses || !server) {
2502 rc = -EIO;
2503 goto err_free_path;
2506 /* resource #2: request */
2507 rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2508 (void **) &req, &total_len);
2509 if (rc)
2510 goto err_free_path;
2513 if (smb3_encryption_required(tcon))
2514 flags |= CIFS_TRANSFORM_REQ;
2516 req->ImpersonationLevel = IL_IMPERSONATION;
2517 req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2518 /* File attributes ignored on open (used in create though) */
2519 req->FileAttributes = cpu_to_le32(file_attributes);
2520 req->ShareAccess = FILE_SHARE_ALL_LE;
2521 req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2522 req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2524 iov[0].iov_base = (char *)req;
2525 /* -1 since last byte is buf[0] which is sent below (path) */
2526 iov[0].iov_len = total_len - 1;
2528 req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2530 /* [MS-SMB2] 2.2.13 NameOffset:
2531 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2532 * the SMB2 header, the file name includes a prefix that will
2533 * be processed during DFS name normalization as specified in
2534 * section 3.3.5.9. Otherwise, the file name is relative to
2535 * the share that is identified by the TreeId in the SMB2
2536 * header.
2538 if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2539 int name_len;
2541 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2542 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2543 &name_len,
2544 tcon->treeName, utf16_path);
2545 if (rc)
2546 goto err_free_req;
2548 req->NameLength = cpu_to_le16(name_len * 2);
2549 uni_path_len = copy_size;
2550 /* free before overwriting resource */
2551 kfree(utf16_path);
2552 utf16_path = copy_path;
2553 } else {
2554 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2555 /* MUST set path len (NameLength) to 0 opening root of share */
2556 req->NameLength = cpu_to_le16(uni_path_len - 2);
2557 if (uni_path_len % 8 != 0) {
2558 copy_size = roundup(uni_path_len, 8);
2559 copy_path = kzalloc(copy_size, GFP_KERNEL);
2560 if (!copy_path) {
2561 rc = -ENOMEM;
2562 goto err_free_req;
2564 memcpy((char *)copy_path, (const char *)utf16_path,
2565 uni_path_len);
2566 uni_path_len = copy_size;
2567 /* free before overwriting resource */
2568 kfree(utf16_path);
2569 utf16_path = copy_path;
2573 iov[1].iov_len = uni_path_len;
2574 iov[1].iov_base = utf16_path;
2575 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2577 if (tcon->posix_extensions) {
2578 /* resource #3: posix buf */
2579 rc = add_posix_context(iov, &n_iov, mode);
2580 if (rc)
2581 goto err_free_req;
2582 pc_buf = iov[n_iov-1].iov_base;
2586 memset(&rqst, 0, sizeof(struct smb_rqst));
2587 rqst.rq_iov = iov;
2588 rqst.rq_nvec = n_iov;
2590 /* no need to inc num_remote_opens because we close it just below */
2591 trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE,
2592 FILE_WRITE_ATTRIBUTES);
2593 /* resource #4: response buffer */
2594 rc = cifs_send_recv(xid, ses, server,
2595 &rqst, &resp_buftype, flags, &rsp_iov);
2596 if (rc) {
2597 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2598 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2599 CREATE_NOT_FILE,
2600 FILE_WRITE_ATTRIBUTES, rc);
2601 goto err_free_rsp_buf;
2604 rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2605 trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid,
2606 ses->Suid, CREATE_NOT_FILE,
2607 FILE_WRITE_ATTRIBUTES);
2609 SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2611 /* Eventually save off posix specific response info and timestaps */
2613 err_free_rsp_buf:
2614 free_rsp_buf(resp_buftype, rsp);
2615 kfree(pc_buf);
2616 err_free_req:
2617 cifs_small_buf_release(req);
2618 err_free_path:
2619 kfree(utf16_path);
2620 return rc;
2624 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2625 struct smb_rqst *rqst, __u8 *oplock,
2626 struct cifs_open_parms *oparms, __le16 *path)
2628 struct smb2_create_req *req;
2629 unsigned int n_iov = 2;
2630 __u32 file_attributes = 0;
2631 int copy_size;
2632 int uni_path_len;
2633 unsigned int total_len;
2634 struct kvec *iov = rqst->rq_iov;
2635 __le16 *copy_path;
2636 int rc;
2638 rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2639 (void **) &req, &total_len);
2640 if (rc)
2641 return rc;
2643 iov[0].iov_base = (char *)req;
2644 /* -1 since last byte is buf[0] which is sent below (path) */
2645 iov[0].iov_len = total_len - 1;
2647 if (oparms->create_options & CREATE_OPTION_READONLY)
2648 file_attributes |= ATTR_READONLY;
2649 if (oparms->create_options & CREATE_OPTION_SPECIAL)
2650 file_attributes |= ATTR_SYSTEM;
2652 req->ImpersonationLevel = IL_IMPERSONATION;
2653 req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2654 /* File attributes ignored on open (used in create though) */
2655 req->FileAttributes = cpu_to_le32(file_attributes);
2656 req->ShareAccess = FILE_SHARE_ALL_LE;
2658 req->CreateDisposition = cpu_to_le32(oparms->disposition);
2659 req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2660 req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2662 /* [MS-SMB2] 2.2.13 NameOffset:
2663 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2664 * the SMB2 header, the file name includes a prefix that will
2665 * be processed during DFS name normalization as specified in
2666 * section 3.3.5.9. Otherwise, the file name is relative to
2667 * the share that is identified by the TreeId in the SMB2
2668 * header.
2670 if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2671 int name_len;
2673 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2674 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2675 &name_len,
2676 tcon->treeName, path);
2677 if (rc)
2678 return rc;
2679 req->NameLength = cpu_to_le16(name_len * 2);
2680 uni_path_len = copy_size;
2681 path = copy_path;
2682 } else {
2683 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2684 /* MUST set path len (NameLength) to 0 opening root of share */
2685 req->NameLength = cpu_to_le16(uni_path_len - 2);
2686 copy_size = uni_path_len;
2687 if (copy_size % 8 != 0)
2688 copy_size = roundup(copy_size, 8);
2689 copy_path = kzalloc(copy_size, GFP_KERNEL);
2690 if (!copy_path)
2691 return -ENOMEM;
2692 memcpy((char *)copy_path, (const char *)path,
2693 uni_path_len);
2694 uni_path_len = copy_size;
2695 path = copy_path;
2698 iov[1].iov_len = uni_path_len;
2699 iov[1].iov_base = path;
2701 if ((!server->oplocks) || (tcon->no_lease))
2702 *oplock = SMB2_OPLOCK_LEVEL_NONE;
2704 if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2705 *oplock == SMB2_OPLOCK_LEVEL_NONE)
2706 req->RequestedOplockLevel = *oplock;
2707 else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2708 (oparms->create_options & CREATE_NOT_FILE))
2709 req->RequestedOplockLevel = *oplock; /* no srv lease support */
2710 else {
2711 rc = add_lease_context(server, iov, &n_iov,
2712 oparms->fid->lease_key, oplock);
2713 if (rc)
2714 return rc;
2717 if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2718 /* need to set Next field of lease context if we request it */
2719 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2720 struct create_context *ccontext =
2721 (struct create_context *)iov[n_iov-1].iov_base;
2722 ccontext->Next =
2723 cpu_to_le32(server->vals->create_lease_size);
2726 rc = add_durable_context(iov, &n_iov, oparms,
2727 tcon->use_persistent);
2728 if (rc)
2729 return rc;
2732 if (tcon->posix_extensions) {
2733 if (n_iov > 2) {
2734 struct create_context *ccontext =
2735 (struct create_context *)iov[n_iov-1].iov_base;
2736 ccontext->Next =
2737 cpu_to_le32(iov[n_iov-1].iov_len);
2740 rc = add_posix_context(iov, &n_iov, oparms->mode);
2741 if (rc)
2742 return rc;
2745 if (tcon->snapshot_time) {
2746 cifs_dbg(FYI, "adding snapshot context\n");
2747 if (n_iov > 2) {
2748 struct create_context *ccontext =
2749 (struct create_context *)iov[n_iov-1].iov_base;
2750 ccontext->Next =
2751 cpu_to_le32(iov[n_iov-1].iov_len);
2754 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2755 if (rc)
2756 return rc;
2759 if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
2760 bool set_mode;
2761 bool set_owner;
2763 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2764 (oparms->mode != ACL_NO_MODE))
2765 set_mode = true;
2766 else {
2767 set_mode = false;
2768 oparms->mode = ACL_NO_MODE;
2771 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
2772 set_owner = true;
2773 else
2774 set_owner = false;
2776 if (set_owner | set_mode) {
2777 if (n_iov > 2) {
2778 struct create_context *ccontext =
2779 (struct create_context *)iov[n_iov-1].iov_base;
2780 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2783 cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2784 rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
2785 if (rc)
2786 return rc;
2790 if (n_iov > 2) {
2791 struct create_context *ccontext =
2792 (struct create_context *)iov[n_iov-1].iov_base;
2793 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2795 add_query_id_context(iov, &n_iov);
2797 rqst->rq_nvec = n_iov;
2798 return 0;
2801 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2802 * All other vectors are freed by kfree().
2804 void
2805 SMB2_open_free(struct smb_rqst *rqst)
2807 int i;
2809 if (rqst && rqst->rq_iov) {
2810 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2811 for (i = 1; i < rqst->rq_nvec; i++)
2812 if (rqst->rq_iov[i].iov_base != smb2_padding)
2813 kfree(rqst->rq_iov[i].iov_base);
2818 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2819 __u8 *oplock, struct smb2_file_all_info *buf,
2820 struct create_posix_rsp *posix,
2821 struct kvec *err_iov, int *buftype)
2823 struct smb_rqst rqst;
2824 struct smb2_create_rsp *rsp = NULL;
2825 struct cifs_tcon *tcon = oparms->tcon;
2826 struct cifs_ses *ses = tcon->ses;
2827 struct TCP_Server_Info *server = cifs_pick_channel(ses);
2828 struct kvec iov[SMB2_CREATE_IOV_SIZE];
2829 struct kvec rsp_iov = {NULL, 0};
2830 int resp_buftype = CIFS_NO_BUFFER;
2831 int rc = 0;
2832 int flags = 0;
2834 cifs_dbg(FYI, "create/open\n");
2835 if (!ses || !server)
2836 return -EIO;
2838 if (smb3_encryption_required(tcon))
2839 flags |= CIFS_TRANSFORM_REQ;
2841 memset(&rqst, 0, sizeof(struct smb_rqst));
2842 memset(&iov, 0, sizeof(iov));
2843 rqst.rq_iov = iov;
2844 rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2846 rc = SMB2_open_init(tcon, server,
2847 &rqst, oplock, oparms, path);
2848 if (rc)
2849 goto creat_exit;
2851 trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
2852 oparms->create_options, oparms->desired_access);
2854 rc = cifs_send_recv(xid, ses, server,
2855 &rqst, &resp_buftype, flags,
2856 &rsp_iov);
2857 rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2859 if (rc != 0) {
2860 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2861 if (err_iov && rsp) {
2862 *err_iov = rsp_iov;
2863 *buftype = resp_buftype;
2864 resp_buftype = CIFS_NO_BUFFER;
2865 rsp = NULL;
2867 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
2868 oparms->create_options, oparms->desired_access, rc);
2869 if (rc == -EREMCHG) {
2870 pr_warn_once("server share %s deleted\n",
2871 tcon->treeName);
2872 tcon->need_reconnect = true;
2874 goto creat_exit;
2875 } else
2876 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid,
2877 ses->Suid, oparms->create_options,
2878 oparms->desired_access);
2880 atomic_inc(&tcon->num_remote_opens);
2881 oparms->fid->persistent_fid = rsp->PersistentFileId;
2882 oparms->fid->volatile_fid = rsp->VolatileFileId;
2883 oparms->fid->access = oparms->desired_access;
2884 #ifdef CONFIG_CIFS_DEBUG2
2885 oparms->fid->mid = le64_to_cpu(rsp->sync_hdr.MessageId);
2886 #endif /* CIFS_DEBUG2 */
2888 if (buf) {
2889 memcpy(buf, &rsp->CreationTime, 32);
2890 buf->AllocationSize = rsp->AllocationSize;
2891 buf->EndOfFile = rsp->EndofFile;
2892 buf->Attributes = rsp->FileAttributes;
2893 buf->NumberOfLinks = cpu_to_le32(1);
2894 buf->DeletePending = 0;
2898 smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
2899 oparms->fid->lease_key, oplock, buf, posix);
2900 creat_exit:
2901 SMB2_open_free(&rqst);
2902 free_rsp_buf(resp_buftype, rsp);
2903 return rc;
2907 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2908 struct smb_rqst *rqst,
2909 u64 persistent_fid, u64 volatile_fid, u32 opcode,
2910 bool is_fsctl, char *in_data, u32 indatalen,
2911 __u32 max_response_size)
2913 struct smb2_ioctl_req *req;
2914 struct kvec *iov = rqst->rq_iov;
2915 unsigned int total_len;
2916 int rc;
2917 char *in_data_buf;
2919 rc = smb2_ioctl_req_init(opcode, tcon, server,
2920 (void **) &req, &total_len);
2921 if (rc)
2922 return rc;
2924 if (indatalen) {
2926 * indatalen is usually small at a couple of bytes max, so
2927 * just allocate through generic pool
2929 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
2930 if (!in_data_buf) {
2931 cifs_small_buf_release(req);
2932 return -ENOMEM;
2936 req->CtlCode = cpu_to_le32(opcode);
2937 req->PersistentFileId = persistent_fid;
2938 req->VolatileFileId = volatile_fid;
2940 iov[0].iov_base = (char *)req;
2942 * If no input data, the size of ioctl struct in
2943 * protocol spec still includes a 1 byte data buffer,
2944 * but if input data passed to ioctl, we do not
2945 * want to double count this, so we do not send
2946 * the dummy one byte of data in iovec[0] if sending
2947 * input data (in iovec[1]).
2949 if (indatalen) {
2950 req->InputCount = cpu_to_le32(indatalen);
2951 /* do not set InputOffset if no input data */
2952 req->InputOffset =
2953 cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
2954 rqst->rq_nvec = 2;
2955 iov[0].iov_len = total_len - 1;
2956 iov[1].iov_base = in_data_buf;
2957 iov[1].iov_len = indatalen;
2958 } else {
2959 rqst->rq_nvec = 1;
2960 iov[0].iov_len = total_len;
2963 req->OutputOffset = 0;
2964 req->OutputCount = 0; /* MBZ */
2967 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
2968 * We Could increase default MaxOutputResponse, but that could require
2969 * more credits. Windows typically sets this smaller, but for some
2970 * ioctls it may be useful to allow server to send more. No point
2971 * limiting what the server can send as long as fits in one credit
2972 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
2973 * to increase this limit up in the future.
2974 * Note that for snapshot queries that servers like Azure expect that
2975 * the first query be minimal size (and just used to get the number/size
2976 * of previous versions) so response size must be specified as EXACTLY
2977 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
2978 * of eight bytes. Currently that is the only case where we set max
2979 * response size smaller.
2981 req->MaxOutputResponse = cpu_to_le32(max_response_size);
2982 req->sync_hdr.CreditCharge =
2983 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
2984 SMB2_MAX_BUFFER_SIZE));
2985 if (is_fsctl)
2986 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
2987 else
2988 req->Flags = 0;
2990 /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
2991 if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
2992 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
2994 return 0;
2997 void
2998 SMB2_ioctl_free(struct smb_rqst *rqst)
3000 int i;
3001 if (rqst && rqst->rq_iov) {
3002 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3003 for (i = 1; i < rqst->rq_nvec; i++)
3004 if (rqst->rq_iov[i].iov_base != smb2_padding)
3005 kfree(rqst->rq_iov[i].iov_base);
3011 * SMB2 IOCTL is used for both IOCTLs and FSCTLs
3014 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3015 u64 volatile_fid, u32 opcode, bool is_fsctl,
3016 char *in_data, u32 indatalen, u32 max_out_data_len,
3017 char **out_data, u32 *plen /* returned data len */)
3019 struct smb_rqst rqst;
3020 struct smb2_ioctl_rsp *rsp = NULL;
3021 struct cifs_ses *ses;
3022 struct TCP_Server_Info *server;
3023 struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3024 struct kvec rsp_iov = {NULL, 0};
3025 int resp_buftype = CIFS_NO_BUFFER;
3026 int rc = 0;
3027 int flags = 0;
3029 cifs_dbg(FYI, "SMB2 IOCTL\n");
3031 if (out_data != NULL)
3032 *out_data = NULL;
3034 /* zero out returned data len, in case of error */
3035 if (plen)
3036 *plen = 0;
3038 if (!tcon)
3039 return -EIO;
3041 ses = tcon->ses;
3042 if (!ses)
3043 return -EIO;
3045 server = cifs_pick_channel(ses);
3046 if (!server)
3047 return -EIO;
3049 if (smb3_encryption_required(tcon))
3050 flags |= CIFS_TRANSFORM_REQ;
3052 memset(&rqst, 0, sizeof(struct smb_rqst));
3053 memset(&iov, 0, sizeof(iov));
3054 rqst.rq_iov = iov;
3055 rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3057 rc = SMB2_ioctl_init(tcon, server,
3058 &rqst, persistent_fid, volatile_fid, opcode,
3059 is_fsctl, in_data, indatalen, max_out_data_len);
3060 if (rc)
3061 goto ioctl_exit;
3063 rc = cifs_send_recv(xid, ses, server,
3064 &rqst, &resp_buftype, flags,
3065 &rsp_iov);
3066 rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3068 if (rc != 0)
3069 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3070 ses->Suid, 0, opcode, rc);
3072 if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3073 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3074 goto ioctl_exit;
3075 } else if (rc == -EINVAL) {
3076 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3077 (opcode != FSCTL_SRV_COPYCHUNK)) {
3078 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3079 goto ioctl_exit;
3081 } else if (rc == -E2BIG) {
3082 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3083 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3084 goto ioctl_exit;
3088 /* check if caller wants to look at return data or just return rc */
3089 if ((plen == NULL) || (out_data == NULL))
3090 goto ioctl_exit;
3092 *plen = le32_to_cpu(rsp->OutputCount);
3094 /* We check for obvious errors in the output buffer length and offset */
3095 if (*plen == 0)
3096 goto ioctl_exit; /* server returned no data */
3097 else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3098 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3099 *plen = 0;
3100 rc = -EIO;
3101 goto ioctl_exit;
3104 if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3105 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3106 le32_to_cpu(rsp->OutputOffset));
3107 *plen = 0;
3108 rc = -EIO;
3109 goto ioctl_exit;
3112 *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3113 *plen, GFP_KERNEL);
3114 if (*out_data == NULL) {
3115 rc = -ENOMEM;
3116 goto ioctl_exit;
3119 ioctl_exit:
3120 SMB2_ioctl_free(&rqst);
3121 free_rsp_buf(resp_buftype, rsp);
3122 return rc;
3126 * Individual callers to ioctl worker function follow
3130 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3131 u64 persistent_fid, u64 volatile_fid)
3133 int rc;
3134 struct compress_ioctl fsctl_input;
3135 char *ret_data = NULL;
3137 fsctl_input.CompressionState =
3138 cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3140 rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3141 FSCTL_SET_COMPRESSION, true /* is_fsctl */,
3142 (char *)&fsctl_input /* data input */,
3143 2 /* in data len */, CIFSMaxBufSize /* max out data */,
3144 &ret_data /* out data */, NULL);
3146 cifs_dbg(FYI, "set compression rc %d\n", rc);
3148 return rc;
3152 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3153 struct smb_rqst *rqst,
3154 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3156 struct smb2_close_req *req;
3157 struct kvec *iov = rqst->rq_iov;
3158 unsigned int total_len;
3159 int rc;
3161 rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3162 (void **) &req, &total_len);
3163 if (rc)
3164 return rc;
3166 req->PersistentFileId = persistent_fid;
3167 req->VolatileFileId = volatile_fid;
3168 if (query_attrs)
3169 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3170 else
3171 req->Flags = 0;
3172 iov[0].iov_base = (char *)req;
3173 iov[0].iov_len = total_len;
3175 return 0;
3178 void
3179 SMB2_close_free(struct smb_rqst *rqst)
3181 if (rqst && rqst->rq_iov)
3182 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3186 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3187 u64 persistent_fid, u64 volatile_fid,
3188 struct smb2_file_network_open_info *pbuf)
3190 struct smb_rqst rqst;
3191 struct smb2_close_rsp *rsp = NULL;
3192 struct cifs_ses *ses = tcon->ses;
3193 struct TCP_Server_Info *server = cifs_pick_channel(ses);
3194 struct kvec iov[1];
3195 struct kvec rsp_iov;
3196 int resp_buftype = CIFS_NO_BUFFER;
3197 int rc = 0;
3198 int flags = 0;
3199 bool query_attrs = false;
3201 cifs_dbg(FYI, "Close\n");
3203 if (!ses || !server)
3204 return -EIO;
3206 if (smb3_encryption_required(tcon))
3207 flags |= CIFS_TRANSFORM_REQ;
3209 memset(&rqst, 0, sizeof(struct smb_rqst));
3210 memset(&iov, 0, sizeof(iov));
3211 rqst.rq_iov = iov;
3212 rqst.rq_nvec = 1;
3214 /* check if need to ask server to return timestamps in close response */
3215 if (pbuf)
3216 query_attrs = true;
3218 trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3219 rc = SMB2_close_init(tcon, server,
3220 &rqst, persistent_fid, volatile_fid,
3221 query_attrs);
3222 if (rc)
3223 goto close_exit;
3225 rc = cifs_send_recv(xid, ses, server,
3226 &rqst, &resp_buftype, flags, &rsp_iov);
3227 rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3229 if (rc != 0) {
3230 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3231 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3232 rc);
3233 goto close_exit;
3234 } else {
3235 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3236 ses->Suid);
3238 * Note that have to subtract 4 since struct network_open_info
3239 * has a final 4 byte pad that close response does not have
3241 if (pbuf)
3242 memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3245 atomic_dec(&tcon->num_remote_opens);
3246 close_exit:
3247 SMB2_close_free(&rqst);
3248 free_rsp_buf(resp_buftype, rsp);
3250 /* retry close in a worker thread if this one is interrupted */
3251 if (rc == -EINTR) {
3252 int tmp_rc;
3254 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3255 volatile_fid);
3256 if (tmp_rc)
3257 cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3258 persistent_fid, tmp_rc);
3260 return rc;
3264 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3265 u64 persistent_fid, u64 volatile_fid)
3267 return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3271 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3272 struct kvec *iov, unsigned int min_buf_size)
3274 unsigned int smb_len = iov->iov_len;
3275 char *end_of_smb = smb_len + (char *)iov->iov_base;
3276 char *begin_of_buf = offset + (char *)iov->iov_base;
3277 char *end_of_buf = begin_of_buf + buffer_length;
3280 if (buffer_length < min_buf_size) {
3281 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3282 buffer_length, min_buf_size);
3283 return -EINVAL;
3286 /* check if beyond RFC1001 maximum length */
3287 if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3288 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3289 buffer_length, smb_len);
3290 return -EINVAL;
3293 if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3294 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3295 return -EINVAL;
3298 return 0;
3302 * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3303 * Caller must free buffer.
3306 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3307 struct kvec *iov, unsigned int minbufsize,
3308 char *data)
3310 char *begin_of_buf = offset + (char *)iov->iov_base;
3311 int rc;
3313 if (!data)
3314 return -EINVAL;
3316 rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3317 if (rc)
3318 return rc;
3320 memcpy(data, begin_of_buf, buffer_length);
3322 return 0;
3326 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3327 struct smb_rqst *rqst,
3328 u64 persistent_fid, u64 volatile_fid,
3329 u8 info_class, u8 info_type, u32 additional_info,
3330 size_t output_len, size_t input_len, void *input)
3332 struct smb2_query_info_req *req;
3333 struct kvec *iov = rqst->rq_iov;
3334 unsigned int total_len;
3335 int rc;
3337 rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3338 (void **) &req, &total_len);
3339 if (rc)
3340 return rc;
3342 req->InfoType = info_type;
3343 req->FileInfoClass = info_class;
3344 req->PersistentFileId = persistent_fid;
3345 req->VolatileFileId = volatile_fid;
3346 req->AdditionalInformation = cpu_to_le32(additional_info);
3348 req->OutputBufferLength = cpu_to_le32(output_len);
3349 if (input_len) {
3350 req->InputBufferLength = cpu_to_le32(input_len);
3351 /* total_len for smb query request never close to le16 max */
3352 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3353 memcpy(req->Buffer, input, input_len);
3356 iov[0].iov_base = (char *)req;
3357 /* 1 for Buffer */
3358 iov[0].iov_len = total_len - 1 + input_len;
3359 return 0;
3362 void
3363 SMB2_query_info_free(struct smb_rqst *rqst)
3365 if (rqst && rqst->rq_iov)
3366 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3369 static int
3370 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3371 u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3372 u32 additional_info, size_t output_len, size_t min_len, void **data,
3373 u32 *dlen)
3375 struct smb_rqst rqst;
3376 struct smb2_query_info_rsp *rsp = NULL;
3377 struct kvec iov[1];
3378 struct kvec rsp_iov;
3379 int rc = 0;
3380 int resp_buftype = CIFS_NO_BUFFER;
3381 struct cifs_ses *ses = tcon->ses;
3382 struct TCP_Server_Info *server;
3383 int flags = 0;
3384 bool allocated = false;
3386 cifs_dbg(FYI, "Query Info\n");
3388 if (!ses)
3389 return -EIO;
3390 server = cifs_pick_channel(ses);
3391 if (!server)
3392 return -EIO;
3394 if (smb3_encryption_required(tcon))
3395 flags |= CIFS_TRANSFORM_REQ;
3397 memset(&rqst, 0, sizeof(struct smb_rqst));
3398 memset(&iov, 0, sizeof(iov));
3399 rqst.rq_iov = iov;
3400 rqst.rq_nvec = 1;
3402 rc = SMB2_query_info_init(tcon, server,
3403 &rqst, persistent_fid, volatile_fid,
3404 info_class, info_type, additional_info,
3405 output_len, 0, NULL);
3406 if (rc)
3407 goto qinf_exit;
3409 trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3410 ses->Suid, info_class, (__u32)info_type);
3412 rc = cifs_send_recv(xid, ses, server,
3413 &rqst, &resp_buftype, flags, &rsp_iov);
3414 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3416 if (rc) {
3417 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3418 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3419 ses->Suid, info_class, (__u32)info_type, rc);
3420 goto qinf_exit;
3423 trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3424 ses->Suid, info_class, (__u32)info_type);
3426 if (dlen) {
3427 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3428 if (!*data) {
3429 *data = kmalloc(*dlen, GFP_KERNEL);
3430 if (!*data) {
3431 cifs_tcon_dbg(VFS,
3432 "Error %d allocating memory for acl\n",
3433 rc);
3434 *dlen = 0;
3435 rc = -ENOMEM;
3436 goto qinf_exit;
3438 allocated = true;
3442 rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3443 le32_to_cpu(rsp->OutputBufferLength),
3444 &rsp_iov, min_len, *data);
3445 if (rc && allocated) {
3446 kfree(*data);
3447 *data = NULL;
3448 *dlen = 0;
3451 qinf_exit:
3452 SMB2_query_info_free(&rqst);
3453 free_rsp_buf(resp_buftype, rsp);
3454 return rc;
3457 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3458 u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3460 return query_info(xid, tcon, persistent_fid, volatile_fid,
3461 FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3462 sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3463 sizeof(struct smb2_file_all_info), (void **)&data,
3464 NULL);
3468 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3469 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3471 size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3472 (sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3473 *plen = 0;
3475 return query_info(xid, tcon, persistent_fid, volatile_fid,
3476 SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3477 output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3481 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3482 u64 persistent_fid, u64 volatile_fid,
3483 void **data, u32 *plen, u32 extra_info)
3485 __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3486 extra_info;
3487 *plen = 0;
3489 return query_info(xid, tcon, persistent_fid, volatile_fid,
3490 0, SMB2_O_INFO_SECURITY, additional_info,
3491 SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3495 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3496 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3498 return query_info(xid, tcon, persistent_fid, volatile_fid,
3499 FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3500 sizeof(struct smb2_file_internal_info),
3501 sizeof(struct smb2_file_internal_info),
3502 (void **)&uniqueid, NULL);
3506 * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3507 * See MS-SMB2 2.2.35 and 2.2.36
3510 static int
3511 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3512 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3513 u64 persistent_fid, u64 volatile_fid,
3514 u32 completion_filter, bool watch_tree)
3516 struct smb2_change_notify_req *req;
3517 struct kvec *iov = rqst->rq_iov;
3518 unsigned int total_len;
3519 int rc;
3521 rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3522 (void **) &req, &total_len);
3523 if (rc)
3524 return rc;
3526 req->PersistentFileId = persistent_fid;
3527 req->VolatileFileId = volatile_fid;
3528 /* See note 354 of MS-SMB2, 64K max */
3529 req->OutputBufferLength =
3530 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3531 req->CompletionFilter = cpu_to_le32(completion_filter);
3532 if (watch_tree)
3533 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3534 else
3535 req->Flags = 0;
3537 iov[0].iov_base = (char *)req;
3538 iov[0].iov_len = total_len;
3540 return 0;
3544 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3545 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3546 u32 completion_filter)
3548 struct cifs_ses *ses = tcon->ses;
3549 struct TCP_Server_Info *server = cifs_pick_channel(ses);
3550 struct smb_rqst rqst;
3551 struct kvec iov[1];
3552 struct kvec rsp_iov = {NULL, 0};
3553 int resp_buftype = CIFS_NO_BUFFER;
3554 int flags = 0;
3555 int rc = 0;
3557 cifs_dbg(FYI, "change notify\n");
3558 if (!ses || !server)
3559 return -EIO;
3561 if (smb3_encryption_required(tcon))
3562 flags |= CIFS_TRANSFORM_REQ;
3564 memset(&rqst, 0, sizeof(struct smb_rqst));
3565 memset(&iov, 0, sizeof(iov));
3566 rqst.rq_iov = iov;
3567 rqst.rq_nvec = 1;
3569 rc = SMB2_notify_init(xid, &rqst, tcon, server,
3570 persistent_fid, volatile_fid,
3571 completion_filter, watch_tree);
3572 if (rc)
3573 goto cnotify_exit;
3575 trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3576 (u8)watch_tree, completion_filter);
3577 rc = cifs_send_recv(xid, ses, server,
3578 &rqst, &resp_buftype, flags, &rsp_iov);
3580 if (rc != 0) {
3581 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3582 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3583 (u8)watch_tree, completion_filter, rc);
3584 } else
3585 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3586 ses->Suid, (u8)watch_tree, completion_filter);
3588 cnotify_exit:
3589 if (rqst.rq_iov)
3590 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3591 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3592 return rc;
3598 * This is a no-op for now. We're not really interested in the reply, but
3599 * rather in the fact that the server sent one and that server->lstrp
3600 * gets updated.
3602 * FIXME: maybe we should consider checking that the reply matches request?
3604 static void
3605 smb2_echo_callback(struct mid_q_entry *mid)
3607 struct TCP_Server_Info *server = mid->callback_data;
3608 struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3609 struct cifs_credits credits = { .value = 0, .instance = 0 };
3611 if (mid->mid_state == MID_RESPONSE_RECEIVED
3612 || mid->mid_state == MID_RESPONSE_MALFORMED) {
3613 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
3614 credits.instance = server->reconnect_instance;
3617 DeleteMidQEntry(mid);
3618 add_credits(server, &credits, CIFS_ECHO_OP);
3621 void smb2_reconnect_server(struct work_struct *work)
3623 struct TCP_Server_Info *server = container_of(work,
3624 struct TCP_Server_Info, reconnect.work);
3625 struct cifs_ses *ses;
3626 struct cifs_tcon *tcon, *tcon2;
3627 struct list_head tmp_list;
3628 int tcon_exist = false;
3629 int rc;
3630 int resched = false;
3633 /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3634 mutex_lock(&server->reconnect_mutex);
3636 INIT_LIST_HEAD(&tmp_list);
3637 cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
3639 spin_lock(&cifs_tcp_ses_lock);
3640 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
3641 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3642 if (tcon->need_reconnect || tcon->need_reopen_files) {
3643 tcon->tc_count++;
3644 list_add_tail(&tcon->rlist, &tmp_list);
3645 tcon_exist = true;
3649 * IPC has the same lifetime as its session and uses its
3650 * refcount.
3652 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3653 list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3654 tcon_exist = true;
3655 ses->ses_count++;
3659 * Get the reference to server struct to be sure that the last call of
3660 * cifs_put_tcon() in the loop below won't release the server pointer.
3662 if (tcon_exist)
3663 server->srv_count++;
3665 spin_unlock(&cifs_tcp_ses_lock);
3667 list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3668 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3669 if (!rc)
3670 cifs_reopen_persistent_handles(tcon);
3671 else
3672 resched = true;
3673 list_del_init(&tcon->rlist);
3674 if (tcon->ipc)
3675 cifs_put_smb_ses(tcon->ses);
3676 else
3677 cifs_put_tcon(tcon);
3680 cifs_dbg(FYI, "Reconnecting tcons finished\n");
3681 if (resched)
3682 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3683 mutex_unlock(&server->reconnect_mutex);
3685 /* now we can safely release srv struct */
3686 if (tcon_exist)
3687 cifs_put_tcp_session(server, 1);
3691 SMB2_echo(struct TCP_Server_Info *server)
3693 struct smb2_echo_req *req;
3694 int rc = 0;
3695 struct kvec iov[1];
3696 struct smb_rqst rqst = { .rq_iov = iov,
3697 .rq_nvec = 1 };
3698 unsigned int total_len;
3700 cifs_dbg(FYI, "In echo request\n");
3702 if (server->tcpStatus == CifsNeedNegotiate) {
3703 /* No need to send echo on newly established connections */
3704 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3705 return rc;
3708 rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
3709 (void **)&req, &total_len);
3710 if (rc)
3711 return rc;
3713 req->sync_hdr.CreditRequest = cpu_to_le16(1);
3715 iov[0].iov_len = total_len;
3716 iov[0].iov_base = (char *)req;
3718 rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3719 server, CIFS_ECHO_OP, NULL);
3720 if (rc)
3721 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3723 cifs_small_buf_release(req);
3724 return rc;
3727 void
3728 SMB2_flush_free(struct smb_rqst *rqst)
3730 if (rqst && rqst->rq_iov)
3731 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3735 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3736 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3737 u64 persistent_fid, u64 volatile_fid)
3739 struct smb2_flush_req *req;
3740 struct kvec *iov = rqst->rq_iov;
3741 unsigned int total_len;
3742 int rc;
3744 rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
3745 (void **) &req, &total_len);
3746 if (rc)
3747 return rc;
3749 req->PersistentFileId = persistent_fid;
3750 req->VolatileFileId = volatile_fid;
3752 iov[0].iov_base = (char *)req;
3753 iov[0].iov_len = total_len;
3755 return 0;
3759 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3760 u64 volatile_fid)
3762 struct cifs_ses *ses = tcon->ses;
3763 struct smb_rqst rqst;
3764 struct kvec iov[1];
3765 struct kvec rsp_iov = {NULL, 0};
3766 struct TCP_Server_Info *server = cifs_pick_channel(ses);
3767 int resp_buftype = CIFS_NO_BUFFER;
3768 int flags = 0;
3769 int rc = 0;
3771 cifs_dbg(FYI, "flush\n");
3772 if (!ses || !(ses->server))
3773 return -EIO;
3775 if (smb3_encryption_required(tcon))
3776 flags |= CIFS_TRANSFORM_REQ;
3778 memset(&rqst, 0, sizeof(struct smb_rqst));
3779 memset(&iov, 0, sizeof(iov));
3780 rqst.rq_iov = iov;
3781 rqst.rq_nvec = 1;
3783 rc = SMB2_flush_init(xid, &rqst, tcon, server,
3784 persistent_fid, volatile_fid);
3785 if (rc)
3786 goto flush_exit;
3788 trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3789 rc = cifs_send_recv(xid, ses, server,
3790 &rqst, &resp_buftype, flags, &rsp_iov);
3792 if (rc != 0) {
3793 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
3794 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
3795 rc);
3796 } else
3797 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
3798 ses->Suid);
3800 flush_exit:
3801 SMB2_flush_free(&rqst);
3802 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3803 return rc;
3807 * To form a chain of read requests, any read requests after the first should
3808 * have the end_of_chain boolean set to true.
3810 static int
3811 smb2_new_read_req(void **buf, unsigned int *total_len,
3812 struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
3813 unsigned int remaining_bytes, int request_type)
3815 int rc = -EACCES;
3816 struct smb2_read_plain_req *req = NULL;
3817 struct smb2_sync_hdr *shdr;
3818 struct TCP_Server_Info *server = io_parms->server;
3820 rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
3821 (void **) &req, total_len);
3822 if (rc)
3823 return rc;
3825 if (server == NULL)
3826 return -ECONNABORTED;
3828 shdr = &req->sync_hdr;
3829 shdr->ProcessId = cpu_to_le32(io_parms->pid);
3831 req->PersistentFileId = io_parms->persistent_fid;
3832 req->VolatileFileId = io_parms->volatile_fid;
3833 req->ReadChannelInfoOffset = 0; /* reserved */
3834 req->ReadChannelInfoLength = 0; /* reserved */
3835 req->Channel = 0; /* reserved */
3836 req->MinimumCount = 0;
3837 req->Length = cpu_to_le32(io_parms->length);
3838 req->Offset = cpu_to_le64(io_parms->offset);
3840 trace_smb3_read_enter(0 /* xid */,
3841 io_parms->persistent_fid,
3842 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
3843 io_parms->offset, io_parms->length);
3844 #ifdef CONFIG_CIFS_SMB_DIRECT
3846 * If we want to do a RDMA write, fill in and append
3847 * smbd_buffer_descriptor_v1 to the end of read request
3849 if (server->rdma && rdata && !server->sign &&
3850 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
3852 struct smbd_buffer_descriptor_v1 *v1;
3853 bool need_invalidate = server->dialect == SMB30_PROT_ID;
3855 rdata->mr = smbd_register_mr(
3856 server->smbd_conn, rdata->pages,
3857 rdata->nr_pages, rdata->page_offset,
3858 rdata->tailsz, true, need_invalidate);
3859 if (!rdata->mr)
3860 return -EAGAIN;
3862 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
3863 if (need_invalidate)
3864 req->Channel = SMB2_CHANNEL_RDMA_V1;
3865 req->ReadChannelInfoOffset =
3866 cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer));
3867 req->ReadChannelInfoLength =
3868 cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
3869 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
3870 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
3871 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
3872 v1->length = cpu_to_le32(rdata->mr->mr->length);
3874 *total_len += sizeof(*v1) - 1;
3876 #endif
3877 if (request_type & CHAINED_REQUEST) {
3878 if (!(request_type & END_OF_CHAIN)) {
3879 /* next 8-byte aligned request */
3880 *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
3881 shdr->NextCommand = cpu_to_le32(*total_len);
3882 } else /* END_OF_CHAIN */
3883 shdr->NextCommand = 0;
3884 if (request_type & RELATED_REQUEST) {
3885 shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
3887 * Related requests use info from previous read request
3888 * in chain.
3890 shdr->SessionId = 0xFFFFFFFF;
3891 shdr->TreeId = 0xFFFFFFFF;
3892 req->PersistentFileId = 0xFFFFFFFF;
3893 req->VolatileFileId = 0xFFFFFFFF;
3896 if (remaining_bytes > io_parms->length)
3897 req->RemainingBytes = cpu_to_le32(remaining_bytes);
3898 else
3899 req->RemainingBytes = 0;
3901 *buf = req;
3902 return rc;
3905 static void
3906 smb2_readv_callback(struct mid_q_entry *mid)
3908 struct cifs_readdata *rdata = mid->callback_data;
3909 struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
3910 struct TCP_Server_Info *server = rdata->server;
3911 struct smb2_sync_hdr *shdr =
3912 (struct smb2_sync_hdr *)rdata->iov[0].iov_base;
3913 struct cifs_credits credits = { .value = 0, .instance = 0 };
3914 struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
3915 .rq_nvec = 1,
3916 .rq_pages = rdata->pages,
3917 .rq_offset = rdata->page_offset,
3918 .rq_npages = rdata->nr_pages,
3919 .rq_pagesz = rdata->pagesz,
3920 .rq_tailsz = rdata->tailsz };
3922 WARN_ONCE(rdata->server != mid->server,
3923 "rdata server %p != mid server %p",
3924 rdata->server, mid->server);
3926 cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
3927 __func__, mid->mid, mid->mid_state, rdata->result,
3928 rdata->bytes);
3930 switch (mid->mid_state) {
3931 case MID_RESPONSE_RECEIVED:
3932 credits.value = le16_to_cpu(shdr->CreditRequest);
3933 credits.instance = server->reconnect_instance;
3934 /* result already set, check signature */
3935 if (server->sign && !mid->decrypted) {
3936 int rc;
3938 rc = smb2_verify_signature(&rqst, server);
3939 if (rc)
3940 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
3941 rc);
3943 /* FIXME: should this be counted toward the initiating task? */
3944 task_io_account_read(rdata->got_bytes);
3945 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3946 break;
3947 case MID_REQUEST_SUBMITTED:
3948 case MID_RETRY_NEEDED:
3949 rdata->result = -EAGAIN;
3950 if (server->sign && rdata->got_bytes)
3951 /* reset bytes number since we can not check a sign */
3952 rdata->got_bytes = 0;
3953 /* FIXME: should this be counted toward the initiating task? */
3954 task_io_account_read(rdata->got_bytes);
3955 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3956 break;
3957 case MID_RESPONSE_MALFORMED:
3958 credits.value = le16_to_cpu(shdr->CreditRequest);
3959 credits.instance = server->reconnect_instance;
3960 fallthrough;
3961 default:
3962 rdata->result = -EIO;
3964 #ifdef CONFIG_CIFS_SMB_DIRECT
3966 * If this rdata has a memmory registered, the MR can be freed
3967 * MR needs to be freed as soon as I/O finishes to prevent deadlock
3968 * because they have limited number and are used for future I/Os
3970 if (rdata->mr) {
3971 smbd_deregister_mr(rdata->mr);
3972 rdata->mr = NULL;
3974 #endif
3975 if (rdata->result && rdata->result != -ENODATA) {
3976 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
3977 trace_smb3_read_err(0 /* xid */,
3978 rdata->cfile->fid.persistent_fid,
3979 tcon->tid, tcon->ses->Suid, rdata->offset,
3980 rdata->bytes, rdata->result);
3981 } else
3982 trace_smb3_read_done(0 /* xid */,
3983 rdata->cfile->fid.persistent_fid,
3984 tcon->tid, tcon->ses->Suid,
3985 rdata->offset, rdata->got_bytes);
3987 queue_work(cifsiod_wq, &rdata->work);
3988 DeleteMidQEntry(mid);
3989 add_credits(server, &credits, 0);
3992 /* smb2_async_readv - send an async read, and set up mid to handle result */
3994 smb2_async_readv(struct cifs_readdata *rdata)
3996 int rc, flags = 0;
3997 char *buf;
3998 struct smb2_sync_hdr *shdr;
3999 struct cifs_io_parms io_parms;
4000 struct smb_rqst rqst = { .rq_iov = rdata->iov,
4001 .rq_nvec = 1 };
4002 struct TCP_Server_Info *server;
4003 struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4004 unsigned int total_len;
4006 cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4007 __func__, rdata->offset, rdata->bytes);
4009 if (!rdata->server)
4010 rdata->server = cifs_pick_channel(tcon->ses);
4012 io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4013 io_parms.server = server = rdata->server;
4014 io_parms.offset = rdata->offset;
4015 io_parms.length = rdata->bytes;
4016 io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4017 io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4018 io_parms.pid = rdata->pid;
4020 rc = smb2_new_read_req(
4021 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4022 if (rc)
4023 return rc;
4025 if (smb3_encryption_required(io_parms.tcon))
4026 flags |= CIFS_TRANSFORM_REQ;
4028 rdata->iov[0].iov_base = buf;
4029 rdata->iov[0].iov_len = total_len;
4031 shdr = (struct smb2_sync_hdr *)buf;
4033 if (rdata->credits.value > 0) {
4034 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4035 SMB2_MAX_BUFFER_SIZE));
4036 shdr->CreditRequest =
4037 cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
4039 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4040 if (rc)
4041 goto async_readv_out;
4043 flags |= CIFS_HAS_CREDITS;
4046 kref_get(&rdata->refcount);
4047 rc = cifs_call_async(server, &rqst,
4048 cifs_readv_receive, smb2_readv_callback,
4049 smb3_handle_read_data, rdata, flags,
4050 &rdata->credits);
4051 if (rc) {
4052 kref_put(&rdata->refcount, cifs_readdata_release);
4053 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4054 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4055 io_parms.tcon->tid,
4056 io_parms.tcon->ses->Suid,
4057 io_parms.offset, io_parms.length, rc);
4060 async_readv_out:
4061 cifs_small_buf_release(buf);
4062 return rc;
4066 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4067 unsigned int *nbytes, char **buf, int *buf_type)
4069 struct smb_rqst rqst;
4070 int resp_buftype, rc;
4071 struct smb2_read_plain_req *req = NULL;
4072 struct smb2_read_rsp *rsp = NULL;
4073 struct kvec iov[1];
4074 struct kvec rsp_iov;
4075 unsigned int total_len;
4076 int flags = CIFS_LOG_ERROR;
4077 struct cifs_ses *ses = io_parms->tcon->ses;
4079 if (!io_parms->server)
4080 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4082 *nbytes = 0;
4083 rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4084 if (rc)
4085 return rc;
4087 if (smb3_encryption_required(io_parms->tcon))
4088 flags |= CIFS_TRANSFORM_REQ;
4090 iov[0].iov_base = (char *)req;
4091 iov[0].iov_len = total_len;
4093 memset(&rqst, 0, sizeof(struct smb_rqst));
4094 rqst.rq_iov = iov;
4095 rqst.rq_nvec = 1;
4097 rc = cifs_send_recv(xid, ses, io_parms->server,
4098 &rqst, &resp_buftype, flags, &rsp_iov);
4099 rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4101 if (rc) {
4102 if (rc != -ENODATA) {
4103 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4104 cifs_dbg(VFS, "Send error in read = %d\n", rc);
4105 trace_smb3_read_err(xid, req->PersistentFileId,
4106 io_parms->tcon->tid, ses->Suid,
4107 io_parms->offset, io_parms->length,
4108 rc);
4109 } else
4110 trace_smb3_read_done(xid, req->PersistentFileId,
4111 io_parms->tcon->tid, ses->Suid,
4112 io_parms->offset, 0);
4113 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4114 cifs_small_buf_release(req);
4115 return rc == -ENODATA ? 0 : rc;
4116 } else
4117 trace_smb3_read_done(xid, req->PersistentFileId,
4118 io_parms->tcon->tid, ses->Suid,
4119 io_parms->offset, io_parms->length);
4121 cifs_small_buf_release(req);
4123 *nbytes = le32_to_cpu(rsp->DataLength);
4124 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4125 (*nbytes > io_parms->length)) {
4126 cifs_dbg(FYI, "bad length %d for count %d\n",
4127 *nbytes, io_parms->length);
4128 rc = -EIO;
4129 *nbytes = 0;
4132 if (*buf) {
4133 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4134 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4135 } else if (resp_buftype != CIFS_NO_BUFFER) {
4136 *buf = rsp_iov.iov_base;
4137 if (resp_buftype == CIFS_SMALL_BUFFER)
4138 *buf_type = CIFS_SMALL_BUFFER;
4139 else if (resp_buftype == CIFS_LARGE_BUFFER)
4140 *buf_type = CIFS_LARGE_BUFFER;
4142 return rc;
4146 * Check the mid_state and signature on received buffer (if any), and queue the
4147 * workqueue completion task.
4149 static void
4150 smb2_writev_callback(struct mid_q_entry *mid)
4152 struct cifs_writedata *wdata = mid->callback_data;
4153 struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4154 struct TCP_Server_Info *server = wdata->server;
4155 unsigned int written;
4156 struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4157 struct cifs_credits credits = { .value = 0, .instance = 0 };
4159 WARN_ONCE(wdata->server != mid->server,
4160 "wdata server %p != mid server %p",
4161 wdata->server, mid->server);
4163 switch (mid->mid_state) {
4164 case MID_RESPONSE_RECEIVED:
4165 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4166 credits.instance = server->reconnect_instance;
4167 wdata->result = smb2_check_receive(mid, server, 0);
4168 if (wdata->result != 0)
4169 break;
4171 written = le32_to_cpu(rsp->DataLength);
4173 * Mask off high 16 bits when bytes written as returned
4174 * by the server is greater than bytes requested by the
4175 * client. OS/2 servers are known to set incorrect
4176 * CountHigh values.
4178 if (written > wdata->bytes)
4179 written &= 0xFFFF;
4181 if (written < wdata->bytes)
4182 wdata->result = -ENOSPC;
4183 else
4184 wdata->bytes = written;
4185 break;
4186 case MID_REQUEST_SUBMITTED:
4187 case MID_RETRY_NEEDED:
4188 wdata->result = -EAGAIN;
4189 break;
4190 case MID_RESPONSE_MALFORMED:
4191 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4192 credits.instance = server->reconnect_instance;
4193 fallthrough;
4194 default:
4195 wdata->result = -EIO;
4196 break;
4198 #ifdef CONFIG_CIFS_SMB_DIRECT
4200 * If this wdata has a memory registered, the MR can be freed
4201 * The number of MRs available is limited, it's important to recover
4202 * used MR as soon as I/O is finished. Hold MR longer in the later
4203 * I/O process can possibly result in I/O deadlock due to lack of MR
4204 * to send request on I/O retry
4206 if (wdata->mr) {
4207 smbd_deregister_mr(wdata->mr);
4208 wdata->mr = NULL;
4210 #endif
4211 if (wdata->result) {
4212 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4213 trace_smb3_write_err(0 /* no xid */,
4214 wdata->cfile->fid.persistent_fid,
4215 tcon->tid, tcon->ses->Suid, wdata->offset,
4216 wdata->bytes, wdata->result);
4217 if (wdata->result == -ENOSPC)
4218 pr_warn_once("Out of space writing to %s\n",
4219 tcon->treeName);
4220 } else
4221 trace_smb3_write_done(0 /* no xid */,
4222 wdata->cfile->fid.persistent_fid,
4223 tcon->tid, tcon->ses->Suid,
4224 wdata->offset, wdata->bytes);
4226 queue_work(cifsiod_wq, &wdata->work);
4227 DeleteMidQEntry(mid);
4228 add_credits(server, &credits, 0);
4231 /* smb2_async_writev - send an async write, and set up mid to handle result */
4233 smb2_async_writev(struct cifs_writedata *wdata,
4234 void (*release)(struct kref *kref))
4236 int rc = -EACCES, flags = 0;
4237 struct smb2_write_req *req = NULL;
4238 struct smb2_sync_hdr *shdr;
4239 struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4240 struct TCP_Server_Info *server = wdata->server;
4241 struct kvec iov[1];
4242 struct smb_rqst rqst = { };
4243 unsigned int total_len;
4245 if (!wdata->server)
4246 server = wdata->server = cifs_pick_channel(tcon->ses);
4248 rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4249 (void **) &req, &total_len);
4250 if (rc)
4251 return rc;
4253 if (smb3_encryption_required(tcon))
4254 flags |= CIFS_TRANSFORM_REQ;
4256 shdr = (struct smb2_sync_hdr *)req;
4257 shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
4259 req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4260 req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4261 req->WriteChannelInfoOffset = 0;
4262 req->WriteChannelInfoLength = 0;
4263 req->Channel = 0;
4264 req->Offset = cpu_to_le64(wdata->offset);
4265 req->DataOffset = cpu_to_le16(
4266 offsetof(struct smb2_write_req, Buffer));
4267 req->RemainingBytes = 0;
4269 trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4270 tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4271 #ifdef CONFIG_CIFS_SMB_DIRECT
4273 * If we want to do a server RDMA read, fill in and append
4274 * smbd_buffer_descriptor_v1 to the end of write request
4276 if (server->rdma && !server->sign && wdata->bytes >=
4277 server->smbd_conn->rdma_readwrite_threshold) {
4279 struct smbd_buffer_descriptor_v1 *v1;
4280 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4282 wdata->mr = smbd_register_mr(
4283 server->smbd_conn, wdata->pages,
4284 wdata->nr_pages, wdata->page_offset,
4285 wdata->tailsz, false, need_invalidate);
4286 if (!wdata->mr) {
4287 rc = -EAGAIN;
4288 goto async_writev_out;
4290 req->Length = 0;
4291 req->DataOffset = 0;
4292 if (wdata->nr_pages > 1)
4293 req->RemainingBytes =
4294 cpu_to_le32(
4295 (wdata->nr_pages - 1) * wdata->pagesz -
4296 wdata->page_offset + wdata->tailsz
4298 else
4299 req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4300 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4301 if (need_invalidate)
4302 req->Channel = SMB2_CHANNEL_RDMA_V1;
4303 req->WriteChannelInfoOffset =
4304 cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4305 req->WriteChannelInfoLength =
4306 cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4307 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4308 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4309 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4310 v1->length = cpu_to_le32(wdata->mr->mr->length);
4312 #endif
4313 iov[0].iov_len = total_len - 1;
4314 iov[0].iov_base = (char *)req;
4316 rqst.rq_iov = iov;
4317 rqst.rq_nvec = 1;
4318 rqst.rq_pages = wdata->pages;
4319 rqst.rq_offset = wdata->page_offset;
4320 rqst.rq_npages = wdata->nr_pages;
4321 rqst.rq_pagesz = wdata->pagesz;
4322 rqst.rq_tailsz = wdata->tailsz;
4323 #ifdef CONFIG_CIFS_SMB_DIRECT
4324 if (wdata->mr) {
4325 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4326 rqst.rq_npages = 0;
4328 #endif
4329 cifs_dbg(FYI, "async write at %llu %u bytes\n",
4330 wdata->offset, wdata->bytes);
4332 #ifdef CONFIG_CIFS_SMB_DIRECT
4333 /* For RDMA read, I/O size is in RemainingBytes not in Length */
4334 if (!wdata->mr)
4335 req->Length = cpu_to_le32(wdata->bytes);
4336 #else
4337 req->Length = cpu_to_le32(wdata->bytes);
4338 #endif
4340 if (wdata->credits.value > 0) {
4341 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4342 SMB2_MAX_BUFFER_SIZE));
4343 shdr->CreditRequest =
4344 cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
4346 rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4347 if (rc)
4348 goto async_writev_out;
4350 flags |= CIFS_HAS_CREDITS;
4353 kref_get(&wdata->refcount);
4354 rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4355 wdata, flags, &wdata->credits);
4357 if (rc) {
4358 trace_smb3_write_err(0 /* no xid */, req->PersistentFileId,
4359 tcon->tid, tcon->ses->Suid, wdata->offset,
4360 wdata->bytes, rc);
4361 kref_put(&wdata->refcount, release);
4362 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4365 async_writev_out:
4366 cifs_small_buf_release(req);
4367 return rc;
4371 * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4372 * The length field from io_parms must be at least 1 and indicates a number of
4373 * elements with data to write that begins with position 1 in iov array. All
4374 * data length is specified by count.
4377 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4378 unsigned int *nbytes, struct kvec *iov, int n_vec)
4380 struct smb_rqst rqst;
4381 int rc = 0;
4382 struct smb2_write_req *req = NULL;
4383 struct smb2_write_rsp *rsp = NULL;
4384 int resp_buftype;
4385 struct kvec rsp_iov;
4386 int flags = 0;
4387 unsigned int total_len;
4388 struct TCP_Server_Info *server;
4390 *nbytes = 0;
4392 if (n_vec < 1)
4393 return rc;
4395 if (!io_parms->server)
4396 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4397 server = io_parms->server;
4398 if (server == NULL)
4399 return -ECONNABORTED;
4401 rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4402 (void **) &req, &total_len);
4403 if (rc)
4404 return rc;
4406 if (smb3_encryption_required(io_parms->tcon))
4407 flags |= CIFS_TRANSFORM_REQ;
4409 req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
4411 req->PersistentFileId = io_parms->persistent_fid;
4412 req->VolatileFileId = io_parms->volatile_fid;
4413 req->WriteChannelInfoOffset = 0;
4414 req->WriteChannelInfoLength = 0;
4415 req->Channel = 0;
4416 req->Length = cpu_to_le32(io_parms->length);
4417 req->Offset = cpu_to_le64(io_parms->offset);
4418 req->DataOffset = cpu_to_le16(
4419 offsetof(struct smb2_write_req, Buffer));
4420 req->RemainingBytes = 0;
4422 trace_smb3_write_enter(xid, io_parms->persistent_fid,
4423 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4424 io_parms->offset, io_parms->length);
4426 iov[0].iov_base = (char *)req;
4427 /* 1 for Buffer */
4428 iov[0].iov_len = total_len - 1;
4430 memset(&rqst, 0, sizeof(struct smb_rqst));
4431 rqst.rq_iov = iov;
4432 rqst.rq_nvec = n_vec + 1;
4434 rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4435 &rqst,
4436 &resp_buftype, flags, &rsp_iov);
4437 rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4439 if (rc) {
4440 trace_smb3_write_err(xid, req->PersistentFileId,
4441 io_parms->tcon->tid,
4442 io_parms->tcon->ses->Suid,
4443 io_parms->offset, io_parms->length, rc);
4444 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4445 cifs_dbg(VFS, "Send error in write = %d\n", rc);
4446 } else {
4447 *nbytes = le32_to_cpu(rsp->DataLength);
4448 trace_smb3_write_done(xid, req->PersistentFileId,
4449 io_parms->tcon->tid,
4450 io_parms->tcon->ses->Suid,
4451 io_parms->offset, *nbytes);
4454 cifs_small_buf_release(req);
4455 free_rsp_buf(resp_buftype, rsp);
4456 return rc;
4459 int posix_info_sid_size(const void *beg, const void *end)
4461 size_t subauth;
4462 int total;
4464 if (beg + 1 > end)
4465 return -1;
4467 subauth = *(u8 *)(beg+1);
4468 if (subauth < 1 || subauth > 15)
4469 return -1;
4471 total = 1 + 1 + 6 + 4*subauth;
4472 if (beg + total > end)
4473 return -1;
4475 return total;
4478 int posix_info_parse(const void *beg, const void *end,
4479 struct smb2_posix_info_parsed *out)
4482 int total_len = 0;
4483 int sid_len;
4484 int name_len;
4485 const void *owner_sid;
4486 const void *group_sid;
4487 const void *name;
4489 /* if no end bound given, assume payload to be correct */
4490 if (!end) {
4491 const struct smb2_posix_info *p = beg;
4493 end = beg + le32_to_cpu(p->NextEntryOffset);
4494 /* last element will have a 0 offset, pick a sensible bound */
4495 if (end == beg)
4496 end += 0xFFFF;
4499 /* check base buf */
4500 if (beg + sizeof(struct smb2_posix_info) > end)
4501 return -1;
4502 total_len = sizeof(struct smb2_posix_info);
4504 /* check owner sid */
4505 owner_sid = beg + total_len;
4506 sid_len = posix_info_sid_size(owner_sid, end);
4507 if (sid_len < 0)
4508 return -1;
4509 total_len += sid_len;
4511 /* check group sid */
4512 group_sid = beg + total_len;
4513 sid_len = posix_info_sid_size(group_sid, end);
4514 if (sid_len < 0)
4515 return -1;
4516 total_len += sid_len;
4518 /* check name len */
4519 if (beg + total_len + 4 > end)
4520 return -1;
4521 name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4522 if (name_len < 1 || name_len > 0xFFFF)
4523 return -1;
4524 total_len += 4;
4526 /* check name */
4527 name = beg + total_len;
4528 if (name + name_len > end)
4529 return -1;
4530 total_len += name_len;
4532 if (out) {
4533 out->base = beg;
4534 out->size = total_len;
4535 out->name_len = name_len;
4536 out->name = name;
4537 memcpy(&out->owner, owner_sid,
4538 posix_info_sid_size(owner_sid, end));
4539 memcpy(&out->group, group_sid,
4540 posix_info_sid_size(group_sid, end));
4542 return total_len;
4545 static int posix_info_extra_size(const void *beg, const void *end)
4547 int len = posix_info_parse(beg, end, NULL);
4549 if (len < 0)
4550 return -1;
4551 return len - sizeof(struct smb2_posix_info);
4554 static unsigned int
4555 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4556 size_t size)
4558 int len;
4559 unsigned int entrycount = 0;
4560 unsigned int next_offset = 0;
4561 char *entryptr;
4562 FILE_DIRECTORY_INFO *dir_info;
4564 if (bufstart == NULL)
4565 return 0;
4567 entryptr = bufstart;
4569 while (1) {
4570 if (entryptr + next_offset < entryptr ||
4571 entryptr + next_offset > end_of_buf ||
4572 entryptr + next_offset + size > end_of_buf) {
4573 cifs_dbg(VFS, "malformed search entry would overflow\n");
4574 break;
4577 entryptr = entryptr + next_offset;
4578 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4580 if (infotype == SMB_FIND_FILE_POSIX_INFO)
4581 len = posix_info_extra_size(entryptr, end_of_buf);
4582 else
4583 len = le32_to_cpu(dir_info->FileNameLength);
4585 if (len < 0 ||
4586 entryptr + len < entryptr ||
4587 entryptr + len > end_of_buf ||
4588 entryptr + len + size > end_of_buf) {
4589 cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4590 end_of_buf);
4591 break;
4594 *lastentry = entryptr;
4595 entrycount++;
4597 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4598 if (!next_offset)
4599 break;
4602 return entrycount;
4606 * Readdir/FindFirst
4608 int SMB2_query_directory_init(const unsigned int xid,
4609 struct cifs_tcon *tcon,
4610 struct TCP_Server_Info *server,
4611 struct smb_rqst *rqst,
4612 u64 persistent_fid, u64 volatile_fid,
4613 int index, int info_level)
4615 struct smb2_query_directory_req *req;
4616 unsigned char *bufptr;
4617 __le16 asteriks = cpu_to_le16('*');
4618 unsigned int output_size = CIFSMaxBufSize -
4619 MAX_SMB2_CREATE_RESPONSE_SIZE -
4620 MAX_SMB2_CLOSE_RESPONSE_SIZE;
4621 unsigned int total_len;
4622 struct kvec *iov = rqst->rq_iov;
4623 int len, rc;
4625 rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
4626 (void **) &req, &total_len);
4627 if (rc)
4628 return rc;
4630 switch (info_level) {
4631 case SMB_FIND_FILE_DIRECTORY_INFO:
4632 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4633 break;
4634 case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4635 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4636 break;
4637 case SMB_FIND_FILE_POSIX_INFO:
4638 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4639 break;
4640 default:
4641 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4642 info_level);
4643 return -EINVAL;
4646 req->FileIndex = cpu_to_le32(index);
4647 req->PersistentFileId = persistent_fid;
4648 req->VolatileFileId = volatile_fid;
4650 len = 0x2;
4651 bufptr = req->Buffer;
4652 memcpy(bufptr, &asteriks, len);
4654 req->FileNameOffset =
4655 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4656 req->FileNameLength = cpu_to_le16(len);
4658 * BB could be 30 bytes or so longer if we used SMB2 specific
4659 * buffer lengths, but this is safe and close enough.
4661 output_size = min_t(unsigned int, output_size, server->maxBuf);
4662 output_size = min_t(unsigned int, output_size, 2 << 15);
4663 req->OutputBufferLength = cpu_to_le32(output_size);
4665 iov[0].iov_base = (char *)req;
4666 /* 1 for Buffer */
4667 iov[0].iov_len = total_len - 1;
4669 iov[1].iov_base = (char *)(req->Buffer);
4670 iov[1].iov_len = len;
4672 trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4673 tcon->ses->Suid, index, output_size);
4675 return 0;
4678 void SMB2_query_directory_free(struct smb_rqst *rqst)
4680 if (rqst && rqst->rq_iov) {
4681 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4686 smb2_parse_query_directory(struct cifs_tcon *tcon,
4687 struct kvec *rsp_iov,
4688 int resp_buftype,
4689 struct cifs_search_info *srch_inf)
4691 struct smb2_query_directory_rsp *rsp;
4692 size_t info_buf_size;
4693 char *end_of_smb;
4694 int rc;
4696 rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4698 switch (srch_inf->info_level) {
4699 case SMB_FIND_FILE_DIRECTORY_INFO:
4700 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4701 break;
4702 case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4703 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4704 break;
4705 case SMB_FIND_FILE_POSIX_INFO:
4706 /* note that posix payload are variable size */
4707 info_buf_size = sizeof(struct smb2_posix_info);
4708 break;
4709 default:
4710 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4711 srch_inf->info_level);
4712 return -EINVAL;
4715 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4716 le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4717 info_buf_size);
4718 if (rc) {
4719 cifs_tcon_dbg(VFS, "bad info payload");
4720 return rc;
4723 srch_inf->unicode = true;
4725 if (srch_inf->ntwrk_buf_start) {
4726 if (srch_inf->smallBuf)
4727 cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4728 else
4729 cifs_buf_release(srch_inf->ntwrk_buf_start);
4731 srch_inf->ntwrk_buf_start = (char *)rsp;
4732 srch_inf->srch_entries_start = srch_inf->last_entry =
4733 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4734 end_of_smb = rsp_iov->iov_len + (char *)rsp;
4736 srch_inf->entries_in_buffer = num_entries(
4737 srch_inf->info_level,
4738 srch_inf->srch_entries_start,
4739 end_of_smb,
4740 &srch_inf->last_entry,
4741 info_buf_size);
4743 srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4744 cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4745 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4746 srch_inf->srch_entries_start, srch_inf->last_entry);
4747 if (resp_buftype == CIFS_LARGE_BUFFER)
4748 srch_inf->smallBuf = false;
4749 else if (resp_buftype == CIFS_SMALL_BUFFER)
4750 srch_inf->smallBuf = true;
4751 else
4752 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
4754 return 0;
4758 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
4759 u64 persistent_fid, u64 volatile_fid, int index,
4760 struct cifs_search_info *srch_inf)
4762 struct smb_rqst rqst;
4763 struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
4764 struct smb2_query_directory_rsp *rsp = NULL;
4765 int resp_buftype = CIFS_NO_BUFFER;
4766 struct kvec rsp_iov;
4767 int rc = 0;
4768 struct cifs_ses *ses = tcon->ses;
4769 struct TCP_Server_Info *server = cifs_pick_channel(ses);
4770 int flags = 0;
4772 if (!ses || !(ses->server))
4773 return -EIO;
4775 if (smb3_encryption_required(tcon))
4776 flags |= CIFS_TRANSFORM_REQ;
4778 memset(&rqst, 0, sizeof(struct smb_rqst));
4779 memset(&iov, 0, sizeof(iov));
4780 rqst.rq_iov = iov;
4781 rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
4783 rc = SMB2_query_directory_init(xid, tcon, server,
4784 &rqst, persistent_fid,
4785 volatile_fid, index,
4786 srch_inf->info_level);
4787 if (rc)
4788 goto qdir_exit;
4790 rc = cifs_send_recv(xid, ses, server,
4791 &rqst, &resp_buftype, flags, &rsp_iov);
4792 rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
4794 if (rc) {
4795 if (rc == -ENODATA &&
4796 rsp->sync_hdr.Status == STATUS_NO_MORE_FILES) {
4797 trace_smb3_query_dir_done(xid, persistent_fid,
4798 tcon->tid, tcon->ses->Suid, index, 0);
4799 srch_inf->endOfSearch = true;
4800 rc = 0;
4801 } else {
4802 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4803 tcon->ses->Suid, index, 0, rc);
4804 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
4806 goto qdir_exit;
4809 rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
4810 srch_inf);
4811 if (rc) {
4812 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4813 tcon->ses->Suid, index, 0, rc);
4814 goto qdir_exit;
4816 resp_buftype = CIFS_NO_BUFFER;
4818 trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
4819 tcon->ses->Suid, index, srch_inf->entries_in_buffer);
4821 qdir_exit:
4822 SMB2_query_directory_free(&rqst);
4823 free_rsp_buf(resp_buftype, rsp);
4824 return rc;
4828 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4829 struct smb_rqst *rqst,
4830 u64 persistent_fid, u64 volatile_fid, u32 pid,
4831 u8 info_class, u8 info_type, u32 additional_info,
4832 void **data, unsigned int *size)
4834 struct smb2_set_info_req *req;
4835 struct kvec *iov = rqst->rq_iov;
4836 unsigned int i, total_len;
4837 int rc;
4839 rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
4840 (void **) &req, &total_len);
4841 if (rc)
4842 return rc;
4844 req->sync_hdr.ProcessId = cpu_to_le32(pid);
4845 req->InfoType = info_type;
4846 req->FileInfoClass = info_class;
4847 req->PersistentFileId = persistent_fid;
4848 req->VolatileFileId = volatile_fid;
4849 req->AdditionalInformation = cpu_to_le32(additional_info);
4851 req->BufferOffset =
4852 cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
4853 req->BufferLength = cpu_to_le32(*size);
4855 memcpy(req->Buffer, *data, *size);
4856 total_len += *size;
4858 iov[0].iov_base = (char *)req;
4859 /* 1 for Buffer */
4860 iov[0].iov_len = total_len - 1;
4862 for (i = 1; i < rqst->rq_nvec; i++) {
4863 le32_add_cpu(&req->BufferLength, size[i]);
4864 iov[i].iov_base = (char *)data[i];
4865 iov[i].iov_len = size[i];
4868 return 0;
4871 void
4872 SMB2_set_info_free(struct smb_rqst *rqst)
4874 if (rqst && rqst->rq_iov)
4875 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
4878 static int
4879 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
4880 u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
4881 u8 info_type, u32 additional_info, unsigned int num,
4882 void **data, unsigned int *size)
4884 struct smb_rqst rqst;
4885 struct smb2_set_info_rsp *rsp = NULL;
4886 struct kvec *iov;
4887 struct kvec rsp_iov;
4888 int rc = 0;
4889 int resp_buftype;
4890 struct cifs_ses *ses = tcon->ses;
4891 struct TCP_Server_Info *server = cifs_pick_channel(ses);
4892 int flags = 0;
4894 if (!ses || !server)
4895 return -EIO;
4897 if (!num)
4898 return -EINVAL;
4900 if (smb3_encryption_required(tcon))
4901 flags |= CIFS_TRANSFORM_REQ;
4903 iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
4904 if (!iov)
4905 return -ENOMEM;
4907 memset(&rqst, 0, sizeof(struct smb_rqst));
4908 rqst.rq_iov = iov;
4909 rqst.rq_nvec = num;
4911 rc = SMB2_set_info_init(tcon, server,
4912 &rqst, persistent_fid, volatile_fid, pid,
4913 info_class, info_type, additional_info,
4914 data, size);
4915 if (rc) {
4916 kfree(iov);
4917 return rc;
4921 rc = cifs_send_recv(xid, ses, server,
4922 &rqst, &resp_buftype, flags,
4923 &rsp_iov);
4924 SMB2_set_info_free(&rqst);
4925 rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
4927 if (rc != 0) {
4928 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
4929 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
4930 ses->Suid, info_class, (__u32)info_type, rc);
4933 free_rsp_buf(resp_buftype, rsp);
4934 kfree(iov);
4935 return rc;
4939 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4940 u64 volatile_fid, u32 pid, __le64 *eof)
4942 struct smb2_file_eof_info info;
4943 void *data;
4944 unsigned int size;
4946 info.EndOfFile = *eof;
4948 data = &info;
4949 size = sizeof(struct smb2_file_eof_info);
4951 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4952 pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
4953 0, 1, &data, &size);
4957 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
4958 u64 persistent_fid, u64 volatile_fid,
4959 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
4961 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4962 current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
4963 1, (void **)&pnntsd, &pacllen);
4967 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
4968 u64 persistent_fid, u64 volatile_fid,
4969 struct smb2_file_full_ea_info *buf, int len)
4971 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4972 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
4973 0, 1, (void **)&buf, &len);
4977 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
4978 const u64 persistent_fid, const u64 volatile_fid,
4979 __u8 oplock_level)
4981 struct smb_rqst rqst;
4982 int rc;
4983 struct smb2_oplock_break *req = NULL;
4984 struct cifs_ses *ses = tcon->ses;
4985 struct TCP_Server_Info *server = cifs_pick_channel(ses);
4986 int flags = CIFS_OBREAK_OP;
4987 unsigned int total_len;
4988 struct kvec iov[1];
4989 struct kvec rsp_iov;
4990 int resp_buf_type;
4992 cifs_dbg(FYI, "SMB2_oplock_break\n");
4993 rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
4994 (void **) &req, &total_len);
4995 if (rc)
4996 return rc;
4998 if (smb3_encryption_required(tcon))
4999 flags |= CIFS_TRANSFORM_REQ;
5001 req->VolatileFid = volatile_fid;
5002 req->PersistentFid = persistent_fid;
5003 req->OplockLevel = oplock_level;
5004 req->sync_hdr.CreditRequest = cpu_to_le16(1);
5006 flags |= CIFS_NO_RSP_BUF;
5008 iov[0].iov_base = (char *)req;
5009 iov[0].iov_len = total_len;
5011 memset(&rqst, 0, sizeof(struct smb_rqst));
5012 rqst.rq_iov = iov;
5013 rqst.rq_nvec = 1;
5015 rc = cifs_send_recv(xid, ses, server,
5016 &rqst, &resp_buf_type, flags, &rsp_iov);
5017 cifs_small_buf_release(req);
5019 if (rc) {
5020 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5021 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5024 return rc;
5027 void
5028 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5029 struct kstatfs *kst)
5031 kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5032 le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5033 kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5034 kst->f_bfree = kst->f_bavail =
5035 le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5036 return;
5039 static void
5040 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5041 struct kstatfs *kst)
5043 kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5044 kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5045 kst->f_bfree = le64_to_cpu(response_data->BlocksAvail);
5046 if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5047 kst->f_bavail = kst->f_bfree;
5048 else
5049 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5050 if (response_data->TotalFileNodes != cpu_to_le64(-1))
5051 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5052 if (response_data->FreeFileNodes != cpu_to_le64(-1))
5053 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5055 return;
5058 static int
5059 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5060 struct TCP_Server_Info *server,
5061 int level, int outbuf_len, u64 persistent_fid,
5062 u64 volatile_fid)
5064 int rc;
5065 struct smb2_query_info_req *req;
5066 unsigned int total_len;
5068 cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5070 if ((tcon->ses == NULL) || server == NULL)
5071 return -EIO;
5073 rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5074 (void **) &req, &total_len);
5075 if (rc)
5076 return rc;
5078 req->InfoType = SMB2_O_INFO_FILESYSTEM;
5079 req->FileInfoClass = level;
5080 req->PersistentFileId = persistent_fid;
5081 req->VolatileFileId = volatile_fid;
5082 /* 1 for pad */
5083 req->InputBufferOffset =
5084 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
5085 req->OutputBufferLength = cpu_to_le32(
5086 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
5088 iov->iov_base = (char *)req;
5089 iov->iov_len = total_len;
5090 return 0;
5094 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5095 u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5097 struct smb_rqst rqst;
5098 struct smb2_query_info_rsp *rsp = NULL;
5099 struct kvec iov;
5100 struct kvec rsp_iov;
5101 int rc = 0;
5102 int resp_buftype;
5103 struct cifs_ses *ses = tcon->ses;
5104 struct TCP_Server_Info *server = cifs_pick_channel(ses);
5105 FILE_SYSTEM_POSIX_INFO *info = NULL;
5106 int flags = 0;
5108 rc = build_qfs_info_req(&iov, tcon, server,
5109 FS_POSIX_INFORMATION,
5110 sizeof(FILE_SYSTEM_POSIX_INFO),
5111 persistent_fid, volatile_fid);
5112 if (rc)
5113 return rc;
5115 if (smb3_encryption_required(tcon))
5116 flags |= CIFS_TRANSFORM_REQ;
5118 memset(&rqst, 0, sizeof(struct smb_rqst));
5119 rqst.rq_iov = &iov;
5120 rqst.rq_nvec = 1;
5122 rc = cifs_send_recv(xid, ses, server,
5123 &rqst, &resp_buftype, flags, &rsp_iov);
5124 cifs_small_buf_release(iov.iov_base);
5125 if (rc) {
5126 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5127 goto posix_qfsinf_exit;
5129 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5131 info = (FILE_SYSTEM_POSIX_INFO *)(
5132 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5133 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5134 le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5135 sizeof(FILE_SYSTEM_POSIX_INFO));
5136 if (!rc)
5137 copy_posix_fs_info_to_kstatfs(info, fsdata);
5139 posix_qfsinf_exit:
5140 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5141 return rc;
5145 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5146 u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5148 struct smb_rqst rqst;
5149 struct smb2_query_info_rsp *rsp = NULL;
5150 struct kvec iov;
5151 struct kvec rsp_iov;
5152 int rc = 0;
5153 int resp_buftype;
5154 struct cifs_ses *ses = tcon->ses;
5155 struct TCP_Server_Info *server = cifs_pick_channel(ses);
5156 struct smb2_fs_full_size_info *info = NULL;
5157 int flags = 0;
5159 rc = build_qfs_info_req(&iov, tcon, server,
5160 FS_FULL_SIZE_INFORMATION,
5161 sizeof(struct smb2_fs_full_size_info),
5162 persistent_fid, volatile_fid);
5163 if (rc)
5164 return rc;
5166 if (smb3_encryption_required(tcon))
5167 flags |= CIFS_TRANSFORM_REQ;
5169 memset(&rqst, 0, sizeof(struct smb_rqst));
5170 rqst.rq_iov = &iov;
5171 rqst.rq_nvec = 1;
5173 rc = cifs_send_recv(xid, ses, server,
5174 &rqst, &resp_buftype, flags, &rsp_iov);
5175 cifs_small_buf_release(iov.iov_base);
5176 if (rc) {
5177 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5178 goto qfsinf_exit;
5180 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5182 info = (struct smb2_fs_full_size_info *)(
5183 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5184 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5185 le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5186 sizeof(struct smb2_fs_full_size_info));
5187 if (!rc)
5188 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5190 qfsinf_exit:
5191 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5192 return rc;
5196 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5197 u64 persistent_fid, u64 volatile_fid, int level)
5199 struct smb_rqst rqst;
5200 struct smb2_query_info_rsp *rsp = NULL;
5201 struct kvec iov;
5202 struct kvec rsp_iov;
5203 int rc = 0;
5204 int resp_buftype, max_len, min_len;
5205 struct cifs_ses *ses = tcon->ses;
5206 struct TCP_Server_Info *server = cifs_pick_channel(ses);
5207 unsigned int rsp_len, offset;
5208 int flags = 0;
5210 if (level == FS_DEVICE_INFORMATION) {
5211 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5212 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5213 } else if (level == FS_ATTRIBUTE_INFORMATION) {
5214 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5215 min_len = MIN_FS_ATTR_INFO_SIZE;
5216 } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5217 max_len = sizeof(struct smb3_fs_ss_info);
5218 min_len = sizeof(struct smb3_fs_ss_info);
5219 } else if (level == FS_VOLUME_INFORMATION) {
5220 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5221 min_len = sizeof(struct smb3_fs_vol_info);
5222 } else {
5223 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5224 return -EINVAL;
5227 rc = build_qfs_info_req(&iov, tcon, server,
5228 level, max_len,
5229 persistent_fid, volatile_fid);
5230 if (rc)
5231 return rc;
5233 if (smb3_encryption_required(tcon))
5234 flags |= CIFS_TRANSFORM_REQ;
5236 memset(&rqst, 0, sizeof(struct smb_rqst));
5237 rqst.rq_iov = &iov;
5238 rqst.rq_nvec = 1;
5240 rc = cifs_send_recv(xid, ses, server,
5241 &rqst, &resp_buftype, flags, &rsp_iov);
5242 cifs_small_buf_release(iov.iov_base);
5243 if (rc) {
5244 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5245 goto qfsattr_exit;
5247 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5249 rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5250 offset = le16_to_cpu(rsp->OutputBufferOffset);
5251 rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5252 if (rc)
5253 goto qfsattr_exit;
5255 if (level == FS_ATTRIBUTE_INFORMATION)
5256 memcpy(&tcon->fsAttrInfo, offset
5257 + (char *)rsp, min_t(unsigned int,
5258 rsp_len, max_len));
5259 else if (level == FS_DEVICE_INFORMATION)
5260 memcpy(&tcon->fsDevInfo, offset
5261 + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5262 else if (level == FS_SECTOR_SIZE_INFORMATION) {
5263 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5264 (offset + (char *)rsp);
5265 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5266 tcon->perf_sector_size =
5267 le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5268 } else if (level == FS_VOLUME_INFORMATION) {
5269 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5270 (offset + (char *)rsp);
5271 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5272 tcon->vol_create_time = vol_info->VolumeCreationTime;
5275 qfsattr_exit:
5276 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5277 return rc;
5281 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5282 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5283 const __u32 num_lock, struct smb2_lock_element *buf)
5285 struct smb_rqst rqst;
5286 int rc = 0;
5287 struct smb2_lock_req *req = NULL;
5288 struct kvec iov[2];
5289 struct kvec rsp_iov;
5290 int resp_buf_type;
5291 unsigned int count;
5292 int flags = CIFS_NO_RSP_BUF;
5293 unsigned int total_len;
5294 struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5296 cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5298 rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5299 (void **) &req, &total_len);
5300 if (rc)
5301 return rc;
5303 if (smb3_encryption_required(tcon))
5304 flags |= CIFS_TRANSFORM_REQ;
5306 req->sync_hdr.ProcessId = cpu_to_le32(pid);
5307 req->LockCount = cpu_to_le16(num_lock);
5309 req->PersistentFileId = persist_fid;
5310 req->VolatileFileId = volatile_fid;
5312 count = num_lock * sizeof(struct smb2_lock_element);
5314 iov[0].iov_base = (char *)req;
5315 iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5316 iov[1].iov_base = (char *)buf;
5317 iov[1].iov_len = count;
5319 cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5321 memset(&rqst, 0, sizeof(struct smb_rqst));
5322 rqst.rq_iov = iov;
5323 rqst.rq_nvec = 2;
5325 rc = cifs_send_recv(xid, tcon->ses, server,
5326 &rqst, &resp_buf_type, flags,
5327 &rsp_iov);
5328 cifs_small_buf_release(req);
5329 if (rc) {
5330 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5331 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5332 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5333 tcon->ses->Suid, rc);
5336 return rc;
5340 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5341 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5342 const __u64 length, const __u64 offset, const __u32 lock_flags,
5343 const bool wait)
5345 struct smb2_lock_element lock;
5347 lock.Offset = cpu_to_le64(offset);
5348 lock.Length = cpu_to_le64(length);
5349 lock.Flags = cpu_to_le32(lock_flags);
5350 if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5351 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5353 return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5357 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5358 __u8 *lease_key, const __le32 lease_state)
5360 struct smb_rqst rqst;
5361 int rc;
5362 struct smb2_lease_ack *req = NULL;
5363 struct cifs_ses *ses = tcon->ses;
5364 int flags = CIFS_OBREAK_OP;
5365 unsigned int total_len;
5366 struct kvec iov[1];
5367 struct kvec rsp_iov;
5368 int resp_buf_type;
5369 __u64 *please_key_high;
5370 __u64 *please_key_low;
5371 struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5373 cifs_dbg(FYI, "SMB2_lease_break\n");
5374 rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5375 (void **) &req, &total_len);
5376 if (rc)
5377 return rc;
5379 if (smb3_encryption_required(tcon))
5380 flags |= CIFS_TRANSFORM_REQ;
5382 req->sync_hdr.CreditRequest = cpu_to_le16(1);
5383 req->StructureSize = cpu_to_le16(36);
5384 total_len += 12;
5386 memcpy(req->LeaseKey, lease_key, 16);
5387 req->LeaseState = lease_state;
5389 flags |= CIFS_NO_RSP_BUF;
5391 iov[0].iov_base = (char *)req;
5392 iov[0].iov_len = total_len;
5394 memset(&rqst, 0, sizeof(struct smb_rqst));
5395 rqst.rq_iov = iov;
5396 rqst.rq_nvec = 1;
5398 rc = cifs_send_recv(xid, ses, server,
5399 &rqst, &resp_buf_type, flags, &rsp_iov);
5400 cifs_small_buf_release(req);
5402 please_key_low = (__u64 *)lease_key;
5403 please_key_high = (__u64 *)(lease_key+8);
5404 if (rc) {
5405 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5406 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5407 ses->Suid, *please_key_low, *please_key_high, rc);
5408 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5409 } else
5410 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5411 ses->Suid, *please_key_low, *please_key_high);
5413 return rc;