HID: hiddev: Fix slab-out-of-bounds write in hiddev_ioctl_usage()
[linux/fpc-iii.git] / fs / cifs / smb2pdu.c
blob4ffd5e177288e2bed644bff5046b0d046668d0d4
1 /*
2 * fs/cifs/smb2pdu.c
4 * Copyright (C) International Business Machines Corp., 2009, 2013
5 * Etersoft, 2012
6 * Author(s): Steve French (sfrench@us.ibm.com)
7 * Pavel Shilovsky (pshilovsky@samba.org) 2012
9 * Contains the routines for constructing the SMB2 PDUs themselves
11 * This library is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published
13 * by the Free Software Foundation; either version 2.1 of the License, or
14 * (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
19 * the GNU Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this library; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
27 /* Note that there are handle based routines which must be */
28 /* treated slightly differently for reconnection purposes since we never */
29 /* want to reuse a stale file handle and only the caller knows the file info */
31 #include <linux/fs.h>
32 #include <linux/kernel.h>
33 #include <linux/vfs.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/uaccess.h>
36 #include <linux/pagemap.h>
37 #include <linux/xattr.h>
38 #include "smb2pdu.h"
39 #include "cifsglob.h"
40 #include "cifsacl.h"
41 #include "cifsproto.h"
42 #include "smb2proto.h"
43 #include "cifs_unicode.h"
44 #include "cifs_debug.h"
45 #include "ntlmssp.h"
46 #include "smb2status.h"
47 #include "smb2glob.h"
48 #include "cifspdu.h"
49 #include "cifs_spnego.h"
52 * The following table defines the expected "StructureSize" of SMB2 requests
53 * in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests.
55 * Note that commands are defined in smb2pdu.h in le16 but the array below is
56 * indexed by command in host byte order.
58 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
59 /* SMB2_NEGOTIATE */ 36,
60 /* SMB2_SESSION_SETUP */ 25,
61 /* SMB2_LOGOFF */ 4,
62 /* SMB2_TREE_CONNECT */ 9,
63 /* SMB2_TREE_DISCONNECT */ 4,
64 /* SMB2_CREATE */ 57,
65 /* SMB2_CLOSE */ 24,
66 /* SMB2_FLUSH */ 24,
67 /* SMB2_READ */ 49,
68 /* SMB2_WRITE */ 49,
69 /* SMB2_LOCK */ 48,
70 /* SMB2_IOCTL */ 57,
71 /* SMB2_CANCEL */ 4,
72 /* SMB2_ECHO */ 4,
73 /* SMB2_QUERY_DIRECTORY */ 33,
74 /* SMB2_CHANGE_NOTIFY */ 32,
75 /* SMB2_QUERY_INFO */ 41,
76 /* SMB2_SET_INFO */ 33,
77 /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
81 static void
82 smb2_hdr_assemble(struct smb2_hdr *hdr, __le16 smb2_cmd /* command */ ,
83 const struct cifs_tcon *tcon)
85 struct smb2_pdu *pdu = (struct smb2_pdu *)hdr;
86 char *temp = (char *)hdr;
87 /* lookup word count ie StructureSize from table */
88 __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_cmd)];
91 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
92 * largest operations (Create)
94 memset(temp, 0, 256);
96 /* Note this is only network field converted to big endian */
97 hdr->smb2_buf_length = cpu_to_be32(parmsize + sizeof(struct smb2_hdr)
98 - 4 /* RFC 1001 length field itself not counted */);
100 hdr->ProtocolId[0] = 0xFE;
101 hdr->ProtocolId[1] = 'S';
102 hdr->ProtocolId[2] = 'M';
103 hdr->ProtocolId[3] = 'B';
104 hdr->StructureSize = cpu_to_le16(64);
105 hdr->Command = smb2_cmd;
106 if (tcon && tcon->ses && tcon->ses->server) {
107 struct TCP_Server_Info *server = tcon->ses->server;
109 spin_lock(&server->req_lock);
110 /* Request up to 2 credits but don't go over the limit. */
111 if (server->credits >= SMB2_MAX_CREDITS_AVAILABLE)
112 hdr->CreditRequest = cpu_to_le16(0);
113 else
114 hdr->CreditRequest = cpu_to_le16(
115 min_t(int, SMB2_MAX_CREDITS_AVAILABLE -
116 server->credits, 2));
117 spin_unlock(&server->req_lock);
118 } else {
119 hdr->CreditRequest = cpu_to_le16(2);
121 hdr->ProcessId = cpu_to_le32((__u16)current->tgid);
123 if (!tcon)
124 goto out;
126 /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
127 /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
128 if ((tcon->ses) && (tcon->ses->server) &&
129 (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
130 hdr->CreditCharge = cpu_to_le16(1);
131 /* else CreditCharge MBZ */
133 hdr->TreeId = tcon->tid;
134 /* Uid is not converted */
135 if (tcon->ses)
136 hdr->SessionId = tcon->ses->Suid;
139 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
140 * to pass the path on the Open SMB prefixed by \\server\share.
141 * Not sure when we would need to do the augmented path (if ever) and
142 * setting this flag breaks the SMB2 open operation since it is
143 * illegal to send an empty path name (without \\server\share prefix)
144 * when the DFS flag is set in the SMB open header. We could
145 * consider setting the flag on all operations other than open
146 * but it is safer to net set it for now.
148 /* if (tcon->share_flags & SHI1005_FLAGS_DFS)
149 hdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
151 if (tcon->ses && tcon->ses->server && tcon->ses->server->sign)
152 hdr->Flags |= SMB2_FLAGS_SIGNED;
153 out:
154 pdu->StructureSize2 = cpu_to_le16(parmsize);
155 return;
158 static int
159 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
161 int rc;
162 struct nls_table *nls_codepage;
163 struct cifs_ses *ses;
164 struct TCP_Server_Info *server;
167 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
168 * check for tcp and smb session status done differently
169 * for those three - in the calling routine.
171 if (tcon == NULL)
172 return 0;
174 if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
175 return 0;
177 if (tcon->tidStatus == CifsExiting) {
179 * only tree disconnect, open, and write,
180 * (and ulogoff which does not have tcon)
181 * are allowed as we start force umount.
183 if ((smb2_command != SMB2_WRITE) &&
184 (smb2_command != SMB2_CREATE) &&
185 (smb2_command != SMB2_TREE_DISCONNECT)) {
186 cifs_dbg(FYI, "can not send cmd %d while umounting\n",
187 smb2_command);
188 return -ENODEV;
191 if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
192 (!tcon->ses->server))
193 return -EIO;
195 ses = tcon->ses;
196 server = ses->server;
199 * Give demultiplex thread up to 10 seconds to reconnect, should be
200 * greater than cifs socket timeout which is 7 seconds
202 while (server->tcpStatus == CifsNeedReconnect) {
204 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
205 * here since they are implicitly done when session drops.
207 switch (smb2_command) {
209 * BB Should we keep oplock break and add flush to exceptions?
211 case SMB2_TREE_DISCONNECT:
212 case SMB2_CANCEL:
213 case SMB2_CLOSE:
214 case SMB2_OPLOCK_BREAK:
215 return -EAGAIN;
218 rc = wait_event_interruptible_timeout(server->response_q,
219 (server->tcpStatus != CifsNeedReconnect),
220 10 * HZ);
221 if (rc < 0) {
222 cifs_dbg(FYI, "%s: aborting reconnect due to a received"
223 " signal by the process\n", __func__);
224 return -ERESTARTSYS;
227 /* are we still trying to reconnect? */
228 if (server->tcpStatus != CifsNeedReconnect)
229 break;
232 * on "soft" mounts we wait once. Hard mounts keep
233 * retrying until process is killed or server comes
234 * back on-line
236 if (!tcon->retry) {
237 cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
238 return -EHOSTDOWN;
242 if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
243 return 0;
245 nls_codepage = load_nls_default();
248 * need to prevent multiple threads trying to simultaneously reconnect
249 * the same SMB session
251 mutex_lock(&tcon->ses->session_mutex);
254 * Recheck after acquire mutex. If another thread is negotiating
255 * and the server never sends an answer the socket will be closed
256 * and tcpStatus set to reconnect.
258 if (server->tcpStatus == CifsNeedReconnect) {
259 rc = -EHOSTDOWN;
260 mutex_unlock(&tcon->ses->session_mutex);
261 goto out;
264 rc = cifs_negotiate_protocol(0, tcon->ses);
265 if (!rc && tcon->ses->need_reconnect) {
266 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
267 if ((rc == -EACCES) && !tcon->retry) {
268 rc = -EHOSTDOWN;
269 mutex_unlock(&tcon->ses->session_mutex);
270 goto failed;
273 if (rc || !tcon->need_reconnect) {
274 mutex_unlock(&tcon->ses->session_mutex);
275 goto out;
278 cifs_mark_open_files_invalid(tcon);
279 rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
280 mutex_unlock(&tcon->ses->session_mutex);
281 cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
282 if (rc)
283 goto out;
284 atomic_inc(&tconInfoReconnectCount);
285 out:
287 * Check if handle based operation so we know whether we can continue
288 * or not without returning to caller to reset file handle.
291 * BB Is flush done by server on drop of tcp session? Should we special
292 * case it and skip above?
294 switch (smb2_command) {
295 case SMB2_FLUSH:
296 case SMB2_READ:
297 case SMB2_WRITE:
298 case SMB2_LOCK:
299 case SMB2_IOCTL:
300 case SMB2_QUERY_DIRECTORY:
301 case SMB2_CHANGE_NOTIFY:
302 case SMB2_QUERY_INFO:
303 case SMB2_SET_INFO:
304 rc = -EAGAIN;
306 failed:
307 unload_nls(nls_codepage);
308 return rc;
312 * Allocate and return pointer to an SMB request hdr, and set basic
313 * SMB information in the SMB header. If the return code is zero, this
314 * function must have filled in request_buf pointer.
316 static int
317 small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
318 void **request_buf)
320 int rc = 0;
322 rc = smb2_reconnect(smb2_command, tcon);
323 if (rc)
324 return rc;
326 /* BB eventually switch this to SMB2 specific small buf size */
327 *request_buf = cifs_small_buf_get();
328 if (*request_buf == NULL) {
329 /* BB should we add a retry in here if not a writepage? */
330 return -ENOMEM;
333 smb2_hdr_assemble((struct smb2_hdr *) *request_buf, smb2_command, tcon);
335 if (tcon != NULL) {
336 #ifdef CONFIG_CIFS_STATS
337 uint16_t com_code = le16_to_cpu(smb2_command);
338 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
339 #endif
340 cifs_stats_inc(&tcon->num_smbs_sent);
343 return rc;
346 #ifdef CONFIG_CIFS_SMB311
347 /* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */
348 #define OFFSET_OF_NEG_CONTEXT 0x68 /* sizeof(struct smb2_negotiate_req) - 4 */
351 #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES cpu_to_le16(1)
352 #define SMB2_ENCRYPTION_CAPABILITIES cpu_to_le16(2)
354 static void
355 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
357 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
358 pneg_ctxt->DataLength = cpu_to_le16(38);
359 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
360 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
361 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
362 pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
365 static void
366 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
368 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
369 pneg_ctxt->DataLength = cpu_to_le16(6);
370 pneg_ctxt->CipherCount = cpu_to_le16(2);
371 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
372 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
375 static void
376 assemble_neg_contexts(struct smb2_negotiate_req *req)
379 /* +4 is to account for the RFC1001 len field */
380 char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4;
382 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
383 /* Add 2 to size to round to 8 byte boundary */
384 pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context);
385 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
386 req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
387 req->NegotiateContextCount = cpu_to_le16(2);
388 inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context)
389 + sizeof(struct smb2_encryption_neg_context)); /* calculate hash */
391 #else
392 static void assemble_neg_contexts(struct smb2_negotiate_req *req)
394 return;
396 #endif /* SMB311 */
401 * SMB2 Worker functions follow:
403 * The general structure of the worker functions is:
404 * 1) Call smb2_init (assembles SMB2 header)
405 * 2) Initialize SMB2 command specific fields in fixed length area of SMB
406 * 3) Call smb_sendrcv2 (sends request on socket and waits for response)
407 * 4) Decode SMB2 command specific fields in the fixed length area
408 * 5) Decode variable length data area (if any for this SMB2 command type)
409 * 6) Call free smb buffer
410 * 7) return
415 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
417 struct smb2_negotiate_req *req;
418 struct smb2_negotiate_rsp *rsp;
419 struct kvec iov[1];
420 int rc = 0;
421 int resp_buftype;
422 struct TCP_Server_Info *server = ses->server;
423 int blob_offset, blob_length;
424 char *security_blob;
425 int flags = CIFS_NEG_OP;
427 cifs_dbg(FYI, "Negotiate protocol\n");
429 if (!server) {
430 WARN(1, "%s: server is NULL!\n", __func__);
431 return -EIO;
434 rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
435 if (rc)
436 return rc;
438 req->hdr.SessionId = 0;
440 req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
442 req->DialectCount = cpu_to_le16(1); /* One vers= at a time for now */
443 inc_rfc1001_len(req, 2);
445 /* only one of SMB2 signing flags may be set in SMB2 request */
446 if (ses->sign)
447 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
448 else if (global_secflags & CIFSSEC_MAY_SIGN)
449 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
450 else
451 req->SecurityMode = 0;
453 req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
455 /* ClientGUID must be zero for SMB2.02 dialect */
456 if (ses->server->vals->protocol_id == SMB20_PROT_ID)
457 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
458 else {
459 memcpy(req->ClientGUID, server->client_guid,
460 SMB2_CLIENT_GUID_SIZE);
461 if (ses->server->vals->protocol_id == SMB311_PROT_ID)
462 assemble_neg_contexts(req);
464 iov[0].iov_base = (char *)req;
465 /* 4 for rfc1002 length field */
466 iov[0].iov_len = get_rfc1002_length(req) + 4;
468 rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags);
470 rsp = (struct smb2_negotiate_rsp *)iov[0].iov_base;
472 * No tcon so can't do
473 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
475 if (rc != 0)
476 goto neg_exit;
478 cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
480 /* BB we may eventually want to match the negotiated vs. requested
481 dialect, even though we are only requesting one at a time */
482 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
483 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
484 else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
485 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
486 else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
487 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
488 else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
489 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
490 #ifdef CONFIG_CIFS_SMB311
491 else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
492 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
493 #endif /* SMB311 */
494 else {
495 cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
496 le16_to_cpu(rsp->DialectRevision));
497 rc = -EIO;
498 goto neg_exit;
500 server->dialect = le16_to_cpu(rsp->DialectRevision);
502 /* SMB2 only has an extended negflavor */
503 server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
504 /* set it to the maximum buffer size value we can send with 1 credit */
505 server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
506 SMB2_MAX_BUFFER_SIZE);
507 server->max_read = le32_to_cpu(rsp->MaxReadSize);
508 server->max_write = le32_to_cpu(rsp->MaxWriteSize);
509 /* BB Do we need to validate the SecurityMode? */
510 server->sec_mode = le16_to_cpu(rsp->SecurityMode);
511 server->capabilities = le32_to_cpu(rsp->Capabilities);
512 /* Internal types */
513 server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
515 security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
516 &rsp->hdr);
518 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
519 * for us will be
520 * ses->sectype = RawNTLMSSP;
521 * but for time being this is our only auth choice so doesn't matter.
522 * We just found a server which sets blob length to zero expecting raw.
524 if (blob_length == 0)
525 cifs_dbg(FYI, "missing security blob on negprot\n");
527 rc = cifs_enable_signing(server, ses->sign);
528 if (rc)
529 goto neg_exit;
530 if (blob_length) {
531 rc = decode_negTokenInit(security_blob, blob_length, server);
532 if (rc == 1)
533 rc = 0;
534 else if (rc == 0)
535 rc = -EIO;
537 neg_exit:
538 free_rsp_buf(resp_buftype, rsp);
539 return rc;
542 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
544 int rc = 0;
545 struct validate_negotiate_info_req vneg_inbuf;
546 struct validate_negotiate_info_rsp *pneg_rsp;
547 u32 rsplen;
549 cifs_dbg(FYI, "validate negotiate\n");
552 * validation ioctl must be signed, so no point sending this if we
553 * can not sign it (ie are not known user). Even if signing is not
554 * required (enabled but not negotiated), in those cases we selectively
555 * sign just this, the first and only signed request on a connection.
556 * Having validation of negotiate info helps reduce attack vectors.
558 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
559 return 0; /* validation requires signing */
561 if (tcon->ses->user_name == NULL) {
562 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
563 return 0; /* validation requires signing */
566 if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
567 cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
569 vneg_inbuf.Capabilities =
570 cpu_to_le32(tcon->ses->server->vals->req_capabilities);
571 memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid,
572 SMB2_CLIENT_GUID_SIZE);
574 if (tcon->ses->sign)
575 vneg_inbuf.SecurityMode =
576 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
577 else if (global_secflags & CIFSSEC_MAY_SIGN)
578 vneg_inbuf.SecurityMode =
579 cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
580 else
581 vneg_inbuf.SecurityMode = 0;
583 vneg_inbuf.DialectCount = cpu_to_le16(1);
584 vneg_inbuf.Dialects[0] =
585 cpu_to_le16(tcon->ses->server->vals->protocol_id);
587 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
588 FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
589 (char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req),
590 (char **)&pneg_rsp, &rsplen);
592 if (rc != 0) {
593 cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
594 return -EIO;
597 if (rsplen != sizeof(struct validate_negotiate_info_rsp)) {
598 cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n",
599 rsplen);
601 /* relax check since Mac returns max bufsize allowed on ioctl */
602 if (rsplen > CIFSMaxBufSize)
603 return -EIO;
606 /* check validate negotiate info response matches what we got earlier */
607 if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->dialect))
608 goto vneg_out;
610 if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
611 goto vneg_out;
613 /* do not validate server guid because not saved at negprot time yet */
615 if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
616 SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
617 goto vneg_out;
619 /* validate negotiate successful */
620 cifs_dbg(FYI, "validate negotiate info successful\n");
621 return 0;
623 vneg_out:
624 cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
625 return -EIO;
629 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
630 const struct nls_table *nls_cp)
632 struct smb2_sess_setup_req *req;
633 struct smb2_sess_setup_rsp *rsp = NULL;
634 struct kvec iov[2];
635 int rc = 0;
636 int resp_buftype = CIFS_NO_BUFFER;
637 __le32 phase = NtLmNegotiate; /* NTLMSSP, if needed, is multistage */
638 struct TCP_Server_Info *server = ses->server;
639 u16 blob_length = 0;
640 struct key *spnego_key = NULL;
641 char *security_blob = NULL;
642 unsigned char *ntlmssp_blob = NULL;
643 bool use_spnego = false; /* else use raw ntlmssp */
644 u64 previous_session = ses->Suid;
646 cifs_dbg(FYI, "Session Setup\n");
648 if (!server) {
649 WARN(1, "%s: server is NULL!\n", __func__);
650 return -EIO;
654 * If we are here due to reconnect, free per-smb session key
655 * in case signing was required.
657 kfree(ses->auth_key.response);
658 ses->auth_key.response = NULL;
661 * If memory allocation is successful, caller of this function
662 * frees it.
664 ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
665 if (!ses->ntlmssp)
666 return -ENOMEM;
667 ses->ntlmssp->sesskey_per_smbsess = true;
669 /* FIXME: allow for other auth types besides NTLMSSP (e.g. krb5) */
670 if (ses->sectype != Kerberos && ses->sectype != RawNTLMSSP)
671 ses->sectype = RawNTLMSSP;
673 ssetup_ntlmssp_authenticate:
674 if (phase == NtLmChallenge)
675 phase = NtLmAuthenticate; /* if ntlmssp, now final phase */
677 rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
678 if (rc)
679 return rc;
681 req->hdr.SessionId = 0; /* First session, not a reauthenticate */
683 /* if reconnect, we need to send previous sess id, otherwise it is 0 */
684 req->PreviousSessionId = previous_session;
686 req->Flags = 0; /* MBZ */
687 /* to enable echos and oplocks */
688 req->hdr.CreditRequest = cpu_to_le16(3);
690 /* only one of SMB2 signing flags may be set in SMB2 request */
691 if (server->sign)
692 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
693 else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
694 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
695 else
696 req->SecurityMode = 0;
698 #ifdef CONFIG_CIFS_DFS_UPCALL
699 req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
700 #else
701 req->Capabilities = 0;
702 #endif /* DFS_UPCALL */
704 req->Channel = 0; /* MBZ */
706 iov[0].iov_base = (char *)req;
707 /* 4 for rfc1002 length field and 1 for pad */
708 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
710 if (ses->sectype == Kerberos) {
711 #ifdef CONFIG_CIFS_UPCALL
712 struct cifs_spnego_msg *msg;
714 spnego_key = cifs_get_spnego_key(ses);
715 if (IS_ERR(spnego_key)) {
716 rc = PTR_ERR(spnego_key);
717 spnego_key = NULL;
718 goto ssetup_exit;
721 msg = spnego_key->payload.data[0];
723 * check version field to make sure that cifs.upcall is
724 * sending us a response in an expected form
726 if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
727 cifs_dbg(VFS,
728 "bad cifs.upcall version. Expected %d got %d",
729 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
730 rc = -EKEYREJECTED;
731 goto ssetup_exit;
733 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
734 GFP_KERNEL);
735 if (!ses->auth_key.response) {
736 cifs_dbg(VFS,
737 "Kerberos can't allocate (%u bytes) memory",
738 msg->sesskey_len);
739 rc = -ENOMEM;
740 goto ssetup_exit;
742 ses->auth_key.len = msg->sesskey_len;
743 blob_length = msg->secblob_len;
744 iov[1].iov_base = msg->data + msg->sesskey_len;
745 iov[1].iov_len = blob_length;
746 #else
747 rc = -EOPNOTSUPP;
748 goto ssetup_exit;
749 #endif /* CONFIG_CIFS_UPCALL */
750 } else if (phase == NtLmNegotiate) { /* if not krb5 must be ntlmssp */
751 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
752 GFP_KERNEL);
753 if (ntlmssp_blob == NULL) {
754 rc = -ENOMEM;
755 goto ssetup_exit;
757 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
758 if (use_spnego) {
759 /* blob_length = build_spnego_ntlmssp_blob(
760 &security_blob,
761 sizeof(struct _NEGOTIATE_MESSAGE),
762 ntlmssp_blob); */
763 /* BB eventually need to add this */
764 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
765 rc = -EOPNOTSUPP;
766 kfree(ntlmssp_blob);
767 goto ssetup_exit;
768 } else {
769 blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
770 /* with raw NTLMSSP we don't encapsulate in SPNEGO */
771 security_blob = ntlmssp_blob;
773 iov[1].iov_base = security_blob;
774 iov[1].iov_len = blob_length;
775 } else if (phase == NtLmAuthenticate) {
776 req->hdr.SessionId = ses->Suid;
777 rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
778 nls_cp);
779 if (rc) {
780 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n",
781 rc);
782 goto ssetup_exit; /* BB double check error handling */
784 if (use_spnego) {
785 /* blob_length = build_spnego_ntlmssp_blob(
786 &security_blob,
787 blob_length,
788 ntlmssp_blob); */
789 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
790 rc = -EOPNOTSUPP;
791 kfree(ntlmssp_blob);
792 goto ssetup_exit;
793 } else {
794 security_blob = ntlmssp_blob;
796 iov[1].iov_base = security_blob;
797 iov[1].iov_len = blob_length;
798 } else {
799 cifs_dbg(VFS, "illegal ntlmssp phase\n");
800 rc = -EIO;
801 goto ssetup_exit;
804 /* Testing shows that buffer offset must be at location of Buffer[0] */
805 req->SecurityBufferOffset =
806 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
807 1 /* pad */ - 4 /* rfc1001 len */);
808 req->SecurityBufferLength = cpu_to_le16(blob_length);
810 inc_rfc1001_len(req, blob_length - 1 /* pad */);
812 /* BB add code to build os and lm fields */
814 rc = SendReceive2(xid, ses, iov, 2, &resp_buftype,
815 CIFS_LOG_ERROR | CIFS_NEG_OP);
817 kfree(security_blob);
818 rsp = (struct smb2_sess_setup_rsp *)iov[0].iov_base;
819 ses->Suid = rsp->hdr.SessionId;
820 if (resp_buftype != CIFS_NO_BUFFER &&
821 rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) {
822 if (phase != NtLmNegotiate) {
823 cifs_dbg(VFS, "Unexpected more processing error\n");
824 goto ssetup_exit;
826 if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
827 le16_to_cpu(rsp->SecurityBufferOffset)) {
828 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
829 le16_to_cpu(rsp->SecurityBufferOffset));
830 rc = -EIO;
831 goto ssetup_exit;
834 /* NTLMSSP Negotiate sent now processing challenge (response) */
835 phase = NtLmChallenge; /* process ntlmssp challenge */
836 rc = 0; /* MORE_PROCESSING is not an error here but expected */
837 rc = decode_ntlmssp_challenge(rsp->Buffer,
838 le16_to_cpu(rsp->SecurityBufferLength), ses);
842 * BB eventually add code for SPNEGO decoding of NtlmChallenge blob,
843 * but at least the raw NTLMSSP case works.
846 * No tcon so can't do
847 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
849 if (rc != 0)
850 goto ssetup_exit;
852 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
853 if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
854 cifs_dbg(VFS, "SMB3 encryption not supported yet\n");
855 ssetup_exit:
856 free_rsp_buf(resp_buftype, rsp);
858 /* if ntlmssp, and negotiate succeeded, proceed to authenticate phase */
859 if ((phase == NtLmChallenge) && (rc == 0))
860 goto ssetup_ntlmssp_authenticate;
862 if (!rc) {
863 mutex_lock(&server->srv_mutex);
864 if (server->ops->generate_signingkey) {
865 rc = server->ops->generate_signingkey(ses);
866 if (rc) {
867 cifs_dbg(FYI,
868 "SMB3 session key generation failed\n");
869 mutex_unlock(&server->srv_mutex);
870 goto keygen_exit;
873 if (!server->session_estab) {
874 server->sequence_number = 0x2;
875 server->session_estab = true;
877 mutex_unlock(&server->srv_mutex);
879 cifs_dbg(FYI, "SMB2/3 session established successfully\n");
880 spin_lock(&GlobalMid_Lock);
881 ses->status = CifsGood;
882 ses->need_reconnect = false;
883 spin_unlock(&GlobalMid_Lock);
886 keygen_exit:
887 if (spnego_key) {
888 key_invalidate(spnego_key);
889 key_put(spnego_key);
891 kfree(ses->ntlmssp);
893 return rc;
897 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
899 struct smb2_logoff_req *req; /* response is also trivial struct */
900 int rc = 0;
901 struct TCP_Server_Info *server;
903 cifs_dbg(FYI, "disconnect session %p\n", ses);
905 if (ses && (ses->server))
906 server = ses->server;
907 else
908 return -EIO;
910 /* no need to send SMB logoff if uid already closed due to reconnect */
911 if (ses->need_reconnect)
912 goto smb2_session_already_dead;
914 rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
915 if (rc)
916 return rc;
918 /* since no tcon, smb2_init can not do this, so do here */
919 req->hdr.SessionId = ses->Suid;
920 if (server->sign)
921 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
923 rc = SendReceiveNoRsp(xid, ses, (char *) &req->hdr, 0);
925 * No tcon so can't do
926 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
929 smb2_session_already_dead:
930 return rc;
933 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
935 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
938 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
940 /* These are similar values to what Windows uses */
941 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
943 tcon->max_chunks = 256;
944 tcon->max_bytes_chunk = 1048576;
945 tcon->max_bytes_copy = 16777216;
949 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
950 struct cifs_tcon *tcon, const struct nls_table *cp)
952 struct smb2_tree_connect_req *req;
953 struct smb2_tree_connect_rsp *rsp = NULL;
954 struct kvec iov[2];
955 int rc = 0;
956 int resp_buftype;
957 int unc_path_len;
958 struct TCP_Server_Info *server;
959 __le16 *unc_path = NULL;
961 cifs_dbg(FYI, "TCON\n");
963 if ((ses->server) && tree)
964 server = ses->server;
965 else
966 return -EIO;
968 if ((tcon && tcon->seal) &&
969 ((ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) == 0)) {
970 cifs_dbg(VFS, "encryption requested but no server support");
971 return -EOPNOTSUPP;
974 unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
975 if (unc_path == NULL)
976 return -ENOMEM;
978 unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
979 unc_path_len *= 2;
980 if (unc_path_len < 2) {
981 kfree(unc_path);
982 return -EINVAL;
985 /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
986 if (tcon)
987 tcon->tid = 0;
989 rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
990 if (rc) {
991 kfree(unc_path);
992 return rc;
995 if (tcon == NULL) {
996 /* since no tcon, smb2_init can not do this, so do here */
997 req->hdr.SessionId = ses->Suid;
998 /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
999 req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
1002 iov[0].iov_base = (char *)req;
1003 /* 4 for rfc1002 length field and 1 for pad */
1004 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1006 /* Testing shows that buffer offset must be at location of Buffer[0] */
1007 req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1008 - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
1009 req->PathLength = cpu_to_le16(unc_path_len - 2);
1010 iov[1].iov_base = unc_path;
1011 iov[1].iov_len = unc_path_len;
1013 inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
1015 rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
1016 rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
1018 if (rc != 0) {
1019 if (tcon) {
1020 cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1021 tcon->need_reconnect = true;
1023 goto tcon_error_exit;
1026 if (tcon == NULL) {
1027 ses->ipc_tid = rsp->hdr.TreeId;
1028 goto tcon_exit;
1031 switch (rsp->ShareType) {
1032 case SMB2_SHARE_TYPE_DISK:
1033 cifs_dbg(FYI, "connection to disk share\n");
1034 break;
1035 case SMB2_SHARE_TYPE_PIPE:
1036 tcon->ipc = true;
1037 cifs_dbg(FYI, "connection to pipe share\n");
1038 break;
1039 case SMB2_SHARE_TYPE_PRINT:
1040 tcon->ipc = true;
1041 cifs_dbg(FYI, "connection to printer\n");
1042 break;
1043 default:
1044 cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1045 rc = -EOPNOTSUPP;
1046 goto tcon_error_exit;
1049 tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1050 tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1051 tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1052 tcon->tidStatus = CifsGood;
1053 tcon->need_reconnect = false;
1054 tcon->tid = rsp->hdr.TreeId;
1055 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1057 if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1058 ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1059 cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1060 init_copy_chunk_defaults(tcon);
1061 if (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)
1062 cifs_dbg(VFS, "Encrypted shares not supported");
1063 if (tcon->ses->server->ops->validate_negotiate)
1064 rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1065 tcon_exit:
1066 free_rsp_buf(resp_buftype, rsp);
1067 kfree(unc_path);
1068 return rc;
1070 tcon_error_exit:
1071 if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
1072 cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1074 goto tcon_exit;
1078 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1080 struct smb2_tree_disconnect_req *req; /* response is trivial */
1081 int rc = 0;
1082 struct TCP_Server_Info *server;
1083 struct cifs_ses *ses = tcon->ses;
1085 cifs_dbg(FYI, "Tree Disconnect\n");
1087 if (ses && (ses->server))
1088 server = ses->server;
1089 else
1090 return -EIO;
1092 if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1093 return 0;
1095 rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
1096 if (rc)
1097 return rc;
1099 rc = SendReceiveNoRsp(xid, ses, (char *)&req->hdr, 0);
1100 if (rc)
1101 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1103 return rc;
1107 static struct create_durable *
1108 create_durable_buf(void)
1110 struct create_durable *buf;
1112 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1113 if (!buf)
1114 return NULL;
1116 buf->ccontext.DataOffset = cpu_to_le16(offsetof
1117 (struct create_durable, Data));
1118 buf->ccontext.DataLength = cpu_to_le32(16);
1119 buf->ccontext.NameOffset = cpu_to_le16(offsetof
1120 (struct create_durable, Name));
1121 buf->ccontext.NameLength = cpu_to_le16(4);
1122 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1123 buf->Name[0] = 'D';
1124 buf->Name[1] = 'H';
1125 buf->Name[2] = 'n';
1126 buf->Name[3] = 'Q';
1127 return buf;
1130 static struct create_durable *
1131 create_reconnect_durable_buf(struct cifs_fid *fid)
1133 struct create_durable *buf;
1135 buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1136 if (!buf)
1137 return NULL;
1139 buf->ccontext.DataOffset = cpu_to_le16(offsetof
1140 (struct create_durable, Data));
1141 buf->ccontext.DataLength = cpu_to_le32(16);
1142 buf->ccontext.NameOffset = cpu_to_le16(offsetof
1143 (struct create_durable, Name));
1144 buf->ccontext.NameLength = cpu_to_le16(4);
1145 buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1146 buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1147 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1148 buf->Name[0] = 'D';
1149 buf->Name[1] = 'H';
1150 buf->Name[2] = 'n';
1151 buf->Name[3] = 'C';
1152 return buf;
1155 static __u8
1156 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1157 unsigned int *epoch)
1159 char *data_offset;
1160 struct create_context *cc;
1161 unsigned int next;
1162 unsigned int remaining;
1163 char *name;
1165 data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
1166 remaining = le32_to_cpu(rsp->CreateContextsLength);
1167 cc = (struct create_context *)data_offset;
1168 while (remaining >= sizeof(struct create_context)) {
1169 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1170 if (le16_to_cpu(cc->NameLength) == 4 &&
1171 strncmp(name, "RqLs", 4) == 0)
1172 return server->ops->parse_lease_buf(cc, epoch);
1174 next = le32_to_cpu(cc->Next);
1175 if (!next)
1176 break;
1177 remaining -= next;
1178 cc = (struct create_context *)((char *)cc + next);
1181 return 0;
1184 static int
1185 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1186 unsigned int *num_iovec, __u8 *oplock)
1188 struct smb2_create_req *req = iov[0].iov_base;
1189 unsigned int num = *num_iovec;
1191 iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
1192 if (iov[num].iov_base == NULL)
1193 return -ENOMEM;
1194 iov[num].iov_len = server->vals->create_lease_size;
1195 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1196 if (!req->CreateContextsOffset)
1197 req->CreateContextsOffset = cpu_to_le32(
1198 sizeof(struct smb2_create_req) - 4 +
1199 iov[num - 1].iov_len);
1200 le32_add_cpu(&req->CreateContextsLength,
1201 server->vals->create_lease_size);
1202 inc_rfc1001_len(&req->hdr, server->vals->create_lease_size);
1203 *num_iovec = num + 1;
1204 return 0;
1207 static struct create_durable_v2 *
1208 create_durable_v2_buf(struct cifs_fid *pfid)
1210 struct create_durable_v2 *buf;
1212 buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1213 if (!buf)
1214 return NULL;
1216 buf->ccontext.DataOffset = cpu_to_le16(offsetof
1217 (struct create_durable_v2, dcontext));
1218 buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1219 buf->ccontext.NameOffset = cpu_to_le16(offsetof
1220 (struct create_durable_v2, Name));
1221 buf->ccontext.NameLength = cpu_to_le16(4);
1223 buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1224 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1225 generate_random_uuid(buf->dcontext.CreateGuid);
1226 memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1228 /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1229 buf->Name[0] = 'D';
1230 buf->Name[1] = 'H';
1231 buf->Name[2] = '2';
1232 buf->Name[3] = 'Q';
1233 return buf;
1236 static struct create_durable_handle_reconnect_v2 *
1237 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1239 struct create_durable_handle_reconnect_v2 *buf;
1241 buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1242 GFP_KERNEL);
1243 if (!buf)
1244 return NULL;
1246 buf->ccontext.DataOffset =
1247 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1248 dcontext));
1249 buf->ccontext.DataLength =
1250 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1251 buf->ccontext.NameOffset =
1252 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1253 Name));
1254 buf->ccontext.NameLength = cpu_to_le16(4);
1256 buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1257 buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1258 buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1259 memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1261 /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1262 buf->Name[0] = 'D';
1263 buf->Name[1] = 'H';
1264 buf->Name[2] = '2';
1265 buf->Name[3] = 'C';
1266 return buf;
1269 static int
1270 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1271 struct cifs_open_parms *oparms)
1273 struct smb2_create_req *req = iov[0].iov_base;
1274 unsigned int num = *num_iovec;
1276 iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1277 if (iov[num].iov_base == NULL)
1278 return -ENOMEM;
1279 iov[num].iov_len = sizeof(struct create_durable_v2);
1280 if (!req->CreateContextsOffset)
1281 req->CreateContextsOffset =
1282 cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1283 iov[1].iov_len);
1284 le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1285 inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2));
1286 *num_iovec = num + 1;
1287 return 0;
1290 static int
1291 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1292 struct cifs_open_parms *oparms)
1294 struct smb2_create_req *req = iov[0].iov_base;
1295 unsigned int num = *num_iovec;
1297 /* indicate that we don't need to relock the file */
1298 oparms->reconnect = false;
1300 iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1301 if (iov[num].iov_base == NULL)
1302 return -ENOMEM;
1303 iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1304 if (!req->CreateContextsOffset)
1305 req->CreateContextsOffset =
1306 cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1307 iov[1].iov_len);
1308 le32_add_cpu(&req->CreateContextsLength,
1309 sizeof(struct create_durable_handle_reconnect_v2));
1310 inc_rfc1001_len(&req->hdr,
1311 sizeof(struct create_durable_handle_reconnect_v2));
1312 *num_iovec = num + 1;
1313 return 0;
1316 static int
1317 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1318 struct cifs_open_parms *oparms, bool use_persistent)
1320 struct smb2_create_req *req = iov[0].iov_base;
1321 unsigned int num = *num_iovec;
1323 if (use_persistent) {
1324 if (oparms->reconnect)
1325 return add_durable_reconnect_v2_context(iov, num_iovec,
1326 oparms);
1327 else
1328 return add_durable_v2_context(iov, num_iovec, oparms);
1331 if (oparms->reconnect) {
1332 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1333 /* indicate that we don't need to relock the file */
1334 oparms->reconnect = false;
1335 } else
1336 iov[num].iov_base = create_durable_buf();
1337 if (iov[num].iov_base == NULL)
1338 return -ENOMEM;
1339 iov[num].iov_len = sizeof(struct create_durable);
1340 if (!req->CreateContextsOffset)
1341 req->CreateContextsOffset =
1342 cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1343 iov[1].iov_len);
1344 le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1345 inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
1346 *num_iovec = num + 1;
1347 return 0;
1351 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
1352 __u8 *oplock, struct smb2_file_all_info *buf,
1353 struct smb2_err_rsp **err_buf)
1355 struct smb2_create_req *req;
1356 struct smb2_create_rsp *rsp;
1357 struct TCP_Server_Info *server;
1358 struct cifs_tcon *tcon = oparms->tcon;
1359 struct cifs_ses *ses = tcon->ses;
1360 struct kvec iov[4];
1361 int resp_buftype;
1362 int uni_path_len;
1363 __le16 *copy_path = NULL;
1364 int copy_size;
1365 int rc = 0;
1366 unsigned int num_iovecs = 2;
1367 __u32 file_attributes = 0;
1368 char *dhc_buf = NULL, *lc_buf = NULL;
1370 cifs_dbg(FYI, "create/open\n");
1372 if (ses && (ses->server))
1373 server = ses->server;
1374 else
1375 return -EIO;
1377 rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
1378 if (rc)
1379 return rc;
1381 if (oparms->create_options & CREATE_OPTION_READONLY)
1382 file_attributes |= ATTR_READONLY;
1383 if (oparms->create_options & CREATE_OPTION_SPECIAL)
1384 file_attributes |= ATTR_SYSTEM;
1386 req->ImpersonationLevel = IL_IMPERSONATION;
1387 req->DesiredAccess = cpu_to_le32(oparms->desired_access);
1388 /* File attributes ignored on open (used in create though) */
1389 req->FileAttributes = cpu_to_le32(file_attributes);
1390 req->ShareAccess = FILE_SHARE_ALL_LE;
1391 req->CreateDisposition = cpu_to_le32(oparms->disposition);
1392 req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
1393 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
1394 /* do not count rfc1001 len field */
1395 req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
1397 iov[0].iov_base = (char *)req;
1398 /* 4 for rfc1002 length field */
1399 iov[0].iov_len = get_rfc1002_length(req) + 4;
1401 /* MUST set path len (NameLength) to 0 opening root of share */
1402 req->NameLength = cpu_to_le16(uni_path_len - 2);
1403 /* -1 since last byte is buf[0] which is sent below (path) */
1404 iov[0].iov_len--;
1405 if (uni_path_len % 8 != 0) {
1406 copy_size = uni_path_len / 8 * 8;
1407 if (copy_size < uni_path_len)
1408 copy_size += 8;
1410 copy_path = kzalloc(copy_size, GFP_KERNEL);
1411 if (!copy_path)
1412 return -ENOMEM;
1413 memcpy((char *)copy_path, (const char *)path,
1414 uni_path_len);
1415 uni_path_len = copy_size;
1416 path = copy_path;
1419 iov[1].iov_len = uni_path_len;
1420 iov[1].iov_base = path;
1421 /* -1 since last byte is buf[0] which was counted in smb2_buf_len */
1422 inc_rfc1001_len(req, uni_path_len - 1);
1424 if (!server->oplocks)
1425 *oplock = SMB2_OPLOCK_LEVEL_NONE;
1427 if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1428 *oplock == SMB2_OPLOCK_LEVEL_NONE)
1429 req->RequestedOplockLevel = *oplock;
1430 else {
1431 rc = add_lease_context(server, iov, &num_iovecs, oplock);
1432 if (rc) {
1433 cifs_small_buf_release(req);
1434 kfree(copy_path);
1435 return rc;
1437 lc_buf = iov[num_iovecs-1].iov_base;
1440 if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1441 /* need to set Next field of lease context if we request it */
1442 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1443 struct create_context *ccontext =
1444 (struct create_context *)iov[num_iovecs-1].iov_base;
1445 ccontext->Next =
1446 cpu_to_le32(server->vals->create_lease_size);
1449 rc = add_durable_context(iov, &num_iovecs, oparms,
1450 tcon->use_persistent);
1451 if (rc) {
1452 cifs_small_buf_release(req);
1453 kfree(copy_path);
1454 kfree(lc_buf);
1455 return rc;
1457 dhc_buf = iov[num_iovecs-1].iov_base;
1460 rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1461 rsp = (struct smb2_create_rsp *)iov[0].iov_base;
1463 if (rc != 0) {
1464 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1465 if (err_buf)
1466 *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
1467 GFP_KERNEL);
1468 goto creat_exit;
1471 oparms->fid->persistent_fid = rsp->PersistentFileId;
1472 oparms->fid->volatile_fid = rsp->VolatileFileId;
1474 if (buf) {
1475 memcpy(buf, &rsp->CreationTime, 32);
1476 buf->AllocationSize = rsp->AllocationSize;
1477 buf->EndOfFile = rsp->EndofFile;
1478 buf->Attributes = rsp->FileAttributes;
1479 buf->NumberOfLinks = cpu_to_le32(1);
1480 buf->DeletePending = 0;
1483 if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1484 *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
1485 else
1486 *oplock = rsp->OplockLevel;
1487 creat_exit:
1488 kfree(copy_path);
1489 kfree(lc_buf);
1490 kfree(dhc_buf);
1491 free_rsp_buf(resp_buftype, rsp);
1492 return rc;
1496 * SMB2 IOCTL is used for both IOCTLs and FSCTLs
1499 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1500 u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data,
1501 u32 indatalen, char **out_data, u32 *plen /* returned data len */)
1503 struct smb2_ioctl_req *req;
1504 struct smb2_ioctl_rsp *rsp;
1505 struct TCP_Server_Info *server;
1506 struct cifs_ses *ses;
1507 struct kvec iov[2];
1508 int resp_buftype;
1509 int num_iovecs;
1510 int rc = 0;
1512 cifs_dbg(FYI, "SMB2 IOCTL\n");
1514 if (out_data != NULL)
1515 *out_data = NULL;
1517 /* zero out returned data len, in case of error */
1518 if (plen)
1519 *plen = 0;
1521 if (tcon)
1522 ses = tcon->ses;
1523 else
1524 return -EIO;
1526 if (ses && (ses->server))
1527 server = ses->server;
1528 else
1529 return -EIO;
1531 rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
1532 if (rc)
1533 return rc;
1535 req->CtlCode = cpu_to_le32(opcode);
1536 req->PersistentFileId = persistent_fid;
1537 req->VolatileFileId = volatile_fid;
1539 if (indatalen) {
1540 req->InputCount = cpu_to_le32(indatalen);
1541 /* do not set InputOffset if no input data */
1542 req->InputOffset =
1543 cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
1544 iov[1].iov_base = in_data;
1545 iov[1].iov_len = indatalen;
1546 num_iovecs = 2;
1547 } else
1548 num_iovecs = 1;
1550 req->OutputOffset = 0;
1551 req->OutputCount = 0; /* MBZ */
1554 * Could increase MaxOutputResponse, but that would require more
1555 * than one credit. Windows typically sets this smaller, but for some
1556 * ioctls it may be useful to allow server to send more. No point
1557 * limiting what the server can send as long as fits in one credit
1558 * Unfortunately - we can not handle more than CIFS_MAX_MSG_SIZE
1559 * (by default, note that it can be overridden to make max larger)
1560 * in responses (except for read responses which can be bigger.
1561 * We may want to bump this limit up
1563 req->MaxOutputResponse = cpu_to_le32(CIFSMaxBufSize);
1565 if (is_fsctl)
1566 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1567 else
1568 req->Flags = 0;
1570 iov[0].iov_base = (char *)req;
1573 * If no input data, the size of ioctl struct in
1574 * protocol spec still includes a 1 byte data buffer,
1575 * but if input data passed to ioctl, we do not
1576 * want to double count this, so we do not send
1577 * the dummy one byte of data in iovec[0] if sending
1578 * input data (in iovec[1]). We also must add 4 bytes
1579 * in first iovec to allow for rfc1002 length field.
1582 if (indatalen) {
1583 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1584 inc_rfc1001_len(req, indatalen - 1);
1585 } else
1586 iov[0].iov_len = get_rfc1002_length(req) + 4;
1588 /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
1589 if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
1590 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1592 rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1593 rsp = (struct smb2_ioctl_rsp *)iov[0].iov_base;
1595 if ((rc != 0) && (rc != -EINVAL)) {
1596 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1597 goto ioctl_exit;
1598 } else if (rc == -EINVAL) {
1599 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
1600 (opcode != FSCTL_SRV_COPYCHUNK)) {
1601 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1602 goto ioctl_exit;
1606 /* check if caller wants to look at return data or just return rc */
1607 if ((plen == NULL) || (out_data == NULL))
1608 goto ioctl_exit;
1610 *plen = le32_to_cpu(rsp->OutputCount);
1612 /* We check for obvious errors in the output buffer length and offset */
1613 if (*plen == 0)
1614 goto ioctl_exit; /* server returned no data */
1615 else if (*plen > 0xFF00) {
1616 cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
1617 *plen = 0;
1618 rc = -EIO;
1619 goto ioctl_exit;
1622 if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
1623 cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
1624 le32_to_cpu(rsp->OutputOffset));
1625 *plen = 0;
1626 rc = -EIO;
1627 goto ioctl_exit;
1630 *out_data = kmalloc(*plen, GFP_KERNEL);
1631 if (*out_data == NULL) {
1632 rc = -ENOMEM;
1633 goto ioctl_exit;
1636 memcpy(*out_data, rsp->hdr.ProtocolId + le32_to_cpu(rsp->OutputOffset),
1637 *plen);
1638 ioctl_exit:
1639 free_rsp_buf(resp_buftype, rsp);
1640 return rc;
1644 * Individual callers to ioctl worker function follow
1648 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1649 u64 persistent_fid, u64 volatile_fid)
1651 int rc;
1652 struct compress_ioctl fsctl_input;
1653 char *ret_data = NULL;
1655 fsctl_input.CompressionState =
1656 cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
1658 rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1659 FSCTL_SET_COMPRESSION, true /* is_fsctl */,
1660 (char *)&fsctl_input /* data input */,
1661 2 /* in data len */, &ret_data /* out data */, NULL);
1663 cifs_dbg(FYI, "set compression rc %d\n", rc);
1665 return rc;
1669 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
1670 u64 persistent_fid, u64 volatile_fid)
1672 struct smb2_close_req *req;
1673 struct smb2_close_rsp *rsp;
1674 struct TCP_Server_Info *server;
1675 struct cifs_ses *ses = tcon->ses;
1676 struct kvec iov[1];
1677 int resp_buftype;
1678 int rc = 0;
1680 cifs_dbg(FYI, "Close\n");
1682 if (ses && (ses->server))
1683 server = ses->server;
1684 else
1685 return -EIO;
1687 rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
1688 if (rc)
1689 return rc;
1691 req->PersistentFileId = persistent_fid;
1692 req->VolatileFileId = volatile_fid;
1694 iov[0].iov_base = (char *)req;
1695 /* 4 for rfc1002 length field */
1696 iov[0].iov_len = get_rfc1002_length(req) + 4;
1698 rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1699 rsp = (struct smb2_close_rsp *)iov[0].iov_base;
1701 if (rc != 0) {
1702 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
1703 goto close_exit;
1706 /* BB FIXME - decode close response, update inode for caching */
1708 close_exit:
1709 free_rsp_buf(resp_buftype, rsp);
1710 return rc;
1713 static int
1714 validate_buf(unsigned int offset, unsigned int buffer_length,
1715 struct smb2_hdr *hdr, unsigned int min_buf_size)
1718 unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
1719 char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
1720 char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1721 char *end_of_buf = begin_of_buf + buffer_length;
1724 if (buffer_length < min_buf_size) {
1725 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
1726 buffer_length, min_buf_size);
1727 return -EINVAL;
1730 /* check if beyond RFC1001 maximum length */
1731 if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
1732 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
1733 buffer_length, smb_len);
1734 return -EINVAL;
1737 if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
1738 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
1739 return -EINVAL;
1742 return 0;
1746 * If SMB buffer fields are valid, copy into temporary buffer to hold result.
1747 * Caller must free buffer.
1749 static int
1750 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
1751 struct smb2_hdr *hdr, unsigned int minbufsize,
1752 char *data)
1755 char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1756 int rc;
1758 if (!data)
1759 return -EINVAL;
1761 rc = validate_buf(offset, buffer_length, hdr, minbufsize);
1762 if (rc)
1763 return rc;
1765 memcpy(data, begin_of_buf, buffer_length);
1767 return 0;
1770 static int
1771 query_info(const unsigned int xid, struct cifs_tcon *tcon,
1772 u64 persistent_fid, u64 volatile_fid, u8 info_class,
1773 size_t output_len, size_t min_len, void *data)
1775 struct smb2_query_info_req *req;
1776 struct smb2_query_info_rsp *rsp = NULL;
1777 struct kvec iov[2];
1778 int rc = 0;
1779 int resp_buftype;
1780 struct TCP_Server_Info *server;
1781 struct cifs_ses *ses = tcon->ses;
1783 cifs_dbg(FYI, "Query Info\n");
1785 if (ses && (ses->server))
1786 server = ses->server;
1787 else
1788 return -EIO;
1790 rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
1791 if (rc)
1792 return rc;
1794 req->InfoType = SMB2_O_INFO_FILE;
1795 req->FileInfoClass = info_class;
1796 req->PersistentFileId = persistent_fid;
1797 req->VolatileFileId = volatile_fid;
1798 /* 4 for rfc1002 length field and 1 for Buffer */
1799 req->InputBufferOffset =
1800 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
1801 req->OutputBufferLength = cpu_to_le32(output_len);
1803 iov[0].iov_base = (char *)req;
1804 /* 4 for rfc1002 length field */
1805 iov[0].iov_len = get_rfc1002_length(req) + 4;
1807 rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1808 rsp = (struct smb2_query_info_rsp *)iov[0].iov_base;
1810 if (rc) {
1811 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
1812 goto qinf_exit;
1815 rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
1816 le32_to_cpu(rsp->OutputBufferLength),
1817 &rsp->hdr, min_len, data);
1819 qinf_exit:
1820 free_rsp_buf(resp_buftype, rsp);
1821 return rc;
1825 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
1826 u64 persistent_fid, u64 volatile_fid,
1827 struct smb2_file_all_info *data)
1829 return query_info(xid, tcon, persistent_fid, volatile_fid,
1830 FILE_ALL_INFORMATION,
1831 sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
1832 sizeof(struct smb2_file_all_info), data);
1836 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
1837 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
1839 return query_info(xid, tcon, persistent_fid, volatile_fid,
1840 FILE_INTERNAL_INFORMATION,
1841 sizeof(struct smb2_file_internal_info),
1842 sizeof(struct smb2_file_internal_info), uniqueid);
1846 * This is a no-op for now. We're not really interested in the reply, but
1847 * rather in the fact that the server sent one and that server->lstrp
1848 * gets updated.
1850 * FIXME: maybe we should consider checking that the reply matches request?
1852 static void
1853 smb2_echo_callback(struct mid_q_entry *mid)
1855 struct TCP_Server_Info *server = mid->callback_data;
1856 struct smb2_echo_rsp *smb2 = (struct smb2_echo_rsp *)mid->resp_buf;
1857 unsigned int credits_received = 1;
1859 if (mid->mid_state == MID_RESPONSE_RECEIVED)
1860 credits_received = le16_to_cpu(smb2->hdr.CreditRequest);
1862 mutex_lock(&server->srv_mutex);
1863 DeleteMidQEntry(mid);
1864 mutex_unlock(&server->srv_mutex);
1865 add_credits(server, credits_received, CIFS_ECHO_OP);
1868 void smb2_reconnect_server(struct work_struct *work)
1870 struct TCP_Server_Info *server = container_of(work,
1871 struct TCP_Server_Info, reconnect.work);
1872 struct cifs_ses *ses;
1873 struct cifs_tcon *tcon, *tcon2;
1874 struct list_head tmp_list;
1875 int tcon_exist = false;
1877 /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
1878 mutex_lock(&server->reconnect_mutex);
1880 INIT_LIST_HEAD(&tmp_list);
1881 cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
1883 spin_lock(&cifs_tcp_ses_lock);
1884 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1885 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
1886 if (tcon->need_reconnect) {
1887 tcon->tc_count++;
1888 list_add_tail(&tcon->rlist, &tmp_list);
1889 tcon_exist = true;
1894 * Get the reference to server struct to be sure that the last call of
1895 * cifs_put_tcon() in the loop below won't release the server pointer.
1897 if (tcon_exist)
1898 server->srv_count++;
1900 spin_unlock(&cifs_tcp_ses_lock);
1902 list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
1903 smb2_reconnect(SMB2_ECHO, tcon);
1904 list_del_init(&tcon->rlist);
1905 cifs_put_tcon(tcon);
1908 cifs_dbg(FYI, "Reconnecting tcons finished\n");
1909 mutex_unlock(&server->reconnect_mutex);
1911 /* now we can safely release srv struct */
1912 if (tcon_exist)
1913 cifs_put_tcp_session(server, 1);
1917 SMB2_echo(struct TCP_Server_Info *server)
1919 struct smb2_echo_req *req;
1920 int rc = 0;
1921 struct kvec iov;
1922 struct smb_rqst rqst = { .rq_iov = &iov,
1923 .rq_nvec = 1 };
1925 cifs_dbg(FYI, "In echo request\n");
1927 if (server->tcpStatus == CifsNeedNegotiate) {
1928 /* No need to send echo on newly established connections */
1929 queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
1930 return rc;
1933 rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
1934 if (rc)
1935 return rc;
1937 req->hdr.CreditRequest = cpu_to_le16(1);
1939 iov.iov_base = (char *)req;
1940 /* 4 for rfc1002 length field */
1941 iov.iov_len = get_rfc1002_length(req) + 4;
1943 rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, server,
1944 CIFS_ECHO_OP);
1945 if (rc)
1946 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
1948 cifs_small_buf_release(req);
1949 return rc;
1953 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1954 u64 volatile_fid)
1956 struct smb2_flush_req *req;
1957 struct TCP_Server_Info *server;
1958 struct cifs_ses *ses = tcon->ses;
1959 struct kvec iov[1];
1960 int resp_buftype;
1961 int rc = 0;
1963 cifs_dbg(FYI, "Flush\n");
1965 if (ses && (ses->server))
1966 server = ses->server;
1967 else
1968 return -EIO;
1970 rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
1971 if (rc)
1972 return rc;
1974 req->PersistentFileId = persistent_fid;
1975 req->VolatileFileId = volatile_fid;
1977 iov[0].iov_base = (char *)req;
1978 /* 4 for rfc1002 length field */
1979 iov[0].iov_len = get_rfc1002_length(req) + 4;
1981 rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1983 if (rc != 0)
1984 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
1986 free_rsp_buf(resp_buftype, iov[0].iov_base);
1987 return rc;
1991 * To form a chain of read requests, any read requests after the first should
1992 * have the end_of_chain boolean set to true.
1994 static int
1995 smb2_new_read_req(struct kvec *iov, struct cifs_io_parms *io_parms,
1996 unsigned int remaining_bytes, int request_type)
1998 int rc = -EACCES;
1999 struct smb2_read_req *req = NULL;
2001 rc = small_smb2_init(SMB2_READ, io_parms->tcon, (void **) &req);
2002 if (rc)
2003 return rc;
2004 if (io_parms->tcon->ses->server == NULL)
2005 return -ECONNABORTED;
2007 req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
2009 req->PersistentFileId = io_parms->persistent_fid;
2010 req->VolatileFileId = io_parms->volatile_fid;
2011 req->ReadChannelInfoOffset = 0; /* reserved */
2012 req->ReadChannelInfoLength = 0; /* reserved */
2013 req->Channel = 0; /* reserved */
2014 req->MinimumCount = 0;
2015 req->Length = cpu_to_le32(io_parms->length);
2016 req->Offset = cpu_to_le64(io_parms->offset);
2018 if (request_type & CHAINED_REQUEST) {
2019 if (!(request_type & END_OF_CHAIN)) {
2020 /* 4 for rfc1002 length field */
2021 req->hdr.NextCommand =
2022 cpu_to_le32(get_rfc1002_length(req) + 4);
2023 } else /* END_OF_CHAIN */
2024 req->hdr.NextCommand = 0;
2025 if (request_type & RELATED_REQUEST) {
2026 req->hdr.Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2028 * Related requests use info from previous read request
2029 * in chain.
2031 req->hdr.SessionId = 0xFFFFFFFF;
2032 req->hdr.TreeId = 0xFFFFFFFF;
2033 req->PersistentFileId = 0xFFFFFFFF;
2034 req->VolatileFileId = 0xFFFFFFFF;
2037 if (remaining_bytes > io_parms->length)
2038 req->RemainingBytes = cpu_to_le32(remaining_bytes);
2039 else
2040 req->RemainingBytes = 0;
2042 iov[0].iov_base = (char *)req;
2043 /* 4 for rfc1002 length field */
2044 iov[0].iov_len = get_rfc1002_length(req) + 4;
2045 return rc;
2048 static void
2049 smb2_readv_callback(struct mid_q_entry *mid)
2051 struct cifs_readdata *rdata = mid->callback_data;
2052 struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
2053 struct TCP_Server_Info *server = tcon->ses->server;
2054 struct smb2_hdr *buf = (struct smb2_hdr *)rdata->iov.iov_base;
2055 unsigned int credits_received = 1;
2056 struct smb_rqst rqst = { .rq_iov = &rdata->iov,
2057 .rq_nvec = 1,
2058 .rq_pages = rdata->pages,
2059 .rq_npages = rdata->nr_pages,
2060 .rq_pagesz = rdata->pagesz,
2061 .rq_tailsz = rdata->tailsz };
2063 cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
2064 __func__, mid->mid, mid->mid_state, rdata->result,
2065 rdata->bytes);
2067 switch (mid->mid_state) {
2068 case MID_RESPONSE_RECEIVED:
2069 credits_received = le16_to_cpu(buf->CreditRequest);
2070 /* result already set, check signature */
2071 if (server->sign) {
2072 int rc;
2074 rc = smb2_verify_signature(&rqst, server);
2075 if (rc)
2076 cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
2077 rc);
2079 /* FIXME: should this be counted toward the initiating task? */
2080 task_io_account_read(rdata->got_bytes);
2081 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2082 break;
2083 case MID_REQUEST_SUBMITTED:
2084 case MID_RETRY_NEEDED:
2085 rdata->result = -EAGAIN;
2086 if (server->sign && rdata->got_bytes)
2087 /* reset bytes number since we can not check a sign */
2088 rdata->got_bytes = 0;
2089 /* FIXME: should this be counted toward the initiating task? */
2090 task_io_account_read(rdata->got_bytes);
2091 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2092 break;
2093 default:
2094 if (rdata->result != -ENODATA)
2095 rdata->result = -EIO;
2098 if (rdata->result)
2099 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
2101 queue_work(cifsiod_wq, &rdata->work);
2102 mutex_lock(&server->srv_mutex);
2103 DeleteMidQEntry(mid);
2104 mutex_unlock(&server->srv_mutex);
2105 add_credits(server, credits_received, 0);
2108 /* smb2_async_readv - send an async write, and set up mid to handle result */
2110 smb2_async_readv(struct cifs_readdata *rdata)
2112 int rc, flags = 0;
2113 struct smb2_hdr *buf;
2114 struct cifs_io_parms io_parms;
2115 struct smb_rqst rqst = { .rq_iov = &rdata->iov,
2116 .rq_nvec = 1 };
2117 struct TCP_Server_Info *server;
2119 cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
2120 __func__, rdata->offset, rdata->bytes);
2122 io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
2123 io_parms.offset = rdata->offset;
2124 io_parms.length = rdata->bytes;
2125 io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
2126 io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
2127 io_parms.pid = rdata->pid;
2129 server = io_parms.tcon->ses->server;
2131 rc = smb2_new_read_req(&rdata->iov, &io_parms, 0, 0);
2132 if (rc) {
2133 if (rc == -EAGAIN && rdata->credits) {
2134 /* credits was reset by reconnect */
2135 rdata->credits = 0;
2136 /* reduce in_flight value since we won't send the req */
2137 spin_lock(&server->req_lock);
2138 server->in_flight--;
2139 spin_unlock(&server->req_lock);
2141 return rc;
2144 buf = (struct smb2_hdr *)rdata->iov.iov_base;
2145 /* 4 for rfc1002 length field */
2146 rdata->iov.iov_len = get_rfc1002_length(rdata->iov.iov_base) + 4;
2148 if (rdata->credits) {
2149 buf->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
2150 SMB2_MAX_BUFFER_SIZE));
2151 buf->CreditRequest = buf->CreditCharge;
2152 spin_lock(&server->req_lock);
2153 server->credits += rdata->credits -
2154 le16_to_cpu(buf->CreditCharge);
2155 spin_unlock(&server->req_lock);
2156 wake_up(&server->request_q);
2157 flags = CIFS_HAS_CREDITS;
2160 kref_get(&rdata->refcount);
2161 rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
2162 cifs_readv_receive, smb2_readv_callback,
2163 rdata, flags);
2164 if (rc) {
2165 kref_put(&rdata->refcount, cifs_readdata_release);
2166 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
2169 cifs_small_buf_release(buf);
2170 return rc;
2174 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
2175 unsigned int *nbytes, char **buf, int *buf_type)
2177 int resp_buftype, rc = -EACCES;
2178 struct smb2_read_rsp *rsp = NULL;
2179 struct kvec iov[1];
2181 *nbytes = 0;
2182 rc = smb2_new_read_req(iov, io_parms, 0, 0);
2183 if (rc)
2184 return rc;
2186 rc = SendReceive2(xid, io_parms->tcon->ses, iov, 1,
2187 &resp_buftype, CIFS_LOG_ERROR);
2189 rsp = (struct smb2_read_rsp *)iov[0].iov_base;
2191 if (rsp->hdr.Status == STATUS_END_OF_FILE) {
2192 free_rsp_buf(resp_buftype, iov[0].iov_base);
2193 return 0;
2196 if (rc) {
2197 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
2198 cifs_dbg(VFS, "Send error in read = %d\n", rc);
2199 } else {
2200 *nbytes = le32_to_cpu(rsp->DataLength);
2201 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
2202 (*nbytes > io_parms->length)) {
2203 cifs_dbg(FYI, "bad length %d for count %d\n",
2204 *nbytes, io_parms->length);
2205 rc = -EIO;
2206 *nbytes = 0;
2210 if (*buf) {
2211 memcpy(*buf, (char *)rsp->hdr.ProtocolId + rsp->DataOffset,
2212 *nbytes);
2213 free_rsp_buf(resp_buftype, iov[0].iov_base);
2214 } else if (resp_buftype != CIFS_NO_BUFFER) {
2215 *buf = iov[0].iov_base;
2216 if (resp_buftype == CIFS_SMALL_BUFFER)
2217 *buf_type = CIFS_SMALL_BUFFER;
2218 else if (resp_buftype == CIFS_LARGE_BUFFER)
2219 *buf_type = CIFS_LARGE_BUFFER;
2221 return rc;
2225 * Check the mid_state and signature on received buffer (if any), and queue the
2226 * workqueue completion task.
2228 static void
2229 smb2_writev_callback(struct mid_q_entry *mid)
2231 struct cifs_writedata *wdata = mid->callback_data;
2232 struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2233 struct TCP_Server_Info *server = tcon->ses->server;
2234 unsigned int written;
2235 struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
2236 unsigned int credits_received = 1;
2238 switch (mid->mid_state) {
2239 case MID_RESPONSE_RECEIVED:
2240 credits_received = le16_to_cpu(rsp->hdr.CreditRequest);
2241 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
2242 if (wdata->result != 0)
2243 break;
2245 written = le32_to_cpu(rsp->DataLength);
2247 * Mask off high 16 bits when bytes written as returned
2248 * by the server is greater than bytes requested by the
2249 * client. OS/2 servers are known to set incorrect
2250 * CountHigh values.
2252 if (written > wdata->bytes)
2253 written &= 0xFFFF;
2255 if (written < wdata->bytes)
2256 wdata->result = -ENOSPC;
2257 else
2258 wdata->bytes = written;
2259 break;
2260 case MID_REQUEST_SUBMITTED:
2261 case MID_RETRY_NEEDED:
2262 wdata->result = -EAGAIN;
2263 break;
2264 default:
2265 wdata->result = -EIO;
2266 break;
2269 if (wdata->result)
2270 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2272 queue_work(cifsiod_wq, &wdata->work);
2273 mutex_lock(&server->srv_mutex);
2274 DeleteMidQEntry(mid);
2275 mutex_unlock(&server->srv_mutex);
2276 add_credits(tcon->ses->server, credits_received, 0);
2279 /* smb2_async_writev - send an async write, and set up mid to handle result */
2281 smb2_async_writev(struct cifs_writedata *wdata,
2282 void (*release)(struct kref *kref))
2284 int rc = -EACCES, flags = 0;
2285 struct smb2_write_req *req = NULL;
2286 struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2287 struct TCP_Server_Info *server = tcon->ses->server;
2288 struct kvec iov;
2289 struct smb_rqst rqst;
2291 rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
2292 if (rc) {
2293 if (rc == -EAGAIN && wdata->credits) {
2294 /* credits was reset by reconnect */
2295 wdata->credits = 0;
2296 /* reduce in_flight value since we won't send the req */
2297 spin_lock(&server->req_lock);
2298 server->in_flight--;
2299 spin_unlock(&server->req_lock);
2301 goto async_writev_out;
2304 req->hdr.ProcessId = cpu_to_le32(wdata->cfile->pid);
2306 req->PersistentFileId = wdata->cfile->fid.persistent_fid;
2307 req->VolatileFileId = wdata->cfile->fid.volatile_fid;
2308 req->WriteChannelInfoOffset = 0;
2309 req->WriteChannelInfoLength = 0;
2310 req->Channel = 0;
2311 req->Offset = cpu_to_le64(wdata->offset);
2312 /* 4 for rfc1002 length field */
2313 req->DataOffset = cpu_to_le16(
2314 offsetof(struct smb2_write_req, Buffer) - 4);
2315 req->RemainingBytes = 0;
2317 /* 4 for rfc1002 length field and 1 for Buffer */
2318 iov.iov_len = get_rfc1002_length(req) + 4 - 1;
2319 iov.iov_base = req;
2321 rqst.rq_iov = &iov;
2322 rqst.rq_nvec = 1;
2323 rqst.rq_pages = wdata->pages;
2324 rqst.rq_npages = wdata->nr_pages;
2325 rqst.rq_pagesz = wdata->pagesz;
2326 rqst.rq_tailsz = wdata->tailsz;
2328 cifs_dbg(FYI, "async write at %llu %u bytes\n",
2329 wdata->offset, wdata->bytes);
2331 req->Length = cpu_to_le32(wdata->bytes);
2333 inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
2335 if (wdata->credits) {
2336 req->hdr.CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
2337 SMB2_MAX_BUFFER_SIZE));
2338 req->hdr.CreditRequest = req->hdr.CreditCharge;
2339 spin_lock(&server->req_lock);
2340 server->credits += wdata->credits -
2341 le16_to_cpu(req->hdr.CreditCharge);
2342 spin_unlock(&server->req_lock);
2343 wake_up(&server->request_q);
2344 flags = CIFS_HAS_CREDITS;
2347 kref_get(&wdata->refcount);
2348 rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, wdata,
2349 flags);
2351 if (rc) {
2352 kref_put(&wdata->refcount, release);
2353 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2356 async_writev_out:
2357 cifs_small_buf_release(req);
2358 return rc;
2362 * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
2363 * The length field from io_parms must be at least 1 and indicates a number of
2364 * elements with data to write that begins with position 1 in iov array. All
2365 * data length is specified by count.
2368 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
2369 unsigned int *nbytes, struct kvec *iov, int n_vec)
2371 int rc = 0;
2372 struct smb2_write_req *req = NULL;
2373 struct smb2_write_rsp *rsp = NULL;
2374 int resp_buftype;
2375 *nbytes = 0;
2377 if (n_vec < 1)
2378 return rc;
2380 rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
2381 if (rc)
2382 return rc;
2384 if (io_parms->tcon->ses->server == NULL)
2385 return -ECONNABORTED;
2387 req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
2389 req->PersistentFileId = io_parms->persistent_fid;
2390 req->VolatileFileId = io_parms->volatile_fid;
2391 req->WriteChannelInfoOffset = 0;
2392 req->WriteChannelInfoLength = 0;
2393 req->Channel = 0;
2394 req->Length = cpu_to_le32(io_parms->length);
2395 req->Offset = cpu_to_le64(io_parms->offset);
2396 /* 4 for rfc1002 length field */
2397 req->DataOffset = cpu_to_le16(
2398 offsetof(struct smb2_write_req, Buffer) - 4);
2399 req->RemainingBytes = 0;
2401 iov[0].iov_base = (char *)req;
2402 /* 4 for rfc1002 length field and 1 for Buffer */
2403 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2405 /* length of entire message including data to be written */
2406 inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
2408 rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
2409 &resp_buftype, 0);
2410 rsp = (struct smb2_write_rsp *)iov[0].iov_base;
2412 if (rc) {
2413 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
2414 cifs_dbg(VFS, "Send error in write = %d\n", rc);
2415 } else
2416 *nbytes = le32_to_cpu(rsp->DataLength);
2418 free_rsp_buf(resp_buftype, rsp);
2419 return rc;
2422 static unsigned int
2423 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
2425 int len;
2426 unsigned int entrycount = 0;
2427 unsigned int next_offset = 0;
2428 char *entryptr;
2429 FILE_DIRECTORY_INFO *dir_info;
2431 if (bufstart == NULL)
2432 return 0;
2434 entryptr = bufstart;
2436 while (1) {
2437 if (entryptr + next_offset < entryptr ||
2438 entryptr + next_offset > end_of_buf ||
2439 entryptr + next_offset + size > end_of_buf) {
2440 cifs_dbg(VFS, "malformed search entry would overflow\n");
2441 break;
2444 entryptr = entryptr + next_offset;
2445 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
2447 len = le32_to_cpu(dir_info->FileNameLength);
2448 if (entryptr + len < entryptr ||
2449 entryptr + len > end_of_buf ||
2450 entryptr + len + size > end_of_buf) {
2451 cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
2452 end_of_buf);
2453 break;
2456 *lastentry = entryptr;
2457 entrycount++;
2459 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
2460 if (!next_offset)
2461 break;
2464 return entrycount;
2468 * Readdir/FindFirst
2471 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
2472 u64 persistent_fid, u64 volatile_fid, int index,
2473 struct cifs_search_info *srch_inf)
2475 struct smb2_query_directory_req *req;
2476 struct smb2_query_directory_rsp *rsp = NULL;
2477 struct kvec iov[2];
2478 int rc = 0;
2479 int len;
2480 int resp_buftype = CIFS_NO_BUFFER;
2481 unsigned char *bufptr;
2482 struct TCP_Server_Info *server;
2483 struct cifs_ses *ses = tcon->ses;
2484 __le16 asteriks = cpu_to_le16('*');
2485 char *end_of_smb;
2486 unsigned int output_size = CIFSMaxBufSize;
2487 size_t info_buf_size;
2489 if (ses && (ses->server))
2490 server = ses->server;
2491 else
2492 return -EIO;
2494 rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
2495 if (rc)
2496 return rc;
2498 switch (srch_inf->info_level) {
2499 case SMB_FIND_FILE_DIRECTORY_INFO:
2500 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
2501 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
2502 break;
2503 case SMB_FIND_FILE_ID_FULL_DIR_INFO:
2504 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
2505 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
2506 break;
2507 default:
2508 cifs_dbg(VFS, "info level %u isn't supported\n",
2509 srch_inf->info_level);
2510 rc = -EINVAL;
2511 goto qdir_exit;
2514 req->FileIndex = cpu_to_le32(index);
2515 req->PersistentFileId = persistent_fid;
2516 req->VolatileFileId = volatile_fid;
2518 len = 0x2;
2519 bufptr = req->Buffer;
2520 memcpy(bufptr, &asteriks, len);
2522 req->FileNameOffset =
2523 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
2524 req->FileNameLength = cpu_to_le16(len);
2526 * BB could be 30 bytes or so longer if we used SMB2 specific
2527 * buffer lengths, but this is safe and close enough.
2529 output_size = min_t(unsigned int, output_size, server->maxBuf);
2530 output_size = min_t(unsigned int, output_size, 2 << 15);
2531 req->OutputBufferLength = cpu_to_le32(output_size);
2533 iov[0].iov_base = (char *)req;
2534 /* 4 for RFC1001 length and 1 for Buffer */
2535 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2537 iov[1].iov_base = (char *)(req->Buffer);
2538 iov[1].iov_len = len;
2540 inc_rfc1001_len(req, len - 1 /* Buffer */);
2542 rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
2543 rsp = (struct smb2_query_directory_rsp *)iov[0].iov_base;
2545 if (rc) {
2546 if (rc == -ENODATA && rsp->hdr.Status == STATUS_NO_MORE_FILES) {
2547 srch_inf->endOfSearch = true;
2548 rc = 0;
2549 } else
2550 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
2551 goto qdir_exit;
2554 rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2555 le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2556 info_buf_size);
2557 if (rc)
2558 goto qdir_exit;
2560 srch_inf->unicode = true;
2562 if (srch_inf->ntwrk_buf_start) {
2563 if (srch_inf->smallBuf)
2564 cifs_small_buf_release(srch_inf->ntwrk_buf_start);
2565 else
2566 cifs_buf_release(srch_inf->ntwrk_buf_start);
2568 srch_inf->ntwrk_buf_start = (char *)rsp;
2569 srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
2570 (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
2571 /* 4 for rfc1002 length field */
2572 end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
2573 srch_inf->entries_in_buffer =
2574 num_entries(srch_inf->srch_entries_start, end_of_smb,
2575 &srch_inf->last_entry, info_buf_size);
2576 srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
2577 cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
2578 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
2579 srch_inf->srch_entries_start, srch_inf->last_entry);
2580 if (resp_buftype == CIFS_LARGE_BUFFER)
2581 srch_inf->smallBuf = false;
2582 else if (resp_buftype == CIFS_SMALL_BUFFER)
2583 srch_inf->smallBuf = true;
2584 else
2585 cifs_dbg(VFS, "illegal search buffer type\n");
2587 return rc;
2589 qdir_exit:
2590 free_rsp_buf(resp_buftype, rsp);
2591 return rc;
2594 static int
2595 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2596 u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class,
2597 unsigned int num, void **data, unsigned int *size)
2599 struct smb2_set_info_req *req;
2600 struct smb2_set_info_rsp *rsp = NULL;
2601 struct kvec *iov;
2602 int rc = 0;
2603 int resp_buftype;
2604 unsigned int i;
2605 struct TCP_Server_Info *server;
2606 struct cifs_ses *ses = tcon->ses;
2608 if (ses && (ses->server))
2609 server = ses->server;
2610 else
2611 return -EIO;
2613 if (!num)
2614 return -EINVAL;
2616 iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
2617 if (!iov)
2618 return -ENOMEM;
2620 rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
2621 if (rc) {
2622 kfree(iov);
2623 return rc;
2626 req->hdr.ProcessId = cpu_to_le32(pid);
2628 req->InfoType = SMB2_O_INFO_FILE;
2629 req->FileInfoClass = info_class;
2630 req->PersistentFileId = persistent_fid;
2631 req->VolatileFileId = volatile_fid;
2633 /* 4 for RFC1001 length and 1 for Buffer */
2634 req->BufferOffset =
2635 cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
2636 req->BufferLength = cpu_to_le32(*size);
2638 inc_rfc1001_len(req, *size - 1 /* Buffer */);
2640 memcpy(req->Buffer, *data, *size);
2642 iov[0].iov_base = (char *)req;
2643 /* 4 for RFC1001 length */
2644 iov[0].iov_len = get_rfc1002_length(req) + 4;
2646 for (i = 1; i < num; i++) {
2647 inc_rfc1001_len(req, size[i]);
2648 le32_add_cpu(&req->BufferLength, size[i]);
2649 iov[i].iov_base = (char *)data[i];
2650 iov[i].iov_len = size[i];
2653 rc = SendReceive2(xid, ses, iov, num, &resp_buftype, 0);
2654 rsp = (struct smb2_set_info_rsp *)iov[0].iov_base;
2656 if (rc != 0)
2657 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
2659 free_rsp_buf(resp_buftype, rsp);
2660 kfree(iov);
2661 return rc;
2665 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
2666 u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2668 struct smb2_file_rename_info info;
2669 void **data;
2670 unsigned int size[2];
2671 int rc;
2672 int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2674 data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2675 if (!data)
2676 return -ENOMEM;
2678 info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
2679 /* 0 = fail if target already exists */
2680 info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */
2681 info.FileNameLength = cpu_to_le32(len);
2683 data[0] = &info;
2684 size[0] = sizeof(struct smb2_file_rename_info);
2686 data[1] = target_file;
2687 size[1] = len + 2 /* null */;
2689 rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2690 current->tgid, FILE_RENAME_INFORMATION, 2, data,
2691 size);
2692 kfree(data);
2693 return rc;
2697 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
2698 u64 persistent_fid, u64 volatile_fid)
2700 __u8 delete_pending = 1;
2701 void *data;
2702 unsigned int size;
2704 data = &delete_pending;
2705 size = 1; /* sizeof __u8 */
2707 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2708 current->tgid, FILE_DISPOSITION_INFORMATION, 1, &data,
2709 &size);
2713 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
2714 u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2716 struct smb2_file_link_info info;
2717 void **data;
2718 unsigned int size[2];
2719 int rc;
2720 int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2722 data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2723 if (!data)
2724 return -ENOMEM;
2726 info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
2727 /* 0 = fail if link already exists */
2728 info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */
2729 info.FileNameLength = cpu_to_le32(len);
2731 data[0] = &info;
2732 size[0] = sizeof(struct smb2_file_link_info);
2734 data[1] = target_file;
2735 size[1] = len + 2 /* null */;
2737 rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2738 current->tgid, FILE_LINK_INFORMATION, 2, data, size);
2739 kfree(data);
2740 return rc;
2744 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2745 u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
2747 struct smb2_file_eof_info info;
2748 void *data;
2749 unsigned int size;
2751 info.EndOfFile = *eof;
2753 data = &info;
2754 size = sizeof(struct smb2_file_eof_info);
2756 if (is_falloc)
2757 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2758 pid, FILE_ALLOCATION_INFORMATION, 1, &data, &size);
2759 else
2760 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2761 pid, FILE_END_OF_FILE_INFORMATION, 1, &data, &size);
2765 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2766 u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
2768 unsigned int size;
2769 size = sizeof(FILE_BASIC_INFO);
2770 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2771 current->tgid, FILE_BASIC_INFORMATION, 1,
2772 (void **)&buf, &size);
2776 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
2777 const u64 persistent_fid, const u64 volatile_fid,
2778 __u8 oplock_level)
2780 int rc;
2781 struct smb2_oplock_break *req = NULL;
2783 cifs_dbg(FYI, "SMB2_oplock_break\n");
2784 rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
2786 if (rc)
2787 return rc;
2789 req->VolatileFid = volatile_fid;
2790 req->PersistentFid = persistent_fid;
2791 req->OplockLevel = oplock_level;
2792 req->hdr.CreditRequest = cpu_to_le16(1);
2794 rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
2795 /* SMB2 buffer freed by function above */
2797 if (rc) {
2798 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
2799 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
2802 return rc;
2805 static void
2806 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
2807 struct kstatfs *kst)
2809 kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
2810 le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
2811 kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
2812 kst->f_bfree = kst->f_bavail =
2813 le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
2814 return;
2817 static int
2818 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
2819 int outbuf_len, u64 persistent_fid, u64 volatile_fid)
2821 int rc;
2822 struct smb2_query_info_req *req;
2824 cifs_dbg(FYI, "Query FSInfo level %d\n", level);
2826 if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
2827 return -EIO;
2829 rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
2830 if (rc)
2831 return rc;
2833 req->InfoType = SMB2_O_INFO_FILESYSTEM;
2834 req->FileInfoClass = level;
2835 req->PersistentFileId = persistent_fid;
2836 req->VolatileFileId = volatile_fid;
2837 /* 4 for rfc1002 length field and 1 for pad */
2838 req->InputBufferOffset =
2839 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
2840 req->OutputBufferLength = cpu_to_le32(
2841 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
2843 iov->iov_base = (char *)req;
2844 /* 4 for rfc1002 length field */
2845 iov->iov_len = get_rfc1002_length(req) + 4;
2846 return 0;
2850 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
2851 u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
2853 struct smb2_query_info_rsp *rsp = NULL;
2854 struct kvec iov;
2855 int rc = 0;
2856 int resp_buftype;
2857 struct cifs_ses *ses = tcon->ses;
2858 struct smb2_fs_full_size_info *info = NULL;
2860 rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
2861 sizeof(struct smb2_fs_full_size_info),
2862 persistent_fid, volatile_fid);
2863 if (rc)
2864 return rc;
2866 rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, 0);
2867 if (rc) {
2868 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2869 goto qfsinf_exit;
2871 rsp = (struct smb2_query_info_rsp *)iov.iov_base;
2873 info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
2874 le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
2875 rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2876 le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2877 sizeof(struct smb2_fs_full_size_info));
2878 if (!rc)
2879 copy_fs_info_to_kstatfs(info, fsdata);
2881 qfsinf_exit:
2882 free_rsp_buf(resp_buftype, iov.iov_base);
2883 return rc;
2887 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
2888 u64 persistent_fid, u64 volatile_fid, int level)
2890 struct smb2_query_info_rsp *rsp = NULL;
2891 struct kvec iov;
2892 int rc = 0;
2893 int resp_buftype, max_len, min_len;
2894 struct cifs_ses *ses = tcon->ses;
2895 unsigned int rsp_len, offset;
2897 if (level == FS_DEVICE_INFORMATION) {
2898 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
2899 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
2900 } else if (level == FS_ATTRIBUTE_INFORMATION) {
2901 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
2902 min_len = MIN_FS_ATTR_INFO_SIZE;
2903 } else if (level == FS_SECTOR_SIZE_INFORMATION) {
2904 max_len = sizeof(struct smb3_fs_ss_info);
2905 min_len = sizeof(struct smb3_fs_ss_info);
2906 } else {
2907 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
2908 return -EINVAL;
2911 rc = build_qfs_info_req(&iov, tcon, level, max_len,
2912 persistent_fid, volatile_fid);
2913 if (rc)
2914 return rc;
2916 rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, 0);
2917 if (rc) {
2918 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2919 goto qfsattr_exit;
2921 rsp = (struct smb2_query_info_rsp *)iov.iov_base;
2923 rsp_len = le32_to_cpu(rsp->OutputBufferLength);
2924 offset = le16_to_cpu(rsp->OutputBufferOffset);
2925 rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
2926 if (rc)
2927 goto qfsattr_exit;
2929 if (level == FS_ATTRIBUTE_INFORMATION)
2930 memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
2931 + (char *)&rsp->hdr, min_t(unsigned int,
2932 rsp_len, max_len));
2933 else if (level == FS_DEVICE_INFORMATION)
2934 memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
2935 + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
2936 else if (level == FS_SECTOR_SIZE_INFORMATION) {
2937 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
2938 (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
2939 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
2940 tcon->perf_sector_size =
2941 le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
2944 qfsattr_exit:
2945 free_rsp_buf(resp_buftype, iov.iov_base);
2946 return rc;
2950 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
2951 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2952 const __u32 num_lock, struct smb2_lock_element *buf)
2954 int rc = 0;
2955 struct smb2_lock_req *req = NULL;
2956 struct kvec iov[2];
2957 int resp_buf_type;
2958 unsigned int count;
2960 cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
2962 rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
2963 if (rc)
2964 return rc;
2966 req->hdr.ProcessId = cpu_to_le32(pid);
2967 req->LockCount = cpu_to_le16(num_lock);
2969 req->PersistentFileId = persist_fid;
2970 req->VolatileFileId = volatile_fid;
2972 count = num_lock * sizeof(struct smb2_lock_element);
2973 inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
2975 iov[0].iov_base = (char *)req;
2976 /* 4 for rfc1002 length field and count for all locks */
2977 iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
2978 iov[1].iov_base = (char *)buf;
2979 iov[1].iov_len = count;
2981 cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
2982 rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, CIFS_NO_RESP);
2983 if (rc) {
2984 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
2985 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
2988 return rc;
2992 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
2993 const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2994 const __u64 length, const __u64 offset, const __u32 lock_flags,
2995 const bool wait)
2997 struct smb2_lock_element lock;
2999 lock.Offset = cpu_to_le64(offset);
3000 lock.Length = cpu_to_le64(length);
3001 lock.Flags = cpu_to_le32(lock_flags);
3002 if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
3003 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
3005 return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
3009 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
3010 __u8 *lease_key, const __le32 lease_state)
3012 int rc;
3013 struct smb2_lease_ack *req = NULL;
3015 cifs_dbg(FYI, "SMB2_lease_break\n");
3016 rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
3018 if (rc)
3019 return rc;
3021 req->hdr.CreditRequest = cpu_to_le16(1);
3022 req->StructureSize = cpu_to_le16(36);
3023 inc_rfc1001_len(req, 12);
3025 memcpy(req->LeaseKey, lease_key, 16);
3026 req->LeaseState = lease_state;
3028 rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
3029 /* SMB2 buffer freed by function above */
3031 if (rc) {
3032 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3033 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
3036 return rc;