drm/panel: panel-himax-hx83102: support for csot-pna957qt1-1 MIPI-DSI panel
[drm/drm-misc.git] / fs / smb / client / smb2pdu.c
blob40ad9e79437a4ba0d8a9d4374c8b163b4de08504
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
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
13 /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
14 /* Note that there are handle based routines which must be */
15 /* treated slightly differently for reconnection purposes since we never */
16 /* want to reuse a stale file handle and only the caller knows the file info */
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/vfs.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/uaccess.h>
23 #include <linux/uuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/xattr.h>
26 #include <linux/netfs.h>
27 #include <trace/events/netfs.h>
28 #include "cifsglob.h"
29 #include "cifsacl.h"
30 #include "cifsproto.h"
31 #include "smb2proto.h"
32 #include "cifs_unicode.h"
33 #include "cifs_debug.h"
34 #include "ntlmssp.h"
35 #include "../common/smb2status.h"
36 #include "smb2glob.h"
37 #include "cifspdu.h"
38 #include "cifs_spnego.h"
39 #include "smbdirect.h"
40 #include "trace.h"
41 #ifdef CONFIG_CIFS_DFS_UPCALL
42 #include "dfs_cache.h"
43 #endif
44 #include "cached_dir.h"
45 #include "compress.h"
48 * The following table defines the expected "StructureSize" of SMB2 requests
49 * in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests.
51 * Note that commands are defined in smb2pdu.h in le16 but the array below is
52 * indexed by command in host byte order.
54 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
55 /* SMB2_NEGOTIATE */ 36,
56 /* SMB2_SESSION_SETUP */ 25,
57 /* SMB2_LOGOFF */ 4,
58 /* SMB2_TREE_CONNECT */ 9,
59 /* SMB2_TREE_DISCONNECT */ 4,
60 /* SMB2_CREATE */ 57,
61 /* SMB2_CLOSE */ 24,
62 /* SMB2_FLUSH */ 24,
63 /* SMB2_READ */ 49,
64 /* SMB2_WRITE */ 49,
65 /* SMB2_LOCK */ 48,
66 /* SMB2_IOCTL */ 57,
67 /* SMB2_CANCEL */ 4,
68 /* SMB2_ECHO */ 4,
69 /* SMB2_QUERY_DIRECTORY */ 33,
70 /* SMB2_CHANGE_NOTIFY */ 32,
71 /* SMB2_QUERY_INFO */ 41,
72 /* SMB2_SET_INFO */ 33,
73 /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
76 int smb3_encryption_required(const struct cifs_tcon *tcon)
78 if (!tcon || !tcon->ses)
79 return 0;
80 if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
81 (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
82 return 1;
83 if (tcon->seal &&
84 (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
85 return 1;
86 if (((global_secflags & CIFSSEC_MUST_SEAL) == CIFSSEC_MUST_SEAL) &&
87 (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
88 return 1;
89 return 0;
92 static void
93 smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
94 const struct cifs_tcon *tcon,
95 struct TCP_Server_Info *server)
97 struct smb3_hdr_req *smb3_hdr;
99 shdr->ProtocolId = SMB2_PROTO_NUMBER;
100 shdr->StructureSize = cpu_to_le16(64);
101 shdr->Command = smb2_cmd;
103 if (server) {
104 /* After reconnect SMB3 must set ChannelSequence on subsequent reqs */
105 if (server->dialect >= SMB30_PROT_ID) {
106 smb3_hdr = (struct smb3_hdr_req *)shdr;
108 * if primary channel is not set yet, use default
109 * channel for chan sequence num
111 if (SERVER_IS_CHAN(server))
112 smb3_hdr->ChannelSequence =
113 cpu_to_le16(server->primary_server->channel_sequence_num);
114 else
115 smb3_hdr->ChannelSequence =
116 cpu_to_le16(server->channel_sequence_num);
118 spin_lock(&server->req_lock);
119 /* Request up to 10 credits but don't go over the limit. */
120 if (server->credits >= server->max_credits)
121 shdr->CreditRequest = cpu_to_le16(0);
122 else
123 shdr->CreditRequest = cpu_to_le16(
124 min_t(int, server->max_credits -
125 server->credits, 10));
126 spin_unlock(&server->req_lock);
127 } else {
128 shdr->CreditRequest = cpu_to_le16(2);
130 shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
132 if (!tcon)
133 goto out;
135 /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
136 /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
137 if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
138 shdr->CreditCharge = cpu_to_le16(1);
139 /* else CreditCharge MBZ */
141 shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
142 /* Uid is not converted */
143 if (tcon->ses)
144 shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
147 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
148 * to pass the path on the Open SMB prefixed by \\server\share.
149 * Not sure when we would need to do the augmented path (if ever) and
150 * setting this flag breaks the SMB2 open operation since it is
151 * illegal to send an empty path name (without \\server\share prefix)
152 * when the DFS flag is set in the SMB open header. We could
153 * consider setting the flag on all operations other than open
154 * but it is safer to net set it for now.
156 /* if (tcon->share_flags & SHI1005_FLAGS_DFS)
157 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
159 if (server && server->sign && !smb3_encryption_required(tcon))
160 shdr->Flags |= SMB2_FLAGS_SIGNED;
161 out:
162 return;
165 /* helper function for code reuse */
166 static int
167 cifs_chan_skip_or_disable(struct cifs_ses *ses,
168 struct TCP_Server_Info *server,
169 bool from_reconnect)
171 struct TCP_Server_Info *pserver;
172 unsigned int chan_index;
174 if (SERVER_IS_CHAN(server)) {
175 cifs_dbg(VFS,
176 "server %s does not support multichannel anymore. Skip secondary channel\n",
177 ses->server->hostname);
179 spin_lock(&ses->chan_lock);
180 chan_index = cifs_ses_get_chan_index(ses, server);
181 if (chan_index == CIFS_INVAL_CHAN_INDEX) {
182 spin_unlock(&ses->chan_lock);
183 goto skip_terminate;
186 ses->chans[chan_index].server = NULL;
187 server->terminate = true;
188 spin_unlock(&ses->chan_lock);
191 * the above reference of server by channel
192 * needs to be dropped without holding chan_lock
193 * as cifs_put_tcp_session takes a higher lock
194 * i.e. cifs_tcp_ses_lock
196 cifs_put_tcp_session(server, from_reconnect);
198 cifs_signal_cifsd_for_reconnect(server, false);
200 /* mark primary server as needing reconnect */
201 pserver = server->primary_server;
202 cifs_signal_cifsd_for_reconnect(pserver, false);
203 skip_terminate:
204 return -EHOSTDOWN;
207 cifs_server_dbg(VFS,
208 "server does not support multichannel anymore. Disable all other channels\n");
209 cifs_disable_secondary_channels(ses);
212 return 0;
215 static int
216 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
217 struct TCP_Server_Info *server, bool from_reconnect)
219 struct cifs_ses *ses;
220 int xid;
221 int rc = 0;
224 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
225 * check for tcp and smb session status done differently
226 * for those three - in the calling routine.
228 if (tcon == NULL)
229 return 0;
231 if (smb2_command == SMB2_TREE_CONNECT)
232 return 0;
234 spin_lock(&tcon->tc_lock);
235 if (tcon->status == TID_EXITING) {
237 * only tree disconnect allowed when disconnecting ...
239 if (smb2_command != SMB2_TREE_DISCONNECT) {
240 spin_unlock(&tcon->tc_lock);
241 cifs_dbg(FYI, "can not send cmd %d while umounting\n",
242 smb2_command);
243 return -ENODEV;
246 spin_unlock(&tcon->tc_lock);
248 ses = tcon->ses;
249 if (!ses)
250 return -EIO;
251 spin_lock(&ses->ses_lock);
252 if (ses->ses_status == SES_EXITING) {
253 spin_unlock(&ses->ses_lock);
254 return -EIO;
256 spin_unlock(&ses->ses_lock);
257 if (!ses->server || !server)
258 return -EIO;
260 spin_lock(&server->srv_lock);
261 if (server->tcpStatus == CifsNeedReconnect) {
263 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
264 * here since they are implicitly done when session drops.
266 switch (smb2_command) {
268 * BB Should we keep oplock break and add flush to exceptions?
270 case SMB2_TREE_DISCONNECT:
271 case SMB2_CANCEL:
272 case SMB2_CLOSE:
273 case SMB2_OPLOCK_BREAK:
274 spin_unlock(&server->srv_lock);
275 return -EAGAIN;
279 /* if server is marked for termination, cifsd will cleanup */
280 if (server->terminate) {
281 spin_unlock(&server->srv_lock);
282 return -EHOSTDOWN;
284 spin_unlock(&server->srv_lock);
286 again:
287 rc = cifs_wait_for_server_reconnect(server, tcon->retry);
288 if (rc)
289 return rc;
291 spin_lock(&ses->chan_lock);
292 if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
293 spin_unlock(&ses->chan_lock);
294 return 0;
296 spin_unlock(&ses->chan_lock);
297 cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
298 tcon->ses->chans_need_reconnect,
299 tcon->need_reconnect);
301 mutex_lock(&ses->session_mutex);
303 * if this is called by delayed work, and the channel has been disabled
304 * in parallel, the delayed work can continue to execute in parallel
305 * there's a chance that this channel may not exist anymore
307 spin_lock(&server->srv_lock);
308 if (server->tcpStatus == CifsExiting) {
309 spin_unlock(&server->srv_lock);
310 mutex_unlock(&ses->session_mutex);
311 rc = -EHOSTDOWN;
312 goto out;
316 * Recheck after acquire mutex. If another thread is negotiating
317 * and the server never sends an answer the socket will be closed
318 * and tcpStatus set to reconnect.
320 if (server->tcpStatus == CifsNeedReconnect) {
321 spin_unlock(&server->srv_lock);
322 mutex_unlock(&ses->session_mutex);
324 if (tcon->retry)
325 goto again;
327 rc = -EHOSTDOWN;
328 goto out;
330 spin_unlock(&server->srv_lock);
333 * need to prevent multiple threads trying to simultaneously
334 * reconnect the same SMB session
336 spin_lock(&ses->ses_lock);
337 spin_lock(&ses->chan_lock);
338 if (!cifs_chan_needs_reconnect(ses, server) &&
339 ses->ses_status == SES_GOOD) {
340 spin_unlock(&ses->chan_lock);
341 spin_unlock(&ses->ses_lock);
342 /* this means that we only need to tree connect */
343 if (tcon->need_reconnect)
344 goto skip_sess_setup;
346 mutex_unlock(&ses->session_mutex);
347 goto out;
349 spin_unlock(&ses->chan_lock);
350 spin_unlock(&ses->ses_lock);
352 rc = cifs_negotiate_protocol(0, ses, server);
353 if (!rc) {
355 * if server stopped supporting multichannel
356 * and the first channel reconnected, disable all the others.
358 if (ses->chan_count > 1 &&
359 !(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
360 rc = cifs_chan_skip_or_disable(ses, server,
361 from_reconnect);
362 if (rc) {
363 mutex_unlock(&ses->session_mutex);
364 goto out;
368 rc = cifs_setup_session(0, ses, server, ses->local_nls);
369 if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED)) {
371 * Try alternate password for next reconnect (key rotation
372 * could be enabled on the server e.g.) if an alternate
373 * password is available and the current password is expired,
374 * but do not swap on non pwd related errors like host down
376 if (ses->password2)
377 swap(ses->password2, ses->password);
380 if ((rc == -EACCES) && !tcon->retry) {
381 mutex_unlock(&ses->session_mutex);
382 rc = -EHOSTDOWN;
383 goto failed;
384 } else if (rc) {
385 mutex_unlock(&ses->session_mutex);
386 goto out;
388 } else {
389 mutex_unlock(&ses->session_mutex);
390 goto out;
393 skip_sess_setup:
394 if (!tcon->need_reconnect) {
395 mutex_unlock(&ses->session_mutex);
396 goto out;
398 cifs_mark_open_files_invalid(tcon);
399 if (tcon->use_persistent)
400 tcon->need_reopen_files = true;
402 rc = cifs_tree_connect(0, tcon);
404 cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
405 if (rc) {
406 /* If sess reconnected but tcon didn't, something strange ... */
407 mutex_unlock(&ses->session_mutex);
408 cifs_dbg(VFS, "reconnect tcon failed rc = %d\n", rc);
409 goto out;
412 spin_lock(&ses->ses_lock);
413 if (ses->flags & CIFS_SES_FLAG_SCALE_CHANNELS) {
414 spin_unlock(&ses->ses_lock);
415 mutex_unlock(&ses->session_mutex);
416 goto skip_add_channels;
418 ses->flags |= CIFS_SES_FLAG_SCALE_CHANNELS;
419 spin_unlock(&ses->ses_lock);
421 if (!rc &&
422 (server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL) &&
423 server->ops->query_server_interfaces) {
424 mutex_unlock(&ses->session_mutex);
427 * query server network interfaces, in case they change
429 xid = get_xid();
430 rc = server->ops->query_server_interfaces(xid, tcon, false);
431 free_xid(xid);
433 if (rc == -EOPNOTSUPP && ses->chan_count > 1) {
435 * some servers like Azure SMB server do not advertise
436 * that multichannel has been disabled with server
437 * capabilities, rather return STATUS_NOT_IMPLEMENTED.
438 * treat this as server not supporting multichannel
441 rc = cifs_chan_skip_or_disable(ses, server,
442 from_reconnect);
443 goto skip_add_channels;
444 } else if (rc)
445 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
446 __func__, rc);
448 if (ses->chan_max > ses->chan_count &&
449 ses->iface_count &&
450 !SERVER_IS_CHAN(server)) {
451 if (ses->chan_count == 1) {
452 cifs_server_dbg(VFS, "supports multichannel now\n");
453 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
454 (SMB_INTERFACE_POLL_INTERVAL * HZ));
457 cifs_try_adding_channels(ses);
459 } else {
460 mutex_unlock(&ses->session_mutex);
463 skip_add_channels:
464 spin_lock(&ses->ses_lock);
465 ses->flags &= ~CIFS_SES_FLAG_SCALE_CHANNELS;
466 spin_unlock(&ses->ses_lock);
468 if (smb2_command != SMB2_INTERNAL_CMD)
469 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
471 atomic_inc(&tconInfoReconnectCount);
472 out:
474 * Check if handle based operation so we know whether we can continue
475 * or not without returning to caller to reset file handle.
478 * BB Is flush done by server on drop of tcp session? Should we special
479 * case it and skip above?
481 switch (smb2_command) {
482 case SMB2_FLUSH:
483 case SMB2_READ:
484 case SMB2_WRITE:
485 case SMB2_LOCK:
486 case SMB2_QUERY_DIRECTORY:
487 case SMB2_CHANGE_NOTIFY:
488 case SMB2_QUERY_INFO:
489 case SMB2_SET_INFO:
490 case SMB2_IOCTL:
491 rc = -EAGAIN;
493 failed:
494 return rc;
497 static void
498 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
499 struct TCP_Server_Info *server,
500 void *buf,
501 unsigned int *total_len)
503 struct smb2_pdu *spdu = buf;
504 /* lookup word count ie StructureSize from table */
505 __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
508 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
509 * largest operations (Create)
511 memset(buf, 0, 256);
513 smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
514 spdu->StructureSize2 = cpu_to_le16(parmsize);
516 *total_len = parmsize + sizeof(struct smb2_hdr);
520 * Allocate and return pointer to an SMB request hdr, and set basic
521 * SMB information in the SMB header. If the return code is zero, this
522 * function must have filled in request_buf pointer.
524 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
525 struct TCP_Server_Info *server,
526 void **request_buf, unsigned int *total_len)
528 /* BB eventually switch this to SMB2 specific small buf size */
529 switch (smb2_command) {
530 case SMB2_SET_INFO:
531 case SMB2_QUERY_INFO:
532 *request_buf = cifs_buf_get();
533 break;
534 default:
535 *request_buf = cifs_small_buf_get();
536 break;
538 if (*request_buf == NULL) {
539 /* BB should we add a retry in here if not a writepage? */
540 return -ENOMEM;
543 fill_small_buf(smb2_command, tcon, server,
544 (struct smb2_hdr *)(*request_buf),
545 total_len);
547 if (tcon != NULL) {
548 uint16_t com_code = le16_to_cpu(smb2_command);
549 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
550 cifs_stats_inc(&tcon->num_smbs_sent);
553 return 0;
556 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
557 struct TCP_Server_Info *server,
558 void **request_buf, unsigned int *total_len)
560 int rc;
562 rc = smb2_reconnect(smb2_command, tcon, server, false);
563 if (rc)
564 return rc;
566 return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
567 total_len);
570 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
571 struct TCP_Server_Info *server,
572 void **request_buf, unsigned int *total_len)
574 /* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
575 if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
576 return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
577 request_buf, total_len);
579 return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
580 request_buf, total_len);
583 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
585 static void
586 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
588 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
589 pneg_ctxt->DataLength = cpu_to_le16(38);
590 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
591 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
592 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
593 pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
596 static void
597 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
599 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
600 pneg_ctxt->DataLength =
601 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
602 - sizeof(struct smb2_neg_context));
603 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
604 pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
605 pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
606 pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
609 static unsigned int
610 build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
612 unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
613 unsigned short num_algs = 1; /* number of signing algorithms sent */
615 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
617 * Context Data length must be rounded to multiple of 8 for some servers
619 pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
620 sizeof(struct smb2_neg_context) +
621 (num_algs * sizeof(u16)), 8));
622 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
623 pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);
625 ctxt_len += sizeof(__le16) * num_algs;
626 ctxt_len = ALIGN(ctxt_len, 8);
627 return ctxt_len;
628 /* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
631 static void
632 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
634 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
635 if (require_gcm_256) {
636 pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
637 pneg_ctxt->CipherCount = cpu_to_le16(1);
638 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
639 } else if (enable_gcm_256) {
640 pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
641 pneg_ctxt->CipherCount = cpu_to_le16(3);
642 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
643 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
644 pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
645 } else {
646 pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
647 pneg_ctxt->CipherCount = cpu_to_le16(2);
648 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
649 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
653 static unsigned int
654 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
656 struct nls_table *cp = load_nls_default();
658 pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
660 /* copy up to max of first 100 bytes of server name to NetName field */
661 pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
662 /* context size is DataLength + minimal smb2_neg_context */
663 return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
666 static void
667 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
669 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
670 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
671 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
672 pneg_ctxt->Name[0] = 0x93;
673 pneg_ctxt->Name[1] = 0xAD;
674 pneg_ctxt->Name[2] = 0x25;
675 pneg_ctxt->Name[3] = 0x50;
676 pneg_ctxt->Name[4] = 0x9C;
677 pneg_ctxt->Name[5] = 0xB4;
678 pneg_ctxt->Name[6] = 0x11;
679 pneg_ctxt->Name[7] = 0xE7;
680 pneg_ctxt->Name[8] = 0xB4;
681 pneg_ctxt->Name[9] = 0x23;
682 pneg_ctxt->Name[10] = 0x83;
683 pneg_ctxt->Name[11] = 0xDE;
684 pneg_ctxt->Name[12] = 0x96;
685 pneg_ctxt->Name[13] = 0x8B;
686 pneg_ctxt->Name[14] = 0xCD;
687 pneg_ctxt->Name[15] = 0x7C;
690 static void
691 assemble_neg_contexts(struct smb2_negotiate_req *req,
692 struct TCP_Server_Info *server, unsigned int *total_len)
694 unsigned int ctxt_len, neg_context_count;
695 struct TCP_Server_Info *pserver;
696 char *pneg_ctxt;
697 char *hostname;
699 if (*total_len > 200) {
700 /* In case length corrupted don't want to overrun smb buffer */
701 cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
702 return;
706 * round up total_len of fixed part of SMB3 negotiate request to 8
707 * byte boundary before adding negotiate contexts
709 *total_len = ALIGN(*total_len, 8);
711 pneg_ctxt = (*total_len) + (char *)req;
712 req->NegotiateContextOffset = cpu_to_le32(*total_len);
714 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
715 ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
716 *total_len += ctxt_len;
717 pneg_ctxt += ctxt_len;
719 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
720 ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
721 *total_len += ctxt_len;
722 pneg_ctxt += ctxt_len;
725 * secondary channels don't have the hostname field populated
726 * use the hostname field in the primary channel instead
728 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
729 cifs_server_lock(pserver);
730 hostname = pserver->hostname;
731 if (hostname && (hostname[0] != 0)) {
732 ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
733 hostname);
734 *total_len += ctxt_len;
735 pneg_ctxt += ctxt_len;
736 neg_context_count = 3;
737 } else
738 neg_context_count = 2;
739 cifs_server_unlock(pserver);
741 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
742 *total_len += sizeof(struct smb2_posix_neg_context);
743 pneg_ctxt += sizeof(struct smb2_posix_neg_context);
744 neg_context_count++;
746 if (server->compression.requested) {
747 build_compression_ctxt((struct smb2_compression_capabilities_context *)
748 pneg_ctxt);
749 ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
750 *total_len += ctxt_len;
751 pneg_ctxt += ctxt_len;
752 neg_context_count++;
755 if (enable_negotiate_signing) {
756 ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
757 pneg_ctxt);
758 *total_len += ctxt_len;
759 pneg_ctxt += ctxt_len;
760 neg_context_count++;
763 /* check for and add transport_capabilities and signing capabilities */
764 req->NegotiateContextCount = cpu_to_le16(neg_context_count);
768 /* If invalid preauth context warn but use what we requested, SHA-512 */
769 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
771 unsigned int len = le16_to_cpu(ctxt->DataLength);
774 * Caller checked that DataLength remains within SMB boundary. We still
775 * need to confirm that one HashAlgorithms member is accounted for.
777 if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
778 pr_warn_once("server sent bad preauth context\n");
779 return;
780 } else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
781 pr_warn_once("server sent invalid SaltLength\n");
782 return;
784 if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
785 pr_warn_once("Invalid SMB3 hash algorithm count\n");
786 if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
787 pr_warn_once("unknown SMB3 hash algorithm\n");
790 static void decode_compress_ctx(struct TCP_Server_Info *server,
791 struct smb2_compression_capabilities_context *ctxt)
793 unsigned int len = le16_to_cpu(ctxt->DataLength);
794 __le16 alg;
796 server->compression.enabled = false;
799 * Caller checked that DataLength remains within SMB boundary. We still
800 * need to confirm that one CompressionAlgorithms member is accounted
801 * for.
803 if (len < 10) {
804 pr_warn_once("server sent bad compression cntxt\n");
805 return;
808 if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
809 pr_warn_once("invalid SMB3 compress algorithm count\n");
810 return;
813 alg = ctxt->CompressionAlgorithms[0];
815 /* 'NONE' (0) compressor type is never negotiated */
816 if (alg == 0 || le16_to_cpu(alg) > 3) {
817 pr_warn_once("invalid compression algorithm '%u'\n", alg);
818 return;
821 server->compression.alg = alg;
822 server->compression.enabled = true;
825 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
826 struct smb2_encryption_neg_context *ctxt)
828 unsigned int len = le16_to_cpu(ctxt->DataLength);
830 cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
832 * Caller checked that DataLength remains within SMB boundary. We still
833 * need to confirm that one Cipher flexible array member is accounted
834 * for.
836 if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
837 pr_warn_once("server sent bad crypto ctxt len\n");
838 return -EINVAL;
841 if (le16_to_cpu(ctxt->CipherCount) != 1) {
842 pr_warn_once("Invalid SMB3.11 cipher count\n");
843 return -EINVAL;
845 cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
846 if (require_gcm_256) {
847 if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
848 cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
849 return -EOPNOTSUPP;
851 } else if (ctxt->Ciphers[0] == 0) {
853 * e.g. if server only supported AES256_CCM (very unlikely)
854 * or server supported no encryption types or had all disabled.
855 * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
856 * in which mount requested encryption ("seal") checks later
857 * on during tree connection will return proper rc, but if
858 * seal not requested by client, since server is allowed to
859 * return 0 to indicate no supported cipher, we can't fail here
861 server->cipher_type = 0;
862 server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
863 pr_warn_once("Server does not support requested encryption types\n");
864 return 0;
865 } else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
866 (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
867 (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
868 /* server returned a cipher we didn't ask for */
869 pr_warn_once("Invalid SMB3.11 cipher returned\n");
870 return -EINVAL;
872 server->cipher_type = ctxt->Ciphers[0];
873 server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
874 return 0;
877 static void decode_signing_ctx(struct TCP_Server_Info *server,
878 struct smb2_signing_capabilities *pctxt)
880 unsigned int len = le16_to_cpu(pctxt->DataLength);
883 * Caller checked that DataLength remains within SMB boundary. We still
884 * need to confirm that one SigningAlgorithms flexible array member is
885 * accounted for.
887 if ((len < 4) || (len > 16)) {
888 pr_warn_once("server sent bad signing negcontext\n");
889 return;
891 if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
892 pr_warn_once("Invalid signing algorithm count\n");
893 return;
895 if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
896 pr_warn_once("unknown signing algorithm\n");
897 return;
900 server->signing_negotiated = true;
901 server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
902 cifs_dbg(FYI, "signing algorithm %d chosen\n",
903 server->signing_algorithm);
907 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
908 struct TCP_Server_Info *server,
909 unsigned int len_of_smb)
911 struct smb2_neg_context *pctx;
912 unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
913 unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
914 unsigned int len_of_ctxts, i;
915 int rc = 0;
917 cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
918 if (len_of_smb <= offset) {
919 cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
920 return -EINVAL;
923 len_of_ctxts = len_of_smb - offset;
925 for (i = 0; i < ctxt_cnt; i++) {
926 int clen;
927 /* check that offset is not beyond end of SMB */
928 if (len_of_ctxts < sizeof(struct smb2_neg_context))
929 break;
931 pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
932 clen = sizeof(struct smb2_neg_context)
933 + le16_to_cpu(pctx->DataLength);
935 * 2.2.4 SMB2 NEGOTIATE Response
936 * Subsequent negotiate contexts MUST appear at the first 8-byte
937 * aligned offset following the previous negotiate context.
939 if (i + 1 != ctxt_cnt)
940 clen = ALIGN(clen, 8);
941 if (clen > len_of_ctxts)
942 break;
944 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
945 decode_preauth_context(
946 (struct smb2_preauth_neg_context *)pctx);
947 else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
948 rc = decode_encrypt_ctx(server,
949 (struct smb2_encryption_neg_context *)pctx);
950 else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
951 decode_compress_ctx(server,
952 (struct smb2_compression_capabilities_context *)pctx);
953 else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
954 server->posix_ext_supported = true;
955 else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
956 decode_signing_ctx(server,
957 (struct smb2_signing_capabilities *)pctx);
958 else
959 cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
960 le16_to_cpu(pctx->ContextType));
961 if (rc)
962 break;
964 offset += clen;
965 len_of_ctxts -= clen;
967 return rc;
970 static struct create_posix *
971 create_posix_buf(umode_t mode)
973 struct create_posix *buf;
975 buf = kzalloc(sizeof(struct create_posix),
976 GFP_KERNEL);
977 if (!buf)
978 return NULL;
980 buf->ccontext.DataOffset =
981 cpu_to_le16(offsetof(struct create_posix, Mode));
982 buf->ccontext.DataLength = cpu_to_le32(4);
983 buf->ccontext.NameOffset =
984 cpu_to_le16(offsetof(struct create_posix, Name));
985 buf->ccontext.NameLength = cpu_to_le16(16);
987 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
988 buf->Name[0] = 0x93;
989 buf->Name[1] = 0xAD;
990 buf->Name[2] = 0x25;
991 buf->Name[3] = 0x50;
992 buf->Name[4] = 0x9C;
993 buf->Name[5] = 0xB4;
994 buf->Name[6] = 0x11;
995 buf->Name[7] = 0xE7;
996 buf->Name[8] = 0xB4;
997 buf->Name[9] = 0x23;
998 buf->Name[10] = 0x83;
999 buf->Name[11] = 0xDE;
1000 buf->Name[12] = 0x96;
1001 buf->Name[13] = 0x8B;
1002 buf->Name[14] = 0xCD;
1003 buf->Name[15] = 0x7C;
1004 buf->Mode = cpu_to_le32(mode);
1005 cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
1006 return buf;
1009 static int
1010 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
1012 unsigned int num = *num_iovec;
1014 iov[num].iov_base = create_posix_buf(mode);
1015 if (mode == ACL_NO_MODE)
1016 cifs_dbg(FYI, "%s: no mode\n", __func__);
1017 if (iov[num].iov_base == NULL)
1018 return -ENOMEM;
1019 iov[num].iov_len = sizeof(struct create_posix);
1020 *num_iovec = num + 1;
1021 return 0;
1027 * SMB2 Worker functions follow:
1029 * The general structure of the worker functions is:
1030 * 1) Call smb2_init (assembles SMB2 header)
1031 * 2) Initialize SMB2 command specific fields in fixed length area of SMB
1032 * 3) Call smb_sendrcv2 (sends request on socket and waits for response)
1033 * 4) Decode SMB2 command specific fields in the fixed length area
1034 * 5) Decode variable length data area (if any for this SMB2 command type)
1035 * 6) Call free smb buffer
1036 * 7) return
1041 SMB2_negotiate(const unsigned int xid,
1042 struct cifs_ses *ses,
1043 struct TCP_Server_Info *server)
1045 struct smb_rqst rqst;
1046 struct smb2_negotiate_req *req;
1047 struct smb2_negotiate_rsp *rsp;
1048 struct kvec iov[1];
1049 struct kvec rsp_iov;
1050 int rc;
1051 int resp_buftype;
1052 int blob_offset, blob_length;
1053 char *security_blob;
1054 int flags = CIFS_NEG_OP;
1055 unsigned int total_len;
1057 cifs_dbg(FYI, "Negotiate protocol\n");
1059 if (!server) {
1060 WARN(1, "%s: server is NULL!\n", __func__);
1061 return -EIO;
1064 rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
1065 (void **) &req, &total_len);
1066 if (rc)
1067 return rc;
1069 req->hdr.SessionId = 0;
1071 memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1072 memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1074 if (strcmp(server->vals->version_string,
1075 SMB3ANY_VERSION_STRING) == 0) {
1076 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1077 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1078 req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1079 req->DialectCount = cpu_to_le16(3);
1080 total_len += 6;
1081 } else if (strcmp(server->vals->version_string,
1082 SMBDEFAULT_VERSION_STRING) == 0) {
1083 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1084 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1085 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1086 req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1087 req->DialectCount = cpu_to_le16(4);
1088 total_len += 8;
1089 } else {
1090 /* otherwise send specific dialect */
1091 req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
1092 req->DialectCount = cpu_to_le16(1);
1093 total_len += 2;
1096 /* only one of SMB2 signing flags may be set in SMB2 request */
1097 if (ses->sign)
1098 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1099 else if (global_secflags & CIFSSEC_MAY_SIGN)
1100 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1101 else
1102 req->SecurityMode = 0;
1104 req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
1105 if (ses->chan_max > 1)
1106 req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1108 /* ClientGUID must be zero for SMB2.02 dialect */
1109 if (server->vals->protocol_id == SMB20_PROT_ID)
1110 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
1111 else {
1112 memcpy(req->ClientGUID, server->client_guid,
1113 SMB2_CLIENT_GUID_SIZE);
1114 if ((server->vals->protocol_id == SMB311_PROT_ID) ||
1115 (strcmp(server->vals->version_string,
1116 SMB3ANY_VERSION_STRING) == 0) ||
1117 (strcmp(server->vals->version_string,
1118 SMBDEFAULT_VERSION_STRING) == 0))
1119 assemble_neg_contexts(req, server, &total_len);
1121 iov[0].iov_base = (char *)req;
1122 iov[0].iov_len = total_len;
1124 memset(&rqst, 0, sizeof(struct smb_rqst));
1125 rqst.rq_iov = iov;
1126 rqst.rq_nvec = 1;
1128 rc = cifs_send_recv(xid, ses, server,
1129 &rqst, &resp_buftype, flags, &rsp_iov);
1130 cifs_small_buf_release(req);
1131 rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
1133 * No tcon so can't do
1134 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1136 if (rc == -EOPNOTSUPP) {
1137 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");
1138 goto neg_exit;
1139 } else if (rc != 0)
1140 goto neg_exit;
1142 rc = -EIO;
1143 if (strcmp(server->vals->version_string,
1144 SMB3ANY_VERSION_STRING) == 0) {
1145 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1146 cifs_server_dbg(VFS,
1147 "SMB2 dialect returned but not requested\n");
1148 goto neg_exit;
1149 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
1150 cifs_server_dbg(VFS,
1151 "SMB2.1 dialect returned but not requested\n");
1152 goto neg_exit;
1153 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1154 /* ops set to 3.0 by default for default so update */
1155 server->ops = &smb311_operations;
1156 server->vals = &smb311_values;
1158 } else if (strcmp(server->vals->version_string,
1159 SMBDEFAULT_VERSION_STRING) == 0) {
1160 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1161 cifs_server_dbg(VFS,
1162 "SMB2 dialect returned but not requested\n");
1163 goto neg_exit;
1164 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
1165 /* ops set to 3.0 by default for default so update */
1166 server->ops = &smb21_operations;
1167 server->vals = &smb21_values;
1168 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1169 server->ops = &smb311_operations;
1170 server->vals = &smb311_values;
1172 } else if (le16_to_cpu(rsp->DialectRevision) !=
1173 server->vals->protocol_id) {
1174 /* if requested single dialect ensure returned dialect matched */
1175 cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
1176 le16_to_cpu(rsp->DialectRevision));
1177 goto neg_exit;
1180 cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1182 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1183 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1184 else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1185 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1186 else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1187 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
1188 else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
1189 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1190 else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
1191 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1192 else {
1193 cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
1194 le16_to_cpu(rsp->DialectRevision));
1195 goto neg_exit;
1198 rc = 0;
1199 server->dialect = le16_to_cpu(rsp->DialectRevision);
1202 * Keep a copy of the hash after negprot. This hash will be
1203 * the starting hash value for all sessions made from this
1204 * server.
1206 memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
1207 SMB2_PREAUTH_HASH_SIZE);
1209 /* SMB2 only has an extended negflavor */
1210 server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1211 /* set it to the maximum buffer size value we can send with 1 credit */
1212 server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
1213 SMB2_MAX_BUFFER_SIZE);
1214 server->max_read = le32_to_cpu(rsp->MaxReadSize);
1215 server->max_write = le32_to_cpu(rsp->MaxWriteSize);
1216 server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1217 if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
1218 cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
1219 server->sec_mode);
1220 server->capabilities = le32_to_cpu(rsp->Capabilities);
1221 /* Internal types */
1222 server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1225 * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
1226 * Set the cipher type manually.
1228 if ((server->dialect == SMB30_PROT_ID ||
1229 server->dialect == SMB302_PROT_ID) &&
1230 (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1231 server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
1233 security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1234 (struct smb2_hdr *)rsp);
1236 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
1237 * for us will be
1238 * ses->sectype = RawNTLMSSP;
1239 * but for time being this is our only auth choice so doesn't matter.
1240 * We just found a server which sets blob length to zero expecting raw.
1242 if (blob_length == 0) {
1243 cifs_dbg(FYI, "missing security blob on negprot\n");
1244 server->sec_ntlmssp = true;
1247 rc = cifs_enable_signing(server, ses->sign);
1248 if (rc)
1249 goto neg_exit;
1250 if (blob_length) {
1251 rc = decode_negTokenInit(security_blob, blob_length, server);
1252 if (rc == 1)
1253 rc = 0;
1254 else if (rc == 0)
1255 rc = -EIO;
1258 if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1259 if (rsp->NegotiateContextCount)
1260 rc = smb311_decode_neg_context(rsp, server,
1261 rsp_iov.iov_len);
1262 else
1263 cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1266 if (server->cipher_type && !rc) {
1267 if (!SERVER_IS_CHAN(server)) {
1268 rc = smb3_crypto_aead_allocate(server);
1269 } else {
1270 /* For channels, just reuse the primary server crypto secmech. */
1271 server->secmech.enc = server->primary_server->secmech.enc;
1272 server->secmech.dec = server->primary_server->secmech.dec;
1275 neg_exit:
1276 free_rsp_buf(resp_buftype, rsp);
1277 return rc;
1280 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1282 int rc;
1283 struct validate_negotiate_info_req *pneg_inbuf;
1284 struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1285 u32 rsplen;
1286 u32 inbuflen; /* max of 4 dialects */
1287 struct TCP_Server_Info *server = tcon->ses->server;
1289 cifs_dbg(FYI, "validate negotiate\n");
1291 /* In SMB3.11 preauth integrity supersedes validate negotiate */
1292 if (server->dialect == SMB311_PROT_ID)
1293 return 0;
1296 * validation ioctl must be signed, so no point sending this if we
1297 * can not sign it (ie are not known user). Even if signing is not
1298 * required (enabled but not negotiated), in those cases we selectively
1299 * sign just this, the first and only signed request on a connection.
1300 * Having validation of negotiate info helps reduce attack vectors.
1302 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1303 return 0; /* validation requires signing */
1305 if (tcon->ses->user_name == NULL) {
1306 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1307 return 0; /* validation requires signing */
1310 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1311 cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1313 pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1314 if (!pneg_inbuf)
1315 return -ENOMEM;
1317 pneg_inbuf->Capabilities =
1318 cpu_to_le32(server->vals->req_capabilities);
1319 if (tcon->ses->chan_max > 1)
1320 pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1322 memcpy(pneg_inbuf->Guid, server->client_guid,
1323 SMB2_CLIENT_GUID_SIZE);
1325 if (tcon->ses->sign)
1326 pneg_inbuf->SecurityMode =
1327 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1328 else if (global_secflags & CIFSSEC_MAY_SIGN)
1329 pneg_inbuf->SecurityMode =
1330 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1331 else
1332 pneg_inbuf->SecurityMode = 0;
1335 if (strcmp(server->vals->version_string,
1336 SMB3ANY_VERSION_STRING) == 0) {
1337 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1338 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1339 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1340 pneg_inbuf->DialectCount = cpu_to_le16(3);
1341 /* SMB 2.1 not included so subtract one dialect from len */
1342 inbuflen = sizeof(*pneg_inbuf) -
1343 (sizeof(pneg_inbuf->Dialects[0]));
1344 } else if (strcmp(server->vals->version_string,
1345 SMBDEFAULT_VERSION_STRING) == 0) {
1346 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1347 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1348 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1349 pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1350 pneg_inbuf->DialectCount = cpu_to_le16(4);
1351 /* structure is big enough for 4 dialects */
1352 inbuflen = sizeof(*pneg_inbuf);
1353 } else {
1354 /* otherwise specific dialect was requested */
1355 pneg_inbuf->Dialects[0] =
1356 cpu_to_le16(server->vals->protocol_id);
1357 pneg_inbuf->DialectCount = cpu_to_le16(1);
1358 /* structure is big enough for 4 dialects, sending only 1 */
1359 inbuflen = sizeof(*pneg_inbuf) -
1360 sizeof(pneg_inbuf->Dialects[0]) * 3;
1363 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1364 FSCTL_VALIDATE_NEGOTIATE_INFO,
1365 (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1366 (char **)&pneg_rsp, &rsplen);
1367 if (rc == -EOPNOTSUPP) {
1369 * Old Windows versions or Netapp SMB server can return
1370 * not supported error. Client should accept it.
1372 cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1373 rc = 0;
1374 goto out_free_inbuf;
1375 } else if (rc != 0) {
1376 cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1377 rc);
1378 rc = -EIO;
1379 goto out_free_inbuf;
1382 rc = -EIO;
1383 if (rsplen != sizeof(*pneg_rsp)) {
1384 cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1385 rsplen);
1387 /* relax check since Mac returns max bufsize allowed on ioctl */
1388 if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1389 goto out_free_rsp;
1392 /* check validate negotiate info response matches what we got earlier */
1393 if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1394 goto vneg_out;
1396 if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1397 goto vneg_out;
1399 /* do not validate server guid because not saved at negprot time yet */
1401 if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1402 SMB2_LARGE_FILES) != server->capabilities)
1403 goto vneg_out;
1405 /* validate negotiate successful */
1406 rc = 0;
1407 cifs_dbg(FYI, "validate negotiate info successful\n");
1408 goto out_free_rsp;
1410 vneg_out:
1411 cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1412 out_free_rsp:
1413 kfree(pneg_rsp);
1414 out_free_inbuf:
1415 kfree(pneg_inbuf);
1416 return rc;
1419 enum securityEnum
1420 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1422 switch (requested) {
1423 case Kerberos:
1424 case RawNTLMSSP:
1425 return requested;
1426 case NTLMv2:
1427 return RawNTLMSSP;
1428 case Unspecified:
1429 if (server->sec_ntlmssp &&
1430 (global_secflags & CIFSSEC_MAY_NTLMSSP))
1431 return RawNTLMSSP;
1432 if ((server->sec_kerberos || server->sec_mskerberos || server->sec_iakerb) &&
1433 (global_secflags & CIFSSEC_MAY_KRB5))
1434 return Kerberos;
1435 fallthrough;
1436 default:
1437 return Unspecified;
1441 struct SMB2_sess_data {
1442 unsigned int xid;
1443 struct cifs_ses *ses;
1444 struct TCP_Server_Info *server;
1445 struct nls_table *nls_cp;
1446 void (*func)(struct SMB2_sess_data *);
1447 int result;
1448 u64 previous_session;
1450 /* we will send the SMB in three pieces:
1451 * a fixed length beginning part, an optional
1452 * SPNEGO blob (which can be zero length), and a
1453 * last part which will include the strings
1454 * and rest of bcc area. This allows us to avoid
1455 * a large buffer 17K allocation
1457 int buf0_type;
1458 struct kvec iov[2];
1461 static int
1462 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1464 int rc;
1465 struct cifs_ses *ses = sess_data->ses;
1466 struct TCP_Server_Info *server = sess_data->server;
1467 struct smb2_sess_setup_req *req;
1468 unsigned int total_len;
1469 bool is_binding = false;
1471 rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1472 (void **) &req,
1473 &total_len);
1474 if (rc)
1475 return rc;
1477 spin_lock(&ses->ses_lock);
1478 is_binding = (ses->ses_status == SES_GOOD);
1479 spin_unlock(&ses->ses_lock);
1481 if (is_binding) {
1482 req->hdr.SessionId = cpu_to_le64(ses->Suid);
1483 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1484 req->PreviousSessionId = 0;
1485 req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1486 cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1487 } else {
1488 /* First session, not a reauthenticate */
1489 req->hdr.SessionId = 0;
1491 * if reconnect, we need to send previous sess id
1492 * otherwise it is 0
1494 req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1495 req->Flags = 0; /* MBZ */
1496 cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
1497 sess_data->previous_session);
1500 /* enough to enable echos and oplocks and one max size write */
1501 if (server->credits >= server->max_credits)
1502 req->hdr.CreditRequest = cpu_to_le16(0);
1503 else
1504 req->hdr.CreditRequest = cpu_to_le16(
1505 min_t(int, server->max_credits -
1506 server->credits, 130));
1508 /* only one of SMB2 signing flags may be set in SMB2 request */
1509 if (server->sign)
1510 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1511 else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1512 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1513 else
1514 req->SecurityMode = 0;
1516 #ifdef CONFIG_CIFS_DFS_UPCALL
1517 req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1518 #else
1519 req->Capabilities = 0;
1520 #endif /* DFS_UPCALL */
1522 req->Channel = 0; /* MBZ */
1524 sess_data->iov[0].iov_base = (char *)req;
1525 /* 1 for pad */
1526 sess_data->iov[0].iov_len = total_len - 1;
1528 * This variable will be used to clear the buffer
1529 * allocated above in case of any error in the calling function.
1531 sess_data->buf0_type = CIFS_SMALL_BUFFER;
1533 return 0;
1536 static void
1537 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1539 struct kvec *iov = sess_data->iov;
1541 /* iov[1] is already freed by caller */
1542 if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1543 memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1545 free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1546 sess_data->buf0_type = CIFS_NO_BUFFER;
1549 static int
1550 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1552 int rc;
1553 struct smb_rqst rqst;
1554 struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1555 struct kvec rsp_iov = { NULL, 0 };
1557 /* Testing shows that buffer offset must be at location of Buffer[0] */
1558 req->SecurityBufferOffset =
1559 cpu_to_le16(sizeof(struct smb2_sess_setup_req));
1560 req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1562 memset(&rqst, 0, sizeof(struct smb_rqst));
1563 rqst.rq_iov = sess_data->iov;
1564 rqst.rq_nvec = 2;
1566 /* BB add code to build os and lm fields */
1567 rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1568 sess_data->server,
1569 &rqst,
1570 &sess_data->buf0_type,
1571 CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1572 cifs_small_buf_release(sess_data->iov[0].iov_base);
1573 if (rc == 0)
1574 sess_data->ses->expired_pwd = false;
1575 else if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED)) {
1576 if (sess_data->ses->expired_pwd == false)
1577 trace_smb3_key_expired(sess_data->server->hostname,
1578 sess_data->ses->user_name,
1579 sess_data->server->conn_id,
1580 &sess_data->server->dstaddr, rc);
1581 sess_data->ses->expired_pwd = true;
1584 memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1586 return rc;
1589 static int
1590 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1592 int rc = 0;
1593 struct cifs_ses *ses = sess_data->ses;
1594 struct TCP_Server_Info *server = sess_data->server;
1596 cifs_server_lock(server);
1597 if (server->ops->generate_signingkey) {
1598 rc = server->ops->generate_signingkey(ses, server);
1599 if (rc) {
1600 cifs_dbg(FYI,
1601 "SMB3 session key generation failed\n");
1602 cifs_server_unlock(server);
1603 return rc;
1606 if (!server->session_estab) {
1607 server->sequence_number = 0x2;
1608 server->session_estab = true;
1610 cifs_server_unlock(server);
1612 cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1613 return rc;
1616 #ifdef CONFIG_CIFS_UPCALL
1617 static void
1618 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1620 int rc;
1621 struct cifs_ses *ses = sess_data->ses;
1622 struct TCP_Server_Info *server = sess_data->server;
1623 struct cifs_spnego_msg *msg;
1624 struct key *spnego_key = NULL;
1625 struct smb2_sess_setup_rsp *rsp = NULL;
1626 bool is_binding = false;
1628 rc = SMB2_sess_alloc_buffer(sess_data);
1629 if (rc)
1630 goto out;
1632 spnego_key = cifs_get_spnego_key(ses, server);
1633 if (IS_ERR(spnego_key)) {
1634 rc = PTR_ERR(spnego_key);
1635 if (rc == -ENOKEY)
1636 cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1637 spnego_key = NULL;
1638 goto out;
1641 msg = spnego_key->payload.data[0];
1643 * check version field to make sure that cifs.upcall is
1644 * sending us a response in an expected form
1646 if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1647 cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1648 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1649 rc = -EKEYREJECTED;
1650 goto out_put_spnego_key;
1653 spin_lock(&ses->ses_lock);
1654 is_binding = (ses->ses_status == SES_GOOD);
1655 spin_unlock(&ses->ses_lock);
1657 /* keep session key if binding */
1658 if (!is_binding) {
1659 kfree_sensitive(ses->auth_key.response);
1660 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1661 GFP_KERNEL);
1662 if (!ses->auth_key.response) {
1663 cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1664 msg->sesskey_len);
1665 rc = -ENOMEM;
1666 goto out_put_spnego_key;
1668 ses->auth_key.len = msg->sesskey_len;
1671 sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1672 sess_data->iov[1].iov_len = msg->secblob_len;
1674 rc = SMB2_sess_sendreceive(sess_data);
1675 if (rc)
1676 goto out_put_spnego_key;
1678 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1679 /* keep session id and flags if binding */
1680 if (!is_binding) {
1681 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1682 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1685 rc = SMB2_sess_establish_session(sess_data);
1686 out_put_spnego_key:
1687 key_invalidate(spnego_key);
1688 key_put(spnego_key);
1689 if (rc) {
1690 kfree_sensitive(ses->auth_key.response);
1691 ses->auth_key.response = NULL;
1692 ses->auth_key.len = 0;
1694 out:
1695 sess_data->result = rc;
1696 sess_data->func = NULL;
1697 SMB2_sess_free_buffer(sess_data);
1699 #else
1700 static void
1701 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1703 cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1704 sess_data->result = -EOPNOTSUPP;
1705 sess_data->func = NULL;
1707 #endif
1709 static void
1710 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1712 static void
1713 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1715 int rc;
1716 struct cifs_ses *ses = sess_data->ses;
1717 struct TCP_Server_Info *server = sess_data->server;
1718 struct smb2_sess_setup_rsp *rsp = NULL;
1719 unsigned char *ntlmssp_blob = NULL;
1720 bool use_spnego = false; /* else use raw ntlmssp */
1721 u16 blob_length = 0;
1722 bool is_binding = false;
1725 * If memory allocation is successful, caller of this function
1726 * frees it.
1728 ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1729 if (!ses->ntlmssp) {
1730 rc = -ENOMEM;
1731 goto out_err;
1733 ses->ntlmssp->sesskey_per_smbsess = true;
1735 rc = SMB2_sess_alloc_buffer(sess_data);
1736 if (rc)
1737 goto out_err;
1739 rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1740 &blob_length, ses, server,
1741 sess_data->nls_cp);
1742 if (rc)
1743 goto out;
1745 if (use_spnego) {
1746 /* BB eventually need to add this */
1747 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1748 rc = -EOPNOTSUPP;
1749 goto out;
1751 sess_data->iov[1].iov_base = ntlmssp_blob;
1752 sess_data->iov[1].iov_len = blob_length;
1754 rc = SMB2_sess_sendreceive(sess_data);
1755 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1757 /* If true, rc here is expected and not an error */
1758 if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1759 rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1760 rc = 0;
1762 if (rc)
1763 goto out;
1765 if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1766 le16_to_cpu(rsp->SecurityBufferOffset)) {
1767 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1768 le16_to_cpu(rsp->SecurityBufferOffset));
1769 rc = -EIO;
1770 goto out;
1772 rc = decode_ntlmssp_challenge(rsp->Buffer,
1773 le16_to_cpu(rsp->SecurityBufferLength), ses);
1774 if (rc)
1775 goto out;
1777 cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1779 spin_lock(&ses->ses_lock);
1780 is_binding = (ses->ses_status == SES_GOOD);
1781 spin_unlock(&ses->ses_lock);
1783 /* keep existing ses id and flags if binding */
1784 if (!is_binding) {
1785 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1786 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1789 out:
1790 kfree_sensitive(ntlmssp_blob);
1791 SMB2_sess_free_buffer(sess_data);
1792 if (!rc) {
1793 sess_data->result = 0;
1794 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1795 return;
1797 out_err:
1798 kfree_sensitive(ses->ntlmssp);
1799 ses->ntlmssp = NULL;
1800 sess_data->result = rc;
1801 sess_data->func = NULL;
1804 static void
1805 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1807 int rc;
1808 struct cifs_ses *ses = sess_data->ses;
1809 struct TCP_Server_Info *server = sess_data->server;
1810 struct smb2_sess_setup_req *req;
1811 struct smb2_sess_setup_rsp *rsp = NULL;
1812 unsigned char *ntlmssp_blob = NULL;
1813 bool use_spnego = false; /* else use raw ntlmssp */
1814 u16 blob_length = 0;
1815 bool is_binding = false;
1817 rc = SMB2_sess_alloc_buffer(sess_data);
1818 if (rc)
1819 goto out;
1821 req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1822 req->hdr.SessionId = cpu_to_le64(ses->Suid);
1824 rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
1825 ses, server,
1826 sess_data->nls_cp);
1827 if (rc) {
1828 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1829 goto out;
1832 if (use_spnego) {
1833 /* BB eventually need to add this */
1834 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1835 rc = -EOPNOTSUPP;
1836 goto out;
1838 sess_data->iov[1].iov_base = ntlmssp_blob;
1839 sess_data->iov[1].iov_len = blob_length;
1841 rc = SMB2_sess_sendreceive(sess_data);
1842 if (rc)
1843 goto out;
1845 rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1847 spin_lock(&ses->ses_lock);
1848 is_binding = (ses->ses_status == SES_GOOD);
1849 spin_unlock(&ses->ses_lock);
1851 /* keep existing ses id and flags if binding */
1852 if (!is_binding) {
1853 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1854 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1857 rc = SMB2_sess_establish_session(sess_data);
1858 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1859 if (ses->server->dialect < SMB30_PROT_ID) {
1860 cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1862 * The session id is opaque in terms of endianness, so we can't
1863 * print it as a long long. we dump it as we got it on the wire
1865 cifs_dbg(VFS, "Session Id %*ph\n", (int)sizeof(ses->Suid),
1866 &ses->Suid);
1867 cifs_dbg(VFS, "Session Key %*ph\n",
1868 SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1869 cifs_dbg(VFS, "Signing Key %*ph\n",
1870 SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1872 #endif
1873 out:
1874 kfree_sensitive(ntlmssp_blob);
1875 SMB2_sess_free_buffer(sess_data);
1876 kfree_sensitive(ses->ntlmssp);
1877 ses->ntlmssp = NULL;
1878 sess_data->result = rc;
1879 sess_data->func = NULL;
1882 static int
1883 SMB2_select_sec(struct SMB2_sess_data *sess_data)
1885 int type;
1886 struct cifs_ses *ses = sess_data->ses;
1887 struct TCP_Server_Info *server = sess_data->server;
1889 type = smb2_select_sectype(server, ses->sectype);
1890 cifs_dbg(FYI, "sess setup type %d\n", type);
1891 if (type == Unspecified) {
1892 cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1893 return -EINVAL;
1896 switch (type) {
1897 case Kerberos:
1898 sess_data->func = SMB2_auth_kerberos;
1899 break;
1900 case RawNTLMSSP:
1901 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1902 break;
1903 default:
1904 cifs_dbg(VFS, "secType %d not supported!\n", type);
1905 return -EOPNOTSUPP;
1908 return 0;
1912 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1913 struct TCP_Server_Info *server,
1914 const struct nls_table *nls_cp)
1916 int rc = 0;
1917 struct SMB2_sess_data *sess_data;
1919 cifs_dbg(FYI, "Session Setup\n");
1921 if (!server) {
1922 WARN(1, "%s: server is NULL!\n", __func__);
1923 return -EIO;
1926 sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1927 if (!sess_data)
1928 return -ENOMEM;
1930 sess_data->xid = xid;
1931 sess_data->ses = ses;
1932 sess_data->server = server;
1933 sess_data->buf0_type = CIFS_NO_BUFFER;
1934 sess_data->nls_cp = (struct nls_table *) nls_cp;
1935 sess_data->previous_session = ses->Suid;
1937 rc = SMB2_select_sec(sess_data);
1938 if (rc)
1939 goto out;
1942 * Initialize the session hash with the server one.
1944 memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1945 SMB2_PREAUTH_HASH_SIZE);
1947 while (sess_data->func)
1948 sess_data->func(sess_data);
1950 if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1951 cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1952 rc = sess_data->result;
1953 out:
1954 kfree_sensitive(sess_data);
1955 return rc;
1959 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1961 struct smb_rqst rqst;
1962 struct smb2_logoff_req *req; /* response is also trivial struct */
1963 int rc = 0;
1964 struct TCP_Server_Info *server;
1965 int flags = 0;
1966 unsigned int total_len;
1967 struct kvec iov[1];
1968 struct kvec rsp_iov;
1969 int resp_buf_type;
1971 cifs_dbg(FYI, "disconnect session %p\n", ses);
1973 if (ses && (ses->server))
1974 server = ses->server;
1975 else
1976 return -EIO;
1978 /* no need to send SMB logoff if uid already closed due to reconnect */
1979 spin_lock(&ses->chan_lock);
1980 if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
1981 spin_unlock(&ses->chan_lock);
1982 goto smb2_session_already_dead;
1984 spin_unlock(&ses->chan_lock);
1986 rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
1987 (void **) &req, &total_len);
1988 if (rc)
1989 return rc;
1991 /* since no tcon, smb2_init can not do this, so do here */
1992 req->hdr.SessionId = cpu_to_le64(ses->Suid);
1994 if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1995 flags |= CIFS_TRANSFORM_REQ;
1996 else if (server->sign)
1997 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1999 flags |= CIFS_NO_RSP_BUF;
2001 iov[0].iov_base = (char *)req;
2002 iov[0].iov_len = total_len;
2004 memset(&rqst, 0, sizeof(struct smb_rqst));
2005 rqst.rq_iov = iov;
2006 rqst.rq_nvec = 1;
2008 rc = cifs_send_recv(xid, ses, ses->server,
2009 &rqst, &resp_buf_type, flags, &rsp_iov);
2010 cifs_small_buf_release(req);
2012 * No tcon so can't do
2013 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
2016 smb2_session_already_dead:
2017 return rc;
2020 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
2022 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
2025 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
2027 /* These are similar values to what Windows uses */
2028 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
2030 tcon->max_chunks = 256;
2031 tcon->max_bytes_chunk = 1048576;
2032 tcon->max_bytes_copy = 16777216;
2036 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
2037 struct cifs_tcon *tcon, const struct nls_table *cp)
2039 struct smb_rqst rqst;
2040 struct smb2_tree_connect_req *req;
2041 struct smb2_tree_connect_rsp *rsp = NULL;
2042 struct kvec iov[2];
2043 struct kvec rsp_iov = { NULL, 0 };
2044 int rc = 0;
2045 int resp_buftype;
2046 int unc_path_len;
2047 __le16 *unc_path = NULL;
2048 int flags = 0;
2049 unsigned int total_len;
2050 struct TCP_Server_Info *server = cifs_pick_channel(ses);
2052 cifs_dbg(FYI, "TCON\n");
2054 if (!server || !tree)
2055 return -EIO;
2057 unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
2058 if (unc_path == NULL)
2059 return -ENOMEM;
2061 unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
2062 if (unc_path_len <= 0) {
2063 kfree(unc_path);
2064 return -EINVAL;
2066 unc_path_len *= 2;
2068 /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
2069 tcon->tid = 0;
2070 atomic_set(&tcon->num_remote_opens, 0);
2071 rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
2072 (void **) &req, &total_len);
2073 if (rc) {
2074 kfree(unc_path);
2075 return rc;
2078 if (smb3_encryption_required(tcon))
2079 flags |= CIFS_TRANSFORM_REQ;
2081 iov[0].iov_base = (char *)req;
2082 /* 1 for pad */
2083 iov[0].iov_len = total_len - 1;
2085 /* Testing shows that buffer offset must be at location of Buffer[0] */
2086 req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
2087 req->PathLength = cpu_to_le16(unc_path_len);
2088 iov[1].iov_base = unc_path;
2089 iov[1].iov_len = unc_path_len;
2092 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
2093 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
2094 * (Samba servers don't always set the flag so also check if null user)
2096 if ((server->dialect == SMB311_PROT_ID) &&
2097 !smb3_encryption_required(tcon) &&
2098 !(ses->session_flags &
2099 (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
2100 ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
2101 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2103 memset(&rqst, 0, sizeof(struct smb_rqst));
2104 rqst.rq_iov = iov;
2105 rqst.rq_nvec = 2;
2107 /* Need 64 for max size write so ask for more in case not there yet */
2108 if (server->credits >= server->max_credits)
2109 req->hdr.CreditRequest = cpu_to_le16(0);
2110 else
2111 req->hdr.CreditRequest = cpu_to_le16(
2112 min_t(int, server->max_credits -
2113 server->credits, 64));
2115 rc = cifs_send_recv(xid, ses, server,
2116 &rqst, &resp_buftype, flags, &rsp_iov);
2117 cifs_small_buf_release(req);
2118 rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
2119 trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
2120 if ((rc != 0) || (rsp == NULL)) {
2121 cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
2122 tcon->need_reconnect = true;
2123 goto tcon_error_exit;
2126 switch (rsp->ShareType) {
2127 case SMB2_SHARE_TYPE_DISK:
2128 cifs_dbg(FYI, "connection to disk share\n");
2129 break;
2130 case SMB2_SHARE_TYPE_PIPE:
2131 tcon->pipe = true;
2132 cifs_dbg(FYI, "connection to pipe share\n");
2133 break;
2134 case SMB2_SHARE_TYPE_PRINT:
2135 tcon->print = true;
2136 cifs_dbg(FYI, "connection to printer\n");
2137 break;
2138 default:
2139 cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
2140 rc = -EOPNOTSUPP;
2141 goto tcon_error_exit;
2144 tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
2145 tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
2146 tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2147 tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
2148 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
2150 if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
2151 ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
2152 cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
2154 if (tcon->seal &&
2155 !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
2156 cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
2158 init_copy_chunk_defaults(tcon);
2159 if (server->ops->validate_negotiate)
2160 rc = server->ops->validate_negotiate(xid, tcon);
2161 if (rc == 0) /* See MS-SMB2 2.2.10 and 3.2.5.5 */
2162 if (tcon->share_flags & SMB2_SHAREFLAG_ISOLATED_TRANSPORT)
2163 server->nosharesock = true;
2164 tcon_exit:
2166 free_rsp_buf(resp_buftype, rsp);
2167 kfree(unc_path);
2168 return rc;
2170 tcon_error_exit:
2171 if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
2172 cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
2173 goto tcon_exit;
2177 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
2179 struct smb_rqst rqst;
2180 struct smb2_tree_disconnect_req *req; /* response is trivial */
2181 int rc = 0;
2182 struct cifs_ses *ses = tcon->ses;
2183 struct TCP_Server_Info *server = cifs_pick_channel(ses);
2184 int flags = 0;
2185 unsigned int total_len;
2186 struct kvec iov[1];
2187 struct kvec rsp_iov;
2188 int resp_buf_type;
2190 cifs_dbg(FYI, "Tree Disconnect\n");
2192 if (!ses || !(ses->server))
2193 return -EIO;
2195 trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2196 spin_lock(&ses->chan_lock);
2197 if ((tcon->need_reconnect) ||
2198 (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
2199 spin_unlock(&ses->chan_lock);
2200 return 0;
2202 spin_unlock(&ses->chan_lock);
2204 invalidate_all_cached_dirs(tcon);
2206 rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, server,
2207 (void **) &req,
2208 &total_len);
2209 if (rc)
2210 return rc;
2212 if (smb3_encryption_required(tcon))
2213 flags |= CIFS_TRANSFORM_REQ;
2215 flags |= CIFS_NO_RSP_BUF;
2217 iov[0].iov_base = (char *)req;
2218 iov[0].iov_len = total_len;
2220 memset(&rqst, 0, sizeof(struct smb_rqst));
2221 rqst.rq_iov = iov;
2222 rqst.rq_nvec = 1;
2224 rc = cifs_send_recv(xid, ses, server,
2225 &rqst, &resp_buf_type, flags, &rsp_iov);
2226 cifs_small_buf_release(req);
2227 if (rc) {
2228 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2229 trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
2231 trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2233 return rc;
2237 static struct create_durable *
2238 create_durable_buf(void)
2240 struct create_durable *buf;
2242 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2243 if (!buf)
2244 return NULL;
2246 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2247 (struct create_durable, Data));
2248 buf->ccontext.DataLength = cpu_to_le32(16);
2249 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2250 (struct create_durable, Name));
2251 buf->ccontext.NameLength = cpu_to_le16(4);
2252 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2253 buf->Name[0] = 'D';
2254 buf->Name[1] = 'H';
2255 buf->Name[2] = 'n';
2256 buf->Name[3] = 'Q';
2257 return buf;
2260 static struct create_durable *
2261 create_reconnect_durable_buf(struct cifs_fid *fid)
2263 struct create_durable *buf;
2265 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2266 if (!buf)
2267 return NULL;
2269 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2270 (struct create_durable, Data));
2271 buf->ccontext.DataLength = cpu_to_le32(16);
2272 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2273 (struct create_durable, Name));
2274 buf->ccontext.NameLength = cpu_to_le16(4);
2275 buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2276 buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2277 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2278 buf->Name[0] = 'D';
2279 buf->Name[1] = 'H';
2280 buf->Name[2] = 'n';
2281 buf->Name[3] = 'C';
2282 return buf;
2285 static void
2286 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2288 struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2290 cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2291 pdisk_id->DiskFileId, pdisk_id->VolumeId);
2292 buf->IndexNumber = pdisk_id->DiskFileId;
2295 static void
2296 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2297 struct create_posix_rsp *posix)
2299 int sid_len;
2300 u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2301 u8 *end = beg + le32_to_cpu(cc->DataLength);
2302 u8 *sid;
2304 memset(posix, 0, sizeof(*posix));
2306 posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2307 posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2308 posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2310 sid = beg + 12;
2311 sid_len = posix_info_sid_size(sid, end);
2312 if (sid_len < 0) {
2313 cifs_dbg(VFS, "bad owner sid in posix create response\n");
2314 return;
2316 memcpy(&posix->owner, sid, sid_len);
2318 sid = sid + sid_len;
2319 sid_len = posix_info_sid_size(sid, end);
2320 if (sid_len < 0) {
2321 cifs_dbg(VFS, "bad group sid in posix create response\n");
2322 return;
2324 memcpy(&posix->group, sid, sid_len);
2326 cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2327 posix->nlink, posix->mode, posix->reparse_tag);
2330 int smb2_parse_contexts(struct TCP_Server_Info *server,
2331 struct kvec *rsp_iov,
2332 unsigned int *epoch,
2333 char *lease_key, __u8 *oplock,
2334 struct smb2_file_all_info *buf,
2335 struct create_posix_rsp *posix)
2337 struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2338 struct create_context *cc;
2339 size_t rem, off, len;
2340 size_t doff, dlen;
2341 size_t noff, nlen;
2342 char *name;
2343 static const char smb3_create_tag_posix[] = {
2344 0x93, 0xAD, 0x25, 0x50, 0x9C,
2345 0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2346 0xDE, 0x96, 0x8B, 0xCD, 0x7C
2349 *oplock = 0;
2351 off = le32_to_cpu(rsp->CreateContextsOffset);
2352 rem = le32_to_cpu(rsp->CreateContextsLength);
2353 if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
2354 return -EINVAL;
2355 cc = (struct create_context *)((u8 *)rsp + off);
2357 /* Initialize inode number to 0 in case no valid data in qfid context */
2358 if (buf)
2359 buf->IndexNumber = 0;
2361 while (rem >= sizeof(*cc)) {
2362 doff = le16_to_cpu(cc->DataOffset);
2363 dlen = le32_to_cpu(cc->DataLength);
2364 if (check_add_overflow(doff, dlen, &len) || len > rem)
2365 return -EINVAL;
2367 noff = le16_to_cpu(cc->NameOffset);
2368 nlen = le16_to_cpu(cc->NameLength);
2369 if (noff + nlen > doff)
2370 return -EINVAL;
2372 name = (char *)cc + noff;
2373 switch (nlen) {
2374 case 4:
2375 if (!strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
2376 *oplock = server->ops->parse_lease_buf(cc, epoch,
2377 lease_key);
2378 } else if (buf &&
2379 !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
2380 parse_query_id_ctxt(cc, buf);
2382 break;
2383 case 16:
2384 if (posix && !memcmp(name, smb3_create_tag_posix, 16))
2385 parse_posix_ctxt(cc, buf, posix);
2386 break;
2387 default:
2388 cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
2389 __func__, nlen, dlen);
2390 if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
2391 cifs_dump_mem("context data: ", cc, dlen);
2392 break;
2395 off = le32_to_cpu(cc->Next);
2396 if (!off)
2397 break;
2398 if (check_sub_overflow(rem, off, &rem))
2399 return -EINVAL;
2400 cc = (struct create_context *)((u8 *)cc + off);
2403 if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2404 *oplock = rsp->OplockLevel;
2406 return 0;
2409 static int
2410 add_lease_context(struct TCP_Server_Info *server,
2411 struct smb2_create_req *req,
2412 struct kvec *iov,
2413 unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2415 unsigned int num = *num_iovec;
2417 iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2418 if (iov[num].iov_base == NULL)
2419 return -ENOMEM;
2420 iov[num].iov_len = server->vals->create_lease_size;
2421 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2422 *num_iovec = num + 1;
2423 return 0;
2426 static struct create_durable_v2 *
2427 create_durable_v2_buf(struct cifs_open_parms *oparms)
2429 struct cifs_fid *pfid = oparms->fid;
2430 struct create_durable_v2 *buf;
2432 buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2433 if (!buf)
2434 return NULL;
2436 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2437 (struct create_durable_v2, dcontext));
2438 buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2439 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2440 (struct create_durable_v2, Name));
2441 buf->ccontext.NameLength = cpu_to_le16(4);
2444 * NB: Handle timeout defaults to 0, which allows server to choose
2445 * (most servers default to 120 seconds) and most clients default to 0.
2446 * This can be overridden at mount ("handletimeout=") if the user wants
2447 * a different persistent (or resilient) handle timeout for all opens
2448 * on a particular SMB3 mount.
2450 buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2451 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2453 /* for replay, we should not overwrite the existing create guid */
2454 if (!oparms->replay) {
2455 generate_random_uuid(buf->dcontext.CreateGuid);
2456 memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2457 } else
2458 memcpy(buf->dcontext.CreateGuid, pfid->create_guid, 16);
2460 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2461 buf->Name[0] = 'D';
2462 buf->Name[1] = 'H';
2463 buf->Name[2] = '2';
2464 buf->Name[3] = 'Q';
2465 return buf;
2468 static struct create_durable_handle_reconnect_v2 *
2469 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2471 struct create_durable_handle_reconnect_v2 *buf;
2473 buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2474 GFP_KERNEL);
2475 if (!buf)
2476 return NULL;
2478 buf->ccontext.DataOffset =
2479 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2480 dcontext));
2481 buf->ccontext.DataLength =
2482 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2483 buf->ccontext.NameOffset =
2484 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2485 Name));
2486 buf->ccontext.NameLength = cpu_to_le16(4);
2488 buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2489 buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2490 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2491 memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2493 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2494 buf->Name[0] = 'D';
2495 buf->Name[1] = 'H';
2496 buf->Name[2] = '2';
2497 buf->Name[3] = 'C';
2498 return buf;
2501 static int
2502 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2503 struct cifs_open_parms *oparms)
2505 unsigned int num = *num_iovec;
2507 iov[num].iov_base = create_durable_v2_buf(oparms);
2508 if (iov[num].iov_base == NULL)
2509 return -ENOMEM;
2510 iov[num].iov_len = sizeof(struct create_durable_v2);
2511 *num_iovec = num + 1;
2512 return 0;
2515 static int
2516 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2517 struct cifs_open_parms *oparms)
2519 unsigned int num = *num_iovec;
2521 /* indicate that we don't need to relock the file */
2522 oparms->reconnect = false;
2524 iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2525 if (iov[num].iov_base == NULL)
2526 return -ENOMEM;
2527 iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2528 *num_iovec = num + 1;
2529 return 0;
2532 static int
2533 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2534 struct cifs_open_parms *oparms, bool use_persistent)
2536 unsigned int num = *num_iovec;
2538 if (use_persistent) {
2539 if (oparms->reconnect)
2540 return add_durable_reconnect_v2_context(iov, num_iovec,
2541 oparms);
2542 else
2543 return add_durable_v2_context(iov, num_iovec, oparms);
2546 if (oparms->reconnect) {
2547 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2548 /* indicate that we don't need to relock the file */
2549 oparms->reconnect = false;
2550 } else
2551 iov[num].iov_base = create_durable_buf();
2552 if (iov[num].iov_base == NULL)
2553 return -ENOMEM;
2554 iov[num].iov_len = sizeof(struct create_durable);
2555 *num_iovec = num + 1;
2556 return 0;
2559 /* See MS-SMB2 2.2.13.2.7 */
2560 static struct crt_twarp_ctxt *
2561 create_twarp_buf(__u64 timewarp)
2563 struct crt_twarp_ctxt *buf;
2565 buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2566 if (!buf)
2567 return NULL;
2569 buf->ccontext.DataOffset = cpu_to_le16(offsetof
2570 (struct crt_twarp_ctxt, Timestamp));
2571 buf->ccontext.DataLength = cpu_to_le32(8);
2572 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2573 (struct crt_twarp_ctxt, Name));
2574 buf->ccontext.NameLength = cpu_to_le16(4);
2575 /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2576 buf->Name[0] = 'T';
2577 buf->Name[1] = 'W';
2578 buf->Name[2] = 'r';
2579 buf->Name[3] = 'p';
2580 buf->Timestamp = cpu_to_le64(timewarp);
2581 return buf;
2584 /* See MS-SMB2 2.2.13.2.7 */
2585 static int
2586 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2588 unsigned int num = *num_iovec;
2590 iov[num].iov_base = create_twarp_buf(timewarp);
2591 if (iov[num].iov_base == NULL)
2592 return -ENOMEM;
2593 iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2594 *num_iovec = num + 1;
2595 return 0;
2598 /* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2599 static void setup_owner_group_sids(char *buf)
2601 struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2603 /* Populate the user ownership fields S-1-5-88-1 */
2604 sids->owner.Revision = 1;
2605 sids->owner.NumAuth = 3;
2606 sids->owner.Authority[5] = 5;
2607 sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2608 sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2609 sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2611 /* Populate the group ownership fields S-1-5-88-2 */
2612 sids->group.Revision = 1;
2613 sids->group.NumAuth = 3;
2614 sids->group.Authority[5] = 5;
2615 sids->group.SubAuthorities[0] = cpu_to_le32(88);
2616 sids->group.SubAuthorities[1] = cpu_to_le32(2);
2617 sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2619 cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2622 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2623 static struct crt_sd_ctxt *
2624 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2626 struct crt_sd_ctxt *buf;
2627 __u8 *ptr, *aclptr;
2628 unsigned int acelen, acl_size, ace_count;
2629 unsigned int owner_offset = 0;
2630 unsigned int group_offset = 0;
2631 struct smb3_acl acl = {};
2633 *len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct smb_ace) * 4), 8);
2635 if (set_owner) {
2636 /* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2637 *len += sizeof(struct owner_group_sids);
2640 buf = kzalloc(*len, GFP_KERNEL);
2641 if (buf == NULL)
2642 return buf;
2644 ptr = (__u8 *)&buf[1];
2645 if (set_owner) {
2646 /* offset fields are from beginning of security descriptor not of create context */
2647 owner_offset = ptr - (__u8 *)&buf->sd;
2648 buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2649 group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2650 buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2652 setup_owner_group_sids(ptr);
2653 ptr += sizeof(struct owner_group_sids);
2654 } else {
2655 buf->sd.OffsetOwner = 0;
2656 buf->sd.OffsetGroup = 0;
2659 buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2660 buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2661 buf->ccontext.NameLength = cpu_to_le16(4);
2662 /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2663 buf->Name[0] = 'S';
2664 buf->Name[1] = 'e';
2665 buf->Name[2] = 'c';
2666 buf->Name[3] = 'D';
2667 buf->sd.Revision = 1; /* Must be one see MS-DTYP 2.4.6 */
2670 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2671 * and "DP" ie the DACL is present
2673 buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2675 /* offset owner, group and Sbz1 and SACL are all zero */
2676 buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2677 /* Ship the ACL for now. we will copy it into buf later. */
2678 aclptr = ptr;
2679 ptr += sizeof(struct smb3_acl);
2681 /* create one ACE to hold the mode embedded in reserved special SID */
2682 acelen = setup_special_mode_ACE((struct smb_ace *)ptr, false, (__u64)mode);
2683 ptr += acelen;
2684 acl_size = acelen + sizeof(struct smb3_acl);
2685 ace_count = 1;
2687 if (set_owner) {
2688 /* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2689 acelen = setup_special_user_owner_ACE((struct smb_ace *)ptr);
2690 ptr += acelen;
2691 acl_size += acelen;
2692 ace_count += 1;
2695 /* and one more ACE to allow access for authenticated users */
2696 acelen = setup_authusers_ACE((struct smb_ace *)ptr);
2697 ptr += acelen;
2698 acl_size += acelen;
2699 ace_count += 1;
2701 acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2702 acl.AclSize = cpu_to_le16(acl_size);
2703 acl.AceCount = cpu_to_le16(ace_count);
2704 /* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2705 memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2707 buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2708 *len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2710 return buf;
2713 static int
2714 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2716 unsigned int num = *num_iovec;
2717 unsigned int len = 0;
2719 iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2720 if (iov[num].iov_base == NULL)
2721 return -ENOMEM;
2722 iov[num].iov_len = len;
2723 *num_iovec = num + 1;
2724 return 0;
2727 static struct crt_query_id_ctxt *
2728 create_query_id_buf(void)
2730 struct crt_query_id_ctxt *buf;
2732 buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2733 if (!buf)
2734 return NULL;
2736 buf->ccontext.DataOffset = cpu_to_le16(0);
2737 buf->ccontext.DataLength = cpu_to_le32(0);
2738 buf->ccontext.NameOffset = cpu_to_le16(offsetof
2739 (struct crt_query_id_ctxt, Name));
2740 buf->ccontext.NameLength = cpu_to_le16(4);
2741 /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2742 buf->Name[0] = 'Q';
2743 buf->Name[1] = 'F';
2744 buf->Name[2] = 'i';
2745 buf->Name[3] = 'd';
2746 return buf;
2749 /* See MS-SMB2 2.2.13.2.9 */
2750 static int
2751 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2753 unsigned int num = *num_iovec;
2755 iov[num].iov_base = create_query_id_buf();
2756 if (iov[num].iov_base == NULL)
2757 return -ENOMEM;
2758 iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2759 *num_iovec = num + 1;
2760 return 0;
2763 static void add_ea_context(struct cifs_open_parms *oparms,
2764 struct kvec *rq_iov, unsigned int *num_iovs)
2766 struct kvec *iov = oparms->ea_cctx;
2768 if (iov && iov->iov_base && iov->iov_len) {
2769 rq_iov[(*num_iovs)++] = *iov;
2770 memset(iov, 0, sizeof(*iov));
2774 static int
2775 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2776 const char *treename, const __le16 *path)
2778 int treename_len, path_len;
2779 struct nls_table *cp;
2780 const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2783 * skip leading "\\"
2785 treename_len = strlen(treename);
2786 if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2787 return -EINVAL;
2789 treename += 2;
2790 treename_len -= 2;
2792 path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2794 /* make room for one path separator only if @path isn't empty */
2795 *out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2798 * final path needs to be 8-byte aligned as specified in
2799 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2801 *out_size = round_up(*out_len * sizeof(__le16), 8);
2802 *out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2803 if (!*out_path)
2804 return -ENOMEM;
2806 cp = load_nls_default();
2807 cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2809 /* Do not append the separator if the path is empty */
2810 if (path[0] != cpu_to_le16(0x0000)) {
2811 UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
2812 UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2815 unload_nls(cp);
2817 return 0;
2820 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2821 umode_t mode, struct cifs_tcon *tcon,
2822 const char *full_path,
2823 struct cifs_sb_info *cifs_sb)
2825 struct smb_rqst rqst;
2826 struct smb2_create_req *req;
2827 struct smb2_create_rsp *rsp = NULL;
2828 struct cifs_ses *ses = tcon->ses;
2829 struct kvec iov[3]; /* make sure at least one for each open context */
2830 struct kvec rsp_iov = {NULL, 0};
2831 int resp_buftype;
2832 int uni_path_len;
2833 __le16 *copy_path = NULL;
2834 int copy_size;
2835 int rc = 0;
2836 unsigned int n_iov = 2;
2837 __u32 file_attributes = 0;
2838 char *pc_buf = NULL;
2839 int flags = 0;
2840 unsigned int total_len;
2841 __le16 *utf16_path = NULL;
2842 struct TCP_Server_Info *server;
2843 int retries = 0, cur_sleep = 1;
2845 replay_again:
2846 /* reinitialize for possible replay */
2847 flags = 0;
2848 n_iov = 2;
2849 server = cifs_pick_channel(ses);
2851 cifs_dbg(FYI, "mkdir\n");
2853 /* resource #1: path allocation */
2854 utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2855 if (!utf16_path)
2856 return -ENOMEM;
2858 if (!ses || !server) {
2859 rc = -EIO;
2860 goto err_free_path;
2863 /* resource #2: request */
2864 rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2865 (void **) &req, &total_len);
2866 if (rc)
2867 goto err_free_path;
2870 if (smb3_encryption_required(tcon))
2871 flags |= CIFS_TRANSFORM_REQ;
2873 req->ImpersonationLevel = IL_IMPERSONATION;
2874 req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2875 /* File attributes ignored on open (used in create though) */
2876 req->FileAttributes = cpu_to_le32(file_attributes);
2877 req->ShareAccess = FILE_SHARE_ALL_LE;
2878 req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2879 req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2881 iov[0].iov_base = (char *)req;
2882 /* -1 since last byte is buf[0] which is sent below (path) */
2883 iov[0].iov_len = total_len - 1;
2885 req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2887 /* [MS-SMB2] 2.2.13 NameOffset:
2888 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2889 * the SMB2 header, the file name includes a prefix that will
2890 * be processed during DFS name normalization as specified in
2891 * section 3.3.5.9. Otherwise, the file name is relative to
2892 * the share that is identified by the TreeId in the SMB2
2893 * header.
2895 if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2896 int name_len;
2898 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2899 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2900 &name_len,
2901 tcon->tree_name, utf16_path);
2902 if (rc)
2903 goto err_free_req;
2905 req->NameLength = cpu_to_le16(name_len * 2);
2906 uni_path_len = copy_size;
2907 /* free before overwriting resource */
2908 kfree(utf16_path);
2909 utf16_path = copy_path;
2910 } else {
2911 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2912 /* MUST set path len (NameLength) to 0 opening root of share */
2913 req->NameLength = cpu_to_le16(uni_path_len - 2);
2914 if (uni_path_len % 8 != 0) {
2915 copy_size = roundup(uni_path_len, 8);
2916 copy_path = kzalloc(copy_size, GFP_KERNEL);
2917 if (!copy_path) {
2918 rc = -ENOMEM;
2919 goto err_free_req;
2921 memcpy((char *)copy_path, (const char *)utf16_path,
2922 uni_path_len);
2923 uni_path_len = copy_size;
2924 /* free before overwriting resource */
2925 kfree(utf16_path);
2926 utf16_path = copy_path;
2930 iov[1].iov_len = uni_path_len;
2931 iov[1].iov_base = utf16_path;
2932 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2934 if (tcon->posix_extensions) {
2935 /* resource #3: posix buf */
2936 rc = add_posix_context(iov, &n_iov, mode);
2937 if (rc)
2938 goto err_free_req;
2939 req->CreateContextsOffset = cpu_to_le32(
2940 sizeof(struct smb2_create_req) +
2941 iov[1].iov_len);
2942 pc_buf = iov[n_iov-1].iov_base;
2946 memset(&rqst, 0, sizeof(struct smb_rqst));
2947 rqst.rq_iov = iov;
2948 rqst.rq_nvec = n_iov;
2950 /* no need to inc num_remote_opens because we close it just below */
2951 trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
2952 FILE_WRITE_ATTRIBUTES);
2954 if (retries)
2955 smb2_set_replay(server, &rqst);
2957 /* resource #4: response buffer */
2958 rc = cifs_send_recv(xid, ses, server,
2959 &rqst, &resp_buftype, flags, &rsp_iov);
2960 if (rc) {
2961 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2962 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2963 CREATE_NOT_FILE,
2964 FILE_WRITE_ATTRIBUTES, rc);
2965 goto err_free_rsp_buf;
2969 * Although unlikely to be possible for rsp to be null and rc not set,
2970 * adding check below is slightly safer long term (and quiets Coverity
2971 * warning)
2973 rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2974 if (rsp == NULL) {
2975 rc = -EIO;
2976 kfree(pc_buf);
2977 goto err_free_req;
2980 trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
2981 CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2983 SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2985 /* Eventually save off posix specific response info and timestamps */
2987 err_free_rsp_buf:
2988 free_rsp_buf(resp_buftype, rsp);
2989 kfree(pc_buf);
2990 err_free_req:
2991 cifs_small_buf_release(req);
2992 err_free_path:
2993 kfree(utf16_path);
2995 if (is_replayable_error(rc) &&
2996 smb2_should_replay(tcon, &retries, &cur_sleep))
2997 goto replay_again;
2999 return rc;
3003 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3004 struct smb_rqst *rqst, __u8 *oplock,
3005 struct cifs_open_parms *oparms, __le16 *path)
3007 struct smb2_create_req *req;
3008 unsigned int n_iov = 2;
3009 __u32 file_attributes = 0;
3010 int copy_size;
3011 int uni_path_len;
3012 unsigned int total_len;
3013 struct kvec *iov = rqst->rq_iov;
3014 __le16 *copy_path;
3015 int rc;
3017 rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
3018 (void **) &req, &total_len);
3019 if (rc)
3020 return rc;
3022 iov[0].iov_base = (char *)req;
3023 /* -1 since last byte is buf[0] which is sent below (path) */
3024 iov[0].iov_len = total_len - 1;
3026 if (oparms->create_options & CREATE_OPTION_READONLY)
3027 file_attributes |= ATTR_READONLY;
3028 if (oparms->create_options & CREATE_OPTION_SPECIAL)
3029 file_attributes |= ATTR_SYSTEM;
3031 req->ImpersonationLevel = IL_IMPERSONATION;
3032 req->DesiredAccess = cpu_to_le32(oparms->desired_access);
3033 /* File attributes ignored on open (used in create though) */
3034 req->FileAttributes = cpu_to_le32(file_attributes);
3035 req->ShareAccess = FILE_SHARE_ALL_LE;
3037 req->CreateDisposition = cpu_to_le32(oparms->disposition);
3038 req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
3039 req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
3041 /* [MS-SMB2] 2.2.13 NameOffset:
3042 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
3043 * the SMB2 header, the file name includes a prefix that will
3044 * be processed during DFS name normalization as specified in
3045 * section 3.3.5.9. Otherwise, the file name is relative to
3046 * the share that is identified by the TreeId in the SMB2
3047 * header.
3049 if (tcon->share_flags & SHI1005_FLAGS_DFS) {
3050 int name_len;
3052 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3053 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
3054 &name_len,
3055 tcon->tree_name, path);
3056 if (rc)
3057 return rc;
3058 req->NameLength = cpu_to_le16(name_len * 2);
3059 uni_path_len = copy_size;
3060 path = copy_path;
3061 } else {
3062 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
3063 /* MUST set path len (NameLength) to 0 opening root of share */
3064 req->NameLength = cpu_to_le16(uni_path_len - 2);
3065 copy_size = round_up(uni_path_len, 8);
3066 copy_path = kzalloc(copy_size, GFP_KERNEL);
3067 if (!copy_path)
3068 return -ENOMEM;
3069 memcpy((char *)copy_path, (const char *)path,
3070 uni_path_len);
3071 uni_path_len = copy_size;
3072 path = copy_path;
3075 iov[1].iov_len = uni_path_len;
3076 iov[1].iov_base = path;
3078 if ((!server->oplocks) || (tcon->no_lease))
3079 *oplock = SMB2_OPLOCK_LEVEL_NONE;
3081 if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3082 *oplock == SMB2_OPLOCK_LEVEL_NONE)
3083 req->RequestedOplockLevel = *oplock;
3084 else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
3085 (oparms->create_options & CREATE_NOT_FILE))
3086 req->RequestedOplockLevel = *oplock; /* no srv lease support */
3087 else {
3088 rc = add_lease_context(server, req, iov, &n_iov,
3089 oparms->fid->lease_key, oplock);
3090 if (rc)
3091 return rc;
3094 if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3095 rc = add_durable_context(iov, &n_iov, oparms,
3096 tcon->use_persistent);
3097 if (rc)
3098 return rc;
3101 if (tcon->posix_extensions) {
3102 rc = add_posix_context(iov, &n_iov, oparms->mode);
3103 if (rc)
3104 return rc;
3107 if (tcon->snapshot_time) {
3108 cifs_dbg(FYI, "adding snapshot context\n");
3109 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
3110 if (rc)
3111 return rc;
3114 if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
3115 bool set_mode;
3116 bool set_owner;
3118 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
3119 (oparms->mode != ACL_NO_MODE))
3120 set_mode = true;
3121 else {
3122 set_mode = false;
3123 oparms->mode = ACL_NO_MODE;
3126 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
3127 set_owner = true;
3128 else
3129 set_owner = false;
3131 if (set_owner | set_mode) {
3132 cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
3133 rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
3134 if (rc)
3135 return rc;
3139 add_query_id_context(iov, &n_iov);
3140 add_ea_context(oparms, iov, &n_iov);
3142 if (n_iov > 2) {
3144 * We have create contexts behind iov[1] (the file
3145 * name), point at them from the main create request
3147 req->CreateContextsOffset = cpu_to_le32(
3148 sizeof(struct smb2_create_req) +
3149 iov[1].iov_len);
3150 req->CreateContextsLength = 0;
3152 for (unsigned int i = 2; i < (n_iov-1); i++) {
3153 struct kvec *v = &iov[i];
3154 size_t len = v->iov_len;
3155 struct create_context *cctx =
3156 (struct create_context *)v->iov_base;
3158 cctx->Next = cpu_to_le32(len);
3159 le32_add_cpu(&req->CreateContextsLength, len);
3161 le32_add_cpu(&req->CreateContextsLength,
3162 iov[n_iov-1].iov_len);
3165 rqst->rq_nvec = n_iov;
3166 return 0;
3169 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
3170 * All other vectors are freed by kfree().
3172 void
3173 SMB2_open_free(struct smb_rqst *rqst)
3175 int i;
3177 if (rqst && rqst->rq_iov) {
3178 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
3179 for (i = 1; i < rqst->rq_nvec; i++)
3180 if (rqst->rq_iov[i].iov_base != smb2_padding)
3181 kfree(rqst->rq_iov[i].iov_base);
3186 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
3187 __u8 *oplock, struct smb2_file_all_info *buf,
3188 struct create_posix_rsp *posix,
3189 struct kvec *err_iov, int *buftype)
3191 struct smb_rqst rqst;
3192 struct smb2_create_rsp *rsp = NULL;
3193 struct cifs_tcon *tcon = oparms->tcon;
3194 struct cifs_ses *ses = tcon->ses;
3195 struct TCP_Server_Info *server;
3196 struct kvec iov[SMB2_CREATE_IOV_SIZE];
3197 struct kvec rsp_iov = {NULL, 0};
3198 int resp_buftype = CIFS_NO_BUFFER;
3199 int rc = 0;
3200 int flags = 0;
3201 int retries = 0, cur_sleep = 1;
3203 replay_again:
3204 /* reinitialize for possible replay */
3205 flags = 0;
3206 server = cifs_pick_channel(ses);
3207 oparms->replay = !!(retries);
3209 cifs_dbg(FYI, "create/open\n");
3210 if (!ses || !server)
3211 return -EIO;
3213 if (smb3_encryption_required(tcon))
3214 flags |= CIFS_TRANSFORM_REQ;
3216 memset(&rqst, 0, sizeof(struct smb_rqst));
3217 memset(&iov, 0, sizeof(iov));
3218 rqst.rq_iov = iov;
3219 rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3221 rc = SMB2_open_init(tcon, server,
3222 &rqst, oplock, oparms, path);
3223 if (rc)
3224 goto creat_exit;
3226 trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3227 oparms->create_options, oparms->desired_access);
3229 if (retries)
3230 smb2_set_replay(server, &rqst);
3232 rc = cifs_send_recv(xid, ses, server,
3233 &rqst, &resp_buftype, flags,
3234 &rsp_iov);
3235 rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3237 if (rc != 0) {
3238 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3239 if (err_iov && rsp) {
3240 *err_iov = rsp_iov;
3241 *buftype = resp_buftype;
3242 resp_buftype = CIFS_NO_BUFFER;
3243 rsp = NULL;
3245 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3246 oparms->create_options, oparms->desired_access, rc);
3247 if (rc == -EREMCHG) {
3248 pr_warn_once("server share %s deleted\n",
3249 tcon->tree_name);
3250 tcon->need_reconnect = true;
3252 goto creat_exit;
3253 } else if (rsp == NULL) /* unlikely to happen, but safer to check */
3254 goto creat_exit;
3255 else
3256 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3257 oparms->create_options, oparms->desired_access);
3259 atomic_inc(&tcon->num_remote_opens);
3260 oparms->fid->persistent_fid = rsp->PersistentFileId;
3261 oparms->fid->volatile_fid = rsp->VolatileFileId;
3262 oparms->fid->access = oparms->desired_access;
3263 #ifdef CONFIG_CIFS_DEBUG2
3264 oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3265 #endif /* CIFS_DEBUG2 */
3267 if (buf) {
3268 buf->CreationTime = rsp->CreationTime;
3269 buf->LastAccessTime = rsp->LastAccessTime;
3270 buf->LastWriteTime = rsp->LastWriteTime;
3271 buf->ChangeTime = rsp->ChangeTime;
3272 buf->AllocationSize = rsp->AllocationSize;
3273 buf->EndOfFile = rsp->EndofFile;
3274 buf->Attributes = rsp->FileAttributes;
3275 buf->NumberOfLinks = cpu_to_le32(1);
3276 buf->DeletePending = 0;
3280 rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
3281 oparms->fid->lease_key, oplock, buf, posix);
3282 creat_exit:
3283 SMB2_open_free(&rqst);
3284 free_rsp_buf(resp_buftype, rsp);
3286 if (is_replayable_error(rc) &&
3287 smb2_should_replay(tcon, &retries, &cur_sleep))
3288 goto replay_again;
3290 return rc;
3294 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3295 struct smb_rqst *rqst,
3296 u64 persistent_fid, u64 volatile_fid, u32 opcode,
3297 char *in_data, u32 indatalen,
3298 __u32 max_response_size)
3300 struct smb2_ioctl_req *req;
3301 struct kvec *iov = rqst->rq_iov;
3302 unsigned int total_len;
3303 int rc;
3304 char *in_data_buf;
3306 rc = smb2_ioctl_req_init(opcode, tcon, server,
3307 (void **) &req, &total_len);
3308 if (rc)
3309 return rc;
3311 if (indatalen) {
3313 * indatalen is usually small at a couple of bytes max, so
3314 * just allocate through generic pool
3316 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3317 if (!in_data_buf) {
3318 cifs_small_buf_release(req);
3319 return -ENOMEM;
3323 req->CtlCode = cpu_to_le32(opcode);
3324 req->PersistentFileId = persistent_fid;
3325 req->VolatileFileId = volatile_fid;
3327 iov[0].iov_base = (char *)req;
3329 * If no input data, the size of ioctl struct in
3330 * protocol spec still includes a 1 byte data buffer,
3331 * but if input data passed to ioctl, we do not
3332 * want to double count this, so we do not send
3333 * the dummy one byte of data in iovec[0] if sending
3334 * input data (in iovec[1]).
3336 if (indatalen) {
3337 req->InputCount = cpu_to_le32(indatalen);
3338 /* do not set InputOffset if no input data */
3339 req->InputOffset =
3340 cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3341 rqst->rq_nvec = 2;
3342 iov[0].iov_len = total_len - 1;
3343 iov[1].iov_base = in_data_buf;
3344 iov[1].iov_len = indatalen;
3345 } else {
3346 rqst->rq_nvec = 1;
3347 iov[0].iov_len = total_len;
3350 req->OutputOffset = 0;
3351 req->OutputCount = 0; /* MBZ */
3354 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3355 * We Could increase default MaxOutputResponse, but that could require
3356 * more credits. Windows typically sets this smaller, but for some
3357 * ioctls it may be useful to allow server to send more. No point
3358 * limiting what the server can send as long as fits in one credit
3359 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3360 * to increase this limit up in the future.
3361 * Note that for snapshot queries that servers like Azure expect that
3362 * the first query be minimal size (and just used to get the number/size
3363 * of previous versions) so response size must be specified as EXACTLY
3364 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3365 * of eight bytes. Currently that is the only case where we set max
3366 * response size smaller.
3368 req->MaxOutputResponse = cpu_to_le32(max_response_size);
3369 req->hdr.CreditCharge =
3370 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3371 SMB2_MAX_BUFFER_SIZE));
3372 /* always an FSCTL (for now) */
3373 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3375 /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3376 if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3377 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3379 return 0;
3382 void
3383 SMB2_ioctl_free(struct smb_rqst *rqst)
3385 int i;
3387 if (rqst && rqst->rq_iov) {
3388 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3389 for (i = 1; i < rqst->rq_nvec; i++)
3390 if (rqst->rq_iov[i].iov_base != smb2_padding)
3391 kfree(rqst->rq_iov[i].iov_base);
3397 * SMB2 IOCTL is used for both IOCTLs and FSCTLs
3400 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3401 u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3402 u32 max_out_data_len, char **out_data,
3403 u32 *plen /* returned data len */)
3405 struct smb_rqst rqst;
3406 struct smb2_ioctl_rsp *rsp = NULL;
3407 struct cifs_ses *ses;
3408 struct TCP_Server_Info *server;
3409 struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3410 struct kvec rsp_iov = {NULL, 0};
3411 int resp_buftype = CIFS_NO_BUFFER;
3412 int rc = 0;
3413 int flags = 0;
3414 int retries = 0, cur_sleep = 1;
3416 if (!tcon)
3417 return -EIO;
3419 ses = tcon->ses;
3420 if (!ses)
3421 return -EIO;
3423 replay_again:
3424 /* reinitialize for possible replay */
3425 flags = 0;
3426 server = cifs_pick_channel(ses);
3428 if (!server)
3429 return -EIO;
3431 cifs_dbg(FYI, "SMB2 IOCTL\n");
3433 if (out_data != NULL)
3434 *out_data = NULL;
3436 /* zero out returned data len, in case of error */
3437 if (plen)
3438 *plen = 0;
3440 if (smb3_encryption_required(tcon))
3441 flags |= CIFS_TRANSFORM_REQ;
3443 memset(&rqst, 0, sizeof(struct smb_rqst));
3444 memset(&iov, 0, sizeof(iov));
3445 rqst.rq_iov = iov;
3446 rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3448 rc = SMB2_ioctl_init(tcon, server,
3449 &rqst, persistent_fid, volatile_fid, opcode,
3450 in_data, indatalen, max_out_data_len);
3451 if (rc)
3452 goto ioctl_exit;
3454 if (retries)
3455 smb2_set_replay(server, &rqst);
3457 rc = cifs_send_recv(xid, ses, server,
3458 &rqst, &resp_buftype, flags,
3459 &rsp_iov);
3460 rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3462 if (rc != 0)
3463 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3464 ses->Suid, 0, opcode, rc);
3466 if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3467 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3468 goto ioctl_exit;
3469 } else if (rc == -EINVAL) {
3470 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3471 (opcode != FSCTL_SRV_COPYCHUNK)) {
3472 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3473 goto ioctl_exit;
3475 } else if (rc == -E2BIG) {
3476 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3477 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3478 goto ioctl_exit;
3482 /* check if caller wants to look at return data or just return rc */
3483 if ((plen == NULL) || (out_data == NULL))
3484 goto ioctl_exit;
3487 * Although unlikely to be possible for rsp to be null and rc not set,
3488 * adding check below is slightly safer long term (and quiets Coverity
3489 * warning)
3491 if (rsp == NULL) {
3492 rc = -EIO;
3493 goto ioctl_exit;
3496 *plen = le32_to_cpu(rsp->OutputCount);
3498 /* We check for obvious errors in the output buffer length and offset */
3499 if (*plen == 0)
3500 goto ioctl_exit; /* server returned no data */
3501 else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3502 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3503 *plen = 0;
3504 rc = -EIO;
3505 goto ioctl_exit;
3508 if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3509 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3510 le32_to_cpu(rsp->OutputOffset));
3511 *plen = 0;
3512 rc = -EIO;
3513 goto ioctl_exit;
3516 *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3517 *plen, GFP_KERNEL);
3518 if (*out_data == NULL) {
3519 rc = -ENOMEM;
3520 goto ioctl_exit;
3523 ioctl_exit:
3524 SMB2_ioctl_free(&rqst);
3525 free_rsp_buf(resp_buftype, rsp);
3527 if (is_replayable_error(rc) &&
3528 smb2_should_replay(tcon, &retries, &cur_sleep))
3529 goto replay_again;
3531 return rc;
3535 * Individual callers to ioctl worker function follow
3539 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3540 u64 persistent_fid, u64 volatile_fid)
3542 int rc;
3543 struct compress_ioctl fsctl_input;
3544 char *ret_data = NULL;
3546 fsctl_input.CompressionState =
3547 cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3549 rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3550 FSCTL_SET_COMPRESSION,
3551 (char *)&fsctl_input /* data input */,
3552 2 /* in data len */, CIFSMaxBufSize /* max out data */,
3553 &ret_data /* out data */, NULL);
3555 cifs_dbg(FYI, "set compression rc %d\n", rc);
3557 return rc;
3561 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3562 struct smb_rqst *rqst,
3563 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3565 struct smb2_close_req *req;
3566 struct kvec *iov = rqst->rq_iov;
3567 unsigned int total_len;
3568 int rc;
3570 rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3571 (void **) &req, &total_len);
3572 if (rc)
3573 return rc;
3575 req->PersistentFileId = persistent_fid;
3576 req->VolatileFileId = volatile_fid;
3577 if (query_attrs)
3578 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3579 else
3580 req->Flags = 0;
3581 iov[0].iov_base = (char *)req;
3582 iov[0].iov_len = total_len;
3584 return 0;
3587 void
3588 SMB2_close_free(struct smb_rqst *rqst)
3590 if (rqst && rqst->rq_iov)
3591 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3595 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3596 u64 persistent_fid, u64 volatile_fid,
3597 struct smb2_file_network_open_info *pbuf)
3599 struct smb_rqst rqst;
3600 struct smb2_close_rsp *rsp = NULL;
3601 struct cifs_ses *ses = tcon->ses;
3602 struct TCP_Server_Info *server;
3603 struct kvec iov[1];
3604 struct kvec rsp_iov;
3605 int resp_buftype = CIFS_NO_BUFFER;
3606 int rc = 0;
3607 int flags = 0;
3608 bool query_attrs = false;
3609 int retries = 0, cur_sleep = 1;
3611 replay_again:
3612 /* reinitialize for possible replay */
3613 flags = 0;
3614 query_attrs = false;
3615 server = cifs_pick_channel(ses);
3617 cifs_dbg(FYI, "Close\n");
3619 if (!ses || !server)
3620 return -EIO;
3622 if (smb3_encryption_required(tcon))
3623 flags |= CIFS_TRANSFORM_REQ;
3625 memset(&rqst, 0, sizeof(struct smb_rqst));
3626 memset(&iov, 0, sizeof(iov));
3627 rqst.rq_iov = iov;
3628 rqst.rq_nvec = 1;
3630 /* check if need to ask server to return timestamps in close response */
3631 if (pbuf)
3632 query_attrs = true;
3634 trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3635 rc = SMB2_close_init(tcon, server,
3636 &rqst, persistent_fid, volatile_fid,
3637 query_attrs);
3638 if (rc)
3639 goto close_exit;
3641 if (retries)
3642 smb2_set_replay(server, &rqst);
3644 rc = cifs_send_recv(xid, ses, server,
3645 &rqst, &resp_buftype, flags, &rsp_iov);
3646 rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3648 if (rc != 0) {
3649 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3650 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3651 rc);
3652 goto close_exit;
3653 } else {
3654 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3655 ses->Suid);
3656 if (pbuf)
3657 memcpy(&pbuf->network_open_info,
3658 &rsp->network_open_info,
3659 sizeof(pbuf->network_open_info));
3660 atomic_dec(&tcon->num_remote_opens);
3663 close_exit:
3664 SMB2_close_free(&rqst);
3665 free_rsp_buf(resp_buftype, rsp);
3667 /* retry close in a worker thread if this one is interrupted */
3668 if (is_interrupt_error(rc)) {
3669 int tmp_rc;
3671 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3672 volatile_fid);
3673 if (tmp_rc)
3674 cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3675 persistent_fid, tmp_rc);
3678 if (is_replayable_error(rc) &&
3679 smb2_should_replay(tcon, &retries, &cur_sleep))
3680 goto replay_again;
3682 return rc;
3686 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3687 u64 persistent_fid, u64 volatile_fid)
3689 return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3693 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3694 struct kvec *iov, unsigned int min_buf_size)
3696 unsigned int smb_len = iov->iov_len;
3697 char *end_of_smb = smb_len + (char *)iov->iov_base;
3698 char *begin_of_buf = offset + (char *)iov->iov_base;
3699 char *end_of_buf = begin_of_buf + buffer_length;
3702 if (buffer_length < min_buf_size) {
3703 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3704 buffer_length, min_buf_size);
3705 return -EINVAL;
3708 /* check if beyond RFC1001 maximum length */
3709 if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3710 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3711 buffer_length, smb_len);
3712 return -EINVAL;
3715 if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3716 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3717 return -EINVAL;
3720 return 0;
3724 * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3725 * Caller must free buffer.
3728 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3729 struct kvec *iov, unsigned int minbufsize,
3730 char *data)
3732 char *begin_of_buf = offset + (char *)iov->iov_base;
3733 int rc;
3735 if (!data)
3736 return -EINVAL;
3738 rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3739 if (rc)
3740 return rc;
3742 memcpy(data, begin_of_buf, minbufsize);
3744 return 0;
3748 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3749 struct smb_rqst *rqst,
3750 u64 persistent_fid, u64 volatile_fid,
3751 u8 info_class, u8 info_type, u32 additional_info,
3752 size_t output_len, size_t input_len, void *input)
3754 struct smb2_query_info_req *req;
3755 struct kvec *iov = rqst->rq_iov;
3756 unsigned int total_len;
3757 size_t len;
3758 int rc;
3760 if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
3761 len > CIFSMaxBufSize))
3762 return -EINVAL;
3764 rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3765 (void **) &req, &total_len);
3766 if (rc)
3767 return rc;
3769 req->InfoType = info_type;
3770 req->FileInfoClass = info_class;
3771 req->PersistentFileId = persistent_fid;
3772 req->VolatileFileId = volatile_fid;
3773 req->AdditionalInformation = cpu_to_le32(additional_info);
3775 req->OutputBufferLength = cpu_to_le32(output_len);
3776 if (input_len) {
3777 req->InputBufferLength = cpu_to_le32(input_len);
3778 /* total_len for smb query request never close to le16 max */
3779 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3780 memcpy(req->Buffer, input, input_len);
3783 iov[0].iov_base = (char *)req;
3784 /* 1 for Buffer */
3785 iov[0].iov_len = len;
3786 return 0;
3789 void
3790 SMB2_query_info_free(struct smb_rqst *rqst)
3792 if (rqst && rqst->rq_iov)
3793 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3796 static int
3797 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3798 u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3799 u32 additional_info, size_t output_len, size_t min_len, void **data,
3800 u32 *dlen)
3802 struct smb_rqst rqst;
3803 struct smb2_query_info_rsp *rsp = NULL;
3804 struct kvec iov[1];
3805 struct kvec rsp_iov;
3806 int rc = 0;
3807 int resp_buftype = CIFS_NO_BUFFER;
3808 struct cifs_ses *ses = tcon->ses;
3809 struct TCP_Server_Info *server;
3810 int flags = 0;
3811 bool allocated = false;
3812 int retries = 0, cur_sleep = 1;
3814 cifs_dbg(FYI, "Query Info\n");
3816 if (!ses)
3817 return -EIO;
3819 replay_again:
3820 /* reinitialize for possible replay */
3821 flags = 0;
3822 allocated = false;
3823 server = cifs_pick_channel(ses);
3825 if (!server)
3826 return -EIO;
3828 if (smb3_encryption_required(tcon))
3829 flags |= CIFS_TRANSFORM_REQ;
3831 memset(&rqst, 0, sizeof(struct smb_rqst));
3832 memset(&iov, 0, sizeof(iov));
3833 rqst.rq_iov = iov;
3834 rqst.rq_nvec = 1;
3836 rc = SMB2_query_info_init(tcon, server,
3837 &rqst, persistent_fid, volatile_fid,
3838 info_class, info_type, additional_info,
3839 output_len, 0, NULL);
3840 if (rc)
3841 goto qinf_exit;
3843 trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3844 ses->Suid, info_class, (__u32)info_type);
3846 if (retries)
3847 smb2_set_replay(server, &rqst);
3849 rc = cifs_send_recv(xid, ses, server,
3850 &rqst, &resp_buftype, flags, &rsp_iov);
3851 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3853 if (rc) {
3854 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3855 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3856 ses->Suid, info_class, (__u32)info_type, rc);
3857 goto qinf_exit;
3860 trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3861 ses->Suid, info_class, (__u32)info_type);
3863 if (dlen) {
3864 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3865 if (!*data) {
3866 *data = kmalloc(*dlen, GFP_KERNEL);
3867 if (!*data) {
3868 cifs_tcon_dbg(VFS,
3869 "Error %d allocating memory for acl\n",
3870 rc);
3871 *dlen = 0;
3872 rc = -ENOMEM;
3873 goto qinf_exit;
3875 allocated = true;
3879 rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3880 le32_to_cpu(rsp->OutputBufferLength),
3881 &rsp_iov, dlen ? *dlen : min_len, *data);
3882 if (rc && allocated) {
3883 kfree(*data);
3884 *data = NULL;
3885 *dlen = 0;
3888 qinf_exit:
3889 SMB2_query_info_free(&rqst);
3890 free_rsp_buf(resp_buftype, rsp);
3892 if (is_replayable_error(rc) &&
3893 smb2_should_replay(tcon, &retries, &cur_sleep))
3894 goto replay_again;
3896 return rc;
3899 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3900 u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3902 return query_info(xid, tcon, persistent_fid, volatile_fid,
3903 FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3904 sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3905 sizeof(struct smb2_file_all_info), (void **)&data,
3906 NULL);
3909 #if 0
3910 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3912 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3913 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3915 size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3916 (sizeof(struct smb_sid) * 2) + (PATH_MAX * 2);
3917 *plen = 0;
3919 return query_info(xid, tcon, persistent_fid, volatile_fid,
3920 SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3921 output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3922 /* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3924 #endif
3927 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3928 u64 persistent_fid, u64 volatile_fid,
3929 void **data, u32 *plen, u32 extra_info)
3931 __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3932 extra_info;
3933 *plen = 0;
3935 return query_info(xid, tcon, persistent_fid, volatile_fid,
3936 0, SMB2_O_INFO_SECURITY, additional_info,
3937 SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3941 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3942 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3944 return query_info(xid, tcon, persistent_fid, volatile_fid,
3945 FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3946 sizeof(struct smb2_file_internal_info),
3947 sizeof(struct smb2_file_internal_info),
3948 (void **)&uniqueid, NULL);
3952 * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3953 * See MS-SMB2 2.2.35 and 2.2.36
3956 static int
3957 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3958 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3959 u64 persistent_fid, u64 volatile_fid,
3960 u32 completion_filter, bool watch_tree)
3962 struct smb2_change_notify_req *req;
3963 struct kvec *iov = rqst->rq_iov;
3964 unsigned int total_len;
3965 int rc;
3967 rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3968 (void **) &req, &total_len);
3969 if (rc)
3970 return rc;
3972 req->PersistentFileId = persistent_fid;
3973 req->VolatileFileId = volatile_fid;
3974 /* See note 354 of MS-SMB2, 64K max */
3975 req->OutputBufferLength =
3976 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3977 req->CompletionFilter = cpu_to_le32(completion_filter);
3978 if (watch_tree)
3979 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3980 else
3981 req->Flags = 0;
3983 iov[0].iov_base = (char *)req;
3984 iov[0].iov_len = total_len;
3986 return 0;
3990 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3991 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3992 u32 completion_filter, u32 max_out_data_len, char **out_data,
3993 u32 *plen /* returned data len */)
3995 struct cifs_ses *ses = tcon->ses;
3996 struct TCP_Server_Info *server;
3997 struct smb_rqst rqst;
3998 struct smb2_change_notify_rsp *smb_rsp;
3999 struct kvec iov[1];
4000 struct kvec rsp_iov = {NULL, 0};
4001 int resp_buftype = CIFS_NO_BUFFER;
4002 int flags = 0;
4003 int rc = 0;
4004 int retries = 0, cur_sleep = 1;
4006 replay_again:
4007 /* reinitialize for possible replay */
4008 flags = 0;
4009 server = cifs_pick_channel(ses);
4011 cifs_dbg(FYI, "change notify\n");
4012 if (!ses || !server)
4013 return -EIO;
4015 if (smb3_encryption_required(tcon))
4016 flags |= CIFS_TRANSFORM_REQ;
4018 memset(&rqst, 0, sizeof(struct smb_rqst));
4019 memset(&iov, 0, sizeof(iov));
4020 if (plen)
4021 *plen = 0;
4023 rqst.rq_iov = iov;
4024 rqst.rq_nvec = 1;
4026 rc = SMB2_notify_init(xid, &rqst, tcon, server,
4027 persistent_fid, volatile_fid,
4028 completion_filter, watch_tree);
4029 if (rc)
4030 goto cnotify_exit;
4032 trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
4033 (u8)watch_tree, completion_filter);
4035 if (retries)
4036 smb2_set_replay(server, &rqst);
4038 rc = cifs_send_recv(xid, ses, server,
4039 &rqst, &resp_buftype, flags, &rsp_iov);
4041 if (rc != 0) {
4042 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
4043 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
4044 (u8)watch_tree, completion_filter, rc);
4045 } else {
4046 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
4047 ses->Suid, (u8)watch_tree, completion_filter);
4048 /* validate that notify information is plausible */
4049 if ((rsp_iov.iov_base == NULL) ||
4050 (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
4051 goto cnotify_exit;
4053 smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
4055 smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
4056 le32_to_cpu(smb_rsp->OutputBufferLength), &rsp_iov,
4057 sizeof(struct file_notify_information));
4059 *out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
4060 le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
4061 if (*out_data == NULL) {
4062 rc = -ENOMEM;
4063 goto cnotify_exit;
4064 } else if (plen)
4065 *plen = le32_to_cpu(smb_rsp->OutputBufferLength);
4068 cnotify_exit:
4069 if (rqst.rq_iov)
4070 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
4071 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4073 if (is_replayable_error(rc) &&
4074 smb2_should_replay(tcon, &retries, &cur_sleep))
4075 goto replay_again;
4077 return rc;
4083 * This is a no-op for now. We're not really interested in the reply, but
4084 * rather in the fact that the server sent one and that server->lstrp
4085 * gets updated.
4087 * FIXME: maybe we should consider checking that the reply matches request?
4089 static void
4090 smb2_echo_callback(struct mid_q_entry *mid)
4092 struct TCP_Server_Info *server = mid->callback_data;
4093 struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
4094 struct cifs_credits credits = { .value = 0, .instance = 0 };
4096 if (mid->mid_state == MID_RESPONSE_RECEIVED
4097 || mid->mid_state == MID_RESPONSE_MALFORMED) {
4098 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4099 credits.instance = server->reconnect_instance;
4102 release_mid(mid);
4103 add_credits(server, &credits, CIFS_ECHO_OP);
4106 void smb2_reconnect_server(struct work_struct *work)
4108 struct TCP_Server_Info *server = container_of(work,
4109 struct TCP_Server_Info, reconnect.work);
4110 struct TCP_Server_Info *pserver;
4111 struct cifs_ses *ses, *ses2;
4112 struct cifs_tcon *tcon, *tcon2;
4113 struct list_head tmp_list, tmp_ses_list;
4114 bool ses_exist = false;
4115 bool tcon_selected = false;
4116 int rc;
4117 bool resched = false;
4119 /* first check if ref count has reached 0, if not inc ref count */
4120 spin_lock(&cifs_tcp_ses_lock);
4121 if (!server->srv_count) {
4122 spin_unlock(&cifs_tcp_ses_lock);
4123 return;
4125 server->srv_count++;
4126 spin_unlock(&cifs_tcp_ses_lock);
4128 /* If server is a channel, select the primary channel */
4129 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4131 /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
4132 mutex_lock(&pserver->reconnect_mutex);
4134 /* if the server is marked for termination, drop the ref count here */
4135 if (server->terminate) {
4136 cifs_put_tcp_session(server, true);
4137 mutex_unlock(&pserver->reconnect_mutex);
4138 return;
4141 INIT_LIST_HEAD(&tmp_list);
4142 INIT_LIST_HEAD(&tmp_ses_list);
4143 cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4145 spin_lock(&cifs_tcp_ses_lock);
4146 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4147 spin_lock(&ses->ses_lock);
4148 if (ses->ses_status == SES_EXITING) {
4149 spin_unlock(&ses->ses_lock);
4150 continue;
4152 spin_unlock(&ses->ses_lock);
4154 tcon_selected = false;
4156 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4157 if (tcon->need_reconnect || tcon->need_reopen_files) {
4158 tcon->tc_count++;
4159 trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
4160 netfs_trace_tcon_ref_get_reconnect_server);
4161 list_add_tail(&tcon->rlist, &tmp_list);
4162 tcon_selected = true;
4166 * IPC has the same lifetime as its session and uses its
4167 * refcount.
4169 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
4170 list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4171 tcon_selected = true;
4172 cifs_smb_ses_inc_refcount(ses);
4175 * handle the case where channel needs to reconnect
4176 * binding session, but tcon is healthy (some other channel
4177 * is active)
4179 spin_lock(&ses->chan_lock);
4180 if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
4181 list_add_tail(&ses->rlist, &tmp_ses_list);
4182 ses_exist = true;
4183 cifs_smb_ses_inc_refcount(ses);
4185 spin_unlock(&ses->chan_lock);
4187 spin_unlock(&cifs_tcp_ses_lock);
4189 list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4190 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4191 if (!rc)
4192 cifs_reopen_persistent_handles(tcon);
4193 else
4194 resched = true;
4195 list_del_init(&tcon->rlist);
4196 if (tcon->ipc)
4197 cifs_put_smb_ses(tcon->ses);
4198 else
4199 cifs_put_tcon(tcon, netfs_trace_tcon_ref_put_reconnect_server);
4202 if (!ses_exist)
4203 goto done;
4205 /* allocate a dummy tcon struct used for reconnect */
4206 tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_reconnect_server);
4207 if (!tcon) {
4208 resched = true;
4209 list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4210 list_del_init(&ses->rlist);
4211 cifs_put_smb_ses(ses);
4213 goto done;
4216 tcon->status = TID_GOOD;
4217 tcon->retry = false;
4218 tcon->need_reconnect = false;
4220 /* now reconnect sessions for necessary channels */
4221 list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4222 tcon->ses = ses;
4223 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4224 if (rc)
4225 resched = true;
4226 list_del_init(&ses->rlist);
4227 cifs_put_smb_ses(ses);
4229 tconInfoFree(tcon, netfs_trace_tcon_ref_free_reconnect_server);
4231 done:
4232 cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4233 if (resched)
4234 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
4235 mutex_unlock(&pserver->reconnect_mutex);
4237 /* now we can safely release srv struct */
4238 cifs_put_tcp_session(server, true);
4242 SMB2_echo(struct TCP_Server_Info *server)
4244 struct smb2_echo_req *req;
4245 int rc = 0;
4246 struct kvec iov[1];
4247 struct smb_rqst rqst = { .rq_iov = iov,
4248 .rq_nvec = 1 };
4249 unsigned int total_len;
4251 cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
4253 spin_lock(&server->srv_lock);
4254 if (server->ops->need_neg &&
4255 server->ops->need_neg(server)) {
4256 spin_unlock(&server->srv_lock);
4257 /* No need to send echo on newly established connections */
4258 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
4259 return rc;
4261 spin_unlock(&server->srv_lock);
4263 rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
4264 (void **)&req, &total_len);
4265 if (rc)
4266 return rc;
4268 req->hdr.CreditRequest = cpu_to_le16(1);
4270 iov[0].iov_len = total_len;
4271 iov[0].iov_base = (char *)req;
4273 rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4274 server, CIFS_ECHO_OP, NULL);
4275 if (rc)
4276 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4278 cifs_small_buf_release(req);
4279 return rc;
4282 void
4283 SMB2_flush_free(struct smb_rqst *rqst)
4285 if (rqst && rqst->rq_iov)
4286 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4290 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4291 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4292 u64 persistent_fid, u64 volatile_fid)
4294 struct smb2_flush_req *req;
4295 struct kvec *iov = rqst->rq_iov;
4296 unsigned int total_len;
4297 int rc;
4299 rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
4300 (void **) &req, &total_len);
4301 if (rc)
4302 return rc;
4304 req->PersistentFileId = persistent_fid;
4305 req->VolatileFileId = volatile_fid;
4307 iov[0].iov_base = (char *)req;
4308 iov[0].iov_len = total_len;
4310 return 0;
4314 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4315 u64 volatile_fid)
4317 struct cifs_ses *ses = tcon->ses;
4318 struct smb_rqst rqst;
4319 struct kvec iov[1];
4320 struct kvec rsp_iov = {NULL, 0};
4321 struct TCP_Server_Info *server;
4322 int resp_buftype = CIFS_NO_BUFFER;
4323 int flags = 0;
4324 int rc = 0;
4325 int retries = 0, cur_sleep = 1;
4327 replay_again:
4328 /* reinitialize for possible replay */
4329 flags = 0;
4330 server = cifs_pick_channel(ses);
4332 cifs_dbg(FYI, "flush\n");
4333 if (!ses || !(ses->server))
4334 return -EIO;
4336 if (smb3_encryption_required(tcon))
4337 flags |= CIFS_TRANSFORM_REQ;
4339 memset(&rqst, 0, sizeof(struct smb_rqst));
4340 memset(&iov, 0, sizeof(iov));
4341 rqst.rq_iov = iov;
4342 rqst.rq_nvec = 1;
4344 rc = SMB2_flush_init(xid, &rqst, tcon, server,
4345 persistent_fid, volatile_fid);
4346 if (rc)
4347 goto flush_exit;
4349 trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4351 if (retries)
4352 smb2_set_replay(server, &rqst);
4354 rc = cifs_send_recv(xid, ses, server,
4355 &rqst, &resp_buftype, flags, &rsp_iov);
4357 if (rc != 0) {
4358 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4359 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4360 rc);
4361 } else
4362 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4363 ses->Suid);
4365 flush_exit:
4366 SMB2_flush_free(&rqst);
4367 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4369 if (is_replayable_error(rc) &&
4370 smb2_should_replay(tcon, &retries, &cur_sleep))
4371 goto replay_again;
4373 return rc;
4376 #ifdef CONFIG_CIFS_SMB_DIRECT
4377 static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
4379 struct TCP_Server_Info *server = io_parms->server;
4380 struct cifs_tcon *tcon = io_parms->tcon;
4382 /* we can only offload if we're connected */
4383 if (!server || !tcon)
4384 return false;
4386 /* we can only offload on an rdma connection */
4387 if (!server->rdma || !server->smbd_conn)
4388 return false;
4390 /* we don't support signed offload yet */
4391 if (server->sign)
4392 return false;
4394 /* we don't support encrypted offload yet */
4395 if (smb3_encryption_required(tcon))
4396 return false;
4398 /* offload also has its overhead, so only do it if desired */
4399 if (io_parms->length < server->smbd_conn->rdma_readwrite_threshold)
4400 return false;
4402 return true;
4404 #endif /* CONFIG_CIFS_SMB_DIRECT */
4407 * To form a chain of read requests, any read requests after the first should
4408 * have the end_of_chain boolean set to true.
4410 static int
4411 smb2_new_read_req(void **buf, unsigned int *total_len,
4412 struct cifs_io_parms *io_parms, struct cifs_io_subrequest *rdata,
4413 unsigned int remaining_bytes, int request_type)
4415 int rc = -EACCES;
4416 struct smb2_read_req *req = NULL;
4417 struct smb2_hdr *shdr;
4418 struct TCP_Server_Info *server = io_parms->server;
4420 rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4421 (void **) &req, total_len);
4422 if (rc)
4423 return rc;
4425 if (server == NULL)
4426 return -ECONNABORTED;
4428 shdr = &req->hdr;
4429 shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4431 req->PersistentFileId = io_parms->persistent_fid;
4432 req->VolatileFileId = io_parms->volatile_fid;
4433 req->ReadChannelInfoOffset = 0; /* reserved */
4434 req->ReadChannelInfoLength = 0; /* reserved */
4435 req->Channel = 0; /* reserved */
4436 req->MinimumCount = 0;
4437 req->Length = cpu_to_le32(io_parms->length);
4438 req->Offset = cpu_to_le64(io_parms->offset);
4440 trace_smb3_read_enter(rdata ? rdata->rreq->debug_id : 0,
4441 rdata ? rdata->subreq.debug_index : 0,
4442 rdata ? rdata->xid : 0,
4443 io_parms->persistent_fid,
4444 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4445 io_parms->offset, io_parms->length);
4446 #ifdef CONFIG_CIFS_SMB_DIRECT
4448 * If we want to do a RDMA write, fill in and append
4449 * smbd_buffer_descriptor_v1 to the end of read request
4451 if (rdata && smb3_use_rdma_offload(io_parms)) {
4452 struct smbd_buffer_descriptor_v1 *v1;
4453 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4455 rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->subreq.io_iter,
4456 true, need_invalidate);
4457 if (!rdata->mr)
4458 return -EAGAIN;
4460 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4461 if (need_invalidate)
4462 req->Channel = SMB2_CHANNEL_RDMA_V1;
4463 req->ReadChannelInfoOffset =
4464 cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4465 req->ReadChannelInfoLength =
4466 cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4467 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4468 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4469 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4470 v1->length = cpu_to_le32(rdata->mr->mr->length);
4472 *total_len += sizeof(*v1) - 1;
4474 #endif
4475 if (request_type & CHAINED_REQUEST) {
4476 if (!(request_type & END_OF_CHAIN)) {
4477 /* next 8-byte aligned request */
4478 *total_len = ALIGN(*total_len, 8);
4479 shdr->NextCommand = cpu_to_le32(*total_len);
4480 } else /* END_OF_CHAIN */
4481 shdr->NextCommand = 0;
4482 if (request_type & RELATED_REQUEST) {
4483 shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4485 * Related requests use info from previous read request
4486 * in chain.
4488 shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4489 shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4490 req->PersistentFileId = (u64)-1;
4491 req->VolatileFileId = (u64)-1;
4494 if (remaining_bytes > io_parms->length)
4495 req->RemainingBytes = cpu_to_le32(remaining_bytes);
4496 else
4497 req->RemainingBytes = 0;
4499 *buf = req;
4500 return rc;
4503 static void
4504 smb2_readv_callback(struct mid_q_entry *mid)
4506 struct cifs_io_subrequest *rdata = mid->callback_data;
4507 struct netfs_inode *ictx = netfs_inode(rdata->rreq->inode);
4508 struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4509 struct TCP_Server_Info *server = rdata->server;
4510 struct smb2_hdr *shdr =
4511 (struct smb2_hdr *)rdata->iov[0].iov_base;
4512 struct cifs_credits credits = {
4513 .value = 0,
4514 .instance = 0,
4515 .rreq_debug_id = rdata->rreq->debug_id,
4516 .rreq_debug_index = rdata->subreq.debug_index,
4518 struct smb_rqst rqst = { .rq_iov = &rdata->iov[1], .rq_nvec = 1 };
4519 unsigned int rreq_debug_id = rdata->rreq->debug_id;
4520 unsigned int subreq_debug_index = rdata->subreq.debug_index;
4522 if (rdata->got_bytes) {
4523 rqst.rq_iter = rdata->subreq.io_iter;
4526 WARN_ONCE(rdata->server != mid->server,
4527 "rdata server %p != mid server %p",
4528 rdata->server, mid->server);
4530 cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%zu/%zu\n",
4531 __func__, mid->mid, mid->mid_state, rdata->result,
4532 rdata->got_bytes, rdata->subreq.len - rdata->subreq.transferred);
4534 switch (mid->mid_state) {
4535 case MID_RESPONSE_RECEIVED:
4536 credits.value = le16_to_cpu(shdr->CreditRequest);
4537 credits.instance = server->reconnect_instance;
4538 /* result already set, check signature */
4539 if (server->sign && !mid->decrypted) {
4540 int rc;
4542 iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4543 rc = smb2_verify_signature(&rqst, server);
4544 if (rc)
4545 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4546 rc);
4548 /* FIXME: should this be counted toward the initiating task? */
4549 task_io_account_read(rdata->got_bytes);
4550 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4551 break;
4552 case MID_REQUEST_SUBMITTED:
4553 case MID_RETRY_NEEDED:
4554 __set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4555 rdata->result = -EAGAIN;
4556 if (server->sign && rdata->got_bytes)
4557 /* reset bytes number since we can not check a sign */
4558 rdata->got_bytes = 0;
4559 /* FIXME: should this be counted toward the initiating task? */
4560 task_io_account_read(rdata->got_bytes);
4561 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4562 break;
4563 case MID_RESPONSE_MALFORMED:
4564 credits.value = le16_to_cpu(shdr->CreditRequest);
4565 credits.instance = server->reconnect_instance;
4566 fallthrough;
4567 default:
4568 rdata->result = -EIO;
4570 #ifdef CONFIG_CIFS_SMB_DIRECT
4572 * If this rdata has a memory registered, the MR can be freed
4573 * MR needs to be freed as soon as I/O finishes to prevent deadlock
4574 * because they have limited number and are used for future I/Os
4576 if (rdata->mr) {
4577 smbd_deregister_mr(rdata->mr);
4578 rdata->mr = NULL;
4580 #endif
4581 if (rdata->result && rdata->result != -ENODATA) {
4582 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4583 trace_smb3_read_err(rdata->rreq->debug_id,
4584 rdata->subreq.debug_index,
4585 rdata->xid,
4586 rdata->req->cfile->fid.persistent_fid,
4587 tcon->tid, tcon->ses->Suid,
4588 rdata->subreq.start + rdata->subreq.transferred,
4589 rdata->subreq.len - rdata->subreq.transferred,
4590 rdata->result);
4591 } else
4592 trace_smb3_read_done(rdata->rreq->debug_id,
4593 rdata->subreq.debug_index,
4594 rdata->xid,
4595 rdata->req->cfile->fid.persistent_fid,
4596 tcon->tid, tcon->ses->Suid,
4597 rdata->subreq.start + rdata->subreq.transferred,
4598 rdata->got_bytes);
4600 if (rdata->result == -ENODATA) {
4601 __set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4602 rdata->result = 0;
4603 } else {
4604 size_t trans = rdata->subreq.transferred + rdata->got_bytes;
4605 if (trans < rdata->subreq.len &&
4606 rdata->subreq.start + trans == ictx->remote_i_size) {
4607 __set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4608 rdata->result = 0;
4610 if (rdata->got_bytes)
4611 __set_bit(NETFS_SREQ_MADE_PROGRESS, &rdata->subreq.flags);
4613 trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
4614 server->credits, server->in_flight,
4615 0, cifs_trace_rw_credits_read_response_clear);
4616 rdata->credits.value = 0;
4617 rdata->subreq.error = rdata->result;
4618 rdata->subreq.transferred += rdata->got_bytes;
4619 trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_progress);
4620 netfs_read_subreq_terminated(&rdata->subreq);
4621 release_mid(mid);
4622 trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
4623 server->credits, server->in_flight,
4624 credits.value, cifs_trace_rw_credits_read_response_add);
4625 add_credits(server, &credits, 0);
4628 /* smb2_async_readv - send an async read, and set up mid to handle result */
4630 smb2_async_readv(struct cifs_io_subrequest *rdata)
4632 int rc, flags = 0;
4633 char *buf;
4634 struct netfs_io_subrequest *subreq = &rdata->subreq;
4635 struct smb2_hdr *shdr;
4636 struct cifs_io_parms io_parms;
4637 struct smb_rqst rqst = { .rq_iov = rdata->iov,
4638 .rq_nvec = 1 };
4639 struct TCP_Server_Info *server;
4640 struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4641 unsigned int total_len;
4642 int credit_request;
4644 cifs_dbg(FYI, "%s: offset=%llu bytes=%zu\n",
4645 __func__, subreq->start, subreq->len);
4647 if (!rdata->server)
4648 rdata->server = cifs_pick_channel(tcon->ses);
4650 io_parms.tcon = tlink_tcon(rdata->req->cfile->tlink);
4651 io_parms.server = server = rdata->server;
4652 io_parms.offset = subreq->start + subreq->transferred;
4653 io_parms.length = subreq->len - subreq->transferred;
4654 io_parms.persistent_fid = rdata->req->cfile->fid.persistent_fid;
4655 io_parms.volatile_fid = rdata->req->cfile->fid.volatile_fid;
4656 io_parms.pid = rdata->req->pid;
4658 rc = smb2_new_read_req(
4659 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4660 if (rc)
4661 return rc;
4663 if (smb3_encryption_required(io_parms.tcon))
4664 flags |= CIFS_TRANSFORM_REQ;
4666 rdata->iov[0].iov_base = buf;
4667 rdata->iov[0].iov_len = total_len;
4668 rdata->got_bytes = 0;
4669 rdata->result = 0;
4671 shdr = (struct smb2_hdr *)buf;
4673 if (rdata->credits.value > 0) {
4674 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length,
4675 SMB2_MAX_BUFFER_SIZE));
4676 credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4677 if (server->credits >= server->max_credits)
4678 shdr->CreditRequest = cpu_to_le16(0);
4679 else
4680 shdr->CreditRequest = cpu_to_le16(
4681 min_t(int, server->max_credits -
4682 server->credits, credit_request));
4684 rc = adjust_credits(server, rdata, cifs_trace_rw_credits_call_readv_adjust);
4685 if (rc)
4686 goto async_readv_out;
4688 flags |= CIFS_HAS_CREDITS;
4691 rc = cifs_call_async(server, &rqst,
4692 cifs_readv_receive, smb2_readv_callback,
4693 smb3_handle_read_data, rdata, flags,
4694 &rdata->credits);
4695 if (rc) {
4696 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4697 trace_smb3_read_err(rdata->rreq->debug_id,
4698 subreq->debug_index,
4699 rdata->xid, io_parms.persistent_fid,
4700 io_parms.tcon->tid,
4701 io_parms.tcon->ses->Suid,
4702 io_parms.offset,
4703 subreq->len - subreq->transferred, rc);
4706 async_readv_out:
4707 cifs_small_buf_release(buf);
4708 return rc;
4712 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4713 unsigned int *nbytes, char **buf, int *buf_type)
4715 struct smb_rqst rqst;
4716 int resp_buftype, rc;
4717 struct smb2_read_req *req = NULL;
4718 struct smb2_read_rsp *rsp = NULL;
4719 struct kvec iov[1];
4720 struct kvec rsp_iov;
4721 unsigned int total_len;
4722 int flags = CIFS_LOG_ERROR;
4723 struct cifs_ses *ses = io_parms->tcon->ses;
4725 if (!io_parms->server)
4726 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4728 *nbytes = 0;
4729 rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4730 if (rc)
4731 return rc;
4733 if (smb3_encryption_required(io_parms->tcon))
4734 flags |= CIFS_TRANSFORM_REQ;
4736 iov[0].iov_base = (char *)req;
4737 iov[0].iov_len = total_len;
4739 memset(&rqst, 0, sizeof(struct smb_rqst));
4740 rqst.rq_iov = iov;
4741 rqst.rq_nvec = 1;
4743 rc = cifs_send_recv(xid, ses, io_parms->server,
4744 &rqst, &resp_buftype, flags, &rsp_iov);
4745 rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4747 if (rc) {
4748 if (rc != -ENODATA) {
4749 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4750 cifs_dbg(VFS, "Send error in read = %d\n", rc);
4751 trace_smb3_read_err(0, 0, xid,
4752 req->PersistentFileId,
4753 io_parms->tcon->tid, ses->Suid,
4754 io_parms->offset, io_parms->length,
4755 rc);
4756 } else
4757 trace_smb3_read_done(0, 0, xid,
4758 req->PersistentFileId, io_parms->tcon->tid,
4759 ses->Suid, io_parms->offset, 0);
4760 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4761 cifs_small_buf_release(req);
4762 return rc == -ENODATA ? 0 : rc;
4763 } else
4764 trace_smb3_read_done(0, 0, xid,
4765 req->PersistentFileId,
4766 io_parms->tcon->tid, ses->Suid,
4767 io_parms->offset, io_parms->length);
4769 cifs_small_buf_release(req);
4771 *nbytes = le32_to_cpu(rsp->DataLength);
4772 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4773 (*nbytes > io_parms->length)) {
4774 cifs_dbg(FYI, "bad length %d for count %d\n",
4775 *nbytes, io_parms->length);
4776 rc = -EIO;
4777 *nbytes = 0;
4780 if (*buf) {
4781 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4782 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4783 } else if (resp_buftype != CIFS_NO_BUFFER) {
4784 *buf = rsp_iov.iov_base;
4785 if (resp_buftype == CIFS_SMALL_BUFFER)
4786 *buf_type = CIFS_SMALL_BUFFER;
4787 else if (resp_buftype == CIFS_LARGE_BUFFER)
4788 *buf_type = CIFS_LARGE_BUFFER;
4790 return rc;
4794 * Check the mid_state and signature on received buffer (if any), and queue the
4795 * workqueue completion task.
4797 static void
4798 smb2_writev_callback(struct mid_q_entry *mid)
4800 struct cifs_io_subrequest *wdata = mid->callback_data;
4801 struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
4802 struct TCP_Server_Info *server = wdata->server;
4803 struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4804 struct cifs_credits credits = {
4805 .value = 0,
4806 .instance = 0,
4807 .rreq_debug_id = wdata->rreq->debug_id,
4808 .rreq_debug_index = wdata->subreq.debug_index,
4810 unsigned int rreq_debug_id = wdata->rreq->debug_id;
4811 unsigned int subreq_debug_index = wdata->subreq.debug_index;
4812 ssize_t result = 0;
4813 size_t written;
4815 WARN_ONCE(wdata->server != mid->server,
4816 "wdata server %p != mid server %p",
4817 wdata->server, mid->server);
4819 switch (mid->mid_state) {
4820 case MID_RESPONSE_RECEIVED:
4821 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4822 credits.instance = server->reconnect_instance;
4823 result = smb2_check_receive(mid, server, 0);
4824 if (result != 0)
4825 break;
4827 written = le32_to_cpu(rsp->DataLength);
4829 * Mask off high 16 bits when bytes written as returned
4830 * by the server is greater than bytes requested by the
4831 * client. OS/2 servers are known to set incorrect
4832 * CountHigh values.
4834 if (written > wdata->subreq.len)
4835 written &= 0xFFFF;
4837 cifs_stats_bytes_written(tcon, written);
4839 if (written < wdata->subreq.len) {
4840 wdata->result = -ENOSPC;
4841 } else if (written > 0) {
4842 wdata->subreq.len = written;
4843 __set_bit(NETFS_SREQ_MADE_PROGRESS, &wdata->subreq.flags);
4845 break;
4846 case MID_REQUEST_SUBMITTED:
4847 case MID_RETRY_NEEDED:
4848 result = -EAGAIN;
4849 break;
4850 case MID_RESPONSE_MALFORMED:
4851 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4852 credits.instance = server->reconnect_instance;
4853 fallthrough;
4854 default:
4855 result = -EIO;
4856 break;
4858 #ifdef CONFIG_CIFS_SMB_DIRECT
4860 * If this wdata has a memory registered, the MR can be freed
4861 * The number of MRs available is limited, it's important to recover
4862 * used MR as soon as I/O is finished. Hold MR longer in the later
4863 * I/O process can possibly result in I/O deadlock due to lack of MR
4864 * to send request on I/O retry
4866 if (wdata->mr) {
4867 smbd_deregister_mr(wdata->mr);
4868 wdata->mr = NULL;
4870 #endif
4871 if (result) {
4872 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4873 trace_smb3_write_err(wdata->rreq->debug_id,
4874 wdata->subreq.debug_index,
4875 wdata->xid,
4876 wdata->req->cfile->fid.persistent_fid,
4877 tcon->tid, tcon->ses->Suid, wdata->subreq.start,
4878 wdata->subreq.len, wdata->result);
4879 if (wdata->result == -ENOSPC)
4880 pr_warn_once("Out of space writing to %s\n",
4881 tcon->tree_name);
4882 } else
4883 trace_smb3_write_done(wdata->rreq->debug_id,
4884 wdata->subreq.debug_index,
4885 wdata->xid,
4886 wdata->req->cfile->fid.persistent_fid,
4887 tcon->tid, tcon->ses->Suid,
4888 wdata->subreq.start, wdata->subreq.len);
4890 trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, wdata->credits.value,
4891 server->credits, server->in_flight,
4892 0, cifs_trace_rw_credits_write_response_clear);
4893 wdata->credits.value = 0;
4894 trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_progress);
4895 cifs_write_subrequest_terminated(wdata, result ?: written, true);
4896 release_mid(mid);
4897 trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
4898 server->credits, server->in_flight,
4899 credits.value, cifs_trace_rw_credits_write_response_add);
4900 add_credits(server, &credits, 0);
4903 /* smb2_async_writev - send an async write, and set up mid to handle result */
4904 void
4905 smb2_async_writev(struct cifs_io_subrequest *wdata)
4907 int rc = -EACCES, flags = 0;
4908 struct smb2_write_req *req = NULL;
4909 struct smb2_hdr *shdr;
4910 struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
4911 struct TCP_Server_Info *server = wdata->server;
4912 struct kvec iov[1];
4913 struct smb_rqst rqst = { };
4914 unsigned int total_len, xid = wdata->xid;
4915 struct cifs_io_parms _io_parms;
4916 struct cifs_io_parms *io_parms = NULL;
4917 int credit_request;
4920 * in future we may get cifs_io_parms passed in from the caller,
4921 * but for now we construct it here...
4923 _io_parms = (struct cifs_io_parms) {
4924 .tcon = tcon,
4925 .server = server,
4926 .offset = wdata->subreq.start,
4927 .length = wdata->subreq.len,
4928 .persistent_fid = wdata->req->cfile->fid.persistent_fid,
4929 .volatile_fid = wdata->req->cfile->fid.volatile_fid,
4930 .pid = wdata->req->pid,
4932 io_parms = &_io_parms;
4934 rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4935 (void **) &req, &total_len);
4936 if (rc)
4937 goto out;
4939 rqst.rq_iov = iov;
4940 rqst.rq_iter = wdata->subreq.io_iter;
4942 rqst.rq_iov[0].iov_len = total_len - 1;
4943 rqst.rq_iov[0].iov_base = (char *)req;
4944 rqst.rq_nvec += 1;
4946 if (smb3_encryption_required(tcon))
4947 flags |= CIFS_TRANSFORM_REQ;
4949 shdr = (struct smb2_hdr *)req;
4950 shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4952 req->PersistentFileId = io_parms->persistent_fid;
4953 req->VolatileFileId = io_parms->volatile_fid;
4954 req->WriteChannelInfoOffset = 0;
4955 req->WriteChannelInfoLength = 0;
4956 req->Channel = SMB2_CHANNEL_NONE;
4957 req->Length = cpu_to_le32(io_parms->length);
4958 req->Offset = cpu_to_le64(io_parms->offset);
4959 req->DataOffset = cpu_to_le16(
4960 offsetof(struct smb2_write_req, Buffer));
4961 req->RemainingBytes = 0;
4963 trace_smb3_write_enter(wdata->rreq->debug_id,
4964 wdata->subreq.debug_index,
4965 wdata->xid,
4966 io_parms->persistent_fid,
4967 io_parms->tcon->tid,
4968 io_parms->tcon->ses->Suid,
4969 io_parms->offset,
4970 io_parms->length);
4972 #ifdef CONFIG_CIFS_SMB_DIRECT
4974 * If we want to do a server RDMA read, fill in and append
4975 * smbd_buffer_descriptor_v1 to the end of write request
4977 if (smb3_use_rdma_offload(io_parms)) {
4978 struct smbd_buffer_descriptor_v1 *v1;
4979 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4981 wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->subreq.io_iter,
4982 false, need_invalidate);
4983 if (!wdata->mr) {
4984 rc = -EAGAIN;
4985 goto async_writev_out;
4987 /* For RDMA read, I/O size is in RemainingBytes not in Length */
4988 req->RemainingBytes = req->Length;
4989 req->Length = 0;
4990 req->DataOffset = 0;
4991 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4992 if (need_invalidate)
4993 req->Channel = SMB2_CHANNEL_RDMA_V1;
4994 req->WriteChannelInfoOffset =
4995 cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4996 req->WriteChannelInfoLength =
4997 cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4998 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4999 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
5000 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
5001 v1->length = cpu_to_le32(wdata->mr->mr->length);
5003 rqst.rq_iov[0].iov_len += sizeof(*v1);
5006 * We keep wdata->subreq.io_iter,
5007 * but we have to truncate rqst.rq_iter
5009 iov_iter_truncate(&rqst.rq_iter, 0);
5011 #endif
5013 if (wdata->subreq.retry_count > 0)
5014 smb2_set_replay(server, &rqst);
5016 cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
5017 io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter));
5019 if (wdata->credits.value > 0) {
5020 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->subreq.len,
5021 SMB2_MAX_BUFFER_SIZE));
5022 credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
5023 if (server->credits >= server->max_credits)
5024 shdr->CreditRequest = cpu_to_le16(0);
5025 else
5026 shdr->CreditRequest = cpu_to_le16(
5027 min_t(int, server->max_credits -
5028 server->credits, credit_request));
5030 rc = adjust_credits(server, wdata, cifs_trace_rw_credits_call_writev_adjust);
5031 if (rc)
5032 goto async_writev_out;
5034 flags |= CIFS_HAS_CREDITS;
5037 /* XXX: compression + encryption is unsupported for now */
5038 if (((flags & CIFS_TRANSFORM_REQ) != CIFS_TRANSFORM_REQ) && should_compress(tcon, &rqst))
5039 flags |= CIFS_COMPRESS_REQ;
5041 rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
5042 wdata, flags, &wdata->credits);
5043 /* Can't touch wdata if rc == 0 */
5044 if (rc) {
5045 trace_smb3_write_err(wdata->rreq->debug_id,
5046 wdata->subreq.debug_index,
5047 xid,
5048 io_parms->persistent_fid,
5049 io_parms->tcon->tid,
5050 io_parms->tcon->ses->Suid,
5051 io_parms->offset,
5052 io_parms->length,
5053 rc);
5054 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
5057 async_writev_out:
5058 cifs_small_buf_release(req);
5059 out:
5060 if (rc) {
5061 trace_smb3_rw_credits(wdata->rreq->debug_id,
5062 wdata->subreq.debug_index,
5063 wdata->credits.value,
5064 server->credits, server->in_flight,
5065 -(int)wdata->credits.value,
5066 cifs_trace_rw_credits_write_response_clear);
5067 add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
5068 cifs_write_subrequest_terminated(wdata, rc, true);
5073 * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
5074 * The length field from io_parms must be at least 1 and indicates a number of
5075 * elements with data to write that begins with position 1 in iov array. All
5076 * data length is specified by count.
5079 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
5080 unsigned int *nbytes, struct kvec *iov, int n_vec)
5082 struct smb_rqst rqst;
5083 int rc = 0;
5084 struct smb2_write_req *req = NULL;
5085 struct smb2_write_rsp *rsp = NULL;
5086 int resp_buftype;
5087 struct kvec rsp_iov;
5088 int flags = 0;
5089 unsigned int total_len;
5090 struct TCP_Server_Info *server;
5091 int retries = 0, cur_sleep = 1;
5093 replay_again:
5094 /* reinitialize for possible replay */
5095 flags = 0;
5096 *nbytes = 0;
5097 if (!io_parms->server)
5098 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
5099 server = io_parms->server;
5100 if (server == NULL)
5101 return -ECONNABORTED;
5103 if (n_vec < 1)
5104 return rc;
5106 rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
5107 (void **) &req, &total_len);
5108 if (rc)
5109 return rc;
5111 if (smb3_encryption_required(io_parms->tcon))
5112 flags |= CIFS_TRANSFORM_REQ;
5114 req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5116 req->PersistentFileId = io_parms->persistent_fid;
5117 req->VolatileFileId = io_parms->volatile_fid;
5118 req->WriteChannelInfoOffset = 0;
5119 req->WriteChannelInfoLength = 0;
5120 req->Channel = 0;
5121 req->Length = cpu_to_le32(io_parms->length);
5122 req->Offset = cpu_to_le64(io_parms->offset);
5123 req->DataOffset = cpu_to_le16(
5124 offsetof(struct smb2_write_req, Buffer));
5125 req->RemainingBytes = 0;
5127 trace_smb3_write_enter(0, 0, xid, io_parms->persistent_fid,
5128 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
5129 io_parms->offset, io_parms->length);
5131 iov[0].iov_base = (char *)req;
5132 /* 1 for Buffer */
5133 iov[0].iov_len = total_len - 1;
5135 memset(&rqst, 0, sizeof(struct smb_rqst));
5136 rqst.rq_iov = iov;
5137 rqst.rq_nvec = n_vec + 1;
5139 if (retries)
5140 smb2_set_replay(server, &rqst);
5142 rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
5143 &rqst,
5144 &resp_buftype, flags, &rsp_iov);
5145 rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
5147 if (rc) {
5148 trace_smb3_write_err(0, 0, xid,
5149 req->PersistentFileId,
5150 io_parms->tcon->tid,
5151 io_parms->tcon->ses->Suid,
5152 io_parms->offset, io_parms->length, rc);
5153 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
5154 cifs_dbg(VFS, "Send error in write = %d\n", rc);
5155 } else {
5156 *nbytes = le32_to_cpu(rsp->DataLength);
5157 cifs_stats_bytes_written(io_parms->tcon, *nbytes);
5158 trace_smb3_write_done(0, 0, xid,
5159 req->PersistentFileId,
5160 io_parms->tcon->tid,
5161 io_parms->tcon->ses->Suid,
5162 io_parms->offset, *nbytes);
5165 cifs_small_buf_release(req);
5166 free_rsp_buf(resp_buftype, rsp);
5168 if (is_replayable_error(rc) &&
5169 smb2_should_replay(io_parms->tcon, &retries, &cur_sleep))
5170 goto replay_again;
5172 return rc;
5175 int posix_info_sid_size(const void *beg, const void *end)
5177 size_t subauth;
5178 int total;
5180 if (beg + 1 > end)
5181 return -1;
5183 subauth = *(u8 *)(beg+1);
5184 if (subauth < 1 || subauth > 15)
5185 return -1;
5187 total = 1 + 1 + 6 + 4*subauth;
5188 if (beg + total > end)
5189 return -1;
5191 return total;
5194 int posix_info_parse(const void *beg, const void *end,
5195 struct smb2_posix_info_parsed *out)
5198 int total_len = 0;
5199 int owner_len, group_len;
5200 int name_len;
5201 const void *owner_sid;
5202 const void *group_sid;
5203 const void *name;
5205 /* if no end bound given, assume payload to be correct */
5206 if (!end) {
5207 const struct smb2_posix_info *p = beg;
5209 end = beg + le32_to_cpu(p->NextEntryOffset);
5210 /* last element will have a 0 offset, pick a sensible bound */
5211 if (end == beg)
5212 end += 0xFFFF;
5215 /* check base buf */
5216 if (beg + sizeof(struct smb2_posix_info) > end)
5217 return -1;
5218 total_len = sizeof(struct smb2_posix_info);
5220 /* check owner sid */
5221 owner_sid = beg + total_len;
5222 owner_len = posix_info_sid_size(owner_sid, end);
5223 if (owner_len < 0)
5224 return -1;
5225 total_len += owner_len;
5227 /* check group sid */
5228 group_sid = beg + total_len;
5229 group_len = posix_info_sid_size(group_sid, end);
5230 if (group_len < 0)
5231 return -1;
5232 total_len += group_len;
5234 /* check name len */
5235 if (beg + total_len + 4 > end)
5236 return -1;
5237 name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
5238 if (name_len < 1 || name_len > 0xFFFF)
5239 return -1;
5240 total_len += 4;
5242 /* check name */
5243 name = beg + total_len;
5244 if (name + name_len > end)
5245 return -1;
5246 total_len += name_len;
5248 if (out) {
5249 out->base = beg;
5250 out->size = total_len;
5251 out->name_len = name_len;
5252 out->name = name;
5253 memcpy(&out->owner, owner_sid, owner_len);
5254 memcpy(&out->group, group_sid, group_len);
5256 return total_len;
5259 static int posix_info_extra_size(const void *beg, const void *end)
5261 int len = posix_info_parse(beg, end, NULL);
5263 if (len < 0)
5264 return -1;
5265 return len - sizeof(struct smb2_posix_info);
5268 static unsigned int
5269 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
5270 size_t size)
5272 int len;
5273 unsigned int entrycount = 0;
5274 unsigned int next_offset = 0;
5275 char *entryptr;
5276 FILE_DIRECTORY_INFO *dir_info;
5278 if (bufstart == NULL)
5279 return 0;
5281 entryptr = bufstart;
5283 while (1) {
5284 if (entryptr + next_offset < entryptr ||
5285 entryptr + next_offset > end_of_buf ||
5286 entryptr + next_offset + size > end_of_buf) {
5287 cifs_dbg(VFS, "malformed search entry would overflow\n");
5288 break;
5291 entryptr = entryptr + next_offset;
5292 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
5294 if (infotype == SMB_FIND_FILE_POSIX_INFO)
5295 len = posix_info_extra_size(entryptr, end_of_buf);
5296 else
5297 len = le32_to_cpu(dir_info->FileNameLength);
5299 if (len < 0 ||
5300 entryptr + len < entryptr ||
5301 entryptr + len > end_of_buf ||
5302 entryptr + len + size > end_of_buf) {
5303 cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
5304 end_of_buf);
5305 break;
5308 *lastentry = entryptr;
5309 entrycount++;
5311 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5312 if (!next_offset)
5313 break;
5316 return entrycount;
5320 * Readdir/FindFirst
5322 int SMB2_query_directory_init(const unsigned int xid,
5323 struct cifs_tcon *tcon,
5324 struct TCP_Server_Info *server,
5325 struct smb_rqst *rqst,
5326 u64 persistent_fid, u64 volatile_fid,
5327 int index, int info_level)
5329 struct smb2_query_directory_req *req;
5330 unsigned char *bufptr;
5331 __le16 asteriks = cpu_to_le16('*');
5332 unsigned int output_size = CIFSMaxBufSize -
5333 MAX_SMB2_CREATE_RESPONSE_SIZE -
5334 MAX_SMB2_CLOSE_RESPONSE_SIZE;
5335 unsigned int total_len;
5336 struct kvec *iov = rqst->rq_iov;
5337 int len, rc;
5339 rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
5340 (void **) &req, &total_len);
5341 if (rc)
5342 return rc;
5344 switch (info_level) {
5345 case SMB_FIND_FILE_DIRECTORY_INFO:
5346 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
5347 break;
5348 case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5349 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
5350 break;
5351 case SMB_FIND_FILE_POSIX_INFO:
5352 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
5353 break;
5354 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5355 req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
5356 break;
5357 default:
5358 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5359 info_level);
5360 return -EINVAL;
5363 req->FileIndex = cpu_to_le32(index);
5364 req->PersistentFileId = persistent_fid;
5365 req->VolatileFileId = volatile_fid;
5367 len = 0x2;
5368 bufptr = req->Buffer;
5369 memcpy(bufptr, &asteriks, len);
5371 req->FileNameOffset =
5372 cpu_to_le16(sizeof(struct smb2_query_directory_req));
5373 req->FileNameLength = cpu_to_le16(len);
5375 * BB could be 30 bytes or so longer if we used SMB2 specific
5376 * buffer lengths, but this is safe and close enough.
5378 output_size = min_t(unsigned int, output_size, server->maxBuf);
5379 output_size = min_t(unsigned int, output_size, 2 << 15);
5380 req->OutputBufferLength = cpu_to_le32(output_size);
5382 iov[0].iov_base = (char *)req;
5383 /* 1 for Buffer */
5384 iov[0].iov_len = total_len - 1;
5386 iov[1].iov_base = (char *)(req->Buffer);
5387 iov[1].iov_len = len;
5389 trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
5390 tcon->ses->Suid, index, output_size);
5392 return 0;
5395 void SMB2_query_directory_free(struct smb_rqst *rqst)
5397 if (rqst && rqst->rq_iov) {
5398 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
5403 smb2_parse_query_directory(struct cifs_tcon *tcon,
5404 struct kvec *rsp_iov,
5405 int resp_buftype,
5406 struct cifs_search_info *srch_inf)
5408 struct smb2_query_directory_rsp *rsp;
5409 size_t info_buf_size;
5410 char *end_of_smb;
5411 int rc;
5413 rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
5415 switch (srch_inf->info_level) {
5416 case SMB_FIND_FILE_DIRECTORY_INFO:
5417 info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5418 break;
5419 case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5420 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO);
5421 break;
5422 case SMB_FIND_FILE_POSIX_INFO:
5423 /* note that posix payload are variable size */
5424 info_buf_size = sizeof(struct smb2_posix_info);
5425 break;
5426 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5427 info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
5428 break;
5429 default:
5430 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5431 srch_inf->info_level);
5432 return -EINVAL;
5435 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5436 le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
5437 info_buf_size);
5438 if (rc) {
5439 cifs_tcon_dbg(VFS, "bad info payload");
5440 return rc;
5443 srch_inf->unicode = true;
5445 if (srch_inf->ntwrk_buf_start) {
5446 if (srch_inf->smallBuf)
5447 cifs_small_buf_release(srch_inf->ntwrk_buf_start);
5448 else
5449 cifs_buf_release(srch_inf->ntwrk_buf_start);
5451 srch_inf->ntwrk_buf_start = (char *)rsp;
5452 srch_inf->srch_entries_start = srch_inf->last_entry =
5453 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
5454 end_of_smb = rsp_iov->iov_len + (char *)rsp;
5456 srch_inf->entries_in_buffer = num_entries(
5457 srch_inf->info_level,
5458 srch_inf->srch_entries_start,
5459 end_of_smb,
5460 &srch_inf->last_entry,
5461 info_buf_size);
5463 srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
5464 cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
5465 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
5466 srch_inf->srch_entries_start, srch_inf->last_entry);
5467 if (resp_buftype == CIFS_LARGE_BUFFER)
5468 srch_inf->smallBuf = false;
5469 else if (resp_buftype == CIFS_SMALL_BUFFER)
5470 srch_inf->smallBuf = true;
5471 else
5472 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5474 return 0;
5478 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5479 u64 persistent_fid, u64 volatile_fid, int index,
5480 struct cifs_search_info *srch_inf)
5482 struct smb_rqst rqst;
5483 struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5484 struct smb2_query_directory_rsp *rsp = NULL;
5485 int resp_buftype = CIFS_NO_BUFFER;
5486 struct kvec rsp_iov;
5487 int rc = 0;
5488 struct cifs_ses *ses = tcon->ses;
5489 struct TCP_Server_Info *server;
5490 int flags = 0;
5491 int retries = 0, cur_sleep = 1;
5493 replay_again:
5494 /* reinitialize for possible replay */
5495 flags = 0;
5496 server = cifs_pick_channel(ses);
5498 if (!ses || !(ses->server))
5499 return -EIO;
5501 if (smb3_encryption_required(tcon))
5502 flags |= CIFS_TRANSFORM_REQ;
5504 memset(&rqst, 0, sizeof(struct smb_rqst));
5505 memset(&iov, 0, sizeof(iov));
5506 rqst.rq_iov = iov;
5507 rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5509 rc = SMB2_query_directory_init(xid, tcon, server,
5510 &rqst, persistent_fid,
5511 volatile_fid, index,
5512 srch_inf->info_level);
5513 if (rc)
5514 goto qdir_exit;
5516 if (retries)
5517 smb2_set_replay(server, &rqst);
5519 rc = cifs_send_recv(xid, ses, server,
5520 &rqst, &resp_buftype, flags, &rsp_iov);
5521 rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5523 if (rc) {
5524 if (rc == -ENODATA &&
5525 rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5526 trace_smb3_query_dir_done(xid, persistent_fid,
5527 tcon->tid, tcon->ses->Suid, index, 0);
5528 srch_inf->endOfSearch = true;
5529 rc = 0;
5530 } else {
5531 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5532 tcon->ses->Suid, index, 0, rc);
5533 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5535 goto qdir_exit;
5538 rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
5539 srch_inf);
5540 if (rc) {
5541 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5542 tcon->ses->Suid, index, 0, rc);
5543 goto qdir_exit;
5545 resp_buftype = CIFS_NO_BUFFER;
5547 trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5548 tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5550 qdir_exit:
5551 SMB2_query_directory_free(&rqst);
5552 free_rsp_buf(resp_buftype, rsp);
5554 if (is_replayable_error(rc) &&
5555 smb2_should_replay(tcon, &retries, &cur_sleep))
5556 goto replay_again;
5558 return rc;
5562 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5563 struct smb_rqst *rqst,
5564 u64 persistent_fid, u64 volatile_fid, u32 pid,
5565 u8 info_class, u8 info_type, u32 additional_info,
5566 void **data, unsigned int *size)
5568 struct smb2_set_info_req *req;
5569 struct kvec *iov = rqst->rq_iov;
5570 unsigned int i, total_len;
5571 int rc;
5573 rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5574 (void **) &req, &total_len);
5575 if (rc)
5576 return rc;
5578 req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5579 req->InfoType = info_type;
5580 req->FileInfoClass = info_class;
5581 req->PersistentFileId = persistent_fid;
5582 req->VolatileFileId = volatile_fid;
5583 req->AdditionalInformation = cpu_to_le32(additional_info);
5585 req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5586 req->BufferLength = cpu_to_le32(*size);
5588 memcpy(req->Buffer, *data, *size);
5589 total_len += *size;
5591 iov[0].iov_base = (char *)req;
5592 /* 1 for Buffer */
5593 iov[0].iov_len = total_len - 1;
5595 for (i = 1; i < rqst->rq_nvec; i++) {
5596 le32_add_cpu(&req->BufferLength, size[i]);
5597 iov[i].iov_base = (char *)data[i];
5598 iov[i].iov_len = size[i];
5601 return 0;
5604 void
5605 SMB2_set_info_free(struct smb_rqst *rqst)
5607 if (rqst && rqst->rq_iov)
5608 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5611 static int
5612 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5613 u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5614 u8 info_type, u32 additional_info, unsigned int num,
5615 void **data, unsigned int *size)
5617 struct smb_rqst rqst;
5618 struct smb2_set_info_rsp *rsp = NULL;
5619 struct kvec *iov;
5620 struct kvec rsp_iov;
5621 int rc = 0;
5622 int resp_buftype;
5623 struct cifs_ses *ses = tcon->ses;
5624 struct TCP_Server_Info *server;
5625 int flags = 0;
5626 int retries = 0, cur_sleep = 1;
5628 replay_again:
5629 /* reinitialize for possible replay */
5630 flags = 0;
5631 server = cifs_pick_channel(ses);
5633 if (!ses || !server)
5634 return -EIO;
5636 if (!num)
5637 return -EINVAL;
5639 if (smb3_encryption_required(tcon))
5640 flags |= CIFS_TRANSFORM_REQ;
5642 iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5643 if (!iov)
5644 return -ENOMEM;
5646 memset(&rqst, 0, sizeof(struct smb_rqst));
5647 rqst.rq_iov = iov;
5648 rqst.rq_nvec = num;
5650 rc = SMB2_set_info_init(tcon, server,
5651 &rqst, persistent_fid, volatile_fid, pid,
5652 info_class, info_type, additional_info,
5653 data, size);
5654 if (rc) {
5655 kfree(iov);
5656 return rc;
5659 if (retries)
5660 smb2_set_replay(server, &rqst);
5662 rc = cifs_send_recv(xid, ses, server,
5663 &rqst, &resp_buftype, flags,
5664 &rsp_iov);
5665 SMB2_set_info_free(&rqst);
5666 rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5668 if (rc != 0) {
5669 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5670 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5671 ses->Suid, info_class, (__u32)info_type, rc);
5674 free_rsp_buf(resp_buftype, rsp);
5675 kfree(iov);
5677 if (is_replayable_error(rc) &&
5678 smb2_should_replay(tcon, &retries, &cur_sleep))
5679 goto replay_again;
5681 return rc;
5685 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5686 u64 volatile_fid, u32 pid, loff_t new_eof)
5688 struct smb2_file_eof_info info;
5689 void *data;
5690 unsigned int size;
5692 info.EndOfFile = cpu_to_le64(new_eof);
5694 data = &info;
5695 size = sizeof(struct smb2_file_eof_info);
5697 trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5699 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5700 pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5701 0, 1, &data, &size);
5705 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5706 u64 persistent_fid, u64 volatile_fid,
5707 struct smb_ntsd *pnntsd, int pacllen, int aclflag)
5709 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5710 current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5711 1, (void **)&pnntsd, &pacllen);
5715 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5716 u64 persistent_fid, u64 volatile_fid,
5717 struct smb2_file_full_ea_info *buf, int len)
5719 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5720 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5721 0, 1, (void **)&buf, &len);
5725 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5726 const u64 persistent_fid, const u64 volatile_fid,
5727 __u8 oplock_level)
5729 struct smb_rqst rqst;
5730 int rc;
5731 struct smb2_oplock_break *req = NULL;
5732 struct cifs_ses *ses = tcon->ses;
5733 struct TCP_Server_Info *server;
5734 int flags = CIFS_OBREAK_OP;
5735 unsigned int total_len;
5736 struct kvec iov[1];
5737 struct kvec rsp_iov;
5738 int resp_buf_type;
5739 int retries = 0, cur_sleep = 1;
5741 replay_again:
5742 /* reinitialize for possible replay */
5743 flags = CIFS_OBREAK_OP;
5744 server = cifs_pick_channel(ses);
5746 cifs_dbg(FYI, "SMB2_oplock_break\n");
5747 rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5748 (void **) &req, &total_len);
5749 if (rc)
5750 return rc;
5752 if (smb3_encryption_required(tcon))
5753 flags |= CIFS_TRANSFORM_REQ;
5755 req->VolatileFid = volatile_fid;
5756 req->PersistentFid = persistent_fid;
5757 req->OplockLevel = oplock_level;
5758 req->hdr.CreditRequest = cpu_to_le16(1);
5760 flags |= CIFS_NO_RSP_BUF;
5762 iov[0].iov_base = (char *)req;
5763 iov[0].iov_len = total_len;
5765 memset(&rqst, 0, sizeof(struct smb_rqst));
5766 rqst.rq_iov = iov;
5767 rqst.rq_nvec = 1;
5769 if (retries)
5770 smb2_set_replay(server, &rqst);
5772 rc = cifs_send_recv(xid, ses, server,
5773 &rqst, &resp_buf_type, flags, &rsp_iov);
5774 cifs_small_buf_release(req);
5775 if (rc) {
5776 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5777 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5780 if (is_replayable_error(rc) &&
5781 smb2_should_replay(tcon, &retries, &cur_sleep))
5782 goto replay_again;
5784 return rc;
5787 void
5788 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5789 struct kstatfs *kst)
5791 kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5792 le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5793 kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5794 kst->f_bfree = kst->f_bavail =
5795 le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5796 return;
5799 static void
5800 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5801 struct kstatfs *kst)
5803 kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5804 kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5805 kst->f_bfree = le64_to_cpu(response_data->BlocksAvail);
5806 if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5807 kst->f_bavail = kst->f_bfree;
5808 else
5809 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5810 if (response_data->TotalFileNodes != cpu_to_le64(-1))
5811 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5812 if (response_data->FreeFileNodes != cpu_to_le64(-1))
5813 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5815 return;
5818 static int
5819 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5820 struct TCP_Server_Info *server,
5821 int level, int outbuf_len, u64 persistent_fid,
5822 u64 volatile_fid)
5824 int rc;
5825 struct smb2_query_info_req *req;
5826 unsigned int total_len;
5828 cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5830 if ((tcon->ses == NULL) || server == NULL)
5831 return -EIO;
5833 rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5834 (void **) &req, &total_len);
5835 if (rc)
5836 return rc;
5838 req->InfoType = SMB2_O_INFO_FILESYSTEM;
5839 req->FileInfoClass = level;
5840 req->PersistentFileId = persistent_fid;
5841 req->VolatileFileId = volatile_fid;
5842 /* 1 for pad */
5843 req->InputBufferOffset =
5844 cpu_to_le16(sizeof(struct smb2_query_info_req));
5845 req->OutputBufferLength = cpu_to_le32(
5846 outbuf_len + sizeof(struct smb2_query_info_rsp));
5848 iov->iov_base = (char *)req;
5849 iov->iov_len = total_len;
5850 return 0;
5853 static inline void free_qfs_info_req(struct kvec *iov)
5855 cifs_buf_release(iov->iov_base);
5859 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5860 u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5862 struct smb_rqst rqst;
5863 struct smb2_query_info_rsp *rsp = NULL;
5864 struct kvec iov;
5865 struct kvec rsp_iov;
5866 int rc = 0;
5867 int resp_buftype;
5868 struct cifs_ses *ses = tcon->ses;
5869 struct TCP_Server_Info *server;
5870 FILE_SYSTEM_POSIX_INFO *info = NULL;
5871 int flags = 0;
5872 int retries = 0, cur_sleep = 1;
5874 replay_again:
5875 /* reinitialize for possible replay */
5876 flags = 0;
5877 server = cifs_pick_channel(ses);
5879 rc = build_qfs_info_req(&iov, tcon, server,
5880 FS_POSIX_INFORMATION,
5881 sizeof(FILE_SYSTEM_POSIX_INFO),
5882 persistent_fid, volatile_fid);
5883 if (rc)
5884 return rc;
5886 if (smb3_encryption_required(tcon))
5887 flags |= CIFS_TRANSFORM_REQ;
5889 memset(&rqst, 0, sizeof(struct smb_rqst));
5890 rqst.rq_iov = &iov;
5891 rqst.rq_nvec = 1;
5893 if (retries)
5894 smb2_set_replay(server, &rqst);
5896 rc = cifs_send_recv(xid, ses, server,
5897 &rqst, &resp_buftype, flags, &rsp_iov);
5898 free_qfs_info_req(&iov);
5899 if (rc) {
5900 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5901 goto posix_qfsinf_exit;
5903 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5905 info = (FILE_SYSTEM_POSIX_INFO *)(
5906 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5907 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5908 le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5909 sizeof(FILE_SYSTEM_POSIX_INFO));
5910 if (!rc)
5911 copy_posix_fs_info_to_kstatfs(info, fsdata);
5913 posix_qfsinf_exit:
5914 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5916 if (is_replayable_error(rc) &&
5917 smb2_should_replay(tcon, &retries, &cur_sleep))
5918 goto replay_again;
5920 return rc;
5924 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5925 u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5927 struct smb_rqst rqst;
5928 struct smb2_query_info_rsp *rsp = NULL;
5929 struct kvec iov;
5930 struct kvec rsp_iov;
5931 int rc = 0;
5932 int resp_buftype;
5933 struct cifs_ses *ses = tcon->ses;
5934 struct TCP_Server_Info *server;
5935 struct smb2_fs_full_size_info *info = NULL;
5936 int flags = 0;
5937 int retries = 0, cur_sleep = 1;
5939 replay_again:
5940 /* reinitialize for possible replay */
5941 flags = 0;
5942 server = cifs_pick_channel(ses);
5944 rc = build_qfs_info_req(&iov, tcon, server,
5945 FS_FULL_SIZE_INFORMATION,
5946 sizeof(struct smb2_fs_full_size_info),
5947 persistent_fid, volatile_fid);
5948 if (rc)
5949 return rc;
5951 if (smb3_encryption_required(tcon))
5952 flags |= CIFS_TRANSFORM_REQ;
5954 memset(&rqst, 0, sizeof(struct smb_rqst));
5955 rqst.rq_iov = &iov;
5956 rqst.rq_nvec = 1;
5958 if (retries)
5959 smb2_set_replay(server, &rqst);
5961 rc = cifs_send_recv(xid, ses, server,
5962 &rqst, &resp_buftype, flags, &rsp_iov);
5963 free_qfs_info_req(&iov);
5964 if (rc) {
5965 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5966 goto qfsinf_exit;
5968 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5970 info = (struct smb2_fs_full_size_info *)(
5971 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5972 rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5973 le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5974 sizeof(struct smb2_fs_full_size_info));
5975 if (!rc)
5976 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5978 qfsinf_exit:
5979 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5981 if (is_replayable_error(rc) &&
5982 smb2_should_replay(tcon, &retries, &cur_sleep))
5983 goto replay_again;
5985 return rc;
5989 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5990 u64 persistent_fid, u64 volatile_fid, int level)
5992 struct smb_rqst rqst;
5993 struct smb2_query_info_rsp *rsp = NULL;
5994 struct kvec iov;
5995 struct kvec rsp_iov;
5996 int rc = 0;
5997 int resp_buftype, max_len, min_len;
5998 struct cifs_ses *ses = tcon->ses;
5999 struct TCP_Server_Info *server;
6000 unsigned int rsp_len, offset;
6001 int flags = 0;
6002 int retries = 0, cur_sleep = 1;
6004 replay_again:
6005 /* reinitialize for possible replay */
6006 flags = 0;
6007 server = cifs_pick_channel(ses);
6009 if (level == FS_DEVICE_INFORMATION) {
6010 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6011 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6012 } else if (level == FS_ATTRIBUTE_INFORMATION) {
6013 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
6014 min_len = MIN_FS_ATTR_INFO_SIZE;
6015 } else if (level == FS_SECTOR_SIZE_INFORMATION) {
6016 max_len = sizeof(struct smb3_fs_ss_info);
6017 min_len = sizeof(struct smb3_fs_ss_info);
6018 } else if (level == FS_VOLUME_INFORMATION) {
6019 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
6020 min_len = sizeof(struct smb3_fs_vol_info);
6021 } else {
6022 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
6023 return -EINVAL;
6026 rc = build_qfs_info_req(&iov, tcon, server,
6027 level, max_len,
6028 persistent_fid, volatile_fid);
6029 if (rc)
6030 return rc;
6032 if (smb3_encryption_required(tcon))
6033 flags |= CIFS_TRANSFORM_REQ;
6035 memset(&rqst, 0, sizeof(struct smb_rqst));
6036 rqst.rq_iov = &iov;
6037 rqst.rq_nvec = 1;
6039 if (retries)
6040 smb2_set_replay(server, &rqst);
6042 rc = cifs_send_recv(xid, ses, server,
6043 &rqst, &resp_buftype, flags, &rsp_iov);
6044 free_qfs_info_req(&iov);
6045 if (rc) {
6046 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
6047 goto qfsattr_exit;
6049 rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
6051 rsp_len = le32_to_cpu(rsp->OutputBufferLength);
6052 offset = le16_to_cpu(rsp->OutputBufferOffset);
6053 rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
6054 if (rc)
6055 goto qfsattr_exit;
6057 if (level == FS_ATTRIBUTE_INFORMATION)
6058 memcpy(&tcon->fsAttrInfo, offset
6059 + (char *)rsp, min_t(unsigned int,
6060 rsp_len, max_len));
6061 else if (level == FS_DEVICE_INFORMATION)
6062 memcpy(&tcon->fsDevInfo, offset
6063 + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
6064 else if (level == FS_SECTOR_SIZE_INFORMATION) {
6065 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
6066 (offset + (char *)rsp);
6067 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
6068 tcon->perf_sector_size =
6069 le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
6070 } else if (level == FS_VOLUME_INFORMATION) {
6071 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
6072 (offset + (char *)rsp);
6073 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
6074 tcon->vol_create_time = vol_info->VolumeCreationTime;
6077 qfsattr_exit:
6078 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6080 if (is_replayable_error(rc) &&
6081 smb2_should_replay(tcon, &retries, &cur_sleep))
6082 goto replay_again;
6084 return rc;
6088 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
6089 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6090 const __u32 num_lock, struct smb2_lock_element *buf)
6092 struct smb_rqst rqst;
6093 int rc = 0;
6094 struct smb2_lock_req *req = NULL;
6095 struct kvec iov[2];
6096 struct kvec rsp_iov;
6097 int resp_buf_type;
6098 unsigned int count;
6099 int flags = CIFS_NO_RSP_BUF;
6100 unsigned int total_len;
6101 struct TCP_Server_Info *server;
6102 int retries = 0, cur_sleep = 1;
6104 replay_again:
6105 /* reinitialize for possible replay */
6106 flags = CIFS_NO_RSP_BUF;
6107 server = cifs_pick_channel(tcon->ses);
6109 cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
6111 rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
6112 (void **) &req, &total_len);
6113 if (rc)
6114 return rc;
6116 if (smb3_encryption_required(tcon))
6117 flags |= CIFS_TRANSFORM_REQ;
6119 req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
6120 req->LockCount = cpu_to_le16(num_lock);
6122 req->PersistentFileId = persist_fid;
6123 req->VolatileFileId = volatile_fid;
6125 count = num_lock * sizeof(struct smb2_lock_element);
6127 iov[0].iov_base = (char *)req;
6128 iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
6129 iov[1].iov_base = (char *)buf;
6130 iov[1].iov_len = count;
6132 cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
6134 memset(&rqst, 0, sizeof(struct smb_rqst));
6135 rqst.rq_iov = iov;
6136 rqst.rq_nvec = 2;
6138 if (retries)
6139 smb2_set_replay(server, &rqst);
6141 rc = cifs_send_recv(xid, tcon->ses, server,
6142 &rqst, &resp_buf_type, flags,
6143 &rsp_iov);
6144 cifs_small_buf_release(req);
6145 if (rc) {
6146 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
6147 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
6148 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
6149 tcon->ses->Suid, rc);
6152 if (is_replayable_error(rc) &&
6153 smb2_should_replay(tcon, &retries, &cur_sleep))
6154 goto replay_again;
6156 return rc;
6160 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
6161 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6162 const __u64 length, const __u64 offset, const __u32 lock_flags,
6163 const bool wait)
6165 struct smb2_lock_element lock;
6167 lock.Offset = cpu_to_le64(offset);
6168 lock.Length = cpu_to_le64(length);
6169 lock.Flags = cpu_to_le32(lock_flags);
6170 if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
6171 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
6173 return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
6177 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
6178 __u8 *lease_key, const __le32 lease_state)
6180 struct smb_rqst rqst;
6181 int rc;
6182 struct smb2_lease_ack *req = NULL;
6183 struct cifs_ses *ses = tcon->ses;
6184 int flags = CIFS_OBREAK_OP;
6185 unsigned int total_len;
6186 struct kvec iov[1];
6187 struct kvec rsp_iov;
6188 int resp_buf_type;
6189 __u64 *please_key_high;
6190 __u64 *please_key_low;
6191 struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
6193 cifs_dbg(FYI, "SMB2_lease_break\n");
6194 rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
6195 (void **) &req, &total_len);
6196 if (rc)
6197 return rc;
6199 if (smb3_encryption_required(tcon))
6200 flags |= CIFS_TRANSFORM_REQ;
6202 req->hdr.CreditRequest = cpu_to_le16(1);
6203 req->StructureSize = cpu_to_le16(36);
6204 total_len += 12;
6206 memcpy(req->LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
6207 req->LeaseState = lease_state;
6209 flags |= CIFS_NO_RSP_BUF;
6211 iov[0].iov_base = (char *)req;
6212 iov[0].iov_len = total_len;
6214 memset(&rqst, 0, sizeof(struct smb_rqst));
6215 rqst.rq_iov = iov;
6216 rqst.rq_nvec = 1;
6218 rc = cifs_send_recv(xid, ses, server,
6219 &rqst, &resp_buf_type, flags, &rsp_iov);
6220 cifs_small_buf_release(req);
6222 please_key_low = (__u64 *)lease_key;
6223 please_key_high = (__u64 *)(lease_key+8);
6224 if (rc) {
6225 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6226 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
6227 ses->Suid, *please_key_low, *please_key_high, rc);
6228 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
6229 } else
6230 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
6231 ses->Suid, *please_key_low, *please_key_high);
6233 return rc;