source: src/linux/universal/linux-3.18/fs/cifs/smb2pdu.c @ 31885

Last change on this file since 31885 was 31885, checked in by brainslayer, 5 weeks ago

update

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