CIFS: Move rename to ops struct
[linux-3.10.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
445         cFYI(1, "sec_flags 0x%x", sec_flags);
446         if (sec_flags & CIFSSEC_MUST_SIGN) {
447                 cFYI(1, "Signing required");
448                 if (!(server->sec_mode & (SMB2_NEGOTIATE_SIGNING_REQUIRED |
449                       SMB2_NEGOTIATE_SIGNING_ENABLED))) {
450                         cERROR(1, "signing required but server lacks support");
451                         rc = -EOPNOTSUPP;
452                         goto neg_exit;
453                 }
454                 server->sec_mode |= SECMODE_SIGN_REQUIRED;
455         } else if (sec_flags & CIFSSEC_MAY_SIGN) {
456                 cFYI(1, "Signing optional");
457                 if (server->sec_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
458                         cFYI(1, "Server requires signing");
459                         server->sec_mode |= SECMODE_SIGN_REQUIRED;
460                 } else {
461                         server->sec_mode &=
462                                 ~(SECMODE_SIGN_ENABLED | SECMODE_SIGN_REQUIRED);
463                 }
464         } else {
465                 cFYI(1, "Signing disabled");
466                 if (server->sec_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
467                         cERROR(1, "Server requires packet signing to be enabled"
468                                   " in /proc/fs/cifs/SecurityFlags.");
469                         rc = -EOPNOTSUPP;
470                         goto neg_exit;
471                 }
472                 server->sec_mode &=
473                         ~(SECMODE_SIGN_ENABLED | SECMODE_SIGN_REQUIRED);
474         }
475
476 #ifdef CONFIG_SMB2_ASN1  /* BB REMOVEME when updated asn1.c ready */
477         rc = decode_neg_token_init(security_blob, blob_length,
478                                    &server->sec_type);
479         if (rc == 1)
480                 rc = 0;
481         else if (rc == 0) {
482                 rc = -EIO;
483                 goto neg_exit;
484         }
485 #endif
486
487 neg_exit:
488         free_rsp_buf(resp_buftype, rsp);
489         return rc;
490 }
491
492 int
493 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
494                 const struct nls_table *nls_cp)
495 {
496         struct smb2_sess_setup_req *req;
497         struct smb2_sess_setup_rsp *rsp = NULL;
498         struct kvec iov[2];
499         int rc = 0;
500         int resp_buftype;
501         __le32 phase = NtLmNegotiate; /* NTLMSSP, if needed, is multistage */
502         struct TCP_Server_Info *server;
503         unsigned int sec_flags;
504         u8 temp = 0;
505         u16 blob_length = 0;
506         char *security_blob;
507         char *ntlmssp_blob = NULL;
508         bool use_spnego = false; /* else use raw ntlmssp */
509
510         cFYI(1, "Session Setup");
511
512         if (ses->server)
513                 server = ses->server;
514         else {
515                 rc = -EIO;
516                 return rc;
517         }
518
519         /*
520          * If memory allocation is successful, caller of this function
521          * frees it.
522          */
523         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
524         if (!ses->ntlmssp)
525                 return -ENOMEM;
526
527         ses->server->secType = RawNTLMSSP;
528
529 ssetup_ntlmssp_authenticate:
530         if (phase == NtLmChallenge)
531                 phase = NtLmAuthenticate; /* if ntlmssp, now final phase */
532
533         rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
534         if (rc)
535                 return rc;
536
537         /* if any of auth flags (ie not sign or seal) are overriden use them */
538         if (ses->overrideSecFlg & (~(CIFSSEC_MUST_SIGN | CIFSSEC_MUST_SEAL)))
539                 sec_flags = ses->overrideSecFlg;  /* BB FIXME fix sign flags?*/
540         else /* if override flags set only sign/seal OR them with global auth */
541                 sec_flags = global_secflags | ses->overrideSecFlg;
542
543         cFYI(1, "sec_flags 0x%x", sec_flags);
544
545         req->hdr.SessionId = 0; /* First session, not a reauthenticate */
546         req->VcNumber = 0; /* MBZ */
547         /* to enable echos and oplocks */
548         req->hdr.CreditRequest = cpu_to_le16(3);
549
550         /* only one of SMB2 signing flags may be set in SMB2 request */
551         if ((sec_flags & CIFSSEC_MUST_SIGN) == CIFSSEC_MUST_SIGN)
552                 temp = SMB2_NEGOTIATE_SIGNING_REQUIRED;
553         else if (ses->server->sec_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED)
554                 temp = SMB2_NEGOTIATE_SIGNING_REQUIRED;
555         else if (sec_flags & CIFSSEC_MAY_SIGN) /* MAY_SIGN is a single flag */
556                 temp = SMB2_NEGOTIATE_SIGNING_ENABLED;
557
558         req->SecurityMode = temp;
559         req->Capabilities = 0;
560         req->Channel = 0; /* MBZ */
561
562         iov[0].iov_base = (char *)req;
563         /* 4 for rfc1002 length field and 1 for pad */
564         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
565         if (phase == NtLmNegotiate) {
566                 ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
567                                        GFP_KERNEL);
568                 if (ntlmssp_blob == NULL) {
569                         rc = -ENOMEM;
570                         goto ssetup_exit;
571                 }
572                 build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
573                 if (use_spnego) {
574                         /* blob_length = build_spnego_ntlmssp_blob(
575                                         &security_blob,
576                                         sizeof(struct _NEGOTIATE_MESSAGE),
577                                         ntlmssp_blob); */
578                         /* BB eventually need to add this */
579                         cERROR(1, "spnego not supported for SMB2 yet");
580                         rc = -EOPNOTSUPP;
581                         kfree(ntlmssp_blob);
582                         goto ssetup_exit;
583                 } else {
584                         blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
585                         /* with raw NTLMSSP we don't encapsulate in SPNEGO */
586                         security_blob = ntlmssp_blob;
587                 }
588         } else if (phase == NtLmAuthenticate) {
589                 req->hdr.SessionId = ses->Suid;
590                 ntlmssp_blob = kzalloc(sizeof(struct _NEGOTIATE_MESSAGE) + 500,
591                                        GFP_KERNEL);
592                 if (ntlmssp_blob == NULL) {
593                         cERROR(1, "failed to malloc ntlmssp blob");
594                         rc = -ENOMEM;
595                         goto ssetup_exit;
596                 }
597                 rc = build_ntlmssp_auth_blob(ntlmssp_blob, &blob_length, ses,
598                                              nls_cp);
599                 if (rc) {
600                         cFYI(1, "build_ntlmssp_auth_blob failed %d", rc);
601                         goto ssetup_exit; /* BB double check error handling */
602                 }
603                 if (use_spnego) {
604                         /* blob_length = build_spnego_ntlmssp_blob(
605                                                         &security_blob,
606                                                         blob_length,
607                                                         ntlmssp_blob); */
608                         cERROR(1, "spnego not supported for SMB2 yet");
609                         rc = -EOPNOTSUPP;
610                         kfree(ntlmssp_blob);
611                         goto ssetup_exit;
612                 } else {
613                         security_blob = ntlmssp_blob;
614                 }
615         } else {
616                 cERROR(1, "illegal ntlmssp phase");
617                 rc = -EIO;
618                 goto ssetup_exit;
619         }
620
621         /* Testing shows that buffer offset must be at location of Buffer[0] */
622         req->SecurityBufferOffset =
623                                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
624                                             1 /* pad */ - 4 /* rfc1001 len */);
625         req->SecurityBufferLength = cpu_to_le16(blob_length);
626         iov[1].iov_base = security_blob;
627         iov[1].iov_len = blob_length;
628
629         inc_rfc1001_len(req, blob_length - 1 /* pad */);
630
631         /* BB add code to build os and lm fields */
632
633         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, CIFS_LOG_ERROR);
634
635         kfree(security_blob);
636         rsp = (struct smb2_sess_setup_rsp *)iov[0].iov_base;
637         if (rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) {
638                 if (phase != NtLmNegotiate) {
639                         cERROR(1, "Unexpected more processing error");
640                         goto ssetup_exit;
641                 }
642                 if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
643                         le16_to_cpu(rsp->SecurityBufferOffset)) {
644                         cERROR(1, "Invalid security buffer offset %d",
645                                   le16_to_cpu(rsp->SecurityBufferOffset));
646                         rc = -EIO;
647                         goto ssetup_exit;
648                 }
649
650                 /* NTLMSSP Negotiate sent now processing challenge (response) */
651                 phase = NtLmChallenge; /* process ntlmssp challenge */
652                 rc = 0; /* MORE_PROCESSING is not an error here but expected */
653                 ses->Suid = rsp->hdr.SessionId;
654                 rc = decode_ntlmssp_challenge(rsp->Buffer,
655                                 le16_to_cpu(rsp->SecurityBufferLength), ses);
656         }
657
658         /*
659          * BB eventually add code for SPNEGO decoding of NtlmChallenge blob,
660          * but at least the raw NTLMSSP case works.
661          */
662         /*
663          * No tcon so can't do
664          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
665          */
666         if (rc != 0)
667                 goto ssetup_exit;
668
669         if (rsp == NULL) {
670                 rc = -EIO;
671                 goto ssetup_exit;
672         }
673
674         ses->session_flags = le16_to_cpu(rsp->SessionFlags);
675 ssetup_exit:
676         free_rsp_buf(resp_buftype, rsp);
677
678         /* if ntlmssp, and negotiate succeeded, proceed to authenticate phase */
679         if ((phase == NtLmChallenge) && (rc == 0))
680                 goto ssetup_ntlmssp_authenticate;
681         return rc;
682 }
683
684 int
685 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
686 {
687         struct smb2_logoff_req *req; /* response is also trivial struct */
688         int rc = 0;
689         struct TCP_Server_Info *server;
690
691         cFYI(1, "disconnect session %p", ses);
692
693         if (ses && (ses->server))
694                 server = ses->server;
695         else
696                 return -EIO;
697
698         rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
699         if (rc)
700                 return rc;
701
702          /* since no tcon, smb2_init can not do this, so do here */
703         req->hdr.SessionId = ses->Suid;
704         if (server->sec_mode & SECMODE_SIGN_REQUIRED)
705                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
706
707         rc = SendReceiveNoRsp(xid, ses, (char *) &req->hdr, 0);
708         /*
709          * No tcon so can't do
710          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
711          */
712         return rc;
713 }
714
715 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
716 {
717         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
718 }
719
720 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
721
722 int
723 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
724           struct cifs_tcon *tcon, const struct nls_table *cp)
725 {
726         struct smb2_tree_connect_req *req;
727         struct smb2_tree_connect_rsp *rsp = NULL;
728         struct kvec iov[2];
729         int rc = 0;
730         int resp_buftype;
731         int unc_path_len;
732         struct TCP_Server_Info *server;
733         __le16 *unc_path = NULL;
734
735         cFYI(1, "TCON");
736
737         if ((ses->server) && tree)
738                 server = ses->server;
739         else
740                 return -EIO;
741
742         if (tcon && tcon->bad_network_name)
743                 return -ENOENT;
744
745         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
746         if (unc_path == NULL)
747                 return -ENOMEM;
748
749         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
750         unc_path_len *= 2;
751         if (unc_path_len < 2) {
752                 kfree(unc_path);
753                 return -EINVAL;
754         }
755
756         rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
757         if (rc) {
758                 kfree(unc_path);
759                 return rc;
760         }
761
762         if (tcon == NULL) {
763                 /* since no tcon, smb2_init can not do this, so do here */
764                 req->hdr.SessionId = ses->Suid;
765                 /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
766                         req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
767         }
768
769         iov[0].iov_base = (char *)req;
770         /* 4 for rfc1002 length field and 1 for pad */
771         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
772
773         /* Testing shows that buffer offset must be at location of Buffer[0] */
774         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
775                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
776         req->PathLength = cpu_to_le16(unc_path_len - 2);
777         iov[1].iov_base = unc_path;
778         iov[1].iov_len = unc_path_len;
779
780         inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
781
782         rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
783         rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
784
785         if (rc != 0) {
786                 if (tcon) {
787                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
788                         tcon->need_reconnect = true;
789                 }
790                 goto tcon_error_exit;
791         }
792
793         if (rsp == NULL) {
794                 rc = -EIO;
795                 goto tcon_exit;
796         }
797
798         if (tcon == NULL) {
799                 ses->ipc_tid = rsp->hdr.TreeId;
800                 goto tcon_exit;
801         }
802
803         if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
804                 cFYI(1, "connection to disk share");
805         else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
806                 tcon->ipc = true;
807                 cFYI(1, "connection to pipe share");
808         } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
809                 tcon->print = true;
810                 cFYI(1, "connection to printer");
811         } else {
812                 cERROR(1, "unknown share type %d", rsp->ShareType);
813                 rc = -EOPNOTSUPP;
814                 goto tcon_error_exit;
815         }
816
817         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
818         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
819         tcon->tidStatus = CifsGood;
820         tcon->need_reconnect = false;
821         tcon->tid = rsp->hdr.TreeId;
822         strncpy(tcon->treeName, tree, MAX_TREE_SIZE);
823
824         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
825             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
826                 cERROR(1, "DFS capability contradicts DFS flag");
827
828 tcon_exit:
829         free_rsp_buf(resp_buftype, rsp);
830         kfree(unc_path);
831         return rc;
832
833 tcon_error_exit:
834         if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
835                 cERROR(1, "BAD_NETWORK_NAME: %s", tree);
836                 tcon->bad_network_name = true;
837         }
838         goto tcon_exit;
839 }
840
841 int
842 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
843 {
844         struct smb2_tree_disconnect_req *req; /* response is trivial */
845         int rc = 0;
846         struct TCP_Server_Info *server;
847         struct cifs_ses *ses = tcon->ses;
848
849         cFYI(1, "Tree Disconnect");
850
851         if (ses && (ses->server))
852                 server = ses->server;
853         else
854                 return -EIO;
855
856         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
857                 return 0;
858
859         rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
860         if (rc)
861                 return rc;
862
863         rc = SendReceiveNoRsp(xid, ses, (char *)&req->hdr, 0);
864         if (rc)
865                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
866
867         return rc;
868 }
869
870 int
871 SMB2_open(const unsigned int xid, struct cifs_tcon *tcon, __le16 *path,
872           u64 *persistent_fid, u64 *volatile_fid, __u32 desired_access,
873           __u32 create_disposition, __u32 file_attributes, __u32 create_options,
874           struct smb2_file_all_info *buf)
875 {
876         struct smb2_create_req *req;
877         struct smb2_create_rsp *rsp;
878         struct TCP_Server_Info *server;
879         struct cifs_ses *ses = tcon->ses;
880         struct kvec iov[2];
881         int resp_buftype;
882         int uni_path_len;
883         int rc = 0;
884         int num_iovecs = 2;
885
886         cFYI(1, "create/open");
887
888         if (ses && (ses->server))
889                 server = ses->server;
890         else
891                 return -EIO;
892
893         rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
894         if (rc)
895                 return rc;
896
897         /* if (server->oplocks)
898                 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_BATCH;
899         else */
900                 req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
901         req->ImpersonationLevel = IL_IMPERSONATION;
902         req->DesiredAccess = cpu_to_le32(desired_access);
903         /* File attributes ignored on open (used in create though) */
904         req->FileAttributes = cpu_to_le32(file_attributes);
905         req->ShareAccess = FILE_SHARE_ALL_LE;
906         req->CreateDisposition = cpu_to_le32(create_disposition);
907         req->CreateOptions = cpu_to_le32(create_options);
908         uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
909         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req)
910                         - 1 /* pad */ - 4 /* do not count rfc1001 len field */);
911
912         iov[0].iov_base = (char *)req;
913         /* 4 for rfc1002 length field */
914         iov[0].iov_len = get_rfc1002_length(req) + 4;
915
916         /* MUST set path len (NameLength) to 0 opening root of share */
917         if (uni_path_len >= 4) {
918                 req->NameLength = cpu_to_le16(uni_path_len - 2);
919                 /* -1 since last byte is buf[0] which is sent below (path) */
920                 iov[0].iov_len--;
921                 iov[1].iov_len = uni_path_len;
922                 iov[1].iov_base = path;
923                 /*
924                  * -1 since last byte is buf[0] which was counted in
925                  * smb2_buf_len.
926                  */
927                 inc_rfc1001_len(req, uni_path_len - 1);
928         } else {
929                 num_iovecs = 1;
930                 req->NameLength = 0;
931         }
932
933         rc = SendReceive2(xid, ses, iov, num_iovecs, &resp_buftype, 0);
934         rsp = (struct smb2_create_rsp *)iov[0].iov_base;
935
936         if (rc != 0) {
937                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
938                 goto creat_exit;
939         }
940
941         if (rsp == NULL) {
942                 rc = -EIO;
943                 goto creat_exit;
944         }
945         *persistent_fid = rsp->PersistentFileId;
946         *volatile_fid = rsp->VolatileFileId;
947
948         if (buf) {
949                 memcpy(buf, &rsp->CreationTime, 32);
950                 buf->AllocationSize = rsp->AllocationSize;
951                 buf->EndOfFile = rsp->EndofFile;
952                 buf->Attributes = rsp->FileAttributes;
953                 buf->NumberOfLinks = cpu_to_le32(1);
954                 buf->DeletePending = 0;
955         }
956 creat_exit:
957         free_rsp_buf(resp_buftype, rsp);
958         return rc;
959 }
960
961 int
962 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
963            u64 persistent_fid, u64 volatile_fid)
964 {
965         struct smb2_close_req *req;
966         struct smb2_close_rsp *rsp;
967         struct TCP_Server_Info *server;
968         struct cifs_ses *ses = tcon->ses;
969         struct kvec iov[1];
970         int resp_buftype;
971         int rc = 0;
972
973         cFYI(1, "Close");
974
975         if (ses && (ses->server))
976                 server = ses->server;
977         else
978                 return -EIO;
979
980         rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
981         if (rc)
982                 return rc;
983
984         req->PersistentFileId = persistent_fid;
985         req->VolatileFileId = volatile_fid;
986
987         iov[0].iov_base = (char *)req;
988         /* 4 for rfc1002 length field */
989         iov[0].iov_len = get_rfc1002_length(req) + 4;
990
991         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
992         rsp = (struct smb2_close_rsp *)iov[0].iov_base;
993
994         if (rc != 0) {
995                 if (tcon)
996                         cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
997                 goto close_exit;
998         }
999
1000         if (rsp == NULL) {
1001                 rc = -EIO;
1002                 goto close_exit;
1003         }
1004
1005         /* BB FIXME - decode close response, update inode for caching */
1006
1007 close_exit:
1008         free_rsp_buf(resp_buftype, rsp);
1009         return rc;
1010 }
1011
1012 static int
1013 validate_buf(unsigned int offset, unsigned int buffer_length,
1014              struct smb2_hdr *hdr, unsigned int min_buf_size)
1015
1016 {
1017         unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
1018         char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
1019         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1020         char *end_of_buf = begin_of_buf + buffer_length;
1021
1022
1023         if (buffer_length < min_buf_size) {
1024                 cERROR(1, "buffer length %d smaller than minimum size %d",
1025                            buffer_length, min_buf_size);
1026                 return -EINVAL;
1027         }
1028
1029         /* check if beyond RFC1001 maximum length */
1030         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
1031                 cERROR(1, "buffer length %d or smb length %d too large",
1032                            buffer_length, smb_len);
1033                 return -EINVAL;
1034         }
1035
1036         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
1037                 cERROR(1, "illegal server response, bad offset to data");
1038                 return -EINVAL;
1039         }
1040
1041         return 0;
1042 }
1043
1044 /*
1045  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
1046  * Caller must free buffer.
1047  */
1048 static int
1049 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
1050                       struct smb2_hdr *hdr, unsigned int minbufsize,
1051                       char *data)
1052
1053 {
1054         char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
1055         int rc;
1056
1057         if (!data)
1058                 return -EINVAL;
1059
1060         rc = validate_buf(offset, buffer_length, hdr, minbufsize);
1061         if (rc)
1062                 return rc;
1063
1064         memcpy(data, begin_of_buf, buffer_length);
1065
1066         return 0;
1067 }
1068
1069 static int
1070 query_info(const unsigned int xid, struct cifs_tcon *tcon,
1071            u64 persistent_fid, u64 volatile_fid, u8 info_class,
1072            size_t output_len, size_t min_len, void *data)
1073 {
1074         struct smb2_query_info_req *req;
1075         struct smb2_query_info_rsp *rsp = NULL;
1076         struct kvec iov[2];
1077         int rc = 0;
1078         int resp_buftype;
1079         struct TCP_Server_Info *server;
1080         struct cifs_ses *ses = tcon->ses;
1081
1082         cFYI(1, "Query Info");
1083
1084         if (ses && (ses->server))
1085                 server = ses->server;
1086         else
1087                 return -EIO;
1088
1089         rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
1090         if (rc)
1091                 return rc;
1092
1093         req->InfoType = SMB2_O_INFO_FILE;
1094         req->FileInfoClass = info_class;
1095         req->PersistentFileId = persistent_fid;
1096         req->VolatileFileId = volatile_fid;
1097         /* 4 for rfc1002 length field and 1 for Buffer */
1098         req->InputBufferOffset =
1099                 cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
1100         req->OutputBufferLength = cpu_to_le32(output_len);
1101
1102         iov[0].iov_base = (char *)req;
1103         /* 4 for rfc1002 length field */
1104         iov[0].iov_len = get_rfc1002_length(req) + 4;
1105
1106         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1107         if (rc) {
1108                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
1109                 goto qinf_exit;
1110         }
1111
1112         rsp = (struct smb2_query_info_rsp *)iov[0].iov_base;
1113
1114         rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
1115                                    le32_to_cpu(rsp->OutputBufferLength),
1116                                    &rsp->hdr, min_len, data);
1117
1118 qinf_exit:
1119         free_rsp_buf(resp_buftype, rsp);
1120         return rc;
1121 }
1122
1123 int
1124 SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
1125                 u64 persistent_fid, u64 volatile_fid,
1126                 struct smb2_file_all_info *data)
1127 {
1128         return query_info(xid, tcon, persistent_fid, volatile_fid,
1129                           FILE_ALL_INFORMATION,
1130                           sizeof(struct smb2_file_all_info) + MAX_NAME * 2,
1131                           sizeof(struct smb2_file_all_info), data);
1132 }
1133
1134 int
1135 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
1136                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
1137 {
1138         return query_info(xid, tcon, persistent_fid, volatile_fid,
1139                           FILE_INTERNAL_INFORMATION,
1140                           sizeof(struct smb2_file_internal_info),
1141                           sizeof(struct smb2_file_internal_info), uniqueid);
1142 }
1143
1144 /*
1145  * This is a no-op for now. We're not really interested in the reply, but
1146  * rather in the fact that the server sent one and that server->lstrp
1147  * gets updated.
1148  *
1149  * FIXME: maybe we should consider checking that the reply matches request?
1150  */
1151 static void
1152 smb2_echo_callback(struct mid_q_entry *mid)
1153 {
1154         struct TCP_Server_Info *server = mid->callback_data;
1155         struct smb2_echo_rsp *smb2 = (struct smb2_echo_rsp *)mid->resp_buf;
1156         unsigned int credits_received = 1;
1157
1158         if (mid->mid_state == MID_RESPONSE_RECEIVED)
1159                 credits_received = le16_to_cpu(smb2->hdr.CreditRequest);
1160
1161         DeleteMidQEntry(mid);
1162         add_credits(server, credits_received, CIFS_ECHO_OP);
1163 }
1164
1165 int
1166 SMB2_echo(struct TCP_Server_Info *server)
1167 {
1168         struct smb2_echo_req *req;
1169         int rc = 0;
1170         struct kvec iov;
1171
1172         cFYI(1, "In echo request");
1173
1174         rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
1175         if (rc)
1176                 return rc;
1177
1178         req->hdr.CreditRequest = cpu_to_le16(1);
1179
1180         iov.iov_base = (char *)req;
1181         /* 4 for rfc1002 length field */
1182         iov.iov_len = get_rfc1002_length(req) + 4;
1183
1184         rc = cifs_call_async(server, &iov, 1, NULL, smb2_echo_callback, server,
1185                              CIFS_ECHO_OP);
1186         if (rc)
1187                 cFYI(1, "Echo request failed: %d", rc);
1188
1189         cifs_small_buf_release(req);
1190         return rc;
1191 }
1192
1193 int
1194 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1195            u64 volatile_fid)
1196 {
1197         struct smb2_flush_req *req;
1198         struct TCP_Server_Info *server;
1199         struct cifs_ses *ses = tcon->ses;
1200         struct kvec iov[1];
1201         int resp_buftype;
1202         int rc = 0;
1203
1204         cFYI(1, "Flush");
1205
1206         if (ses && (ses->server))
1207                 server = ses->server;
1208         else
1209                 return -EIO;
1210
1211         rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
1212         if (rc)
1213                 return rc;
1214
1215         req->PersistentFileId = persistent_fid;
1216         req->VolatileFileId = volatile_fid;
1217
1218         iov[0].iov_base = (char *)req;
1219         /* 4 for rfc1002 length field */
1220         iov[0].iov_len = get_rfc1002_length(req) + 4;
1221
1222         rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, 0);
1223
1224         if ((rc != 0) && tcon)
1225                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
1226
1227         free_rsp_buf(resp_buftype, iov[0].iov_base);
1228         return rc;
1229 }
1230
1231 /*
1232  * To form a chain of read requests, any read requests after the first should
1233  * have the end_of_chain boolean set to true.
1234  */
1235 static int
1236 smb2_new_read_req(struct kvec *iov, struct cifs_io_parms *io_parms,
1237                   unsigned int remaining_bytes, int request_type)
1238 {
1239         int rc = -EACCES;
1240         struct smb2_read_req *req = NULL;
1241
1242         rc = small_smb2_init(SMB2_READ, io_parms->tcon, (void **) &req);
1243         if (rc)
1244                 return rc;
1245         if (io_parms->tcon->ses->server == NULL)
1246                 return -ECONNABORTED;
1247
1248         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1249
1250         req->PersistentFileId = io_parms->persistent_fid;
1251         req->VolatileFileId = io_parms->volatile_fid;
1252         req->ReadChannelInfoOffset = 0; /* reserved */
1253         req->ReadChannelInfoLength = 0; /* reserved */
1254         req->Channel = 0; /* reserved */
1255         req->MinimumCount = 0;
1256         req->Length = cpu_to_le32(io_parms->length);
1257         req->Offset = cpu_to_le64(io_parms->offset);
1258
1259         if (request_type & CHAINED_REQUEST) {
1260                 if (!(request_type & END_OF_CHAIN)) {
1261                         /* 4 for rfc1002 length field */
1262                         req->hdr.NextCommand =
1263                                 cpu_to_le32(get_rfc1002_length(req) + 4);
1264                 } else /* END_OF_CHAIN */
1265                         req->hdr.NextCommand = 0;
1266                 if (request_type & RELATED_REQUEST) {
1267                         req->hdr.Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
1268                         /*
1269                          * Related requests use info from previous read request
1270                          * in chain.
1271                          */
1272                         req->hdr.SessionId = 0xFFFFFFFF;
1273                         req->hdr.TreeId = 0xFFFFFFFF;
1274                         req->PersistentFileId = 0xFFFFFFFF;
1275                         req->VolatileFileId = 0xFFFFFFFF;
1276                 }
1277         }
1278         if (remaining_bytes > io_parms->length)
1279                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
1280         else
1281                 req->RemainingBytes = 0;
1282
1283         iov[0].iov_base = (char *)req;
1284         /* 4 for rfc1002 length field */
1285         iov[0].iov_len = get_rfc1002_length(req) + 4;
1286         return rc;
1287 }
1288
1289 static void
1290 smb2_readv_callback(struct mid_q_entry *mid)
1291 {
1292         struct cifs_readdata *rdata = mid->callback_data;
1293         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1294         struct TCP_Server_Info *server = tcon->ses->server;
1295         struct smb2_hdr *buf = (struct smb2_hdr *)rdata->iov[0].iov_base;
1296         unsigned int credits_received = 1;
1297
1298         cFYI(1, "%s: mid=%llu state=%d result=%d bytes=%u", __func__,
1299                 mid->mid, mid->mid_state, rdata->result, rdata->bytes);
1300
1301         switch (mid->mid_state) {
1302         case MID_RESPONSE_RECEIVED:
1303                 credits_received = le16_to_cpu(buf->CreditRequest);
1304                 /* result already set, check signature */
1305                 if (server->sec_mode &
1306                     (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) {
1307                         int rc;
1308
1309                         rc = smb2_verify_signature2(rdata->iov, rdata->nr_iov,
1310                                                     server);
1311                         if (rc)
1312                                 cERROR(1, "SMB signature verification returned "
1313                                        "error = %d", rc);
1314                 }
1315                 /* FIXME: should this be counted toward the initiating task? */
1316                 task_io_account_read(rdata->bytes);
1317                 cifs_stats_bytes_read(tcon, rdata->bytes);
1318                 break;
1319         case MID_REQUEST_SUBMITTED:
1320         case MID_RETRY_NEEDED:
1321                 rdata->result = -EAGAIN;
1322                 break;
1323         default:
1324                 if (rdata->result != -ENODATA)
1325                         rdata->result = -EIO;
1326         }
1327
1328         if (rdata->result)
1329                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
1330
1331         queue_work(cifsiod_wq, &rdata->work);
1332         DeleteMidQEntry(mid);
1333         add_credits(server, credits_received, 0);
1334 }
1335
1336 /* smb2_async_readv - send an async write, and set up mid to handle result */
1337 int
1338 smb2_async_readv(struct cifs_readdata *rdata)
1339 {
1340         int rc;
1341         struct smb2_hdr *buf;
1342         struct cifs_io_parms io_parms;
1343
1344         cFYI(1, "%s: offset=%llu bytes=%u", __func__,
1345                 rdata->offset, rdata->bytes);
1346
1347         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
1348         io_parms.offset = rdata->offset;
1349         io_parms.length = rdata->bytes;
1350         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
1351         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
1352         io_parms.pid = rdata->pid;
1353         rc = smb2_new_read_req(&rdata->iov[0], &io_parms, 0, 0);
1354         if (rc)
1355                 return rc;
1356
1357         buf = (struct smb2_hdr *)rdata->iov[0].iov_base;
1358         /* 4 for rfc1002 length field */
1359         rdata->iov[0].iov_len = get_rfc1002_length(rdata->iov[0].iov_base) + 4;
1360
1361         kref_get(&rdata->refcount);
1362         rc = cifs_call_async(io_parms.tcon->ses->server, rdata->iov, 1,
1363                              cifs_readv_receive, smb2_readv_callback,
1364                              rdata, 0);
1365         if (rc)
1366                 kref_put(&rdata->refcount, cifs_readdata_release);
1367
1368         cifs_small_buf_release(buf);
1369         return rc;
1370 }
1371
1372 int
1373 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
1374           unsigned int *nbytes, char **buf, int *buf_type)
1375 {
1376         int resp_buftype, rc = -EACCES;
1377         struct smb2_read_rsp *rsp = NULL;
1378         struct kvec iov[1];
1379
1380         *nbytes = 0;
1381         rc = smb2_new_read_req(iov, io_parms, 0, 0);
1382         if (rc)
1383                 return rc;
1384
1385         rc = SendReceive2(xid, io_parms->tcon->ses, iov, 1,
1386                           &resp_buftype, CIFS_LOG_ERROR);
1387
1388         rsp = (struct smb2_read_rsp *)iov[0].iov_base;
1389
1390         if (rsp->hdr.Status == STATUS_END_OF_FILE) {
1391                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1392                 return 0;
1393         }
1394
1395         if (rc) {
1396                 cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
1397                 cERROR(1, "Send error in read = %d", rc);
1398         } else {
1399                 *nbytes = le32_to_cpu(rsp->DataLength);
1400                 if ((*nbytes > CIFS_MAX_MSGSIZE) ||
1401                     (*nbytes > io_parms->length)) {
1402                         cFYI(1, "bad length %d for count %d", *nbytes,
1403                                 io_parms->length);
1404                         rc = -EIO;
1405                         *nbytes = 0;
1406                 }
1407         }
1408
1409         if (*buf) {
1410                 memcpy(*buf, (char *)rsp->hdr.ProtocolId + rsp->DataOffset,
1411                        *nbytes);
1412                 free_rsp_buf(resp_buftype, iov[0].iov_base);
1413         } else if (resp_buftype != CIFS_NO_BUFFER) {
1414                 *buf = iov[0].iov_base;
1415                 if (resp_buftype == CIFS_SMALL_BUFFER)
1416                         *buf_type = CIFS_SMALL_BUFFER;
1417                 else if (resp_buftype == CIFS_LARGE_BUFFER)
1418                         *buf_type = CIFS_LARGE_BUFFER;
1419         }
1420         return rc;
1421 }
1422
1423 /*
1424  * Check the mid_state and signature on received buffer (if any), and queue the
1425  * workqueue completion task.
1426  */
1427 static void
1428 smb2_writev_callback(struct mid_q_entry *mid)
1429 {
1430         struct cifs_writedata *wdata = mid->callback_data;
1431         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1432         unsigned int written;
1433         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
1434         unsigned int credits_received = 1;
1435
1436         switch (mid->mid_state) {
1437         case MID_RESPONSE_RECEIVED:
1438                 credits_received = le16_to_cpu(rsp->hdr.CreditRequest);
1439                 wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
1440                 if (wdata->result != 0)
1441                         break;
1442
1443                 written = le32_to_cpu(rsp->DataLength);
1444                 /*
1445                  * Mask off high 16 bits when bytes written as returned
1446                  * by the server is greater than bytes requested by the
1447                  * client. OS/2 servers are known to set incorrect
1448                  * CountHigh values.
1449                  */
1450                 if (written > wdata->bytes)
1451                         written &= 0xFFFF;
1452
1453                 if (written < wdata->bytes)
1454                         wdata->result = -ENOSPC;
1455                 else
1456                         wdata->bytes = written;
1457                 break;
1458         case MID_REQUEST_SUBMITTED:
1459         case MID_RETRY_NEEDED:
1460                 wdata->result = -EAGAIN;
1461                 break;
1462         default:
1463                 wdata->result = -EIO;
1464                 break;
1465         }
1466
1467         if (wdata->result)
1468                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
1469
1470         queue_work(cifsiod_wq, &wdata->work);
1471         DeleteMidQEntry(mid);
1472         add_credits(tcon->ses->server, credits_received, 0);
1473 }
1474
1475 /* smb2_async_writev - send an async write, and set up mid to handle result */
1476 int
1477 smb2_async_writev(struct cifs_writedata *wdata)
1478 {
1479         int i, rc = -EACCES;
1480         struct smb2_write_req *req = NULL;
1481         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
1482         struct kvec *iov = NULL;
1483
1484         rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
1485         if (rc)
1486                 goto async_writev_out;
1487
1488         /* 1 iov per page + 1 for header */
1489         iov = kzalloc((wdata->nr_pages + 1) * sizeof(*iov), GFP_NOFS);
1490         if (iov == NULL) {
1491                 rc = -ENOMEM;
1492                 goto async_writev_out;
1493         }
1494
1495         req->hdr.ProcessId = cpu_to_le32(wdata->cfile->pid);
1496
1497         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
1498         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
1499         req->WriteChannelInfoOffset = 0;
1500         req->WriteChannelInfoLength = 0;
1501         req->Channel = 0;
1502         req->Offset = cpu_to_le64(wdata->offset);
1503         /* 4 for rfc1002 length field */
1504         req->DataOffset = cpu_to_le16(
1505                                 offsetof(struct smb2_write_req, Buffer) - 4);
1506         req->RemainingBytes = 0;
1507
1508         /* 4 for rfc1002 length field and 1 for Buffer */
1509         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1510         iov[0].iov_base = (char *)req;
1511
1512         /*
1513          * This function should marshal up the page array into the kvec
1514          * array, reserving [0] for the header. It should kmap the pages
1515          * and set the iov_len properly for each one. It may also set
1516          * wdata->bytes too.
1517          */
1518         cifs_kmap_lock();
1519         wdata->marshal_iov(iov, wdata);
1520         cifs_kmap_unlock();
1521
1522         cFYI(1, "async write at %llu %u bytes", wdata->offset, wdata->bytes);
1523
1524         req->Length = cpu_to_le32(wdata->bytes);
1525
1526         inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
1527
1528         kref_get(&wdata->refcount);
1529         rc = cifs_call_async(tcon->ses->server, iov, wdata->nr_pages + 1,
1530                              NULL, smb2_writev_callback, wdata, 0);
1531
1532         if (rc)
1533                 kref_put(&wdata->refcount, cifs_writedata_release);
1534
1535         /* send is done, unmap pages */
1536         for (i = 0; i < wdata->nr_pages; i++)
1537                 kunmap(wdata->pages[i]);
1538
1539 async_writev_out:
1540         cifs_small_buf_release(req);
1541         kfree(iov);
1542         return rc;
1543 }
1544
1545 /*
1546  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
1547  * The length field from io_parms must be at least 1 and indicates a number of
1548  * elements with data to write that begins with position 1 in iov array. All
1549  * data length is specified by count.
1550  */
1551 int
1552 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
1553            unsigned int *nbytes, struct kvec *iov, int n_vec)
1554 {
1555         int rc = 0;
1556         struct smb2_write_req *req = NULL;
1557         struct smb2_write_rsp *rsp = NULL;
1558         int resp_buftype;
1559         *nbytes = 0;
1560
1561         if (n_vec < 1)
1562                 return rc;
1563
1564         rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
1565         if (rc)
1566                 return rc;
1567
1568         if (io_parms->tcon->ses->server == NULL)
1569                 return -ECONNABORTED;
1570
1571         req->hdr.ProcessId = cpu_to_le32(io_parms->pid);
1572
1573         req->PersistentFileId = io_parms->persistent_fid;
1574         req->VolatileFileId = io_parms->volatile_fid;
1575         req->WriteChannelInfoOffset = 0;
1576         req->WriteChannelInfoLength = 0;
1577         req->Channel = 0;
1578         req->Length = cpu_to_le32(io_parms->length);
1579         req->Offset = cpu_to_le64(io_parms->offset);
1580         /* 4 for rfc1002 length field */
1581         req->DataOffset = cpu_to_le16(
1582                                 offsetof(struct smb2_write_req, Buffer) - 4);
1583         req->RemainingBytes = 0;
1584
1585         iov[0].iov_base = (char *)req;
1586         /* 4 for rfc1002 length field and 1 for Buffer */
1587         iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1588
1589         /* length of entire message including data to be written */
1590         inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
1591
1592         rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
1593                           &resp_buftype, 0);
1594
1595         if (rc) {
1596                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
1597                 cERROR(1, "Send error in write = %d", rc);
1598         } else {
1599                 rsp = (struct smb2_write_rsp *)iov[0].iov_base;
1600                 *nbytes = le32_to_cpu(rsp->DataLength);
1601                 free_rsp_buf(resp_buftype, rsp);
1602         }
1603         return rc;
1604 }