CIFS: Add writepage support for SMB2
[firefly-linux-kernel-4.4.55.git] / fs / cifs / smb2pdu.c
1 /*
2  *   fs/cifs/smb2pdu.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2011
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
49 /*
50  *  The following table defines the expected "StructureSize" of SMB2 requests
51  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
52  *
53  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
54  *  indexed by command in host byte order.
55  */
56 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
57         /* SMB2_NEGOTIATE */ 36,
58         /* SMB2_SESSION_SETUP */ 25,
59         /* SMB2_LOGOFF */ 4,
60         /* SMB2_TREE_CONNECT */ 9,
61         /* SMB2_TREE_DISCONNECT */ 4,
62         /* SMB2_CREATE */ 57,
63         /* SMB2_CLOSE */ 24,
64         /* SMB2_FLUSH */ 24,
65         /* SMB2_READ */ 49,
66         /* SMB2_WRITE */ 49,
67         /* SMB2_LOCK */ 48,
68         /* SMB2_IOCTL */ 57,
69         /* SMB2_CANCEL */ 4,
70         /* SMB2_ECHO */ 4,
71         /* SMB2_QUERY_DIRECTORY */ 33,
72         /* SMB2_CHANGE_NOTIFY */ 32,
73         /* SMB2_QUERY_INFO */ 41,
74         /* SMB2_SET_INFO */ 33,
75         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
76 };
77
78
79 static void
80 smb2_hdr_assemble(struct smb2_hdr *hdr, __le16 smb2_cmd /* command */ ,
81                   const struct cifs_tcon *tcon)
82 {
83         struct smb2_pdu *pdu = (struct smb2_pdu *)hdr;
84         char *temp = (char *)hdr;
85         /* lookup word count ie StructureSize from table */
86         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_cmd)];
87
88         /*
89          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
90          * largest operations (Create)
91          */
92         memset(temp, 0, 256);
93
94         /* Note this is only network field converted to big endian */
95         hdr->smb2_buf_length = cpu_to_be32(parmsize + sizeof(struct smb2_hdr)
96                         - 4 /*  RFC 1001 length field itself not counted */);
97
98         hdr->ProtocolId[0] = 0xFE;
99         hdr->ProtocolId[1] = 'S';
100         hdr->ProtocolId[2] = 'M';
101         hdr->ProtocolId[3] = 'B';
102         hdr->StructureSize = cpu_to_le16(64);
103         hdr->Command = smb2_cmd;
104         hdr->CreditRequest = cpu_to_le16(2); /* BB make this dynamic */
105         hdr->ProcessId = cpu_to_le32((__u16)current->tgid);
106
107         if (!tcon)
108                 goto out;
109
110         hdr->TreeId = tcon->tid;
111         /* Uid is not converted */
112         if (tcon->ses)
113                 hdr->SessionId = tcon->ses->Suid;
114         /* BB check following DFS flags BB */
115         /* BB do we have to add check for SHI1005_FLAGS_DFS_ROOT too? */
116         if (tcon->share_flags & SHI1005_FLAGS_DFS)
117                 hdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS;
118         /* BB how does SMB2 do case sensitive? */
119         /* if (tcon->nocase)
120                 hdr->Flags |= SMBFLG_CASELESS; */
121         /* if (tcon->ses && tcon->ses->server &&
122             (tcon->ses->server->sec_mode & SECMODE_SIGN_REQUIRED))
123                 hdr->Flags |= SMB2_FLAGS_SIGNED; */
124 out:
125         pdu->StructureSize2 = cpu_to_le16(parmsize);
126         return;
127 }
128
129 static int
130 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
131 {
132         int rc = 0;
133         struct nls_table *nls_codepage;
134         struct cifs_ses *ses;
135         struct TCP_Server_Info *server;
136
137         /*
138          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
139          * check for tcp and smb session status done differently
140          * for those three - in the calling routine.
141          */
142         if (tcon == NULL)
143                 return rc;
144
145         if (smb2_command == SMB2_TREE_CONNECT)
146                 return rc;
147
148         if (tcon->tidStatus == CifsExiting) {
149                 /*
150                  * only tree disconnect, open, and write,
151                  * (and ulogoff which does not have tcon)
152                  * are allowed as we start force umount.
153                  */
154                 if ((smb2_command != SMB2_WRITE) &&
155                    (smb2_command != SMB2_CREATE) &&
156                    (smb2_command != SMB2_TREE_DISCONNECT)) {
157                         cFYI(1, "can not send cmd %d while umounting",
158                                 smb2_command);
159                         return -ENODEV;
160                 }
161         }
162         if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
163             (!tcon->ses->server))
164                 return -EIO;
165
166         ses = tcon->ses;
167         server = ses->server;
168
169         /*
170          * Give demultiplex thread up to 10 seconds to reconnect, should be
171          * greater than cifs socket timeout which is 7 seconds
172          */
173         while (server->tcpStatus == CifsNeedReconnect) {
174                 /*
175                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
176                  * here since they are implicitly done when session drops.
177                  */
178                 switch (smb2_command) {
179                 /*
180                  * BB Should we keep oplock break and add flush to exceptions?
181                  */
182                 case SMB2_TREE_DISCONNECT:
183                 case SMB2_CANCEL:
184                 case SMB2_CLOSE:
185                 case SMB2_OPLOCK_BREAK:
186                         return -EAGAIN;
187                 }
188
189                 wait_event_interruptible_timeout(server->response_q,
190                         (server->tcpStatus != CifsNeedReconnect), 10 * HZ);
191
192                 /* are we still trying to reconnect? */
193                 if (server->tcpStatus != CifsNeedReconnect)
194                         break;
195
196                 /*
197                  * on "soft" mounts we wait once. Hard mounts keep
198                  * retrying until process is killed or server comes
199                  * back on-line
200                  */
201                 if (!tcon->retry) {
202                         cFYI(1, "gave up waiting on reconnect in smb_init");
203                         return -EHOSTDOWN;
204                 }
205         }
206
207         if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
208                 return rc;
209
210         nls_codepage = load_nls_default();
211
212         /*
213          * need to prevent multiple threads trying to simultaneously reconnect
214          * the same SMB session
215          */
216         mutex_lock(&tcon->ses->session_mutex);
217         rc = cifs_negotiate_protocol(0, tcon->ses);
218         if (!rc && tcon->ses->need_reconnect)
219                 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
220
221         if (rc || !tcon->need_reconnect) {
222                 mutex_unlock(&tcon->ses->session_mutex);
223                 goto out;
224         }
225
226         cifs_mark_open_files_invalid(tcon);
227         rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
228         mutex_unlock(&tcon->ses->session_mutex);
229         cFYI(1, "reconnect tcon rc = %d", rc);
230         if (rc)
231                 goto out;
232         atomic_inc(&tconInfoReconnectCount);
233         /*
234          * BB FIXME add code to check if wsize needs update due to negotiated
235          * smb buffer size shrinking.
236          */
237 out:
238         /*
239          * Check if handle based operation so we know whether we can continue
240          * or not without returning to caller to reset file handle.
241          */
242         /*
243          * BB Is flush done by server on drop of tcp session? Should we special
244          * case it and skip above?
245          */
246         switch (smb2_command) {
247         case SMB2_FLUSH:
248         case SMB2_READ:
249         case SMB2_WRITE:
250         case SMB2_LOCK:
251         case SMB2_IOCTL:
252         case SMB2_QUERY_DIRECTORY:
253         case SMB2_CHANGE_NOTIFY:
254         case SMB2_QUERY_INFO:
255         case SMB2_SET_INFO:
256                 return -EAGAIN;
257         }
258         unload_nls(nls_codepage);
259         return rc;
260 }
261
262 /*
263  * Allocate and return pointer to an SMB request hdr, and set basic
264  * SMB information in the SMB header. If the return code is zero, this
265  * function must have filled in request_buf pointer.
266  */
267 static int
268 small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
269                 void **request_buf)
270 {
271         int rc = 0;
272
273         rc = smb2_reconnect(smb2_command, tcon);
274         if (rc)
275                 return rc;
276
277         /* BB eventually switch this to SMB2 specific small buf size */
278         *request_buf = cifs_small_buf_get();
279         if (*request_buf == NULL) {
280                 /* BB should we add a retry in here if not a writepage? */
281                 return -ENOMEM;
282         }
283
284         smb2_hdr_assemble((struct smb2_hdr *) *request_buf, smb2_command, tcon);
285
286         if (tcon != NULL) {
287 #ifdef CONFIG_CIFS_STATS2
288                 uint16_t com_code = le16_to_cpu(smb2_command);
289                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
290 #endif
291                 cifs_stats_inc(&tcon->num_smbs_sent);
292         }
293
294         return rc;
295 }
296
297 static void
298 free_rsp_buf(int resp_buftype, void *rsp)
299 {
300         if (resp_buftype == CIFS_SMALL_BUFFER)
301                 cifs_small_buf_release(rsp);
302         else if (resp_buftype == CIFS_LARGE_BUFFER)
303                 cifs_buf_release(rsp);
304 }
305
306 #define SMB2_NUM_PROT 1
307
308 #define SMB2_PROT   0
309 #define SMB21_PROT  1
310 #define BAD_PROT 0xFFFF
311
312 #define SMB2_PROT_ID  0x0202
313 #define SMB21_PROT_ID 0x0210
314 #define BAD_PROT_ID   0xFFFF
315
316 static struct {
317         int index;
318         __le16 name;
319 } smb2protocols[] = {
320         {SMB2_PROT,  cpu_to_le16(SMB2_PROT_ID)},
321         {SMB21_PROT, cpu_to_le16(SMB21_PROT_ID)},
322         {BAD_PROT,   cpu_to_le16(BAD_PROT_ID)}
323 };
324
325 /*
326  *
327  *      SMB2 Worker functions follow:
328  *
329  *      The general structure of the worker functions is:
330  *      1) Call smb2_init (assembles SMB2 header)
331  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
332  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
333  *      4) Decode SMB2 command specific fields in the fixed length area
334  *      5) Decode variable length data area (if any for this SMB2 command type)
335  *      6) Call free smb buffer
336  *      7) return
337  *
338  */
339
340 int
341 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
342 {
343         struct smb2_negotiate_req *req;
344         struct smb2_negotiate_rsp *rsp;
345         struct kvec iov[1];
346         int rc = 0;
347         int resp_buftype;
348         struct TCP_Server_Info *server;
349         unsigned int sec_flags;
350         u16 i;
351         u16 temp = 0;
352         int blob_offset, blob_length;
353         char *security_blob;
354         int flags = CIFS_NEG_OP;
355
356         cFYI(1, "Negotiate protocol");
357
358         if (ses->server)
359                 server = ses->server;
360         else {
361                 rc = -EIO;
362                 return rc;
363         }
364
365         rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
366         if (rc)
367                 return rc;
368
369         /* if any of auth flags (ie not sign or seal) are overriden use them */
370         if (ses->overrideSecFlg & (~(CIFSSEC_MUST_SIGN | CIFSSEC_MUST_SEAL)))
371                 sec_flags = ses->overrideSecFlg;  /* BB FIXME fix sign flags?*/
372         else /* if override flags set only sign/seal OR them with global auth */
373                 sec_flags = global_secflags | ses->overrideSecFlg;
374
375         cFYI(1, "sec_flags 0x%x", sec_flags);
376
377         req->hdr.SessionId = 0;
378
379         for (i = 0; i < SMB2_NUM_PROT; i++)
380                 req->Dialects[i] = smb2protocols[i].name;
381
382         req->DialectCount = cpu_to_le16(i);
383         inc_rfc1001_len(req, i * 2);
384
385         /* only one of SMB2 signing flags may be set in SMB2 request */
386         if ((sec_flags & CIFSSEC_MUST_SIGN) == CIFSSEC_MUST_SIGN)
387                 temp = SMB2_NEGOTIATE_SIGNING_REQUIRED;
388         else if (sec_flags & CIFSSEC_MAY_SIGN) /* MAY_SIGN is a single flag */
389                 temp = SMB2_NEGOTIATE_SIGNING_ENABLED;
390
391         req->SecurityMode = cpu_to_le16(temp);
392
393         req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
394
395         iov[0].iov_base = (char *)req;
396         /* 4 for rfc1002 length field */
397         iov[0].iov_len = get_rfc1002_length(req) + 4;
398
399         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags);
400
401         rsp = (struct smb2_negotiate_rsp *)iov[0].iov_base;
402         /*
403          * No tcon so can't do
404          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
405          */
406         if (rc != 0)
407                 goto neg_exit;
408
409         if (rsp == NULL) {
410                 rc = -EIO;
411                 goto neg_exit;
412         }
413
414         cFYI(1, "mode 0x%x", rsp->SecurityMode);
415
416         if (rsp->DialectRevision == smb2protocols[SMB21_PROT].name)
417                 cFYI(1, "negotiated smb2.1 dialect");
418         else if (rsp->DialectRevision == smb2protocols[SMB2_PROT].name)
419                 cFYI(1, "negotiated smb2 dialect");
420         else {
421                 cERROR(1, "Illegal dialect returned by server %d",
422                            le16_to_cpu(rsp->DialectRevision));
423                 rc = -EIO;
424                 goto neg_exit;
425         }
426         server->dialect = le16_to_cpu(rsp->DialectRevision);
427
428         server->maxBuf = le32_to_cpu(rsp->MaxTransactSize);
429         server->max_read = le32_to_cpu(rsp->MaxReadSize);
430         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
431         /* BB Do we need to validate the SecurityMode? */
432         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
433         server->capabilities = le32_to_cpu(rsp->Capabilities);
434         /* Internal types */
435         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
436
437         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
438                                                &rsp->hdr);
439         if (blob_length == 0) {
440                 cERROR(1, "missing security blob on negprot");
441                 rc = -EIO;
442                 goto neg_exit;
443         }
444 #ifdef CONFIG_SMB2_ASN1  /* BB REMOVEME when updated asn1.c ready */
445         rc = decode_neg_token_init(security_blob, blob_length,
446                                    &server->sec_type);
447         if (rc == 1)
448                 rc = 0;
449         else if (rc == 0) {
450                 rc = -EIO;
451                 goto neg_exit;
452         }
453 #endif
454
455 neg_exit:
456         free_rsp_buf(resp_buftype, rsp);
457         return rc;
458 }
459
460 int
461 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
462                 const struct nls_table *nls_cp)
463 {
464         struct smb2_sess_setup_req *req;
465         struct smb2_sess_setup_rsp *rsp = NULL;
466         struct kvec iov[2];
467         int rc = 0;
468         int resp_buftype;
469         __le32 phase = NtLmNegotiate; /* NTLMSSP, if needed, is multistage */
470         struct TCP_Server_Info *server;
471         unsigned int sec_flags;
472         u8 temp = 0;
473         u16 blob_length = 0;
474         char *security_blob;
475         char *ntlmssp_blob = NULL;
476         bool use_spnego = false; /* else use raw ntlmssp */
477
478         cFYI(1, "Session Setup");
479
480         if (ses->server)
481                 server = ses->server;
482         else {
483                 rc = -EIO;
484                 return rc;
485         }
486
487         /*
488          * If memory allocation is successful, caller of this function
489          * frees it.
490          */
491         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
492         if (!ses->ntlmssp)
493                 return -ENOMEM;
494
495         ses->server->secType = RawNTLMSSP;
496
497 ssetup_ntlmssp_authenticate:
498         if (phase == NtLmChallenge)
499                 phase = NtLmAuthenticate; /* if ntlmssp, now final phase */
500
501         rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
502         if (rc)
503                 return rc;
504
505         /* if any of auth flags (ie not sign or seal) are overriden use them */
506         if (ses->overrideSecFlg & (~(CIFSSEC_MUST_SIGN | CIFSSEC_MUST_SEAL)))
507                 sec_flags = ses->overrideSecFlg;  /* BB FIXME fix sign flags?*/
508         else /* if override flags set only sign/seal OR them with global auth */
509                 sec_flags = global_secflags | ses->overrideSecFlg;
510
511         cFYI(1, "sec_flags 0x%x", sec_flags);
512
513         req->hdr.SessionId = 0; /* First session, not a reauthenticate */
514         req->VcNumber = 0; /* MBZ */
515         /* to enable echos and oplocks */
516         req->hdr.CreditRequest = cpu_to_le16(3);
517
518         /* only one of SMB2 signing flags may be set in SMB2 request */
519         if ((sec_flags & CIFSSEC_MUST_SIGN) == CIFSSEC_MUST_SIGN)
520                 temp = SMB2_NEGOTIATE_SIGNING_REQUIRED;
521         else if (ses->server->sec_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED)
522                 temp = SMB2_NEGOTIATE_SIGNING_REQUIRED;
523         else if (sec_flags & CIFSSEC_MAY_SIGN) /* MAY_SIGN is a single flag */
524                 temp = SMB2_NEGOTIATE_SIGNING_ENABLED;
525
526         req->SecurityMode = temp;
527         req->Capabilities = 0;
528         req->Channel = 0; /* MBZ */
529
530         iov[0].iov_base = (char *)req;
531         /* 4 for rfc1002 length field and 1 for pad */
532         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
533         if (phase == NtLmNegotiate) {
534                 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
535                                        GFP_KERNEL);
536                 if (ntlmssp_blob == NULL) {
537                         rc = -ENOMEM;
538                         goto ssetup_exit;
539                 }
540                 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
541                 if (use_spnego) {
542                         /* blob_length = build_spnego_ntlmssp_blob(
543                                         &security_blob,
544                                         sizeof(struct _NEGOTIATE_MESSAGE),
545                                         ntlmssp_blob); */
546                         /* BB eventually need to add this */
547                         cERROR(1, "spnego not supported for SMB2 yet");
548                         rc = -EOPNOTSUPP;
549                         kfree(ntlmssp_blob);
550                         goto ssetup_exit;
551                 } else {
552                         blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
553                         /* with raw NTLMSSP we don't encapsulate in SPNEGO */
554                         security_blob = ntlmssp_blob;
555                 }
556         } else if (phase == NtLmAuthenticate) {
557                 req->hdr.SessionId = ses->Suid;
558                 ntlmssp_blob = kzalloc(sizeof(struct _NEGOTIATE_MESSAGE) + 500,
559                                        GFP_KERNEL);
560                 if (ntlmssp_blob == NULL) {
561                         cERROR(1, "failed to malloc ntlmssp blob");
562                         rc = -ENOMEM;
563                         goto ssetup_exit;
564                 }
565                 rc = build_ntlmssp_auth_blob(ntlmssp_blob, &blob_length, ses,
566                                              nls_cp);
567                 if (rc) {
568                         cFYI(1, "build_ntlmssp_auth_blob failed %d", rc);
569                         goto ssetup_exit; /* BB double check error handling */
570                 }
571                 if (use_spnego) {
572                         /* blob_length = build_spnego_ntlmssp_blob(
573                                                         &security_blob,
574                                                         blob_length,
575                                                         ntlmssp_blob); */
576                         cERROR(1, "spnego not supported for SMB2 yet");
577                         rc = -EOPNOTSUPP;
578                         kfree(ntlmssp_blob);
579                         goto ssetup_exit;
580                 } else {
581                         security_blob = ntlmssp_blob;
582                 }
583         } else {
584                 cERROR(1, "illegal ntlmssp phase");
585                 rc = -EIO;
586                 goto ssetup_exit;
587         }
588
589         /* Testing shows that buffer offset must be at location of Buffer[0] */
590         req->SecurityBufferOffset =
591                                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
592                                             1 /* pad */ - 4 /* rfc1001 len */);
593         req->SecurityBufferLength = cpu_to_le16(blob_length);
594         iov[1].iov_base = security_blob;
595         iov[1].iov_len = blob_length;
596
597         inc_rfc1001_len(req, blob_length - 1 /* pad */);
598
599         /* BB add code to build os and lm fields */
600
601         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, CIFS_LOG_ERROR);
602
603         kfree(security_blob);
604         rsp = (struct smb2_sess_setup_rsp *)iov[0].iov_base;
605         if (rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) {
606                 if (phase != NtLmNegotiate) {
607                         cERROR(1, "Unexpected more processing error");
608                         goto ssetup_exit;
609                 }
610                 if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
611                         le16_to_cpu(rsp->SecurityBufferOffset)) {
612                         cERROR(1, "Invalid security buffer offset %d",
613                                   le16_to_cpu(rsp->SecurityBufferOffset));
614                         rc = -EIO;
615                         goto ssetup_exit;
616                 }
617
618                 /* NTLMSSP Negotiate sent now processing challenge (response) */
619                 phase = NtLmChallenge; /* process ntlmssp challenge */
620                 rc = 0; /* MORE_PROCESSING is not an error here but expected */
621                 ses->Suid = rsp->hdr.SessionId;
622                 rc = decode_ntlmssp_challenge(rsp->Buffer,
623                                 le16_to_cpu(rsp->SecurityBufferLength), ses);
624         }
625
626         /*
627          * BB eventually add code for SPNEGO decoding of NtlmChallenge blob,
628          * but at least the raw NTLMSSP case works.
629          */
630         /*
631          * No tcon so can't do
632          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
633          */
634         if (rc != 0)
635                 goto ssetup_exit;
636
637         if (rsp == NULL) {
638                 rc = -EIO;
639                 goto ssetup_exit;
640         }
641
642         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
643 ssetup_exit:
644         free_rsp_buf(resp_buftype, rsp);
645
646         /* if ntlmssp, and negotiate succeeded, proceed to authenticate phase */
647         if ((phase == NtLmChallenge) && (rc == 0))
648                 goto ssetup_ntlmssp_authenticate;
649         return rc;
650 }
651
652 int
653 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
654 {
655         struct smb2_logoff_req *req; /* response is also trivial struct */
656         int rc = 0;
657         struct TCP_Server_Info *server;
658
659         cFYI(1, "disconnect session %p", ses);
660
661         if (ses && (ses->server))
662                 server = ses->server;
663         else
664                 return -EIO;
665
666         rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
667         if (rc)
668                 return rc;
669
670          /* since no tcon, smb2_init can not do this, so do here */
671         req->hdr.SessionId = ses->Suid;
672
673         rc = SendReceiveNoRsp(xid, ses, (char *) &req->hdr, 0);
674         /*
675          * No tcon so can't do
676          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
677          */
678         return rc;
679 }
680
681 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
682 {
683         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
684 }
685
686 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
687
688 int
689 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
690           struct cifs_tcon *tcon, const struct nls_table *cp)
691 {
692         struct smb2_tree_connect_req *req;
693         struct smb2_tree_connect_rsp *rsp = NULL;
694         struct kvec iov[2];
695         int rc = 0;
696         int resp_buftype;
697         int unc_path_len;
698         struct TCP_Server_Info *server;
699         __le16 *unc_path = NULL;
700
701         cFYI(1, "TCON");
702
703         if ((ses->server) && tree)
704                 server = ses->server;
705         else
706                 return -EIO;
707
708         if (tcon && tcon->bad_network_name)
709                 return -ENOENT;
710
711         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
712         if (unc_path == NULL)
713                 return -ENOMEM;
714
715         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
716         unc_path_len *= 2;
717         if (unc_path_len < 2) {
718                 kfree(unc_path);
719                 return -EINVAL;
720         }
721
722         rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
723         if (rc) {
724                 kfree(unc_path);
725                 return rc;
726         }
727
728         if (tcon == NULL) {
729                 /* since no tcon, smb2_init can not do this, so do here */
730                 req->hdr.SessionId = ses->Suid;
731                 /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
732                         req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
733         }
734
735         iov[0].iov_base = (char *)req;
736         /* 4 for rfc1002 length field and 1 for pad */
737         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
738
739         /* Testing shows that buffer offset must be at location of Buffer[0] */
740         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
741                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
742         req->PathLength = cpu_to_le16(unc_path_len - 2);
743         iov[1].iov_base = unc_path;
744         iov[1].iov_len = unc_path_len;
745
746         inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
747
748         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
749         rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
750
751         if (rc != 0) {
752                 if (tcon) {
753                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
754                         tcon->need_reconnect = true;
755                 }
756                 goto tcon_error_exit;
757         }
758
759         if (rsp == NULL) {
760                 rc = -EIO;
761                 goto tcon_exit;
762         }
763
764         if (tcon == NULL) {
765                 ses->ipc_tid = rsp->hdr.TreeId;
766                 goto tcon_exit;
767         }
768
769         if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
770                 cFYI(1, "connection to disk share");
771         else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
772                 tcon->ipc = true;
773                 cFYI(1, "connection to pipe share");
774         } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
775                 tcon->print = true;
776                 cFYI(1, "connection to printer");
777         } else {
778                 cERROR(1, "unknown share type %d", rsp->ShareType);
779                 rc = -EOPNOTSUPP;
780                 goto tcon_error_exit;
781         }
782
783         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
784         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
785         tcon->tidStatus = CifsGood;
786         tcon->need_reconnect = false;
787         tcon->tid = rsp->hdr.TreeId;
788         strncpy(tcon->treeName, tree, MAX_TREE_SIZE);
789
790         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
791             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
792                 cERROR(1, "DFS capability contradicts DFS flag");
793
794 tcon_exit:
795         free_rsp_buf(resp_buftype, rsp);
796         kfree(unc_path);
797         return rc;
798
799 tcon_error_exit:
800         if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
801                 cERROR(1, "BAD_NETWORK_NAME: %s", tree);
802                 tcon->bad_network_name = true;
803         }
804         goto tcon_exit;
805 }
806
807 int
808 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
809 {
810         struct smb2_tree_disconnect_req *req; /* response is trivial */
811         int rc = 0;
812         struct TCP_Server_Info *server;
813         struct cifs_ses *ses = tcon->ses;
814
815         cFYI(1, "Tree Disconnect");
816
817         if (ses && (ses->server))
818                 server = ses->server;
819         else
820                 return -EIO;
821
822         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
823                 return 0;
824
825         rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
826         if (rc)
827                 return rc;
828
829         rc = SendReceiveNoRsp(xid, ses, (char *)&req->hdr, 0);
830         if (rc)
831                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
832
833         return rc;
834 }
835
836 int
837 SMB2_open(const unsigned int xid, struct cifs_tcon *tcon, __le16 *path,
838           u64 *persistent_fid, u64 *volatile_fid, __u32 desired_access,
839           __u32 create_disposition, __u32 file_attributes, __u32 create_options,
840           struct smb2_file_all_info *buf)
841 {
842         struct smb2_create_req *req;
843         struct smb2_create_rsp *rsp;
844         struct TCP_Server_Info *server;
845         struct cifs_ses *ses = tcon->ses;
846         struct kvec iov[2];
847         int resp_buftype;
848         int uni_path_len;
849         int rc = 0;
850         int num_iovecs = 2;
851
852         cFYI(1, "create/open");
853
854         if (ses && (ses->server))
855                 server = ses->server;
856         else
857                 return -EIO;
858
859         rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
860         if (rc)
861                 return rc;
862
863         /* if (server->oplocks)
864                 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_BATCH;
865         else */
866                 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
867         req->ImpersonationLevel = IL_IMPERSONATION;
868         req->DesiredAccess = cpu_to_le32(desired_access);
869         /* File attributes ignored on open (used in create though) */
870         req->FileAttributes = cpu_to_le32(file_attributes);
871         req->ShareAccess = FILE_SHARE_ALL_LE;
872         req->CreateDisposition = cpu_to_le32(create_disposition);
873         req->CreateOptions = cpu_to_le32(create_options);
874         uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
875         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req)
876                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
877
878         iov[0].iov_base = (char *)req;
879         /* 4 for rfc1002 length field */
880         iov[0].iov_len = get_rfc1002_length(req) + 4;
881
882         /* MUST set path len (NameLength) to 0 opening root of share */
883         if (uni_path_len >= 4) {
884                 req->NameLength = cpu_to_le16(uni_path_len - 2);
885                 /* -1 since last byte is buf[0] which is sent below (path) */
886                 iov[0].iov_len--;
887                 iov[1].iov_len = uni_path_len;
888                 iov[1].iov_base = path;
889                 /*
890                  * -1 since last byte is buf[0] which was counted in
891                  * smb2_buf_len.
892                  */
893                 inc_rfc1001_len(req, uni_path_len - 1);
894         } else {
895                 num_iovecs = 1;
896                 req->NameLength = 0;
897         }
898
899         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
900         rsp = (struct smb2_create_rsp *)iov[0].iov_base;
901
902         if (rc != 0) {
903                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
904                 goto creat_exit;
905         }
906
907         if (rsp == NULL) {
908                 rc = -EIO;
909                 goto creat_exit;
910         }
911         *persistent_fid = rsp->PersistentFileId;
912         *volatile_fid = rsp->VolatileFileId;
913
914         if (buf) {
915                 memcpy(buf, &rsp->CreationTime, 32);
916                 buf->AllocationSize = rsp->AllocationSize;
917                 buf->EndOfFile = rsp->EndofFile;
918                 buf->Attributes = rsp->FileAttributes;
919                 buf->NumberOfLinks = cpu_to_le32(1);
920                 buf->DeletePending = 0;
921         }
922 creat_exit:
923         free_rsp_buf(resp_buftype, rsp);
924         return rc;
925 }
926
927 int
928 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
929            u64 persistent_fid, u64 volatile_fid)
930 {
931         struct smb2_close_req *req;
932         struct smb2_close_rsp *rsp;
933         struct TCP_Server_Info *server;
934         struct cifs_ses *ses = tcon->ses;
935         struct kvec iov[1];
936         int resp_buftype;
937         int rc = 0;
938
939         cFYI(1, "Close");
940
941         if (ses && (ses->server))
942                 server = ses->server;
943         else
944                 return -EIO;
945
946         rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
947         if (rc)
948                 return rc;
949
950         req->PersistentFileId = persistent_fid;
951         req->VolatileFileId = volatile_fid;
952
953         iov[0].iov_base = (char *)req;
954         /* 4 for rfc1002 length field */
955         iov[0].iov_len = get_rfc1002_length(req) + 4;
956
957         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
958         rsp = (struct smb2_close_rsp *)iov[0].iov_base;
959
960         if (rc != 0) {
961                 if (tcon)
962                         cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
963                 goto close_exit;
964         }
965
966         if (rsp == NULL) {
967                 rc = -EIO;
968                 goto close_exit;
969         }
970
971         /* BB FIXME - decode close response, update inode for caching */
972
973 close_exit:
974         free_rsp_buf(resp_buftype, rsp);
975         return rc;
976 }
977
978 static int
979 validate_buf(unsigned int offset, unsigned int buffer_length,
980              struct smb2_hdr *hdr, unsigned int min_buf_size)
981
982 {
983         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
984         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
985         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
986         char *end_of_buf = begin_of_buf + buffer_length;
987
988
989         if (buffer_length < min_buf_size) {
990                 cERROR(1, "buffer length %d smaller than minimum size %d",
991                            buffer_length, min_buf_size);
992                 return -EINVAL;
993         }
994
995         /* check if beyond RFC1001 maximum length */
996         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
997                 cERROR(1, "buffer length %d or smb length %d too large",
998                            buffer_length, smb_len);
999                 return -EINVAL;
1000         }
1001
1002         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
1003                 cERROR(1, "illegal server response, bad offset to data");
1004                 return -EINVAL;
1005         }
1006
1007         return 0;
1008 }
1009
1010 /*
1011  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
1012  * Caller must free buffer.
1013  */
1014 static int
1015 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
1016                       struct smb2_hdr *hdr, unsigned int minbufsize,
1017                       char *data)
1018
1019 {
1020         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1021         int rc;
1022
1023         if (!data)
1024                 return -EINVAL;
1025
1026         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
1027         if (rc)
1028                 return rc;
1029
1030         memcpy(data, begin_of_buf, buffer_length);
1031
1032         return 0;
1033 }
1034
1035 static int
1036 query_info(const unsigned int xid, struct cifs_tcon *tcon,
1037            u64 persistent_fid, u64 volatile_fid, u8 info_class,
1038            size_t output_len, size_t min_len, void *data)
1039 {
1040         struct smb2_query_info_req *req;
1041         struct smb2_query_info_rsp *rsp = NULL;
1042         struct kvec iov[2];
1043         int rc = 0;
1044         int resp_buftype;
1045         struct TCP_Server_Info *server;
1046         struct cifs_ses *ses = tcon->ses;
1047
1048         cFYI(1, "Query Info");
1049
1050         if (ses && (ses->server))
1051                 server = ses->server;
1052         else
1053                 return -EIO;
1054
1055         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
1056         if (rc)
1057                 return rc;
1058
1059         req->InfoType = SMB2_O_INFO_FILE;
1060         req->FileInfoClass = info_class;
1061         req->PersistentFileId = persistent_fid;
1062         req->VolatileFileId = volatile_fid;
1063         /* 4 for rfc1002 length field and 1 for Buffer */
1064         req->InputBufferOffset =
1065                 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
1066         req->OutputBufferLength = cpu_to_le32(output_len);
1067
1068         iov[0].iov_base = (char *)req;
1069         /* 4 for rfc1002 length field */
1070         iov[0].iov_len = get_rfc1002_length(req) + 4;
1071
1072         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1073         if (rc) {
1074                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
1075                 goto qinf_exit;
1076         }
1077
1078         rsp = (struct smb2_query_info_rsp *)iov[0].iov_base;
1079
1080         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
1081                                    le32_to_cpu(rsp->OutputBufferLength),
1082                                    &rsp->hdr, min_len, data);
1083
1084 qinf_exit:
1085         free_rsp_buf(resp_buftype, rsp);
1086         return rc;
1087 }
1088
1089 int
1090 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
1091                 u64 persistent_fid, u64 volatile_fid,
1092                 struct smb2_file_all_info *data)
1093 {
1094         return query_info(xid, tcon, persistent_fid, volatile_fid,
1095                           FILE_ALL_INFORMATION,
1096                           sizeof(struct smb2_file_all_info) + MAX_NAME * 2,
1097                           sizeof(struct smb2_file_all_info), data);
1098 }
1099
1100 int
1101 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
1102                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
1103 {
1104         return query_info(xid, tcon, persistent_fid, volatile_fid,
1105                           FILE_INTERNAL_INFORMATION,
1106                           sizeof(struct smb2_file_internal_info),
1107                           sizeof(struct smb2_file_internal_info), uniqueid);
1108 }
1109
1110 /*
1111  * This is a no-op for now. We're not really interested in the reply, but
1112  * rather in the fact that the server sent one and that server->lstrp
1113  * gets updated.
1114  *
1115  * FIXME: maybe we should consider checking that the reply matches request?
1116  */
1117 static void
1118 smb2_echo_callback(struct mid_q_entry *mid)
1119 {
1120         struct TCP_Server_Info *server = mid->callback_data;
1121         struct smb2_echo_rsp *smb2 = (struct smb2_echo_rsp *)mid->resp_buf;
1122         unsigned int credits_received = 1;
1123
1124         if (mid->mid_state == MID_RESPONSE_RECEIVED)
1125                 credits_received = le16_to_cpu(smb2->hdr.CreditRequest);
1126
1127         DeleteMidQEntry(mid);
1128         add_credits(server, credits_received, CIFS_ECHO_OP);
1129 }
1130
1131 int
1132 SMB2_echo(struct TCP_Server_Info *server)
1133 {
1134         struct smb2_echo_req *req;
1135         int rc = 0;
1136         struct kvec iov;
1137
1138         cFYI(1, "In echo request");
1139
1140         rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
1141         if (rc)
1142                 return rc;
1143
1144         req->hdr.CreditRequest = cpu_to_le16(1);
1145
1146         iov.iov_base = (char *)req;
1147         /* 4 for rfc1002 length field */
1148         iov.iov_len = get_rfc1002_length(req) + 4;
1149
1150         rc = cifs_call_async(server, &iov, 1, NULL, smb2_echo_callback, server,
1151                              CIFS_ECHO_OP);
1152         if (rc)
1153                 cFYI(1, "Echo request failed: %d", rc);
1154
1155         cifs_small_buf_release(req);
1156         return rc;
1157 }
1158
1159 int
1160 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1161            u64 volatile_fid)
1162 {
1163         struct smb2_flush_req *req;
1164         struct TCP_Server_Info *server;
1165         struct cifs_ses *ses = tcon->ses;
1166         struct kvec iov[1];
1167         int resp_buftype;
1168         int rc = 0;
1169
1170         cFYI(1, "Flush");
1171
1172         if (ses && (ses->server))
1173                 server = ses->server;
1174         else
1175                 return -EIO;
1176
1177         rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
1178         if (rc)
1179                 return rc;
1180
1181         req->PersistentFileId = persistent_fid;
1182         req->VolatileFileId = volatile_fid;
1183
1184         iov[0].iov_base = (char *)req;
1185         /* 4 for rfc1002 length field */
1186         iov[0].iov_len = get_rfc1002_length(req) + 4;
1187
1188         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1189
1190         if ((rc != 0) && tcon)
1191                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
1192
1193         free_rsp_buf(resp_buftype, iov[0].iov_base);
1194         return rc;
1195 }
1196
1197 /*
1198  * To form a chain of read requests, any read requests after the first should
1199  * have the end_of_chain boolean set to true.
1200  */
1201 static int
1202 smb2_new_read_req(struct kvec *iov, struct cifs_io_parms *io_parms,
1203                   unsigned int remaining_bytes, int request_type)
1204 {
1205         int rc = -EACCES;
1206         struct smb2_read_req *req = NULL;
1207
1208         rc = small_smb2_init(SMB2_READ, io_parms->tcon, (void **) &req);
1209         if (rc)
1210                 return rc;
1211         if (io_parms->tcon->ses->server == NULL)
1212                 return -ECONNABORTED;
1213
1214         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1215
1216         req->PersistentFileId = io_parms->persistent_fid;
1217         req->VolatileFileId = io_parms->volatile_fid;
1218         req->ReadChannelInfoOffset = 0; /* reserved */
1219         req->ReadChannelInfoLength = 0; /* reserved */
1220         req->Channel = 0; /* reserved */
1221         req->MinimumCount = 0;
1222         req->Length = cpu_to_le32(io_parms->length);
1223         req->Offset = cpu_to_le64(io_parms->offset);
1224
1225         if (request_type & CHAINED_REQUEST) {
1226                 if (!(request_type & END_OF_CHAIN)) {
1227                         /* 4 for rfc1002 length field */
1228                         req->hdr.NextCommand =
1229                                 cpu_to_le32(get_rfc1002_length(req) + 4);
1230                 } else /* END_OF_CHAIN */
1231                         req->hdr.NextCommand = 0;
1232                 if (request_type & RELATED_REQUEST) {
1233                         req->hdr.Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
1234                         /*
1235                          * Related requests use info from previous read request
1236                          * in chain.
1237                          */
1238                         req->hdr.SessionId = 0xFFFFFFFF;
1239                         req->hdr.TreeId = 0xFFFFFFFF;
1240                         req->PersistentFileId = 0xFFFFFFFF;
1241                         req->VolatileFileId = 0xFFFFFFFF;
1242                 }
1243         }
1244         if (remaining_bytes > io_parms->length)
1245                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
1246         else
1247                 req->RemainingBytes = 0;
1248
1249         iov[0].iov_base = (char *)req;
1250         /* 4 for rfc1002 length field */
1251         iov[0].iov_len = get_rfc1002_length(req) + 4;
1252         return rc;
1253 }
1254
1255 static void
1256 smb2_readv_callback(struct mid_q_entry *mid)
1257 {
1258         struct cifs_readdata *rdata = mid->callback_data;
1259         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1260         struct TCP_Server_Info *server = tcon->ses->server;
1261         struct smb2_hdr *buf = (struct smb2_hdr *)rdata->iov[0].iov_base;
1262         unsigned int credits_received = 1;
1263
1264         cFYI(1, "%s: mid=%llu state=%d result=%d bytes=%u", __func__,
1265                 mid->mid, mid->mid_state, rdata->result, rdata->bytes);
1266
1267         switch (mid->mid_state) {
1268         case MID_RESPONSE_RECEIVED:
1269                 credits_received = le16_to_cpu(buf->CreditRequest);
1270                 /* result already set, check signature */
1271                 /* if (server->sec_mode &
1272                     (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
1273                         if (smb2_verify_signature(mid->resp_buf, server))
1274                                 cERROR(1, "Unexpected SMB signature"); */
1275                 /* FIXME: should this be counted toward the initiating task? */
1276                 task_io_account_read(rdata->bytes);
1277                 cifs_stats_bytes_read(tcon, rdata->bytes);
1278                 break;
1279         case MID_REQUEST_SUBMITTED:
1280         case MID_RETRY_NEEDED:
1281                 rdata->result = -EAGAIN;
1282                 break;
1283         default:
1284                 if (rdata->result != -ENODATA)
1285                         rdata->result = -EIO;
1286         }
1287
1288         if (rdata->result)
1289                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
1290
1291         queue_work(cifsiod_wq, &rdata->work);
1292         DeleteMidQEntry(mid);
1293         add_credits(server, credits_received, 0);
1294 }
1295
1296 /* smb2_async_readv - send an async write, and set up mid to handle result */
1297 int
1298 smb2_async_readv(struct cifs_readdata *rdata)
1299 {
1300         int rc;
1301         struct smb2_hdr *buf;
1302         struct cifs_io_parms io_parms;
1303
1304         cFYI(1, "%s: offset=%llu bytes=%u", __func__,
1305                 rdata->offset, rdata->bytes);
1306
1307         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
1308         io_parms.offset = rdata->offset;
1309         io_parms.length = rdata->bytes;
1310         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
1311         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
1312         io_parms.pid = rdata->pid;
1313         rc = smb2_new_read_req(&rdata->iov[0], &io_parms, 0, 0);
1314         if (rc)
1315                 return rc;
1316
1317         buf = (struct smb2_hdr *)rdata->iov[0].iov_base;
1318         /* 4 for rfc1002 length field */
1319         rdata->iov[0].iov_len = get_rfc1002_length(rdata->iov[0].iov_base) + 4;
1320
1321         kref_get(&rdata->refcount);
1322         rc = cifs_call_async(io_parms.tcon->ses->server, rdata->iov, 1,
1323                              cifs_readv_receive, smb2_readv_callback,
1324                              rdata, 0);
1325         if (rc)
1326                 kref_put(&rdata->refcount, cifs_readdata_release);
1327
1328         cifs_small_buf_release(buf);
1329         return rc;
1330 }
1331
1332 int
1333 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
1334           unsigned int *nbytes, char **buf, int *buf_type)
1335 {
1336         int resp_buftype, rc = -EACCES;
1337         struct smb2_read_rsp *rsp = NULL;
1338         struct kvec iov[1];
1339
1340         *nbytes = 0;
1341         rc = smb2_new_read_req(iov, io_parms, 0, 0);
1342         if (rc)
1343                 return rc;
1344
1345         rc = SendReceive2(xid, io_parms->tcon->ses, iov, 1,
1346                           &resp_buftype, CIFS_LOG_ERROR);
1347
1348         rsp = (struct smb2_read_rsp *)iov[0].iov_base;
1349
1350         if (rsp->hdr.Status == STATUS_END_OF_FILE) {
1351                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1352                 return 0;
1353         }
1354
1355         if (rc) {
1356                 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
1357                 cERROR(1, "Send error in read = %d", rc);
1358         } else {
1359                 *nbytes = le32_to_cpu(rsp->DataLength);
1360                 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
1361                     (*nbytes > io_parms->length)) {
1362                         cFYI(1, "bad length %d for count %d", *nbytes,
1363                                 io_parms->length);
1364                         rc = -EIO;
1365                         *nbytes = 0;
1366                 }
1367         }
1368
1369         if (*buf) {
1370                 memcpy(*buf, (char *)rsp->hdr.ProtocolId + rsp->DataOffset,
1371                        *nbytes);
1372                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1373         } else if (resp_buftype != CIFS_NO_BUFFER) {
1374                 *buf = iov[0].iov_base;
1375                 if (resp_buftype == CIFS_SMALL_BUFFER)
1376                         *buf_type = CIFS_SMALL_BUFFER;
1377                 else if (resp_buftype == CIFS_LARGE_BUFFER)
1378                         *buf_type = CIFS_LARGE_BUFFER;
1379         }
1380         return rc;
1381 }
1382
1383 /*
1384  * Check the mid_state and signature on received buffer (if any), and queue the
1385  * workqueue completion task.
1386  */
1387 static void
1388 smb2_writev_callback(struct mid_q_entry *mid)
1389 {
1390         struct cifs_writedata *wdata = mid->callback_data;
1391         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1392         unsigned int written;
1393         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
1394         unsigned int credits_received = 1;
1395
1396         switch (mid->mid_state) {
1397         case MID_RESPONSE_RECEIVED:
1398                 credits_received = le16_to_cpu(rsp->hdr.CreditRequest);
1399                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
1400                 if (wdata->result != 0)
1401                         break;
1402
1403                 written = le32_to_cpu(rsp->DataLength);
1404                 /*
1405                  * Mask off high 16 bits when bytes written as returned
1406                  * by the server is greater than bytes requested by the
1407                  * client. OS/2 servers are known to set incorrect
1408                  * CountHigh values.
1409                  */
1410                 if (written > wdata->bytes)
1411                         written &= 0xFFFF;
1412
1413                 if (written < wdata->bytes)
1414                         wdata->result = -ENOSPC;
1415                 else
1416                         wdata->bytes = written;
1417                 break;
1418         case MID_REQUEST_SUBMITTED:
1419         case MID_RETRY_NEEDED:
1420                 wdata->result = -EAGAIN;
1421                 break;
1422         default:
1423                 wdata->result = -EIO;
1424                 break;
1425         }
1426
1427         if (wdata->result)
1428                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
1429
1430         queue_work(cifsiod_wq, &wdata->work);
1431         DeleteMidQEntry(mid);
1432         add_credits(tcon->ses->server, credits_received, 0);
1433 }
1434
1435 /* smb2_async_writev - send an async write, and set up mid to handle result */
1436 int
1437 smb2_async_writev(struct cifs_writedata *wdata)
1438 {
1439         int i, rc = -EACCES;
1440         struct smb2_write_req *req = NULL;
1441         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1442         struct kvec *iov = NULL;
1443
1444         rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
1445         if (rc)
1446                 goto async_writev_out;
1447
1448         /* 1 iov per page + 1 for header */
1449         iov = kzalloc((wdata->nr_pages + 1) * sizeof(*iov), GFP_NOFS);
1450         if (iov == NULL) {
1451                 rc = -ENOMEM;
1452                 goto async_writev_out;
1453         }
1454
1455         req->hdr.ProcessId = cpu_to_le32(wdata->cfile->pid);
1456
1457         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
1458         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
1459         req->WriteChannelInfoOffset = 0;
1460         req->WriteChannelInfoLength = 0;
1461         req->Channel = 0;
1462         req->Offset = cpu_to_le64(wdata->offset);
1463         /* 4 for rfc1002 length field */
1464         req->DataOffset = cpu_to_le16(
1465                                 offsetof(struct smb2_write_req, Buffer) - 4);
1466         req->RemainingBytes = 0;
1467
1468         /* 4 for rfc1002 length field and 1 for Buffer */
1469         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1470         iov[0].iov_base = (char *)req;
1471
1472         /*
1473          * This function should marshal up the page array into the kvec
1474          * array, reserving [0] for the header. It should kmap the pages
1475          * and set the iov_len properly for each one. It may also set
1476          * wdata->bytes too.
1477          */
1478         cifs_kmap_lock();
1479         wdata->marshal_iov(iov, wdata);
1480         cifs_kmap_unlock();
1481
1482         cFYI(1, "async write at %llu %u bytes", wdata->offset, wdata->bytes);
1483
1484         req->Length = cpu_to_le32(wdata->bytes);
1485
1486         inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
1487
1488         kref_get(&wdata->refcount);
1489         rc = cifs_call_async(tcon->ses->server, iov, wdata->nr_pages + 1,
1490                              NULL, smb2_writev_callback, wdata, 0);
1491
1492         if (rc)
1493                 kref_put(&wdata->refcount, cifs_writedata_release);
1494
1495         /* send is done, unmap pages */
1496         for (i = 0; i < wdata->nr_pages; i++)
1497                 kunmap(wdata->pages[i]);
1498
1499 async_writev_out:
1500         cifs_small_buf_release(req);
1501         kfree(iov);
1502         return rc;
1503 }
1504
1505 /*
1506  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
1507  * The length field from io_parms must be at least 1 and indicates a number of
1508  * elements with data to write that begins with position 1 in iov array. All
1509  * data length is specified by count.
1510  */
1511 int
1512 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
1513            unsigned int *nbytes, struct kvec *iov, int n_vec)
1514 {
1515         int rc = 0;
1516         struct smb2_write_req *req = NULL;
1517         struct smb2_write_rsp *rsp = NULL;
1518         int resp_buftype;
1519         *nbytes = 0;
1520
1521         if (n_vec < 1)
1522                 return rc;
1523
1524         rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
1525         if (rc)
1526                 return rc;
1527
1528         if (io_parms->tcon->ses->server == NULL)
1529                 return -ECONNABORTED;
1530
1531         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1532
1533         req->PersistentFileId = io_parms->persistent_fid;
1534         req->VolatileFileId = io_parms->volatile_fid;
1535         req->WriteChannelInfoOffset = 0;
1536         req->WriteChannelInfoLength = 0;
1537         req->Channel = 0;
1538         req->Length = cpu_to_le32(io_parms->length);
1539         req->Offset = cpu_to_le64(io_parms->offset);
1540         /* 4 for rfc1002 length field */
1541         req->DataOffset = cpu_to_le16(
1542                                 offsetof(struct smb2_write_req, Buffer) - 4);
1543         req->RemainingBytes = 0;
1544
1545         iov[0].iov_base = (char *)req;
1546         /* 4 for rfc1002 length field and 1 for Buffer */
1547         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1548
1549         /* length of entire message including data to be written */
1550         inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
1551
1552         rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
1553                           &resp_buftype, 0);
1554
1555         if (rc) {
1556                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
1557                 cERROR(1, "Send error in write = %d", rc);
1558         } else {
1559                 rsp = (struct smb2_write_rsp *)iov[0].iov_base;
1560                 *nbytes = le32_to_cpu(rsp->DataLength);
1561                 free_rsp_buf(resp_buftype, rsp);
1562         }
1563         return rc;
1564 }