~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/cifs/smb2pdu.c

Version: ~ [ linux-5.11-rc3 ] ~ [ linux-5.10.7 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.89 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.167 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.215 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.251 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.251 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp