CIFS: Request durable open for SMB2 opens
[profile/ivi/kernel-x86-ivi.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/pagemap.h>
37 #include <linux/xattr.h>
38 #include "smb2pdu.h"
39 #include "cifsglob.h"
40 #include "cifsacl.h"
41 #include "cifsproto.h"
42 #include "smb2proto.h"
43 #include "cifs_unicode.h"
44 #include "cifs_debug.h"
45 #include "ntlmssp.h"
46 #include "smb2status.h"
47 #include "smb2glob.h"
48 #include "cifspdu.h"
49
50 /*
51  *  The following table defines the expected "StructureSize" of SMB2 requests
52  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
53  *
54  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
55  *  indexed by command in host byte order.
56  */
57 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
58         /* SMB2_NEGOTIATE */ 36,
59         /* SMB2_SESSION_SETUP */ 25,
60         /* SMB2_LOGOFF */ 4,
61         /* SMB2_TREE_CONNECT */ 9,
62         /* SMB2_TREE_DISCONNECT */ 4,
63         /* SMB2_CREATE */ 57,
64         /* SMB2_CLOSE */ 24,
65         /* SMB2_FLUSH */ 24,
66         /* SMB2_READ */ 49,
67         /* SMB2_WRITE */ 49,
68         /* SMB2_LOCK */ 48,
69         /* SMB2_IOCTL */ 57,
70         /* SMB2_CANCEL */ 4,
71         /* SMB2_ECHO */ 4,
72         /* SMB2_QUERY_DIRECTORY */ 33,
73         /* SMB2_CHANGE_NOTIFY */ 32,
74         /* SMB2_QUERY_INFO */ 41,
75         /* SMB2_SET_INFO */ 33,
76         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
77 };
78
79
80 static void
81 smb2_hdr_assemble(struct smb2_hdr *hdr, __le16 smb2_cmd /* command */ ,
82                   const struct cifs_tcon *tcon)
83 {
84         struct smb2_pdu *pdu = (struct smb2_pdu *)hdr;
85         char *temp = (char *)hdr;
86         /* lookup word count ie StructureSize from table */
87         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_cmd)];
88
89         /*
90          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
91          * largest operations (Create)
92          */
93         memset(temp, 0, 256);
94
95         /* Note this is only network field converted to big endian */
96         hdr->smb2_buf_length = cpu_to_be32(parmsize + sizeof(struct smb2_hdr)
97                         - 4 /*  RFC 1001 length field itself not counted */);
98
99         hdr->ProtocolId[0] = 0xFE;
100         hdr->ProtocolId[1] = 'S';
101         hdr->ProtocolId[2] = 'M';
102         hdr->ProtocolId[3] = 'B';
103         hdr->StructureSize = cpu_to_le16(64);
104         hdr->Command = smb2_cmd;
105         hdr->CreditRequest = cpu_to_le16(2); /* BB make this dynamic */
106         hdr->ProcessId = cpu_to_le32((__u16)current->tgid);
107
108         if (!tcon)
109                 goto out;
110
111         /* BB FIXME when we do write > 64K add +1 for every 64K in req or rsp */
112         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
113         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
114         if ((tcon->ses) &&
115             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
116                 hdr->CreditCharge = cpu_to_le16(1);
117         /* else CreditCharge MBZ */
118
119         hdr->TreeId = tcon->tid;
120         /* Uid is not converted */
121         if (tcon->ses)
122                 hdr->SessionId = tcon->ses->Suid;
123
124         /*
125          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
126          * to pass the path on the Open SMB prefixed by \\server\share.
127          * Not sure when we would need to do the augmented path (if ever) and
128          * setting this flag breaks the SMB2 open operation since it is
129          * illegal to send an empty path name (without \\server\share prefix)
130          * when the DFS flag is set in the SMB open header. We could
131          * consider setting the flag on all operations other than open
132          * but it is safer to net set it for now.
133          */
134 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
135                 hdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
136
137         if (tcon->ses && tcon->ses->server && tcon->ses->server->sign)
138                 hdr->Flags |= SMB2_FLAGS_SIGNED;
139 out:
140         pdu->StructureSize2 = cpu_to_le16(parmsize);
141         return;
142 }
143
144 static int
145 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
146 {
147         int rc = 0;
148         struct nls_table *nls_codepage;
149         struct cifs_ses *ses;
150         struct TCP_Server_Info *server;
151
152         /*
153          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
154          * check for tcp and smb session status done differently
155          * for those three - in the calling routine.
156          */
157         if (tcon == NULL)
158                 return rc;
159
160         if (smb2_command == SMB2_TREE_CONNECT)
161                 return rc;
162
163         if (tcon->tidStatus == CifsExiting) {
164                 /*
165                  * only tree disconnect, open, and write,
166                  * (and ulogoff which does not have tcon)
167                  * are allowed as we start force umount.
168                  */
169                 if ((smb2_command != SMB2_WRITE) &&
170                    (smb2_command != SMB2_CREATE) &&
171                    (smb2_command != SMB2_TREE_DISCONNECT)) {
172                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
173                                  smb2_command);
174                         return -ENODEV;
175                 }
176         }
177         if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
178             (!tcon->ses->server))
179                 return -EIO;
180
181         ses = tcon->ses;
182         server = ses->server;
183
184         /*
185          * Give demultiplex thread up to 10 seconds to reconnect, should be
186          * greater than cifs socket timeout which is 7 seconds
187          */
188         while (server->tcpStatus == CifsNeedReconnect) {
189                 /*
190                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
191                  * here since they are implicitly done when session drops.
192                  */
193                 switch (smb2_command) {
194                 /*
195                  * BB Should we keep oplock break and add flush to exceptions?
196                  */
197                 case SMB2_TREE_DISCONNECT:
198                 case SMB2_CANCEL:
199                 case SMB2_CLOSE:
200                 case SMB2_OPLOCK_BREAK:
201                         return -EAGAIN;
202                 }
203
204                 wait_event_interruptible_timeout(server->response_q,
205                         (server->tcpStatus != CifsNeedReconnect), 10 * HZ);
206
207                 /* are we still trying to reconnect? */
208                 if (server->tcpStatus != CifsNeedReconnect)
209                         break;
210
211                 /*
212                  * on "soft" mounts we wait once. Hard mounts keep
213                  * retrying until process is killed or server comes
214                  * back on-line
215                  */
216                 if (!tcon->retry) {
217                         cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
218                         return -EHOSTDOWN;
219                 }
220         }
221
222         if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
223                 return rc;
224
225         nls_codepage = load_nls_default();
226
227         /*
228          * need to prevent multiple threads trying to simultaneously reconnect
229          * the same SMB session
230          */
231         mutex_lock(&tcon->ses->session_mutex);
232         rc = cifs_negotiate_protocol(0, tcon->ses);
233         if (!rc && tcon->ses->need_reconnect)
234                 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
235
236         if (rc || !tcon->need_reconnect) {
237                 mutex_unlock(&tcon->ses->session_mutex);
238                 goto out;
239         }
240
241         cifs_mark_open_files_invalid(tcon);
242         rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
243         mutex_unlock(&tcon->ses->session_mutex);
244         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
245         if (rc)
246                 goto out;
247         atomic_inc(&tconInfoReconnectCount);
248         /*
249          * BB FIXME add code to check if wsize needs update due to negotiated
250          * smb buffer size shrinking.
251          */
252 out:
253         /*
254          * Check if handle based operation so we know whether we can continue
255          * or not without returning to caller to reset file handle.
256          */
257         /*
258          * BB Is flush done by server on drop of tcp session? Should we special
259          * case it and skip above?
260          */
261         switch (smb2_command) {
262         case SMB2_FLUSH:
263         case SMB2_READ:
264         case SMB2_WRITE:
265         case SMB2_LOCK:
266         case SMB2_IOCTL:
267         case SMB2_QUERY_DIRECTORY:
268         case SMB2_CHANGE_NOTIFY:
269         case SMB2_QUERY_INFO:
270         case SMB2_SET_INFO:
271                 return -EAGAIN;
272         }
273         unload_nls(nls_codepage);
274         return rc;
275 }
276
277 /*
278  * Allocate and return pointer to an SMB request hdr, and set basic
279  * SMB information in the SMB header. If the return code is zero, this
280  * function must have filled in request_buf pointer.
281  */
282 static int
283 small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
284                 void **request_buf)
285 {
286         int rc = 0;
287
288         rc = smb2_reconnect(smb2_command, tcon);
289         if (rc)
290                 return rc;
291
292         /* BB eventually switch this to SMB2 specific small buf size */
293         *request_buf = cifs_small_buf_get();
294         if (*request_buf == NULL) {
295                 /* BB should we add a retry in here if not a writepage? */
296                 return -ENOMEM;
297         }
298
299         smb2_hdr_assemble((struct smb2_hdr *) *request_buf, smb2_command, tcon);
300
301         if (tcon != NULL) {
302 #ifdef CONFIG_CIFS_STATS2
303                 uint16_t com_code = le16_to_cpu(smb2_command);
304                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
305 #endif
306                 cifs_stats_inc(&tcon->num_smbs_sent);
307         }
308
309         return rc;
310 }
311
312 static void
313 free_rsp_buf(int resp_buftype, void *rsp)
314 {
315         if (resp_buftype == CIFS_SMALL_BUFFER)
316                 cifs_small_buf_release(rsp);
317         else if (resp_buftype == CIFS_LARGE_BUFFER)
318                 cifs_buf_release(rsp);
319 }
320
321
322 /*
323  *
324  *      SMB2 Worker functions follow:
325  *
326  *      The general structure of the worker functions is:
327  *      1) Call smb2_init (assembles SMB2 header)
328  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
329  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
330  *      4) Decode SMB2 command specific fields in the fixed length area
331  *      5) Decode variable length data area (if any for this SMB2 command type)
332  *      6) Call free smb buffer
333  *      7) return
334  *
335  */
336
337 int
338 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
339 {
340         struct smb2_negotiate_req *req;
341         struct smb2_negotiate_rsp *rsp;
342         struct kvec iov[1];
343         int rc = 0;
344         int resp_buftype;
345         struct TCP_Server_Info *server = ses->server;
346         int blob_offset, blob_length;
347         char *security_blob;
348         int flags = CIFS_NEG_OP;
349
350         cifs_dbg(FYI, "Negotiate protocol\n");
351
352         if (!server) {
353                 WARN(1, "%s: server is NULL!\n", __func__);
354                 return -EIO;
355         }
356
357         rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
358         if (rc)
359                 return rc;
360
361         req->hdr.SessionId = 0;
362
363         req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
364
365         req->DialectCount = cpu_to_le16(1); /* One vers= at a time for now */
366         inc_rfc1001_len(req, 2);
367
368         /* only one of SMB2 signing flags may be set in SMB2 request */
369         if (ses->sign)
370                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
371         else if (global_secflags & CIFSSEC_MAY_SIGN)
372                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
373         else
374                 req->SecurityMode = 0;
375
376         req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
377
378         memcpy(req->ClientGUID, cifs_client_guid, SMB2_CLIENT_GUID_SIZE);
379
380         iov[0].iov_base = (char *)req;
381         /* 4 for rfc1002 length field */
382         iov[0].iov_len = get_rfc1002_length(req) + 4;
383
384         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags);
385
386         rsp = (struct smb2_negotiate_rsp *)iov[0].iov_base;
387         /*
388          * No tcon so can't do
389          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
390          */
391         if (rc != 0)
392                 goto neg_exit;
393
394         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
395
396         /* BB we may eventually want to match the negotiated vs. requested
397            dialect, even though we are only requesting one at a time */
398         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
399                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
400         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
401                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
402         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
403                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
404         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
405                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
406         else {
407                 cifs_dbg(VFS, "Illegal dialect returned by server %d\n",
408                          le16_to_cpu(rsp->DialectRevision));
409                 rc = -EIO;
410                 goto neg_exit;
411         }
412         server->dialect = le16_to_cpu(rsp->DialectRevision);
413
414         /* SMB2 only has an extended negflavor */
415         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
416         server->maxBuf = le32_to_cpu(rsp->MaxTransactSize);
417         server->max_read = le32_to_cpu(rsp->MaxReadSize);
418         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
419         /* BB Do we need to validate the SecurityMode? */
420         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
421         server->capabilities = le32_to_cpu(rsp->Capabilities);
422         /* Internal types */
423         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
424
425         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
426                                                &rsp->hdr);
427         /*
428          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
429          * for us will be
430          *      ses->sectype = RawNTLMSSP;
431          * but for time being this is our only auth choice so doesn't matter.
432          * We just found a server which sets blob length to zero expecting raw.
433          */
434         if (blob_length == 0)
435                 cifs_dbg(FYI, "missing security blob on negprot\n");
436
437         rc = cifs_enable_signing(server, ses->sign);
438 #ifdef CONFIG_SMB2_ASN1  /* BB REMOVEME when updated asn1.c ready */
439         if (rc)
440                 goto neg_exit;
441         if (blob_length)
442                 rc = decode_neg_token_init(security_blob, blob_length,
443                                    &server->sec_type);
444         if (rc == 1)
445                 rc = 0;
446         else if (rc == 0) {
447                 rc = -EIO;
448                 goto neg_exit;
449         }
450 #endif
451
452 neg_exit:
453         free_rsp_buf(resp_buftype, rsp);
454         return rc;
455 }
456
457 int
458 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
459                 const struct nls_table *nls_cp)
460 {
461         struct smb2_sess_setup_req *req;
462         struct smb2_sess_setup_rsp *rsp = NULL;
463         struct kvec iov[2];
464         int rc = 0;
465         int resp_buftype;
466         __le32 phase = NtLmNegotiate; /* NTLMSSP, if needed, is multistage */
467         struct TCP_Server_Info *server = ses->server;
468         u16 blob_length = 0;
469         char *security_blob;
470         char *ntlmssp_blob = NULL;
471         bool use_spnego = false; /* else use raw ntlmssp */
472
473         cifs_dbg(FYI, "Session Setup\n");
474
475         if (!server) {
476                 WARN(1, "%s: server is NULL!\n", __func__);
477                 return -EIO;
478         }
479
480         /*
481          * If memory allocation is successful, caller of this function
482          * frees it.
483          */
484         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
485         if (!ses->ntlmssp)
486                 return -ENOMEM;
487
488         /* FIXME: allow for other auth types besides NTLMSSP (e.g. krb5) */
489         ses->sectype = RawNTLMSSP;
490
491 ssetup_ntlmssp_authenticate:
492         if (phase == NtLmChallenge)
493                 phase = NtLmAuthenticate; /* if ntlmssp, now final phase */
494
495         rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
496         if (rc)
497                 return rc;
498
499         req->hdr.SessionId = 0; /* First session, not a reauthenticate */
500         req->VcNumber = 0; /* MBZ */
501         /* to enable echos and oplocks */
502         req->hdr.CreditRequest = cpu_to_le16(3);
503
504         /* only one of SMB2 signing flags may be set in SMB2 request */
505         if (server->sign)
506                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
507         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
508                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
509         else
510                 req->SecurityMode = 0;
511
512         req->Capabilities = 0;
513         req->Channel = 0; /* MBZ */
514
515         iov[0].iov_base = (char *)req;
516         /* 4 for rfc1002 length field and 1 for pad */
517         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
518         if (phase == NtLmNegotiate) {
519                 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
520                                        GFP_KERNEL);
521                 if (ntlmssp_blob == NULL) {
522                         rc = -ENOMEM;
523                         goto ssetup_exit;
524                 }
525                 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
526                 if (use_spnego) {
527                         /* blob_length = build_spnego_ntlmssp_blob(
528                                         &security_blob,
529                                         sizeof(struct _NEGOTIATE_MESSAGE),
530                                         ntlmssp_blob); */
531                         /* BB eventually need to add this */
532                         cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
533                         rc = -EOPNOTSUPP;
534                         kfree(ntlmssp_blob);
535                         goto ssetup_exit;
536                 } else {
537                         blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
538                         /* with raw NTLMSSP we don't encapsulate in SPNEGO */
539                         security_blob = ntlmssp_blob;
540                 }
541         } else if (phase == NtLmAuthenticate) {
542                 req->hdr.SessionId = ses->Suid;
543                 ntlmssp_blob = kzalloc(sizeof(struct _NEGOTIATE_MESSAGE) + 500,
544                                        GFP_KERNEL);
545                 if (ntlmssp_blob == NULL) {
546                         rc = -ENOMEM;
547                         goto ssetup_exit;
548                 }
549                 rc = build_ntlmssp_auth_blob(ntlmssp_blob, &blob_length, ses,
550                                              nls_cp);
551                 if (rc) {
552                         cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n",
553                                  rc);
554                         goto ssetup_exit; /* BB double check error handling */
555                 }
556                 if (use_spnego) {
557                         /* blob_length = build_spnego_ntlmssp_blob(
558                                                         &security_blob,
559                                                         blob_length,
560                                                         ntlmssp_blob); */
561                         cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
562                         rc = -EOPNOTSUPP;
563                         kfree(ntlmssp_blob);
564                         goto ssetup_exit;
565                 } else {
566                         security_blob = ntlmssp_blob;
567                 }
568         } else {
569                 cifs_dbg(VFS, "illegal ntlmssp phase\n");
570                 rc = -EIO;
571                 goto ssetup_exit;
572         }
573
574         /* Testing shows that buffer offset must be at location of Buffer[0] */
575         req->SecurityBufferOffset =
576                                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
577                                             1 /* pad */ - 4 /* rfc1001 len */);
578         req->SecurityBufferLength = cpu_to_le16(blob_length);
579         iov[1].iov_base = security_blob;
580         iov[1].iov_len = blob_length;
581
582         inc_rfc1001_len(req, blob_length - 1 /* pad */);
583
584         /* BB add code to build os and lm fields */
585
586         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype,
587                           CIFS_LOG_ERROR | CIFS_NEG_OP);
588
589         kfree(security_blob);
590         rsp = (struct smb2_sess_setup_rsp *)iov[0].iov_base;
591         if (resp_buftype != CIFS_NO_BUFFER &&
592             rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) {
593                 if (phase != NtLmNegotiate) {
594                         cifs_dbg(VFS, "Unexpected more processing error\n");
595                         goto ssetup_exit;
596                 }
597                 if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
598                                 le16_to_cpu(rsp->SecurityBufferOffset)) {
599                         cifs_dbg(VFS, "Invalid security buffer offset %d\n",
600                                  le16_to_cpu(rsp->SecurityBufferOffset));
601                         rc = -EIO;
602                         goto ssetup_exit;
603                 }
604
605                 /* NTLMSSP Negotiate sent now processing challenge (response) */
606                 phase = NtLmChallenge; /* process ntlmssp challenge */
607                 rc = 0; /* MORE_PROCESSING is not an error here but expected */
608                 ses->Suid = rsp->hdr.SessionId;
609                 rc = decode_ntlmssp_challenge(rsp->Buffer,
610                                 le16_to_cpu(rsp->SecurityBufferLength), ses);
611         }
612
613         /*
614          * BB eventually add code for SPNEGO decoding of NtlmChallenge blob,
615          * but at least the raw NTLMSSP case works.
616          */
617         /*
618          * No tcon so can't do
619          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
620          */
621         if (rc != 0)
622                 goto ssetup_exit;
623
624         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
625 ssetup_exit:
626         free_rsp_buf(resp_buftype, rsp);
627
628         /* if ntlmssp, and negotiate succeeded, proceed to authenticate phase */
629         if ((phase == NtLmChallenge) && (rc == 0))
630                 goto ssetup_ntlmssp_authenticate;
631         return rc;
632 }
633
634 int
635 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
636 {
637         struct smb2_logoff_req *req; /* response is also trivial struct */
638         int rc = 0;
639         struct TCP_Server_Info *server;
640
641         cifs_dbg(FYI, "disconnect session %p\n", ses);
642
643         if (ses && (ses->server))
644                 server = ses->server;
645         else
646                 return -EIO;
647
648         rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
649         if (rc)
650                 return rc;
651
652          /* since no tcon, smb2_init can not do this, so do here */
653         req->hdr.SessionId = ses->Suid;
654         if (server->sign)
655                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
656
657         rc = SendReceiveNoRsp(xid, ses, (char *) &req->hdr, 0);
658         /*
659          * No tcon so can't do
660          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
661          */
662         return rc;
663 }
664
665 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
666 {
667         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
668 }
669
670 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
671
672 int
673 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
674           struct cifs_tcon *tcon, const struct nls_table *cp)
675 {
676         struct smb2_tree_connect_req *req;
677         struct smb2_tree_connect_rsp *rsp = NULL;
678         struct kvec iov[2];
679         int rc = 0;
680         int resp_buftype;
681         int unc_path_len;
682         struct TCP_Server_Info *server;
683         __le16 *unc_path = NULL;
684
685         cifs_dbg(FYI, "TCON\n");
686
687         if ((ses->server) && tree)
688                 server = ses->server;
689         else
690                 return -EIO;
691
692         if (tcon && tcon->bad_network_name)
693                 return -ENOENT;
694
695         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
696         if (unc_path == NULL)
697                 return -ENOMEM;
698
699         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
700         unc_path_len *= 2;
701         if (unc_path_len < 2) {
702                 kfree(unc_path);
703                 return -EINVAL;
704         }
705
706         rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
707         if (rc) {
708                 kfree(unc_path);
709                 return rc;
710         }
711
712         if (tcon == NULL) {
713                 /* since no tcon, smb2_init can not do this, so do here */
714                 req->hdr.SessionId = ses->Suid;
715                 /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
716                         req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
717         }
718
719         iov[0].iov_base = (char *)req;
720         /* 4 for rfc1002 length field and 1 for pad */
721         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
722
723         /* Testing shows that buffer offset must be at location of Buffer[0] */
724         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
725                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
726         req->PathLength = cpu_to_le16(unc_path_len - 2);
727         iov[1].iov_base = unc_path;
728         iov[1].iov_len = unc_path_len;
729
730         inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
731
732         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
733         rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
734
735         if (rc != 0) {
736                 if (tcon) {
737                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
738                         tcon->need_reconnect = true;
739                 }
740                 goto tcon_error_exit;
741         }
742
743         if (tcon == NULL) {
744                 ses->ipc_tid = rsp->hdr.TreeId;
745                 goto tcon_exit;
746         }
747
748         if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
749                 cifs_dbg(FYI, "connection to disk share\n");
750         else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
751                 tcon->ipc = true;
752                 cifs_dbg(FYI, "connection to pipe share\n");
753         } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
754                 tcon->print = true;
755                 cifs_dbg(FYI, "connection to printer\n");
756         } else {
757                 cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
758                 rc = -EOPNOTSUPP;
759                 goto tcon_error_exit;
760         }
761
762         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
763         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
764         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
765         tcon->tidStatus = CifsGood;
766         tcon->need_reconnect = false;
767         tcon->tid = rsp->hdr.TreeId;
768         strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
769
770         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
771             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
772                 cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
773
774 tcon_exit:
775         free_rsp_buf(resp_buftype, rsp);
776         kfree(unc_path);
777         return rc;
778
779 tcon_error_exit:
780         if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
781                 cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
782                 tcon->bad_network_name = true;
783         }
784         goto tcon_exit;
785 }
786
787 int
788 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
789 {
790         struct smb2_tree_disconnect_req *req; /* response is trivial */
791         int rc = 0;
792         struct TCP_Server_Info *server;
793         struct cifs_ses *ses = tcon->ses;
794
795         cifs_dbg(FYI, "Tree Disconnect\n");
796
797         if (ses && (ses->server))
798                 server = ses->server;
799         else
800                 return -EIO;
801
802         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
803                 return 0;
804
805         rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
806         if (rc)
807                 return rc;
808
809         rc = SendReceiveNoRsp(xid, ses, (char *)&req->hdr, 0);
810         if (rc)
811                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
812
813         return rc;
814 }
815
816 static struct create_lease *
817 create_lease_buf(u8 *lease_key, u8 oplock)
818 {
819         struct create_lease *buf;
820
821         buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
822         if (!buf)
823                 return NULL;
824
825         buf->lcontext.LeaseKeyLow = cpu_to_le64(*((u64 *)lease_key));
826         buf->lcontext.LeaseKeyHigh = cpu_to_le64(*((u64 *)(lease_key + 8)));
827         if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
828                 buf->lcontext.LeaseState = SMB2_LEASE_WRITE_CACHING |
829                                            SMB2_LEASE_READ_CACHING;
830         else if (oplock == SMB2_OPLOCK_LEVEL_II)
831                 buf->lcontext.LeaseState = SMB2_LEASE_READ_CACHING;
832         else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
833                 buf->lcontext.LeaseState = SMB2_LEASE_HANDLE_CACHING |
834                                            SMB2_LEASE_READ_CACHING |
835                                            SMB2_LEASE_WRITE_CACHING;
836
837         buf->ccontext.DataOffset = cpu_to_le16(offsetof
838                                         (struct create_lease, lcontext));
839         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
840         buf->ccontext.NameOffset = cpu_to_le16(offsetof
841                                 (struct create_lease, Name));
842         buf->ccontext.NameLength = cpu_to_le16(4);
843         buf->Name[0] = 'R';
844         buf->Name[1] = 'q';
845         buf->Name[2] = 'L';
846         buf->Name[3] = 's';
847         return buf;
848 }
849
850 static struct create_durable *
851 create_durable_buf(void)
852 {
853         struct create_durable *buf;
854
855         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
856         if (!buf)
857                 return NULL;
858
859         buf->ccontext.DataOffset = cpu_to_le16(offsetof
860                                         (struct create_durable, Reserved));
861         buf->ccontext.DataLength = cpu_to_le32(16);
862         buf->ccontext.NameOffset = cpu_to_le16(offsetof
863                                 (struct create_durable, Name));
864         buf->ccontext.NameLength = cpu_to_le16(4);
865         buf->Name[0] = 'D';
866         buf->Name[1] = 'H';
867         buf->Name[2] = 'n';
868         buf->Name[3] = 'Q';
869         return buf;
870 }
871
872 static __u8
873 parse_lease_state(struct smb2_create_rsp *rsp)
874 {
875         char *data_offset;
876         struct create_lease *lc;
877         bool found = false;
878         unsigned int next = 0;
879         char *name;
880
881         data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
882         lc = (struct create_lease *)data_offset;
883         do {
884                 lc = (struct create_lease *)((char *)lc + next);
885                 name = le16_to_cpu(lc->ccontext.NameOffset) + (char *)lc;
886                 if (le16_to_cpu(lc->ccontext.NameLength) != 4 ||
887                     strncmp(name, "RqLs", 4)) {
888                         next = le32_to_cpu(lc->ccontext.Next);
889                         continue;
890                 }
891                 if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
892                         return SMB2_OPLOCK_LEVEL_NOCHANGE;
893                 found = true;
894                 break;
895         } while (next != 0);
896
897         if (!found)
898                 return 0;
899
900         return smb2_map_lease_to_oplock(lc->lcontext.LeaseState);
901 }
902
903 static int
904 add_lease_context(struct kvec *iov, unsigned int *num_iovec, __u8 *oplock)
905 {
906         struct smb2_create_req *req = iov[0].iov_base;
907         unsigned int num = *num_iovec;
908
909         iov[num].iov_base = create_lease_buf(oplock+1, *oplock);
910         if (iov[num].iov_base == NULL)
911                 return -ENOMEM;
912         iov[num].iov_len = sizeof(struct create_lease);
913         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
914         if (!req->CreateContextsOffset)
915                 req->CreateContextsOffset = cpu_to_le32(
916                                 sizeof(struct smb2_create_req) - 4 +
917                                 iov[num - 1].iov_len);
918         req->CreateContextsLength = cpu_to_le32(
919                                 le32_to_cpu(req->CreateContextsLength) +
920                                 sizeof(struct create_lease));
921         inc_rfc1001_len(&req->hdr, sizeof(struct create_lease));
922         *num_iovec = num + 1;
923         return 0;
924 }
925
926 static int
927 add_durable_context(struct kvec *iov, unsigned int *num_iovec)
928 {
929         struct smb2_create_req *req = iov[0].iov_base;
930         unsigned int num = *num_iovec;
931
932         iov[num].iov_base = create_durable_buf();
933         if (iov[num].iov_base == NULL)
934                 return -ENOMEM;
935         iov[num].iov_len = sizeof(struct create_durable);
936         if (!req->CreateContextsOffset)
937                 req->CreateContextsOffset =
938                         cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
939                                                                 iov[1].iov_len);
940         req->CreateContextsLength =
941                         cpu_to_le32(le32_to_cpu(req->CreateContextsLength) +
942                                                 sizeof(struct create_durable));
943         inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
944         *num_iovec = num + 1;
945         return 0;
946 }
947
948 int
949 SMB2_open(const unsigned int xid, struct cifs_tcon *tcon, __le16 *path,
950           u64 *persistent_fid, u64 *volatile_fid, __u32 desired_access,
951           __u32 create_disposition, __u32 create_options, __u8 *oplock,
952           struct smb2_file_all_info *buf)
953 {
954         struct smb2_create_req *req;
955         struct smb2_create_rsp *rsp;
956         struct TCP_Server_Info *server;
957         struct cifs_ses *ses = tcon->ses;
958         struct kvec iov[4];
959         int resp_buftype;
960         int uni_path_len;
961         __le16 *copy_path = NULL;
962         int copy_size;
963         int rc = 0;
964         unsigned int num_iovecs = 2;
965         __u32 file_attributes = 0;
966
967         cifs_dbg(FYI, "create/open\n");
968
969         if (ses && (ses->server))
970                 server = ses->server;
971         else
972                 return -EIO;
973
974         rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
975         if (rc)
976                 return rc;
977
978         if (create_options & CREATE_OPTION_READONLY)
979                 file_attributes |= ATTR_READONLY;
980
981         req->ImpersonationLevel = IL_IMPERSONATION;
982         req->DesiredAccess = cpu_to_le32(desired_access);
983         /* File attributes ignored on open (used in create though) */
984         req->FileAttributes = cpu_to_le32(file_attributes);
985         req->ShareAccess = FILE_SHARE_ALL_LE;
986         req->CreateDisposition = cpu_to_le32(create_disposition);
987         req->CreateOptions = cpu_to_le32(create_options & CREATE_OPTIONS_MASK);
988         uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
989         /* do not count rfc1001 len field */
990         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
991
992         iov[0].iov_base = (char *)req;
993         /* 4 for rfc1002 length field */
994         iov[0].iov_len = get_rfc1002_length(req) + 4;
995
996         /* MUST set path len (NameLength) to 0 opening root of share */
997         req->NameLength = cpu_to_le16(uni_path_len - 2);
998         /* -1 since last byte is buf[0] which is sent below (path) */
999         iov[0].iov_len--;
1000         if (uni_path_len % 8 != 0) {
1001                 copy_size = uni_path_len / 8 * 8;
1002                 if (copy_size < uni_path_len)
1003                         copy_size += 8;
1004
1005                 copy_path = kzalloc(copy_size, GFP_KERNEL);
1006                 if (!copy_path)
1007                         return -ENOMEM;
1008                 memcpy((char *)copy_path, (const char *)path,
1009                         uni_path_len);
1010                 uni_path_len = copy_size;
1011                 path = copy_path;
1012         }
1013
1014         iov[1].iov_len = uni_path_len;
1015         iov[1].iov_base = path;
1016         /* -1 since last byte is buf[0] which was counted in smb2_buf_len */
1017         inc_rfc1001_len(req, uni_path_len - 1);
1018
1019         if (!server->oplocks)
1020                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
1021
1022         if (!(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1023             *oplock == SMB2_OPLOCK_LEVEL_NONE)
1024                 req->RequestedOplockLevel = *oplock;
1025         else {
1026                 rc = add_lease_context(iov, &num_iovecs, oplock);
1027                 if (rc) {
1028                         cifs_small_buf_release(req);
1029                         kfree(copy_path);
1030                         return rc;
1031                 }
1032         }
1033
1034         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1035                 /* need to set Next field of lease context if we request it */
1036                 if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1037                         struct create_context *ccontext =
1038                             (struct create_context *)iov[num_iovecs-1].iov_base;
1039                         ccontext->Next = sizeof(struct create_lease);
1040                 }
1041                 rc = add_durable_context(iov, &num_iovecs);
1042                 if (rc) {
1043                         cifs_small_buf_release(req);
1044                         kfree(copy_path);
1045                         kfree(iov[num_iovecs-1].iov_base);
1046                         return rc;
1047                 }
1048         }
1049
1050         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1051         rsp = (struct smb2_create_rsp *)iov[0].iov_base;
1052
1053         if (rc != 0) {
1054                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1055                 goto creat_exit;
1056         }
1057
1058         *persistent_fid = rsp->PersistentFileId;
1059         *volatile_fid = rsp->VolatileFileId;
1060
1061         if (buf) {
1062                 memcpy(buf, &rsp->CreationTime, 32);
1063                 buf->AllocationSize = rsp->AllocationSize;
1064                 buf->EndOfFile = rsp->EndofFile;
1065                 buf->Attributes = rsp->FileAttributes;
1066                 buf->NumberOfLinks = cpu_to_le32(1);
1067                 buf->DeletePending = 0;
1068         }
1069
1070         if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1071                 *oplock = parse_lease_state(rsp);
1072         else
1073                 *oplock = rsp->OplockLevel;
1074 creat_exit:
1075         kfree(copy_path);
1076         free_rsp_buf(resp_buftype, rsp);
1077         return rc;
1078 }
1079
1080 /*
1081  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
1082  */
1083 int
1084 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1085            u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data,
1086            u32 indatalen, char **out_data, u32 *plen /* returned data len */)
1087 {
1088         struct smb2_ioctl_req *req;
1089         struct smb2_ioctl_rsp *rsp;
1090         struct TCP_Server_Info *server;
1091         struct cifs_ses *ses = tcon->ses;
1092         struct kvec iov[2];
1093         int resp_buftype;
1094         int num_iovecs;
1095         int rc = 0;
1096
1097         cifs_dbg(FYI, "SMB2 IOCTL\n");
1098
1099         /* zero out returned data len, in case of error */
1100         if (plen)
1101                 *plen = 0;
1102
1103         if (ses && (ses->server))
1104                 server = ses->server;
1105         else
1106                 return -EIO;
1107
1108         rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
1109         if (rc)
1110                 return rc;
1111
1112         req->CtlCode = cpu_to_le32(opcode);
1113         req->PersistentFileId = persistent_fid;
1114         req->VolatileFileId = volatile_fid;
1115
1116         if (indatalen) {
1117                 req->InputCount = cpu_to_le32(indatalen);
1118                 /* do not set InputOffset if no input data */
1119                 req->InputOffset =
1120                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
1121                 iov[1].iov_base = in_data;
1122                 iov[1].iov_len = indatalen;
1123                 num_iovecs = 2;
1124         } else
1125                 num_iovecs = 1;
1126
1127         req->OutputOffset = 0;
1128         req->OutputCount = 0; /* MBZ */
1129
1130         /*
1131          * Could increase MaxOutputResponse, but that would require more
1132          * than one credit. Windows typically sets this smaller, but for some
1133          * ioctls it may be useful to allow server to send more. No point
1134          * limiting what the server can send as long as fits in one credit
1135          */
1136         req->MaxOutputResponse = cpu_to_le32(0xFF00); /* < 64K uses 1 credit */
1137
1138         if (is_fsctl)
1139                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1140         else
1141                 req->Flags = 0;
1142
1143         iov[0].iov_base = (char *)req;
1144         /* 4 for rfc1002 length field */
1145         iov[0].iov_len = get_rfc1002_length(req) + 4;
1146
1147         if (indatalen)
1148                 inc_rfc1001_len(req, indatalen);
1149
1150         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
1151         rsp = (struct smb2_ioctl_rsp *)iov[0].iov_base;
1152
1153         if (rc != 0) {
1154                 if (tcon)
1155                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
1156                 goto ioctl_exit;
1157         }
1158
1159         /* check if caller wants to look at return data or just return rc */
1160         if ((plen == NULL) || (out_data == NULL))
1161                 goto ioctl_exit;
1162
1163         *plen = le32_to_cpu(rsp->OutputCount);
1164
1165         /* We check for obvious errors in the output buffer length and offset */
1166         if (*plen == 0)
1167                 goto ioctl_exit; /* server returned no data */
1168         else if (*plen > 0xFF00) {
1169                 cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
1170                 *plen = 0;
1171                 rc = -EIO;
1172                 goto ioctl_exit;
1173         }
1174
1175         if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) {
1176                 cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
1177                         le32_to_cpu(rsp->OutputOffset));
1178                 *plen = 0;
1179                 rc = -EIO;
1180                 goto ioctl_exit;
1181         }
1182
1183         *out_data = kmalloc(*plen, GFP_KERNEL);
1184         if (*out_data == NULL) {
1185                 rc = -ENOMEM;
1186                 goto ioctl_exit;
1187         }
1188
1189         memcpy(*out_data, rsp->hdr.ProtocolId + le32_to_cpu(rsp->OutputOffset),
1190                *plen);
1191 ioctl_exit:
1192         free_rsp_buf(resp_buftype, rsp);
1193         return rc;
1194 }
1195
1196 int
1197 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
1198            u64 persistent_fid, u64 volatile_fid)
1199 {
1200         struct smb2_close_req *req;
1201         struct smb2_close_rsp *rsp;
1202         struct TCP_Server_Info *server;
1203         struct cifs_ses *ses = tcon->ses;
1204         struct kvec iov[1];
1205         int resp_buftype;
1206         int rc = 0;
1207
1208         cifs_dbg(FYI, "Close\n");
1209
1210         if (ses && (ses->server))
1211                 server = ses->server;
1212         else
1213                 return -EIO;
1214
1215         rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
1216         if (rc)
1217                 return rc;
1218
1219         req->PersistentFileId = persistent_fid;
1220         req->VolatileFileId = volatile_fid;
1221
1222         iov[0].iov_base = (char *)req;
1223         /* 4 for rfc1002 length field */
1224         iov[0].iov_len = get_rfc1002_length(req) + 4;
1225
1226         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1227         rsp = (struct smb2_close_rsp *)iov[0].iov_base;
1228
1229         if (rc != 0) {
1230                 if (tcon)
1231                         cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
1232                 goto close_exit;
1233         }
1234
1235         /* BB FIXME - decode close response, update inode for caching */
1236
1237 close_exit:
1238         free_rsp_buf(resp_buftype, rsp);
1239         return rc;
1240 }
1241
1242 static int
1243 validate_buf(unsigned int offset, unsigned int buffer_length,
1244              struct smb2_hdr *hdr, unsigned int min_buf_size)
1245
1246 {
1247         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
1248         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
1249         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1250         char *end_of_buf = begin_of_buf + buffer_length;
1251
1252
1253         if (buffer_length < min_buf_size) {
1254                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
1255                          buffer_length, min_buf_size);
1256                 return -EINVAL;
1257         }
1258
1259         /* check if beyond RFC1001 maximum length */
1260         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
1261                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
1262                          buffer_length, smb_len);
1263                 return -EINVAL;
1264         }
1265
1266         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
1267                 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
1268                 return -EINVAL;
1269         }
1270
1271         return 0;
1272 }
1273
1274 /*
1275  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
1276  * Caller must free buffer.
1277  */
1278 static int
1279 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
1280                       struct smb2_hdr *hdr, unsigned int minbufsize,
1281                       char *data)
1282
1283 {
1284         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1285         int rc;
1286
1287         if (!data)
1288                 return -EINVAL;
1289
1290         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
1291         if (rc)
1292                 return rc;
1293
1294         memcpy(data, begin_of_buf, buffer_length);
1295
1296         return 0;
1297 }
1298
1299 static int
1300 query_info(const unsigned int xid, struct cifs_tcon *tcon,
1301            u64 persistent_fid, u64 volatile_fid, u8 info_class,
1302            size_t output_len, size_t min_len, void *data)
1303 {
1304         struct smb2_query_info_req *req;
1305         struct smb2_query_info_rsp *rsp = NULL;
1306         struct kvec iov[2];
1307         int rc = 0;
1308         int resp_buftype;
1309         struct TCP_Server_Info *server;
1310         struct cifs_ses *ses = tcon->ses;
1311
1312         cifs_dbg(FYI, "Query Info\n");
1313
1314         if (ses && (ses->server))
1315                 server = ses->server;
1316         else
1317                 return -EIO;
1318
1319         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
1320         if (rc)
1321                 return rc;
1322
1323         req->InfoType = SMB2_O_INFO_FILE;
1324         req->FileInfoClass = info_class;
1325         req->PersistentFileId = persistent_fid;
1326         req->VolatileFileId = volatile_fid;
1327         /* 4 for rfc1002 length field and 1 for Buffer */
1328         req->InputBufferOffset =
1329                 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
1330         req->OutputBufferLength = cpu_to_le32(output_len);
1331
1332         iov[0].iov_base = (char *)req;
1333         /* 4 for rfc1002 length field */
1334         iov[0].iov_len = get_rfc1002_length(req) + 4;
1335
1336         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1337         rsp = (struct smb2_query_info_rsp *)iov[0].iov_base;
1338
1339         if (rc) {
1340                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
1341                 goto qinf_exit;
1342         }
1343
1344         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
1345                                    le32_to_cpu(rsp->OutputBufferLength),
1346                                    &rsp->hdr, min_len, data);
1347
1348 qinf_exit:
1349         free_rsp_buf(resp_buftype, rsp);
1350         return rc;
1351 }
1352
1353 int
1354 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
1355                 u64 persistent_fid, u64 volatile_fid,
1356                 struct smb2_file_all_info *data)
1357 {
1358         return query_info(xid, tcon, persistent_fid, volatile_fid,
1359                           FILE_ALL_INFORMATION,
1360                           sizeof(struct smb2_file_all_info) + MAX_NAME * 2,
1361                           sizeof(struct smb2_file_all_info), data);
1362 }
1363
1364 int
1365 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
1366                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
1367 {
1368         return query_info(xid, tcon, persistent_fid, volatile_fid,
1369                           FILE_INTERNAL_INFORMATION,
1370                           sizeof(struct smb2_file_internal_info),
1371                           sizeof(struct smb2_file_internal_info), uniqueid);
1372 }
1373
1374 /*
1375  * This is a no-op for now. We're not really interested in the reply, but
1376  * rather in the fact that the server sent one and that server->lstrp
1377  * gets updated.
1378  *
1379  * FIXME: maybe we should consider checking that the reply matches request?
1380  */
1381 static void
1382 smb2_echo_callback(struct mid_q_entry *mid)
1383 {
1384         struct TCP_Server_Info *server = mid->callback_data;
1385         struct smb2_echo_rsp *smb2 = (struct smb2_echo_rsp *)mid->resp_buf;
1386         unsigned int credits_received = 1;
1387
1388         if (mid->mid_state == MID_RESPONSE_RECEIVED)
1389                 credits_received = le16_to_cpu(smb2->hdr.CreditRequest);
1390
1391         DeleteMidQEntry(mid);
1392         add_credits(server, credits_received, CIFS_ECHO_OP);
1393 }
1394
1395 int
1396 SMB2_echo(struct TCP_Server_Info *server)
1397 {
1398         struct smb2_echo_req *req;
1399         int rc = 0;
1400         struct kvec iov;
1401         struct smb_rqst rqst = { .rq_iov = &iov,
1402                                  .rq_nvec = 1 };
1403
1404         cifs_dbg(FYI, "In echo request\n");
1405
1406         rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
1407         if (rc)
1408                 return rc;
1409
1410         req->hdr.CreditRequest = cpu_to_le16(1);
1411
1412         iov.iov_base = (char *)req;
1413         /* 4 for rfc1002 length field */
1414         iov.iov_len = get_rfc1002_length(req) + 4;
1415
1416         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, server,
1417                              CIFS_ECHO_OP);
1418         if (rc)
1419                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
1420
1421         cifs_small_buf_release(req);
1422         return rc;
1423 }
1424
1425 int
1426 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1427            u64 volatile_fid)
1428 {
1429         struct smb2_flush_req *req;
1430         struct TCP_Server_Info *server;
1431         struct cifs_ses *ses = tcon->ses;
1432         struct kvec iov[1];
1433         int resp_buftype;
1434         int rc = 0;
1435
1436         cifs_dbg(FYI, "Flush\n");
1437
1438         if (ses && (ses->server))
1439                 server = ses->server;
1440         else
1441                 return -EIO;
1442
1443         rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
1444         if (rc)
1445                 return rc;
1446
1447         req->PersistentFileId = persistent_fid;
1448         req->VolatileFileId = volatile_fid;
1449
1450         iov[0].iov_base = (char *)req;
1451         /* 4 for rfc1002 length field */
1452         iov[0].iov_len = get_rfc1002_length(req) + 4;
1453
1454         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1455
1456         if ((rc != 0) && tcon)
1457                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
1458
1459         free_rsp_buf(resp_buftype, iov[0].iov_base);
1460         return rc;
1461 }
1462
1463 /*
1464  * To form a chain of read requests, any read requests after the first should
1465  * have the end_of_chain boolean set to true.
1466  */
1467 static int
1468 smb2_new_read_req(struct kvec *iov, struct cifs_io_parms *io_parms,
1469                   unsigned int remaining_bytes, int request_type)
1470 {
1471         int rc = -EACCES;
1472         struct smb2_read_req *req = NULL;
1473
1474         rc = small_smb2_init(SMB2_READ, io_parms->tcon, (void **) &req);
1475         if (rc)
1476                 return rc;
1477         if (io_parms->tcon->ses->server == NULL)
1478                 return -ECONNABORTED;
1479
1480         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1481
1482         req->PersistentFileId = io_parms->persistent_fid;
1483         req->VolatileFileId = io_parms->volatile_fid;
1484         req->ReadChannelInfoOffset = 0; /* reserved */
1485         req->ReadChannelInfoLength = 0; /* reserved */
1486         req->Channel = 0; /* reserved */
1487         req->MinimumCount = 0;
1488         req->Length = cpu_to_le32(io_parms->length);
1489         req->Offset = cpu_to_le64(io_parms->offset);
1490
1491         if (request_type & CHAINED_REQUEST) {
1492                 if (!(request_type & END_OF_CHAIN)) {
1493                         /* 4 for rfc1002 length field */
1494                         req->hdr.NextCommand =
1495                                 cpu_to_le32(get_rfc1002_length(req) + 4);
1496                 } else /* END_OF_CHAIN */
1497                         req->hdr.NextCommand = 0;
1498                 if (request_type & RELATED_REQUEST) {
1499                         req->hdr.Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
1500                         /*
1501                          * Related requests use info from previous read request
1502                          * in chain.
1503                          */
1504                         req->hdr.SessionId = 0xFFFFFFFF;
1505                         req->hdr.TreeId = 0xFFFFFFFF;
1506                         req->PersistentFileId = 0xFFFFFFFF;
1507                         req->VolatileFileId = 0xFFFFFFFF;
1508                 }
1509         }
1510         if (remaining_bytes > io_parms->length)
1511                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
1512         else
1513                 req->RemainingBytes = 0;
1514
1515         iov[0].iov_base = (char *)req;
1516         /* 4 for rfc1002 length field */
1517         iov[0].iov_len = get_rfc1002_length(req) + 4;
1518         return rc;
1519 }
1520
1521 static void
1522 smb2_readv_callback(struct mid_q_entry *mid)
1523 {
1524         struct cifs_readdata *rdata = mid->callback_data;
1525         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1526         struct TCP_Server_Info *server = tcon->ses->server;
1527         struct smb2_hdr *buf = (struct smb2_hdr *)rdata->iov.iov_base;
1528         unsigned int credits_received = 1;
1529         struct smb_rqst rqst = { .rq_iov = &rdata->iov,
1530                                  .rq_nvec = 1,
1531                                  .rq_pages = rdata->pages,
1532                                  .rq_npages = rdata->nr_pages,
1533                                  .rq_pagesz = rdata->pagesz,
1534                                  .rq_tailsz = rdata->tailsz };
1535
1536         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
1537                  __func__, mid->mid, mid->mid_state, rdata->result,
1538                  rdata->bytes);
1539
1540         switch (mid->mid_state) {
1541         case MID_RESPONSE_RECEIVED:
1542                 credits_received = le16_to_cpu(buf->CreditRequest);
1543                 /* result already set, check signature */
1544                 if (server->sign) {
1545                         int rc;
1546
1547                         rc = smb2_verify_signature(&rqst, server);
1548                         if (rc)
1549                                 cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
1550                                          rc);
1551                 }
1552                 /* FIXME: should this be counted toward the initiating task? */
1553                 task_io_account_read(rdata->bytes);
1554                 cifs_stats_bytes_read(tcon, rdata->bytes);
1555                 break;
1556         case MID_REQUEST_SUBMITTED:
1557         case MID_RETRY_NEEDED:
1558                 rdata->result = -EAGAIN;
1559                 break;
1560         default:
1561                 if (rdata->result != -ENODATA)
1562                         rdata->result = -EIO;
1563         }
1564
1565         if (rdata->result)
1566                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
1567
1568         queue_work(cifsiod_wq, &rdata->work);
1569         DeleteMidQEntry(mid);
1570         add_credits(server, credits_received, 0);
1571 }
1572
1573 /* smb2_async_readv - send an async write, and set up mid to handle result */
1574 int
1575 smb2_async_readv(struct cifs_readdata *rdata)
1576 {
1577         int rc;
1578         struct smb2_hdr *buf;
1579         struct cifs_io_parms io_parms;
1580         struct smb_rqst rqst = { .rq_iov = &rdata->iov,
1581                                  .rq_nvec = 1 };
1582
1583         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
1584                  __func__, rdata->offset, rdata->bytes);
1585
1586         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
1587         io_parms.offset = rdata->offset;
1588         io_parms.length = rdata->bytes;
1589         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
1590         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
1591         io_parms.pid = rdata->pid;
1592         rc = smb2_new_read_req(&rdata->iov, &io_parms, 0, 0);
1593         if (rc)
1594                 return rc;
1595
1596         buf = (struct smb2_hdr *)rdata->iov.iov_base;
1597         /* 4 for rfc1002 length field */
1598         rdata->iov.iov_len = get_rfc1002_length(rdata->iov.iov_base) + 4;
1599
1600         kref_get(&rdata->refcount);
1601         rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
1602                              cifs_readv_receive, smb2_readv_callback,
1603                              rdata, 0);
1604         if (rc) {
1605                 kref_put(&rdata->refcount, cifs_readdata_release);
1606                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
1607         }
1608
1609         cifs_small_buf_release(buf);
1610         return rc;
1611 }
1612
1613 int
1614 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
1615           unsigned int *nbytes, char **buf, int *buf_type)
1616 {
1617         int resp_buftype, rc = -EACCES;
1618         struct smb2_read_rsp *rsp = NULL;
1619         struct kvec iov[1];
1620
1621         *nbytes = 0;
1622         rc = smb2_new_read_req(iov, io_parms, 0, 0);
1623         if (rc)
1624                 return rc;
1625
1626         rc = SendReceive2(xid, io_parms->tcon->ses, iov, 1,
1627                           &resp_buftype, CIFS_LOG_ERROR);
1628
1629         rsp = (struct smb2_read_rsp *)iov[0].iov_base;
1630
1631         if (rsp->hdr.Status == STATUS_END_OF_FILE) {
1632                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1633                 return 0;
1634         }
1635
1636         if (rc) {
1637                 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
1638                 cifs_dbg(VFS, "Send error in read = %d\n", rc);
1639         } else {
1640                 *nbytes = le32_to_cpu(rsp->DataLength);
1641                 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
1642                     (*nbytes > io_parms->length)) {
1643                         cifs_dbg(FYI, "bad length %d for count %d\n",
1644                                  *nbytes, io_parms->length);
1645                         rc = -EIO;
1646                         *nbytes = 0;
1647                 }
1648         }
1649
1650         if (*buf) {
1651                 memcpy(*buf, (char *)rsp->hdr.ProtocolId + rsp->DataOffset,
1652                        *nbytes);
1653                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1654         } else if (resp_buftype != CIFS_NO_BUFFER) {
1655                 *buf = iov[0].iov_base;
1656                 if (resp_buftype == CIFS_SMALL_BUFFER)
1657                         *buf_type = CIFS_SMALL_BUFFER;
1658                 else if (resp_buftype == CIFS_LARGE_BUFFER)
1659                         *buf_type = CIFS_LARGE_BUFFER;
1660         }
1661         return rc;
1662 }
1663
1664 /*
1665  * Check the mid_state and signature on received buffer (if any), and queue the
1666  * workqueue completion task.
1667  */
1668 static void
1669 smb2_writev_callback(struct mid_q_entry *mid)
1670 {
1671         struct cifs_writedata *wdata = mid->callback_data;
1672         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1673         unsigned int written;
1674         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
1675         unsigned int credits_received = 1;
1676
1677         switch (mid->mid_state) {
1678         case MID_RESPONSE_RECEIVED:
1679                 credits_received = le16_to_cpu(rsp->hdr.CreditRequest);
1680                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
1681                 if (wdata->result != 0)
1682                         break;
1683
1684                 written = le32_to_cpu(rsp->DataLength);
1685                 /*
1686                  * Mask off high 16 bits when bytes written as returned
1687                  * by the server is greater than bytes requested by the
1688                  * client. OS/2 servers are known to set incorrect
1689                  * CountHigh values.
1690                  */
1691                 if (written > wdata->bytes)
1692                         written &= 0xFFFF;
1693
1694                 if (written < wdata->bytes)
1695                         wdata->result = -ENOSPC;
1696                 else
1697                         wdata->bytes = written;
1698                 break;
1699         case MID_REQUEST_SUBMITTED:
1700         case MID_RETRY_NEEDED:
1701                 wdata->result = -EAGAIN;
1702                 break;
1703         default:
1704                 wdata->result = -EIO;
1705                 break;
1706         }
1707
1708         if (wdata->result)
1709                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
1710
1711         queue_work(cifsiod_wq, &wdata->work);
1712         DeleteMidQEntry(mid);
1713         add_credits(tcon->ses->server, credits_received, 0);
1714 }
1715
1716 /* smb2_async_writev - send an async write, and set up mid to handle result */
1717 int
1718 smb2_async_writev(struct cifs_writedata *wdata)
1719 {
1720         int rc = -EACCES;
1721         struct smb2_write_req *req = NULL;
1722         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1723         struct kvec iov;
1724         struct smb_rqst rqst;
1725
1726         rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
1727         if (rc)
1728                 goto async_writev_out;
1729
1730         req->hdr.ProcessId = cpu_to_le32(wdata->cfile->pid);
1731
1732         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
1733         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
1734         req->WriteChannelInfoOffset = 0;
1735         req->WriteChannelInfoLength = 0;
1736         req->Channel = 0;
1737         req->Offset = cpu_to_le64(wdata->offset);
1738         /* 4 for rfc1002 length field */
1739         req->DataOffset = cpu_to_le16(
1740                                 offsetof(struct smb2_write_req, Buffer) - 4);
1741         req->RemainingBytes = 0;
1742
1743         /* 4 for rfc1002 length field and 1 for Buffer */
1744         iov.iov_len = get_rfc1002_length(req) + 4 - 1;
1745         iov.iov_base = req;
1746
1747         rqst.rq_iov = &iov;
1748         rqst.rq_nvec = 1;
1749         rqst.rq_pages = wdata->pages;
1750         rqst.rq_npages = wdata->nr_pages;
1751         rqst.rq_pagesz = wdata->pagesz;
1752         rqst.rq_tailsz = wdata->tailsz;
1753
1754         cifs_dbg(FYI, "async write at %llu %u bytes\n",
1755                  wdata->offset, wdata->bytes);
1756
1757         req->Length = cpu_to_le32(wdata->bytes);
1758
1759         inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
1760
1761         kref_get(&wdata->refcount);
1762         rc = cifs_call_async(tcon->ses->server, &rqst, NULL,
1763                                 smb2_writev_callback, wdata, 0);
1764
1765         if (rc) {
1766                 kref_put(&wdata->refcount, cifs_writedata_release);
1767                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
1768         }
1769
1770 async_writev_out:
1771         cifs_small_buf_release(req);
1772         return rc;
1773 }
1774
1775 /*
1776  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
1777  * The length field from io_parms must be at least 1 and indicates a number of
1778  * elements with data to write that begins with position 1 in iov array. All
1779  * data length is specified by count.
1780  */
1781 int
1782 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
1783            unsigned int *nbytes, struct kvec *iov, int n_vec)
1784 {
1785         int rc = 0;
1786         struct smb2_write_req *req = NULL;
1787         struct smb2_write_rsp *rsp = NULL;
1788         int resp_buftype;
1789         *nbytes = 0;
1790
1791         if (n_vec < 1)
1792                 return rc;
1793
1794         rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
1795         if (rc)
1796                 return rc;
1797
1798         if (io_parms->tcon->ses->server == NULL)
1799                 return -ECONNABORTED;
1800
1801         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1802
1803         req->PersistentFileId = io_parms->persistent_fid;
1804         req->VolatileFileId = io_parms->volatile_fid;
1805         req->WriteChannelInfoOffset = 0;
1806         req->WriteChannelInfoLength = 0;
1807         req->Channel = 0;
1808         req->Length = cpu_to_le32(io_parms->length);
1809         req->Offset = cpu_to_le64(io_parms->offset);
1810         /* 4 for rfc1002 length field */
1811         req->DataOffset = cpu_to_le16(
1812                                 offsetof(struct smb2_write_req, Buffer) - 4);
1813         req->RemainingBytes = 0;
1814
1815         iov[0].iov_base = (char *)req;
1816         /* 4 for rfc1002 length field and 1 for Buffer */
1817         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1818
1819         /* length of entire message including data to be written */
1820         inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
1821
1822         rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
1823                           &resp_buftype, 0);
1824         rsp = (struct smb2_write_rsp *)iov[0].iov_base;
1825
1826         if (rc) {
1827                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
1828                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
1829         } else
1830                 *nbytes = le32_to_cpu(rsp->DataLength);
1831
1832         free_rsp_buf(resp_buftype, rsp);
1833         return rc;
1834 }
1835
1836 static unsigned int
1837 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
1838 {
1839         int len;
1840         unsigned int entrycount = 0;
1841         unsigned int next_offset = 0;
1842         FILE_DIRECTORY_INFO *entryptr;
1843
1844         if (bufstart == NULL)
1845                 return 0;
1846
1847         entryptr = (FILE_DIRECTORY_INFO *)bufstart;
1848
1849         while (1) {
1850                 entryptr = (FILE_DIRECTORY_INFO *)
1851                                         ((char *)entryptr + next_offset);
1852
1853                 if ((char *)entryptr + size > end_of_buf) {
1854                         cifs_dbg(VFS, "malformed search entry would overflow\n");
1855                         break;
1856                 }
1857
1858                 len = le32_to_cpu(entryptr->FileNameLength);
1859                 if ((char *)entryptr + len + size > end_of_buf) {
1860                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
1861                                  end_of_buf);
1862                         break;
1863                 }
1864
1865                 *lastentry = (char *)entryptr;
1866                 entrycount++;
1867
1868                 next_offset = le32_to_cpu(entryptr->NextEntryOffset);
1869                 if (!next_offset)
1870                         break;
1871         }
1872
1873         return entrycount;
1874 }
1875
1876 /*
1877  * Readdir/FindFirst
1878  */
1879 int
1880 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
1881                      u64 persistent_fid, u64 volatile_fid, int index,
1882                      struct cifs_search_info *srch_inf)
1883 {
1884         struct smb2_query_directory_req *req;
1885         struct smb2_query_directory_rsp *rsp = NULL;
1886         struct kvec iov[2];
1887         int rc = 0;
1888         int len;
1889         int resp_buftype;
1890         unsigned char *bufptr;
1891         struct TCP_Server_Info *server;
1892         struct cifs_ses *ses = tcon->ses;
1893         __le16 asteriks = cpu_to_le16('*');
1894         char *end_of_smb;
1895         unsigned int output_size = CIFSMaxBufSize;
1896         size_t info_buf_size;
1897
1898         if (ses && (ses->server))
1899                 server = ses->server;
1900         else
1901                 return -EIO;
1902
1903         rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
1904         if (rc)
1905                 return rc;
1906
1907         switch (srch_inf->info_level) {
1908         case SMB_FIND_FILE_DIRECTORY_INFO:
1909                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
1910                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
1911                 break;
1912         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
1913                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
1914                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
1915                 break;
1916         default:
1917                 cifs_dbg(VFS, "info level %u isn't supported\n",
1918                          srch_inf->info_level);
1919                 rc = -EINVAL;
1920                 goto qdir_exit;
1921         }
1922
1923         req->FileIndex = cpu_to_le32(index);
1924         req->PersistentFileId = persistent_fid;
1925         req->VolatileFileId = volatile_fid;
1926
1927         len = 0x2;
1928         bufptr = req->Buffer;
1929         memcpy(bufptr, &asteriks, len);
1930
1931         req->FileNameOffset =
1932                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
1933         req->FileNameLength = cpu_to_le16(len);
1934         /*
1935          * BB could be 30 bytes or so longer if we used SMB2 specific
1936          * buffer lengths, but this is safe and close enough.
1937          */
1938         output_size = min_t(unsigned int, output_size, server->maxBuf);
1939         output_size = min_t(unsigned int, output_size, 2 << 15);
1940         req->OutputBufferLength = cpu_to_le32(output_size);
1941
1942         iov[0].iov_base = (char *)req;
1943         /* 4 for RFC1001 length and 1 for Buffer */
1944         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1945
1946         iov[1].iov_base = (char *)(req->Buffer);
1947         iov[1].iov_len = len;
1948
1949         inc_rfc1001_len(req, len - 1 /* Buffer */);
1950
1951         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
1952         rsp = (struct smb2_query_directory_rsp *)iov[0].iov_base;
1953
1954         if (rc) {
1955                 cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
1956                 goto qdir_exit;
1957         }
1958
1959         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
1960                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
1961                           info_buf_size);
1962         if (rc)
1963                 goto qdir_exit;
1964
1965         srch_inf->unicode = true;
1966
1967         if (srch_inf->ntwrk_buf_start) {
1968                 if (srch_inf->smallBuf)
1969                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
1970                 else
1971                         cifs_buf_release(srch_inf->ntwrk_buf_start);
1972         }
1973         srch_inf->ntwrk_buf_start = (char *)rsp;
1974         srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
1975                 (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
1976         /* 4 for rfc1002 length field */
1977         end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
1978         srch_inf->entries_in_buffer =
1979                         num_entries(srch_inf->srch_entries_start, end_of_smb,
1980                                     &srch_inf->last_entry, info_buf_size);
1981         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
1982         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
1983                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
1984                  srch_inf->srch_entries_start, srch_inf->last_entry);
1985         if (resp_buftype == CIFS_LARGE_BUFFER)
1986                 srch_inf->smallBuf = false;
1987         else if (resp_buftype == CIFS_SMALL_BUFFER)
1988                 srch_inf->smallBuf = true;
1989         else
1990                 cifs_dbg(VFS, "illegal search buffer type\n");
1991
1992         if (rsp->hdr.Status == STATUS_NO_MORE_FILES)
1993                 srch_inf->endOfSearch = 1;
1994         else
1995                 srch_inf->endOfSearch = 0;
1996
1997         return rc;
1998
1999 qdir_exit:
2000         free_rsp_buf(resp_buftype, rsp);
2001         return rc;
2002 }
2003
2004 static int
2005 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2006                u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class,
2007                unsigned int num, void **data, unsigned int *size)
2008 {
2009         struct smb2_set_info_req *req;
2010         struct smb2_set_info_rsp *rsp = NULL;
2011         struct kvec *iov;
2012         int rc = 0;
2013         int resp_buftype;
2014         unsigned int i;
2015         struct TCP_Server_Info *server;
2016         struct cifs_ses *ses = tcon->ses;
2017
2018         if (ses && (ses->server))
2019                 server = ses->server;
2020         else
2021                 return -EIO;
2022
2023         if (!num)
2024                 return -EINVAL;
2025
2026         iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
2027         if (!iov)
2028                 return -ENOMEM;
2029
2030         rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
2031         if (rc) {
2032                 kfree(iov);
2033                 return rc;
2034         }
2035
2036         req->hdr.ProcessId = cpu_to_le32(pid);
2037
2038         req->InfoType = SMB2_O_INFO_FILE;
2039         req->FileInfoClass = info_class;
2040         req->PersistentFileId = persistent_fid;
2041         req->VolatileFileId = volatile_fid;
2042
2043         /* 4 for RFC1001 length and 1 for Buffer */
2044         req->BufferOffset =
2045                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
2046         req->BufferLength = cpu_to_le32(*size);
2047
2048         inc_rfc1001_len(req, *size - 1 /* Buffer */);
2049
2050         memcpy(req->Buffer, *data, *size);
2051
2052         iov[0].iov_base = (char *)req;
2053         /* 4 for RFC1001 length */
2054         iov[0].iov_len = get_rfc1002_length(req) + 4;
2055
2056         for (i = 1; i < num; i++) {
2057                 inc_rfc1001_len(req, size[i]);
2058                 le32_add_cpu(&req->BufferLength, size[i]);
2059                 iov[i].iov_base = (char *)data[i];
2060                 iov[i].iov_len = size[i];
2061         }
2062
2063         rc = SendReceive2(xid, ses, iov, num, &resp_buftype, 0);
2064         rsp = (struct smb2_set_info_rsp *)iov[0].iov_base;
2065
2066         if (rc != 0) {
2067                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
2068                 goto out;
2069         }
2070 out:
2071         free_rsp_buf(resp_buftype, rsp);
2072         kfree(iov);
2073         return rc;
2074 }
2075
2076 int
2077 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
2078             u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2079 {
2080         struct smb2_file_rename_info info;
2081         void **data;
2082         unsigned int size[2];
2083         int rc;
2084         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2085
2086         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2087         if (!data)
2088                 return -ENOMEM;
2089
2090         info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
2091                               /* 0 = fail if target already exists */
2092         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
2093         info.FileNameLength = cpu_to_le32(len);
2094
2095         data[0] = &info;
2096         size[0] = sizeof(struct smb2_file_rename_info);
2097
2098         data[1] = target_file;
2099         size[1] = len + 2 /* null */;
2100
2101         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2102                            current->tgid, FILE_RENAME_INFORMATION, 2, data,
2103                            size);
2104         kfree(data);
2105         return rc;
2106 }
2107
2108 int
2109 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
2110                   u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
2111 {
2112         struct smb2_file_link_info info;
2113         void **data;
2114         unsigned int size[2];
2115         int rc;
2116         int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
2117
2118         data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
2119         if (!data)
2120                 return -ENOMEM;
2121
2122         info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
2123                               /* 0 = fail if link already exists */
2124         info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
2125         info.FileNameLength = cpu_to_le32(len);
2126
2127         data[0] = &info;
2128         size[0] = sizeof(struct smb2_file_link_info);
2129
2130         data[1] = target_file;
2131         size[1] = len + 2 /* null */;
2132
2133         rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
2134                            current->tgid, FILE_LINK_INFORMATION, 2, data, size);
2135         kfree(data);
2136         return rc;
2137 }
2138
2139 int
2140 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2141              u64 volatile_fid, u32 pid, __le64 *eof)
2142 {
2143         struct smb2_file_eof_info info;
2144         void *data;
2145         unsigned int size;
2146
2147         info.EndOfFile = *eof;
2148
2149         data = &info;
2150         size = sizeof(struct smb2_file_eof_info);
2151
2152         return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid,
2153                              FILE_END_OF_FILE_INFORMATION, 1, &data, &size);
2154 }
2155
2156 int
2157 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
2158               u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
2159 {
2160         unsigned int size;
2161         size = sizeof(FILE_BASIC_INFO);
2162         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
2163                              current->tgid, FILE_BASIC_INFORMATION, 1,
2164                              (void **)&buf, &size);
2165 }
2166
2167 int
2168 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
2169                   const u64 persistent_fid, const u64 volatile_fid,
2170                   __u8 oplock_level)
2171 {
2172         int rc;
2173         struct smb2_oplock_break *req = NULL;
2174
2175         cifs_dbg(FYI, "SMB2_oplock_break\n");
2176         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
2177
2178         if (rc)
2179                 return rc;
2180
2181         req->VolatileFid = volatile_fid;
2182         req->PersistentFid = persistent_fid;
2183         req->OplockLevel = oplock_level;
2184         req->hdr.CreditRequest = cpu_to_le16(1);
2185
2186         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
2187         /* SMB2 buffer freed by function above */
2188
2189         if (rc) {
2190                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
2191                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
2192         }
2193
2194         return rc;
2195 }
2196
2197 static void
2198 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
2199                         struct kstatfs *kst)
2200 {
2201         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
2202                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
2203         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
2204         kst->f_bfree  = le64_to_cpu(pfs_inf->ActualAvailableAllocationUnits);
2205         kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
2206         return;
2207 }
2208
2209 static int
2210 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
2211                    int outbuf_len, u64 persistent_fid, u64 volatile_fid)
2212 {
2213         int rc;
2214         struct smb2_query_info_req *req;
2215
2216         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
2217
2218         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
2219                 return -EIO;
2220
2221         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
2222         if (rc)
2223                 return rc;
2224
2225         req->InfoType = SMB2_O_INFO_FILESYSTEM;
2226         req->FileInfoClass = level;
2227         req->PersistentFileId = persistent_fid;
2228         req->VolatileFileId = volatile_fid;
2229         /* 4 for rfc1002 length field and 1 for pad */
2230         req->InputBufferOffset =
2231                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
2232         req->OutputBufferLength = cpu_to_le32(
2233                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
2234
2235         iov->iov_base = (char *)req;
2236         /* 4 for rfc1002 length field */
2237         iov->iov_len = get_rfc1002_length(req) + 4;
2238         return 0;
2239 }
2240
2241 int
2242 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
2243               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
2244 {
2245         struct smb2_query_info_rsp *rsp = NULL;
2246         struct kvec iov;
2247         int rc = 0;
2248         int resp_buftype;
2249         struct cifs_ses *ses = tcon->ses;
2250         struct smb2_fs_full_size_info *info = NULL;
2251
2252         rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
2253                                 sizeof(struct smb2_fs_full_size_info),
2254                                 persistent_fid, volatile_fid);
2255         if (rc)
2256                 return rc;
2257
2258         rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, 0);
2259         if (rc) {
2260                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2261                 goto qinf_exit;
2262         }
2263         rsp = (struct smb2_query_info_rsp *)iov.iov_base;
2264
2265         info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
2266                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
2267         rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
2268                           le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
2269                           sizeof(struct smb2_fs_full_size_info));
2270         if (!rc)
2271                 copy_fs_info_to_kstatfs(info, fsdata);
2272
2273 qinf_exit:
2274         free_rsp_buf(resp_buftype, iov.iov_base);
2275         return rc;
2276 }
2277
2278 int
2279 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
2280            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2281            const __u32 num_lock, struct smb2_lock_element *buf)
2282 {
2283         int rc = 0;
2284         struct smb2_lock_req *req = NULL;
2285         struct kvec iov[2];
2286         int resp_buf_type;
2287         unsigned int count;
2288
2289         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
2290
2291         rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
2292         if (rc)
2293                 return rc;
2294
2295         req->hdr.ProcessId = cpu_to_le32(pid);
2296         req->LockCount = cpu_to_le16(num_lock);
2297
2298         req->PersistentFileId = persist_fid;
2299         req->VolatileFileId = volatile_fid;
2300
2301         count = num_lock * sizeof(struct smb2_lock_element);
2302         inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
2303
2304         iov[0].iov_base = (char *)req;
2305         /* 4 for rfc1002 length field and count for all locks */
2306         iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
2307         iov[1].iov_base = (char *)buf;
2308         iov[1].iov_len = count;
2309
2310         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
2311         rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, CIFS_NO_RESP);
2312         if (rc) {
2313                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
2314                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
2315         }
2316
2317         return rc;
2318 }
2319
2320 int
2321 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
2322           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
2323           const __u64 length, const __u64 offset, const __u32 lock_flags,
2324           const bool wait)
2325 {
2326         struct smb2_lock_element lock;
2327
2328         lock.Offset = cpu_to_le64(offset);
2329         lock.Length = cpu_to_le64(length);
2330         lock.Flags = cpu_to_le32(lock_flags);
2331         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
2332                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
2333
2334         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
2335 }
2336
2337 int
2338 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
2339                  __u8 *lease_key, const __le32 lease_state)
2340 {
2341         int rc;
2342         struct smb2_lease_ack *req = NULL;
2343
2344         cifs_dbg(FYI, "SMB2_lease_break\n");
2345         rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
2346
2347         if (rc)
2348                 return rc;
2349
2350         req->hdr.CreditRequest = cpu_to_le16(1);
2351         req->StructureSize = cpu_to_le16(36);
2352         inc_rfc1001_len(req, 12);
2353
2354         memcpy(req->LeaseKey, lease_key, 16);
2355         req->LeaseState = lease_state;
2356
2357         rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, CIFS_OBREAK_OP);
2358         /* SMB2 buffer freed by function above */
2359
2360         if (rc) {
2361                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
2362                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
2363         }
2364
2365         return rc;
2366 }