Merge tag 'mfd-next-4.12' of git://git.kernel.org/pub/scm/linux/kernel/git/lee/mfd
[linux-block.git] / fs / cifs / smb2pdu.c
1 /*
2  *   fs/cifs/smb2pdu.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  *   This library is free software; you can redistribute it and/or modify
12  *   it under the terms of the GNU Lesser General Public License as published
13  *   by the Free Software Foundation; either version 2.1 of the License, or
14  *   (at your option) any later version.
15  *
16  *   This library is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
19  *   the GNU Lesser General Public License for more details.
20  *
21  *   You should have received a copy of the GNU Lesser General Public License
22  *   along with this library; if not, write to the Free Software
23  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  */
25
26  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
27  /* Note that there are handle based routines which must be                   */
28  /* treated slightly differently for reconnection purposes since we never     */
29  /* want to reuse a stale file handle and only the caller knows the file info */
30
31 #include <linux/fs.h>
32 #include <linux/kernel.h>
33 #include <linux/vfs.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/uaccess.h>
36 #include <linux/uuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/xattr.h>
39 #include "smb2pdu.h"
40 #include "cifsglob.h"
41 #include "cifsacl.h"
42 #include "cifsproto.h"
43 #include "smb2proto.h"
44 #include "cifs_unicode.h"
45 #include "cifs_debug.h"
46 #include "ntlmssp.h"
47 #include "smb2status.h"
48 #include "smb2glob.h"
49 #include "cifspdu.h"
50 #include "cifs_spnego.h"
51
52 /*
53  *  The following table defines the expected "StructureSize" of SMB2 requests
54  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
55  *
56  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
57  *  indexed by command in host byte order.
58  */
59 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
60         /* SMB2_NEGOTIATE */ 36,
61         /* SMB2_SESSION_SETUP */ 25,
62         /* SMB2_LOGOFF */ 4,
63         /* SMB2_TREE_CONNECT */ 9,
64         /* SMB2_TREE_DISCONNECT */ 4,
65         /* SMB2_CREATE */ 57,
66         /* SMB2_CLOSE */ 24,
67         /* SMB2_FLUSH */ 24,
68         /* SMB2_READ */ 49,
69         /* SMB2_WRITE */ 49,
70         /* SMB2_LOCK */ 48,
71         /* SMB2_IOCTL */ 57,
72         /* SMB2_CANCEL */ 4,
73         /* SMB2_ECHO */ 4,
74         /* SMB2_QUERY_DIRECTORY */ 33,
75         /* SMB2_CHANGE_NOTIFY */ 32,
76         /* SMB2_QUERY_INFO */ 41,
77         /* SMB2_SET_INFO */ 33,
78         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
79 };
80
81 static int encryption_required(const struct cifs_tcon *tcon)
82 {
83         if (!tcon)
84                 return 0;
85         if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
86             (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
87                 return 1;
88         if (tcon->seal &&
89             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
90                 return 1;
91         return 0;
92 }
93
94 static void
95 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
96                   const struct cifs_tcon *tcon)
97 {
98         shdr->ProtocolId = SMB2_PROTO_NUMBER;
99         shdr->StructureSize = cpu_to_le16(64);
100         shdr->Command = smb2_cmd;
101         if (tcon && tcon->ses && tcon->ses->server) {
102                 struct TCP_Server_Info *server = tcon->ses->server;
103
104                 spin_lock(&server->req_lock);
105                 /* Request up to 2 credits but don't go over the limit. */
106                 if (server->credits >= server->max_credits)
107                         shdr->CreditRequest = cpu_to_le16(0);
108                 else
109                         shdr->CreditRequest = cpu_to_le16(
110                                 min_t(int, server->max_credits -
111                                                 server->credits, 2));
112                 spin_unlock(&server->req_lock);
113         } else {
114                 shdr->CreditRequest = cpu_to_le16(2);
115         }
116         shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
117
118         if (!tcon)
119                 goto out;
120
121         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
122         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
123         if ((tcon->ses) && (tcon->ses->server) &&
124             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
125                 shdr->CreditCharge = cpu_to_le16(1);
126         /* else CreditCharge MBZ */
127
128         shdr->TreeId = tcon->tid;
129         /* Uid is not converted */
130         if (tcon->ses)
131                 shdr->SessionId = tcon->ses->Suid;
132
133         /*
134          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
135          * to pass the path on the Open SMB prefixed by \\server\share.
136          * Not sure when we would need to do the augmented path (if ever) and
137          * setting this flag breaks the SMB2 open operation since it is
138          * illegal to send an empty path name (without \\server\share prefix)
139          * when the DFS flag is set in the SMB open header. We could
140          * consider setting the flag on all operations other than open
141          * but it is safer to net set it for now.
142          */
143 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
144                 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
145
146         if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
147             !encryption_required(tcon))
148                 shdr->Flags |= SMB2_FLAGS_SIGNED;
149 out:
150         return;
151 }
152
153 static int
154 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
155 {
156         int rc = 0;
157         struct nls_table *nls_codepage;
158         struct cifs_ses *ses;
159         struct TCP_Server_Info *server;
160
161         /*
162          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
163          * check for tcp and smb session status done differently
164          * for those three - in the calling routine.
165          */
166         if (tcon == NULL)
167                 return rc;
168
169         if (smb2_command == SMB2_TREE_CONNECT)
170                 return rc;
171
172         if (tcon->tidStatus == CifsExiting) {
173                 /*
174                  * only tree disconnect, open, and write,
175                  * (and ulogoff which does not have tcon)
176                  * are allowed as we start force umount.
177                  */
178                 if ((smb2_command != SMB2_WRITE) &&
179                    (smb2_command != SMB2_CREATE) &&
180                    (smb2_command != SMB2_TREE_DISCONNECT)) {
181                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
182                                  smb2_command);
183                         return -ENODEV;
184                 }
185         }
186         if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
187             (!tcon->ses->server))
188                 return -EIO;
189
190         ses = tcon->ses;
191         server = ses->server;
192
193         /*
194          * Give demultiplex thread up to 10 seconds to reconnect, should be
195          * greater than cifs socket timeout which is 7 seconds
196          */
197         while (server->tcpStatus == CifsNeedReconnect) {
198                 /*
199                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
200                  * here since they are implicitly done when session drops.
201                  */
202                 switch (smb2_command) {
203                 /*
204                  * BB Should we keep oplock break and add flush to exceptions?
205                  */
206                 case SMB2_TREE_DISCONNECT:
207                 case SMB2_CANCEL:
208                 case SMB2_CLOSE:
209                 case SMB2_OPLOCK_BREAK:
210                         return -EAGAIN;
211                 }
212
213                 wait_event_interruptible_timeout(server->response_q,
214                         (server->tcpStatus != CifsNeedReconnect), 10 * HZ);
215
216                 /* are we still trying to reconnect? */
217                 if (server->tcpStatus != CifsNeedReconnect)
218                         break;
219
220                 /*
221                  * on "soft" mounts we wait once. Hard mounts keep
222                  * retrying until process is killed or server comes
223                  * back on-line
224                  */
225                 if (!tcon->retry) {
226                         cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
227                         return -EHOSTDOWN;
228                 }
229         }
230
231         if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
232                 return rc;
233
234         nls_codepage = load_nls_default();
235
236         /*
237          * need to prevent multiple threads trying to simultaneously reconnect
238          * the same SMB session
239          */
240         mutex_lock(&tcon->ses->session_mutex);
241         rc = cifs_negotiate_protocol(0, tcon->ses);
242         if (!rc && tcon->ses->need_reconnect)
243                 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
244
245         if (rc || !tcon->need_reconnect) {
246                 mutex_unlock(&tcon->ses->session_mutex);
247                 goto out;
248         }
249
250         cifs_mark_open_files_invalid(tcon);
251         if (tcon->use_persistent)
252                 tcon->need_reopen_files = true;
253
254         rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
255         mutex_unlock(&tcon->ses->session_mutex);
256
257         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
258         if (rc)
259                 goto out;
260
261         if (smb2_command != SMB2_INTERNAL_CMD)
262                 queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
263
264         atomic_inc(&tconInfoReconnectCount);
265 out:
266         /*
267          * Check if handle based operation so we know whether we can continue
268          * or not without returning to caller to reset file handle.
269          */
270         /*
271          * BB Is flush done by server on drop of tcp session? Should we special
272          * case it and skip above?
273          */
274         switch (smb2_command) {
275         case SMB2_FLUSH:
276         case SMB2_READ:
277         case SMB2_WRITE:
278         case SMB2_LOCK:
279         case SMB2_IOCTL:
280         case SMB2_QUERY_DIRECTORY:
281         case SMB2_CHANGE_NOTIFY:
282         case SMB2_QUERY_INFO:
283         case SMB2_SET_INFO:
284                 rc = -EAGAIN;
285         }
286         unload_nls(nls_codepage);
287         return rc;
288 }
289
290 static void
291 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
292                unsigned int *total_len)
293 {
294         struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
295         /* lookup word count ie StructureSize from table */
296         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
297
298         /*
299          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
300          * largest operations (Create)
301          */
302         memset(buf, 0, 256);
303
304         smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
305         spdu->StructureSize2 = cpu_to_le16(parmsize);
306
307         *total_len = parmsize + sizeof(struct smb2_sync_hdr);
308 }
309
310 /* init request without RFC1001 length at the beginning */
311 static int
312 smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
313                     void **request_buf, unsigned int *total_len)
314 {
315         int rc;
316         struct smb2_sync_hdr *shdr;
317
318         rc = smb2_reconnect(smb2_command, tcon);
319         if (rc)
320                 return rc;
321
322         /* BB eventually switch this to SMB2 specific small buf size */
323         *request_buf = cifs_small_buf_get();
324         if (*request_buf == NULL) {
325                 /* BB should we add a retry in here if not a writepage? */
326                 return -ENOMEM;
327         }
328
329         shdr = (struct smb2_sync_hdr *)(*request_buf);
330
331         fill_small_buf(smb2_command, tcon, shdr, total_len);
332
333         if (tcon != NULL) {
334 #ifdef CONFIG_CIFS_STATS2
335                 uint16_t com_code = le16_to_cpu(smb2_command);
336
337                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
338 #endif
339                 cifs_stats_inc(&tcon->num_smbs_sent);
340         }
341
342         return rc;
343 }
344
345 /*
346  * Allocate and return pointer to an SMB request hdr, and set basic
347  * SMB information in the SMB header. If the return code is zero, this
348  * function must have filled in request_buf pointer. The returned buffer
349  * has RFC1001 length at the beginning.
350  */
351 static int
352 small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
353                 void **request_buf)
354 {
355         int rc;
356         unsigned int total_len;
357         struct smb2_pdu *pdu;
358
359         rc = smb2_reconnect(smb2_command, tcon);
360         if (rc)
361                 return rc;
362
363         /* BB eventually switch this to SMB2 specific small buf size */
364         *request_buf = cifs_small_buf_get();
365         if (*request_buf == NULL) {
366                 /* BB should we add a retry in here if not a writepage? */
367                 return -ENOMEM;
368         }
369
370         pdu = (struct smb2_pdu *)(*request_buf);
371
372         fill_small_buf(smb2_command, tcon, get_sync_hdr(pdu), &total_len);
373
374         /* Note this is only network field converted to big endian */
375         pdu->hdr.smb2_buf_length = cpu_to_be32(total_len);
376
377         if (tcon != NULL) {
378 #ifdef CONFIG_CIFS_STATS2
379                 uint16_t com_code = le16_to_cpu(smb2_command);
380                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
381 #endif
382                 cifs_stats_inc(&tcon->num_smbs_sent);
383         }
384
385         return rc;
386 }
387
388 #ifdef CONFIG_CIFS_SMB311
389 /* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */
390 #define OFFSET_OF_NEG_CONTEXT 0x68  /* sizeof(struct smb2_negotiate_req) - 4 */
391
392
393 #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES     cpu_to_le16(1)
394 #define SMB2_ENCRYPTION_CAPABILITIES            cpu_to_le16(2)
395
396 static void
397 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
398 {
399         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
400         pneg_ctxt->DataLength = cpu_to_le16(38);
401         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
402         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
403         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
404         pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
405 }
406
407 static void
408 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
409 {
410         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
411         pneg_ctxt->DataLength = cpu_to_le16(6);
412         pneg_ctxt->CipherCount = cpu_to_le16(2);
413         pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
414         pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
415 }
416
417 static void
418 assemble_neg_contexts(struct smb2_negotiate_req *req)
419 {
420
421         /* +4 is to account for the RFC1001 len field */
422         char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4;
423
424         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
425         /* Add 2 to size to round to 8 byte boundary */
426         pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context);
427         build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
428         req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
429         req->NegotiateContextCount = cpu_to_le16(2);
430         inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context) + 2
431                         + sizeof(struct smb2_encryption_neg_context)); /* calculate hash */
432 }
433 #else
434 static void assemble_neg_contexts(struct smb2_negotiate_req *req)
435 {
436         return;
437 }
438 #endif /* SMB311 */
439
440 /*
441  *
442  *      SMB2 Worker functions follow:
443  *
444  *      The general structure of the worker functions is:
445  *      1) Call smb2_init (assembles SMB2 header)
446  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
447  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
448  *      4) Decode SMB2 command specific fields in the fixed length area
449  *      5) Decode variable length data area (if any for this SMB2 command type)
450  *      6) Call free smb buffer
451  *      7) return
452  *
453  */
454
455 int
456 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
457 {
458         struct smb2_negotiate_req *req;
459         struct smb2_negotiate_rsp *rsp;
460         struct kvec iov[1];
461         struct kvec rsp_iov;
462         int rc = 0;
463         int resp_buftype;
464         struct TCP_Server_Info *server = ses->server;
465         int blob_offset, blob_length;
466         char *security_blob;
467         int flags = CIFS_NEG_OP;
468
469         cifs_dbg(FYI, "Negotiate protocol\n");
470
471         if (!server) {
472                 WARN(1, "%s: server is NULL!\n", __func__);
473                 return -EIO;
474         }
475
476         rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
477         if (rc)
478                 return rc;
479
480         req->hdr.sync_hdr.SessionId = 0;
481
482         req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
483
484         req->DialectCount = cpu_to_le16(1); /* One vers= at a time for now */
485         inc_rfc1001_len(req, 2);
486
487         /* only one of SMB2 signing flags may be set in SMB2 request */
488         if (ses->sign)
489                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
490         else if (global_secflags & CIFSSEC_MAY_SIGN)
491                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
492         else
493                 req->SecurityMode = 0;
494
495         req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
496
497         /* ClientGUID must be zero for SMB2.02 dialect */
498         if (ses->server->vals->protocol_id == SMB20_PROT_ID)
499                 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
500         else {
501                 memcpy(req->ClientGUID, server->client_guid,
502                         SMB2_CLIENT_GUID_SIZE);
503                 if (ses->server->vals->protocol_id == SMB311_PROT_ID)
504                         assemble_neg_contexts(req);
505         }
506         iov[0].iov_base = (char *)req;
507         /* 4 for rfc1002 length field */
508         iov[0].iov_len = get_rfc1002_length(req) + 4;
509
510         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
511         cifs_small_buf_release(req);
512         rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
513         /*
514          * No tcon so can't do
515          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
516          */
517         if (rc != 0)
518                 goto neg_exit;
519
520         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
521
522         /* BB we may eventually want to match the negotiated vs. requested
523            dialect, even though we are only requesting one at a time */
524         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
525                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
526         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
527                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
528         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
529                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
530         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
531                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
532 #ifdef CONFIG_CIFS_SMB311
533         else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
534                 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
535 #endif /* SMB311 */
536         else {
537                 cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
538                          le16_to_cpu(rsp->DialectRevision));
539                 rc = -EIO;
540                 goto neg_exit;
541         }
542         server->dialect = le16_to_cpu(rsp->DialectRevision);
543
544         /* SMB2 only has an extended negflavor */
545         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
546         /* set it to the maximum buffer size value we can send with 1 credit */
547         server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
548                                SMB2_MAX_BUFFER_SIZE);
549         server->max_read = le32_to_cpu(rsp->MaxReadSize);
550         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
551         /* BB Do we need to validate the SecurityMode? */
552         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
553         server->capabilities = le32_to_cpu(rsp->Capabilities);
554         /* Internal types */
555         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
556
557         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
558                                                &rsp->hdr);
559         /*
560          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
561          * for us will be
562          *      ses->sectype = RawNTLMSSP;
563          * but for time being this is our only auth choice so doesn't matter.
564          * We just found a server which sets blob length to zero expecting raw.
565          */
566         if (blob_length == 0) {
567                 cifs_dbg(FYI, "missing security blob on negprot\n");
568                 server->sec_ntlmssp = true;
569         }
570
571         rc = cifs_enable_signing(server, ses->sign);
572         if (rc)
573                 goto neg_exit;
574         if (blob_length) {
575                 rc = decode_negTokenInit(security_blob, blob_length, server);
576                 if (rc == 1)
577                         rc = 0;
578                 else if (rc == 0)
579                         rc = -EIO;
580         }
581 neg_exit:
582         free_rsp_buf(resp_buftype, rsp);
583         return rc;
584 }
585
586 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
587 {
588         int rc = 0;
589         struct validate_negotiate_info_req vneg_inbuf;
590         struct validate_negotiate_info_rsp *pneg_rsp;
591         u32 rsplen;
592
593         cifs_dbg(FYI, "validate negotiate\n");
594
595         /*
596          * validation ioctl must be signed, so no point sending this if we
597          * can not sign it.  We could eventually change this to selectively
598          * sign just this, the first and only signed request on a connection.
599          * This is good enough for now since a user who wants better security
600          * would also enable signing on the mount. Having validation of
601          * negotiate info for signed connections helps reduce attack vectors
602          */
603         if (tcon->ses->server->sign == false)
604                 return 0; /* validation requires signing */
605
606         vneg_inbuf.Capabilities =
607                         cpu_to_le32(tcon->ses->server->vals->req_capabilities);
608         memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid,
609                                         SMB2_CLIENT_GUID_SIZE);
610
611         if (tcon->ses->sign)
612                 vneg_inbuf.SecurityMode =
613                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
614         else if (global_secflags & CIFSSEC_MAY_SIGN)
615                 vneg_inbuf.SecurityMode =
616                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
617         else
618                 vneg_inbuf.SecurityMode = 0;
619
620         vneg_inbuf.DialectCount = cpu_to_le16(1);
621         vneg_inbuf.Dialects[0] =
622                 cpu_to_le16(tcon->ses->server->vals->protocol_id);
623
624         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
625                 FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
626                 false /* use_ipc */,
627                 (char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req),
628                 (char **)&pneg_rsp, &rsplen);
629
630         if (rc != 0) {
631                 cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
632                 return -EIO;
633         }
634
635         if (rsplen != sizeof(struct validate_negotiate_info_rsp)) {
636                 cifs_dbg(VFS, "invalid size of protocol negotiate response\n");
637                 return -EIO;
638         }
639
640         /* check validate negotiate info response matches what we got earlier */
641         if (pneg_rsp->Dialect !=
642                         cpu_to_le16(tcon->ses->server->vals->protocol_id))
643                 goto vneg_out;
644
645         if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
646                 goto vneg_out;
647
648         /* do not validate server guid because not saved at negprot time yet */
649
650         if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
651               SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
652                 goto vneg_out;
653
654         /* validate negotiate successful */
655         cifs_dbg(FYI, "validate negotiate info successful\n");
656         return 0;
657
658 vneg_out:
659         cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
660         return -EIO;
661 }
662
663 enum securityEnum
664 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
665 {
666         switch (requested) {
667         case Kerberos:
668         case RawNTLMSSP:
669                 return requested;
670         case NTLMv2:
671                 return RawNTLMSSP;
672         case Unspecified:
673                 if (server->sec_ntlmssp &&
674                         (global_secflags & CIFSSEC_MAY_NTLMSSP))
675                         return RawNTLMSSP;
676                 if ((server->sec_kerberos || server->sec_mskerberos) &&
677                         (global_secflags & CIFSSEC_MAY_KRB5))
678                         return Kerberos;
679                 /* Fallthrough */
680         default:
681                 return Unspecified;
682         }
683 }
684
685 struct SMB2_sess_data {
686         unsigned int xid;
687         struct cifs_ses *ses;
688         struct nls_table *nls_cp;
689         void (*func)(struct SMB2_sess_data *);
690         int result;
691         u64 previous_session;
692
693         /* we will send the SMB in three pieces:
694          * a fixed length beginning part, an optional
695          * SPNEGO blob (which can be zero length), and a
696          * last part which will include the strings
697          * and rest of bcc area. This allows us to avoid
698          * a large buffer 17K allocation
699          */
700         int buf0_type;
701         struct kvec iov[2];
702 };
703
704 static int
705 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
706 {
707         int rc;
708         struct cifs_ses *ses = sess_data->ses;
709         struct smb2_sess_setup_req *req;
710         struct TCP_Server_Info *server = ses->server;
711
712         rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
713         if (rc)
714                 return rc;
715
716         /* First session, not a reauthenticate */
717         req->hdr.sync_hdr.SessionId = 0;
718
719         /* if reconnect, we need to send previous sess id, otherwise it is 0 */
720         req->PreviousSessionId = sess_data->previous_session;
721
722         req->Flags = 0; /* MBZ */
723         /* to enable echos and oplocks */
724         req->hdr.sync_hdr.CreditRequest = cpu_to_le16(3);
725
726         /* only one of SMB2 signing flags may be set in SMB2 request */
727         if (server->sign)
728                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
729         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
730                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
731         else
732                 req->SecurityMode = 0;
733
734         req->Capabilities = 0;
735         req->Channel = 0; /* MBZ */
736
737         sess_data->iov[0].iov_base = (char *)req;
738         /* 4 for rfc1002 length field and 1 for pad */
739         sess_data->iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
740         /*
741          * This variable will be used to clear the buffer
742          * allocated above in case of any error in the calling function.
743          */
744         sess_data->buf0_type = CIFS_SMALL_BUFFER;
745
746         return 0;
747 }
748
749 static void
750 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
751 {
752         free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
753         sess_data->buf0_type = CIFS_NO_BUFFER;
754 }
755
756 static int
757 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
758 {
759         int rc;
760         struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
761         struct kvec rsp_iov = { NULL, 0 };
762
763         /* Testing shows that buffer offset must be at location of Buffer[0] */
764         req->SecurityBufferOffset =
765                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
766                         1 /* pad */ - 4 /* rfc1001 len */);
767         req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
768
769         inc_rfc1001_len(req, sess_data->iov[1].iov_len - 1 /* pad */);
770
771         /* BB add code to build os and lm fields */
772
773         rc = SendReceive2(sess_data->xid, sess_data->ses,
774                                 sess_data->iov, 2,
775                                 &sess_data->buf0_type,
776                                 CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
777         cifs_small_buf_release(sess_data->iov[0].iov_base);
778         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
779
780         return rc;
781 }
782
783 static int
784 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
785 {
786         int rc = 0;
787         struct cifs_ses *ses = sess_data->ses;
788
789         mutex_lock(&ses->server->srv_mutex);
790         if (ses->server->ops->generate_signingkey) {
791                 rc = ses->server->ops->generate_signingkey(ses);
792                 if (rc) {
793                         cifs_dbg(FYI,
794                                 "SMB3 session key generation failed\n");
795                         mutex_unlock(&ses->server->srv_mutex);
796                         return rc;
797                 }
798         }
799         if (!ses->server->session_estab) {
800                 ses->server->sequence_number = 0x2;
801                 ses->server->session_estab = true;
802         }
803         mutex_unlock(&ses->server->srv_mutex);
804
805         cifs_dbg(FYI, "SMB2/3 session established successfully\n");
806         spin_lock(&GlobalMid_Lock);
807         ses->status = CifsGood;
808         ses->need_reconnect = false;
809         spin_unlock(&GlobalMid_Lock);
810         return rc;
811 }
812
813 #ifdef CONFIG_CIFS_UPCALL
814 static void
815 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
816 {
817         int rc;
818         struct cifs_ses *ses = sess_data->ses;
819         struct cifs_spnego_msg *msg;
820         struct key *spnego_key = NULL;
821         struct smb2_sess_setup_rsp *rsp = NULL;
822
823         rc = SMB2_sess_alloc_buffer(sess_data);
824         if (rc)
825                 goto out;
826
827         spnego_key = cifs_get_spnego_key(ses);
828         if (IS_ERR(spnego_key)) {
829                 rc = PTR_ERR(spnego_key);
830                 spnego_key = NULL;
831                 goto out;
832         }
833
834         msg = spnego_key->payload.data[0];
835         /*
836          * check version field to make sure that cifs.upcall is
837          * sending us a response in an expected form
838          */
839         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
840                 cifs_dbg(VFS,
841                           "bad cifs.upcall version. Expected %d got %d",
842                           CIFS_SPNEGO_UPCALL_VERSION, msg->version);
843                 rc = -EKEYREJECTED;
844                 goto out_put_spnego_key;
845         }
846
847         ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
848                                          GFP_KERNEL);
849         if (!ses->auth_key.response) {
850                 cifs_dbg(VFS,
851                         "Kerberos can't allocate (%u bytes) memory",
852                         msg->sesskey_len);
853                 rc = -ENOMEM;
854                 goto out_put_spnego_key;
855         }
856         ses->auth_key.len = msg->sesskey_len;
857
858         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
859         sess_data->iov[1].iov_len = msg->secblob_len;
860
861         rc = SMB2_sess_sendreceive(sess_data);
862         if (rc)
863                 goto out_put_spnego_key;
864
865         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
866         ses->Suid = rsp->hdr.sync_hdr.SessionId;
867
868         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
869
870         rc = SMB2_sess_establish_session(sess_data);
871 out_put_spnego_key:
872         key_invalidate(spnego_key);
873         key_put(spnego_key);
874 out:
875         sess_data->result = rc;
876         sess_data->func = NULL;
877         SMB2_sess_free_buffer(sess_data);
878 }
879 #else
880 static void
881 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
882 {
883         cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
884         sess_data->result = -EOPNOTSUPP;
885         sess_data->func = NULL;
886 }
887 #endif
888
889 static void
890 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
891
892 static void
893 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
894 {
895         int rc;
896         struct cifs_ses *ses = sess_data->ses;
897         struct smb2_sess_setup_rsp *rsp = NULL;
898         char *ntlmssp_blob = NULL;
899         bool use_spnego = false; /* else use raw ntlmssp */
900         u16 blob_length = 0;
901
902         /*
903          * If memory allocation is successful, caller of this function
904          * frees it.
905          */
906         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
907         if (!ses->ntlmssp) {
908                 rc = -ENOMEM;
909                 goto out_err;
910         }
911         ses->ntlmssp->sesskey_per_smbsess = true;
912
913         rc = SMB2_sess_alloc_buffer(sess_data);
914         if (rc)
915                 goto out_err;
916
917         ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
918                                GFP_KERNEL);
919         if (ntlmssp_blob == NULL) {
920                 rc = -ENOMEM;
921                 goto out;
922         }
923
924         build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
925         if (use_spnego) {
926                 /* BB eventually need to add this */
927                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
928                 rc = -EOPNOTSUPP;
929                 goto out;
930         } else {
931                 blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
932                 /* with raw NTLMSSP we don't encapsulate in SPNEGO */
933         }
934         sess_data->iov[1].iov_base = ntlmssp_blob;
935         sess_data->iov[1].iov_len = blob_length;
936
937         rc = SMB2_sess_sendreceive(sess_data);
938         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
939
940         /* If true, rc here is expected and not an error */
941         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
942                 rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
943                 rc = 0;
944
945         if (rc)
946                 goto out;
947
948         if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
949                         le16_to_cpu(rsp->SecurityBufferOffset)) {
950                 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
951                         le16_to_cpu(rsp->SecurityBufferOffset));
952                 rc = -EIO;
953                 goto out;
954         }
955         rc = decode_ntlmssp_challenge(rsp->Buffer,
956                         le16_to_cpu(rsp->SecurityBufferLength), ses);
957         if (rc)
958                 goto out;
959
960         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
961
962
963         ses->Suid = rsp->hdr.sync_hdr.SessionId;
964         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
965
966 out:
967         kfree(ntlmssp_blob);
968         SMB2_sess_free_buffer(sess_data);
969         if (!rc) {
970                 sess_data->result = 0;
971                 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
972                 return;
973         }
974 out_err:
975         kfree(ses->ntlmssp);
976         ses->ntlmssp = NULL;
977         sess_data->result = rc;
978         sess_data->func = NULL;
979 }
980
981 static void
982 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
983 {
984         int rc;
985         struct cifs_ses *ses = sess_data->ses;
986         struct smb2_sess_setup_req *req;
987         struct smb2_sess_setup_rsp *rsp = NULL;
988         unsigned char *ntlmssp_blob = NULL;
989         bool use_spnego = false; /* else use raw ntlmssp */
990         u16 blob_length = 0;
991
992         rc = SMB2_sess_alloc_buffer(sess_data);
993         if (rc)
994                 goto out;
995
996         req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
997         req->hdr.sync_hdr.SessionId = ses->Suid;
998
999         rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1000                                         sess_data->nls_cp);
1001         if (rc) {
1002                 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1003                 goto out;
1004         }
1005
1006         if (use_spnego) {
1007                 /* BB eventually need to add this */
1008                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1009                 rc = -EOPNOTSUPP;
1010                 goto out;
1011         }
1012         sess_data->iov[1].iov_base = ntlmssp_blob;
1013         sess_data->iov[1].iov_len = blob_length;
1014
1015         rc = SMB2_sess_sendreceive(sess_data);
1016         if (rc)
1017                 goto out;
1018
1019         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1020
1021         ses->Suid = rsp->hdr.sync_hdr.SessionId;
1022         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1023
1024         rc = SMB2_sess_establish_session(sess_data);
1025 out:
1026         kfree(ntlmssp_blob);
1027         SMB2_sess_free_buffer(sess_data);
1028         kfree(ses->ntlmssp);
1029         ses->ntlmssp = NULL;
1030         sess_data->result = rc;
1031         sess_data->func = NULL;
1032 }
1033
1034 static int
1035 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1036 {
1037         int type;
1038
1039         type = smb2_select_sectype(ses->server, ses->sectype);
1040         cifs_dbg(FYI, "sess setup type %d\n", type);
1041         if (type == Unspecified) {
1042                 cifs_dbg(VFS,
1043                         "Unable to select appropriate authentication method!");
1044                 return -EINVAL;
1045         }
1046
1047         switch (type) {
1048         case Kerberos:
1049                 sess_data->func = SMB2_auth_kerberos;
1050                 break;
1051         case RawNTLMSSP:
1052                 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1053                 break;
1054         default:
1055                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1056                 return -EOPNOTSUPP;
1057         }
1058
1059         return 0;
1060 }
1061
1062 int
1063 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1064                 const struct nls_table *nls_cp)
1065 {
1066         int rc = 0;
1067         struct TCP_Server_Info *server = ses->server;
1068         struct SMB2_sess_data *sess_data;
1069
1070         cifs_dbg(FYI, "Session Setup\n");
1071
1072         if (!server) {
1073                 WARN(1, "%s: server is NULL!\n", __func__);
1074                 return -EIO;
1075         }
1076
1077         sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1078         if (!sess_data)
1079                 return -ENOMEM;
1080
1081         rc = SMB2_select_sec(ses, sess_data);
1082         if (rc)
1083                 goto out;
1084         sess_data->xid = xid;
1085         sess_data->ses = ses;
1086         sess_data->buf0_type = CIFS_NO_BUFFER;
1087         sess_data->nls_cp = (struct nls_table *) nls_cp;
1088
1089         while (sess_data->func)
1090                 sess_data->func(sess_data);
1091
1092         rc = sess_data->result;
1093 out:
1094         kfree(sess_data);
1095         return rc;
1096 }
1097
1098 int
1099 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1100 {
1101         struct smb2_logoff_req *req; /* response is also trivial struct */
1102         int rc = 0;
1103         struct TCP_Server_Info *server;
1104         int flags = 0;
1105
1106         cifs_dbg(FYI, "disconnect session %p\n", ses);
1107
1108         if (ses && (ses->server))
1109                 server = ses->server;
1110         else
1111                 return -EIO;
1112
1113         /* no need to send SMB logoff if uid already closed due to reconnect */
1114         if (ses->need_reconnect)
1115                 goto smb2_session_already_dead;
1116
1117         rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
1118         if (rc)
1119                 return rc;
1120
1121          /* since no tcon, smb2_init can not do this, so do here */
1122         req->hdr.sync_hdr.SessionId = ses->Suid;
1123
1124         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1125                 flags |= CIFS_TRANSFORM_REQ;
1126         else if (server->sign)
1127                 req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1128
1129         rc = SendReceiveNoRsp(xid, ses, (char *) req, flags);
1130         cifs_small_buf_release(req);
1131         /*
1132          * No tcon so can't do
1133          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1134          */
1135
1136 smb2_session_already_dead:
1137         return rc;
1138 }
1139
1140 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1141 {
1142         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1143 }
1144
1145 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1146
1147 /* These are similar values to what Windows uses */
1148 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1149 {
1150         tcon->max_chunks = 256;
1151         tcon->max_bytes_chunk = 1048576;
1152         tcon->max_bytes_copy = 16777216;
1153 }
1154
1155 int
1156 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1157           struct cifs_tcon *tcon, const struct nls_table *cp)
1158 {
1159         struct smb2_tree_connect_req *req;
1160         struct smb2_tree_connect_rsp *rsp = NULL;
1161         struct kvec iov[2];
1162         struct kvec rsp_iov;
1163         int rc = 0;
1164         int resp_buftype;
1165         int unc_path_len;
1166         struct TCP_Server_Info *server;
1167         __le16 *unc_path = NULL;
1168         int flags = 0;
1169
1170         cifs_dbg(FYI, "TCON\n");
1171
1172         if ((ses->server) && tree)
1173                 server = ses->server;
1174         else
1175                 return -EIO;
1176
1177         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1178         if (unc_path == NULL)
1179                 return -ENOMEM;
1180
1181         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1182         unc_path_len *= 2;
1183         if (unc_path_len < 2) {
1184                 kfree(unc_path);
1185                 return -EINVAL;
1186         }
1187
1188         /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1189         if (tcon)
1190                 tcon->tid = 0;
1191
1192         rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
1193         if (rc) {
1194                 kfree(unc_path);
1195                 return rc;
1196         }
1197
1198         if (tcon == NULL) {
1199                 if ((ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA))
1200                         flags |= CIFS_TRANSFORM_REQ;
1201
1202                 /* since no tcon, smb2_init can not do this, so do here */
1203                 req->hdr.sync_hdr.SessionId = ses->Suid;
1204                 if (ses->server->sign)
1205                         req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1206         } else if (encryption_required(tcon))
1207                 flags |= CIFS_TRANSFORM_REQ;
1208
1209         iov[0].iov_base = (char *)req;
1210         /* 4 for rfc1002 length field and 1 for pad */
1211         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1212
1213         /* Testing shows that buffer offset must be at location of Buffer[0] */
1214         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1215                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
1216         req->PathLength = cpu_to_le16(unc_path_len - 2);
1217         iov[1].iov_base = unc_path;
1218         iov[1].iov_len = unc_path_len;
1219
1220         inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
1221
1222         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
1223         cifs_small_buf_release(req);
1224         rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1225
1226         if (rc != 0) {
1227                 if (tcon) {
1228                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1229                         tcon->need_reconnect = true;
1230                 }
1231                 goto tcon_error_exit;
1232         }
1233
1234         if (tcon == NULL) {
1235                 ses->ipc_tid = rsp->hdr.sync_hdr.TreeId;
1236                 goto tcon_exit;
1237         }
1238
1239         if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
1240                 cifs_dbg(FYI, "connection to disk share\n");
1241         else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
1242                 tcon->ipc = true;
1243                 cifs_dbg(FYI, "connection to pipe share\n");
1244         } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
1245                 tcon->print = true;
1246                 cifs_dbg(FYI, "connection to printer\n");
1247         } else {
1248                 cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1249                 rc = -EOPNOTSUPP;
1250                 goto tcon_error_exit;
1251         }
1252
1253         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1254         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1255         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1256         tcon->tidStatus = CifsGood;
1257         tcon->need_reconnect = false;
1258         tcon->tid = rsp->hdr.sync_hdr.TreeId;
1259         strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1260
1261         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1262             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1263                 cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1264
1265         if (tcon->seal &&
1266             !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1267                 cifs_dbg(VFS, "Encryption is requested but not supported\n");
1268
1269         init_copy_chunk_defaults(tcon);
1270         if (tcon->ses->server->ops->validate_negotiate)
1271                 rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1272 tcon_exit:
1273         free_rsp_buf(resp_buftype, rsp);
1274         kfree(unc_path);
1275         return rc;
1276
1277 tcon_error_exit:
1278         if (rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1279                 cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1280         }
1281         goto tcon_exit;
1282 }
1283
1284 int
1285 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1286 {
1287         struct smb2_tree_disconnect_req *req; /* response is trivial */
1288         int rc = 0;
1289         struct TCP_Server_Info *server;
1290         struct cifs_ses *ses = tcon->ses;
1291         int flags = 0;
1292
1293         cifs_dbg(FYI, "Tree Disconnect\n");
1294
1295         if (ses && (ses->server))
1296                 server = ses->server;
1297         else
1298                 return -EIO;
1299
1300         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1301                 return 0;
1302
1303         rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
1304         if (rc)
1305                 return rc;
1306
1307         if (encryption_required(tcon))
1308                 flags |= CIFS_TRANSFORM_REQ;
1309
1310         rc = SendReceiveNoRsp(xid, ses, (char *)req, flags);
1311         cifs_small_buf_release(req);
1312         if (rc)
1313                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1314
1315         return rc;
1316 }
1317
1318
1319 static struct create_durable *
1320 create_durable_buf(void)
1321 {
1322         struct create_durable *buf;
1323
1324         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1325         if (!buf)
1326                 return NULL;
1327
1328         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1329                                         (struct create_durable, Data));
1330         buf->ccontext.DataLength = cpu_to_le32(16);
1331         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1332                                 (struct create_durable, Name));
1333         buf->ccontext.NameLength = cpu_to_le16(4);
1334         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1335         buf->Name[0] = 'D';
1336         buf->Name[1] = 'H';
1337         buf->Name[2] = 'n';
1338         buf->Name[3] = 'Q';
1339         return buf;
1340 }
1341
1342 static struct create_durable *
1343 create_reconnect_durable_buf(struct cifs_fid *fid)
1344 {
1345         struct create_durable *buf;
1346
1347         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1348         if (!buf)
1349                 return NULL;
1350
1351         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1352                                         (struct create_durable, Data));
1353         buf->ccontext.DataLength = cpu_to_le32(16);
1354         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1355                                 (struct create_durable, Name));
1356         buf->ccontext.NameLength = cpu_to_le16(4);
1357         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1358         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1359         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1360         buf->Name[0] = 'D';
1361         buf->Name[1] = 'H';
1362         buf->Name[2] = 'n';
1363         buf->Name[3] = 'C';
1364         return buf;
1365 }
1366
1367 static __u8
1368 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1369                   unsigned int *epoch)
1370 {
1371         char *data_offset;
1372         struct create_context *cc;
1373         unsigned int next;
1374         unsigned int remaining;
1375         char *name;
1376
1377         data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
1378         remaining = le32_to_cpu(rsp->CreateContextsLength);
1379         cc = (struct create_context *)data_offset;
1380         while (remaining >= sizeof(struct create_context)) {
1381                 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1382                 if (le16_to_cpu(cc->NameLength) == 4 &&
1383                     strncmp(name, "RqLs", 4) == 0)
1384                         return server->ops->parse_lease_buf(cc, epoch);
1385
1386                 next = le32_to_cpu(cc->Next);
1387                 if (!next)
1388                         break;
1389                 remaining -= next;
1390                 cc = (struct create_context *)((char *)cc + next);
1391         }
1392
1393         return 0;
1394 }
1395
1396 static int
1397 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1398                   unsigned int *num_iovec, __u8 *oplock)
1399 {
1400         struct smb2_create_req *req = iov[0].iov_base;
1401         unsigned int num = *num_iovec;
1402
1403         iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
1404         if (iov[num].iov_base == NULL)
1405                 return -ENOMEM;
1406         iov[num].iov_len = server->vals->create_lease_size;
1407         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1408         if (!req->CreateContextsOffset)
1409                 req->CreateContextsOffset = cpu_to_le32(
1410                                 sizeof(struct smb2_create_req) - 4 +
1411                                 iov[num - 1].iov_len);
1412         le32_add_cpu(&req->CreateContextsLength,
1413                      server->vals->create_lease_size);
1414         inc_rfc1001_len(&req->hdr, server->vals->create_lease_size);
1415         *num_iovec = num + 1;
1416         return 0;
1417 }
1418
1419 static struct create_durable_v2 *
1420 create_durable_v2_buf(struct cifs_fid *pfid)
1421 {
1422         struct create_durable_v2 *buf;
1423
1424         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1425         if (!buf)
1426                 return NULL;
1427
1428         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1429                                         (struct create_durable_v2, dcontext));
1430         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1431         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1432                                 (struct create_durable_v2, Name));
1433         buf->ccontext.NameLength = cpu_to_le16(4);
1434
1435         buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1436         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1437         generate_random_uuid(buf->dcontext.CreateGuid);
1438         memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1439
1440         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1441         buf->Name[0] = 'D';
1442         buf->Name[1] = 'H';
1443         buf->Name[2] = '2';
1444         buf->Name[3] = 'Q';
1445         return buf;
1446 }
1447
1448 static struct create_durable_handle_reconnect_v2 *
1449 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1450 {
1451         struct create_durable_handle_reconnect_v2 *buf;
1452
1453         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1454                         GFP_KERNEL);
1455         if (!buf)
1456                 return NULL;
1457
1458         buf->ccontext.DataOffset =
1459                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1460                                      dcontext));
1461         buf->ccontext.DataLength =
1462                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1463         buf->ccontext.NameOffset =
1464                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1465                             Name));
1466         buf->ccontext.NameLength = cpu_to_le16(4);
1467
1468         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1469         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1470         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1471         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1472
1473         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1474         buf->Name[0] = 'D';
1475         buf->Name[1] = 'H';
1476         buf->Name[2] = '2';
1477         buf->Name[3] = 'C';
1478         return buf;
1479 }
1480
1481 static int
1482 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1483                     struct cifs_open_parms *oparms)
1484 {
1485         struct smb2_create_req *req = iov[0].iov_base;
1486         unsigned int num = *num_iovec;
1487
1488         iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1489         if (iov[num].iov_base == NULL)
1490                 return -ENOMEM;
1491         iov[num].iov_len = sizeof(struct create_durable_v2);
1492         if (!req->CreateContextsOffset)
1493                 req->CreateContextsOffset =
1494                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1495                                                                 iov[1].iov_len);
1496         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1497         inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2));
1498         *num_iovec = num + 1;
1499         return 0;
1500 }
1501
1502 static int
1503 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1504                     struct cifs_open_parms *oparms)
1505 {
1506         struct smb2_create_req *req = iov[0].iov_base;
1507         unsigned int num = *num_iovec;
1508
1509         /* indicate that we don't need to relock the file */
1510         oparms->reconnect = false;
1511
1512         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1513         if (iov[num].iov_base == NULL)
1514                 return -ENOMEM;
1515         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1516         if (!req->CreateContextsOffset)
1517                 req->CreateContextsOffset =
1518                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1519                                                                 iov[1].iov_len);
1520         le32_add_cpu(&req->CreateContextsLength,
1521                         sizeof(struct create_durable_handle_reconnect_v2));
1522         inc_rfc1001_len(&req->hdr,
1523                         sizeof(struct create_durable_handle_reconnect_v2));
1524         *num_iovec = num + 1;
1525         return 0;
1526 }
1527
1528 static int
1529 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1530                     struct cifs_open_parms *oparms, bool use_persistent)
1531 {
1532         struct smb2_create_req *req = iov[0].iov_base;
1533         unsigned int num = *num_iovec;
1534
1535         if (use_persistent) {
1536                 if (oparms->reconnect)
1537                         return add_durable_reconnect_v2_context(iov, num_iovec,
1538                                                                 oparms);
1539                 else
1540                         return add_durable_v2_context(iov, num_iovec, oparms);
1541         }
1542
1543         if (oparms->reconnect) {
1544                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1545                 /* indicate that we don't need to relock the file */
1546                 oparms->reconnect = false;
1547         } else
1548                 iov[num].iov_base = create_durable_buf();
1549         if (iov[num].iov_base == NULL)
1550                 return -ENOMEM;
1551         iov[num].iov_len = sizeof(struct create_durable);
1552         if (!req->CreateContextsOffset)
1553                 req->CreateContextsOffset =
1554                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1555                                                                 iov[1].iov_len);
1556         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1557         inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
1558         *num_iovec = num + 1;
1559         return 0;
1560 }
1561
1562 static int
1563 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
1564                             const char *treename, const __le16 *path)
1565 {
1566         int treename_len, path_len;
1567         struct nls_table *cp;
1568         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
1569
1570         /*
1571          * skip leading "\\"
1572          */
1573         treename_len = strlen(treename);
1574         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
1575                 return -EINVAL;
1576
1577         treename += 2;
1578         treename_len -= 2;
1579
1580         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
1581
1582         /*
1583          * make room for one path separator between the treename and
1584          * path
1585          */
1586         *out_len = treename_len + 1 + path_len;
1587
1588         /*
1589          * final path needs to be null-terminated UTF16 with a
1590          * size aligned to 8
1591          */
1592
1593         *out_size = roundup((*out_len+1)*2, 8);
1594         *out_path = kzalloc(*out_size, GFP_KERNEL);
1595         if (!*out_path)
1596                 return -ENOMEM;
1597
1598         cp = load_nls_default();
1599         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
1600         UniStrcat(*out_path, sep);
1601         UniStrcat(*out_path, path);
1602         unload_nls(cp);
1603
1604         return 0;
1605 }
1606
1607 int
1608 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
1609           __u8 *oplock, struct smb2_file_all_info *buf,
1610           struct smb2_err_rsp **err_buf)
1611 {
1612         struct smb2_create_req *req;
1613         struct smb2_create_rsp *rsp;
1614         struct TCP_Server_Info *server;
1615         struct cifs_tcon *tcon = oparms->tcon;
1616         struct cifs_ses *ses = tcon->ses;
1617         struct kvec iov[4];
1618         struct kvec rsp_iov;
1619         int resp_buftype;
1620         int uni_path_len;
1621         __le16 *copy_path = NULL;
1622         int copy_size;
1623         int rc = 0;
1624         unsigned int n_iov = 2;
1625         __u32 file_attributes = 0;
1626         char *dhc_buf = NULL, *lc_buf = NULL;
1627         int flags = 0;
1628
1629         cifs_dbg(FYI, "create/open\n");
1630
1631         if (ses && (ses->server))
1632                 server = ses->server;
1633         else
1634                 return -EIO;
1635
1636         rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
1637         if (rc)
1638                 return rc;
1639
1640         if (encryption_required(tcon))
1641                 flags |= CIFS_TRANSFORM_REQ;
1642
1643         if (oparms->create_options & CREATE_OPTION_READONLY)
1644                 file_attributes |= ATTR_READONLY;
1645         if (oparms->create_options & CREATE_OPTION_SPECIAL)
1646                 file_attributes |= ATTR_SYSTEM;
1647
1648         req->ImpersonationLevel = IL_IMPERSONATION;
1649         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
1650         /* File attributes ignored on open (used in create though) */
1651         req->FileAttributes = cpu_to_le32(file_attributes);
1652         req->ShareAccess = FILE_SHARE_ALL_LE;
1653         req->CreateDisposition = cpu_to_le32(oparms->disposition);
1654         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
1655
1656         iov[0].iov_base = (char *)req;
1657         /* 4 for rfc1002 length field */
1658         iov[0].iov_len = get_rfc1002_length(req) + 4;
1659         /* -1 since last byte is buf[0] which is sent below (path) */
1660         iov[0].iov_len--;
1661
1662         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
1663
1664         /* [MS-SMB2] 2.2.13 NameOffset:
1665          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
1666          * the SMB2 header, the file name includes a prefix that will
1667          * be processed during DFS name normalization as specified in
1668          * section 3.3.5.9. Otherwise, the file name is relative to
1669          * the share that is identified by the TreeId in the SMB2
1670          * header.
1671          */
1672         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
1673                 int name_len;
1674
1675                 req->hdr.sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
1676                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
1677                                                  &name_len,
1678                                                  tcon->treeName, path);
1679                 if (rc)
1680                         return rc;
1681                 req->NameLength = cpu_to_le16(name_len * 2);
1682                 uni_path_len = copy_size;
1683                 path = copy_path;
1684         } else {
1685                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
1686                 /* MUST set path len (NameLength) to 0 opening root of share */
1687                 req->NameLength = cpu_to_le16(uni_path_len - 2);
1688                 if (uni_path_len % 8 != 0) {
1689                         copy_size = roundup(uni_path_len, 8);
1690                         copy_path = kzalloc(copy_size, GFP_KERNEL);
1691                         if (!copy_path)
1692                                 return -ENOMEM;
1693                         memcpy((char *)copy_path, (const char *)path,
1694                                uni_path_len);
1695                         uni_path_len = copy_size;
1696                         path = copy_path;
1697                 }
1698         }
1699
1700         iov[1].iov_len = uni_path_len;
1701         iov[1].iov_base = path;
1702         /* -1 since last byte is buf[0] which was counted in smb2_buf_len */
1703         inc_rfc1001_len(req, uni_path_len - 1);
1704
1705         if (!server->oplocks)
1706                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
1707
1708         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1709             *oplock == SMB2_OPLOCK_LEVEL_NONE)
1710                 req->RequestedOplockLevel = *oplock;
1711         else {
1712                 rc = add_lease_context(server, iov, &n_iov, oplock);
1713                 if (rc) {
1714                         cifs_small_buf_release(req);
1715                         kfree(copy_path);
1716                         return rc;
1717                 }
1718                 lc_buf = iov[n_iov-1].iov_base;
1719         }
1720
1721         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1722                 /* need to set Next field of lease context if we request it */
1723                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1724                         struct create_context *ccontext =
1725                             (struct create_context *)iov[n_iov-1].iov_base;
1726                         ccontext->Next =
1727                                 cpu_to_le32(server->vals->create_lease_size);
1728                 }
1729
1730                 rc = add_durable_context(iov, &n_iov, oparms,
1731                                         tcon->use_persistent);
1732                 if (rc) {
1733                         cifs_small_buf_release(req);
1734                         kfree(copy_path);
1735                         kfree(lc_buf);
1736                         return rc;
1737                 }
1738                 dhc_buf = iov[n_iov-1].iov_base;
1739         }
1740
1741         rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
1742         cifs_small_buf_release(req);
1743         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
1744
1745         if (rc != 0) {
1746                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1747                 if (err_buf)
1748                         *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
1749                                            GFP_KERNEL);
1750                 goto creat_exit;
1751         }
1752
1753         oparms->fid->persistent_fid = rsp->PersistentFileId;
1754         oparms->fid->volatile_fid = rsp->VolatileFileId;
1755
1756         if (buf) {
1757                 memcpy(buf, &rsp->CreationTime, 32);
1758                 buf->AllocationSize = rsp->AllocationSize;
1759                 buf->EndOfFile = rsp->EndofFile;
1760                 buf->Attributes = rsp->FileAttributes;
1761                 buf->NumberOfLinks = cpu_to_le32(1);
1762                 buf->DeletePending = 0;
1763         }
1764
1765         if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1766                 *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
1767         else
1768                 *oplock = rsp->OplockLevel;
1769 creat_exit:
1770         kfree(copy_path);
1771         kfree(lc_buf);
1772         kfree(dhc_buf);
1773         free_rsp_buf(resp_buftype, rsp);
1774         return rc;
1775 }
1776
1777 /*
1778  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
1779  */
1780 int
1781 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1782            u64 volatile_fid, u32 opcode, bool is_fsctl, bool use_ipc,
1783            char *in_data, u32 indatalen,
1784            char **out_data, u32 *plen /* returned data len */)
1785 {
1786         struct smb2_ioctl_req *req;
1787         struct smb2_ioctl_rsp *rsp;
1788         struct smb2_sync_hdr *shdr;
1789         struct TCP_Server_Info *server;
1790         struct cifs_ses *ses;
1791         struct kvec iov[2];
1792         struct kvec rsp_iov;
1793         int resp_buftype;
1794         int n_iov;
1795         int rc = 0;
1796         int flags = 0;
1797
1798         cifs_dbg(FYI, "SMB2 IOCTL\n");
1799
1800         if (out_data != NULL)
1801                 *out_data = NULL;
1802
1803         /* zero out returned data len, in case of error */
1804         if (plen)
1805                 *plen = 0;
1806
1807         if (tcon)
1808                 ses = tcon->ses;
1809         else
1810                 return -EIO;
1811
1812         if (ses && (ses->server))
1813                 server = ses->server;
1814         else
1815                 return -EIO;
1816
1817         rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
1818         if (rc)
1819                 return rc;
1820
1821         if (use_ipc) {
1822                 if (ses->ipc_tid == 0) {
1823                         cifs_small_buf_release(req);
1824                         return -ENOTCONN;
1825                 }
1826
1827                 cifs_dbg(FYI, "replacing tid 0x%x with IPC tid 0x%x\n",
1828                          req->hdr.sync_hdr.TreeId, ses->ipc_tid);
1829                 req->hdr.sync_hdr.TreeId = ses->ipc_tid;
1830         }
1831         if (encryption_required(tcon))
1832                 flags |= CIFS_TRANSFORM_REQ;
1833
1834         req->CtlCode = cpu_to_le32(opcode);
1835         req->PersistentFileId = persistent_fid;
1836         req->VolatileFileId = volatile_fid;
1837
1838         if (indatalen) {
1839                 req->InputCount = cpu_to_le32(indatalen);
1840                 /* do not set InputOffset if no input data */
1841                 req->InputOffset =
1842                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
1843                 iov[1].iov_base = in_data;
1844                 iov[1].iov_len = indatalen;
1845                 n_iov = 2;
1846         } else
1847                 n_iov = 1;
1848
1849         req->OutputOffset = 0;
1850         req->OutputCount = 0; /* MBZ */
1851
1852         /*
1853          * Could increase MaxOutputResponse, but that would require more
1854          * than one credit. Windows typically sets this smaller, but for some
1855          * ioctls it may be useful to allow server to send more. No point
1856          * limiting what the server can send as long as fits in one credit
1857          */
1858         req->MaxOutputResponse = cpu_to_le32(0xFF00); /* < 64K uses 1 credit */
1859
1860         if (is_fsctl)
1861                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1862         else
1863                 req->Flags = 0;
1864
1865         iov[0].iov_base = (char *)req;
1866
1867         /*
1868          * If no input data, the size of ioctl struct in
1869          * protocol spec still includes a 1 byte data buffer,
1870          * but if input data passed to ioctl, we do not
1871          * want to double count this, so we do not send
1872          * the dummy one byte of data in iovec[0] if sending
1873          * input data (in iovec[1]). We also must add 4 bytes
1874          * in first iovec to allow for rfc1002 length field.
1875          */
1876
1877         if (indatalen) {
1878                 iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1879                 inc_rfc1001_len(req, indatalen - 1);
1880         } else
1881                 iov[0].iov_len = get_rfc1002_length(req) + 4;
1882
1883
1884         rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
1885         cifs_small_buf_release(req);
1886         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
1887
1888         if ((rc != 0) && (rc != -EINVAL)) {
1889                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1890                 goto ioctl_exit;
1891         } else if (rc == -EINVAL) {
1892                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
1893                     (opcode != FSCTL_SRV_COPYCHUNK)) {
1894                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1895                         goto ioctl_exit;
1896                 }
1897         }
1898
1899         /* check if caller wants to look at return data or just return rc */
1900         if ((plen == NULL) || (out_data == NULL))
1901                 goto ioctl_exit;
1902
1903         *plen = le32_to_cpu(rsp->OutputCount);
1904
1905         /* We check for obvious errors in the output buffer length and offset */
1906         if (*plen == 0)
1907                 goto ioctl_exit; /* server returned no data */
1908         else if (*plen > 0xFF00) {
1909                 cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
1910                 *plen = 0;
1911                 rc = -EIO;
1912                 goto ioctl_exit;
1913         }
1914
1915         if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
1916                 cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
1917                         le32_to_cpu(rsp->OutputOffset));
1918                 *plen = 0;
1919                 rc = -EIO;
1920                 goto ioctl_exit;
1921         }
1922
1923         *out_data = kmalloc(*plen, GFP_KERNEL);
1924         if (*out_data == NULL) {
1925                 rc = -ENOMEM;
1926                 goto ioctl_exit;
1927         }
1928
1929         shdr = get_sync_hdr(rsp);
1930         memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen);
1931 ioctl_exit:
1932         free_rsp_buf(resp_buftype, rsp);
1933         return rc;
1934 }
1935
1936 /*
1937  *   Individual callers to ioctl worker function follow
1938  */
1939
1940 int
1941 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1942                      u64 persistent_fid, u64 volatile_fid)
1943 {
1944         int rc;
1945         struct  compress_ioctl fsctl_input;
1946         char *ret_data = NULL;
1947
1948         fsctl_input.CompressionState =
1949                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
1950
1951         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1952                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
1953                         false /* use_ipc */,
1954                         (char *)&fsctl_input /* data input */,
1955                         2 /* in data len */, &ret_data /* out data */, NULL);
1956
1957         cifs_dbg(FYI, "set compression rc %d\n", rc);
1958
1959         return rc;
1960 }
1961
1962 int
1963 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
1964            u64 persistent_fid, u64 volatile_fid)
1965 {
1966         struct smb2_close_req *req;
1967         struct smb2_close_rsp *rsp;
1968         struct TCP_Server_Info *server;
1969         struct cifs_ses *ses = tcon->ses;
1970         struct kvec iov[1];
1971         struct kvec rsp_iov;
1972         int resp_buftype;
1973         int rc = 0;
1974         int flags = 0;
1975
1976         cifs_dbg(FYI, "Close\n");
1977
1978         if (ses && (ses->server))
1979                 server = ses->server;
1980         else
1981                 return -EIO;
1982
1983         rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
1984         if (rc)
1985                 return rc;
1986
1987         if (encryption_required(tcon))
1988                 flags |= CIFS_TRANSFORM_REQ;
1989
1990         req->PersistentFileId = persistent_fid;
1991         req->VolatileFileId = volatile_fid;
1992
1993         iov[0].iov_base = (char *)req;
1994         /* 4 for rfc1002 length field */
1995         iov[0].iov_len = get_rfc1002_length(req) + 4;
1996
1997         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
1998         cifs_small_buf_release(req);
1999         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
2000
2001         if (rc != 0) {
2002                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
2003                 goto close_exit;
2004         }
2005
2006         /* BB FIXME - decode close response, update inode for caching */
2007
2008 close_exit:
2009         free_rsp_buf(resp_buftype, rsp);
2010         return rc;
2011 }
2012
2013 static int
2014 validate_buf(unsigned int offset, unsigned int buffer_length,
2015              struct smb2_hdr *hdr, unsigned int min_buf_size)
2016
2017 {
2018         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
2019         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
2020         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2021         char *end_of_buf = begin_of_buf + buffer_length;
2022
2023
2024         if (buffer_length < min_buf_size) {
2025                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
2026                          buffer_length, min_buf_size);
2027                 return -EINVAL;
2028         }
2029
2030         /* check if beyond RFC1001 maximum length */
2031         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
2032                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
2033                          buffer_length, smb_len);
2034                 return -EINVAL;
2035         }
2036
2037         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
2038                 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
2039                 return -EINVAL;
2040         }
2041
2042         return 0;
2043 }
2044
2045 /*
2046  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
2047  * Caller must free buffer.
2048  */
2049 static int
2050 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
2051                       struct smb2_hdr *hdr, unsigned int minbufsize,
2052                       char *data)
2053
2054 {
2055         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2056         int rc;
2057
2058         if (!data)
2059                 return -EINVAL;
2060
2061         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
2062         if (rc)
2063                 return rc;
2064
2065         memcpy(data, begin_of_buf, buffer_length);
2066
2067         return 0;
2068 }
2069
2070 static int
2071 query_info(const unsigned int xid, struct cifs_tcon *tcon,
2072            u64 persistent_fid, u64 volatile_fid, u8 info_class,
2073            size_t output_len, size_t min_len, void *data)
2074 {
2075         struct smb2_query_info_req *req;
2076         struct smb2_query_info_rsp *rsp = NULL;
2077         struct kvec iov[2];
2078         struct kvec rsp_iov;
2079         int rc = 0;
2080         int resp_buftype;
2081         struct TCP_Server_Info *server;
2082         struct cifs_ses *ses = tcon->ses;
2083         int flags = 0;
2084
2085         cifs_dbg(FYI, "Query Info\n");
2086
2087         if (ses && (ses->server))
2088                 server = ses->server;
2089         else
2090                 return -EIO;
2091
2092         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
2093         if (rc)
2094                 return rc;
2095
2096         if (encryption_required(tcon))
2097                 flags |= CIFS_TRANSFORM_REQ;
2098
2099         req->InfoType = SMB2_O_INFO_FILE;
2100         req->FileInfoClass = info_class;
2101         req->PersistentFileId = persistent_fid;
2102         req->VolatileFileId = volatile_fid;
2103         /* 4 for rfc1002 length field and 1 for Buffer */
2104         req->InputBufferOffset =
2105                 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
2106         req->OutputBufferLength = cpu_to_le32(output_len);
2107
2108         iov[0].iov_base = (char *)req;
2109         /* 4 for rfc1002 length field */
2110         iov[0].iov_len = get_rfc1002_length(req) + 4;
2111
2112         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2113         cifs_small_buf_release(req);
2114         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2115
2116         if (rc) {
2117                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2118                 goto qinf_exit;
2119         }
2120
2121         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
2122                                    le32_to_cpu(rsp->OutputBufferLength),
2123                                    &rsp->hdr, min_len, data);
2124
2125 qinf_exit:
2126         free_rsp_buf(resp_buftype, rsp);
2127         return rc;
2128 }
2129
2130 int
2131 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
2132                 u64 persistent_fid, u64 volatile_fid,
2133                 struct smb2_file_all_info *data)
2134 {
2135         return query_info(xid, tcon, persistent_fid, volatile_fid,
2136                           FILE_ALL_INFORMATION,
2137                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
2138                           sizeof(struct smb2_file_all_info), data);
2139 }
2140
2141 int
2142 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
2143                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
2144 {
2145         return query_info(xid, tcon, persistent_fid, volatile_fid,
2146                           FILE_INTERNAL_INFORMATION,
2147                           sizeof(struct smb2_file_internal_info),
2148                           sizeof(struct smb2_file_internal_info), uniqueid);
2149 }
2150
2151 /*
2152  * This is a no-op for now. We're not really interested in the reply, but
2153  * rather in the fact that the server sent one and that server->lstrp
2154  * gets updated.
2155  *
2156  * FIXME: maybe we should consider checking that the reply matches request?
2157  */
2158 static void
2159 smb2_echo_callback(struct mid_q_entry *mid)
2160 {
2161         struct TCP_Server_Info *server = mid->callback_data;
2162         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
2163         unsigned int credits_received = 1;
2164
2165         if (mid->mid_state == MID_RESPONSE_RECEIVED)
2166                 credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2167
2168         mutex_lock(&server->srv_mutex);
2169         DeleteMidQEntry(mid);
2170         mutex_unlock(&server->srv_mutex);
2171         add_credits(server, credits_received, CIFS_ECHO_OP);
2172 }
2173
2174 void smb2_reconnect_server(struct work_struct *work)
2175 {
2176         struct TCP_Server_Info *server = container_of(work,
2177                                         struct TCP_Server_Info, reconnect.work);
2178         struct cifs_ses *ses;
2179         struct cifs_tcon *tcon, *tcon2;
2180         struct list_head tmp_list;
2181         int tcon_exist = false;
2182         int rc;
2183         int resched = false;
2184
2185
2186         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
2187         mutex_lock(&server->reconnect_mutex);
2188
2189         INIT_LIST_HEAD(&tmp_list);
2190         cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
2191
2192         spin_lock(&cifs_tcp_ses_lock);
2193         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2194                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2195                         if (tcon->need_reconnect || tcon->need_reopen_files) {
2196                                 tcon->tc_count++;
2197                                 list_add_tail(&tcon->rlist, &tmp_list);
2198                                 tcon_exist = true;
2199                         }
2200                 }
2201         }
2202         /*
2203          * Get the reference to server struct to be sure that the last call of
2204          * cifs_put_tcon() in the loop below won't release the server pointer.
2205          */
2206         if (tcon_exist)
2207                 server->srv_count++;
2208
2209         spin_unlock(&cifs_tcp_ses_lock);
2210
2211         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
2212                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon);
2213                 if (!rc)
2214                         cifs_reopen_persistent_handles(tcon);
2215                 else
2216                         resched = true;
2217                 list_del_init(&tcon->rlist);
2218                 cifs_put_tcon(tcon);
2219         }
2220
2221         cifs_dbg(FYI, "Reconnecting tcons finished\n");
2222         if (resched)
2223                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
2224         mutex_unlock(&server->reconnect_mutex);
2225
2226         /* now we can safely release srv struct */
2227         if (tcon_exist)
2228                 cifs_put_tcp_session(server, 1);
2229 }
2230
2231 int
2232 SMB2_echo(struct TCP_Server_Info *server)
2233 {
2234         struct smb2_echo_req *req;
2235         int rc = 0;
2236         struct kvec iov[2];
2237         struct smb_rqst rqst = { .rq_iov = iov,
2238                                  .rq_nvec = 2 };
2239
2240         cifs_dbg(FYI, "In echo request\n");
2241
2242         if (server->tcpStatus == CifsNeedNegotiate) {
2243                 /* No need to send echo on newly established connections */
2244                 queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
2245                 return rc;
2246         }
2247
2248         rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
2249         if (rc)
2250                 return rc;
2251
2252         req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
2253
2254         /* 4 for rfc1002 length field */
2255         iov[0].iov_len = 4;
2256         iov[0].iov_base = (char *)req;
2257         iov[1].iov_len = get_rfc1002_length(req);
2258         iov[1].iov_base = (char *)req + 4;
2259
2260         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
2261                              server, CIFS_ECHO_OP);
2262         if (rc)
2263                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
2264
2265         cifs_small_buf_release(req);
2266         return rc;
2267 }
2268
2269 int
2270 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2271            u64 volatile_fid)
2272 {
2273         struct smb2_flush_req *req;
2274         struct TCP_Server_Info *server;
2275         struct cifs_ses *ses = tcon->ses;
2276         struct kvec iov[1];
2277         struct kvec rsp_iov;
2278         int resp_buftype;
2279         int rc = 0;
2280         int flags = 0;
2281
2282         cifs_dbg(FYI, "Flush\n");
2283
2284         if (ses && (ses->server))
2285                 server = ses->server;
2286         else
2287                 return -EIO;
2288
2289         rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
2290         if (rc)
2291                 return rc;
2292
2293         if (encryption_required(tcon))
2294                 flags |= CIFS_TRANSFORM_REQ;
2295
2296         req->PersistentFileId = persistent_fid;
2297         req->VolatileFileId = volatile_fid;
2298
2299         iov[0].iov_base = (char *)req;
2300         /* 4 for rfc1002 length field */
2301         iov[0].iov_len = get_rfc1002_length(req) + 4;
2302
2303         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2304         cifs_small_buf_release(req);
2305
2306         if (rc != 0)
2307                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
2308
2309         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2310         return rc;
2311 }
2312
2313 /*
2314  * To form a chain of read requests, any read requests after the first should
2315  * have the end_of_chain boolean set to true.
2316  */
2317 static int
2318 smb2_new_read_req(void **buf, unsigned int *total_len,
2319                   struct cifs_io_parms *io_parms, unsigned int remaining_bytes,
2320                   int request_type)
2321 {
2322         int rc = -EACCES;
2323         struct smb2_read_plain_req *req = NULL;
2324         struct smb2_sync_hdr *shdr;
2325
2326         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
2327                                  total_len);
2328         if (rc)
2329                 return rc;
2330         if (io_parms->tcon->ses->server == NULL)
2331                 return -ECONNABORTED;
2332
2333         shdr = &req->sync_hdr;
2334         shdr->ProcessId = cpu_to_le32(io_parms->pid);
2335
2336         req->PersistentFileId = io_parms->persistent_fid;
2337         req->VolatileFileId = io_parms->volatile_fid;
2338         req->ReadChannelInfoOffset = 0; /* reserved */
2339         req->ReadChannelInfoLength = 0; /* reserved */
2340         req->Channel = 0; /* reserved */
2341         req->MinimumCount = 0;
2342         req->Length = cpu_to_le32(io_parms->length);
2343         req->Offset = cpu_to_le64(io_parms->offset);
2344
2345         if (request_type & CHAINED_REQUEST) {
2346                 if (!(request_type & END_OF_CHAIN)) {
2347                         /* next 8-byte aligned request */
2348                         *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
2349                         shdr->NextCommand = cpu_to_le32(*total_len);
2350                 } else /* END_OF_CHAIN */
2351                         shdr->NextCommand = 0;
2352                 if (request_type & RELATED_REQUEST) {
2353                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2354                         /*
2355                          * Related requests use info from previous read request
2356                          * in chain.
2357                          */
2358                         shdr->SessionId = 0xFFFFFFFF;
2359                         shdr->TreeId = 0xFFFFFFFF;
2360                         req->PersistentFileId = 0xFFFFFFFF;
2361                         req->VolatileFileId = 0xFFFFFFFF;
2362                 }
2363         }
2364         if (remaining_bytes > io_parms->length)
2365                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
2366         else
2367                 req->RemainingBytes = 0;
2368
2369         *buf = req;
2370         return rc;
2371 }
2372
2373 static void
2374 smb2_readv_callback(struct mid_q_entry *mid)
2375 {
2376         struct cifs_readdata *rdata = mid->callback_data;
2377         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
2378         struct TCP_Server_Info *server = tcon->ses->server;
2379         struct smb2_sync_hdr *shdr =
2380                                 (struct smb2_sync_hdr *)rdata->iov[1].iov_base;
2381         unsigned int credits_received = 1;
2382         struct smb_rqst rqst = { .rq_iov = rdata->iov,
2383                                  .rq_nvec = 2,
2384                                  .rq_pages = rdata->pages,
2385                                  .rq_npages = rdata->nr_pages,
2386                                  .rq_pagesz = rdata->pagesz,
2387                                  .rq_tailsz = rdata->tailsz };
2388
2389         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
2390                  __func__, mid->mid, mid->mid_state, rdata->result,
2391                  rdata->bytes);
2392
2393         switch (mid->mid_state) {
2394         case MID_RESPONSE_RECEIVED:
2395                 credits_received = le16_to_cpu(shdr->CreditRequest);
2396                 /* result already set, check signature */
2397                 if (server->sign && !mid->decrypted) {
2398                         int rc;
2399
2400                         rc = smb2_verify_signature(&rqst, server);
2401                         if (rc)
2402                                 cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
2403                                          rc);
2404                 }
2405                 /* FIXME: should this be counted toward the initiating task? */
2406                 task_io_account_read(rdata->got_bytes);
2407                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2408                 break;
2409         case MID_REQUEST_SUBMITTED:
2410         case MID_RETRY_NEEDED:
2411                 rdata->result = -EAGAIN;
2412                 if (server->sign && rdata->got_bytes)
2413                         /* reset bytes number since we can not check a sign */
2414                         rdata->got_bytes = 0;
2415                 /* FIXME: should this be counted toward the initiating task? */
2416                 task_io_account_read(rdata->got_bytes);
2417                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
2418                 break;
2419         default:
2420                 if (rdata->result != -ENODATA)
2421                         rdata->result = -EIO;
2422         }
2423
2424         if (rdata->result)
2425                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
2426
2427         queue_work(cifsiod_wq, &rdata->work);
2428         mutex_lock(&server->srv_mutex);
2429         DeleteMidQEntry(mid);
2430         mutex_unlock(&server->srv_mutex);
2431         add_credits(server, credits_received, 0);
2432 }
2433
2434 /* smb2_async_readv - send an async read, and set up mid to handle result */
2435 int
2436 smb2_async_readv(struct cifs_readdata *rdata)
2437 {
2438         int rc, flags = 0;
2439         char *buf;
2440         struct smb2_sync_hdr *shdr;
2441         struct cifs_io_parms io_parms;
2442         struct smb_rqst rqst = { .rq_iov = rdata->iov,
2443                                  .rq_nvec = 2 };
2444         struct TCP_Server_Info *server;
2445         unsigned int total_len;
2446         __be32 req_len;
2447
2448         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
2449                  __func__, rdata->offset, rdata->bytes);
2450
2451         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
2452         io_parms.offset = rdata->offset;
2453         io_parms.length = rdata->bytes;
2454         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
2455         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
2456         io_parms.pid = rdata->pid;
2457
2458         server = io_parms.tcon->ses->server;
2459
2460         rc = smb2_new_read_req((void **) &buf, &total_len, &io_parms, 0, 0);
2461         if (rc) {
2462                 if (rc == -EAGAIN && rdata->credits) {
2463                         /* credits was reset by reconnect */
2464                         rdata->credits = 0;
2465                         /* reduce in_flight value since we won't send the req */
2466                         spin_lock(&server->req_lock);
2467                         server->in_flight--;
2468                         spin_unlock(&server->req_lock);
2469                 }
2470                 return rc;
2471         }
2472
2473         if (encryption_required(io_parms.tcon))
2474                 flags |= CIFS_TRANSFORM_REQ;
2475
2476         req_len = cpu_to_be32(total_len);
2477
2478         rdata->iov[0].iov_base = &req_len;
2479         rdata->iov[0].iov_len = sizeof(__be32);
2480         rdata->iov[1].iov_base = buf;
2481         rdata->iov[1].iov_len = total_len;
2482
2483         shdr = (struct smb2_sync_hdr *)buf;
2484
2485         if (rdata->credits) {
2486                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
2487                                                 SMB2_MAX_BUFFER_SIZE));
2488                 shdr->CreditRequest = shdr->CreditCharge;
2489                 spin_lock(&server->req_lock);
2490                 server->credits += rdata->credits -
2491                                                 le16_to_cpu(shdr->CreditCharge);
2492                 spin_unlock(&server->req_lock);
2493                 wake_up(&server->request_q);
2494                 flags |= CIFS_HAS_CREDITS;
2495         }
2496
2497         kref_get(&rdata->refcount);
2498         rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
2499                              cifs_readv_receive, smb2_readv_callback,
2500                              smb3_handle_read_data, rdata, flags);
2501         if (rc) {
2502                 kref_put(&rdata->refcount, cifs_readdata_release);
2503                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
2504         }
2505
2506         cifs_small_buf_release(buf);
2507         return rc;
2508 }
2509
2510 int
2511 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
2512           unsigned int *nbytes, char **buf, int *buf_type)
2513 {
2514         int resp_buftype, rc = -EACCES;
2515         struct smb2_read_plain_req *req = NULL;
2516         struct smb2_read_rsp *rsp = NULL;
2517         struct smb2_sync_hdr *shdr;
2518         struct kvec iov[2];
2519         struct kvec rsp_iov;
2520         unsigned int total_len;
2521         __be32 req_len;
2522         struct smb_rqst rqst = { .rq_iov = iov,
2523                                  .rq_nvec = 2 };
2524         int flags = CIFS_LOG_ERROR;
2525         struct cifs_ses *ses = io_parms->tcon->ses;
2526
2527         *nbytes = 0;
2528         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, 0, 0);
2529         if (rc)
2530                 return rc;
2531
2532         if (encryption_required(io_parms->tcon))
2533                 flags |= CIFS_TRANSFORM_REQ;
2534
2535         req_len = cpu_to_be32(total_len);
2536
2537         iov[0].iov_base = &req_len;
2538         iov[0].iov_len = sizeof(__be32);
2539         iov[1].iov_base = req;
2540         iov[1].iov_len = total_len;
2541
2542         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2543         cifs_small_buf_release(req);
2544
2545         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
2546         shdr = get_sync_hdr(rsp);
2547
2548         if (shdr->Status == STATUS_END_OF_FILE) {
2549                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2550                 return 0;
2551         }
2552
2553         if (rc) {
2554                 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
2555                 cifs_dbg(VFS, "Send error in read = %d\n", rc);
2556         } else {
2557                 *nbytes = le32_to_cpu(rsp->DataLength);
2558                 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
2559                     (*nbytes > io_parms->length)) {
2560                         cifs_dbg(FYI, "bad length %d for count %d\n",
2561                                  *nbytes, io_parms->length);
2562                         rc = -EIO;
2563                         *nbytes = 0;
2564                 }
2565         }
2566
2567         if (*buf) {
2568                 memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes);
2569                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2570         } else if (resp_buftype != CIFS_NO_BUFFER) {
2571                 *buf = rsp_iov.iov_base;
2572                 if (resp_buftype == CIFS_SMALL_BUFFER)
2573                         *buf_type = CIFS_SMALL_BUFFER;
2574                 else if (resp_buftype == CIFS_LARGE_BUFFER)
2575                         *buf_type = CIFS_LARGE_BUFFER;
2576         }
2577         return rc;
2578 }
2579
2580 /*
2581  * Check the mid_state and signature on received buffer (if any), and queue the
2582  * workqueue completion task.
2583  */
2584 static void
2585 smb2_writev_callback(struct mid_q_entry *mid)
2586 {
2587         struct cifs_writedata *wdata = mid->callback_data;
2588         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2589         struct TCP_Server_Info *server = tcon->ses->server;
2590         unsigned int written;
2591         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
2592         unsigned int credits_received = 1;
2593
2594         switch (mid->mid_state) {
2595         case MID_RESPONSE_RECEIVED:
2596                 credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2597                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
2598                 if (wdata->result != 0)
2599                         break;
2600
2601                 written = le32_to_cpu(rsp->DataLength);
2602                 /*
2603                  * Mask off high 16 bits when bytes written as returned
2604                  * by the server is greater than bytes requested by the
2605                  * client. OS/2 servers are known to set incorrect
2606                  * CountHigh values.
2607                  */
2608                 if (written > wdata->bytes)
2609                         written &= 0xFFFF;
2610
2611                 if (written < wdata->bytes)
2612                         wdata->result = -ENOSPC;
2613                 else
2614                         wdata->bytes = written;
2615                 break;
2616         case MID_REQUEST_SUBMITTED:
2617         case MID_RETRY_NEEDED:
2618                 wdata->result = -EAGAIN;
2619                 break;
2620         default:
2621                 wdata->result = -EIO;
2622                 break;
2623         }
2624
2625         if (wdata->result)
2626                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2627
2628         queue_work(cifsiod_wq, &wdata->work);
2629         mutex_lock(&server->srv_mutex);
2630         DeleteMidQEntry(mid);
2631         mutex_unlock(&server->srv_mutex);
2632         add_credits(tcon->ses->server, credits_received, 0);
2633 }
2634
2635 /* smb2_async_writev - send an async write, and set up mid to handle result */
2636 int
2637 smb2_async_writev(struct cifs_writedata *wdata,
2638                   void (*release)(struct kref *kref))
2639 {
2640         int rc = -EACCES, flags = 0;
2641         struct smb2_write_req *req = NULL;
2642         struct smb2_sync_hdr *shdr;
2643         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2644         struct TCP_Server_Info *server = tcon->ses->server;
2645         struct kvec iov[2];
2646         struct smb_rqst rqst = { };
2647
2648         rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
2649         if (rc) {
2650                 if (rc == -EAGAIN && wdata->credits) {
2651                         /* credits was reset by reconnect */
2652                         wdata->credits = 0;
2653                         /* reduce in_flight value since we won't send the req */
2654                         spin_lock(&server->req_lock);
2655                         server->in_flight--;
2656                         spin_unlock(&server->req_lock);
2657                 }
2658                 goto async_writev_out;
2659         }
2660
2661         if (encryption_required(tcon))
2662                 flags |= CIFS_TRANSFORM_REQ;
2663
2664         shdr = get_sync_hdr(req);
2665         shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
2666
2667         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
2668         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
2669         req->WriteChannelInfoOffset = 0;
2670         req->WriteChannelInfoLength = 0;
2671         req->Channel = 0;
2672         req->Offset = cpu_to_le64(wdata->offset);
2673         /* 4 for rfc1002 length field */
2674         req->DataOffset = cpu_to_le16(
2675                                 offsetof(struct smb2_write_req, Buffer) - 4);
2676         req->RemainingBytes = 0;
2677
2678         /* 4 for rfc1002 length field and 1 for Buffer */
2679         iov[0].iov_len = 4;
2680         iov[0].iov_base = req;
2681         iov[1].iov_len = get_rfc1002_length(req) - 1;
2682         iov[1].iov_base = (char *)req + 4;
2683
2684         rqst.rq_iov = iov;
2685         rqst.rq_nvec = 2;
2686         rqst.rq_pages = wdata->pages;
2687         rqst.rq_npages = wdata->nr_pages;
2688         rqst.rq_pagesz = wdata->pagesz;
2689         rqst.rq_tailsz = wdata->tailsz;
2690
2691         cifs_dbg(FYI, "async write at %llu %u bytes\n",
2692                  wdata->offset, wdata->bytes);
2693
2694         req->Length = cpu_to_le32(wdata->bytes);
2695
2696         inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
2697
2698         if (wdata->credits) {
2699                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
2700                                                     SMB2_MAX_BUFFER_SIZE));
2701                 shdr->CreditRequest = shdr->CreditCharge;
2702                 spin_lock(&server->req_lock);
2703                 server->credits += wdata->credits -
2704                                                 le16_to_cpu(shdr->CreditCharge);
2705                 spin_unlock(&server->req_lock);
2706                 wake_up(&server->request_q);
2707                 flags |= CIFS_HAS_CREDITS;
2708         }
2709
2710         kref_get(&wdata->refcount);
2711         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
2712                              wdata, flags);
2713
2714         if (rc) {
2715                 kref_put(&wdata->refcount, release);
2716                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2717         }
2718
2719 async_writev_out:
2720         cifs_small_buf_release(req);
2721         return rc;
2722 }
2723
2724 /*
2725  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
2726  * The length field from io_parms must be at least 1 and indicates a number of
2727  * elements with data to write that begins with position 1 in iov array. All
2728  * data length is specified by count.
2729  */
2730 int
2731 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
2732            unsigned int *nbytes, struct kvec *iov, int n_vec)
2733 {
2734         int rc = 0;
2735         struct smb2_write_req *req = NULL;
2736         struct smb2_write_rsp *rsp = NULL;
2737         int resp_buftype;
2738         struct kvec rsp_iov;
2739         int flags = 0;
2740
2741         *nbytes = 0;
2742
2743         if (n_vec < 1)
2744                 return rc;
2745
2746         rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
2747         if (rc)
2748                 return rc;
2749
2750         if (io_parms->tcon->ses->server == NULL)
2751                 return -ECONNABORTED;
2752
2753         if (encryption_required(io_parms->tcon))
2754                 flags |= CIFS_TRANSFORM_REQ;
2755
2756         req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
2757
2758         req->PersistentFileId = io_parms->persistent_fid;
2759         req->VolatileFileId = io_parms->volatile_fid;
2760         req->WriteChannelInfoOffset = 0;
2761         req->WriteChannelInfoLength = 0;
2762         req->Channel = 0;
2763         req->Length = cpu_to_le32(io_parms->length);
2764         req->Offset = cpu_to_le64(io_parms->offset);
2765         /* 4 for rfc1002 length field */
2766         req->DataOffset = cpu_to_le16(
2767                                 offsetof(struct smb2_write_req, Buffer) - 4);
2768         req->RemainingBytes = 0;
2769
2770         iov[0].iov_base = (char *)req;
2771         /* 4 for rfc1002 length field and 1 for Buffer */
2772         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2773
2774         /* length of entire message including data to be written */
2775         inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
2776
2777         rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
2778                           &resp_buftype, flags, &rsp_iov);
2779         cifs_small_buf_release(req);
2780         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
2781
2782         if (rc) {
2783                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
2784                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
2785         } else
2786                 *nbytes = le32_to_cpu(rsp->DataLength);
2787
2788         free_rsp_buf(resp_buftype, rsp);
2789         return rc;
2790 }
2791
2792 static unsigned int
2793 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
2794 {
2795         int len;
2796         unsigned int entrycount = 0;
2797         unsigned int next_offset = 0;
2798         FILE_DIRECTORY_INFO *entryptr;
2799
2800         if (bufstart == NULL)
2801                 return 0;
2802
2803         entryptr = (FILE_DIRECTORY_INFO *)bufstart;
2804
2805         while (1) {
2806                 entryptr = (FILE_DIRECTORY_INFO *)
2807                                         ((char *)entryptr + next_offset);
2808
2809                 if ((char *)entryptr + size > end_of_buf) {
2810                         cifs_dbg(VFS, "malformed search entry would overflow\n");
2811                         break;
2812                 }
2813
2814                 len = le32_to_cpu(entryptr->FileNameLength);
2815                 if ((char *)entryptr + len + size > end_of_buf) {
2816                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
2817                                  end_of_buf);
2818                         break;
2819                 }
2820
2821                 *lastentry = (char *)entryptr;
2822                 entrycount++;
2823
2824                 next_offset = le32_to_cpu(entryptr->NextEntryOffset);
2825                 if (!next_offset)
2826                         break;
2827         }
2828
2829         return entrycount;
2830 }
2831
2832 /*
2833  * Readdir/FindFirst
2834  */
2835 int
2836 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
2837                      u64 persistent_fid, u64 volatile_fid, int index,
2838                      struct cifs_search_info *srch_inf)
2839 {
2840         struct smb2_query_directory_req *req;
2841         struct smb2_query_directory_rsp *rsp = NULL;
2842         struct kvec iov[2];
2843         struct kvec rsp_iov;
2844         int rc = 0;
2845         int len;
2846         int resp_buftype = CIFS_NO_BUFFER;
2847         unsigned char *bufptr;
2848         struct TCP_Server_Info *server;
2849         struct cifs_ses *ses = tcon->ses;
2850         __le16 asteriks = cpu_to_le16('*');
2851         char *end_of_smb;
2852         unsigned int output_size = CIFSMaxBufSize;
2853         size_t info_buf_size;
2854         int flags = 0;
2855
2856         if (ses && (ses->server))
2857                 server = ses->server;
2858         else
2859                 return -EIO;
2860
2861         rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
2862         if (rc)
2863                 return rc;
2864
2865         if (encryption_required(tcon))
2866                 flags |= CIFS_TRANSFORM_REQ;
2867
2868         switch (srch_inf->info_level) {
2869         case SMB_FIND_FILE_DIRECTORY_INFO:
2870                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
2871                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
2872                 break;
2873         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
2874                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
2875                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
2876                 break;
2877         default:
2878                 cifs_dbg(VFS, "info level %u isn't supported\n",
2879                          srch_inf->info_level);
2880                 rc = -EINVAL;
2881                 goto qdir_exit;
2882         }
2883
2884         req->FileIndex = cpu_to_le32(index);
2885         req->PersistentFileId = persistent_fid;
2886         req->VolatileFileId = volatile_fid;
2887
2888         len = 0x2;
2889         bufptr = req->Buffer;
2890         memcpy(bufptr, &asteriks, len);
2891
2892         req->FileNameOffset =
2893                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
2894         req->FileNameLength = cpu_to_le16(len);
2895         /*
2896          * BB could be 30 bytes or so longer if we used SMB2 specific
2897          * buffer lengths, but this is safe and close enough.
2898          */
2899         output_size = min_t(unsigned int, output_size, server->maxBuf);
2900         output_size = min_t(unsigned int, output_size, 2 << 15);
2901         req->OutputBufferLength = cpu_to_le32(output_size);
2902
2903         iov[0].iov_base = (char *)req;
2904         /* 4 for RFC1001 length and 1 for Buffer */
2905         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2906
2907         iov[1].iov_base = (char *)(req->Buffer);
2908         iov[1].iov_len = len;
2909
2910         inc_rfc1001_len(req, len - 1 /* Buffer */);
2911
2912         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
2913         cifs_small_buf_release(req);
2914         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
2915
2916         if (rc) {
2917                 if (rc == -ENODATA &&
2918                     rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) {
2919                         srch_inf->endOfSearch = true;
2920                         rc = 0;
2921                 }
2922                 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
2923                 goto qdir_exit;
2924         }
2925
2926         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2927                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2928                           info_buf_size);
2929         if (rc)
2930                 goto qdir_exit;
2931
2932         srch_inf->unicode = true;
2933
2934         if (srch_inf->ntwrk_buf_start) {
2935                 if (srch_inf->smallBuf)
2936                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
2937                 else
2938                         cifs_buf_release(srch_inf->ntwrk_buf_start);
2939         }
2940         srch_inf->ntwrk_buf_start = (char *)rsp;
2941         srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
2942                 (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
2943         /* 4 for rfc1002 length field */
2944         end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
2945         srch_inf->entries_in_buffer =
2946                         num_entries(srch_inf->srch_entries_start, end_of_smb,
2947                                     &srch_inf->last_entry, info_buf_size);
2948         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
2949         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
2950                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
2951                  srch_inf->srch_entries_start, srch_inf->last_entry);
2952         if (resp_buftype == CIFS_LARGE_BUFFER)
2953                 srch_inf->smallBuf = false;
2954         else if (resp_buftype == CIFS_SMALL_BUFFER)
2955                 srch_inf->smallBuf = true;
2956         else
2957                 cifs_dbg(VFS, "illegal search buffer type\n");
2958
2959         return rc;
2960
2961 qdir_exit:
2962         free_rsp_buf(resp_buftype, rsp);
2963         return rc;
2964 }
2965
2966 static int
2967 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2968                u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class,
2969                unsigned int num, void **data, unsigned int *size)
2970 {
2971         struct smb2_set_info_req *req;
2972         struct smb2_set_info_rsp *rsp = NULL;
2973         struct kvec *iov;
2974         struct kvec rsp_iov;
2975         int rc = 0;
2976         int resp_buftype;
2977         unsigned int i;
2978         struct TCP_Server_Info *server;
2979         struct cifs_ses *ses = tcon->ses;
2980         int flags = 0;
2981
2982         if (ses && (ses->server))
2983                 server = ses->server;
2984         else
2985                 return -EIO;
2986
2987         if (!num)
2988                 return -EINVAL;
2989
2990         iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
2991         if (!iov)
2992                 return -ENOMEM;
2993
2994         rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
2995         if (rc) {
2996                 kfree(iov);
2997                 return rc;
2998         }
2999
3000         if (encryption_required(tcon))
3001                 flags |= CIFS_TRANSFORM_REQ;
3002
3003         req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
3004
3005         req->InfoType = SMB2_O_INFO_FILE;
3006         req->FileInfoClass = info_class;
3007         req->PersistentFileId = persistent_fid;
3008         req->VolatileFileId = volatile_fid;
3009
3010         /* 4 for RFC1001 length and 1 for Buffer */
3011         req->BufferOffset =
3012                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
3013         req->BufferLength = cpu_to_le32(*size);
3014
3015         inc_rfc1001_len(req, *size - 1 /* Buffer */);
3016
3017         memcpy(req->Buffer, *data, *size);
3018
3019         iov[0].iov_base = (char *)req;
3020         /* 4 for RFC1001 length */
3021         iov[0].iov_len = get_rfc1002_length(req) + 4;
3022
3023         for (i = 1; i < num; i++) {
3024                 inc_rfc1001_len(req, size[i]);
3025                 le32_add_cpu(&req->BufferLength, size[i]);
3026                 iov[i].iov_base = (char *)data[i];
3027                 iov[i].iov_len = size[i];
3028         }
3029
3030         rc = SendReceive2(xid, ses, iov, num, &resp_buftype, flags, &rsp_iov);
3031         cifs_small_buf_release(req);
3032         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
3033
3034         if (rc != 0)
3035                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
3036
3037         free_rsp_buf(resp_buftype, rsp);
3038         kfree(iov);
3039         return rc;
3040 }
3041
3042 int
3043 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
3044             u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3045 {
3046         struct smb2_file_rename_info info;
3047         void **data;
3048         unsigned int size[2];
3049         int rc;
3050         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3051
3052         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3053         if (!data)
3054                 return -ENOMEM;
3055
3056         info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
3057                               /* 0 = fail if target already exists */
3058         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3059         info.FileNameLength = cpu_to_le32(len);
3060
3061         data[0] = &info;
3062         size[0] = sizeof(struct smb2_file_rename_info);
3063
3064         data[1] = target_file;
3065         size[1] = len + 2 /* null */;
3066
3067         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3068                            current->tgid, FILE_RENAME_INFORMATION, 2, data,
3069                            size);
3070         kfree(data);
3071         return rc;
3072 }
3073
3074 int
3075 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
3076                   u64 persistent_fid, u64 volatile_fid)
3077 {
3078         __u8 delete_pending = 1;
3079         void *data;
3080         unsigned int size;
3081
3082         data = &delete_pending;
3083         size = 1; /* sizeof __u8 */
3084
3085         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3086                         current->tgid, FILE_DISPOSITION_INFORMATION, 1, &data,
3087                         &size);
3088 }
3089
3090 int
3091 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
3092                   u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3093 {
3094         struct smb2_file_link_info info;
3095         void **data;
3096         unsigned int size[2];
3097         int rc;
3098         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3099
3100         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3101         if (!data)
3102                 return -ENOMEM;
3103
3104         info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
3105                               /* 0 = fail if link already exists */
3106         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3107         info.FileNameLength = cpu_to_le32(len);
3108
3109         data[0] = &info;
3110         size[0] = sizeof(struct smb2_file_link_info);
3111
3112         data[1] = target_file;
3113         size[1] = len + 2 /* null */;
3114
3115         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3116                            current->tgid, FILE_LINK_INFORMATION, 2, data, size);
3117         kfree(data);
3118         return rc;
3119 }
3120
3121 int
3122 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3123              u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
3124 {
3125         struct smb2_file_eof_info info;
3126         void *data;
3127         unsigned int size;
3128
3129         info.EndOfFile = *eof;
3130
3131         data = &info;
3132         size = sizeof(struct smb2_file_eof_info);
3133
3134         if (is_falloc)
3135                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3136                         pid, FILE_ALLOCATION_INFORMATION, 1, &data, &size);
3137         else
3138                 return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3139                         pid, FILE_END_OF_FILE_INFORMATION, 1, &data, &size);
3140 }
3141
3142 int
3143 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3144               u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
3145 {
3146         unsigned int size;
3147         size = sizeof(FILE_BASIC_INFO);
3148         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3149                              current->tgid, FILE_BASIC_INFORMATION, 1,
3150                              (void **)&buf, &size);
3151 }
3152
3153 int
3154 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
3155                   const u64 persistent_fid, const u64 volatile_fid,
3156                   __u8 oplock_level)
3157 {
3158         int rc;
3159         struct smb2_oplock_break *req = NULL;
3160         int flags = CIFS_OBREAK_OP;
3161
3162         cifs_dbg(FYI, "SMB2_oplock_break\n");
3163         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
3164         if (rc)
3165                 return rc;
3166
3167         if (encryption_required(tcon))
3168                 flags |= CIFS_TRANSFORM_REQ;
3169
3170         req->VolatileFid = volatile_fid;
3171         req->PersistentFid = persistent_fid;
3172         req->OplockLevel = oplock_level;
3173         req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
3174
3175         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
3176         cifs_small_buf_release(req);
3177
3178         if (rc) {
3179                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3180                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
3181         }
3182
3183         return rc;
3184 }
3185
3186 static void
3187 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
3188                         struct kstatfs *kst)
3189 {
3190         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
3191                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
3192         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
3193         kst->f_bfree  = le64_to_cpu(pfs_inf->ActualAvailableAllocationUnits);
3194         kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
3195         return;
3196 }
3197
3198 static int
3199 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
3200                    int outbuf_len, u64 persistent_fid, u64 volatile_fid)
3201 {
3202         int rc;
3203         struct smb2_query_info_req *req;
3204
3205         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
3206
3207         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
3208                 return -EIO;
3209
3210         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
3211         if (rc)
3212                 return rc;
3213
3214         req->InfoType = SMB2_O_INFO_FILESYSTEM;
3215         req->FileInfoClass = level;
3216         req->PersistentFileId = persistent_fid;
3217         req->VolatileFileId = volatile_fid;
3218         /* 4 for rfc1002 length field and 1 for pad */
3219         req->InputBufferOffset =
3220                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
3221         req->OutputBufferLength = cpu_to_le32(
3222                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
3223
3224         iov->iov_base = (char *)req;
3225         /* 4 for rfc1002 length field */
3226         iov->iov_len = get_rfc1002_length(req) + 4;
3227         return 0;
3228 }
3229
3230 int
3231 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
3232               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
3233 {
3234         struct smb2_query_info_rsp *rsp = NULL;
3235         struct kvec iov;
3236         struct kvec rsp_iov;
3237         int rc = 0;
3238         int resp_buftype;
3239         struct cifs_ses *ses = tcon->ses;
3240         struct smb2_fs_full_size_info *info = NULL;
3241         int flags = 0;
3242
3243         rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
3244                                 sizeof(struct smb2_fs_full_size_info),
3245                                 persistent_fid, volatile_fid);
3246         if (rc)
3247                 return rc;
3248
3249         if (encryption_required(tcon))
3250                 flags |= CIFS_TRANSFORM_REQ;
3251
3252         rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3253         cifs_small_buf_release(iov.iov_base);
3254         if (rc) {
3255                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3256                 goto qfsinf_exit;
3257         }
3258         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3259
3260         info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
3261                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
3262         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
3263                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
3264                           sizeof(struct smb2_fs_full_size_info));
3265         if (!rc)
3266                 copy_fs_info_to_kstatfs(info, fsdata);
3267
3268 qfsinf_exit:
3269         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3270         return rc;
3271 }
3272
3273 int
3274 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
3275               u64 persistent_fid, u64 volatile_fid, int level)
3276 {
3277         struct smb2_query_info_rsp *rsp = NULL;
3278         struct kvec iov;
3279         struct kvec rsp_iov;
3280         int rc = 0;
3281         int resp_buftype, max_len, min_len;
3282         struct cifs_ses *ses = tcon->ses;
3283         unsigned int rsp_len, offset;
3284         int flags = 0;
3285
3286         if (level == FS_DEVICE_INFORMATION) {
3287                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3288                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3289         } else if (level == FS_ATTRIBUTE_INFORMATION) {
3290                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
3291                 min_len = MIN_FS_ATTR_INFO_SIZE;
3292         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
3293                 max_len = sizeof(struct smb3_fs_ss_info);
3294                 min_len = sizeof(struct smb3_fs_ss_info);
3295         } else {
3296                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
3297                 return -EINVAL;
3298         }
3299
3300         rc = build_qfs_info_req(&iov, tcon, level, max_len,
3301                                 persistent_fid, volatile_fid);
3302         if (rc)
3303                 return rc;
3304
3305         if (encryption_required(tcon))
3306                 flags |= CIFS_TRANSFORM_REQ;
3307
3308         rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3309         cifs_small_buf_release(iov.iov_base);
3310         if (rc) {
3311                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3312                 goto qfsattr_exit;
3313         }
3314         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3315
3316         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
3317         offset = le16_to_cpu(rsp->OutputBufferOffset);
3318         rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
3319         if (rc)
3320                 goto qfsattr_exit;
3321
3322         if (level == FS_ATTRIBUTE_INFORMATION)
3323                 memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
3324                         + (char *)&rsp->hdr, min_t(unsigned int,
3325                         rsp_len, max_len));
3326         else if (level == FS_DEVICE_INFORMATION)
3327                 memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
3328                         + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
3329         else if (level == FS_SECTOR_SIZE_INFORMATION) {
3330                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
3331                         (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
3332                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
3333                 tcon->perf_sector_size =
3334                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
3335         }
3336
3337 qfsattr_exit:
3338         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3339         return rc;
3340 }
3341
3342 int
3343 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
3344            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3345            const __u32 num_lock, struct smb2_lock_element *buf)
3346 {
3347         int rc = 0;
3348         struct smb2_lock_req *req = NULL;
3349         struct kvec iov[2];
3350         struct kvec rsp_iov;
3351         int resp_buf_type;
3352         unsigned int count;
3353         int flags = CIFS_NO_RESP;
3354
3355         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
3356
3357         rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
3358         if (rc)
3359                 return rc;
3360
3361         if (encryption_required(tcon))
3362                 flags |= CIFS_TRANSFORM_REQ;
3363
3364         req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
3365         req->LockCount = cpu_to_le16(num_lock);
3366
3367         req->PersistentFileId = persist_fid;
3368         req->VolatileFileId = volatile_fid;
3369
3370         count = num_lock * sizeof(struct smb2_lock_element);
3371         inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
3372
3373         iov[0].iov_base = (char *)req;
3374         /* 4 for rfc1002 length field and count for all locks */
3375         iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
3376         iov[1].iov_base = (char *)buf;
3377         iov[1].iov_len = count;
3378
3379         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
3380         rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, flags,
3381                           &rsp_iov);
3382         cifs_small_buf_release(req);
3383         if (rc) {
3384                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
3385                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
3386         }
3387
3388         return rc;
3389 }
3390
3391 int
3392 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
3393           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3394           const __u64 length, const __u64 offset, const __u32 lock_flags,
3395           const bool wait)
3396 {
3397         struct smb2_lock_element lock;
3398
3399         lock.Offset = cpu_to_le64(offset);
3400         lock.Length = cpu_to_le64(length);
3401         lock.Flags = cpu_to_le32(lock_flags);
3402         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
3403                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
3404
3405         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
3406 }
3407
3408 int
3409 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
3410                  __u8 *lease_key, const __le32 lease_state)
3411 {
3412         int rc;
3413         struct smb2_lease_ack *req = NULL;
3414         int flags = CIFS_OBREAK_OP;
3415
3416         cifs_dbg(FYI, "SMB2_lease_break\n");
3417         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
3418         if (rc)
3419                 return rc;
3420
3421         if (encryption_required(tcon))
3422                 flags |= CIFS_TRANSFORM_REQ;
3423
3424         req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
3425         req->StructureSize = cpu_to_le16(36);
3426         inc_rfc1001_len(req, 12);
3427
3428         memcpy(req->LeaseKey, lease_key, 16);
3429         req->LeaseState = lease_state;
3430
3431         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
3432         cifs_small_buf_release(req);
3433
3434         if (rc) {
3435                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3436                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
3437         }
3438
3439         return rc;
3440 }